Spaccogram/webk/public/appDialogsManager-DIyIdzjh.js

308 lines
1.6 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<n)return;let c=o/n;if(l!==s.length-1){const d=s[l===s.length-1?l:l+1].m;c%=d}t.push({duration:c|0,type:r.t})});const a=t.slice(-e).reverse();for(let r=a.length-1;r>=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<n&&(l[1]=l[1]||"",l[1]+=new Array(n-l[1].length+1).join("0")),l.join(r)}function In(o,e,t,s,i){if(o=+o,e===Eg){if(i)return ke.format("StarsCount",!0,[o]);const p=document.createElement("span");return p.classList.add("xtr"),p.append(Le("star","xtr-icon")," ",""+o),p}const n=o<0,a=Xb[e];if(!a)throw new Error("CURRENCY_WRAP_INVALID");const r=o/Math.pow(10,a.exp);let l=a.exp;e=="IRR"&&Math.floor(r)==r&&(l=0);let c=P0(r,l,a.decimal_sep,a.thousands_sep);if(t)return c;let d=s&&a.native||a.symbol;n&&!a.space_between&&a.symbol_left&&(d="-"+d,c=c.replace("-",""));let h;const u=a.space_between?" ":"";return a.symbol_left?h=d+u+c:h=c+u+d,h}window.p=In;function at(o){if(o!==void 0&&(o.isPeerId&&o.isPeerId()))return o;if(_g(o)){const s=o.user_id;if(s!==void 0)return s.toPeerId(!1);const i=o.channel_id||o.chat_id;return i!==void 0?i.toPeerId(!0):Tt}else if(!o)return Tt;const e=o.charAt(0)==="u",t=o.substr(1).split("_");return e?t[0].toPeerId():(t[0]||"").toPeerId(!0)}function vo(o,e=[]){return e.forEach(t=>{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",`
<linearGradient id="${s}" x1="0" x2="0" y1="0" y2="1">
<stop style="stop-color: #${t};" offset="0%" />
<stop style="stop-color: hsla(${a}, ${r}%, ${Math.max(0,l-30)}%, ${c});" offset="100%" />
</linearGradient>
`),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<n;++i){const a=o[i];(e(a,i,o)?t:s).push(a)}return[t,s]}function Ed(o){if(o instanceof DocumentFragment)return o;const e=document.createElement("template");return o=o.trim(),e.innerHTML=o,e.content}const _0=new Set(["all","web","webk"]),k0=new Set;function Zb(o){return o.find(e=>_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)<r&&aa(o,"language",i)})}function O0(o,e){return K(()=>{const t=o();if(!t)return;Ru?.();const s=dr[t];if(!(s&&s.total<R0&&!s.isFull)&&!(s&&s.totalForeign/s.total<D0))return s?.language})}const kp=new Map;function aw(o,e){return K(()=>{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<f;g+=2)a.splice(g,0,", ");o.text&&f&&a.push(", ")}if(e.action){const m=await lw({...o,noLinks:!0,noTextFormat:!0});m&&l(void 0,m)}if(h&&(o.text=Zb(e.restriction_reason).text,p=[]),o.text)if(o.text=Aa(o.text,100),p??(p=Ko(o.text)),s)a.push(vo(o.text,p));else{if(i){let g=!1,f;const y=new RegExp(T0(i),"gi");for(p=p.slice();(f=y.exec(o.text))!==null;)p.push({_:"messageEntityHighlight",length:i.length,offset:f.index}),g=!0;g&&my(p)}if(e.peerId===Cd&&e.fromId===e.peerId){const g=o.text.match(/[\d\-]{5,7}/);g&&(p=p.slice(),p.push({_:"messageEntitySpoiler",offset:g.index,length:g[0].length}),my(p))}let m;o.canTranslate?m=_d({peerId:e.peerId,message:e,richTextOptions:u,middleware:o.middleware,onTextWithEntities: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;n<s;++n){const a=e[n],r=a.length/t,l=this.startAngle+i*2*Math.PI,c=l+r*2*Math.PI;this.context.beginPath(),this.context.arc(this.centerX,this.centerY,this.radius,l,c,!1),this.context.strokeStyle=a.color,this.context.lineWidth=a.lineWidth*this.dpr,this.context.stroke(),i+=r}}}function mw({container:o,media:e,url:t,needFadeIn:s,aspecter:i=o,thumbImage:n,fadeInElement:a=e,onRender:r,onRenderFinish:l,useRenderCache:c}){return s&&a.classList.add("fade-in"),Ki(e,t,c).then(()=>Dh.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=`
<div class="loading-wrap is-loading">
<div class="loading"></div>
<div class="loading_bezel-wrap">
<div class="loading"></div>
</div>
</div>`:this.preloader.innerHTML=`
<div class="you-spin-me-round">
<svg xmlns="http://www.w3.org/2000/svg" class="preloader-circular" viewBox="${this.streamable?"25 25 50 50":"27 27 54 54"}">
<circle class="preloader-path-new" cx="${this.streamable?"50":"54"}" cy="${this.streamable?"50":"54"}" r="${this.streamable?19:24}" fill="none" stroke-miterlimit="10"/>
</svg>
</div>`,this.streamable?this.totalLength=118.61124420166016:this.totalLength=149.82473754882812,this.cancelable?(this.preloader.innerHTML+=`
<svg xmlns="http://www.w3.org/2000/svg" class="preloader-close" viewBox="0 0 24 24">
<g fill="none" fill-rule="evenodd">
<polygon points="0 0 24 0 24 24 0 24"/>
<path fill="#000" fill-rule="nonzero" d="M5.20970461,5.38710056 L5.29289322,5.29289322 C5.65337718,4.93240926 6.22060824,4.90467972 6.61289944,5.20970461 L6.70710678,5.29289322 L12,10.585 L17.2928932,5.29289322 C17.6834175,4.90236893 18.3165825,4.90236893 18.7071068,5.29289322 C19.0976311,5.68341751 19.0976311,6.31658249 18.7071068,6.70710678 L13.415,12 L18.7071068,17.2928932 C19.0675907,17.6533772 19.0953203,18.2206082 18.7902954,18.6128994 L18.7071068,18.7071068 C18.3466228,19.0675907 17.7793918,19.0953203 17.3871006,18.7902954 L17.2928932,18.7071068 L12,13.415 L6.70710678,18.7071068 C6.31658249,19.0976311 5.68341751,19.0976311 5.29289322,18.7071068 C4.90236893,18.3165825 4.90236893,17.6834175 5.29289322,17.2928932 L10.585,12 L5.29289322,6.70710678 C4.93240926,6.34662282 4.90467972,5.77939176 5.20970461,5.38710056 L5.29289322,5.29289322 L5.20970461,5.38710056 Z"/>
</g>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" class="preloader-download" viewBox="0 0 24 24">
<g fill="none" fill-rule="evenodd">
<polygon points="0 0 24 0 24 24 0 24"/>
<path fill="#000" fill-rule="nonzero" d="M5,19 L19,19 C19.5522847,19 20,19.4477153 20,20 C20,20.5128358 19.6139598,20.9355072 19.1166211,20.9932723 L19,21 L5,21 C4.44771525,21 4,20.5522847 4,20 C4,19.4871642 4.38604019,19.0644928 4.88337887,19.0067277 L5,19 L19,19 L5,19 Z M11.8833789,3.00672773 L12,3 C12.5128358,3 12.9355072,3.38604019 12.9932723,3.88337887 L13,4 L13,13.585 L16.2928932,10.2928932 C16.6533772,9.93240926 17.2206082,9.90467972 17.6128994,10.2097046 L17.7071068,10.2928932 C18.0675907,10.6533772 18.0953203,11.2206082 17.7902954,11.6128994 L17.7071068,11.7071068 L12.7071068,16.7071068 C12.3466228,17.0675907 11.7793918,17.0953203 11.3871006,16.7902954 L11.2928932,16.7071068 L6.29289322,11.7071068 C5.90236893,11.3165825 5.90236893,10.6834175 6.29289322,10.2928932 C6.65337718,9.93240926 7.22060824,9.90467972 7.61289944,10.2097046 L7.70710678,10.2928932 L11,13.585 L11,4 C11,3.48716416 11.3860402,3.06449284 11.8833789,3.00672773 L12,3 L11.8833789,3.00672773 Z"/>
</g>
</svg>`,this.downloadSvg=this.preloader.lastElementChild,this.cancelSvg=this.downloadSvg.previousElementSibling):this.preloader.classList.add("preloader-swing"),this.circle=this.preloader.firstElementChild.firstElementChild.firstElementChild,this.cancelable&&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<r?this.detach():setTimeout(()=>{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<m&&u.height<m&&(u=l=l.aspectCovered(vs(m,m))),n&&(n.message||n.factcheck||n.reply_to_mid||n.media.webpage||n.replies&&n.replies.pFlags.comments&&n.replies.channel_id.toChatId()!==nL)&&u.width<Tm&&(u=vs(Tm,u.height),p=!1);const g=o?.type==="video"&&c?X0:Q0;u.width<g&&n&&(u=vs(g,u.height),p=!1)}return e.style.width=u.width+"px",e.style.height=u.height+"px",{photoSize:r,size:l,isFit:p}}async function Ks({photo:o,message:e,container:t,boxWidth:s,boxHeight:i,withTail:n,isOut:a,lazyLoadQueue:r,middleware:l,size:c,withoutPreloader:d,loadPromises:h,autoDownloadSize:u,noBlur:p,noThumb:m,noFadeIn:g,blurAfter:f,managers:y=I.managers,processUrl:v,fadeInElement:w,onRender:b,onRenderFinish:S,useBlur:C,useRenderCache:P,canHaveVideoPlayer:L,uploadingFileName:E}){const _={loadPromises:{thumb:Promise.resolve(),full:Promise.resolve()},images:{thumb:null,full:null},preloader:null,aspecter:null};t||(d=!0,r=void 0);const k=aL(o),x=o._==="document",A=x&&o.mime_type.startsWith("image/")&&!c,T=Bb(o);if(!(o.sizes||o.thumbs)&&!T&&!A&&!k)return s&&i&&!c&&x&&jo({photo:o,element:t,boxWidth:s,boxHeight:i,message:e,canHaveVideoPlayer:L}),_;let B=u===0;c||(s===void 0&&(s=$e.active.regular.width),i===void 0&&(i=$e.active.regular.height)),t&&t.classList.add("media-container");let R=t,O=!0,X=Promise.resolve(),F,H;if(s&&i&&!c&&!k&&t){const re=jo({photo:o,element:t,boxWidth:s,boxHeight:i,message:e,photoSize:A?{_:"photoSize",w:o.w,h:o.h,size:o.size,type:Rg}:void 0,canHaveVideoPlayer:L});if(c=re.photoSize,O=re.isFit,H=fe.getCacheContext(o,c.type),!O&&!T){R=document.createElement("div"),R.classList.add("media-container-aspecter"),R.style.width=re.size.width+"px",R.style.height=re.size.height+"px";const ge=Oc({photo:o,cacheContext:H,useBlur:C!==void 0?C:!p,ignoreCache:!0,onlyStripped:!0});if(ge){X=ge.loadPromise;const be=ge.image;be.classList.add("media-photo"),t.append(be)}else(await Ks({container:t,message:e,photo:o,boxWidth:0,boxHeight:0,size:c,lazyLoadQueue:r,isOut:a,loadPromises:h,middleware:l,withoutPreloader:!0,withTail:n,autoDownloadSize:u,noBlur:p,noThumb:!0,blurAfter:!0,managers:y})).images.full.classList.add("media-photo","thumbnail");t.classList.add("media-container-fitted"),t.append(R)}}else!c&&!k&&(c=Sn(o,s,i,!0)),H=fe.getCacheContext(o,c?.type);if(!m&&!T&&!k&&R){const re=Oc({photo:o,cacheContext:H,useBlur:C!==void 0?C:!p});re&&(X=Promise.all([X,re.loadPromise]),_.loadPromises.thumb=_.loadPromises.full=X,F=_.images.thumb=re.image,F.classList.add("media-photo"),R.append(F))}if(_.aspecter=R,c?._==="photoSizeEmpty"&&x||c?.bytes)return _;let G;c?._==="videoSize"?(G=_.images.full=hl({middleware:l}),G.autoplay=!0,G.loop=!0,G.muted=!0,G.classList.add("media-photo")):(G=_.images.full=new Image,G.classList.add("media-photo"));const z=(F||!H.downloaded)&&st.isAvailable("animations")&&!g;let q;E??(E=e?.uploadingFileName?.[0]),d||((!H.downloaded||E)&&(q=new tn({attachMethod:"prepend",isUpload:!!E})),E&&(q.attachPromise(cs.getUpload(E)),q.attach(t),B=void 0));const $=()=>{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("<div class=avatar-stories-simple>"),J0=ce("<div><div>"),eP=ce("<div class=avatar-background>"),tP=ce("<div>"),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<Be;++pe)Ne[pe].render()}const Ze=await Z;if(be())return E&&(E=!1),F(Ze)};o.onStoriesStatus&&ye(()=>{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.length<this.loadWhenLeft&&this.load(!this.reverse),this.previous.length<this.loadWhenLeft&&this.load(this.reverse),this.current=i,t&&this.onJump?.(i,e>0),this.current}unsetCurrent(e){e?this.previous.push(this.current):this.next.unshift(this.current),this.current=void 0}goUnsafe(e,t){const s=e>0?Math.max(0,e-this.next.length):Math.min(0,e+this.previous.length),i=this.go(e,s?!1:t);return{item:s?void 0:i,leftLength:s}}setLoaded(e,t){return(e?this.loadedAllDown:this.loadedAllUp)!==t?(e?this.loadedAllDown=t:this.loadedAllUp=t,t||(e?this.loadPromiseDown=null:this.loadPromiseUp=null),!0):!1}load(e){if(e?this.loadedAllDown:this.loadedAllUp)return Promise.resolve();let t=e?this.loadPromiseDown:this.loadPromiseUp;if(t)return t;let s;return e?s=this.reverse?this.previous[0]:this.next[this.next.length-1]:s=this.reverse?this.next[this.next.length-1]:this.previous[0],s??(s=this.current),t=this.loadMore(s,e,this.loadCount).then(async i=>{if((e?this.loadPromiseDown:this.loadPromiseUp)!==t)return;i.items.length<this.loadCount&&this.setLoaded(e,!0),this.count===void 0&&(this.count=i.count||i.items.length);const n=[];(e&&!this.reverse?i.items.forEach.bind(i.items):bi.bind(null,i.items))(l=>{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&&s<t&&(t+=1),t?e.childElementCount>t?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;r<a;r++)if(i(n,t(o[r]))>0)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<o.length;e++){const t=o.charAt(e);if(!/[a-zA-Z0-9_]/.test(t))return!1}if(o.charAt(o.length-1)==="")return!1;for(let e=1;e<o.length;e++)if(o.charAt(e-1)===""&&o.charAt(e)==="_")return!1;return!0}function vP(o){return o.length>=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<i&&this.getSortableTarget(r);++l)this.siblings.push(r),r=r[a];if((n||[]).forEach(l=>{this.siblings.includes(l)||(l.style.transform="")}),this.siblings.forEach(l=>{const c=this.elementRect.height*(s<0?1:-1);l.style.transform=`translateY(${c}px)`}),this.scrollableRect){const l=s,c=l>0,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("<div class=selector-empty-placeholder><div class=selector-empty-placeholder-title>"),LP=ce("<div class=selector-empty-placeholder-description>");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<i;++h){const u=n<i&&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<c;++d)this.drawChat(i,d,d*a+l),l+=r;return t.createPattern(s,"no-repeat")}drawChat(e,t,s){let i=this.generatedValues[t];i||(i=this.generatedValues[t]={firstLineWidth:40+Math.random()*100,secondLineWidth:this.noSecondLine?0:120+Math.random()*130,statusWidth:this.statusWidth?this.statusWidth+Math.random()*16:void 0});const{firstLineWidth:n,secondLineWidth:a,statusWidth:r}=i,{canvas:l}=e,{dpr:c}=l;s/=c;const{avatarSize:d,marginVertical:h,lineHeight:u,lineBorderRadius:p,lineMarginVertical:m}=this;let g=this.marginLeft;d&&(PP(e,g,s+h,d/2,!0),g+=d+this.avatarMarginRight),Eh(e,g,s+h+m,n,u,p),a&&Eh(e,g,s+this.totalHeight-h-u-m,a,u,p),r&&Eh(e,l.width/c-24-r,s+h+m,r,u,p)}}function ni(o,e=!0){const t=document.createElement("a");return t.href="#",t.onclick=s=>{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.size<e)return this.getMoreDialogs()}async filterByRights(e){const t=fe.getPeer(e);if(e.isUser())return this.chatRightsActions[0]!=="send_plain"||CP(t);if(this.chatRightsActions.every(s=>fa(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.channelParticipants=!0)}async _getMoreCustom(){if(this.loadedWhat.custom)return;const{middleware:e}=this.getTempId("custom"),t=this.getMoreCustom(this.query,e);t.catch(()=>{e()&&(this.loadedWhat.custom=!0)});const s=await t;if(!e())return;const{result:i,isEnd:n}=s;this.exceptSelf&&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<d}},deleteImporter:c=>{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=/[-]/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<o;)s===4?(e.push(yl),s=0):(e.push(Qt),++t,++s);return e});function jP(o){const e=Ad(o);if(e==="amex")return GP;if(e==="diners14")return zP;const{minLength:t,maxLength:s}=lf[e],i=Xu(o).length,n=Math.min(Math.max(t,i),s);return WP(n)}const fc={cardNumber:jP,cardExpiry:()=>[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<s){const n=s-t,a=or.optionalPattern(/\d/);n&&i.push(...nh(n,a))}return i}),postalCodeFromCountry:Zh(o=>{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<n;){const m=i[l],g=m(e.slice(c)),{type:f,result:y,consumed:v}=g;if(f==="required")if(y){if(a.push(...r,y),r.length=0,++l,g.partial){p(e.length-c);break}p(v)}else{if(!v)break;p(1)}else if(f==="optional")y&&(a.push(...r,y),r.length=0,p(v)),++l;else if(f==="formatting"){if(!s&&c>=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<n?"invalid_expiry_month_past":null}function JP(o){const e=Xu(o),t=Ad(o);return{sanitized:e,brand:t,minLength:lf[t].minLength}}function eM(o,e,t){return o.length>=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;x<A;++x){const T=p[x];if(T instanceof Dr?!T.validateNew(void 0,void 0,!0):!T.value){Zs(T.input,!0);break}}}}else L.input.addEventListener("keydown",E)});const m=document.createElement("div");m.classList.add("input-fields-row"),m.append(h.container,u.container);const g=document.createElement("form");g.append(...[l.container,m,c?.container].filter(Boolean)),t.content.append(g);let f;const{countryInputField:y,postcodeInputField:v}=jw(s.need_country,s.need_zip);(s.need_country||s.need_zip)&&(f=new Pe({name:"PaymentInfo.Billing.Title",noDelimiter:!0,noShadow:!0}),f.content.append(...[y,v].filter(Boolean).map(L=>L.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(/<custom-emoji-renderer-element.+\/custom-emoji-renderer-element>/,"").replace(/(<custom-emoji-element.+?>).+?\/custom-emoji-element>/g,"$1</custom-emoji-element>"),this.inputFake.innerHTML=e}setValueSilently(e,t){super.setValueSilently(e,t),this.updateInnerHTML(),t||this.onFakeInput()}}(function(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<a.numberOfChannels;l++)r[l]=a.getChannelData(l);this.encoder.postMessage({command:"encode",buffers:r})}},n.prototype.initAudioContext=function(a){return a&&a.context?(this.audioContext=a.context,this.closeAudioContext=!1):(this.audioContext=new i,this.closeAudioContext=!0),this.audioContext},n.prototype.initAudioGraph=function(){this.encodeBuffers=function(){delete this.encodeBuffers},this.scriptProcessorNode=this.audioContext.createScriptProcessor(this.config.bufferLength,this.config.numberOfChannels,this.config.numberOfChannels),this.scriptProcessorNode.connect(this.audioContext.destination),this.scriptProcessorNode.onaudioprocess=a=>{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&&this.handler(!0,i),s.bottom>=n.top&&s.bottom<n.bottom&&this.handler(!1,i)}},{threshold:0,root:this.container})}observeElements(){this.elementsObserver=new IntersectionObserver(e=>{const t=e.filter(i=>i.boundingClientRect.top<i.rootBounds.top).sort((i,n)=>i.boundingClientRect.top-n.boundingClientRect.top)[0];if(!t)return;const s=t.isIntersecting?t.target:t.target.nextElementSibling;this.handler(!0,s)},{root:this.container})}addSentinel(e,t){const s=document.createElement("div");return s.classList.add("sticky_sentinel",t),e.appendChild(s)}observeStickyHeaderChanges(e){const t=this.addSentinel(e,"sticky_sentinel--top");this.headersObserver.observe(t),this.elementsObserver.observe(e)}disconnect(){this.headersObserver.disconnect(),this.elementsObserver.disconnect()}unobserve(e,t){this.elementsObserver.unobserve(e),this.headersObserver.unobserve(t)}}function 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"&&gt.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<c){o.textContent=f+Hy+y;break}}e.elementWidth=Op(o)}else o.removeAttribute("title")}class hf extends HTMLElement{connectedCallback(){Kc.set(this,null),this.dataset.sizeType||this.getSize?eS(this):(Wc.add(this),Jw())}disconnectedCallback(){Kc.delete(this),Wc.delete(this)}}customElements.define("middle-ellipsis-element",hf);class ep extends Td{constructor(e={}){super({step:1e3/60/1e3,min:0,max:1,withTransition:e.withTransition,useTransform:e.useTransform},0),this.options=e,this.onLoadedData=()=>{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<t;++r){const l=e.start(r);s>=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<t;n++){const a=n*5/8|0,r=n*5%8,l=i.getUint16(a,!0);s[n]=l>>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;++y){const b=o[y]||0;if(w+h>=d){w=w+h-d,w<(h+1)/2&&u<b&&(u=b);const S=Math.max((u*p+(c+1)/2)/(c+1),4),C=`<rect class="audio-waveform-bar" x="${v}" y="${n-S}" width="2" height="${S}" rx="1" ry="1"></rect>`;m+=C,v+=4,w<(h+1)/2?u=0:u=b}else u<b&&(u=b),w+=h}let g,f;return m&&(g=document.createElement("div"),g.classList.add("audio-waveform"),f=document.createElementNS("http://www.w3.org/2000/svg","svg"),f.classList.add("audio-waveform-bars"),f.setAttributeNS(null,"width",""+l),f.setAttributeNS(null,"height",""+n),f.setAttributeNS(null,"viewBox",`0 0 ${l} ${n}`),f.insertAdjacentHTML("beforeend",m),g.append(f)),{svg:f,container:g,availW:l}}async function EE(o){o.classList.add("is-voice");const e=o.message,t=Xs(e);e.pFlags.out&&o.classList.add("is-out");let s=t.attributes.find(p=>p._==="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='<svg class="audio-transcribe-outline" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 24"><rect class="audio-transcribe-outline-rect" fill="transparent" stroke-width="3" stroke-linejoin="round" rx="6" ry="6" stroke="var(--message-primary-color)" stroke-dashoffset="1" stroke-dasharray="32,68" width="32" height="24"></rect></svg>',p.append(m),p.onclick=()=>{const f=(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",`
<div class="audio-details">
<div class="audio-title"></div>
<div class="audio-subtitle"><div class="audio-time"></div></div>
</div>`);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].mid<e||t.length&&t[t.length-1].mid>e)&&([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=`
<div class="audio-toggle audio-ico">
<div class="audio-play-icon">
<div class="part one" x="0" y="0" fill="#fff"></div>
<div class="part two" x="0" y="0" fill="#fff"></div>
</div>
</div>`;const 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&&h<e.length&&(rt.playbackRate=e[h])},r=()=>s.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?`
<span class="left-controls-watching"></span>
`:`
<time class="ckin__time-elapsed">0:00</time>
<span> / </span>
<time class="ckin__time-duration">0:00</time>
`;return`
<div class="${e}__gradient-bottom ckin__controls"></div>
<div class="${e}__controls ckin__controls">
<div class="bottom-controls night">
<div class="left-controls">
<div class="ckin__time">
${t}
</div>
</div>
<div class="right-controls"></div>
</div>
</div>`}}cancelFullScreen(){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=`<svg class="progress-ring" width="${Ze.width}" height="${Ze.width}" style="transform: rotate(-90deg);">
<circle class="progress-ring__circle" stroke="white" stroke-opacity="0.3" stroke-width="${pe}" cx="${Ne}" cy="${Ne}" r="${Be}" fill="transparent"/>
</svg>`;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&&gt.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;C<u.length;++C){const P=u[C];g.has(P)?b.side="end":(n.has(P)||(v.push(P),n.add(P)),b.element=P,b.previousIndex=C,d(b)),S&&P!==f[C]&&(S=!1)}return!v.length&&S?u:(s({list:f,added:y,removed:v,unchanged:w,finishRemoved:c}),i=g,f)})},e.appear?[]:t.slice())}var su=o=>o 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("<div class=emoticons-search-input-category><div class=emoticons-search-input-category-sticker>"),NE=ce("<div class=emoticons-search-input-categories>");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&&gt.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;t<s;++t){const i=this.map.get(e[t].id);Ps(i,this.element,t)}}add(e,t=this.element){if(this.map.has(e.id))return;const s=document.createElement("div");s.classList.add("gif","grid-item"),s.dataset.docId=""+e.id,s.middlewareHelper=this.middlewareHelper.get().create(),this.map.set(e.id,s),t.append(s),this.lazyLoadQueue.observe({div:s,load:Wt}),qn({doc:e,container:s,lazyLoadQueue:null,noInfo:!0,onlyPreview:!0,middleware:s.middlewareHelper.get()})}delete(e){const t=this.map.get(e);t&&(t.remove(),t.middlewareHelper.destroy(),this.map.delete(e))}}class zp extends vf{constructor(e){super({managers:e.managers,noMenu:!0,searchFetcher:async t=>t?this.managers.appGifsManager.searchGifs(this.query=t):{documents:[],nextOffset:""},groupFetcher:async t=>t?._!=="emojiGroup"?{documents:[],nextOffset:""}:this.managers.appGifsManager.searchGifs(this.query=t.emoticons.join("")),processSearchResult:async({data:{documents:t,nextOffset:s},searching:i,grouping:n})=>{if(!t||!i&&!n)return;if(!t.length){const 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='<div class="sticker-set-name"></div>',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<l;++c){const d=document.createElement("div");d.classList.add("sticker-set-sticker"),r.append(d)}this.managers.appStickersManager.getStickerSet(e).then(c=>{for(let d=0;d<l;++d){const h=r.children[d],u=c.documents[d];u._!=="documentEmpty"&&Rs({doc:u,div:h,lazyLoadQueue:this.lazyLoadQueue,group:"STICKERS-SEARCH",play:!0,loop:!0,width:68,height:68,withLock:!0})}}),t.dataset.stickerSet=""+e.id,t.dataset.access_hash=""+e.access_hash,t.dataset.title=e.title,t.append(s,r),this.setsDiv.append(t)}renderFeatured(){return this.managers.appStickersManager.getFeaturedStickers().then(e=>{this.inputSearch.value||(e=this.filterRendered("",e),e.forEach(t=>{this.renderSet(t.set)}))})}filterRendered(e,t){t=t.slice();const s=Array.from(this.setsDiv.children);return 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<jE);return a}function YE(o,e,t,s){for(var i=0;i<zE;++i){var n=dS(e,t,s);if(n===0)return e;var a=nu(e,t,s)-o;e-=a/n}return e}function XE(o){return o}function _h(o,e,t,s){if(!(0<=o&&o<=1&&0<=t&&t<=1))throw new Error("bezier x values must be in [0, 1] range");if(o===e&&t===s)return XE;for(var i=qE?new Float32Array(dc):new Array(dc),n=0;n<dc;++n)i[n]=nu(n*rh,o,t);function a(r){for(var l=0,c=1,d=dc-1;c!==d&&i[c]<=r;++c)l+=rh;--c;var h=(r-i[c])/(i[c+1]-i[c]),u=l+h*rh,p=dS(u,o,t);return p>=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=`<div class="emoji-dropdown" style="display: none;">
<div class="emoji-container">
<div class="tabs-container"></div>
</div>
<div class="emoji-tabs menu-horizontal-div emoticons-menu no-stripe"></div>
</div>`;const e=[["search justify-self-start","search",-1],["emoji","smile",0],["stickers","stickers_face",1],["gifs","gifs",2],["delete justify-self-end","deleteleft",-1]],t=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<a;++n)e[n].bubble.classList.remove("is-group-last","is-group-first");const i=e[0].bubble;i.classList.remove("is-group-first"),i.classList.add("is-group-last")}insertItem(e){const{items:t}=this;$m(t,e,this.groups.sortGroupItemsKey,this.groups.reverse=e.reverse),e.group=this,t.length===1&&this.groups.insertGroup(this)}removeItem(e){us(this.items,e),this.items.length||us(this.groups.groups,this),e.group=void 0}mount(e){if(!this.groups.groups.includes(this)||!this.items.length){debugger;this.mounted&&this.onItemUnmount();return}const{offset:t,items:s}=this,{length:i}=s;bi(s,(n,a)=>{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<s;++t){const i=e[t];i.mounted=!1,i.group.removeItem(i),--s,--t}}getItemByBubble(e){return this.itemsMap.get(e)}get firstGroup(){return this.groups[this.groups.length-1]}get lastGroup(){return this.groups[0]}changeBubbleMessage(e,t){const s=this.getItemByBubble(e);s&&(s.mid=t.mid,s.message=t,s.groupMid=this.generateGroupMid(t,s.dateTimestamp),us(this.itemsArr,s),this.insertItemToArray(s,this.itemsArr))}changeItemBubble(e,t){this.itemsMap.delete(e.bubble),e.bubble=t,this.itemsMap.set(t,e)}changeBubbleByBubble(e,t){const s=this.getItemByBubble(e);s&&this.changeItemBubble(s,t)}canItemsBeGrouped(e,t){const s=this.chat.isOutMessage(e.message);return t.fromId===e.fromId&&e.dateTimestamp===t.dateTimestamp&&Math.abs(t.timestamp-e.timestamp)<=this.newGroupDiff&&!e.single&&!t.single&&s===this.chat.isOutMessage(t.message)&&(!this.chat.isAllMessagesForum||ha(e.message,!0)===ha(t.message,!0))&&(!s||e.message.fromId===I.myId)&&e.message.peerId===t.message.peerId}getSiblingsAtIndex(e,t){return[t[e-1],t[e+1]]}findGroupSiblingByItem(e,t){t=t.slice();const s=this.insertItemToArray(e,t);return this.findGroupSiblingInItems(e,t,s)}findGroupSiblingInItems(e,t,s=t.indexOf(e),i=t.length){const n=t[s-1];let a;if(n?.group&&this.canItemsBeGrouped(e,n))a=n;else for(let r=s+1;r<i;++r){const l=t[r];if(this.canItemsBeGrouped(e,l))l.group&&(a=l);else break}return a}addItemToGroup(e,t){t.insertItem(e),this.addItemToCache(e)}insertItemToArray(e,t){return $m(t,e,this.sortItemsKey,this.reverse=e.reverse)}insertGroup(e){return $m(this.groups,e,this.sortGroupsKey,this.reverse)}updateGroupsClassNames(){this.groups.forEach((e,t,s)=>{e.container.classList.toggle("bubbles-group-last",t===0),e.container.classList.toggle("bubbles-group-first",t===s.length-1)})}addItemToCache(e){this.insertItemToArray(e,this.itemsArr),this.itemsMap.set(e.bubble,e)}removeItemFromCache(e){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;i<t;++i){const n=e[i];if(n.group)continue;let a=!0;const r=this.getSiblingsAtIndex(i,e),d=this.findGroupSiblingInItems(n,e,i,t)?.group??(a=!1,new e_(this.chat,this,n.dateTimestamp));if(s.add(d),d.insertItem(n),!a){const h=this.splitSiblingsOnGrouping(r);h&&h.forEach(u=>s.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<this.minDate&&e.setFullYear(this.minDate.getFullYear(),this.minDate.getMonth(),this.minDate.getDate()),this.controlsDiv=document.createElement("div"),this.controlsDiv.classList.add("date-picker-controls"),this.prevBtn=it("down date-picker-prev",{noRipple:!0}),N(this.prevBtn,this.onPrevClick,{listenerSetter:this.listenerSetter}),this.nextBtn=it("down date-picker-next",{noRipple:!0}),N(this.nextBtn,this.onNextClick,{listenerSetter:this.listenerSetter}),this.monthTitle=document.createElement("div"),this.monthTitle.classList.add("date-picker-month-title"),this.controlsDiv.append(this.prevBtn,this.monthTitle,this.nextBtn),this.monthsContainer=document.createElement("div"),this.monthsContainer.classList.add("date-picker-months"),N(this.monthsContainer,this.onDateClick,{listenerSetter:this.listenerSetter}),this.body.append(this.controlsDiv,this.monthsContainer),s.withTime){this.timeDiv=document.createElement("div"),this.timeDiv.classList.add("date-picker-time");const n=document.createElement("div");n.classList.add("date-picker-time-delimiter"),n.append(":");const a=(r,l,c,d)=>{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;c<n;++c)this.options.showOverflowMonths?(a.setDate(a.getDate()+1),this.month.append(this.renderElement(!0,""+a.getDate()))):this.month.append(this.renderElement(!0));do{const c=e.getDate(),d=this.renderElement(e>this.maxDate||e<this.minDate,""+c);d.dataset.timestamp=""+e.getTime(),e.getTime()===this.selectedDate.getTime()&&(this.selectedEl=d,d.classList.add("active")),this.month.append(d),e.setDate(c+1)}while(e.getDate()!==1);const r=this.month.childElementCount%7;if(this.options.showOverflowMonths&&r)for(let c=r;c<7;++c)this.month.append(this.renderElement(!0,""+e.getDate())),e.setDate(e.getDate()+1);const l=Math.ceil(this.month.childElementCount/7);this.container.dataset.lines=""+l,this.monthsContainer.append(this.month)}}class va extends Es{constructor(e,t,s=["send_plain"],i){super({peerType:["dialogs","contacts"],onSelect:!e&&t?t:async(n,a)=>{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.max_id),this.classList.toggle("is-unread",n)}let i=this.children[1];if(!i){i=document.createElement("span"),i.classList.add("replies-footer-text");const n=Le("next","replies-footer-icon","replies-footer-icon-next"),a=document.createElement("div");Ni(a),this.append(i,n,a)}dt(i,s.element)}else this.classList.add("bubble-beside-button"),this.innerHTML=`<span class="replies-beside-text">${e?.replies?on(e.replies,0):""}</span>`,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_="&nbsp;",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",'<span class="time-post-author-comma">,'+i_+"</span>"),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<t;++i){let n=-1,a=1;for(let r=0;r<s;++r){const l=o[r]%1;l>=.5&&l<a&&(a=l,n=r)}if(n===-1)return;o[n]-=a}}else if(e<100){const t=100-e,s=o.length;for(let i=0;i<t;++i){let n=-1,a=0;for(let r=0;r<s;++r){const l=o[r]%1;l<.5&&l>a&&(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=`
<div class="poll-answer" data-index="${l}">
<div class="circle-hover">
<div class="animation-ring"></div>
<svg class="progress-ring">
<circle class="progress-ring__circle" cx="13" cy="13" r="9"></circle>
</svg>
</div>
<div class="poll-answer-percents"></div>
<div class="poll-answer-text"></div>
<svg version="1.1" class="poll-line" style="display: none;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 485.9 35" xml:space="preserve">
<use href="#poll-line"></use>
</svg>
</div>
`,d=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=`
<div class="poll-title"></div>
<div class="poll-desc">
<div class="poll-type"></div>
<div class="poll-avatars"></div>
</div>
`,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<Fo;++r)setTimeout(()=>{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;i<t;i+=s){const n=+o.slice(i,i+s),a=+e.slice(i,i+s),r=n-a;if(r)return r}return 0}function o_(o,e){if(o.toExponential){const t=o-e;return t<0?-1:t>0?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<i;++s)t[s]=e[s];return t}insertSlice(e,t=!0){if(!e.length)return;const s=this.slices[0];if(!s.length)return s.push(...e),s;const i=e[e.length-1],n=e[0];let a,r=-1,l=-1,c=0;for(;c<this.slices.length&&(a=this.slices[c],r=a.indexOf(i),l=a.indexOf(n),!(l!==-1&&r!==-1));++c)if(l!==-1||r!==-1)break;if(!(l!==-1&&r!==-1))if(l!==-1){const d=e.slice(a.length-l);a.push(...d)}else if(r!==-1){const d=e.slice(0,e.length-r-1);a.unshift(...d)}else{let d=0;for(const h=this.slices.length;d<h;++d){const u=this.slices[d];if(this.compareValue(e[0],u[0])===1)break}this.slices.splice(d,0,this.constructSlice(...e)),c=d}if(t)return this.flatten(c)}flatten(e){if(this.slices.length>=2)for(let t=0,s=this.slices.length;t<s-1;++t){const i=this.slices[t],n=this.slices[t+1];i.indexOf(n[0])!==-1&&(i.setEnd(n.end),this.slices.splice(t+1,1),t<e&&--e,--s,--t,this.insertSlice(n,!1))}return this.slices[e]}get first(){return this.slices[0]}get last(){return this.slices[this.slices.length-1]}get slice(){return this.first}get length(){return this.slice.length}findSlice(e){for(let t=0,s=this.slices.length;t<s;++t){const i=this.slices[t],n=i.indexOf(e);if(n!==-1)return{slice:i,index:n}}}findOffsetInSlice(e,t){for(let s=0;s<t.length;++s)if(this.compareValue(e,t[s])>=0)return{slice:t,offset:e===t[s]?s+1:s}}findSliceOffset(e){let t;for(let s=0;s<this.slices.length;++s){t=this.slices[s];const i=this.findOffsetInSlice(e,t);if(i)return{...i,sliceIndex:s}}if(t?.isEnd(1))return{slice:t,offset:t.length,sliceIndex:this.slices.length-1}}sliceMe(e,t,s){let i=this.slice,n=0,a=0;if(e){const m=this.findSliceOffset(e);if(!m)return;i=m.slice,n=a=m.offset}else if(!i.isEnd(2))return;const r=Math.max(a+t,0),l=a+t+s,c=i.slice(r,l),d=t<0?s+t:s,h=Math.abs(t),u=i.length-a>=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<s;++l){if(l<o.ip)continue;const c=i[l-1]||{},d={},h=a.computeAtPoint(l);h?(d.translation=h,t&&(d.anchor=t.k)):(d.translation=c.translation,d.anchor=c.anchor);const u=r.computeAtPoint(l);u?d.scale=u:d.scale=c.scale;const p=n.computeAtPoint(l);p?d.opacity=p:d.opacity=c.opacity,(h||u||p)&&(i[l]=d)}return i}let jp;function p_(){if(jp)return jp;const o=_s.makeAssetUrl("ReactionGeneric");return jp=_s.loadAnimationDataFromURL(o,"json").then(t=>{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",`
<div class="reaction-tag-background"></div>
<svg class="reaction-tag-svg" width="43" height="30" viewBox="0 0 43 30" xmlns="http://www.w3.org/2000/svg">
<path class="reaction-tag-svg-path" d="M40.8317 12.0432L34.9967 4.08636C33.1129 1.51761 30.1181 0 26.9326 0H7C3.13401 0 0 3.13401 0 7V23C0 26.866 3.13401 30 7 30H26.9326C30.1181 30 33.1129 28.4824 34.9967 25.9136L40.8317 17.9568C42.1223 16.1969 42.1223 13.8031 40.8317 12.0432Z" />
</svg>
<div class="reaction-tag-dot"></div>
`)}setCanRenderAvatars(e){this.canRenderAvatars=e}render(e){const t=!!this.stickerContainer;if(!t)this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add(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;$<H.length;++$){const Y=H[$][X];if(!Y)continue;let Q=!1,he=!1,le=!1,re=B,ge=B;if(Y.scale){const[de,Ze]=Y.scale;re*=de*4/100,ge*=Ze*4/100,he=de<0,le=Ze<0}let[be,Z]=Y.translation;be=(be+Y.anchor[0])*F-Math.abs(re)/2,Z=(Z+Y.anchor[1])*F-Math.abs(ge)/2,(he||le)&&(Q=!0,x.save(),x.scale(he?-1:1,le?-1:1),he&&(be=-be),le&&(Z=-Z)),Y.opacity&&(Q||(Q=!0,x.save()),x.globalAlpha=Y.opacity[0]/100),q?x.putImageData(z,be,Z):x.drawImage(z,be,Z,re,ge),Q&&x.restore()}X++,X>=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<Gm[this.type],c=new Array(n.length);this.sorted=n.map((d,h,u)=>{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;i<n;++i){const a=t[i],r=s.get(a.target);if(!r){console.error("intersection process no callbacks:",a);debugger;continue}a.isIntersecting?this.intersecting.add(a.target):this.intersecting.delete(a.target);for(const l of r)try{l(a)}catch(c){console.error("intersection process callback error:",c)}}},e)}getIntersecting(){return this.intersecting}disconnect(){this.observing.clear(),this.observingQueue.clear(),this.intersecting.clear(),this.observer.disconnect()}toggleObservingNew(e){if(this.freezedObservingNew===e)return;this.freezedObservingNew=e;const t=this.observingQueue;if(!e&&t.size){for(const[s,i]of t)for(const n of i)this.observe(s,n);t.clear()}}has(e,t,s=this.observing){const i=s.get(e);return!!(i&&i.has(t))}observe(e,t){if(this.freezedObservingNew&&this.has(e,t))return;const s=this.freezedObservingNew?this.observingQueue:this.observing;let i=s.get(e);i&&i.has(t)||(i||(i=new Set,s.set(e,i),s===this.observing&&this.observer.observe(e)),i.add(t))}unobserve(e,t){const s=this.freezedObservingNew&&!this.has(e,t)?this.observingQueue:this.observing,i=s.get(e);i&&(i.delete(t),i.size||(s.delete(e),this.observer.unobserve(e),this.intersecting.delete(e)))}}function f_(o){Fs(o.textContent)}function CS(o,e,t){if(t)return Yt(o.description||"",{...e,entities:o.entities});const s=Aa(o.description||"",150,180);return Yt(s,e)}function IS(o){let e=o.title||o.author||"";return e=Aa(e,80,100),Yt(e,{noLinks:!0,noLinebreaks:!0})}function ev(o){if(!o)return!1;const e=o.media?.document;return!!(o.pFlags.media_unread&&o.pFlags.mentioned&&(!e||!["voice","round"].includes(e.type)))}function LS(o){let e=0,t;for(const s of o)if(s.message){if(++e>1)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<this.minWidth?1.5:1,w=(()=>{for(let S=1;S!==g;++S)if(m[S-1]>m[S])return 1.5;return 1})(),b=Math.abs(f-this.maxHeight)*v*w;(!n||b<a)&&(n=u,a=b)}const r=n.lineCounts,l=n.heights,c=r.length;let d=0,h=0;for(let u=0;u!==c;++u){const p=r[u],m=l[u],g=Math.round(m);let f=0;for(let y=0;y!==p;++y){const v=Ye.None|(u===0?Ye.Top:Ye.None)|(u===c-1?Ye.Bottom:Ye.None)|(y===0?Ye.Left:Ye.None)|(y===p-1?Ye.Right:Ye.None),w=this.ratios[d],b=y===p-1?this.maxWidth-f:Math.round(w*m);e[d]={geometry:{x:f,y:h,width:b,height:g},sides:v},f+=b+this.spacing,++d}h+=g+this.spacing}return e}}function PS(o){const t=new au(o.items,o.maxWidth,o.minWidth,o.spacing,o.maxHeight).layout(),s=t.find(c=>c.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<t.particlesCount&&(this.genBuffer(),this.reset=!0),e.viewport(0,0,this.canvas.width,this.canvas.height),e.clear(e.COLOR_BUFFER_BIT),e.useProgram(this.program),e.uniform1f(this.resetHandle,this.reset?1:0),this.reset&&(this.time=0,this.reset=!1),e.uniform1f(this.timeHandle,this.time),e.uniform1f(this.deltaTimeHandle,i),e.uniform2f(this.sizeHandle,this.canvas.width,this.canvas.height),e.uniform1f(this.seedHandle,t.seed),e.uniform1f(this.radiusHandle,t.radius),e.uniform1f(this.noiseScaleHandle,t.noiseScale),e.uniform1f(this.noiseSpeedHandle,t.noiseSpeed),e.uniform1f(this.dampingMultHandle,t.dampingMult),e.uniform1f(this.velocityMultHandle,t.velocityMult),e.uniform1f(this.forceMultHandle,t.forceMult),e.uniform1f(this.longevityHandle,t.longevity),e.uniform1f(this.maxVelocityHandle,t.maxVelocity),e.uniform1f(this.noiseMovementHandle,t.noiseMovement),e.uniform3f(this.colorHandle,(t.color>>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=`<img src="${h.url}">`,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||!_?"":'<div class="document-download"></div>'}
<div class="document-name"></div>
<div class="document-size"></div>
`;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("<div>"),F_=ce("<div><div>"),R_=ce("<hr>"),D_=ce("<div class=sidebar-left-section-name-right>"),Cc="sidebar-left-section",xS=o=>(()=>{const e=TS();return D(e,()=>o.children),Ve(()=>Ce(e,ot(Cc+"-content",o.class))),e})(),tv=o=>j(xS,{class:Cc+"-caption",get children(){return M(o.caption,o.captionArgs)}}),gs=o=>{const[,e]=Xn(o,["name","nameArgs","nameRight","caption","captionArgs","captionOld","noDelimiter","fakeGradientDelimiter","noShadow","class"]);return(()=>{const t=F_(),s=t.firstChild,i=o.ref;return typeof i=="function"?wt(i,t):o.ref=t,uo(t,Ai({get class(){return ot(Cc+"-container",o.class)}},e),!1,!0),D(s,(()=>{const n=K(()=>!!o.fakeGradientDelimiter);return()=>n()?Ku():(()=>{const a=K(()=>!o.noDelimiter);return()=>a()&&R_()})()})(),null),D(s,j(xS,{get children(){return[K(()=>K(()=>!!o.name)()&&(()=>{const n=TS();return D(n,(()=>{const a=K(()=>typeof o.name=="string");return()=>a()?M(o.name,o.nameArgs):o.name})(),null),D(n,(()=>{const a=K(()=>!!o.nameRight);return()=>a()&&(()=>{const r=D_();return D(r,()=>o.nameRight),r})()})(),null),Ve(()=>Ce(n,ot("sidebar-left-h2",Cc+"-name"))),n})()),K(()=>o.children)]}}),null),D(s,(()=>{const n=K(()=>!!(o.caption&&o.captionOld));return()=>n()&&j(tv,o)})(),null),D(t,(()=>{const n=K(()=>!!(o.caption&&!o.captionOld));return()=>n()&&j(tv,o)})(),null),Ve(()=>Ce(s,ot(Cc,o.noShadow&&"no-shadow",o.fakeGradientDelimiter?"with-fake-delimiter":o.noDelimiter&&"no-delimiter"))),t})()},B_=()=>{const o=new Date;return o.setHours(0,0,0,0),o},AS=()=>{const o=new Date;return o.setFullYear(o.getFullYear()+1),o.setDate(o.getDate()-1),o},N_=(o,e)=>{const t=o.getTime()>AS().getTime()?new Date:o;return e&&t.setMinutes(t.getMinutes()+e),t};class If extends ip{constructor(e){if(super(N_(e.initDate,e.canSendWhenOnline!==void 0?10:void 0),e.onPick,{noButtons:!0,noTitle:!0,closable:!0,withConfirm:!0,minDate:e.minDate??B_(),maxDate:e.maxDate??AS(),withTime:!0,showOverflowMonths:!0,confirmShortcutIsSendShortcut:!0,title:!0}),this.canSendWhenOnline=e.canSendWhenOnline,this.isCustomButtonText=!!e.btnConfirmLangKey,this.element.classList.add("popup-schedule"),this.header.append(this.controlsDiv),this.title.replaceWith(this.monthTitle),this.body.append(this.btnConfirm),e.canSendWhenOnline){const t=ze("btn-primary btn-secondary btn-primary-transparent primary popup-schedule-secondary",{text:"Schedule.SendWhenOnline"});this.body.append(t),N(t,()=>{e.onPick(xc),this.hide()})}e.btnConfirmLangKey&&(this.btnConfirm.replaceChildren(M(e.btnConfirmLangKey)),this.btnConfirm.classList.add("text-uppercase"))}setTimeTitle(){if(super.setTimeTitle(),!(this.btnConfirm&&this.selectedDate)||this.isCustomButtonText)return;let e;const t=[],s=new Date;s.setHours(0,0,0,0);const i={minute:"2-digit",hour:"2-digit"},n=new Date(this.selectedDate.getTime());if(n.setHours(+this.hoursInputField.value,+this.minutesInputField.value),this.selectedDate.getTime()===s.getTime())e="Schedule.SendToday";else{e="Schedule.SendDate";const a={month:"short",day:"numeric"};n.getFullYear()!==s.getFullYear()&&(a.year="numeric"),t.push(new ke.IntlDateElement({date:n,options:a}).element)}t.push(new ke.IntlDateElement({date:n,options:i}).element),this.btnConfirm.replaceChildren(M(e,t))}}const O_=ce("<span>"),xi=o=>{const[,e]=Xn(o,["icon"]);return(()=>{const t=O_();return uo(t,Ai(e,{get class(){return ot("tgico",o.class)}}),!1,!0),D(t,()=>bb(o.icon)),t})()},U_=ce("<div>");let sv=!1;const H_=()=>{if(sv)return;const o=[];Xc.forEach((e,t)=>{const s=[...e.keys()],i=I.managers.appStoriesManager.getStoriesById(t,s,!0).then(()=>{s.forEach(n=>{e.get(n).mounted||(e.delete(n),e.size||Xc.delete(t))})});o.push(i)}),Promise.all(o).then(()=>{sv=!1})},Xc=new Map;window.wrappedStories=Xc;setInterval(H_,3e5);const Dd=o=>{const[e,t]=ne(),[s,i]=ne(),[n,a]=ne(!1);let r=Xc.get(o.peerId);r||Xc.set(o.peerId,r=new Map);let l=r.get(o.storyItem.id);l||r.set(o.storyItem.id,l={mounted:0}),++l.mounted,ut(()=>{--l.mounted});const c=Vr(o.storyItem.media),d=Ys().get();let h;const u=(()=>{const f=U_(),y=h;return typeof y=="function"?wt(y,f):h=f,uo(f,Ai(()=>o.containerProps||{}),!1,!1),f})(),p=(f,y)=>{[f.images.thumb,f.images.full].filter(Boolean).forEach(v=>{v.classList.add(y)})},m={photo:f=>{const y=f.document||f.photo,v=Ks({...o,container:h,photo:y,middleware:d,...o.forPreview&&{...o.noAspecter&&{size:Sn(y,150,200)},useRenderCache:!1},...o.forViewer&&{size:Sn(y,1/0,1/0),noFadeIn:!0},withoutPreloader:!o.withPreloader});return v.then(async w=>{d()&&(o.childrenClassName&&p(w,o.childrenClassName),await w.loadPromises.thumb,d()&&(t(w.images.thumb),a(!0),await w.loadPromises.full,d()&&i(w.images.full)))}),v},video:f=>{const y=f.document,v=f.alt_document,w=qn({...o,container:h,doc:y,altDoc:v,middleware:d,...o.forViewer&&{noInfo:!0,noAutoplayAttribute:!0},...o.forPreview&&{...o.noAspecter&&{photoSize:Sn(y,200,200,!1)},onlyPreview:!0},withoutPreloader:!o.withPreloader});return w.then(async b=>{if(!d()||(o.childrenClassName&&(b?.thumb&&p(b.thumb,o.childrenClassName),b?.video&&b.video.classList.add(o.childrenClassName)),b?.thumb&&await b.thumb.loadPromises.thumb,!d()))return;b?.thumb&&t(b.thumb.images.full||b.thumb.images.thumb),a(!0);const S=b?.video;S&&o.forViewer&&(S.loop=!1,S.muted=!0,Pi&&S.load()),await b?.loadPromise,d()&&i(S)}),w}};let g;switch(c._){case"messageMediaPhoto":{g=m.photo(c);break}case"messageMediaDocument":{g=m.video(c);break}}return{container:u,div:h,media:s,mediaResult:g,thumb:e,ready:n}},$_=o=>{let{loadPromises:e}=o;e&&delete o.loadPromises;const t=e&&Pt();e?.push(t),e=void 0;const[s,i]=ne(void 0,{equals:!1}),[n,a]=ne();return I.managers.acknowledged.appStoriesManager.getStoryById(o.peerId,o.storyId).then(async l=>{l.cached||t?.resolve();const c=await l.result;i(c)}),ye($s(()=>s(),l=>{if(!l){o.onExpiredStory?.(),t.resolve();return}ut(()=>{t?.reject()});const{container:c,ready:d}=Dd({...o,storyItem:l,forPreview:!0});ye($s(()=>d(),()=>{t?.resolve(),a(c)},{defer:!0}))},{defer:!0})),n},V_=ce("<span class=statistics-overview-item-value-description>"),G_=ce("<span>"),z_=ce("<div class=statistics-overview-item><div class=statistics-overview-item-value></div><div class=statistics-overview-item-name>"),K_=ce("<div class=statistics-overview>"),W_=ce("<div class=statistics-chart>"),j_=ce("<div>"),q_={growth_graph:"GrowthChartTitle",followers_graph:"FollowersChartTitle",mute_graph:"Notifications",top_hours_graph:"TopHoursChartTitle",views_by_source_graph:"ViewsBySourceChartTitle",new_followers_by_source_graph:"NewFollowersBySourceChartTitle",languages_graph:"LanguagesChartTitle",interactions_graph:"InteractionsChartTitle",iv_interactions_graph:"IVInteractionsChartTitle",reactions_by_emotion_graph:"ReactionsByEmotionChartTitle",story_interactions_graph:"StoryInteractionsChartTitle",story_reactions_by_emotion_graph:"StoryReactionsByEmotionChartTitle"},Q_={growth_graph:"GrowthChartTitle",members_graph:"GroupMembersChartTitle",new_members_by_source_graph:"NewMembersBySourceChartTitle",languages_graph:"MembersLanguageChartTitle",messages_graph:"MessagesChartTitle",actions_graph:"ActionsChartTitle",top_hours_graph:"TopHoursChartTitle",weekdays_graph:"TopDaysOfWeekChartTitle"},FS={views_graph:"ViewsAndSharesChartTitle",reactions_by_emotion_graph:"ReactionsByEmotionChartTitle"},Y_=FS,X_={followers:"FollowersChartTitle",enabled_notifications:"EnabledNotifications",views_per_post:"ViewsPerPost",views_per_story:"ViewsPerStory",shares_per_post:"SharesPerPost",shares_per_story:"SharesPerStory",reactions_per_post:"ReactionsPerPost",reactions_per_story:"ReactionsPerStory"},Z_={members:"MembersOverviewTitle",messages:"MessagesOverview",viewers:"ViewingMembers",posters:"PostingMembers"},RS={views:"StatisticViews",public_shares:"PublicShares",reactions:"Reactions",private_shares:"PrivateShares"},J_=RS;let ek,DS;function tk(){return ek??(ek=uL(()=>import("./chart-BIax9IsQ.js"),__vite__mapDeps([0,1]),import.meta.url).then(o=>{DS=o.default}))}function sk(o){return o.substring(o.indexOf("#"))}const Hn=(o,e)=>({_:"statsAbsValueAndPrev",current:o,previous:0,approximate:e}),Bd=(o={})=>ne({rendered:[],values:[],left:0,count:0,...o},{equals:!1}),Wm=(o,e,t,s="PollResults.LoadMore")=>{const i=ze("btn btn-primary btn-transparent primary",{icon:"down",text:s,textArgs:[o]});return N(i,()=>{e(i)},{listenerSetter:t}),i},ik=({value:o,title:e,includeZeroValue:t,describePercentage:s})=>{const i=o._==="statsPercentValue";let n;if(i)n=`${(o.part/o.total*100).toFixed(2)}%`,s&&(n=[K(()=>`≈${o.part} `),(()=>{const r=V_();return D(r,n),r})()]);else{if(n=on(o.current,1),o.approximate&&(n="≈"+n),!o.current&&!o.previous&&!t)return;if(o.current!==o.previous&&o.previous){const a=o.current-o.previous,r=Math.abs(a),l=`${a>0?"+":"-"}${on(r,1)}`,c=+(Math.abs(1-o.current/o.previous)*100).toFixed(2),d=`${l} (${c}%)`;n=[n," ",(()=>{const h=G_();return D(h,d),Ve(()=>Ce(h,ot("statistics-overview-item-value-description",a>0?"green":"red"))),h})()]}}return(()=>{const a=z_(),r=a.firstChild,l=r.nextSibling;return D(r,n),D(l,()=>M(e)),a})()},BS=o=>(()=>{const e=K_();return D(e,j(ti,{get each(){return o.items},children:ik})),e})();class Nd extends Xt{constructor(){super(...arguments);Lr(this,"renderPeer",async t=>{const s=t._==="message"?t.peerId:t.user_id.toPeerId(!1),i=[],{dom:n}=Xe.addDialogNew({peerId:s,container:!1,rippleEnabled:!0,avatarSize:"abitbigger",loadPromises:i,wrapOptions:{middleware:this.middlewareHelper.get()},meAsSaved:!1});let a;return t._==="message"?(a=[await da(s.toChatId()),M("Views",[on(t.views,1)])],n.listEl.dataset.mid=""+t.mid):t._==="statsGroupTopPoster"?a=[t.messages&&M("messages",[t.messages]),t.avg_chars&&M("CharactersPerMessage",[M("Characters",[t.avg_chars])])]:t._==="statsGroupTopAdmin"?a=[t.deleted&&M("Deletions",[t.deleted]),t.banned&&M("Bans",[t.banned]),t.kicked&&M("Restrictions",[t.kicked])]:a=[t.invitations&&M("Invitations",[t.invitations])],a=a.filter(Boolean),a.length&&n.lastMessageSpan.replaceChildren(...pi(a,!1)),await Promise.all(i),{container:n.listEl,peerId:s}});Lr(this,"renderPublicForward",async t=>{if(t._==="publicForwardMessage"){const n=t.message;return this.renderRecentPost({_:"postInteractionCountersMessage",forwards:n.forwards,msg_id:n.mid,views:n.views,reactions:n.reactions?n.reactions.results.reduce((a,r)=>a+r.count,0):0},n.peerId,n)}const s=t.story;if(!s)return;const i=s.views;return this.renderRecentPost({_:"postInteractionCountersStory",forwards:i?.forwards_count||0,story_id:s.id,views:i?.views_count||0,reactions:i?.reactions_count||0},at(t.peer),void 0,s)})}onOpenAfterTimeout(){this.openPromise.resolve()}_construct(t,s,i,n,a,r){const l=this,c=new ke.IntlDateElement({options:{}}),d=(L,E={})=>{E.displayYear??(E.displayYear=!0),E.isMonthShort??(E.isMonthShort=!0);const _=new Date(L);return c.update({date:_,options:{weekday:E.displayWeekDay?E.isShort?"short":"long":void 0,year:E.displayYear?"numeric":void 0,hour:E.displayHours?"2-digit":void 0,minute:E.displayHours?"2-digit":void 0,month:E.isMonthShort?"short":"long",day:"numeric"}}),c.element.textContent},h=L=>{const E=new Date(L);return c.update({date:E,options:{hour:"2-digit",minute:"2-digit"}}),c.element.textContent},u=()=>{const L=Ls.getProperty("surface-color"),E=Ls.getProperty("primary-color"),_=Ls.getProperty("secondary-color"),k=_n(L),x=oc(_n(_),oc(_n(E),k,.1),.2),A=oc(_n(_),oc(_n(E),k,.3),.4);return{primary:Ls.getProperty("primary-color"),secondary:Ls.getProperty("secondary-color"),background:L,backgroundRgb:k,text:Ls.getProperty("primary-text-color"),dates:Ls.getProperty("secondary-text-color"),grid:`rgba(${_n(Ls.getProperty("secondary-text-color")).join(", ")}, 0.2)`,axis:{x:Ls.getProperty("secondary-text-color"),y:Ls.getProperty("secondary-text-color")},barsSelectionBackground:`rgba(${k.join(", ")}, 0.5)`,miniMask:`rgba(${x.join(", ")}, 0.6)`,miniFrame:`rgb(${A.join(", ")})`}};let p=u();this.listenerSetter.add(I)("theme_changed",()=>{p=u()});const m=this.isBroadcast?q_:this.isMegagroup?Q_:this.isStory?Y_:FS,g=Object.keys(m).map(L=>{const E=this.stats[L];return E&&{statsGraph:E,title:m[L],percentage:L==="languages_graph"}}).filter(Boolean),f=({statsGraph:L,title:E,percentage:_})=>{vr(()=>{let B=JSON.parse(L.json.data);const R=(G,z)=>{for(const q in G.colors){const $=G.colors[q];G.colors[q]=sk($)}if(z)for(const q in G.types)G.types[q]==="bar"&&(G.types[q]="area");return G};B=R(B,_);const O={getLabelDate:d,getLabelTime:h,tooltipOnHover:!0},X=L.zoom_token,F=DS.render({container:T,data:{...B,...O,x_on_zoom:X?async G=>{const z=await this.managers.appStatisticsManager.loadAsyncGraph(X,G,this.dcId);if(z._!=="statsGraphError")return{...R(JSON.parse(z.json.data),_),...O}}:void 0},settings:{darkMode:as.isNight(),ALL_LABEL:ke.format("Chart.Tooltip.All",!0),DATES_SIDE:"left",DATES_WEIGHT:"normal",DATES_FONT_SIZE:14,ZOOM_TEXT:ke.format("ZoomOut",!0),FONT:{family:dl,bold:"500",normal:"400"},COLORS:p}}),H=()=>{[["primary-color",p.primary],["background-color",p.background],["background-color-rgb",p.backgroundRgb.join(", ")],["text-color",p.text],["secondary-color",p.secondary],["font-family",dl]].forEach(([z,q])=>{F.$wrapper.style.setProperty(`--tchart-${z}`,q)})};H(),this.listenerSetter.add(I)("theme_changed",()=>{F.setDarkMode(as.isNight(),{...p}),H()})});const k=document.createElement("div"),x=document.createElement("div");k.classList.add("statistics-title");const A=M(E);A.classList.add("statistics-title-text"),k.append(A);let T;return j(gs,{name:k,nameRight:x,get children(){const B=W_(),R=T;return typeof R=="function"?wt(R,B):T=B,B}})},y=this.stats._==="stats.broadcastStats"?X_:this.isMegagroup?Z_:this.isStory?J_:RS,v=Object.keys(y).map(L=>{const E=this.stats[L];return E&&{value:E,title:y[L]}}).filter(Boolean),w=(L,E)=>mo([L,E].map(_=>new ke.IntlDateElement({date:new Date(_*1e3),options:{month:"short",day:"numeric",year:"numeric"}}).element)," — "),b=this.stats.period,S=["TopMembers","TopAdmins","TopInviters"];let C;const P=[r&&j(gs,{get children(){return r.container}}),j(gs,{name:"StatisticOverview",get nameRight(){return b&&w(b.min_date,b.max_date)},get children(){return j(BS,{items:v})}}),j(ti,{each:g,children:f}),K((()=>{const L=K(()=>!!t.length);return()=>L()&&j(gs,{ref(E){const _=C;typeof _=="function"?_(E):C=E},name:"RecentPosts",get children(){return t.map(({container:E})=>E)}})})()),j(ti,{each:[s,i,n],children:(L,E)=>{if(!L.length)return;L=L.slice();const _=Xe.createChatList();_.append(...L.splice(0,10).map(({container:x})=>x));let k;return L.length&&(k=Wm(L.length,()=>{k.remove(),_.append(...L.map(({container:x})=>x))},l.listenerSetter)),j(gs,{get name(){return S[E()]},get nameRight(){return b&&w(b.min_date,b.max_date)},get children(){return[_,k]}})}}),K((()=>{const L=K(()=>!!a().count);return()=>L()&&j(gs,{name:"PublicSharesCount",get nameArgs(){return[a().count]},get children(){return[(()=>{const E=j_();return wt(_=>{Xe.setListClickListener({list:_,onFound:k=>{if(k.dataset.storyId)return mr({target:()=>k.querySelector(".avatar"),peerId:k.dataset.peerId.toPeerId(),id:+k.dataset.storyId}),!1},withContext:void 0,autonomous:void 0,openInner:!0})},E),D(E,()=>a().rendered),E})(),K(()=>K(()=>!!a().loadMore)()&&Wm(a().count-a().rendered.length,E=>{const _=jt(E,!0);a().loadMore().finally(()=>_())},l.listenerSetter))]}})})())];if(C){const L=new Map;t.forEach(({container:x,postInteractionCounters:A})=>{L.set(x,A)});const E=x=>U(x.target,"statistics-post");let _;const k=()=>{this.slider.createTab(Nd).open(this.chatId,_.msg_id,_.story_id)};N(C,x=>{_=L.get(E(x)),_&&k()},{listenerSetter:this.listenerSetter}),ln({buttons:[{icon:"statistics",text:"ViewStatistics",onClick:k},{icon:"message",text:"Message.Context.Goto",onClick:()=>{me.setInnerPeer({peerId:this.chatId.toPeerId(!0),lastMsgId:_.msg_id})},verify:()=>_._==="postInteractionCountersMessage"},{icon:"stories",text:"ViewStory",onClick:()=>{mr({peerId:this.chatId.toPeerId(!0),id:_.story_id})},verify:()=>_._==="postInteractionCountersStory"}],listenTo:C,listenerSetter:this.listenerSetter,findElement:x=>{const A=E(x);return _=L.get(A),A},middleware:this.middlewareHelper.get()})}return P}async renderRecentPost(t,s=this.chatId.toPeerId(!0),i,n,a){const r=document.createDocumentFragment(),l=[["reactions",t.reactions],["reply",t.forwards]];!a&&l.forEach(([p,m])=>{if(!m)return;const g=Le(p,"statistics-post-counter-icon");p==="reply"&&g.classList.add("icon-reflect");const f=document.createElement("span");f.classList.add("statistics-post-counter"),f.append(g,on(m,1)),r.append(f)});const c=new ve({title:!0,titleRight:a?void 0:M("Views",[Ha(t.views)]),subtitle:!0,subtitleRight:a?void 0:r,clickable:!0,noWrap:!0,asLink:!!(i||n)}),{container:d}=c;d.classList.add("statistics-post"),c.title.classList.add("statistics-post-title");const h=this.middlewareHelper.get(),u=document.createElement("div");if(u.classList.add("statistics-post-media"),i||n){const{node:p,readyThumbPromise:m,setStoriesSegments:g}=es({middleware:h,size:42,isDialog:!0,peerId:s});c.container.dataset.peerId=""+s,n?(g([{length:1,type:"unread"}]),c.container.dataset.storyId=""+n.id):c.container.dataset.mid=""+i.mid,u.append(p),await m,c.title.append(await Oe({peerId:s})),c.subtitle.append(ws(i?.date||n?.date)),c.applyMediaElement(u,"abitbigger")}else if(t._==="postInteractionCountersMessage"){if(d.classList.add("statistics-post-message"),i||(i=this.messages.get(t.msg_id)),!await wf({titleEl:c.subtitle,title:ws(i.date),subtitleEl:c.title,message:i,mediaEl:u,middleware:h,withoutMediaType:!0})){const{node:m,readyThumbPromise:g}=es({middleware:h,peerId:s,size:42});u.append(m),await g}c.applyMediaElement(u,"abitbigger")}else{d.classList.add("statistics-post-story"),n||(n=this.stories.get(t.story_id)),c.title.append(M("Story")),c.subtitle.append(ws(n.date));const p=document.createElement("div");p.classList.add("avatar-stories-simple","is-unread"),u.append(p),await Jt(m=>{h.onDestroy(m);const{ready:g,div:f}=Dd({storyItem:n,peerId:this.chatId.toPeerId(!0),forPreview:!0,noInfo:!0,withPreloader:!1,noAspecter:!0}),y=Pt();return ye(()=>{g()&&(u.append(f),y.resolve())}),y}),c.applyMediaElement(u,"abitbigger")}return{container:d,postInteractionCounters:t}}async loadStats(){const t=this.chatId.toPeerId(!0),s=this.managers.appStatisticsManager,i=100,n=this.isBroadcast?s.getBroadcastStats:this.isMegagroup?s.getMegagroupStats:this.isStory?s.getStoryStats:s.getMessageStats,a=this.isMessage?this.managers.appMessagesManager.reloadMessages(t,this.mid):void 0,r=this.isMessage?s.getMessagePublicForwards({peerId:t,mid:this.mid,limit:i}):void 0,l=this.isStory?this.managers.appStoriesManager.getStoryById(t,this.storyId):void 0,c=this.isStory?s.getStoryPublicForwards({peerId:t,id:this.storyId,limit:i}):void 0,{stats:d,dcId:h}=await n({peerId:t,dark:as.isNight(),storyId:this.storyId,mid:this.mid});this.stats=d,this.dcId=h;const u=[];for(const S in d){const C=d[S];if(C._==="statsGraphAsync"){const P=s.loadAsyncGraph(C.token,void 0,h).then(L=>{if(L._==="statsGraphError"){delete d[S];return}d[S]=L});u.push(P)}else C._==="statsGraphError"&&delete d[S]}const p=d.recent_posts_interactions||[];p.forEach(S=>{let C;S._==="postInteractionCountersMessage"?C=this.managers.appMessagesManager.reloadMessages(t,S.msg_id).then(P=>{if(!P){us(p,S);return}this.messages.set(P.mid,P)}):C=this.managers.appStoriesManager.getStoryById(t,S.story_id).then(P=>{if(!P){us(p,S);return}this.stories.set(P.id,P)}),u.push(C)});const m=Promise.all([a,r,l,c]).then(async([S,C,P,L])=>{const[E,_]=Bd();if(!S&&!P)return E;if(S){this.messages.set(S.mid,S);const k=C.count;d.views=Hn(S.views),d.reactions=Hn(S.reactions?S.reactions.results.reduce((T,B)=>T+B.count,0):0),d.public_shares=Hn(k),d.private_shares=Hn(S.forwards-k,!0),_(T=>(T.count=k,T));let x;const A=async T=>{x=T.next_offset;const B=T.forwards.map(this.renderPublicForward),R=await Promise.all(B);_(O=>(O.rendered.push(...R.map(({container:X})=>X)),O.loadMore=x?()=>s.getMessagePublicForwards({peerId:t,mid:this.mid,limit:i,offset:x}).then(A):void 0,O))};await A(C)}else{const k=L.count,x=P.views;d.views=Hn(x.views_count),d.reactions=Hn(x.reactions_count||0),d.public_shares=Hn(k),d.private_shares=Hn(Math.abs((x.forwards_count||0)-k),!0),_(B=>(B.count=k,B));let A;const T=async B=>{A=B.next_offset;const R=B.forwards.map(this.renderPublicForward),O=await Promise.all(R);_(X=>(X.rendered.push(...O.map(({container:F})=>F)),X.loadMore=A?()=>s.getStoryPublicForwards({peerId:t,id:P.id,limit:i,offset:A}).then(T):void 0,X))};await T(L)}return E});u.push(m);const g=d.top_posters||[],f=d.top_admins||[],y=d.top_inviters||[],v=g.map(this.renderPeer),w=f.map(this.renderPeer),b=y.map(this.renderPeer);return Promise.all(u).then(()=>{const S=p.map(L=>this.renderRecentPost(L)),C=this.isMessage?this.renderRecentPost({_:"postInteractionCountersMessage",msg_id:this.mid,forwards:0,reactions:0,views:0},void 0,void 0,void 0,!0):void 0,P=[Promise.all(S),Promise.all(v),Promise.all(w),Promise.all(b),m,C];return Promise.all(P)})}async init(t,s,i){this.container.classList.add("statistics-container"),this.chatId=t,this.mid=s,this.storyId=i,this.messages=new Map,this.stories=new Map,this.openPromise=Pt(),s?this.isMessage=!0:i?this.isStory=!0:(this.isBroadcast=await this.managers.appChatsManager.isBroadcast(t),this.isMegagroup=await this.managers.appChatsManager.isMegagroup(t)),this.setTitle(this.isBroadcast?"Statistics":this.isMegagroup?"GroupStats.Title":this.isStory?"StoryStatistics":"PostStatistics");const n=Promise.all([tk(),this.openPromise,this.loadStats()]),[a,r]=ne(!1),l=await Rw({title:()=>M("LoadingStats"),description:()=>M("LoadingStatsDescription"),assetName:"StatsEmoji",middleware:this.middlewareHelper.get(),hide:a,isFullSize:!0});this.scrollable.append(l),n.then(async([c,d,h])=>{console.log(this.stats,this.messages,this.stories);const u=document.createElement("div");this.scrollable.append(u);const p=Hi(()=>this._construct(...h),u);if(this.eventListener.addEventListener("destroy",p),st.isAvailable("animations")){const m=[{opacity:"1"},{opacity:"0"}],g={duration:200,fill:"forwards",easing:"ease-in-out"},f=[l.animate(m,g),u.animate(m.slice().reverse(),g)];await Promise.all(f.map(y=>y.finished))}r(!0)})}}const nk=ce("<div class=popup-gift-link-wrapper><div class=popup-gift-link-header><img class=popup-gift-link-image><div class=popup-gift-link-title></div><div class=popup-gift-link-subtitle>"),ak=ce("<div class=popup-gift-link-share>");class ya extends ee{constructor(e,t,s){super("popup-boosts popup-gift-link",{closable:!0,overlayClosable:!0,body:!0,withConfirm:!0,scrollable:!0,floatingHeader:!0,footer:!0,title:!0}),this.slug=e,this.stack=t,this.checkedGiftCode=s,this.isInChat=!!s,this.construct()}_construct(e){const t=this,s=!!this.checkedGiftCode.used_date,i=s?"BoostingUsedGiftLink":"BoostingGiftLink";this.title.replaceChildren(M(i));const n=this.isInChat&&!s?"":"https://t.me/giftcode/"+this.slug,a=new xd({button:!1,listenerSetter:this.listenerSetter,url:n,noRightButton:!n,onClick:!n&&(()=>{Ee({langPackKey:"BoostingOnlyRecipientCode"})})});e&&(e.classList.add("invite-link-dots"),a.container.appendChild(e));const r=v=>{const w=this;return j(ZC,{peerId:v,onClick:()=>{w.hideWithCallback(()=>{me.setInnerPeer({peerId:v})})}})},l=this.checkedGiftCode.pFlags.via_giveaway,c=at(this.checkedGiftCode.from_id),d=this.checkedGiftCode.to_id&&at(this.checkedGiftCode.to_id),h=this.checkedGiftCode.giveaway_msg_id||l?document.createElement("a"):void 0;h&&(h.href="#",h.append(M("BoostingIncompleteGiveaway")),N(h,()=>{this.hideWithCallback(()=>{me.setInnerPeer({peerId:c,lastMsgId:this.checkedGiftCode.giveaway_msg_id})})},{listenerSetter:this.listenerSetter}));const u=d?d===I.myId?M("BoostingYouWereSelected"):M("BoostingUserWasSelected",[new Rt({peerId:d}).element]):h;let p=[["BoostingFrom",r(c)],["BoostingTo",d?r(d):M("BoostingNoRecipient")],["BoostingGift",M("BoostingTelegramPremiumFor",[eo(this.checkedGiftCode.months)])],!this.isInChat&&["BoostingReason",u],["BoostingDate",ws(this.checkedGiftCode.date,void 0,!0)]];p=p.filter(Boolean);const m=ni(v=>{oe(v),this.hideWithCallback(()=>{ya.shareGiftLink(n,!0)})});let g;const f=(()=>{const v=nk(),w=v.firstChild,b=w.firstChild,S=b.nextSibling,C=S.nextSibling,P=g;return typeof P=="function"?wt(P,b):g=b,D(S,()=>M(i)),D(C,()=>s?M("BoostingLinkUsed"):M(d===I.myId?"BoostingLinkAllows":d?"BoostingLinkAllowsToUser":"BoostingLinkAllowsAnyone",d?[new Rt({peerId:d}).element]:void 0)),D(v,()=>a.container,null),D(v,j(XC,{content:p}),null),D(v,(()=>{const L=K(()=>!t.isInChat||!s);return()=>L()&&(()=>{const E=ak();return D(E,()=>s?M("BoostingUsedLinkDate",[ws(t.checkedGiftCode.used_date,void 0,!0)]):t.isInChat&&!t.checkedGiftCode.slug?M("BoostingLinkNotActivated"):M(d?"Giveaway.SendLinkToFriend":"Giveaway.SendLinkToAnyone",[m])),E})()})(),null),v})();Kn(g,`assets/img/premium-star${window.devicePixelRatio>1?"@2x":""}.png`);const y=!this.isInChat&&!s;return this.btnConfirm.append(M(y?"BoostingUseLink":"OK")),this.btnConfirm.classList.add("popup-boosts-button"),this.footer.append(this.btnConfirm),this.body.after(this.footer),this.footer.classList.add("abitlarger"),N(this.btnConfirm,()=>{if(!y){this.hide();return}ya.applyGiftCode(this.slug,this.btnConfirm,this)},{listenerSetter:this.listenerSetter}),f}async construct(){if(this.checkedGiftCode??(this.checkedGiftCode=await this.managers.appPaymentsManager.checkGiftCode(this.slug)),Kh(this.checkedGiftCode)){this.destroy(),Vt.show({gift:this.checkedGiftCode,stack:this.stack});return}let e;if(this.isInChat&&!this.checkedGiftCode.used_date){const{canvas:i,readyResult:n}=Qc.create({width:320,height:32,middleware:this.middlewareHelper.get(),animationGroup:"STICKERS-POPUP",config:{particlesCount:1e3,color:as.isNight()?16777215:0}});await n,e=i}const t=document.createElement("div");this.scrollable.append(t,this.btnConfirm);const s=Hi(()=>this._construct(e),t);this.addEventListener("closeAfterTimeout",s),this.show()}static async shareGiftLink(e,t){const s=await Es.createSharingPicker2();I.managers.appMessagesManager.sendText({peerId:s,text:e}),t?me.setInnerPeer({peerId:s}):Ee({langPackKey:I.myId===s?"BoostingGiftLinkForwardedToSavedMsg":"BoostingGiftLinkForwardedTo",langPackArguments:[await Oe({peerId:s})]})}static async applyGiftCode(e,t,s){const i=jt(t,!0);try{await ee.MANAGERS.appPaymentsManager.applyGiftCode(e),s.hide(),Ee({langPackKey:"GiftLink.UseSuccess"})}catch(n){if(n.type.includes("PREMIUM_SUB_ACTIVE_UNTIL_")){s.hide();const a=+n.type.split("_").pop();let r;Ct({titleLangKey:"GiftPremiumActivateErrorTitle",descriptionLangKey:"GiftCode.Activation.After",descriptionLangArgs:[ws(a),ni(()=>{fs(r.element),s.hide(),this.shareGiftLink("https://t.me/giftcode/"+e)})],button:r={langKey:"OK",isCancel:!0}})}console.error("giftcode error",n),i()}}}const rk=ce("<div><div class=menu-horizontal-div-item-span><i>"),kh=ce("<div>"),ok=ce('<div class="menu-horizontal-div-item boosts-users-tab"><div class=menu-horizontal-div-item-span><i>'),lk=ce('<div class="menu-horizontal-div boosts-users-tabs">'),ck=ce("<div class=boosts-users-contents>"),NS=o=>o===12?"red":o===3?"green":"blue",iv=(o,e)=>{const t=(e-o)/86400;return Math.round(t/30)},OS=o=>{const{quantity:e,months:t}=o.giveaway,s=new ve({titleLangKey:"BoostingGiveawayMsgInfoPlural1",titleLangArgs:[e],subtitleLangKey:"Giveaway.Prepaid.Subtitle",subtitleLangArgs:[e,M("Giveaway.Prepaid.Period",[t])],clickable:o.clickable,listenerSetter:o.listenerSetter,rightContent:HS({boosts:(o.appConfig.giveaway_boosts_per_premium||1)*e})});s.title.classList.add("text-bold");const i=s.createMedia("abitbigger"),n=Fn({size:42});return n.set({icon:"gift_premium",color:NS(t)}),i.append(n.node),s.container};function dk(o){const e=o.class,t=c=>(()=>{const d=rk(),h=d.firstChild,u=h.firstChild;return D(h,()=>c.children,u),Ve(()=>Ce(d,ot("menu-horizontal-div-item",`${e}-tab`))),d})(),s=c=>(()=>{const d=kh();return D(d,()=>c.children),Ve(()=>Ce(d,ot(`${e}-content`,c.hide&&"hide"))),d})();let i,n;const a=[(()=>{const c=kh(),d=i;return typeof d=="function"?wt(d,c):i=c,D(c,j(ti,{get each(){return o.menu},children:h=>j(t,{children:h})})),Ve(()=>Ce(c,ot("menu-horizontal-div",`${e}-tabs`))),c})(),(()=>{const c=kh(),d=n;return typeof d=="function"?wt(d,c):n=c,D(c,j(ti,{get each(){return o.content},children:(h,u)=>j(s,{get hide(){return u()!==o.tab()},children:h})})),Ve(()=>Ce(c,ot(`${e}-contents`))),c})()],r=new Ut;return ut(()=>{r.removeAll()}),Ml(i,n,c=>{o.onChange(c)},void 0,void 0,void 0,r)(o.tab()),a}class hk extends Xt{constructor(){super(...arguments);Lr(this,"renderBoost",async t=>{const s=1*(t.multiplier||1),i=iv(t.date,t.expires);let n=t.user_id?.toPeerId(!1);n===I.myId&&t.pFlags.unclaimed&&(n=void 0);let a;s>1&&(a=document.createElement("span"),a.classList.add("boosts-user-boosts","boosts-user-badge"),a.append(Le("boost"),` ${s}`));let r;n?(r=await Oe({peerId:n}),r.classList.add("boosts-user-name")):r=M(t.pFlags.unclaimed?"BoostingUnclaimed":"BoostingToBeDistributed");let l;n?l=M("BoostsExpiration",[s,ws(t.expires,void 0,!0)]):(l=document.createElement("span"),l.append(...mo([M("BoostingShortMonths",[i]),ws(t.expires,void 0,!0)]," • ")));let c;(t.pFlags.giveaway||t.pFlags.gift)&&(c=document.createElement("span"),c.classList.add("boosts-user-badge-right","boosts-user-badge"),c.append(Le(t.pFlags.giveaway?"gift_premium":"gift"),M(t.pFlags.giveaway?"BoostingGiveaway":"BoostingGift")),c.classList.toggle("is-gift",!t.pFlags.giveaway&&!!t.pFlags.gift));const d=new ve({title:!0,subtitle:l,clickable:!0,noWrap:!0,rightContent:c});n&&(d.container.dataset.peerId=""+n),d.title.classList.add("boosts-user-title"),d.title.append(...[r,a].filter(Boolean));const h=d.createMedia("abitbigger"),u=es({peerId:n,size:42,middleware:this.middlewareHelper.get()});return h.append(u.node),n?await u.readyThumbPromise:u.set({icon:t.pFlags.unclaimed?"deleteuser":"noncontacts",color:NS(i)}),this.targets.set(d.container,t),d.container})}_construct(t,s,i,n){const a=this,r=new Vu({progress:!0,hint:{icon:"boost",noStartEnd:!0}}),c=t.next_level_boosts===void 0?1:(t.boosts-t.current_level_boosts)/(t.next_level_boosts-t.current_level_boosts);r.setProgress(c,""+t.boosts,{from1:M("BoostsLevel",[t.level]),to1:M("BoostsLevel",[t.level+1]),from2:M("BoostsLevel",[t.level]),to2:M("BoostsLevel",[t.level+1])}),r._setHintActive();const d=t.boost_url,h=new xd({listenerSetter:this.listenerSetter,url:d}),u=ze("btn-primary btn-transparent primary",{icon:"gift_premium",text:"BoostingGetBoostsViaGifts"});N(u,()=>{ee.createPopup(av,this.peerId)},{listenerSetter:this.listenerSetter});const p=M("NoBoostersHint");p.classList.add("boosts-no-boosters");let m,g;const f=_=>(()=>{const k=ok(),x=k.firstChild,A=x.firstChild;return D(x,()=>M(_.key,[_.count]),A),k})(),y=_=>{const k=this;return(()=>{const x=kh();return D(x,(()=>{const A=K(()=>!!_.list.count);return()=>A()?[K(()=>_.list.rendered),K((()=>{const T=K(()=>!!_.list.loadMore);return()=>T()&&Wm(_.list.count-_.list.rendered.length,B=>{const R=jt(B,!0);_.list.loadMore().finally(()=>R())},k.listenerSetter,_.moreKey)})())]:p})()),Ve(()=>Ce(x,ot("boosts-users-content",!_.list.count&&"is-empty",_.hide&&"hide"))),x})()},[v,w]=ne(0),[b,S]=ne(t.prepaid_giveaways?.slice()||[],{equals:!1}),C=K(()=>t.gift_boosts===t.boosts),P=K(()=>!C()&&!!n().count),L=[j(gs,{get children(){return[K(()=>r.container),j(BS,{get items(){return[{title:"BoostsLevel2",value:Hn(t.level),includeZeroValue:!0},{title:"PremiumSubscribers",value:t.premium_audience,includeZeroValue:!0,describePercentage:!0},{title:"BoostsExisting",value:Hn(t.boosts),includeZeroValue:!0},{title:"BoostsToLevel",value:Hn(t.next_level_boosts-t.boosts)}]}})]}}),K((()=>{const _=K(()=>!!(a.canCreateGiveaway&&b().length));return()=>_()&&j(gs,{name:"Giveaway.Prepaid",nameArgs:[1],caption:"BoostingSelectPaidGiveaway",get children(){return j(ti,{get each(){return b()},children:k=>j(OS,{giveaway:k,appConfig:s,clickable:()=>{ee.createPopup(av,a.peerId,k,()=>{S(x=>(us(x,k),x))})},get listenerSetter(){return a.listenerSetter}})})}})})()),j(gs,{class:"boosts-users-container",get children(){return[(()=>{const _=lk(),k=m;return typeof k=="function"?wt(k,_):m=_,D(_,j(f,{key:"BoostingBoostsCount",get count(){return i().count}}),null),D(_,(()=>{const x=K(()=>!!P());return()=>x()&&j(f,{key:"BoostingGiftsCount",get count(){return n().count}})})(),null),_})(),(()=>{const _=ck();_.$$click=async x=>{const A=U(x.target,"row"),T=a.targets.get(A);if(!T)return;const B=T.used_gift_slug,R=T.user_id?.toPeerId(!1);R&&!T.pFlags.gift&&!T.pFlags.unclaimed&&!T.pFlags.giveaway?me.setInnerPeer({peerId:T.user_id.toPeerId(!1)}):R&&R!==I.myId?ee.createPopup(ya,B,void 0,{_:"payments.checkedGiftCode",chats:[],date:T.date,months:iv(T.date,T.expires),pFlags:{via_giveaway:T.pFlags.giveaway||void 0},users:[],from_id:await a.managers.appPeersManager.getOutputPeer(a.peerId),giveaway_msg_id:T.giveaway_msg_id,slug:B,to_id:R.toUserId(),used_date:B?1:void 0}):B?ee.createPopup(ya,B):Ee({langPackKey:"BoostingRecipientWillBeSelected"})};const k=g;return typeof k=="function"?wt(k,_):g=_,D(_,j(y,{get list(){return i()},get hide(){return v()!==0},moreKey:"BoostingShowMoreBoosts"}),null),D(_,(()=>{const x=K(()=>!!P());return()=>x()&&j(y,{get list(){return n()},get hide(){return v()!==1},moreKey:"BoostingShowMoreGifts"})})(),null),_})()]}}),j(gs,{name:"LinkForBoosting",caption:"BoostingShareThisLink",get children(){return h.container}}),K((()=>{const _=K(()=>!!a.canCreateGiveaway);return()=>_()&&j(gs,{caption:"BoostingGetMoreBoosts",children:u})})())];return Ml(m,g,_=>{w(_)},void 0,void 0,void 0,this.listenerSetter)(v()),L}async init(t){this.container.classList.add("boosts-container"),this.peerId=t,this.targets=new Map,this.setTitle("Boosts");const s=p=>{const m=this.middlewareHelper.get();let g="",f=!0;const y=async()=>{const b=f?20:100;f=!1;const S=await this.managers.appBoostsManager.getBoostsList({peerId:t,offset:g,limit:b,gifts:p});if(!m())return;const C=S.boosts.map(this.renderBoost),P=await Promise.all(C);w(L=>(L.count=S.count,g=S.next_offset,g||(L.loadMore=void 0),L.rendered.push(...P),L))},[v,w]=Bd({loadMore:y});return v},[i,n]=Jt(p=>(this.middlewareHelper.get().onDestroy(p),[s(!1),s(!0)])),[a,r,l,c,d]=await Promise.all([this.managers.appBoostsManager.getBoostsStatus(t),this.managers.apiManager.getAppConfig(),i().loadMore(),n().loadMore(),this.managers.appChatsManager.hasRights(t.toChatId(),"create_giveaway")]);this.canCreateGiveaway=d;const h=document.createElement("div");this.scrollable.append(h);const u=Hi(()=>this._construct(a,r,i,n),h);this.eventListener.addEventListener("destroy",u)}}Ui(["click"]);const uk=ce("<span class=popup-boosts-badge>"),pk=ce("<span class=popup-boosts-button-text>"),US=ce("<span>"),mk=ce('<span class="primary is-flex"> '),nv=ce("<form>"),gk=ce('<div class=popup-boosts-additional-row><div class=popup-boosts-additional-row-count></div><input class="input-clear popup-boosts-additional-row-input">'),fk=ce("<div class=popup-boosts-star-container><img class=popup-boosts-star>"),yk=ce("<div class=popup-boosts-title>"),vk=ce("<div class=popup-boosts-subtitle>"),HS=o=>(()=>{const e=uk();return D(e,j(xi,{icon:"boost",class:"popup-boosts-badge-icon"}),null),D(e,()=>o.boosts,null),e})(),$S=o=>{let e,t;(()=>{const s=pk(),i=e;return typeof i=="function"?wt(i,s):e=s,D(s,()=>M(o.langKey(),o.langArgs?.())),s})(),(()=>{const s=US(),i=t;return typeof i=="function"?wt(i,s):t=s,D(s,j(xi,{icon:"boost",class:"popup-boosts-button-badge-icon"}),null),D(s,()=>o.boosts(),null),Ve(()=>Ce(s,ot("popup-boosts-button-badge",!o.boosts()&&"hide"))),s})(),o.button.classList.add("popup-boosts-button"),o.button.append(e,t)};class av extends ee{constructor(e,t,s){super("popup-boosts",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,title:"BoostsViaGifts.Title",floatingHeader:!0,footer:!0,withConfirm:!0}),this.peerId=e,this.prepaidGiveaway=t,this.onCreated=s,this.construct()}_construct(){const e=this,t=this,[s,i]=ne(0),[n,a]=ne(Ms(!0)+3*86400),[r,l]=ne([this.peerId]),[c,d]=ne([]),[h,u]=ne(!1),[p,m]=ne(),[g,f]=ne(),[y,v]=ne(),[w,b]=ne(!1),[S,C]=ne(!1),[P,L]=ne(""),[E,_]=ne(!0),k=K(()=>!!this.prepaidGiveaway),x=K(()=>s()*(this.appConfig.giveaway_boosts_per_premium??1)),A=new qh({generateStep:pe=>[""+pe,pe],onValue:pe=>{i(pe)},middleware:this.middlewareHelper.get(),noFirstLast:!0}),T=[1,3,5,7,10,25,50,100].filter(pe=>this.premiumGiftCodeOptions.some(Be=>Be.users===pe)),B=A.generateSteps(T);k()?i(this.prepaidGiveaway.quantity):A.setSteps(B,T.indexOf(10));const R={round:!0,asRadio:!0},O=new ve({titleLangKey:"Ends",titleRightSecondary:!0,clickable:()=>{const pe=new Date(Date.now()+(this.appConfig.giveaway_period_max??604800)*1e3),Be=new Date(n()*1e3);new If({initDate:Be,onPick:De=>{a(De)},btnConfirmLangKey:"Save",maxDate:pe}).show()},listenerSetter:this.listenerSetter});O.titleRight.classList.add("primary"),ye(()=>{O.titleRight.replaceChildren(ws(n()))});const X=pe=>{i(pe?c().length:A.value),u(pe),this.scrollable.updateThumb()};let F,H,G,z;if(this.prepaidGiveaway)H=OS({giveaway:this.prepaidGiveaway,appConfig:this.appConfig});else{const pe=new ve({titleLangKey:"BoostsViaGifts.Create",subtitleLangKey:"BoostsViaGifts.CreateSubtitle",clickable:()=>{X(!1)},checkboxField:new pt({...R,checked:!h(),name:"giveaway-type"}),listenerSetter:this.listenerSetter}),Be=pe.createMedia("abitbigger"),He=Fn({size:42});He.set({icon:"gift_premium"}),Be.append(He.node),G=pe.container;const De=new ve({titleLangKey:"BoostsViaGifts.Specific",subtitle:!0,clickable:We=>{oe(We),ee.createPopup(Es,{peerType:["channelParticipants"],peerId:this.peerId,onMultiSelect:Ue=>{d(Ue),X(!0),De.checkboxField.setValueSilently(!0)},placeholder:"SearchPlaceholder",exceptSelf:!0,titleLangKey:"Giveaway.Type.Specific.Modal.SelectUsers",initial:c()}).selector.setLimit(this.subscribersLimit,()=>{Ee({langPackKey:"Giveaway.MaximumSubscribers",langPackArguments:[this.subscribersLimit]})})},checkboxField:new pt({...R,checked:h(),name:"giveaway-type"}),listenerSetter:this.listenerSetter});ye(()=>{const We=c(),Fe=!(!We.length||We.length>2);if(De.subtitle.classList.toggle("is-flex",!Fe),!Fe)De.subtitle.replaceChildren(M(We.length>2?"Recipient":"BoostsViaGifts.SpecificSubtitle",[We.length]),q());else{De.subtitle.classList.remove("is-flex");const Ue=We.map(nt=>new Rt({peerId:nt}).element);De.subtitle.replaceChildren(...pi(Ue,!1))}}),De.subtitle.classList.add("primary");const Ae=De.createMedia("abitbigger"),Ke=Fn({size:42});Ke.set({icon:"newgroup_filled",color:"pink"}),Ae.append(Ke.node),z=De.container,z.classList.add("popup-boosts-type","popup-boosts-specific"),G.classList.add("popup-boosts-type")}const q=()=>Le("next","popup-boosts-specific-next"),$=ni(()=>{Vt.show()});let se;ye(()=>{const pe=s(),Be=new Map;this.premiumGiftCodeOptions.forEach((Ae,Ke,We)=>{const Fe=Ae.months;if(Be.has(Fe))return;const Ue=We.filter(At=>At.months===Fe).sort((At,rs)=>At.users-rs.users),nt=Ue.findIndex(At=>At.users>=pe),Lt=Ue[nt]||Ue[Ue.length-1];Be.set(Fe,Lt)});const He=[...Be.values()].sort((Ae,Ke)=>Ke.months-Ae.months),De=xI({periodOptions:He,onOption:Ae=>{se=He.indexOf(Ae),f(Ae)},checked:se,users:pe,discountInTitle:!0});m(De)});const Y=ze("btn btn-primary btn-transparent primary",{icon:"add",text:"AddChannel"});N(Y,async()=>{const pe=jt(Y,!0),Be=ee.createPopup(Es,{filterPeerTypeBy:["isBroadcast"],onMultiSelect:Ae=>{l([this.peerId,...Ae])},placeholder:"SearchPlaceholder",titleLangKey:"AddChannels",initial:r().filter(Ae=>Ae!==this.peerId),excludePeerIds:new Set([this.peerId])});Be.selector.setLimit(this.channelsLimit,()=>{Ee({langPackKey:"BoostingSelectUpToWarningChannelsPlural",langPackArguments:[this.channelsLimit]})}),Be.addEventListener("closeAfterTimeout",()=>pe(),{once:!0});const He=Be.selector.add.bind(Be.selector);let De;Be.selector.add=Ae=>{const Ke=Ae.key.toPeerId(),We=fe.getChat(Ke.toChatId());return!ui(We)[0]&&De!==Ke&&Be.selector.getSelected().length<this.channelsLimit?(Ct({titleLangKey:"BoostingGiveawayPrivateChannel",descriptionLangKey:"BoostingGiveawayPrivateChannelWarning",button:{langKey:"Add"}}).then(()=>{De=Ke,Be.selector.add({key:Ke}),Be.selector.toggleElementCheckboxByPeerId(Ke,!0),De=void 0}),!1):He(Ae)}},{listenerSetter:this.listenerSetter});const Q=()=>(()=>{const pe=mk(),Be=pe.firstChild;return D(pe,()=>M(y()?"BoostingFromCountriesCount":"BoostingFromAllCountries",[y()?.length]),Be),D(pe,q,null),pe})(),he=pe=>{if(!U(pe.target,"row").querySelector(".checkbox-field-input").checked)return;let De;const Ae=ee.createPopup(Es,{peerType:["custom"],renderResultsFunc:We=>{We.forEach(Fe=>{const Ue=De.get(Fe),nt=Lm(Ue.iso2),Lt=document.createDocumentFragment(),At=document.createElement("span");At.classList.add("selector-countries-emoji"),At.append(_e(nt)),Lt.append(At," ",M(Ue.default_name));const rs=new ve({title:Lt,clickable:!0,havePadding:!0});rs.container.append(Ae.selector.checkbox(Ae.selector.selected.has(Fe))),rs.container.dataset.peerId=""+Fe,Ae.selector.list.append(rs.container)})},placeholder:"Search",onMultiSelect:We=>{v(We)},getMoreCustom:async We=>{const Fe=y0(We,!0);return De=new Map,{result:Fe.map(Ue=>(De.set(Ue.iso2,Ue),Ue.iso2)),isEnd:!0}},titleLangKey:"BoostingSelectCountry",checkboxSide:"left",noPlaceholder:!0}),Ke=Ae.selector.add.bind(Ae.selector);Ae.selector.add=({key:We,scroll:Fe})=>{const Ue=ke.countriesList.find(Lt=>Lt.iso2===We),nt=Ke({key:We,title:M(Ue.default_name),scroll:Fe});return _g(nt)&&nt.avatar.render({peerTitle:Lm(Ue.iso2)}),nt},Ae.selector.searchSection.container.classList.add("is-countries"),Ae.selector.container.classList.add("is-countries"),Ae.selector.addInitial(y()),Ae.selector.setLimit(this.countriesLimit,()=>{Ee({langPackKey:"BoostingSelectUpToWarningCountriesPlural",langPackArguments:[this.countriesLimit]})})},le=[K((()=>{const pe=K(()=>!k());return()=>pe()&&j(gs,{name:"BoostsViaGifts.Quantity",get nameRight(){return j(HS,{get boosts(){return x()}})},caption:"BoostsViaGifts.QuantitySubtitle",captionOld:!0,get children(){return A.container}})})()),j(gs,{name:"BoostsViaGifts.Channels",get children(){return[j(ti,{get each(){return r()},children:(pe,Be)=>{const He=new Rt;He.update({peerId:pe}),He.element.classList.add("text-bold");let De;(()=>{const Ke=US(),We=De;return typeof We=="function"?wt(We,Ke):De=Ke,D(Ke,(()=>{const Fe=K(()=>Be()===0);return()=>Fe()&&M("BoostsViaGifts.ChannelSubscription",[x()])})(),null),D(Ke,(()=>{const Fe=K(()=>Be()!==0);return()=>Fe()&&da(pe.toChatId(),void 0,void 0,!0)})(),null),Ke})();const Ae=new ve({title:He.element,subtitle:De,...pe!==e.peerId&&{clickable:Ke=>{Ae.openContextMenu(Ke)},contextMenu:{buttons:[{icon:"delete",danger:!0,text:"Remove",onClick:()=>{l(Ke=>Ke.filter(We=>We!==pe))}}]}}});return Ae.container.classList.add("popup-boosts-channel"),Ae.createMedia("abitbigger").append(Fn({peerId:pe,size:42}).node),Ae.container}}),Y]}}),j(gs,{name:"BoostsViaGifts.Users",caption:"BoostsViaGifts.UsersSubtitle",captionOld:!0,get children(){const pe=nv();return D(pe,()=>new ve({titleLangKey:"AllSubscribers",clickable:Be=>(b(!1),he(Be)),checkboxField:new pt({...R,checked:!0,name:"giveaway-users"}),subtitle:Q(),listenerSetter:e.listenerSetter}).container,null),D(pe,()=>new ve({titleLangKey:"OnlyNewSubscribers",clickable:Be=>(b(!0),he(Be)),checkboxField:new pt({...R,name:"giveaway-users"}),subtitle:Q(),listenerSetter:e.listenerSetter}).container,null),pe}})],re=(()=>{const pe=gk(),Be=pe.firstChild,He=Be.nextSibling;return D(Be,s),He.$$input=De=>{const Ae=De.target;let Ke=Ae.value;const We=Ke.length>128;We&&(Ae.value=Ke=Ke.slice(0,128)),L(Ke),We&&Va(Ae)},wt(De=>{Zt(De,"BoostsViaGifts.AdditionalPrizeLabel",void 0,"placeholder")},He),pe})(),ge=[j(gs,{get caption(){return S()?"BoostsViaGifts.AdditionalPrizesSubtitle":"BoostsViaGifts.AdditionalPrizesSubtitleOff"},get captionArgs(){return K(()=>!!S())()?[M(P()?"BoostsViaGifts.AdditionalPrizesDetailedWith":"BoostsViaGifts.AdditionalPrizesDetailed",[s(),P(),eo(g().months,!0)].filter(Boolean))]:void 0},captionOld:!0,get children(){return[K(()=>new ve({titleLangKey:"BoostsViaGifts.AdditionalPrizes",clickable:()=>{C(pe=>!pe)},checkboxField:new pt({toggle:!0,checked:Et(S)}),listenerSetter:t.listenerSetter}).container),K(()=>S()&&re)]}}),j(gs,{caption:"BoostsViaGifts.ShowWinnersSubtitle",captionOld:!0,get children(){return new ve({titleLangKey:"BoostsViaGifts.ShowWinners",clickable:()=>{_(pe=>!pe)},checkboxField:new pt({toggle:!0,checked:Et(E)}),listenerSetter:t.listenerSetter}).container}}),j(gs,{name:"BoostsViaGifts.End",caption:"BoostsViaGifts.EndSubtitle",get captionArgs(){return[x()]},captionOld:!0,get children(){return O.container}})],be=[j(gs,{noDelimiter:!0,get children(){return[(()=>{const pe=fk(),Be=pe.firstChild,He=F;return typeof He=="function"?wt(He,Be):F=Be,pe})(),(()=>{const pe=yk();return D(pe,()=>M("BoostsViaGifts.Title")),pe})(),(()=>{const pe=vk();return D(pe,()=>M("BoostsViaGifts.Subtitle")),pe})(),K(()=>k()&&H),K(()=>K(()=>!k())()&&(()=>{const pe=nv();return D(pe,G,null),D(pe,z,null),pe})())]}}),K(()=>!h()&&le),K((()=>{const pe=K(()=>!k());return()=>pe()&&j(gs,{name:"BoostsViaGifts.Duration",caption:"BoostsViaGifts.DurationSubtitle",captionArgs:[$],captionOld:!0,get children(){return p()}})})()),K(()=>!h()&&ge)];Kn(F,`assets/img/premiumboostsstar${window.devicePixelRatio>1?"@2x":""}.png`),$S({button:this.btnConfirm,langKey:()=>"BoostsViaGifts.Start",boosts:x}),this.footer.append(this.btnConfirm),this.body.after(this.footer),this.footer.classList.add("abitlarger");const Z=async()=>{const{amount:pe,currency:Be}=g(),He=await Promise.all(r().map(De=>this.managers.appPeersManager.getInputPeerById(De)));return{_:"inputStorePaymentPremiumGiveaway",pFlags:{only_new_subscribers:w()||void 0,winners_are_visible:E()||void 0},amount:pe,currency:Be,boost_peer:He[0],random_id:Pd(),until_date:n(),additional_peers:He.length>1?He.slice(1):void 0,countries_iso2:y()?.length?y():void 0,prize_description:S()&&P()||void 0}},de=async()=>{const{amount:pe,currency:Be}=g(),He=await Promise.all(c().map(De=>this.managers.appUsersManager.getUserInput(De.toUserId())));return{_:"inputStorePaymentPremiumGiftCode",amount:pe,currency:Be,boost_peer:await this.managers.appPeersManager.getInputPeerById(this.peerId),users:He}},Ze=async pe=>(await Ct({titleLangKey:"BoostingStartGiveawayConfirmTitle",descriptionLangKey:"BoostingStartGiveawayConfirmText",button:{langKey:"Start"}}),this.managers.appPaymentsManager.launchPrepaidGiveaway(this.peerId,this.prepaidGiveaway.id,pe)),Ne=async pe=>{const Be={_:"inputInvoicePremiumGiftCode",purpose:pe,option:g()},He=await gr.create({inputInvoice:Be});await new Promise((De,Ae)=>{He.addEventListener("finish",Ke=>{Ke==="cancelled"||Ke==="failed"?Ae():De()})})};return N(this.btnConfirm,async()=>{const pe=jt(this.btnConfirm,!0);try{const Be=await(h()?de:Z)();let He;k()?He=Ze(Be):He=Ne(Be),await He,this.onCreated?.(),this.hide()}catch(Be){console.error("boosts via gifts error",Be),pe()}},{listenerSetter:this.listenerSetter}),be}async construct(){const[e,t]=await Promise.all([this.managers.appPaymentsManager.getPremiumGiftCodeOptions(this.peerId),this.managers.apiManager.getAppConfig()]);this.premiumGiftCodeOptions=e,this.appConfig=t,this.subscribersLimit=this.channelsLimit=t.giveaway_add_peers_max??10,this.countriesLimit=t.giveaway_countries_max??10,this.appendSolid(()=>this._construct()),this.show()}}Ui(["input"]);const bk=ce("<div class=popup-boost-avatars-avatar-container>"),wk=ce("<div><div class=popup-boost-avatars-left></div><div class=popup-boost-avatars-right>"),Sk=ce("<div class=popup-boost-title>"),Ck=ce("<span>"),Xl="popup-boost";class Ik extends Ss{constructor(e,t,s){super("popup-forward popup-chatlist-invite "+Xl,{closable:!0,overlayClosable:!0,body:!0,description:!0,footer:!0,withConfirm:!0}),this.peerId=e,this.myBoosts=t,this.appConfig=s,this.btnClose.remove(),this.header.remove(),Jt(i=>{this.middlewareHelper.get().onDestroy(i),this.construct()})}async construct(){const[e,t]=ne([]),[s,i]=ne(0),n=new Map,a=()=>{const u=v=>{const w=Et(()=>Fn({peerId:v.peerId,size:60}));return w.node.classList.add(`${Xl}-avatars-avatar`),w.node.append(),w},p=u({peerId:this.peerId,right:!0}),m=K(v=>{const w=new Map;v?.forEach((S,C)=>{w.set(S,C)});const b=$a(e().map(S=>at(S.peer)).reverse());return b.sort((S,C)=>(w.get(S)??0)-(w.get(C)??0)),b}),g=26,f=j(ti,{get each(){return m()},children:(v,w)=>{const{element:b}=u({peerId:v}),S=K(()=>m().length-w()-1);return(()=>{const C=bk();return D(C,b,null),D(C,j(xi,{icon:"boostcircle",get class(){return ot(`${Xl}-avatars-avatar-icon`,!S()&&"is-visible")}}),null),Ve(P=>zi(C,`--offset: ${S()*-g}px`,P)),C})()}}),y=gf(ff(()=>f).toArray,{exitMethod:"keep-index",onChange:({added:v,removed:w,finishRemoved:b})=>{const S={duration:st.isAvailable("animations")?200:0,easing:"ease-in-out"},C=[{transform:"translateX(var(--offset)) scale(0)"},{transform:"translateX(var(--offset)) scale(1)"}];queueMicrotask(()=>{for(const E of v)E.animate(C,S);const P=C.slice().reverse(),L=[];for(const E of w){const _=E.animate(P,S);L.push(_.finished)}Promise.all(L).then(()=>b(w))})}});return(()=>{const v=wk(),w=v.firstChild,b=w.nextSibling;return D(w,y),D(v,j(xi,{icon:"next",class:`${Xl}-avatars-arrow`}),b),D(b,()=>p.element),Ve(S=>{const C=ot(`${Xl}-avatars`,m().length&&"has-left"),P=`transform: translateX(${Math.max(0,m().length-1)*(g/2)}px)`;return C!==S._v$&&Ce(v,S._v$=C),S._v$2=zi(v,P,S._v$2),S},{_v$:void 0,_v$2:void 0}),v})()};this.description.before(a(),(()=>{const u=Sk();return D(u,()=>M("Boost.Replace")),u})());const r=new Map;this.selector=new Mi({middleware:this.middlewareHelper.get(),appendTo:this.body,onChange:u=>{t(this.selector.getSelected().map(p=>n.get(p))),i(u)},onFirstRender:()=>{this.show()},multiSelect:!0,noSearch:!0,sectionNameLangPackKey:"BoostingRemoveBoostFrom",avatarSize:"abitbigger",managers:this.managers,peerType:[],getSubtitleForElement:u=>{const p=n.get(u);return Jt(m=>{this.middlewareHelper.get().onDestroy(()=>{m(),clearInterval(w)});const g=M("BoostsExpiration",[1,ws(p.expires,void 0,!0)]),[f,y]=ne(Ms(!0)),v=K(b=>{const S=Math.max(0,(p.cooldown_until_date||0)-f());return!S&&b!==void 0&&clearInterval(w),S});r.set(u,v);const w=v()?window.setInterval(()=>{y(Ms(!0))},1e3):void 0;return(()=>{const b=Ck();return D(b,(()=>{const S=K(()=>!!v());return()=>S()?M("BoostingAvailableIn",[Qb(v())]):g})()),b})()})},getPeerIdFromKey:u=>u.split("_")[1].toPeerId(),processElementAfter:(u,p)=>{const m=r.get(u);Jt(g=>{this.middlewareHelper.get().onDestroy(g),ye(()=>{p.container.classList.toggle("is-unavailable",!!m())})})}});const l=this.selector.add.bind(this.selector);this.selector.add=(...u)=>this.selector.getElementByPeerId(u[0].key).classList.contains("is-unavailable")?(Ee({langPackKey:"Boost.Reassign.Wait",langPackArguments:[M("MoreBoosts",[this.appConfig.boosts_per_sent_gift??1]),ni(()=>{bo(),this.hideWithCallback(()=>{me.initGifting()})})]}),!1):l(...u);const c=this.myBoosts.my_boosts.map(u=>{const p=at(u.peer);if(p===this.peerId)return;const m="S"+u.slot+"_"+p;return n.set(m,u),m}).filter(Boolean);this.scrollable=this.selector.scrollable,this.attachScrollableListeners(),this.selector.renderResultsFunc(c);let d=!1;const h=async u=>{oe(u),d=!0;const p=jt(this.btnConfirm,!0);try{const m=e().map(f=>f.slot),g=$a(e().map(f=>at(f.peer)));await this.managers.appBoostsManager.applyBoost(this.peerId,m),this.hide(),Ee({langPackKey:"BoostingReassignedFromPlural",langPackArguments:[m.length,M("BoostingFromOtherChannel",[g.length])]})}catch(m){console.error("error replacing boosts",m),p()}d=!1};N(this.btnConfirm,h,{listenerSetter:this.listenerSetter}),$S({button:this.btnConfirm,langKey:()=>"Boost.Reassign",langArgs:()=>[s()||1],boosts:s}),ye(()=>{d||jt(this.btnConfirm,!s())}),this.description.append(M("Boost.Reassign.Description",[await Oe({peerId:this.peerId}),M("Boost.GiftPremium",[ni(()=>{this.hideWithCallback(()=>{me.initGifting()})})]),M("Boost.Additional",[this.appConfig.boosts_per_sent_gift??1])])),this.footer.append(this.btnConfirm),this.body.after(this.footer)}}const lh="popup-boost";class Lk extends Ss{constructor(e){super(lh,{closable:!0,overlayClosable:!0,description:!0}),this.peerId=e,this.btnClose.remove(),this.header.remove(),this.construct()}async construct(){let[e,t,s,i]=await Promise.all([this.managers.appBoostsManager.getBoostsStatus(this.peerId),this.managers.appBoostsManager.getMyBoosts(),this.managers.apiManager.getAppConfig(),fe.isPremiumPurchaseBlocked()]);const n=Mi.renderEntity({key:this.peerId,middleware:this.middlewareHelper.get(),avatarSize:30});n.element.classList.add(`${lh}-entity`,"selector-user-alone","hover-primary");const a=bl("span",20,"premium");a.classList.add(`${lh}-entity-badge`),n.element.append(a),N(n.element,()=>{this.hideWithCallback(()=>{me.setInnerPeer({peerId:this.peerId})})},{listenerSetter:this.listenerSetter});const r=document.createElement("div");r.classList.add(`${lh}-title`);const l=await Oe({peerId:this.peerId});await n.avatar.readyThumbPromise;let c,d,h,u,p=!1;const m=L=>{e=L,c=e.level>0||e.next_level_boosts===e.boosts,d=e.next_level_boosts-e.boosts,h=e.next_level_boosts===void 0,u=!!e.pFlags.my_boost},g=()=>{u?r.replaceChildren(M("YouBoostedChannel")):h?r.replaceChildren(M("BoostsMaxLevelReached")):c?r.replaceChildren(M("HelpUpgradeChannel")):r.replaceChildren(M("Boost.EnableStoriesFor"))},f=()=>{p&&e.level===0&&c?this.description.replaceChildren(M("Boost.DescriptionJustReachedLevel1")):h||p&&e.level>0?this.description.replaceChildren(M("Boost.DescriptionJustReachedLevel",[e.level,M("Boost.StoriesCount",[e.level+1])])):c?this.description.replaceChildren(M("ChannelNeedBoostsDescriptionForNewFeatures",[l,M("MoreBoosts",[d])])):this.description.replaceChildren(M("ChannelNeedBoostsDescriptionLevel1",[M("MoreBoosts",[d])]))},y=new Vu({progress:!0,hint:{icon:"boost",noStartEnd:!0}});this.description.before(y.container,r,n.element);const v=()=>t.my_boosts.filter(L=>at(L.peer)===this.peerId),w=()=>{const L=h?1:(e.boosts-e.current_level_boosts)/(e.next_level_boosts-e.current_level_boosts);y.setProgress(L,""+e.boosts,{from1:M("BoostsLevel",[e.level]),to1:M("BoostsLevel",[e.level+1]),from2:M("BoostsLevel",[e.level]),to2:M("BoostsLevel",[e.level+1])}),g(),f(),b(),a.textContent=`x${v().length}`,a.classList.toggle("is-badge-empty",!u)},b=()=>{this.setButtons(fr([h||v().length===t.my_boosts.length&&i?{langKey:"OK",isCancel:!0}:{langKey:"BoostChannel",iconLeft:"boost",callback:P}]))},S=L=>{if(L==="PREMIUM_ACCOUNT_REQUIRED")C();else if(L.includes("FLOOD_WAIT")){const E=+L.split("_")[2];Ct({titleLangKey:"CantBoostTooOften",descriptionLangKey:"CantBoostTooOftenDescription",descriptionLangArgs:[kl(yo(E,2),!1)],button:{langKey:"OK",isCancel:!0}})}else L==="PREMIUM_GIFTED_NOT_ALLOWED"&&Ct({titleLangKey:"CantBoostWithGiftedPremium",descriptionLangKey:"CantBoostWithGiftedPremiumDescription",button:{langKey:"OK",isCancel:!0}})},C=()=>{Ct({titleLangKey:"PremiumNeeded",descriptionLangKey:"PremiumNeededForBoosting",button:{langKey:"Yes"}}).then(()=>{Vt.show()})},P=async L=>{oe(L);try{const E=v(),_=t.my_boosts.find(x=>!x.peer);let k;if(!I.premium)k="PREMIUM_ACCOUNT_REQUIRED";else if(E.length===t.my_boosts.length){await Ct({titleLangKey:"BoostingMoreBoostsNeeded",descriptionLangKey:"Boost.GetMoreBoosts",descriptionLangArgs:[await Oe({peerId:this.peerId}),s.boosts_per_sent_gift??1],button:{langKey:"GiftPremium"}}),this.hideWithCallback(()=>{me.initGifting()});return}else if(!_){this.hide(),ee.createPopup(Ik,this.peerId,t,s);return}if(k)throw{type:k};await this.managers.appBoostsManager.applyBoost(this.peerId,[_.slot]),[t,e]=await Promise.all([this.managers.appBoostsManager.getMyBoosts(),this.managers.appBoostsManager.getBoostsStatus(this.peerId)]),p=!0,m(e),w()}catch(E){S(E.type)}return!1};m(e),w(),y._setHintActive(),this.show()}}class Pk{constructor(){this.processMessageLink=e=>{const t=e.post?+e.post:void 0,s=e.comment?+e.comment:void 0,i=e.thread?+e.thread:void 0;return me.openUsername({userName:e.domain,lastMsgId:t,commentId:s,startParam:e.start,stack:e.stack,threadId:i,mediaTimestamp:e.t&&+e.t,text:e.text})},this.processPrivatePostLink=async e=>{const t=e.channel.toChatId(),s=await this.managers.appChatsManager.getChat(t);if(!s)try{await this.managers.appChatsManager.resolveChannel(t)}catch(a){throw Ee({langPackKey:"LinkNotFound"}),a}const i=+e.post,n=e.thread?+e.thread:void 0;return me.op({peer:s,lastMsgId:i,threadId:n,stack:e.stack,mediaTimestamp:e.t&&+e.t})},this.processStickerSetLink=e=>{const t=ee.createPopup(Cn,{id:e.set},e._===vt.EMOJI_SET);return t.show(),t},this.processJoinChatLink=e=>this.managers.appChatInvitesManager.checkChatInvite(e.invite).then(t=>{if(t._==="chatInviteAlready"||t._==="chatInvitePeek"){me.setInnerPeer({peerId:t.chat.id.toPeerId(!0)});return}return ee.createPopup(ru,e.invite,t)},t=>{t.type==="INVITE_HASH_EXPIRED"&&zs(M("InviteExpired"))}),this.processVoiceChatLink=async e=>{const t=s=>{if(me.chat.peerId!==s)return me.setInnerPeer({peerId:s})};if(e.livestream!==void 0){const i=(await this.managers.appUsersManager.resolveUsername(e.domain)).id.toPeerId(!0);return await t(i),me.joinLiveStream(i)}if(Ac&&e.id){const s=e.chat_id.toPeerId(!0);return await t(s),me.joinGroupCall(s,e.id)}},this.processUserPhoneNumberLink=e=>this.managers.appUsersManager.resolvePhone(e.phone).then(t=>me.setInnerPeer({peerId:t.id.toPeerId(!1),text:e.text})).catch(t=>{t.type==="PHONE_NOT_OCCUPIED"&&Ee({langPackKey:"Alert.UserDoesntExists"})}),this.processInvoiceLink=e=>this.managers.appPaymentsManager.getInputInvoiceBySlug(e.slug).then(t=>this.managers.appPaymentsManager.getPaymentForm(t).then(s=>gr.create({inputInvoice:t,paymentForm:s}),s=>{throw s.type==="SLUG_INVALID"&&Ee({langPackKey:"PaymentInvoiceLinkInvalid"}),s})),this.processAttachMenuBotLink=async e=>{const t=e.attach||e.domain||e.nestedLink.domain,s=await this.managers.appUsersManager.resolveUserByUsername(t).catch(()=>{});let i;e.attach!==void 0&&(i=this.processInternalLink(e.nestedLink));let n;if(s?s.pFlags.bot_attach_menu||(n="BotCantAddToAttachMenu"):n="Alert.UserDoesntExists",n){Ee({langPackKey:n});return}i&&await i;const a=await me.toggleBotInAttachMenu(s.id,!0);if(e.choose){const r=e.choose.split("+"),l={bots:"attachMenuPeerTypeBotPM",users:"attachMenuPeerTypePM",groups:"attachMenuPeerTypeChat",channels:"attachMenuPeerTypeBroadcast"},c=r.filter(h=>{const u=l[h];return a.peer_types.some(p=>p._===u)}),d=await Es.createPicker(c);await me.setInnerPeer({peerId:d})}me.chat.openWebApp({attachMenuBot:a,startParam:e.startattach})},this.processWebAppLink=async e=>{const t=await this.managers.appUsersManager.resolveUserByUsername(e.domain).catch(()=>{});if(!t){Ee({langPackKey:"Alert.UserDoesntExists"});return}const s=t.id;let i;try{i=await this.managers.appAttachMenuBotsManager.getBotApp(s,e.appname)}catch(r){if(r.type==="BOT_APP_INVALID"){Ee({langPackKey:"Alert.BotAppDoesntExist"});return}else throw r}const n=t.pFlags.bot_attach_menu&&await me.toggleBotInAttachMenu(s,!0);let a;n||(i.pFlags.inactive||e.masked)&&(a=await me.confirmBotWebViewInner({botId:s,requestWriteAccess:i.pFlags.request_write_access,showDisclaimer:t.pFlags.bot_attach_menu&&i.pFlags.inactive})),me.chat.openWebApp({attachMenuBot:n,startParam:e.startapp,writeAllowed:a,botId:s,app:i.app,noConfirmation:!n,hasSettings:i.pFlags.has_settings})},this.processListLink=async e=>{let t;try{t=await this.managers.filtersStorage.checkChatlistInvite(e.slug)}catch(s){if(s.type==="INVITE_SLUG_EXPIRED"){Ee({langPackKey:"SharedFolder.Link.Expired"});return}throw s}ee.createPopup(Cf,{chatlistInvite:t,slug:e.slug})},this.processStoryLink=async e=>{const t=window.event,s=U(t.target,"bubble");if(s&&s.classList.contains("story")){fs(s.querySelector(".media-container").querySelector("img, video"));return}let i;try{i=await this.managers.appUsersManager.resolveUsername(e.domain)}catch(r){r.type==="USERNAME_NOT_OCCUPIED"?Ee({langPackKey:"NoUsernameFound"}):console.error(r);return}const n=i.id.toPeerId(i._!=="user");if(!await this.managers.appStoriesManager.getStoryById(n,+e.story)){Ee({langPackKey:"NoStoryFound"});return}mr({peerId:n,id:+e.story})},this.processBoostLink=async e=>{let t=e.channel?e.channel.toPeerId(!0):void 0;t===void 0&&(t=(await this.managers.appUsersManager.resolveUsername(e.domain)).id.toPeerId(!0)),ee.createPopup(Lk,t)},this.processPremiumFeaturesLink=async e=>{if(I.premium){Ee({langPackKey:"Premium.Offset.AlreadyHave"});return}Vt.show()},this.processGiftCodeLink=e=>{ee.createPopup(ya,e.slug,e.stack)},this.processBusinessChatLink=async e=>{const t=await this.managers.appBusinessManager.resolveBusinessChatLink(e.slug);me.setInnerPeer({peerId:t.peerId,text:t.message,entities:t.entities})}}construct(e){this.managers=e,Us({name:"showMaskedAlert",callback:(t,s)=>{const i=s.href,n=s.cloneNode(!0);n.className="anchor-url",n.innerText=i,n.removeAttribute("onclick");const a=ee.createPopup(Ss,"popup-masked-url",{titleLangKey:"OpenUrlTitle",descriptionLangKey:"OpenUrlAlert2",descriptionLangArgs:[n],buttons:[{langKey:"Open",callback:()=>{n.click()}}]});return a.show(),a}}),Us({name:"execBotCommand",callback:({uriParams:t})=>{const{command:s,bot:i}=t;return this.managers.appMessagesManager.sendText({peerId:me.chat.peerId,text:"/"+s+(i?"@"+i:"")})}}),Us({name:"searchByHashtag",callback:({uriParams:t})=>{const{hashtag:s}=t;if(s)return me.chat.initSearch({query:"#"+s+" "})}}),Us({name:"setMediaTimestamp",callback:(t,s)=>{const i=+s.dataset.timestamp;if(U(s,"bubble")){me.chat.bubbles.playMediaWithTimestamp(s,i);return}if(U(s,"media-viewer-caption"))return window.appMediaViewer.setMediaTimestamp(i)}}),[["addstickers",vt.STICKER_SET],["addemoji",vt.EMOJI_SET]].forEach(([t,s])=>{Us({name:t,callback:({pathnameParams:i})=>{if(!i[1])return;const n={_:s,set:i[1]};return this.processInternalLink(n)}}),Us({name:t,protocol:"tg",callback:({uriParams:i})=>{const n=this.makeLink(s,i);return this.processInternalLink(n)}})}),Us({name:"invoice",callback:({pathnameParams:t})=>{const s={_:vt.INVOICE,slug:t.length>1?t[1]:t[0].slice(1)};return this.processInternalLink(s)}}),Us({name:"addlist",callback:({pathnameParams:t})=>{const s={_:vt.ADD_LIST,slug:t[1]};return this.processInternalLink(s)}}),Us({name:"joinchat",callback:({pathnameParams:t})=>{const s={_:vt.JOIN_CHAT,invite:t[1]||decodeURIComponent(t[0]).slice(1)};return this.processInternalLink(s)}}),Ac&&Us({name:"voicechat",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(vt.VOICE_CHAT,t);return this.processInternalLink(s)}}),Us({name:"im",callback:async({pathnameParams:t,uriParams:s},i,n)=>{let a;if("voicechat"in s||"videochat"in s||"livestream"in s)a={_:vt.VOICE_CHAT,domain:t[0],...s};else if("boost"in s||t?.[0]==="boost"){const r=t?.[0]==="c"?t[1]:s.c;a={_:vt.BOOST,domain:r?void 0:"boost"in s?t[0]:t[1],channel:r}}else if(t?.[1]==="s")a={_:vt.STORY,domain:t[0],story:t[2]};else if(pL.test(t[0]))a={_:vt.USER_PHONE_NUMBER,phone:t[0],text:s.text};else if(t[0]==="c"){t.shift();const r="thread"in s?s.thread:t[2]&&t[1];a={_:vt.PRIVATE_POST,channel:t[0],post:t[2]||t[1],thread:r,comment:s.comment,stack:me.getStackFromElement(i),t:s.t}}else if(t[1]&&vP(t[1]))a={_:vt.WEB_APP,domain:t[0],appname:t[1],startapp:s.startapp,masked:n};else{const r="thread"in s?s.thread:t[2]&&t[1];a={_:vt.MESSAGE,domain:t[0],post:t[2]||t[1],thread:r,comment:s.comment,start:"start"in s?s.start:void 0,stack:me.getStackFromElement(i),t:s.t,text:s.text}}return("startattach"in s||"attach"in s)&&(a={_:vt.ATTACH_MENU_BOT,nestedLink:a,...s}),this.processInternalLink(a)}}),Us({name:"resolve",protocol:"tg",callback:({uriParams:t},s,i)=>{let n;if(t.voicechat!==void 0||t.videochat!==void 0||t.livestream!==void 0?n=this.makeLink(vt.VOICE_CHAT,t):t.story?n=this.makeLink(vt.STORY,t):t.phone?n=this.makeLink(vt.USER_PHONE_NUMBER,t):t.domain==="telegrampassport"||(t.appname?n=this.makeLink(vt.WEB_APP,{masked:i,...t}):n=this.makeLink(vt.MESSAGE,{...t,stack:me.getStackFromElement(s)})),t.attach!==void 0||t.startattach!==void 0){const a=n;n=this.makeLink(vt.ATTACH_MENU_BOT,t),n.nestedLink=a}return this.processInternalLink(n)}}),Us({name:"privatepost",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(vt.PRIVATE_POST,t);return this.processInternalLink(s)}}),Us({name:"invoice",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(vt.INVOICE,t);return this.processInternalLink(s)}}),Us({name:"addlist",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(vt.ADD_LIST,t);return this.processInternalLink(s)}}),["joinchat","join"].forEach(t=>{Us({name:t,protocol:"tg",callback:({uriParams:s})=>{const i=this.makeLink(vt.JOIN_CHAT,s);return this.processInternalLink(i)}})}),Us({name:"boost",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(vt.BOOST,t);return this.processInternalLink(s)}}),Us({name:"boost",callback:({pathnameParams:t})=>{const s={_:vt.BOOST,domain:t[1]};return this.processInternalLink(s)}}),Us({name:"premium_offer",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(vt.PREMIUM_FEATURES,t);return this.processInternalLink(s)}}),Us({name:"giftcode",callback:({pathnameParams:t},s)=>{const i={_:vt.GIFT_CODE,slug:t[1],stack:me.getStackFromElement(s)};return this.processInternalLink(i)}}),Us({name:"giftcode",protocol:"tg",callback:({uriParams:t},s)=>{const i=this.makeLink(vt.GIFT_CODE,t);return i.stack=me.getStackFromElement(s),this.processInternalLink(i)}}),Us({name:"m",callback:({pathnameParams:t})=>{const s={_:vt.BUSINESS_CHAT,slug:t[1]};return this.processInternalLink(s)}}),Us({name:"message",protocol:"tg",callback:({uriParams:t})=>{const s=this.makeLink(vt.BUSINESS_CHAT,t);return this.processInternalLink(s)}})}makeLink(e,t){return{_:e,...t}}processInternalLink(e){const s={[vt.MESSAGE]:this.processMessageLink,[vt.PRIVATE_POST]:this.processPrivatePostLink,[vt.EMOJI_SET]:this.processStickerSetLink,[vt.STICKER_SET]:this.processStickerSetLink,[vt.JOIN_CHAT]:this.processJoinChatLink,[vt.VOICE_CHAT]:this.processVoiceChatLink,[vt.USER_PHONE_NUMBER]:this.processUserPhoneNumberLink,[vt.INVOICE]:this.processInvoiceLink,[vt.ATTACH_MENU_BOT]:this.processAttachMenuBotLink,[vt.WEB_APP]:this.processWebAppLink,[vt.ADD_LIST]:this.processListLink,[vt.STORY]:this.processStoryLink,[vt.BOOST]:this.processBoostLink,[vt.PREMIUM_FEATURES]:this.processPremiumFeaturesLink,[vt.GIFT_CODE]:this.processGiftCodeLink,[vt.BUSINESS_CHAT]:this.processBusinessChatLink}[e._];if(!s){console.warn("Not supported internal link:",e);return}return s(e)}}const lp=new Pk;Ws&&(Ws.internalLinkProcessor=lp);function VS(){return window.getSelection?window.getSelection().toString():document.selection?document.selection.createRange().text:""}const Mk=ce("<span class=delimiter-with-text><span class=delimiter-with-text-stripe></span><span class=delimiter-with-text-stripe>"),Ek=ce("<a class=bubble-giveaway-link>"),_k=ce("<b>"),kk=ce("<br>"),rv=ce("<div class=bubble-giveaway-channels>"),Tk=ce("<div class=bubble-giveaway-countries>"),xk=ce("<div class=bubble-giveaway-and-more>"),Ak=ce("<div><div class=bubble-giveaway-sticker><div class=bubble-giveaway-sticker-counter></div></div><div class=bubble-giveaway-row><div class=bubble-giveaway-row-title></div></div><div class=bubble-giveaway-row><div class=bubble-giveaway-row-title></div></div><div class=bubble-giveaway-row><div class=bubble-giveaway-row-title>");function jm(o){return{3:"Gift3",6:"Gift6",12:"Gift12"}[Kt(o,3,12)]}function GS(o){return(()=>{const e=Mk(),t=e.firstChild,s=t.nextSibling;return D(e,()=>M(o.langKey),s),e})()}async function Fk(o){const e=o.media,t=await I.managers.appPaymentsManager.getGiveawayInfo(o.peerId,o.mid),s=document.createDocumentFragment(),i=eo(e.months,!0),n=o.fwdFromId||o.peerId,a=e._==="messageMediaGiveawayResults",r=t._==="payments.giveawayInfoResults",l=r&&t.pFlags.refunded,c=!l&&r&&t.pFlags.winner,d=!r&&t.pFlags.participating,h=e.pFlags.only_new_subscribers,u=a?e.winners_count+e.unclaimed_count:e.quantity,p=a?e.additional_peers_count||0:e.channels.length-1,m=P=>ws(P,void 0,!0);let g="Giveaway.Info";const f=[m(r?t.finish_date:e.until_date),M("Giveaway.Info.Users",[u]),await Oe({peerId:n})];p&&(g+=".Several",f.push(M("Giveaway.Info.OtherChannels",[p]))),h&&(g+=".Date",f.push(m(t.start_date))),r&&(g+=".End");let y,v,w;l?y="BoostingGiveawayCanceledByPayment":c?(y="Giveaway.Won",v=[_e("🏆")],w=!0):r?(y="BoostingGiveawayYouNotWon",w=!0):t.joined_too_early_date?(y="BoostingGiveawayNotEligible",v=[m(t.joined_too_early_date)]):t.disallowed_country?y="BoostingGiveawayNotEligibleCountry":t.admin_disallowed_chat_id?(y="BoostingGiveawayNotEligibleAdmin",v=[await Oe({peerId:t.admin_disallowed_chat_id.toPeerId(!0)})]):(y=d?"Giveaway.Participation":"Giveaway.TakePart",v=[await Oe({peerId:n})],p&&(y+=".Multi",v.push(M("Giveaway.Info.OtherChannels",[p]))),!d&&t.start_date&&v.push(m(e.until_date)));const b=M(r?"BoostingGiveawayHowItWorksTextEnd":"BoostingGiveawayHowItWorksText",[void 0,await Oe({peerId:n}),u,i]),S=M(g,f),C=M(y,v);(w||l)&&C.classList.add("popup-description-framed"),l&&C.classList.add("popup-description-danger"),s.append(...[...w?[C,document.createElement("br")]:[],b,document.createElement("br"),document.createElement("br"),...e.prize_description?[M("Giveaway.AlsoPrizes",[await Oe({peerId:n}),u,_e(e.prize_description),M("Giveaway.AlsoPrizes2",[u])]),document.createElement("br"),document.createElement("br")]:[],S,...r&&t.activated_count?[" ",M("BoostingGiveawayUsedLinksPlural",[t.activated_count])]:[],...w?[]:[document.createElement("br"),document.createElement("br"),C]].filter(Boolean)),await Ct({titleLangKey:r?"BoostingGiveawayEnd":"BoostingGiveAwayAbout",description:s,button:c?{langKey:"BoostingGiveawayViewPrize"}:{langKey:"OK",isCancel:!0}}),c&&ee.createPopup(ya,t.gift_code_slug)}function Rk(o){const e=Ys().get(),t=o.giveaway,s=t._==="messageMediaGiveawayResults",i=s?t.winners_count:t.quantity,n=!s&&t.countries_iso2?.map(f=>{const y=document.createElement("span");y.classList.add("bubble-giveaway-country");const v=ke.countriesList.find(w=>w.iso2===f);return y.append(_e(Lm(f)+" "+(v.name||v.default_name))),y}),a=eo(t.months,!0);let r;if(s){let f;(()=>{const y=Ek(),v=f;return typeof v=="function"?wt(v,y):f=y,Ve(()=>Ti(y,"data-saved-from",`${t.channel_id.toPeerId(!0)}_${t.launch_msg_id}`)),y})(),r=K(()=>M("Giveaway.Results.Subtitle",[i,f]))}else r=t.prize_description?[(()=>{const f=_k();return D(f,`${i} `),f})(),K(()=>_e(t.prize_description)),j(GS,{langKey:"Giveaway.With"}),K(()=>M(i>1?"Giveaway.WithSubscriptionsPlural":"Giveaway.WithSubscriptionsSingle",[a]))]:[K(()=>M("BoostingGiveawayMsgInfoPlural1",[i])),kk(),K(()=>M("BoostingGiveawayMsgInfoPlural2",[a]))];const l=f=>{const y=Mi.renderEntity({key:f,middleware:e,avatarSize:30,meAsSaved:!1});return me.setPeerColorToElement({peerId:f,element:y.element}),y.element.classList.add("bubble-giveaway-channel","hover-primary"),y.element},c=!s&&(()=>{const f=rv();return D(f,j(ti,{get each(){return t.channels},children:y=>l(y.toPeerId(!0))})),f})(),d=n&&(()=>{const f=Tk();return D(f,()=>M("BoostingGiveAwayFromCountries",[pi(n)])),f})();let h;s?h=[(()=>{const f=rv();return D(f,j(ti,{get each(){return t.winners},children:y=>l(y.toPeerId(!1))})),f})(),K((()=>{const f=K(()=>t.winners_count>t.winners.length);return()=>f()&&(()=>{const y=xk();return D(y,()=>M("Giveaway.Results.AndMore",[t.winners_count-t.winners.length])),y})()})())]:h=[K(()=>M(t.pFlags.only_new_subscribers?"BoostingGiveawayMsgNewSubsPlural":"BoostingGiveawayMsgAllSubsPlural",[t.channels.length])),c,d];let u;const p=(()=>{const f=Ak(),y=f.firstChild,v=y.firstChild,w=y.nextSibling,b=w.firstChild,S=w.nextSibling,C=S.firstChild,P=S.nextSibling,L=P.firstChild,E=u;return typeof E=="function"?wt(E,y):u=y,D(v,`X${i}`),D(b,()=>M(s?"Giveaway.Results.Title":"BoostingGiveawayPrizes",[i])),D(w,r,null),D(C,()=>M(s?"BoostingGiveawayResultsMsgWinners":"BoostingGiveawayMsgParticipants",[i])),D(S,h,null),D(L,()=>M(s?"Giveaway.Results.Footer":"BoostingWinnersDate",[i])),D(P,()=>!s&&ws(t.until_date),null),Ve(()=>Ce(f,ot("bubble-giveaway","no-select","disable-hover",s&&"bubble-giveaway-results"))),f})(),m=s?80:160,g=ju({width:m,height:m,assetName:s?"Congratulations":jm(t.months),middleware:e,loop:!1,autoplay:st.isAvailable("stickers_chat")}).then(({container:f,promise:y})=>(u.style.position="relative",u.style.width=u.style.height=m+"px",u.append(f),y));return o.loadPromises.push(g),p}function Dk(o,e){const t=[];for(;o.parentElement&&o.parentElement!==document.body&&(o=o.parentElement,t.push(o),!(e&&o.matches(e))););return t}const Bk=ce("<button>"),kn=o=>{const[,e]=Xn(o,["icon","noRipple"]),t=(()=>{const s=Bk();return uo(s,Ai(e,{get class(){return ot("btn-icon",o.class)},tabIndex:-1}),!1,!0),D(s,(()=>{const i=K(()=>!!o.icon);return()=>i()?Le(o.icon):o.children})()),s})();return o.noRipple||Ni(t),t},Nk=ce('<div><div class="tooltip-part tooltip-background"></div><span class="tooltip-part tooltip-notch"></span><div class="tooltip-part tooltip-text">'),Qp=new $u(void 0,!0);function ur({element:o,container:e=o.parentElement,vertical:t,text:s,textElement:i,paddingX:n=0,centerVertically:a,onClose:r,icon:l,auto:c}){const d=e.getBoundingClientRect(),h=o.getBoundingClientRect(),u=document.body;let p;return Jt(m=>{const[g,f]=ne(),y=()=>{const P={"max-width":Math.min(d.width-n*2,320)+"px"},L=g();if(!L)return P;const E=Math.min(d.left+n,d.right),_=Math.max(d.left,d.right-Math.min(d.width,L.width)-n),k=h.left+(h.width-L.width)/2,x=Kt(k,E,_),A=12;t==="top"?P.top=(a?h.top+h.height/2:h.top)-L.height-A+"px":P.top=h.bottom+A+"px",P.left=x+"px";const T=h.left+(h.width-19)/2;return P["--notch-offset"]=T-x+"px",P};let v;const w=(()=>{const P=Nk(),L=P.firstChild,E=L.nextSibling,_=E.nextSibling,k=v;return typeof k=="function"?wt(k,P):v=P,D(_,l&&j(xi,{icon:l,class:"tooltip-icon"}),null),D(_,i,null),Ve(x=>{const A=ot("tooltip","tooltip-"+t,l&&"tooltip-with-icon"),T=y();return A!==x._v$&&Ce(P,x._v$=A),x._v$2=zi(P,T,x._v$2),x},{_v$:void 0,_v$2:void 0}),P})();j(_u,{mount:u,children:w}),vr(()=>{f(v.getBoundingClientRect()),v.classList.add("mounted"),bt({element:v,className:"is-visible",duration:200,useRafs:2,forwards:!0})});let b=!1;const S=P=>{P||(b=!0,clearTimeout(C),bt({element:v,className:"is-visible",duration:200,forwards:!1,onTransitionEnd:()=>{r?.(),m()}}))};p=()=>{b||Qp.close()};const C=c?window.setTimeout(p,3e3):0;Promise.resolve().then(()=>{Qp.open(u),Qp.addEventListener("toggle",S,{once:!0})})}),{close:p}}const Ok=ce("<div><span class=similar-channels-channel-badge>"),Uk=ce("<div class=similar-channels-channel-avatar-stack><div class=similar-channels-channel-avatar-stack-middle></div><div class=similar-channels-channel-avatar-stack-last>"),Hk=ce("<div class=similar-channels-list>"),ov=ce("<div class=similar-channels-list-margin>"),$k=ce('<div class=similar-channels-container><svg class=similar-channels-notch width=19 height=7 viewBox="0 0 19 7"fill=none xmlns=http://www.w3.org/2000/svg><path class=similar-channels-notch-path fill-rule=evenodd clip-rule=evenodd d="M19 7C16.8992 7 13.59 3.88897 11.5003 1.67424C10.7648 0.894688 10.397 0.50491 10.0434 0.385149C9.70568 0.270811 9.4225 0.270474 9.08456 0.38401C8.73059 0.50293 8.36133 0.892443 7.62279 1.67147C5.52303 3.88637 2.18302 7 0 7L19 7Z"></path></svg><div class=similar-channels-header>');function Vk(o){const[e,t]=ne(I.premium),[s,i]=ne(),[n,a]=ne();let{onAcked:r,onReady:l,onEmpty:c}=o;const d=document.createElement("canvas");d.width=20,d.height=20;const h=d.getContext("2d",{alpha:!1,willReadFrequently:!0});I.addEventListener("premium_toggle",t);const u=async()=>{const p=fe.isPremiumFeaturesHidden(),m=await Promise.all([I.managers.acknowledged.appChatsManager.getChannelRecommendations(o.chatId),I.managers.acknowledged.apiManager.getLimit("recommendedChannels",!1),I.managers.acknowledged.apiManager.getLimit("recommendedChannels",!0),{cached:!(p instanceof Promise),result:Promise.resolve(p)}]);return{cached:m.every(g=>g.cached),results:Promise.all(m.map(g=>g.result))}};return ye(async()=>{e();const p=Ys().get(),{cached:m,results:g}=await u();if(r?.(m),r=void 0,!p())return;const f=await g;if(p()){if(!f[0].chats.length){o.onEmpty?.();return}i(f)}}),ye(async()=>{const p=s();if(!p)return;const[m,g,f,y]=p,v=m.count??m.chats.length,w=v>g&&!y,b=new Map,S=(k,x)=>{const[A,T]=ne(),B=G=>{G.naturalWidth<100||(h.drawImage(G,0,0,d.width,d.height),T(i0(d)))},R=k.id.toPeerId(!0),O=w&&x()===g-1,X=Et(()=>Fn({peerId:R,size:60,processImageOnLoad:B}));X.node.classList.add("similar-channels-channel-avatar"),P.push(X.readyThumbPromise),O&&X.node.classList.add("similar-channels-channel-avatar-stack-first");let F;if(O)F=M("MoreSimilar");else{const G=new Rt;P.push(G.update({peerId:R})),F=G.element}F.classList.add("similar-channels-channel-name");const H=j(xi,{icon:O?"premium_lock":"newprivate_filled",class:"similar-channels-channel-badge-icon"});return(()=>{const G=Ok(),z=G.firstChild;return wt(q=>b.set(q,O?void 0:k),G),D(G,()=>O?(()=>{const q=Uk(),$=q.firstChild;return D(q,()=>X.element,$),q})():X.element,z),D(z,O?[`+${v-g}`,K(()=>!Et(e)&&H)]:[H,K(()=>on(k.participants_count||1,1))]),D(G,F,null),Ve(q=>{const $=ot("similar-channels-channel",O&&"is-last"),se=A()&&{"background-image":`url(${A()})`};return $!==q._v$&&Ce(G,q._v$=$),q._v$2=zi(z,se,q._v$2),q},{_v$:void 0,_v$2:void 0}),G})()},C=Ys().get(),P=[];let L;const E=(()=>{const k=Hk(),x=L;return typeof x=="function"?wt(x,k):L=k,D(k,j(ti,{get each(){return m.chats.slice(0,g)},children:S})),k})(),_=N(L,k=>{const x=U(k.target,"similar-channels-channel");if(!x)return;oe(k);const A=b.get(x);if(A){me.setInnerPeer({peerId:A.id.toPeerId(!0)});return}if(e()){ee.createPopup(Es,{onSelect:R=>{me.setInnerPeer({peerId:R})},peerType:["custom"],getMoreCustom:async()=>({result:m.chats.map(R=>R.id.toPeerId(!0)),isEnd:!0}),headerLangPackKey:"SimilarChannels"});return}const T=ni(()=>{B(),Vt.show()});T.classList.add("primary");const{close:B}=ur({element:x.querySelector(".similar-channels-channel-avatar-stack, .similar-channels-channel-avatar"),container:x.parentElement,vertical:"top",textElement:M("SimilarChannels.Unlock",[T,f]),icon:"star"})});ut(_),await Promise.all(P),C()&&(a(E),l?.(),l=void 0)}),(()=>{const p=$k(),m=p.firstChild,g=m.nextSibling;return D(g,()=>M("SimilarChannels"),null),D(g,j(kn,{icon:"close",get onClick(){return o.onClose}}),null),D(p,j(td,{get children(){return[ov(),K(()=>n()),ov()]}}),null),p})()}function Fa(o){return o?._==="forumTopic"}function la(o){return o?._==="savedDialog"}function lr(o){return o?._==="dialog"}function zS(o){const e=o.fwd_from;if(!e)return!1;const t=Rn(e),s=at(e.from_id);return!!(t&&(s||e.from_name&&e.saved_from_name&&e.from_name!==e.saved_from_name))||!!e.saved_from_id}function ou(o){return o[0]}function KS(o){if(o.type==="click"){oe(o);return}document.body.addEventListener("click",oe,{once:!0,capture:!0})}function Yp(o){const t=o?.reactions?.recent_reactions;if(!t)return;const s=t.filter(i=>i.pFlags.unread);if(s.length)return s}const cp=o=>{const{callback:e,onEnd:t}=o,s=yf(()=>o.children);return ye(()=>{const{dispose:i,element:n}=Ni(s(),e,t,!0);ut(()=>{i(),n.remove()})}),o.children},Gk=ce("<div dir=auto>"),lv=ce("<div>"),zk=ce("<div class=row-right>");function Ra(o={}){const e=h=>{if(h.part)return(()=>{const u=Gk();return D(u,()=>h.part),Ve(()=>Ce(u,ot("row-"+h.class,s()&&"no-wrap"))),u})()},t=h=>{const u=j(e,{get class(){return h.class},get part(){return h.left}});return h.right?(()=>{const p=lv();return D(p,u,null),D(p,j(e,{get class(){return`${h.class} row-${h.class}-right${h.rightSecondary?` row-${h.class}-right-secondary`:""}`},get part(){return h.right}}),null),Ve(()=>Ce(p,ot("row-row",`row-${h.class}-row`))),p})():u},s=()=>o.noWrap,i=j(t,{class:"title",get left(){return o.title},get right(){return o.titleRight||o.checkboxFieldToggle},get rightSecondary(){return o.titleRightSecondary}}),n=j(t,{class:"subtitle",get left(){return o.subtitle},get right(){return o.subtitleRight}}),a=()=>!!(o.checkboxField||o.checkboxFieldToggle||o.radioField),r=()=>!!(o.clickable||a()),l=()=>!!(!o.noRipple&&r()),c=()=>!!(o.havePadding||o.icon||o.checkboxField||o.radioField||o.media),d=j(Cg,{ref(h){const u=o.ref;typeof u=="function"?u(h):o.ref=h},get component(){return K(()=>!!o.asLink)()?"a":o.asLabel||a()?"label":"div"},get classList(){return{row:!0,"no-subtitle":!n,"no-wrap":o.noWrap,"row-with-icon":!!o.icon,"row-with-padding":c(),[`row-clickable hover-${o.color?o.color+"-":""}effect`]:r(),"is-disabled":o.disabled,"is-fake-disabled":o.fakeDisabled,"row-grid":!!o.rightContent,"with-midtitle":!!o.midtitle}},get onClick(){return typeof o.clickable!="boolean"&&o.clickable},get children(){return[i,K(()=>K(()=>!!o.midtitle)()&&j(t,{class:"midtitle",get left(){return o.midtitle}})),n,K(()=>K(()=>!!o.icon)()&&j(xi,{get icon(){return o.icon},get class(){return ot("row-icon",...o.iconClasses||[])}})),K(()=>o.checkboxField||o.radioField),K(()=>K(()=>!!o.rightContent)()&&(()=>{const h=zk();return D(h,()=>o.rightContent),h})()),K(()=>K(()=>!!o.media)()&&(()=>{const h=lv();return D(h,()=>o.media),Ve(()=>Ce(h,ot("row-media",o.mediaSize&&`row-media-${o.mediaSize}`))),h})())]}});return K((()=>{const h=K(()=>!!l());return()=>h()?j(cp,{children:d}):d})())}const Kk=ce("<div class=popup-about-ad-icon>"),Wk=ce("<div class=popup-about-ad-title>"),jk=ce("<div class=popup-about-ad-subtitle>"),qk=ce("<div class=popup-about-ad-caption><div class=popup-about-ad-caption-title></div><div class=popup-about-ad-caption-subtitle>");class WS extends ee{constructor(){super("popup-about-ad",{overlayClosable:!0,body:!0,scrollable:!0,withConfirm:"RevenueSharingAdsAlertButton",footer:!0}),this.header.remove(),this.footer.append(this.btnConfirm),N(this.btnConfirm,()=>{this.hide()}),this.construct()}_construct(){return[(()=>{const e=Kk();return D(e,j(xi,{icon:"ads"})),e})(),(()=>{const e=Wk();return D(e,()=>M("AboutRevenueSharingAds")),e})(),(()=>{const e=jk();return D(e,()=>M("RevenueSharingAdsAlertSubtitle")),e})(),j(Ra,{icon:"lock",get title(){return M("RevenueSharingAdsInfo1Title")},get subtitle(){return M("RevenueSharingAdsInfo1Subtitle")}}),j(Ra,{icon:"revenue",get title(){return M("RevenueSharingAdsInfo2Title")},get subtitle(){return M("RevenueSharingAdsInfo2Subtitle")}}),j(Ra,{icon:"nochannel",get title(){return M("RevenueSharingAdsInfo3Title")},get subtitle(){return M("RevenueSharingAdsInfo3Subtitle")}}),(()=>{const e=qk(),t=e.firstChild,s=t.nextSibling;return D(t,()=>M("RevenueSharingAdsInfo4Title")),D(s,()=>M("RevenueSharingAdsInfo4Subtitle2",[M("RevenueSharingAdsInfo4SubtitleLearnMore1")])),e})()]}async construct(){const e=document.createElement("div");this.scrollable.append(e);const t=Hi(()=>this._construct(),e);this.addEventListener("closeAfterTimeout",t),this.show()}}function jS(o,e,t,s){return{_:"inputWebFileGeoPointLocation",access_hash:o.access_hash,geo_point:{_:"inputGeoPoint",lat:o.lat,long:o.long},w:e,h:t,scale:window.devicePixelRatio,zoom:s}}function Lf(o){return"https://maps.google.com/maps?q="+o.lat+","+o.long}function Qk({messageMedia:o,attachmentDiv:e,bubble:t,timeSpan:s,wrapOptions:i,message:n,middleware:a,loadPromises:r,messageDiv:l,updateLocationOnEdit:c}){t.classList.add("photo");const d=document.createElement("a");d.classList.add("geo-container","shimmer-bright");const h=o._==="messageMediaVenue",u=o._==="messageMediaGeoLive",{geo:p}=o,m=277,g=195;d.innerHTML=`
<svg class="geo-svg" width="${m}px" height="${g}px" viewBox="0 0 277 195" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="Artboard" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<path class="geo-svg-path" d="M274.275109,103.333333 C275.780025,103.333333 277,104.567636 277,106.090226 L277,195 L201.724891,195 C200.219975,195 199,193.765697 199,192.243108 L199,109.536341 C199,106.110514 201.744944,103.333333 205.131004,103.333333 L274.275109,103.333333 Z M71.8689956,103.333333 C75.2550558,103.333333 78,106.110514 78,109.536341 L78,192.243108 C78,193.765697 76.7800248,195 75.2751092,195 L3.05533376e-13,195 L3.05533376e-13,106.090226 C3.05533376e-13,104.567636 1.21997518,103.333333 2.72489083,103.333333 L71.8689956,103.333333 Z M179.467331,145 C185.100269,145 190,149.937497 190,155.617021 L190,192.257683 C190,193.772223 188.448961,195 186.946844,195 L90.0531561,195 C88.5510395,195 87,193.772223 87,192.257683 L87,155.617021 C87,149.937497 91.8997314,145 97.5326689,145 L179.467331,145 Z M141.438333,165.734879 L136.933333,167.553888 L136.933333,166.559118 C136.933333,166.237002 136.805833,166.000152 136.550833,165.848568 C136.295833,165.696983 136.026667,165.678035 135.743333,165.791724 L130.02,168.236016 C129.698889,168.368652 129.448611,168.581817 129.269167,168.875512 C129.089722,169.169206 129,169.486585 129,169.827649 L129,180.628013 C129,181.101713 129.165278,181.504358 129.495833,181.835948 C129.826389,182.167538 130.227778,182.333333 130.7,182.333333 L149.966667,182.333333 C150.438889,182.333333 150.840278,182.167538 151.170833,181.835948 C151.501389,181.504358 151.666667,181.101713 151.666667,180.628013 L151.666667,168.690769 L142.6,168.690769 L142.6,166.530696 C142.6,166.227528 142.477222,165.990678 142.231667,165.820146 C141.986111,165.649613 141.721667,165.621191 141.438333,165.734879 Z M140.5,173.333333 C140.740741,173.333333 140.939815,173.410069 141.097222,173.563542 C141.25463,173.717014 141.333333,173.911111 141.333333,174.145833 L141.333333,176.854167 C141.333333,177.088889 141.25463,177.282986 141.097222,177.436458 C140.939815,177.589931 140.740741,177.666667 140.5,177.666667 C140.259259,177.666667 140.060185,177.589931 139.902778,177.436458 C139.74537,177.282986 139.666667,177.088889 139.666667,176.854167 L139.666667,174.145833 C139.666667,173.911111 139.74537,173.717014 139.902778,173.563542 C140.060185,173.410069 140.259259,173.333333 140.5,173.333333 Z M135.833333,173.333333 C136.074074,173.333333 136.273148,173.410069 136.430556,173.563542 C136.587963,173.717014 136.666667,173.911111 136.666667,174.145833 L136.666667,176.854167 C136.666667,177.088889 136.587963,177.282986 136.430556,177.436458 C136.273148,177.589931 136.074074,177.666667 135.833333,177.666667 C135.592593,177.666667 135.393519,177.589931 135.236111,177.436458 C135.078704,177.282986 135,177.088889 135,176.854167 L135,174.145833 C135,173.911111 135.078704,173.717014 135.236111,173.563542 C135.393519,173.410069 135.592593,173.333333 135.833333,173.333333 Z M144.833333,173.333333 C145.074074,173.333333 145.273148,173.410069 145.430556,173.563542 C145.587963,173.717014 145.666667,173.911111 145.666667,174.145833 L145.666667,176.854167 C145.666667,177.088889 145.587963,177.282986 145.430556,177.436458 C145.273148,177.589931 145.074074,177.666667 144.833333,177.666667 C144.592593,177.666667 144.393519,177.589931 144.236111,177.436458 C144.078704,177.282986 144,177.088889 144,176.854167 L144,174.145833 C144,173.911111 144.078704,173.717014 144.236111,173.563542 C144.393519,173.410069 144.592593,173.333333 144.833333,173.333333 Z M149.658824,159.666667 L148.341176,159.666667 C148.139869,159.666667 147.966013,159.735119 147.819608,159.872024 C147.673203,160.008929 147.581699,160.177778 147.545098,160.378571 L146.666667,167.333333 L151.333333,167.333333 L150.454902,160.378571 C150.418301,160.177778 150.326797,160.008929 150.180392,159.872024 C150.033987,159.735119 149.860131,159.666667 149.658824,159.666667 Z M249.919094,140.666667 L238.414239,140.666667 C237.928803,140.666667 237.516181,140.839506 237.176375,141.185185 C236.83657,141.530864 236.666667,141.950617 236.666667,142.444444 L236.666667,144.518519 L242.812298,148.903704 C243.02589,149.061728 243.200647,149.298765 243.33657,149.614815 C243.472492,149.930864 243.540453,150.237037 243.540453,150.533333 L243.540453,162 L249.919094,162 C250.404531,162 250.817152,161.82716 251.156958,161.481481 C251.496764,161.135802 251.666667,160.716049 251.666667,160.222222 L251.666667,142.444444 C251.666667,141.950617 251.496764,141.530864 251.156958,141.185185 C250.817152,140.839506 250.404531,140.666667 249.919094,140.666667 Z M233.681454,145 C233.306839,145 232.961799,145.109357 232.646334,145.32807 L226.406038,149.831579 C226.169439,149.990643 225.987061,150.204386 225.858903,150.472807 C225.730746,150.741228 225.666667,151.01462 225.666667,151.292982 L225.666667,161.105263 C225.666667,161.363743 225.750462,161.577485 225.918053,161.746491 C226.085644,161.915497 226.297597,162 226.553913,162 L231.315465,162 L231.315465,155.408772 L236.047443,155.408772 L236.047443,162 L240.779421,162 C241.035736,162 241.247689,161.915497 241.41528,161.746491 C241.582871,161.577485 241.666667,161.363743 241.666667,161.105263 L241.666667,151.292982 C241.666667,151.01462 241.602588,150.741228 241.47443,150.472807 C241.346272,150.204386 241.163894,149.990643 240.927295,149.831579 L234.716574,145.32807 C234.401109,145.109357 234.056069,145 233.681454,145 Z M28.1107355,151 C26.7011204,151.535116 25.6080384,152.177255 24.8314897,152.926418 C24.054941,153.67558 23.6666667,154.507839 23.6666667,155.423195 C23.6666667,156.313825 24.0383266,157.128954 24.7816465,157.868583 C25.5249664,158.608212 26.5730748,159.243985 27.9259717,159.775903 L28.3614887,159.946655 C29.6189312,160.436878 31.0759356,160.969375 32.7325021,161.229902 C34.5839587,161.521079 36.6177601,161.666667 38.8339062,161.666667 C41.0575639,161.666667 43.0932432,161.521079 44.940944,161.229902 C46.7886449,160.938725 48.3905989,160.30782 49.746806,159.775903 C51.1030131,159.243985 52.1509305,158.608212 52.8905583,157.868583 C53.6301861,157.128954 54,156.313825 54,155.423195 C54,154.74612 53.7747506,154.109424 53.3242518,153.513108 C52.8737529,152.916792 52.232252,152.376601 51.399749,151.892537 C51.0481091,152.042615 50.6745076,152.157696 50.2789446,152.237779 C49.8833815,152.317862 49.4585364,152.366145 49.0044091,152.382629 C48.0792219,153.944799 46.7901408,155.168707 45.137166,156.054355 C43.4841911,156.940003 41.5781488,157.382827 39.4190391,157.382827 L38.373477,157.382827 C36.7571047,157.382827 35.2762577,157.12145 33.9309359,156.598697 C32.5856141,156.075944 31.4161441,155.337853 30.4225259,154.384424 C29.4289077,153.430995 28.6583108,152.302854 28.1107355,151 Z M246.666667,155.666667 L246.666667,157.333333 L245,157.333333 L245,155.666667 L246.666667,155.666667 Z M38.9247583,138.333333 C36.8805223,138.333333 35.0878837,138.524784 33.5468423,138.907687 C32.005801,139.290589 30.807178,139.825485 29.9509735,140.512377 C29.0947689,141.199268 28.6666667,142.000558 28.6666667,142.916248 L28.6666667,145.217011 C28.6666667,146.65308 28.8977785,147.968639 29.3600021,149.163689 C29.8222257,150.358738 30.4832473,151.391681 31.343067,152.262516 C32.2028866,153.133352 33.2290636,153.807308 34.421598,154.284385 C35.6141324,154.761462 36.9411543,155 38.4026637,155 L39.4443793,155 C41.3903102,155 43.0928254,154.597401 44.5519248,153.792202 C46.0110242,152.987003 47.1473979,151.850115 47.961046,150.381537 C48.0380117,150.24262 48.1113372,150.101439 48.1810225,149.957994 L48.8310449,149.957752 C50.1301926,149.957752 51.1498054,149.643464 51.8898832,149.014889 C52.6299611,148.386314 53,147.516781 53,146.406291 C53,145.303865 52.6297708,144.436566 51.8893124,143.804392 C51.2166514,143.230102 50.3137723,142.916665 49.1810488,142.863979 C49.1649624,141.970034 48.735209,141.186167 47.8917885,140.512377 C47.0319689,139.825485 45.8315067,139.290589 44.2904019,138.907687 C42.7492971,138.524784 40.9607493,138.333333 38.9247583,138.333333 Z M246.666667,150.333333 L246.666667,152 L245,152 L245,150.333333 L246.666667,150.333333 Z M49.3462947,144.666667 C49.9216674,144.707967 50.3794206,144.850985 50.719554,145.095721 C51.1287402,145.390142 51.3333333,145.798671 51.3333333,146.321307 C51.3333333,146.844067 51.1285423,147.254623 50.7189604,147.552974 C50.312817,147.848821 49.7398788,147.997986 49,148 C49.2305654,147.116215 49.3458481,146.164212 49.3458481,145.143993 L49.3462947,144.666667 Z M246.666667,145.333333 L246.666667,147 L245,147 L245,145.333333 L246.666667,145.333333 Z M39.0006663,140.333333 C40.5947307,140.333333 42.0207584,140.451406 43.2787493,140.687551 C44.5367403,140.923696 45.527002,141.243793 46.2495345,141.647842 C46.9720671,142.051891 47.3333333,142.502395 47.3333333,142.999356 C47.3333333,143.49558 46.9718767,143.9459 46.2489634,144.350317 C45.5260501,144.754734 44.5357884,145.07523 43.2781782,145.311805 C42.020568,145.548379 40.5947307,145.666667 39.0006663,145.666667 C37.406475,145.666667 35.9822242,145.548379 34.7279138,145.311805 C33.4736034,145.07523 32.4831513,144.754734 31.7565574,144.350317 C31.0299636,143.9459 30.6666667,143.49558 30.6666667,142.999356 C30.6666667,142.502395 31.0297732,142.051891 31.7559863,141.647842 C32.4821994,141.243793 33.4724611,140.923696 34.7267715,140.687551 C35.9810819,140.451406 37.4057135,140.333333 39.0006663,140.333333 Z M176.83043,52 C183.919688,52 190,58.1245592 190,65.2683983 L190,122.398268 C190,129.542107 183.919688,135 176.83043,135 L100.16957,135 C93.0803124,135 87,129.542107 87,122.398268 L87,65.2683983 C87,58.1245592 93.0803124,52 100.16957,52 L176.83043,52 Z M138.333333,80.3333333 C135.511111,80.3333333 133.027778,81.3372814 130.883333,83.3451777 C128.738889,85.3530739 127.666667,88.0490694 127.666667,91.4331641 C127.666667,93.6215454 128.488889,95.9791314 130.133333,98.5059222 C131.777778,101.032713 134.255556,103.77383 137.566667,106.729272 C137.677778,106.819515 137.8,106.887197 137.933333,106.932318 C138.066667,106.977439 138.211111,107 138.366667,107 C138.5,107 138.627778,106.977439 138.75,106.932318 C138.872222,106.887197 138.988889,106.819515 139.1,106.729272 C142.411111,103.77383 144.888889,101.032713 146.533333,98.5059222 C148.177778,95.9791314 149,93.6215454 149,91.4331641 C149,88.0490694 147.927778,85.3530739 145.783333,83.3451777 C143.638889,81.3372814 141.155556,80.3333333 138.333333,80.3333333 Z M138,88 C138.920635,88 139.706349,88.3253968 140.357143,88.9761905 C141.007937,89.6269841 141.333333,90.4126984 141.333333,91.3333333 C141.333333,92.2539683 141.007937,93.0396825 140.357143,93.6904762 C139.706349,94.3412698 138.920635,94.6666667 138,94.6666667 C137.079365,94.6666667 136.293651,94.3412698 135.642857,93.6904762 C134.992063,93.0396825 134.666667,92.2539683 134.666667,91.3333333 C134.666667,90.4126984 134.992063,89.6269841 135.642857,88.9761905 C136.293651,88.3253968 137.079365,88 138,88 Z M277,0 L277,91.2454212 C277,92.7667331 275.781665,94 274.278772,94 L205.227621,94 C201.846113,94 199.104859,91.2251494 199.104859,87.8021978 L199.104859,66.7985348 C199.104859,54.8182041 189.51047,41.6630037 177.675192,41.6630037 L149.102302,41.6630037 C146.284378,41.6630037 144,39.3506282 144,36.4981685 L144,2.75457875 C144,1.23326692 145.218335,0 146.721228,0 L277,0 Z M129.945299,0 C131.448269,0 132.666667,1.23326692 132.666667,2.75457875 L132.666667,36.4981685 C132.666667,39.3506282 130.382171,41.6630037 127.564103,41.6630037 L99.3299145,41.6630037 C87.4940275,41.6630037 77.8991453,54.8182041 77.8991453,66.7985348 L77.8991453,87.8021978 C77.8991453,91.2251494 75.1577504,94 71.7760684,94 L2.72136752,94 C1.21839774,94 0,92.7667331 0,91.2454212 L0,0 L129.945299,0 Z M237.333333,28.6666667 C235.486111,28.6666667 233.875868,29.2909326 232.502604,30.5394645 C231.12934,31.7879963 230.333333,33.3393899 230.114583,35.1936451 C228.753472,35.7622834 227.671875,36.6708685 226.869792,37.9194003 C226.067708,39.1679322 225.666667,40.5339002 225.666667,42.0173044 C225.666667,44.0693469 226.377604,45.8185276 227.799479,47.2648467 C229.221354,48.7111658 230.940972,49.4343254 232.958333,49.4343254 L236.239583,49.4343254 L236.239583,55.0331916 L232.958333,55.0331916 C232.642361,55.0331916 232.381076,55.1382661 232.174479,55.348415 C231.967882,55.5585639 231.864583,56.5660426 231.864583,56.8874469 C231.864583,57.2088511 231.967882,57.4746277 232.174479,57.6847766 C232.381076,57.8949255 232.642361,58 232.958333,58 L241.34375,58 C241.659722,58 241.921007,57.8949255 242.127604,57.6847766 C242.334201,57.4746277 242.4375,57.2088511 242.4375,56.8874469 C242.4375,56.5660426 242.334201,55.5585639 242.127604,55.348415 C241.921007,55.1382661 241.659722,55.0331916 241.34375,55.0331916 L238.427083,55.0331916 L238.427083,49.4343254 L241.708333,49.4343254 C243.725694,49.4343254 245.445312,48.7111658 246.867188,47.2648467 C248.289062,45.8185276 249,44.0693469 249,42.0173044 C249,40.5339002 248.598958,39.1679322 247.796875,37.9194003 C246.994792,36.6708685 245.913194,35.7622834 244.552083,35.1936451 C244.333333,33.3393899 243.537326,31.7879963 242.164062,30.5394645 C240.790799,29.2909326 239.180556,28.6666667 237.333333,28.6666667 Z M39.3280935,33 C39.2243891,33 39.1258699,33.0154494 39.0325359,33.0463483 C38.9392019,33.0772472 38.8510531,33.1235955 38.7680896,33.1853933 L31.8613745,38.3405982 L31.8613745,37.6966292 L31.8583795,37.640264 C31.8289402,37.347262 31.5754523,36.7755434 30.7901174,36.7755434 L30.6207017,36.7767977 L30.4578933,36.7810704 C29.9778294,36.7994331 29.824306,36.8638758 29.6931536,36.9792263 L29.6369144,37.0323034 C29.4606169,37.207397 29.3724681,37.428839 29.3724681,37.6966292 L29.3724681,40.2921348 L26.3857805,42.5477528 C26.1783716,42.7125468 26.0539263,42.9185393 26.0124445,43.1657303 C25.9709628,43.4129213 26.0331854,43.6395131 26.1991125,43.8455056 C26.3650396,44.0514981 26.5724485,44.1750936 26.8213391,44.2162921 C27.0702297,44.2574906 27.2983795,44.1956929 27.5057883,44.0308989 L29.3724681,42.6095506 L29.3724681,54.0730337 C29.3724681,54.340824 29.4606169,54.5622659 29.6369144,54.7373596 C29.8132119,54.9124532 30.0361765,55 30.305808,55 L36.866591,55 C37.3669257,55 37.7725271,54.5921805 37.7725271,54.0891096 L37.7725271,49.1292135 C37.7725271,48.8614232 37.8606758,48.6399813 38.0369734,48.4648876 C38.2132709,48.289794 39.058462,47.9008773 39.3280935,47.9008773 C39.5977251,47.9008773 40.4429162,48.289794 40.6192137,48.4648876 C40.7955112,48.6399813 40.88366,48.8614232 40.88366,49.1292135 L40.88366,54.0891096 C40.88366,54.5921805 41.2892614,55 41.7895961,55 L48.3503791,55 C48.6200106,55 48.8429751,54.9124532 49.0192726,54.7373596 C49.1955702,54.5622659 49.283719,54.340824 49.283719,54.0730337 L49.283719,42.6095506 L51.2441994,44.0774017 C51.4336674,44.2081039 51.6357355,44.2595506 51.8504036,44.2317416 C52.0889238,44.2008427 52.2911475,44.082397 52.4570746,43.8764045 C52.6230016,43.670412 52.6904095,43.4438202 52.6592982,43.1966292 C52.6281869,42.9494382 52.5089268,42.7434457 52.3015179,42.5786517 L39.8880975,33.1853933 C39.8051339,33.1235955 39.7169851,33.0772472 39.6236512,33.0463483 C39.5303172,33.0154494 39.431798,33 39.3280935,33 Z" id="Shape" fill="#FFFFFF"></path>
</g>
</svg>`,Jr(d);const f=d.firstElementChild;e.append(d);const y=16,v=A=>{d.href=Lf(A)},w=$e.isMobile?m:420;let b=0;const S=(A,T)=>{const B=A.geo,R=++b,O=d.querySelector(".geo-image-container");O&&(st.isAvailable("animations")?O.classList.add("fade-out"):O.remove()),d.classList.add("shimmer"),d.prepend(f);const X={...i,...R!==0?{lazyLoadQueue:void 0}:{}},F=document.createElement("div");if(F.classList.add("geo-image-container"),u){const H=document.createElement("div");H.classList.add("geo-live-pin");const G=document.createElement("div");G.classList.add("geo-live-pin-heading"),H.append(G),H.insertAdjacentHTML("beforeend",`
<svg version="1.1" class="geo-live-pin-svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 64 64" style="enable-background:new 0 0 64 64;" xml:space="preserve">
<g>
<circle cx="32" cy="32" r="24.5"/>
<path d="M32,8c13.23,0,24,10.77,24,24S45.23,56,32,56S8,45.23,8,32S18.77,8,32,8 M32,7C18.19,7,7,18.19,7,32s11.19,25,25,25 s25-11.19,25-25S45.81,7,32,7L32,7z"/>
</g>
<g>
<polygon points="29.38,57.67 27.4,56.08 30.42,54.42 32,51.54 33.58,54.42 36.6,56.08 34.69,57.61 32,60.73"></polygon>
<path d="M32,52.58l1.07,1.95l0.14,0.26l0.26,0.14l2.24,1.22l-1.33,1.06l-0.07,0.06l-0.06,0.07L32,59.96l-2.24-2.61l-0.06-0.07 l-0.07-0.06l-1.33-1.06l2.24-1.22l0.26-0.14l0.14-0.26L32,52.58 M32,50.5l-1.94,3.56L26.5,56l2.5,2l3,3.5l3-3.5l2.5-2l-3.56-1.94 L32,50.5L32,50.5z"/>
</g>
</svg>
`);const z=es({middleware:a,size:54,peerId:n.fromId,isDialog:!1,wrapOptions:X});z.node.classList.add("geo-live-pin-avatar"),T?.push(z.readyThumbPromise),H.append(z.node),F.append(H)}else F.innerHTML=`
<svg class="geo-pin" xmlns="http://www.w3.org/2000/svg" width="21.333" height="37.218" viewBox="0 0 20 34.892">
<g transform="translate(-965.773 -331.784) scale(1.18559)">
<path d="M817.112 282.971c-1.258 1.343-2.046 3.299-2.015 5.139.064 3.845 1.797 5.3 4.568 10.592.999 2.328 2.04 4.792 3.031 8.873.138.602.272 1.16.335 1.21.062.048.196-.513.334-1.115.99-4.081 2.033-6.543 3.031-8.871 2.771-5.292 4.504-6.748 4.568-10.592.031-1.84-.759-3.798-2.017-5.14-1.437-1.535-3.605-2.67-5.916-2.717-2.312-.048-4.481 1.087-5.919 2.621z" style="fill:#ea4336;stroke:#ea4336;stroke-width:1;"/>
<circle r="3.035" cy="288.253" cx="823.031" style="fill:#970a0a;stroke-width:0"/>
</g>
</svg>
`;Ks({photo:jS(B,w,w/(m/g),y),container:F,fadeInElement:F,onRender:()=>{R===b&&d.append(F)},onRenderFinish:()=>{R===b&&(d.classList.remove("shimmer"),f.remove(),O?.remove())},loadPromises:T,...X})};function C(A,T){return 156543.03392*Math.cos(A*(Math.PI/180))/2**T}v(p),S(o,r);let P=u?(n.date+o.period)*1e3:void 0;const L=u&&Date.now()>=P;let E,_,k,x;if(h||u&&!L?(t.classList.remove("is-message-empty"),E=document.createElement("div"),E.classList.add("geo-footer"),_=document.createElement("div"),_.classList.add("geo-footer-title"),k=document.createElement("div"),k.classList.add("geo-footer-address"),E.append(_,k),l.append(E)):x=!1,u&&(d.classList.add("is-live"),d.classList.toggle("is-expired",L)),h)_.append(_e(o.title)),k.append(_e(o.address));else if(u&&!L){s.classList.add("hide"),_.classList.add("disable-hover"),k.classList.add("disable-hover"),E.classList.add("is-live");const A=new ke.IntlElement;_.append(M("AttachLiveLocation")),k.append(A.element);const T=document.createElement("div");T.classList.add("geo-footer-timer");const B=13,R=(B+2)*2,O=B*2*Math.PI,X=new ke.IntlElement;T.append(X.element),T.insertAdjacentHTML("beforeend",`
<svg class="geo-footer-timer-svg" width="${R}px" height="${R}px">
<circle cx="${R/2}" cy="${R/2}" r="${B}" class="geo-footer-timer-circle" transform="rotate(-90, ${R/2}, ${R/2})" stroke-dasharray="${O} ${O}"></circle>
</svg>
`);const F=T.lastElementChild.firstElementChild,H=F.cloneNode(!0);H.classList.add("geo-footer-timer-circle-shadow"),T.lastElementChild.append(H),E.append(T);let G=n,z=!1;const q=(Y=G,Q)=>{if(z)return;const he=Y.media,{period:le}=he,re=he.geo;if(P=Q?0:(Y.date+le)*1e3,G!==Y&&(G&&(p.lat!==re.lat||p.long!==re.long)&&(v(re),S(he)),G=Y),Date.now()>=P){t.classList.add("is-message-empty"),d.classList.add("is-expired"),s.classList.remove("hide"),E.replaceWith(s),se();return}if(d.style.setProperty("--heading",`${he.heading}deg`),re.accuracy_radius!==void 0){const Ze=re.accuracy_radius/C(re.lat,y);d.style.setProperty("--accuracy-size",`${Ze*2}px`)}let ge,be;Ms(!0)-(Y.edit_date??Y.date)<60?ge="LocationUpdatedJustNow":(ge="UpdatedMinutes",be=[Math.floor((Ms(!0)-Y.edit_date)/60)]);const Z=(P-Date.now())/1e3,de=(1-Z/le)*O;F.setAttribute("stroke-dashoffset",`-${de}`),A.compareAndUpdate({key:ge,args:be}),X.compareAndUpdate({key:Z<3600?"JustArgument":"MessageTimer.ShortHours",args:[Math.round(Z<3600?Z/60:Z/3600)]})},$=setInterval(q,1e3);q();const se=()=>{z=!0,c.delete(t),clearInterval($)};c.set(t,q),a.onClean(se)}return k&&k.append(s),x}function qS({button:o,chat:e,message:t,noTextInject:s,replyMarkup:i}){let n=Yt(o.text,{noLinks:!0,noLinebreaks:!0}),a,r,l;const{peerId:c}=e,d=t?.media,h=i?.mid||t?.mid,u=i?.fromId||t?.viaBotId||t?.fromId;switch(o._){case"keyboardButtonUrl":{const p=Yt(" ",{entities:[{_:"messageEntityTextUrl",length:1,offset:0,url:o.url}]});a=Ed(p).firstElementChild,a.classList.add("is-link"),r=Le("arrow_next");break}case"keyboardButtonSwitchInline":{a=document.createElement("button"),a.classList.add("is-switch-inline"),r=Le("forward_filled"),l=p=>{oe(p);let m;o.pFlags.same_peer?m=Promise.resolve(c):m=I.managers.appInlineBotsManager.checkSwitchReturn(u).then(g=>{if(g)return g;let f;if(o.peer_types){const y={inlineQueryPeerTypePM:"users",inlineQueryPeerTypeBotPM:"bots",inlineQueryPeerTypeBroadcast:"channels",inlineQueryPeerTypeChat:"groups",inlineQueryPeerTypeMegagroup:"groups"};f=o.peer_types.map(v=>y[v._])}return Es.createPicker(f,["send_inline"])}),m.then(async g=>{const f=c===g?e.threadId:void 0;await e.appImManager.setInnerPeer({peerId:g,threadId:f}),I.managers.appInlineBotsManager.switchInlineQuery(g,f,u,o.query)})};break}case"keyboardButtonBuy":{const p=d._==="messageMediaInvoice"?d:void 0;if(p?.extended_media)break;a=document.createElement("button"),a.classList.add("is-buy"),r=Le("card"),p?.receipt_msg_id&&(n=M("Message.ReplyActionButtonShowReceipt"));break}case"keyboardButtonUrlAuth":{a=document.createElement("button"),a.classList.add("is-url-auth");const{url:p,button_id:m}=o;l=()=>{const g=jt([a],!0);e.appImManager.handleUrlAuth({peerId:c,mid:h,url:p,buttonId:m}).then(()=>{g()})};break}case"keyboardButtonSimpleWebView":case"keyboardButtonWebView":{a=document.createElement("button"),a.classList.add("is-web-view"),r=Le("webview"),l=()=>{const p=jt([a],!0);e.openWebApp({botId:u,url:o.url,isSimpleWebView:o._==="keyboardButtonSimpleWebView",buttonText:o.text}).finally(()=>{p()})};break}case"keyboardButtonRequestPhone":{a=document.createElement("button"),a.classList.add("is-request-phone"),l=()=>{e.appImManager.requestPhone(c)};break}case"keyboardButtonCallback":{a=document.createElement("button"),l=()=>{I.managers.appInlineBotsManager.callbackButtonClick(c,h,o).then(p=>{typeof p.message=="string"&&p.message.length&&zs(Yt(p.message,{noLinks:!0,noLinebreaks:!0}))})};break}case"keyboardButtonRequestPeer":{a=document.createElement("button"),l=async()=>{let p;const m=o.peer_type,g=m._==="requestPeerTypeUser",f=m._==="requestPeerTypeBroadcast",y=m._==="requestPeerTypeChat",v=["dialogs"];if(g)p=b=>!(b._!=="user"||m.bot!==void 0&&m.bot!==!!b.pFlags.bot||m.premium!==void 0&&m.premium!==!!b.pFlags.premium),v.push("contacts");else{let b;y&&(b=(await I.managers.appUsersManager.getCommonChats(c,100)).chats.map(C=>C.id)),p=S=>{if(S._!=="channel"&&(f||S._!=="chat")||!!S.pFlags.broadcast!==f||m.pFlags.creator&&!S.pFlags.creator||m.has_username!==void 0&&!!ui(S)[0]!=!!m.has_username||m.forum!==void 0&&m.forum!==!!S.pFlags.forum)return!1;if(m.user_admin_rights){for(const C in m.user_admin_rights.pFlags)if(!fa(S,C))return!1}return!(m.pFlags.bot_participant&&!b.includes(S.id)&&!fa(S,"invite_users"))}}const w=await Es.createPicker2({peerType:v,filterPeerTypeBy:p,multiSelect:!0,limit:o.max_quantity,limitCallback:()=>{Ee({langPackKey:"RequestPeer.MultipleLimit",langPackArguments:[M(g?"RequestPeer.MultipleLimit.Users":f?"RequestPeer.MultipleLimit.Channels":"RequestPeer.MultipleLimit.Groups",[o.max_quantity])]})},titleLangKey:g?"RequestPeer.Title.Users":f?"RequestPeer.Title.Channels":"RequestPeer.Title.Groups"});if(!g){const b=await Promise.all(w.map(E=>Oe({peerId:E}))),S=pi(b,!1);let C;S.length===1?C=S[0]:(C=document.createElement("span"),C.append(...S));const P=[C,await Oe({peerId:c})];await Ct({descriptionLangKey:"Chat.Service.PeerRequest.Confirm.Plain",descriptionLangArgs:P,button:{langKey:"Chat.Service.PeerRequest.Confirm.Ok"}})}I.managers.appMessagesManager.sendBotRequestedPeer(c,h,o.button_id,w).catch(b=>{b.type==="CHAT_ADMIN_INVITE_REQUIRED"&&Ee({langPackKey:f?"Error.RequestPeer.NoRights.Channel":"Error.RequestPeer.NoRights.Group"})})};break}default:{a=document.createElement("button"),t||(l=()=>{I.managers.appMessagesManager.sendText({peerId:c,text:o.text})});break}}return r&&r.classList.add("reply-markup-button-icon"),s||a?.append(n),{text:n,buttonEl:a,buttonIcon:r,onClick:l}}const lu=ce("<div>"),Yk=ce("<div class=webpage-name><strong>"),Xk=ce("<span class=webpage-name-tip>"),Zk=ce("<div class=webpage-title><strong>"),Jk=ce("<div class=webpage-text>"),eT=ce("<div class=webpage-preview-resizer>"),qo="webpage";function tT(o){return o?.content&&(()=>{const e=lu(),t=o.ref;return typeof t=="function"?wt(t,e):o.ref=e,D(e,()=>o.content,null),D(e,(()=>{const s=K(()=>!!o.link);return()=>s()&&j(xi,{icon:"arrow_next",class:`${qo}-footer-icon`})})(),null),Ve(s=>{const i=ku(),n=ot(`${qo}-footer`,o.link&&"is-link",o.text&&"is-text",!o.text&&"is-button");return i!==s._v$&&Ti(e,"dir",s._v$=i),n!==s._v$2&&Ce(e,s._v$2=n),s},{_v$:void 0,_v$2:void 0}),e})()}function sT(o){return o?.content&&(()=>{const e=Yk(),t=e.firstChild;return D(t,()=>o.content),D(e,(()=>{const s=K(()=>!!o.tip);return()=>s()&&(()=>{const i=Xk();return Pl(i,"click",o.tip.onClick,!0),D(i,()=>o.tip.content),i})()})(),null),Ve(()=>Ti(e,"dir",ku())),e})()}function iT(o){return o&&(()=>{const e=Zk(),t=e.firstChild;return D(t,o),Ve(()=>Ti(e,"dir",ku())),e})()}function nT(o){return(()=>{const e=Jk();return D(e,()=>o.children),Ve(()=>Ti(e,"dir",ku())),e})()}function aT(o){if(!o)return;const e=`${qo}-preview`,t=o.hasDocument&&`${e}-with-document`;return o.content&&o.content.classList.add(...[e,t].filter(Boolean)),(()=>{const s=eT();return D(s,()=>o.content||(()=>{const i=lu(),n=o.ref;return typeof n=="function"?wt(n,i):o.ref=i,Ve(()=>Ce(i,ot(e,t))),i})()),s})()}function cv(o){const e=tT(o.footer),t=sT(o.name),s=iT(o.title),i=aT(o.media),n=(()=>{const l=lu();return D(l,()=>o.media?.position==="top"&&i,null),D(l,t,null),D(l,s,null),D(l,(()=>{const c=K(()=>!!o.text);return()=>c()&&j(nT,{get children(){return o.text}})})(),null),D(l,()=>o.media?.position==="bottom"&&i,null),D(l,e,null),Ve(()=>Ce(l,ot(`${qo}-content`,o.media?.hasDocument&&"has-document",o.minContent&&"min-content"))),l})(),a=(()=>{const l=lu();return D(l,n),Ve(()=>Ce(l,ot(`${qo}-quote`,"quote-like-border"))),l})(),r=j(Cg,{get component(){return o.clickable?"a":"div"},ref(l){const c=o.ref;typeof c=="function"?c(l):o.ref=l},get class(){return ot(qo,"quote-like",o.clickable&&"quote-like-hoverable",o.media?.photoSize&&`has-${o.media.photoSize}-photo`)},children:a});return o.clickable?j(cp,{children:r}):r}Ui(["click"]);function rT(){const o=document.createElement("span");return o.classList.add("clearfix"),o}function ro(o){window.open(o,"_blank","noreferrer")}const oT=!1,lT=!1,dv=!1,cT=[["messageActionHistoryClear",!0],["messageActionChatCreate",o=>o.pFlags.out],["messageActionChannelMigrateFrom",!0],["messageActionChatMigrateTo",!0],["messageActionContactSignUp",!0]],dT=new Map(cT),Pf=new Set;Fc&&Pf.add("messageActionPhoneCall");let hv=0;const uv=1,QS=3,pv=300,Xp=new Error("peer changed"),hT=!1,uT=Pi,Zp=!0,YS={1:96,2:90,3:84,4:72,5:60,6:48,7:36},pT=Object.keys(YS).length,mT={telegram_channel:"Chat.Message.ViewChannel",telegram_megagroup:"OpenGroup",telegram_bot:"Chat.Message.ViewBot",telegram_botapp:"Chat.Message.ViewApp",telegram_user:"Chat.Message.SendMessage",telegram_chatlist:"OpenChatlist",telegram_story:"OpenStory",telegram_channel_boost:"BoostLinkButton",telegram_giftcode:"Open",telegram_chat:"OpenGroup",telegram_livestream:"VoipChannelJoinVoiceChatUrl"},mv={telegram_livestream:"PeerInfo.Action.LiveStream"};function Jp(o){return Math.min(...o)}const gT=o=>o.photo;function $t(o,e){return typeof o=="object"&&(e=o.mid,o=o.peerId),`${o}_${e}`}function Bn(o){if(!(!o||o.dataset.mid===void 0))return $t(o.dataset.peerId.toPeerId(),+o.dataset.mid)}function Is(o){const[e,t]=o.split("_");return{peerId:e.toPeerId(),mid:+t}}const Ds=$t(Tt,0);function ch(o,e,t){o.timeAppenders.unshift({element:e,callback:t}),t()}class fT{constructor(e,t){this.chat=e,this.managers=t,this.unreadOut=new Set,this.needUpdate=[],this.bubbles={},this.skippedMids=new Set,this.bubblesNewByGroupedId={},this.bubblesNew={},this.dateMessages={},this.scrolledDown=!0,this.isScrollingTimeout=0,this.unreaded=new Map,this.unreadedContent=new Map,this.unreadedSeen=new Set,this.unreadedContentSeen=new Set,this.preloader=null,this.messagesQueueOnRenderAdditional=null,this.firstUnreadBubble=null,this.middlewareHelper=xt(),this.followStack=[],this.isHeavyAnimationInProgress=!1,this.isFirstLoad=!0,this.passEntities={},this.viewsMids=new Set,this.isTopPaddingSet=!1,this.renderingMessages=new Set,this.bubblesToEject=new Set,this.bubblesToReplace=new Map,this.setPeerTempId=0,this.renderNewPromises=new Set,this.extendedMediaMessages=new Set,this.updateLocationOnEdit=new Map,this.unreadedObserverCallback=n=>{if(n.isIntersecting){const a=n.target,r=this.unreaded.get(a);this.onUnreadedInViewport("history",a,r)}},this.unreadedContentObserverCallback=n=>{if(n.isIntersecting){const a=n.target,r=this.unreadedContent.get(a);this.onUnreadedInViewport("content",a,r)}},this.viewsObserverCallback=n=>{if(n.isIntersecting){const a=Bn(n.target);if(this.observer.unobserve(n.target,this.viewsObserverCallback),a)this.viewsMids.add(a),this.sendViewCountersDebounced();else{const{sponsoredMessage:r}=this;if(!r||r.viewed)return;r.viewed=!0,this.managers.appChatsManager.viewSponsoredMessage(this.peerId.toChatId(),r.random_id)}}},this._stickerEffectObserverCallback=(n,a,r)=>{if(n.isIntersecting){this.observer.unobserve(n.target,a);const l=n.target.querySelector(r);As().then(()=>{ca(l)&&fs(l)})}},this.stickerEffectObserverCallback=n=>{this._stickerEffectObserverCallback(n,this.stickerEffectObserverCallback,".attachment")},this.messageEffectObserverCallback=n=>{this._stickerEffectObserverCallback(n,this.messageEffectObserverCallback,".time-inner .time-effect")},this.onBubblesMouseMove=async n=>{U(n.target,"media-video-mini")?.onMouseMove?.(n);const r=U(n.target,"bubble-content");if(!(this.chat.type!==te.Scheduled&&r&&!this.chat.selection.isSelecting&&!U(n.target,"service")&&!U(n.target,"bubble-beside-button")&&this.peerId!==I.myId)){this.unhoverPrevious();return}const l=U(r,"bubble");if(!this.chat.selection.canSelectBubble(l)){this.unhoverPrevious();return}let{hoverBubble:c,hoverReaction:d}=this;if(l===c)return;if(this.unhoverPrevious(),c=this.hoverBubble=l,d=this.hoverReaction,d){d.dataset.loaded&&this.setHoverVisible(d,!0);return}d=this.hoverReaction=document.createElement("div"),d.classList.add("bubble-hover-reaction");const u=(d.middlewareHelper=this.getMiddleware().create()).get(()=>this.hoverReaction===d),p=document.createElement("div");p.classList.add("bubble-hover-reaction-sticker"),d.append(p),r.append(d);let m=this.chat.getMessage(Bn(l));if(m?._!=="message"){this.unhoverPrevious();return}m=await this.managers.appMessagesManager.getGroupsFirstMessage(m),Promise.all([this.managers.appReactionsManager.getAvailableReactionsByMessage(m,!0),fe.getAvailableReactions(),Hs(400)]).then(async([{reactions:g},f])=>{const y=g[0];if(!y){d.remove();return}const w=(y._==="reactionEmoji"?f.find(b=>b.reaction===y.emoticon):void 0)?.select_animation??await this.managers.appEmojiManager.getCustomEmojiDocument(y.document_id);u()&&Rs({div:p,doc:w,width:18,height:18,needUpscale:!0,middleware:u,group:this.chat.animationGroup,withThumb:!1,needFadeIn:!1}).then(({render:b})=>b).then(b=>{const S=()=>{u()&&(d.dataset.loaded="1",this.setHoverVisible(d,!0))};Array.isArray(b)?S():b.addEventListener("firstFrame",S,{once:!0}),N(d,C=>{oe(C),this.chat.sendReaction({message:m,reaction:y}),this.unhoverPrevious()},{listenerSetter:this.listenerSetter})},Wt)})},this.unhoverPrevious=()=>{const{hoverBubble:n,hoverReaction:a}=this;n&&(this.setHoverVisible(a,!1),this.hoverBubble=this.hoverReaction=void 0)},this.onBubblesClick=async n=>{let a=n.target,r=null,l;try{r=U(a,"bubble"),r&&(l=Bn(r))}catch{}if(!r&&!this.chat.selection.isSelecting){const C=U(a,"user-avatar");if(!C)return;const P=C.dataset.peerId.toPeerId();P!==Tt?this.chat.appImManager.setInnerPeer({peerId:P}):zs(ke.format("HidAccount",!0));return}if(!r)return;if(r.classList.contains("is-date")&&U(a,"bubble-content")){if(r.classList.contains("is-fake")&&(r=r.previousElementSibling),r.classList.contains("is-sticky")&&!this.chatInner.classList.contains("is-scrolling"))return;for(const C in this.dateMessages)if(this.dateMessages[C].div===r){ee.createPopup(ip,new Date(+C),this.onDatePick).show();break}return}const c=U(a,"time-effect");if(c){n_({timeEffect:c,bubble:r,e:n,scrollable:this.scrollable});return}if(!Je&&U(a,"time")){this.chat.selection.toggleByElement(r);return}if(this.chat.selection.isSelecting&&n.isTrusted){if(r.classList.contains("service")&&l===void 0)return;if(oe(n),Je&&this.chat.selection.selectedText){this.chat.selection.selectedText=void 0;return}this.chat.selection.toggleByElement(U(a,"grouped-item")||r);return}const d=U(a,"contact");if(d){const C=d.dataset.peerId.toPeerId();if(C)this.chat.appImManager.setInnerPeer({peerId:C});else{const P=d.querySelector(".contact-number");Fs(P.innerText.replace(/\s/g,"")),Ee({langPackKey:"PhoneCopied"}),oe(n)}return}const h=U(a,"bubble-call");if(h){this.chat.appImManager.callUser(this.peerId.toUserId(),h.dataset.type);return}if(U(a,"is-buy")){oe(n);const C=this.chat.getMessage(l);if(!C)return;const P=C.media,L=P?._==="messageMediaPaidMedia"?P:void 0,E=await gr.create({message:C,inputInvoice:await this.managers.appPaymentsManager.getInputInvoiceByPeerId(C.peerId,C.mid),paidMedia:L});L&&E.addEventListener("finish",async _=>{_==="paid"&&ap({icon:"cash_circle",title:M("StarsMediaPurchaseCompleted"),textElement:M("StarsMediaPurchaseCompletedInfo",[L.stars_amount,await Oe({peerId:C.fwdFromId||C.peerId})]),appendTo:this.container,from:"top",duration:5e3})});return}const p=U(a,"media-spoiler-container");if(p){MS({event:n,mediaSpoiler:p});return}const m=Bi(a,"REACTION-ELEMENT");if(m){if(oe(n),m.classList.contains("is-inactive"))return;const C=m.parentElement,P=C.getReactionCount(m),{reaction:L}=P;if(C.getType()===vn.Tag){if(!I.premium){Vt.show({feature:"saved_tags"});return}const E=this.chat.searchSignal();if(en(E?.reaction,L)){this.chat.contextMenu.onContextMenu(n);return}this.chat.initSearch({reaction:L})}else{const E=C.getContext();this.chat.sendReaction({message:E,reaction:L})}return}const g=Ch(a,"data-sticker-emoji");if(g&&g.parentElement.querySelectorAll("[data-sticker-emoji]").length===1&&r.classList.contains("emoji-big")){this.chat.appImManager.onEmojiStickerClick({event:n,container:g,managers:this.managers,middleware:this.getMiddleware(),peerId:this.peerId}).then(C=>{C||this.openEmojiPackByTarget(g)});return}else if(g){this.openEmojiPackByTarget(g);return}const f=U(a,"quote-like-collapsable");if(f){const C=f.classList.contains("is-truncated"),P=f.classList.contains("is-expanded");if((C||P)&&window.getSelection().isCollapsed){oe(n);const E=st.isAvailable("animations");E&&(f.ignoreQuoteResize=1/0);const _=this.createScrollSaver(!1);_.save();let k;const x=E?Promise.race([Hs(1e3).then(()=>{f.removeEventListener("transitionend",k)}),new Promise(A=>{k=T=>{T.target===f&&(A(),delete f.ignoreQuoteResize)},f.addEventListener("transitionend",k,{once:!0})})]):Promise.resolve();this.animateSomethingWithScroll(x,_),f.classList.toggle("is-expanded"),f.classList.toggle("is-truncated",P);return}}if(U(a,"replies")){if(this.peerId===cr){const C=this.chat.getMessage(l),P=at(C.reply_to.reply_to_peer_id),L=C.reply_to.reply_to_top_id,E=C.fwd_from.saved_from_msg_id;this.chat.appImManager.openThread({peerId:P,lastMsgId:E,threadId:L})}else{const C=this.chat.getMessage(l),P=await this.managers.appMessagesManager.getMessageWithReplies(C),L=P.replies;L&&this.managers.appMessagesManager.getDiscussionMessage(this.peerId,P.mid).then(E=>{this.chat.appImManager.setInnerPeer({peerId:L.channel_id.toPeerId(!0),type:te.Discussion,threadId:E.mid})})}return}const v=U(a,"is-via");if(v){const C=v.querySelector(".peer-title");if(a===C||Ns(a,C)){if(this.chat.input.canSendPlain()){const P=C.innerText+" ";this.managers.appDraftsManager.setDraft(this.peerId,this.chat.threadId,P)}oe(n);return}}const w=U(a,"peer-title")||Uc(a)||U(a,"selector-user")||Ch(a,"data-saved-from");if(w&&w!==r){a=w||a;const C=a.dataset.peerId||a.getAttribute("peer")||a.dataset.key,P=a.dataset.savedFrom;if(typeof C=="string"||P)if(P){const{peerId:L,mid:E}=Is(P);if(a.classList.contains("is-receipt-link")){const _=await this.managers.appMessagesManager.getMessageByPeer(L.toPeerId(),+E);if(_){const k=await this.managers.appPaymentsManager.getInputInvoiceByPeerId(_.peerId,_.mid);gr.create({message:_,inputInvoice:k,isReceipt:!0})}}else this.chat.appImManager.setInnerPeer({peerId:L.toPeerId(),lastMsgId:+E,stack:this.chat.appImManager.getStackFromElement(a)})}else{const L=C.toPeerId();L!==Tt?(this.chat.appImManager.setInnerPeer({peerId:L}),this.chat.appImManager.clickIfSponsoredMessage(r.message)):zs(ke.format("HidAccount",!0))}return}if(r.classList.contains("sticker")&&a.parentElement.classList.contains("attachment")){const P=this.chat.getMessage(l).media?.document;P?.stickerSetInput&&ee.createPopup(Cn,P.stickerSetInput,void 0,this.chat.input).show();return}const b=U(a,"media-video-mini");if(this.checkTargetForMediaViewer(a,n)){KS(n);return}const S=U(a,"webpage");if(S){if(U(a,"webpage-name-tip"))return;if(U(a,"webpage-preview-resizer")){n.preventDefault();return}const C=S.dataset.callback;C&&window[C](Bi(a,"A"),n);const P=S.callback;P?.();return}if(["IMG","DIV","SPAN"].indexOf(a.tagName)===-1&&(a=Bi(a,"DIV")),["DIV","SPAN"].indexOf(a.tagName)!==-1){if(a.classList.contains("goto-original")){const P=r.dataset.savedFrom,{peerId:L,mid:E}=Is(P);this.chat.appImManager.setInnerPeer({peerId:L.toPeerId(),lastMsgId:+E});return}else if(a.classList.contains("forward")){const P=this.chat.getMessage(l);ee.createPopup(va,{[this.peerId]:await this.managers.appMessagesManager.getMidsByMessage(P)});return}let C=!1;try{C=!!U(n.target,"reply")}catch{}if(C&&r.classList.contains("is-reply")){const P=this.chat.getMessage(l),L=P.reply_to;if(L._==="messageReplyStoryHeader"){const k=r.querySelector(".reply-media"),x=at(L.peer);mr({target:()=>k,peerId:x,id:L.story_id});return}let E=L.reply_to_msg_id;if(!E){Ee({langPackKey:L.pFlags.quote?"QuotePrivate":"ReplyPrivate"});return}let _=L.reply_to_peer_id?at(L.reply_to_peer_id):P.peerId;if(this.chat.type===te.Discussion&&!this.chat.isForum){const k=await this.managers.appMessagesManager.getHistory({peerId:_,threadId:this.chat.threadId,limit:1,offsetId:1,addOffset:-1}),x=this.chat.getMessageByPeer(_,k.history[0]);x.fwd_from?.channel_post===E&&(E=x.mid,_=x.peerId)}this.followStack.push(l),this.chat.appImManager.setInnerPeer({peerId:_,lastMsgId:E,type:this.chat.type,threadId:this.chat.threadId})}}},this.onScroll=(n,a,r)=>{if(this.isHeavyAnimationInProgress){if(this.sliceViewportDebounced?.clearTimeout(),this.scrolledDown&&!n)return}else this.chat.topbar.pinnedMessage?.setCorrectIndexThrottled(this.scrollable.lastScrollDirection),this.sliceViewportDebounced?.(),this.setStickyDateManually();if(a&&a.distanceToEnd<pv&&this.scrolledDown)return;const l=this.observer?.getIntersecting();if(l){const d=Array.from(l).filter(g=>g instanceof HTMLVideoElement&&g.mini),h=lt.height/2;let p=d.map(g=>{const f=g.getBoundingClientRect(),y=Math.abs(f.top+f.height/2-h);return{video:g,distance:y}}).sort((g,f)=>g.distance-f.distance)[0];p&&p.distance>150&&(p=void 0);const m=p?.video;if(this.lastPlayingVideo!==m){const g=gt.getAnimations(this.lastPlayingVideo)[0];if(g&&(gt.toggleItemLock(g,!0),this.lastPlayingVideo.pause()),this.lastPlayingVideo=m,m){const f=gt.getAnimations(m)[0];gt.toggleItemLock(f,!1),wi(m)}}}const c=r?0:a?.distanceToEnd??this.scrollable.getDistanceToEnd();(this.scrollable.lastScrollDirection!==0&&c>0||a||r)&&(this.isScrollingTimeout?clearTimeout(this.isScrollingTimeout):this.chatInner.classList.contains("is-scrolling")||this.chatInner.classList.add("is-scrolling"),this.isScrollingTimeout=window.setTimeout(()=>{this.chatInner.classList.remove("is-scrolling"),this.isScrollingTimeout=0},1350+(a?.duration??0))),c<pv&&(r||this.scrollable.loadedAll.bottom||this.chat.setPeerPromise||!this.peerId)?(this.container.classList.add("scrolled-down"),this.scrolledDown=!0):this.container.classList.contains("scrolled-down")&&(this.container.classList.remove("scrolled-down"),this.scrolledDown=!1)},this.processBatch=async(...n)=>{let[a,r,l]=n;const c=T=>T.filter(B=>B&&this.getBubble($t(B.message))===B.bubble&&!this.changedMids.has(B.message.mid));a=c(a),l("messages rendered");const{firstGroup:d,lastGroup:h}=this.bubbleGroups,u=d?.firstMid,p=h?.lastMid,{groups:m,avatarPromises:g}=this.groupBubbles(a.filter(T=>T.updatePosition)),{firstGroup:f,lastGroup:y}=this.bubbleGroups,v=f?.firstMid;let w=y?.lastMid;const b=a.find(({message:T})=>T.pFlags.sponsored);b&&(w=b.message.mid);const S=u!==v,C=!!h&&p!==w,L=a?.[0]?.reverse,_=a.every(({reverse:T})=>T===L)?L:S&&!C;l("changed ends",S,C);const k=a.reduce((T,B)=>{const R=performance.now(),O=B.promises.slice(),X=O.map(async F=>(await F,performance.now()-R));return Promise.all(X).then(F=>{l.groupCollapsed("media message time",performance.now()-R,B,F),F.forEach((H,G)=>{l("media message time",H,G,O[G])}),l.groupEnd()}),T.push(...B.promises),T},[]);k.push(...g),k.push(As()),l("media promises to call",k,a,this.isHeavyAnimationInProgress),await r(Promise.all([...k,this.setUnreadDelimiter()]).catch(Wt)),await r(ym()),l("media promises end"),a=c(a);const{restoreScroll:x,scrollSaver:A}=this.prepareToSaveScroll(_,u===v,p===w);a.some(T=>T.canAnimateLadder)&&this.messagesQueueOnRenderAdditional?.(),this.ejectBubbles();for(const[T,B]of this.bubblesToReplace){if(A&&A.replaceSaved(B,T),!a.find(O=>O.bubble===T))continue;const R=this.bubbleGroups.getItemByBubble(T);R?(R.mounted=!1,m.includes(R.group)||m.push(R.group)):this.log.error("NO ITEM BY BUBBLE",T),this.bubblesToReplace.delete(T)}this.chat.selection.isSelecting&&a.forEach(({bubble:T})=>{this.chat.selection.toggleElementCheckbox(T,!0)}),a.forEach(({message:T,bubble:B,updatePosition:R})=>{if(T.pFlags.local&&R){this.chatInner[T.pFlags.sponsored?"append":"prepend"](B);return}}),this.bubbleGroups.mountUnmountGroups(m),this.updatePlaceholderPosition?.(),x?.(),r(Hs(this.chat.setPeerPromise?1e3:0)).then(()=>r(As())).then(()=>{this.lazyLoadQueue.setAllSeen()}).catch(Wt)},this.modifyBubble=async n=>{const a=!this.batchingModifying;(this.batchingModifying??(this.batchingModifying=[])).push(n),a&&Hs(0).then(async()=>{await As();const r=this.batchingModifying,l=this.createScrollSaver(!1);l.save(),r.forEach(c=>c()),l.restore(),this.batchingModifying=void 0})},this.onDatePick=n=>{const a=this.peerId;this.managers.appMessagesManager.requestHistory({...this.chat.requestHistoryOptionsPart,offsetId:0,limit:2,addOffset:-1,offsetDate:n}).then(r=>{if(r?.messages?.length){if(this.peerId!==a)return}else{this.log.error("no history!");return}this.chat.setMessageId({lastMsgId:r.messages[0].mid})})},this.log=this.chat.log,this.listenerSetter=new Ut,this.constructBubbles(),this.batchProcessor=new _w({log:this.log,process:this.processBatch,possibleError:Xp}),this.preloader=new tn({cancelable:!1}),this.lazyLoadQueue=new Ga(void 0,!0),this.lazyLoadQueue.queueId=++hv,this.changedMids=new Map,this.listenerSetter.add(I)("history_update",async({storageKey:n,sequential:a,message:r})=>{if(this.chat.messagesStorageKey!==n||this.chat.type===te.Scheduled)return;const{mid:l}=r,c=$t(r),d=this.getBubble(c);if(!d||(this.renderNewPromises.size&&await Promise.all(Array.from(this.renderNewPromises)),this.messagesQueuePromise&&await this.messagesQueuePromise,this.getBubble(c)!==d))return;const h=this.bubbleGroups.getItemByBubble(d);if(h){if(h.mid===l)return}else return;if(a){const p=h.group,m=this.bubbleGroups.createItem(d,r,h.reverse),g=this.bubbleGroups.itemsArr.slice();us(g,h);const f=this.bubbleGroups.findGroupSiblingByItem(m,g);if(p===f?.group||p===this.bubbleGroups.lastGroup&&p.items.length===1&&m.dateTimestamp===h.dateTimestamp||this.peerId===I.myId&&a&&m.dateTimestamp===h.dateTimestamp){this.bubbleGroups.changeBubbleMessage(d,r);return}}this.bubbleGroups.removeAndUnmountBubble(d);const{groups:u}=this.groupBubbles([{bubble:d,message:r,reverse:h.reverse}]);this.bubbleGroups.mountUnmountGroups(u),this.scrollingToBubble&&this.scrollToEnd()}),this.listenerSetter.add(I)("dialog_flush",({peerId:n})=>{this.peerId===n&&this.deleteMessagesByIds(this.getRenderedHistory("asc"))}),this.listenerSetter.add(I)("message_sent",n=>{const{storageKey:a,tempId:r,tempMessage:l,mid:c,message:d}=n;if(this.chat.messagesStorageKey!==a)return;this.changedMids.set(r,c);const h=$t(l),u=$t(d);let p=this.getBubble(h);if(p){const v=p;delete this.bubbles[h],this.bubbles[u]=v,v.dataset.mid=""+c,bs(()=>{const w=+v.dataset.mid;if(this.getBubble(u)!==v||!v.classList.contains("is-outgoing"))return;v.classList.remove("is-outgoing");let b;v.classList.contains("is-out")&&(b=this.peerId===I.myId&&this.chat.type!==te.Scheduled||!this.unreadOut.has(w)?"read":"sent"),this.setBubbleSendingStatus(v,b)})}if(this.unreadOut.has(r)&&(this.unreadOut.delete(r),this.unreadOut.add(c)),this.chat.type===te.Scheduled){const v=Date.now()/1e3|0,w=l.date-10;v>=w&&this.deleteMessagesByIds([u])}let m,g;const f=d.grouped_id;if(f){m=fe.getMessagesByGroupedId(f);const v=m.map(({mid:b})=>b),w=v[v.length-1];if(w!==c)return;p=this.getBubble(d.peerId,Jp(v)),g=Array.from(p.querySelectorAll(".grouped-item")).map(b=>+b.dataset.mid),p.maxBubbleMid=w}else m=[d],g=[r],p&&(p.maxBubbleMid=c);if(!p)return;const y=Array.from(p.querySelectorAll("reactions-element"));if(y.length){const v=fe.getGroupsFirstMessage(d);y.forEach(w=>{w.changeContext(v)})}m.forEach((v,w)=>{if(!v)return;const b=g[w],S=v.mid,C=p.querySelector(`.document-container[data-mid="${S}"]`)||p;if(v._!=="message")return;if(v.replies){const k=p.querySelector("replies-element");k&&(k.message=v,k.init())}const P=v.media??{},L=P.document,E=P.poll,_=P.webpage;if(L){const k=C.querySelector(`.document-container[data-mid="${b}"]`),x=k?.querySelector(".document");x&&!l.media?.document?.thumbs?.length&&L.thumbs?.length&&As().then(async()=>{const T=x.querySelector(".time"),B=await Yc({message:v,fontSize:I.settings.messagesTextSize});x.replaceWith(B),T&&(B.querySelector(".document")||B).append(T)}),k&&(k.dataset.mid=""+S);const A=C.querySelector(`audio-element[data-mid="${b}"], .document[data-doc-id="${b}"], .media-round[data-mid="${b}"]`);A&&(A instanceof pf||A.classList.contains("media-round")?(A.dataset.mid=""+v.mid,delete A.dataset.isOutgoing,A.message=v,A.onLoad(!0)):(A.dataset.docId=""+L.id,A.doc=L))}else if(E){const k=C.querySelector("poll-element");k&&(k.message=v,k.setAttribute("poll-id",""+E.id),k.setAttribute("message-id",""+S))}else _&&!C.querySelector(".web")&&As().then(()=>{this.safeRenderMessage({message:v,reverse:!0,bubble:C}),this.scrollToBubbleIfLast(C)});if(f){const k=C.querySelector(`.grouped-item[data-mid="${b}"]`)||(C.classList.contains("document-container")?C:void 0);k&&(k.dataset.mid=""+S)}})}),this.listenerSetter.add(I)("message_edit",async({storageKey:n,message:a})=>{if(n!==this.chat.messagesStorageKey)return;const r=$t(a),l=this.getBubble(r);if(!l||(await As(),this.getBubble(r)!==l))return;const c=this.updateLocationOnEdit.get(l);if(c){c(a);return}l.querySelector(".geo-container")||this.safeRenderMessage({message:a,reverse:!0,bubble:l})}),this.listenerSetter.add(I)("message_error",async({storageKey:n,tempId:a,peerId:r})=>{if(n!==this.chat.messagesStorageKey)return;const l=$t(r,a),c=this.getBubble(l);c&&(await As(),this.getBubble(l)===c&&(c.classList.remove("is-outgoing"),this.setBubbleSendingStatus(c,"error")))}),this.listenerSetter.add(I)("replies_short_update",n=>{if(this.peerId!==n.peerId)return;const a=this.getBubble($t(n));a&&this.setBubbleRepliesCount(a,n.replies.replies)}),this.listenerSetter.add(I)("message_transcribed",({peerId:n,mid:a,text:r,pending:l})=>{if(n!==this.peerId)return;const c=this.getBubble($t(n,a));if(!c)return;const d=c.querySelector("audio-element");if(!d)return;const h=c.querySelector(".document-wrapper, .quote-text.has-document"),u=d.querySelector(".audio-to-text-button span"),p=d.querySelector(".loader");if(h&&u){let m=h.querySelector(".audio-transcribed-text");if(m)l||m.querySelector(".audio-transcribing-dots")?.remove();else if(m=document.createElement("div"),m.classList.add("audio-transcribed-text"),m.append(document.createTextNode("")),h.classList.contains("document-wrapper")?d.after(m):h.append(m),l){const g=document.createElement("span");g.classList.add("audio-transcribing-dots"),m.append(g)}!r&&!l?(m.replaceChildren(M("Chat.Voice.Transribe.Error")),m.classList.add("is-error")):r&&(m.firstChild.textContent=r),u.classList.remove(_a("transcribe")),u.classList.add(_a("up")),!l&&p&&(p.classList.remove("active"),setTimeout(()=>{p.remove()},300)),d.transcriptionState=2}}),this.listenerSetter.add(I)("grouped_edit",({peerId:n,messages:a,deletedMids:r})=>{if(n!==this.peerId)return;const l=a.map(({mid:g})=>g),c=l.concat(Array.from(r)),d=Jp(c),h=$t(n,d),u=this.getBubble(h);if(!u)return;delete this.bubbles[h];const p=Jp(l),m=a.find(g=>g.mid===p);this.safeRenderMessage({message:m,reverse:!0,bubble:u})}),this.listenerSetter.add(I)("messages_reactions",async n=>{if(this.chat.type===te.Scheduled)return;let a;const r=n.map(async({message:c,changedResults:d})=>{if(this.peerId!==c.peerId&&!Zp)return;const h=await this.getMountedBubble(c);if(h)return{bubble:U(h.bubble,"bubble"),message:c,changedResults:d}}),l=Pt();(await Promise.all(r)).filter(Boolean).forEach(({bubble:c,message:d,changedResults:h})=>{a||(a=this.createScrollSaver(!1),a.save()),c.dataset.ignoreReactions&&(delete c.dataset.ignoreReactions,h=[]);const u=Yp(d);u&&(h=[]);const p=d.peerId+"_"+d.mid,m=Ho.get(p);if(m){for(const g of m)if(g.update(d,h,l),!d.reactions||!d.reactions.results.length){const f=g.parentElement;g.remove(),g.querySelector(".time")&&(ga(c.timeAppenders,({element:v})=>v===g),c.timeAppenders[0].callback()),f.classList.contains("document-message")&&!f.childNodes.length&&f.remove()}}else{if(!d.reactions||!d.reactions.results.length)return;this.appendReactionsElementToBubble(c,d,d,h)}u&&this.setUnreadObserver("content",c,d.mid)}),a?.restore(),l.resolve()});const s=async n=>{const a=this.getMiddleware();if(await As(),!a())return;const r=[],l=n.peerId,c=n.mids||n.ids,d=this.needUpdate,h=n.mids?"replyMid":"replyStoryId",u=c.map(m=>{const g=[];bi(d,(y,v)=>{y[h]===m&&(y.replyToPeerId===l||!l)&&(d.splice(v,1)[0],g.push(y))});const f=g.map(async({peerId:y,mid:v,replyMid:w,replyToPeerId:b})=>{const S=$t(y,v),C=this.getBubble(S);if(!C)return;const[P,L]=await Promise.all([this.chat.getMessage(S),w&&this.managers.appMessagesManager.getMessageByPeer(b,w)]);r.push(async()=>{const E=Uo.setReply({chat:this.chat,bubble:C,message:P,middleware:C.middlewareHelper.get(),lazyLoadQueue:this.lazyLoadQueue,needUpdate:this.needUpdate,isStandaloneMedia:C.classList.contains("just-media"),isOut:C.classList.contains("is-out")});if(!L)return E;await E;let _;const k=C.querySelectorAll(".timestamp");(_=Sc(L))&&k.forEach(x=>{+x.dataset.timestamp<_?x.classList.remove("is-disabled"):x.removeAttribute("href")})})});return Promise.all(f)});if(await Promise.all(u),!a()||!r.length)return;const p=this.createScrollSaver(!0);p.save(),await Promise.all(r.map(m=>m())),p.restore()};this.listenerSetter.add(I)("messages_downloaded",s),this.listenerSetter.add(I)("stories_downloaded",s),Al({listenTo:this.scrollable.container,listenerSetter:this.listenerSetter,findTarget:n=>{const a=n.target;return a.closest(".attachment.media-sticker-wrapper, .attachment.media-gif-wrapper")||U(a,"attachment")&&a.closest(".custom-emoji")}}),N(this.scrollable.container,this.onBubblesClick,{listenerSetter:this.listenerSetter}),this.listenerSetter.add(this.scrollable.container)("mousedown",n=>{if(n.button!==0)return;const a=U(n.target,"code-header")&&U(n.target,"code"),r=a?.querySelector(".code-code")||U(n.target,"monospace-text");if(r){const l=!!U(n.target,"code-header-toggle-wrap");oe(n),l||f_(r);const d=N(window,h=>{if(oe(h),l){const u=a.classList.toggle("is-scrollable");r.classList.toggle("no-scrollbar",u);return}Ee({langPackKey:"CodeCopied",onClose:()=>{d()}})},{listenerSetter:this.listenerSetter,once:!0,capture:!0,ignoreMove:!0});return}}),this.stickyIntersector=new Xw(this.scrollable.container,(n,a)=>{for(const r in this.dateMessages){const l=this.dateMessages[r];if(l.container===a){const c=l.div;c.classList.toggle("is-sticky",n),n&&(this.previousStickyDate=c);break}}this.previousStickyDate}),uT||(this.sliceViewportDebounced=ii(this.sliceViewport.bind(this),3e3,!1,!0));let i;Pg(()=>{this.isHeavyAnimationInProgress=!0,this.lazyLoadQueue.lock(),i=this.getMiddleware()},()=>{this.isHeavyAnimationInProgress=!1,i?.()&&this.lazyLoadQueue.unlockAndRefresh(),i=null},this.listenerSetter)}constructBubbles(){const e=this.container=document.createElement("div");e.classList.add("bubbles","scrolled-down"),(this.chatInner=document.createElement("div")).classList.add("bubbles-inner");const s=document.createElement("div");s.classList.add("bubbles-remover-container");const i=this.remover=document.createElement("div");i.classList.add("bubbles-remover","bubbles-inner"),s.append(i),this.setScroll(),e.append(s,this.scrollable.container)}attachContainerListeners(){const e=this.container;if(this.chat.contextMenu.attachTo(e),this.chat.selection.attachListeners(e,new Ut),$i&&this.listenerSetter.add(e)("dblclick",t=>{const s=U(t.target,"grouped-item")||U(t.target,"bubble");if(s){const i=Bn(s);this.log("debug message:",this.chat.getMessage(i)),this.highlightBubble(s)}}),!Oi&&!lT)this.listenerSetter.add(e)("dblclick",async t=>{if(this.chat.type===te.Pinned||this.chat.selection.isSelecting||!this.chat.input.canSendPlain()||U(t.target,"attachment")||U(t.target,"audio")||U(t.target,"document")||U(t.target,"contact")||U(t.target,"time")||U(t.target,"code-header-button"))return;const s=t.target;let i=s.classList.contains("bubble")?s:s.classList.contains("document-selection")?s.parentElement:null;const n=VS();if(!i&&(!n.trim()||/^\s/.test(n))&&(i=U(s,"bubble")),i&&!i.classList.contains("bubble-first")){const a=this.chat.getMessage(Bn(i));if(a.pFlags.is_outgoing||a.peerId!==this.peerId)return;this.chat.input.initMessageReply({replyToMsgId:a.mid})}});else if(Je){const t="is-gesturing-reply";let n=!1,a,r,l;this.replySwipeHandler=SS({element:e,verifyTouchTarget:async c=>{if(this.chat.type===te.Pinned||this.chat.selection.isSelecting||!await this.chat.canSend()||(a=U(c.target,"bubble"),!a||a.classList.contains("service")||a.classList.contains("is-sending")))return!1;if(a){try{const d=a.parentElement.querySelector(".bubbles-group-avatar");d&&go(d,a)&&(l=d)}catch{}[a,l].filter(Boolean).forEach(d=>{bt({element:d,className:t,forwards:!0,duration:250}),d.offsetLeft}),r?(r.classList.remove("is-visible"),r.style.opacity=""):r=Le("reply_filled","bubble-gesture-reply-icon"),a.append(r)}return!!a},onSwipe:c=>{n=c>=48,n&&!r.classList.contains("is-visible")&&r.classList.add("is-visible"),r.style.opacity=""+Math.min(1,c/48);const h=`translateX(${-Math.max(0,Math.min(64,c))}px)`;a.style.transform=h,l&&(l.style.transform=h),Sw()},onReset:()=>{const c=a,d=l;a=l=void 0;const h=()=>{r.parentElement===c&&(r.classList.remove("is-visible"),r.remove())};[c,d].filter(Boolean).forEach((u,p)=>{bt({element:u,className:t,forwards:!1,duration:250,onTransitionEnd:p===0?h:void 0})}),bs(()=>{if(c.style.transform="",d&&(d.style.transform=""),n){const{mid:u}=c.dataset;this.chat.input.initMessageReply({replyToMsgId:+u}),n=!1}})},listenerOptions:{capture:!0}})}}constructPeerHelpers(){this.listenerSetter.add(I)("history_append",async({storageKey:s,message:i})=>{if(!(s!==this.chat.messagesStorageKey||this.chat.type===te.Scheduled)&&(st.isAvailable("chat_background")&&(this.updateGradient=!0),!(this.chat.threadId&&ha(i,this.chat.isForum)!==this.chat.threadId))){if(!this.chat.threadId&&this.chat.appImManager.chats.some(n=>this.chat!==n&&n.peerId===this.peerId&&n.threadId)){this.renderNewMessage(i);return}this.scrollable.loadedAll.bottom?this.renderNewMessage(i,!0):this.chat.setMessageId()}}),this.listenerSetter.add(I)("history_multiappend",s=>{this.peerId!==s.peerId||this.chat.type===te.Scheduled||this.renderNewMessage(s)}),this.listenerSetter.add(I)("history_delete",({peerId:s,msgs:i})=>{s!==this.peerId&&!Zp||this.chat.type===te.Scheduled||this.deleteMessagesByIds([...i.keys()].map(n=>$t(s,n)))}),this.listenerSetter.add(I)("history_delete_key",({historyKey:s,mid:i})=>{this.chat.historyStorageKey===s&&this.deleteMessagesByIds([$t(this.peerId,i)])}),this.listenerSetter.add(I)("dialog_unread",({peerId:s})=>{s===this.peerId&&(this.chat.input.setUnreadCount(),As().then(()=>{this.updateUnreadByDialog()}))}),this.listenerSetter.add(I)("dialogs_multiupdate",s=>{!s.has(this.peerId)||this.chat.type===te.Scheduled||this.chat.type===te.Saved||this.chat.input.setUnreadCount()}),this.listenerSetter.add(I)("dialog_notify_settings",s=>{this.peerId!==s.peerId||this.chat.type===te.Scheduled||this.chat.type===te.Saved||this.chat.input.setUnreadCount()});const e=async()=>{(await Promise.all([this.finishPeerChange(),this.chat.input.finishPeerChange({peerId:this.peerId,middleware:this.getMiddleware()})])).forEach(i=>i())};this.listenerSetter.add(I)("user_full_update",async s=>{if(s.toPeerId(!1)!==this.peerId)return;const n=this.getMiddleware(),[a,r]=await Promise.all([this.managers.appProfileManager.isCachedUserBlocked(s),this.chat.isPremiumRequiredToContact()]);if(!n())return;const l=this.chat.isUserBlocked,c=this.chat.isPremiumRequired;let d=!1;(l===void 0?a:l!==a)&&(this.chat.isUserBlocked=a,d=!0),(c===void 0?r:c!==r)&&(this.chat.isPremiumRequired=r,d=!0,this.cleanupPlaceholders(),this.checkIfEmptyPlaceholderNeeded()),d&&e()}),this.listenerSetter.add(I)("chat_update",async s=>{const{peerId:i}=this;if(i!==s.toPeerId(!0))return;const n=this.getMiddleware(),a=fe.getChat(s),r=this.chatInner.classList.contains("has-rights"),l=this.chat.input.canSendPlain(),[c,d,h]=await Promise.all([this.chat.canSend("send_messages"),this.chat.canSend("send_plain"),this.chat.canSend("embed_links")]);n()&&((r!==c||l!==d)&&await e(),n()&&((h&&!this.chat.input.willSendWebPage||!h&&this.chat.input.willSendWebPage)&&(this.chat.input.lastUrl="",this.chat.input.onMessageInput()),!!a.pFlags.forum!==this.chat.isForum&&this.chat.type===te.Chat&&(this.chat.peerId=0,this.chat.appImManager.setPeer({peerId:i}))))}),this.listenerSetter.add(I)("history_reload",s=>{if(s!==this.peerId)return;const i=this.getRenderedHistory("desc",!0),n=i.map(r=>Is(r).mid),a=this.getMiddleware();this.managers.appMessagesManager.reloadMessages(s,n).then(r=>{if(!a())return;const l=[];r.forEach((c,d)=>{const h=i[d];if(c){const u=this.getBubble(s,c.mid);if(!u)return;this.safeRenderMessage({message:c,reverse:!0,bubble:u})}else l.push(h)}),this.deleteMessagesByIds(l),this.setLoaded("top",!1),this.setLoaded("bottom",!1),this.scrollable.checkForTriggers()})}),this.listenerSetter.add(I)("settings_updated",({key:s})=>{s==="settings.emoji.big"&&this.getRenderedHistory("desc").map(a=>{const r=this.getBubble(a);if(r.classList.contains("can-have-big-emoji")){const{peerId:l,mid:c}=Is(a);return{bubble:r,message:this.chat.getMessageByPeer(l,c),fullMid:a}}}).filter(Boolean).forEach(({bubble:a,message:r,fullMid:l})=>{this.getBubble(l)===a&&this.safeRenderMessage({message:r,reverse:!0,bubble:a})})}),this.listenerSetter.add(I)("messages_views",s=>{this.chat.type!==te.Scheduled&&bs(()=>{let i;for(const{peerId:n,views:a,mid:r}of s){if(this.peerId!==n&&!Zp)continue;const l=this.getBubble(n,r);if(!l)continue;const c=Array.from(l.querySelectorAll(".post-views"));if(!c.length)continue;const d=on(a,1);let h=!1;c.forEach(u=>{(h||u.textContent!==d)&&(i||(i=this.createScrollSaver(!0),i.save()),h=!0,u.textContent=d)})}i?.restore()})}),this.observer=new g_({root:this.scrollable.container}),this.sendViewCountersDebounced=ii(()=>{const s=[...this.viewsMids];this.viewsMids.clear();const i=new Map;s.forEach(n=>{const{peerId:a,mid:r}=Is(n);let l=i.get(a);l||i.set(a,l=[]),l.push(r)}),i.forEach((n,a)=>{this.managers.appMessagesManager.incrementMessageViews(a,n)})},1e3,!1,!0),this.listenerSetter.add(I)("peer_pinned_messages",({peerId:s,mids:i,pinned:n})=>{this.chat.type!==te.Pinned||s!==this.peerId||i&&(n||this.deleteMessagesByIds(i.map(a=>$t(s,a))))});const t=async()=>{this.chat.topbar.setTitle((await this.managers.appMessagesManager.getScheduledMessagesStorage(this.peerId)).size)};this.listenerSetter.add(I)("scheduled_new",s=>{this.chat.type!==te.Scheduled||s.peerId!==this.peerId||(this.renderNewMessage(s),t())}),this.listenerSetter.add(I)("scheduled_delete",({peerId:s,mids:i})=>{this.chat.type!==te.Scheduled||s!==this.peerId||(this.deleteMessagesByIds(i.map(n=>$t(s,n))),t())})}get peerId(){return this.chat.peerId}get messagesQueuePromise(){return this.batchProcessor.queuePromise}createScrollSaver(e=!0){return new Zu(this.scrollable,".bubble:not(.is-date)",e)}createResizeObserver(){if(!("ResizeObserver"in window)||this.resizeObserver)return;const e=this.scrollable.container;let t=0,s=!1,i=!1,n=0,a=0;const r=()=>{const h=e.offsetHeight,u=this.scrollable.isScrolledToEnd;h!==t&&(!i||!u)&&(n+=t-h),n&&this.scrollable.setScrollPositionSilently(this.scrollable.scrollPosition+Math.round(n)),t=h,a=0,n=0,s=!1,i=!1},l=h=>{a&&window.cancelAnimationFrame(a),a=window.requestAnimationFrame(()=>{a=window.requestAnimationFrame(r)})},c=h=>{if(i){l();return}const p=h[0].contentRect.height;if(!t){t=p;return}const m=t-p;let g=m+n;const f=g%1;if(g-=f,!s&&(s=!0,m<0&&this.scrollable.isScrolledToEnd)){n=-m,i=!0,l();return}if(g){const y=this.scrollable.scrollPosition+g;this.scrollable.setScrollPositionSilently(y)}l(),n=f,t=p};(this.resizeObserver=new ResizeObserver(c)).observe(e)}destroyResizeObserver(){const e=this.resizeObserver;e&&(e.disconnect(),this.resizeObserver=void 0)}setReactionsHoverListeners(){this.listenerSetter.add(Js)("toggle",this.unhoverPrevious),this.listenerSetter.add(Li)("change",this.unhoverPrevious),this.listenerSetter.add(this.chat.selection)("toggle",this.unhoverPrevious),this.listenerSetter.add(this.container)("mousemove",this.onBubblesMouseMove)}setHoverVisible(e,t){e.parentElement&&e.parentElement.classList.toggle("hover-reaction-visible",t),bt({element:e,className:"is-visible",forwards:t,duration:200,onTransitionEnd:t?void 0:()=>{e.remove(),e.middlewareHelper.destroy()},useRafs:t?2:0})}setStickyDateManually(){}getRenderedLength(){return this.getRenderedHistory().length}onUnreadedInViewport(e,t,s){let{unreadedSeen:i,unreadedObserverCallback:n,unreaded:a}=this;e==="content"&&(i=this.unreadedContentSeen,n=this.unreadedContentObserverCallback,a=this.unreadedContent),i.add(s),this.observer.unobserve(t,n),a.delete(t),this.readUnreaded(e)}readUnreaded(e){const t=e==="history"?"readPromise":"readContentPromise";if(this[t])return;const s=e==="history"?"unreadedSeen":"unreadedContentSeen",i=this.getMiddleware();this[t]=xa.getFocusPromise().then(async()=>{if(!i())return;const{peerId:n,threadId:a}=this.chat;let r;if(e==="history"){let c=Math.max(...Array.from(this[s]));if(this.scrollable.loadedAll.bottom){const d=this.getRenderedHistory("desc",!0),h=d?Is(d[0]).mid:-1;if(c>=h&&(c=Math.max(await this.chat.getHistoryMaxId()||0,c),!i()))return}this.unreaded.forEach((d,h)=>{d<=c&&this.onUnreadedInViewport("history",h,d)}),$i&&this.log("will readHistory by maxId:",c),r=()=>this.managers.appMessagesManager.readHistory(n,c,a)}else{const c=[];for(const d of this.unreadedContentSeen){const h=this.chat.getMessage(d);(ev(h)||Yp(h))&&c.push(d)}$i&&this.log("will readMessages",c),r=()=>this.managers.appMessagesManager.readMessages(n,c)}return this[s].clear(),r().catch(c=>{this.log.error("read err:",e,c),r()}).finally(()=>{i()&&(this[t]=void 0,this[s].size&&this.readUnreaded(e))})})}openEmojiPackByTarget(e){this.managers.appEmojiManager.getCustomEmojiDocument(e.dataset.docId).then(t=>{const s=t.attributes.find(n=>n._==="documentAttributeCustomEmoji");if(!s)return;const i=s.stickerset;ee.createPopup(Cn,i,!0,this.chat.input).show()})}checkTargetForMediaViewer(e,t,s){const i=U(e,"bubble"),n=U(e,"document-with-thumb");if(e.tagName==="IMG"&&!e.classList.contains("emoji")&&!e.classList.contains("document-thumb")||e.classList.contains("album-item")||e.classList.contains("album-item-media")||e.tagName==="VIDEO"&&!i.classList.contains("round")||n&&!n.querySelector(".preloader-container")||e.classList.contains("canvas-thumbnail")){const a=U(e,"album-item")||U(e,"document-container"),r=(a||i).querySelector(".preloader-container");if(r&&t){fs(r),oe(t);return}oe(t);const l=a?+(a.dataset.index??-1):-1,c=Bn(l!==-1?i:a||i),d=this.chat.getMessage(c);if(!d){this.log.warn("no message by messageId:",c);return}if(i.classList.contains("story")){const y=Ch(e,"data-story-peer-id"),v=y.dataset.storyPeerId.toPeerId(),w=+y.dataset.storyId;mr({target:()=>y.querySelector(".media-container-aspecter")||e,peerId:v,id:w});return}const h="single-media",u=i.classList.contains(h),p=n?y=>ho.isMediaCompatibleForDocumentViewer(y):y=>y._==="photo"||["video","gif"].includes(y.type),m=[],g=u?[c]:this.getRenderedHistory("asc").map(y=>{const v=this.getBubble(y);if(!u&&v.classList.contains(h))return;const w=this.chat.getMessage(y),b=Xs(w);return b&&p(b)&&y}).filter(Boolean);g.forEach(y=>{let v=this.skippedMids.has(y)?void 0:this.getBubble(y);if(v||(v=this.chatInner.querySelector(`.grouped-item:not(.album-item)[data-mid="${y}"]`),v&&(v=U(v,"bubble"))),!v)return;let w;if(n)w=".document-container";else{const C=v.classList.contains("with-media-tail");w=".album-item, .webpage-preview, ",C?w+=".bubble__media-container":w+=".attachment"}const b=Array.from(v.querySelectorAll(w)),S=new Set;if(n)b.forEach(C=>{m.push({element:C.querySelector(".document-ico"),mid:+C.dataset.mid,peerId:this.peerId,fullMid:Bn(C)})});else{const C=!!v.querySelector(".media-container-aspecter");b.forEach(P=>{if(P=P.querySelector("video, img")||P,C&&!U(P,"media-container-aspecter"))return;const L=U(P,"album-item"),E=L||P.parentElement;if(S.has(E))return;S.add(E);const _=l!==-1?y:Bn(L||P)||y;m.push({element:P,mid:Is(_).mid,peerId:this.peerId,fullMid:_,index:L&&+(L.dataset.index??-1)})})}}),bi(m,(y,v,w)=>{const b=w.findIndex(S=>S.element===y.element);b!==v&&w.splice(b,1)});const f=l===-1?m.findIndex(y=>y.fullMid===c):m.findIndex(y=>y.index===l);if($i&&this.log("open mediaViewer single with ids:",g,f,m),!m[f]){this.log("no target for media viewer!",e);return}return new ho().setSearchContext({threadId:this.chat.threadId,peerId:this.peerId,inputFilter:{_:n?"inputMessagesFilterDocument":"inputMessagesFilterPhotoVideo"},useSearch:this.chat.type!==te.Scheduled&&!u,isScheduled:this.chat.type===te.Scheduled}).openMedia({message:d,index:m[f].index,target:m[f].element,fromRight:0,reverse:!0,prevTargets:m.slice(0,f),nextTargets:m.slice(f+1),mediaTimestamp:s}),!0}}async onGoDownClick(){if(!this.followStack.length){this.chat.setMessageId();return}const e=this.getMiddleware(),t=this.followStack.slice(),s=await Promise.all(t.map(a=>this.chat.getMessage(a)));if(!e())return;t.forEach((a,r)=>{const l=s[r],c=this.getBubble(a);let d=!0;if(c){const h=c.getBoundingClientRect();d=lt.height/2>h.top}else l&&(d=!1);d&&this.followStack.splice(this.followStack.indexOf(a),1)}),this.followStack.sort((a,r)=>Is(r).mid-Is(a).mid);const i=this.followStack.pop(),{mid:n}=Is(i);this.chat.setMessageId({lastMsgId:n})}getBubbleByPoint(e){const t=this.getViewportSlice();return t.visible[e==="top"?0:t.visible.length-1]?.element}async getGroupedBubble(e,t){const s=await this.managers.appMessagesManager.getMidsByGroupedId(t);for(const i of s){const n=$t(e,i),a=this.getBubble(n);if(a&&!this.skippedMids.has(n))return{bubble:a,peerId:e,mid:i}}}getBubbleGroupedItems(e){return Array.from(e.querySelectorAll(".grouped-item"))}async getMountedBubble(e){let t,s,i;if(typeof e=="string"){const r=Is(e);s=r.peerId,i=r.mid,t=this.chat.getMessageByPeer(s,i)}else t=e,s=t.peerId,i=t.mid,e=$t(s,i);if(!t)return;const n=t.grouped_id;if(n){const r=await this.getGroupedBubble(s,n);if(r)return r.bubble=r.bubble.querySelector(`.document-container[data-mid="${i}"]`)||r.bubble,r}const a=this.getBubble(e);if(!(!a||this.skippedMids.has(e)))return{bubble:a,peerId:s,mid:i}}findNextMountedBubbleByMsgId(e,t){if(this.chat.type===te.Search){const a=this.getRenderedHistory("desc",!0),r=a.indexOf(e);if(r===-1)return;const l=a[r+(t?-1:1)];return this.getBubble(l)}const s=this.getRenderedHistory(t?"desc":"asc");let i;t?i=a=>Is(a).mid<Is(e).mid:i=a=>Is(e).mid<Is(a).mid;const n=s.find(a=>i(a)?!!this.getBubble(a)?.parentElement:!1);return this.getBubble(n)}getRenderedHistory(e="desc",t){let s=Ln(this.bubbleGroups.groups.map(i=>i.items.map(n=>$t(n.message))));return e==="asc"&&s.reverse(),t&&(s=s.filter(i=>{const{mid:n}=Is(i);return n>0&&mL(n,!1)===n})),s}loadMoreHistory(e,t=!1){if(!this.peerId||this.chat.setPeerPromise||this.isHeavyAnimationInProgress||e&&(this.getHistoryTopPromise||this.scrollable.loadedAll.top)||!e&&(this.getHistoryBottomPromise||this.scrollable.loadedAll.bottom))return;const s=this.getRenderedHistory("asc");s.length||s.push(Ds),e?($i&&this.log("Will load more (up) history by id:",s[0],"maxId:",s[s.length-1],t),this.getHistory1(s[0],!0,void 0,void 0,t)):($i&&this.log("Will load more (down) history by id:",s[s.length-1],t),this.getHistory1(s[s.length-1],!1,!0,void 0,t))}setScroll(){this.scrollable&&this.destroyScrollable(),this.scrollable=new vi(null,"IM",300),this.setLoaded("top",!1,!1),this.setLoaded("bottom",!1,!1),this.scrollable.container.append(this.chatInner),this.scrollable.onAdditionalScroll=this.onScroll,this.scrollable.onScrolledTop=()=>this.loadMoreHistory(!0),this.scrollable.onScrolledBottom=()=>this.loadMoreHistory(!1),Je}async updateUnreadByDialog(){const e=await this.chat.getHistoryStorage(),t=this.peerId===I.myId?e.readMaxId:e.readOutboxMaxId;for(const s of this.unreadOut)if(s>0&&s<=t){const i=$t(this.peerId,s),n=this.getBubble(i);if(!n||(this.unreadOut.delete(s),n.classList.contains("is-outgoing")||n.classList.contains("is-error")))continue;this.setBubbleSendingStatus(n,"read")}}destroyBubble(e,t,s=Bn(e)){let i,n,a,r;if(t&&e.isConnected){const c=[".bubbles-date-group",".bubbles-group",".bubble"];n=[e,...Dk(e,c[0])].map((d,h,u)=>{const p=u.length,m=c.slice(0,p-h),g=Array.from(u[p-1].parentElement.querySelectorAll(m.join(" "))),f=g[g.indexOf(d)-1];return{element:d,parentElement:d.parentElement,index:Ri(d,!1),rect:d.getBoundingClientRect(),previousElement:d.previousElementSibling,marginBottom:parseInt(window.getComputedStyle(d).marginBottom),previousSameKindElement:f}}),r=this.setTopPadding(),a=this.scrollable.scrollSize,i=document.createElement("div"),i.classList.add("bubble-delete-placeholder")}this.getBubble(s)===e&&delete this.bubbles[s],this.skippedMids.delete(s),this.firstUnreadBubble===e&&(this.firstUnreadBubble=null);const l=n&&this.createScrollSaver(!1);if(l?.save(),this.bubbleGroups.removeAndUnmountBubble(e),this.observer&&(this.observer.unobserve(e,this.unreadedObserverCallback),this.unreaded.delete(e),this.observer.unobserve(e,this.unreadedContentObserverCallback),this.unreadedContent.delete(e),this.observer.unobserve(e,this.viewsObserverCallback),this.viewsMids.delete(s),this.observer.unobserve(e,this.stickerEffectObserverCallback),this.observer.unobserve(e,this.messageEffectObserverCallback)),e.timeAppenders=e.timeSpan=void 0,n){let c;n.forEach(S=>{S.element.parentElement||(c=S)});const d=a-this.scrollable.scrollSize,h=c===n[0],u=e.classList.contains("is-group-last"),p=e.classList.contains("is-group-first");i.style.cssText=`width: 100%; height: ${d}px;`,c.element.style.cssText=`position: absolute; z-index: 0; left: 0; right: 0; top: ${c.rect.top-56}px; height: ${c.rect.height}px;`,this.remover.append(c.element),n.forEach(S=>{S.element.parentElement||Ps(S.element,S.parentElement,S.index,-1)}),c.previousElement&&!c.previousElement.parentElement&&n[0].previousSameKindElement?n[0].previousSameKindElement.after(i):Ps(i,c.parentElement,c.index,-1),l.restore(),l.save();const m={duration:300,fill:"forwards",easing:"cubic-bezier(.4, .0, .2, 1)"},g=h&&u&&!p&&c.parentElement.querySelector(".bubbles-group-avatar"),f=i.animate([{height:"0.01px",marginBottom:"0px"}],m),y=c.element.animate([{opacity:0}],m),v=g?g.animate([{transform:`translateY(-${c.marginBottom}px)`},{transform:`translateY(-${c.marginBottom}px)`}],m):void 0,w=[f,y,v].filter(Boolean).map(S=>S.finished),b=Promise.all(w).then(()=>{i.remove(),c.element.remove(),v?.cancel(),e.middlewareHelper.destroy(),As().then(()=>{r.unsetPadding?.()})});this.animateSomethingWithScroll(b,l)}else e.middlewareHelper.destroy()}animateSomethingWithScroll(e,t){t||(t=this.createScrollSaver(!0),t.save());let s=!1;e.then(()=>{s=!0}),Xr(e),t&&Ba(()=>s?!1:(t.restore(),!0),this.scrollable.container)}deleteMessagesByIds(e,t=!0,s){if(e=e.filter(a=>!!this.getBubble(a)),!e.length)return;const i=this.getRenderedHistory("desc"),n={};if(i.forEach((a,r)=>n[a]=r),e.slice().sort((a,r)=>(n[a]??0)-(n[r]??0)).forEach(a=>{const r=this.getBubble(a);this.destroyBubble(r,t&&st.isAvailable("animations"))}),this.scrollable.ignoreNextScrollEvent(),t&&this.chat.selection.isSelecting){let a;e.forEach(r=>{const{peerId:l,mid:c}=Is(r);a=this.chat.selection.deleteSelectedMids(l,[c],!0)}),a?.()}gt.checkAnimations(!1,this.chat.animationGroup),this.deleteEmptyDateGroups(),s||this.scrollable.onScroll()}pollExtendedMediaMessages(){const e=Array.from(this.extendedMediaMessages);return this.managers.appMessagesManager.getExtendedMedia(this.peerId,e)}setExtendedMediaMessagesPollInterval(){this.pollExtendedMediaMessagesPromise||!this.extendedMediaMessages.size||(this.pollExtendedMediaMessagesPromise=Hs(3e4).then(()=>this.pollExtendedMediaMessages()).then(()=>this.setExtendedMediaMessagesPollInterval()))}setTopPadding(e=this.getMiddleware()){let t=!1,s;if(!this.isTopPaddingSet&&this.chat.type!==te.Scheduled){const{clientHeight:i,scrollHeight:n}=this.scrollable.container;t=i===n,t&&(s=this.chatInner,s.style.paddingTop=i+"px",this.scrollable.setScrollPositionSilently(n),this.isTopPaddingSet=!0)}return{isPaddingNeeded:t,unsetPadding:t?()=>{e()&&(s.style.paddingTop="",this.isTopPaddingSet=!1)}:void 0}}renderNewMessage(e,t){const s=this._renderNewMessage(e,t);return this.renderNewPromises.add(s),s.catch(Wt).finally(()=>{this.renderNewPromises.delete(s)}),s}async _renderNewMessage(e,t){if(!this.scrollable.loadedAll.bottom){const c=this.chat.setPeerPromise;if(c){const d=this.getMiddleware();c.then(()=>{if(!d())return;const h=this.chat.getMessageByPeer(e.peerId,e.mid);this.renderNewMessage(h)})}return}if(this.chat.threadId&&ha(e,this.chat.isForum)!==this.chat.threadId)return;const{savedReaction:s}=this.chat;if(s?.length){const{reactions:c}=e;if(!(c?.results&&s.every(h=>c.results.some(u=>en(u.reaction,h)))))return}const i=$t(e);if(this.getBubble(i))return;t||(t=this.scrolledDown&&(!this.scrollingToBubble||this.scrollingToBubble===this.getLastBubble()||this.scrollingToBubble===this.chatInner));const n=this.getMiddleware(),{isPaddingNeeded:a,unsetPadding:r}=this.setTopPadding(n),l=this.performHistoryResult({history:[e]},!1);return t&&l.then(()=>{if(!n())return;let c;this.chat.type===te.Scheduled&&(c=this.getBubble(i));const d=c?this.scrollToBubbleEnd(c):this.scrollToEnd();a&&d.then(r)}),l}getLastBubble(){return this.bubbleGroups.lastGroup?.lastItem?.bubble}scrollToBubble(e,t,s,i){const n=U(e,"bubble");e.parentElement||this.log.error("element is not connected",n);let a;if(n&&t!=="end"){const d=this.bubbleGroups.getItemByBubble(n);d&&d.group.firstItem===d&&Ri(d.group.container)===(this.stickyIntersector?QS:1)&&(a=d.group.container.parentElement)}const r=4,l=this.chat.input.messageInput&&this.chat.input.messageInput.classList.contains("is-changing-height")||this.chat.container.classList.contains("is-toggling-helper"),c=this.scrollable.scrollIntoViewNew({element:e,position:t,margin:r,forceDirection:s,forceDuration:i,axis:"y",getNormalSize:l?({rect:d})=>{let h=lt.height;return h-=this.container.offsetTop,h-=$e.isMobile||lt.height<570?58:78,h}:void 0,fallbackToElementStartWhenCentering:a,startCallback:d=>{if(this.onScroll(!0,d),this.updateGradient){const{gradientRenderer:h}=this.chat;h?.toNextPosition(d.getProgress),this.updateGradient=void 0}}});return s===Rh.Static&&(this.scrollable.lastScrollPosition=this.scrollable.scrollPosition),c}scrollToEnd(){return this.scrollToBubbleEnd(this.chatInner)}async scrollToBubbleEnd(e){if(e){this.scrollingToBubble=e;const t=this.getMiddleware();if(await this.scrollToBubble(e,"end",void 0,void 0),!t())return;this.scrollingToBubble=void 0}}async scrollToBubbleIfLast(e){if(this.getLastBubble()===e)return this.scrollToEnd()}highlightBubble(e){const t="highlightTimeout";e.dataset[t]&&(clearTimeout(+e.dataset[t]),e.classList.remove("is-highlighted"),e.offsetWidth),e.classList.add("is-highlighted"),e.dataset[t]=""+setTimeout(()=>{e.classList.remove("is-highlighted"),delete e.dataset[t]},2e3)}createDateBubble(e,t=new Date(e*1e3)){let s;const i=new Date;i.setHours(0,0,0,0);const n=this.chat.type===te.Scheduled;i.getTime()===t.getTime()?s=M(n?"Chat.Date.ScheduledForToday":"Date.Today"):n&&e===xc?s=M("MessageScheduledUntilOnline"):(s=wb(t,i),n&&(s=M("Chat.Date.ScheduledFor",[s])));const a=document.createElement("div");a.className="bubble service is-date";const r=document.createElement("div");r.classList.add("bubble-content");const l=document.createElement("div");return l.classList.add("service-msg"),l.append(s),r.append(l),a.append(r),a}getDateForDateContainer(e){const t=new Date(e*1e3);return e!==xc&&t.setHours(0,0,0),{date:t,dateTimestamp:t.getTime()}}getDateContainerByTimestamp(e){const{date:t,dateTimestamp:s}=this.getDateForDateContainer(e);let i=this.dateMessages[s];if(i)return i;const n=this.createDateBubble(e,t),a=this.createDateBubble(e,t);a.classList.add("is-fake");const r=document.createElement("section");r.className="bubbles-date-group",r.append(n,a),i=this.dateMessages[s]={div:n,container:r,firstTimestamp:t.getTime(),groupsLength:0};const l=kb(this.dateMessages,"asc"),c=l.length;let d=0,h;for(;d<l.length;++d){const u=l[d];if(h=this.dateMessages[u].container,s<u)break}return d===c&&h&&(h=h.nextElementSibling),h?this.chatInner.insertBefore(r,h):this.chatInner.append(r),this.stickyIntersector?.observeStickyHeaderChanges(r),this.chatInner.parentElement&&this.container.classList.add("has-groups"),i}destroyScrollable(){this.scrollable.destroy()}destroy(){this.destroyScrollable(),this.listenerSetter.removeAll(),this.lazyLoadQueue.clear(),this.observer&&this.observer.disconnect(),this.stickyIntersector&&this.stickyIntersector.disconnect(),delete this.lazyLoadQueue,this.observer&&delete this.observer,this.stickyIntersector&&delete this.stickyIntersector}cleanup(e=!1){this.log("cleanup"),this.bubbles={},this.setLoaded("top",!1,!1),this.setLoaded("bottom",!1,!1),Mg(this.scrollable.container),tL(),this.skippedMids.clear(),this.dateMessages={},this.bubbleGroups?.cleanup(),this.bubbleGroups=new t_(this.chat),this.unreadOut.clear(),this.needUpdate=[],this.lazyLoadQueue.clear(),this.renderNewPromises.clear(),this.changedMids.clear(),e&&(this.scrollable.replaceChildren(),this.chatInner.replaceChildren(),this.cleanupPlaceholders()),this.firstUnreadBubble=null,this.attachedUnreadBubble=!1,this.batchProcessor.clear(),this.getHistoryTopPromise=this.getHistoryBottomPromise=void 0,this.fetchNewPromise=void 0,this.getSponsoredMessagePromise=void 0,this.updateGradient=void 0,this.stickyIntersector&&this.stickyIntersector.disconnect(),this.observer&&(this.observer.disconnect(),this.unreaded.clear(),this.unreadedContent.clear(),this.unreadedSeen.clear(),this.unreadedContentSeen.clear(),this.readPromise=void 0,this.readContentPromise=void 0,this.viewsMids.clear()),this.middlewareHelper.clean(),this.onAnimateLadder=void 0,this.resolveLadderAnimation=void 0,this.attachPlaceholderOnRender=void 0,this.emptyPlaceholderBubble=void 0,this.sponsoredMessage=void 0,this.previousStickyDate=void 0,this.scrollingToBubble=void 0,this.isTopPaddingSet=!1,this.renderingMessages.clear(),this.bubblesToEject.clear(),this.bubblesToReplace.clear(),this.isScrollingTimeout&&(clearTimeout(this.isScrollingTimeout),this.isScrollingTimeout=0),this.container.classList.remove("has-sticky-dates"),this.scrollable.cancelMeasure()}cleanupPlaceholders(e=this.emptyPlaceholderBubble){e&&this.destroyBubble(e)}tryToForceStartParam(e){const t=this.chat.input.startParam;t!==void 0&&this.chat.isStartButtonNeeded().then(s=>{!e()||s||this.chat.input.startParam!==t||this.chat.input.startBot()})}async setPeer(e){const{samePeer:t,sameSearch:s,peerId:i,stack:n}=e;let{lastMsgId:a,lastMsgPeerId:r,startParam:l}=e;const c=++this.setPeerTempId;let d,h;if(!i)return this.cleanup(!0),this.preloader.detach(),null;const u=performance.now(),p=this.log.bindPrefix("setPeer");p.warn("start");const m=()=>this.setPeerTempId===c,g=so(m,Xp);t||await g(this.chat.onChangePeer(e,g));const f=this.chat.type;f===te.Scheduled||this.chat.isRestricted?d=Ds:a?d=$t(r??i,a):d=Ds;const y=await g(this.chat.getHistoryStorage());f===te.Pinned?h=$t(i,await g(this.managers.appMessagesManager.getPinnedMessagesMaxId(i,this.chat.threadId))):y.searchHistory?h=y.searchHistory.first[0]??Ds:h=y.maxId?$t(i,y.maxId):Ds;const v=d!==Ds;n&&this.chat.appImManager.clickIfSponsoredMessage(n.message);let w,b=0,S,C;if(!v&&(t||(S=this.chat.appImManager.getChatSavedPosition(this.chat)),!S)){if(this.chat.type===te.Search)d=h;else if(h!==Ds){let se;if(e.savedReaction||([b,se]=await g(Promise.all([this.managers.appMessagesManager.getReadMaxIdIfUnread(i,this.chat.threadId),this.chat.getDialogOrTopic()]))),b&&!t&&(!se||!la(se)&&se.unread_count!==1)){const Y=y.history.findSliceOffset(b);Y&&Y.slice.isEnd(Ro.Bottom)&&(C=Y.slice[Y.offset-25]||Y.slice[0]||b),w=!v,d=$t(i,b)}else d=h}}const P=d===h||d===Ds&&!w,L=d!==h;if(P&&d!==Ds&&(this.chat.getMessage(d)||(this.log("fix going to bottom end without existing message",d),d=Ds)),l===void 0&&await g(this.chat.isStartButtonNeeded())&&(l=Tb),t&&s){n&&d!==Ds&&this.followStack.push($t(n.peerId,n.mid));let Y=(await g(this.getMountedBubble(d)))?.bubble;if(!Y&&this.skippedMids.has(d)&&(Y=this.findNextMountedBubbleByMsgId(d,!1)||this.findNextMountedBubbleByMsgId(d,!0)),Y)return v?(this.scrollToBubble(Y,"center"),this.highlightBubble(Y),this.chat.dispatchEvent("setPeer",a,!1)):h!==Ds&&!L&&(this.scrollToEnd(),this.chat.dispatchEvent("setPeer",a,!0)),l!==void 0&&(this.chat.input.setStartParam(l),this.tryToForceStartParam(m)),e.mediaTimestamp&&As().then(()=>{this.playMediaWithTimestampAndMid({lastMsgFullMid:d,middleware:m,mediaTimestamp:e.mediaTimestamp})}),null}else this.peerId&&(this.lazyLoadQueue.queueId=++hv,this.managers.apiFileManager.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)),this.followStack.length=0,this.passEntities={messageEntityBotCommand:await g(this.managers.appPeersManager.isAnyGroup(i))||this.chat.isBot};$i&&p("setPeer peerId:",i,y,d,h);const E=L||[te.Search,te.Scheduled].includes(f)||this.chat.isRestricted?void 0:C??Is(h).mid,_=E?$t(i,E):void 0;let k=Ds;if(t){const se=this.getBubbleByPoint("bottom");se&&(k=Bn(se)),k||(k=this.getRenderedHistory("desc",!0)[0]||Ds)}else this.isFirstLoad=!0,this.destroyResizeObserver();const x=this.chatInner,A=this.emptyPlaceholderBubble;this.cleanup();const T=this.chatInner=document.createElement("div");t?(T.className=x.className,T.classList.remove("disable-hover","is-scrolling")):T.classList.add("bubbles-inner"),this.lazyLoadQueue.lock();const B=t&&s,R=B||h!==Ds&&L||v,O=k!==Ds&&(d===Ds||await(async()=>{const se=await this.chat.getHistoryStorage(),Y=se.searchHistory||se.history;if(Y===se.searchHistory){const Q=Y.first.indexOf(d),he=Y.first.indexOf(k);return Q<he}else return Is(k).mid<Is(d).mid})()),X=!O&&B,F=!X&&O&&B;if(this.willScrollOnLoad=X||F,this.setPeerOptions={lastMsgFullMid:d,topMessageFullMid:h,savedPosition:S},!t){this.ranks=void 0,this.processRanks=void 0,this.canShowRanks=!1;let se=this.chat.isMegagroup,Y=this.peerId.toChatId();if(this.chat.type===te.Saved&&!this.chat.threadId.isUser()&&(se=fe.getChat(Y=this.chat.threadId.toChatId())?._==="channel"),se){this.canShowRanks=!0;const Q=this.processRanks=new Set,he=this.managers.acknowledged.appProfileManager.getParticipants({id:Y,filter:{_:"channelParticipantsAdmins"},limit:100}),le=await g(he),re=le.result.then(ge=>{if(this.processRanks!==Q)return;const be=ge.participants;this.ranks=new Map,be.forEach(Z=>{const de=Zg(Z);this.ranks.set(Z.user_id.toPeerId(),de)}),As().then(()=>{this.processRanks===Q&&(Q.forEach(Z=>Z()),this.processRanks=void 0)})},ge=>{ge.type!=="CHAT_ADMIN_REQUIRED"&&this.log.error("ranks error",ge),this.ranks=new Map});le.cached&&await g(re)}}let H;S?H={promise:As().then(()=>this.performHistoryResult({history:S.mids},!0)),cached:!0,waitPromise:Promise.resolve()}:H=await g(this.getHistory1(!L&&!_&&d===h?Ds:d,!0,L,_)),this.setPeerCached=H.cached,p.warn("got history");const{promise:G,cached:z}=H,q={peerId:i,isTarget:v,isJump:L,lastMsgId:a,startParam:l,middleware:m,text:e.text,entities:e.entities};!z&&!t&&(await g(this.chat.finishPeerChange(q)),this.scrollable.replaceChildren(),this.preloader.attach(this.container)),gt.lockGroup(this.chat.animationGroup);const $=g(G).then(async()=>{p.warn("promise fulfilled");const se=R?await g(d!==Ds?this.getMountedBubble(d):{bubble:this.getLastBubble()}):void 0;z&&!t&&(p.warn("finishing peer change"),await g(this.chat.finishPeerChange(q)),p.warn("finished peer change")),this.preloader.detach(),this.resolveLadderAnimation&&(this.resolveLadderAnimation(),this.resolveLadderAnimation=void 0),this.setPeerCached=void 0;const Y=this.scrollable;Y.lastScrollDirection=0,Y.lastScrollPosition=0,Y.replaceChildren(T),A&&this.cleanupPlaceholders(A),this.attachPlaceholderOnRender?.(),!v&&this.chat.isPinnedMessagesNeeded()&&this.chat.topbar.pinnedMessage?.setCorrectIndex(0),this.container.classList.toggle("has-groups",!!Object.keys(this.dateMessages).length),p.warn("mounted chat",this.chatInner===T,this.chatInner.parentElement,performance.now()-u),gt.unlockGroup(this.chat.animationGroup),gt.checkAnimations(!1,this.chat.animationGroup),this.lazyLoadQueue.unlock();const Q=Promise.all([$,As()]);if(S)Y.setScrollPositionSilently(S.top);else if(R){let he;if(X)Y.setScrollPositionSilently(99999);else if(F){const be=this.setTopPadding();be.isPaddingNeeded&&(he=be.unsetPadding),Y.setScrollPositionSilently(0)}let le=w&&this.firstUnreadBubble||se?.bubble;const re=!!le?.parentElement;re||(le=this.findNextMountedBubbleByMsgId(d,!1)||this.findNextMountedBubbleByMsgId(d,!0));let ge;if(le){const be=this.getLastBubble(),Z=w?"start":!L&&!v&&be===le?"end":"center";Z==="end"&&be===le&&t?ge=this.scrollToEnd():ge=this.scrollToBubble(le,Z,t?void 0:Rh.Static),!w&&v&&re&&this.highlightBubble(le)}v&&!re&&Q.then(()=>{Ee({langPackKey:"MessageNotFound"})}),he&&(ge||Promise.resolve()).then(()=>{he()})}else Y.setScrollPositionSilently(99999);Y.updateThumb(Y.lastScrollPosition),this.onRenderScrollSet(),this.onScroll(),Q.then(()=>{m()&&(Y.onScroll(),e.mediaTimestamp!==void 0&&(z&&!t&&st.isAvailable("animations")&&this.chat.appImManager.chats.length>1?Hs(400):Promise.resolve()).then(()=>this.playMediaWithTimestampAndMid({lastMsgFullMid:d,middleware:m,mediaTimestamp:e.mediaTimestamp})),this.tryToForceStartParam(m))}),this.chat.dispatchEvent("setPeer",a,!L),Promise.all([this.setFetchReactionsInterval(Q),this.setFetchHistoryInterval({afterSetPromise:Q,samePeer:t,savedPosition:S})]).then(()=>{p("scrolledAllDown:",Y.loadedAll.bottom),Y.loadedAll.bottom&&h!==Ds&&!this.unreaded.size&&this.onScrolledAllDown()}),f===te.Chat&&!this.chat.isForumTopic&&(await g(this.managers.appMessagesManager.getDialogOnly(i)))?.pFlags.unread_mark&&this.managers.appMessagesManager.markDialogUnread(i,!0)}).catch(se=>{throw p.error("setPeer promise error:",se),m()||this.preloader.detach(),se});return{cached:z,promise:$}}playMediaWithTimestampAndMid({middleware:e,lastMsgFullMid:t,mediaTimestamp:s}){this.getMountedBubble(t).then(i=>{!e()||!i||this.playMediaWithTimestamp(i.bubble,s)})}playMediaWithTimestamp(e,t){const s=U(e,"bubble"),i=U(e,"grouped-item"),n=i?+i.dataset.mid:+s.dataset.textMid;let a=s.querySelector(".attachment");if(a){n&&(a=a.querySelector(`[data-mid="${n}"]`));const d=a.querySelector("img, video, canvas");this.checkTargetForMediaViewer(d,void 0,t);return}const r=(i||s).querySelector(".audio");if(r){r.playWithTimestamp(t);return}const l=s.dataset.replyToPeerId.toPeerId(),c=+s.dataset.replyToMid;l&&c&&(l===this.peerId?this.chat.setMessageId({lastMsgId:c,mediaTimestamp:t}):this.chat.appImManager.setInnerPeer({peerId:l,mediaTimestamp:t}))}async setFetchReactionsInterval(e){const t=this.getMiddleware();if(this.chat.isChannel){const i=()=>{if(!t())return;const n=this.getRenderedHistory(void 0,!0),a=new Map;for(const c of n){let d=this.chat.getMessage(c);if(d?._!=="message")continue;d=fe.getGroupsFirstMessage(d);const{peerId:h,mid:u}=d;let p=a.get(h);p||a.set(h,p=new Set),p.add(u)}const r=[...a.entries()].map(([c,d])=>this.managers.appReactionsManager.getMessagesReactions(c,[...d]));Promise.all(r).then(()=>{setTimeout(i,1e4)})};Promise.all([e,As(),Hs(500)]).then(()=>{i()})}}async setFetchHistoryInterval({afterSetPromise:e,savedPosition:t,samePeer:s}){const i=this.peerId;if(i.isUser())return;const n=this.getMiddleware(),a=await this.managers.appMessagesManager.isFetchIntervalNeeded(i);if(!(t||a)||(await e,!n()))return;const l=i.toChatId();n.onClean(()=>{this.managers.apiUpdatesManager.unsubscribeFromChannelUpdates(l)}),this.managers.apiUpdatesManager.subscribeToChannelUpdates(l)}async onScrolledAllDown(){if(this.chat.type===te.Chat||this.chat.type===te.Discussion){const{peerId:e,threadId:t}=this.chat,s=await this.chat.getHistoryMaxId();this.managers.appMessagesManager.readHistory(e,s,t,!0)}}async finishPeerChange(){const[e,t,s]=await Promise.all([this.chat.isBroadcast,this.chat.canSend(),this.chat.isAnyGroup]);return()=>{this.chatInner.classList.toggle("has-rights",t),this.container.classList.toggle("is-chat-input-hidden",!t),[this.chatInner,this.remover].forEach(i=>{i.classList.toggle("is-chat",s),i.classList.toggle("is-broadcast",e)}),this.createResizeObserver()}}renderMessagesQueue(e){return this.batchProcessor.addToQueue(e)}ejectBubbles(){for(const e of this.bubblesToEject)e.remove();this.bubblesToEject.clear()}groupBubbles(e){let t;this.chat.type===te.Scheduled&&(t=new Set,e.forEach(({bubble:n,message:a})=>{const r=this.bubbleGroups.getItemByBubble(n),l=r?.group;l&&r.message.date!==a.date&&(this.bubbleGroups.removeItem(r),t.add(l))})),e.forEach(({bubble:n,message:a,reverse:r})=>{this.bubbleGroups.prepareForGrouping(n,a,r)});const s=this.bubbleGroups.groupUngrouped(),i=Array.from(s).map(n=>{if(n.avatar)return;const a=n.firstItem;if(a&&this.chat.isAvatarNeeded(a.message))return n.createAvatar(a.message)}).filter(Boolean);if(t)for(const n of t)s.add(n);return{groups:[...s],avatarPromises:i}}getMiddleware(e){return this.middlewareHelper.get(e)}async wrapMediaSpoiler({media:e,promise:t,middleware:s,attachmentDiv:i}){if(await t,!s())return;const{width:n,height:a}=i.style,r=await Rd({media:e,width:parseInt(n),height:parseInt(a),middleware:s,animationGroup:this.chat.animationGroup});s()&&i.append(r)}getBubble(e,t){let s;return t?s=$t(e,t):s=e,this.bubbles[s]}async safeRenderMessage({message:e,reverse:t,bubble:s,updatePosition:i=!0,processResult:n,canAnimateLadder:a}){const r=$t(e);if(!e||this.renderingMessages.has(r)||this.getBubble(r)&&!s)return;const l=xt(),c=l.get(),d=this.getMiddleware();d.onClean(()=>{(this.chat.destroyPromise||this.chat.setPeerPromise||Promise.resolve()).then(()=>{l.destroy()})});let h;try{this.renderingMessages.add(r);const u=document.createElement("div");u.middlewareHelper=l,u.dataset.mid=""+e.mid,u.dataset.peerId=""+e.peerId,u.dataset.timestamp=""+e.date,s&&(s.middlewareHelper.destroy(),this.skippedMids.delete(r),this.bubblesToEject.add(s),this.bubblesToReplace.delete(s),this.bubblesToReplace.set(u,s),this.bubbleGroups.changeBubbleByBubble(s,u)),s=this.bubbles[r]=u;let p=this.renderMessage(e,t,s,c);n&&(p=n(p,s));const m=p.then(g=>g&&d()?{...g,updatePosition:i,canAnimateLadder:a}:void 0);if(this.renderMessagesQueue(m.catch(()=>{})),h=await m,!d())return;h||this.skippedMids.add(r)}catch(u){this.log.error("renderMessage error:",u)}if(d())return this.renderingMessages.delete(r),h}setBubbleSendingStatus(e,t,s){!s&&e.classList.remove("is-sending","is-error","is-sent","is-read"),t&&e.classList.add("is-"+t),e.querySelectorAll(".time, .time-inner").forEach(i=>{const n=!!i.querySelector(".time-sending-status");if(!t){n&&i.firstElementChild.remove();return}let a;t==="error"?a="sendingerror":t==="sending"?a="sending":t==="sent"?a="check":a="checks";const r=Le(a,"time-sending-status");n?i.firstElementChild.replaceWith(r):i.prepend(r)})}setBubbleRepliesCount(e,t){this.chat.threadId||e.querySelectorAll(".time, .time-inner").forEach(s=>{let i=s.querySelector(".time-replies");if(!t){i?.remove();return}i||(i=document.createElement("span"),i.classList.add("time-replies"),i.append(document.createTextNode(""),Le("reply_filled","time-replies-icon","time-icon"))),i.firstChild.textContent=Ha(t),i.parentElement||s.prepend(i)})}setUnreadObserver(e,t,s,i=t){s??(s=t.maxBubbleMid),this.observer.observe(i,e==="history"?this.unreadedObserverCallback:this.unreadedContentObserverCallback),(e==="history"?this.unreaded:this.unreadedContent).set(i,s)}async renderMessage(e,t=!1,s,i){const n=e._==="message",a=n&&e.grouped_id;let r,l;const c=a?fe.getMessagesByGroupedId(a):void 0,d=this.chat.type!==te.Pinned;if(a&&d){r=c.map(xe=>xe.mid);const J=ou(c);if(e.mid!==J.mid)return}const h=r?Math.max(...r):e.mid;s.maxBubbleMid=h,n&&(l=a?ou(c):e);const u=this.chat.isOurMessage(e),p=document.createElement("div");p.classList.add("message","spoilers-container");const m=document.createElement("div");m.classList.add("bubble-content-wrapper");const g=document.createElement("div");g.classList.add("bubble-content"),s.classList.add("bubble"),m.append(g),s.append(m);let f=!u&&!e.pFlags.out&&e.pFlags.unread;const y=ev(e),v=Yp(e);if(!f&&this.chat.peerId.isAnyChat()){const J=await this.managers.appMessagesManager.getReadMaxIdIfUnread(this.chat.peerId,this.chat.threadId);J!==void 0&&J<h&&(f=!0)}const w=[],b={bubble:s,promises:w,message:e,reverse:t},S={lazyLoadQueue:this.lazyLoadQueue,middleware:i,customEmojiSize:this.chat.appImManager.customEmojiSize,animationGroup:this.chat.animationGroup},C=n&&e.media?.pFlags?.via_mention,P=!!C;let L;if(P||!n&&(!e.action||!Pf.has(e.action._))){const J=e.action;if(J){const je=J._,Ge=dT.get(je);if(Ge&&(Ge===!0||Ge(e))||Bh.hasOwnProperty(je)&&!Bh[je])return}s.className="bubble service",g.replaceChildren();const xe=document.createElement("div");if(xe.classList.add("service-msg"),J){const je=J._==="messageActionGiftCode";let Ge;if(je&&!Kh(J)){const ae=J.pFlags.unclaimed,Se=J.pFlags.via_giveaway,V=M(ae?"BoostingUnclaimedPrize":"BoostingCongratulations"),ie=document.createElement("span");ie.append(M(ae?"BoostingYouHaveUnclaimedPrize":Se?"BoostingReceivedPrizeFrom":J.boost_peer?"BoostingReceivedGiftFrom":"BoostingReceivedGiftNoName",J.boost_peer?[await Oe({peerId:at(J.boost_peer)})]:void 0),document.createElement("br"),document.createElement("br"),M(ae?"BoostingUnclaimedPrizeDuration":Se?"BoostingReceivedPrizeDuration":"BoostingReceivedGiftDuration",[eo(J.months,!0)]));const we=jm(J.months);this.wrapGift({content:g,service:xe,middleware:i,loadPromises:w,assetName:we,title:V,subtitle:ie,buttonText:"BoostingReceivedGiftOpenBtn",buttonCallback:()=>{ee.createPopup(ya,J.slug)}})}else if(J._==="messageActionChannelMigrateFrom"){const ae=new Rt;Ge=ae.update({peerId:J.chat_id.toPeerId(!0),wrapOptions:S}),xe.append(M("ChatMigration.From",[ae.element]))}else if(J._==="messageActionChatMigrateTo"){const ae=new Rt;Ge=ae.update({peerId:J.channel_id.toPeerId(!0),wrapOptions:S}),xe.append(M("ChatMigration.To",[ae.element]))}else Ge=lw({message:e,...S}).then(ae=>xe.append(ae));if(J._==="messageActionGiftPremium"||je&&Kh(J)){const ae=g.cloneNode(!1);ae.classList.add("has-service-before");const Se=xe.cloneNode(!1),V=J.months,ie=jm(V),we=M("ActionGiftPremiumTitle"),Ie=M("ActionGiftPremiumSubtitle",[eo(V,!1)]);this.wrapGift({content:ae,service:Se,middleware:i,loadPromises:w,assetName:ie,title:we,subtitle:Ie,buttonText:je&&e.fromId===e.peerId?"GiftPremiumUseGiftBtn":"ActionGiftPremiumView",buttonCallback:()=>{if(je){const Te={_:vt.GIFT_CODE,slug:J.slug,stack:this.chat.appImManager.getStackFromElement(s)};lp.processGiftCodeLink(Te);return}Vt.show({gift:J,peerId:this.peerId,isOut:!!e.pFlags.out})}}),ae.append(Se),g.after(ae)}else if(J._==="messageActionChannelJoined"){s.classList.add("is-similar-channels");const ae=document.createElement("div");ae.classList.add("bubble-similar-channels");let Se=!1;const V=(Qe=!Se,Re)=>{if(Qe===Se)return;Se=Qe,Qe&&!ae.parentElement&&g.after(ae),st.isAvailable("animations")||(Re=!0);let tt;s.isConnected&&(tt=this.createScrollSaver(!0),tt.save());const ct={duration:Re?0:300,fill:"forwards",easing:"cubic-bezier(.4, .0, .2, 1)"},Mt=[{height:"0"},{height:"9.125rem"}];Qe||Mt.reverse();const Ht=ae.animate(Mt,ct);tt&&this.animateSomethingWithScroll(Ht.finished,tt),Qe||Ht.finished.then(()=>{Se===Qe&&ae.remove()}),we(!Qe)},ie=Pt(),we=async Qe=>{const Re=await fe.getState();Qe?Re.hiddenSimilarChannels.push(Ie):us(Re.hiddenSimilarChannels,Ie),await this.managers.appStateManager.pushToState("hiddenSimilarChannels",Re.hiddenSimilarChannels)},Ie=this.chat.peerId;let Te;this.wrapSomeSolid(()=>Vk({chatId:Ie.toChatId(),onClose:()=>{V(!1)},onAcked:Qe=>{Te=Qe,Te||ie.resolve()},onReady:async()=>{g.classList.add("is-clickable"),await As(),(await fe.getState()).hiddenSimilarChannels.includes(Ie)||V(!0,Te),Te&&ie.resolve(),N(g,()=>{V()})},onEmpty:()=>{ie.isFulfilled&&V(!1),ie.resolve()}}),ae,i),w.push(ie)}w.push(Ge)}else if(C){const je=e.media,Ge=at(je.peer),ae=je.id,Se=Ge===I.myId,V=await to(this.managers.acknowledged.appStoriesManager.getStoryById(Ge,ae));if(!V.cached)xe.append(M("Loading")),V.result.then(()=>{this.safeRenderMessage({message:e,reverse:!0,bubble:s})});else if(V.result){xe.classList.add("bubble-story-mention-wrapper");const ie=document.createElement("div");ie.classList.add("bubble-story-mention-avatar-container");const we=es({middleware:i,size:100,peerId:Ge,lazyLoadQueue:this.lazyLoadQueue,withStories:!0,storyId:ae,storyColors:{read:"rgba(255, 255, 255, .3)"}});we.node.dataset.storyId=""+ae,w.push(we.readyThumbPromise);const Ie=Pt();w.push(Ie),ei(V.result,Re=>{if(!i()||!Re||Re.pFlags.noforwards){Ie.resolve();return}Jt(tt=>{i.onClean(()=>{Ie.resolve(),tt()});const{container:ct,ready:Mt}=Dd({peerId:Ge,storyItem:Re,forPreview:!0,noInfo:!0,lazyLoadQueue:this.lazyLoadQueue,withPreloader:!0,noAspecter:!0});ye(()=>{Mt()&&(Ie.resolve(),ct.classList.add("bubble-story-mention-preview"),N(ie,Ht=>{oe(Ht),mr({peerId:Ge,id:ae,target:()=>ct})},{listenerSetter:this.listenerSetter}),ie.append(ct))})})}),ie.append(we.node);const Te=M(Se?"StoryMentionYou":"StoryMention",[await Oe({peerId:Se?e.peerId:Ge})]);Te.classList.add("bubble-story-mention-text");const Qe=ze("bubble-service-button bubble-story-mention-button",{noRipple:!0,text:"StoryMentionView"});N(Qe,()=>{fs(we.node)},{listenerSetter:this.listenerSetter}),xe.append(ie,Te,Qe)}else{let ie;Se?ie=M("ExpiredStoryMentionYou",[await Oe({peerId:e.peerId})]):ie=M("ExpiredStoryMention");const we=Le("bomb","expired-story-icon");xe.append(we,ie)}}g.append(xe),e.pFlags.is_single&&s.classList.add("is-group-last"),L=!0}const E=f&&this.observer?this.setUnreadObserver.bind(this,"history",s,h):void 0,_=this.chat.isBroadcast;if(L)return E?.(),b;_||E?.(),this.observer&&(y||v)&&this.setUnreadObserver("content",s,l.mid);const k=e.pFlags.sponsored,x=e.sponsoredMessage,A=n&&e.factcheck;let T=n&&e.media,B=!0,R,O,X,F;if(n){if(a&&d){const xe=F=LS(c);R=xe?.message||"",O=xe?.totalEntities||[],X=F}else R=e.message,O=e.totalEntities,X=e;const J=T?.document;J&&(J?.type==="sticker"?R=O=void 0:["video","gif"].includes(J.type)||(B=!1))}else e.action._==="messageActionPhoneCall"&&(T={_:"messageMediaCall",action:e.action});let H=0,G;if(O&&!T&&!A){const J=[];for(let Ge=0,ae=O.length;Ge<ae;++Ge){const Se=O[Ge];Se._==="messageEntityCustomEmoji"?(++Ge,J.push(Se)):Se._==="messageEntityEmoji"&&J.push(Se)}const xe=R.replace(/\s/g,"").length;if(J.reduce((Ge,ae)=>Ge+ae.length,0)===xe){H=Math.min(pT,J.length),G=$e.active.customEmoji;const Ge=YS[H];Ge&&(G=vs(Ge,Ge),s.style.setProperty("--emoji-size",Ge+"px"))}}G??(G=this.chat.appImManager.customEmojiSize);let z=Sc(F||e);F&&B&&(s.dataset.textMid=""+F.mid);let q=e.reply_to;if(q?._==="messageReplyHeader"){const J=q.reply_to_peer_id?at(q.reply_to_peer_id):this.peerId;if(s.dataset.replyToPeerId=""+J,s.dataset.replyToMid=""+e.reply_to_mid,z===void 0){const xe=fe.getMessageByPeer(J,e.reply_to_mid);xe?z=Sc(xe):z=1/0}}else q&&(s.dataset.replyToPeerId=""+at(q.peer),s.dataset.replyToStoryId=""+q.story_id);const $=J=>({entities:J,passEntities:this.passEntities,loadPromises:w,lazyLoadQueue:this.lazyLoadQueue,customEmojiSize:G,middleware:i,animationGroup:this.chat.animationGroup,maxMediaTimestamp:z,textColor:"primary-text-color",passMaskedLinks:!!e.sponsoredMessage}),se=!H&&!u&&this.chat.type!==te.Search,Y=se?{peerId:e.peerId,middleware:i,observeElement:s,observer:this.observer,onTranslation:this.modifyBubble,richTextOptions:$()}:void 0,Q=R?se?_d({message:X,...Y}):Yt(R,$(O)):void 0;let he=!R&&!k&&!A,le=!1,re=!0,ge=!1,be=!1,Z;if(H){if(I.settings.emoji.big){const J=H===1&&!O.find(xe=>xe._==="messageEntityCustomEmoji")&&await this.managers.appStickersManager.getAnimatedEmojiSticker(R);H===1&&!T&&J?T={_:"messageMediaDocument",document:J,pFlags:{}}:(Z=document.createElement("div"),Z.classList.add("attachment","spoilers-container"),kt(Z,Q),g.append(Z)),he=!0,s.classList.add("emoji-big"),be=!0,re=!1,B=!1}s.classList.add("can-have-big-emoji")}B&&kt(p,Q);const de=this.chat.isOutMessage(e),Ze=k_(R);let Ne;if(k)s.classList.add("is-sponsored");else{Ne=s.timeSpan=Uo.setTime({chat:this.chat,chatType:this.chat.type,message:e,reactionsMessage:l,isOut:de,middleware:i,loadPromises:w}),s.timeAppenders=[];let J;ch(s,p,()=>{p.append(Ne,J??(J=rT()))}),(ke.isRTL?!T_(R):Ze)&&Ne.classList.add("is-block"),_&&E?.(Ne)}g.prepend(p);let pe;if(n&&(this.chat.isAllMessagesForum||this.chat.hashtagType==="my"&&de)){const J=await kS({peerId:e.peerId,threadId:ha(e,this.chat.isForum),lastMsgId:e.mid,wrapOptions:{middleware:i},withIcons:!0,dialog:!0,noLink:this.chat.type===te.Search}),{element:xe}=J;pe=document.createElement("div"),pe.classList.add("topic-name-button-container"),pe.append(xe)}if(n&&e.views){if(s.classList.add("channel-post"),!e.fwd_from?.saved_from_msg_id&&this.chat.type!==te.Pinned){const J=document.createElement("div");J.classList.add("bubble-beside-button","with-hover","forward"),J.append(Le("forward_filled")),g.append(J),s.classList.add("with-beside-button")}!e.pFlags.is_outgoing&&this.observer&&this.observer.observe(s,this.viewsObserverCallback)}const Be=n&&e.reply_markup;let He=Be?._==="replyInlineMarkup"&&Be.rows;if(He&&(He=He.filter(J=>J.buttons.length)),He){const J=document.createElement("div");J.classList.add("reply-markup");const xe=new Map;He.forEach((Ge,ae,Se)=>{const V=Ge.buttons,ie=ae===Se.length-1,we=document.createElement("div");we.classList.add("reply-markup-row"),V.forEach((Ie,Te,Qe)=>{const Re=Te===0,tt=Te===Qe.length-1,{text:ct,buttonEl:Mt,buttonIcon:Ht,onClick:li}=qS({button:Ie,chat:this.chat,message:e,noTextInject:!0});if(!Mt)return;li&&xe.set(Mt,li),ie&&(Re&&Mt.classList.add("is-first"),tt&&Mt.classList.add("is-last")),Mt.classList.add("reply-markup-button","rp");const ts=document.createElement("span");ts.classList.add("reply-markup-button-text"),ts.append(ct),Ni(Mt),Mt.append(...[Ht,ts].filter(Boolean)),we.append(Mt)}),we.childElementCount&&J.append(we)});const je=!!J.childElementCount;je&&N(J,Ge=>{let ae=Ge.target;ae=U(ae,"reply-markup-button");const Se=xe.get(ae);Se&&(Se(Ge),oe(Ge))}),je&&(s.classList.add("with-reply-markup"),m.append(J))}const De=e.pFlags.is_outgoing;De&&!e.error&&(s.classList.add("is-outgoing"),e.reactions&&(s.dataset.ignoreReactions="1"));const Ae=n&&await this.managers.appMessagesManager.getMessageWithCommentReplies(e),Ke=!!Ae&&e.mid>0;Ke&&s.classList.add("with-replies");const We=n&&e.fwd_from,Fe=n&&e.fwdFromId,Ue=this.chat.isForwardOfForward(e);let nt=g;const Lt=!e.viaBotId&&(e.fromId===I.myId||!e.pFlags.out)&&(!e.post_author||!We)&&!Ue,At=n&&e.pFlags.invert_media;At&&s.classList.add("invert-media");let rs;A&&(Jt(xe=>{i.onDestroy(xe);const je=()=>ke.countriesList.find(ie=>ie.iso2===A.country),Ge=()=>{const ie=je();return ie.name||ie.default_name},[ae,Se]=ne(),V=ie=>{Se(ie.text)};A.text?V(A):this.managers.appMessagesManager.getFactCheck(e.peerId,e.mid).then(ie=>{this.modifyBubble(()=>{V(ie)})}),cv({footer:{content:M("FactCheckFooter",[Ge()]),text:!0},name:{content:M("FactCheck"),tip:{content:M("FactCheckWhat"),onClick:ie=>{ur({element:ie.target,container:this.container,vertical:"top",textElement:M("FactCheckToast",[Ge()])})}}},get text(){if(!ae())return M("Loading");const{text:ie,entities:we}=Bc(ae());return Yt(ie,{entities:we})},ref:ie=>{rs=ie,Ne?Ne.before(ie):p.append(ie)},minContent:!0})}),document.createElement("div").classList.add("bubble-fact-check","quote-like","quote-like-hoverable"));const Cs=he||At;let os,js=!1,mi=!1;if(T){switch(Z=document.createElement("div"),Z.classList.add("attachment"),T._){case"messageMediaPhotoExternal":case"messageMediaPhoto":{const J=T.photo;if(ge=Cs,Lt&&s.classList.add("hide-name"),s.classList.add("photo"),d&&a&&r.length!==1){s.classList.add("is-album","is-grouped"),qp({messages:c,attachmentDiv:Z,middleware:this.getMiddleware(),isOut:u,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:w,autoDownload:this.chat.autoDownload});break}const xe=!gm&&re&&!Ke&&dv;xe&&s.classList.add("with-media-tail");const je=Ks({photo:J,message:e,container:Z,withTail:xe,isOut:de,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:w,autoDownloadSize:this.chat.autoDownload.photo});T.pFlags?.spoiler&&w.push(this.wrapMediaSpoiler({media:J,promise:je,middleware:i,attachmentDiv:Z}));break}case"messageMediaWebPage":{js=!0,Z=void 0;const J=T.webpage;if(J._!=="webPage")break;mi=!0;const xe=J.attributes?.find(St=>St._==="webPageAttributeStory"),je=xe&&at(xe.peer),Ge=xe?.id;if(xe&&await this.getStoryReplyIfExpired(je,Ge,!0)===null)break;const ae={},Se=[],V=cl(J.url);if(V.onclick&&!A_.has(V.onclick)||k)if(k){p.classList.add("margin-bigger");const St=cl(x.url);ae.footer={content:_e(x.button_text),link:!St.onclick,ref:ss=>this.observer.observe(ss,this.viewsObserverCallback)},Se.push(ss=>{ss.callback=()=>{this.chat.appImManager.clickIfSponsoredMessage(e),St.onclick?this.chat.appImManager.openUrl(x.url):ro(St.url)}})}else{const St=mT[J.type]||"OpenMessage";ae.footer={content:M(St)},Se.push(ss=>{ss.dataset.callback=V.onclick})}else{const St=!T.pFlags.safe;Se.push(ss=>{Jr(ss),St&&(ss.dataset.callback="showMaskedAlert")})}V?.url&&!k&&Se.push(St=>{St.href=V.url}),s.classList.add("has-webpage","single-media");let we;const Ie=J.document,Te=!!J.pFlags.has_large_media,Qe=!!(Te&&T.pFlags.force_small_media),Re=x&&gT(x),tt=Re||J.photo,ct=!!Re;if(!!(tt||Ie||xe||ct)&&(we=document.createElement("div"),ae.media={content:we,position:"top"}),Ie)if(Ie.type==="gif"||Ie.type==="video"||Ie.type==="round"){const St=Ie.type==="round"?$e.active.round:$e.active.webpage;Ie.type==="round"?(s.classList.add("round"),we.classList.add("is-round")):s.classList.add("video"),qn({doc:Ie,container:we,message:e,boxWidth:St.width,boxHeight:St.height,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),isOut:de,group:this.chat.animationGroup,loadPromises:w,autoDownload:this.chat.autoDownload,noInfo:e.mid<0,observer:this.observer,setShowControlsOn:s})}else{const St=await Yc({message:e,autoDownloadSize:this.chat.autoDownload.file,lazyLoadQueue:this.lazyLoadQueue,loadPromises:w,sizeType:"documentName",searchContext:{useSearch:!1,peerId:this.peerId,inputFilter:{_:"inputMessagesFilterEmpty"}},fontSize:I.settings.messagesTextSize,canTranscribeVoice:!0});we.append(St),ae.media.hasDocument=!0}if(J.site_name||x){let St;if(x?(St=M(x.pFlags.recommended?"SponsoredMessageRecommended":"SponsoredMessage"),St.classList.add("text-capitalize")):mv[J.type]?St=M(mv[J.type]):St=_e(J.site_name),!x){const ss=Yt(J.url),Vs=Ed(ss).firstElementChild;Vs.replaceChildren(St),St=Vs}ae.name={content:St,tip:x&&x.pFlags.can_report&&{content:M("SponsoredMessageAdWhatIsThis"),onClick:ss=>{oe(ss),ee.createPopup(WS)}}}}const Ht=IS(J);(Ht.textContent||x)&&(ae.title=x?_e(x.title):Ht);const li=CS(J,$(J.entities),k);li.textContent&&(ae.text=li);let ts=!1;if(ct||tt&&!Ie){s.classList.add("photo");const St=48,ss=!x&&tt.sizes[tt.sizes.length-1];(!ss||ss.w===ss.h&&!Te||Qe)&&(ae.name||ae.title||ae.text)?(s.classList.add("is-square-photo"),ae.media.photoSize="square",ts=!0,we.style.width=we.style.height=`${St}px`):ss.h>ss.w&&!Te&&(s.classList.add("is-vertical-photo"),ae.media.photoSize="vertical"),Ks({photo:tt,message:e,container:we,boxWidth:ts?0:$e.active.webpage.width,boxHeight:ts?0:$e.active.webpage.height,isOut:de,lazyLoadQueue:this.lazyLoadQueue,middleware:i,loadPromises:w,withoutPreloader:ts,autoDownloadSize:this.chat.autoDownload.photo})}if(xe){s.classList.add("photo","story");const St=$e.active.webpage;jo({photo:{_:"photo",id:0,sizes:[{_:"photoSize",w:180,h:320,type:"q",size:0}],pFlags:{},access_hash:0,file_reference:[],date:0,dc_id:0},element:we,boxWidth:St.width,boxHeight:St.height,message:e}),this.wrapStory({message:e,bubble:s,storyPeerId:je,storyId:Ge,container:we,middleware:i,loadPromises:w,boxWidth:St.width,boxHeight:St.height})}we&&(ae.media.position=At||ts?"top":"bottom"),Jt(St=>{i.onDestroy(St),cv({...ae,ref:ss=>{Se.forEach(Vs=>Vs(ss)),rs&&!At?rs.before(ss):Ne?At?(Ne.parentElement.prepend(ss),ss.parentElement.classList.add("mt-bigger")):Ne.before(ss):p.append(ss)},clickable:!0})});break}case"messageMediaDocument":{const J=T.document;if(J.sticker){s.classList.add("sticker"),re=!1,be=!0,J.animated&&s.classList.add("sticker-animated");const xe=$e.active,je=s.classList.contains("emoji-big"),Ge=je?xe.emojiSticker:J.animated?xe.animatedSticker:xe.staticSticker;jo({photo:J,element:Z,boxWidth:Ge.width,boxHeight:Ge.height}),g.style.minWidth=Z.style.width,g.style.minHeight=Z.style.height;const ae=T?.pFlags?.nopremium;Rs({doc:J,div:Z,middleware:i,lazyLoadQueue:this.lazyLoadQueue,group:this.chat.animationGroup,play:!0,liteModeKey:"stickers_chat",loop:!0,emoji:je?R:void 0,withThumb:!0,loadPromises:w,isOut:de,noPremium:ae,scrollable:this.scrollable,showPremiumInfo:()=>{const V=ni(()=>{bo(),ee.createPopup(Cn,J.stickerSetInput,void 0,this.chat.input).show()});Ee({langPackKey:"Sticker.Premium.Click.Info",langPackArguments:[V]})}}),(fo(J)||je)&&(f||De)&&this.observer.observe(s,this.stickerEffectObserverCallback)}else if(J.type==="video"||J.type==="gif"||J.type==="round"){const xe=J.type==="round";if(xe&&(be=!0),xe?re=!1:ge=Cs,Lt&&s.classList.add("hide-name"),s.classList.add(xe?"round":"video"),d&&a&&r.length!==1)s.classList.add("is-album","is-grouped"),qp({messages:c,attachmentDiv:Z,middleware:i,isOut:u,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:w,autoDownload:this.chat.autoDownload});else{const je=!gm&&!Zr&&!xe&&re&&!Ke&&dv;je&&s.classList.add("with-media-tail");const Ge=qn({doc:J,container:Z,message:e,boxWidth:$e.active.regular.width,boxHeight:$e.active.regular.height,withTail:je,isOut:de,lazyLoadQueue:this.lazyLoadQueue,middleware:i,group:this.chat.animationGroup,loadPromises:w,autoDownload:this.chat.autoDownload,searchContext:xe?{peerId:this.peerId,inputFilter:{_:"inputMessagesFilterRoundVoice"},threadId:this.chat.threadId,useSearch:!e.pFlags.is_scheduled,isScheduled:e.pFlags.is_scheduled}:void 0,noInfo:e.mid<=0,noAutoplayAttribute:!!T.pFlags.spoiler,observer:this.observer,setShowControlsOn:s});T.pFlags.spoiler&&w.push(this.wrapMediaSpoiler({media:J,promise:Ge,middleware:i,attachmentDiv:Z}))}}else{const xe=await M_({albumMustBeRenderedFull:d,message:e,bubble:s,messageDiv:p,chat:this.chat,loadPromises:w,autoDownloadSize:this.chat.autoDownload.file,lazyLoadQueue:this.lazyLoadQueue,searchContext:J.type==="voice"||J.type==="audio"?{peerId:this.peerId,inputFilter:{_:J.type==="voice"?"inputMessagesFilterRoundVoice":"inputMessagesFilterMusic"},threadId:this.chat.threadId,useSearch:!e.pFlags.is_scheduled,isScheduled:e.pFlags.is_scheduled}:void 0,sizeType:"documentName",fontSize:I.settings.messagesTextSize,richTextFragment:Q,richTextOptions:$(),canTranscribeVoice:!0,translatableParams:Y,factCheckBox:rs,isOut:de}),je=document.createElement("div");je.classList.add("bubble-content-background"),g.prepend(je),xe&&(nt=xe);const Ge=p.lastElementChild.querySelector(".document-message")||p.lastElementChild.querySelector(".document, .audio");Ge&&ch(s,Ge,()=>Ge.append(Ne)),le=!0;const ae=(["photo","pdf"].includes(J.type)?"document":J.type||"document")+"-message";s.classList.add(ae),ae!=="document-message"&&s.classList.add("min-content"),s.classList.contains("is-multiple-documents")||s.classList.add("is-single-document"),js=!0}break}case"messageMediaCall":{const J=T.action,xe=document.createElement("div");xe.classList.add("bubble-call"),xe.append(Le(J.pFlags.video?"videocamera":"phone","bubble-call-icon"));const je=J.pFlags.video?"video":"voice";xe.dataset.type=je;const Ge=document.createElement("div");Ge.classList.add("bubble-call-title"),Zt(Ge,de?J.pFlags.video?"CallMessageVideoOutgoing":"CallMessageOutgoing":J.pFlags.video?"CallMessageVideoIncoming":"CallMessageIncoming");const ae=document.createElement("div");if(ae.classList.add("bubble-call-subtitle"),J.duration!==void 0)ae.append(Lh(J.duration));else{let Se;switch(J.reason._){case"phoneCallDiscardReasonBusy":Se="Call.StatusBusy";break;case"phoneCallDiscardReasonMissed":Se="Chat.Service.Call.Missed";break;default:Se="Chat.Service.Call.Cancelled";break}ae.classList.add("is-reason"),Zt(ae,Se)}ae.prepend(Le("arrow_next","bubble-call-arrow","bubble-call-arrow-"+(J.duration!==void 0?"green":"red"))),xe.append(Ge,ae),js=!0,le=!0,s.classList.add("call-message"),p.append(xe);break}case"messageMediaContact":{const J=T,xe=document.createElement("div");xe.classList.add("contact"),xe.dataset.peerId=""+J.user_id,js=!0;const je=document.createElement("div");je.className="contact-details";const Ge=document.createElement("div");Ge.className="contact-name";const ae=[J.first_name,J.last_name].filter(Boolean).join(" ");Ge.append(ae.trim()?_e(ae):M("AttachContact"));const Se=document.createElement("div");Se.className="contact-number",Se.textContent=J.phone_number?"+"+_l(J.phone_number).formatted:"Unknown phone number",xe.append(je),je.append(Ge,Se);const V=es({middleware:i,size:54,lazyLoadQueue:this.lazyLoadQueue,peerId:J.user_id.toPeerId(),peerTitle:J.user_id?void 0:ae.trim()?ae:ke.format("AttachContact",!0)[0]});xe.prepend(V.node),le=!0,s.classList.add("contact-message"),p.append(xe);break}case"messageMediaPoll":{le=!0;const J=E_({message:e,managers:this.managers,middleware:i,translatableParams:Y,richTextOptions:$()});p.prepend(J),s.classList.add("poll-message");break}case"messageMediaPaidMedia":case"messageMediaInvoice":{const xe=(T.pFlags||{}).test,je=T._==="messageMediaInvoice",Ge=(Array.isArray(T.extended_media)?T.extended_media:[T.extended_media]).filter(Boolean),ae=Ge[0]?._==="messageExtendedMedia",Se=Ge[0]?._==="messageExtendedMediaPreview";je||(s.classList.add("single-media"),Lt&&s.classList.add("hide-name"),ge=Cs);let V,ie;je?V=T.photo:ae&&(V=Ge.map(Re=>Xs(Re)));const we=je?In(T.total_amount,T.currency):In(T.stars_amount,Eg);let Ie;if(!Ge.length||!je&&ae){Ie=document.createElement(V?"span":"div");const Re=document.createDocumentFragment(),tt=M(T.receipt_msg_id?"PaymentReceipt":xe?"PaymentTestInvoice":"PaymentInvoice");tt.classList.add("text-uppercase");const ct=" "+cf,Mt=document.createElement("span");if(Mt.classList.add("text-bold"),Mt.append(we),Re.append(Mt),je?(Mt.append(ct),Re.append(tt)):Ie.classList.add("other-side"),xe&&T.receipt_msg_id){const Ht=document.createElement("span");Ht.classList.add("text-uppercase","pre-wrap"),Ht.append(ct+"(Test)"),Re.append(Ht)}kt(Ie,Re)}else Se&&(Z.classList.add("is-buy"),Ie=document.createElement("span"),Ie.classList.add("extended-media-buy"),je?Ie.append(Le("premium_lock","extended-media-buy-icon"),M("Checkout.PayPrice",[we])):Ie.append(M("PaidMedia.Unlock",[we])),ie=Ge.map(Re=>{const tt=Re.video_duration;if(tt===void 0)return;const ct=document.createElement("span");return ct.classList.add("video-time"),ct.textContent=Fi(tt,!1),ct}),ie.length===1&&ie[0]&&Z.append(ie[0]));if(Se&&(V=Ge.map(Re=>df(Re))),Array.isArray(V)&&V.length===1&&(V=V[0]),V){const Re=Ge.length?$e.active.extendedInvoice:$e.active.invoice;Array.isArray(V)?(s.classList.add("is-album","photo"),qp({media:V,attachmentDiv:Z,middleware:this.getMiddleware(),isOut:u,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:w,autoDownload:this.chat.autoDownload,spoilered:!ae,videoTimes:ie,uploadingFileName:e.uploadingFileName})):V._==="document"?(qn({doc:V,container:Z,withTail:!1,isOut:de,lazyLoadQueue:this.lazyLoadQueue,middleware:i,loadPromises:w,boxWidth:Re.width,boxHeight:Re.height,group:this.chat.animationGroup,message:e,observer:this.observer,setShowControlsOn:s,uploadingFileName:e.uploadingFileName[0]}),s.classList.add("video")):(Ks({photo:V,container:Z,withTail:!1,isOut:de,lazyLoadQueue:this.lazyLoadQueue,middleware:i,loadPromises:w,boxWidth:Re.width,boxHeight:Re.height,message:ae?e:void 0}),s.classList.add("photo")),Ie&&((!Ge.length||!je&&ae)&&Ie.classList.add("video-time"),Z.append(Ie))}else Z=void 0;if(Se){const{mid:Re}=e;if(this.extendedMediaMessages.add(Re),i.onClean(()=>{this.extendedMediaMessages.delete(Re)}),this.setExtendedMediaMessagesPollInterval(),Ge.length===1){const{width:tt,height:ct}=Z.style,{canvas:Mt,readyResult:Ht}=Qc.create({width:parseInt(tt),height:parseInt(ct),middleware:i,animationGroup:this.chat.animationGroup});w?.push(Ht),Z.append(Mt)}}let Te;je&&(Te=document.createElement("div"),Te.classList.add("bubble-primary-color"),kt(Te,_e(T.title)));let Qe;je&&(Qe=ae?void 0:_e(T.description)),p.prepend(...[Te,Qe].filter(Boolean)),Z.append(...[(!V||!je)&&Ie].filter(Boolean)),je&&(Qe?le=!0:re=!1),s.classList.add("is-invoice");break}case"messageMediaGeoLive":case"messageMediaVenue":case"messageMediaGeo":{const J=Qk({attachmentDiv:Z,bubble:s,loadPromises:w,message:e,messageDiv:p,messageMedia:T,middleware:i,timeSpan:Ne,updateLocationOnEdit:this.updateLocationOnEdit,wrapOptions:S});J!==void 0&&(re=J);break}case"messageMediaStory":{const J=T.id,xe=at(T.peer),je=await this.getStoryReplyIfExpired(xe,J,!1,!0);if(je){s.classList.add("is-expired-story"),le=!0,p.append(je),p.classList.add("expired-story-message","is-empty");break}s.classList.add("photo","story"),Ke?jo({size:vs(Tm,$e.active.regular.height),boxWidth:$e.active.regular.width,boxHeight:$e.active.regular.height,message:e,element:Z}):this.setStoryContainerDimensions(Z),he&&(re=!1),os=xe,this.wrapStory({message:e,bubble:s,storyPeerId:xe,storyId:J,container:Z,middleware:i,loadPromises:w});break}case"messageMediaGiveawayResults":case"messageMediaGiveaway":{const J=T;J._==="messageMediaGiveawayResults"&&(q=void 0),le=!0,s.classList.add("is-giveaway"),js=!0;const xe=this.makeViewButton({text:"BoostingHowItWork"}),je=document.createElement("div");p.before(je,xe),N(xe,()=>{Fk(e)}),this.wrapSomeSolid(()=>Rk({giveaway:J,loadPromises:w}),je,i);break}default:Z=void 0,le=!0,js=!0,p.replaceChildren(M(pm)),s.timeAppenders[0].callback(),this.log.warn("unrecognized media type:",T._,e);break}if(js)Z=void 0;else{At?p.after(Z):p.before(Z);const J=Z.style.width;J&&(g.style.maxWidth=`min(100%, ${J})`)}ge&&!Ke&&s.classList.add("has-plain-media-tail")}const oi=Ne&&(he&&!le||At&&!mi);if(he&&!le?(p.remove(),s.classList.add("is-message-empty")):Z&&(Z.classList.add(At?"no-brt":"no-brb"),p.classList.add(At?"mb-shorter":"mt-shorter")),oi&&(Ne.classList.add("is-floating"),s.classList.add("has-floating-time"),s.timeAppenders=[],ch(s,g,()=>g.append(Ne))),be&&s.classList.add("just-media"),x){const J=x.pFlags.can_report,xe=document.createElement("div");xe.classList.add("bubble-beside-button","bubble-beside-button-top");let je;if(J){xe.classList.add("bubble-sponsored-buttons"),je=it("close bubble-sponsored-buttons-button",{noRipple:!0});const Ge=document.createElement("div");Ge.classList.add("bubble-sponsored-buttons-delimiter");const ae=it("more bubble-sponsored-buttons-button",{noRipple:!0});xe.append(je,Ge,ae),N(ae,Se=>{this.chat.contextMenu.onContextMenu(Se)})}else je=xe,je.append(Le("close")),xe.classList.add("bubble-sponsored-hide");g.prepend(xe),s.classList.add("with-beside-button"),N(je,()=>{Vt.show({feature:"no_ads"})})}let si="";(be||!de||e.fwdFromId)&&this.chat.appImManager.setPeerColorToElement({peerId:e.fwdFromId||e.fromId,element:s,messageHighlighting:be,colorAsOut:de,color:x?.color});const cn=e.fromId!==I.myId&&this.chat.isAnyGroup||e.viaBotId||os;if(cn||We||q||pe){let J,xe;const je=e.fromId,Ge=e.from_id?._==="peerChannel"&&e.fromId===Fe,ae=Rn(We),Se=Ue&&!de&&We.from_name&&We.saved_from_name;let V=!!e.viaBotId||os;const ie=!!(We&&(!We.from_id||ae));e.viaBotId&&(xe=document.createElement("span"),xe.innerText="@"+await this.managers.appPeersManager.getPeerUsername(e.viaBotId),xe.classList.add("peer-title"));let we=!!(os||Fe||We);if(we&&this.chat.type===te.Saved&&Fe===I.myId&&(we=!1),ie&&!Fe)J=document.createElement("span"),J.classList.add("peer-title"),kt(J,_e(We.from_name||ae)),s.classList.add("hidden-profile");else{const Re=os||Fe||e.fromId;J=this.createTitle(Re,S,we).element}let Ie;n&&(q?._==="messageReplyStoryHeader"||e.reply_to_mid&&e.reply_to_mid!==this.chat.threadId||q?.reply_from)&&(!this.chat.isAllMessagesForum||q.reply_to_top_id)&&(Ie=await Uo.setReply({chat:this.chat,bubble:s,bubbleContainer:g,message:e,appendCallback:Re=>{nt.prepend(Re),!he&&(!Z||At)&&Re.classList.add("mb-shorter"),Z&&Z.classList.add("no-brt")},middleware:i,lazyLoadQueue:this.lazyLoadQueue,needUpdate:this.needUpdate,isStandaloneMedia:be,isOut:de}));let Te;if(we){const Re=this.peerId===I.myId&&(!this.chat.threadId||!zS(e));!Re&&!Ge&&s.classList.add("forwarded"),e.savedFrom&&(si=e.savedFrom,J.dataset.savedFrom=si),Te=document.createElement("div");const tt=os||Fe;if(J.dataset.peerId=""+tt,(Re||this.peerId===cr||Ge)&&!be&&!Se&&!Ue&&!os)Te.classList.add("colored-name"),Te.append(J);else{V||(V=!0),s.classList.remove("hide-name");const ct=[J];if(tt){const ts=es({middleware:i,size:20,lazyLoadQueue:this.lazyLoadQueue,peerId:tt,isDialog:!1});ts.node.classList.add("bubble-name-forwarded-avatar"),ct.unshift(ts.node)}else J.classList.add("text-normal");{const ts=document.createElement("br");ts.classList.add("hide-ol"),ct.unshift(ts)}let Mt;const Ht=[ct];if(We?.post_author){Mt=os?"ForwardedStoryFromAuthor1":"ForwardedFromAuthor";const ts=document.createElement("span");ts.append(_e(We.post_author)),Ht.push(ts)}else Mt=os?"ForwardedStoryFrom1":"ForwardedFrom";const li=M(Mt,Ht);if(li.classList.add("bubble-name-forwarded"),Te.append(li),Se){let ts;if(ae)ts=document.createElement("span"),ts.classList.add("peer-title"),ts.style.color="var(--message-primary-color)",ts.dataset.peerId=""+Tt,ts.append(_e(ae));else{const ss=at(We.saved_from_id),{element:Vs,textColorProperty:Zn}=this.createTitle(ss,S,!1);Vs.style.color=`rgb(var(--${Zn}))`,ts=Vs}const St=document.createElement("div");St.classList.add("name-first-line"),St.append(ts),Te.prepend(St)}}}else if(!e.viaBotId)if(!be&&cn){Te=document.createElement("div"),Te.append(J);{const tt=fe.getPeer(je)?.pFlags;tt&&(tt.scam||tt.fake)&&Te.append(jb(tt.scam)),u||Te.classList.add("colored-name"),Te.dataset.peerId=""+je}}else s.classList.add("hide-name");if(e.viaBotId){Te?Te.append(" "):Te=document.createElement("div");const Re=document.createElement("span");Re.append(M("ViaBot")," ",xe),Re.classList.add("is-via"),Te.append(Re)}if(pe&&(be?pe.classList.add("floating-part"):(Te||(Te=document.createElement("div")),Te.append(pe),s.classList.remove("hide-name"))),Te&&!s.classList.contains("hide-name")){Te.classList.add("name"),Oa(Te);const Re=tt=>{p&&tt.nextElementSibling===p&&tt.classList.add("next-is-message")};if(be){const tt=document.createElement("div");tt.classList.add("name-with-reply","floating-part"),nt.prepend(tt),Re(tt),nt=tt}else Te.classList.add("floating-part");nt.prepend(Te),be||Re(Te),be&&Ie&&Te.after(Ie)}else be&&Ie&&Ie.classList.add("floating-part");const Qe=Te?.firstElementChild||J;if(this.canShowRanks&&J&&!ie&&!Fe){const Re=()=>{const ct=this.ranks.get(e.fromId);ct&&this.wrapTitleAndRank(Qe,ct)},tt=e.post_author;if(tt)this.wrapTitleAndRank(Qe,tt);else if(this.ranks)Re();else{const ct=this.processRanks;ct.add(Re),i.onDestroy(()=>{ct.delete(Re)})}}else this.chat.isMegagroup&&!e.fromId.isUser()&&e.views&&this.wrapTitleAndRank(Qe,0);if(pe&&be)if(Z)Z.after(pe);else{this.log.error("no attachment div?",s,e);debugger}V&&s.classList.add("must-have-name")}else s.classList.add("hide-name");if(this.chat.type===te.Pinned&&(si=$t(this.chat.peerId,e.mid)),Ae&&Ae.mid===this.chat.threadId&&s.classList.add("is-thread-starter","is-group-last"),si&&(this.chat.type===te.Pinned||We.saved_from_msg_id)&&this.peerId!==cr){const J=document.createElement("div");J.classList.add("bubble-beside-button","with-hover","goto-original"),J.append(Le("arrow_next")),g.append(J),s.dataset.savedFrom=si,s.classList.add("with-beside-button")}if(s.classList.add(de?"is-out":"is-in"),Ke)Uo.renderReplies({bubble:s,bubbleContainer:g,message:Ae,messageDiv:p,loadPromises:w,lazyLoadQueue:this.lazyLoadQueue,middleware:i})?re=!0:s.classList.add("with-beside-replies");else if(n&&e.replies&&this.chat.isAnyGroup){const J=e.replies;this.setBubbleRepliesCount(s,J.replies)}if(n&&this.appendReactionsElementToBubble(s,e,l,void 0,w),re&&(s.classList.add("can-have-tail"),g.append(XS())),u&&(this.peerId!==I.myId||de)){(e.pFlags.unread||De)&&this.unreadOut.add(e.mid);let J;e.error?J="error":De?J="sending":J=e.pFlags.unread||e.pFlags.is_scheduled?"sent":"read",(de||J!=="sent"&&J!=="read")&&this.setBubbleSendingStatus(s,J,!0)}return n&&Jt(J=>{i.onDestroy(J),ye(()=>{s.classList.toggle("no-forwards",!this.canForward(e))})}),n&&e.effect&&(f||De)&&this.observer.observe(s,this.messageEffectObserverCallback),b}canForward(e){return e?._!=="message"||e.pFlags.noforwards?!1:e.peerId.isUser()?!0:!xb(e.peerId).pFlags.noforwards}appendReactionsElementToBubble(e,t,s,i,n){if(this.peerId.isUser()&&oT||!s?.reactions||!s.reactions.results.length)return;const a=new op;if(a.init({context:s,type:vn.Block,middleware:e.middlewareHelper.get(),animationGroup:this.chat.animationGroup,lazyLoadQueue:this.lazyLoadQueue}),a.render(i),e.classList.contains("has-floating-time"))e.querySelector(".bubble-content-wrapper").append(a);else{const r=e.timeSpan,l=e.querySelector(".message");if(ch(e,a,()=>a.append(r)),e.classList.contains("is-multiple-documents")){const c=l.lastElementChild;let d=c.querySelector(".document-message");d||(d=document.createElement("div"),d.classList.add("document-message"),c.querySelector(".document-wrapper").append(d)),d.append(a)}else l.append(a)}}setStoryContainerDimensions(e){e.style.width="144px",e.style.height="256px"}async getStoryReplyIfExpired(e,t,s,i){const n=await this.managers.acknowledged.appStoriesManager.getStoryById(e,t);if(n.cached&&!await n.result){if(s)return null;const a=await Oe({peerId:e}),{container:r,fillPromise:l}=Fd({title:s?a:void 0,subtitle:s?void 0:M("ExpiredStorySubtitle",[a]),isStoryExpired:!0,noBorder:i});return r}}wrapGift({content:e,service:t,middleware:s,loadPromises:i,assetName:n,title:a,subtitle:r,buttonText:l,buttonCallback:c}){e.classList.add("bubble-premium-gift-container"),t.classList.add("bubble-premium-gift-wrapper"),a.classList.add("text-bold");const d=160,h=ju({width:d,height:d,assetName:n,middleware:s,loop:!1,autoplay:st.isAvailable("stickers_chat")}).then(({container:p,promise:m})=>(p.classList.add("bubble-premium-gift-sticker"),p.style.position="relative",p.style.width=p.style.height=d+"px",t.prepend(p),m)),u=l&&ze("bubble-service-button",{noRipple:!0,text:l});u&&c&&N(u,c),t.append(a,r),u&&t.append(u),i.push(h)}wrapSomeSolid(e,t,s){const i=Hi(e,t);s.onClean(i)}wrapStory({message:e,bubble:t,storyPeerId:s,storyId:i,container:n,middleware:a,loadPromises:r,boxWidth:l,boxHeight:c}){n.dataset.storyPeerId=""+s,n.dataset.storyId=""+i,this.wrapSomeSolid(()=>$_({message:e,peerId:s,storyId:i,boxWidth:l,boxHeight:c,lazyLoadQueue:this.lazyLoadQueue,autoDownload:this.chat.autoDownload,loadPromises:r,canAutoplay:!1,onExpiredStory:async()=>{await As(),e=this.chat.getMessageByPeer(e.peerId,e.mid),this.safeRenderMessage({message:e,reverse:!0,bubble:t})},withPreloader:!0}),n,a)}wrapTitleAndRank(e,t){const s=this.createBubbleNameRank(t),i=document.createElement("div");i.classList.add("title-flex"),e.replaceWith(i),i.append(e,s)}createBubbleNameRank(e){const t=document.createElement("span");return t.classList.add("bubble-name-rank"),t.append(Tw(e)),t}createTitle(e,t,s){const i=Nu(fe.getPeer(e));let n;return i!==-1&&(n=`peer-${i}-color-rgb`),{element:new Rt({peerId:e,withPremiumIcon:!s,wrapOptions:{...t,textColor:n}}).element,textColorProperty:n}}prepareToSaveScroll(e,t,s){if(!!!this.chatInner.parentElement)return{};const n=this.log.bindPrefix("prepareToSaveScroll");n("save");const a=this.createScrollSaver(e);if(a.save(),(t||s)&&this.getRenderedLength()&&!this.chat.setPeerPromise){const r=this.getViewportSlice(!0);t||(r.invisibleTop.length=0),s||(r.invisibleBottom.length=0),this.deleteViewportSlice(r,!0)}return{restoreScroll:()=>{n("restore"),a.restore(e),this.onRenderScrollSet(a.getSaved())},scrollSaver:a}}async performHistoryResult(e,t){const s=this.log.bindPrefix("perform-"+(Math.random()*1e3|0));s?.("start",this.chatInner.parentElement,e);let i=e.messages||e.history;i=i.slice(),this.needReflowScroll&&(l_(this.scrollable.container),this.needReflowScroll=!1);const n=d=>{if(d)return d.pFlags.local?this.processLocalMessageRender(d):this.safeRenderMessage({message:d,reverse:t,canAnimateLadder:!0})},a=i.map(d=>typeof d=="number"?this.chat.getMessage(d):d),r=[];if(!this.scrollable.loadedAll.bottom||!this.scrollable.loadedAll.top){let d=e.isEnd;if(!d){const h=await this.chat.getHistoryStorage(),u=h.history.first,p=h.history.last;d={top:!1,bottom:!1,both:!1},u.isEnd(Ro.Bottom)&&(!u.length||i.includes(u[0]))&&(d.bottom=!0),p.isEnd(Ro.Top)&&(!p.length||i.includes(p[p.length-1]))&&(d.top=!0)}if(!d.bottom&&this.setPeerOptions){const{lastMsgFullMid:h,topMessageFullMid:u,savedPosition:p}=this.setPeerOptions;this.setPeerOptions=void 0,(h===Ds&&!p||u!==Ds&&this.getBubble(u)||h===u)&&(d.bottom=!0)}d.top&&r.push(this.setLoaded("top",!0)),d.bottom&&r.push(this.setLoaded("bottom",!0))}r.length&&await Promise.all(r);let l=[];this.chat.type,te.Search,l=a.map(n),l.length&&await Promise.all(l),await this.messagesQueuePromise;const c=this.checkIfEmptyPlaceholderNeeded();c&&await c,this.messagesQueuePromise&&await this.messagesQueuePromise,this.scrollable.loadedAll.top&&this.messagesQueueOnRenderAdditional&&(this.messagesQueueOnRenderAdditional(),this.messagesQueueOnRenderAdditional?.()),s?.("performHistoryResult end")}onRenderScrollSet(e){const t="has-sticky-dates";if(!this.container.classList.contains(t)&&(!this.preloader.detached||(e??(e={scrollHeight:this.scrollable.scrollSize,clientHeight:this.scrollable.clientSize}),e.scrollHeight!==e.clientHeight))){const i=this.getMiddleware(),n=()=>{i()&&this.container.classList.add(t)};this.willScrollOnLoad?n():setTimeout(n,600);return}this.willScrollOnLoad=void 0}requestHistory(e,t,s){let i;if(typeof e=="string"){const{peerId:n,mid:a}=Is(e);i=n,e=a}if([te.Chat,te.Discussion,te.Saved,te.Search].includes(this.chat.type))return this.managers.acknowledged.appMessagesManager.getHistory({...this.chat.requestHistoryOptionsPart,offsetPeerId:i,offsetId:e,limit:t,backLimit:s});if(this.chat.type===te.Pinned)return this.managers.acknowledged.appMessagesManager.getHistory({peerId:this.peerId,inputFilter:{_:"inputMessagesFilterPinned"},offsetPeerId:i,offsetId:e,limit:t,backLimit:s});if(this.chat.type===te.Scheduled)return this.managers.acknowledged.appMessagesManager.getScheduledMessages(this.peerId).then(n=>({cached:n.cached,result:Promise.resolve(n.result).then(a=>({history:a.slice().reverse(),count:a.length,isEnd:{both:!0,bottom:!0,top:!0}}))}))}async animateAsLadder(e,t,s,i,n){const a=this.log.bindPrefix("ladder");if(this.chat.setPeerPromise&&!this.resolveLadderAnimation){a.warn("will be delayed"),this.resolveLadderAnimation=this.animateAsLadder.bind(this,e,t,s,i,n);return}const r=this.getRenderedHistory("desc");if(!r.length){a.warn("no bubbles");return}let l=r.slice();s&&t.length&&(l=l.filter(P=>!t.includes(P)));let c;i?c=n||l[0]:e?c=e:c=l[0];const d=l.slice(l.findIndex(P=>c>P)),h=s?[]:[c],u=s?[]:l.slice(0,l.findIndex(P=>c>=P)).reverse();$i&&a("targeting mid:",c,n,e,d,u);const p=[];this.chatInner.classList.add("zoom-fading");const m=s?10:40,g=s?0:1,f=(P,L=0)=>{const E=Pt();let _=0;return P.forEach((k,x)=>{const A=this.getBubble(k);if(!A||this.skippedMids.has(k)){a.warn("no bubble by mid:",k);return}_=(x+L||.1)*m;const T=A.lastElementChild;if(!T){a.warn("bubble not ready yet",k,this.batchProcessor);return}const B=[T],R=this.bubbleGroups.getItemByBubble(A);if(R&&R.group.avatar&&R.group.lastItem===R&&B.push(R.group.avatar.node),B.forEach(O=>{O.classList.add("zoom-fade","can-zoom-fade"),O.style.setProperty("transition-delay",_+"ms","important")}),x===P.length-1){const O=X=>{X.target===T&&(E.resolve(),T.removeEventListener("transitionend",O))};T.addEventListener("transitionend",O)}p.push(...B)}),P.length||E.resolve(),{lastMsDelay:_,animationPromise:E}},y=f(d,g),v=f(h),w=f(u,g),b=[y.animationPromise,v.animationPromise,w.animationPromise],S=[y.lastMsDelay,v.lastMsDelay,w.lastMsDelay];this.onAnimateLadder&&await this.onAnimateLadder(),bs(()=>{this.setStickyDateManually(),p.forEach(P=>{P.classList.remove("zoom-fade")})});let C;if(d.length||h.length||u.length){C=Promise.all(b);const L=Math.max(...S)+300;Xr(C,L).then(()=>{bs(()=>{p.forEach(E=>{E.style.transitionDelay="",E.classList.remove("can-zoom-fade")}),this.chatInner.classList.remove("zoom-fading")})})}return C}async renderEmptyPlaceholder(e,t,s,i){const n="empty-bubble-placeholder";t.classList.add(n,n+"-"+e);let a;e==="group"?a=M("GroupEmptyTitle1"):e==="saved"?a=M("ChatYourSelfTitle"):e==="noMessages"||e==="greeting"?a=M("NoMessages"):e==="noScheduledMessages"?a=M("NoScheduledMessages"):e==="restricted"&&(a=document.createElement("span"),a.innerText=await this.managers.appPeersManager.getRestrictionReasonText(this.peerId)),a&&(a.classList.add("center",n+"-title"),i.push(a));let r;if(e==="group")i.push(M("GroupEmptyTitle2")),r=[M("GroupDescription1"),M("GroupDescription2"),M("GroupDescription3"),M("GroupDescription4")];else if(e==="saved")r=[M("ChatYourSelfDescription1"),M("ChatYourSelfDescription2"),M("ChatYourSelfDescription3"),M("ChatYourSelfDescription4")];else if(e==="greeting"){let l=M("NoMessagesGreetingsDescription");const c=document.createElement("div");c.classList.add(n+"-sticker");const d=this.getMiddleware();await Promise.all([this.managers.appStickersManager.getGreetingSticker(),this.managers.appProfileManager.getProfile(s.peerId.toUserId())]).then(async([u,p])=>{if(!d())return;const m=p.business_intro;if(m){if(m.title){const w=document.createElement("span");w.append(_e(m.title)),w.className=a.className,i[i.indexOf(a)]=w}m.description&&(l=document.createElement("span"),l.append(_e(m.description))),m.sticker&&(u=m.sticker);const f=t.querySelector(".bubble-content"),y=f.cloneNode(!1),v=f.querySelector(".service-msg").cloneNode(!1);v.append(M(m.title||m.description?"ChatEmpty.BusinessIntro.How":"ChatEmpty.BusinessIntro.Sticker.How",[await Oe({peerId:s.peerId,onlyFirstName:!0}),ni(()=>{Vt.show()})])),y.classList.add("has-service-before"),y.append(v),f.after(y),t.classList.add("wider")}const g=[];return await Rs({doc:u,div:c,middleware:d,lazyLoadQueue:this.lazyLoadQueue,group:this.chat.animationGroup,play:!0,loop:!0,withThumb:!0,loadPromises:g,liteModeKey:"stickers_chat"}),N(c,f=>{oe(f),this.chat.input.emoticonsDropdown.onMediaClick({target:f.target},void 0,void 0,!0)}),Promise.all(g)}),l.classList.add("center",n+"-subtitle"),i.push(l,c)}else if(e==="premiumRequired"){const l=document.createElement("div");l.classList.add(n+"-sticker"),l.append(Le("premium_restrict"));const c=M("Chat.PremiumRequired",[await Oe({peerId:this.peerId,onlyFirstName:!0})]);c.classList.add("center",n+"-subtitle");const d=ze("bubble-service-button",{noRipple:!0,text:"Chat.PremiumRequiredButton"});N(d,()=>{Vt.show()}),i.push(l,c,d)}r&&(i.push(...r.map(l=>{const c=document.createElement("span");return c.classList.add(n+"-list-item"),c.append(l),c})),e==="group"?r.forEach(l=>{const c=Le("check",n+"-list-check");l.prepend(c)}):e==="saved"&&r.forEach(l=>{const c=document.createElement("span");c.classList.add(n+"-list-bullet"),c.innerText="•",l.prepend(c)})),i.length>1&&t.classList.add("has-description"),i.forEach(l=>l.classList.add(n+"-line"))}async processLocalMessageRender(e,t){const s=!!e.pFlags.sponsored,i=()=>{this.log.warn("local message was cleared before render",e)},n=async a=>{const{bubble:r}=await a;if(!r)return i(),a;const l=$t(e),c=r.middlewareHelper.get(),d=so(c);r.message=e,r.classList.add("is-group-last","is-group-first");const h=()=>{if(this.updatePlaceholderPosition===h&&(this.updatePlaceholderPosition=void 0),!c()||this.getBubble(l)!==r){i();return}f[y](m)};s||(r.classList.add("bubble-first"),r.classList.remove("can-have-tail","is-in"));const u=[],p=this.chat.isBot,m=r;let g,f=this.container,y="append";if(this.chat.isRestricted)g=this.renderEmptyPlaceholder("restricted",r,e,u);else if(s)r.classList.add("avoid-selection"),this.sponsoredMessage=e.sponsoredMessage,f=this.chatInner,y="append",t=!1;else if(p&&e._==="message"){const b=document.createElement("b");b.append(M("BotInfoTitle")),u.push(b,`
`),f=this.chatInner,y="prepend"}else this.chat.isAnyGroup&&fe.getPeer(this.peerId).pFlags.creator?g=this.renderEmptyPlaceholder("group",r,e,u):this.chat.type===te.Scheduled?g=this.renderEmptyPlaceholder("noScheduledMessages",r,e,u):I.myId===this.peerId?g=this.renderEmptyPlaceholder("saved",r,e,u):this.peerId.isUser()&&!p&&await d(this.chat.canSend())&&this.chat.type===te.Chat?await this.managers.appUsersManager.isPremiumRequiredToContact(this.peerId.toUserId())?g=this.renderEmptyPlaceholder("premiumRequired",r,e,u):g=this.renderEmptyPlaceholder("greeting",r,e,u):g=this.renderEmptyPlaceholder("noMessages",r,e,u);g&&await g,u.length&&r.querySelector(".message, .service-msg").prepend(...u);const v=!!this.messagesQueueOnRenderAdditional,w=this.setPeerCached&&!v;if(w){const b=r.firstElementChild;b.classList.add("no-transition"),this.chat.setPeerPromise&&this.chat.setPeerPromise.catch(Wt).finally(()=>{b.classList.remove("no-transition")})}if(t===void 0&&!w&&(t=!0),v||t?(this.updatePlaceholderPosition=h,this.onAnimateLadder=()=>{if(this.onAnimateLadder=void 0,!this.messagesQueuePromise)return ym()}):this.chat.setPeerPromise?this.attachPlaceholderOnRender=()=>{this.attachPlaceholderOnRender=void 0,h()}:this.updatePlaceholderPosition=h,!v&&t){await d(As());const b=this.getRenderedHistory("asc");us(b,l),this.animateAsLadder(l,b,!1,0,Ds)}return r.middlewareHelper.onDestroy(()=>{this.emptyPlaceholderBubble===r&&(this.emptyPlaceholderBubble=void 0)}),this.emptyPlaceholderBubble=r,a};return this.safeRenderMessage({message:e,reverse:!s,updatePosition:!1,processResult:n,canAnimateLadder:!0})}makeViewButton(e){const t=ze("btn-primary btn-primary-transparent bubble-view-button",e),s=t.querySelector(".i18n");return s&&s.classList.add("bubble-view-button-text"),t}generateLocalMessageId(e=0){const t=(this.chat.type===te.Scheduled?-1:0)+e,s=-Math.abs(t);return{id:s,mid:s}}async generateLocalFirstMessage(e,t,s=0){const{id:i,mid:n}=this.generateLocalMessageId(s);let a={_:e?"messageService":"message",date:0,id:i,mid:n,peer_id:await this.managers.appPeersManager.getOutputPeer(this.peerId),pFlags:{local:!0}};return e||(a.message=""),t?.(a),a=(await this.managers.appMessagesManager.saveMessages([a],{storage:new Map}))[0],a.mid=n,a}getViewportSlice(e){return zb({overflowElement:this.scrollable.container,selector:".bubbles-date-group .bubble:not(.is-date)",extraSize:e?Math.max(700,lt.height)*2:void 0,extraMinLength:e?5:void 0})}deleteViewportSlice(e,t){const{invisibleTop:s,invisibleBottom:i}=e,n=s.concat(i);if(!n.length)return;const a=this.log.bindPrefix("VIEWPORT-SLICE");s.length&&(this.setLoaded("top",!1),this.getHistoryTopPromise=void 0,a("will slice top",n)),i.length&&(this.setLoaded("bottom",!1),this.getHistoryBottomPromise=void 0,a("will slice bottom",n));const r=n.map(({element:c})=>Bn(c));let l;t||(l=this.createScrollSaver(!!s.length),l.save()),a("slicing mids",r),this.deleteMessagesByIds(r,!1,!0),l?l.restore():s.length&&(this.scrollable.lastScrollPosition=this.scrollable.scrollPosition)}sliceViewport(e){if(Pi||this.isHeavyAnimationInProgress&&!e||hT)return;const t=this.getViewportSlice(!0);this.deleteViewportSlice(t)}async setLoaded(e,t,s=!0){if(!(!(this.scrollable.loadedAll[e]!==t)||(this.log.bindPrefix("setLoaded")("change",e,t),this.scrollable.loadedAll[e]=t,this.scrollable.onScroll(),this.scrollable.loadedAll.bottom&&this.scrollable.loadedAll.top&&B0(this.peerId),!s)))return!this.chat.isRestricted&&(e==="bottom"&&this.chat.isBroadcast&&this.chat.type===te.Chat&&this.toggleSponsoredMessage(t),e==="top"&&t&&this.chat.isBot)?this.renderBotPlaceholder():this.checkIfEmptyPlaceholderNeeded()}async toggleSponsoredMessage(e){const t=this.log.bindPrefix("sponsored-"+(Math.random()*1e3|0));t("checking",e);const{mid:s}=this.generateLocalMessageId(uv),i=$t(this.peerId,s);if(e){const n=this.getMiddleware(()=>this.scrollable.loadedAll.bottom&&this.getSponsoredMessagePromise===a),a=this.getSponsoredMessagePromise=this.managers.appChatsManager.getSponsoredMessage(this.peerId.toChatId()).then(r=>{if(!n()||r._==="messages.sponsoredMessagesEmpty")return;const l=r.messages[0];if(!l){t("no message");return}const c=this.generateLocalFirstMessage(!1,d=>{d.message="",d.from_id={_:"peerUser",user_id:Tt},d.pFlags.sponsored=!0,d.sponsoredMessage=l;const h={_:"webPage",id:d.mid,pFlags:{},url:"",display_url:"",hash:0,description:l.message,entities:l.entities};d.media={_:"messageMediaWebPage",pFlags:{},webpage:h}},uv);return Promise.all([c,this.getHistoryTopPromise,this.messagesQueuePromise]).then(([d])=>{if(n())return t("rendering",d),this.performHistoryResult({history:[d]},!1)})}).finally(()=>{this.getSponsoredMessagePromise===a&&(this.getSponsoredMessagePromise=void 0)})}else t("clearing rendered",s),this.getSponsoredMessagePromise=void 0,this.deleteMessagesByIds([i],!1)}async renderBotPlaceholder(){const e=this.log.bindPrefix("bot placeholder"),t=this.getMiddleware(),s=await this.managers.acknowledged.appProfileManager.getProfile(this.peerId.toUserId());e("getting profile, cached:",s.cached);const i=s.result.then(async n=>{if(!t())return;if(!n.bot_info?.description)return e.warn("no description"),this.checkIfEmptyPlaceholderNeeded();const a=await this.generateLocalFirstMessage(!1,l=>{const c=n.bot_info;l.message=c.description,c.description_document&&(l.media={_:"messageMediaDocument",document:c.description_document,pFlags:{}}),c.description_photo&&(l.media={_:"messageMediaPhoto",photo:c.description_photo,pFlags:{}})});return t()?(e("rendering"),{renderPromise:this.processLocalMessageRender(a,!s.cached).then(()=>{e("done")})}):void 0});if(s.cached)return i}async checkIfEmptyPlaceholderNeeded(){if(this.scrollable.loadedAll.top&&this.scrollable.loadedAll.bottom&&this.emptyPlaceholderBubble===void 0&&(this.chat.isRestricted||Object.keys(this.bubbles).length&&!this.getRenderedLength()||this.chat.type===te.Scheduled&&!this.getRenderedLength()||!(await this.chat.getHistoryStorage()).count)){this.log("inject empty peer placeholder");const e=await this.generateLocalFirstMessage(!0);return{renderPromise:this.processLocalMessageRender(e)}}}getHistory1(e,t,s,i,n){const a=this.getMiddleware(n?void 0:()=>(t?this.getHistoryTopPromise:this.getHistoryBottomPromise)===l),r=this.getHistory(e,t,s,i,n,a),l=r.then(c=>c&&(c.waitPromise||c.promise));return t?this.getHistoryTopPromise=l:this.getHistoryBottomPromise=l,l.then(()=>{a()&&(t?this.getHistoryTopPromise=void 0:this.getHistoryBottomPromise=void 0,n||this.chat.type===te.Chat&&setTimeout(()=>{t?this.loadMoreHistory(!0,!0):this.loadMoreHistory(!1,!0)},0))}),r}async getHistory(e=Ds,t=!1,s=!1,i,n=!1,a){const r=this.peerId,l=this.chat.isBroadcast,c=Math.min(40,lt.height/40|0);let h=l?20:this.getRenderedHistory(void 0,!0).length>0?Math.max(35,c):c,u=0;s&&(u=h,t||(h=0));let p;if(i&&!s)if(this.chat.type===te.Pinned)p=[i];else{const E=(await this.chat.getHistoryStorage()).history,_=E.slice;if(_.isEnd(Ro.Bottom)&&!_.isEnd(Ro.Both)){const{mid:k,peerId:x}=Is(i),A=E.sliceMe(k,0,h);A?p=[i,...A.slice.map(T=>$t(x,T))]:p=_.slice(0,h).map(T=>$t(x,T));for(let T=p.length-1;T>=0&&this.chat.getMessage(p[T])?.grouped_id;--T)p.splice(T,1);h=Math.max(0,h-p.length),e=p[p.length-1]||e}}let m=await this.requestHistory(e,h,u),g;this.log("i vin brehnya",m,e,h,u);const f=!!p?.length,y=this.isFirstLoad&&!m.cached&&(f||h>0);f&&(g=m.result,m={cached:!0,result:Promise.resolve({history:p.map(L=>Is(L).mid)})}),this.isFirstLoad=!1;const v=async L=>{L.isEnd?.top&&await this.managers.appProfileManager.getProfileByPeerId(r)},w=L=>As().then(()=>v(L)).then(()=>(!f&&i&&L.history.unshift(Is(i).mid),this.performHistoryResult(L,t))),b=L=>Promise.resolve(L).then(_=>{if(a&&!a())throw Xp;if(n){this.scrollable.onScroll();return}return w(_)},_=>{throw this.log.error("getHistory error:",_),_});let S,C;if(!m.cached)C=!1,S=b(m.result);else{if(n)return this.scrollable.onScroll(),null;C=!0,S=w(await m.result)}const P=f?b(g):S;if(y&&st.isAvailable("animations")){let L=f?2:1;this.messagesQueueOnRenderAdditional=()=>{if(this.log("messagesQueueOnRenderAdditional"),--L)return;this.messagesQueueOnRenderAdditional=void 0,this.animateAsLadder(i,p,f,u,e).then(()=>{setTimeout(()=>{this.loadMoreHistory(t,!0)},0)})}}else this.messagesQueueOnRenderAdditional=void 0;return n?null:{cached:C,promise:S,waitPromise:P}}async setUnreadDelimiter(){if(!(this.chat.type===te.Chat||this.chat.type===te.Discussion)||this.attachedUnreadBubble)return;const e=this.getMiddleware(),{peerId:t,threadId:s}=this.chat,i=await this.chat.getHistoryMaxId();let n=await this.managers.appMessagesManager.getReadMaxIdIfUnread(t,s);if(!n||!e()||(n=this.getRenderedHistory("asc",!0).filter(r=>!this.getBubble(r).classList.contains("is-out")).map(r=>Is(r).mid).find(r=>r>n),!n))return;const a=this.getBubble(t,n);a&&(this.firstUnreadBubble&&this.firstUnreadBubble!==a&&(this.firstUnreadBubble.classList.remove("is-first-unread"),this.firstUnreadBubble=null),n!==i&&a.classList.add("is-first-unread"),this.firstUnreadBubble=a,this.attachedUnreadBubble=!0)}deleteEmptyDateGroups(){let e=!1;for(const t in this.dateMessages){const s=this.dateMessages[t];s.groupsLength||(s.container.remove(),this.stickyIntersector?.unobserve(s.container,s.div),delete this.dateMessages[t],e=!0)}e&&(Object.keys(this.dateMessages).length||this.container.classList.remove("has-groups"),this.checkIfEmptyPlaceholderNeeded(),this.setStickyDateManually())}}function XS(o){if(o){const s=document.createElement("span");return s.classList.add("bubble-tail"),s}const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttributeNS(null,"viewBox","0 0 11 20"),e.setAttributeNS(null,"width","11"),e.setAttributeNS(null,"height","20"),e.classList.add("bubble-tail");const t=document.createElementNS("http://www.w3.org/2000/svg","use");return t.setAttributeNS(null,"href","#message-tail-filled"),e.append(t),e}class ZS extends Ss{constructor(e,t,s){super("popup-delete-chat",{title:`Send Message${t.length>1?"s":""} Now`,description:t.length>1?"Send "+t.length+" messages now?":"Send message now?",buttons:[{langKey:"Send",callback:()=>{s&&s(),this.managers.appMessagesManager.sendScheduledMessages(e,t)}}]}),this.show()}}function Nr(){window.getSelection?window.getSelection().empty?window.getSelection().empty():window.getSelection().removeAllRanges&&window.getSelection().removeAllRanges():document.selection&&document.selection.empty()}const yT=window.matchMedia("(display-mode: standalone)").matches,gv=o=>[...o.values()].reduce((e,t)=>e+t.size,0);class JS extends Si{constructor(e){super(!1),this.selectedMids=new Map,this.isSelecting=!1,this.onMouseDown=t=>{const s=U(t.target,this.targetLookupClassName);if(t.button!==0||this.verifyTarget&&!this.verifyTarget(t,s))return;const i=new Map;let n,a=s;const r=(u,p=!0)=>{const m=+u.dataset.mid;if(!m||!u.dataset.peerId)return;const g=u.dataset.peerId.toPeerId();ca(a)||(a=u);let f=i.get(g);if(f||i.set(g,f=new Set),f.has(m))return;const y=this.isMidSelected(g,m);if(n===void 0&&(n=!y),f.add(m),n&&!y||!n&&y){const v=gv(i);if(this.toggleByElement&&p){v<2&&Ns(u,a)&&(a=u);const w=this.getElementsBetween(a,u);w.length&&w.forEach(b=>{r(b,!1)})}if(this.selectedMids.size)this.toggleByElement&&this.toggleByElement(u);else if(v===2&&this.toggleByMid)for(const[w,b]of i)for(const S of b)this.toggleByMid(w,S)}};let l=!1;const c=u=>{l||(Nr(),l=!0,document.body.classList.add("no-select"));const p=this.getElementFromTarget(u.target);if(p){if(this.verifyMouseMoveTarget&&!this.verifyMouseMoveTarget(u,p,n)){this.listenerSetter.removeManual(this.listenElement,"mousemove",c),this.listenerSetter.removeManual(document,"mouseup",d,h);return}r(p)}},d=u=>{document.body.classList.remove("no-select"),i.size&&N(window,oe,{capture:!0,once:!0,passive:!1}),this.listenerSetter.removeManual(this.listenElement,"mousemove",c),Nr()},h={once:!0};this.listenerSetter.add(this.listenElement)("mousemove",c),this.listenerSetter.add(document)("mouseup",d,h)},this.getElementsBetween=(t,s)=>{if(t===s)return[];const i=t.getBoundingClientRect(),n=s.getBoundingClientRect(),r=(i.top-n.top||i.left-n.left)<0,l=U(t,this.lookupBetweenParentClassName);if(!l)return[];const c=Array.from(l.querySelectorAll(this.lookupBetweenElementsQuery));let d=c.indexOf(t),h=c.indexOf(s);return r||([h,d]=[d,h]),c.slice(d+1,h)},this.cancelSelection=t=>{t&&(this.doNotAnimate=!0),this.onCancelSelection?.(),this.selectedMids.clear(),this.toggleSelection(),Nr(),t&&(this.doNotAnimate=void 0)},It(this,e),this.navigationType="multiselect-"+Pd()}attachListeners(e,t){if(this.listenElement&&this.listenerSetter.removeAll(),this.listenElement=e,this.listenerSetter=t,!!e){if(Je){t.add(e)("touchend",()=>{this.isSelecting&&(this.selectedText=VS())}),za({element:e,callback:s=>{if(this.isSelecting||this.verifyTouchLongPress&&!this.verifyTouchLongPress())return;this.onTouchLongPress?.(s),document.body.classList.add("no-select"),e.addEventListener("touchend",n=>{oe(n),document.body.classList.remove("no-select")},{once:!0,capture:!0}),Ua&&yT&&e.addEventListener("mousedown",oe,{once:!0,capture:!0}),Nr(),oe(s);const i=this.getElementFromTarget(s.target);i&&this.toggleByElement(i)},listenerSetter:t});return}t.add(e)("mousedown",this.onMouseDown)}}isElementShouldBeSelected(e){return this.isMidSelected(e.dataset.peerId.toPeerId(),+e.dataset.mid)}appendCheckbox(e,t){e.prepend(t.label)}toggleElementCheckbox(e,t){const s=!!this.getCheckboxInputFromElement(e);if(t){if(s)return!1;const i=new pt({name:e.dataset.mid,round:!0});this.isSelecting&&this.isElementShouldBeSelected(e)&&(i.input.checked=!0,e.classList.add("is-selected")),this.appendCheckbox(e,i)}else s&&(this.getCheckboxInputFromElement(e).parentElement.remove(),bt({element:e,className:"is-selected",forwards:!1,duration:200}));return!0}getCheckboxInputFromElement(e){return e.firstElementChild?.tagName==="LABEL"&&e.firstElementChild.firstElementChild}async updateContainer(e=!1){const t=this.selectedMids.size;if(!t&&!e)return;let s=!t,i=!t,n=!t,a=!t;if(this.isStories){s=!0,n=!0;const r=this.selectedMids.keys().next().value,l=await this.managers.appStoriesManager.cantPinDeleteStories(r,Array.from(this.selectedMids.get(r)));a=l.cantPin,i=l.cantDelete}else for(const[r,l]of this.selectedMids){const c=this.getStorageKey(r),d=await this.managers.appMessagesManager.cantForwardDeleteMids(c,Array.from(l));if(s=d.cantForward,i=d.cantDelete,s&&i)break}this.onUpdateContainer?.(s,i,n,a)}getStorageKey(e){return`${e}_${this.isScheduled?"scheduled":"history"}`}getSelectedMids(){return Ln([...this.selectedMids.values()].map(e=>[...e])).sort((e,t)=>e-t)}getSelectedMessages(){const e=[];return this.selectedMids.forEach((t,s)=>{const i=this.getStorageKey(s),n=Array.from(t).map(a=>this.managers.appMessagesManager.getMessageFromStorage(i,a));e.push(...n)}),Promise.all(e)}toggleSelection(e=!0,t=!1){const s=this.isSelecting,i=this.selectedMids.size;if(this.isSelecting=!!i||t,s===this.isSelecting)return!1;this.dispatchEvent("toggle",this.isSelecting),Je||(this.listenElement.classList.toggle("no-select",this.isSelecting),s&&Nr()),Dn();const n=!!i||t,a=this.onToggleSelection?.(n,!this.doNotAnimate);return Ua||(n?ft.pushItem({type:this.navigationType,onPop:()=>{this.cancelSelection()}}):ft.removeByType(this.navigationType)),t&&(a||Promise.resolve()).then(()=>this.updateContainer(t)),!0}cleanup(){this.doNotAnimate=!0,this.selectedMids.clear(),this.toggleSelection(!1),this.doNotAnimate=void 0}updateElementSelection(e,t){this.toggleElementCheckbox(e,!0);const s=this.getCheckboxInputFromElement(e);s.checked=t,this.toggleSelection(),this.updateContainer(),bt({element:e,className:"is-selected",forwards:t,duration:200})}isMidSelected(e,t){return!!this.selectedMids.get(e)?.has(t)}length(){return gv(this.selectedMids)}toggleMid(e,t,s){let i=this.selectedMids.get(e);return s||s===void 0&&i?.has(t)?i&&(i.delete(t),i.size||this.selectedMids.delete(e)):(i||(i=new Set,this.selectedMids.set(e,i)),i.add(t)),!0}deleteSelectedMids(e,t,s){const i=this.selectedMids.get(e);if(!i)return;t.forEach(a=>{i.delete(a)}),i.size||this.selectedMids.delete(e);const n=()=>{this.updateContainer(),this.toggleSelection()};return s||n(),n}}class vT extends JS{constructor(e,t,s){super({managers:t,verifyTarget:(i,n)=>!!n&&this.isSelecting,getElementFromTarget:i=>U(i,"search-super-item"),targetLookupClassName:"search-super-item",lookupBetweenParentClassName:"tabs-tab",lookupBetweenElementsQuery:".search-super-item"}),this.searchSuper=e,this.toggleByElement=i=>{const n=+i.dataset.mid,a=i.dataset.peerId.toPeerId();this.toggleMid(a,n)&&this.updateElementSelection(i,this.isMidSelected(a,n))},this.toggleByMid=(i,n)=>{const a=this.searchSuper.mediaTab.contentTab.querySelector(`.search-super-item[data-peer-id="${i}"][data-mid="${n}"]`);this.toggleByElement(a)},this.onDeleteStoriesClick=async i=>{const n=[...this.selectedMids.keys()][0];i||(i=[...this.selectedMids.get(n)]),await Ct({titleLangKey:i.length===1?"DeleteStoryTitle":"DeleteStoriesTitle",descriptionLangKey:i.length===1?"DeleteStorySubtitle":"DeleteStoriesSubtitle",descriptionLangArgs:[i.length],button:{langKey:"Delete",isDanger:!0}}),this.cancelSelection(),this.managers.appStoriesManager.deleteStories(n,i)},this.onPinClick=(i,n)=>{const a=[...this.selectedMids.keys()][0];i||(i=[...this.selectedMids.get(a)]);const r=this.managers.appStoriesManager.togglePinned(a,i,n);this.cancelSelection(),r.then(()=>{i.length===1?Ee({langPackKey:n?"StoryPinnedToProfile":"StoryArchivedFromProfile"}):Ee({langPackKey:n?"StorySavedTitle":"StoryArchived",langPackArguments:[i.length]})})},this.onPinToTopClick=(i,n)=>{const a=[...this.selectedMids.keys()][0]||this.searchSuper.searchContext.peerId,r=this.managers.appStoriesManager.togglePinnedToTop(a,i,n);this.cancelSelection(),r.catch(l=>{l.type==="STORY_ID_TOO_MANY"&&Ee({langPackKey:"StoriesPinLimit",langPackArguments:[l.limit]})})},this.onUpdateContainer=(i,n,a,r)=>{const l=this.length();dt(this.selectionCountEl,M(this.isStories?"StoriesCount":"messages",[l])),this.selectionPinBtn.classList.toggle("hide",!this.isStories||r),this.selectionGotoBtn.classList.toggle("hide",this.isStories||l!==1),this.selectionForwardBtn.classList.toggle("hide",i),this.selectionDeleteBtn&&this.selectionDeleteBtn.classList.toggle("hide",n)},this.onToggleSelection=(i,n)=>{if(bt({element:this.searchSuper.navScrollableContainer,className:"is-selecting",forwards:i,duration:n?200:0,onTransitionEnd:()=>{this.isSelecting||(this.selectionContainer.remove(),this.selectionContainer=this.selectionForwardBtn=this.selectionDeleteBtn=null,this.selectedText=void 0)}}),bt({element:this.searchSuper.container,className:"is-selecting",forwards:i,duration:200}),this.isSelecting&&!this.selectionContainer){const a="search-super-selection";this.selectionContainer=document.createElement("div"),this.selectionContainer.classList.add(a+"-container");const r=it(`close ${a}-cancel`,{noRipple:!0});N(r,()=>this.cancelSelection(),{listenerSetter:this.listenerSetter,once:!0}),this.selectionCountEl=document.createElement("div"),this.selectionCountEl.classList.add(a+"-count");const l={listenerSetter:this.listenerSetter};this.selectionPinBtn=it(`${this.isStoriesArchive?"pin":"unpin"} ${a}-pin`),N(this.selectionPinBtn,()=>this.onPinClick(void 0,this.isStoriesArchive),l),this.selectionGotoBtn=it(`message ${a}-goto`),N(this.selectionGotoBtn,()=>{const d=[...this.selectedMids.keys()][0],h=[...this.selectedMids.get(d)][0];this.cancelSelection(),me.setInnerPeer({peerId:d,lastMsgId:h,threadId:this.searchSuper.mediaTab.type==="saved"?this.searchSuper.searchContext.peerId:this.searchSuper.searchContext.threadId})},l),this.selectionForwardBtn=it(`forward ${a}-forward`),N(this.selectionForwardBtn,()=>{const d={};for(const[h,u]of this.selectedMids)d[h]=Array.from(u).sort((p,m)=>p-m);ee.createPopup(va,d,()=>{this.cancelSelection()})},l),this.isPrivate&&(this.selectionDeleteBtn=it(`delete danger ${a}-delete`),N(this.selectionDeleteBtn,()=>{if(this.isStories){this.onDeleteStoriesClick();return}const d=this.searchSuper.searchContext.peerId;ee.createPopup(Rl,d,this.getSelectedMids(),te.Chat,()=>{this.cancelSelection()})},l)),this.selectionContainer.append(...[r,this.selectionCountEl,this.selectionPinBtn,this.selectionGotoBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean));const c=this.selectionContainer;c.style.opacity="0",this.searchSuper.navScrollableContainer.append(c),c.offsetLeft,c.style.opacity=""}},this.isPrivate=!e.showSender,!Je&&this.attachListeners(e.container,s)}toggleSelection(e=!0,t=!1){const s=super.toggleSelection(e,t);return s&&e&&Array.from(this.searchSuper.tabsContainer.querySelectorAll(".search-super-item")).forEach(n=>{this.toggleElementCheckbox(n,this.isSelecting)}),s}}class bT extends JS{constructor(e,t,s,i){super({managers:i,getElementFromTarget:n=>U(n,"grouped-item")||U(n,"bubble"),verifyTarget:(n,a)=>!(!this.selectedMids.size&&!n.target.classList.contains("bubble")&&!n.target.classList.contains("document-selection")&&a),verifyMouseMoveTarget:(n,a,r)=>!(n.target!==a&&!n.target.classList.contains("document-selection")&&r===void 0&&!this.selectedMids.size),verifyTouchLongPress:()=>!this.chat.input.recording,targetLookupClassName:"bubble",lookupBetweenParentClassName:"bubbles-inner",lookupBetweenElementsQuery:".bubble:not(.is-multiple-documents), .grouped-item",onTouchLongPress:()=>{const{replySwipeHandler:n}=this.chat.bubbles;n?.reset()}}),this.chat=e,this.bubbles=t,this.input=s,this.toggleByElement=n=>{if(!this.canSelectBubble(n))return;const a=+n.dataset.mid,r=n.dataset.peerId.toPeerId();if(n.classList.contains("is-grouped")){if(!this.isGroupedBubbleSelected(n)){const d=this.selectedMids.get(r);d&&this.getMidsFromGroupContainer(n).forEach(({mid:u})=>d.delete(u))}this.bubbles.getBubbleGroupedItems(n).map(this.toggleByElement);return}if(!this.toggleMid(r,a))return;if(n.classList.contains("grouped-item")){const d=U(n,"bubble"),h=this.isGroupedBubbleSelected(d),u=this.isGroupedMidsSelected(d);(u||h)&&this.updateElementSelection(d,u)}this.updateElementSelection(n,this.isMidSelected(r,a))},this.toggleByMid=async(n,a)=>{const r=await this.bubbles.getMountedBubble($t(n,a));r&&this.toggleByElement(r.bubble)},this.onToggleSelection=async(n,a)=>{const{needTranslateX:r,widthFrom:l,widthTo:c}=await this.chat.input.center(a);bt({element:this.listenElement,className:"is-selecting",forwards:n,duration:a?200:0,onTransitionEnd:()=>{this.isSelecting||(this.selectionInputWrapper.remove(),this.selectionInputWrapper=this.selectionContainer=this.selectionSendNowBtn=this.selectionForwardBtn=this.selectionDeleteBtn=this.selectionLeft=this.selectionRight=null,this.selectedText=void 0)}});const d=l<c?void 0:r*2;if(this.isSelecting){if(!this.selectionContainer){this.selectionInputWrapper=document.createElement("div"),this.selectionInputWrapper.classList.add("chat-input-wrapper","selection-wrapper"),this.selectionContainer=document.createElement("div"),this.selectionContainer.classList.add("selection-container");const h={listenerSetter:this.listenerSetter},u=it("close",{noRipple:!0});N(u,()=>this.cancelSelection(),{once:!0,listenerSetter:this.listenerSetter}),this.selectionCountEl=document.createElement("div"),this.selectionCountEl.classList.add("selection-container-count"),this.chat.type===te.Scheduled?(this.selectionSendNowBtn=ze("btn-primary btn-transparent btn-short text-bold selection-container-send",{icon:"send2"}),this.selectionSendNowBtn.append(M("MessageScheduleSend")),N(this.selectionSendNowBtn,()=>{ee.createPopup(ZS,this.chat.peerId,[...this.selectedMids.get(this.chat.peerId)],()=>{this.cancelSelection()})},h)):(this.selectionForwardBtn=ze("btn-primary btn-transparent text-bold selection-container-forward",{icon:"forward"}),this.selectionForwardBtn.append(M("Forward")),N(this.selectionForwardBtn,()=>{const g={};for(const[f,y]of this.selectedMids)g[f]=Array.from(y).sort((v,w)=>v-w);ee.createPopup(va,g,()=>{this.cancelSelection()})},h)),this.selectionDeleteBtn=ze("btn-primary btn-transparent danger text-bold selection-container-delete",{icon:"delete"}),this.selectionDeleteBtn.append(M("Delete")),N(this.selectionDeleteBtn,()=>{ee.createPopup(Rl,this.chat.peerId,this.getSelectedMids(),this.chat.type,()=>{this.cancelSelection()})},h);const p=this.selectionLeft=document.createElement("div");p.classList.add("selection-container-left"),p.append(u,this.selectionCountEl);const m=this.selectionRight=document.createElement("div");m.classList.add("selection-container-right"),m.append(...[this.selectionSendNowBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean)),d!==void 0&&(p.style.transform=`translateX(${-d}px)`,m.style.transform=`translateX(${d}px)`),this.selectionContainer.append(p,m),this.selectionInputWrapper.style.opacity="0",this.selectionInputWrapper.append(this.selectionContainer),this.input.inputContainer.append(this.selectionInputWrapper),this.selectionInputWrapper.offsetLeft,this.selectionInputWrapper.style.opacity=""}this.selectionLeft.style.transform="",this.selectionRight.style.transform=""}else this.selectionLeft&&d!==void 0&&(this.selectionLeft.style.transform=`translateX(-${d}px)`,this.selectionRight.style.transform=`translateX(${d}px)`)},this.onUpdateContainer=(n,a,r)=>{dt(this.selectionCountEl,M("messages",[this.length()])),this.selectionSendNowBtn?.toggleAttribute("disabled",r),this.selectionForwardBtn?.toggleAttribute("disabled",n),this.selectionDeleteBtn?.toggleAttribute("disabled",a)},this.onCancelSelection=async()=>{}}appendCheckbox(e,t){t.label.classList.add("bubble-select-checkbox"),e.classList.contains("document-container")?e.querySelector(".document, audio-element").append(t.label):super.appendCheckbox(e,t)}toggleSelection(e=!0,t=!1){const s=super.toggleSelection(e,t);if(s&&e){const i=this.bubbles.getRenderedHistory("asc");for(const n of i){if(this.bubbles.skippedMids.has(n))continue;const a=this.bubbles.getBubble(n);this.toggleElementCheckbox(a,this.isSelecting)}}return s}toggleElementCheckbox(e,t){if(!this.canSelectBubble(e))return;const s=super.toggleElementCheckbox(e,t);return s&&e.classList.contains("is-grouped")&&this.bubbles.getBubbleGroupedItems(e).forEach(n=>this.toggleElementCheckbox(n,t)),s}isElementShouldBeSelected(e){const t=e.classList.contains("is-grouped");return super.isElementShouldBeSelected(e)&&(!t||this.isGroupedMidsSelected(e))}isGroupedBubbleSelected(e){return this.getCheckboxInputFromElement(e)?.checked}getMidsFromGroupContainer(e){const t=this.chat.bubbles.getBubbleGroupedItems(e);return t.length||t.push(e),t.map(s=>({mid:+s.dataset.mid,peerId:s.dataset.peerId.toPeerId()}))}isGroupedMidsSelected(e){const t=this.getMidsFromGroupContainer(e),s=t.filter(({peerId:i,mid:n})=>this.isMidSelected(i,n));return t.length===s.length}getCheckboxInputFromElement(e){return e.classList.contains("document-container")?e.querySelector("label input"):super.getCheckboxInputFromElement(e)}canSelectBubble(e){return e&&!e.classList.contains("service")&&!e.classList.contains("is-outgoing")&&!e.classList.contains("is-error")&&!e.classList.contains("bubble-first")&&!e.classList.contains("avoid-selection")}}const Er="pinned-container";class Fl{constructor(e){this.floating=!1,It(this,e);const{divAndCaption:t,className:s}=this;t?(this.container=t.container,t.title.classList.add(Er+"-title"),t.subtitle.classList.add(Er+"-subtitle"),t.content.classList.add(Er+"-content")):(this.container=document.createElement("div"),this.container.classList.add("pinned-"+this.className)),this.container.classList.add(Er,"hide"),this.btnClose=it(`close ${Er+"-close"} pinned-${s}-close`,{noRipple:!0}),this.wrapper=document.createElement("div"),this.wrapper.classList.add(Er+"-wrapper",`pinned-${s}-wrapper`),Ni(this.wrapper),this.wrapperUtils=document.createElement("div"),this.wrapperUtils.classList.add(Er+"-wrapper-utils",`pinned-${s}-wrapper-utils`),this.wrapperUtils.append(this.btnClose),this.wrapper.append(...t?Array.from(t.container.children):[],this.wrapperUtils),t&&t.container.append(this.wrapper),this.attachOnCloseEvent(this.btnClose)}destroy(){}attachOnCloseEvent(e){N(e,t=>{oe(t),((this.onClose?this.onClose():null)||Promise.resolve(!0)).then(s=>{s&&this.toggle(!0)})},{listenerSetter:this.listenerSetter})}toggle(e){const t=this.container.classList.contains("hide");if(e===void 0)e=!t;else if(e===t)return;const s=(this.floating||$e.isMobile)&&!e;this.container.classList.toggle("is-floating",s),this.container.classList.toggle("hide",e),this.topbar.container.classList.toggle(`is-pinned-${this.className}-shown`,!e),this.topbar.setFloating(),this.topbar.setUtilsWidth()}isVisible(){return!this.container.classList.contains("hide")}isFloating(){return this.container.classList.contains("is-floating")}fill(e){const{message:t}=e;this.container.dataset.peerId=""+t.peerId,this.container.dataset.mid=""+t.mid,this.divAndCaption.fill(e),this.topbar.setUtilsWidth()}}class wT extends Fl{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"audio",divAndCaption:new np("pinned-audio",h=>{dt(this.divAndCaption.title,h.title),this.divAndCaption.subtitle.replaceChildren(this.time," • ",h.subtitle)}),onClose:()=>{rt.stop(void 0,!0)},floating:!0,height:52}),this.topbar=e,this.chat=t,this.managers=s,this.onPlaybackParams=h=>{this.playbackRateButton.setIcon(),this.playbackRateButton.element.classList.toggle("active",h.playbackRate!==1),this.repeatEl.querySelector(".button-icon").replaceWith(Le(h.loop?"audio_repeat_single":"audio_repeat","button-icon")),this.repeatEl.classList.toggle("active",h.loop||h.round)},this.onPause=()=>{this.setPlayIcon(!0)},this.onStop=()=>{this.toggle(!0)},this.onMediaPlay=({doc:h,message:u,media:p,playbackParams:m})=>{let g,f;const y=h.type!=="voice"&&h.type!=="round";if(!y)g=new Rt({peerId:u.fromId,fromName:Rn(u.fwd_from)}).element,f=ws(u.date);else{const v=h.attributes.find(w=>w._==="documentAttributeAudio");g=_e(v?.title??h.file_name),f=v?.performer?_e(v.performer):M("AudioUnknownArtist")}this.repeatEl.classList.toggle("hide",!y),this.onPlaybackParams(m),this.volumeSelector.setGlobalVolume(),this.progressLine.setMedia({media:p,duration:this.duration=h.duration}),this.fill({title:g,subtitle:f,message:u}),this.setPlayIcon(p.paused),this.toggle(!1)},this.divAndCaption.border.remove();const i=it("fast_rewind active",{noRipple:!0}),n=it("fast_forward active",{noRipple:!0});this.time=document.createElement("span"),this.time.classList.add("pinned-audio-time");const a=(h,u)=>{N(h,p=>{oe(p),u()},{listenerSetter:this.topbar.listenerSetter})};a(i,()=>{rt.previous()}),a(n,()=>{rt.next()}),this.toggleEl=it("",{noRipple:!0}),this.toggleEl.classList.add("active","pinned-audio-ico"),a(this.toggleEl,()=>{rt.toggle()}),this.wrapper.prepend(this.wrapper.firstElementChild,i,this.toggleEl,n),this.volumeSelector=new tu({listenerSetter:this.listenerSetter,vertical:!0,useGlobalVolume:"auto"});const r=document.createElement("div");r.classList.add("progress-line-container"),r.append(this.volumeSelector.container);const l=document.createElement("div");l.classList.add("pinned-audio-volume-tunnel"),this.volumeSelector.btn.classList.add("pinned-audio-volume","active"),this.volumeSelector.btn.prepend(l),this.volumeSelector.btn.append(r),this.repeatEl=it("audio_repeat",{noRipple:!0}),a(this.repeatEl,()=>{const h=rt.getPlaybackParams();h.round?h.loop?(rt.round=!1,rt.loop=!1):rt.loop=!rt.loop:rt.round=!0}),this.playbackRateButton=iS({direction:"bottom-left"}),this.wrapperUtils.prepend(this.volumeSelector.btn,this.playbackRateButton.element,this.repeatEl);const c=document.createElement("div");c.classList.add("pinned-audio-progress-wrapper"),this.progressLine=new ep({withTransition:!0,useTransform:!0,onTimeUpdate:h=>{this.time.textContent=Fi(h,!0)}}),this.progressLine.container.classList.add("pinned-audio-progress"),c.append(this.progressLine.container),this.wrapper.insertBefore(c,this.wrapperUtils),this.topbar.listenerSetter.add(rt)("play",this.onMediaPlay),this.topbar.listenerSetter.add(rt)("pause",this.onPause),this.topbar.listenerSetter.add(rt)("stop",this.onStop),this.topbar.listenerSetter.add(rt)("playbackParams",this.onPlaybackParams);const d=rt.getPlayingDetails();d&&(this.onMediaPlay(d),this.onPlaybackParams(d.playbackParams))}destroy(){super.destroy(),this.progressLine?.removeListeners()}setPlayIcon(e){po(this.toggleEl,e?"play":"pause")}}class Zc{constructor(e,t,s,i){this.peerId=e,this.mid=t,this.unpin=s,this.onConfirm=i,this.construct()}async construct(){const{peerId:e,mid:t,unpin:s,onConfirm:i}=this;let n,a,r;const l=[],c=[],d=ee.MANAGERS,h=await d.appPeersManager.canPinMessage(e),u=(m,g,f,y)=>{setTimeout(()=>{let v;s&&!t?h?v=d.appMessagesManager.unpinAllMessages(e):v=d.appMessagesManager.hidePinnedMessages(e):v=d.appMessagesManager.updatePinnedMessage(e,t,s,y,f),i&&v.then(i)},300)};if(s){let m="UnpinMessage";t?(n="UnpinMessageAlertTitle",a="Chat.Confirm.Unpin"):h?(n="Popup.Unpin.AllTitle",a="Chat.UnpinAllMessagesConfirmation",r=[""+(await d.appMessagesManager.getPinnedMessagesCount(e)||1)]):(n="Popup.Unpin.HideTitle",a="Popup.Unpin.HideDescription",m="Popup.Unpin.Hide"),l.push({langKey:m,isDanger:!0,callback:u})}else{n="PinMessageAlertTitle";const m="PinMessage";e.isAnyChat()?(l.push({langKey:m,callback:(g,f)=>u(g,f,!1,!f.size)}),await d.appChatsManager.isBroadcast(e.toChatId())?a="PinMessageAlertChannel":(a="PinMessageAlert",c.push({text:"PinNotify",checked:!0}))):(a="PinMessageAlertChat",e===I.myId?l.push({langKey:m,callback:u}):(l.push({langKey:m,callback:(g,f)=>u(g,f,!f.size)}),c.push({text:"PinAlsoFor",textArgs:[await Oe({peerId:e})],checked:!0})))}fr(l),ee.createPopup(Ss,"popup-delete-chat",{peerId:e,titleLangKey:n,descriptionLangKey:a,descriptionLangArgs:r,buttons:l,checkboxes:c}).show()}}const qa=1,em=2,Eo="pinned-message-border";class ST{constructor(){this.drawRect=(e,t,s,i,n)=>`M${e},${t+n}a${n},${n},0,0,1,${s},0v${i-2*n}a${n},${n},0,0,1,${-s},0Z`,this.getClipPath=(e,t,s)=>{let n="";if(s===2)n=this.drawRect(0,0,em,t,1)+this.drawRect(0,t+qa*2,em,t,1);else for(let a=0;a<s;++a)n+=this.drawRect(0,(t+qa)*a,em,t,1);return this.clipPath||(this.clipPath=document.createElementNS("http://www.w3.org/2000/svg","clipPath"),this.path=document.createElementNS("http://www.w3.org/2000/svg","path"),this.clipPath.append(this.path)),this.clipPath.id=e,this.path.setAttributeNS(null,"d",n),this.clipPath},this.getBarHeight=(e,t)=>{let s;return e<=1?s=32:e===2?s=15:e===3?s=10:(e===4||e>3)&&(s=8),s},this.getMarkHeight=(e,t)=>{let s;return e<=1?s=32:e===2?s=15:e===3?s=10:(e===4||e>3)&&(s=8),s},this.getMarkTranslateY=(e,t,s)=>{if(s===1)return 0;if(s===2)return e?t+qa:0;if(s===3){if(e){if(e===1)return t+qa}else return 0;return t*2+qa*2+1}else return(t+qa)*e},this.getTrackTranslateY=(e,t,s,i)=>t<=4||e<=1?0:e>=t-2?i-32-s:(e-2)*s+e*qa,this.getTrackHeight=(e,t)=>e<=3?32:t*e+qa*(e-1)}render(e,t){if(this.border||(this.border=document.createElement("div"),this.border.classList.add(Eo),this.wrapper=document.createElement("div"),this.border.append(this.wrapper)),e===1)return this.count!==e&&(this.wrapper.className=Eo+"-wrapper-1",this.border.classList.remove(Eo+"-mask"),this.wrapper.replaceChildren(),this.wrapper.style.cssText=""),this.border;const s=this.getBarHeight(e,t),i=this.getMarkHeight(e,t),n=this.getTrackHeight(e,s),a=`clipPath_${e}`,r=this.getClipPath(a,s,e),l=this.getMarkTranslateY(t,s,e),c=this.getTrackTranslateY(t,e,s,n);return this.border.classList.toggle(Eo+"-mask",e>4),t<=1?(this.border.classList.add("mask-bottom"),this.border.classList.remove("mask-top")):t>=e-2?(this.border.classList.add("mask-top"),this.border.classList.remove("mask-bottom")):this.border.classList.add("mask-top","mask-bottom"),this.wrapper.className=Eo+"-wrapper",this.wrapper.style.cssText=`clip-path: url(#${a}); width: 2px; height: ${n}px; transform: translateY(-${c}px);`,this.svg||(this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.setAttributeNS(null,"height","0"),this.svg.setAttributeNS(null,"width","0"),this.defs=document.createElementNS("http://www.w3.org/2000/svg","defs"),this.defs.append(r),this.svg.append(this.defs),this.mark=document.createElement("div"),this.mark.classList.add(Eo+"-mark")),this.svg.parentElement||this.wrapper.append(this.svg,this.mark),this.mark.style.cssText=`height: ${i}px; transform: translateY(${l}px);`,this.count=e,this.index=t,this.border}}function CT(o,e,t,s){if(Je){let i;const n={passive:!0};s.add(o)("touchstart",l=>{if(l.touches.length>1){r();return}i=l.touches[0].clientY,s.add(o)("touchmove",a,n),s.add(o)("touchend",r,n)},n);const a=l=>{const c=l.touches[0].clientY;c<i&&t(),i=c},r=()=>{s.removeManual(o,"touchmove",a,n),s.removeManual(o,"touchend",r,n)}}else s.add(o)("wheel",i=>{i.deltaY>0&&t()},{passive:!0})}const $r=class $r{constructor(){this.rows={},this.container=document.createElement("div"),this.container.className=$r.BASE_CLASS}getRow(e,t=!1){if(this.rows[e])return this.rows[e].element;const s=document.createElement("div"),i=!Object.keys(this.rows).length&&!t;return s.className=$r.BASE_CLASS+"-row"+(i?"":" is-hiding hide"),this.rows[e]={element:s,middleware:s.middlewareHelper=xt(),new:!0},this.container.append(s),s}clearRow(e){this.rows[e]&&(this.rows[e].element.remove(),this.rows[e].middleware.destroy(),delete this.rows[e])}clearRows(e){this.clearTimeout&&clearTimeout(this.clearTimeout),this.clearTimeout=window.setTimeout(()=>{for(const t in this.rows)+t!==e&&this.clearRow(+t)},$r.DURATION)}setNewRow(e,t=!1){const s=this.rows[e];s.new&&(t?(s.element.classList.remove("hide"),s.element.offsetLeft):s.element.classList.remove("is-hiding","hide"),delete s.new),this.clearRows(e)}animate(e,t,s=e>t,i=!1){if(e===t)return this.setNewRow(e);const n=this.rows[e],a=this.rows[t];if(!a&&!i)return this.setNewRow(e);const r=["from-top","from-bottom"];s||r.reverse(),n.element.classList.add(r[0]),n.element.classList.remove(r[1]),a&&(a.element.classList.add(r[1]),a.element.classList.remove(r[0])),n.new&&this.setNewRow(e,!0),n.element.classList.toggle("is-hiding",!1),a&&a.element.classList.toggle("is-hiding",!0),this.clearRows(e)}destroy(){for(const e in this.rows)this.clearRow(+e)}};$r.DURATION=200,$r.BASE_CLASS="animated-super";let wl=$r;const On=class On{constructor(e=!1){this.reverse=e,this.decimals=[],this.previousNumber=0,this.container=document.createElement("div"),this.container.className=On.BASE_CLASS}getDecimal(e){if(this.decimals[e])return this.decimals[e];const t=document.createElement("div");t.className=On.BASE_CLASS+"-decimal";const s=document.createElement("div");s.className=On.BASE_CLASS+"-decimal-placeholder";const i=new wl;return i.container.className=On.BASE_CLASS+"-decimal-wrapper",t.append(s,i.container),this.container.append(t),this.decimals[e]={container:t,placeholder:s,animatedSuper:i}}clear(e){this.clearTimeout&&clearTimeout(this.clearTimeout);const t=(""+e).length;t>=this.decimals.length||(this.clearTimeout=window.setTimeout(()=>{this.decimals.splice(t,this.decimals.length-t).forEach(i=>{i.container.remove()})},wl.DURATION))}hideLeft(e){const t=(""+e).length;this.decimals.slice(t).forEach(i=>{const n=+i.placeholder.innerText||0;i.animatedSuper.getRow(On.EMPTY_INDEX,!0),i.animatedSuper.animate(On.EMPTY_INDEX,n,this.reverse?e<this.previousNumber:e>this.previousNumber,!0)}),this.clear(e)}setCount(e){const t=Array.from(""+this.previousNumber).map(i=>+i);Array.from(""+e).map(i=>+i).forEach((i,n)=>{const a=this.getDecimal(n),r=a.animatedSuper.getRow(i,!0),l=t[n]??On.EMPTY_INDEX;r.innerText=a.placeholder.innerText=""+i,a.animatedSuper.animate(i,l,this.reverse?e<this.previousNumber:e>this.previousNumber,!0)}),this.hideLeft(e),this.previousNumber=e}destroy(){this.decimals.forEach(e=>{e.animatedSuper.destroy()})}};On.EMPTY_INDEX=-1,On.BASE_CLASS="animated-counter";let qm=On;const IT=!1,Ca=class Ca{constructor(e,t,s){this.topbar=e,this.chat=t,this.managers=s,this.pinnedMaxMid=0,this.pinnedMid=0,this.pinnedIndex=-1,this.wasPinnedIndex=0,this.wasPinnedMediaIndex=0,this.locked=!1,this.waitForScrollBottom=!1,this.count=0,this.mids=[],this.offsetIndex=0,this.loading=!1,this.loadedBottom=!1,this.loadedTop=!1,this.hidden=!1,this.listenerSetter=new Ut,this.log=ri("PM"),this.debug=!0,this.isStatic=!1;const i=new hS("pinned-message");this.pinnedMessageContainer=new Fl({topbar:e,chat:t,listenerSetter:this.listenerSetter,className:"message",divAndCaption:i,onClose:async()=>(await s.appPeersManager.canPinMessage(this.chat.peerId)?ee.createPopup(Zc,this.chat.peerId,this.pinnedMid,!0):ee.createPopup(Zc,this.chat.peerId,0,!0),!1),floating:IT,height:52}),this.pinnedMessageBorder=new ST,i.border.replaceWith(this.pinnedMessageBorder.render(1,0)),this.animatedSubtitle=new wl,i.subtitle.append(this.animatedSubtitle.container),this.animatedMedia=new wl,this.animatedMedia.container.classList.add("pinned-message-media-container"),i.content.prepend(this.animatedMedia.container),this.animatedCounter=new qm(!0),i.title.append(M("PinnedMessage")," ",this.animatedCounter.container);const n=this.pinnedMessageContainer.btnClose.cloneNode(!0);this.pinnedMessageContainer.attachOnCloseEvent(n),i.container.prepend(n),this.btnOpen=it("pinlist pinned-container-close pinned-message-pinlist",{noRipple:!0}),this.pinnedMessageContainer.wrapperUtils.prepend(this.btnOpen),N(this.btnOpen,a=>{oe(a),this.topbar.openPinned(!0)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(I)("peer_pinned_messages",({peerId:a})=>{a===this.chat.peerId&&(this.hidden&&this.pinnedMessageContainer.toggle(this.hidden=!1),this.loadedTop=this.loadedBottom=!1,this.pinnedIndex=-1,this.pinnedMid=0,this.count=0,this.mids=[],this.offsetIndex=0,this.pinnedMaxMid=0,this.setCorrectIndex(0))}),this.listenerSetter.add(I)("peer_pinned_hidden",({peerId:a})=>{a===this.chat.peerId&&this.pinnedMessageContainer.toggle(this.hidden=!0)}),this.setPinnedMessage=ii(()=>this._setPinnedMessage(),100,!0,!0),this.setCorrectIndexThrottled=ma(this.setCorrectIndex.bind(this),100,!1),this.isStatic=!this.chat.isPinnedMessagesNeeded()}destroy(){this.animatedMedia.destroy(),this.animatedSubtitle.destroy(),this.animatedCounter.destroy(),this.pinnedMessageContainer.container.remove(),this.pinnedMessageContainer.toggle(!0),this.listenerSetter.removeAll(),this.unsetScrollDownListener(!1)}setCorrectIndex(e){if(this.isStatic||(this.debug&&this.log("setCorrectIndex",e),this.locked||this.hidden)||(this.loadedBottom||this.loadedTop)&&!this.count)return;const t=this.chat.bubbles.getBubbleByPoint("bottom");if(!t)return;const s=t.dataset.mid;s!==void 0&&this.testMid(+s,e)}testMid(e,t){if(this.isStatic||this.hidden)return;let s=this.mids.findIndex(n=>n<=e);if(s!==-1&&!this.isNeededMore(s))s+=this.offsetIndex;else if(this.loadedTop&&e<this.mids[this.mids.length-1])s=this.mids.length-1+this.offsetIndex;else return this.getCurrentIndexPromise??(this.getCurrentIndexPromise=this.getCurrentIndex(e,t!==void 0));if(this.pinnedIndex!==s)return this.waitForScrollBottom&&t!==void 0&&(this.pinnedIndex===0||this.pinnedIndex>s)?void 0:(this.pinnedIndex=s,this.pinnedMid=this.mids.find(n=>n<=e)||this.mids[this.mids.length-1],this.setPinnedMessage())}isNeededMore(e){return this.count>Ca.LOAD_COUNT&&(!this.loadedBottom&&e<=Ca.LOAD_OFFSET||!this.loadedTop&&this.count-1-e<=Ca.LOAD_OFFSET)}async getCurrentIndex(e,t=!0){if(!this.loading){this.loading=!0;try{const s=this.debug?this.log.bindPrefix("getCurrentIndex"):void 0;s&&s("start",e,t);let i=!1;const n=[this.managers.appMessagesManager.getHistory({peerId:this.chat.peerId,inputFilter:{_:"inputMessagesFilterPinned"},offsetId:e,limit:Ca.LOAD_COUNT,backLimit:Ca.LOAD_COUNT,threadId:this.chat.threadId,needRealOffsetIdOffset:!0}).then(c=>(i=!0,c))];if(!this.pinnedMaxMid){const c=this.managers.appMessagesManager.getPinnedMessage(this.chat.peerId,this.chat.threadId).then(d=>{d.maxId&&(this.pinnedMaxMid=d.maxId,!i&&t&&(this.mids=[this.pinnedMaxMid],this.count=d.count,this.pinnedIndex=0,this.pinnedMid=this.mids[0],this.setPinnedMessage()))});n.push(c)}const a=(await Promise.all(n))[0],r=a.history;let l=r.findIndex(c=>c<=e);l===-1&&(l=r.length),this.offsetIndex=Math.max(0,a.offsetIdOffset)?a.offsetIdOffset-l:0,this.mids=r.slice(),this.count=a.count,this.count||this.pinnedMessageContainer.toggle(!0),this.loadedTop=this.offsetIndex+this.mids.length===this.count,this.loadedBottom=!this.offsetIndex,s&&s("result",e,a,l,this.offsetIndex,this.loadedTop,this.loadedBottom)}catch(s){this.log.error("getCurrentIndex error",s)}this.loading=!1,this.locked?this.testMid(e):t&&this.setCorrectIndex(0),this.getCurrentIndexPromise=void 0}}setScrollDownListener(){this.waitForScrollBottom=!0,this.scrollDownListenerSetter||(this.scrollDownListenerSetter=new Ut,CT(this.chat.bubbles.scrollable.container,"bottom",()=>{this.unsetScrollDownListener()},this.scrollDownListenerSetter))}unsetScrollDownListener(e=!0){this.waitForScrollBottom=!1,this.scrollDownListenerSetter&&(this.scrollDownListenerSetter.removeAll(),this.scrollDownListenerSetter=void 0),e&&this.setCorrectIndex(0)}async handleFollowingPinnedMessage(){this.locked=!0,this.debug&&this.log("handleFollowingPinnedMessage");try{this.setScrollDownListener();const e=this.chat.setPeerPromise;e instanceof Promise&&await e,await As(),this.getCurrentIndexPromise&&await this.getCurrentIndexPromise,this.debug&&this.log("handleFollowingPinnedMessage: unlock"),this.locked=!1}catch(e){this.log.error("handleFollowingPinnedMessage error:",e),this.locked=!1,this.waitForScrollBottom=!1,this.setCorrectIndex(0)}}followPinnedMessage(e){this.chat.getMessage(e)&&(this.chat.setMessageId({lastMsgId:e}),(this.chat.setPeerPromise||Promise.resolve()).then(()=>{this.handleFollowingPinnedMessage(),this.testMid(this.pinnedIndex>=this.count-1?this.pinnedMaxMid:e-1)}))}async _setPinnedMessage(){const e=this.count;if(e){const t=this.pinnedIndex,s=this.chat.getMessage(this.pinnedMid),i=t===0;this.animatedCounter.container.classList.toggle("is-last",i),i||this.animatedCounter.setCount(e-t),this.pinnedMessageContainer.toggle(!1);const n=t>this.wasPinnedIndex;this.debug&&this.log("setPinnedMessage: fromTop",n,t,this.wasPinnedIndex);const a=this.animatedSubtitle.getRow(t),r=this.animatedMedia.getRow(t);r.classList.add("pinned-message-media");const l=[],c=await wf({titleEl:null,subtitleEl:a,message:s,mediaEl:r,loadPromises:l,animationGroup:this.chat.animationGroup,textColor:"primary-text-color",canTranslate:!s.pFlags.out,middleware:this.animatedSubtitle.getRow(t).middlewareHelper.get()});await Promise.all(l),this.pinnedMessageContainer.container.classList.toggle("is-media",c),this.animatedSubtitle.animate(t,this.wasPinnedIndex),c?(this.animatedMedia.animate(t,this.wasPinnedMediaIndex),this.wasPinnedMediaIndex=t):this.animatedMedia.clearRows(),this.pinnedMessageBorder.render(e,e-t-1),this.wasPinnedIndex=t,this.pinnedMessageContainer.container.dataset.mid=""+s.mid}else this.pinnedMessageContainer.toggle(!0),this.wasPinnedIndex=0;this.pinnedMessageContainer.container.classList.toggle("is-many",this.count>1)}};Ca.LOAD_COUNT=50,Ca.LOAD_OFFSET=5;let cu=Ca;function Mf(o){return"+"+_l(o).formatted}class Qm extends Dt{async init(){const{peerId:e}=this,t=e.toUserId();this.container.classList.add("edit-peer-container","edit-contact-container");const[s,i]=await Promise.all([this.managers.appUsersManager.isContact(t),this.managers.appPrivacyManager.getPrivacy("inputPrivacyKeyPhoneNumber")]),n=!s;this.setTitle(n?"AddContactTitle":"Edit");{const a=new Pe({noDelimiter:!0}),r=[],l=document.createElement("div");if(l.classList.add("input-wrapper"),this.nameInputField=new _t({label:"FirstName",name:"contact-name",maxLength:70,required:!0}),this.lastNameInputField=new _t({label:"LastName",name:"contact-lastname",maxLength:70}),t){const c=await this.managers.appUsersManager.getUser(t);n?(this.nameInputField.setDraftValue(c.first_name),this.lastNameInputField.setDraftValue(c.last_name)):(this.nameInputField.setOriginalValue(c.first_name),this.lastNameInputField.setOriginalValue(c.last_name))}if(l.append(this.nameInputField.container,this.lastNameInputField.container),r.push(this.nameInputField,this.lastNameInputField),this.editPeer=new kd({peerId:e,inputFields:r,listenerSetter:this.listenerSetter,doNotEditAvatar:!0,middleware:this.middlewareHelper.get()}),this.content.append(this.editPeer.nextBtn),e){const c=document.createElement("div");c.classList.add("avatar-edit"),c.append(this.editPeer.avatarElem.node);const d=new pt({text:"Notifications"});d.input.addEventListener("change",p=>{p.isTrusted&&this.managers.appMessagesManager.togglePeerMute({peerId:e})}),this.listenerSetter.add(I)("notify_settings",async p=>{if(p.peer._!=="notifyPeer")return;const m=at(p.peer.peer);if(m===m){const g=!await this.managers.appNotificationsManager.isMuted(p.notify_settings);g!==d.checked&&(d.checked=g)}});const h=document.createElement("div");h.classList.add("profile-name"),h.append(new Rt({peerId:e}).element);const u=document.createElement("div");if(u.classList.add("profile-subtitle"),u.append(M("EditContact.OriginalName")),a.content.append(c,h,u,l),n){const p=await this.managers.appUsersManager.getUser(t),m=new ve({icon:"phone",titleLangKey:p.phone?void 0:"MobileHidden",title:p.phone?Mf(p.phone):void 0,subtitleLangKey:p.phone?"Phone":"MobileHiddenExceptionInfo",subtitleLangArgs:p.phone?void 0:[new Rt({peerId:e}).element]});a.content.append(m.container)}else{const p=new ve({checkboxField:d,withCheckboxSubtitle:!0,listenerSetter:this.listenerSetter}),m=!await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:e,respectType:!1});d.checked=m,a.content.append(p.container)}}else a.content.append(l);this.scrollable.append(a.container)}if(n){if(i.some(a=>a._==="privacyValueDisallowAll")&&!i.some(a=>a._==="privacyValueAllowUsers"&&a.users.includes(t))){const a=new Pe({caption:"NewContact.Exception.ShareMyPhoneNumber.Desc",captionArgs:[await Oe({peerId:this.peerId})]}),r=this.sharePhoneCheckboxField=new pt({text:"NewContact.Exception.ShareMyPhoneNumber",checked:!0}),l=rr(r);a.content.append(l.container),this.scrollable.append(a.container)}}else{const a=new Pe,r=ze("btn-primary btn-transparent danger",{icon:"delete",text:"PeerInfo.DeleteContact"});N(r,()=>{ee.createPopup(Ss,"popup-delete-contact",{peerId:e,titleLangKey:"DeleteContact",descriptionLangKey:"AreYouSureDeleteContact",buttons:fr([{langKey:"Delete",callback:()=>{const l=jt([r],!0);this.managers.appUsersManager.deleteContacts([t]).then(()=>{this.close()},()=>{l()})},isDanger:!0}])}).show()},{listenerSetter:this.listenerSetter}),a.content.append(r),this.scrollable.append(a.container)}N(this.editPeer.nextBtn,async()=>{this.editPeer.nextBtn.disabled=!0,this.managers.appUsersManager.addContact(t,this.nameInputField.value,this.lastNameInputField.value,(await this.managers.appUsersManager.getUser(t)).phone,this.sharePhoneCheckboxField?.checked).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()})},{listenerSetter:this.listenerSetter})}}const LT="assets/audio/";class eC{constructor(e){this.assets=e,this.tempId=0}playSound(e,t=!1){++this.tempId,this.assetName=e;try{const s=this.createAudio();s.autoplay=!0,s.src=LT+e,s.loop=t,wi(s)}catch(s){console.error("playSound",e,s)}}playSoundIfDifferent(e,t){this.assetName!==e&&this.playSound(e,t)}createAudio(){let{audio:e}=this;return e||(e=this.audio=new Audio,wi(e),e)}stopSound(){this.audio&&this.audio.pause()}cancelDelayedPlay(){++this.tempId}playSoundWithTimeout(e,t,s){const i=++this.tempId;setTimeout(()=>{this.tempId===i&&this.playSound(e,t)},s)}}let PT;function MT(){return PT??(PT=new eC(["group_call_connect.mp3","group_call_end.mp3","group_call_start.mp3","voip_onallowtalk.mp3"]))}function ET(o){return(!!navigator?.mediaDevices?.getSupportedConstraints())[o]}function tC(){const o={channelCount:2};return["noiseSuppression","echoCancellation","autoGainControl"].forEach(t=>{ET(t)&&(o[t]=!0)}),o}function sC(o){const e={video:{width:{max:1920},height:{max:1080},frameRate:{max:30}}};return o||(e.audio=!0),e}async function iC(o){const e=await navigator.mediaDevices.getDisplayMedia(o),t=e.getVideoTracks()[0];return t.contentHint="text",e}async function dp(o,e){const t=await navigator.mediaDevices.getUserMedia(o);return t.getTracks().forEach(s=>{s.enabled=!e}),t}window.getStream=dp;function nC(){const o={main:{},screen:{}};return async e=>{const{isScreen:t,constraints:s}=e,i=o[t?"screen":"main"];let n=i[s.audio?"audio":"video"];n||(n=(t?iC:dp)(s,e.muted),s.audio&&!i.audio&&(i.audio=n.finally(()=>i.audio=void 0)),s.video&&!i.video&&(i.video=n.finally(()=>i.video=void 0)));try{return await n}catch(a){throw a}}}window.getStreamCached=nC;function Ef(){return{width:{min:1280,max:1920},height:{min:720,max:1080},frameRate:{min:24,max:30}}}function hp(o){o.stop(),Sd(o,"ended")}const _T=50,aC=100,fv=1,kT=2;class Ym{constructor(e=`\r
`){this.joiner=e,this.lines=[],this.newLine=[]}add(...e){return this.lines.push(...e),this}push(e){return this.newLine.push(e),this}addJoined(e=""){return this.add(this.newLine.join(e)),this.newLine=[],this}join(){return this.lines.join(this.joiner)}finalize(){return this.join()+this.joiner}}function _f(o){return o<<0}function yv(o){return o>>>0}function TT(o,e=3){if(!o)return 0;const{length:t}=o;let s=0;for(let n=0;n<t;++n)s+=o[n]*o[n];const i=Math.sqrt(s/t)/255;return Math.min(1,i*e)}const rC="9";function up(o){return o==="screencast"?"video":o}function xT(o){const e=[];return e.push("a=candidate:"),e.push(`${o.foundation} ${o.component} ${o.protocol.toUpperCase()} ${o.priority} ${o.ip} ${o.port} typ ${o.type}`),o["rel-addr"]!==void 0&&e.push(` raddr ${o["rel-addr"]} rport ${o["rel-port"]}`),e.push(` generation ${o.generation}`),e.join("")}function oC(o){return o==="application"?"DTLS/SCTP":"UDP/TLS/RTP/SAVPF"}function lC(o,e=rC,t){const s=oC(o);return`m=${up(o)} ${e} ${s} ${t.join(" ")}`}class pp extends Ym{addCandidate(e){return this.add(xT(e))}addHeader(e,t){const s=t.join(" ");return this.add("v=0",`o=- ${e} 2 IN IP4 0.0.0.0`,"s=-","t=0 0","a=extmap-allow-mixed",`a=group:BUNDLE ${s}`,"a=ice-options:trickle","a=msid-semantic:WMS *")}addTransport(e,t){this.add(`a=ice-ufrag:${e.ufrag}`,`a=ice-pwd:${e.pwd}`,"a=ice-options:trickle");for(const s of e.fingerprints)this.add(`a=fingerprint:${s.hash} ${s.fingerprint}`,`a=setup:${s.setup}`);if(!t&&e.candidates)for(const s of e.candidates)this.addCandidate(s);return this}addSsrc(e){let t="stream",{type:s,sourceGroups:i}=e;const n=yv(e.source);t+=n,s+=n;const a=()=>{this.add(`a=msid:${t} ${s}`)},r=l=>{this.add(`a=ssrc:${l} cname:${t}`,`a=ssrc:${l} msid:${t} ${s}`,`a=ssrc:${l} mslabel:${t}`,`a=ssrc:${l} label:${s}`)};return a(),i?.length?i.forEach(l=>{if(l.sources.length){const c=l.sources.map(yv);this.add(`a=ssrc-group:${l.semantics} ${c.join(" ")}`),c.forEach(r)}}):r(n),this}addSsrcEntry(e,t,s){const i=(...f)=>this.add(...f),{type:n,mid:a,direction:r,port:l}=e,c=t.transport,d=n==="application",h=d?void 0:t[n],u=r==="inactive";if(e.shouldBeSkipped(s))return i(`m=${up(n)} 0 ${oC(n)} 0`,"c=IN IP4 0.0.0.0","a=inactive",`a=mid:${a}`);const p=d?[{id:5e3}]:h["payload-types"],m=p.map(f=>f.id);i(lC(n,l,m),"c=IN IP4 0.0.0.0",`a=rtcp:${l} IN IP4 0.0.0.0`),c["rtcp-mux"]&&i("a=rtcp-mux"),i(`a=mid:${a}`);let g=r;if(r!=="sendrecv"&&s&&!(u||d)&&(g=r==="sendonly"?"recvonly":"sendonly"),i(`a=${g}`),this.addTransport(c),d)i(`a=sctpmap:${p[0].id} webrtc-datachannel 256`);else{const f=h["rtp-hdrexts"];f?.length&&f.forEach(y=>{i(`a=extmap:${y.id} ${y.uri}`)}),p.forEach(y=>{i(`a=rtpmap:${y.id} ${y.name}/${y.clockrate}${y.channels&&y.channels>1?`/${y.channels}`:""}`);const v=y.parameters;if(Array.isArray(v))v.length&&console.error("parameters is array???",v);else if(v&&Object.keys(v).length){const b=[];for(const S in v)b.push(`${S}=${v[S]}`);i(`a=fmtp:${y.id} ${b.join(";")}`)}const w=y["rtcp-fbs"];w?.length&&w.forEach(b=>{i(`a=rtcp-fb:${y.id} ${b.type}${b.subtype?" "+b.subtype:""}`)})})}return e.source&&(g==="sendonly"||g==="sendrecv")&&this.addSsrc(e),this}addConference(e){const{conference:t,entries:s,bundle:i,isAnswer:n}=e;this.addHeader(t.sessionId,i),Uh&&this.addTransport(t.transport);for(const a of s)this.addSsrcEntry((n?a.recvEntry||a.sendEntry:a.sendEntry||a.recvEntry)||a,t,n);return this}static fromConference(e){return new pp().addConference(e).finalize()}}class AT{constructor(e,t){const s=this.streamSource=e.createMediaStreamSource(t),i=this.analyser=e.createAnalyser();this.gain=e.createGain(),i.minDecibels=-100,i.maxDecibels=-30,i.smoothingTimeConstant=.05,i.fftSize=1024,s.connect(i)}}const Mc=class Mc{constructor(e){this.interval=e,this.getAmplitude=t=>{const{streamAnalyser:s,stream:i,track:n,source:a,type:r}=t,l=s.analyser;if(!l)return;const c=new Uint8Array(l.frequencyBinCount);l.getByteFrequencyData(c);const d=TT(c);return{type:r,source:a,stream:i,track:n,value:d}},this.analyse=()=>{const t=this.counter%3===0,n=(t?this.items:this.items.filter(a=>a.type==="input")).filter(a=>a.kind==="audio").slice(0,_T).map(this.getAmplitude);++this.counter>=1e3&&(this.counter=0),Mc.ANALYSER_LISTENER.dispatchEvent("amplitude",{amplitudes:n,type:t?"all":"input"})},this.context=new(window.AudioContext||window.webkitAudioContext),this.items=[],this.outputStream=new MediaStream,this.inputStream=new MediaStream,this.counter=0,this.log=ri("SM"),this.direction="sendonly",this.canCreateConferenceEntry=!0,this.types=["audio","video"]}addStream(e,t){e.getTracks().forEach(s=>{this.addTrack(e,s,t)})}addTrack(e,t,s){this.log("addTrack",s,t,e);const{context:i,items:n,inputStream:a,outputStream:r}=this,l=t.kind,c=Mc.getSource(e,s);switch(s){case"input":{a?a.addTrack(t):this.inputStream=e;break}case"output":{for(let d=0;d<n.length;++d){const{track:h,type:u,source:p}=n[d];if(p===c&&u==="input"){n.splice(d,1),r.removeTrack(h);break}}l!=="video"&&r.addTrack(t);break}}this.finalizeAddingTrack({type:s,source:c,stream:e,track:t,kind:l,streamAnalyser:l==="audio"?new AT(i,e):void 0}),l==="audio"&&this.interval&&this.changeTimer()}finalizeAddingTrack(e){const{track:t}=e;t.addEventListener("ended",()=>{this.removeTrack(t)},{once:!0}),this.items.push(e)}hasInputTrackKind(e){return this.items.find(t=>t.type==="input"&&t.kind===e)}static getSource(e,t){return t==="input"?e.source||e.id:""+_f(+e.id.substring(6))}removeTrack(e){this.log("removeTrack",e);const{items:t}=this;let s=!1;for(let i=0,n=t.length;!s&&i<n;++i){const{track:a,type:r}=t[i];switch(r){case"output":{a===e&&(t.splice(i,1),this.outputStream.removeTrack(e),s=!0);break}case"input":{a===e&&(t.splice(i,1),this.inputStream.removeTrack(e),s=!0);break}}}e.kind==="audio"&&this.interval&&this.changeTimer()}replaceInputAudio(e,t){this.removeTrack(t),this.addStream(e,"input")}changeTimer(){this.timer!==void 0&&clearInterval(this.timer),this.items.length&&(this.timer=window.setInterval(this.analyse,this.interval))}appendToConference(e){if(this.locked)return;const{inputStream:t,direction:s,canCreateConferenceEntry:i}=this,n={direction:s,streams:[t]},a=this.types.map(l=>[l,n]),r=t.getTracks();for(const[l,c]of a){let d=e.findEntry(f=>f.direction===s&&f.type===l);if(!d){if(!i)continue;d=e.createEntry(l)}let{transceiver:h}=d;h||(h=d.createTransceiver(e.connection,c)),d.direction!==h.direction&&(h.direction=d.direction);const u=up(l),p=r.findIndex(f=>f.kind===u),m=p!==-1?r.splice(p,1)[0]:void 0,g=h.sender;g.track!==m&&g.replaceTrack(m).catch(f=>{this.log.error(f)})}}stop(){try{this.inputStream.getTracks().concat(this.outputStream.getTracks()).forEach(t=>{hp(t)})}catch(e){this.log.error(e)}}};Mc.ANALYSER_LISTENER=new Si;let oo=Mc;class cC extends Si{constructor(){super(!1);const e=this.player=document.createElement("div");e.classList.add("call-player"),e.style.display="none",document.body.append(e),this.elements=new Map;const t=this.audio=new Audio;t.autoplay=!0,t.volume=1,this.player.append(t),this.elements.set("audio",t),this.fixSafariAudio(),this.getStream=nC()}get isSharingAudio(){return!!this.streamManager.hasInputTrackKind("audio")}get isSharingVideo(){return!!this.streamManager.hasInputTrackKind("video")}fixSafariAudio(){wi(this.audio)}requestAudioSource(e){return this.requestInputSource(!0,!1,e)}requestInputSource(e,t,s){const{streamManager:i}=this;if(i){const a=!e||this.isSharingAudio,r=!t||this.isSharingVideo;if(a&&r)return Promise.resolve()}const n={audio:e&&tC(),video:t&&Ef()};return this.getStream({constraints:n,muted:s}).then(a=>{this.onInputStream(a)})}requestScreen(){return this.getStream({isScreen:!0,constraints:sC(!0)}).then(e=>{this.onInputStream(e)})}getElement(e){return this.elements.get(""+e)}cleanup(){this.player.textContent="",this.player.remove(),this.elements.clear(),this.streamManager.stop(),super.cleanup()}onTrack(e){this.tryAddTrack({stream:e.streams[0],track:e.track,type:"output"})}saveInputVideoStream(e,t){const s=e.getVideoTracks()[0];this.tryAddTrack({stream:e,track:s,type:"input",source:t||"main"})}tryAddTrack({stream:e,track:t,type:s,source:i}){i||(i=oo.getSource(e,s)),this.log("tryAddTrack",e,t,s,i);const n=s==="output",{player:a,elements:r,streamManager:l}=this,c=t.kind,d=c==="video",h=d?i:c;let u=r.get(h);d&&t.addEventListener("ended",()=>{this.log("[track] onended"),r.delete(h)},{once:!0}),n&&l.addTrack(e,t,s);const p=d?e:l.outputStream;if(u)u.paused&&wi(u),u.srcObject=p;else{if(u=document.createElement(c),u.autoplay=!0,u.srcObject=p,u.volume=1,u.sinkId!=="undefined"){const{outputDeviceId:m}=this;m&&u.setSinkId(m)}d?(u.setAttribute("playsinline","true"),u.muted=!0):a.appendChild(u),r.set(h,u)}return i}setMuted(e){this.streamManager.inputStream.getAudioTracks().forEach(t=>{t?.kind==="audio"&&(t.enabled=e===void 0?!t.enabled:!e)})}onInputStream(e){if(this.isClosing)e.getTracks().forEach(t=>{hp(t)});else{e.getVideoTracks().length&&this.saveInputVideoStream(e,"main");const{streamManager:s,description:i}=this;s.addStream(e,"input"),i&&s.appendToConference(i)}}}function FT(o,e,t){t||(t=ri("RTCDataChannel"));const s=o.createDataChannel("data",e);return s.addEventListener("message",i=>{t("onmessage",i)}),s.addEventListener("open",()=>{t("onopen")}),s.addEventListener("close",()=>{t("onclose")}),s.log=t,s}function RT(o,e){e||(e=ri("RTCPeerConnection")),e("constructor");const t=new RTCPeerConnection(o);return t.addEventListener("track",s=>{e("ontrack",s)}),t.addEventListener("signalingstatechange",()=>{e("onsignalingstatechange",t.signalingState)}),t.addEventListener("connectionstatechange",()=>{e("onconnectionstatechange",t.connectionState)}),t.addEventListener("negotiationneeded",()=>{e("onnegotiationneeded",t.signalingState)}),t.addEventListener("icecandidate",s=>{e("onicecandidate",s)}),t.addEventListener("iceconnectionstatechange",()=>{e("oniceconnectionstatechange",t.iceConnectionState)}),t.addEventListener("datachannel",()=>{e("ondatachannel")}),t.log=e,{connection:t}}class mp{constructor(e,t){this.mid=e,this.type=t,this.port=rC}setDirection(e){return this.originalDirection||(this.originalDirection=e),this.direction=e}setPort(e){return this.port=e}setEndpoint(e){return this.endpoint=e}setPeerId(e){return this.peerId=e}createTransceiver(e,t){return t?.direction&&this.setDirection(t.direction),this.transceiver=e.addTransceiver(up(this.type),t)}setSource(e){let t;if(Array.isArray(e)){if(!e[0])return;t=e,e=t[0].sources[0]}return this.sourceGroups=t,this.source=e}shouldBeSkipped(e){return e&&this.direction==="inactive"}}function Th(o,e,t){let s;if(Array.isArray(e)){if(!e[0])return;s=e,e=s[0].sources[0]}return{endpoint:t,type:o,source:e,sourceGroups:s}}class DT{constructor(e){this.connection=e,this.sessionId=""+Date.now(),this.maxSeenId=-1,this.entries=[],this.entriesByMid=new Map,this.entriesBySource=new Map,this.entriesByPeerId=new Map}setData(e){return It(this,e)}createEntry(e){const t=""+ ++this.maxSeenId,s=new mp(t,e);return this.entries.push(s),this.entriesByMid.set(t,s),s}deleteEntry(e){us(this.entries,e),this.entriesByMid.delete(e.mid),this.entriesBySource.delete(e.source);const t=this.entriesByPeerId.get(e.peerId);t&&(t.delete(e),t.size||this.entriesByPeerId.delete(e.peerId))}setEntrySource(e,t){e.setSource(t),this.entriesBySource.set(e.source,e)}setEntryPeerId(e,t){e.setPeerId(t);let s=this.entriesByPeerId.get(t);s||this.entriesByPeerId.set(t,s=new Set),s.add(e)}findEntry(e){return this.entries.find(e)}findFreeSendRecvEntry(e,t){let s=this.entries.find(i=>i.direction==="sendrecv"&&i.type===e&&!(t?i.sendEntry:i.recvEntry));return s||(s=this.createEntry(e),s.setDirection("sendrecv")),s}getEntryByMid(e){return this.entriesByMid.get(e)}getEntryBySource(e){return this.entriesBySource.get(e)}getEntriesByPeerId(e){return this.entriesByPeerId.get(e)}generateSdp(e){return pp.fromConference({conference:this,...e})}}class dC{constructor(e){It(this,e),this.log||(this.log=this.connection?.log||ri("CALL-CONNECTION-BASE")),this.sources={}}createPeerConnection(e){return this.connection||(this.connection=RT(e,this.log.bindPrefix("connection")).connection)}createDataChannel(e){return this.dataChannel||(this.dataChannel=FT(this.connection,e,this.log.bindPrefix("data")))}createDescription(){return this.description||(this.description=new DT(this.connection))}appendStreamToConference(){return this.streamManager.appendToConference(this.description)}closeConnection(){const{connection:e}=this;if(e)try{e.log("close"),e.close()}catch(t){this.log.error(t)}}closeConnectionAndStream(e){this.closeConnection(),e&&this.streamManager.stop()}negotiate(){const e=this.negotiating;return e||(this.negotiating=this.negotiateInternal().finally(()=>{this.negotiating=void 0}))}sendDataChannelData(e){this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(e))}}function BT(o,e){const t=i=>{const n={};return i.attributes.get("extmap").forEach(r=>{const l=r.key.split("/",1)[0];n[l]=r.value}),n};["audio","video"].filter(i=>e[i]).map(i=>[e[i],i]).forEach(([i,n])=>{const a=o.find(l=>l.mediaType===n);if(!a)return;const r=t(a);bi(i["rtp-hdrexts"],(l,c,d)=>{r[l.id]!==l.uri&&(d.splice(c,1),console.log("[sdp] filtered extmap:",l,c,n))})})}var id,nd;class NT{constructor(e,t){ds(this,id,void 0);ds(this,nd,void 0);Ft(this,id,e),Ft(this,nd,t)}get session(){return Bt(this,id)}get media(){return Bt(this,nd)}get bundle(){return this.session.lines.find(t=>t.parsed?.key==="group").value.split(" ").slice(1)}toString(){return this.session.lines.concat(...this.media.map(e=>e.lines)).map(e=>e.toString()).join(`\r
`)+`\r
`}}id=new WeakMap,nd=new WeakMap;function kf(o,e,t){const s=o.split(e),i=[];for(;t>0&&s.length;)i.push(s.shift()),--t;return s.length&&i.push(s.join(e)),i}var el,ad,rd;class OT{constructor(e,t){ds(this,el,void 0);ds(this,ad,void 0);ds(this,rd,void 0);Ft(this,el,new Set),Ft(this,ad,e),Ft(this,rd,t)}generate(){const e=Bt(this,ad),t=Bt(this,rd),s=Bt(this,el),i=t-e+1;let n=Math.floor(e+i*Math.random()),a=0;for(;s.has(n);)if(n<t?++n:n=e,++a>=i)return null;return s.add(n),n}add(e){Bt(this,el).add(e)}}el=new WeakMap,ad=new WeakMap,rd=new WeakMap;var od,ld;class tm{constructor(e,t){ds(this,od,void 0);ds(this,ld,void 0);Ft(this,od,e),Ft(this,ld,t)}get key(){return Bt(this,od)}get value(){return Bt(this,ld)}}od=new WeakMap,ld=new WeakMap;var cd,dd,hd,ud;class vv{constructor(e,t,s,i){ds(this,cd,void 0);ds(this,dd,void 0);ds(this,hd,void 0);ds(this,ud,void 0);Ft(this,cd,e),Ft(this,dd,t),Ft(this,hd,s),Ft(this,ud,i)}get type(){return Bt(this,cd)}get port(){return Bt(this,dd)}get protocol(){return Bt(this,hd)}get ids(){return Bt(this,ud)}toString(){return this.type+" "+this.port+" "+this.protocol+" "+this.ids.join(" ")}}cd=new WeakMap,dd=new WeakMap,hd=new WeakMap,ud=new WeakMap;var pd,Wr,tl,sl;class UT{constructor(e,t){ds(this,pd,void 0);ds(this,Wr,void 0);ds(this,tl,void 0);ds(this,sl,void 0);if(Ft(this,pd,e),typeof t=="string"){if(Ft(this,Wr,t),e==="m"){const s=t.split(" ");Ft(this,tl,new vv(s[0],s[1],s[2],s.slice(3)))}else if(e==="a"){const s=kf(t,":",1);t=s[0],Ft(this,sl,s.length===1?new tm(t,null):new tm(t,s[1]))}}else t instanceof vv?(Ft(this,tl,t),Ft(this,Wr,t.toString())):t instanceof tm&&(Ft(this,sl,t),Ft(this,Wr,t.value?`${t.key}:${t.value}`:t.key))}get key(){return Bt(this,pd)}get value(){return Bt(this,Wr)}get parsed(){return Bt(this,sl)}get mediaLineParts(){return Bt(this,tl)}toString(){return`${this.key}=${this.value}`}}pd=new WeakMap,Wr=new WeakMap,tl=new WeakMap,sl=new WeakMap;var md,gd,fd,nr,il,nl;const sr=class sr{constructor(e,t,s=":",i=!1){ds(this,md,void 0);ds(this,gd,void 0);ds(this,fd,void 0);ds(this,nr,void 0);ds(this,il,void 0);ds(this,nl,void 0);Ft(this,md,e),Ft(this,gd,t),Ft(this,fd,s),Ft(this,il,i),Ft(this,nr,i?new Map:null),Ft(this,nl,i?[]:null)}get lines(){return Bt(this,gd)}get value(){return Bt(this,il)||!this.lines.length?null:this.lines[0]}get exists(){return!Bt(this,il)}get key(){return Bt(this,md)}get keys(){return sr.fill(this),Bt(this,nl)}forEach(e){sr.fill(this),Bt(this,nr).forEach(e)}get(e){return sr.fill(this),Bt(this,nr).get(e)||new sr(e,[],":",!0)}static fill(e){if(Bt(e,nr)!==null)return;const t=new Map;e.lines.forEach(i=>{const[n,a]=kf(i,Bt(e,fd),1),r=t.get(n)||[];t.set(n,[...r,a||""])});const s=Ft(e,nr,sr.makeAttributes(t));Ft(e,nl,Array.from(s.keys()))}static makeAttributes(e){const t=new Map;return e.forEach((s,i)=>{t.set(i,new sr(i,s))}),t}};md=new WeakMap,gd=new WeakMap,fd=new WeakMap,nr=new WeakMap,il=new WeakMap,nl=new WeakMap;let du=sr;var yd,al;const Jf=class Jf{constructor(e){ds(this,yd,void 0);ds(this,al,void 0);Ft(this,yd,e),Ft(this,al,new Map),Jf.fillAttributes(this)}get(e){return Bt(this,al).get(e)||new du(e,[]," ",!0)}static fillAttributes(e){const t=new Map;Bt(e,yd).forEach(s=>{if(s.key==="a"){const{key:i,value:n}=s.parsed;let a=t.get(i);a||(a=[],t.set(i,a)),a.push(n||"")}}),t.forEach((s,i)=>{Bt(e,al).set(i,new du(i,s," ",!1))})}};yd=new WeakMap,al=new WeakMap;let Xm=Jf;var vd,rl,jr,qr;class hC{constructor(e){ds(this,vd,void 0);ds(this,rl,void 0);ds(this,jr,void 0);ds(this,qr,void 0);Ft(this,vd,e),Ft(this,rl,e[0]),Ft(this,jr,Ft(this,qr,null))}get lines(){return Bt(this,vd)}get mediaLine(){return Bt(this,rl)}get mediaLineParts(){return Bt(this,rl).mediaLineParts}get mediaType(){return this.mediaLineParts.type}get direction(){if(!Bt(this,qr)){const e=this.attributes;let t;e.get("sendonly").exists?t="sendonly":e.get("recvonly").exists?t="recvonly":e.get("inactive").exists?t="inactive":t="sendrecv",Ft(this,qr,t)}return Bt(this,qr)}get isSending(){return this.direction==="sendrecv"||this.direction==="sendonly"}get isReceiving(){return this.direction==="sendrecv"||this.direction==="recvonly"}get attributes(){return Bt(this,jr)||Ft(this,jr,new Xm(this.lines)),Bt(this,jr)}get mid(){return this.attributes.get("mid").value}lookupAttributeKeys(e){const t={};for(const s in e){const i=this.attributes.get(s),n=!e[s];i?t[s]=n?i.lines:i.value:t[s]=n?[]:void 0}return t}}vd=new WeakMap,rl=new WeakMap,jr=new WeakMap,qr=new WeakMap;var bd,wd;class HT{constructor(e){ds(this,bd,void 0);ds(this,wd,void 0);Ft(this,bd,e),Ft(this,wd,e.filter(t=>t.key==="o").map(t=>t.value.split(" ")[1])[0])}get lines(){return Bt(this,bd)}get sessionId(){return Bt(this,wd)}}bd=new WeakMap,wd=new WeakMap;function hu(o){function e(){t?i.push(new hC(s)):t=new HT(s)}let t=null,s=[];const i=[];return o.split(/\r?\n/).forEach(n=>{if(!$T(n)){const a=hc(n);a.key==="m"&&(e(),s=[]),s.push(a)}}),e(),new NT(t,i)}function $T(o){return/^[\s\xa0]*$/.test(o)}function hc(o){const e=kf(o,"=",1);return new UT(e[0],e[1])}function VT(o){let e;return o.media.forEach((t,s)=>{if(t.mediaType==="video"&&t.isSending&&!t.attributes.get("ssrc-group").get("SIM").exists){e||(e=new OT(2,4294967295));const i=t.attributes.get("ssrc-group").get("FID").value.split(" "),n=t.lines;i.forEach(c=>e.add(+c));const a=[i[0],e.generate(),e.generate()],r=[i[1],e.generate(),e.generate()];n.push(hc("a=ssrc-group:SIM "+a.join(" ")));const l=t.attributes.get("ssrc").get(i[0]).lines;a.forEach((c,d)=>{const h=r[d];d>0&&(n.push(hc("a=ssrc-group:FID "+c+" "+h)),l.forEach(u=>{n.push(hc("a=ssrc:"+c+" "+u))}),l.forEach(u=>{n.push(hc("a=ssrc:"+h+" "+u))}))}),o.media[s]=new hC(n)}}),!!e}function GT(o){const e=o.map(t=>{const[s,...i]=t.split(" ");return{_:"groupCallParticipantVideoSourceGroup",semantics:s,sources:i.map(a=>_f(+a))}});return e.length?e:void 0}function uu(o,e){const t=e.lookupAttributeKeys({"ice-ufrag":!0,"ice-pwd":!0,fingerprint:!0,setup:!0,ssrc:!0,mid:!0,"ssrc-group":!1});if(!t.fingerprint){const r=o.session.lines.find(l=>l.parsed?.key==="fingerprint");t.fingerprint=r.parsed.value}const s=GT(t["ssrc-group"]),[i,n]=t.fingerprint.split(" ",2),a=t.ssrc&&_f(+t.ssrc.split(" ",1)[0]);return{raw:t,ufrag:t["ice-ufrag"],pwd:t["ice-pwd"],fingerprint:{fingerprint:n,setup:t.setup,hash:i},source:a,sourceGroups:s,mid:t.mid}}function zT(o){const{offer:e,data:t}=o,s=hu(e.sdp);let i=!1;if(o.skipAddingMulticast||(i=VT(s)||i),bi(s.media,(n,a,r)=>{if(n.isSending||n.mediaType==="application")return;const l=n.mediaLine,c=l.mediaLineParts;c.ids;const d=l.toString(),p=t[n.mediaType]["payload-types"].map(g=>""+g.id),m=lC(n.mediaType,void 0,p);if(d!==m){const g=uu(s,n),f={...t};f.transport=Wi(f.transport),f.transport.ufrag=g.ufrag,f.transport.pwd=g.pwd,f.transport.fingerprints=[g.fingerprint],f.transport.candidates=[];const y=new mp(g.mid,c.type);y.setPort(c.port),g.source&&y.setSource(g.sourceGroups||g.source),y.setDirection(n.direction);const v=new pp().addSsrcEntry(y,f).finalize(),w=hu(v).media[0];r[a]=w,i=!0}}),i){const n=s.toString();e.sdp=n}return{offer:e,sdp:s}}function KT(o,e){const t=uu(o,e),s=e.mediaType,i={source:t.source,sourceGroups:t.sourceGroups,type:s};t.fingerprint.setup="active";const n={fingerprints:[t.fingerprint],pwd:t.pwd,ssrc:t.source,"ssrc-groups":t.sourceGroups||[],ufrag:t.ufrag};return{params:{_:"dataJSON",data:JSON.stringify(n)},source:t.source,media:e,sourceGroups:t.sourceGroups,entry:i}}class WT extends dC{constructor(e){super(e),this.negotiateThrottled=ma(this.negotiate.bind(this),0,!1)}createPeerConnection(){return this.connection||super.createPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",iceCandidatePoolSize:0})}createDataChannel(){if(this.dataChannel)return this.dataChannel;const e=super.createDataChannel();return e.addEventListener("open",()=>{this.maybeUpdateRemoteVideoConstraints()}),e.addEventListener("close",()=>{this.updateConstraintsInterval&&(clearInterval(this.updateConstraintsInterval),this.updateConstraintsInterval=void 0)}),e}createDescription(){return this.description?this.description:super.createDescription()}appendStreamToConference(){super.appendStreamToConference()}async invokeJoinGroupCall(e,t,s){const{groupCall:i,description:n}=this,a=i.id,r=t.map(f=>{const y=KT(e,f);return this.sources[y.entry.type]=y.entry,y}),l=r.find(f=>f.media.mediaType==="audio"),c=r.find(f=>f.media.mediaType==="video");let{source:d,params:h}=l||{};const u=c||l,p={audio:l,video:c};if(n.entries.forEach(f=>{if(f.direction==="sendonly"){const y=p[f.type];if(!y)return;n.setEntrySource(f,y.sourceGroups||y.source),n.setEntryPeerId(f,I.myId)}}),h!==u.params){const f=JSON.parse(u.params.data);d?f.ssrc=d:delete f.ssrc,h={_:"dataJSON",data:JSON.stringify(f)}}const m=await this.managers.appGroupCallsManager.joinGroupCall(a,h,s),g=JSON.parse(m.params.data);return g.audio=g.audio||i.connections.main.description.audio,n.setData(g),BT(t,g),g}async negotiateInternal(){const{connection:e,description:t}=this,s=e.iceConnectionState==="new"&&!t.getEntryByMid("0").source,i=this.log.bindPrefix("startNegotiation");i("start");const n=await e.createOffer({iceRestart:!1});s&&this.dataChannel&&t.createEntry("application").setDirection("sendrecv");const{sdp:a,offer:r}=zT({offer:n,data:t});i("[sdp] setLocalDescription",r.sdp),await e.setLocalDescription(r);const l=a.media.filter(m=>m.mediaType!=="application"&&m.isSending);if(s)try{await this.invokeJoinGroupCall(a,l,this.options)}catch(m){this.log.error("[tdweb] joinGroupCall error",m)}const c=!0,d=[],h=a.bundle;bi(h,(m,g,f)=>{const y=t.getEntryByMid(m);y.shouldBeSkipped(c)&&(f.splice(g,1),d.push(y))});const u=a.media.map(m=>{const g=m.mid;let f=t.getEntryByMid(g);return f||(f=new mp(g,m.mediaType),f.setDirection("inactive")),f}),p={type:"answer",sdp:t.generateSdp({bundle:h,entries:u,isAnswer:c})};d.forEach(m=>{t.deleteEntry(m)}),i(`[sdp] setRemoteDescription signaling=${e.signalingState} ice=${e.iceConnectionState} gathering=${e.iceGatheringState} connection=${e.connectionState}`,p.sdp),await e.setRemoteDescription(p),i("end")}negotiate(){let e=this.negotiating;return e||(e=super.negotiate(),this.updateConstraints&&e.then(()=>{this.maybeUpdateRemoteVideoConstraints(),this.updateConstraints=!1}),this.options.type==="presentation"&&e.then(()=>{this.connection.getTransceivers().find(t=>{t.sender?.track?.kind==="video"&&t.sender.setParameters({...t.sender.getParameters(),degradationPreference:"maintain-resolution"})})}),e)}maybeUpdateRemoteVideoConstraints(){if(this.dataChannel.readyState!=="open")return;this.log("maybeUpdateRemoteVideoConstraints");const e={colibriClass:"ReceiverVideoConstraints",constraints:{},defaultConstraints:{maxHeight:0},onStageEndpoints:[]};for(const t of this.description.entries){if(t.direction!=="recvonly"||t.type!=="video")continue;const{endpoint:s}=t;e.onStageEndpoints.push(s),e.constraints[s]={minHeight:180,maxHeight:720}}this.sendDataChannelData(e),e.onStageEndpoints.length?this.updateConstraintsInterval||(this.updateConstraintsInterval=window.setInterval(this.maybeUpdateRemoteVideoConstraints.bind(this),5e3)):this.updateConstraintsInterval&&(clearInterval(this.updateConstraintsInterval),this.updateConstraintsInterval=void 0)}addInputVideoStream(e){this.groupCall.saveInputVideoStream(e,this.type),this.streamManager.addStream(e,"input"),this.appendStreamToConference()}}var hs=(o=>(o[o.UNMUTED=0]="UNMUTED",o[o.MUTED=1]="MUTED",o[o.MUTED_BY_ADMIN=2]="MUTED_BY_ADMIN",o[o.CONNECTING=3]="CONNECTING",o[o.CLOSED=4]="CLOSED",o))(hs||{});class Ar extends cC{constructor(e){super(),It(this,e),this.log||(this.log=ri("GROUP-CALL")),this.connections||(this.connections={}),this.isSpeakingMap||(this.isSpeakingMap=new Map),this.pinnedSources=[],this.participantsSsrcs=new Map,this.hadAutoPinnedSources=new Set,this.dispatchPinnedThrottled=ma(()=>{this.dispatchEvent("pinned",this.pinnedSource)},0,!1),this.addEventListener("state",t=>{t===hs.CLOSED&&this.cleanup()})}get connectionState(){return this.connections.main.connection.iceConnectionState}get state(){const{connectionState:e}=this;if(e==="closed")return hs.CLOSED;if(e!=="connected"&&(!Pi||e!=="completed"))return hs.CONNECTING;{const{participant:t}=this;return t.pFlags.can_self_unmute?t.pFlags.muted?hs.MUTED:hs.UNMUTED:hs.MUTED_BY_ADMIN}}get participants(){return this.managers.appGroupCallsManager.getCachedParticipants(this.id)}get isSharingScreen(){return!!this.connections.presentation}get pinnedSource(){return this.pinnedSources[this.pinnedSources.length-1]}get isMuted(){return this.state!==hs.UNMUTED}get isClosing(){const{state:e}=this;return e===hs.CLOSED}get streamManager(){return this.connections.main.streamManager}get description(){return this.connections.main.description}pinSource(e){us(this.pinnedSources,e),this.pinnedSources.push(e),this.dispatchPinnedThrottled()}unpinSource(e){this.hadAutoPinnedSources.delete(e),us(this.pinnedSources,e),this.dispatchPinnedThrottled()}unpinAll(){this.pinnedSources.length=0,this.dispatchPinnedThrottled()}async getParticipantByPeerId(e){return Tt===e?this.participant:(await this.participants).get(e)}toggleMuted(){return this.requestAudioSource(!0).then(()=>this.changeUserMuted(Tt))}async changeUserMuted(e,t){const s=await this.getParticipantByPeerId(e);return Tt===e&&s.pFlags.can_self_unmute&&(t=t===void 0?!s.pFlags.muted:t),this.editParticipant(s,{muted:t})}getElement(e){return super.getElement(e)}getVideoElementFromParticipantByType(e,t){let s;e.pFlags.self?s=t==="video"?"main":"presentation":s=e[t].source_groups[0].sources[0];const i=this.getElement(s);if(!i)return;const n=i.cloneNode();return n.srcObject=i.srcObject,{video:n,source:s}}createConnectionInstance(e){return this.connections[e.type]=new WT({groupCall:this,log:this.log.bindPrefix(e.type),managers:this.managers,...e})}changeRaiseHand(e){return this.editParticipant(this.participant,{raiseHand:e})}async startScreenSharingInternal(){try{const e="presentation",t=await iC(sC()),s=new oo,i=this.createConnectionInstance({streamManager:s,type:e,options:{type:e}});i.createPeerConnection().addEventListener("negotiationneeded",()=>{i.negotiate()}),t.getVideoTracks()[0].addEventListener("ended",()=>{this.connections.presentation&&this.stopScreenSharing()},{once:!0}),i.createDescription(),i.addInputVideoStream(t)}catch(e){this.log.error("start screen sharing error",e)}}startScreenSharing(){return this.startScreenSharingPromise??(this.startScreenSharingPromise=this.startScreenSharingInternal().finally(()=>{this.startScreenSharingPromise=void 0}))}stopScreenSharing(){const e=this.connections.presentation;return e?(delete this.connections.presentation,this.unpinSource("presentation"),e.closeConnectionAndStream(!0),delete this.participant.presentation,this.managers.appGroupCallsManager.saveApiParticipant(this.id,this.participant),this.managers.appGroupCallsManager.leaveGroupCallPresentation(this.id)):Promise.resolve()}toggleScreenSharing(){return this.isSharingScreen?this.stopScreenSharing():this.startScreenSharing()}async startVideoSharingInternal(){const e={video:Ef()};try{const t=await dp(e,!1);this.connections.main.addInputVideoStream(t),await this.editParticipant(this.participant,{videoPaused:!1,videoStopped:!1})}catch(t){this.log.error("startVideoSharing error",t,e)}}startVideoSharing(){return this.startVideoSharingPromise??(this.startVideoSharingPromise=this.startVideoSharingInternal().finally(()=>{this.startVideoSharingPromise=void 0}))}async stopVideoSharing(){const e=this.connections.main,t=e.streamManager.inputStream.getVideoTracks()[0];t&&(hp(t),e.streamManager.appendToConference(e.description),await this.editParticipant(this.participant,{videoStopped:!0}))}toggleVideoSharing(){return this.isSharingVideo?this.stopVideoSharing():this.startVideoSharing()}async hangUp(e=!1,t=!1,s=!1){for(const i in this.connections)this.connections[i].closeConnectionAndStream(!t);if(this.dispatchEvent("state",this.state),!s&&!t){const i=e||(this.joined?this.connections.main.sources.audio.source:void 0);this.managers.appGroupCallsManager.hangUp(this.id,i)}}tryAddTrack(e){const{description:t}=this,s=super.tryAddTrack(e);if(e.type==="output"){const i=t.getEntryBySource(+s);this.getParticipantByPeerId(i.peerId).then(n=>{n&&I.dispatchEvent("group_call_participant",{groupCallId:this.id,participant:n})})}return s}async editParticipant(e,t){if(Object.keys(t).length){if(e){const s=e.pFlags.self;if(s&&t.muted!==void 0&&!this.isSharingAudio&&(delete t.muted,!Object.keys(t).length))return;const i=t.muted;i!==void 0&&e.pFlags.self&&(i?e.pFlags.muted=!0:e.pFlags.can_self_unmute&&delete e.pFlags.muted),t.raiseHand!==void 0&&(t.raiseHand?e.raise_hand_rating="1":delete e.raise_hand_rating),s&&(t.videoStopped!==void 0&&(t.videoStopped?delete e.video:e.video=YT(this.connections.main.sources.video)),!e.pFlags.muted&&e.pFlags.can_self_unmute&&this.setMuted(!1),this.dispatchEvent("state",this.state))}return this.managers.appGroupCallsManager.editParticipant(this.id,e,t)}}onParticipantUpdate(e,t){const s=this.connections.main,{connection:i,description:n}=s,a=at(e.peer),r=!!e.pFlags.left,l=this.participantsSsrcs.get(a)||[];if(e.presentation&&!r){const{source:h}=Do(e,"video",e.presentation.source_groups,e.presentation.endpoint);this.hadAutoPinnedSources.has(h)||(this.hadAutoPinnedSources.add(h),this.pinSource(e.pFlags.self?"presentation":h))}if(e.pFlags.self){this.participant=e,s.sources.audio.source!==e.source&&this.hangUp();let h=!1;e.pFlags.can_self_unmute?e.pFlags.muted&&(h=!0):(this.stopScreenSharing(),this.stopVideoSharing(),h=!0),h&&this.setMuted(!0),t!==a&&this.dispatchEvent("state",this.state);return}const c=r?[]:QT(e);r?this.participantsSsrcs.delete(a):this.participantsSsrcs.set(a,c);const d=new Set;l.forEach(h=>{const u=h.source;if(!c.find(m=>m.source===u)){this.unpinSource(u);const m=n.getEntryBySource(u);m&&m.direction!=="inactive"&&(m.setDirection("inactive"),d.add(m.type))}}),c.forEach(h=>{let u=n.getEntryBySource(h.source);if(u){u.direction==="inactive"&&(u.setDirection(u.originalDirection),d.add(u.type));return}u=n.createEntry(h.type),n.setEntrySource(u,h.sourceGroups||h.source),n.setEntryPeerId(u,a),h.type==="video"&&u.setEndpoint(h.endpoint),u.createTransceiver(i,{direction:"recvonly"}),d.add(u.type)}),d.size&&(d.has("video")&&(s.updateConstraints=!0),s.negotiateThrottled())}}async function jT(o,e){const t={audio:tC(),video:e&&Ef()},s=new oo(aC);try{const i=await dp(t,o);s.addStream(i,"input")}catch(i){console.error("joinGroupCall getStream error",i,t),s.inputStream=new MediaStream}return s}const qT=!0;function QT(o){return[Do(o,"audio",o.source),o.video?.audio_source&&Do(o,"audio",o.video.audio_source),o.video&&Do(o,"video",o.video.source_groups,o.video.endpoint),o.presentation?.audio_source&&Do(o,"audio",o.presentation.audio_source),o.presentation&&Do(o,"video",o.presentation.source_groups,o.presentation.endpoint)].filter(Boolean)}function Do(o,e,t,s){return Th(e,t,s)}function YT(o,e){return o&&{_:"groupCallParticipantVideo",pFlags:{},endpoint:"",source_groups:o.sourceGroups,audio_source:e}}class XT extends Si{construct(e){this.managers=e,this.audioAsset=MT(),this.log=ri("GCC"),I.addEventListener("group_call_update",t=>{const{currentGroupCall:s}=this;s?.id===t.id&&(s.groupCall=t,t._==="groupCallDiscarded"&&s.hangUp(!1,!1,!0))}),I.addEventListener("group_call_participant",({groupCallId:t,participant:s})=>{const{currentGroupCall:i}=this;i?.id===t&&i.onParticipantUpdate(s)})}get groupCall(){return this.currentGroupCall}setCurrentGroupCall(e){this.currentGroupCall=e,e&&this.dispatchEvent("instance",e)}startConnectingSound(){this.stopConnectingSound(),this.audioAsset.playSoundWithTimeout("group_call_connect.mp3",!0,2500)}stopConnectingSound(){this.audioAsset.stopSound(),this.audioAsset.cancelDelayedPlay()}async joinGroupCall(e,t,s=qT,i,n){this.audioAsset.createAudio(),this.log(`joinGroupCall chatId=${e} id=${t} muted=${s} rejoin=${i}`);let a;return i?a=this.currentGroupCall.connections.main.streamManager:a=await jT(s,n),this.joinGroupCallInternal(e,t,a,s,i,n).then(()=>{const{currentGroupCall:r}=this;r.participants.then(l=>{this.currentGroupCall!==r||r.state===hs.CLOSED||l.forEach(c=>{c.pFlags.self||r.onParticipantUpdate(c)})})})}async joinGroupCallInternal(e,t,s,i,n=!1,a){const r=this.log.bindPrefix("joinGroupCallInternal");r("start",t);const l="main";let{currentGroupCall:c}=this;if(c&&n)c.handleUpdateGroupCallParticipants=!1,c.updatingSdp=!1,r("update currentGroupCall",t,c);else{c=new Ar({chatId:e,id:t,managers:this.managers}),c.fixSafariAudio(),c.addEventListener("state",u=>{this.currentGroupCall===c&&u===hs.CLOSED&&(this.setCurrentGroupCall(null),this.stopConnectingSound(),this.audioAsset.playSound("group_call_end.mp3"),I.dispatchEvent("chat_update",c.chatId))}),c.groupCall=await this.managers.appGroupCallsManager.getGroupCallFull(t);const d=c.createConnectionInstance({streamManager:s,type:l,options:{type:l,isMuted:i,joinVideo:a,rejoin:n}}),h=d.createPeerConnection();return h.addEventListener("negotiationneeded",()=>{d.negotiate()}),h.addEventListener("track",u=>{r("ontrack",u),c.onTrack(u)}),h.addEventListener("iceconnectionstatechange",()=>{c.dispatchEvent("state",c.state);const{iceConnectionState:u}=h;switch(u==="disconnected"||u==="checking"||u==="new"?this.startConnectingSound():this.stopConnectingSound(),u){case"checking":break;case"closed":{c.hangUp();break}case"completed":break;case"connected":{c.joined||(c.joined=!0,this.audioAsset.playSound("group_call_start.mp3"),this.managers.appGroupCallsManager.getGroupCallParticipants(t));break}case"disconnected":break;case"failed":{c.hangUp();break}}}),d.createDescription(),d.createDataChannel(),d.appendStreamToConference(),this.setCurrentGroupCall(c),r("set currentGroupCall",t,c),this.startConnectingSound(),d.negotiate()}}}const zn=new XT;Ws&&(Ws.groupCallController=zn);class Zm extends Xt{async init(e,t){const s=await this.managers.appChatsManager.isBroadcast(e);this.container.classList.add("edit-peer-container","chat-members-container","chat-requests-container"),this.setTitle(s?"SubscribeRequests":"MemberRequests");const{importersMap:i,deleteImporter:n,load:a}=Dm({chatId:e,managers:this.managers,requested:!0,link:t}),r=new Map,{selector:l,loadPromise:c}=Ow({appendTo:this.content,managers:this.managers,middleware:this.middlewareHelper.get(),peerId:e.toPeerId(!0),peerType:["custom"],getMoreCustom:a,getSubtitleForElement:h=>M("RequestedToJoinAt",[ws(i.get(h)?.date)]),processElementAfter:(h,u)=>{const p=document.createElement("div");p.classList.add("chatlist-chat-buttons");const m=ze("btn-primary btn-control-small btn-color-primary",{text:s?"AddToChannel":"AddToGroup"}),g=ze("btn-transparent btn-control-small primary",{text:"Dismiss"});p.append(m,g),u.container.append(p),r.set(h,u)},placeholderElementsGap:36});let d=0;return N(l.scrollable.container,async h=>{const u=U(h.target,"chatlist-chat");if(!u)return;const p=u.dataset.peerId.toPeerId(),m=r.get(p),g=U(h.target,"btn-color-primary"),f=U(h.target,"btn-transparent"),y=g?!0:f?!1:void 0;if(y===void 0){me.setInnerPeer({peerId:p});return}const v=m.toggleDisability(!0);try{await this.managers.appChatsManager.hideChatJoinRequest(e,p,y),++d,l.deletePeerId(p),r.delete(p),n(p)}catch{v()}},{listenerSetter:this.listenerSetter}),this.eventListener.addEventListener("close",()=>{this.eventListener.dispatchEvent("finish",d)}),c}}class ZT extends Fl{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"requests",divAndCaption:new np("pinned-requests",i=>{}),onClose:()=>{fe.getState().then(i=>{i.hideChatJoinRequests[this.peerId]=Date.now(),this.managers.appStateManager.pushToState("hideChatJoinRequests",i.hideChatJoinRequests)})},floating:!0,height:52}),this.topbar=e,this.chat=t,this.managers=s,N(this.wrapper,async i=>{if(oe(i),ls.isTabExists(Zm))return;await ls.createTab(Zm).open(this.chat.peerId.toChatId()),ls.toggleSidebar(!0)},{listenerSetter:this.topbar.listenerSetter}),this.divAndCaption.border.remove(),this.divAndCaption.content.remove(),this.titleElement=new ke.IntlElement({key:"Chat.Header.RequestToJoin",args:[0],element:this.divAndCaption.title})}unset(e){this.peerId=e,this.stackedAvatars&&(this.stackedAvatars.container.remove(),this.stackedAvatarsMiddlewareHelper.destroy()),this.toggle(!0)}async set(e,t,s){if(!t.length)return()=>this.unset(e);const i=this.stackedAvatars,n=this.stackedAvatarsMiddlewareHelper;this.stackedAvatarsMiddlewareHelper=xt();const a=this.stackedAvatars=new Co({avatarSize:32,middleware:this.stackedAvatarsMiddlewareHelper.get()}),r=[];return a.render(t,r),await Promise.all(r),()=>{this.peerId=e,this.titleElement.compareAndUpdate({args:[s]}),this.wrapperUtils.before(a.container,this.titleElement.element),i&&(i.container.remove(),n?.destroy()),this.toggle(!1)}}setPeerId(e){return Promise.all([this.chat.managers.acknowledged.appProfileManager.getProfileByPeerId(e),fe.getState()]).then(([t,s])=>({cached:t.cached,result:ei(t.result,i=>{const n=i?.recent_requesters;return n&&(!s.hideChatJoinRequests[e]||Date.now()-s.hideChatJoinRequests[e]>=xg)?this.set(e,n.slice(0,3).map(a=>a.toPeerId(!1)),i.requests_pending):this.set(e,[],0)})}))}}class JT extends Fl{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"actions",divAndCaption:new np("pinned-actions",n=>{}),onClose:()=>{this.managers.appProfileManager.hidePeerSettingsBar(this.peerId)},floating:!0,height:52}),this.topbar=e,this.chat=t,this.managers=s,this.wrapper.firstElementChild.remove(),this.divAndCaption.border.remove(),this.divAndCaption.content.remove(),((n,a)=>{N(n,r=>{oe(r),a(r)},{listenerSetter:this.topbar.listenerSetter})})(this.wrapper,n=>{const a=U(n.target,"pinned-actions-button");if(!a)return;const r=a.dataset.key;this.actions.find(c=>c.key===r).onClick()}),this.actions=[{key:"autoarchived",onClick:async()=>{const n=this.managers.appMessagesManager.editPeerFolders([this.peerId],0);this.freeze(n)}},{key:"block_contact",onClick:()=>{this.chat.topbar.blockUser(this.filteredActions.some(n=>n.key==="report_spam"),!0,n=>{this.freeze(n)})},danger:!0},{key:"add_contact",onClick:()=>{this.chat.topbar.addContact()}},{key:"report_spam",onClick:async()=>{const n=this.peerId;if(n.isUser())this.actions.find(a=>a.key==="block_contact").onClick();else{await Ct({titleLangKey:"Chat.Confirm.ReportSpam.Header",descriptionLangKey:this.managers.appPeersManager.isBroadcast(n)?"Chat.Confirm.ReportSpam.Channel":"Chat.Confirm.ReportSpam.Group",button:{langKey:"ReportChat"}});const a=Promise.all([this.managers.appMessagesManager.reportSpam(n),this.managers.appChatsManager.leave(n.toChatId())]);this.freeze(a)}},danger:!0}]}async freeze(e){this.wrapper.classList.add("is-disabled");try{await e}catch{}this.wrapper.classList.remove("is-disabled")}unset(e){this.peerId=e,this.toggle(!0)}set(e,t){const s=t?.pFlags?this.actions.filter(i=>t.pFlags[i.key]):[];return s.length?()=>{this.peerId=e,this.filteredActions=s;const i={add_contact:"AddContact",autoarchived:"Unarchive",block_contact:"BlockUser",report_spam:"DeleteReportSpam"},n=[];for(let a=0,r=Math.min(2,s.length);a<r;++a){const l=s[a],c=document.createElement("div");c.classList.add("pinned-actions-button",l.danger?"danger":"primary"),r>1&&c.classList.add("half",a===0?"is-first":"is-last"),c.dataset.key=l.key,n.push(c);const d=M(i[l.key]);d.classList.add("pinned-actions-button-text"),Ni(c),c.append(d)}this.wrapper.replaceChildren(...n,this.wrapperUtils),this.toggle(!1)}:()=>this.unset(e)}setPeerId(e){return Promise.all([this.chat.managers.acknowledged.appProfileManager.getPeerSettings(e)]).then(([t])=>({cached:t.cached,result:ei(t.result,s=>this.set(e,s))}))}}function Qo(o,e){dt(o,e),o.classList.toggle("is-badge-empty",!e)}const Ic=(o="")=>`pinned-live${o}`,e1=ce("<div>"),t1=ce("<button><div>"),s1=o=>{const e=st.isAvailable("animations"),[t,s]=ne(e);return e&&ye($s(o.animationTrigger,()=>{s(!0)})),(()=>{const i=t1(),n=i.firstChild,a=o.ref;return typeof a=="function"?wt(a,i):o.ref=i,D(i,j(an,{get when(){return t()},get children(){const r=e1();return r.addEventListener("animationend",()=>s(!1)),Ve(()=>Ce(r,Ic("-button-animation"))),r}}),n),D(n,()=>M("Rtmp.Topbar.Join")),Ve(r=>{const l=Ic("-button-wrap"),c=Ic("-button");return l!==r._v$&&Ce(i,r._v$=l),c!==r._v$2&&Ce(n,r._v$2=c),r},{_v$:void 0,_v$2:void 0}),i})()};function i1(o){return K(()=>{const e=o.name||"s";return{enterActive:(o.enterActiveClass||e+"-enter-active").split(" "),enter:(o.enterClass||e+"-enter").split(" "),enterTo:(o.enterToClass||e+"-enter-to").split(" "),exitActive:(o.exitActiveClass||e+"-exit-active").split(" "),exit:(o.exitClass||e+"-exit").split(" "),exitTo:(o.exitToClass||e+"-exit-to").split(" ")}})}function uC(o){requestAnimationFrame(()=>requestAnimationFrame(o))}function n1(o,e,t,s,i){const{onBeforeEnter:n,onEnter:a,onAfterEnter:r}=e;let l;n?.(t),t.classList.add(...o.enter),t.classList.add(...o.enterActive),queueMicrotask(()=>{if(!t.parentNode)return s?.();a?.(t,()=>c())}),uC(()=>{t.classList.remove(...o.enter),t.classList.add(...o.enterTo),(!a||a.length<2)&&(t.addEventListener("transitionend",c),t.addEventListener("animationend",c),i!==void 0&&(l=window.setTimeout(()=>c(),i)))});function c(d){(!d||d.target===t)&&(clearTimeout(l),s?.(),t.removeEventListener("transitionend",c),t.removeEventListener("animationend",c),t.classList.remove(...o.enterActive),t.classList.remove(...o.enterTo),r?.(t))}}function a1(o,e,t,s,i){const{onBeforeExit:n,onExit:a,onAfterExit:r}=e;if(!t.parentNode)return s?.();let l;n?.(t),t.classList.add(...o.exit),t.classList.add(...o.exitActive),a?.(t,()=>c()),uC(()=>{t.classList.remove(...o.exit),t.classList.add(...o.exitTo),(!a||a.length<2)&&(t.addEventListener("transitionend",c),t.addEventListener("animationend",c),i!==void 0&&(l=window.setTimeout(()=>c(),i)))});function c(d){(!d||d.target===t)&&(clearTimeout(l),s?.(),t.removeEventListener("transitionend",c),t.removeEventListener("animationend",c),t.classList.remove(...o.exitActive),t.classList.remove(...o.exitTo),r?.(t))}}var r1=()=>{},bv=(o,e)=>e();function o1(o,e){const t=Et(o),s=t?[t]:[],{onEnter:i=bv,onExit:n=bv}=e,[a,r]=ne(e.appear?[]:s),[l]=Eb();let c,d=!1;function h(m,g){if(!m)return g&&g();d=!0,n(m,()=>{oa(()=>{d=!1,r(f=>f.filter(y=>y!==m)),g&&g()})})}function u(m){const g=c;if(!g)return m&&m();c=void 0,r(f=>[g,...f]),i(g,m??r1)}const p=e.mode==="out-in"?m=>d||h(m,u):e.mode==="in-out"?m=>u(()=>h(m)):m=>{h(m),u()};return gL(m=>{const g=o();return Et(l)?(l(),m):(g!==m&&(c=g,oa(()=>Et(()=>p(m)))),g)},e.appear?void 0:t),a}const l1={inout:"in-out",outin:"out-in"},gp=o=>{const e=i1(o);return o1(yf(()=>o.children),{mode:l1[o.mode],appear:o.appear,onEnter(t,s){n1(e(),o,t,s,o.duration)},onExit(t,s){a1(e(),o,t,s,o.duration)}})},c1=ce("<div>"),d1=ce("<div class=skeleton-child>"),pu=o=>{const e=()=>typeof o.children=="function"?o.children():o.children,t=()=>typeof o.loading=="function"?o.loading():o.loading,s=j(an,{get when(){return t()},get fallback(){return K(()=>!!e())()&&(()=>{const i=d1();return D(i,e),i})()},get children(){const i=c1();return Ve(()=>Ce(i,`skeleton ${o.class??""}`)),i}});return j(gp,{name:"fade",mode:"outin",duration:100,children:s})},h1=ce("<div>"),u1=o=>{const e=()=>o.watching>0?M("Rtmp.Watching",[Xg(Math.max(0,o.watching))]):M("Rtmp.Topbar.NoViewers"),t=(()=>{const a=h1();return D(a,j(pu,{get loading(){return o.watching===void 0},get children(){return e()}})),a})(),{container:s}=Fd({title:M("Rtmp.Topbar.Title"),subtitle:t}),i=document.createElement("div");i.classList.add(Ic()+"-background"),s.prepend(i),s.classList.remove("quote-like-hoverable"),s.classList.add(Ic()+"-wrapper"),ut(N(s,o.onJoin));let n;return j(s1,{ref(a){const r=n;typeof r=="function"?r(a):n=a},get animationTrigger(){return o.animationTrigger}}),s.append(n),s};var nn=(o=>(o[o.PLAYING=0]="PLAYING",o[o.BUFFERING=1]="BUFFERING",o[o.CONNECTING=2]="CONNECTING",o[o.CLOSED=3]="CLOSED",o))(nn||{});class Nn extends Si{constructor(e){super(!1),Object.assign(this,e),this._state=nn.CONNECTING}cleanup(){super.cleanup()}get state(){return this._state}set state(e){this._state=e,this.dispatchEvent("state",e)}}class p1 extends Si{constructor(){super(...arguments),this.onGroupCallUpdate=e=>{if(e.id===this.currentCall?.call.id){if(e._==="groupCallDiscarded"){this.currentCall=void 0;return}this.currentCall.call=e,this.dispatchEvent("currentCallChanged",this.currentCall)}}}construct(e){this.managers=e,I.addEventListener("group_call_update",this.onGroupCallUpdate),fe.serviceMessagePort.addEventListener("rtmpStreamTime",({callId:t,time:s})=>{this.currentCall?.call.id===t&&(this.currentCall.lastKnownTime=s)})}get currentCall(){return this._currentCall}set currentCall(e){this.currentCall!==e&&(this._currentCall?.cleanup(),this.dispatchEvent("currentCallChanged",this._currentCall=e))}randomSsrc(){return(Math.random()<.5?-1:1)*fL(16)}getJoinPayload(e){return{_:"dataJSON",data:JSON.stringify({fingerprints:[],pwd:"",ssrc:e,"ssrc-groups":[],ufrag:""})}}async joinCall(e){if(this.currentCall)throw new Error("Already in rtmp call");const t=e.toPeerId(!0);this.dispatchEvent("startedJoining",t);const s=this.randomSsrc(),i=this.getJoinPayload(s),n=await this.managers.appProfileManager.getChatFull(e);if(n._!=="channelFull")throw new Error("Not a chat");const a=await this.managers.appGroupCallsManager.getGroupCallFull(n.call.id);if(a._!=="groupCall")throw new Error("Not a group call");const r=await this.managers.appGroupCallsManager.joinGroupCall(n.call.id,i,{type:"main"});if(JSON.parse(r.params.data).rtmp!==!0)throw new Error("Not an rtmp call");this.currentCall=new Nn({call:a,inputCall:{_:"inputGroupCall",id:a.id,access_hash:a.access_hash},chatId:e,peerId:t,ssrc:s,pip:!1,admin:!!n.pFlags?.can_delete_channel,lastKnownTime:"0"})}async leaveCall(e=!1){if(!this.currentCall)return;const t=this.currentCall;this.currentCall=void 0,fe.serviceMessagePort.invokeVoid("leaveRtmpCall",[t.call.id,!0]),await this.managers.appGroupCallsManager.hangUp(t.call.id,e?!0:t.ssrc)}async isCurrentCallDead(e=!1,t=!1){if(!this.currentCall)return"dead";const s=await this.managers.appGroupCallsManager.fetchRtmpState(this.currentCall.inputCall);if(!e)return s.channels.length===0?"dead":"alive";const i=s.channels.find(n=>n.channel===fv);if(!i)return"dead";try{const n=this.currentCall.lastKnownTime==="0"?i.last_timestamp_ms:this.currentCall.lastKnownTime;return await this.managers.appGroupCallsManager.fetchRtmpPart({_:"inputGroupCallStream",call:this.currentCall.inputCall,video_channel:fv,video_quality:kT,scale:i.scale,time_ms:n},s.dcId),"alive"}catch(n){if(n.type==="GROUPCALL_JOIN_MISSING"&&!t)try{return await this.rejoinCall(),this.isCurrentCallDead(!0,!0)}catch{}}return"dying"}async rejoinCall(){if(!this.currentCall)return;this.currentCall.ssrc=this.randomSsrc();const e=this.getJoinPayload(this.currentCall.ssrc);await this.managers.appGroupCallsManager.joinGroupCall(this.currentCall.call.id,e,{type:"main"})}}const Nt=new p1;Ws&&(Ws.rtmpCallsController=Nt);function m1(){const[o,e]=ne(Nt.currentCall,{equals:!1}),[t,s]=ne(Tt);return sn(Nt)("currentCallChanged",i=>{e(i),s(i?.peerId)}),sn(Nt)("startedJoining",i=>{s(i)}),{call:o,peerId:t}}class g1 extends Fl{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"live",floating:!0,height:56}),this.topbar=e,this.chat=t,this.managers=s,[this.peerId,this.setPeerId]=ne(Tt),this.dispose=Hi(()=>this.init(),this.container)}init(){const{peerId:e}=this,[t,s]=ne(),i=yL(()=>e().toChatId()),n=m1(),a=K(()=>{const d=i();return!!(d&&d.pFlags.broadcast&&d.pFlags.call_active&&d.pFlags.call_not_empty)}),r=K(()=>a()&&n.peerId()!==e()),l=()=>I.managers.appProfileManager.getChatFull(e().toChatId());sn(I)("group_call_update",async d=>{if(!a()||d._!=="groupCall")return;const h=await l();h?._==="channelFull"&&d.id===h.call?.id&&s(d.participants_count)}),ye(d=>{if(!(!i()||!i().pFlags.broadcast))return d!==e()&&s(),ye(async()=>{a()||s();const h=await l();if(h?._!=="channelFull"||!h.call)return;const u=await I.managers.appGroupCallsManager.getGroupCallFull(h.call.id);u?._==="groupCall"&&s(u.participants_count)}),e()}),ye(()=>{this.toggle(!r())});const c=()=>{me.joinLiveStream(e())};return j(an,{get when(){return r()},get children(){return j(u1,{get watching(){return t()},animationTrigger:e,onJoin:c})}})}destroy(){super.destroy(),this.dispose()}}const f1=ce("<div><div><div>"),y1=ce("<div><div><div><div></div><div></div></div></div><div><div><div></div><div>"),qs=(o="")=>`rtmp-data${o}`,pC=o=>{const[e,t]=ne(!1),s=()=>e()?o.key:o.key.slice(0,20).replace(/./g,"·"),i=a=>{a.stopPropagation(),t(!e())},n=(a,r)=>{Fs(a),Ee({langPackKey:r})};return(()=>{const a=y1(),r=a.firstChild,l=r.firstChild,c=l.firstChild,d=c.nextSibling,h=r.nextSibling,u=h.firstChild,p=u.firstChild,m=p.nextSibling;return r.$$click=()=>n(o.url,"Rtmp.StreamPopup.URLCopied"),D(r,j(xi,{icon:"link",get class(){return qs("-row-icon")}}),l),D(c,j(pu,{get loading(){return o.loading},get children(){return o.url}})),D(d,()=>M("Rtmp.StreamPopup.ServerURL")),D(r,j(xi,{icon:"copy",get class(){return qs("-row-icon")}}),null),h.$$click=()=>n(o.key,"Rtmp.StreamPopup.KeyCopied"),D(h,j(xi,{icon:"lock",get class(){return qs("-row-icon")}}),u),D(p,j(pu,{get loading(){return o.loading},get children(){return s()}})),D(m,()=>M("Rtmp.StreamPopup.StreamKey"),null),D(m,j(kn,{get icon(){return e()?"eye2":"eye1"},onClick:i,get class(){return qs("-row-item-show")}}),null),D(h,j(xi,{icon:"copy",get class(){return qs("-row-icon")}}),null),D(a,j(an,{get when(){return o.showRevoke},get children(){const g=f1(),f=g.firstChild,y=f.firstChild;return Pl(g,"click",o.onRevoke,!0),D(g,j(xi,{icon:"rotate_left",get class(){return qs("-row-icon")}}),f),D(y,()=>M("Rtmp.StreamPopup.RevokeStreamKey")),Ve(v=>{const w=ot(qs("-row"),qs("-row_danger")),b=qs("-row-item"),S=qs("-row-item-label");return w!==v._v$&&Ce(g,v._v$=w),b!==v._v$2&&Ce(f,v._v$2=b),S!==v._v$3&&Ce(y,v._v$3=S),v},{_v$:void 0,_v$2:void 0,_v$3:void 0}),g}}),null),Ve(g=>{const f={[qs()]:!0,[qs("_contrast")]:o.contrast},y=qs("-row"),v=qs("-row-item"),w=qs("-row-item-text"),b=qs("-row-item-label"),S=qs("-row"),C=qs("-row-item"),P={[qs("-row-item-text")]:!0,[qs("-row-item-text_hidden")]:!e()},L=qs("-row-item-label");return g._v$4=pa(a,f,g._v$4),y!==g._v$5&&Ce(r,g._v$5=y),v!==g._v$6&&Ce(l,g._v$6=v),w!==g._v$7&&Ce(c,g._v$7=w),b!==g._v$8&&Ce(d,g._v$8=b),S!==g._v$9&&Ce(h,g._v$9=S),C!==g._v$10&&Ce(u,g._v$10=C),g._v$11=pa(p,P,g._v$11),L!==g._v$12&&Ce(m,g._v$12=L),g},{_v$4:void 0,_v$5:void 0,_v$6:void 0,_v$7:void 0,_v$8:void 0,_v$9:void 0,_v$10:void 0,_v$11:void 0,_v$12:void 0}),a})()};Ui(["click"]);const v1=ce("<div>"),b1=ce("<button>"),w1=ce("<div><div>"),Bo=(o="")=>`rtmp-popup${o}`;class mC extends ee{constructor(e){super(Bo(),{overlayClosable:!0,closable:!0,title:!0,body:!0}),this.props=e;const{active:t}=e;t||(this.btnMore=ai({buttons:[{icon:"stop",regularText:"Revoke",danger:!0,onClick:()=>this._revokeKey()}],direction:"bottom-left"}),this.header.append(this.btnMore)),this.title.append(t?M("Rtmp.StreamPopup.TitleSettings"):M("Rtmp.StreamPopup.Title")),this._render()}_render(){this._dispose=Jt(e=>{const[t,s]=ne(""),[i,n]=ne(""),[a,r]=ne(!0);this._setLoading=r,this._setUrl=s,this._setKey=n;const l=Hi(()=>{const c=this;return j(S1,{get url(){return t()},get key(){return i()},get loading(){return a()},get active(){return!!c.props.active},onStreamStart:()=>c._onStreamStart(),onRevoked:()=>c._revokeKey()})},this.body);return this._fetchData(),()=>{s(""),n(""),r(!1),l(),e()}})}_revokeKey(){this._setLoading(!0),this._fetchData(!0)}_fetchData(e=!1){this.managers.appGroupCallsManager.fetchRtmpUrl(this.props.peerId,e).then(({url:t,key:s})=>{this._setUrl(t),this._setKey(s),this._setLoading(!1)}).catch(()=>{Ee({langPackKey:"Error.AnError"}),this.forceHide()})}_onStreamStart(){if(this.forceHide(),this.props.active){this.props.onEndStream();return}const e=this.props.peerId.toChatId();this.managers.appGroupCallsManager.createGroupCall(e,void 0,void 0,!0).then(()=>{Nt.joinCall(e)})}cleanup(){super.cleanup(),this._dispose()}}const S1=o=>(()=>{const e=w1(),t=e.firstChild;return D(t,()=>M("Rtmp.StreamPopup.Description")),D(e,j(pC,{get key(){return o.key},get url(){return o.url},get loading(){return o.loading},get showRevoke(){return o.active},get onRevoke(){return o.onRevoked}}),null),D(e,j(an,{get when(){return!o.active},get children(){const s=v1();return D(s,()=>M("Rtmp.StreamPopup.Hint")),Ve(()=>Ce(s,Bo("-text"))),s}}),null),D(e,j(cp,{get children(){const s=b1();return Pl(s,"click",o.onStreamStart,!0),D(s,(()=>{const i=K(()=>!!o.active);return()=>i()?M("Rtmp.StreamPopup.EndLiveStream"):M("Rtmp.StreamPopup.StartStreaming")})()),Ve(i=>pa(s,{[Bo("-button")]:!0,[Bo("-button_danger")]:o.active},i)),s}}),null),Ve(s=>{const i=Bo("-content"),n=Bo("-text");return i!==s._v$&&Ce(e,s._v$=i),n!==s._v$2&&Ce(t,s._v$2=n),s},{_v$:void 0,_v$2:void 0}),e})();Ui(["click"]);class gC{constructor(e={}){this.options=e,this.fullTexts=new Map,e.minChars??(e.minChars=0)}indexObject(e,t){if(t.trim()&&(t=this.processSearchText(t)),!t)return this.fullTexts.delete(e),!1;this.fullTexts.set(e,t)}indexObjectArray(e,t){return this.indexObject(e,t.join(" "))}_search(e,t=e.split(" ").filter(i=>i.trim()),s=this.options.minChars){const i=[],n=this.fullTexts,a=t.length;return n.forEach((r,l)=>{let c=!0,d=0;for(let h=0;h<a;++h){const u=t[h],p=r.indexOf(u),m=h===a-1;if(p===-1||this.options.fullWords&&!m&&r[p+u.length]!==" "||p!==0&&r[p-1]!==" "){c=!1;break}d+=u.length}if(c){d+=a-1;const h=r.length;(s<=d||h<=d)&&i.push({fullText:r,fullTextLength:h,what:l,foundChars:d})}}),i}search(e,t){e=this.processSearchText(e);const i=e.split("").map(r=>this._search(r,void 0,t)),n=Ln(i);return n.sort((r,l)=>{const c=r.fullTextLength-r.foundChars,d=l.fullTextLength-l.foundChars;return c-d||r.fullTextLength-l.fullTextLength}),new Set(n.map(r=>r.what))}processSearchText(e){return this.options?P_(e,this.options):e}}const wv=[["af","Afrikaans"],["sq","Shqip"],["am","አማርኛ"],["ar","العربية"],["hy","Հայերեն"],["az","Azərbaycan dili"],["eu","Euskara"],["be","Беларуская"],["bn","বাংলা"],["bs","Bosanski"],["bg","Български"],["ca","Català"],["ceb","Cebuano"],["zh-CN","简体中文"],["zh","中文"],["zh-TW","繁體中文"],["co","Corsu"],["hr","Hrvatski"],["cs","Čeština"],["da","Dansk"],["nl","Nederlands"],["en","English"],["eo","Esperanto"],["et","Eesti"],["fi","Suomi"],["fr","Français"],["fy","Frysk"],["gl","Galego"],["ka","ქართული"],["de","Deutsch"],["el","Ελληνικά"],["gu","ગુજરાતી"],["ht","Kreyòl ayisyen"],["ha","Hausa"],["haw","ʻŌlelo Hawaiʻi"],["he","עברית"],["iw","עברית"],["hi","हिन्दी"],["hmn","Hmoob"],["hu","Magyar"],["is","Íslenska"],["ig","Igbo"],["id","Indonesia"],["ga","Gaeilge"],["it","Italiano"],["ja","日本語"],["jv","Basa Jawa"],["kn","ಕನ್ನಡ"],["kk","Қазақ тілі"],["km","ភាសាខ្មែរ"],["rw","Kinyarwanda"],["ko","한국어"],["ku","Kurdî"],["ky","Кыргызча"],["lo","ລາວ"],["la","Latina"],["lv","Latviešu"],["lt","Lietuvių"],["lb","Lëtzebuergesch"],["mk","Македонски"],["mg","Malagasy"],["ms","Bahasa Melayu"],["ml","മലയാളം"],["mt","Malti"],["mi","Māori"],["mr","मराठी"],["mn","Монгол"],["my","ဗမာ"],["ne","नेपाली"],["no","Norsk"],["ny","Chichewa"],["or","ଓଡ଼ିଆ"],["ps","پښتو"],["fa","فارسی"],["pl","Polski"],["pt","Português"],["pa","ਪੰਜਾਬੀ"],["ro","Română"],["ru","Русский"],["sm","Gagana fa'a Samoa"],["gd","Gàidhlig"],["sr","Српски"],["st","Sesotho"],["sn","Shona"],["sd","سنڌي"],["si","සිංහල"],["sk","Slovenčina"],["sl","Slovenščina"],["so","Soomaali"],["es","Español"],["su","Basa Sunda"],["sw","Kiswahili"],["sv","Svenska"],["tl","Tagalog"],["tg","Тоҷикӣ"],["ta","தமிழ்"],["tt","Татар теле"],["te","తెలుగు"],["th","ไทย"],["tr","Türkçe"],["tk","Türkmen"],["uk","Українська"],["ur","اردو"],["ug","ئۇيغۇرچە"],["uz","Ozbek"],["vi","Tiếng Việt"],["cy","Cymraeg"],["xh","isiXhosa"],["yi","ייִדיש"],["yo","Yorùbá"],["zu","isiZulu"]],C1=ce("<div class=pinned-translation-button>");function Tf(o,e){const t=Pt(),s=new gC({ignoreCase:!0}),i=new Map;wv.forEach(([a,r])=>{const l=ke.format(`Language.${a}`,!0);i.set(a,[r,l]),s.indexObjectArray(a,[a,r,l])});const n=ee.createPopup(Es,{peerType:["custom"],renderResultsFunc:a=>{a.forEach(r=>{const[l,c]=i.get(r),d=new ve({title:c,subtitle:l,clickable:!0,havePadding:o});o&&d.container.append(n.selector.checkbox(n.selector.selected.has(r))),d.container.dataset.peerId=""+r,n.selector.list.append(d.container)})},placeholder:"Search",getMoreCustom:async a=>({result:a?[...s.search(a)]:wv.map(([l])=>l),isEnd:!0}),onSelect:o?void 0:t.resolve.bind(t),onMultiSelect:o?t.resolve.bind(t):void 0,titleLangKey:o?"Telegram.LanguageViewController":void 0,checkboxSide:"left",noPlaceholder:!0});if(n.addEventListener("close",()=>{t.reject()}),e){const a=n.selector.add.bind(n.selector);n.selector.add=({key:r,scroll:l})=>a({key:r,title:M(`Language.${r}`),scroll:l,fallbackIcon:"check"}),n.selector.addInitial(e)}return t}class I1 extends Fl{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"translation",floating:!0,height:42}),this.topbar=e,this.chat=t,this.managers=s,[this.peerId,this.setPeerId]=ne(Tt),this.dispose=Hi(()=>this.init(),this.container)}init(){const{peerId:e}=this,t=new ke.IntlElement({key:"DoNotTranslateLanguage"}),s=K(()=>pl(e())),i=Du();ye(()=>{t.compareAndUpdate({args:[M(`Language.${s().peerLanguage()}`)]})}),ye(()=>{this.toggle(!s().shouldShow())});const n=new Ut;ut(()=>n.removeAll());const a=ai({direction:"bottom-left",buttons:[{icon:"premium_translate",text:"Chat.Translate.Menu.To",onClick:async()=>{const r=await Tf(!1);s().setLanguage(r)},verify:i},{icon:"hand",textElement:t.element,onClick:()=>{const[r,l]=El();l("translations","doNotTranslate",c=>[...c,s().peerLanguage()])},verify:i,separatorDown:!0},{icon:"crossround",text:"Hide",onClick:()=>{this.managers.appTranslationsManager.togglePeerTranslations(e(),!0)}}],listenerSetter:n});return a.classList.add("pinned-translation-menu","primary"),[(()=>{const r=C1();return r.$$click=()=>{if(!i()){Vt.show({feature:"translations"});return}const l=s();l.toggle(!l.enabled())},D(r,()=>Le("premium_translate","pinned-translation-button-icon"),null),D(r,(()=>{const l=K(()=>!!s().enabled());return()=>l()?M("ShowOriginalButton"):M("TranslateToButton",[M(`Language.${s().language()}`)])})(),null),r})(),a]}destroy(){super.destroy(),this.dispose()}}Ui(["click"]);const L1=!1;class P1{constructor(e,t,s){this.chat=e,this.appSidebarRight=t,this.managers=s,this.verifyButtons=i=>{const n=!!i||!!(this.btnMore&&this.btnMore.classList.contains("menu-open"));i&&oe(i),(async()=>{const r=this.buttonsToVerify.concat(n?this.menuButtons:[]);(await Promise.all(r.map(async c=>({result:await c.verify(),button:c})))).forEach(({button:c,result:d})=>{c.element.classList.toggle("hide",!d)})})()},this.verifyVideoChatButton=async i=>{if(!Ac||this.peerId.isUser()||this.chat.type!==te.Chat||this.chat.threadId)return!1;const n=zn.groupCall,a=this.peerId.toChatId();if(n?.chatId===a||i&&(i==="group"&&await this.managers.appPeersManager.isBroadcast(this.peerId)||i==="broadcast"&&await this.managers.appPeersManager.isAnyGroup(this.peerId)))return!1;const r=fe.getChat(a);if(fa(r,"manage_call")&&i==="admin")return!r.pFlags?.call_active;if(!r.pFlags?.call_active)return!1;const l=await this.managers.appProfileManager.getChatFull(a),c=await this.managers.appGroupCallsManager.getGroupCallFull(l.call.id);return c?._!=="groupCall"?!1:!c.pFlags.rtmp_stream},this.verifyCallButton=async i=>{if(!Fc||!this.peerId.isUser()||this.chat.type!==te.Chat)return!1;const n=this.peerId.toUserId(),a=await this.managers.appProfileManager.getCachedFullUser(n);return!!a&&!!(i==="voice"?a.pFlags.phone_calls_available:a.pFlags.video_calls_available)},this.onJoinGroupCallClick=()=>{this.chat.appImManager.joinGroupCall(this.peerId)},this.onJoinClick=async i=>{const n=this.chat.bubbles.getMiddleware();i.setAttribute("disabled","true");const a=this.peerId.toChatId();let r;await this.managers.appChatsManager.isChannel(a)?r=this.managers.appChatsManager.joinChannel(a):r=this.managers.appChatsManager.addChatUser(a,I.myId),r.catch(l=>{switch(l.type){case"INVITE_REQUEST_SENT":{Ee({langPackKey:"Chat.SendJoinRequest.Info"});return}}throw l}).finally(()=>{n()&&i.removeAttribute("disabled")})},this.onMuteClick=()=>{ee.createPopup(Cw,this.peerId)},this.onUnmuteClick=()=>{this.managers.appMessagesManager.togglePeerMute({peerId:this.peerId,threadId:this.chat.threadId})},this.onResize=()=>{this.setUtilsWidth(!0),this.setFloating()},this.onChangeScreen=(i,n)=>{const a=n===hi.mobile||L1;this.pinnedMessage&&this.pinnedMessage.pinnedMessageContainer.container.classList.toggle("is-floating",a),this.onResize()},this.setUtilsWidth=(i=!1)=>{this.setUtilsRAF&&window.cancelAnimationFrame(this.setUtilsRAF),Pi&&i&&this.chatUtils.classList.add("hide"),this.setUtilsRAF=window.requestAnimationFrame(()=>{Pi&&i&&this.chatUtils.classList.remove("hide");const n=this.chatUtils.getBoundingClientRect().width;this.chat.log("utils width:",n),this.container.style.setProperty("--utils-width",n+"px"),this.setUtilsRAF=0})},this.setFloating=()=>{const i=[...this.pinnedContainers||[],this.pinnedMessage?.pinnedMessageContainer].filter(Boolean);let n=56,a=0;const r=i.reduce((l,c)=>{const d=c.isFloating();return this.container.classList.toggle(`is-pinned-${c.className}-floating`,d),c.isVisible()?(d?(a+=c.height,c.container.style.top=n+"px",n+=c.height):c.container.style.top="",l+ +d):l},0);this.container.dataset.floating=""+r,this.container.style.setProperty("--pinned-floating-height",`calc(${a}px + var(--topbar-floating-call-height)`)},this.listenerSetter=new Ut,this.menuButtons=[],this.buttonsToVerify=[]}construct(){this.container=document.createElement("div"),this.container.classList.add("sidebar-header","topbar","hide"),this.container.dataset.floating="0",this.btnBack=it("left sidebar-close-button",{noRipple:!0}),this.btnBackBadge=bl("span",20,"primary"),this.btnBackBadge.classList.add("back-unread-badge"),this.btnBack.append(this.btnBackBadge),this.chatInfoContainer=document.createElement("div"),this.chatInfoContainer.classList.add("chat-info-container"),this.chatInfo=document.createElement("div"),this.chatInfo.classList.add("chat-info");const e=this.person=document.createElement("div");e.classList.add("person");const t=document.createElement("div");t.classList.add("content");const s=document.createElement("div");s.classList.add("top"),this.title=document.createElement("div"),this.title.classList.add("user-title"),s.append(this.title);const i=document.createElement("div");i.classList.add("bottom"),this.subtitle&&i.append(this.subtitle),t.append(s,i),e.append(t),this.chatInfo.append(e),this.chatUtils=document.createElement("div"),this.chatUtils.classList.add("chat-utils"),this.chatAudio=new wT(this,this.chat,this.managers),this.chatRequests=new ZT(this,this.chat,this.managers),this.chatActions=new JT(this,this.chat,this.managers),vm&&(this.chatLive=new g1(this,this.chat,this.managers)),this.chatTranslation=new I1(this,this.chat,this.managers),this.menuButtons.length&&(this.btnMore=ai({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:this.menuButtons,onOpen:async(r,l)=>{const c=this.menuButtons[this.menuButtons.length-1];if(c?.element){const d=await this.managers.appPeersManager.getDeleteButtonText(this.peerId);c.element.lastChild.replaceWith(M(d))}}})),this.chatUtils.append(...[this.btnJoin,this.btnPinned,this.btnCall,this.btnGroupCall,this.btnGroupCallMenu,this.btnMute,this.btnSearch,this.btnMore].filter(Boolean)),this.pushButtonToVerify(this.btnCall,this.verifyCallButton.bind(this,"voice")),this.pushButtonToVerify(this.btnGroupCall,this.verifyVideoChatButton.bind(this,"nonadmin")),this.pushButtonToVerify(this.btnGroupCallMenu,this.verifyVideoChatButton.bind(this,"admin")),this.chatInfoContainer.append(this.btnBack,this.chatInfo,this.chatUtils),this.container.append(this.chatInfoContainer),this.pinnedMessage&&this.appendPinnedMessage(this.pinnedMessage);const n=this.pinnedContainers=[this.chatAudio,this.chatRequests,this.chatActions,this.chatLive,this.chatTranslation].filter(Boolean);this.container.append(...n.map(r=>r.container)),this.listenerSetter.add(window)("resize",this.onResize),this.listenerSetter.add($e)("changeScreen",this.onChangeScreen),N(this.container,r=>{if(U(r.target,"topbar-search-container")||!r.target.isConnected||U(r.target,"pinned-translation")||U(r.target,"chat-search-top"))return;const l=U(r.target,"pinned-container");if(Dn(),l){if(oe(r),U(r.target,"progress-line")||U(r.target,"pinned-container-wrapper-utils"))return;const c=+l.dataset.mid;if(l.classList.contains("pinned-message"))this.pinnedMessage.followPinnedMessage(c);else if(l.dataset.peerId){const d=l.dataset.peerId.toPeerId(),h=rt.getSearchContext();this.chat.appImManager.setInnerPeer({peerId:d,lastMsgId:c,type:h.isScheduled?te.Scheduled:void 0,threadId:h.threadId})}}else{const c=Uc(r.target);if($e.activeScreen===hi.medium&&document.body.classList.contains(Pc))a();else if(c){if(c.classList.contains("has-stories"))return;this.appSidebarRight.toggleSidebar(!document.body.classList.contains(Lc))}else this.appSidebarRight.toggleSidebar(!0)}},{listenerSetter:this.listenerSetter});const a=r=>{if(r&&oe(r),this.chat.type===te.Search){this.chat.resetSearch();return}if($e.activeScreen===hi.medium&&document.body.classList.contains(Pc))this.chat.appImManager.setPeer({peerId:this.peerId});else{const l=this.chat.appImManager.chats.indexOf(this.chat)===0;ft.back(l?"im":"chat")}};N(this.btnBack,a,{listenerSetter:this.listenerSetter})}pushButtonToVerify(e,t){e&&this.buttonsToVerify.push({element:e,verify:t})}constructUtils(){this.menuButtons=[{icon:"search",text:"Search",onClick:()=>{this.chat.initSearch()},verify:()=>$e.isMobile},{icon:"mute",text:"ChatList.Context.Mute",onClick:this.onMuteClick,verify:async()=>this.chat.type===te.Chat&&I.myId!==this.peerId&&!await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.peerId,respectType:!1,threadId:this.chat.threadId})},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:this.onUnmuteClick,verify:()=>this.chat.type===te.Chat&&I.myId!==this.peerId&&this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.peerId,respectType:!1,threadId:this.chat.threadId})},{icon:"comments",text:"ViewDiscussion",onClick:()=>{const e=this.chat.bubbles.getMiddleware();Promise.resolve(this.managers.appProfileManager.getChannelFull(this.peerId.toChatId())).then(t=>{e()&&t.linked_chat_id&&this.chat.appImManager.setInnerPeer({peerId:t.linked_chat_id.toPeerId(!0)})})},verify:async()=>{const e=await this.managers.appProfileManager.getCachedFullChat(this.peerId.toChatId());return this.chat.type===te.Chat&&!!e?.linked_chat_id}},{icon:"phone",text:"Call",onClick:this.onCallClick.bind(this,"voice"),verify:this.verifyCallButton.bind(this,"voice")},{icon:"videocamera",text:"VideoCall",onClick:this.onCallClick.bind(this,"video"),verify:this.verifyCallButton.bind(this,"video")},{icon:"videochat",text:"PeerInfo.Action.LiveStream",onClick:this.onJoinGroupCallClick,verify:this.verifyVideoChatButton.bind(this,"broadcast")},{icon:"videochat",text:"PeerInfo.Action.VoiceChat",onClick:this.onJoinGroupCallClick,verify:this.verifyVideoChatButton.bind(this,"group")},{icon:"topics",text:"TopicViewAsTopics",onClick:()=>{this.chat.appImManager.toggleViewAsMessages(this.peerId,!1)},verify:async()=>{const e=await this.managers.appMessagesManager.getDialogOnly(this.peerId);return!!(e&&e.pFlags.view_forum_as_messages)}},{icon:"topics",text:"SavedViewAsChats",onClick:()=>{this.chat.appImManager.toggleViewAsMessages(this.peerId,!1)},verify:()=>this.peerId===I.myId&&!this.chat.threadId&&!Tc.settings.savedAsForum},{icon:"select",text:"Chat.Menu.SelectMessages",onClick:()=>{const e=this.chat.selection;e.toggleSelection(!0,!0),fe.getState().then(t=>{if(t.chatContextMenuHintWasShown)return;const s=e.toggleByElement.bind(e);e.toggleByElement=async i=>{this.managers.appStateManager.pushToState("chatContextMenuHintWasShown",!0),zs(M("Chat.Menu.Hint")),e.toggleByElement=s,e.toggleByElement(i)}})},verify:()=>!this.chat.selection.isSelecting&&!!this.chat.bubbles.getRenderedLength()},{icon:"select",text:"Chat.Menu.ClearSelection",onClick:()=>{this.chat.selection.cancelSelection()},verify:()=>this.chat.selection.isSelecting},{icon:"adduser",text:"AddContact",onClick:()=>{this.addContact()},verify:async()=>this.peerId.isUser()&&!await this.managers.appPeersManager.isContact(this.peerId)},{icon:"forward",text:"ShareContact",onClick:()=>{const e=this.peerId;Es.createSharingPicker({onSelect:t=>new Promise((s,i)=>{ee.createPopup(Ss,"",{titleLangKey:"SendMessageTitle",descriptionLangKey:"SendContactToGroupText",descriptionLangArgs:[new Rt({peerId:t,dialog:!0}).element],buttons:[{langKey:"Send",callback:()=>{s(),this.managers.appMessagesManager.sendContact(t,e),this.chat.appImManager.setInnerPeer({peerId:t})}},{langKey:"Cancel",callback:()=>{i()},isCancel:!0}],peerId:t,overlayClosable:!0}).show()})})},verify:async()=>I.myId!==this.peerId&&this.peerId.isUser()&&await this.managers.appPeersManager.isContact(this.peerId)&&!!(await this.managers.appUsersManager.getUser(this.peerId.toUserId())).phone},{icon:"gift",text:"GiftPremium",onClick:()=>this.chat.appImManager.giftPremium(this.peerId),verify:()=>this.chat.canGiftPremium()},{icon:"statistics",text:"Statistics",onClick:()=>{this.appSidebarRight.createTab(Nd).open(this.peerId.toChatId()),this.appSidebarRight.toggleSidebar(!0)},verify:()=>this.managers.appProfileManager.canViewStatistics(this.peerId)},{icon:"addboost",text:"Boosts",onClick:()=>{this.appSidebarRight.createTab(hk).open(this.peerId),this.appSidebarRight.toggleSidebar(!0)},verify:()=>this.chat.isBroadcast&&this.managers.appProfileManager.canViewStatistics(this.peerId)},{icon:"bots",text:"Settings",onClick:()=>{this.managers.appMessagesManager.sendText({peerId:this.peerId,text:"/settings"})},verify:async()=>{try{return!!(await this.managers.appAttachMenuBotsManager.getAttachMenuBot(this.peerId.toUserId()))?.pFlags?.has_settings}catch{return!1}}},{icon:"lock",text:"BlockUser",onClick:()=>{this.blockUser()},verify:async()=>{if(!this.peerId.isUser())return!1;const e=await this.managers.appProfileManager.getCachedFullUser(this.peerId.toUserId());return this.peerId!==I.myId&&e&&!e.pFlags?.blocked}},{icon:"lockoff",text:"Unblock",onClick:()=>{this.managers.appUsersManager.toggleBlock(this.peerId,!1).then(()=>{Ee({langPackKey:"UserUnblocked"})})},verify:async()=>!!(await this.managers.appProfileManager.getCachedFullUser(this.peerId.toUserId()))?.pFlags?.blocked},{icon:"delete",danger:!0,text:"Delete",onClick:()=>{ee.createPopup(Hu,this.peerId,void 0,void 0,this.chat.threadId)},verify:async()=>this.chat.type===te.Saved||this.chat.type===te.Chat&&!!await this.managers.appMessagesManager.getDialogOnly(this.peerId)}],this.btnSearch=it("search"),this.attachClickEvent(this.btnSearch,e=>{this.chat.initSearch()},!0)}addContact(){if(!this.appSidebarRight.isTabExists(Qm)){const e=this.appSidebarRight.createTab(Qm);e.peerId=this.peerId,e.open(),this.appSidebarRight.toggleSidebar(!0)}}async blockUser(e,t,s){const i=this.peerId,n=[e&&{text:"DeleteReportSpam",checked:!0},t&&{text:"DeleteThisChat",checked:!0}],a=await Ct({peerId:i,titleLangKey:"BlockUser",descriptionLangKey:"AreYouSureBlockContact2",descriptionLangArgs:[new Rt({peerId:i}).element],button:{langKey:"BlockUser",isDanger:!0},checkboxes:n.filter(Boolean)}),[r,l]=Array.isArray(a)?a:[],c=Promise.all([r&&this.managers.appMessagesManager.reportSpam(i),l&&this.managers.appMessagesManager.flushHistory(i,!1,!0),this.managers.appUsersManager.toggleBlock(i,!0)]);s?.(c),await c,Ee({langPackKey:"UserBlocked"})}attachClickEvent(e,t,s){N(e,i=>{oe(i),!s&&Dn(),t(i)},{listenerSetter:this.listenerSetter})}onCallClick(e){this.chat.appImManager.callUser(this.peerId.toUserId(),e)}get peerId(){return this.chat.peerId}constructPeerHelpers(){return this.subtitle=document.createElement("div"),this.subtitle.classList.add("info"),this.pinnedMessage=new cu(this,this.chat,this.managers),this.btnJoin=ze("btn-primary btn-color-primary chat-join hide"),this.btnCall=it("phone"),this.btnGroupCall=it("videochat"),this.btnGroupCallMenu=ai({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[{icon:"videochat",text:"Rtmp.Topbar.StartVideoChat",onClick:this.onJoinGroupCallClick},{icon:"link",text:"Rtmp.Topbar.StreamWith",onClick:()=>{ee.createPopup(mC,{peerId:this.peerId}).show()},verify:()=>vm}],icon:"videochat"}),this.btnPinned=it("pinlist chat-pinlist"),this.btnMute=it("mute"),this.attachClickEvent(this.btnCall,this.onCallClick.bind(this,"voice")),this.attachClickEvent(this.btnGroupCall,this.onJoinGroupCallClick),this.attachClickEvent(this.btnPinned,()=>{this.openPinned(!0)}),this.attachClickEvent(this.btnMute,()=>{!!+this.btnMute.dataset.muted?this.onUnmuteClick():this.onMuteClick()}),this.attachClickEvent(this.btnJoin,this.onJoinClick.bind(this,this.btnJoin)),this.listenerSetter.add(I)("folder_unread",e=>{if(e.id!==Ci)return;const t=e.unreadUnmutedPeerIds.size;Qo(this.btnBackBadge,t?""+on(t,1):"")}),this.listenerSetter.add(I)("chat_update",e=>{if(this.peerId===e.toPeerId(!0)){const t=fe.getChat(e);if(!t.pFlags.broadcast)return;this.btnJoin.classList.toggle("hide",!t?.pFlags?.left),this.setUtilsWidth(),this.verifyButtons()}}),this.listenerSetter.add(I)("dialog_notify_settings",e=>{e.peerId===this.peerId&&this.setMutedState()}),this.listenerSetter.add(I)("peer_full_update",e=>{this.peerId===e&&this.verifyButtons()}),this.listenerSetter.add(I)("chat_requests",({chatId:e,recentRequesters:t,requestsPending:s})=>{if(this.peerId!==e.toPeerId(!0))return;const i=this.chat.bubbles.getMiddleware();this.chatRequests.set(this.peerId,t.map(n=>n.toPeerId(!1)),s).then(n=>{i()&&n()})}),this.listenerSetter.add(I)("peer_settings",async({peerId:e,settings:t})=>{if(this.peerId!==e)return;this.chatActions.set(e,t)()}),this.chat.addEventListener("setPeer",(e,t)=>{const s=this.chat.bubbles.getMiddleware();fe.getState().then(i=>{!s()||!this.pinnedMessage||(this.pinnedMessage.hidden=!!i.hiddenPinnedMessages[this.chat.peerId],t?(this.pinnedMessage.unsetScrollDownListener(),this.pinnedMessage.testMid(e,0)):this.pinnedMessage.locked||(this.pinnedMessage.handleFollowingPinnedMessage(),this.pinnedMessage.testMid(e)))})}),this.listenerSetter.add(I)("peer_pinned_messages",({peerId:e,mids:t})=>{this.chat.type!==te.Pinned||e!==this.peerId||t&&this.setTitle()}),this}openPinned(e){this.chat.appImManager.setInnerPeer({peerId:this.peerId,lastMsgId:e?+this.pinnedMessage.pinnedMessageContainer.container.dataset.mid:0,type:te.Pinned})}destroy(){this.listenerSetter.removeAll(),this.status?.destroy(),this.titleMiddlewareHelper?.destroy(),this.avatarMiddlewareHelper?.destroy(),this.pinnedMessage?.destroy(),this.pinnedContainers?.forEach(e=>e.destroy()),delete this.pinnedMessage,delete this.chatAudio,delete this.chatRequests,delete this.chatActions,delete this.chatLive,delete this.chatTranslation}cleanup(){this.chat.peerId||this.container.classList.add("hide")}appendPinnedMessage(e){const t=e.pinnedMessageContainer.container;this.pinnedMessage&&this.pinnedMessage!==e?this.pinnedMessage.pinnedMessageContainer.container.replaceWith(t):this.chatUtils.prepend(t)}async finishPeerChange(e){const{peerId:t,threadId:s}=this.chat,{middleware:i}=e;let n,a;const r=this.chat.type===te.Saved,l=this.chat.type===te.Search;if([te.Chat].includes(this.chat.type)||r){const b=r?s:t,S=r?void 0:s,C=this.avatar;!C||C.node.dataset.peerId.toPeerId()!==b||C.node.dataset.threadId!==(S?""+S:void 0)||t===I.myId?(n=es({middleware:(a=xt()).get(),isDialog:!0,size:42,peerId:b,threadId:S,wrapOptions:{customEmojiSize:vs(32,32)},withStories:!0,meAsNotes:r}),n.node.classList.add("person-avatar")):n=this.avatar}this.status?.destroy();const c=this.status=this.createStatus(),d=[this.managers.appPeersManager.isBroadcast(t),this.managers.appPeersManager.isAnyChat(t),t.isAnyChat()?fe.getChat(t.toChatId()):void 0,n?.readyThumbPromise,this.setTitleManual(),c?.prepare(!0),fe.getState(),to(this.chatRequests?.setPeerId(t)),to(this.chatActions?.setPeerId(t))],[h,u,p,m,g,f,y,v,w]=await Promise.all(d);return!i()&&a&&a.destroy(),()=>{const b=!(this.chat.type===te.Pinned||this.chat.type===te.Scheduled);this.btnMute&&this.btnMute.classList.toggle("hide",!h||!b),this.btnJoin&&(h&&!this.chat.isRestricted&&b?(dt(this.btnJoin,M(h?"Chat.Subscribe":"ChannelJoin")),this.btnJoin.classList.toggle("hide",!p?.pFlags?.left)):this.btnJoin.classList.add("hide")),this.btnSearch&&this.btnSearch.classList.toggle("hide",!b),this.btnPinned&&this.btnPinned.classList.toggle("hide",!b),this.avatar!==n&&(n&&this.person.prepend(n.node),this.avatar&&(this.avatarMiddlewareHelper.destroy(),this.avatar.node.remove()),this.avatar=n,this.avatarMiddlewareHelper=a,this.container.classList.toggle("has-avatar",!!n)),this.setUtilsWidth(),this.verifyButtons(),this.btnMore&&this.btnMore.classList.toggle("hide",!b);const S=this.chat.isPinnedMessagesNeeded();if(S||this.chat.type===te.Discussion){if(this.chat.wasAlreadyUsed||!this.pinnedMessage){const C=new cu(this,this.chat,this.managers);this.appendPinnedMessage(C),this.pinnedMessage?.destroy(),this.pinnedMessage=C}S?this.pinnedMessage.hidden=!!y.hiddenPinnedMessages[t]:this.chat.type===te.Discussion&&(this.pinnedMessage.pinnedMid=this.chat.threadId,this.pinnedMessage.count=1,this.pinnedMessage.pinnedIndex=0,this.pinnedMessage._setPinnedMessage())}else this.pinnedMessage&&(this.pinnedMessage.destroy(),this.pinnedMessage=void 0);g(),f?.(),this.subtitle.classList.toggle("hide",!f),this.setMutedState(),this.container.classList.remove("hide"),v.result instanceof Promise&&this.chatRequests.unset(t),w.result instanceof Promise&&this.chatActions.unset(t),this.chatLive?.setPeerId(t),this.chatTranslation?.setPeerId(t),ei(v.result,C=>{i()&&C()}),ei(w.result,C=>{i()&&C()}),this.container.classList.toggle("show-back-button",l)}}async setTitleManual(e){const{peerId:t,threadId:s}=this.chat;let i;this.titleMiddlewareHelper?.destroy();const r=(this.titleMiddlewareHelper=xt()).get();if(this.chat.type===te.Pinned)e===void 0?i=M("Loading"):i=M("PinnedMessagesCount",[e]),e===void 0&&this.managers.appMessagesManager.getSearchCounters(t,[{_:"inputMessagesFilterPinned"}],!1).then(l=>{if(!r())return;const c=l[0].count;if(this.setTitle(c),!c){this.chat.appImManager.setPeer();const d=this.chat.appImManager.chat;d.topbar.pinnedMessage&&d.topbar.pinnedMessage.pinnedMessageContainer.toggle(!0)}});else if(this.chat.type===te.Scheduled)i=M(t===I.myId?"Reminders":"ScheduledMessages");else if(this.chat.type===te.Discussion){const l=this.messagesCounter(r,"Chat.Title.Comments",this.chat.isForum);if(e===void 0){const c=await this.chat.getHistoryStorage();if(!r())return;l.compareAndUpdate(c.count===null?{key:"Loading",args:void 0}:{args:[c.count-(this.chat.isForum?1:0)]})}i=l.element}else if(this.chat.type===te.Chat||this.chat.type===te.Saved){const l=this.chat.type===te.Saved?s:t;if([i]=await Promise.all([Oe({peerId:l,dialog:!0,withIcons:!s,threadId:s,wrapOptions:{middleware:r},meAsNotes:this.chat.type===te.Saved})]),!r())return}return()=>{dt(this.title,i)}}setTitle(e){this.setTitleManual(e).then(t=>t())}async setMutedState(){if(!this.btnMute)return;const e=this.peerId,t=await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:e,respectType:!1,threadId:this.chat.threadId}),s=await this.managers.appPeersManager.isBroadcast(e);s&&(po(this.btnMute,t?"unmute":"mute"),this.btnMute.dataset.muted=""+ +t),this.btnMute.style.display=s?"":"none"}messagesCounter(e,t,s){const i=new ke.IntlElement({key:t,args:[1]}),n=this.chat.historyStorageKey,a=({historyKey:r,count:l})=>{n===r&&i.compareAndUpdate({key:t,args:[l-(s?1:0)]})};return I.addEventListener("history_count",a),this.managers.appMessagesManager.toggleHistoryKeySubscription(n,!0),e.onDestroy(()=>{I.removeEventListener("history_count",a),this.managers.appMessagesManager.toggleHistoryKeySubscription(n,!1)}),i}createStatus(){if(!this.subtitle||this.chat.type!==te.Chat&&this.chat.type!==te.Saved)return;const e=xt(),t=e.get(),s=new Ut;let i;if(this.chat.type===te.Saved){const a=this.messagesCounter(t,"messages");i=async()=>{const r=await this.chat.getHistoryStorage();return a.compareAndUpdate({args:[r.count]}),()=>dt(this.subtitle,a.element)}}else if(this.chat.threadId)i=async()=>{const a=await Oe({peerId:this.peerId,dialog:!0}),r=M("TopicProfileStatus",[a]);return()=>dt(this.subtitle,r)};else{const a=this.peerId;s.add(I)("peer_typings",({peerId:l})=>{a===l&&n()}),s.add(I)("user_update",l=>{a===l.toPeerId()&&n()});const r=window.setInterval(()=>n(),6e4);t.onDestroy(()=>{clearInterval(r)}),i=l=>this.chat.appImManager.setPeerStatus({peerId:a,element:this.subtitle,needClear:l,useWhitespace:!1,middleware:t})}t.onDestroy(()=>{s.removeAll()});const n=()=>{i(!1).then(a=>t()&&a?.())};return{prepare:i,destroy:()=>e.destroy()}}}class fC extends Dt{constructor(){super(...arguments),this.threadId=0,this.query=""}onOpenAfterTimeout(){this.appSearch.beginSearch(this.peerId,this.threadId,this.query)}init(e,t,s,i){this.container.id="search-private-container",this.container.classList.add("chatlist-container"),this.inputSearch=new wo({placeholder:"Search"}),this.title.replaceWith(this.inputSearch.container),this.btnPickDate=it("calendar sidebar-header-right"),this.header.append(this.btnPickDate);const n=document.createElement("div");n.classList.add("chatlist-container"),this.scrollable.container.replaceWith(n),this.appSearch=new gP(n,this.inputSearch,{messages:new Rr("Chat.Search.PrivateSearch","messages")},this.middlewareHelper.get(),void 0,void 0,!!(e===I.myId&&t)),this.peerId?this.appSearch.beginSearch(this.peerId,this.threadId,i):(this.query=i,this.peerId=e,this.threadId=t,this.onDatePick=s,this.btnPickDate.classList.toggle("hide",!this.onDatePick),this.onDatePick&&N(this.btnPickDate,()=>{ee.createPopup(ip,new Date,this.onDatePick).show()},{listenerSetter:this.listenerSetter}),i&&this.appSearch.searchInput.inputField.setValueSilently(i),ls.toggleSidebar(!0))}}async function M1(o){let e,t=0,s=0,i=0;const n=I.settings,a=I.managers.appPeersManager;return!n.autoDownloadNew.pFlags.disabled&&o&&(o.isUser()?await a.isContact(o)?e="contacts":e="private":await a.isBroadcast(o)?e="channels":e="groups",n.autoDownload.photo[e]&&(t=n.autoDownloadNew.photo_size_max),n.autoDownload.video[e]&&(s=n.autoDownloadNew.video_size_max),n.autoDownload.file[e]&&(i=n.autoDownloadNew.file_size_max)),{photo:t,video:s,file:i}}function E1(o,e){return-e*o*(o-2)}const Jm=50,Sv=Jm;class Jc{constructor(){this._width=Jm,this._height=Sv,this._tails=90,this._curve=[0,.25,.5,.75,1,1.5,2,2.5,3,3.5,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,18.3,18.6,18.9,19.2,19.5,19.8,20.1,20.4,20.7,21,21.3,21.6,21.9,22.2,22.5,22.8,23.1,23.4,23.7,24,24.3,24.6,24.9,25.2,25.5,25.8,26.1,26.3,26.4,26.5,26.6,26.7,26.8,26.9,27],this._positions=[{x:.8,y:.1},{x:.6,y:.2},{x:.35,y:.25},{x:.25,y:.6},{x:.2,y:.9},{x:.4,y:.8},{x:.65,y:.75},{x:.75,y:.4}],this._phases=this._positions.length,this.drawNextPositionAnimated=t=>{let s,i;if(t){const n=t();s=n>=1;const a=E1(n,1),r=this._nextPositionTail??0,c=(this._nextPositionTail=this._nextPositionTails*a)-r;c&&(this._nextPositionLeft-=c,this.changeTailAndDraw(-c))}else{const n=this._frames;i=n.shift(),s=!n.length}return i&&this.drawImageData(i),s&&(this._nextPositionLeft=void 0,this._nextPositionTails=void 0,this._nextPositionTail=void 0,this._animatingToNextPosition=void 0),!s};const e=this._tails/this._curve[this._curve.length-1];for(let t=0,s=this._curve.length;t<s;++t)this._curve[t]=this._curve[t]*e;this._incrementalCurve=this._curve.map((t,s,i)=>t-(i[s-1]??0))}hexToRgb(e){const t=_n(e);return{r:t[0],g:t[1],b:t[2]}}getPositions(e){const t=this._positions.slice();t.push(...t.splice(0,e));const s=[];for(let i=0;i<t.length;i+=2)s.push(t[i]);return s}getNextPositions(e,t,s){const i=this.getPositions(e);if(!s[0]&&s.length===1)return[i];const a=this.getPositions(++e%this._phases).map((l,c)=>({x:(l.x-i[c].x)/t,y:(l.y-i[c].y)/t}));return s.map(l=>a.map((c,d)=>({x:i[d].x+c.x*l,y:i[d].y+c.y*l})))}curPosition(e,t){return this.getNextPositions(e,this._tails,[t])[0]}changeTail(e){for(this._tail+=e;this._tail>=this._tails;)this._tail-=this._tails,++this._phase>=this._phases&&(this._phase-=this._phases);for(;this._tail<0;)this._tail+=this._tails,--this._phase<0&&(this._phase+=this._phases)}changeTailAndDraw(e){this.changeTail(e);const t=this.curPosition(this._phase,this._tail);this.drawGradient(t)}getGradientImageData(e,t=this._phase,s=1-this._tail/this._tails){const i=this._hctx.createImageData(this._width,this._height),n=i.data,a=this._colors.length,r=u=>{const p=[];for(let m=0;m!=4;++m)p[m]={...this._positions[(u+m*2)%this._positions.length]},p[m].y=1-p[m].y;return p},l=(t+1)%this._positions.length,c=r(l),d=r(t);let h=0;for(let u=0;u<this._height;++u){const m=u/this._height-.5,g=m*m;for(let f=0;f<this._width;++f){const v=f/this._width-.5,b=.35*Math.sqrt(v*v+g),S=b*b*.8*8,C=Math.sin(S),P=Math.cos(S),L=Math.max(0,Math.min(1,.5+v*P-m*C)),E=Math.max(0,Math.min(1,.5+v*C+m*P));let _=0,k=0,x=0,A=0;for(let T=0;T<a;++T){const B=c[T].x+(d[T].x-c[T].x)*s,R=c[T].y+(d[T].y-c[T].y)*s,O=L-B,X=E-R;let F=Math.max(0,.9-Math.sqrt(O*O+X*X));F=F*F*F*F,_+=F,k+=F*this._colors[T].r,x+=F*this._colors[T].g,A+=F*this._colors[T].b}n[h++]=k/_,n[h++]=x/_,n[h++]=A/_,n[h++]=255}}return i}drawImageData(e){this._hctx.putImageData(e,0,0),this._ctx.drawImage(this._hc,0,0,this._width,this._height)}drawGradient(e){this.drawImageData(this.getGradientImageData(e))}init(e){this._frames=[],this._phase=0,this._tail=0;const t=e.getAttribute("data-colors").split(",");this._colors=t.map(s=>this.hexToRgb(s)),this._hc||(this._hc=document.createElement("canvas"),this._hc.width=this._width,this._hc.height=this._height,this._hctx=this._hc.getContext("2d",{alpha:!1})),this._canvas=e,this._ctx=this._canvas.getContext("2d",{alpha:!1}),this.update()}update(){if(this._colors.length<2){const t=this._colors[0];this._ctx.fillStyle=`rgb(${t.r}, ${t.g}, ${t.b})`,this._ctx.fillRect(0,0,this._width,this._height);return}const e=this.curPosition(this._phase,this._tail);this.drawGradient(e)}toNextPosition(e){if(this._colors.length<2)return;if(e){this._nextPositionLeft=this._tails+(this._nextPositionLeft??0),this._nextPositionTails=this._nextPositionLeft,this._nextPositionTail=void 0,this._animatingToNextPosition=!0,Ba(this.drawNextPositionAnimated.bind(this,e),this);return}const t=this._tail,s=this._tails;let i;const n=[];for(let l=0,c=this._incrementalCurve.length;l<c;++l){const d=this._incrementalCurve[l];let h=(n[l-1]??t)+d;+h.toFixed(2)>s&&i===void 0&&(i=l,h%=s),n.push(h)}const a=n.slice(0,i),r=i!==void 0?n.slice(i):[];[a,r].forEach((l,c,d)=>{const h=l[l.length-1];if(h!==void 0&&h>s&&(l[l.length-1]=+h.toFixed(2)),this._tail=h??0,!l.length)return;const u=this.getNextPositions(this._phase,s,l);c!==d.length-1&&++this._phase>=this._phases&&(this._phase-=this._phases);const p=u.map(m=>this.getGradientImageData(m));this._frames.push(...p)}),this._animatingToNextPosition=!0,Ba(this.drawNextPositionAnimated,this)}cleanup(){}static createCanvas(e){const t=document.createElement("canvas");return t.width=Jm,t.height=Sv,e!==void 0&&(t.dataset.colors=e),t}static create(e){const t=this.createCanvas(e),s=new Jc;return s.init(t),{gradientRenderer:s,canvas:t}}}const _1=!1,k1=Gh&&Uh,Ec=class Ec{constructor(){this.canvases=new Set}static getInstance(e){let t=this.INSTANCES.find(s=>Di(s.options,e));return t||(t=new Ec,t.init(e),this.INSTANCES.push(t)),t}init(e){this.options=e}renderToCanvas(e){return this.renderImageFromUrl(this.options.url).then(()=>this.fillCanvas(e))}renderImageFromUrl(e){if(this.renderImageFromUrlPromise)return this.renderImageFromUrlPromise;const t=this.image=document.createElement("img");return t.crossOrigin="anonymous",this.renderImageFromUrlPromise=Ki(t,e,!1).then(()=>!Gh||!k1?t:createImageBitmap(t,{resizeWidth:1440,resizeHeight:2960}).then(s=>(this.imageBitmap=s,t)))}cleanup(e){this.canvases.delete(e),this.canvases.size||(us(Ec.INSTANCES,this),this.imageBitmap?.close())}fillCanvas(e){const t=e.getContext("2d"),{width:s,height:i}=e,n=this.imageBitmap||this.image;let a=n.width,r=n.height;const l=(500+lt.height/2.5)*e.dpr,c=l/r;a*=c,r=l,this.options.mask?(t.fillStyle="#000",t.fillRect(0,0,s,i),t.globalCompositeOperation="destination-out"):t.globalCompositeOperation="source-over";const d=p=>{for(let m=0;m<s;m+=a)t.drawImage(n,m,p,a,r)},h=(i-r)/2;if(d(h),h>0){let p=h;do d(p-=r);while(p>=0)}const u=i-1;for(let p=h+r;p<u;p+=r)d(p)}setCanvasDimensions(e){const t=Math.min(2,window.devicePixelRatio),s=this.options.width*t;let i=this.options.height*t;e.dpr=t,e.dataset.originalHeight=""+i,$e.activeScreen===hi.large&&_1&&(i*=1.5),e.width=s,e.height=i}createCanvas(){const e=document.createElement("canvas");return this.canvases.add(e),this.setCanvasDimensions(e),e}resize(e,t){this.init({...this.options,width:e,height:t});const s=[];for(const i of this.canvases)this.setCanvasDimensions(i),s.push(this.renderToCanvas(i));return Promise.all(s)}static resizeInstances(e,t){return Promise.all(this.INSTANCES.map(s=>s.resize(e,t)))}};Ec.INSTANCES=[];let mu=Ec;function T1(o){let e;return lr(o)?e=o.peerId:Fa(o)?e=o.id:la(o)&&(e=o.savedPeerId),e}function x1(o){if(o.inputFilter||o.savedReaction||o.query||o.isPublicHashtag)return o.isCacheableSearch?"cached":o.query||!o.peerId||o.fromPeerId?"uncached":"cached"}function yC(o){const{type:e,peerId:t,threadId:s}=o,i=A1(o);return[e,t,i,s].filter(Boolean).join("_")}function A1({inputFilter:o,savedReaction:e,query:t,hashtagType:s}){let i;return e&&(i=`tag-${e.map(r=>r.document_id||r.emoticon).join(",")}`,o??(o={_:"inputMessagesFilterEmpty"})),[o?._,s!=="this"&&s,t,i].filter(Boolean).join("_")}function vC(o){return x1(o)?"search":o.threadId?"replies":"history"}const dh="keydown",F1="active",Cv=["ArrowUp","ArrowDown"],Iv=["ArrowLeft","ArrowRight"];function bC({list:o,type:e,onSelect:t,once:s,waitForKey:i,activeClassName:n=F1,cancelMouseDown:a,target:r}){let l=i?.length?new Set(i):void 0;const c=new Set(e==="xy"?Cv.concat(Iv):e==="x"?Iv:Cv),d=()=>r||o.querySelector("."+n)||o.firstElementChild,h=(E,_)=>{if(r===E)return;let k=!1;r&&(k=!0,r.classList.remove(n)),r=E,r&&(r.classList.add(n),k&&f&&_&&Lg({container:f,element:r,position:"center",forceDuration:100,axis:e==="x"?"x":"y"}))},u=(E,_)=>{let k;return _?k=E.nextElementSibling||o.firstElementChild:k=E.previousElementSibling||o.lastElementChild,k},p=(E,_)=>{const k=_?"nextElementSibling":"previousElementSibling",x=_?"firstElementChild":"lastElementChild",A=E.getBoundingClientRect();let T=E[k]||o[x];for(;T!==E;){const B=T.getBoundingClientRect();if(B.x===A.x&&B.y!==A.y)break;T=T[k]||o[x]}return T};let m;e==="xy"?m=(E,_)=>_==="ArrowUp"||_==="ArrowDown"?p(E,_==="ArrowDown"):u(E,_==="ArrowRight"):m=(E,_)=>u(E,_==="ArrowRight"||_==="ArrowDown");let g=E=>{const _=E.key;if(!c.has(_)){(_==="Enter"||e!=="xy"&&_==="Tab")&&(oe(E),w(d()));return}if(oe(E),o.childElementCount>1){let k=d();k=m(k,_),h(k,!0)}};const f=U(o,"scrollable");o.classList.add("navigable-list");const y=E=>{const _=Ns(E.target,o);_&&h(_,!1)},v=E=>{oe(E);const _=Ns(E.target,o);_&&(h(_,!1),w(d()))},w=async E=>{const _=await t(E);(_!==void 0?!_:s)&&P()};let b=!1,S;const C=()=>{b||(b=!0,document.addEventListener(dh,g,{capture:!0,passive:!1}),o.addEventListener("mousemove",y,{passive:!0}),a&&o.addEventListener("mousedown",oe),S=N(o,v,{ignoreMove:a}))},P=()=>{b&&(b=!1,document.removeEventListener(dh,g,{capture:!0}),o.removeEventListener("mousemove",y),a&&o.removeEventListener("mousedown",oe),S(),S=void 0)},L=()=>{l||h(o.firstElementChild,!1)};if(l){const E=g;g=_=>{l.has(_.key)&&(oe(_),document.removeEventListener(dh,g,{capture:!0}),g=E,document.addEventListener(dh,g,{capture:!0,passive:!1}),l=void 0,L())}}else r||L();return C(),{attach:C,detach:P,resetTarget:L}}function Lv(o,e){return o.length>e?o.slice(0,e/2|0)+"..."+o.slice(-Math.round(e/2)):o}function R1(){const[o,e]=ne($e.activeScreen);return sn($e)("changeScreen",(t,s)=>e(s)),o}const uc=ce("<div>"),D1=ce("<span><b></b> "),B1=ce("<span class=secondary>"),N1=ce("<div><div class=chat-search-footer-left><span></span></div><div><span class=chat-search-footer-type>"),O1=ce('<div class="chat-search-results chatlist-container">'),U1=ce("<div class=chat-search-top>"),H1=ce("<span>"),$1=ce("<div class=topbar-search-input-tools>"),V1=ce("<div class=topbar-search-left-results-empty>"),G1=ce("<div class=topbar-search-left-results-padding>"),z1=ce("<div class=topbar-search-left-delimiter>"),hh=ce("<div class=topbar-search-left-reactions-padding>"),K1=ce("<div class=topbar-search-left-search-types>"),W1=ce("<div class=topbar-search-container><div><div class=topbar-search-left-background>"),Pv=ce('<div class="topbar-search-left-reactions-container topbar-search-left-collapsable"><div class=topbar-search-left-delimiter>'),j1=ce("<div class=topbar-search-right-container>"),q1=o=>{const[,e]=Xn(o,["onScrolledBottom","onScrolledTop"]);let t;const s=(()=>{const n=uc(),a=t;return typeof a=="function"?wt(a,n):t=n,uo(n,e,!1,!0),D(n,()=>o.children),n})(),i=new vi(void 0,void 0,void 0,void 0,t);return i.onScrolledBottom=o.onScrolledBottom,i.onScrolledTop=o.onScrolledTop,ut(()=>{i.destroy()}),s},Q1=["this","my","public"],Mv=void 0,Y1=({middleware:o,peerId:e,fromSavedDialog:t,messages:s,query:i,searchType:n})=>{const a=s.map(async r=>{const l=r.fromId,c=[],{dom:d}=Xe.addDialogAndSetLastMessage({peerId:t?I.myId:l||e,container:!1,avatarSize:"abitbigger",meAsSaved:n==="my",message:r,query:i,wrapOptions:{middleware:o},loadPromises:c,threadId:t?r.saved_peer_id?at(r.saved_peer_id):I.myId:void 0,autonomous:!0});return await Promise.all(c),d.containerEl});return Promise.all(a)},X1=o=>{const{middleware:e,peerId:t,threadId:s,query:i,fromPeerId:n,reaction:a,searchType:r}=o,l=!!(t===I.myId&&s);let c,d=!1,h;const u=async()=>{if(d)return;d=!0;const g=c?.mid||0,f=c?.peerId||Tt,y={peerId:r==="this"||!r?t:Tt,threadId:r==="this"||!r?s:void 0,query:i,inputFilter:{_:"inputMessagesFilterEmpty"},offsetId:g,offsetPeerId:f,limit:30,fromPeerId:n,savedReaction:a?[a]:void 0,nextRate:h,isPublicHashtag:r==="public",isCacheableSearch:!!r,hashtagType:r},v=yC({type:vC(y),...y});I.managers.appMessagesManager.toggleHistoryKeySubscription(v,!0),ut(()=>{I.managers.appMessagesManager.toggleHistoryKeySubscription(v,!1)});const w=await I.managers.appMessagesManager.getHistory(y);if(!e())return;let b;w.messages?(b=w.messages,h=w.nextRate):b=w.history.map(C=>fe.getMessageByPeer(t,C));const S=await Y1({...o,fromSavedDialog:l,messages:b});e()&&(m(C=>(C.count=w.count,C.values.push(...b),c=b[b.length-1],w.isEnd.top&&(C.loadMore=void 0),C.rendered.push(...S),C)),d=!1)},[p,m]=Bd({loadMore:u});return p},Z1=o=>{const{middleware:e,peerId:t,query:s}=o;let i=!1,n=0;const a=async()=>{if(i)return;i=!0;const c=await I.managers.appProfileManager.getParticipants({id:t.toChatId(),filter:{_:"channelParticipantsSearch",q:s},limit:30,offset:n,forMessagesSearch:!0});if(!e())return;const d=c.participants.map(gl),h=d.map(async p=>{const m=await Oe({peerId:p}),g=fe.getPeer(p),f=ui(g)[0],y=new ve({title:(()=>{const b=D1(),S=b.firstChild;return S.nextSibling,D(S,m),D(b,f&&(()=>{const C=B1();return D(C,`@${f}`),C})(),null),b})(),clickable:!0});y.container.classList.add("topbar-search-left-sender");const v=40,w=es({peerId:p,size:v,middleware:e});return y.createMedia(`${v}`).append(w.node),await w.readyThumbPromise,y.container}),u=await Promise.all(h);e()&&(l(p=>{p.count=c.count??d.length;const m=p.values.push(...d);return n=m,m>=p.count&&(p.loadMore=void 0),p.rendered.push(...u),p}),i=!1)},[r,l]=Bd({loadMore:a});return r};function J1(o){return(()=>{const e=N1(),t=e.firstChild,s=t.firstChild,i=t.nextSibling,n=i.firstChild;return D(t,()=>o.pickDateBtn,s),D(t,()=>o.pickUserBtn,s),D(s,(()=>{const a=K(()=>o.count()===0);return()=>a()?M("NoResult"):(()=>{const r=K(()=>!!o.resultsShown());return()=>r()?M("messages",[o.count()]):M("Of",[o.index()+1,o.count()])})()})()),n.$$click=()=>o.onToggle(),D(n,()=>M(o.resultsShown()?"SearchAsChat":"SearchAsList")),Ve(a=>{const r=ot("chat-search-footer",o.choosingSender()&&"hide"),l=ot("chat-search-footer-count",o.count()===void 0&&"hide"),c=ot("chat-search-footer-right",!o.count()&&"hide");return r!==a._v$&&Ce(e,a._v$=r),l!==a._v$2&&Ce(s,a._v$2=l),c!==a._v$3&&Ce(i,a._v$3=c),a},{_v$:void 0,_v$2:void 0,_v$3:void 0}),e})()}function ex(o){return(()=>{const e=O1();return D(e,()=>o.scrollable),e})()}function tx(o){return(()=>{const e=U1();return D(e,()=>o.hasSearchTypes()?o.searchTypesScrollable:o.reactionsScrollable),e})()}function sx(o){const e=(s,i)=>{const n=Ei({icon:s,className:"bubbles-corner-button chat-secondary-button chat-search-go chat-search-go-"+s}),a=N(n,i);ut(a);const r=K(()=>s==="down"?o.index()===0:o.index()===o.count()-1);return ye(()=>{n.classList.toggle("is-end",r()),n.classList.toggle("hide",(o.count()||0)<2)}),n},t=[e("up",o.onArrowButtonClick.bind(null,"up")),e("down",o.onArrowButtonClick.bind(null,"down"))];o.chat.bubbles.container.after(...t),ut(()=>{t.forEach(s=>{s.remove()})})}function ix(o){const e=R1(),t=K(()=>e()===hi.mobile),[s,i]=ne(!1),[n,a]=ne(""),[r,l]=ne(),[c,d]=ne(),[h,u]=ne(),[p,m]=ne(),[g,f]=ne(),[y,v]=ne(),[w,b]=ne(void 0,{equals:!1}),[S,C]=ne(!1),[P,L]=ne(),[E,_]=ne(),[k,x]=ne(void 0,{equals:!1}),[A,T]=ne(),[B,R]=ne(void 0,{equals:!1}),[O,X]=ne(Mv),[F,H]=ne(!1),G=K(()=>S()&&!P()),z=K(()=>t()?F():s()),q=K(()=>z()&&r()&&h()||void 0),$=K(()=>{if(S()||B())return;const V=n();return V.startsWith("#")?V.slice(1):void 0}),se=K(()=>$()!==void 0),Y=K(()=>{if(se())return!1;const V=A(),ie=k();return!!(V&&ie?.length)}),Q=K(()=>se()),he=K(()=>(!t()||!P())&&S()),le=K(()=>t()||Y()||z()),re=Du();o.onActive&&(ye(()=>{o.onActive(le(),Y(),t())}),ut(()=>{o.onActive(!1,!1,t())})),ye(()=>{Z.onChange(Z.value=o.query()),C(!!o.filterPeerId()),L(o.filterPeerId()),R(o.reaction()),vr(()=>{Zs(Z.input)})}),ye(()=>{const{element:V}=q()||{};if(!V)return;const ie=V.firstElementChild,we="menu-open",Ie=ie.querySelector(`.${we}`);Ie&&Ie.classList.remove(we);const{detach:Te}=bC({list:ie,type:"y",onSelect:Qe=>{const Re=!!(!S()||P());b(Qe),Re&&Dn()},activeClassName:we,cancelMouseDown:!0,target:Et(w)});ut(()=>{Te()})});const ge={type:"topbar-search",onPop:()=>{if(s()&&n())return Dn(),!1;o.onClose?.()}};ft.pushItem(ge),ut(()=>{ft.removeItem(ge)});const be=(V,ie=Z.inputField.isEmpty())=>{if(P()){V&&oe(V),ie&&L(void 0);return}if(S()){V&&oe(V),ie&&C(!1);return}if(ie){if(t())return;o.onClose?.()}},Z=new wo({placeholder:"Search",onChange:a,onClear:be,onFocusChange:i,onBack:()=>{o.onClose?.()},alwaysShowClear:!0,noBorder:!0,verifyDebounce:V=>V!=="#"&&!Z.container.classList.contains("show-placeholder")&&!!V.trim(),arrowBack:t()});Z.container.classList.add("topbar-search-input-container"),Z.input.classList.add("topbar-search-input");const de=V=>{if(V.key!=="Backspace")return;const ie=Z.inputField.isEmpty();ie&&(P()||S())&&be(void 0,ie)};sn(Z.input)("keydown",de),ut(()=>{Z.remove()});const Ze=fl("#",Hh),Ne=ke.format("Search.From",!0)+" ",pe=fl(Ne,Hh),Be=(()=>{const V=H1();return D(V,Ne),Ve(()=>Ce(V,ot("topbar-search-input-from",he()&&"is-visible"))),V})();Z.container.append(Be),ye(V=>{const ie=S(),we=se();V&&(V.classList.remove("scale-in"),V.offsetWidth,V.classList.add("scale-out"),setTimeout(()=>{V.remove()},200));const Ie=E();if(Ie){Ie.classList.add("topbar-search-input-entity","scale-in");const Te=N(Ie,Qe=>{oe(Qe),we?X():L()},{cancelMouseDown:!0});ut(Te),Z.container.append(Ie)}return Z.container.style.setProperty("--padding-placeholder",(he()?pe:0)+"px"),Z.container.style.setProperty("--padding-hashtag",(we?Ze:0)+"px"),Z.container.style.setProperty("--padding-sender",(Ie?Ie.offsetWidth+6:0)+"px"),Z.setPlaceholder(ie&&!Ie?"Search.Member":we?"Search.Hashtag":"Search"),Ie}),ye(()=>{Z.container.classList.toggle("show-placeholder",$()==="")});const He=V=>{const ie=Ys().get(),we=Et(()=>Mi.renderEntity({key:V.peerId,title:V.title,fallbackIcon:V.fallbackIcon,middleware:ie,avatarSize:30,meAsSaved:!1}));if(V.active!==void 0&&ye(()=>{we.element.classList.toggle("active",V.active())}),V.onClick){const Ie=N(we.element,Te=>{oe(Te),V.onClick()},{cancelMouseDown:!0});ut(Ie)}return V.onPromises&&V.onPromises(we.promises),we.element},De=V=>{const ie=V.type==="this"?o.peerId:V.type==="my"?I.myId:"public",we=M(`Search.Types.${V.type==="this"?"ThisChat":V.type==="my"?"MyMessages":"PublicPosts"}`);return j(He,Ai({peerId:ie,title:we},()=>!V.notList&&{active:()=>O()===V.type,onClick:()=>X(Ie=>Ie===V.type?Mv:V.type)},{get fallbackIcon(){return V.type==="public"?"newchannel_filled":void 0},get onPromises(){return V.onPromises}}))};ye(async()=>{const V=P(),ie=O(),we=Ys().get();let Ie;(V||ie)&&(Ie=await new Promise(Te=>{let Qe;const Re=async tt=>(await Promise.all(tt),Te(Qe));ie?Qe=De({type:ie,notList:!0,onPromises:Re}):Qe=He({peerId:V,onPromises:Re})}),!we())||_(Ie)});const Ae=43,Ke=271,We=V=>{let ie=w();if(!ie){ie=gi.querySelector(".chatlist-chat"),b(ie);return}if(V==="down"?ie=ie.previousElementSibling:ie=ie.nextElementSibling,!ie||!ie.classList.contains("chatlist-chat"))return;const we=ie.offsetTop,Ie=Ke;gi.scrollTop=we-Ie/2+ie.clientHeight/2,b(ie)},Fe=({direction:V})=>j(kn,{icon:V,get class(){return ot("input-search-part","topbar-search-input-arrow",(!r()||S()&&!P())&&"hide")},noRipple:!0,onClick:()=>{We(V)}}),Ue=Z.clearBtn.previousSibling;let nt;(()=>{const V=$1(),ie=nt;return typeof ie=="function"?wt(ie,V):nt=V,D(V,(()=>{const we=K(()=>!t());return()=>we()&&[j(Fe,{direction:"up"}),j(Fe,{direction:"down"})]})(),null),D(V,()=>Z.clearBtn,null),V})(),Ue.after(nt);const Lt=(V,ie)=>{me.chat.setMessageId({query:V&&ie||void 0,isPublicHashtag:V==="public"||void 0,isCacheableSearch:!!V||void 0,inputFilter:ie&&V?{_:"inputMessagesFilterEmpty"}:void 0,type:ie&&V?te.Search:o.chatType,hashtagType:V})};ye(V=>{V||(V={});const{peerId:ie,threadId:we}=o,Ie=n(),Te=P(),Qe=G(),Re=Ys().get(),tt=!Ie.trim()||Ie==="#",ct=se(),Mt=!Qe&&B(),Ht=O();if(Ht&&!Ie){X(),Lt(void 0,void 0);return}v(()=>{}),m(),f(),b();const li=(Qe?Z1:X1)({middleware:Re,peerId:ie,threadId:we,query:Ie,fromPeerId:Te,reaction:Mt,searchType:Ht}),ts=K(()=>r()===0||ct&&r()===void 0);let St;(()=>{const ji=uc(),Cr=St;return typeof Cr=="function"?wt(Cr,ji):St=ji,D(ji,(()=>{const Lo=K(()=>!!ts());return()=>Lo()?(()=>{const Pn=V1();return D(Pn,()=>ct&&(r()===void 0?M("Search.HelpHashtag"):M("Search.EmptyHashtag",[_e(Lv(Ie,18))])),null),D(Pn,()=>!ct&&(Te?M("Search.EmptyFrom",[new Rt({peerId:Te}).element]):M("Search.Empty",[_e(Lv(Ie,18))])),null),Pn})():[(()=>{const Pn=uc();return D(Pn,()=>li().rendered),Pn})(),K((()=>{const Pn=K(()=>!!li().rendered);return()=>Pn()&&G1()})())]})()),Ve(()=>Ce(ji,ot(!Et(t)&&"topbar-search-left-chatlist","chatlist",ts()&&"is-empty"))),ji})();let ss=!0;const Vs=ji=>{ss&&(Z.toggleLoading(!1),u({element:St,type:Qe?"senders":"messages"}),gi.scrollTop=0,ss=!1,Et(t)&&!Qe&&b(Et(p)&&ji))};(Ht!==V.searchType||Ht&&Ie!==V.query)&&(o.onSearchTypeChange?.(),Lt(Ht,Ie));const Zn={searchType:Ht,query:Ie};return!Qe&&!Te&&!Mt&&tt?(l(),d(),Vs(),Zn):(ye($s(()=>li(),({rendered:ji,values:Cr,count:Lo,loadMore:Pn})=>{l(ji.length),d(Lo),v(()=>Pn),Qe?f(Cr):m(Cr),Vs(ji[0])},{defer:!0})),Z.toggleLoading(!0),Et(()=>li().loadMore()),Zn)}),ye($s(w,V=>{const ie=Ri(V);if(ie===-1)return;if(G()){const Te=g()[ie];oa(()=>{L(Te),Z.onChange(Z.value="")});return}const we=V.parentElement.querySelector(".active");we&&we.classList.remove("active"),V.classList.add("active"),H(!1);const Ie=p()[ie];me.chat.setMessageId({lastMsgId:Ie.mid,lastMsgPeerId:Ie.peerId})},{defer:!0}));const At=V=>({_:"reactionCount",count:V.count,reaction:V.reaction}),rs=V=>({_:"messageReactions",pFlags:{reactions_as_tags:!0},results:V.map(At)}),Cs=({savedPeerId:V,tags:ie})=>{V===o.threadId&&x(ie)};sn(I)("saved_tags",Cs),ye(V=>{const ie=k(),we=A();if(!ie||!we)return V;const Ie={...we.getContext(),reactions:rs(ie)},Te=B();let Qe;if(Te){const tt=Ie.reactions.results.find(ct=>en(ct.reaction,Te));tt&&(Qe=tt,tt.chosen_order=0)}if(V?.remove(),we.update(Ie),Qe){const tt=we.getSorted().find(ct=>en(ct.reactionCount.reaction,Te));Lg({container:xe,element:tt,position:"center",axis:"x"})}const Re=re();if(we.classList.toggle("is-locked",!Re),!Re){const tt="premium_lock",ct=new wr;ct.init(vn.Tag,Ys().get()),ct.reactionCount={_:"reactionCount",count:1,reaction:tt},ct.setCanRenderAvatars(!1),ct.renderCounter(void 0,M("Unlock")),ct.classList.add("reaction-tag-lock");const Mt=document.createElement("div");return Mt.classList.add("reaction-sticker","reaction-sticker-icon"),Mt.append(Le(tt)),ct.lastElementChild.before(Mt),we.prepend(ct),ct}}),ye(()=>{if(o.peerId!==I.myId){T(),x();return}const V=Ys().get(),ie=xt();ut(()=>{setTimeout(()=>{ie.destroy()},400)});const we=new op;we.init({context:{peerId:o.peerId,mid:0,reactions:rs([])},type:vn.Block,middleware:ie.get(),forceCounter:!0}),we.classList.remove("has-no-reactions"),we.classList.add("topbar-search-left-reactions");const Ie=N(we,Qe=>{const Re=U(Qe.target,"reaction-tag");if(!Re)return;if(!re()){Vt.show({feature:"saved_tags"});return}const{reactionCount:tt}=Re,{reaction:ct}=tt;R(Mt=>{if(!en(Mt,ct))return ct}),Zs(Z.input)},{cancelMouseDown:!0});ut(Ie);const Te=()=>{I.managers.appReactionsManager.getSavedReactionTags(o.threadId).then(Qe=>{V()&&(T(we),x(Qe))})};Te(),I.addEventListener("saved_tags_clear",Te),ut(()=>{I.removeEventListener("saved_tags_clear",Te)})});let os=!0;ye($s(B,V=>{os&&(os=!1,!V)||me.chat.setMessageId({savedReaction:V?[V]:void 0})})),ut(()=>{B()&&me.chat.setMessageId({lastMsgId:void 0,lastMsgPeerId:void 0,mediaTimestamp:void 0,savedReaction:void 0})}),ut(()=>{me.chat.type===te.Search&&Lt(void 0,void 0)}),ye(()=>{if(Z.setArrowBack(t()),!t())return;const V=()=>Ri(w()),ie=J1({index:V,count:c,pickUserBtn:si,pickDateBtn:cn,resultsShown:z,onToggle:()=>{H(Re=>!Re)},choosingSender:G}),we=ex({scrollable:J}),Ie=tx({reactionsScrollable:je,searchTypesScrollable:ae,hasReactions:()=>!!mi(),hasSearchTypes:()=>!!oi()});sx({index:V,count:c,chat:o.chat,onArrowButtonClick:We});const Te=(Re=F())=>{o.chat.bubbles.container.classList.toggle("search-results-active",Re),we.classList.toggle("active",Re)},Qe=Re=>{Re??(Re=!!(mi()||oi())),o.chat.topbar.container.classList.toggle("search-top-active",Re),we.classList.toggle("search-top-active",Re),Re?Se.after(Ie):Ie.remove()};ye(()=>Te()),ye(()=>Qe()),ye(()=>{G()?H(!0):S()||H(!1)}),ut(()=>{ie.remove(),H(!1),Te(),Qe(!1),setTimeout(()=>{we.remove()},400)}),o.chat.input.chatInput.before(we,ie)});const js=K(()=>{if(!z())return 0;const V=r();if(V===void 0&&!se())return 0;const ie=8*2;let we;return V?h().type==="senders"?we=1+ie+V*48:we=1+ie+V*56:we=Ae,Math.min(Ke,we)}),mi=K(()=>le()&&Y()?61:0),oi=K(()=>le()&&Q()?61:0),si=o.canFilterSender&&j(kn,{get class(){return ot(!t()&&"topbar-search-right-filter-button")},icon:"newprivate",ref:V=>{const ie=N(V,we=>{oe(we),Z.onChange(Z.value=""),C(!0),Zs(Z.input,!0)},{cancelMouseDown:!0});ut(ie)}}),cn=o.onDatePick&&j(kn,{icon:"calendar",onClick:()=>{ee.createPopup(ip,new Date,o.onDatePick).show()}});let gi;const J=j(q1,Ai({ref(V){const ie=gi;typeof ie=="function"?ie(V):gi=V}},()=>!t()&&{class:"topbar-search-left-results topbar-search-left-collapsable",style:js()?{height:js()+"px"}:void 0},{onScrolledBottom:()=>{y()?.()},get children(){return[K(()=>K(()=>!t())()&&z1()),j(tp,{type:"cross-fade",get children(){return h()?.element}})]}}));let xe;const je=j(td,{ref(V){const ie=xe;typeof ie=="function"?ie(V):xe=V},class:"topbar-search-left-reactions-scrollable",get children(){return[hh(),K(()=>A()),hh()]}});let Ge;const ae=j(td,{ref(V){const ie=Ge;typeof ie=="function"?ie(V):Ge=V},class:"topbar-search-left-reactions-scrollable",get children(){return[hh(),(()=>{const V=K1();return D(V,()=>Q1.map(ie=>j(De,{type:ie}))),V})(),hh()]}});let Se;return(()=>{const V=W1(),ie=V.firstChild;ie.firstChild;const we=Se;return typeof we=="function"?wt(we,V):Se=V,D(ie,()=>Z.container,null),D(ie,(()=>{const Ie=K(()=>!t());return()=>Ie()&&(()=>{const Te=Pv();return Te.firstChild,D(Te,je,null),Ve(Qe=>zi(Te,mi()?{height:mi()+"px"}:void 0,Qe)),Te})()})(),null),D(ie,(()=>{const Ie=K(()=>!t());return()=>Ie()&&(()=>{const Te=Pv();return Te.firstChild,D(Te,ae,null),Ve(Qe=>zi(Te,oi()?{height:oi()+"px"}:void 0,Qe)),Te})()})(),null),D(ie,()=>!t()&&J,null),D(V,(()=>{const Ie=K(()=>!t());return()=>Ie()&&(()=>{const Te=j1();return D(Te,si&&(()=>{const Qe=uc();return D(Qe,si),Ve(()=>Ce(Qe,ot("topbar-search-right-filter",(S()||se())&&"is-hidden"))),Qe})(),null),D(Te,cn&&(()=>{const Qe=uc();return D(Qe,cn),Ve(()=>Ce(Qe,ot("topbar-search-right-filter",se()&&"is-hidden"))),Qe})(),null),Te})()})(),null),Ve(()=>Ce(ie,ot("topbar-search-left-container",le()&&"is-focused"))),V})()}Ui(["click"]);function xf(o){const e=o.getContext("2d"),t=new Array(4).fill(0),s=e.getImageData(0,0,o.width,o.height).data,i=s.length/4;for(let a=0;a<s.length;a+=4)t[0]+=s[a],t[1]+=s[a+1],t[2]+=s[a+2],t[3]+=s[a+3];const n=new Uint8ClampedArray(4);return n[0]=t[0]/i,n[1]=t[1]/i,n[2]=t[2]/i,n[3]=t[3]/i,n}function nx(o,e,t){const s=document.createElement("canvas"),i=e/t,n=50;return i===1?(s.width=n,s.height=s.width/i):i>1?(s.height=n,s.width=s.height/i):s.width=s.height=n,s.getContext("2d").drawImage(o,0,0,e,t,0,0,s.width,s.height),xf(s)}function wC(o){return nx(o,o.naturalWidth,o.naturalHeight)}async function ax(o){const e=document.createElement("img");return await Ki(e,o,!1),wC(e)}function Af(o){let{h:e,s:t,l:s}=$h(o[0],o[1],o[2]);return t>0&&(t=Math.min(100,t+5+.1*(100-t))),s=Math.max(0,s*.65),`hsla(${e}, ${t}%, ${s}%, .4)`}var te=(o=>(o.Chat="chat",o.Pinned="pinned",o.Discussion="discussion",o.Scheduled="scheduled",o.Stories="stories",o.Saved="saved",o.Search="search",o))(te||{});const sm=["query","isCacheableSearch","isPublicHashtag","savedReaction","fromPeerId","inputFilter","hashtagType"];class SC extends Si{constructor(e,t,s,i={}){super(),this.appImManager=e,this.managers=t,this.isMainChat=s,this.excludeParts=i,this.log=ri("CHAT",Gi.Log|Gi.Warn|Gi.Debug|Gi.Error),this.log.warn("constructor"),this.type="chat",this.animationGroup=`chat-${Math.round(Math.random()*65535)}`,this.middlewareHelper=xt(),this.destroyMiddlewareHelper=xt(),this.hadAnyBackground=!1,this.excludeParts.elements||(this.container=document.createElement("div"),this.container.classList.add("chat","tabs-tab"),this.backgroundEl=document.createElement("div"),this.backgroundEl.classList.add("chat-background"),this.container.append(this.backgroundEl)),this.peerId=Tt,this.backgroundTempId=0,this.sharedMediaTabs=[]}hasBackgroundSet(){return!!(this.theme||this.wallPaper)}async setBackground({url:e,theme:t,wallPaper:s,skipAnimation:i,manual:n,onCachedStatus:a}){this.hadAnyBackground=!0;const r=this.log.bindPrefix("setBackground");r("start");const l=!t,c=as.getTheme(),d=as.getThemeSettings(c).wallpaper,h=t??c,u=!!(h||!l||s);if(s||(s=as.getThemeSettings(h).wallpaper),this.wallPaper===s&&this.theme===h){r("same background"),a?.(!0);return}const p=bm(s),m=s?.slug;let g,f;const y=!!p&&!m&&!s.settings.intensity;if(y&&document.documentElement.style.cursor==="grabbing"&&this.gradientRenderer&&!this.patternRenderer){r("just changing color"),this.gradientCanvas.dataset.colors=p,this.gradientRenderer.init(this.gradientCanvas),a?.(!0);return}const v=++this.backgroundTempId;if(!e&&!y){const T=s.settings,B=this.appImManager.getBackground({slug:m,canDownload:!0,blur:T&&T.pFlags.blur}),R=!(B instanceof Promise);if(r("getting background, cached",R),a?.(R),i??(i=R),R||(n=void 0),e=await B,this.backgroundTempId!==v)return}else r("global background"),a?.(!0);const w=this.gradientRenderer,b=this.patternRenderer;this.gradientCanvas;const S=this.patternCanvas;this.theme,this.wallPaper,this.gradientRenderer=this.patternRenderer=this.gradientCanvas=this.patternCanvas=this.theme=this.wallPaper=void 0,h!==c&&(this.theme=t),s!==d&&(this.wallPaper=s);const C=!!s.pFlags.pattern,P=s.settings?.intensity&&s.settings.intensity/100,L=!!P&&P<0;let E,_=g?.firstElementChild,k;if(!g)if(g=document.createElement("div"),g.classList.add("chat-background-item"),e)if(C){g.classList.add("is-pattern");const T=this.appImManager.chatsContainer.getBoundingClientRect();E=this.patternRenderer=mu.getInstance({url:e,width:T.width,height:T.height,mask:L}),_=this.patternCanvas=E.createCanvas(),_.classList.add("chat-background-item-canvas","chat-background-item-pattern-canvas"),L&&g.classList.add("is-dark")}else f=document.createElement("img"),f.classList.add("chat-background-item-image"),g.classList.add("is-image","chat-background-item-scalable"),g.append(f);else g.classList.add("is-color");let x;if(p){const{canvas:T,gradientRenderer:B}=Jc.create(p);x=this.gradientRenderer=B,k=this.gradientCanvas=T,k.classList.add("chat-background-item-canvas","chat-background-item-color-canvas"),k.classList.add("chat-background-item-scalable")}if(P&&(!f||as.isNight())){let T;f?T=f:T=L?k:_;let B=Math.abs(P)*(L?.5:1);f?B=Math.max(.3,1-P):L&&(B=Math.max(.3,B)),T.style.setProperty("--opacity-max",""+B)}const A=new Promise(T=>{const B=()=>{if(this.backgroundTempId!==v){E?.cleanup(_),x?.cleanup();return}const X=this.backgroundEl.lastElementChild;if(X===g)return;const F=()=>{const G=performance.now();let z;f?z=wC(f):z=xf(k);const q=Af(Array.from(z));return r("getHighlightningColor",q,performance.now()-G),q},H=[k,_].filter(Boolean);H.length&&g.append(...H),this.backgroundEl.append(g),bt({element:g,className:"is-visible",forwards:!0,duration:i?0:200,onTransitionStart:()=>{const G=performance.now();h&&as.applyTheme(h,this.container),u&&as.applyHighlightingColor({hsla:F(),element:this.container}),r("transition start time",performance.now()-G)},onTransitionEnd:X?()=>{b?.cleanup(S),w?.cleanup(),X.remove()}:null,useRafs:2})},R=()=>{r("background is ready",performance.now()-O),n?T(B):(B(),T(void 0))},O=performance.now();E?E.renderToCanvas(_).then(R):e?Kn(f,e,R,!1):R()});return n?A:this.setBackgroundPromise=Promise.race([Hs(500),A]).then(()=>{})}setBackgroundIfNotSet(e){if(!this.hasBackgroundSet())return this.setBackground(e)}_handleBackgrounds(){const e=this.log.bindPrefix("handleBackgrounds"),t=Pt();let s=!0;const i=d=>{const h=this.setBackground({manual:s,onCachedStatus:u=>{u||t.resolve(void 0)},...d});return vL(h,t),h},n=d=>{if(!d)return;const{accountThemes:h}=c;return h.themes?.find(u=>u.emoticon===d)},a=()=>{if(!this.hasBackgroundSet()&&this.hadAnyBackground){e("no background"),t.resolve(void 0);return}e("resetting background"),i(this.getResetBackgroundOptions())},r=()=>{const d=l();if(!d){a();return}let h=Vr(d.wallpaper);const u=d.theme_emoticon||h&&h.settings?.emoticon,p=Vr(n(u));if(!p&&!h){a();return}u&&p&&(h=void 0),e("updating",d,p,h),i({theme:p,wallPaper:h,skipAnimation:s});const m=Ou();ye($s(m,r,{defer:!0}))},l=sw(()=>this.peerId),[c]=El();return ye(()=>{r(),s=!1}),t}handleBackgrounds(){return this.type==="stories"?Promise.resolve(Wt):Jt(e=>(this.middlewareHelper.get().onClean(e),this._handleBackgrounds()))}setType(e){this.type=e}init(){this.topbar=new P1(this,ls,this.managers),this.bubbles=new fT(this,this.managers),this.input=new bu(this,this.appImManager,this.managers,"chat-input-main"),this.contextMenu=new ki(this,this.managers),this.selection=new bT(this,this.bubbles,this.input,this.managers),this.topbar.constructUtils(),this.topbar.constructPeerHelpers(),this.topbar.construct(),this.input.construct(),this.bubbles.constructPeerHelpers(),this.input.constructPeerHelpers(),Je||this.bubbles.setReactionsHoverListeners(),this.bubbles.attachContainerListeners(),this.container.append(this.topbar.container,this.bubbles.container,this.input.chatInput),this.bubbles.listenerSetter.add(I)("dialog_migrate",({migrateFrom:t,migrateTo:s})=>{this.peerId===t&&this.setPeer({peerId:s})}),this.bubbles.listenerSetter.add(I)("dialog_drop",t=>{t.peerId===this.peerId&&(lr(t)||this.threadId===T1(t))&&this.appImManager.setPeer()}),this.bubbles.listenerSetter.add(I)("chat_update",async t=>{const{peerId:s}=this;if(s.isAnyChat()&&s.toChatId()===t){const i=await this.managers.appMessagesManager.isAnonymousSending(s);s===this.peerId&&(this.isAnonymousSending=i)}});const e=t=>{const s=()=>{this.bubbles.observer?.toggleObservingNew(t),gt.toggleIntersectionGroup(this.animationGroup,t),t&&gt.checkAnimations(t,this.animationGroup)};t?s():setTimeout(()=>{s()},400)};this.bubbles.listenerSetter.add(this.appImManager)("chat_changing",({to:t})=>{e(t!==this)}),this.bubbles.listenerSetter.add(this.appImManager)("tab_changing",t=>{e(this.appImManager.chat!==this||t!==Ll.CHAT&&$e.activeScreen===hi.mobile)}),this.searchSignal=Ja(),Jt(t=>{this.middlewareHelper.get().onDestroy(t);const s=async(u,p)=>{const m=st.isAvailable("animations"),g=[{opacity:0},{opacity:1}],f={fill:"forwards",duration:m?200:0,easing:"ease-in-out"};p||g.reverse();const y=this.topbar.container.querySelectorAll(".content, .chat-utils"),v=[],w=u.animate(g,f).finished;g.reverse();const b=Array.from(y).map(S=>S.animate(g,f).finished);return v.push(w,...b),Promise.all(v)},[i,n]=ne(!1),[a,r]=ne("",{equals:!1}),[l,c]=ne(void 0,{equals:!1}),[d,h]=ne(void 0,{equals:!1});ye(u=>{if(!i()){if(!u)return;s(u,!1).then(()=>{u.remove()});return}return u=Et(()=>ix({chat:this,chatType:this.type,peerId:this.peerId,threadId:this.threadId,canFilterSender:this.isRealGroup,query:a,filterPeerId:l,reaction:d,onClose:()=>{this.searchSignal(void 0)},onDatePick:p=>{this.bubbles.onDatePick(p)},onActive:(p,m,g)=>{const f="is-search-active",y=!!(p&&(m||g));if(this.container.classList.contains(f)===y)return;const w=this.bubbles.createScrollSaver();w.save(),this.container.classList.toggle(f,!g&&y),this.topbar.container.classList.toggle("hide-pinned",g),w.restore()},onSearchTypeChange:()=>{this.ignoreSearchCleaning=!0}})),this.topbar.container.append(u),s(u,!0),u}),ye(()=>{const u=this.searchSignal();r(u?.query),c(u?.filterPeerId),h(u?.reaction),n(!!u)})})}beforeDestroy(){this.destroyPromise=Pt(),this.bubbles.cleanup(),this.searchSignal?.(void 0)}cleanupBackground(){++this.backgroundTempId,this.patternRenderer?.cleanup(this.patternCanvas),this.gradientRenderer?.cleanup(),this.patternRenderer=this.gradientRenderer=void 0}destroy(){this.destroyPromise?.resolve(),this.destroySharedMediaTab(),this.topbar?.destroy(),this.bubbles?.destroy(),this.input?.destroy(),this.contextMenu?.destroy(),this.selection?.attachListeners(void 0,void 0),this.destroyMiddlewareHelper.destroy(),this.cleanupBackground(),this.topbar=this.bubbles=this.input=this.contextMenu=this.selection=void 0,this.container?.remove(),this.changeHistoryStorageKey(void 0)}cleanup(e=!0){this.input?.cleanup(e),this.topbar?.cleanup(),this.selection?.cleanup(),this.ignoreSearchCleaning?this.ignoreSearchCleaning=void 0:this.searchSignal?.(void 0)}get isForumTopic(){return!!(this.isForum&&this.threadId)}async onChangePeer(e,t){const{peerId:s,threadId:i}=e;this.excludeParts.elements||ls.getTab(fC)?.close();const n=fe.isForum(s);i&&!n&&(e.type=e.peerId===I.myId?"saved":"discussion"),e.query&&(e.type="search");const a=e.type??"chat";this.setType(a);const[r,l,c,d,h,u,p,m,g,f,y,v]=await t(Promise.all([this.managers.appPeersManager.noForwards(s),this.managers.appPeersManager.isPeerRestricted(s),this._isAnyGroup(s),this.managers.appPeersManager.isAnyGroup(s),this.setAutoDownloadMedia(),this.managers.appPeersManager.isMegagroup(s),this.managers.appPeersManager.isBroadcast(s),this.managers.appPeersManager.isChannel(s),this.managers.appPeersManager.isBot(s),this.managers.appMessagesManager.isAnonymousSending(s),s.isUser()&&this.managers.appProfileManager.isCachedUserBlocked(s),s.isUser()&&this.managers.appUsersManager.isPremiumRequiredToContact(s.toUserId(),!0)]));n&&i&&await t(this.managers.dialogsStorage.getForumTopicOrReload(s,i)),this.noForwards=r,this.isRestricted=l,this.isAnyGroup=c,this.isRealGroup=d,this.isMegagroup=u,this.isBroadcast=p,this.isChannel=m,this.isBot=g,this.isForum=n,this.isAllMessagesForum=n&&!i,this.isAnonymousSending=f,this.isUserBlocked=y,this.isPremiumRequired=v,this.selection&&(this.selection.isScheduled=a==="scheduled"),this.messagesStorageKey=`${this.peerId}_${this.type==="scheduled"?"scheduled":"history"}`,this.excludeParts.sharedMedia||(this.sharedMediaTab=ls.createSharedMediaTab(),this.sharedMediaTabs.push(this.sharedMediaTab),this.sharedMediaTab.setPeer(s,i)),this.input?.clearHelper(),this.selection?.cleanup()}get requestHistoryOptionsPart(){const e={peerId:this.peerId,threadId:this.threadId};return sm.forEach(t=>{e[t]=this[t]}),this.hashtagType&&this.hashtagType!=="this"&&(e.peerId=Tt,e.threadId=void 0),e}setPeer(e){const{peerId:t,threadId:s}=e;t?this.inited||(this.init&&(this.init(),this.init=null),this.inited=!0):this.inited=void 0;const i=this.appImManager.isSamePeer(this,e);if(!i)this.appImManager.dispatchEvent("peer_changing",this),this.peerId=t||Tt,this.threadId=s,this.middlewareHelper.clean();else if(this.setPeerPromise)return;if(!t){this.peerId=0;let d;this.hasBackgroundSet()&&this===this.appImManager.chats[0]&&(d=this.setBackground(this.getResetBackgroundOptions())),ei(d,()=>{ls.toggleSidebar(!1),this.cleanup(!0),this.bubbles.setPeer({peerId:t,samePeer:!1,sameSearch:!1}),this.appImManager.dispatchEvent("peer_changed",this),this.excludeParts.sharedMedia||(ls.replaceSharedMediaTab(),this.destroySharedMediaTab(),this.sharedMediaTab=void 0)});return}this.peerChanged=i;let n=!0;(!i||sm.some(d=>e.hasOwnProperty(d)))&&(sm.forEach(d=>{this[d]=e[d]}),n=!1);const{requestHistoryOptionsPart:a}=this,r=yC({type:vC(a),...a});this.changeHistoryStorageKey(r);const l=this.bubbles.setPeer({...e,samePeer:i,sameSearch:n}),c=this.setPeerPromise=l.then(d=>d.promise).catch(Wt).finally(()=>{this.setPeerPromise===c&&(this.setPeerPromise=null)});return l}changeHistoryStorageKey(e){this.historyStorageKey!==e&&(this.historyStorageKey&&this.managers.appMessagesManager.toggleHistoryKeySubscription(this.historyStorageKey,!1),this.historyStorageKey=e,this.historyStorageKey&&this.managers.appMessagesManager.toggleHistoryKeySubscription(this.historyStorageKey,!0))}getResetBackgroundOptions(){return{url:this.appImManager.lastBackgroundUrl,skipAnimation:!0}}destroySharedMediaTab(e=this.sharedMediaTab){e&&(us(this.sharedMediaTabs,e),e.destroy())}async setAutoDownloadMedia(){this.autoDownload=await M1(this.peerId)}setMessageId(e={}){return this.setPeer({peerId:this.peerId,threadId:this.threadId,...e})}async finishPeerChange(e){if(this.peerChanged)return;const t=this.peerId;this.peerChanged=!0,this.wasAlreadyUsed=!0;const{middleware:s}=e;this.cleanup(!1);const i=this.sharedMediaTab,n=[this.topbar?.finishPeerChange(e),this.bubbles?.finishPeerChange(),this.input?.finishPeerChange(e),i?.fillProfileElements(),this.handleBackgrounds()],r=await Promise.all(n);i?.loadSidebarMedia(!0),s()&&(r.forEach(l=>{l?.()}),i&&(ls.replaceSharedMediaTab(i),this.sharedMediaTabs.filter(l=>l!==i).forEach(l=>this.destroySharedMediaTab(l))),this.container&&(this.container.dataset.type=this.type==="search"?"chat":this.type,this.container.classList.toggle("can-click-date",["chat","discussion","saved"].includes(this.type))),this.log.setPrefix("CHAT-"+t+"-"+this.type),this.isMainChat&&this.appImManager.dispatchEvent("peer_changed",this))}getMessage(e){if(typeof e=="string"){const{peerId:t,mid:s}=Is(e);return fe.getMessageByPeer(t,s)}return fe.getMessageFromStorage(this.messagesStorageKey,e)}getMessageByPeer(e,t){return this.query?fe.getMessageByPeer(e,t):this.getMessage(t)}async getMidsByMid(e,t){return this.managers.appMessagesManager.getMidsByMessage(this.getMessageByPeer(e,t))}getHistoryStorage(e){return this.managers.appMessagesManager.getHistoryStorageTransferable({...this.requestHistoryOptionsPart,threadId:e?void 0:this.threadId}).then(t=>({...t,history:vl.fromJSON(t.historySerialized),searchHistory:t.searchHistorySerialized&&vl.fromJSON(t.searchHistorySerialized)}))}getDialogOrTopic(){return this.managers.dialogsStorage.getAnyDialog(this.peerId,(this.isForum||this.type==="saved")&&this.threadId)}getHistoryMaxId(){return this.getHistoryStorage().then(e=>e.maxId)}_isAnyGroup(e){return e===I.myId||e===cr||this.type==="search"&&this.hashtagType!=="this"||this.managers.appPeersManager.isAnyGroup(e)}resetSearch(){this.searchSignal?.(void 0)}initSearch(e={}){this.peerId&&(e.query||(e.query=""),this.searchSignal(e))}canSend(e){return this.type==="saved"&&this.threadId!==this.peerId?Promise.resolve(!1):this.managers.appMessagesManager.canSendToPeer(this.peerId,this.threadId,e)}isStartButtonNeeded(){return Promise.all([this.managers.appPeersManager.isBot(this.peerId),this.managers.appMessagesManager.getDialogOnly(this.peerId),this.getHistoryStorage(!0),this.peerId.isUser()?this.managers.appProfileManager.isCachedUserBlocked(this.peerId.toUserId()):void 0]).then(([e,t,s,i])=>e?!t&&!s.history.length||i:!1)}isPremiumRequiredToContact(){return this.peerId.isUser()?this.managers.appUsersManager.isPremiumRequiredToContact(this.peerId.toUserId(),!0):Promise.resolve(!1)}getMessageSendingParams(){return{peerId:this.peerId,threadId:this.threadId,updateStickersetOrder:I.settings.stickers.dynamicPackOrder,...this.input&&{...this.input.getReplyTo()||!1,scheduleDate:this.input.scheduleDate,silent:this.input.sendSilent,sendAsPeerId:this.input.sendAsPeerId,effect:this.input.effect()},savedReaction:this.savedReaction}}isOurMessage(e){return this.isMegagroup?!!e.pFlags.out:!!(e.fromId===I.myId||e.fwd_from?.pFlags?.saved_out)}isOutMessage(e){const t=e.fwd_from;return!!(this.isOurMessage(e)&&(!t||this.peerId!==I.myId||this.threadId))}isAvatarNeeded(e){return this.isAnyGroup&&!this.isOutMessage(e)}isPinnedMessagesNeeded(){return this.type==="chat"||this.isForum}isForwardOfForward(e){let t=zS(e);const s=e.fwd_from;return t&&s.saved_from_id&&this.type==="saved"&&at(s.saved_from_id)===this.threadId&&(t=!1),t}getPostAuthor(e){const t=e.fwd_from;if(e.pFlags.post||t?.post_author&&!this.isOutMessage(e))return e.post_author||t?.post_author}async canGiftPremium(){const e=this.peerId;if(!e.isUser())return!1;const[t,s]=await Promise.all([this.managers.appProfileManager.canGiftPremium(this.peerId.toUserId()),fe.isPremiumPurchaseBlocked()]);return e.isUser()&&t&&!s}async openWebApp(e){return Object.assign(e,this.getMessageSendingParams()),e.peerId??(e.peerId=this.peerId),this.appImManager.openWebApp(e)}sendReaction(e){return this.managers.appReactionsManager.sendReaction({sendAsPeerId:this.getMessageSendingParams().sendAsPeerId,...e})}}const rx=ce("<div>"),_r="popup-delete-megagroup-messages";class ox extends ee{constructor(e){super(_r,{body:!0,scrollable:!0,title:M("DeleteOptionsTitle",[e.messages.length]),overlayClosable:!0,buttons:fr([{langKey:"DeleteProceedBtn",isDanger:!0,callback:()=>this.onConfirmClick(),iconLeft:"delete_filled"}])}),this.messages=e.messages,this.onConfirm=e.onConfirm,this.construct()}async onConfirmClick(){const t=this.fields.filter(r=>r.checkboxField.checked&&r.peerId).reduce((r,l)=>{let c=r.get(l.peerId);return c||r.set(l.peerId,c=new Set),c.add(l.action),r},new Map),s=this.messages.map(({mid:r})=>r),i=this.messages[0].peerId,{restricting:n,managers:a}=this;for(const[r,l]of t){const c=[];if(l.has("ban")&&n){const d=this.chatPermissions.takeOut();c.push(a.appChatsManager.editBanned(i.toChatId(),r,d))}else l.has("ban")&&c.push(a.appChatsManager.kickFromChannel(i.toChatId(),r));l.has("report")&&c.push(a.appMessagesManager.reportMessages(i,s,"inputReportReasonSpam")),l.has("delete")?c.push(a.appMessagesManager.doFlushHistory(i,!1,!0,void 0,r)):c.push(a.appMessagesManager.deleteMessages(i,s,!0))}return this.onConfirm?.(),!0}async construct(){const e=$a(this.messages.map(({fromId:g})=>g)),t=this.messages[0].peerId,s=new Co({middleware:this.middlewareHelper.get(),avatarSize:32}),i=[];s.render(e.slice(0,3),i),s.container.classList.add(`${_r}-avatars`),this.header.prepend(s.container);const n=e.length===1,a=[{action:"report",peerIds:e,langKey:"DeleteReportSpam"},{action:"delete",peerIds:e,langKey:n?"DeleteAllFrom":"DeleteAllFromUsers",langArgs:n?[await Oe({peerId:e[0],onlyFirstName:!0})]:void 0},{action:"ban",peerIds:e,langKey:n?"DeleteBan":"DeleteBanUsers",langArgs:n?[await Oe({peerId:e[0],onlyFirstName:!0})]:void 0}],r="delete-fields",l=(...g)=>[r,...g].join("-"),c=g=>{const f=n?[]:g.peerIds.map(y=>{const v=l(g.action,""+y);return{action:g.action,name:v,peerId:y}});return[{action:g.action,text:g.langKey,textArgs:g.langArgs,nested:n?void 0:f,name:n?l(g.action,""+t):l(g.action),peerId:n?g.peerIds[0]:void 0},...f]},d=this.fields=Ln(a.map(c)),h=new qu({fields:d,listenerSetter:this.listenerSetter,round:!0,onRowCreation:(g,f)=>{if(!f.nestedTo)return;g.container.classList.add(`${_r}-row`);const y=document.createElement("div");y.classList.add(`${_r}-row-title`);const v=g.createTitle(),w=es({peerId:f.peerId,middleware:this.middlewareHelper.get(),size:32}),b=new Rt,S=b.update({peerId:f.peerId,onlyFirstName:!0});v.append(b.element),i.push(w.readyThumbPromise,S),y.append(w.node,v),g.container.append(y)},rightButtonIcon:"group_filled",onAnyChange:()=>{m()},onExpand:()=>{const f=Date.now();ll(()=>(this.scrollable.onScroll(),Math.min((Date.now()-f)/300,1)<1))}}),u=d.map(g=>h.createField(g)?.nodes).filter(Boolean),p=document.createElement("div");this.chatPermissions=new af({appendTo:p,chatId:t.toChatId(),listenerSetter:this.listenerSetter},this.managers);let m;this.appendSolid(()=>{const[g,f]=ne([]),[y,v]=ne(!0),w=()=>y()?g().length===1?"DeleteToggleRestrictUser":"DeleteToggleRestrictUsers":g().length===1?"DeleteToggleBanUser":"DeleteToggleBanUsers";return m=()=>{const b=d.filter(S=>S.action==="ban"&&S.checkboxField.checked&&S.peerId).map(({peerId:S})=>S);f(b)},ye(()=>{g().length||v(!0)}),ye(()=>{const b=d.find(C=>C.action==="ban"&&(n?!0:!C.peerId)),S=ke.weakMap.get(b.row.title.firstElementChild);this.restricting=!y(),S.compareAndUpdate({key:y()?n?"DeleteBan":"DeleteBanUsers":n?"DeleteRestrict":"DeleteRestrictUsers"})}),ye(()=>{if(!y()){const S=Date.now(),C=this.scrollable.scrollPosition+this.scrollable.clientSize,L=712+this.scrollable.scrollSize-C;ll(()=>{const E=Math.min((Date.now()-S)/300,1),_=C+L*E;return this.scrollable.scrollPosition=_,E<1})}}),[j(gs,{name:"DeleteAdditionalActions",noShadow:!0,noDelimiter:!0,get children(){return Ln(u)}}),j(gs,{class:`${_r}-permissions`,name:"UserRestrictionsCanDoUsers",get nameArgs(){return[g().length]},noShadow:!0,get style(){return{"max-height":y()?"0px":"712px"}},children:p}),j(gs,{get classList(){return{hide:!g().length}},get children(){return j(Ra,{ref:b=>{b.classList.add("primary")},get title(){return(()=>{const b=rx();return D(b,()=>M(w()),null),D(b,j(xi,{icon:"down",class:`${_r}-expand-row-icon`}),null),Ve(()=>Ce(b,ot(`${_r}-expand-row`,!y()&&"is-expanded"))),b})()},clickable:()=>{v(b=>!b)},color:"primary"})}})]}),await Promise.all(i),this.show()}}class Rl{constructor(e,t,s,i,n){this.peerId=e,this.mids=t,this.type=s,this.onConfirm=i,this.threadId=n,this.construct()}async construct(){let{peerId:e,mids:t,type:s,onConfirm:i,threadId:n}=this;t=t.slice();const a=ee.MANAGERS,r=await Oe({peerId:e,threadId:n,onlyFirstName:!0}),l=await Promise.all(t.map(v=>a.appMessagesManager.getMessageByPeer(e,v))),c=await a.appPeersManager.isMegagroup(e);if(c&&!l.some(v=>v.pFlags.out)){const v=await a.appProfileManager.getParticipants({id:e.toChatId(),filter:{_:"channelParticipantsAdmins"},limit:100});if(!l.some(b=>v.participants.some(S=>gl(S)===b.fromId))){ee.createPopup(ox,{messages:l,onConfirm:this.onConfirm});return}}const d=(v,w,b)=>{i?.(),s===te.Scheduled?a.appMessagesManager.deleteScheduledMessages(e,t):a.appMessagesManager.deleteMessages(e,t,!!w.size||b)},h=[{langKey:"Delete",isDanger:!0,callback:d}],u=[];let p,m,g,f;if(t.length===1?p="DeleteSingleMessagesTitle":(p="DeleteMessagesTitle",m=[M("messages",[t.length])]),c?g=t.length===1?"AreYouSureDeleteSingleMessageMega":"AreYouSureDeleteFewMessagesMega":g=t.length===1?"AreYouSureDeleteSingleMessage":"AreYouSureDeleteFewMessages",!(e===I.myId||s===te.Scheduled))if(e.isUser())u.push({text:"DeleteMessagesOptionAlso",textArgs:[r]});else{const v=await a.appChatsManager.getChat(e.toChatId()),w=fa(v,"delete_messages");if(v._==="chat"){const b=w?t.slice():t.filter((S,C)=>l[C].fromId===I.myId);b.length&&(b.length===t.length?u.push({text:"DeleteForAll"}):(u.push({text:"DeleteMessagesOption"}),g="DeleteMessagesTextGroup",f=[M("messages",[b.length])]))}else{let b;l.find(S=>S&&S.media?._==="messageMediaGiveaway"&&!S.fwdFromId&&(b=S.media)),b&&b.until_date>=Ms(!0)&&(p="BoostingGiveawayDeleteMsgTitle",g="BoostingGiveawayDeleteMsgText",f=[ws(b.until_date,void 0,!0)]),h[0].callback=(S,C)=>d(S,C,!0)}}fr(h),ee.createPopup(Ss,"popup-delete-chat",{peerId:e,threadId:n,titleLangKey:p,titleLangArgs:m,descriptionLangKey:g,descriptionLangArgs:f,buttons:h,checkboxes:u}).show()}}function Yo(o=window.getSelection()){if(!o?.rangeCount)return!0;const e=o.getRangeAt(0);return!!(e.collapsed||!e.START_TO_END)}function CC(o,e,t){return I.managers.appStickersManager.preloadAnimatedEmojiSticker(o).then(({doc:s})=>{if(s)return cs.downloadMedia({media:s}).then(async i=>{const n=$e.active.emojiSticker,a=n0(o),r=xt(),l=await _s.loadAnimationWorker({container:void 0,animationData:i,width:n.width,height:n.height,name:"doc"+s.id,autoplay:!1,loop:!1,toneIndex:a,group:"none",middleware:r.get()});l.addEventListener("firstFrame",()=>{a0(s,l.canvas[0],a),r.destroy()},{once:!0})})})}async function Sr(o){const{emoji:e,div:t,managers:s=I.managers}=o,i=await s.appStickersManager.getAnimatedEmojiSticker(e);if(!i)throw t.classList.add("media-sticker-wrapper"),new Error("no sticker");return Rs({doc:i,play:!0,loop:!1,...o})}const Mu=class Mu extends Ss{constructor(e,t,s,i,n){super("popup-report-messages-confirm",{noTitle:!0,descriptionLangKey:"ReportInfo",buttons:[{langKey:"ReportChat",callback:()=>{if(!l.isValid())return;c=!0,i?.();let d;n?d=this.managers.appStoriesManager.report(e,t,s,l.value):d=this.managers.appMessagesManager.reportMessages(e,t,s,l.value),d.then(()=>{Ee({langPackKey:"ReportSentInfo"})})}}],body:!0});const a=document.createElement("div"),r=100;Sr({div:a,emoji:Mu.STICKER_EMOJI,width:r,height:r}).then(({render:d})=>d).finally(()=>{this.show()}),this.header.replaceWith(a);const l=new _t({label:"ReportHint",maxLength:512,placeholder:"ReportChatDescription"});l.input.addEventListener("input",()=>{this.buttons[0].element.toggleAttribute("disabled",!l.isValid())});let c=!1;i&&this.addEventListener("close",()=>{c||i()},{once:!0}),this.body.append(l.container)}};Mu.STICKER_EMOJI="👮‍♀️";let gu=Mu;class IC extends Ss{constructor(e,t,s,i){super("popup-report-messages",{titleLangKey:i?"Story.ReportTitle":"ChatTitle.ReportMessages",buttons:[],body:!0}),t=t.slice();const n=[["ReportChatSpam","inputReportReasonSpam"],["ReportChatViolence","inputReportReasonViolence"],["ReportChatChild","inputReportReasonChildAbuse"],["ReportChatPornography","inputReportReasonPornography"],["ReportChatOther","inputReportReasonOther"],["ReportChatPersonalDetails","inputReportReasonPersonalDetails"],["ReportChatIllegalDrugs","inputReportReasonIllegalDrugs"]],a="btn-primary btn-transparent";n.forEach(c=>{const d=ze(a,{text:c[0]});this.body.append(d)});const r=CC(gu.STICKER_EMOJI);let l=!1;N(this.body,c=>{const d=U(c.target,"btn-primary"),h=n[Ri(d)][1];r.then(()=>{l=!0,this.hide(),ee.createPopup(gu,e,t,h,s,i)})},{listenerSetter:this.listenerSetter}),s&&this.addEventListener("close",()=>{l||s()},{once:!0}),this.buttonsEl.style.marginTop=".5rem",this.show()}}class lx extends Ss{constructor(){super("popup-sponsored",{titleLangKey:"Chat.Message.Sponsored.What",descriptionLangKey:"Chat.Message.Ad.Text",descriptionLangArgs:[M("Chat.Message.Sponsored.Link")],buttons:[{langKey:"OK",isCancel:!0},{langKey:"Chat.Message.Ad.ReadMore",callback:()=>{ro(ke.format("Chat.Message.Sponsored.Link",!0))},isCancel:!0}],scrollable:!0}),this.scrollable.append(this.description),this.show()}}const Ev=24,cx=vs(Ev,Ev);async function LC({peerId:o,dialogElement:e,reaction:t,middleware:s,isMine:i,date:n,mediaSize:a=cx}){const{dom:r}=e;if(t){const l=document.createElement("div");if(l.classList.add("reacted-list-reaction-icon"),t._==="reactionEmoji"){const c=await I.managers.appReactionsManager.getReaction(t.emoticon);Rs({doc:c.static_icon,div:l,width:24,height:24,middleware:s})}else t._==="reactionCustomEmoji"&&l.append(Kg({docIds:[t.document_id],customEmojiSize:a,middleware:s}));r.listEl.append(l)}if(n&&i){const l=document.createElement("span");r.lastMessageSpan.style.cssText="display: flex !important; align-items: center;";const c=Le(t?"reactions":"checks","reacted-list-checks"),d=document.createDocumentFragment();l.append(ws(n,!1)),d.append(c,l),dt(r.lastMessageSpan,d)}else{const l=await I.managers.appUsersManager.getUser(o.toUserId());dt(r.lastMessageSpan,br(l))}}class dx extends ee{constructor(e){super("popup-reacted-list",{closable:!0,overlayClosable:!0,body:!0}),this.message=e,this.init()}async init(){const e=this.middlewareHelper.get(),t=await this.managers.appMessagesManager.getGroupsFirstMessage(this.message);if(!e())return;const s=await this.managers.appMessagesManager.canViewMessageReadParticipants(t);if(!e())return;const i=new op,n={...t,mid:0,id:0,reactions:{_:"messageReactions",results:[],...t.reactions,pFlags:{},recent_reactions:[]}};n.reactions.results=n.reactions.results.map(d=>({...d,chosen_order:void 0,pFlags:{}})),i.init({context:n,type:vn.Block,middleware:this.middlewareHelper.get()}),i.render(),i.classList.add("no-stripe"),i.classList.remove("has-no-reactions"),i.append(this.btnClose),this.header.append(i);const a=document.createElement("div");a.classList.add("tabs-container"),a.dataset.animation="tabs";const r=new Map;if(n.reactions.results.length){const d=this.createFakeReaction("reactions",n.reactions.results.reduce((h,u)=>h+u.count,0));i.prepend(d),n.reactions.results.unshift(d.reactionCount)}let l=!1;if(s)try{const d=await this.managers.appMessagesManager.getMessageReadParticipants(t.peerId,t.mid);if(!e())return;if(!d.length)throw"";const h=this.createFakeReaction("checks",d.length);i.prepend(h),n.reactions.results.unshift(h.reactionCount),l=!0}catch{}i.customEmojiRenderer&&i.append(i.customEmojiRenderer),n.reactions.results.forEach(d=>{const h=new vi(void 0);h.container.classList.add("tabs-tab");const u=new Pe({noShadow:!0,noDelimiter:!0}),p=Xe.createChatList({dialogSize:72});Xe.setListClickListener({list:p,onFound:()=>{this.hide()},withContext:void 0,autonomous:!1,openInner:!0}),u.content.append(p),h.append(u.container);const m=d.reaction!=="checks",g=d.reaction==="checks";["checks","reactions"].includes(d.reaction)&&(d.reaction=void 0);let f;const y=new nf({scrollable:h,getPromise:async()=>{const v=await this.managers.appMessagesManager.getMessageReactionsListAndReadParticipants(t,void 0,d.reaction,f,m,g);return f=v.nextOffset,await Promise.all(v.combined.map(async({peerId:w,reaction:b,date:S})=>{const C=Xe.addDialogNew({peerId:w,autonomous:!0,container:p,avatarSize:"abitbigger",rippleEnabled:!1,meAsSaved:!1,wrapOptions:{middleware:this.middlewareHelper.get()}});await LC({dialogElement:C,date:S,isMine:t.pFlags.out,middleware:e,peerId:w,reaction:b})})),!f}});r.set(h.container,y),a.append(h.container)}),this.body.append(a);const c=Ml(i,a,(d,h)=>{if(d>=i.childElementCount-(i.customEmojiRenderer?2:1))return!1;const u=i.children[d],p=c.prevId();p!==-1&&i.children[p].setIsChosen(!1),u.setIsChosen(!0),r.get(h).load()},void 0,void 0,void 0,this.listenerSetter);c(0,!1),this.show()}createFakeReaction(e,t){const s=new wr;s.init(vn.Block,this.middlewareHelper.get()),s.reactionCount={_:"reactionCount",count:t,reaction:e},s.setCanRenderAvatars(!1),s.renderCounter();const i=document.createElement("div");return i.classList.add("reaction-counter","reaction-sticker-icon"),i.append(Le(e)),s.prepend(i),s}}const Sa="btn-menu-reactions",_o=Sa+"-reaction",uh=7,eg=28,hx=6,_v=eg+hx*2,ux=!Pi,px=ux&&!1;class Ff{constructor(e){this.render=async(i,n)=>{const a=this.middlewareHelper.get();if(await Promise.all(i),!a())return;if(n&&!this.noMoreButton){const l=it(`${this.openSide==="bottom"?"down":"up"} ${Sa}-more`,{noRipple:!0});this.container.append(l),N(l,this.onMoreClick,{listenerSetter:this.listenerSetter})}return()=>{this.widthContainer.classList.add("is-visible")}},this.reactionToDocId=i=>{let n=i.document_id;return n||(n=this.availableReactions.find(r=>r.reaction===i.emoticon).select_animation.id),n},this.reactionsToDocIds=i=>i.map(this.reactionToDocId),this.loadTags=()=>[this.managers.appReactionsManager.getTagReactions().then(this.reactionsToDocIds)],this.loadEffects=()=>[this.managers.appReactionsManager.getAvailableEffects().then(n=>n.filter(a=>!!a.effect_animation_id).map(a=>a.effect_sticker_id))],this.loadReactions=()=>{const i=Promise.resolve(this.reactions).then(this.reactionsToDocIds),n=this.managers.appReactionsManager.getRecentReactions().then(this.reactionsToDocIds),a=i.then(l=>this.noPacks?l:l.slice(0,16)),r=this.noPacks?void 0:Promise.all([i,n,a]).then(([l,c,d])=>(c=c.filter(h=>!d.includes(h)),c.push(...l.slice(16)),$a(c)));return[a,r].filter(Boolean)},this.onMoreClick=i=>{oe(i);const n=this.noPacks&&this.noSearch,a=new Un({noRegularEmoji:!0,noPacks:this.noPacks,noSearch:this.noSearch,managers:this.managers,mainSets:this.isTags?this.loadTags:this.isEffects?this.loadEffects:this.loadReactions,additionalLocalStickerSet:this.isEffects?async()=>{const c=await this.managers.appReactionsManager.getAvailableEffects();return(await this.splitAvailableEffects(c)).localStickerSet}:void 0,onClick:async c=>{if(c.docId&&c.emoji){const u=(await fe.getAvailableReactions()).find(p=>p.select_animation?.id===c.docId);u&&(c.emoji=u.reaction,delete c.docId)}const d=c.docId?{_:"reactionCustomEmoji",document_id:c.docId}:{_:"reactionEmoji",emoticon:c.emoji};l.resolve(d),r.hideAndDestroy()},freeCustomEmoji:this.freeCustomEmoji,onReady:()=>{const c=r.getElement();if(n){const d=c.querySelector(".emoticons-categories-container");c.style.setProperty("--height",d.offsetHeight+"px")}},searchFetcher:this.isEffects?async c=>{const d=await this.managers.appReactionsManager.searchAvailableEffects({q:c});return this.splitAvailableEffects(d)}:void 0,groupFetcher:this.isEffects?async c=>{const d=await this.managers.appReactionsManager.searchAvailableEffects({emoticon:c.emoticons});return this.splitAvailableEffects(d)}:void 0,showLocks:this.isEffects}),r=new no({tabsToRender:[a],customParentElement:document.body,getOpenPosition:()=>this.getOpenPosition(!this.noPacks)});n&&r.getElement().classList.add("shrink"),this.isEffects&&r.getElement().classList.add("smaller");const l=Pt();this.onFinish(l),r.addEventListener("closed",()=>{l.resolve(void 0),r.hideAndDestroy()}),r.onButtonClick()},this.onMouseMove=i=>{const n=U(i.target,_o);if(!n)return;const a=this.reactionsMap.get(n);if(!a||!a.appear?.paused)return;const r=a.select;r&&r.paused&&(r.autoplay=!0,r.restart())},this.managers=e.managers,this.middlewareHelper=e.middleware?e.middleware.create():xt(),this.onFinish=e.onFinish,this.listenerSetter=new Ut,this.size=e.size??eg,this.openSide=e.openSide??"bottom",this.getOpenPosition=e.getOpenPosition,this.noMoreButton=e.noMoreButton,this.isTags=e.isTags,this.isEffects=e.isEffects,this.middlewareHelper.get().onDestroy(()=>{this.listenerSetter.removeAll()});const t=this.widthContainer=document.createElement("div");if(t.classList.add(Sa+"-container",Sa+"-container-"+e.type,"btn-menu-transition"),this.isTags||this.isEffects){t.classList.add(Sa+"-container-tags");const i=this.isEffects?M("AddEffectMessageHint"):M(I.premium?"Reactions.Tag.Description":"Reactions.Tag.PremiumHint",[ni(()=>{Js.close(),Vt.show({feature:"saved_tags"})})]);i.classList.add(Sa+"-description"),t.append(i)}const s=this.container=document.createElement("div");s.classList.add(Sa),["big"].forEach(i=>{const n=document.createElement("div");n.classList.add(Sa+"-bubble",Sa+"-bubble-"+i),t.append(n)}),this.reactionsMap=new Map,this.animationGroup=`CHAT-MENU-REACTIONS-${Date.now()}`,gt.setOverrideIdleGroup(this.animationGroup,!0),Je||s.addEventListener("mousemove",this.onMouseMove),N(s,i=>{const n=U(i.target,_o);if(!n)return;const a=this.reactionsMap.get(n);a&&this.onFinish(a.reaction)},{listenerSetter:this.listenerSetter}),t.append(s)}renderReactions({type:e,reactions:t},s){s&&(this.availableReactions=s,this.freeCustomEmoji=new Set(this.availableReactions.map(n=>n.select_animation.id)));const i=t.slice(0,uh).map(n=>{const a=n._==="reactionEmoji"?s.find(r=>r.reaction===n.emoticon):void 0;return this.renderReaction(n,a)});return this.render(i,t.length>uh)}renderEffects(e){const t=e.slice(0,uh).map(s=>this.renderReaction({_:"reactionCustomEmoji",document_id:s.effect_sticker_id}));return this.render(t,e.length>uh)}async prepareReactions(e){const t=this.middlewareHelper.get(),s=fe.getAvailableReactions(),i=await this.managers.acknowledged.appReactionsManager.getAvailableReactionsByMessage(e),n=!(s instanceof Promise)&&i.cached,a=rp([i.result,s],async([r,l])=>{if(t()&&r.type!=="chatReactionsNone")return this.reactions=r.reactions,this.noPacks=this.noSearch=r.type!=="chatReactionsAll",this.renderReactions(r,l)});return[n,a]}async prepareEffects(){const e=this.middlewareHelper.get(),t=await this.managers.acknowledged.appReactionsManager.getAvailableEffects(),{cached:s}=t,i=ei(t.result,async n=>{if(e())return this.freeCustomEmoji=new Set(n.filter(a=>!a.pFlags.premium_required).map(a=>a.effect_sticker_id)),this.noPacks=!0,this.renderEffects(n)});return[s,i]}async init(e){let t,s;this.isEffects?[t,s]=await this.prepareEffects():[t,s]=await this.prepareReactions(e),t&&await s,s.then(i=>{i&&(t?i():bs(i))}),this.inited=!0}cleanup(){this.middlewareHelper.clean(),this.reactionsMap.clear(),gt.setOverrideIdleGroup(this.animationGroup,!1),gt.checkAnimations(!0,this.animationGroup,!0)}async splitAvailableEffects(e){const[t,s]=ul(e,a=>!a.effect_animation_id),i=t.map(a=>a.effect_sticker_id),n=await Promise.all(i.map(a=>this.managers.appDocsManager.getDoc(a)));return{emojis:s.map(a=>({emoji:"",docId:a.effect_sticker_id})),localStickerSet:{title:"StickerEffects",stickers:n}}}canUseAnimations(){return st.isAvailable("animations")&&st.isAvailable("stickers_chat")&&!Oi}async renderReaction(e,t){const s=document.createElement("div");s.classList.add(_o);const i=document.createElement("div");i.classList.add(_o+"-scale");const n=document.createElement("div");let a;n.classList.add(_o+"-appear"),this.canUseAnimations()&&(a=document.createElement("div"),a.classList.add(_o+"-select","hide"));const r={selectWrapper:a,appearWrapper:n,reaction:e};this.reactionsMap.set(s,r);const l=this.middlewareHelper.get(),d=eg*(Je||!px?1:1.25),h=[],u={width:d,height:d,skipRatio:1,needFadeIn:!1,withThumb:!1,group:this.animationGroup,middleware:l,loadPromises:h};if(this.container.append(s),!this.canUseAnimations()||!t){delete u.needFadeIn,delete u.withThumb;const p=()=>{Rs({doc:m,div:n,liteModeKey:!1,play:t===void 0?!0:void 0,...u})};let m=t?.static_icon,g=!1;if(!m){const f=await this.managers.acknowledged.appEmojiManager.getCustomEmojiDocument(e.document_id);f.cached?m=await f.result:(delete u.loadPromises,g=!0,f.result.then(y=>(m=y,p())))}g||p()}else{let p=!0;Rs({doc:t.appear_animation,div:n,play:!0,liteModeKey:!1,...u}).then(({render:g})=>g).then(g=>{r.appear=g,g.addEventListener("enterFrame",f=>{g.maxFrame===f&&m.then(y=>{n.classList.add("hide"),a.classList.remove("hide"),p&&(r.select=y,p=!1)},Wt)})},Wt);const m=Rs({doc:t.select_animation,div:a,liteModeKey:!1,...u}).then(({render:g})=>g).then(g=>_s.waitForFirstFrame(g)).catch(Wt)}return i.append(n),a&&i.append(a),s.append(i),Promise.all(h)}}function PC(o){return o&&!o.pFlags.is_outgoing&&!o.pFlags.noforwards&&!o.media?.extended_media}function MC(o){return{width:o.width,height:o.height,top:o.top,right:o.right,bottom:o.bottom,left:o.left}}const mx=ce("<div class=popup-toggle-read-date-title>"),gx=ce("<div class=popup-toggle-read-date-subtitle>"),fx=ce("<button>"),yx=ce("<div class=popup-toggle-read-date-sticker>");class EC extends ee{constructor(e,t){super("popup-toggle-read-date",{closable:!0,overlayClosable:!0,body:!0}),this.peerId=e,this.type=t,this.construct()}_construct(){const e=this,t=n=>{let a;return[(()=>{const r=mx();return D(r,()=>n.title),r})(),(()=>{const r=gx();return D(r,()=>n.text),r})(),(()=>{const r=fx();r.$$click=()=>{n.onClick()instanceof Promise&&jt(a,!0)};const l=a;return typeof l=="function"?wt(l,r):a=r,D(r,()=>M(n.buttonText)),Ve(()=>Ce(r,"btn-primary btn-color-primary popup-toggle-read-date-button"+(n.isPremium?" popup-gift-premium-confirm shimmer":""))),r})()]},i={lastSeen:{title1:"PremiumLastSeenHeader1",text1:"PremiumLastSeenText1",lockedText:"PremiumLastSeenText1Locked",buttonText1:"PremiumLastSeenButton1",onClick:async()=>{await this.managers.appPrivacyManager.setPrivacy("inputPrivacyKeyStatusTimestamp",[{_:"inputPrivacyValueAllowAll"}]),this.hide(),Ee({langPackKey:"PremiumLastSeenSet"})},title2:"PremiumLastSeenHeader2",text2:"PremiumLastSeenText2",buttonText2:"PremiumLastSeenButton2"},readTime:{title1:"PremiumReadHeader1",text1:"PremiumReadText1",lockedText:"PremiumReadText1Locked",buttonText1:"PremiumReadButton1",onClick:async()=>{const n=await this.managers.appPrivacyManager.getGlobalPrivacySettings();await this.managers.appPrivacyManager.setGlobalPrivacySettings({_:"globalPrivacySettings",pFlags:{...n.pFlags,hide_read_marks:void 0}}),this.hide(),Ee({langPackKey:"PremiumReadSet"})},title2:"PremiumReadHeader2",text2:"PremiumReadText2",buttonText2:"PremiumReadButton2"}}[this.type];return[(()=>{const n=yx();return D(n,()=>e.stickerContainer),n})(),j(t,{get title(){return M(i.title1)},get text(){return M(e.isPremiumPurchaseBlocked?i.lockedText:i.text1,[e.titles[0]])},get buttonText(){return i.buttonText1},get onClick(){return i.onClick}}),K((()=>{const n=K(()=>!e.isPremiumPurchaseBlocked);return()=>n()&&[j(GS,{langKey:"PremiumOr"}),j(t,{get title(){return M(i.title2)},get text(){return M(i.text2,[e.titles[1]])},get buttonText(){return i.buttonText2},onClick:()=>{e.hide(),Vt.show()},isPremium:!0})]})())]}async construct(){const[e,t,s]=await Promise.all([Promise.all(new Array(2).fill(0).map(()=>Oe({peerId:this.peerId,onlyFirstName:!0}))),fe.isPremiumPurchaseBlocked(),ju({width:86,height:86,assetName:this.type==="lastSeen"?"large_lastseen":"large_readtime",middleware:this.middlewareHelper.get(),loop:!1,autoplay:st.isAvailable("stickers_chat")}).then(async({container:i,promise:n})=>(await n,i))]);this.titles=e,this.isPremiumPurchaseBlocked=t,this.stickerContainer=s,this.appendSolid(()=>this._construct()),this.show()}}Ui(["click"]);const vx=ce("<div dir=auto>"),bx=ce("<span class=popup-translate-text-text>"),wx=ce('<span class="popup-translate-text-more primary">'),Sx=ce("<div class=popup-translate-preloader>");class _C extends ee{constructor(e){super("popup-translate",{buttons:[{langKey:"OK",isCancel:!0},{langKey:"Telegram.LanguageViewController",callback:()=>(Tf(!1).then(s=>{pl(this.options.peerId).setLanguage(s)}),!1)}],scrollable:!0,body:!0,overlayClosable:!0}),this.options=e,this.header.remove();const t=Hi(()=>this.d(),this.scrollable.container);this.addEventListener("closeAfterTimeout",t)}d(){const e=this,t=this;vr(()=>{setTimeout(()=>{this.show()},0)});let s=this.options.textWithEntities;this.options.message&&(s={_:"textWithEntities",text:this.options.message.message,entities:this.options.message.totalEntities});const i={middleware:this.middlewareHelper.get(),textColor:"primary-text-color"},n=p=>{let m;const g=(()=>{const y=vx(),v=m;return typeof v=="function"?wt(v,y):m=y,D(y,()=>p.children),Ve(()=>Ce(y,ot("popup-translate-text","spoilers-container",p.limited&&"is-limited"))),y})(),f=y=>{const v=m&&Ud(m,y);v&&(m.removeEventListener("click",f,{capture:!0}),this.hideWithCallback(v))};return m.addEventListener("click",f,{capture:!0}),g},a=(p,m)=>{const g=this,[f,y]=ne(p.text.length>m),[v,w]=ne();return ye(()=>{const b=Yt(p.text,{...i,entities:p.entities,noTextFormat:f()});w(Wo(b))}),j(n,{get limited(){return f()},get children(){return j(an,{get when(){return f()},get fallback(){return v()},get children(){return[(()=>{const b=bx();return D(b,v),b})(),(()=>{const b=wx();return b.$$click=()=>{y(!1),setTimeout(()=>{g.scrollable.onScroll()},0)},D(b,()=>M("Show")),b})()]}})}})},r=pl(this.options.peerId),l=rn(void 0,!0),[c,d]=ne(!0),h=[],u=j(ow,{get peerId(){return e.options.peerId},get message(){return e.options.message},get textWithEntities(){return e.options.textWithEntities},get richTextOptions(){return{...i,loadPromises:h}},enabled:!0});return Promise.all(h).then(()=>{d(!1),setTimeout(()=>{this.scrollable.onScroll()},0)}),[j(gs,{noShadow:!0,get name(){return`Language.${t.options.detectedLanguage}`},get children(){return a(s,120)}}),j(gs,{noShadow:!0,get name(){return`Language.${r.language()}`},fakeGradientDelimiter:!0,get children(){return j(an,{get when(){return!c()},get fallback(){return(()=>{const p=Sx();return D(p,l),p})()},get children(){return j(n,{children:u})}})}})]}}Ui(["click"]);function Cx(o){const t=document.getSelection().getRangeAt(0),{startContainer:s,startOffset:i,endContainer:n,endOffset:a}=t,r=s.nodeValue,l=n.nodeValue,c="",d=U(o,"spoilers-container"),u=[".reply"].map(P=>{const L=d.querySelector(P);if(L){const E=document.createTextNode("");return L.replaceWith(E),[E,L]}}).filter(Boolean);let p,m;r===null&&s.parentNode.insertBefore(p=document.createTextNode(c),i===0?s:s.nextSibling),l===null&&n.parentNode.insertBefore(m=document.createTextNode(c),a===0?n:n.nextSibling),s===n&&!p?s.nodeValue=r.slice(0,i)+c+r.slice(i,a)+c+r.slice(a):(m||(n.nodeValue=l.slice(0,a)+c+l.slice(a)),p||(s.nodeValue=r.slice(0,i)+c+r.slice(i)));const{value:g}=fn(d),f=g.indexOf(c),y=g.indexOf(c,f+1)-1;p?p.remove():s.nodeValue=r,m?m.remove():n.nodeValue=l;const v=new Set(["messageEntityBold","messageEntityItalic","messageEntityUnderline","messageEntityStrike","messageEntitySpoiler","messageEntityCustomEmoji","messageEntityEmoji"]),{value:w,entities:b}=fn(d,!0),S=w.slice(f,y);for(let P=0;P<b.length;++P){const L=b[P],E=L.offset;if(E+L.length<f||E>=y||!v.has(L._)){b.splice(P--,1);continue}L.offset=Math.max(E-f,0);const k=Math.max(f-E,0),x=y-f-L.offset;L.length=Math.min(L.length-k,x)}return u.forEach(([P,L])=>P.replaceWith(L)),Nr(),{text:S,entities:b.length?b:void 0,offset:f}}async function kC(o){const[e]=El();if(!o||!e.translations.showInMenu)return;const t=await iw(o);if(!e.translations.doNotTranslate.includes(t))return t}const TC=o=>{const e=(n,a)=>{const r=o.transitions.get(n);ye(l=>{const c=r();if(l||c)return c||a(),!0})},t=new Map,s=(n,a)=>{Jt(r=>{t.set(n,r),e(n,()=>{r(),a()}),ut(()=>{t.get(n)===r&&t.delete(n)})})};return ut(()=>{t.forEach(n=>n())}),gf(ff(()=>o.children).toArray,{exitMethod:"keep-relative",onChange:({added:n,removed:a,finishRemoved:r})=>{for(const c of n)t.get(c)?.();if(o.noWait?.()||!st.isAvailable("animations")){r(a);return}const l=[];for(const c of a){if(!o.transitions.has(c)){l.push(c);continue}s(c,()=>{r([c])})}l.length&&r(l)}})},Ix=ce("<div class=popup-report-ad-tab-options>"),Lx=ce('<div class="popup-report-ad-tabs tabs-container">'),Px=ce('<div class="transition slide-fade"><div class=transition-item></div><div class=transition-item><div class=popup-report-ad-header-rows><div class=popup-report-ad-header-title></div><div class=popup-report-ad-header-subtitle>');class Mx extends ee{constructor(t,s,i){super("popup-report-ad",{closable:!0,overlayClosable:!0,body:!0,onBackClick:()=>(this.setSections(n=>n.slice(0,-1)),!1),title:!0,scrollable:!0});Lr(this,"report",t=>this.managers.appChatsManager.reportSponsoredMessage(this.peerId.toChatId(),this.sponsoredMessage.random_id,t));this.peerId=t,this.sponsoredMessage=s,this.onAdHide=i,this.construct()}renderSection(t,s){const[i,n]=ne(void 0,{equals:!1}),[a]=zo(()=>i()?.option,this.report);ye(()=>{const m=a();if(!m)return;const g=m._==="channels.sponsoredMessageReportResultReported",f=m._==="channels.sponsoredMessageReportResultAdsHidden";if(g||f){this.hide(),this.onAdHide?.(),Ee({langPackKey:g?"Ads.Reported":"AdHidden"});return}this.setSections(y=>[...y,this.renderSection(m,Et(i).text)]),n()});const[r,l]=ne(!1);let c;const d=m=>{if(m.target!==u)return;const g=m.type==="transitionstart";l(g),clearTimeout(c),g&&(c=window.setTimeout(()=>{l(!1)},300))},h=48*t.options.length;let u;const p=K(()=>this.activeSection()?.maxHeight);return j(gs,{ref(m){const g=u;typeof g=="function"?g(m):u=m},get name(){return _e(t.title)},caption:"ReportAdLearnMore",class:"popup-report-ad-tab tabs-tab",noShadow:!0,noDelimiter:!0,onTransitionStart:d,onTransitionEnd:d,get children(){const m=Ix();return D(m,j(ti,{get each(){return t.options},children:g=>j(Ra,{get title(){return _e(g.text)},clickable:()=>n(g),get rightContent(){return Le("next","popup-report-ad-option-arrow-icon")}})})),Ve(()=>(p()||h)+"px"!=null?m.style.setProperty("height",(p()||h)+"px"):m.style.removeProperty("height")),m}}),this.transitions.set(u,r),ut(()=>this.transitions.delete(u)),{container:u,transition:r,maxHeight:h,prevText:s}}_construct(){const t=this,[s,i]=ne([]),[n,a]=ne();this.sections=s,this.setSections=i,this.activeSection=n,i([this.renderSection(this.reportResult)]),ye(()=>{const p=s();this.btnCloseAnimatedIcon.classList.toggle("state-back",p.length>1),c(p.length-1),u(p.length===1?0:1),Et(n)||a(p[p.length-1])});let r;const l=(()=>{const p=Lx(),m=r;return typeof m=="function"?wt(m,p):r=p,D(p,j(TC,{get transitions(){return t.transitions},get children(){return s().map(({container:g})=>g)}})),p})(),c=Na({content:r,type:"tabs",transitionTime:150,animateFirst:!1,onTransitionStartAfter:()=>{a(s()[s().length-1])}}),d=K(p=>n()?.prevText??p);let h;this.title.append((()=>{const p=Px(),m=p.firstChild,g=m.nextSibling,f=g.firstChild,y=f.firstChild,v=y.nextSibling,w=h;return typeof w=="function"?wt(w,p):h=p,D(m,()=>M("ReportAd")),D(y,()=>M("ReportAd")),D(v,()=>_e(d())),p})());const u=Na({content:h,type:"slide-fade",transitionTime:400,isHeavy:!1});return l}async construct(){this.transitions=new WeakMap,this.reportResult=await this.report(new Uint8Array),this.appendSolid(()=>this._construct()),this.show()}}class ki{constructor(e,t){this.chat=e,this.managers=t,this.onContextMenu=s=>{let i,n,a;try{n=U(s.target,"bubble-content-wrapper"),i=n?n.parentElement:U(s.target,"bubble"),a=U(s.target,"bubbles-group-avatar")||void 0}catch{}if((!i||i.classList.contains("bubble-first"))&&!a)return;let r=this.element;if((s instanceof MouseEvent||s.hasOwnProperty("preventDefault"))&&s.preventDefault(),r&&r.classList.contains("active"))return!1;(s instanceof MouseEvent||s.hasOwnProperty("cancelBubble"))&&(s.cancelBubble=!0);let l=a?0:+i.dataset.mid;if(!l&&l!==0)return;if(a&&!a.dataset.peerId){Ee({langPackKey:"HidAccount"});return}const c=U(s.target,"reaction-tag");(async()=>{const h=this.isSponsored=l<0;if(this.isSelectable=this.chat.selection.canSelectBubble(i),this.messagePeerId=i?i.dataset.peerId.toPeerId():void 0,this.peerId=this.messagePeerId??this.chat.peerId,this.target=s.target,this.isTextSelected=!Yo(),this.isAnchorTarget=this.target.tagName==="A"&&(this.target.target==="_blank"||this.target.classList.contains("anchor-url")),this.isUsernameTarget=this.target.tagName==="A"&&this.target.classList.contains("mention"),this.isTag=!!c,this.reactionElement=c,this.isTag&&!I.premium){Vt.show({feature:"saved_tags"});return}if(this.isTextSelected){const C=document.getSelection().getRangeAt(0);this.isTextFromMultipleMessagesSelected=U(C.startContainer.parentElement,"spoilers-container")!==U(C.endContainer.parentElement,"spoilers-container")}else this.isTextFromMultipleMessagesSelected=!1;this.sponsoredMessage=h?i.message.sponsoredMessage:void 0;const u=a?[]:await this.chat.getMidsByMid(this.messagePeerId,l);if(this.chat.selection.isSelecting&&!n&&l){if(h)return;if(u.length>1){const C=this.chat.selection.isMidSelected(this.messagePeerId,l)?l:u.find(P=>this.chat.selection.isMidSelected(this.messagePeerId,P));C&&(l=C)}}this.isOverBubble=!!n,this.avatarPeerId=a&&a.dataset.peerId.toPeerId();const p=U(this.target,"grouped-item");this.isTargetAGroupedItem=!!p,p?this.mid=+p.dataset.mid:this.mid=l,this.isLegacy=this.messagePeerId&&this.messagePeerId!==this.peerId,this.isSelected=this.chat.selection.isMidSelected(this.messagePeerId,this.mid),this.message=a?void 0:i.message||this.chat.getMessageByPeer(this.messagePeerId,this.mid),this.groupedMessages=this.message?.grouped_id?await this.managers.appMessagesManager.getMessagesByGroupedId(this.message.grouped_id):void 0,!p&&this.groupedMessages&&(this.message=ou(this.groupedMessages)),this.mainMessage=this.groupedMessages?ou(this.groupedMessages):this.message,this.selectedMessages=this.chat.selection.isSelecting&&!a?await this.chat.selection.getSelectedMessages():void 0,this.noForwards=this.message&&!h&&!(await Promise.all((this.selectedMessages||[this.message]).map(C=>this.managers.appMessagesManager.canForward(C)))).every(Boolean),this.viewerPeerId=void 0,this.canOpenReactedList=void 0,this.linkToMessage=await this.getUrlToMessage(),this.selectedMessagesText=await this.getSelectedMessagesText(),this.messageLanguage=this.selectedMessages||!this.message?void 0:await kC(this.message.message);const m=await this.init();if(!m)return;r=m.element;const{cleanup:g,destroy:f,menuPadding:y,reactionsMenu:v,reactionsMenuPosition:w}=m,b=v&&ki.appendReactionsMenu({element:r,reactionsMenu:v,reactionsMenuPosition:w}),S=!i||i.classList.contains("is-in")?"left":"right";Tl(s.touches?s.touches[0]:s,r,S,y),Js.openBtnMenu(r,()=>{b?.onClose(),this.mid=0,this.peerId=void 0,this.target=null,this.viewerPeerId=void 0,this.canOpenReactedList=void 0,g(),setTimeout(()=>{f()},300)}),b?.onAfterInit()})()},this.onSendScheduledClick=async()=>{this.chat.selection.isSelecting?fs(this.chat.selection.selectionSendNowBtn):ee.createPopup(ZS,this.peerId,await this.chat.getMidsByMid(this.messagePeerId,this.mid))},this.onReplyClick=async()=>{const{mid:s,peerId:i}=this,n={replyToMsgId:s};if(!await this.chat.canSend()){n.replyToPeerId=i,this.chat.input.createReplyPicker(n);return}this.chat.input.initMessageReply(n)},this.onFaveStickerClick=s=>{const i=this.message.media.document,n=i.id;i.type==="gif"?this.managers.appGifsManager.saveGif(n,s):this.managers.appStickersManager.faveSticker(n,s)},this.onEditClick=()=>{const s=this.getMessageWithText();this.chat.input.initMessageEditing(this.isTargetAGroupedItem?this.mid:s.mid)},this.onEditFactCheckClick=async()=>{const{mainMessage:s}=this,i=s.factcheck,n=new ke.IntlElement({key:"Done"}),a={text:n.element},r=new _t({placeholder:"FactCheckPlaceholder",withLinebreaks:!0,onRawInput:i?h=>{n.compareAndUpdate({key:h?"Done":"Remove"}),a.element&&(a.element.classList.toggle("primary",!!h),a.element.classList.toggle("danger",!h))}:void 0,canHaveFormatting:["bold","italic","link"]});i&&r.setValueSilently(Au(i.text.text,{entities:i.text.entities}));try{await Ct({titleLangKey:"FactCheckDialog",inputField:r,button:a,confirmShortcutIsSendShortcut:!0})}catch{return}const{value:l,entities:c}=fn(r.input,!0,!1),d=l?{_:"textWithEntities",text:l,entities:c}:void 0;i&&Di(i.text,d)||this.managers.appMessagesManager.updateFactCheck(s.peerId,s.mid,d).then(()=>{Ee({langPackKey:l?"FactCheckEdited":"FactCheckDeleted"})})},this.onCopyClick=async()=>{if(Yo()){const{text:s,html:i}=this.selectedMessagesText;Fs(s,i)}else document.execCommand("copy")},this.onCopyAnchorLinkClick=()=>{let s=this.target.href;s=s.replace(/^mailto:/,""),Fs(s)},this.onCopyLinkClick=()=>{const{url:s,isPrivate:i}=this.linkToMessage,n=i?"LinkCopiedPrivateInfo":"LinkCopied";zs(ke.format(n,!0)),Fs(s)},this.onPinClick=()=>{ee.createPopup(Zc,this.messagePeerId,this.mid)},this.onUnpinClick=()=>{ee.createPopup(Zc,this.messagePeerId,this.mid,!0)},this.onRetractVote=()=>{this.managers.appPollsManager.sendVote(this.message,[])},this.onStopPoll=()=>{this.managers.appPollsManager.stopPoll(this.message)},this.onForwardClick=async()=>{if(this.chat.selection.isSelecting)fs(this.chat.selection.selectionForwardBtn);else{const s=this.messagePeerId,i=this.isTargetAGroupedItem?[this.mid]:await this.chat.getMidsByMid(s,this.mid);va.create({[s]:i})}},this.onSelectClick=()=>{this.chat.selection.toggleByElement(U(this.target,"grouped-item")||U(this.target,"bubble"))},this.onClearSelectionClick=()=>{this.chat.selection.cancelSelection()},this.onDeleteClick=async()=>{if(this.chat.selection.isSelecting){fs(this.chat.selection.selectionDeleteBtn);return}const{message:s}=this,{peerId:i,mid:n}=s;ee.createPopup(Rl,i,this.isTargetAGroupedItem?[n]:await this.chat.getMidsByMid(i,n),this.chat.type)},this.onQuoteClick=async()=>{const s=this.getMessageWithText(),{peerId:i,mid:n}=s;let{text:a,entities:r=[],offset:l}=this.getQuotedText(),d=(await this.managers.apiManager.getAppConfig()).quote_length_max??1024;const h=a.length-a.trimEnd().length;h&&(d=Math.min(a.length-h,d)),a.length>d&&(a=a.slice(0,d),r=r.filter(m=>m.offset<d).map(m=>(m.offset+m.length>d&&(m.length=d-m.offset),m)));const u={text:a,entities:r.length?r:void 0,offset:l},p={replyToMsgId:n,replyToQuote:u};if(!await this.chat.canSend()){p.replyToPeerId=i,this.chat.input.createReplyPicker(p);return}this.chat.input.initMessageReply(p)},this.onStatisticsClick=()=>{this.chat.topbar.appSidebarRight.createTab(Nd).open(this.messagePeerId.toChatId(),this.mid),this.chat.topbar.appSidebarRight.toggleSidebar(!0)},this.listenerSetter=new Ut,this.attachListenerSetter=new Ut,this.middleware=xt()}attachTo(e){this.attachListenerSetter.removeAll(),Je?N(e,t=>{if(this.chat.selection.isSelecting)return;this.chat.log("touchend",t);const s=[".name",".peer-title",".reply",".document","audio-element","a",".bubble-beside-button","replies-element","[data-saved-from]:not(.bubble)","poll-element",".attachment",".reply-markup-button",".bubble-view-button",".webpage",".bubbles-group-avatar",".bubble-service-button"];!t.target.closest(s.join(", "))&&(oe(t),this.onContextMenu(t))},{listenerSetter:this.attachListenerSetter}):za({element:e,callback:this.onContextMenu,listenerSetter:this.attachListenerSetter})}cleanup(){this.listenerSetter.removeAll(),this.reactionsMenu&&this.reactionsMenu.cleanup(),this.middleware.clean()}destroy(){this.cleanup(),this.attachListenerSetter.removeAll()}async filterButtons(e){return Zi(e,async t=>{let s;return this.isSponsored&&!t.isSponsored||!this.isSponsored&&t.isSponsored?!1:(this.chat.selection.isSelecting&&!t.withSelection?s=!1:s=(this.isOverBubble||Je,await t.verify()),!!s)})}setButtons(){if(this.isTag){const s=this.reactionElement.findTitle(),i=this.reactionElement.reactionCount,n=s?"SavedTagRenameTag":"SavedTagLabelTag";this.buttons=[{icon:"tag_filter",text:"SavedTagFilterByTag",onClick:()=>{this.chat.initSearch({reaction:i.reaction})},verify:()=>!0},{icon:"tag_name",text:n,onClick:async()=>{const a=new _t({maxLength:12,label:"SavedTagLabelPlaceholder"});s&&a.setOriginalValue(s),await Ct({titleLangKey:n,descriptionLangKey:"SavedTagLabelTagText",button:{langKey:"Save"},inputField:a}),this.managers.appReactionsManager.updateSavedReactionTag(i.reaction,a.value)},verify:()=>!0},{icon:"tag_crossed",text:"SavedTagRemoveTag",onClick:()=>{this.chat.sendReaction({message:this.message,reaction:i.reaction})},verify:()=>!0,danger:!0},{text:"Loading",onClick:()=>{this.emojiInputsPromise.then(a=>{ee.createPopup(Cn,a,!0,this.chat.input).show()})},verify:()=>i.reaction._==="reactionCustomEmoji",localName:"emojis"}];return}if(this.avatarPeerId!==void 0){const s=()=>{this.chat.appImManager.setInnerPeer({peerId:this.avatarPeerId})};this.buttons=[{icon:"message",text:"SendMessage",onClick:s,verify:()=>this.chat.peerId!==this.avatarPeerId&&this.avatarPeerId.isUser()},{icon:"newgroup",text:"OpenGroup2",onClick:s,verify:()=>this.chat.peerId!==this.avatarPeerId&&this.managers.appPeersManager.isAnyGroup(this.avatarPeerId)},{icon:"newchannel",text:"OpenChannel2",onClick:s,verify:()=>this.chat.peerId!==this.avatarPeerId&&this.managers.appPeersManager.isBroadcast(this.avatarPeerId)},{icon:"mention",text:"Mention",onClick:()=>{this.chat.input.mentionUser(this.avatarPeerId,!1)},verify:()=>this.chat.canSend("send_plain")},{icon:"search",text:"Search",onClick:()=>{this.chat.initSearch({filterPeerId:this.avatarPeerId})},verify:()=>this.chat.isRealGroup}];return}const e=this.message.media?.document?.type==="gif",t=async s=>{const i=this.message.media?.document;if(!i?.sticker&&!e)return!1;const n=await(e?this.managers.acknowledged.appGifsManager.getGifs():this.managers.acknowledged.appStickersManager.getFavedStickersStickers());if(!n.cached)return!1;const a=(await n.result).some(r=>r.id===i.id);return s?!a:a};this.buttons=[{onClick:()=>{this.canViewReadTime===!1&&ee.createPopup(EC,this.peerId,"readTime")},verify:()=>this.peerId.isUser()&&this.managers.appMessagesManager.canViewMessageReadParticipants(this.message),notDirect:()=>!0,localName:"views",checkForClose:()=>this.canViewReadTime!==void 0},{icon:"send2",text:"MessageScheduleSend",onClick:this.onSendScheduledClick,verify:()=>this.chat.type===te.Scheduled&&!this.message.pFlags.is_outgoing},{icon:"send2",text:"Message.Context.Selection.SendNow",onClick:this.onSendScheduledClick,verify:()=>this.chat.type===te.Scheduled&&this.isSelected&&!this.chat.selection.selectionSendNowBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"schedule",text:"MessageScheduleEditTime",onClick:()=>{this.chat.input.scheduleSending(()=>{this.message,this.managers.appMessagesManager.editMessage(this.message,this.message.message,{scheduleDate:this.chat.input.scheduleDate,entities:this.message.entities}),this.chat.input.onMessageSent(!1,!1)},new Date(this.message.date*1e3))},verify:()=>this.chat.type===te.Scheduled},{icon:"message_quote",text:"Quote",onClick:this.onQuoteClick,verify:async()=>!this.message.pFlags.is_outgoing&&!!this.chat.input.messageInput&&!!this.message.message&&this.isTextSelected&&!this.isTextFromMultipleMessagesSelected&&(!pl(this.peerId).enabled()||this.message.pFlags.out)&&(this.chat.bubbles.canForward(this.message)||this.chat.canSend())},{icon:"reply",text:"Reply",onClick:this.onReplyClick,verify:async()=>!this.isLegacy&&!this.message.pFlags.is_outgoing&&!!this.chat.input.messageInput&&this.chat.type!==te.Scheduled&&(this.chat.bubbles.canForward(this.message)||this.chat.canSend())},{icon:"bubblereply",text:"ViewReplies",textArgs:[this.message?.replies?.replies],onClick:()=>{this.chat.appImManager.openThread({peerId:this.message.peerId,threadId:this.message.mid,lastMsgId:0})},verify:()=>{if(this.chat.threadId)return!1;const s=this.message?.replies;return!!(s&&!s.pFlags.comments&&s.replies)}},{icon:e?"gifs":"favourites",text:e?"SaveToGIFs":"AddToFavorites",onClick:this.onFaveStickerClick.bind(this,!1),verify:()=>t(!0)},{icon:e?"crossgif":"crossstar",text:e?"Message.Context.RemoveGif":"DeleteFromFavorites",onClick:this.onFaveStickerClick.bind(this,!0),verify:()=>t(!1)},{icon:"edit",text:"Edit",onClick:this.onEditClick,verify:async()=>await this.managers.appMessagesManager.canEditMessage(this.message,"text")&&!!this.chat.input.messageInput},{icon:"factcheck",text:this.mainMessage?.factcheck?"EditFactCheck":"AddFactCheck",onClick:this.onEditFactCheckClick,verify:()=>this.mainMessage&&this.managers.appMessagesManager.canUpdateFactCheck(this.mainMessage.peerId,this.mainMessage.mid)},{icon:"copy",text:"Copy",onClick:this.onCopyClick,verify:()=>!this.noForwards&&!!this.message.message&&!this.isTextSelected&&(!this.isAnchorTarget||this.message.message!==this.target.innerText)},{icon:"copy",text:"Chat.CopySelectedText",onClick:this.onCopyClick,verify:()=>!this.noForwards&&!!this.message.message&&this.isTextSelected},{icon:"search",text:"Chat.SearchSelected",onClick:()=>{const s=document.getSelection();this.chat.initSearch({query:s.toString()})},verify:()=>!!this.message.message&&this.isTextSelected},{icon:"copy",text:"Message.Context.Selection.Copy",onClick:this.onCopyClick,verify:async()=>{if(!this.isSelected||this.noForwards)return!1;for(const[s,i]of this.chat.selection.selectedMids){const n=`${s}_${this.chat.type===te.Scheduled?"scheduled":"history"}`;for(const a of i)if((await this.managers.appMessagesManager.getMessageFromStorage(n,a)).message)return!0}return!1},notDirect:()=>!0,withSelection:!0},{icon:"copy",text:"CopyLink",onClick:this.onCopyAnchorLinkClick,verify:()=>this.isAnchorTarget,withSelection:!0},{icon:"copy",text:"Text.Context.Copy.Username",onClick:()=>{Fs(this.target.textContent)},verify:()=>this.isUsernameTarget,withSelection:!0},{icon:"copy",text:"Text.Context.Copy.Hashtag",onClick:()=>{Fs(this.target.textContent)},verify:()=>this.target.classList.contains("anchor-hashtag"),withSelection:!0},{icon:"premium_translate",text:"TranslateMessage",onClick:()=>{if(!I.premium)Vt.show({feature:"translations"});else{let s;if(this.isTextSelected){const{text:i,entities:n}=this.getQuotedText();s={_:"textWithEntities",text:i,entities:n}}ee.createPopup(_C,{peerId:s?this.peerId:this.message.peerId,textWithEntities:s,message:s?void 0:this.message,detectedLanguage:this.messageLanguage})}},verify:()=>!!this.messageLanguage},{icon:"link",text:"MessageContext.CopyMessageLink1",onClick:this.onCopyLinkClick,verify:async()=>!this.isLegacy&&await this.managers.appPeersManager.isChannel(this.peerId)&&!this.message.pFlags.is_outgoing},{icon:"pin",text:"Message.Context.Pin",onClick:this.onPinClick,verify:async()=>!this.isLegacy&&!this.message.pFlags.is_outgoing&&this.message._!=="messageService"&&!this.message.pFlags.pinned&&await this.managers.appPeersManager.canPinMessage(this.message.peerId)&&this.chat.type!==te.Scheduled},{icon:"unpin",text:"Message.Context.Unpin",onClick:this.onUnpinClick,verify:()=>this.message.pFlags.pinned&&this.managers.appPeersManager.canPinMessage(this.message.peerId)},{icon:"download",text:"MediaViewer.Context.Download",onClick:()=>ki.onDownloadClick(this.message,this.noForwards),verify:()=>ki.canDownload(this.message,this.target,this.noForwards)},{icon:"checkretract",text:"Chat.Poll.Unvote",onClick:this.onRetractVote,verify:()=>{const s=this.message.media?.poll;return s&&s.chosenIndexes.length&&!s.pFlags.closed&&!s.pFlags.quiz}},{icon:"stop",text:"Chat.Poll.Stop",onClick:this.onStopPoll,verify:async()=>{const s=this.message.media?.poll;return await this.managers.appMessagesManager.canEditMessage(this.message,"poll")&&s&&!s.pFlags.closed&&!this.message.pFlags.is_outgoing}},{icon:"statistics",text:"ViewStatistics",onClick:this.onStatisticsClick,verify:async()=>await this.managers.appPeersManager.isBroadcast(this.messagePeerId)&&await this.managers.appProfileManager.canViewStatistics(this.messagePeerId)&&!this.message.pFlags.is_outgoing},{icon:"forward",text:"Forward",onClick:this.onForwardClick,verify:()=>!this.noForwards&&this.chat.type!==te.Scheduled&&(!this.message.pFlags.is_outgoing||this.message.fromId===Cd)&&this.message._!=="messageService"},{icon:"forward",text:"Message.Context.Selection.Forward",onClick:this.onForwardClick,verify:()=>this.chat.selection.selectionForwardBtn&&this.isSelected&&!this.chat.selection.selectionForwardBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"download",text:"Message.Context.Selection.Download",onClick:()=>ki.onDownloadClick(this.selectedMessages,this.noForwards),verify:()=>this.selectedMessages&&ki.canDownload(this.selectedMessages,void 0,this.noForwards),withSelection:!0},{icon:"flag",text:"ReportChat",onClick:()=>{ee.createPopup(IC,this.messagePeerId,[this.mid])},verify:()=>!this.message.pFlags.out&&this.message._==="message"&&!this.message.pFlags.is_outgoing&&this.managers.appPeersManager.isChannel(this.messagePeerId),notDirect:()=>!0,withSelection:!0},{icon:"select",text:"Message.Context.Select",onClick:this.onSelectClick,verify:()=>!this.message.action&&!this.isSelected&&this.isSelectable,notDirect:()=>!0,withSelection:!0},{icon:"select",text:"Message.Context.Selection.Clear",onClick:this.onClearSelectionClick,verify:()=>this.isSelected,notDirect:()=>!0,withSelection:!0},{onClick:()=>{if(this.viewerPeerId,this.canOpenReactedList)ee.createPopup(dx,this.message);else return!1},verify:()=>!this.peerId.isUser()&&(!!this.message.reactions?.recent_reactions?.length||this.managers.appMessagesManager.canViewMessageReadParticipants(this.message)),notDirect:()=>!0,localName:"views"},{icon:"delete",className:"danger",text:"Delete",onClick:this.onDeleteClick,verify:async()=>this.managers.appMessagesManager.canDeleteMessage(this.message)},{icon:"delete",className:"danger",text:"Message.Context.Selection.Delete",onClick:this.onDeleteClick,verify:()=>this.isSelected&&!this.chat.selection.selectionDeleteBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"info",text:"Chat.Message.Sponsored.What",onClick:()=>{ee.createPopup(lx)},verify:()=>this.isSponsored&&!this.sponsoredMessage.pFlags.can_report,isSponsored:!0},{icon:"info",text:"AboutRevenueSharingAds",onClick:()=>{ee.createPopup(WS)},verify:()=>this.isSponsored&&!!this.sponsoredMessage.pFlags.can_report,isSponsored:!0},{icon:"hand",text:"HideAd",onClick:()=>{Vt.show({feature:"no_ads"})},verify:()=>this.isSponsored&&!this.sponsoredMessage.pFlags.can_report,isSponsored:!0},{icon:"hand",text:"ReportAd",onClick:()=>{ee.createPopup(Mx,this.peerId,this.sponsoredMessage,()=>{this.chat.bubbles.deleteMessagesByIds([$t(this.message.peerId,this.message.mid)],!0)})},verify:()=>this.isSponsored&&!!this.sponsoredMessage.pFlags.can_report,isSponsored:!0},{icon:"crossround",text:"RemoveAds",onClick:()=>{Vt.show({feature:"no_ads"})},verify:()=>this.isSponsored&&!!this.sponsoredMessage.pFlags.can_report,isSponsored:!0},{icon:"copy",text:"Copy",onClick:this.onCopyClick,verify:()=>this.isSponsored,isSponsored:!0},{text:"Loading",onClick:()=>{this.emojiInputsPromise.then(s=>{ee.createPopup(Cn,s,!0,this.chat.input).show()})},verify:()=>!!this.getUniqueCustomEmojisFromMessage().length,notDirect:()=>!0,localName:"emojis"},{regularText:this.sponsoredMessage?.sponsor_info?_e(this.sponsoredMessage.sponsor_info):void 0,separator:!0,secondary:!0,onClick:()=>Fs(this.sponsoredMessage.sponsor_info),verify:()=>!!this.sponsoredMessage.sponsor_info,isSponsored:!0},{regularText:this.sponsoredMessage?.additional_info?_e(this.sponsoredMessage.additional_info):void 0,separator:!0,secondary:!0,onClick:()=>Fs(this.sponsoredMessage.additional_info),verify:()=>!!this.sponsoredMessage.additional_info,isSponsored:!0}]}static canDownload(e,t,s){if(Array.isArray(e))return e.some(r=>ki.canDownload(r,t,s));if(!PC(e)||s)return!1;const i=!!e.media?.photo;let n=!1;if(i)n=!0;else{if(!e.media?.document)return!1;n=!0}let a=!t||!!Je;return n&&t&&(a||(a=!!(U(t,"document")||U(t,"audio")||U(t,"media-sticker-wrapper")||U(t,"media-photo")||U(t,"media-video")))),n&&a}getMessageWithText(){return this.groupedMessages&&LS(this.groupedMessages)||this.message}getUniqueCustomEmojisFromMessage(){const e=[],t=this.getMessageWithText(),s=t.entities;if(s){const n=s.filter(a=>a._==="messageEntityCustomEmoji");e.push(...n.map(a=>a.document_id))}const i=t.reactions;if(i){const n=i.results.filter(a=>a.reaction._==="reactionCustomEmoji");e.push(...n.map(a=>a.reaction.document_id))}return $a(e)}async init(){this.cleanup(),this.setButtons();const e=await this.filterButtons(this.buttons);if(!e.length)return;const t=this.element=await Qg({buttons:e,listenerSetter:this.listenerSetter});t.id="bubble-contextmenu",t.classList.add("contextmenu");const s=e.find(l=>l.localName==="views");if(s&&this.peerId.isUser()){s.element.prepend(Le("checks","btn-menu-item-icon"));const l=document.createElement("div");l.classList.add("btn-menu-item-loader","shimmer"),s.textElement.append(l),s.element.after(document.createElement("hr"));const c=s.element.nextElementSibling,d=this.middleware.get();this.managers.appMessagesManager.getOutboxReadDate(this.message.peerId,this.message.mid).then(h=>{d()&&(this.canViewReadTime=!0,l.replaceWith(ws(h.date,!0,!1)))},h=>{if(!d())return;if(h.type!=="YOUR_PRIVACY_RESTRICTED"){c.remove(),s.element.remove();return}this.canViewReadTime=!1;const u=M("PmReadShowWhen");u.classList.add("show-when"),l.replaceWith(M("Chat.ContextMenu.Read")," ",u)})}else if(s){const l=this.message.reactions,c=l?.recent_reactions,d=!!c?.length,h=await this.managers.appMessagesManager.canViewMessageReadParticipants(this.message)?(await this.managers.appPeersManager.getPeer(this.peerId)).participants_count:void 0,u=l?l.results.reduce((w,b)=>w+b.count,0):void 0;s.element.prepend(Le(d?"reactions":"checks","btn-menu-item-icon"));const p=new ke.IntlElement({key:d?h===void 0?"Chat.Context.ReactedFast":"Chat.Context.Reacted":"NobodyViewed",args:d?h===void 0?[u]:[h,h]:void 0,element:s.textElement});let m;d?h===void 0?m=M("Chat.Context.ReactedFast",[u]):m=M(c.length===h?"Chat.Context.ReactedFast":"Chat.Context.Reacted",[c.length,h]):m=M("Loading"),m.classList.add("btn-menu-item-text-fake"),s.element.append(m);const g=22,f=3,y=1.125;p.element.style.visibility="hidden",p.element.style.paddingRight=d?y*Math.min(f,c.length)+"rem":"1rem";const v=this.middleware.get();this.managers.appMessagesManager.getMessageReactionsListAndReadParticipants(this.message).then(w=>{if(!v())return;m?.remove();const b=w.combined,S=h===void 0?w.reactionsCount:d?b.filter(P=>P.reaction).length:b.length;let C;if(b.length===1)C=new Rt({peerId:b[0].peerId,onlyFirstName:!0,dialog:!1}).element,(!d||w.readParticipantDates.length<=1)&&(this.viewerPeerId=b[0].peerId);else if(d){const P=S===b.length||h===void 0;C=M(P?"Chat.Context.ReactedFast":"Chat.Context.Reacted",P?[S]:[S,b.length])}else b.length?C=M("MessageSeen",[b.length]):p.element.style.visibility="";if(C&&(C.style.paddingRight=y*Math.min(f,S)+"rem",C.classList.add("btn-menu-item-text-fake"),s.element.append(C)),b.length){const P=new Co({avatarSize:g,middleware:v});P.render(c?c.map(L=>at(L.peer_id)):b.map(L=>L.peerId)),s.element.append(P.container),this.canOpenReactedList=!0}})}let i,n,a;if(this.message?._==="message"&&!this.chat.selection.isSelecting&&!this.message.pFlags.is_outgoing&&!this.message.pFlags.is_scheduled&&!this.message.pFlags.local&&!this.reactionElement){const l=this.message.reactions,c=this.message.peerId===I.myId&&(!l||l.pFlags.reactions_as_tags),d=await this.managers.appMessagesManager.getGroupsFirstMessage(this.message);a=(Zr||Je,"horizontal"),n=this.reactionsMenu=new Ff({managers:this.managers,type:a,middleware:this.middleware.get(),onFinish:async h=>{if(Js.close(),h=await h,!!h){if(!I.premium&&c){Vt.show({feature:"saved_tags"});return}this.chat.sendReaction({message:d,reaction:h})}},getOpenPosition:h=>ki.getReactionsOpenPosition(n,h),isTags:c}),await n.init(d),i=ki.getReactionsMenuPadding(a)}const r=e.find(l=>l.localName==="emojis");if(r){r.element.classList.add("is-multiline"),r.element.parentElement.insertBefore(document.createElement("hr"),r.element);const l=()=>{i??(i={}),i.bottom=24},c=this.reactionElement?[this.reactionElement.reactionCount.reaction.document_id]:this.getUniqueCustomEmojisFromMessage(),d=this.emojiInputsPromise=Pt();await this.managers.appEmojiManager.getCachedCustomEmojiDocuments(c).then(async h=>{const u=async p=>{const m=new Map;p.forEach(f=>{!f||m.has(f.stickerSetInput.id)||m.set(f.stickerSetInput.id,f.stickerSetInput)});const g=[...m.values()];if(d.resolve(g),m.size===1){const f=await this.managers.acknowledged.appStickersManager.getStickerSet(g[0]),y=f.result.then(v=>{const w=M(this.isTag?"Reaction.Tag.From":this.reactionElement?"MessageContainsReactionPack":"MessageContainsEmojiPack",[_e(v.set.title)]);dt(r.textElement,w)});return f.cached?y:(l(),void 0)}dt(r.textElement,M("MessageContainsEmojiPacks",[m.size]))};if(h.some(p=>!p))l(),this.managers.appEmojiManager.getCustomEmojiDocuments(c).then(u);else return u(h)})}return this.chat.container.append(t),{element:t,cleanup:()=>{this.cleanup(),n&&n.cleanup()},destroy:()=>{t.remove(),n&&n.widthContainer.remove()},menuPadding:i,reactionsMenu:n,reactionsMenuPosition:a}}async getUrlToMessage(){if(!this.message||this.messagePeerId.isUser())return;let e;const{peerId:t,mid:s}=this.message,i=this.chat.threadId;this.chat.type===te.Discussion&&(e=await this.managers.appMessagesManager.getMessageByPeer(t,i));const n=await this.managers.appPeersManager.getPeerUsername(e?e.fromId:t),a=yn(s);let r="https://t.me/";return n?(r+=n,e?r+=`/${yn(e.fwd_from.channel_post)}?comment=${a}`:i?r+=`/${yn(i)}/${a}`:r+="/"+a):(r+="c/"+t.toChatId(),e?r+=`/${a}?thread=${yn(e.mid)}`:i?r+=`/${yn(i)}/${a}`:r+="/"+a),{url:r,isPrivate:!n}}async getSelectedMessagesText(){if(this.avatarPeerId||!Yo())return;let e;if(this.chat.selection.isSelecting){const a=[...this.chat.selection.selectedMids.entries()].map(([r,l])=>[...l].map(c=>$t(r,c)));e=Ln(a)}else{const n=this.getMessageWithText();if(!n)return;e=[$t(n.peerId,n.mid)]}let t;this.isSponsored?t=[this.sponsoredMessage]:t=e.map(n=>this.chat.getMessage(n));const s=t.map(n=>{if(!n?.message)return;const a=Yt(n.message,{entities:n.totalEntities||n.entities,wrappingDraft:!0});return r0(a)});return{text:t.map(n=>n?.message).filter(Boolean).join(`
`),html:s.filter(Boolean).join(`
`)}}getQuotedText(){return Cx(this.target)}static onDownloadClick(e,t){if(Array.isArray(e))return e.map(s=>this.onDownloadClick(s));if(this.canDownload(e,void 0,t))return cs.downloadToDisc({media:Xs(e,!0)})}static getReactionsMenuPadding(e){let n=56;const a=40;Je&&(n+=32);let r;return e==="vertical"?r={top:n,left:44}:r={top:44,right:a,left:n},r}static getReactionsOpenPosition(e,t){const s=e.container.getBoundingClientRect(),i=MC(s);return i.left-=21/2,i.top-=121/2,t||(i.top+=37),i}static appendReactionsMenu({element:e,reactionsMenu:t,reactionsMenuPosition:s}){let i=!1;if(t){const n="is-visible";if(i=t.container.classList.contains(n),i&&t.container.classList.remove(n),s==="horizontal"){const a=e.offsetWidth,c=(a-8)/_v%1,d=.65;if(c<d){const h=a+(d-c)*_v|0;e.style.minWidth=h+"px"}}}if(t){const n=t.widthContainer;if(Oi)e.prepend(n);else{const a=document.createElement("div");a.classList.add("btn-menu-items","btn-menu-transition"),a.append(...Array.from(e.childNodes)),e.classList.add("has-items-wrapper"),e.append(n,a)}n.style.setProperty("--height",n.offsetHeight+"px")}return{onAfterInit:()=>{i&&t.container.classList.add("is-visible")},onClose:()=>{t&&t.container.classList.remove("is-visible")}}}}class Rf{constructor(e){this.options=e,this.middlewareHelper=e.middleware.create(),this.createMenu()}setPeerId(e){this.type=e===I.myId?"reminder":"schedule"}createButtons(){return[{icon:"mute",text:"Chat.Send.WithoutSound",onClick:this.options.onSilentClick,verify:()=>this.type==="schedule"},{icon:"schedule",text:"Chat.Send.ScheduledMessage",onClick:this.options.onScheduleClick,verify:()=>this.type==="schedule"},{icon:"schedule",text:"Chat.Send.SetReminder",onClick:this.options.onScheduleClick,verify:()=>this.type==="reminder"},{icon:"online",text:"Schedule.SendWhenOnline",onClick:this.options.onSendWhenOnlineClick,verify:()=>this.type==="schedule"&&this.options.canSendWhenOnline?.()},{icon:"crossround",text:"Effect.Remove",danger:!0,onClick:()=>this.options.onEffect(void 0),verify:()=>!!this.options.effect?.()}]}createMenu(){this.middlewareHelper.clean();const e=this.middlewareHelper.get(),t=new Ut;e.onClean(()=>{t.removeAll()}),this.createButtons();const s=this.createButtons(),i=jn({buttons:s,listenerSetter:t});i.classList.add("menu-send",this.options.openSide),this.options.onRef(i),za({element:this.options.onContextElement,callback:async n=>{if(this.options.onOpen&&!this.options.onOpen())return;oe(n),await Promise.all(s.map(async h=>{const u=await h.verify();h.element.classList.toggle("hide",!u)}));const a=xt(),r=a.get(),l="horizontal";let c;this.options.withEffects?.()&&(c=new Ff({managers:I.managers,type:l,middleware:r,onFinish:async h=>{if(Js.close(),h=await h,!h)return;const u=h.document_id;if(!I.premium&&!c.freeCustomEmoji.has(u)){Vt.show({feature:"premium_stickers"});return}const m=(await I.managers.appReactionsManager.getAvailableEffects()).find(g=>g.effect_sticker_id===u);this.options.onEffect(m.id)},getOpenPosition:h=>ki.getReactionsOpenPosition(c,h),isEffects:!0}),await c.init());const d=c&&ki.appendReactionsMenu({element:i,reactionsMenu:c,reactionsMenuPosition:l});Js.openBtnMenu(i,()=>{d?.onClose(),a.destroy(),this.createMenu(),setTimeout(()=>{i.remove()},400)}),d?.onAfterInit()},listenerSetter:t})}}const kv=255,Tv=100,xv=200;class Ex extends ee{constructor(e){super("popup-create-poll popup-new-media",{closable:!0,overlayClosable:!0,withConfirm:"Create",body:!0,title:"NewPoll",isConfirmationNeededOnClose:()=>{if(!(!this.getFilledAnswers().length||this.sent))return Ct({titleLangKey:"CancelPollAlertTitle",descriptionLangKey:"CancelPollAlertText",button:{langKey:"Discard",isDanger:!0}})}}),this.chat=e,this.tempId=0,this.onSubmitClick=()=>{this.send()},this.onInput=t=>{const s=t.target,i=Bi(s,"LABEL"),n=Pm(s);n||(s.parentElement.classList.add("is-filled"),i.classList.remove("hidden-widget"),i.firstElementChild.removeAttribute("disabled")),!i.nextElementSibling&&!n&&this.questions.childElementCount<10&&this.appendMoreField(),this.handleChange()},this.onDeleteClick=t=>{const s=t.target,i=Bi(s,"LABEL"),n=Ri(i);this.correctAnswers&&this.correctAnswers[0][0]===n&&(this.correctAnswers=void 0),i.remove(),this.optionInputFields.splice(n,1),this.optionInputFields.forEach((a,r)=>{a.options.labelOptions.length=0,a.options.labelOptions.push(r+1),ke.weakMap.get(a.label.firstElementChild).update()}),this.handleChange()},this.construct()}async construct(){this.questionInputField=new _t({placeholder:"AskAQuestion",label:"AskAQuestion",name:"question",maxLength:kv}),this.listenerSetter.add(this.questionInputField.input)("input",()=>{this.handleChange()}),this.optionInputFields=[],this.chat.type!==te.Scheduled&&new Rf({onSilentClick:()=>{this.chat.input.sendSilent=!0,this.send()},onScheduleClick:()=>{this.chat.input.scheduleSending(()=>{this.send()})},openSide:"bottom-left",onContextElement:this.btnConfirm,middleware:this.middlewareHelper.get(),onRef:h=>{this.header.append(h)}}).setPeerId(this.chat.peerId),this.header.append(this.questionInputField.container);const e=document.createElement("hr"),t=document.createElement("div");t.classList.add("caption"),Zt(t,"PollOptions"),this.questions=document.createElement("form"),this.questions.classList.add("poll-create-questions");const s=document.createElement("div");s.classList.add("poll-create-settings");const i=document.createElement("div");i.classList.add("caption"),Zt(i,"Settings"),await this.chat.managers.appPeersManager.isBroadcast(this.chat.peerId)||(this.anonymousCheckboxField=new pt({text:"NewPoll.Anonymous",name:"anonymous"}),this.anonymousCheckboxField.input.checked=!0,s.append(this.anonymousCheckboxField.label)),this.multipleCheckboxField=new pt({text:"NewPoll.MultipleChoice",name:"multiple"}),this.quizCheckboxField=new pt({text:"NewPoll.Quiz",name:"quiz"}),this.listenerSetter.add(this.multipleCheckboxField.input)("change",()=>{const d=this.multipleCheckboxField.checked;this.quizCheckboxField.input.toggleAttribute("disabled",d)}),this.listenerSetter.add(this.quizCheckboxField.input)("change",()=>{const d=this.quizCheckboxField.checked;Array.from(this.questions.children).map(h=>{h.classList.toggle("radio-field",d)}),d||(this.correctAnswers=void 0,this.quizSolutionField.setValueSilently("")),n.forEach(h=>h.classList.toggle("hide",!d)),this.multipleCheckboxField.input.toggleAttribute("disabled",d),this.handleChange()}),s.append(this.multipleCheckboxField.label,this.quizCheckboxField.label);const n=[],a=document.createElement("div");a.classList.add("caption"),Zt(a,"AccDescrQuizExplanation");const r=document.createElement("hr"),l=document.createElement("div");l.classList.add("poll-create-questions"),this.quizSolutionField=new _t({placeholder:"NewPoll.Explanation.Placeholder",label:"NewPoll.Explanation.Placeholder",name:"solution",maxLength:xv}),this.listenerSetter.add(this.questionInputField.input)("input",()=>{this.handleChange()});const c=document.createElement("div");c.classList.add("subtitle"),Zt(c,"AddAnExplanationInfo"),l.append(this.quizSolutionField.container,c),n.push(r,a,l),n.forEach(d=>d.classList.add("hide")),this.body.parentElement.insertBefore(e,this.body),this.body.append(t,this.questions,document.createElement("hr"),i,s,...n),N(this.btnConfirm,this.onSubmitClick,{listenerSetter:this.listenerSetter}),this.scrollable=new vi(this.body),this.appendMoreField(),this.handleChange()}getFilledAnswers(){return Array.from(this.questions.children).map((t,s)=>{const i=t.querySelector(".input-field-input");return i instanceof HTMLInputElement?i.value:fn(i,!1,!1).value}).filter(t=>!!t.trim())}validate(){const e=this.questionInputField.value;if(!e||e.length>kv||this.quizCheckboxField.checked&&!this.correctAnswers?.length)return!1;const t=this.getFilledAnswers();if(t.length<2||t.find(n=>n.length>Tv))return!1;const{value:i}=fn(this.quizSolutionField.input,!1,!1);return!(i.length>xv)}handleChange(){const e=this.validate();this.btnConfirm.toggleAttribute("disabled",!e)}async send(e=!1){const t=this.questionInputField.value,s=this.getFilledAnswers(),{value:i,entities:n}=fn(this.quizSolutionField.input,!0,!1);if(this.chat.type===te.Scheduled&&!e){this.chat.input.scheduleSending(()=>{this.send(!0)});return}this.sent=!0,this.hide();const a={};this.anonymousCheckboxField&&!this.anonymousCheckboxField.checked&&(a.public_voters=!0),this.multipleCheckboxField.checked&&(a.multiple_choice=!0),this.quizCheckboxField.checked&&(a.quiz=!0);const r={_:"poll",pFlags:a,question:{_:"textWithEntities",text:t,entities:[]},answers:s.map((c,d)=>({_:"pollAnswer",text:{_:"textWithEntities",text:c,entities:[]},option:new Uint8Array([d])})),id:void 0},l=await this.chat.managers.appPollsManager.getInputMediaPoll(r,this.correctAnswers,i,n);this.chat.managers.appMessagesManager.sendOther({...this.chat.getMessageSendingParams(),inputMedia:l}),this.chat.input.helperType==="reply"&&this.chat.input.clearHelper(),this.chat.input.onMessageSent(!1,!1)}appendMoreField(){const e=this.tempId++,t=this.questions.childElementCount+1,s=new _t({placeholder:"NewPoll.OptionsAddOption",label:"NewPoll.OptionLabel",labelOptions:[t],name:"question-"+e,maxLength:Tv});this.listenerSetter.add(s.input)("input",this.onInput);const i=new _i({text:"",name:"question"});i.main.append(s.container),N(s.input,oe,{listenerSetter:this.listenerSetter}),i.label.classList.add("hidden-widget"),i.input.disabled=!0,this.quizCheckboxField.checked||i.label.classList.remove("radio-field"),this.listenerSetter.add(i.input)("change",()=>{if(i.input.checked){const r=Ri(i.label);this.correctAnswers=[new Uint8Array([r])],this.handleChange()}});const n=it("close");s.container.append(n),N(n,this.onDeleteClick,{listenerSetter:this.listenerSetter,once:!0}),this.questions.append(i.label),this.scrollable.scrollIntoViewNew({element:this.questions.lastElementChild,position:"center"}),this.optionInputFields.push(s)}}function fu(o){return new Promise(async e=>{const t=document.createElement("canvas"),s=o.size??o.mediaSize.aspectFitted(o.boxSize),i=window.devicePixelRatio&&1;t.width=s.width*i,t.height=s.height*i;const n=t.getContext("2d");let a;Gh?a=await createImageBitmap(o.media,{resizeWidth:s.width,resizeHeight:s.height}):a=o.media,n.drawImage(a,0,0,t.width,t.height),Gh&&a?.close();const r=o.mimeType??"image/jpeg",l=o.quality??1;if(o.toDataURL){const c=t.toDataURL(r,l);e({url:c,size:s})}else t.toBlob(c=>{e({blob:c,size:s})},r,l)})}function xC(o){let e,t;return o instanceof HTMLVideoElement?(e=o.videoWidth,t=o.videoHeight):(e=o.naturalWidth,t=o.naturalHeight),fu({media:o,mediaSize:vs(e,t),boxSize:vs(320,240),quality:.9})}function _x(o){return new Promise((e,t)=>{o.onseeked=()=>{o.onseeked=()=>{xC(o).then(e),o.onseeked=void 0},yi(o,0)},o.onerror=t,yi(o,Math.min(o.duration,1))})}function kx(o){const e=o.src;return fetch(e).then(t=>t.arrayBuffer()).then(t=>{const s=new Uint8Array(t);let i=0;for(let n=0,a=s.length;n<a;++n)if(s[n]==33&&s[n+1]==249&&s[n+2]==4&&s[n+7]==0){const r=s[n+5]<<8|s[n+4]&255;i+=r<2?10:r}return i/1e3})}function Tx(o,e){const t={writable:!0,configurable:!0},s={};e.forEach(i=>{o.hasOwnProperty(i)||(s[i]=t)}),Object.defineProperties(o,s)}const ph=new Set(["audio/mpeg","audio/aac","audio/wav"]);function AC(o,e){const t=Ko(o.message),s=o.entities||[],i=Qr(s,t);return Au(o.message,{...e,entities:i})}const xx=ce("<div class=btn-send-effect>"),Ax=ce("<div>");function FC(o){const[e,t]=ne(),s=K(n=>e()||n),[i]=zo(async()=>I.managers.appReactionsManager.getAvailableEffects());return ye(async()=>{const n=o.effect();if(!n||!i()){t();return}const a=i().find(u=>u.id===n);let r;const l=(()=>{const u=xx(),p=r;return typeof p=="function"?wt(p,u):r=u,u})(),d=Ys().get(),h=[];Rs({doc:await I.managers.appDocsManager.getDoc(a.static_icon_id),div:r,middleware:d,loadPromises:h,width:20,height:20}),await Promise.all(h),d()&&t(l),vS({isOut:!0,effectId:n,element:r,middleware:d})}),(()=>{const n=Ax();return D(n,j(tp,{type:"cross-fade",get children(){return s()}})),Ve(()=>Ce(n,ot("btn-send-effect-container",e()&&"is-visible"))),n})()}const[Fx,tg]=ne(),Av=()=>I.managers.appPaymentsManager.getStarsStatus(!0).then(o=>tg(o.balance));function fp(){return aw(()=>fp.name,()=>{Av(),I.addEventListener("stars_balance",tg);const o=setInterval(()=>{Av()},6e4);return ut(()=>{clearInterval(o),I.removeEventListener("stars_balance",tg)}),Fx})()}const Rx=ce('<svg width=26 height=25 viewBox="0 0 26 25"fill=none xmlns=http://www.w3.org/2000/svg><path fill-rule=evenodd clip-rule=evenodd d="M12.413 20.3615L7.4621 23.3945C6.9473 23.7098 6.27431 23.5482 5.95894 23.0333C5.80491 22.7819 5.75899 22.4789 5.8316 22.1931L6.598 19.1766C6.87465 18.0876 7.61981 17.1774 8.63265 16.6911L14.0338 14.0979C14.2857 13.977 14.3918 13.6749 14.2709 13.4231C14.173 13.2191 13.9516 13.105 13.7287 13.1436L7.71644 14.1845C6.49429 14.3961 5.24099 14.0586 4.29035 13.2619L2.39103 11.6702C1.92831 11.2825 1.86756 10.593 2.25533 10.1303C2.44393 9.90522 2.71514 9.7655 3.00787 9.74259L8.81084 9.28846C9.2208 9.25637 9.57808 8.99693 9.73546 8.61702L11.9741 3.21299C12.2052 2.65524 12.8447 2.39039 13.4024 2.62145C13.6702 2.7324 13.883 2.94518 13.9939 3.21299L16.2326 8.61702C16.39 8.99693 16.7473 9.25637 17.1572 9.28846L22.9921 9.74509C23.594 9.79219 24.0437 10.3183 23.9966 10.9202C23.974 11.2097 23.837 11.4783 23.616 11.6668L19.166 15.4605C18.8527 15.7275 18.7161 16.148 18.8124 16.5482L20.1805 22.2314C20.3218 22.8184 19.9605 23.4087 19.3735 23.55C19.0915 23.6179 18.794 23.5709 18.5467 23.4194L13.5551 20.3615C13.2046 20.1468 12.7634 20.1468 12.413 20.3615Z"fill=url(#paint0_linear_4300_30119) stroke=url(#paint1_linear_4300_30119) stroke-width=1.22222></path><path fill-rule=evenodd clip-rule=evenodd d="M12.413 20.3615L7.4621 23.3945C6.9473 23.7098 6.27431 23.5482 5.95894 23.0334C5.80491 22.7819 5.75899 22.4789 5.8316 22.1931L6.598 19.1766C6.87465 18.0876 7.61981 17.1774 8.63265 16.6911L14.0338 14.0979C14.2857 13.977 14.3918 13.6749 14.2709 13.4231C14.173 13.2191 13.9516 13.105 13.7287 13.1436L7.71644 14.1845C6.49429 14.3961 5.24099 14.0586 4.29035 13.2619L2.39103 11.6702C1.92831 11.2825 1.86756 10.593 2.25533 10.1303C2.44393 9.90522 2.71514 9.7655 3.00787 9.74259L8.81084 9.28846C9.2208 9.25637 9.57808 8.99693 9.73546 8.61702L11.9741 3.21299C12.2052 2.65524 12.8447 2.39039 13.4024 2.62145C13.6702 2.7324 13.883 2.94518 13.9939 3.21299L16.2326 8.61702C16.39 8.99693 16.7473 9.25637 17.1572 9.28846L22.9921 9.74509C23.594 9.79219 24.0437 10.3183 23.9966 10.9202C23.974 11.2097 23.837 11.4783 23.616 11.6668L19.166 15.4605C18.8527 15.7275 18.7161 16.148 18.8124 16.5482L20.1805 22.2314C20.3218 22.8184 19.9605 23.4087 19.3735 23.55C19.0915 23.6179 18.794 23.5709 18.5467 23.4194L13.5551 20.3615C13.2046 20.1468 12.7634 20.1468 12.413 20.3615Z"stroke=url(#paint2_linear_4300_30119) stroke-width=2.44444 style=mix-blend-mode:soft-light></path><defs><linearGradient id=paint0_linear_4300_30119 x1=0.0870915 y1=28.1529 x2=41.4 y2=-18.3997 gradientUnits=userSpaceOnUse><stop stop-color=#FDEB32></stop><stop offset=0.439058 stop-color=#FEBD04></stop><stop offset=1 stop-color=#D75902></stop></linearGradient><linearGradient id=paint1_linear_4300_30119 x1=27.0556 y1=3.61111 x2=9.33333 y2=15.8333 gradientUnits=userSpaceOnUse><stop stop-color=#DB5A00></stop><stop offset=1 stop-color=#FF9145></stop></linearGradient><linearGradient id=paint2_linear_4300_30119 x1=29.5 y1=3.00001 x2=13 y2=13.0592 gradientUnits=userSpaceOnUse><stop stop-color=var(--star-background-color) stop-opacity=0></stop><stop offset=0.395833 stop-color=var(--star-background-color) stop-opacity=0.85></stop><stop offset=0.520833 stop-color=var(--star-background-color)></stop><stop offset=0.645833 stop-color=var(--star-background-color) stop-opacity=0.85></stop><stop offset=1 stop-color=var(--star-background-color) stop-opacity=0>'),Dx=ce('<svg><path d="M1.55275 9.54149L2.08783 9.9899L1.55275 9.54149C0.839803 10.3922 0.951509 11.6599 1.80225 12.3728L3.70157 13.9645C4.85897 14.9344 6.38486 15.3453 7.87281 15.0877L10.9718 14.5512L8.2359 15.8647C6.9783 16.4685 6.05307 17.5988 5.70955 18.9509L4.94315 21.9674C4.80966 22.4929 4.89409 23.0499 5.17728 23.5122C5.75711 24.4587 6.99445 24.7559 7.94094 24.1761L12.8919 21.1432C12.9484 21.1085 13.0197 21.1085 13.0762 21.1432L18.0678 24.201C18.5226 24.4796 19.0695 24.5661 19.5881 24.4412C20.6672 24.1815 21.3315 23.096 21.0717 22.0169L19.7036 16.3336C19.6881 16.269 19.7101 16.2012 19.7607 16.1581L24.2107 12.3643L23.616 11.6668L24.2107 12.3643C24.617 12.0179 24.8688 11.524 24.9105 10.9917C24.9971 9.8851 24.1702 8.91782 23.0636 8.83122L17.2288 8.37458C17.1626 8.3694 17.1049 8.32752 17.0795 8.26619L16.2326 8.61702L17.0795 8.26619L14.8408 2.86217C14.6368 2.36977 14.2456 1.97856 13.7532 1.77457C12.7278 1.34976 11.5521 1.83669 11.1273 2.86216L8.88858 8.26619C8.86318 8.32752 8.8055 8.3694 8.73932 8.37458L2.93635 8.82872C2.39814 8.87084 1.8995 9.12772 1.55275 9.54149Z"stroke=var(--star-background-color) stroke-width=1.83333></svg>',!1,!0),Bx=ce("<div class=stars-balance><div class=stars-balance-title></div><div class=stars-balance-subtitle>"),RC=ce("<div>"),Nx=ce("<span class=popup-stars-pay-amount-status>"),Ox=ce("<b>"),Ux=ce("<div class=popup-stars-title>"),Hx=ce("<div class=popup-stars-subtitle>"),$x=ce("<div class=popup-stars-options>"),Vx=ce("<div class=popup-stars-option-stars>"),Gx=ce("<div class=popup-stars-option><div class=popup-stars-option-title></div><div class=popup-stars-option-subtitle>");function ed(o){return(()=>{const e=Rx(),t=e.firstChild;return D(e,(()=>{const s=K(()=>!!o.stroke);return()=>s()&&Dx()})(),t),Ve(s=>{const i=ot("stars-star-icon",o.stroke&&"stars-star-icon-stroke"),n=o.style;return i!==s._v$&&Ti(e,"class",s._v$=i),s._v$2=zi(e,n,s._v$2),s},{_v$:void 0,_v$2:void 0}),e})()}function DC(){const o=fp();return(()=>{const e=Bx(),t=e.firstChild,s=t.nextSibling;return D(t,()=>M("StarsBalance")),D(s,j(ed,{}),null),D(s,()=>""+(o()??0),null),e})()}function BC(o){return(()=>{const e=RC();return D(e,()=>`${+o.stars>0?"+":""}${o.stars}`,null),D(e,j(ed,{}),null),D(e,(()=>{const t=K(()=>!!o.isRefund);return()=>t()&&(()=>{const s=Nx();return D(s,()=>M("StarsRefunded")),s})()})(),null),Ve(()=>Ce(e,ot("popup-stars-pay-amount",+o.stars>0?"green":"danger"))),e})()}function zx(o){const t={starsTransactionPeerFragment:"Stars.Via.Fragment",starsTransactionPeerPremiumBot:"Stars.Via.Bot",starsTransactionPeerAppStore:"Stars.Via.App",starsTransactionPeerPlayMarket:"Stars.Via.App"}[o.peer._]??"Stars.Via.Unsupported";return M(t)}async function NC(o,e,t,s,i){const[n,a]=await Promise.all([s||o?.extended_media||!o?Oe({peerId:i||at(o.peer.peer)}):o.peer._==="starsTransactionPeer"?Oe({peerId:at(o.peer.peer)}):zx(o),(async()=>{const r=async(c,d)=>{const h=[];Ks({container:c,photo:d,boxWidth:t,boxHeight:t,middleware:e,loadPromises:h,withoutPreloader:!0}),await Promise.all(h)};if(s||o?.extended_media){const c=s?.extended_media||o.extended_media;let d;if(s){const p=s.extended_media[0];d=df(p)}else{const p=o.extended_media[0];d=p.photo||p.document}const h=document.createElement("div");if(h.classList.add("popup-stars-transaction-media","is-paid-media"),s){const p=await Rd({media:d,animationGroup:"chat",middleware:e,width:t,height:t});h.append(p)}else await r(h,d);const u=c.length;if(u>1){const p=document.createElement("span");p.classList.add("popup-stars-transaction-media-counter"),p.textContent=""+u,h.append(p)}return h}if(o?.photo){const c=document.createElement("div");return c.classList.add("popup-stars-transaction-media","is-paid-media"),await r(c,o?.photo),c}if(!o||o.peer._==="starsTransactionPeer"){const c=es({peerId:o?at(o.peer.peer):i,size:t,middleware:e});return await c.readyThumbPromise,c.node}const l=document.createElement("div");return l.classList.add("popup-stars-transaction-media"),l.append(Le("star")),l})()]);return{title:n,media:a}}class yu extends ee{constructor(t={}){super("popup-stars",{closable:!0,overlayClosable:!0,floatingHeader:!0,body:!0,title:"TelegramStars",scrollable:!0});Lr(this,"renderTransaction",async t=>{const s=this.middlewareHelper.get(),{title:i,media:n}=await NC(t,s,42);return Jt(a=>{s.onDestroy(a);const r=t.extended_media?M("StarMediaPurchase"):i,l=t.extended_media?i:t.description?_e(t.description):+t.stars>0?M("Stars.TopUp"):void 0,c=ws(t.date);let d;t.pFlags.refund?d=M("StarsRefunded"):t.pFlags.failed?d=M("StarsFailed"):t.pFlags.pending&&(d=M("StarsPending"));let h;return j(Ra,{ref(u){const p=h;typeof p=="function"?p(u):h=u},get title(){return(()=>{const u=Ox();return D(u,r),u})()},midtitle:l,subtitle:d?[c," — ",d]:c,media:n,mediaSize:"abitbigger",clickable:()=>{gr.create({transaction:t})},get rightContent(){return j(BC,{get stars(){return t.stars}})}}),h})});It(this,t),this.construct()}_construct(t,s){const i=this;this.header.append(DC());const n=fp(),a=K(()=>this.paymentForm?+this.paymentForm.invoice.prices[0].amount-+n():0),r=K(()=>{if(this.paymentForm){const S=this.topupOptions.filter(C=>+C.stars>=a());return S.length?S:[this.topupOptions[this.topupOptions.length-1]]}return this.topupOptions}),l=r().length>3?r().filter(S=>!S.pFlags.extended):r(),[c,d]=ne(r().length<=3),h=K(()=>Math.ceil((c()?r().length:l.length)/2)),u=ze("btn-primary btn-transparent primary popup-stars-more",{icon:"down",text:"ShowMoreOptions"}),p=N(u,()=>{d(S=>!S),u.classList.toggle("is-visible")});ut(p),c()||u.classList.add("is-visible");let m=!1;const g=j(gs,{caption:"Stars.TOS",get children(){return[t,(()=>{const S=Ux();return D(S,(()=>{const C=K(()=>!!i.paymentForm);return()=>C()?M("StarsNeededTitle",[a()]):M("TelegramStars")})()),S})(),(()=>{const S=Hx();return D(S,(()=>{const C=K(()=>!!i.paymentForm);return()=>C()?M("StarsNeededText",[s]):M("TelegramStarsInfo")})()),S})(),(()=>{const S=$x();return D(S,j(ti,{get each(){return r()},children:(C,P)=>{const L=K(()=>c()||C.pFlags.extended?P():l.indexOf(C)),E=K(()=>L()%2?"calc(100% + .5rem)":"0"),_=K(()=>Math.floor(L()/2)*79+Math.floor(L()/2)*8+"px"),k=K(()=>(c()?r():l).length%2?c()||C.pFlags.extended?L()===r().length-1:L()===l.length-1:!1),x=+C.stars;let A=1;x>=2500?A=6:x>=1e3?A=5:x>=500?A=4:x>=250?A=3:x>=50&&(A=2);let T;if(A>1){T=[];for(let B=0;B<A;++B)T.push(j(ed,{stroke:B!==A-1,get style(){return{"margin-right":Math.min(B,1)*-32+"px"}}}))}else T=j(ed,{});return T=(()=>{const B=Vx();return D(B,T),Ve(R=>zi(B,`width: ${26+(A-1)*6}px`,R)),B})(),(()=>{const B=Gx(),R=B.firstChild,O=R.nextSibling;return B.$$click=async()=>{if(m)return;m=!0;const X={_:"inputInvoiceStars",option:C};try{const F=await i.managers.appPaymentsManager.getPaymentForm(X);(await gr.create({inputInvoice:X,paymentForm:F})).addEventListener("finish",G=>{G==="paid"&&i.onTopup&&(i.hide(),i.onTopup())})}catch(F){console.error("stars error",F)}m=!1},D(R,()=>`+${C.stars}`,null),D(R,T,null),D(O,()=>In(C.amount,C.currency)),Ve(X=>{const F=!!(C.pFlags.extended&&!c()),H=!!k(),G=`translate(${E()}, ${_()})`;return F!==X._v$3&&B.classList.toggle("invisible",X._v$3=F),H!==X._v$4&&B.classList.toggle("full",X._v$4=H),G!==X._v$5&&((X._v$5=G)!=null?B.style.setProperty("transform",G):B.style.removeProperty("transform")),X},{_v$3:void 0,_v$4:void 0,_v$5:void 0}),B})()}})),Ve(()=>h()*79+(h()-1)*8+"px"!=null?S.style.setProperty("height",h()*79+(h()-1)*8+"px"):S.style.removeProperty("height")),S})(),u]}}),f=S=>{const C=this.middlewareHelper.get();let P="",L=!1;const E=async()=>{if(L)return;L=!0;const x=await this.managers.appPaymentsManager.getStarsTransactions(P,S);if(S===void 0&&console.log("stars",x),!C())return;const A=x.history.map(this.renderTransaction),T=await Promise.all(A);C()&&(k(B=>(P=x.next_offset,P||(B.loadMore=void 0),B.rendered.push(...T),B)),L=!1)},[_,k]=Bd({loadMore:E});return _},y=[void 0,!0,!1].map(S=>{const C=f(S);return C().loadMore(),C}),[v,w]=ne(0);this.scrollable.onScrolledBottom=()=>{const S=y[v()];S().loadMore?.()};const b=j(gs,{class:"popup-stars-transactions-section",get children(){return j(dk,{tab:v,onChange:w,class:"popup-stars-transactions",get menu(){return[M("StarsTransactionsAll"),M("StarsTransactionsIncoming"),M("StarsTransactionsOutgoing")]},get content(){return y.map(S=>(()=>{const C=RC();return D(C,()=>S().rendered),C})())}})}});return[g,K(()=>!a()&&b)]}async construct(){const[t,s,i]=await Promise.all([(async()=>{const n=document.createElement("img");return n.classList.add("popup-stars-image"),await Ki(n,`assets/img/${Qw("stars")}.png`),n})(),this.paymentForm?Oe({peerId:this.paymentForm.bot_id.toPeerId(!1)}):void 0,this.managers.appPaymentsManager.getStarsTopupOptions()]);this.topupOptions=i,this.appendSolid(()=>this._construct(t,s)),this.show()}}Ui(["click"]);class Fv extends ee{constructor(e,t){if(super("popup-make-paid",{closable:!0,overlayClosable:!0,body:!0,title:"PaidMedia.Title",withConfirm:"PaidMedia.Button",footer:!0,withFooterConfirm:!0}),this.editingFrom=t,this.footer.classList.add("abitlarger"),N(this.btnConfirm,()=>{const s=parseInt(this.inputField.value||"0");s>0?(e(s),this.hide()):Va(this.inputField.container)},{listenerSetter:this.listenerSetter}),t){const s=ze("btn-primary btn-primary-transparent primary",{text:"PaidMedia.KeepFree"});N(s,()=>{e(0),this.hide()},{listenerSetter:this.listenerSetter}),this.btnConfirm.after(s)}this.d()}async d(){const e=await this.managers.apiManager.getAppConfig();this.appendSolid(()=>{const t=this.inputField=new _t({inputMode:"numeric",label:"PaidMedia.Enter",plainText:!0,withLinebreaks:!1}),s=ed({});return s.classList.add("popup-make-paid-star"),t.container.append(s),sn(t.input)("input",()=>{let n=(""+ +t.value).replace(/[^0-9]/g,"");+n>e.stars_paid_post_amount_max&&(n=""+e.stars_paid_post_amount_max),t.setValueSilently(n)}),this.editingFrom&&(t.value=""+this.editingFrom),setTimeout(()=>{this.show(),Zs(t.input)},0),j(gs,{caption:"PaidMedia.Caption",get captionArgs(){return[ni(()=>{ee.createPopup(yu)})]},noShadow:!0,noDelimiter:!0,get children(){return t.container}})})}}let xh;const Rv=384;function sg(){return xh}class pr extends ee{constructor(e,t,s,i){super("popup-send-photo popup-new-media",{closable:!0,withConfirm:"Modal.Send",confirmShortcutIsSendShortcut:!0,body:!0,title:!0,scrollable:!0}),this.chat=e,this.files=t,this.ignoreInputValue=i,this.onScroll=()=>{const{input:n}=this.messageInputField;this.scrollable.onAdditionalScroll(),n.scrollTop>0&&n.scrollHeight>130&&this.scrollable.container.classList.remove("scrolled-bottom")},this.onKeyDown=n=>{const a=n.target,{input:r}=this.messageInputField;if(a!==r){if(a.tagName==="INPUT"||a.isContentEditable)return;r.focus(),Zs(r)}},this.attachFile=n=>{const a=this.willAttach,r=this.shouldCompress(n.type),l=document.createElement("div");l.classList.add("popup-item");const c={file:n};Tx(c,["scaledBlob","middlewareHelper","itemDiv","mediaSpoiler"]),c.middlewareHelper=this.middlewareHelper.get().create(),c.itemDiv=l;const d=r?this.attachMedia(c):this.attachDocument(c);return a.sendFileDetails.push(c),d.catch(h=>{l.style.backgroundColor="#000",console.error("error rendering file",h)})},this.animationGroup="NEW-MEDIA",this.construct(s)}static async canSend({peerId:e,onlyVisible:t,threadId:s}){const i=["send_photos","send_videos","send_docs","send_audios","send_gifs"],n=i.map(l=>e.isAnyChat()&&!t?I.managers.appChatsManager.hasRights(e.toChatId(),l,void 0,s?!0:void 0):!0),a={},r=await Promise.all(n);return i.forEach((l,c)=>{a[l]=r[c]}),a}async construct(e){this.willAttach={type:e,sendFileDetails:[],group:!0};const t=await this.managers.apiManager.getLimit("caption");this.captionLengthMax=t;const s=await pr.canSend({...this.chat.getMessageSendingParams(),onlyVisible:!0}),i=s.send_photos,n=s.send_videos,a=s.send_docs;N(this.btnConfirm,async()=>(await Hs(0),this.send()),{listenerSetter:this.listenerSetter});const r=ai({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[{icon:"plusround",text:"Add",onClick:()=>{this.chat.input.onAttachClick(!1,!1,!1)},verify:()=>!0},{icon:"image",text:"Popup.Attach.AsMedia",onClick:()=>this.changeType("media"),verify:()=>{if(!this.hasAnyMedia()||this.willAttach.type!=="document"||!i&&!n)return!1;if(!i||!n){const p=i?Vh:Sh,{media:m,files:g}=this.partition(p);if(g.length)return!1}return!0}},{icon:"document",text:"SendAsFile",onClick:()=>this.changeType("document"),verify:()=>this.files.length===1&&this.willAttach.type!=="document"&&a},{icon:"document",text:"SendAsFiles",onClick:()=>this.changeType("document"),verify:()=>this.files.length>1&&this.willAttach.type!=="document"&&a},{icon:"groupmedia",text:"Popup.Attach.GroupMedia",onClick:()=>this.changeGroup(!0),verify:()=>!this.willAttach.group&&this.canGroupSomething()},{icon:"groupmediaoff",text:"Popup.Attach.UngroupMedia",onClick:()=>this.changeGroup(!1),verify:()=>this.willAttach.group&&this.canGroupSomething()},{icon:"mediaspoiler",text:"EnablePhotoSpoiler",onClick:()=>this.changeSpoilers(!0),verify:()=>this.canToggleSpoilers(!0,!0)},{icon:"mediaspoiler",text:"Popup.Attach.EnableSpoilers",onClick:()=>this.changeSpoilers(!0),verify:()=>this.canToggleSpoilers(!0,!1)},{icon:"mediaspoileroff",text:"DisablePhotoSpoiler",onClick:()=>this.changeSpoilers(!1),verify:()=>this.canToggleSpoilers(!1,!0)},{icon:"mediaspoileroff",text:"Popup.Attach.RemoveSpoilers",onClick:()=>this.changeSpoilers(!1),verify:()=>this.canToggleSpoilers(!1,!1)},{icon:"captionup",text:"CaptionAbove",onClick:()=>this.moveCaption(!0),verify:()=>this.canMoveCaption()&&!this.willAttach.invertMedia},{icon:"captiondown",text:"CaptionBelow",onClick:()=>this.moveCaption(!1),verify:()=>this.canMoveCaption()&&!!this.willAttach.invertMedia},{icon:"cash_circle",text:"PaidMedia.Menu.Edit",onClick:()=>{ee.createPopup(Fv,p=>{this.setPaidMedia(p)},this.willAttach.stars)},verify:()=>!!this.willAttach.stars&&this.canSendPaidMedia()},{icon:"cash_circle",text:"PaidMedia.Menu",onClick:()=>{ee.createPopup(Fv,p=>{this.setPaidMedia(p)})},verify:()=>!this.willAttach.stars&&this.canSendPaidMedia()}]});this.header.append(r),this.btnConfirm.remove(),this.mediaContainer=document.createElement("div"),this.mediaContainer.classList.add("popup-photo"),this.scrollable.container.append(this.mediaContainer);const l=document.createElement("div");l.classList.add("popup-input-container");const c=document.createElement("div");if(c.classList.add("popup-input-inputs","input-message-container"),this.messageInputField=new Yw({placeholder:"PreviewSender.CaptionPlaceholder",name:"message",withLinebreaks:!0,maxLength:this.captionLengthMax}),this.messageInputField.input.dataset.animationGroup=this.animationGroup,this.listenerSetter.add(this.scrollable.container)("scroll",this.onScroll),this.listenerSetter.add(this.messageInputField.input)("scroll",this.onScroll),this.messageInputField.input.classList.replace("input-field-input","input-message-input"),this.messageInputField.inputFake.classList.replace("input-field-input","input-message-input"),c.append(this.messageInputField.input,this.messageInputField.placeholder,this.messageInputField.inputFake),l.append(c,this.btnConfirm),!this.ignoreInputValue&&!this.chat.input.editMsgId&&(this.wasDraft=this.chat.input.getCurrentInputAsDraft(),this.wasDraft)){const p=AC(this.wasDraft,{wrappingForPeerId:this.chat.peerId,animationGroup:this.animationGroup});this.messageInputField.setValueSilently(p),this.chat.input.messageInputField.value=""}this.container.append(l),this.attachFiles(),this.addEventListener("close",()=>{this.files.length=0,this.willAttach.sendFileDetails.length=0,xh===this&&(xh=void 0)});let d,h,u;ln({buttons:[{icon:"mediaspoiler",text:"EnablePhotoSpoiler",onClick:()=>{this.applyMediaSpoiler(u)},verify:()=>h&&!u.mediaSpoiler&&!this.willAttach.stars},{icon:"mediaspoileroff",text:"DisablePhotoSpoiler",onClick:()=>{this.removeMediaSpoiler(u)},verify:()=>!!(h&&u.mediaSpoiler)&&!this.willAttach.stars}],listenTo:this.mediaContainer,listenerSetter:this.listenerSetter,findElement:p=>(d=U(p.target,"popup-item"),h=d.classList.contains("popup-item-media"),u=this.willAttach.sendFileDetails.find(m=>m.itemDiv===d),d)}),this.chat.type!==te.Scheduled&&(Jt(m=>{this.chat.destroyMiddlewareHelper.onDestroy(m);const[g,f]=ne(this.wasDraft?.effect);this.effect=g,this.setEffect=f,this.btnConfirm.append(FC({effect:this.effect}))}),new Rf({onSilentClick:()=>{this.chat.input.sendSilent=!0,this.send()},onScheduleClick:()=>{this.chat.input.scheduleSending(()=>{this.send()})},onSendWhenOnlineClick:()=>{this.chat.input.setScheduleTimestamp(xc,()=>{this.send()})},openSide:"top-left",onContextElement:this.btnConfirm,middleware:this.middlewareHelper.get(),canSendWhenOnline:this.chat.input.canSendWhenOnline,onRef:m=>{this.container.append(m)},withEffects:()=>this.chat.peerId.isUser()&&this.chat.peerId!==I.myId,effect:this.effect,onEffect:this.setEffect}).setPeerId(this.chat.peerId)),xh=this}async canSendPaidMedia(){return await this.managers.appPeersManager.isBroadcast(this.chat.peerId)&&!!(await this.managers.appProfileManager.getChannelFull(this.chat.peerId.toChatId())).pFlags.paid_media_allowed}willSendPaidMedia(){return this.willAttach.stars&&this.willAttach.type==="media"&&this.willAttach.sendFileDetails.length<=10}setPaidMedia(e){this.willAttach.stars=e,this.changeSpoilers(!!e),this.setUnlockPlaceholders()}setUnlockPlaceholders(){const{stars:e}=this.willAttach;this.mediaContainer.querySelectorAll(".popup-item-album, .popup-item-media:not(.grouped-item)").forEach(t=>{const s="extended-media-buy";if(t.querySelector(`.${s}`)?.remove(),!this.willSendPaidMedia())return;const i=document.createElement("span");i.classList.add(s),i.append(M("PaidMedia.Unlock",[In(e,Eg)])),t.append(i)})}async applyMediaSpoiler(e,t){const s=e.middlewareHelper.get(),{width:i,height:n}=e.itemDiv.style;let a,r;if(e.itemDiv.classList.contains("album-item")){const{width:p,height:m}=e.itemDiv.parentElement.style,g=parseInt(p),f=parseInt(m);a=+i.slice(0,-1)/100*g,r=+n.slice(0,-1)/100*f}else a=parseInt(i),r=parseInt(n);const{url:l}=await fu({media:e.itemDiv.firstElementChild,boxSize:vs(40,40),mediaSize:vs(a,r),toDataURL:!0,quality:.2}),c=o0(l),d={_:"photoStrippedSize",bytes:c,type:"i"};e.strippedBytes=c;const h={_:"photo",sizes:[d],id:0,access_hash:0,date:0,dc_id:0,file_reference:[],pFlags:{}},u=await Rd({middleware:s,width:a,height:r,animationGroup:this.animationGroup,media:h});s()&&(t||u.classList.add("is-revealing"),e.mediaSpoiler=u,e.itemDiv.append(u),await Qn(),s()&&Km({mediaSpoiler:u,reveal:!1}))}removeMediaSpoiler(e){Km({mediaSpoiler:e.mediaSpoiler,reveal:!0,destroyAfter:!0}),e.mediaSpoiler=void 0}appendDrops(e){this.body.append(e)}partition(e=ka){const t=[],s=[],i=[];return this.willAttach.sendFileDetails.forEach(n=>{e.has(n.file.type)?t.push(n):ph.has(n.file.type)?i.push(n):s.push(n)}),{media:t,files:s,audio:i}}mediaCount(){return this.partition().media.length}hasAnyMedia(){return this.mediaCount()>0}messagesCount(){let e=0;return this.iterate(()=>{++e}),e}canGroupSomething(){const{media:e,files:t,audio:s}=this.partition();return e.length>1||t.length>1||s.length>1}canToggleSpoilers(e,t){if(this.willSendPaidMedia())return!1;let s=this.willAttach.type==="media"&&this.hasAnyMedia();if(t&&s&&(s=this.files.length===1),s){const i=this.willAttach.sendFileDetails.filter(a=>ka.has(a.file.type)),n=i.filter(a=>a.mediaSpoiler);s=t?!0:i.length>1,s&&(s=e?i.length!==n.length:i.length===n.length)}return s}changeType(e){e==="document"&&this.moveCaption(!1),this.willAttach.type=e,this.attachFiles()}changeGroup(e){this.willAttach.group=e,this.attachFiles()}changeSpoilers(e){this.partition().media.forEach(t=>{e&&!t.mediaSpoiler?this.applyMediaSpoiler(t):!e&&t.mediaSpoiler&&this.removeMediaSpoiler(t)})}canMoveCaption(){return!this.messageInputField.isEmpty()&&this.willAttach.type==="media"}moveCaption(e){this.willAttach.invertMedia=e||void 0}addFiles(e){const t=e.filter(s=>!this.files.find(n=>n.lastModified===s.lastModified&&n.name===s.name&&n.size===s.size));t.length&&(this.files.push(...t),this.willSendPaidMedia()&&this.files.length>10&&this.changeSpoilers(!1),this.attachFiles())}async send(e=!1){let{value:t,entities:s}=fn(this.messageInputField.input,!0,!1);if(t.length>this.captionLengthMax){zs(ke.format("Error.PreviewSender.CaptionTooLong",!0));return}if(await this.chat.input.showSlowModeTooltipIfNeeded({sendingFew:this.messagesCount()>1,container:this.btnConfirm.parentElement,element:this.btnConfirm}))return;const{input:n}=this.chat,a=await pr.canSend(this.chat.getMessageSendingParams()),r=this.willAttach;r.isMedia=r.type==="media"||void 0;const{sendFileDetails:l,isMedia:c}=r;let d=!1;if(this.iterate(m=>{if(d)return;const f=m.map(y=>{const v=[[ph,"GlobalAttachAudioRestricted","send_audios"],[()=>!ka.has(y.file.type),"GlobalAttachDocumentsRestricted","send_docs"]];c&&v.unshift([Vh,"GlobalAttachPhotoRestricted","send_photos"],[()=>Sh.has(y.file.type)&&y.noSound,"GlobalAttachGifRestricted","send_gifs"],[Sh,"GlobalAttachVideoRestricted","send_videos"]);const w=v.find(([b])=>typeof b=="function"?b():b.has(y.file.type));return w?a[w[2]]?void 0:w[1]:!c&&!a.send_docs&&"GlobalAttachDocumentsRestricted"||void 0}).find(y=>typeof y=="string");f&&(Ee({langPackKey:f}),st.isAvailable("animations")&&Va(this.body)),d||(d=!!f)}),d)return;if(this.chat.type===te.Scheduled&&!e){this.chat.input.scheduleSending(()=>{this.send(!0)});return}const{length:h}=l,u=this.chat.getMessageSendingParams();let p=this.effect();this.iterate(m=>{t&&m.length!==h&&(this.managers.appMessagesManager.sendText({...u,text:t,entities:s,effect:p}),t=s=p=void 0);const g=this.willSendPaidMedia(),f=m.map(v=>({...v,file:v.scaledBlob||v.file,spoiler:g?void 0:!!v.mediaSpoiler})),y={...r,sendFileDetails:f};g||delete y.stars,this.managers.appMessagesManager.sendGrouped({...u,caption:t,entities:s,effect:p,isMedia:c,...y}),t=s=p=void 0}),u.replyToMsgId&&n.onHelperCancel(),this.wasDraft=void 0,this.hide()}modifyMimeTypeForTelegram(e){return hy.has(e)?"image/jpeg":e}async scaleImageForTelegram(e,t,s){let n=e.src,a;if(t!=="image/gif"&&(Math.max(e.naturalWidth,e.naturalHeight)>2560||s&&!hy.has(t))){const{blob:r}=await fu({media:e,boxSize:vs(2560,2560),mediaSize:vs(e.naturalWidth,e.naturalHeight),mimeType:this.modifyMimeTypeForTelegram(t)});a=r,URL.revokeObjectURL(n),n=await fe.invoke("createObjectURL",r),await Ki(e,n)}return a&&{url:n,blob:a}}async attachMedia(e){const{itemDiv:t}=e;t.classList.add("popup-item-media");const s=e.file;if(s.type.startsWith("video/")){const n=hl({middleware:e.middlewareHelper.get()});n.src=e.objectURL=await fe.invoke("createObjectURL",s),n.autoplay=!0,n.controls=!1,n.muted=!0,n.addEventListener("timeupdate",()=>{n.pause()},{once:!0}),t.append(n);let a;try{const c=Wn(n);await Bg(n,c)}catch(c){a=c}if(e.width=n.videoWidth,e.height=n.videoHeight,e.duration=Math.floor(n.duration),a)throw a;const r=n.webkitAudioDecodedByteCount;r!==void 0&&(e.noSound=!r);const l=await _x(n);e.thumb={url:await fe.invoke("createObjectURL",l.blob),...l}}else{const n=new Image;t.append(n);const a=e.objectURL=await fe.invoke("createObjectURL",s);await Ki(n,a);const r=e.file.type,l=await this.scaleImageForTelegram(n,r,!0);if(l&&(e.objectURL=l.url,e.scaledBlob=l.blob),e.width=n.naturalWidth,e.height=n.naturalHeight,s.type==="image/gif")return e.noSound=!0,Promise.all([kx(n).then(c=>{e.duration=Math.ceil(c)}),xC(n).then(async c=>{e.thumb={url:await fe.invoke("createObjectURL",c.blob),...c}})]).then(()=>{})}}async attachDocument(e){const{itemDiv:t}=e;t.classList.add("popup-item-document");const s=e.file,i=s.type.startsWith("image/"),n=ph.has(s.type);(i||n||s.size<2e7)&&(e.objectURL||(e.objectURL=await fe.invoke("createObjectURL",s)));const a=[];let r;if(i&&e.objectURL){r=new Image,await Ki(r,e.objectURL);const h=await this.scaleImageForTelegram(r,e.file.type);h&&(e.objectURL=h.url)}if(n&&e.objectURL)try{const h=new Audio;h.src=e.objectURL,h.muted=!0,h.autoplay=!0,await Wn(h),e.duration=h.duration,a.push({_:"documentAttributeAudio",duration:e.duration,pFlags:{}})}catch(h){console.error("audio loading error",h)}const l={_:"document",file:s,file_name:s.name||"",size:s.size,type:n?"audio":i?"photo":void 0,access_hash:0,attributes:a,date:0,dc_id:0,file_reference:[],id:0,pFlags:{},duration:e.duration};let c;e.objectURL&&(c={url:e.objectURL,downloaded:s.size,type:Rg});const d=await Yc({message:{_:"message",pFlags:{is_outgoing:!0},mid:0,peerId:0,media:{_:"messageMediaDocument",document:l}},cacheContext:c});i&&(e.width=r.naturalWidth,e.height=r.naturalHeight),t.append(d)}shouldCompress(e){return this.willAttach.type==="media"&&ka.has(e)}onRender(){this.element.classList.contains("active")||(this.listenerSetter.add(document.body)("keydown",this.onKeyDown),gt.setOnlyOnePlayableGroup(this.animationGroup),this.addEventListener("close",()=>{gt.setOnlyOnePlayableGroup(),!this.ignoreInputValue&&this.wasDraft&&this.chat.input.setDraft(this.wasDraft,!1,!0)}),this.show())}setTitle(){const{willAttach:e,title:t,files:s}=this;let i;const n=[];if(e.type==="document")i="PreviewSender.SendFile",n.push(s.length);else{let a=0,r=0,l=0;s.forEach(c=>{c.type.startsWith("image/")?++a:c.type.startsWith("video/")?++r:++l}),[a,r,l].filter(c=>c>0).length>1?(i="PreviewSender.SendFile",n.push(s.length)):a?(i="PreviewSender.SendPhoto",n.push(a)):r&&(i="PreviewSender.SendVideo",n.push(r))}dt(t,M(i,n))}appendMediaToContainer(e){if(this.shouldCompress(e.file.type)){const t=bL(e.width,e.height,Rv,320);e.itemDiv.style.width=t.width+"px",e.itemDiv.style.height=t.height+"px"}this.mediaContainer.append(e.itemDiv)}iterate(e){const{sendFileDetails:t}=this.willAttach;if(!this.willAttach.group){t.forEach(i=>e([i]));return}const s=t.length;for(let i=0;i<s;){const n=t[i].file.type;let a=0,r;for(;a<10&&i<s;++i,++a){const l=t[i].file.type,c=ph.has(l);if(r??(r=c),c!==r||this.shouldCompress(n)!==this.shouldCompress(l))break}e(t.slice(i-a,i))}}attachFiles(){const{files:e,willAttach:t,mediaContainer:s}=this,i=t.sendFileDetails.splice(0,t.sendFileDetails.length);i.forEach(a=>{a.middlewareHelper.destroy()});const n=e.map(a=>this.attachFile(a));Promise.all(n).then(()=>{s.replaceChildren(),e.length&&(this.setTitle(),this.iterate(a=>{const r=this.shouldCompress(a[0].file.type);if(r&&a.length>1){const l=document.createElement("div");l.classList.add("popup-item-album","popup-item"),l.append(...a.map(c=>c.itemDiv)),PS({container:l,items:a.map(c=>({w:c.width,h:c.height})),maxWidth:Rv,minWidth:100,spacing:4}),s.append(l)}else a.forEach(l=>{this.appendMediaToContainer(l)});r&&a.forEach(l=>{(i.find(d=>d.file===l.file)?.mediaSpoiler||this.willSendPaidMedia())&&this.applyMediaSpoiler(l,!0)})}),this.setUnlockPlaceholders())}).then(()=>{this.onRender(),this.onScroll()})}}window.PopupNewMedia=pr;class yp extends Si{constructor(e){super(!1),this.hidden=!0,this.onVisible=()=>{this.detach?.();const t=this.list,{attach:s,detach:i,resetTarget:n}=bC({list:t,type:this.listType,onSelect:this.onSelect,once:!0,waitForKey:this.waitForKey});this.attach=s,this.detach=i,this.resetTarget=n,!Oi&&!this.navigationItem&&(this.navigationItem={type:"autocomplete-helper",onPop:()=>{this.navigationItem=void 0,this.toggle(!0)},noBlurOnPop:!0},ft.pushItem(this.navigationItem)),this.addEventListener("hidden",()=>{this.resetTarget=void 0,this.attach=void 0,this.detach=void 0,t.replaceChildren(),i(),this.navigationItem&&(ft.removeItem(this.navigationItem),this.navigationItem=void 0)},{once:!0})},It(this,e),this.container=document.createElement("div"),this.container.classList.add("autocomplete-helper","z-depth-1"),e.appendTo.append(this.container),this.attachNavigation(),this.controller?.addHelper(this)}toggleListNavigation(e){e?this.attach?.():this.detach?.()}attachNavigation(){this.addEventListener("visible",this.onVisible)}toggle(e,t=!1,s){if(this.init)return;if(e===void 0&&(e=this.container.classList.contains("is-visible")&&!this.container.classList.contains("backwards")),this.hidden===e){e||this.dispatchEvent("visible");return}this.hidden=e,e?(this.navigationItem&&(ft.removeItem(this.navigationItem),this.navigationItem=void 0),!t&&this.controller&&this.controller.hideOtherHelpers(),this.detach?.()):(this.controller&&this.controller.hideOtherHelpers(this),this.dispatchEvent("visible"));const i=this.controller||e?0:2;e&&this.dispatchEvent("hiding"),bt({element:this.container,className:"is-visible",forwards:!e,duration:st.isAvailable("animations")&&!s?300:0,onTransitionEnd:()=>{this.hidden&&this.dispatchEvent("hidden")},useRafs:i})}}class Kx extends yp{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"xy",onSelect:async n=>!await this.chat.input.emoticonsDropdown.onMediaClick({target:n},!0),waitForKey:["ArrowUp","ArrowDown"]}),this.chat=s,this.managers=i,this.container.classList.add("stickers-helper"),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.scrollPosition=0},0),I.dispatchEvent("choosing_sticker",!0)}),this.addEventListener("hidden",()=>{this.onChangeScreen&&($e.removeEventListener("changeScreen",this.onChangeScreen),this.onChangeScreen=void 0,this.listenerSetter.removeAll(),this.listenerSetter=void 0),I.dispatchEvent("choosing_sticker",!1)})}checkEmoticon(e){const t=this.controller.getMiddleware();this.lazyLoadQueue?.clear(),CC(e),this.managers.appStickersManager.getStickersByEmoticon({emoticon:e,includeOurStickers:!0,includeServerStickers:I.settings.stickers.suggest==="all"}).then(s=>{if(!t())return;this.init&&(this.init(),this.init=null);const i=this.list.cloneNode();let n;this.lazyLoadQueue.clear(),s.length?(n=new Promise(a=>{const r=[];s.forEach(l=>{i.append(this.superStickerRenderer.renderSticker(l,void 0,r))}),Promise.all(r).finally(a)}),t.onClean(()=>{this.superStickerRenderer.clear()})):n=Promise.resolve(),n.then(()=>{this.list.replaceWith(i),this.list=i,this.onChangeScreen||(this.onChangeScreen=()=>{const a=this.list.childElementCount*$e.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=a+"px"},$e.addEventListener("changeScreen",this.onChangeScreen),this.listenerSetter=new Ut,Al({listenTo:this.container,listenerSetter:this.listenerSetter})),this.onChangeScreen(),this.toggle(!s.length),this.scrollable.scrollPosition=0})})}init(){this.list=document.createElement("div"),this.list.classList.add("stickers-helper-stickers","super-stickers"),this.container.append(this.list),this.scrollable=new vi(this.container),this.lazyLoadQueue=new Ga,this.superStickerRenderer=new sp({regularLazyLoadQueue:this.lazyLoadQueue,group:this.chat.animationGroup,managers:this.managers})}}class Wx extends yp{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"x",onSelect:n=>{s.onEmojiSelected(iu(n),!0)}}),this.chatInput=s,this.managers=i,this.container.classList.add("emoji-helper")}init(){this.list=document.createElement("div"),this.list.classList.add("emoji-helper-emojis","super-emojis"),this.container.append(this.list),this.scrollable=new yr(this.container),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.scrollPosition=0},0)})}renderEmojis(e,t){const s=new Map;if(this.list.replaceChildren(),I.premium||(e=e.filter(i=>this.chatInput.emoticonsDropdown.canUseEmoji(i,!1))),e.forEach(i=>{const n=rS(i,!0);if(this.list.append(n),i.docId){const a=n.firstElementChild;s.set(a.docId,new Set([a]))}}),s.size){const i=Ug.create({animationGroup:"INLINE-HELPER",customEmojiSize:$e.active.esgCustomEmoji,textColor:"primary-text-color",observeResizeElement:!1,middleware:t.create().get()});this.list.prepend(i),i.setDimensionsFromRect({width:e.length*42+8,height:42}),i.add({addCustomEmojis:s});const n=new Ut;t.onClean(()=>n.removeAll()),Al({listenTo:this.container,listenerSetter:n})}}render(e,t,s){if(this.init){if(!e.length)return;this.init(),this.init=null}e=e.slice(0,80),e.length&&this.renderEmojis(e,s),this.waitForKey=t?["ArrowUp","ArrowDown"]:void 0,this.toggle(!e.length)}checkQuery(e,t){const s=this.controller.getMiddleware(),i=e.replace(/^:/,"");this.managers.appEmojiManager.prepareAndSearchEmojis({q:i,addCustom:!0}).then(async n=>{s()&&this.render(n,t!==":",s)})}}const Ia=class Ia extends yp{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"y",onSelect:i}),this.className=s,this.container.classList.add(Ia.BASE_CLASS,s)}init(){this.list=document.createElement("div"),this.list.classList.add(Ia.BASE_CLASS+"-list",this.className+"-list"),this.container.append(this.list),this.scrollable=new vi(this.container),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.scrollPosition=0},0)})}render(e,t,s){if(this.init){if(!e.length)return;this.init(),this.init=null}e.length&&(this.list.replaceChildren(),e.forEach(i=>{const n=Ia.listElement({className:this.className,peerId:i.peerId,name:i.name,description:i.description,middleware:t});this.list.append(n)})),s||this.toggle(!e.length)}static listElement(e){const t=Ia.BASE_CLASS_LIST_ELEMENT;e.className+="-list-element";const s=document.createElement("div");s.classList.add(t,e.className),s.dataset.peerId=""+e.peerId;const{node:i}=es({middleware:e.middleware,isBig:!1,size:30,peerId:e.peerId});i.classList.add(t+"-avatar",e.className+"-avatar");const n=document.createElement("div");if(n.classList.add(t+"-name",e.className+"-name"),e.name?kt(n,_e(e.name)):n.append(new Rt({peerId:e.peerId,dialog:!1,onlyFirstName:!1,plainText:!1}).element),s.append(i,n),e.description){const a=document.createElement("div");a.classList.add(t+"-description",e.className+"-description"),kt(a,_e(e.description)),s.append(a)}return s}};Ia.BASE_CLASS="autocomplete-peer-helper",Ia.BASE_CLASS_LIST_ELEMENT=Ia.BASE_CLASS+"-list-element";let lo=Ia;function OC(o,e,t){const s=[].concat(e.bot_info);let i;t!==void 0&&(i=new gC({ignoreCase:!0}));const n=new Map;s.forEach(r=>{r.commands&&r.commands.forEach(({command:l,description:c},d)=>{const h="/"+l;n.set(l,{peerId:r.user_id?r.user_id.toPeerId(!1):o,command:l,name:h,description:c,index:d}),i&&i.indexObject(l,h)})});let a;if(!i)a=[...n.values()];else{const r=i.search(t);a=Array.from(r).map(l=>n.get(l))}return a=a.sort((r,l)=>n.get(r.command).index-n.get(l.command).index),a}class jx extends lo{constructor(e,t,s,i){super(e,t,"commands-helper",n=>{const a=n.querySelector(`.${lo.BASE_CLASS_LIST_ELEMENT}-name`).innerHTML;return s.getReadyToSend(()=>{s.messageInput.innerHTML=a,s.sendMessage(!0)})}),this.managers=i}async checkQuery(e,t){if(!await this.managers.appUsersManager.isBot(t))return!1;const s=this.controller.getMiddleware();return this.managers.appProfileManager.getProfileByPeerId(t).then(i=>{if(!s())return;const n=OC(t,i,e);this.render(n,s)}),!0}}class qx{constructor(){this.helpers=new Set,this.middleware=xt()}toggleListNavigation(e){for(const t of this.helpers)t.toggleListNavigation(e)}getMiddleware(){return this.middleware.clean(),this.middleware.get()}addHelper(e){this.helpers.add(e)}hideOtherHelpers(e){this.helpers.forEach(t=>{t!==e&&t.toggle(!0,!0)}),e||this.middleware.clean()}}class Qx extends lo{constructor(e,t,s,i){super(e,t,"mentions-helper",n=>{const a=n.dataset.peerId.toPeerId();s.mentionUser(a,!0)}),this.managers=i}checkQuery(e,t,s,i){const n=e.trim();if(e.length!==n.length)return!1;const a=this.controller.getMiddleware();return this.managers.appProfileManager.getMentions(t&&t.toChatId(),n,s,i).then(async r=>{if(!a())return;r=r.filter(d=>d!==I.myId);const l=r.map(async d=>{const h=await this.managers.appUsersManager.getUser(d),u=ui(h);return{peerId:d,description:u[0]?"@"+u[0]:void 0}}),c=(await Promise.all(l)).filter(Boolean);a()&&this.render(c,a)}),!0}}const Vo=class Vo extends yc{constructor(e){super({element:document.createElement("div")}),this.onBodyTouchStart=t=>{const s=t.touches[0].target;!Ns(s,this.element)&&s!==this.btnHover&&(oe(t),this.toggle(!1))},It(this,e),this.element.classList.add(Vo.BASE_CLASS),this.element.style.display="none",this.onClickMap=new Map,this.scrollable=new vi,this.element.append(this.scrollable.container),this.attachButtonListener(this.btnHover,this.listenerSetter),this.listenerSetter.add(I)("history_reply_markup",async({peerId:t})=>{this.peerId===t&&(this.checkAvailability()&&this.isActive()&&await this.render(),As().then(()=>{this.checkForceReply()}))})}init(){return this.appendTo.append(this.element),this.listenerSetter.add(this)("open",async()=>{await this.render(),Je&&(this.touchListener=this.listenerSetter.add(document.body)("touchstart",this.onBodyTouchStart,{passive:!1,capture:!0}),this.listenerSetter.add(this)("close",()=>{this.listenerSetter.remove(this.touchListener)},{once:!0}))}),N(this.element,e=>{const t=U(e.target,"btn");if(!t)return;this.onClickMap.get(t)?.(e),this.toggle(!1)},{listenerSetter:this.listenerSetter}),super.init()}async checkForceReply(){const e=await this.getReplyMarkup();e._==="replyKeyboardForceReply"&&!e.pFlags.hidden&&!e.pFlags.used&&(e.pFlags.used=!0,this.chatInput.initMessageReply({replyToMsgId:e.mid}))}async getReplyMarkup(){return(await this.managers.appMessagesManager.getHistoryStorageTransferable({peerId:this.peerId})).replyMarkup??{_:"replyKeyboardHide",pFlags:{}}}async render(e){e===void 0&&(e=await this.getReplyMarkup()),this.onClickMap.clear(),this.scrollable.replaceChildren();for(const t of e.rows){const s=document.createElement("div");s.classList.add(Vo.BASE_CLASS+"-row");for(const i of t.buttons){const{buttonEl:n,onClick:a}=qS({button:i,chat:this.chatInput.chat,replyMarkup:e});this.onClickMap.set(n,a),n.classList.add(Vo.BASE_CLASS+"-button","btn"),s.append(n)}this.scrollable.append(s)}}async checkAvailability(e){e===void 0&&(e=await this.getReplyMarkup());const t=e._==="replyKeyboardHide"||!e.rows?.length;return this.btnHover.classList.toggle("hide",t),t&&this.toggle(!1),!t}setPeer(e){this.peerId=e,this.checkAvailability(),this.checkForceReply()}};Vo.BASE_CLASS="reply-keyboard";let ig=Vo;function Yx(o,e){return o+"_"+e}const Dv="INLINE-HELPER";class Xx extends yp{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"xy",waitForKey:["ArrowUp","ArrowDown"],onSelect:n=>{if(!n)return!1;const{peerId:a,botId:r,queryId:l}=this.list.dataset;return this.chat.input.getReadyToSend(()=>{const c=Yx(l,n.dataset.resultId);this.managers.appInlineBotsManager.sendInlineResult(a.toPeerId(),r,c,{...this.chat.getMessageSendingParams(),clearDraft:!0}),this.chat.input.onMessageSent(!0,!0)})}}),this.chat=s,this.managers=i,this._checkQuery=async(n,a,r,l)=>{const c=this.controller.getMiddleware(),d=await this.managers.appUsersManager.resolveUsername(a);if(!c())throw"PEER_CHANGED";if(d._!=="user"||!d.pFlags.bot)throw"NOT_A_BOT";if(!l)throw c()?(this.init&&(this.init(),this.init=null),this.container.classList.add("cant-send"),this.toggle(!1),"NO_INLINES"):"PEER_CHANGED";const h=d.id,u=this.managers.appInlineBotsManager.getInlineResults(n,h,r).then(p=>{if(!c())throw"PEER_CHANGED";this.init&&(this.init(),this.init=null);const m=this.list.cloneNode();m.dataset.peerId=""+n,m.dataset.botId=""+h,m.dataset.queryId=""+p.query_id;const g=new bf(null,Dv,this.scrollable,!1);this.lazyLoadQueue.clear(),this.superStickerRenderer.clear();const f=[],y=!!p.pFlags.gallery;for(const v of p.results){const w=document.createElement("div");w.classList.add("inline-helper-result"),w.dataset.resultId=v.id;const b=y?void 0:document.createElement("div");if(b&&(b.classList.add("inline-helper-result-preview"),w.append(b)),m.append(w),y)w.classList.add("grid-item");else{b.classList.add("empty"),kt(b,_e([...v.title.trim()][0]));const S=document.createElement("div");S.classList.add("inline-helper-result-title"),kt(S,_e(v.title));const C=document.createElement("div");C.classList.add("inline-helper-result-description"),kt(C,Yt(v.description,{noCommands:!0,noLinks:!0})),w.append(S,C);const P=document.createElement("div");P.classList.add("inline-helper-separator"),m.append(P)}if(v._==="botInlineResult"){if(v.thumb&&v.thumb.mime_type.indexOf("image/")===0){let S;b?(S=document.createElement("div"),b.append(S)):S=w,S.classList.add("media-container"),y&&S.classList.add("no-border-radius"),this.lazyLoadQueue.push({div:w,load:()=>cs.download({dcId:4,location:{_:"inputWebFileLocation",access_hash:v.thumb.access_hash,url:v.thumb.url},size:v.thumb.size,mimeType:v.thumb.mime_type}).then(C=>{const P=new Image;P.classList.add("media-photo"),JI(C).then(L=>{mw({container:S,media:P,url:L,needFadeIn:st.isAvailable("animations")})})})})}}else{const S=v.document||v.photo;if(["sticker","gif"].includes(S?.type)&&y)S.type==="gif"?g.add(S,w):S.type==="sticker"&&(w.classList.add("super-sticker"),this.superStickerRenderer.renderSticker(S,w,f),S.animated&&this.superStickerRenderer.observeAnimated(w));else if(S){const C=y?48:void 0;y&&w.classList.add("no-border-radius"),Ks({photo:S,container:y?w:b,boxWidth:C,boxHeight:C,middleware:c,lazyLoadQueue:this.lazyLoadQueue,loadPromises:f})}}}return Promise.all(f).then(()=>{if(!c()){g.clear();return}m.classList.toggle("is-gallery",y),m.classList.toggle("super-stickers",y),this.container.classList.toggle("is-gallery",y);const v=this.list.parentElement;v.textContent="";const w=p.switch_pm||p.switch_webview;if(w){const b=ze("btn-primary btn-secondary btn-primary-transparent primary");kt(b,_e(w.text)),N(b,async S=>{w._==="inlineBotSwitchPM"?(await this.chat.appImManager.setInnerPeer({peerId:n}),this.managers.appInlineBotsManager.switchToPM(n,h,w.start_param)):this.chat.openWebApp({botId:h,url:w.url,isSimpleWebView:!0,buttonText:w.text,fromSwitchWebView:!0})}),v.append(b)}v.append(this.list=m),this.container.classList.remove("cant-send"),this.gifsMasonry?.detach(),this.gifsMasonry=g,g.attach(),this.onChangeScreen||(this.onChangeScreen=()=>{if(this.list.classList.contains("is-gallery")){const b=this.list.childElementCount*$e.active.popupSticker.width+(this.list.childElementCount-1);this.list.style.width=b+"px"}else this.list.style.width=""},$e.addEventListener("changeScreen",this.onChangeScreen)),this.onChangeScreen(),this.toggle(!p.results.length&&!w),this.scrollable.scrollPosition=0})});return{user:d,renderPromise:u}},this.container.classList.add("inline-helper"),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.scrollPosition=0},0)}),this.checkQuery=ii(this._checkQuery,200,!0,!0),this.addEventListener("hidden",()=>{this.onChangeScreen&&($e.removeEventListener("changeScreen",this.onChangeScreen),this.onChangeScreen=void 0)})}init(){this.list=document.createElement("div"),this.list.classList.add("inline-helper-results"),this.container.append(this.list),this.scrollable=new vi(this.container),this.lazyLoadQueue=new Ga,this.superStickerRenderer=new sp({regularLazyLoadQueue:this.lazyLoadQueue,group:Dv,managers:this.managers});const e=M(Or.send_inline);e.classList.add("inline-helper-cant-send"),this.container.append(e)}}const Zx="bot-commands";class Jx extends lo{constructor(e,t,s){super(e,void 0,Zx,i=>{const n=i.querySelector(`.${lo.BASE_CLASS_LIST_ELEMENT}-name`).innerHTML;return t.getReadyToSend(()=>{t.messageInput.innerHTML=n,t.sendMessage(!0),this.toggle(!0)})}),this.managers=s}setUserId(e,t){if(this.userId===e&&this.list?.childElementCount){this.toggle(!1);return}return this.userId=e,ei(this.managers.appProfileManager.getProfile(e),s=>{if(!t())return;const i=OC(e.toPeerId(!1),s),r=i.length*50+8+24;this.container.style.setProperty("--height",r+"px"),this.render(i,t)})}}function Bv(o,e=[],t){const s=[];let i=!1;const n=d=>c0(e,d)?i=!1:(s.push(d),i=!0),a=[];let r=0,l;for(;l=o.match(wL);){const d=r+l.index,h=l.index+l[0].length,u=l.index>0&&o.slice(0,l.index);u&&a.push(u);const p=l[3]||l[8]||l[11]||l[13];let m;if(i=!1,p.match(/^`*$/))a.push(l[0]);else if(l[3]){let f=l[3].match(/(.*?)\n/);f?.[1]||(f=void 0);let y=f?l[3].slice(f[1].length):l[3];const v=y[0]===`
`?1:0,w=y[y.length-1]===`
`?-1:void 0;if(y=y.slice(v,w),m={_:"messageEntityPre",language:f?.[1]||"",offset:d+l[1].length,length:y.length},n(m)){w&&(r-=1),f&&(r-=f[0].length);let b="";if(l[1])b=l[1];else{const S=a[a.length-1];S&&!/\s/.test(S[S.length-1])&&(b=`
`)}a.push(b,y,l[5]),r-=l[2].length+l[4].length}}else if(l[7]){const f=l[6]==="";m={_:Ab[l[7]],offset:d+(f?0:l[6].length),length:p.length},n(m)&&(f?a.push(p):a.push(l[6]+p+l[9]),r-=l[7].length*2+(f?2:0))}else l[11]?(m={_:"messageEntityMentionName",user_id:l[10].toUserId(),offset:d,length:p.length},n(m)&&(a.push(p),r-=l[0].length-p.length)):l[12]&&(m={_:"messageEntityTextUrl",url:l[14],offset:d,length:p.length},n(m)&&(a.push(p),r-=l[12].length-p.length));i||a.push(l[0]),o=o.substr(l.index+l[0].length),r+=l.index+l[0].length;const g=r-h;g&&e.forEach(f=>{f.offset>=d&&(f.offset+=g)})}o&&a.push(o);let c=a.join("");return c.replace(/\s+/g,"").length||(c=o,s.splice(0,s.length)),e=Qr(e,s),l0(e),c.length,[c,e]}const im=300;class eA{constructor(e,t,s){this.managers=e,this.onReady=t,this.onChange=s,this.middlewareHelper=xt(),this.listenerSetter=new Ut,this.construct()}construct(){this.container=document.createElement("div"),this.container.classList.add("new-message-send-as-container"),this.closeBtn=document.createElement("div"),this.closeBtn.classList.add("new-message-send-as-close","new-message-send-as-avatar"),this.closeBtn.append(Le("close"));const e=[{text:"SendMessageAsTitle",onClick:void 0}];this.buttons=[];let t;const s=i=>{i&&(t=this.avatar);const n=this.avatar!==t,a=!i&&n?2:0;bt({element:this.closeBtn,className:"is-visible",forwards:i,duration:im,useRafs:a}),n||bt({element:t.node,className:"is-visible",forwards:!i,duration:im,useRafs:a})};ai({buttonOptions:{noRipple:!0},listenerSetter:this.listenerSetter,container:this.container,direction:"top-right",buttons:e,onOpenBefore:()=>{s(!0)},onOpen:(i,n)=>{e[0].element.classList.add("btn-menu-item-header"),this.btnMenu=n,this.btnMenu.classList.add("scrollable","scrollable-y"),this.btnMenu.append(...this.buttons.map(a=>a.element))},onClose:()=>{s(!1)},onCloseAfter:()=>{this.btnMenu=void 0}}),this.container.append(this.closeBtn)}async updateButtons(e){const t=e.map(async(i,n)=>{const a=document.createElement("div"),{peerId:r,needPremium:l}=i,c=document.createElement("div");c.classList.add("btn-menu-item-subtitle"),r.isUser()?c.append(M("Chat.SendAs.PersonalAccount")):r===this.peerId?c.append(M("VoiceChat.DiscussionGroup")):c.append(await da(r.toChatId()));const d=document.createElement("div");return d.append(new Rt({peerId:r}).element),l&&d.append(Le("premium_lock","new-message-send-as-lock")),a.append(d,c),{onClick:n?async()=>{if(i.needPremium&&!I.premium){Vt.show();return}const h=this.peerId;this.changeSendAsPeerId(r);const u=this.middlewareHelper.get(),p=()=>{if(this.sendAsPeerId!==r||!u())return;const m=this.sendAsPeers.slice(),g=m.findIndex(f=>f.peerId===r);g!==-1&&m.splice(g,1),m.unshift(i),this.updateButtons(m)};st.isAvailable("animations")?setTimeout(p,250):p(),this.managers.appMessagesManager.saveDefaultSendAs(h,r)}:void 0,textElement:a}}),s=await Promise.all(t);jn({buttons:s}),s.forEach((i,n)=>{const{peerId:a}=e[n],r=es({middleware:this.middlewareHelper.get(),size:26,peerId:a});r.node.classList.add("btn-menu-item-icon"),n||r.node.classList.add("active"),i.element.prepend(r.node)}),this.buttons=s,this.btnMenu?.append(...this.buttons.map(i=>i.element))}async updateAvatar(e,t){const s=this.avatar;if(s&&s.node.dataset.peerId.toPeerId()===e)return;s||(t=!0);const i=t?0:2,n=t?0:im,a=this.avatar=es({middleware:this.middlewareHelper.get(),size:30,isDialog:!1,peerId:e});a.node.classList.add("new-message-send-as-avatar"),await a.readyThumbPromise,bt({element:a.node,className:"is-visible",forwards:!0,duration:n,useRafs:i}),s&&bt({element:s.node,className:"is-visible",forwards:!1,duration:n,onTransitionEnd:()=>{s.node.remove()},useRafs:i}),this.container.append(a.node)}changeSendAsPeerId(e,t){return this.sendAsPeerId=e,this.onChange(e),this.updateAvatar(e,t)}getDefaultSendAs(){return this.managers.acknowledged.appProfileManager.getChannelFull(this.peerId.toChatId()).then(e=>({cached:e.cached,result:e.result.then(t=>t.default_send_as?at(t.default_send_as):void 0)}))}async updateManual(e){const t=this.peerId;if(this.updatingPromise||!await this.managers.appPeersManager.isChannel(t))return;const s=this.middlewareHelper.get(()=>!this.updatingPromise||this.updatingPromise===c),{container:i}=this,n=t.toChatId(),a=(await to(this.getDefaultSendAs())).result,r=e;a instanceof Promise&&(e=void 0);const l=r&&!e,c=this.updatingPromise=ei(a,async d=>{if(!s()||d===void 0||(await this.changeSendAsPeerId(d,e),!s()))return;Promise.all([this.managers.appChatsManager.getSendAs(n),fe.isPremiumFeaturesHidden()]).then(([u,p])=>{if(!s())return;p&&(u=u.filter(f=>!f.pFlags.premium_required));const m=u.map(f=>({peerId:at(f.peer),needPremium:f.pFlags.premium_required}));this.sendAsPeers=m.slice();const g=m.findIndex(f=>f.peerId===d);if(g!==-1){const f=m.splice(g,1)[0];m.unshift(f)}else m.unshift({peerId:d});this.updateButtons(m)});const h=()=>{this.onReady(i,e),this.addedListener||(this.listenerSetter.add(I)("peer_full_update",u=>{this.peerId===u&&this.update()}),this.addedListener=!0)};if(l){h();return}return h});if(c.finally(()=>{this.updatingPromise===c&&(this.updatingPromise=void 0)}),!l)return c}update(e){return this.updateManual(e).then(t=>t?.())}setPeerId(e){this.middlewareHelper.clean(),this.updatingPromise=void 0,this.peerId=e}destroy(){this.container.remove(),this.setPeerId(),this.listenerSetter.removeAll()}}function tA(o,e){return Di(o,e)}function Nv(o,e){return Di(o,e,["date","reply_to"])&&tA(o?.reply_to,e?.reply_to)}function Df(o){if(o)return o.icons.find(e=>e.name===SL)}function vu(o){return o?o.match(CL):null}function ng(o,e){const t={};o.forEach(d=>t[d]={elements:[],active:!1});const s=window.getSelection();if(s.isCollapsed)return t;const i=s.getRangeAt(0),n=i.commonAncestorContainer,r=(n.nodeType===n.ELEMENT_NODE?n:n.parentElement).closest('[contenteditable="true"]');if(!r)return t;const l=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:d=>i.intersectsNode(d)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});let c;for(;c=l.nextNode();)for(const d of o){const h=d0[d],u=c.nodeType===c.ELEMENT_NODE?c:c.parentElement;u.closest(h.match)&&t[d].elements.push(u)}for(const d of o)t[d].active=t[d].elements.length>=1;return t}class Dl{constructor(){this.buttons={},this.addedListener=!1,this.waitingForMouseUp=!1,this.mouseUpCounter=0,this.onMouseUpSingle=e=>{if(this.waitingForMouseUp=!1,Je)if(e&&oe(e),this.mouseUpCounter++===0)this.resetSelection(this.savedRange);else{this.hide();return}this.show()}}static getInstance(){return this.INSTANCE||(this.INSTANCE=new Dl)}init(){this.container=document.createElement("div"),this.container.classList.add("markup-tooltip","z-depth-1","hide"),this.wrapper=document.createElement("div"),this.wrapper.classList.add("markup-tooltip-wrapper");const e=document.createElement("div"),t=document.createElement("div");e.classList.add("markup-tooltip-tools","markup-tooltip-tools-regular"),t.classList.add("markup-tooltip-tools","markup-tooltip-tools-link"),["bold","italic","underline","strikethrough","monospace","spoiler",["quote","quote_outline"],"link"].forEach(l=>{const c=typeof l=="string"?l:l[0],d=typeof l=="string"?l:l[1],h=it(d,{noRipple:!0});e.append(this.buttons[c]=h),l!=="link"?h.addEventListener("mousedown",u=>{oe(u),ag(this.input,c),this.cancelClosening()}):N(h,u=>{oe(u),this.showLinkEditor(),this.cancelClosening()})}),this.linkBackButton=it("left",{noRipple:!0}),this.linkInput=document.createElement("input"),Zt(this.linkInput,"MarkupTooltip.LinkPlaceholder",void 0,"placeholder"),this.linkInput.classList.add("input-clear"),this.linkInput.addEventListener("keydown",l=>{const c=!this.linkInput.value.length||!!vu(this.linkInput.value);l.key==="Enter"&&(c?this.applyLink(l):(this.linkInput.classList.contains("error")&&(this.linkInput.classList.remove("error"),this.linkInput.offsetLeft),this.linkInput.classList.add("error")))}),this.linkInput.addEventListener("input",l=>{const c=this.isLinkValid();this.linkInput.classList.toggle("is-valid",c),this.linkInput.classList.remove("error")}),this.linkBackButton.addEventListener("mousedown",l=>{oe(l),this.container.classList.remove("is-link"),this.resetSelection(),this.setTooltipPosition(),this.cancelClosening()}),this.linkApplyButton=it("check markup-tooltip-link-apply",{noRipple:!0}),this.linkApplyButton.addEventListener("mousedown",l=>{this.applyLink(l)});const i=document.createElement("div");i.classList.add("markup-tooltip-link-apply-container");const n=document.createElement("span"),a=document.createElement("span"),r=document.createElement("span");n.classList.add("markup-tooltip-delimiter"),a.classList.add("markup-tooltip-delimiter"),r.classList.add("markup-tooltip-delimiter"),e.insertBefore(n,this.buttons.link),i.append(r,this.linkApplyButton),t.append(this.linkBackButton,a,this.linkInput,i),this.wrapper.append(e,t),this.container.append(this.wrapper),document.body.append(this.container),window.addEventListener("resize",()=>{this.hide()})}showLinkEditor(){(!this.container||!this.container.classList.contains("is-visible"))&&this.show();const e=this.buttons.link;this.container.classList.add("is-link");const t=document.getSelection();this.savedRange=t.getRangeAt(0);const i=ng(["link"]).link.elements.find(n=>n.tagName==="A");e.classList.contains("active")?this.linkInput.value=i.href:this.linkInput.value="",this.setTooltipPosition(!0),setTimeout(()=>{this.linkInput.focus()},200),this.linkInput.classList.toggle("is-valid",this.isLinkValid())}applyLink(e){oe(e),this.resetSelection();let t=this.linkInput.value;t&&!IL(t)&&(t="https://"+t),ag(this.input,"link",t),setTimeout(()=>{this.hide()},0)}isLinkValid(){return!this.linkInput.value.length||!!vu(this.linkInput.value)}resetSelection(e=this.savedRange){const t=window.getSelection();t.removeAllRanges(),t.addRange(e),this.input.focus()}hide(){this.init||(this.input=void 0,this.container.classList.remove("is-visible"),document.removeEventListener("mouseup",this.onMouseUpSingle),this.waitingForMouseUp=!1,ft.removeByType("markup"),this.hideTimeout&&clearTimeout(this.hideTimeout),this.hideTimeout=window.setTimeout(()=>{this.hideTimeout=void 0,this.container.classList.add("hide"),this.container.classList.remove("is-link")},200))}getActiveMarkupButton(){const e=new Set,t=Object.keys(this.buttons),s=ng(t);return t.forEach(i=>{s[i].active&&e.add(this.buttons[i])}),[...e]}setActiveMarkupButton(){const e=this.getActiveMarkupButton();for(const t in this.buttons){const s=this.buttons[t];s.classList.toggle("active",e.includes(s))}}setTooltipPosition(e=!1){const s=document.getSelection().getRangeAt(0),i=U(this.input,"rows-wrapper")||U(this.input,"input-message-container")||U(this.input,"input-field"),n=this.container.classList.contains("is-link")?this.wrapper.lastElementChild:this.wrapper.firstElementChild,a=document.body.getBoundingClientRect(),r=s.getBoundingClientRect(),l=i.getBoundingClientRect(),c=n.getBoundingClientRect();this.container.style.maxWidth=l.width+"px";const d=go(void 0,this.input,!1,r),{newHeight:h=0,oldHeight:u=h}=this.input;if(!d)return;const m=(d?d.rect.top:l.top)+a.top*-1-c.height-8+(u-h),g=l.left,f=l.left+l.width-Math.min(l.width,c.width);let y;if(e){const v=this.container.getBoundingClientRect();y=Kt(v.left,g,f)}else{const v=r.left+(r.width-c.width)/2;y=Kt(v,g,f)}this.container.style.transform=`translate3d(${y}px, ${m}px, 0)`}show(){if(this.init&&(this.init(),this.init=null),Yo()){this.hide();return}if(this.hideTimeout!==void 0&&clearTimeout(this.hideTimeout),this.container.classList.contains("is-visible"))return;this.container.classList.toggle("night",Li.isDarkOverlayActive),this.setActiveMarkupButton(),this.container.classList.remove("is-link");const e=this.container.classList.contains("hide");e&&(this.container.classList.remove("hide"),this.container.classList.add("no-transition")),this.setTooltipPosition(),e&&(this.container.offsetLeft,this.container.classList.remove("no-transition")),this.container.classList.add("is-visible"),Oi||ft.pushItem({type:"markup",onPop:()=>{this.hide()}})}setMouseUpEvent(){this.waitingForMouseUp||(this.waitingForMouseUp=!0,document.addEventListener("mouseup",this.onMouseUpSingle,{once:!0}))}cancelClosening(){Je&&!Zr&&(document.removeEventListener("mouseup",this.onMouseUpSingle),document.addEventListener("mouseup",e=>{oe(e),this.mouseUpCounter=1,this.waitingForMouseUp=!1,this.setMouseUpEvent()},{once:!0}))}canFormatInput(e){return e.classList.contains("input-message-input")||e.getAttribute("can-format")}handleSelection(){this.addedListener||(this.addedListener=!0,document.addEventListener("selectionchange",e=>{if(document.activeElement===this.linkInput)return;const t=document.activeElement;if(this.input?t!==this.input:!this.canFormatInput(t)){this.hide();return}const s=document.getSelection();if(Yo(s)){this.hide();return}if(this.input=t,Je)if(Zr)this.show(),this.setTooltipPosition();else{if(this.mouseUpCounter===2){this.mouseUpCounter=0;return}this.savedRange=s.getRangeAt(0),this.setMouseUpEvent()}else this.container&&this.container.classList.contains("is-visible")?(this.setActiveMarkupButton(),this.setTooltipPosition()):this.input.matches(":active")?this.setMouseUpEvent():this.show()}),document.addEventListener("beforeinput",e=>{(e.inputType==="historyRedo"||e.inputType==="historyUndo")&&e.target.addEventListener("input",()=>this.setActiveMarkupButton(),{once:!0})}))}}function sA(o){const e=document.createRange();if(o.endContainer.nodeType===Node.TEXT_NODE&&o.endOffset<o.endContainer.nodeValue.length)return e.setStart(o.endContainer,o.endOffset),e.setEnd(o.endContainer,o.endOffset+1),e.toString();const t=iA(o.endContainer);if(t)return e.setStart(t,0),e.setEnd(t,Math.min(t.nodeValue.length,1)),e.toString()}function iA(o){for(;o&&!o.nextSibling;)o=o.parentNode;if(o&&o.nextSibling)return UC(o.nextSibling)}function UC(o){if(o.nodeType===Node.TEXT_NODE)return o;for(let e=0;e<o.childNodes.length;e++){const t=o.childNodes[e],s=UC(t);if(s)return s}}const HC=new WeakMap;function nA(o){const e=HC.get(o);e&&(e.canRedoFromHTML="",e.undoHistory.length=0,e.executedHistory.length=0,e.canUndoFromHTML="")}function aA(o){const e=HC.get(o);e&&e.canRedoFromHTML&&!e.lockRedo&&o.innerHTML!==e.canRedoFromHTML&&(e.canRedoFromHTML="",e.undoHistory.length=0)}function ag(o,e,t){const s={link:t?()=>document.execCommand("createLink",!1,t):()=>document.execCommand("unlink",!1,null)},i=u=>{s[u]=()=>{const p=(n.includes(u)?n:[u]).filter(g=>h[g]?.active);if(us(p,u)||p.push(u),u==="quote"){const g=document.getSelection();g.rangeCount&&sA(g.getRangeAt(0))===`
`&&g.modify(g.isCollapsed?"move":"extend","forward","character")}let m;return p.length?m=document.execCommand("fontName",!1,"markup-"+p.join("-")):m=oA(),$C(o),m}},n=["bold","italic","underline","strikethrough","spoiler","quote"];if(n.forEach(u=>{i(u)}),i("monospace"),!s[e])return!1;const a=s[e],r=[],c=Hg.getInstance().prepareApplyingMarkdown(),d={capture:!0,passive:!1};o.addEventListener("input",oe,d),r.push(document.execCommand("styleWithCSS",!1,"true"));const h=ng(Object.keys(s));return h.monospace?.active&&e==="link"&&r.push(rA()),r.push(typeof a=="function"?a():document.execCommand(a,!1,null)),r.push(document.execCommand("styleWithCSS",!1,"false")),c(),Dl.getInstance().setActiveMarkupButton(),o.removeEventListener("input",oe,d),Sd(o,"input"),!0}function $C(o){o.querySelectorAll('[style*="font-family"]').forEach(e=>{if(e.style.caretColor){e.style.cssText="";return}const t=e.style.fontFamily;t!==wm&&(e.classList.add("is-markup"),e.dataset.markup=t,Oa(e),t.includes("quote")&&e.classList.add("quote-like","quote-like-icon","quote-like-border"))}),o.querySelectorAll(".is-markup").forEach(e=>{const t=e.style.fontFamily;t&&t!==wm||(t.includes("quote")||e.classList.remove("quote-like","quote-like-icon","quote-like-border"),e.classList.remove("is-markup"),delete e.dataset.markup)})}function rA(){return document.execCommand("removeFormat",!1,null)}function oA(){return document.execCommand("fontName",!1,wm)}function lA(o,e){const t={KeyB:"bold",KeyI:"italic",KeyU:"underline",KeyS:"strikethrough",KeyM:"monospace",KeyP:"spoiler"};t.KeyK="link";const s=e.code,i=t[s],n=document.getSelection();!Yo(n)&&i&&(s==="KeyK"?Dl.getInstance().showLinkEditor():ag(o,i),oe(e))}function Bf(o,e,t=!0){const s=()=>{clearTimeout(n)},i=o;t||(o=Wt);let n;return function a(){o(),n=Oh.setTimeout(a,Math.max(0,e()))}(),o=i,s}function cA(o,e){return Bf(o,()=>1e3-new Date().getMilliseconds(),e)}const dA=500,hA=!1,Or={send_voices:"GlobalAttachVoiceRestricted",send_stickers:"GlobalAttachStickersRestricted",send_gifs:"GlobalAttachGifRestricted",send_media:"GlobalAttachMediaRestricted",send_plain:"GlobalSendMessageRestricted",send_polls:"ErrorSendRestrictedPollsAll",send_inline:"GlobalAttachInlineRestricted"},mh="chat-input",ko=new Set([te.Scheduled,te.Stories,te.Saved]),_c=class _c{constructor(e,t,s,i){this.chat=e,this.appImManager=t,this.managers=s,this.className=i,this.lastUrl="",this.lastTimeType=0,this.replyElements={},this.willSendWebPage=null,this.webPageOptions={},this.recording=!1,this.recordCanceled=!1,this.recordStartTime=0,this.onAttachClick=async(n,a,r)=>{if(await this.showSlowModeTooltipIfNeeded({element:this.attachMenu}))return;const l=this.fileSelectionPromise=Pt();this.fileInput.value="",l.finally(()=>{xa.removeEventListener("change",c),this.fileSelectionPromise});const c=d=>{if(l!==this.fileSelectionPromise){l.reject();return}d||setTimeout(()=>{l.reject()},1e3)};if(xa.addEventListener("change",c),n)this.fileInput.removeAttribute("accept"),this.willAttachType="document";else{const d=[...a?Vh:[],...r?Sh:[]].join(", ");this.fileInput.setAttribute("accept",d||"*/*"),this.willAttachType="media"}this.fileInput.click(),this.onFileSelection?.(this.fileSelectionPromise)},this.unblockUser=()=>{const n=this.toggleControlButtonDisability=jt([this.unblockBtn],!0),a=this.chat.peerId,r=this.getMiddleware(()=>this.chat.peerId===a&&this.toggleControlButtonDisability===n);this.managers.appUsersManager.toggleBlock(a,!1).then(()=>{r()&&(n(),this.toggleControlButtonDisability=void 0)})},this.startBot=()=>{const{startParam:n}=this,a=this.toggleControlButtonDisability=jt([this.botStartBtn],!0),r=this.chat.peerId,l=this.getMiddleware(()=>this.chat.peerId===r&&this.startParam===n&&this.toggleControlButtonDisability===a);this.managers.appMessagesManager.startBot(r.toUserId(),void 0,n).then(()=>{l()&&(a(),this.toggleControlButtonDisability=void 0,this.setStartParam())})},this.onCancelRecordClick=n=>{n&&oe(n),this.recordCanceled=!0,this.recorder.stop(),Xd.setKeepAlive(!1)},this.onEmoticonsToggle=n=>{this.btnToggleEmoticons&&(Je?po(this.btnToggleEmoticons,n?"keyboard":"smile"):this.btnToggleEmoticons.classList.toggle("active",n))},this.onEmoticonsOpen=()=>{this.onEmoticonsToggle(!0)},this.onEmoticonsClose=()=>{this.onEmoticonsToggle(!1)},this.canSendWhenOnline=async()=>{const n=this.chat.peerId;return I.myId===n||!n.isUser()||!await this.managers.appUsersManager.isUserOnlineVisible(n)?!1:(await this.managers.appUsersManager.getUser(n)).status?._!=="userStatusOnline"},this.scheduleSending=async(n=this.sendMessage.bind(this,!0),a=new Date)=>{const r=this.getMiddleware(),l=await this.canSendWhenOnline();r()&&ee.createPopup(If,{initDate:a,onPick:c=>{r()&&this.setScheduleTimestamp(c,n)},canSendWhenOnline:l}).show()},this.onMessageInput=n=>{const{value:a,entities:r,caretPos:l}=fn(this.messageInputField.input),[c,d]=Bv(a,r),h=Qr(d,Ko(c));if(aA(this.messageInput),this.processWebPage(a,h),!a.trim())this.lastTimeType&&this.managers.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageCancelAction"},void 0,this.chat.threadId),Dl.getInstance().hide(),document.activeElement===this.messageInput&&!Oi&&setTimeout(()=>{document.activeElement===this.messageInput&&(this.messageInput.textContent="1",Zs(this.messageInput),this.messageInput.textContent="")},0);else{const p=Date.now();p-this.lastTimeType>=6e3&&n?.isTrusted&&(this.lastTimeType=p,this.managers.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageTypingAction"},void 0,this.chat.threadId)),this.botCommands?.toggle(!0)}this.botCommands&&this.updateBotCommandsToggle(),!this.editMsgId&&!this.processingDraftMessage&&this.saveDraftDebounced(),this.checkAutocomplete(a,l,h),$C(this.messageInput),this.updateSendBtn()},this.onEmojiSelected=(n,a)=>{const r=n.docId?{_:"messageEntityCustomEmoji",document_id:n.docId,length:n.emoji.length,offset:0}:zh(n.emoji);return this.insertAtCaret(n.emoji,r,a),!0},this.onBtnSendClick=async n=>{oe(n);const a=this.isInputEmpty();if(this.chat.type===te.Stories&&a&&!this.freezedFocused&&this.canForwardStory){this.forwardStoryCallback?.(n);return}else if(!this.recorder||this.recording||!a||this.forwarding||this.editMsgId)this.recording?Date.now()-this.recordStartTime<dA?this.onCancelRecordClick():this.recorder.stop():this.sendMessage();else{const r=this.chat.peerId.isAnyChat(),l="send_voices";if(r&&!await this.chat.canSend(l)){Ee({langPackKey:Or[l]});return}if(await this.showSlowModeTooltipIfNeeded())return;this.chatInput.classList.add("is-locked"),Dn();let c=!1;if(r||(await this.managers.appProfileManager.getProfile(this.chat.peerId.toUserId()))?.pFlags.voice_messages_forbidden&&(Ee({langPackKey:"Chat.SendVoice.PrivacyError",langPackArguments:[await Oe({peerId:this.chat.peerId})]}),c=!0),c){this.chatInput.classList.remove("is-locked");return}this.recorder.start().then(()=>{this.releaseMediaPlayback=rt.setSingleMedia(),this.recordCanceled=!1,this.setRecording(!0),Xd.setKeepAlive(!0);const d=()=>{ee.createPopup(Ss,"popup-cancel-record",{titleLangKey:"DiscardVoiceMessageTitle",descriptionLangKey:"DiscardVoiceMessageDescription",buttons:[{langKey:"DiscardVoiceMessageAction",callback:()=>{fs(this.btnCancelRecord)}},{langKey:"Continue",isCancel:!0}]}).show()};this.recordingOverlayListener=this.listenerSetter.add(document.body)("mousedown",v=>{!U(v.target,mh)&&!U(v.target,"popup-cancel-record")&&(oe(v),d())},{capture:!0,passive:!1}),ft.pushItem(this.recordingNavigationItem={type:"voice",onPop:()=>(setTimeout(()=>{d()},0),!1)}),this.recordStartTime=Date.now();const h=this.recorder.sourceNode,p=h.context.createAnalyser();h.connect(p),p.fftSize=32;const m=new Uint8Array(p.frequencyBinCount),g=m.length*255,f=54/150,y=()=>{if(!this.recording)return;p.getByteFrequencyData(m);let v=0;m.forEach(P=>{v+=P});const w=Math.min(1,v/g+f);this.recordRippleEl.style.transform=`scale(${w})`;const b=Date.now()-this.recordStartTime,S=b%1e3,C=Fi(b/1e3)+","+("00"+Math.round(S/10)).slice(-2);this.recordTimeEl.textContent=C,bs(y)};y()}).catch(d=>{switch(d.name){case"NotAllowedError":{zs("Please allow access to your microphone");break}case"NotReadableError":{zs(d.message);break}default:console.error("Recorder start error:",d,d.name,d.message),zs(d.message);break}this.setRecording(!1),this.chatInput.classList.remove("is-locked")})}},this.onHelperCancel=async(n,a)=>{if(n&&oe(n),this.willSendWebPage){const r=this.lastUrl;let l=!1;if(this.helperType&&(await this.helperFunc(),l=!0),this.lastUrl=r,this.noWebPage=!0,this.willSendWebPage=null,l)return}if(this.helperType==="edit"&&!a){const r=this.editMessage,l=this.getCurrentInputAsDraft(!0);l&&delete l.pFlags.no_webpage;const c=r.reply_to?._==="messageReplyHeader"?r.reply_to:void 0,d=r?.media?._==="messageMediaWebPage"?r.media:void 0,h=d?.webpage?.pFlags?.has_large_media,u={_:"draftMessage",date:l?.date,message:r.message,entities:r.entities,pFlags:{invert_media:r.pFlags.invert_media},media:d&&{_:"inputMediaWebPage",pFlags:{force_large_media:h&&d.pFlags.force_large_media||void 0,force_small_media:h&&d.pFlags.force_small_media||void 0,optional:!0},url:d.webpage.url},reply_to:c&&{_:"inputReplyToMessage",reply_to_msg_id:c.reply_to_msg_id}};if(u.entities?.length||l?.entities?.length){const p=new Set(Object.values(Ab));p.add("messageEntityCustomEmoji"),u?.entities&&(u.entities=u.entities.slice()),[u,l].forEach(m=>{m?.entities&&(bi(m.entities,(g,f,y)=>{p.has(g._)||y.splice(f,1)}),m.entities.length||delete m.entities)})}if(!Nv(l,u)){ee.createPopup(Ss,"discard-editing",{buttons:[{langKey:"Alert.Confirm.Discard",callback:()=>{this.onHelperCancel(void 0,!0)}}],descriptionLangKey:"Chat.Edit.Cancel.Text"}).show();return}}else this.helperType==="reply"&&this.saveDraftDebounced();this.clearHelper(),this.updateSendBtn()},this.onHelperClick=n=>{if(n&&oe(n),n&&!U(n.target,"reply"))return;let a;this.helperType==="forward"?a=this.forwardElements?.container:this.helperType==="reply"?(this.chat.setMessageId({lastMsgId:this.replyToMsgId}),a=this.replyElements?.menuContainer):this.helperType==="edit"?this.chat.setMessageId({lastMsgId:this.editMsgId}):this.helperType||(a=this.webPageElements?.container),Je&&a&&!a.classList.contains("active")&&Js.openBtnMenu(a)},this.listenerSetter=new Ut,this.hoverListenerSetter=new Ut,this.excludeParts={},this.isFocused=!1,this.emoticonsDropdown=Ji}construct(){const e=this.className;this.chatInput=document.createElement("div"),this.chatInput.classList.add(mh,e,"hide"),this.inputContainer=document.createElement("div"),this.inputContainer.classList.add(`${mh}-container`,`${e}-container`),this.rowsWrapperWrapper=document.createElement("div"),this.rowsWrapperWrapper.classList.add("rows-wrapper-wrapper"),this.rowsWrapper=document.createElement("div"),this.rowsWrapper.classList.add(...["rows-wrapper",`${mh}-wrapper`,`${e}-wrapper`,this.chat.type!==te.Stories&&"chat-rows-wrapper"].filter(Boolean)),this.rowsWrapperWrapper.append(this.rowsWrapper);const t=XS(!this.chat.isMainChat);this.rowsWrapper.append(t);const s=this.fakeRowsWrapper=document.createElement("div");s.classList.add("fake-wrapper","fake-rows-wrapper");const i=this.fakeSelectionWrapper=document.createElement("div");i.classList.add("fake-wrapper","fake-selection-wrapper"),this.inputContainer.append(this.rowsWrapperWrapper,s,i),this.chatInput.append(this.inputContainer),this.excludeParts.downButton||this.constructGoDownButton();const n=this.controlContainer=document.createElement("div");n.classList.add("chat-input-control","chat-input-wrapper"),this.inputContainer.append(n)}freezeFocused(e){this.freezedFocused!==e&&(this.freezedFocused=e,this.updateSendBtn())}createButtonIcon(...e){this.noRipple&&(e[1]??(e[1]={}),e[1].noRipple=!0);const t=it(...e);return t.tabIndex=-1,t}constructGoDownButton(){this.goDownBtn=Ei({icon:"arrow_down",className:"bubbles-corner-button chat-secondary-button bubbles-go-down hide"}),this.inputContainer.append(this.goDownBtn),N(this.goDownBtn,e=>{oe(e),this.chat.bubbles.onGoDownClick()},{listenerSetter:this.listenerSetter})}constructReplyElements(){this.replyElements.container=document.createElement("div"),this.replyElements.container.classList.add("reply-wrapper","rows-wrapper-row"),this.replyElements.iconBtn=this.createButtonIcon(""),this.replyElements.cancelBtn=this.createButtonIcon("close reply-cancel",{noRipple:!0}),this.replyElements.container.append(this.replyElements.iconBtn,this.replyElements.cancelBtn),N(this.replyElements.cancelBtn,this.onHelperCancel,{listenerSetter:this.listenerSetter}),N(this.replyElements.container,this.onHelperClick,{listenerSetter:this.listenerSetter});const e=[{icon:"message_jump",text:"ShowMessage",onClick:()=>{this.onHelperClick(),this.replyHover.toggle(!1)}},this.replyElements.replyInAnother={icon:"replace",text:"ReplyToAnotherChat",onClick:()=>this.changeReplyRecipient()},this.replyElements.doNotReply={icon:"delete",text:"DoNotReply",onClick:this.onHelperCancel,danger:!0},this.replyElements.doNotQuote={icon:"delete",text:"DoNotQuote",onClick:this.onHelperCancel,danger:!0}],t=this.replyElements.menuContainer=jn({buttons:e,listenerSetter:this.listenerSetter});Je||(this.replyHover=new yc({element:t})),this.replyElements.container.append(t)}constructForwardElements(){const e=()=>{i=!0},t=()=>{i=!1},s=this.forwardElements={};let i=!1;const n=[s.showSender={text:"Chat.Alert.Forward.Action.Show1",onClick:e,checkForClose:()=>this.canToggleHideAuthor(),radioGroup:"author"},s.hideSender={text:"Chat.Alert.Forward.Action.Hide1",onClick:e,checkForClose:()=>this.canToggleHideAuthor(),radioGroup:"author"},s.showCaption={text:"Chat.Alert.Forward.Action.ShowCaption",onClick:t,radioGroup:"caption"},s.hideCaption={text:"Chat.Alert.Forward.Action.HideCaption",onClick:t,radioGroup:"caption"},s.changePeer={text:"Chat.Alert.Forward.Action.Another",onClick:()=>{this.changeForwardRecipient()},icon:"replace"},{icon:"delete",text:"DoNotForward",onClick:this.onHelperCancel,danger:!0}],a=s.container=jn({buttons:n,radioGroups:[{name:"author",onChange:r=>{const l=!!+r;i&&(this.forwardWasDroppingAuthor=!l);const c=this.replyElements.container.querySelector(".reply-title");if(c){const d=c.firstElementChild,h=ke.weakMap.get(d),u=s.showSender.checkboxField.checked?"Chat.Accessory.Forward":"Chat.Accessory.Hidden";h.key=u,h.update()}},checked:0},{name:"caption",onChange:r=>{const l=!!+r;let c;l&&this.forwardWasDroppingAuthor!==void 0?c=this.forwardWasDroppingAuthor?s.hideSender:s.showSender:c=l?s.showSender:s.hideSender,c.checkboxField.checked=!0},checked:0}],listenerSetter:this.listenerSetter});Je||(this.forwardHover=new yc({element:a})),s.modifyArgs=n.slice(0,-2),this.replyElements.container.append(a)}constructWebPageElements(){this.webPageElements={};const e=[this.webPageElements.above={text:"AboveMessage",onClick:()=>{},radioGroup:"position"},this.webPageElements.below={text:"BelowMessage",onClick:()=>{},radioGroup:"position"},this.webPageElements.larger={text:"LargerMedia",onClick:()=>{},radioGroup:"size"},this.webPageElements.smaller={text:"SmallerMedia",onClick:()=>{},radioGroup:"size"},{text:"WebPage.RemovePreview",onClick:()=>{this.onHelperCancel()},icon:"delete",danger:!0}],t=this.webPageElements.container=jn({buttons:e,radioGroups:[{name:"position",onChange:s=>{this.invertMedia=!!+s,this.saveDraftDebounced?.()},checked:0},{name:"size",onChange:s=>{this.webPageOptions.largeMedia=!!+s,this.webPageOptions.smallMedia=!+s,this.saveDraftDebounced?.()},checked:0}],listenerSetter:this.listenerSetter});Je||(this.webPageHover=new yc({element:t})),this.replyElements.container.append(t)}constructMentionButton(e){const t=Ei({icon:e?"reactions":"mention",className:"bubbles-corner-button chat-secondary-button bubbles-go-mention bubbles-go-reaction"}),s=bl("span",24,"primary");t.append(s),this.inputContainer.append(t),N(t,i=>{oe(i);const n=this.getMiddleware();this.managers.appMessagesManager.goToNextMention({peerId:this.chat.peerId,threadId:this.chat.threadId,isReaction:e}).then(a=>{n()&&a&&this.chat.setMessageId({lastMsgId:a})})},{listenerSetter:this.listenerSetter}),ln({buttons:[{icon:"readchats",text:e?"ReadAllReactions":"ReadAllMentions",onClick:()=>{this.managers.appMessagesManager.readMentions(this.chat.peerId,this.chat.threadId,e)}}],listenTo:t,listenerSetter:this.listenerSetter}),e?(this.goReactionUnreadBadge=s,this.goReactionBtn=t):(this.goMentionUnreadBadge=s,this.goMentionBtn=t)}constructScheduledButton(){this.btnScheduled=this.createButtonIcon("scheduled btn-scheduled float hide",{noRipple:!0}),N(this.btnScheduled,e=>{this.appImManager.openScheduled(this.chat.peerId)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(I)("scheduled_new",({peerId:e})=>{this.chat.peerId===e&&this.btnScheduled.classList.remove("hide")}),this.listenerSetter.add(I)("scheduled_delete",({peerId:e})=>{this.chat.peerId===e&&this.managers.appMessagesManager.getScheduledMessages(this.chat.peerId).then(t=>{this.btnScheduled.classList.toggle("hide",!t.length)})})}constructReplyMarkup(){this.btnToggleReplyMarkup=this.createButtonIcon("botcom toggle-reply-markup float hide",{noRipple:!0}),this.replyKeyboard=new ig({appendTo:this.rowsWrapper,listenerSetter:this.listenerSetter,managers:this.managers,btnHover:this.btnToggleReplyMarkup,chatInput:this}),this.listenerSetter.add(this.replyKeyboard)("open",()=>this.btnToggleReplyMarkup.classList.add("active")),this.listenerSetter.add(this.replyKeyboard)("close",()=>this.btnToggleReplyMarkup.classList.remove("active"))}constructBotCommands(){this.botCommands=new Jx(this.rowsWrapper,this,this.managers),this.botCommandsToggle=document.createElement("div"),this.botCommandsToggle.classList.add("new-message-bot-commands"),this.botCommandsToggle.append(Le("webview","new-message-bot-commands-view-icon"));const e=document.createElement("div");e.classList.add("new-message-bot-commands-icon-scale");const t=this.botCommandsIcon=document.createElement("div");t.classList.add("animated-menu-icon","animated-menu-close-icon"),e.append(t),this.botCommandsView=document.createElement("div"),this.botCommandsView.classList.add("new-message-bot-commands-view"),this.botCommandsToggle.append(e,this.botCommandsView);let s=0,i=!1;N(this.botCommandsToggle,n=>{oe(n);const a=this.chat.peerId.toUserId(),{botMenuButton:r}=this;if(r){if(i)return;const d=++s;i=!0,Promise.resolve().then(()=>{if(s===d)return this.chat.openWebApp({botId:a,url:r.url,buttonText:r.text,fromBotMenu:!0})}).finally(()=>{s===d&&(i=!1)});return}const l=this.getMiddleware();t.classList.contains("state-back")?this.botCommands.toggle(!0):this.botCommands.setUserId(a,l)},{listenerSetter:this.listenerSetter}),this.botCommands.addEventListener("visible",()=>{t.classList.add("state-back")}),this.botCommands.addEventListener("hiding",()=>{t.classList.remove("state-back")})}constructRecorder(){const e=window.Recorder;if(e)try{this.recorder=new e({encoderSampleRate:48e3,monitorGain:0,numberOfChannels:1,recordingGain:1,reuseWorker:!0})}catch(t){console.error("Recorder constructor error:",t)}this.recorder&&(N(this.btnCancelRecord,this.onCancelRecordClick,{listenerSetter:this.listenerSetter}),this.recorder.onstop=()=>{this.setRecording(!1),this.chatInput.classList.remove("is-locked"),this.recordRippleEl.style.transform=""},this.recorder.ondataavailable=t=>{if(this.releaseMediaPlayback&&(this.releaseMediaPlayback(),this.releaseMediaPlayback=void 0),this.recordingOverlayListener&&(this.listenerSetter.remove(this.recordingOverlayListener),this.recordingOverlayListener=void 0),this.recordingNavigationItem&&(ft.removeItem(this.recordingNavigationItem),this.recordingNavigationItem=void 0),this.recordCanceled)return;const s=this.chat.getMessageSendingParams(),i=(Date.now()-this.recordStartTime)/1e3|0,n=new Blob([t],{type:"audio/ogg"});Xd.decode(t,!0).then(a=>{Xd.setKeepAlive(!1),this.managers.appMessagesManager.sendFile({...s,file:n,isVoiceMessage:!0,isMedia:!0,duration:i,waveform:a.waveform,objectURL:a.url,clearDraft:!0}),this.onMessageSent(!1,!0)})})}constructPeerHelpers(){this.excludeParts.reply||(this.constructReplyElements(),this.excludeParts.forwardOptions||(this.constructForwardElements(),this.constructWebPageElements())),this.newMessageWrapper=document.createElement("div"),this.newMessageWrapper.classList.add("new-message-wrapper","rows-wrapper-row"),this.excludeParts.emoticons||(this.btnToggleEmoticons=this.createButtonIcon("smile toggle-emoticons",{noRipple:!0})),this.inputMessageContainer=document.createElement("div"),this.inputMessageContainer.classList.add("input-message-container"),this.goDownBtn&&(this.goDownUnreadBadge=bl("span",24,"primary"),this.goDownBtn.append(this.goDownUnreadBadge)),this.excludeParts.mentionButton||(this.constructMentionButton(),this.constructMentionButton(!0)),this.excludeParts.scheduled||this.constructScheduledButton(),this.excludeParts.replyMarkup||this.constructReplyMarkup(),this.excludeParts.botCommands||this.constructBotCommands(),this.attachMenuButtons=[{icon:"image",text:"Chat.Input.Attach.PhotoOrVideo",onClick:()=>this.onAttachClick(!1,!0,!0)},{icon:"document",text:"Chat.Input.Attach.Document",onClick:()=>this.onAttachClick(!0)},{icon:"gift",text:"GiftPremium",onClick:()=>this.chat.appImManager.giftPremium(this.chat.peerId),verify:()=>this.chat&&Promise.all([this.chat.canGiftPremium(),this.managers.apiManager.getAppConfig()]).then(([i,{premium_gift_attach_menu_icon:n}])=>i&&n)},{icon:"poll",text:"Poll",onClick:async()=>{const i="send_polls";if(!await this.chat.canSend(i)){Ee({langPackKey:Or[i]});return}ee.createPopup(Ex,this.chat).show()},verify:()=>this.chat.peerId.isAnyChat()||this.chat.isBot}];const e=this.attachMenuButtons.slice();this.attachMenu=ai({buttonOptions:{noRipple:!0},listenerSetter:this.listenerSetter,direction:"top-left",buttons:this.attachMenuButtons,onOpenBefore:this.excludeParts.attachMenu?void 0:async()=>{const i=await this.managers.appAttachMenuBotsManager.getAttachMenuBots(),n=e.slice(),a=i.filter(r=>r.pFlags.show_in_attach_menu).map(r=>{const l=Df(r);return{regularText:_e(r.short_name),onClick:()=>{this.chat.openWebApp({attachMenuBot:r,fromAttachMenu:!0})},iconDoc:l?.icon,verify:async()=>{let d=!1;const h={attachMenuPeerTypeSameBotPM:()=>this.chat.peerId.toUserId()===r.bot_id,attachMenuPeerTypeBotPM:()=>this.chat.isBot,attachMenuPeerTypePM:()=>this.chat.peerId.isUser(),attachMenuPeerTypeChat:()=>this.chat.isAnyGroup,attachMenuPeerTypeBroadcast:()=>this.chat.isBroadcast};for(const u of r.peer_types){const p=h[u._];if(d=await p(),d)break}return d}}});n.splice(n.length,0,...a),this.attachMenuButtons.splice(0,this.attachMenuButtons.length,...n)},onOpen:()=>{this.emoticonsDropdown?.toggle(!1),this.onMenuToggle?.(!0)},onClose:()=>{this.onMenuToggle?.(!1)}}),this.attachMenu.classList.add("attach-file"),this.attachMenu.firstElementChild.replaceWith(Le("attach")),this.recordTimeEl=document.createElement("div"),this.recordTimeEl.classList.add("record-time"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=!0,this.fileInput.style.display="none",this.newMessageWrapper.append(...[this.botCommandsToggle,this.btnToggleEmoticons,this.inputMessageContainer,this.btnScheduled,this.btnToggleReplyMarkup,this.attachMenu,this.recordTimeEl,this.fileInput].filter(Boolean)),this.replyElements?.container&&this.rowsWrapper.append(this.replyElements.container),this.autocompleteHelperController=new qx,this.stickersHelper=new Kx(this.rowsWrapper,this.autocompleteHelperController,this.chat,this.managers),this.emojiHelper=new Wx(this.rowsWrapper,this.autocompleteHelperController,this,this.managers),this.excludeParts.commandsHelper||(this.commandsHelper=new jx(this.rowsWrapper,this.autocompleteHelperController,this,this.managers)),this.mentionsHelper=new Qx(this.rowsWrapper,this.autocompleteHelperController,this,this.managers),this.inlineHelper=new Xx(this.rowsWrapper,this.autocompleteHelperController,this.chat,this.managers),this.rowsWrapper.append(this.newMessageWrapper),this.btnCancelRecord=this.createButtonIcon("binfilled btn-circle btn-record-cancel chat-input-secondary-button chat-secondary-button"),this.btnSendContainer=document.createElement("div"),this.btnSendContainer.classList.add("btn-send-container"),this.recordRippleEl=document.createElement("div"),this.recordRippleEl.classList.add("record-ripple"),this.btnSend=this.createButtonIcon(),this.btnSend.classList.add("btn-circle","btn-send","animated-button-icon");const t=[["send","send"],["schedule","schedule"],["check","edit"],["microphone_filled","record"],["forward_filled","forward"]];this.btnSend.append(...t.map(([i,n])=>Le(i,"animated-button-icon-icon","btn-send-icon-"+n))),this.btnSendContainer.append(this.recordRippleEl,this.btnSend),Jt(i=>{this.chat.destroyMiddlewareHelper.onDestroy(i);const[n,a]=ne();this.effect=n,this.setEffect=a,this.btnSendContainer.append(FC({effect:this.effect}))}),this.sendMenu=new Rf({onSilentClick:()=>{this.sendSilent=!0,this.sendMessage()},onScheduleClick:()=>{this.scheduleSending(void 0)},onSendWhenOnlineClick:()=>{this.setScheduleTimestamp(xc,this.sendMessage.bind(this,!0))},middleware:this.chat.destroyMiddlewareHelper.get(),openSide:"top-left",onContextElement:this.btnSend,onOpen:()=>{const i=this.chat.type!==te.Scheduled&&(!this.isInputEmpty()||!!Object.keys(this.forwarding).length)&&!this.editMsgId;return i&&this.emoticonsDropdown?.toggle(!1),i},canSendWhenOnline:this.canSendWhenOnline,onRef:i=>{this.btnSendContainer.append(i)},withEffects:()=>this.chat.peerId.isUser()&&this.chat.peerId!==I.myId,effect:this.effect,onEffect:this.setEffect}),this.inputContainer.append(...[this.btnReaction,this.btnCancelRecord,this.btnSendContainer].filter(Boolean)),this.btnToggleEmoticons&&(this.emoticonsDropdown.attachButtonListener(this.btnToggleEmoticons,this.listenerSetter),this.listenerSetter.add(this.emoticonsDropdown)("open",this.onEmoticonsOpen),this.listenerSetter.add(this.emoticonsDropdown)("close",this.onEmoticonsClose),Ji===this.emoticonsDropdown&&Jt(i=>{this.chat.destroyMiddlewareHelper.onDestroy(i),ye(()=>{const n=lt.height>=570&&lt.width>600;this.emoticonsDropdown.getElement().classList.toggle("is-under",!n)})})),this.attachMessageInputField(),this.listenerSetter.add(I)("settings_updated",()=>{(this.stickersHelper||this.emojiHelper)&&(this.previousQuery="",this.checkAutocomplete()),this.messageInputField?.onFakeInput()}),this.chat&&this.setChatListeners(),this.constructRecorder(),this.updateSendBtn(),this.listenerSetter.add(this.fileInput)("change",i=>{const n=i.target.files,a=Array.from(n).slice();if(this.fileSelectionPromise.resolve(a),!a.length)return;const r=sg();r?r.addFiles(a):ee.createPopup(pr,this.chat,a,this.willAttachType),this.fileInput.value=""},!1),N(this.btnSend,this.onBtnSendClick,{listenerSetter:this.listenerSetter,touchMouseDown:!0}),this.saveDraftDebounced=ii(()=>this.saveDraft(),2500,!1,!0);const s=i=>{const n=ze("btn-primary btn-transparent text-bold chat-input-control-button");return n.append(i instanceof HTMLElement?i:M(i)),n};this.botStartBtn=s("BotStart"),this.unblockBtn=s("Unblock"),this.joinBtn=this.chat.topbar&&s("ChannelJoin"),this.onlyPremiumBtnText=new ke.IntlElement({key:"Chat.Input.PremiumRequiredButton",args:[0,document.createElement("a")]}),this.onlyPremiumBtn=s(this.onlyPremiumBtnText.element),N(this.botStartBtn,this.startBot,{listenerSetter:this.listenerSetter}),N(this.unblockBtn,this.unblockUser,{listenerSetter:this.listenerSetter}),N(this.onlyPremiumBtn,()=>{Vt.show()},{listenerSetter:this.listenerSetter}),this.joinBtn&&N(this.joinBtn,this.chat.topbar.onJoinClick.bind(this.chat.topbar,this.joinBtn),{listenerSetter:this.listenerSetter}),this.pinnedControlBtn=ze("btn-primary btn-transparent text-bold chat-input-control-button",{icon:"unpin"}),this.listenerSetter.add(this.pinnedControlBtn)("click",()=>{const i=this.chat.peerId;ee.createPopup(Zc,i,0,!0,()=>{this.chat.appImManager.setPeer();const n=this.chat.appImManager.chat;n.topbar.pinnedMessage&&n.topbar.pinnedMessage.pinnedMessageContainer.toggle(!0)})}),this.openChatBtn=s("OpenChat"),N(this.openChatBtn,()=>{this.chat.appImManager.setInnerPeer({peerId:this.chat.threadId})},{listenerSetter:this.listenerSetter}),this.controlContainer.append(...[this.botStartBtn,this.unblockBtn,this.joinBtn,this.onlyPremiumBtn,this.replyInTopicOverlay,this.pinnedControlBtn,this.openChatBtn].filter(Boolean))}setChatListeners(){this.listenerSetter.add(I)("draft_updated",({peerId:e,threadId:t,draft:s,force:i})=>{this.chat.threadId!==t||this.chat.peerId!==e||ko.has(this.chat.type)||this.setDraft(s,!0,i)}),this.listenerSetter.add(this.appImManager)("peer_changing",e=>{this.chat===e&&(this.chat.type===te.Chat||this.chat.type===te.Discussion)&&this.saveDraft()}),this.listenerSetter.add(this.appImManager)("chat_changing",({from:e,to:t})=>{this.chat===e?this.autocompleteHelperController.toggleListNavigation(!1):this.chat===t&&this.autocompleteHelperController.toggleListNavigation(!0)}),this.listenerSetter.add(I)("scheduled_delete",({peerId:e,mids:t})=>{this.chat.type===te.Scheduled&&this.chat.peerId===e&&t.includes(this.editMsgId)&&this.onMessageSent()}),this.listenerSetter.add(I)("history_delete",({peerId:e,msgs:t})=>{this.chat.peerId===e&&!ko.has(this.chat.type)&&(t.has(this.editMsgId)&&this.onMessageSent(),this.replyToMsgId&&t.has(this.replyToMsgId)&&this.clearHelper("reply"))}),this.listenerSetter.add(I)("dialogs_multiupdate",e=>{e.has(this.chat.peerId)&&(this.chat.type===te.Chat||this.chat.type===te.Discussion)&&(this.startParam===Tb?this.setStartParam():this.center(!0))})}_center(e,t){if(!e&&!this.inputContainer.classList.contains("is-centering")||e===this.fakeWrapperTo)return;const s=e||this.fakeWrapperTo,i=!!e,n=this.fakeWrapperTo;let a="",r="",l;const c=s.getBoundingClientRect(),d=this.fakeRowsWrapper.getBoundingClientRect(),h=d.width,u=c.width;if(h!==u){const m=u/h,g=(h-u)/2;l=c.left-d.left-g,i&&(a=`translateX(${l}px) scaleX(${m})`,m<1&&(r=""+(16+16*(1-m))+"px"))}this.fakeWrapperTo=e;const p=t?200:0;return bt({element:this.inputContainer,className:"is-centering",forwards:i,duration:p}),bt({element:this.rowsWrapperWrapper,className:"is-centering-to-control",forwards:!!(i&&e&&e.classList.contains("chat-input-control")),duration:p}),this.rowsWrapper.style.transform=a,this.rowsWrapper.style.borderRadius=r,{transform:a,borderRadius:r,needTranslateX:n&&(e&&e.classList.contains("chat-input-control")&&n===this.fakeSelectionWrapper||n.classList.contains("chat-input-control"))?l*-.5:l,widthFrom:h,widthTo:u}}async center(e=!1){return this._center(await this.getNeededFakeContainer(),e)}setStartParam(e){this.startParam!==e&&(this.startParam=e,this.center(!0))}isReplyInTopicOverlayNeeded(){return hA}getJoinButtonType(){const{peerId:e,threadId:t}=this.chat;if(e.isUser())return;const s=fe.getChat(e.toChatId());if(!(!s||!s.pFlags.left||s.pFlags.broadcast)){if(s.pFlags.join_request)return"request";if(s.pFlags.join_to_send||!t)return"join"}}async getNeededFakeContainer(e=this.startParam){if(this.chat.selection?.isSelecting)return this.fakeSelectionWrapper;if(this.chat.type===te.Pinned||this.chat.type===te.Saved&&this.chat.threadId!==this.chat.peerId||await this.chat.isStartButtonNeeded()||this.isReplyInTopicOverlayNeeded()||this.chat.peerId.isUser()&&(this.chat.isUserBlocked||this.chat.isPremiumRequired)||this.getJoinButtonType())return this.controlContainer}getReadyToSend(e){return this.chat.type===te.Scheduled?(this.scheduleSending(e),!0):(e(),!1)}setScheduleTimestamp(e,t){const s=this.getMiddleware(),i=(Date.now()/1e3|0)+10;e<=i&&(e=void 0),this.scheduleDate=e,t(),this.chat.type!==te.Scheduled&&this.chat.type!==te.Stories&&e&&setTimeout(()=>{if(!s())return;ee.getPopups(Cn).forEach(a=>a.hide()),this.appImManager.openScheduled(this.chat.peerId)},0)}getMiddleware(...e){return this.chat.bubbles.getMiddleware(...e)}async setUnreadCount(){if(!this.goDownUnreadBadge)return;const e=await this.managers.dialogsStorage.getAnyDialog(this.chat.peerId,this.chat.type===te.Discussion?void 0:this.chat.threadId);if(la(e))return;const t=e?.unread_count;Qo(this.goDownUnreadBadge,""+(t||""));const s=await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.chat.peerId,respectType:!0,threadId:this.chat.threadId});if(this.goDownUnreadBadge.classList.toggle("badge-gray",s),this.goMentionUnreadBadge&&this.chat.type===te.Chat){const i=!!(e?.unread_mentions_count&&e.unread_count);Qo(this.goMentionUnreadBadge,i?""+e.unread_mentions_count:""),this.goMentionBtn.classList.toggle("is-visible",i)}if(this.goReactionUnreadBadge&&this.chat.type===te.Chat){const i=!!e?.unread_reactions_count;Qo(this.goReactionUnreadBadge,i?""+e.unread_reactions_count:""),this.goReactionBtn.classList.toggle("is-visible",i)}}getCurrentInputAsDraft(e){const{value:t,entities:s}=fn(this.messageInputField.input,!0,!1);let i;if(t.length||e||this.replyToMsgId||this.willSendWebPage){const n=this.willSendWebPage,a=this.webPageOptions,r=!!n?.pFlags?.has_large_media,l=this.getReplyTo();i={_:"draftMessage",date:Ms(!0),message:t.trim(),entities:s.length?s:void 0,pFlags:{no_webpage:this.noWebPage,invert_media:this.invertMedia||void 0},reply_to:l?{_:"inputReplyToMessage",reply_to_msg_id:l.replyToMsgId,top_msg_id:this.chat.threadId,reply_to_peer_id:l.replyToPeerId,...l.replyToQuote&&{quote_text:l.replyToQuote.text,quote_entities:l.replyToQuote.entities,quote_offset:l.replyToQuote.offset}}:void 0,media:n?{_:"inputMediaWebPage",pFlags:{force_large_media:r&&a?.largeMedia||void 0,force_small_media:r&&a?.smallMedia||void 0,optional:!0},url:n.url}:void 0,effect:this.effect()}}return i}saveDraft(){if(!this.chat.peerId||this.editMsgId||ko.has(this.chat.type))return;const e=this.getCurrentInputAsDraft();this.managers.appDraftsManager.syncDraft(this.chat.peerId,this.chat.threadId,e)}mentionUser(e,t){Promise.resolve(this.managers.appPeersManager.getPeer(e)).then(s=>{let i="",n;const a=ui(s);a[0]?i="@"+a[0]:(e.isUser()?i=s.first_name||s.last_name:i=s.title,n={_:"messageEntityMentionName",length:i.length,offset:0,user_id:s.id}),i+=" ",this.insertAtCaret(i,n,t)})}destroy(){this.listenerSetter.removeAll(),this.setCurrentHover()}cleanup(e=!0){this.chat&&!this.chat.peerId&&(this.chatInput.classList.add("hide"),this.goDownBtn.classList.add("hide")),Nr(),this.lastTimeType=0,this.startParam=void 0,this.toggleControlButtonDisability&&(this.toggleControlButtonDisability(),this.toggleControlButtonDisability=void 0),this.messageInput&&(this.clearInput(),e&&this.clearHelper())}async setDraft(e,t=!0,s=!1){if(!s&&!Pm(this.messageInput)||ko.has(this.chat.type))return!1;if(!e&&(e=await this.managers.appDraftsManager.getDraft(this.chat.peerId,this.chat.threadId),!e))return s&&(this.chat.container.classList.contains("is-helper-active")&&this.t(),this.messageInputField.inputFake.textContent="",this.messageInputField.onFakeInput(!1),(this.chat.bubbles.messagesQueuePromise||Promise.resolve()).then(()=>{bs(()=>{this.onMessageSent()})})),!1;const i=AC(e,{wrappingForPeerId:this.chat.peerId}),n=this.getCurrentInputAsDraft(),a=e.reply_to,r=a?.reply_to_msg_id;return Nv(e,n)?!1:(t&&this.clearHelper(),this.noWebPage=e.pFlags.no_webpage,r&&this.initMessageReply({replyToMsgId:r,replyToPeerId:a.reply_to_peer_id&&at(a.reply_to_peer_id),replyToQuote:a.quote_text&&{text:a.quote_text,entities:a.quote_entities,offset:a.quote_offset}}),this.setInputValue(i,t,t,e),!0)}createSendAs(){if(this.sendAsPeerId=void 0,this.chat&&(this.chat.type===te.Chat||this.chat.type===te.Discussion)){let e=!0;this.sendAs=new eA(this.managers,(t,s)=>{let i=0;t.parentElement||(this.newMessageWrapper.prepend(t),i=2),this.updateOffset("as",!0,s,i)},t=>{if(this.sendAsPeerId=t,e){e=!1;return}this.getPlaceholderParams().then(s=>{this.updateMessageInputPlaceholder(s)})})}else this.sendAs=void 0;return this.sendAs}async finishPeerChange(e){const{peerId:t,startParam:s,middleware:i}=e,{forwardElements:n,btnScheduled:a,replyKeyboard:r,sendMenu:l,goDownBtn:c,chatInput:d,botCommandsToggle:h,attachMenu:u}=this,p=this.sendAs,m=this.createSendAs(),g=this.filterAttachMenuButtons(),[f,y,v,w,b,S,C,P,L,E,_]=await Promise.all([this.managers.appPeersManager.isBroadcast(t),this.managers.appPeersManager.canPinMessage(t),this.managers.appPeersManager.isBot(t),this.chat?.canSend("send_messages")||!0,this.chat?.canSend("send_plain")||!0,this.getNeededFakeContainer(s),to(this.managers.acknowledged.appProfileManager.getProfileByPeerId(t)),a?to(this.managers.acknowledged.appMessagesManager.getScheduledMessages(t)):void 0,m?(m.setPeerId(t),m.updateManual(!0)):void 0,Oe({peerId:t,onlyFirstName:!0}),this.chat.isPremiumRequiredToContact()]),k=this.messageInput?await this.getPlaceholderParams(b):void 0;return()=>{if(d.classList.remove("hide"),c&&(c.classList.toggle("is-broadcast",f),c.classList.remove("hide")),this.goDownUnreadBadge&&this.setUnreadCount(),this.chat?.type===te.Pinned&&d.classList.toggle("can-pin",y),n&&(this.forwardWasDroppingAuthor=!1,n.showCaption.checkboxField.setValueSilently(!0),n.showSender.checkboxField.setValueSilently(!0)),a&&P&&(a.classList.add("hide"),ei(P.result,A=>{!i()||!A||a.classList.toggle("hide",!A.length)})),this.newMessageWrapper&&this.updateOffset(null,!1,!0),h&&(this.hasBotCommands=void 0,this.botMenuButton=void 0,this.botCommands.toggle(!0,void 0,!0),this.updateBotCommandsToggle(!0),h.remove(),v)){const A=C.result;ei(A,T=>{i()&&this.updateBotCommands(T,!(A instanceof Promise))})}p?.destroy(),L?.(),r?.setPeer(t),l?.setPeerId(t);let x=!1;if(this.chat&&this.joinBtn){const A=this.getJoinButtonType(),T=!x&&!!A;x||(x=T),this.joinBtn.classList.toggle("hide",!T),this.joinBtn.replaceChildren(M(A==="request"?"ChannelJoinRequest":"ChannelJoin"))}if(this.chat&&this.pinnedControlBtn){const A=!x&&this.chat.type===te.Pinned;x||(x=A),this.pinnedControlBtn.classList.toggle("hide",!A),this.pinnedControlBtn.replaceChildren(M(y?"Chat.Input.UnpinAll":"Chat.Pinned.DontShow"))}if(this.chat&&this.openChatBtn){const A=!x&&this.chat.type===te.Saved;if(x||(x=A),A){const T=this.chat.threadId,B=fe.getPeer(T),R=B.pFlags.broadcast?"OpenChannel2":T.isUser()?B.pFlags.bot?"BotWebViewOpenBot":"OpenChat":"OpenGroup2",O=M(R);this.openChatBtn.querySelector(".i18n").replaceWith(O)}this.openChatBtn.classList.toggle("hide",!A)}if(this.chat&&this.onlyPremiumBtn){const A=!x&&!v&&t.isUser()&&_;x||(x=A),this.onlyPremiumBtnText.compareAndUpdate({args:[E,this.onlyPremiumBtnText.args[1]]}),this.onlyPremiumBtn.classList.toggle("hide",!A)}if(this.chat){const A=!x&&!v&&t.isUser();x||(x=A),this.unblockBtn.classList.toggle("hide",!A)}this.botStartBtn.classList.toggle("hide",x),this.messageInput&&(this.updateMessageInput(w||x,b,k,t.isUser()?e.text:void 0,t.isUser()?e.entities:void 0),this.messageInput.dataset.peerId=""+t,g&&u&&g.then(A=>{i()&&(u.toggleAttribute("disabled",!A.length),u.classList.toggle("btn-disabled",!A.length))})),this.messageInputField?.onFakeInput(void 0,!0),this.startParam=s,this._center(S,!1)}}updateOffset(e,t,s,i,n){const a=this.hasOffset,r={type:e,forwards:t};Di(a,r)&&!n||(this.hasOffset=r,e?this.newMessageWrapper.dataset.offset=e:delete this.newMessageWrapper.dataset.offset,!(a?.forwards===r.forwards&&!n)&&bt({element:this.newMessageWrapper,className:"has-offset",forwards:t,duration:s?0:300,useRafs:i}))}updateBotCommands(e,t){const s=e.bot_info,i=s?.menu_button;this.hasBotCommands=!!s?.commands?.length,this.botMenuButton=i?._==="botMenuButton"?i:void 0,dt(this.botCommandsView,this.botMenuButton?_e(this.botMenuButton.text):""),this.botCommandsIcon.classList.toggle("hide",!!this.botMenuButton),this.botCommandsView.classList.toggle("hide",!this.botMenuButton),this.botCommandsToggle.classList.toggle("is-view",!!this.botMenuButton),this.updateBotCommandsToggle(t)}updateBotCommandsToggle(e){const{botCommandsToggle:t,hasBotCommands:s,botMenuButton:i}=this,n=!!(s||i),a=this.isInputEmpty(),r=n&&(a||!!i);if(!n){if(!t.parentElement)return;t.remove()}const l=r,c=t.parentElement?0:2;if(i&&a){const d=fl(i.text,Hh)+22+20+6;this.newMessageWrapper.style.setProperty("--commands-size",`${Math.ceil(d)}px`)}else this.newMessageWrapper.style.removeProperty("--commands-size");t.parentElement||this.newMessageWrapper.prepend(t),this.updateOffset("commands",l,e,c,!0)}async getPlaceholderParams(e){e??(e=await this.chat.canSend("send_plain"));const{peerId:t,threadId:s,isForum:i,type:n}=this.chat;let a,r;if(!e)a="Channel.Persmission.MessageBlock";else if(s&&!i&&!t.isUser())a="Comment";else if(await this.managers.appPeersManager.isBroadcast(t))a="ChannelBroadcast";else if(this.sendAsPeerId!==void 0&&this.sendAsPeerId!==I.myId||await this.managers.appMessagesManager.isAnonymousSending(t))a="SendAnonymously";else if(n===te.Stories)a="Story.ReplyPlaceholder";else if(i&&n===te.Chat&&!s){const l=await this.managers.dialogsStorage.getForumTopic(t,Id);l?(a="TypeMessageIn",r=[_e(l.title)]):a="Message"}else a="Message";return{key:a,args:r}}updateMessageInputPlaceholder({key:e,args:t=[]}){const s=ke.weakMap.get(this.messageInputField.placeholder);if(!s)return;const i=s.key,n=s.args;return s.compareAndUpdate({key:e,args:t}),{oldKey:i,oldArgs:n}}filterAttachMenuButtons(){if(this.attachMenuButtons)return Zi(this.attachMenuButtons,e=>e.verify?e.verify():!0)}updateMessageInput(e,t,s,i,n){const{chatInput:a,messageInput:r}=this;a.classList.contains("is-hidden")!==!e&&(a.classList.add("no-transition"),a.classList.toggle("is-hidden",!e),a.offsetLeft,a.classList.remove("no-transition"));const d=e&&!t&&this.restoreInputLock;!d&&this.updateMessageInputPlaceholder(s),d?this.restoreInputLock=()=>{this.updateMessageInputPlaceholder(s),this.messageInput.contentEditable="false"}:!e||!t?(r.contentEditable="false",t||this.messageInputField.onFakeInput(void 0,!0)):(this.restoreInputLock=void 0,r.contentEditable="true",i&&this.managers.appDraftsManager.setDraft(this.chat.peerId,void 0,i,n),this.setDraft(void 0,!1),r.innerHTML||this.messageInputField.onFakeInput(void 0,!0)),this.updateSendBtn()}attachMessageInputField(){const e=this.messageInputField;this.messageInputField=new Yw({placeholder:"Message",name:"message",withLinebreaks:!0}),this.messageInputField.input.tabIndex=-1,this.messageInputField.input.classList.replace("input-field-input","input-message-input"),this.messageInputField.inputFake.classList.replace("input-field-input","input-message-input"),this.messageInput=this.messageInputField.input,this.attachMessageInputListeners(),this.messageInput,LL&&PL(this.messageInput),e?(e.input.replaceWith(this.messageInputField.input),e.placeholder.replaceWith(this.messageInputField.placeholder),e.inputFake.replaceWith(this.messageInputField.inputFake)):this.inputMessageContainer.append(this.messageInputField.input,this.messageInputField.placeholder,this.messageInputField.inputFake)}attachMessageInputListeners(){this.listenerSetter.add(this.messageInput)("keydown",e=>{const t=e.key;if(eL(e))oe(e),this.sendMessage();else if(e.ctrlKey||e.metaKey)lA(this.messageInput,e);else if((t==="PageUp"||t==="PageDown")&&!e.shiftKey)if(e.preventDefault(),t==="PageUp"){const s=document.createRange(),i=window.getSelection();s.setStart(this.messageInput.childNodes[0]||this.messageInput,0),s.collapse(!0),i.removeAllRanges(),i.addRange(s)}else Zs(this.messageInput)}),N(this.messageInput,e=>{if(!this.canSendPlain()){Ee({langPackKey:Or.send_plain});return}const t=(i,n)=>{const a=n.getBoundingClientRect(),r=i.clientX,l=i.clientY;return r>a.right-20&&r<a.right&&l>a.top&&l<a.top+20},s=U(e.target,"can-send-collapsed");if(s&&t(e,s)){s.dataset.collapsed?delete s.dataset.collapsed:s.dataset.collapsed="1",Ee({langPackKey:s.dataset.collapsed?"Input.Quote.Collapsed":"Input.Quote.Expanded"});return}},{listenerSetter:this.listenerSetter}),Je&&N(this.messageInput,e=>{if(this.emoticonsDropdown.isActive()){this.emoticonsDropdown.toggle(!1),Dn(),oe(e);return}this.chat.isStandalone||this.appImManager.selectTab(Ll.CHAT)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(this.messageInput)("input",this.onMessageInput),this.listenerSetter.add(this.messageInput)("keyup",()=>{this.checkAutocomplete()}),this.listenerSetter.add(this.messageInput)("focusin",()=>{this.isFocused=!0,(this.chat.type===te.Chat||this.chat.type===te.Discussion)&&this.chat.bubbles.scrollable.loadedAll.bottom&&this.managers.appMessagesManager.readAllHistory(this.chat.peerId,this.chat.threadId),this.onFocusChange?.(!0)}),this.listenerSetter.add(this.messageInput)("focusout",()=>{this.isFocused=!1,this.onFocusChange?.(!1)})}canSendPlain(){return this.messageInput.isContentEditable&&!this.chatInput.classList.contains("is-hidden")}processWebPage(e,t,s=this.processingDraftMessage||this.editMessage){const i=s?.media,n=s?.pFlags?.invert_media,a=i?._==="inputMediaWebPage"?i.url:i?.webpage?.url,r=(!i||a)&&t.filter(h=>h._==="messageEntityUrl"||h._==="messageEntityTextUrl");if(!r?.length){this.lastUrl&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null,this.helperType?this.helperFunc():this.clearHelper());return}let l=a;if(!l)for(const h of r){let u;if(h._==="messageEntityTextUrl")u=h.url;else if(u=e.slice(h.offset,h.offset+h.length),!(u.includes("http://")||u.includes("https://")))continue;l=u;break}if(this.lastUrl===l)return;if(!l){this.willSendWebPage&&this.onHelperCancel();return}this.lastUrl=l;const c=a,d=this.getWebPagePromise=Promise.all([this.managers.appWebPagesManager.getWebPage(l),this.chat.canSend("embed_links")]).then(([h,u])=>{if(this.getWebPagePromise===d&&(this.getWebPagePromise=void 0),this.lastUrl===l)if(h?._==="webPage"&&u){const p=this.setTopInfo({type:"webpage",callerFunc:()=>{},title:h.site_name||h.title||"Webpage",subtitle:h.description||h.url||""});if(this.setCurrentHover(this.webPageHover,p),delete this.noWebPage,this.willSendWebPage=h,this.webPageElements){const m=c&&n?this.webPageElements.above:this.webPageElements.below;m.checkboxField.checked=!0;const g=c&&i.pFlags.force_small_media?this.webPageElements.smaller:this.webPageElements.larger;g.checkboxField.checked=!0,g.element.parentElement.classList.toggle("hide",!h.pFlags.has_large_media)}this.webPageOptions={optional:!0,...c?{smallMedia:c&&i.pFlags.force_small_media||void 0,largeMedia:c&&i.pFlags.force_large_media||void 0}:{}}}else this.willSendWebPage&&this.onHelperCancel()})}insertAtCaret(e,t,s=!0){if(!this.canSendPlain()){Ee({langPackKey:Or.send_plain});return}Hg.getInstance().makeFocused(this.messageInput);const{value:i,caretPos:n,entities:a}=fn(this.messageInput),r=n>=0?n:i.length,l=i.substr(0,r);i.substr(r);const c=s?l.match(_c.AUTO_COMPLETE_REG_EXP):null,d=c?c.index+(c[0].length-c[2].length):l.length;if(l.slice(0,d),s&&n!==-1){const h=c?c[2]:i,u=document.getSelection();let p=0;for(;u.toString()!==h;){if(++p>=1e4)throw new Error("lolwhat");u.modify("extend","backward","character")}}h0(this.messageInput,e,t?[t]:void 0,this.chat.peerId)}async checkAutocomplete(e,t,s){const i=e!==void 0;if(!i){const l=fn(this.messageInputField.input,!0,!0);e=l.value,t=l.caretPos,s=l.entities}if(t===-1&&(t=e.length),s===void 0||!i){const[l,c]=Bv(e,s);s=Qr(c,Ko(l))}if(e=e.slice(0,t),this.previousQuery===e)return;this.previousQuery=e;const n=e.match(_c.AUTO_COMPLETE_REG_EXP);let a;if(n){const l=s[0];let c=n[2];const d=c[0];if(this.stickersHelper&&I.settings.stickers.suggest!=="none"&&await this.chat.canSend("send_stickers")&&["messageEntityEmoji","messageEntityCustomEmoji"].includes(l?._)&&l.length===e.length&&!l.offset)a=this.stickersHelper,this.stickersHelper.checkEmoticon(e);else if(d==="@"){const h=this.chat.threadId?yn(this.chat.threadId):void 0;this.mentionsHelper.checkQuery(c,this.chat.peerId.isUser()?Tt:this.chat.peerId,h,this.globalMentions)&&(a=this.mentionsHelper)}else!n[1]&&d==="/"?this.commandsHelper&&await this.commandsHelper.checkQuery(c,this.chat.peerId)&&(a=this.commandsHelper):I.settings.emoji.suggest&&(c=c.replace(/^\s*/,""),!e.match(/^\s*:(.+):\s*$/)&&!e.match(/:[;!@#$%^&*()-=|]/)&&c&&(a=this.emojiHelper,this.emojiHelper.checkQuery(c,d)))}let r;a||(r=await this.chat.canSend("send_inline")),a=this.checkInlineAutocomplete(e,r,a),this.autocompleteHelperController.hideOtherHelpers(a)}checkInlineAutocomplete(e,t,s){let i=!1;const n=a=>{this.btnPreloader&&(a&&!t&&(a=!1),bt({element:this.btnPreloader,className:"show",forwards:a,duration:400}))};if(!s){const a=e.match(/^@([a-zA-Z\\d_]{3,32})\s/);if(a){const r=a[1],l=e.slice(a[0].length);i=a[0].length===e.length,s=this.inlineHelper,this.btnPreloader?n(!0):(this.btnPreloader=this.createButtonIcon("none btn-preloader float show disable-hover",{noRipple:!0}),rn(this.btnPreloader,!0),this.inputMessageContainer.parentElement.insertBefore(this.btnPreloader,this.inputMessageContainer.nextSibling)),this.inlineHelper.checkQuery(this.chat.peerId,r,l,t).then(({user:c,renderPromise:d})=>{i&&c.bot_inline_placeholder&&(this.messageInput.dataset.inlinePlaceholder=c.bot_inline_placeholder),d.then(()=>{n(!1)})}).catch(c=>{n(!1)})}}return i||delete this.messageInput.dataset.inlinePlaceholder,s!==this.inlineHelper&&n(!1),s}setRecording(e){this.recording!==e&&(this.recording=e,this.setShrinking(this.recording,["is-recording"]),this.updateSendBtn(),this.onRecording?.(e))}setShrinking(e,t){e||(e=this.recording),bt({element:this.chatInput,className:"is-shrinking"+(t?" "+t.join(" "):""),forwards:e,duration:200})}setCanForwardStory(e){this.canForwardStory=e||!0,this.updateSendBtn()}async showSlowModeTooltipIfNeeded({container:e,element:t,sendingFew:s,textOverflow:i}={}){const{peerId:n}=this.chat;if(n.isUser())return!1;const a=n.toChatId();if(!fe.getChat(a).pFlags.slowmode_enabled)return!1;let l,c;if(i)l=M("SlowmodeSendErrorTooLong");else if(s)l=M("SlowmodeSendError");else if(await this.managers.appMessagesManager.hasOutgoingMessage(n))l=M("SlowmodeSendError");else{const h=await this.managers.appProfileManager.getChatFull(a),u=()=>Math.max(0,(h.slowmode_next_send_date||0)-Ms(!0));if(!u())return!1;const p=document.createElement("span");c=cA(()=>{const m=u();p.replaceChildren(Yb(m)),m||d()},!0),l=M("SlowModeHint",[p])}const{close:d}=ur({element:t||this.btnSendContainer,vertical:"top",container:e||this.btnSendContainer.parentElement,textElement:l,onClose:()=>{c?.(),this.emoticonsDropdown.setIgnoreMouseOut("tooltip",!1)},auto:!0});return this.emoticonsDropdown.setIgnoreMouseOut("tooltip",!0),!0}changeForwardRecipient(){if(this.helperWaitingForward||!this.helperFunc)return;this.helperWaitingForward=!0;const e=Wi(this.forwarding),t=this.helperFunc;this.clearHelper(),this.updateSendBtn();let s=!1;ee.createPopup(va,e,()=>{s=!0}).addEventListener("close",()=>{this.helperWaitingForward=!1,s||t()})}async changeReplyRecipient(){if(this.helperWaitingReply)return;this.helperWaitingReply=!0;const e=this.getReplyTo();e.replyToPeerId??(e.replyToPeerId=this.chat.peerId);const t=this.helperFunc;this.clearHelper(),this.updateSendBtn();try{await this.createReplyPicker(e)}catch{t()}this.helperWaitingReply=!1}async createReplyPicker(e){const t=await Es.createReplyPicker();this.appImManager.setInnerPeer({peerId:t}).then(()=>{this.appImManager.chat.input.initMessageReply(e)})}getReplyTo(){if(!this.replyToMsgId&&!this.replyToStoryId)return;const{replyToMsgId:e,replyToStoryId:t,replyToQuote:s,replyToPeerId:i}=this;return{replyToMsgId:e,replyToStoryId:t,replyToQuote:s,replyToPeerId:i}}async clearInput(e=!0,t=!0,s=""){if(document.activeElement===this.messageInput&&Ua){const n=document.createElement("input");document.body.append(n),uy(n),this.messageInputField.setValueSilently(s),uy(this.messageInput),n.remove()}else this.messageInputField.setValueSilently(s);Je||nA(this.messageInput),this.setEffect();let i=!1;e&&(i=await this.setDraft(void 0,!1)),!i&&t&&this.onMessageInput()}isInputEmpty(){return Pm(this.messageInput)}updateSendBtn(){let e;const t=this.isInputEmpty();this.chat.type===te.Stories&&t&&!this.freezedFocused&&this.canForwardStory?e="forward":this.editMsgId?e="edit":!this.recorder||this.recording||!t||this.forwarding?e=this.chat.type===te.Scheduled?"schedule":"send":e="record",["send","record","edit","schedule","forward"].forEach(s=>{this.btnSend.classList.toggle(s,e===s)}),this.btnScheduled&&this.btnScheduled.classList.toggle("show",t&&this.chat.type!==te.Scheduled),this.btnToggleReplyMarkup&&this.btnToggleReplyMarkup.classList.toggle("show",t&&this.chat.type!==te.Scheduled),this.onUpdateSendBtn?.(e)}getValueAndEntities(e){const{entities:t,value:s}=fn(e,!0,!1),i=Ko(s),n=Qr(t,i);return{value:s,totalEntities:n}}onMessageSent(e=!0,t){ko.has(this.chat.type)||this.managers.appMessagesManager.readAllHistory(this.chat.peerId,this.chat.threadId,!0),this.scheduleDate=void 0,this.sendSilent=void 0;const{totalEntities:s}=this.getValueAndEntities(this.messageInput);let i=0;s.filter(a=>{if(a._==="messageEntityEmoji"||a._==="messageEntityCustomEmoji"){const r=a.offset+a.length;return r<=i?!1:(i=r,!0)}return!1}).forEach(a=>{const r=a._==="messageEntityEmoji"?{emoji:Og(a.unicode)}:{docId:a.document_id,emoji:""};this.managers.appEmojiManager.pushRecentEmoji(r)}),e&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null,this.clearInput()),(t||e)&&this.clearHelper(),this.updateSendBtn(),this.onMessageSent2?.()}async sendMessage(e=!1){const{editMsgId:t,chat:s}=this;if(s.type===te.Scheduled&&!e&&!t){this.scheduleSending();return}const{peerId:i}=s,{noWebPage:n}=this,a=this.chat.getMessageSendingParams(),{value:r,entities:l}=fn(this.messageInputField.input,!0,!1),c=r.trim();if(s.type!==te.Scheduled&&!t){let d=0;if(this.forwarding)for(const m in this.forwarding)d+=this.forwarding[m].length;d+=+!!c;const u=(await this.managers.apiManager.getConfig()).message_length_max,p=r.length>u;if(p&&++d,await this.showSlowModeTooltipIfNeeded({sendingFew:d>1,textOverflow:p}))return}if(t){const d=this.editMessage;if(c||d.media)this.managers.appMessagesManager.editMessage(d,r,{entities:l,noWebPage:n,webPage:this.getWebPagePromise?void 0:this.willSendWebPage,webPageOptions:this.webPageOptions,invertMedia:this.willSendWebPage?this.invertMedia:void 0}),this.onMessageSent();else{ee.createPopup(Rl,i,[t],s.type);return}}else c&&(this.managers.appMessagesManager.sendText({...a,text:r,entities:l,noWebPage:n,webPage:this.getWebPagePromise?void 0:this.willSendWebPage,webPageOptions:this.webPageOptions,invertMedia:this.willSendWebPage?this.invertMedia:void 0,clearDraft:!0}),ko.has(this.chat.type)?this.onMessageSent(!0):this.onMessageSent(!1,!1));if(this.forwarding){const d=Wi(this.forwarding);for(const h in d)this.managers.appMessagesManager.forwardMessages({...a,fromPeerId:h.toPeerId(),mids:d[h],dropAuthor:this.forwardElements&&this.forwardElements.hideSender.checkboxField.checked,dropCaptions:this.isDroppingCaptions()}).catch(async u=>{u.type==="VOICE_MESSAGES_FORBIDDEN"&&Ee({langPackKey:"Chat.SendVoice.PrivacyError",langPackArguments:[await Oe({peerId:i})]})});r||this.onMessageSent()}}async sendMessageWithDocument({document:e,force:t=!1,clearDraft:s=!1,silent:i=!1,target:n,ignoreNoPremium:a}){e=await this.managers.appDocsManager.getDoc(e);const r=e.type==="sticker"?"send_stickers":e.type==="gif"?"send_gifs":"send_media";return this.chat.peerId.isAnyChat()&&!await this.chat.canSend(r)?(Ee({langPackKey:Or[r]}),!1):this.chat.type===te.Scheduled&&!t?(this.scheduleSending(()=>this.sendMessageWithDocument({document:e,force:!0,clearDraft:s,silent:i,target:n})),!1):e?e.sticker&&fo(e)&&!I.premium&&!a?(Vt.show({feature:"premium_stickers"}),!1):await this.showSlowModeTooltipIfNeeded({element:n})?!1:(this.managers.appMessagesManager.sendFile({...this.chat.getMessageSendingParams(),file:e,isMedia:!0,clearDraft:s,silent:i}),this.onMessageSent(s,!0),e.type==="sticker"&&this.managers.appStickersManager.saveRecentSticker(e.id),!0):!1}canToggleHideAuthor(){const{forwardElements:e}=this;if(!e)return!1;const t=e.hideCaption.checkboxField;return!t.checked||Bi(t.label,"FORM").classList.contains("hide")}isDroppingCaptions(){return!this.canToggleHideAuthor()}initMessageEditing(e){const t=this.chat.getMessage(e);let s=Au(t.message,{entities:t.totalEntities,wrappingForPeerId:this.chat.peerId});const i=async()=>{let n;if(!this.messageInput.isContentEditable){const r=await this.getPlaceholderParams(!0),{contentEditable:l}=this.messageInput;this.messageInput.contentEditable="true";const{oldKey:c,oldArgs:d}=this.updateMessageInputPlaceholder(r);n=()=>{this.messageInput.contentEditable=l,this.updateMessageInputPlaceholder({key:c,args:d})}}const a=await hr({message:t,usingMids:[t.mid]});this.setTopInfo({type:"edit",callerFunc:i,title:M("AccDescrEditing"),subtitle:a,input:s,message:t}),this.editMsgId=e,this.editMessage=t,s=void 0,this.restoreInputLock=n};i()}initMessagesForward(e){const t=async()=>{const s=Object.keys(e).map(S=>S.toPeerId()),i=new Set;let n=0,a=0;const r=s.map(async S=>{const C=e[S],P=C.map(async L=>{const E=await this.managers.appMessagesManager.getMessageByPeer(S,L);Rn(E.fwd_from)&&!E.fromId&&!E.fwdFromId?i.add("N"+Rn(E.fwd_from)):i.add("P"+E.fromId),E.media&&!["messageMediaWebPage"].includes(E.media._)&&E.message&&++a});await Promise.all(P),n+=C.length});await Promise.all(r);const l=i.size>2,c=[...i].map(S=>{const C=S[0];if(S=S.slice(1),C==="P"){const P=S.toPeerId();return P===I.myId?M("Chat.Accessory.Forward.You"):new Rt({peerId:P,dialog:!1,onlyFirstName:l}).element}else return l?S.split(" ")[0]:S}),{forwardElements:d}=this;Bi(d.showCaption.checkboxField.label,"FORM").classList.toggle("hide",!a);const u=d.hideCaption.checkboxField.checked;a&&u?d.hideSender.checkboxField.setValueSilently(!0):this.forwardWasDroppingAuthor!==void 0&&(this.forwardWasDroppingAuthor?d.hideSender:d.showSender).checkboxField.setValueSilently(!0);const p=d.showSender.checkboxField.checked?"Chat.Accessory.Forward":"Chat.Accessory.Hidden",m=M(p,[n]),g=document.createDocumentFragment();c.length<3?g.append(...pi(c,!1)):g.append(c[0],M("AndOther",[c.length-1]));let f,y;if(s.length===1){const S=s[0],C=e[S];if(f=await this.managers.appMessagesManager.getMessageByPeer(S,C[0]),y=!!f.grouped_id,y){const P=await this.managers.appMessagesManager.getMidsByMessage(f);(P.length!==n||P.find(L=>!C.includes(L)))&&(y=!1)}}const v=document.createDocumentFragment(),w=": ";if(y||n===1){const S=e[s[0]],C=await hr({message:f,usingMids:S});v.append(g,w,C)}else v.append(M("Chat.Accessory.Forward.From"),w,g);const b=this.setTopInfo({type:"forward",callerFunc:t,title:m,subtitle:v});d.modifyArgs.forEach((S,C)=>{const P=S.textElement,L=ke.weakMap.get(P);L.args=[C<2?s.length:a],L.update()}),this.setCurrentHover(this.forwardHover,b),this.forwarding=e};t()}async initMessageReply(e){if(Di(this.getReplyTo(),e))return;let{replyToMsgId:t,replyToQuote:s,replyToPeerId:i}=e;i??(i=this.chat.peerId);let n=await(i?this.managers.appMessagesManager.getMessageByPeer(i,t):this.chat.getMessage(t));const a=()=>{let r,l;if(!n)r=M("Loading"),this.managers.appMessagesManager.reloadMessages(i,t).then(d=>{Di(this.getReplyTo(),e)&&(n=d,n?a():this.clearHelper("reply"))});else{const d=n.fromId;r=new Rt({peerId:n.fromId,dialog:!1,fromName:d?void 0:Rn(n.fwd_from)}).element,r=M(s?"ReplyToQuote":"ReplyTo",[r])}const c=this.setTopInfo({type:"reply",callerFunc:a,title:r,subtitle:l,message:n,setColorPeerId:n?.fromId,quote:n?s:void 0});this.setReplyTo(e),this.replyElements.replyInAnother.element.classList.toggle("hide",!this.chat.bubbles.canForward(n)),this.replyElements.doNotReply.element.classList.toggle("hide",!!s),this.replyElements.doNotQuote.element.classList.toggle("hide",!s),this.setCurrentHover(this.replyHover,c)};a()}setCurrentHover(e,t){this.currentHover&&this.currentHover.toggle(!1),this.hoverListenerSetter.removeAll(),this.currentHover=e,e?.attachButtonListener(t,this.listenerSetter)}setReplyTo(e){const{replyToMsgId:t,replyToQuote:s,replyToPeerId:i,replyToStoryId:n}=e||{};this.replyToMsgId=t,this.replyToStoryId=n,this.replyToQuote=s,this.replyToPeerId=i,this.center(!0)}clearHelper(e){this.helperType==="edit"&&e!=="edit"&&this.clearInput(),e&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null),e!=="reply"&&(this.setReplyTo(void 0),this.forwarding=void 0),this.editMsgId=this.editMessage=void 0,this.helperType=this.helperFunc=void 0,this.setCurrentHover(),this.saveDraftDebounced(),this.restoreInputLock&&(this.restoreInputLock(),this.restoreInputLock=void 0),this.chat.container&&this.chat.container.classList.contains("is-helper-active")&&(ft.removeByType("input-helper"),this.chat.container.classList.remove("is-helper-active"),this.t())}t(){const e="is-toggling-helper";bt({element:this.chat.container,className:e,forwards:!0,duration:150,onTransitionEnd:()=>{this.chat.container.classList.remove(e)}})}setInputValue(e,t=!0,s=!0,i){e||(e=""),t?this.clearInput(!1,!1,e):this.messageInputField.setValueSilently(e),bs(()=>{s&&Zs(this.messageInput),this.processingDraftMessage=i,this.setEffect(i.effect),this.onMessageInput(),this.processingDraftMessage=void 0,this.messageInput.scrollTop=this.messageInput.scrollHeight})}setTopInfo({type:e,callerFunc:t,title:s,subtitle:i,setColorPeerId:n,input:a,message:r,quote:l}){if(this.willSendWebPage&&e==="reply")return;e!=="webpage"&&(this.clearHelper(e),this.helperType=e,this.helperFunc=t);const c=this.replyElements.container,d=c.lastElementChild.previousElementSibling,h=d.classList.contains("reply");this.replyElements.iconBtn.replaceWith(this.replyElements.iconBtn=this.createButtonIcon((e==="webpage"?"link":e)+" reply-icon",{noRipple:!0}));const{container:u}=Fd({title:s,subtitle:i,setColorPeerId:n,animationGroup:this.chat.animationGroup,message:r,textColor:"secondary-text-color",quote:l});return this.appImManager.setPeerColorToElement({peerId:n,element:c}),h?d.replaceWith(u):c.lastElementChild.before(u),this.chat.container.classList.contains("is-helper-active")||(this.chat.container.classList.add("is-helper-active"),this.t()),Oi||ft.pushItem({type:"input-helper",onPop:()=>{this.onHelperCancel()}}),a!==void 0&&this.setInputValue(a),setTimeout(()=>{this.updateSendBtn()},0),u}};_c.AUTO_COMPLETE_REG_EXP=/(\s|^)((?:(?:@|^\/)\S*)|(?::|^[^:@\/])(?!.*[:@\/]).*)$/;let bu=_c;function uA(o){let e;return o.pFlags.close_friends?e="close":o.pFlags.public?e="public":o.pFlags.selected_contacts?e="selected":o.pFlags.contacts?e="contacts":o.privacy&&(o.privacy.some(t=>t._==="privacyValueAllowContacts")?e="contacts":e="selected"),e}function VC(o,e){if(o.focus(),Zs(o),e){const t=new KeyboardEvent(e.type,e);o.dispatchEvent(t)}}var Kr=(o=>(o.Stories="stories",o.Pinned="pinnedStories",o.Archive="archiveStories",o))(Kr||{});function Ov(o,e,t,s,i){const n=e;return s===Kr.Pinned?Yr(o,n,a=>{const r=a.id,l=a.pinnedIndex;return l!==void 0?4294967295-l:r}):s===Kr.Archive?Yr(o,n,a=>a.id):Yr(o,n,a=>4294967295-a.id)}const GC=(o=new Map)=>({positions:o,onPosition:({peerId:t,position:s})=>{s?o.set(t,s):o.delete(t)}}),{positions:pA,onPosition:mA}=GC();I.addEventListener("stories_position",mA);const gA=o=>{for(const e in o){const t=o[e];o[e]=(...s)=>Et(()=>t(...s))}return o},fA=o=>{const e=(F,H,G=n.index,z=n.peers[G])=>{const q=F?1:-1,$=z.index+q,se=F?$>=z.stories.length:$<0,Y=F?G>=n.peers.length-1:G<=0;if(se)if(Y){if(H){const Q=n.peers[F?0:n.peers.length-1];return{peer:Q,index:Q.index}}}else{const Q=n.peers[G+q];return{peer:Q,index:Q.index}}else return{peer:z,index:$}},t={index:o.index||0,paused:!0,ended:!1,muted:!0,loop:!1,buffering:!1,hideInterface:!1,playAfterGesture:!1,ready:!!o.peers,hasViewer:!1,startTime:0,get elapsedTime(){return n.elapsedTimeOnPause||Date.now()-n.startTime},elapsedTimeOnPause:0,changeTimeout:0,storyDuration:0,width:0,height:0,pinned:o.pinned,archive:o.archive,peers:o.peers||[],get peer(){return n.peers[n.index]},freezedSorting:new Set,getNearestStory:e};let s,i;const[n,a]=Tg(t),r=o.peerId||o.peers&&o.peers[0].peerId,l=o.archive?"archive":"stories",{positions:c,onPosition:d}=GC(new Map(pA)),h=[],u=F=>{const H=F.maxReadId||0,G=F.stories.findIndex(z=>z.id>H);return Math.max(0,G)},p=(F,H,G)=>{let z;const q=[];for(let $=0;$<H&&(z=n.getNearestStory(F,G,z?.peer?n.peers.indexOf(z.peer):void 0),!!z);++$)q.push(z);return q},m=()=>{[...p(!0,3,!1),...p(!1,3,!1)].forEach(F=>{const H=F.peer.stories[F.index];H?._==="storyItemSkipped"&&I.managers.appStoriesManager.getStoryById(F.peer.peerId,H.id)})},g=()=>{const{peerId:F,pinned:H,archive:G}=o;if(F){if(H||G){const{peer:z}=n,q=z?z.stories[z.stories.length-1].id:0,$=30;let se;return H?se=I.managers.appStoriesManager.getPinnedStories(F,$,q):se=I.managers.appStoriesManager.getStoriesArchive(F,$,q),se.then(({count:Y,stories:Q,pinnedToTop:he})=>(q?(a("peers",0,"stories",le=>[...le,...Q]),a("peers",0,"count",Y)):(E([{index:0,peerId:F,stories:Q,count:Y}]),a({ready:!0})),i=Q.length<$))}return I.managers.appStoriesManager.getPeerStories(F).then(z=>(k([z]),i=!0))}return I.managers.appStoriesManager.getAllStories(s?!0:void 0,s,G).then(z=>(s=z.state,i=!z.pFlags.has_more,k(z.peer_stories),i||g(),i))},f={set:F=>{if(!F){a({ended:!0});return}const H=n.peers.indexOf(F.peer);F.index!==void 0&&a("peers",H,"index",F.index),f.stop(),n.peer!==F.peer&&a({index:H}),m()},pause:F=>{a({paused:!0,playAfterGesture:F&&!n.paused}),f.toggleInterface(F)},play:(F=n.storyDuration)=>{n.buffering||!n.hasViewer||(a({paused:!1,storyDuration:F}),f.toggleInterface(!1))},stop:()=>{f.pause(),a({startTime:0,elapsedTimeOnPause:0})},restart:()=>{a({buffering:!1}),f.stop(),f.play()},toggle:(F=n.paused)=>{F?f.play():f.pause()},previous:()=>f.goToNearestStory(!1),next:()=>f.goToNearestStory(!0),goToNearestStorySafe:F=>{if(F){f.next();return}const H=n.getNearestStory(F);!H||n.storyDuration!==KC&&n.elapsedTime/n.storyDuration>.5?f.restart():f.set(H)},goToNearestStory:F=>{const H=n.getNearestStory(F);f.set(H)},viewerReady:F=>{a({hasViewer:F,ended:!1})},resetIndexes:()=>{a("peers",{},F=>({index:u(F)}))},toggleMute:()=>{a({muted:!n.muted})},toggleInterface:F=>{a({hideInterface:F})},toggleSorting:(F,H)=>{H?n.freezedSorting.add(F):(n.freezedSorting.delete(F),n.freezedSorting.size?F==="viewer"&&bi(h,(G,z)=>{G.position&&G.position.type!==l&&(h.splice(z,1),X(G,!0))}):h.splice(0,1/0).forEach(G=>X(G,!0)))},load:g,setBuffering:F=>{a({buffering:F})},setLoop:F=>{a({loop:F})}};gA(f);const y=()=>{clearTimeout(n.changeTimeout),a({startTime:Date.now()-n.elapsedTimeOnPause,changeTimeout:window.setTimeout(()=>{n.loop?f.restart():f.next()},n.storyDuration-n.elapsedTimeOnPause)})};ye($s(K(()=>n.paused||n.buffering),F=>{F?(clearTimeout(n.changeTimeout),a({elapsedTimeOnPause:Date.now()-n.startTime})):y()},{defer:!0}));const v=WC(),w=()=>lt.height-48-8-8*2-8,b=(F=w())=>Math.min(lt.width,F*.5625),S=()=>{const F=w();return{width:b(F),height:F}};ye(()=>{a(S())});const P=(F,H=n.peers)=>H.findIndex(G=>G.peerId===F),L=F=>{const H={peerId:at(F.peer),stories:F.stories,maxReadId:F.max_read_id,count:F.stories.length};return H.index=u(H),H},E=F=>{const H=[];let G=n.index;const z=n.peers.slice(),q=new Map(z.map((Y,Q)=>[Y.peerId,Q])),$=n.peer?.peerId,se=q.get($)??-1;for(const Y of F){const Q=q.get(Y.peerId)??-1,he=z[Q],le=Kt(he?.index||u(Y),0,Y.stories.length-1);Y.index!==le&&H.push({peerId:Y.peerId,index:le}),Q!==-1&&(z[Q]=Y),Yr(z,Y,re=>c.get(re.peerId)?.index??0,Q)}if(se!==-1){const Y=P($,z);Y!==se&&(G=Y)}oa(()=>{a("peers",wh(z,{key:"peerId",merge:!0})),a({index:G});for(const{peerId:Y,index:Q}of H){const he=P(Y,z);a("peers",he,"index",Q)}})},_=F=>{if(r)return r===F;const H=c.get(F);return H?H.type===l:!1},k=F=>{const H=F.map(L);E(H),a({ready:!0})},x=(F,H=P(F))=>{if(H===-1)return;const G=n.index===H;oa(()=>{const z=n.peers.slice();z.splice(H,1);const q=n.index>H?n.index-1:n.index;a({peers:z,...z.length?{}:{ended:!0},...q<z.length?{index:q}:{ended:!0}}),G&&f.restart()})},A=({peerId:F,story:H,modifiedPinned:G,modifiedArchive:z,modifiedPinnedToTop:q})=>{const $=P(F);if($===-1)return;const se=n.peers[$],Y=se.stories.findIndex(Q=>Q.id===H.id);if(o.pinned&&G){H.pFlags.pinned?B({peerId:F,story:H,cacheType:Kr.Pinned,maxReadId:se.maxReadId}):R({peerId:F,id:H.id});return}if(o.pinned&&q){if(H.pinnedIndex===void 0&&H.id<se.stories[se.stories.length-1].id&&!i){R({peerId:F,id:H.id});return}Y===-1?B({peerId:F,story:H,cacheType:Kr.Pinned,maxReadId:se.maxReadId}):a("peers",$,"stories",wh((he=>(he=he.slice(),he.splice(Y,1),Ov(he,H,!1,Kr.Pinned),he))(se.stories),{key:"id",merge:!0}));return}if(Y===-1){o.archive&&r&&z&&B({peerId:F,story:H,cacheType:Kr.Archive,maxReadId:se.maxReadId});return}a("peers",$,"stories",Y,wh(H))},T=F=>{const H=at(F.peer);_(H)&&k([F])},B=({peerId:F,story:H,cacheType:G,maxReadId:z})=>{if(!_(F)||o.pinned&&!H.pFlags?.pinned)return;const q=P(F);if(q===-1){const Q={peerId:F,stories:[H],maxReadId:z,count:1};Q.index=u(Q),E([Q]);return}const Y=n.peers[q].stories.findIndex(Q=>Q.id===H.id);if(Y!==-1){a("peers",q,"stories",Y,H);return}oa(()=>{const Q=n.peer.index;let he;a("peers",q,"stories",le=>(le=le.slice(),he=Ov(le,H,!1,G),le)),a("peers",q,"count",le=>le+1),he<=Q&&a("peers",q,"index",le=>le+1)})},R=({peerId:F,id:H})=>{const G=P(F);if(G===-1)return;const z=n.peers[G],q=z.stories,$=q.findIndex(se=>se.id===H);if($!==-1){if(q.length===1){x(F,G);return}oa(()=>{n.peer===z&&z.index===$&&f.next(),a("peers",G,"stories",se=>(se=se.slice(),se.splice($,1),se)),a("peers",G,"count",se=>se-1),z.index>=$&&a("peers",G,"index",z.index-1)})}},O=({peerId:F,maxReadId:H})=>{const G=P(F);G!==-1&&a("peers",G,"maxReadId",H)},X=(F,H)=>{const{peerId:G,position:z}=F;if(n.freezedSorting.size&&!H){const $=c.get(G);if($?.type===z?.type||n.hasViewer&&$&&z){ga(h,se=>se.peerId===G),h.push(F);return}}if(d(F),!_(G)){x(G);return}const q=n.peers.find($=>$.peerId===G);q&&E([q])};return v.add(I)("story_update",A),v.add(I)("story_deleted",R),!o.archive&&!o.pinned&&v.add(I)("story_expired",R),o.singleStory||v.add(I)("story_new",B),r||(v.add(I)("stories_stories",T),v.add(I)("stories_read",O),v.add(I)("stories_position",X)),o.onLoadCallback?o.onLoadCallback(f.load):n.ready?n.peer.index===void 0&&f.resetIndexes():f.load(),[n,f]},zC=ML(),Nf=o=>(Xn(o,["peers","index","peerId","pinned","archive"]),j(zC.Provider,{get value(){return fA(o)},get children(){return o.children}})),Io=()=>EL(zC);function yA(o){return!!o&&o.tagName==="INPUT"&&!["checkbox","radio"].includes(o.type)||o.isContentEditable}function Uv(o){const e=o.fwd_from;let t;if(!(!e&&(t=(o.media_areas||[]).find(s=>s._==="mediaAreaChannelPost"),!t)))return{fwdFrom:e,mediaAreaChannelPost:t}}const Gn=ce("<div>"),vA=ce("<a>"),bA=ce("<div><div></div><div>"),Zl=ce("<span>"),wA=ce("<div><div><div dir=auto>"),Hv=ce("<div><span>"),SA=ce("<div><div><div></div><div><div></div><div></div><div><div><div><div></div><div></div></div></div><div>"),CA=ce("<div><div>"),KC=5e3,rg=32,pc=.33,og=2,IA=2,LA="storyrepost";let Fr=Cd;I.addEventListener("app_config",o=>{const e=o.stories_changelog_user_id;Fr=e?e.toPeerId(!1):Cd});const $v=new $u(void 0,!0);function WC(){const o=new Ut;return ut(()=>o.removeAll()),o}const PA=o=>{let e,t;if(o.splitByDays){const i=a=>{const r=a.date,l=new Date(r*1e3);return l.setHours(0,0,0),l.getTime()},n=K(()=>{const a=o.state.stories,r={};return a.forEach(l=>{const c=i(l);(r[c]??(r[c]=[])).push(l)}),r});t=K(()=>{const a=n(),r=o.currentStory(),l=i(r);return a[l]}),e=K(()=>{const a=o.currentStory();return t().indexOf(a)})}else t=()=>o.state.stories,e=()=>o.state.index;return j(ti,{get each(){return t()},children:(i,n)=>j(MA,Ai(()=>Ai(o,{slideIndex:n,storyIndex:e})))})},MA=o=>{const[e,t]=ne(0),[s]=Io(),i=()=>{const d=(Date.now()-s.startTime)/s.storyDuration;t(d)},n=()=>s.peer!==o.state||o.storyIndex()!==o.slideIndex()||s.paused?(a(),!1):(i(),!0),a=()=>{Mg(l)},r=()=>{Ba(n,l)};ye(()=>{if(s.peer!==o.state){a();return}ye($s(()=>[o.storyIndex(),o.slideIndex()],([c,d])=>{c===d?(t(void 0),ye(()=>{s.paused||s.buffering?a():r()})):(a(),t(c>d?1:void 0))}))});const l=(()=>{const c=Gn();return Ve(d=>{const h=Me.ViewerStorySlidesSlide,u=e()!==void 0?{"--progress":Math.min(100,e()*100)+"%"}:{};return h!==d._v$&&Ce(c,d._v$=h),d._v$2=zi(c,u,d._v$2),d},{_v$:void 0,_v$2:void 0}),c})();return l},Of="❤",EA=o=>o?.emoticon===Of,_A=o=>{const[e,t]=Io(),[s,i]=o.focusedSignal,[n,a]=o.inputEmptySignal,[r,l]=o.inputMenuOpenSignal,[c,d]=ne(!1),h=Ys(),u=h.get(),p=new SC(me,I.managers,!1,{elements:!0,sharedMedia:!0});p.setType(te.Stories),p.isStandalone=!0;const m=async()=>{const E=!o.currentStory().sent_reaction?{_:"reactionEmoji",emoticon:Of}:void 0;o.sendReaction({reaction:E,target:g})};let g;j(kn,{ref(P){const L=g;typeof L=="function"?L(P):g=P},onClick:m,tabIndex:-1,class:"btn-circle btn-reaction chat-input-secondary-button chat-secondary-button",noRipple:!0,get children(){return o.reaction()}});const f=p.input=new bu(p,me,I.managers,"stories-input");f.noRipple=!0,f.btnReaction=g,f.excludeParts={replyMarkup:!0,scheduled:!0,downButton:!0,reply:!0,forwardOptions:!0,mentionButton:!0,attachMenu:!0,commandsHelper:!0,botCommands:!0,emoticons:Oi},f.globalMentions=!0,f.getMiddleware=(...P)=>u.create().get(...P);const y=P=>{const L=P.target;!U(L,Me.ViewerStoryReactions)&&(U(L,Me.ViewerStory)||L.classList.contains(Me.Viewer))&&(oe(P),i(!1))};ut(()=>{v&&(ft.removeItem(v),v=void 0)});let v;ye($s(()=>s(),P=>{P?(w=Et(()=>!e.paused),document.addEventListener("click",y,{capture:!0}),ft.pushItem(v={type:"stories-focus",onPop:()=>{i(!1)}})):(document.removeEventListener("click",y,{capture:!0}),ft.removeItem(v),v=void 0),t.toggle(P?!1:w),f.freezeFocused(P),f.chatInput.classList.toggle("is-focused",P)},{defer:!0}));let w=!1;f.onFocusChange=P=>{f.emoticonsDropdown.isActive()||P&&i(P)};let b=!1;const S=P=>{P&&(b=!e.paused),t.toggle(P?!1:b),l(P)};f.onMenuToggle=S,f.construct(),f.constructPeerHelpers(),f.messageInput.dataset.textColor="white",ye(()=>{if(o.isActive()){const P=()=>(S(!0),void 0),L=()=>(S(!1),void 0);Ji.addEventListener("open",P),Ji.addEventListener("close",L),Ji.chatInput=f,ut(()=>{Ji.removeEventListener("open",P),Ji.removeEventListener("close",L)})}}),ye(()=>{f.chatInput.classList.toggle("is-private",!o.isPublic()),f.setCanForwardStory(o.isPublic())}),ye(()=>{const[P,L,E]=[s(),c(),o.isPublic()],A=Math.min(2,[!P,P?!0:E,L].reduce((F,H)=>F+ +H,0)),T=48,B=8,R=o.isFull()?8:0,O=o.isFull()?0:135,X=e.width-(T+B)*A+(P?O:0)-R*2;f.rowsWrapper.style.setProperty("width",X+"px","important"),f.chatInput.classList.toggle("is-focused",P)});const C=Tu();return p.peerId=o.state.peerId,p.onChangePeer({peerId:p.peerId,type:te.Stories},so(u)).then(()=>{if(u())return p.finishPeerChange({peerId:p.peerId,middleware:u})}).then(()=>{u()&&(o.setInputReady(!0),Rc(C,()=>{ye(()=>{f.setReplyTo({replyToStoryId:o.currentStory().id})})}))}),ut(()=>{f.onFocusChange=f.onFileSelection=f.onMenuToggle=f.onRecording=f.onUpdateSendBtn=f.onMessageSent2=f.forwardStoryCallback=void 0,h.destroy(),p.destroy()}),f.onFileSelection=P=>{S(!0),P.finally(()=>{S(!1)})},f.onUpdateSendBtn=P=>{a(P==="record"||P==="forward")},f.onMessageSent2=()=>{Dn(),i(!1),o.onMessageSent()},f.forwardStoryCallback=P=>{o.onShareButtonClick(P,f.btnSendContainer)},f.onRecording=P=>{d(P)},f.chatInput},Vv=" • ",jC=async o=>{let e;const{reaction:t,div:s,size:i,textColor:n,play:a,uReaction:r}=o,l=t._==="reactionCustomEmoji",c=Ys().get();r(null);let d;if(l){const u=await I.managers.acknowledged.appEmojiManager.getCustomEmojiDocument(t.document_id);if(!c())return;u.cached||r(),e=await u.result,d=fe.getReaction(e.stickerEmojiRaw)}else{const u=fe.getAvailableReactions();u instanceof Promise&&r();const p=await u;if(!c())return;d=p.find(m=>en(t,m)),e=a?d.select_animation:d.static_icon}d&&ei(d,u=>{u?.around_animation&&cs.downloadMedia({media:u.around_animation})});const h=[];await Rs({div:s,doc:e,width:i,height:i,play:a,textColor:n,middleware:c,loadPromises:h,loop:a||void 0}),await Promise.all(h),c()&&r(s)},kA=o=>{const[e,t]=Io(),{x:s,y:i,w:n,h:a,rotation:r}=o.mediaArea.coordinates,l=K(L=>L||o.isActive()&&e.startTime),[c,d]=ne(),h=K(()=>o.mediaArea._==="mediaAreaGeoPoint"||o.mediaArea._==="mediaAreaVenue"),u=K(()=>o.mediaArea._==="mediaAreaSuggestedReaction"),p=K(()=>o.mediaArea._==="mediaAreaChannelPost"),m=K(()=>o.mediaArea._==="mediaAreaUrl"),g=async()=>{const L=o.mediaArea.geo,E=Lf(L),_=async R=>{if(x){x=!1;return}A=!0,oe(R);try{await Ct({descriptionLangKey:"Popup.OpenInGoogleMaps",button:{langKey:"Open"}})}catch{T&&t.play();return}x=!0,k.click()};let k,x=!1,A;(()=>{const R=vA();R.$$click=_;const O=k;return typeof O=="function"?wt(O,R):k=R,Ti(R,"href",E),D(R,()=>M("StoryViewLocation")),R})(),Jr(k);const T=!e.paused;t.pause();const{close:B}=ur({element:P,vertical:"top",textElement:k,centerVertically:!!r,onClose:()=>{if(A){A=!1;return}T&&t.play()}});o.setTooltipCloseCallback(()=>B)},f=()=>{const L=o.mediaArea,E=e.width*n/100;o.sendReaction({reaction:L.reaction,target:P,sizes:{genericEffect:E*.375,genericEffectSize:E*1.5,size:E,effectSize:E*2.6875},textColor:L.pFlags.dark?"white":void 0,fireSame:!0})},y=L=>{const E=ni(()=>{k(),L.callback()});E.append(L.text);const _=!e.paused;t.pause();const{close:k}=ur({element:P,vertical:"top",textElement:E,centerVertically:!1,onClose:()=>{_&&t.play()}});o.setTooltipCloseCallback(()=>k)},v=()=>{y({callback:()=>{o.close(()=>{const E=o.mediaArea;me.setInnerPeer({peerId:E.channel_id.toPeerId(!0),lastMsgId:E.msg_id})})},text:M("Story.ViewPost")})},w=()=>{y({callback:()=>{const L=o.mediaArea.url;cl(L).onclick?o.close(()=>{me.openUrl(L)}):ro(L)},text:M("OpenUrlTitle")})},b=L=>{o.isActive()&&(oe(L),C(L))},S=L=>{const E=L.reaction,[_,k]=ne(0),x=Ja(),A=e.width*n/100*.72;let T;(()=>{const B=Gn(),R=T;return typeof R=="function"?wt(R,B):T=B,Ve(()=>Ce(B,ot(Me.ViewerStoryMediaAreaReactionInner,_()&&Me.hasCount))),B})(),jC({reaction:E,uReaction:x,div:T,size:A,textColor:L.pFlags.dark?"white":void 0,play:!0}),Ve(()=>{const O=o.story.views?.reactions?.find(X=>en(X.reaction,E));k(O?.count??0)}),ye(()=>{const B=x();B!==null&&(d([(()=>{const R=bA(),O=R.firstChild,X=O.nextSibling;return Ve(F=>{const H=ot(Me.ViewerStoryMediaAreaReactionBubbles,L.pFlags.dark&&Me.dark,_()&&Me.hasCount),G=Me.ViewerStoryMediaAreaReactionBubble,z=ot(Me.ViewerStoryMediaAreaReactionBubble,Me.small);return H!==F._v$3&&Ce(R,F._v$3=H),G!==F._v$4&&Ce(O,F._v$4=G),z!==F._v$5&&Ce(X,F._v$5=z),F},{_v$3:void 0,_v$4:void 0,_v$5:void 0}),R})(),B,(()=>{const R=Gn();return`calc(var(--stories-width) * ${n/100*.72*.275})`!=null?R.style.setProperty("font-size",`calc(var(--stories-width) * ${n/100*.72*.275})`):R.style.removeProperty("font-size"),D(R,(()=>{const O=K(()=>!!_());return()=>O()?on(_(),1):""})()),Ve(()=>Ce(R,ot(Me.ViewerStoryMediaAreaReactionCount,L.pFlags.dark&&Me.dark,_()&&Me.hasCount))),R})()]),o.setReady(!0))})};let C;u()?(C=f,S(o.mediaArea)):h()?(C=g,o.setReady(!0)):p()?(C=v,o.setReady(!0)):(m()&&(C=w),o.setReady(!0));let P;return(()=>{const L=Gn();L.$$click=b;const E=P;return typeof E=="function"?wt(E,L):P=L,D(L,c),Ve(_=>{const k=ot(Me.ViewerStoryMediaArea,...h()?[l()&&"shimmer","shimmer-bright","shimmer-once"]:[],...u()?[Me.ViewerStoryMediaAreaReaction]:[]),x=`left: ${s}%; top: ${i}%; width: ${n}%; height: ${a}%; --rotate: ${r}deg`;return k!==_._v$6&&Ce(L,_._v$6=k),_._v$7=zi(L,x,_._v$7),_},{_v$6:void 0,_v$7:void 0}),L})()},TA=o=>{const e=Fn({size:rg,peerId:o.state.peerId,isDialog:!1});e.node.classList.add(Me.ViewerStoryHeaderAvatar);const t=I.myId===o.state.peerId,s=!t&&new Rt;let i;s?(s.update({peerId:o.state.peerId,dialog:!1}),i=s.element):i=M("YourStory"),i.classList.add(Me.ViewerStoryHeaderName);const n=(W=!h.paused)=>()=>a(W),a=W=>{W&&u.play()},r=(W=!h.paused)=>{u.pause(),Es.createSharingPicker({onSelect:async qe=>{const et=o.state.peerId,yt=await I.managers.appPeersManager.getInputPeerById(et);I.managers.appMessagesManager.sendOther({peerId:qe,inputMedia:{_:"inputMediaStory",id:Fe().id,peer:yt}}),iy(M(qe===I.myId?"StorySharedToSavedMessages":"StorySharedTo",[await Oe({peerId:qe})]))},chatRightsActions:["send_media"]}).addEventListener("closeAfterTimeout",n(W))},l=(W,ue)=>{if(Fe().pFlags.noforwards){const{open:et}=ln({buttons:[{icon:"link",text:"CopyLink",onClick:Ht}],listenTo:ue,...li});et(W)}else r()},c=Fn({size:162,peerId:o.state.peerId,isDialog:!1,withStories:!0,storyColors:{read:"rgba(255, 255, 255, .3)"}});c.node.classList.add(Me.ViewerStoryInfoAvatar);let d;if(t)d=M("MyStory");else{const W=new Rt;W.update({peerId:o.state.peerId,dialog:!1,onlyFirstName:!0}),d=W.element}d.classList.add(Me.ViewerStoryInfoName);const[h,u]=Io(),[p,m]=ne(),[g,f]=ne(),[y,v]=ne(),[w,b]=ne(),[S,C]=ne(),[P,L]=ne(0),[E,_]=ne(!1),[k,x]=ne(),[A,T]=ne(!1),[B,R]=ne(),O=ne(!1),X=ne(),F=ne(!0),H=ne(!1),G=ne(!1),[z,q]=O,[$,se]=X,[Y]=F,[Q]=H,[he,le]=G,[re,ge]=ne(!1),[be,Z]=o.transitionSignal,[de,Ze]=ne(),[Ne,pe]=ne(),[Be,He]=ne(),[De,Ae]=ne(),[Ke,We]=ne(),Fe=K(()=>o.state.stories[o.state.index]),Ue=K(()=>{const ue=Fe().expire_date;return ue?ue<=Ms(!0):!1}),nt=K(()=>h.peer===o.state),[Lt,At]=ne(!1,{equals:!1});let rs;ye(()=>{Fe(),rs=Ys().get()});const Cs=(W,ue=Et(()=>$()))=>{if(!ue||ue.target===$l)return;const qe=ue.sizes??{genericEffect:26,genericEffectSize:100,size:40,effectSize:80};wr.fireAroundAnimation({middleware:ue.fireSame?rs:Ys().get(),reaction:W,sizes:qe,stickerContainer:ue.target,cache:ue.fireSame?{}:ue.target,textColor:ue.textColor})};ye(()=>{const W=Fe().sent_reaction;W&&(W?.document_id,Lt(),Cs(W))});const os=async W=>{let{reaction:ue}=W;const qe=o.state.peerId,et=Fe(),yt=et.id,mt=et.sent_reaction;if(ue instanceof Promise&&(ue=await ue,!ue))return;const Gt=!en(mt,ue);!Gt&&!W.fireSame&&(ue=void 0),q(!1),se(W),!Gt&&W.fireSame&&At(!0),await I.managers.acknowledged.appStoriesManager.sendReaction(qe,yt,Vr(ue)),se()},js=()=>{const[W,ue]=ne(!1),qe=Ys().get(),et=new Ff({managers:I.managers,type:"horizontal",middleware:qe,onFinish:mt=>os({reaction:mt,target:$l}),size:36,openSide:"top",getOpenPosition:()=>{},noMoreButton:!0});et.widthContainer.classList.add(Me.ViewerStoryReactions),et.init().finally(()=>{ue(!0)});let yt;ye(()=>{if(!W())return;const mt=mi();et.widthContainer.classList.toggle("is-visible",mt),mt?clearTimeout(yt):yt=window.setTimeout(()=>{We(),et.cleanup()},st.isAvailable("animations")?200:0)}),We(et)},mi=()=>z()&&Y()&&!Q(),oi=K(()=>Ke()?!0:mi());ye(()=>{oi()&&js()});const si=W=>{let ue=!1;ut(()=>{ue=!0,W.pause(),W.removeEventListener("waiting",et),W.removeEventListener("canplay",qe)});const qe=()=>{T(!1),nt()&&u.setBuffering(!1)},et=()=>{const ks=W.networkState===W.NETWORK_LOADING,Os=W.readyState<W.HAVE_FUTURE_DATA;ks&&Os&&(T(!0),nt()&&u.setBuffering(!0),W.addEventListener("canplay",qe,{once:!0}))},yt=()=>{W.currentTime&&yi(W,0)};W.addEventListener("waiting",et),ut(()=>{h.buffering&&u.setBuffering(!1)}),ye(()=>{h.paused||!nt()?W.pause():W.play()});const mt=()=>{ye($s(()=>[nt()],([ks])=>{ks||yt()})),ye(()=>{W.muted=h.muted})};nt()?mt():Ao(mt)(()=>nt());const Gt=Et(()=>Fe());ye(()=>{nt()&&!h.startTime&&Fe()===Gt&&yt()}),Et(re)||fe.getState().then(ks=>{!ue&&!ks.seenTooltips.storySound&&(Rc(zt,()=>{const Os=K(is=>is||nt()&&h.startTime);ye(()=>{if(Os()){const{close:is}=ur({...cy,textElement:M("Story.SoundTooltip")});Ae(()=>is)}})}),I.managers.appStateManager.setByKey(Gs("seenTooltips","storySound"),!0))});const zt=Tu()},cn=W=>{let ue=uA(W);ue==="public"&&(ue=void 0);const et=Vr(W.media)?.document,yt=et&&et.attributes.find(ys=>ys._==="documentAttributeVideo"),mt=yt?!!yt.pFlags.nosound:!1,Gt=yt?.duration,zt=W.date,ks=W.pFlags.edited,Os=!!W.pFlags.public,is=fe.getPeer(o.state.peerId),ns=ui(is);Ze(ue),x({timestamp:zt,edited:ks}),ge(mt),f(Gt&&Gt*1e3),le(Os),R(Os&&(!W.pFlags.noforwards||!!ns[0]))},gi=async W=>{if(T(!0),W._!=="storyItem"){He(),m(),v(),C(),pe(),b(),cn(W),I.managers.appStoriesManager.getStoryById(o.state.peerId,W.id),o.onReady?.();return}const ue=Ys().get(),qe=t?Ja():void 0,et=Ja(),yt=Ja(),mt=Ja(),Gt=Ja(),zt=Ja(),ks=t?K(is=>{const ys=W.views?.recent_viewers;return is?.join()===ys?.join()?is:ys}):void 0,Os=(is,ns,ys)=>({entities:ns,middleware:ue,textColor:"white",loadPromises:ys,passMaskedLinks:Fr===is});t&&ye(async()=>{let is;const ns=ks();if(ns?.length){is=new Co({avatarSize:30,middleware:ue});const ys=ns.map(fi=>fi.toPeerId(!1));if(qe(null),await is.render(ys),!ue())return}qe(is)}),ye(async()=>{let is;const{caption:ns,entities:ys}=W;if(ns?.trim()){const fi=[],{message:hn,totalEntities:ht}=Em(ns,ys?.slice()),qt=Yt(hn,Os(o.state.peerId,ht,fi));if(et(null),await Promise.all(fi),!ue())return;is=Wo(qt)}et(is)}),ye(()=>{if(!Et(()=>Xs(W)).id){yt();return}yt(null);const ys=Dd({peerId:o.state.peerId,storyItem:Vr(W),forViewer:!0,containerProps:{class:Me.ViewerStoryContentMediaContainer},childrenClassName:Me.ViewerStoryContentMedia,useBlur:40}),fi=()=>{yt(ys.container)},hn=()=>{ue()&&(T(!1),Et(()=>V()))},ht=()=>{const qt=ys.media();qt instanceof HTMLVideoElement?(si(qt),Wn(qt).then(hn)):hn()};Ao(fi)(()=>ys.ready()),Ao(ht)(()=>ys.media())}),ye(()=>{let is;const ns=W.sent_reaction,ys=EA(ns);if(!ns||ys)is=Le("reactions_filled",...["btn-reaction-icon",ys&&"btn-reaction-default"].filter(Boolean)),mt(is);else{const fi=document.createElement("div");fi.classList.add("btn-reaction-sticker","night"),jC({reaction:ns,uReaction:mt,div:fi,size:26,textColor:"white",play:!1})}}),ye(()=>{if(!W.media_areas?.length){Gt();return}Gt(null);const[is,ns]=ne(!1),[ys,fi]=ne(0),hn=j(ti,{get each(){return W.media_areas},children:ht=>{const[qt,ci]=ne(!1);return Ao(()=>{fi(Ts=>Ts+1),ys()===W.media_areas.length&&ns(!0)})(qt),j(kA,{story:W,mediaArea:ht,isActive:nt,setTooltipCloseCallback:Ae,setReady:ci,sendReaction:os,get close(){return o.close}})}});Ao(()=>{Gt(hn)})(is)}),ye(async()=>{const is=Uv(W);if(!is){zt();return}const{fwdFrom:ns,mediaAreaChannelPost:ys}=is;zt(null);const[fi,hn]=ne(),[ht,qt]=ne(),ci={header:(()=>{const qi=Zl();return D(qi,fi),Ve(()=>Ce(qi,Me.ViewerStoryHeaderRepost)),qi})()};let Ts,un,ba;ns?(Ts=ns.from&&at(ns.from),un=ns.from_name,ba=ns.story_id):Ts=ys.channel_id.toPeerId(!0);const Vl={peerId:Ts,fromName:un},{node:zd,readyThumbPromise:Kd}=es({peerId:Ts,peerTitle:un,size:16,middleware:ue}),Wd=(()=>{const qi=Zl();return D(qi,ht),qi})(),jd=async(qi,Ka)=>{const Kl=await qi;if(!ue())return;if(Ka&&!Kl.caption){qt(M("Story"));return}const Yd=[],{message:Ir,totalEntities:Pp}=Em(Kl.caption,Kl.entities?.slice()),QI=Yt(Ir,Os(Ts,Pp,Yd));await Promise.all(Yd),ue()&&qt(Wo(QI))},qd=ba&&I.managers.acknowledged.appStoriesManager.getStoryById(Ts,ba).then(async qi=>{const Ka=jd(qi.result,qi.cached);if(!qi.cached){qt(M("Story"));return}return Ka}),[Gl,zl,Qd]=await Promise.all([Oe(Vl).then(async qi=>{const Ka=document.createDocumentFragment();if(Ts){const Ir=await I.managers.appPeersManager.isBroadcast(Ts),Pp=Le(Ir?"newchannel_filled":Ts.isUser()?"newprivate_filled":"group_filled","inline-icon","reply-title-icon","with-margin");Ka.append(Pp)}if(Ka.append(qi),un||ys){const Ir=document.createElement("div");return Ir.classList.add(Me.ViewerStoryRepostSmall),Ir.append(Ka),Ir}const{container:Kl,fillPromise:Yd}=Fd({title:Ka,subtitle:Wd,useHighlightingColor:!0,setColorPeerId:Ts});return await Yd,Kl}),Oe(Vl),Kd.then(()=>zd),qd]);ue()&&(zl.classList.add(Me.ViewerStoryHeaderRepostTitle),Gl.classList.add(Me.ViewerStoryRepost),ci.reply=Gl,hn([Le(LA,Me.ViewerStoryHeaderRepostIcon),Qd,zl]),zt(ci))}),ye($s(()=>[DI(),qe?.(),et(),yt(),mt?.(),Gt(),zt()],([is,...ns])=>{if(!is||ns.some(Ts=>Ts===null))return;const[ys,fi,hn,ht,qt,ci]=ns;He(ys),v(fi),m(hn),C(ht),pe(qt),b(ci),o.onReady?.(),ye(()=>{cn(W)})},{defer:!0}))};ye(()=>{const W=Fe();L(0),_(!1),ye(()=>{gi(W)})});const J=()=>{if(!xe.size)return;const W=Array.from(xe);xe.clear(),I.managers.appStoriesManager.getStoriesById(o.state.peerId,W,!0)},xe=new Set;let je;ye(()=>{nt()?(je=window.setInterval(J,6e4),ye(()=>{xe.add(Fe().id)})):clearInterval(je)});const Ge=W=>{ae.size&&(I.managers.appStoriesManager.incrementStoryViews(o.state.peerId,Array.from(ae)),ae.clear()),I.managers.appStoriesManager.readStories(o.state.peerId,W)},ae=new Set,Se=ii(Ge,5e3,!0,!0);ye(()=>{if(!nt())return;let W;ye(()=>{const ue=Fe();o.pinned&&Et(()=>Ue())&&ae.add(ue.id),Se(W=ue.id)}),ut(()=>{Se.isDebounced()&&(Se.clearTimeout(),Ge(W))})});const V=()=>{!h.hasViewer||Et(()=>!nt())||Te()};ye(V);const ie=j(PA,Ai(()=>Ai(o,{currentStory:Fe})));let we=!0;const Ie=()=>{let W=Vd();if(!W)return"0px";Lp()&&h.hasViewer&&ly()&&we&&(W>0?++W:--W);const ue=h.width,qe=40,et=W>0?1:-1,yt=ue*pc;let mt=ue*et;const Gt=(ue-yt)/2-qe;if(mt=(ue-Gt)*et,Math.abs(W)!==1){const zt=W-1*et;mt+=zt*yt+qe*zt}return mt+"px"},Te=()=>{if(Et(()=>A()))return;const W=Et(()=>g()),ue=W?W+.001:KC;u.play(ue)},Qe=W=>{W&&W.target!==Hl||Z(!0)},Re=W=>{W&&W.target!==Hl||(we=!0,Z(!1),nt()&&Te())},tt=W=>{if(re()){const{close:ue}=ur({...cy,textElement:M("Story.NoSound")});Ae(()=>ue);return}u.toggleMute()};let ct;const Mt=j(kn,{ref(W){const ue=ct;typeof ue=="function"?ue(W):ct=W},get classList(){return{[Me.noSound]:re()}},get icon(){return h.muted||re()?"speakerofffilled":"speakerfilled"},onClick:tt}),Ht=()=>{Fs(`https://t.me/${ui(wp)[0]}/s/${Fe().id}`),Ee({langPackKey:"LinkCopied"})},li={onOpenBefore:async()=>{wp=await I.managers.appStoriesManager.getPeer(o.state.peerId),dn=Fe(),Jn=o.state.peerId},onOpen:()=>{Ol=!h.paused,u.pause()},onCloseAfter:()=>{Ol&&!Ul&&u.play(),Ul=!1}},ts=.2;ye(()=>{nt()&&u.setLoop(g()!==void 0&&E())});let St;const ss=W=>{const ue=Math.min(1,W/100),qe=ue>=ts;L(ue),_(qe),g()===void 0&&(qe?St===void 0&&(St=!h.paused,u.pause()):St&&(St=void 0,u.play()))};let Vs,Zn,ji=!1;const Cr=()=>{if(ji)return;const W=Vs.scrollTop;ss(W)},Lo=W=>{const ue=Math.max(0,W),qe=Date.now();ji=!0;const et=Fe();Ba(()=>{if(Fe()!==et)return!1;const yt=Math.min(1,(Date.now()-qe)/300),mt=wE(yt,1),Gt=W*(1-mt),zt=Math.round(ue-Gt);return Vs.scrollTop=zt,ss(zt),yt<1},Vs).finally(()=>{ji=!1})},Pn=W=>{if(Vs.scrollHeight<=Vs.clientHeight||Vs.scrollTop)return;oe(W);const qe=Math.min(Zn.scrollHeight-56,Vs.clientHeight-60);Lo(qe)},sy=(()=>{const W=wA(),ue=W.firstChild,qe=ue.firstChild;W.addEventListener("scroll",Cr);const et=Vs;typeof et=="function"?wt(et,W):Vs=W,ue.$$click=Pn;const yt=Zn;return typeof yt=="function"?wt(yt,ue):Zn=ue,D(qe,()=>w()?.reply,null),D(qe,y,null),Ve(mt=>{const Gt=ot("scrollable","scrollable-y","no-scrollbar",Me.ViewerStoryCaption,w()&&y()&&Me.hasReply),zt=ot("spoilers-container",Me.ViewerStoryCaptionText),ks=Me.ViewerStoryCaptionTextCell;return Gt!==mt._v$8&&Ce(W,mt._v$8=Gt),zt!==mt._v$9&&Ce(ue,mt._v$9=zt),ks!==mt._v$10&&Ce(qe,mt._v$10=ks),mt},{_v$8:void 0,_v$9:void 0,_v$10:void 0}),W})(),FI=(()=>{const W=Gn();return D(W,p),Ve(ue=>{const qe=Me.ViewerStoryContentItem,et=P()&&{opacity:1-P()*.5};return qe!==ue._v$11&&Ce(W,ue._v$11=qe),ue._v$12=zi(W,et,ue._v$12),ue},{_v$11:void 0,_v$12:void 0}),W})(),RI=()=>{const{timestamp:W,edited:ue}=k()||{};if(!W)return;const qe=Ms(!0)-W,et=yo(qe),yt={[Xi.Seconds]:"StoryJustNow",[Xi.Minutes]:"MinutesShortAgo",[Xi.Hours]:"HoursShortAgo"},mt=et[0],Gt=yt[mt.type],zt=[];Gt?mt.type===Xi.Days&&mt.duration!==1?zt.push(Md(new Date(W*1e3))):zt.push(M(Gt,[mt.duration])):zt.push((()=>{const Os=Zl();return D(Os,()=>Wo(ws(W))),Os})()),ue&&zt.push(M("EditedMessage")),w()&&zt.unshift(w().header);let ks=mo(zt,Vv);return w()&&(ks=[ks[0],(()=>{const Os=Zl();return D(Os,()=>ks.slice(1)),Ve(()=>Ce(Os,Me.ViewerStoryHeaderSecondary)),Os})()]),ks},iy=(W,ue)=>{let qe;ue&&(qe=document.createElement("a"),qe.href="#",qe.addEventListener("click",et=>{oe(et),o.close(()=>{me.setInnerPeer({peerId:ue})})},{capture:!0,passive:!1}),qe.append(M("ViewInChat"))),ap({textElement:W,textRight:qe,appendTo:$l,from:"bottom",duration:3e3,icon:"checkround_filled"})},ny=o.state.peerId!==Fr&&o.state.peerId!==I.myId&&o.state.peerId.isUser(),[DI,BI]=ne(!ny),NI=ny&&j(_A,Ai(()=>Ai(o,{currentStory:Fe,isActive:nt,focusedSignal:O,inputEmptySignal:F,inputMenuOpenSignal:H,sendReaction:os,isPublic:he,shareStory:r,reaction:S,onShareButtonClick:l,onMessageSent:()=>{iy(M("Story.Tooltip.MessageSent"),o.state.peerId)},setInputReady:BI}))),ay=async W=>{const ue=o.state.peerId;if(ue===I.myId||ue===Fr)return!1;const[qe,et]=await Promise.all([I.managers.appStoriesManager.getPeer(ue),I.managers.appStoriesManager.isSubcribedToPeer(ue)]),yt=!!qe.pFlags.stories_hidden;return(W?!yt:yt)&&et},ry=async W=>{const ue=o.state.peerId;I.managers.appStoriesManager.toggleStoriesHidden(ue,W),Ee({langPackKey:W?"StoriesMovedToContacts":"StoriesMovedToDialogs",langPackArguments:[await Oe({peerId:ue})]})},$d=async W=>{const ue=o.state.peerId;I.managers.appStoriesManager.togglePinned(ue,Fe().id,W).then(()=>{Ee({langPackKey:W?ue.isUser()?"StoryPinnedToProfile":"StoryPinnedToPosts":ue.isUser()?"StoryArchivedFromProfile":"StoryUnpinnedFromPosts"})})};let Ol=!1,wp,Jn,dn,Ul=!1;const oy=ai({buttons:[{icon:"plusround",text:"Story.AddToProfile",onClick:()=>$d(!0),verify:()=>Jn===I.myId&&!dn.pFlags?.pinned},{icon:"crossround",text:"Story.RemoveFromProfile",onClick:()=>$d(!1),verify:()=>Jn===I.myId&&!!dn.pFlags?.pinned},{icon:"plusround",text:"SaveToPosts",onClick:()=>$d(!0),verify:()=>!Jn.isUser()&&!dn.pFlags?.pinned&&I.managers.appStoriesManager.hasRights(Jn,dn.id,"pin")},{icon:"crossround",text:"RemoveFromPosts",onClick:()=>$d(!1),verify:()=>!Jn.isUser()&&!!dn.pFlags?.pinned&&I.managers.appStoriesManager.hasRights(Jn,dn.id,"pin")},{icon:"forward",text:"ShareFile",onClick:()=>{Ul=!0,r(Ol)},verify:()=>!!dn?.pFlags?.public&&!dn.pFlags.noforwards},{icon:"link",text:"CopyLink",onClick:Ht,verify:()=>dn._!=="storyItem"?!1:dn.pFlags.public&&!!ui(wp)[0]},{icon:"download",text:"MediaViewer.Context.Download",onClick:()=>{const W=Fe(),ue=Xs(W,!0);ue&&cs.downloadToDisc({media:Vr(ue)})},verify:()=>{if(o.state.peerId===I.myId)return!0;const W=Fe();return!!(W?._==="storyItem"&&!W.pFlags.noforwards&&I.premium)}},{icon:"archive",text:"ArchivePeerStories",onClick:()=>ry(!0),verify:()=>ay(!0)},{icon:"unarchive",text:"UnarchiveStories",onClick:()=>ry(!1),verify:()=>ay(!1)},{icon:"statistics",text:"ViewStatistics",onClick:()=>{const W=Fe().id;o.close(()=>{setTimeout(()=>{ls.createTab(Nd).open(Jn.toChatId(),void 0,W),ls.toggleSidebar(!0)},0)})},verify:()=>I.managers.appProfileManager.canViewStatistics(Jn)},{icon:"delete danger",text:"Delete",onClick:async()=>{const W=Fe().id,ue=o.state.peerId;Ul=!0;const qe=n(Ol);try{await Ct({titleLangKey:"DeleteStoryTitle",descriptionLangKey:"DeleteStorySubtitle",button:{langKey:"Delete",isDanger:!0}})}catch{qe();return}I.managers.appStoriesManager.deleteStories(ue,[W])},verify:()=>I.managers.appStoriesManager.hasRights(Jn,dn.id,"delete")},{icon:"flag",className:"danger",text:"ReportChat",onClick:()=>{Ul=!0;const W=n(Ol);ee.createPopup(IC,o.state.peerId,[Fe().id],W,!0)},verify:()=>!dn.pFlags?.out&&o.state.peerId!==Fr}],direction:"bottom-left",...li});oy.classList.add("night");const OI={close:"star_filled",contacts:"newprivate_filled",public:"newchannel_filled",selected:"newgroup_filled"},UI=async()=>{const W=de(),ue=await Oe({peerId:o.state.peerId,onlyFirstName:!0}),{close:qe}=ur({container:Gd,element:Sp,vertical:"bottom",textElement:M(W==="close"?"StoryCloseFriendsHint":W==="selected"?"StorySelectedContactsHint":"StoryContactsHint",[ue]),paddingX:13});Ae(()=>qe)};ye(()=>{const W=De();W&&(ut(W),ye($s(()=>[nt(),Fe()],()=>{W(),Ae()},{defer:!0})))});let Sp;const HI=(()=>{const W=Gn();W.$$click=()=>UI();const ue=Sp;return typeof ue=="function"?wt(ue,W):Sp=W,D(W,()=>Le(OI[de()])),Ve(()=>Ce(W,ot(Me.ViewerStoryPrivacy,"privacy-bg",`privacy-bg-${de()}`))),W})(),$I=t&&(()=>{const W=Fe();if(W._!=="storyItem")return;const ue=W.views?.views_count??0;return ue?M("Views",[ue]):W.expire_date<=Ms(!0)?M("NobodyViewsArchived"):M("NobodyViews")}),VI=t&&(()=>{let W;const ue=new Map,qe=ee.createPopup(Es,{peerType:["custom"],getMoreCustom:et=>I.managers.appStoriesManager.getStoryViewsList(o.state.peerId,Fe().id,50,W,et).then(({nextOffset:mt,views:Gt})=>(W=mt,{result:Gt.map(zt=>{const ks=zt.user_id.toPeerId(!1);return ue.set(ks,zt),ks}),isEnd:!W})),processElementAfter:(et,yt)=>{const mt=ue.get(et);return LC({dialogElement:yt,peerId:et,date:mt.date,isMine:!0,middleware:qe.selector.middlewareHelperLoader.get(),reaction:mt.reaction})},onSelect:et=>{o.close(()=>{me.setInnerPeer({peerId:et})})},placeholder:"SearchPlaceholder",exceptSelf:!0,meAsSaved:!1})}),GI=t&&(async()=>{const W=o.state.peerId,ue=Fe().id;await Ct({titleLangKey:"DeleteStoryTitle",descriptionLangKey:"DeleteStorySubtitle",button:{isDanger:!0,langKey:"Delete"}}),I.managers.appStoriesManager.deleteStories(W,[ue])});if(t){const W=new Set,ue=2;let qe;const et=async()=>{if(qe)return;const Gt=Fe(),zt=o.state.stories.indexOf(Gt);o.state.stories.slice(Math.max(0,zt-ue),zt+ue).forEach(is=>{W.add(is.id)});const Os=Array.from(W);W.clear(),qe=I.managers.appStoriesManager.getStoriesViews(o.state.peerId,Os).then(()=>{qe=void 0}),mt&&clearInterval(yt)},yt=setInterval(et,1e4);ye(()=>{const Gt=Fe();W.add(Gt.id)});let mt=!1;ut(()=>{mt=!0}),vr(()=>{et()})}let Cp;const zI=(t||Fr===o.state.peerId||!o.state.peerId.isUser())&&(()=>{const W=Gn();return D(W,()=>t?[(()=>{const ue=Gn();return Pl(ue,"click",VI,!0),D(ue,(()=>{const qe=K(()=>!!Be());return()=>qe()&&Be().container})(),null),D(ue,$I,null),Ve(()=>Ce(ue,Me.ViewerStoryFooterLeft)),ue})(),(()=>{const ue=Gn();return D(ue,j(kn,{icon:"delete",onClick:GI})),Ve(()=>Ce(ue,Me.ViewerStoryFooterRight)),ue})()]:o.state.peerId.isUser()?M("StoryCantReply"):[(()=>{const ue=Hv(),qe=ue.firstChild;return D(qe,()=>Le("eye1",Me.ViewerStoryFooterIconIcon),null),D(qe,()=>on(Fe().views?.views_count||1,1),null),Ve(et=>{const yt=Me.ViewerStoryFooterLeft,mt=Me.ViewerStoryFooterIcon;return yt!==et._v$13&&Ce(ue,et._v$13=yt),mt!==et._v$14&&Ce(qe,et._v$14=mt),et},{_v$13:void 0,_v$14:void 0}),ue})(),(()=>{const ue=Hv(),qe=ue.firstChild;D(ue,(()=>{const yt=K(()=>!!B());return()=>yt()&&j(kn,{icon:"forward",onClick:mt=>{l(mt,mt.target)}})})(),qe),qe.$$click=yt=>os({reaction:{_:"reactionEmoji",emoticon:Of},target:Cp.firstElementChild});const et=Cp;return typeof et=="function"?wt(et,qe):Cp=qe,D(qe,j(xi,{get icon(){return Fe().sent_reaction?"reactions_filled":"reactions"},get class(){return Me.ViewerStoryFooterIconIcon}}),null),D(qe,()=>Fe().views?.reactions_count||0,null),Ve(yt=>{const mt=Me.ViewerStoryFooterRight,Gt=ot(Me.ViewerStoryFooterIcon,Me.ViewerStoryFooterReaction,Fe().sent_reaction&&Me.isReacted);return mt!==yt._v$15&&Ce(ue,yt._v$15=mt),Gt!==yt._v$16&&Ce(qe,yt._v$16=Gt),yt},{_v$15:void 0,_v$16:void 0}),ue})()]),Ve(()=>Ce(W,ot(Me.ViewerStoryFooter,Me.hideOnSmall,I.myId===o.state.peerId&&Me.isMe,Fr===o.state.peerId&&Me.isChangelog))),W})();ye($s(()=>[nt(),Fe()],()=>{st.isAvailable("animations")||Et(()=>{Qe(),Re()})}));const KI=()=>{const W=o.state.peerId;o.close(()=>{me.setInnerPeer({peerId:W})})},Vd=K(()=>o.index()-o.peers.indexOf(h.peer)),WI=K(W=>be()?W:Vd()<0),jI=K(W=>be()?W:Vd()>0),[ly,Ip]=ne(!1),Lp=K(()=>{const W=Math.abs(Vd());let ue;return h.hasViewer?ue=W<=og:(ue=W===0,!o.isFull()&&W<=og&&(we=!1)),ue});ye(W=>{if(Lp()){if(W)return Ip(!0),Qn().then(()=>{Ip(!1)}),!0}else return Ip(!0),!0});let Hl,$l,Gd;const qI=(()=>{const W=SA(),ue=W.firstChild,qe=ue.firstChild,et=qe.nextSibling,yt=et.firstChild,mt=yt.nextSibling,Gt=mt.nextSibling,zt=Gt.firstChild,ks=zt.firstChild,Os=ks.firstChild,is=Os.nextSibling,ns=zt.nextSibling;W.addEventListener("transitionend",Re),W.addEventListener("transitionstart",Qe),W.$$click=ht=>{if(!nt())u.set({peer:o.state,index:o.state.index});else if(U(ht.target,Me.ViewerStoryRepost)){const qt=Fe(),ci=Uv(qt);if(!ci){Ee({langPackKey:"HidAccount"});return}const{fwdFrom:Ts,mediaAreaChannelPost:un}=ci;(Ts?.from||un)&&o.close(()=>{const ba=Ts?at(Ts.from):un.channel_id.toPeerId(!0);Ts?.story_id?mr({peerId:ba,id:Ts.story_id}):me.setInnerPeer({peerId:ba,lastMsgId:un?.msg_id})})}else if(Vs.scrollTop&&!Ns(ht.target,Zn)&&!U(ht.target,Me.ViewerStoryHeader))Lo(-Vs.scrollTop);else if(!h.paused&&!h.hideInterface&&!Ns(ht.target,Zn)&&!U(ht.target,Me.ViewerStoryHeader)&&!U(ht.target,"stories-input")&&!U(ht.target,Me.ViewerStoryReactions)&&U(ht.target,Me.ViewerStory)){const qt=Hl.getBoundingClientRect(),ci=ht.clientX>qt.left+qt.width/3;u.goToNearestStorySafe(ci)}};const ys=Hl;typeof ys=="function"?wt(ys,W):Hl=W;const fi=$l;typeof fi=="function"?wt(fi,ue):$l=ue,D(qe,FI),D(mt,ie);const hn=Gd;return typeof hn=="function"?wt(hn,Gt):Gd=Gt,zt.$$click=KI,D(zt,()=>e.element,ks),D(Os,i,null),D(Os,(()=>{const ht=K(()=>!!o.splitByDays);return()=>ht()&&(()=>{const qt=Zl();return D(qt,()=>`${Vv}${o.state.index+1}/${o.state.stories.length}`),Ve(()=>Ce(qt,Me.ViewerStoryHeaderSecondary)),qt})()})(),null),D(is,RI),D(ns,()=>de()&&HI,null),D(ns,j(kn,{get icon(){return h.paused&&!h.playAfterGesture?"play":"pause"},onClick:()=>u.toggle()}),null),D(ns,()=>g()&&Mt,null),D(ns,oy,null),D(ns,(()=>{const ht=K(()=>!!o.isFull());return()=>ht()&&j(kn,{icon:"close",onClick:()=>o.close()})})(),null),D(et,()=>(y()||w())&&sy,null),D(et,(()=>{const ht=K(()=>!!Ne());return()=>ht()&&(()=>{const qt=Gn();return D(qt,Ne),Ve(ci=>{const Ts=Me.ViewerStoryMediaAreas,un=P()&&{opacity:1-P()*.5,"z-index":0};return Ts!==ci._v$31&&Ce(qt,ci._v$31=Ts),ci._v$32=zi(qt,un,ci._v$32),ci},{_v$31:void 0,_v$32:void 0}),qt})()})(),null),D(et,()=>Ke()?.widthContainer,null),D(ue,(()=>{const ht=K(()=>!o.isFull());return()=>ht()&&(()=>{const qt=Gn();return D(qt,()=>c.node,null),D(qt,d,null),Ve(()=>Ce(qt,Me.ViewerStoryInfo)),qt})()})(),null),D(W,NI||zI,null),Ve(ht=>{const qt=Me.ViewerStoryContainer,ci={...o.isFull()?{[Me.fromLeft]:WI(),[Me.current]:nt(),[Me.fromRight]:jI()}:{[Me.small]:!nt()},[Me.hold]:h.hideInterface&&nt(),[Me.focused]:z(),[Me.fadeIn]:ly()},Ts=!o.isFull()&&{"--translateX":Ie()},un=ot(Me.ViewerStory,A()&&nt()&&"shimmer"),ba=Me.ViewerStoryContent,Vl=Me.hideOnSmall,zd=ot(Me.ViewerStoryShadow,y()&&Me.hasCaption),Kd=Me.ViewerStorySlides,Wd=ot(Me.ViewerStoryHeader,"night"),jd=Me.ViewerStoryHeaderLeft,qd=Me.ViewerStoryHeaderInfo,Gl=Me.ViewerStoryHeaderRow,zl=ot(w()?Me.hasRepost:Me.ViewerStoryHeaderSecondary,Me.ViewerStoryHeaderTime),Qd=Me.ViewerStoryHeaderRight;return qt!==ht._v$17&&Ce(W,ht._v$17=qt),ht._v$18=pa(W,ci,ht._v$18),ht._v$19=zi(W,Ts,ht._v$19),un!==ht._v$20&&Ce(ue,ht._v$20=un),ba!==ht._v$21&&Ce(qe,ht._v$21=ba),Vl!==ht._v$22&&Ce(et,ht._v$22=Vl),zd!==ht._v$23&&Ce(yt,ht._v$23=zd),Kd!==ht._v$24&&Ce(mt,ht._v$24=Kd),Wd!==ht._v$25&&Ce(Gt,ht._v$25=Wd),jd!==ht._v$26&&Ce(zt,ht._v$26=jd),qd!==ht._v$27&&Ce(ks,ht._v$27=qd),Gl!==ht._v$28&&Ce(Os,ht._v$28=Gl),zl!==ht._v$29&&Ce(is,ht._v$29=zl),Qd!==ht._v$30&&Ce(ns,ht._v$30=Qd),ht},{_v$17:void 0,_v$18:void 0,_v$19:void 0,_v$20:void 0,_v$21:void 0,_v$22:void 0,_v$23:void 0,_v$24:void 0,_v$25:void 0,_v$26:void 0,_v$27:void 0,_v$28:void 0,_v$29:void 0,_v$30:void 0}),W})(),cy={container:Gd,element:ct,vertical:"bottom",paddingX:13};return j(an,{get when(){return Lp()},children:qI})};function xA(o){const[e,t]=Io(),[s,i]=ne(!1),n=K(()=>lt.height>lt.width||lt.width<e.width+135+8*2||e.width===lt.width),a=K(R=>R||s());t.viewerReady(!1);const r=new Set(["ArrowRight","ArrowLeft","ArrowDown","Space"]),l=R=>{if(yA(document.activeElement)){c.clear();return}const O=P();if(B||O.querySelector(".is-recording")){c.clear(),oe(R);return}if(r.has(R.key)||r.has(R.code))oe(R);else{const X=O.querySelector(".input-message-input");X&&!Je&&X.isContentEditable&&Li.overlaysActive===E&&VC(X,R)}if(R.key==="ArrowDown"){c.clear(),d();return}c(R)},c=ma(R=>{R.key==="ArrowRight"?t.goToNearestStorySafe(!0):R.key==="ArrowLeft"?t.goToNearestStorySafe(!1):R.code==="Space"&&t.toggle()},200,!0);Ji.getElement().classList.add("night"),Ji.setTextColor("white"),ut(()=>{document.body.removeEventListener("keydown",l),_(!1),y.removeListeners(),ft.removeItem(C),Ji.getElement().classList.remove("night"),Ji.setTextColor(),Ji.chatInput=void 0});const d=R=>{R&&Rc(S,()=>{ut(()=>{R()})}),t.viewerReady(!1),m&&(T=Pt(),Xr(T,1e3),m(),m=void 0),t.pause(),c.clear(),i(!1),h.removeEventListener("click",b,{capture:!0})};let h,u,p,m;const g=Jt(R=>{m=R,ye(()=>{e.ended&&d()});const O=new Set,X=new Set,F=performance.now();let H=!1;const G=()=>{clearTimeout(z),H=!0,console.log("ready",performance.now()-F),Rc(S,()=>{vr(()=>{w()})})},z=setTimeout(()=>{console.error("stories timeout"),e.peers.filter(le=>X.has(le.peerId)&&!O.has(le.peerId)).forEach(le=>{console.error("stories not ready",le)}),G()},250),q=(le,re)=>{const ge=()=>{O.add(le.peerId),!H&&O.size===X.size&&G()};X.add(le.peerId);const be=ne(!1),Z=j(TA,{state:le,index:re,get splitByDays(){return o.splitByDays},get pinned(){return o.pinned},onReady:ge,close:d,get peers(){return Y()},isFull:n,transitionSignal:be}),de=yf(()=>Z);return ye(()=>{const Ze=de();Ze&&(he.set(Ze,be[0]),ut(()=>{he.delete(Ze)}))}),Z},$=og+IA,se=le=>e.peers.slice(Math.max(le-$,0),Math.min(le+$+1,e.peers.length)),Y=K(()=>se(e.index)),Q=j(kn,{ref(le){const re=p;typeof re=="function"?re(le):p=le},icon:"close",get class(){return Me.ViewerClose},onClick:()=>d()}),he=new WeakMap;return(()=>{const le=CA(),re=le.firstChild;le.$$click=Z=>{if(B){oe(Z);return}Z.target===h&&d()};const ge=h;typeof ge=="function"?wt(ge,le):h=le;const be=u;return typeof be=="function"?wt(be,re):u=re,D(le,()=>!n()&&Q,null),D(le,j(TC,{noWait:()=>n(),transitions:he,get children(){return j(ti,{get each(){return Y()},children:q})}}),null),Ve(Z=>{const de=ot(Me.Viewer,!s()&&Me.isInvisible,n()&&Me.isFull,e.hasViewer&&Me.isReady),Ze=e.width+"px",Ne=e.height+"px",pe=Me.ViewerBackground;return de!==Z._v$33&&Ce(le,Z._v$33=de),Ze!==Z._v$34&&((Z._v$34=Ze)!=null?le.style.setProperty("--stories-width",Ze):le.style.removeProperty("--stories-width")),Ne!==Z._v$35&&((Z._v$35=Ne)!=null?le.style.setProperty("--stories-height",Ne):le.style.removeProperty("--stories-height")),pe!==Z._v$36&&Ce(re,Z._v$36=pe),Z},{_v$33:void 0,_v$34:void 0,_v$35:void 0,_v$36:void 0}),le})()});let f;const y=new So({element:h,onSwipe:(R,O,X)=>{if(!(X instanceof TouchEvent))return;const F=Math.min(125,lt.width/3),H=Math.min(125,lt.height*.2);if(O>H)return d(),!0;if(Math.abs(R)<F)return!1;const z=e.peers.indexOf(e.peer)+(R<0?1:-1),q=e.peers[z];return q?t.set({peer:q}):d(),!0},verifyTouchTarget:R=>!U(R.target,"btn-icon")&&!U(R.target,"btn-corner")&&!U(R.target,Me.ViewerStoryRepost)&&!U(R.target,Me.ViewerStoryMediaArea)&&!U(R.target,Me.ViewerStoryPrivacy)&&!U(R.target,Me.ViewerStoryCaptionText)&&!U(R.target,Me.ViewerStoryReactions)&&!!U(R.target,Me.ViewerStory)&&!U(R.target,Me.small)&&!U(R.target,Me.focused),onStart:()=>{f=window.setTimeout(()=>{t.pause(!0)},200)},onReset:R=>{if(window.clearTimeout(f),!R||!e.paused||U(R.target,"btn-icon")||U(R.target,Me.ViewerStoryPrivacy)||U(R.target,"btn-corner")||U(R.target,Me.ViewerStoryReactions))return;const O=U(R.target,Me.ViewerStory);if(O?.querySelector("."+Me.ViewerStoryCaption)?.scrollTop)return;O&&e.hideInterface&&document.addEventListener("click",oe,{capture:!0,once:!0});const F=e.playAfterGesture||!e.hideInterface;t.toggleInterface(!1),F&&t.play()}});let v;const w=()=>{const R=o.target?.();if(!R||!R.classList.contains("avatar")){i(!0);return}v=Fn({size:rg,isDialog:!1,useCache:!1}),v.node.style.cssText="position: absolute; visibility: hidden; z-index: 1000; transform-origin: top left;",document.body.append(v.node),Et(()=>s())||ye(()=>{v.ready()&&i(!0)}),ye(()=>{const O=e.peer?.peerId;!O||!v||Et(()=>{v.render({peerId:O})})}),ut(()=>{v&&v.node.remove()})},b=R=>{B&&oe(R);const X=U(R.target,Me.ViewerStory)?.querySelector("."+Me.ViewerStoryCaptionText),F=X&&Ud(X,R);if(F)return d(F),!1};h.addEventListener("click",b,{capture:!0});const S=Tu(),C={type:"stories",onPop:()=>{if(B)return!1;d()}};ft.pushItem(C);const P=(R=h)=>R.querySelector(`.${Me.ViewerStoryContainer}:not(.${Me.small})`),L=(R,O,X)=>{const F=P(R);if(!st.isAvailable("animations")||!F){X();return}const H=Array.from(R.querySelectorAll(`.${Me.ViewerStoryContainer}`));let G;const z=Et(()=>{const De=o.target?.();if(!De)return;const Ae=U(De,"scrollable");if(!Ae)return De;const Ke=go(De,Ae);if(!Ke){v&&(v.node.remove(),v=void 0);return}return v&&(Ke.overflow.horizontal||Ke.overflow.vertical)&&(G=!0),De}),q=z&&(z.querySelector(".avatar")||z).getBoundingClientRect(),$=F.getBoundingClientRect(),se=v?"50%":window.getComputedStyle(F).borderRadius,Y=De=>(O||De.reverse(),De),Q={duration:250,easing:"cubic-bezier(0.4, 0.0, 0.6, 1)"};let he,le;if(v){le=F.querySelector(`.${Me.ViewerStoryHeaderAvatar}`),le.style.visibility="hidden";const De=le.getBoundingClientRect();v.node.style.top=`${q.top}px`,v.node.style.left=`${q.left}px`,v.node.style.visibility="",v.node.parentElement||document.body.append(v.node);const Ae=De.left-q.left,Ke=De.top-q.top,We=Y([{transform:`translate(0, 0) scale(${q.width/rg})`},{transform:`translate(${Ae}px, ${Ke}px) scale(1)`}]);G&&(We[0].opacity=0,We[1].opacity=1),he=v.node.animate(We,Q)}const re=q&&q.left-lt.width/2+q.width/2,ge=q&&q.top-lt.height/2+q.height/2,be=q&&F.animate(Y([{borderRadius:se,transform:`translate3d(${re}px, ${ge}px, 0) scale3d(${q.width/$.width}, ${q.height/$.height}, 1)`,opacity:0},{opacity:1,offset:.3},{borderRadius:"0%",transform:"translate3d(0, 0, 0) scale3d(1, 1, 1)"}]),Q),Z=(be?[u,!n()&&p].filter(Boolean):[F,R]).map(De=>De.animate(Y([{opacity:0},{opacity:1}]),Q)),de=H.indexOf(F);H.splice(de,1);const Ze=H.slice(0,de),Ne=H.slice(de),pe=(De,Ae)=>q?De.map((Ke,We,Fe)=>{const Ue=(Ae?We+1:Fe.length-We)*60*(Ae?-1:1);return Ke.animate(Y([{transform:`translate3d(calc(var(--translateX) + ${Ue}px), 0, 0) scale3d(${pc/2}, ${pc/2}, 1)`,opacity:.001},{opacity:.001,offset:.5},{transform:`translate3d(var(--translateX), 0, 0) scale3d(${pc}, ${pc}, 1)`,opacity:1}]),Q)}):De.map(Ke=>Ke.animate(Y([{opacity:0},{opacity:1}]),Q)),He=[...Z,be,he,...pe(Ze,!1),...pe(Ne,!0)].map(De=>De?.finished);return Promise.all(He).then(()=>{v&&(v.node.remove(),le.style.visibility=""),X()})};let E;const _=R=>{t.toggleSorting("viewer",R),Li.isDarkOverlayActive=R,gt.checkAnimations2(R),R&&(E=Li.overlaysActive)},k=WC();let x;k.add(xa)("change",R=>{if(R){x=!e.paused,t.pause(),$v.open();return}const O=()=>{clearTimeout(X)};document.body.addEventListener("mousedown",O,{once:!0});const X=setTimeout(()=>{document.body.removeEventListener("mousedown",O),$v.close()},100);x&&t.play()});let A;k.add(Li)("change",()=>{const R=Li.overlaysActive;R>E?(A=!e.paused,t.pause()):R===E&&A&&t.play()});let T=Pt(),B=!0;return j(an,{get when(){return a()},fallback:g,get children(){return j(gp,{onEnter:(R,O)=>{Xr(T,1e3),document.body.addEventListener("keydown",l),_(!0),L(R,!0,O)},onAfterEnter:()=>{B=!1,t.viewerReady(!0),T.resolve()},onExit:(R,O)=>{B=!0,t.viewerReady(!1),L(R,!1,O)},onAfterExit:()=>{B=!1,o.onExit?.(),stop(),T.resolve()},appear:!0,get children(){return s()&&g}})}})}const Od=o=>o.peers&&!o.onExit?Jt(e=>(o.onExit=()=>e(),j(Nf,{get peers(){return o.peers},get index(){return o.index},get children(){return Od(o)}}))):j(_u,{get mount(){return document.getElementById("stories-viewer")},get children(){return j(xA,o)}}),AA=o=>{const[,e]=Xn(o,["peerId","storyItem"]);return Od({...e,peers:[{peerId:o.peerId,stories:[o.storyItem],index:0,count:1}],index:0})},mr=async o=>{const[,e]=Xn(o,["peerId","id"]),t=await I.managers.appStoriesManager.getPeerStories(o.peerId),s=o.id?t.stories.findIndex(i=>i.id===o.id):void 0;if(o.id){const i=await I.managers.appStoriesManager.getStoryById(o.peerId,o.id);if(!i){Ee({langPackKey:"Story.ExpiredToast"});return}AA({...e,peerId:o.peerId,storyItem:i,singleStory:!0});return}Od({...e,peers:[{peerId:o.peerId,stories:t.stories,maxReadId:t.max_read_id,index:s,count:t.stories.length}],index:0})};Ui(["click"]);const FA="_List_pejiw_41",RA="_ListItem_pejiw_56",DA="_ListItemName_pejiw_71",BA="_isRead_pejiw_83",NA="_isMasked_pejiw_86",OA="_ListContainer_pejiw_115",UA="_skipAnimation_pejiw_123",Qa={List:FA,"space-evenly":"_space-evenly_pejiw_45",ListItem:RA,ListItemName:DA,isRead:BA,isMasked:NA,ListContainer:OA,skipAnimation:UA};class Sl extends Dt{static getInitArgs(){return{animationData:_s.loadAnimationFromURLManually("UtyanStories")}}init(e=Sl.getInitArgs()){this.header.classList.add("with-border"),this.container.classList.add("chat-folders-container",`${this.isArchive?"archive":"my"}-stories-container`),this.setTitle(this.isArchive?"MyStories.Archive":"MyStories.Title");const t=()=>{const c=this.slider.createTab(Sl);c.isArchive=!0,c.open()};let s,i;if(this.isArchive)i=new Pe({caption:"ProfileStoriesArchiveHint"}),i.innerContainer.remove();else{s=document.createElement("div"),s.classList.add("my-stories-placeholder","hide"),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container");const c=document.createElement("div");c.classList.add("caption"),Nh({element:c,key:"MyStories.Subtitle"}),this.showArchiveBtn=ze("btn-primary btn-color-primary btn-control",{text:"MyStories.ShowArchive"}),N(this.showArchiveBtn,t,{listenerSetter:this.listenerSetter}),s.append(this.stickerContainer,c,this.showArchiveBtn)}const n=ai({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[{icon:"archive",text:"MyStories.ShowArchive",onClick:t,verify:()=>!this.isArchive},{icon:"select",text:"Message.Context.Select",onClick:()=>{r.selection.toggleSelection(!0,!0)},verify:()=>!!(a&&!r.selection.isSelecting)},{icon:"select",text:"Message.Context.Selection.Clear",onClick:()=>{r.selection.cancelSelection()},verify:()=>r.selection.isSelecting}]});this.header.append(n);let a;const r=this.searchSuper=new $f({mediaTabs:[{inputFilter:"inputMessagesFilterEmpty",name:"Stories",type:"stories"}],scrollable:this.scrollable,hideEmptyTabs:!0,managers:this.managers,storiesArchive:this.isArchive});r.onStoriesLengthChange=c=>{a=c,s&&s.classList.toggle("hide",c>0)},r.setQuery({peerId:I.myId}),r.selectTab(0),this.middlewareHelper.onDestroy(()=>{r.destroy()}),this.scrollable.append(...[i?.container,r.container,s].filter(Boolean));const l=this.middlewareHelper.get();return Promise.all([this.loadAnimationPromise=!this.isArchive&&e.animationData.then(async c=>{const d=await c({container:this.stickerContainer,loop:!1,autoplay:!1,width:100,height:100,middleware:l});return this.animation=d,_s.waitForFirstFrame(d)}),r.load(!0)])}}const Jl=1,To=0;function qC(o){const[e,t]=ne(Jl),[s,i]=ne(!1),n=K(()=>e()===Jl),a=(y,v)=>{st.isAvailable("animations")&&!v&&i(!0),t(y)},r=(y,v)=>{const w=Date.now(),b=c=Ba(()=>{const S=Kt((Date.now()-w)/125,0,1);let C=y;return(y>.5||v===!1)&&v!==!0?(C+=(1-y)*S,d=!1):(d=!0,C-=y*S),a(C),S<1},o.container()).finally(()=>{b===c&&(c=void 0)})},l=()=>{Mg(o.container())};let c,d;const u=ii(()=>{},75,!1,!0),p=(y,v)=>{const w=o.scrollable().scrollTop,b=v instanceof WheelEvent;{const P=y<0?To:Jl;if(w&&e()!==To||u.isDebounced()){u();return}if(e()===P)return;v&&oe(v),a(P);return}const S=e();if(o.container().classList.add(o.skipAnimationClassName),y>0&&c&&d){u.clearTimeout(),r(S,!1);return}if(c||S>=Jl&&y>0||S<=To&&y<=0)return;let C=y/600;C=Kt(S+C,0,1),console.log("value",C),a(C),C>=1||C<=0?u.clearTimeout():(v&&oe(v),u())},m=y=>{if(o.shouldIgnore?.())return;const w=-y.wheelDeltaY;p(w,y)};if(sn(o.listenWheelOn)("wheel",m,{passive:!1}),Je){const y=new So({element:o.listenWheelOn,onSwipe:(v,w,b)=>{const S=-w;p(S,b)},cancelEvent:!1,cursor:"",verifyTouchTarget:v=>v instanceof TouchEvent&&!o.shouldIgnore?.()&&!U(v.target,"folders-tabs-scrollable")});ut(()=>{y.removeListeners()})}const g=y=>{e()!==To&&(l(),a(To),y&&oe(y))},f=()=>{r(e(),!1)};return ye(()=>{const y=o.container();y&&(y.classList.toggle("disable-hover",(o.disableHoverWhenFolded?n():!1)||s()),o.skipAnimationClassName&&y.classList.toggle(o.skipAnimationClassName,n()&&!s()))}),ye(()=>{const y=o.container();y&&(sn(y)("transitionstart",v=>v.target===y&&i(!0)),sn(y)("transitionend",v=>v.target===y&&i(!1)))}),{folded:n,unfold:g,fold:f,progress:e,clearAnimation:l,isTransition:s,STATE_FOLDED:Jl,STATE_UNFOLDED:To}}const lg=ce("<div>"),HA=ce("<div><div>"),td=o=>{const[,e]=Xn(o,["onAdditionalScroll"]);let t;const s=(()=>{const n=lg(),a=t;return typeof a=="function"?wt(a,n):t=n,uo(n,e,!1,!0),D(n,()=>o.children),n})(),i=new yr(void 0,void 0,void 0,void 0,t);return o.onAdditionalScroll&&(i.setListeners(),i.onAdditionalScroll=o.onAdditionalScroll),ut(()=>{i.destroy()}),s},QC=o=>{const e=new Rt,[t]=zo(()=>o.peerId,s=>e.update({peerId:s,dialog:!1,onlyFirstName:o.onlyFirstName}).then(()=>!0));return K(()=>t()&&e.element)};function $A(o){const[e,t]=Io(),[s,i]=ne(),[n,a]=ne(),r=K(()=>e.peers);let l,c;const d=K(()=>r().findIndex($=>$.peerId===I.myId)),h=K(()=>{const $=n();return $&&$.width>r().length*y?($.width-r().length*y)/(r().length+1):0}),u=new WeakMap,p=new WeakMap,m=$=>O($);ye(()=>{if(!s())return;const se=()=>{i(void 0)},Y=K(()=>u.get(e.peer)?.querySelector(".avatar"));Od({onExit:se,target:Y})});const g=($,se)=>{if(H()!==G)return m(se);t.resetIndexes(),t.set({peer:$}),i($)},y=74+0*2,v=54,w=3,b=K(()=>Math.min(w,r().length-(d()!==-1?1:0))),S=K(()=>({min:d()===0&&r().length>1?1:0,max:d()===0?b():b()-1})),C=($,se=S())=>{const{min:Y,max:Q}=se;return $<Y||$>Q},P=($,se)=>{const Y=g.bind(null,$),Q=K(()=>{const ge=n(),be=H(),Z=se(),de=h(),Ze=de?0:E,Ne=S(),pe=C(Z,Ne),He=c.left+Ze+Z*y+de*(Z+1);if(ge.left+Ze+Z*y+de*(Z+1)>ge.right)return;const Ae={};pe?Ae["z-index"]=100-Z:Ae["z-index"]=100+b()+1-Z;const Ke=l.right+(o.offsetX||0),We=pe?0:(Ne.max-Z)*16;let Fe=Ke-He+5-We,Ue;pe?(Ae["transform-origin"]="center 43.75%",Fe+=8*(Z<Ne.min?1:-1),Ue=.2):Ue=26.67/48;const Lt=`translateX(${Fe*be*(ke.isRTL?-1:1)}px)`,rs=`scale(${1-be*(1-Ue)})`;return Ae.transform=`${Lt} ${rs}`,{isOut:pe,isLastIn:!pe&&Z===Ne.max,cssProperties:Ae}}),he=Fn({peerId:$.peerId,size:v,props:{onClick:Y},isDialog:!1,withStories:!0,isStoryFolded:q}),le=$.peerId===I.myId,re=(()=>{const ge=HA(),be=ge.firstChild;return Pl(ge,"click",Y,!0),wt(Z=>(u.set($,Z),p.set(Z,$)),ge),D(ge,()=>he.element,be),D(be,()=>le?M("MyStory"):j(QC,{get peerId(){return $.peerId},onlyFirstName:!0})),Ve(Z=>{const de=Qa.ListItem,Ze={[Qa.isRead]:!le&&$.maxReadId&&$.maxReadId>=$.stories[$.stories.length-1].id,[Qa.isMasked]:(()=>{const Be=Q();return Be&&!Be.isOut&&!Be.isLastIn})()},Ne=Q()?.cssProperties,pe=Qa.ListItemName;return de!==Z._v$&&Ce(ge,Z._v$=de),Z._v$2=pa(ge,Ze,Z._v$2),Z._v$3=zi(ge,Ne,Z._v$3),pe!==Z._v$4&&Ce(be,Z._v$4=pe),Z},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0}),ge})();return j(an,{get when(){return Q()||!R()},children:re})},L=-69,E=6,_=92;let k=!1;const x=()=>{const $=H(),se=!k&&A();se?.scrollLeft&&(k=!0,vb(se).then(()=>{k=!1}));const Q=`translateY(${$*L}px)`;return o.setScrolledOn.style.setProperty("--stories-scrolled",$*_+"px"),{transform:Q,"--progress":$}};ye($s(()=>r().length,$=>{$||X()},{defer:!0}));const A=()=>B.firstElementChild;ye(()=>{if(R()||F()){const $=oe,se=A();sn(se)("wheel",$,{capture:!0})}}),ye(()=>{F()||t.toggleSorting("list",!R())});const T=()=>{l=o.foldInto.getBoundingClientRect(),c=o.foldInto.parentElement.getBoundingClientRect(),a(o.foldInto.parentElement.parentElement.getBoundingClientRect())};sn($e)("resize",T),T(),o.resizeCallback?.(T);let B;const{folded:R,unfold:O,fold:X,isTransition:F,progress:H,STATE_UNFOLDED:G}=qC({scrollable:o.getScrollable,container:()=>B,listenWheelOn:o.listenWheelOn,shouldIgnore:()=>!r().length,disableHoverWhenFolded:!0}),z=(()=>{const $=lg(),se=B;return typeof se=="function"?wt(se,$):B=$,D($,j(td,{get children(){const Y=lg();return D(Y,j(ti,{get each(){return r()},children:P})),Ve(Q=>{const he=Qa.List,le={[Qa["space-evenly"]]:!!h()};return he!==Q._v$5&&Ce(Y,Q._v$5=he),Q._v$6=pa(Y,le,Q._v$6),Q},{_v$5:void 0,_v$6:void 0}),Y}})),Ve(Y=>{const Q=Qa.ListContainer,he=x();return Q!==Y._v$7&&Ce($,Y._v$7=Q),Y._v$8=zi($,he,Y._v$8),Y},{_v$7:void 0,_v$8:void 0}),$})();vr(()=>{const $=async he=>{I.managers.appNotificationsManager.toggleStoriesMute(Y.peerId,he),Ee({langPackKey:he?"NotificationsStoryMutedHint":"NotificationsStoryUnmutedHint",langPackArguments:[await Oe({peerId:Y.peerId})]})},se=async he=>{I.managers.appStoriesManager.toggleStoriesHidden(Y.peerId,he),Ee({langPackKey:he?"StoriesMovedToContacts":"StoriesMovedToDialogs",langPackArguments:[await Oe({peerId:Y.peerId})]})};let Y,Q;ln({buttons:[{icon:"stories",text:"SavedStories",onClick:()=>{Ii.createTab(Sl).open()},verify:()=>Q},{icon:"archive",text:"ArchivedStories",onClick:()=>{const he=Ii.createTab(Sl);he.isArchive=!0,he.open()},verify:()=>Q},{icon:"message",text:"SendMessage",onClick:()=>{me.setInnerPeer({peerId:Y.peerId,type:te.Chat})},verify:()=>!Q&&Y.peerId.isUser()},{icon:"channel",text:"OpenChannel2",onClick:()=>{me.setInnerPeer({peerId:Y.peerId,type:te.Chat})},verify:()=>!Y.peerId.isUser()},{icon:"mute",text:"NotificationsStoryMute2",onClick:()=>$(!0),verify:()=>!Q&&I.managers.appNotificationsManager.isPeerStoriesMuted(Y.peerId).then(he=>!he),multiline:!0},{icon:"unmute",text:"NotificationsStoryUnmute2",onClick:()=>$(!1),verify:()=>!Q&&I.managers.appNotificationsManager.isPeerStoriesMuted(Y.peerId),multiline:!0},{icon:"archive",text:"ArchivePeerStories",onClick:()=>se(!0),verify:()=>!Q&&!o.archive},{icon:"unarchive",text:"UnarchiveStories",onClick:()=>se(!1),verify:()=>!Q&&!!o.archive}],listenTo:B,middleware:Ys().get(),findElement:he=>!R()&&U(he.target,Qa.ListItem),onOpen:(he,le)=>{Y=p.get(le),Q=Y.peerId===I.myId},onClose:()=>{Y=void 0}})});const q=K(()=>H()!==G);return K(()=>e.ready&&z)}function YC(o){const[,e]=Xn(o,["foldInto","getScrollable","listenWheelOn","setScrolledOn","offsetX","resizeCallback"]);return j(Nf,Ai(e,{get children(){return j($A,o)}}))}Ui(["click"]);const VA=ce("<table class=table>"),GA=ce('<tr class=table-row><td class="table-cell table-key"></td><td class=table-cell>'),zA=ce("<div class=table-peer>");function XC(o){return(()=>{const e=VA();return D(e,j(ti,{get each(){return o.content},children:([t,s])=>(()=>{const i=GA(),n=i.firstChild,a=n.nextSibling;return D(n,()=>M(t)),D(a,s),i})()})),e})()}function ZC(o){const e=Et(()=>Fn({peerId:o.peerId,size:24}));return(()=>{const t=zA();return Pl(t,"click",o.onClick,!0),D(t,()=>e.element,null),D(t,j(QC,{get peerId(){return o.peerId}}),null),t})()}Ui(["click"]);const KA=ce("<span>"),WA=ce("<div class=popup-stars-pay-padding><div class=popup-stars-pay-images><div class=popup-stars-pay-avatar></div></div><div class=popup-stars-title>"),jA=ce("<div class=popup-stars-subtitle>"),qA=ce("<div class=popup-stars-pay-tos>");class QA extends ee{constructor(e){super("popup-stars popup-stars-pay",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,footer:!0,withConfirm:!0,title:!0}),It(this,e),this.footer.classList.add("abitlarger"),this.result="cancelled";const t=async()=>{const{paymentForm:s}=this;if(this.isReceipt||!s){this.hide();return}const i=rn(this.btnConfirm),n=jt([this.btnConfirm],!0);this.result="pending";const a=this.managers.appPaymentsManager.sendStarsForm(e.inputInvoice,s.form_id);try{await a,this.result="paid",this.hide()}catch(r){let l=!1;r.type==="BALANCE_TOO_LOW"?ee.createPopup(yu,{paymentForm:s,onTopup:async()=>{await this.reloadForm(),t()}}):r.type==="FORM_EXPIRED"?(await this.reloadForm(),l=!0):this.result="failed",n(),i.remove(),l&&t()}};N(this.btnConfirm,t,{listenerSetter:this.listenerSetter})}get form(){return this.paymentForm||this.transaction}hide(){return this.dispatchEvent("finish",this.result),super.hide()}async reloadForm(){this.paymentForm=await this.managers.appPaymentsManager.getPaymentForm(this.inputInvoice)}setPaymentForm(e){this.paymentForm=e,this.isReceipt=!!this.transaction||e._==="payments.paymentReceiptStars",this.construct()}_construct(e,t,s,i,n){const a=this;this.isReceipt||this.header.append(DC()),this.footer.append(this.btnConfirm),this.body.after(this.footer);let r;this.paymentForm?r=this.paymentForm.invoice.prices[0].amount:r=this.transaction.stars,this.isReceipt?this.btnConfirm.append(M("OK")):(this.btnConfirm.append(M("Stars.ConfirmPurchaseButton",[r])),po(this.btnConfirm,"star"));let l,c;if(this.transaction?.extended_media)l=M("StarMediaPurchase");else if(this.paidMedia){const[g,f]=ul(this.paidMedia.extended_media,w=>w._==="messageExtendedMedia"?w.media._!=="messageMediaDocument":w.video_duration===void 0),y=M("Stars.Unlock.Photos",[g.length]),v=M("Stars.Unlock.Videos",[f.length]);l=M("StarsConfirmPurchaseTitle"),c=M("Stars.Unlock",[g.length&&f.length?M("Stars.Unlock.Media",[y,v]):(g.length||f.length)===1?M(g.length?"Stars.Unlock.Photo":"Stars.Unlock.Video"):g.length?y:v,t,M("Stars.Unlock.Stars",[r])])}else this.transaction&&!this.form.title?l=M("Stars.TopUp"):(l=this.isReceipt?_e(this.form.title):M("StarsConfirmPurchaseTitle"),c=this.isReceipt?_e(this.form.description):M("StarsConfirmPurchaseText",[r,_e(this.paymentForm.title),t]));const d=this.transaction?.id??this.paymentForm.transaction_id,h=()=>{Fs(d),Ee({langPackKey:"StarsTransactionIDCopied"})},u=(g,f)=>{oe(f),this.hide(),ee.getPopups(yu)?.[0]?.hide(),this.hideWithCallback(g)},p=n&&Gb(n);p&&(p.textContent=n.replace("https://",""),p.onclick=g=>u(()=>me.openUrl(n),g));const m=this.isReceipt&&[this.peerId?["BoostingTo",ZC({peerId:this.peerId,onClick:()=>{u(()=>{me.setInnerPeer({peerId:this.peerId})})}})]:["Stars.Via",t],this.transaction?.extended_media&&["StarsTransactionMedia",p],["StarsTransactionID",(()=>{const g=KA();return g.$$click=h,D(g,()=>Yt(d,{entities:[{_:"messageEntityCode",length:d.length,offset:0}]})),g})()],["StarsTransactionDate",ws(this.form.date,void 0,!0)]];return(()=>{const g=WA(),f=g.firstChild,y=f.firstChild,v=f.nextSibling;return D(g,e,f),D(f,i,y),y.$$click=async()=>{if(!a.isReceipt||!a.transaction.extended_media)return;const w=a.transaction.extended_media,b=w.map(P=>P.photo||P.document),S=await a.managers.appMessagesManager.generateStandaloneOutgoingMessage(a.peerId);S.media={_:"messageMediaPaidMedia",extended_media:w.map(P=>({_:"messageExtendedMedia",media:P})),stars_amount:0},S.id=yn(a.transaction.msg_id),S.mid=a.transaction.msg_id;const C=b.map((P,L)=>({element:null,mid:0,peerId:0,index:L,message:S}));C[0].element=s,new ho(!0).setSearchContext({peerId:0,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1}).openMedia({message:S,target:C[0].element,fromRight:0,reverse:!1,prevTargets:[],nextTargets:C.slice(1)})},D(y,s),D(v,l),D(g,c&&(()=>{const w=jA();return D(w,c),w})(),null),D(g,(()=>{const w=K(()=>!!a.isReceipt);return()=>w()&&[j(BC,{get stars(){return a.transaction?r:-+r},get isRefund(){return!!a.transaction?.pFlags?.refund}}),j(XC,{get content(){return m.filter(Boolean)}}),(()=>{const b=qA();return D(b,()=>M("Stars.TransactionTOS")),b})()]})(),null),g})()}async construct(){this.paymentForm?this.peerId=this.paymentForm.bot_id.toPeerId(!1):this.transaction.peer._==="starsTransactionPeer"&&(this.peerId=at(this.transaction.peer.peer));const[e,{title:t,media:s},i,n]=await Promise.all([(async()=>{const a=document.createElement("img");return a.classList.add("popup-stars-image"),await Ki(a,`assets/img/${Qw("stars_pay")}.png`),a})(),(async()=>{const a=await NC(this.transaction,this.middlewareHelper.get(),90,this.paidMedia,this.message?this.message.fwdFromId||this.message.peerId:this.peerId);return a.media.classList.add("popup-stars-pay-item"),a})(),(async()=>{})(),(async()=>{if(this.transaction?.extended_media)return this.managers.apiManager.invokeApi("channels.exportMessageLink",{channel:await this.managers.appChatsManager.getChannelInput(this.peerId.toChatId()),id:yn(this.transaction.msg_id)}).then(a=>a.link)})()]);this.body.classList.toggle("is-receipt",this.isReceipt),this.appendSolid(()=>this._construct(e,t,s,i,n)),this.show()}}Ui(["click"]);const YA=!0,XA="assets/img/",ZA=["amex","card","diners","discover","jcb","mastercard","visa","unionpay","mir","logo"];function JC(o){if(ZA.includes(o))return`${XA}${o}.svg`}function Cl(o){const e=o.textEl??new ke.IntlElement({key:o.key??"PaymentInfo.Done"}),t=e.key,s=ze("btn-primary btn-color-primary payment-item-pay");return s.append(e.element),N(s,async()=>{const i=o.onClick();if(!(i instanceof Promise))return;const n=rn(s),a=jt([s],!0);e.compareAndUpdate({key:"PleaseWait"});try{await i}catch(r){r.handled||console.error("payment button error",r),a(),e.compareAndUpdate({key:t}),n.remove()}}),s}class eI{constructor(e={}){this.options=e;const t=this.input=document.createElement("input");t.type="tel",t.classList.add("input-clear");const s=t instanceof HTMLInputElement?1:2,i=()=>{if(r){--r;return}r=s,Zs(t)},n=()=>{setTimeout(()=>{r=s,Zs(t),document.addEventListener("selectionchange",i)},0)},a=()=>{t.addEventListener("focus",n,{once:!0}),document.removeEventListener("selectionchange",i)};let r;t.addEventListener("focusout",a),a()}get value(){return this.input.value}set value(e){this.input.value=e,this.onValue()}onValue(){document.activeElement===this.input&&Zs(this.input),this.setWidth()}setWidth(){const e=fl(this.value,this.options?.fontWeight?`${this.options.fontWeight} ${Mb} ${dl}`:Hh);this.input.style.width=e+"px"}}class gr extends ee{constructor(e){super("popup-payment",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,title:!0}),It(this,e),this.result="cancelled",this.tipButtonsMap=new Map}hide(){return this.dispatchEvent("finish",this.result),super.hide()}setPaymentForm(e){this.paymentForm=e,this.d().catch(t=>{console.error("payment popup error",t),this.hide()})}async d(){this.element.classList.add("is-loading"),this.show();let e=!1;const t=()=>{e||(this.result="paid",e=!0,gi&&gi.hide(),this.hide())},{paymentForm:s,message:i}=this;i&&this.listenerSetter.add(I)("payment_sent",({peerId:ae,mid:Se})=>{i.peerId===ae&&i.mid===Se&&t()});const n=i?.media,a=this.isReceipt??(n?!!n.receipt_msg_id||n.extended_media?._==="messageExtendedMedia":s._==="payments.paymentReceipt"),r=n?n.pFlags.test:s.invoice.pFlags.test,l=s._==="payments.paymentFormStars",c=n?n.photo:s.photo,d=n?n.title:s.title,h=n?n.description:s.description;Zt(this.title,a?"PaymentReceipt":"PaymentCheckout"),r&&this.title.append(" (Test)");const u="payment-item",p=document.createElement("div");p.classList.add(u);const m=u+"-details",g=document.createElement("div");g.classList.add(m);let f;if(c){f=document.createElement("div"),f.classList.add(m+"-photo","media-container-contain");const ae=c.attributes.find(V=>V._==="documentAttributeImageSize"),Se=vs(100,100);if(ae){const ie=vs(ae.w,ae.h).aspectFitted(Se);f.style.width=ie.width+"px",f.style.height=ie.height+"px"}Ks({photo:c,container:f,boxWidth:Se.width,boxHeight:Se.height,size:{_:"photoSizeEmpty",type:""}}),g.append(f)}const y=m+"-lines",v=document.createElement("div");v.classList.add(y);const w=document.createElement("div");w.classList.add(y+"-title");const b=document.createElement("div");b.classList.add(y+"-description");const S=document.createElement("div");S.classList.add(y+"-bot-name"),v.append(w,b,S),kt(w,_e(d)),kt(b,_e(h));const C=new Rt;S.append(C.element),g.append(v),p.append(g),this.scrollable.append(p);const P=document.createElement("div");P.classList.add(u+"-preloader-container"),rn(P,!0),this.scrollable.append(P);const L=this.inputInvoice;let E=s.saved_info||s.info;const _=s.saved_credentials?.[0];let[k,x,A]=await Promise.all([!a&&E&&this.managers.appPaymentsManager.validateRequestedInfo(L,E).catch(ae=>{console.error("validateRequestedInfo",ae,E)}),_&&this.managers.passwordManager.getState(),Oe({peerId:l?Tt:s.provider_id.toPeerId()})]);await C.update({peerId:s.bot_id.toPeerId()}),P.remove(),this.element.classList.remove("is-loading");const T=(ae,Se)=>In(ae,R,Se,YA,!0),{invoice:B}=s,R=B.currency,O=B.pFlags.recurring&&!a,X=!!B.terms_url;await C.update({peerId:s.bot_id.toPeerId()});const F=O||X?await Oe({peerId:s.bot_id.toPeerId()}):void 0;P.remove(),this.element.classList.remove("is-loading");const H=()=>{const ae=document.createElement("div");ae.classList.add(G+"-price");const Se=document.createElement("span"),V=document.createElement("span");return ae.append(Se,V),{label:ae,left:Se,right:V}},G=u+"-prices",z=document.createElement("div");z.classList.add(G);const q=ae=>ae.map(Se=>{const{amount:V,label:ie}=Se,we=H();we.left.append(_e(ie));const Ie=T(V);return we.right.textContent=Ie,we.label}),$=q(B.prices);let se=()=>0,Y=0;const Q=()=>ge+se()+Y,he=()=>{const ae=T(Q());re.right.textContent=ae,le.compareAndUpdate({key:"PaymentCheckoutPay",args:[ae]})},le=new ke.IntlElement,re=H();re.label.classList.add("is-total"),Zt(re.left,"PaymentTransactionTotal");const ge=io(B.prices.map(({amount:ae})=>+ae),0),be=B.max_tip_amount!==void 0&&!a||!!s.tip_amount;if(be){const ae=u+"-tips",Se=Xb[R];se=()=>+we.value.replace(/\D/g,"");const V=Re=>{Re=Math.min(+Re,+B.max_tip_amount);const tt=T(Re,!0);we.value=tt,Qe?.();const ct=this.tipButtonsMap.get(Re);ct&&ct.classList.add("active"),he()},ie=H();Zt(ie.left,a?"PaymentTip":"PaymentTipOptional");const we=new eI({fontWeight:500}),{input:Ie}=we;Ie.classList.add("input-clear",ae+"-input"),ie.right.append(Ie),a?ie.label.classList.add("disable-hover"):ie.label.style.cursor="text",ie.label.addEventListener("mousedown",Re=>{Ns(Re.target,Ie)||Zs(Ie)}),Ie.addEventListener("input",()=>{V(se())});const Te=[Se.native||Se.symbol,Se.space_between?" ":""];Se.symbol_left||Te.reverse(),ie.right[Se.symbol_left?"prepend":"append"](Te.join("")),$.push(ie.label);let Qe;if(a)V(s.tip_amount);else{const Re=document.createElement("div");Re.classList.add(ae);const tt=ae+"-tip",ct=B.suggested_tip_amounts.map(Mt=>{const Ht=ze(tt,{noRipple:!0});return Ht.textContent=T(Mt),this.tipButtonsMap.set(+Mt,Ht),Ht});Qe=()=>{const Mt=Re.querySelector(".active");Mt&&Mt.classList.remove("active")},N(Re,Mt=>{const Ht=U(Mt.target,tt);if(!Ht)return;let li=0;if(Ht.classList.contains("active"))Ht.classList.remove("active");else{Qe(),Ht.classList.add("active");for(const[ts,St]of this.tipButtonsMap)if(St===Ht){li=ts;break}}V(li)}),V(0),Re.append(...ct),$.push(Re)}}else he();$.push(re.label),z.append(...$),p.append(z);const Z=async(ae,Se)=>{const V=document.createElement("img");V.classList.add("media-photo"),await Ki(V,JC(Se));let ie=ae.media;ie?dt(ie,V):(ie=ae.createMedia("small"),ie.classList.add("media-container-cover"),ie.append(V)),ae.container.classList.remove("row-with-icon")},de=ae=>{ae.titleLangKey&&(ae.subtitleLangKey=ae.titleLangKey),ae.noWrap=!0;const Se=new ve(ae);return Se.container.classList.add(u+"-row"),ae.titleLangKey&&Se.subtitle.classList.add("hide"),Se},Ze=(ae,Se)=>{if(ae.title.textContent=Se,!Se){const V=ke.weakMap.get(ae.subtitle.firstElementChild);ae.title.append(M(V.key))}ae.subtitle.classList.toggle("hide",!Se)},Ne=ae=>{let Se,V,ie;"title"in ae?(Se=ae.title.split(" ").shift(),V=ae.title,ie=ae.icon):(Se=$w(ae.cardNumber),V=Se+" *"+ae.cardNumber.split(" ").pop()),De.container.querySelector(`.${_a("card_outline")}`)?.remove(),Z(De,ie||Se.toLowerCase()),Ze(De,V)},pe=async()=>{ee.createPopup(nM,s,await this.managers.appUsersManager.getSelf(),Be).addEventListener("finish",({token:ae,card:Se})=>{He=ae,Be=Se,Ne(Se)})};let Be,He;const De=de({titleLangKey:"PaymentCheckoutMethod",clickable:a?void 0:pe,icon:"card_outline"});De.container.classList.add(u+"-method-row"),_?Ne(_):s.credentials_title&&Ne({title:s.credentials_title});const Ae=de({title:A,subtitleLangKey:"PaymentCheckoutProvider"}),Ke=es({middleware:this.middlewareHelper.get(),size:32,peerId:l?Tt:s.provider_id.toPeerId()});Ae.createMedia("small").append(Ke.node);let We,Fe,Ue,nt,Lt,At,rs,Cs;const os=B.pFlags.shipping_address_requested?ae=>{if(!ae){Lt.subtitle.classList.add("hide"),dt(Lt.title,M("PaymentShippingAddress"));return}const Se=ae.shipping_address;Ze(We,[Se.city,Se.street_line1,Se.street_line2].filter(Boolean).join(", ")),Lt.container.classList.toggle("hide",!k?.shipping_options&&!a)}:void 0,js=ae=>{os&&os?.(ae),Fe&&Ze(Fe,ae.name),Ue&&Ze(Ue,ae.email),nt&&Ze(nt,ae.phone&&"+"+_l(ae.phone).formatted)};if(a||(rs=ae=>{ee.createPopup(rM,s,L,ae).addEventListener("finish",({shippingAddress:Se,requestedInfo:V})=>{k=V,E=s.saved_info=Se,js(Se)})}),B.pFlags.shipping_address_requested){const ae=ie=>{const we=new Zu(this.scrollable,void 0,!0);if(we.save(),Se&&Se.forEach(Te=>Te.remove()),!ie){Y=0,he(),we.restore(),this.onContentUpdate();return}At=ie,Ze(Lt,ie.title),Y=io(ie.prices.map(({amount:Te})=>+Te),0),Se=q(ie.prices);let Ie=re.label;be&&(Ie=Ie.previousElementSibling,a||(Ie=Ie.previousElementSibling)),Se.forEach(Te=>Ie.parentElement.insertBefore(Te,Ie)),he(),we.restore(),this.onContentUpdate()};We=de({icon:"location",titleLangKey:"PaymentShippingAddress",clickable:!a&&rs.bind(null,void 0)});let Se;Lt=de({icon:"shipping",titleLangKey:"PaymentCheckoutShippingMethod",clickable:!a&&(Cs=()=>{ee.createPopup(oM,s,k,At).addEventListener("finish",ie=>{ae(ie)})})}),Lt.container.classList.add("hide");const V=s.shipping;V&&ae(V)}B.pFlags.name_requested&&(Fe=de({icon:"newprivate",titleLangKey:"PaymentCheckoutName",clickable:!a&&rs.bind(null,"name")})),B.pFlags.email_requested&&(Ue=de({icon:"mention",titleLangKey:"PaymentShippingEmailPlaceholder",clickable:!a&&rs.bind(null,"email")})),B.pFlags.phone_requested&&(nt=de({icon:"phone",titleLangKey:"PaymentCheckoutPhoneNumber",clickable:!a&&rs.bind(null,"phone")})),E&&js(E);const mi=[De,Ae,We,Lt,Fe,Ue,nt].filter(Boolean),oi=(O||X)&&new pt({text:O?"Payments.Recurrent.Accept":"Payments.Terms.Accept",textArgs:[Yt(B.terms_url),F]}),si=oi&&de({checkboxField:oi}),cn=oi?[document.createElement("hr"),si.container]:[];this.scrollable.append(...[document.createElement("hr"),...mi.map(ae=>ae.container),...cn].filter(Boolean));let gi,J;const xe=()=>{const ae=B.pFlags.name_requested&&!E?.name?"name":B.pFlags.email_requested&&!E?.email?"email":B.pFlags.phone_requested&&!E?.phone?"phone":void 0;if(B.pFlags.shipping_address_requested)if(k){if(!At&&k.shipping_options){Cs();return}}else{rs();return}else if(ae){rs(ae);return}if(!Be&&!J){if(!_){pe();return}Promise.resolve(x??this.managers.passwordManager.getState()).then(Se=>{ee.createPopup(aM,_.title,Se).addEventListener("finish",V=>{x=void 0,J=V,fs(Ge);const ie=V.valid_until-Ms(!0)-5;setTimeout(()=>{J===V&&(J=void 0)},ie*1e3)})});return}return Promise.resolve().then(async()=>{const Se=J?{_:"inputPaymentCredentialsSaved",id:_.id,tmp_password:J.tmp_password}:{_:"inputPaymentCredentials",data:{_:"dataJSON",data:JSON.stringify(He.token?He:{type:He.type,id:He.id})},pFlags:{save:Be.save||void 0}};try{this.result="pending";const V=await this.managers.appPaymentsManager.sendPaymentForm(L,s.form_id,k?.id,At?.id,Se,se());V._==="payments.paymentResult"?t():(gi=ee.createPopup(iM,V.url,!n?.extended_media),gi.addEventListener("finish",()=>{gi=void 0,t()}),await new Promise((ie,we)=>{gi.addEventListener("close",()=>{if(gi=void 0,e)ie();else{const Ie=new Error("payment not finished");Ie.handled=!0,we(Ie),this.result="failed"}})}))}catch(V){throw V.type==="BOT_PRECHECKOUT_TIMEOUT"?(Ee({langPackKey:"Error.AnError"}),V.handled=!0):V.type==="TMP_PASSWORD_INVALID"?(x=J=void 0,fs(Ge),V.handled=!0):this.result="failed",V}})},je=()=>{Ge.disabled=!!(oi&&!oi.checked)};let Ge;a?Ge=Cl({onClick:()=>this.hide(),key:"Done"}):Ge=Cl({onClick:xe,textEl:le}),je(),oi&&oi.input.addEventListener("change",je),this.body.append(this.btnConfirmOnEnter=Ge),this.onContentUpdate()}static async create(e){let t;!e.paymentForm&&!e.transaction?e.isReceipt?t=I.managers.appPaymentsManager.getPaymentReceipt(e.message.peerId,e.message.media.receipt_msg_id||e.inputInvoice.msg_id):t=I.managers.appPaymentsManager.getPaymentForm(e.inputInvoice):t=Promise.resolve(e.paymentForm);const s=await t,i=e.transaction||s._==="payments.paymentFormStars"||s._==="payments.paymentReceiptStars"?QA:gr,n=ee.createPopup(i,e);return n.setPaymentForm(s),n}}function Gv(o,e){return o.map((s,i)=>({idx:i,diff:Math.abs(s-e)})).sort((s,i)=>s.diff-i.diff)[0]}class zv extends Xt{async init({chatId:e,invite:t}){this.setTitle(t?"InviteLinks.Edit":"NewLink"),this.confirmBtn=Ei({className:"is-visible",icon:"check"}),this.content.append(this.confirmBtn),N(this.confirmBtn,async()=>{$g(this.confirmBtn);const l=n.value,c=l instanceof Date?l.getTime()/1e3|0:l?Ms(!0)+l:0,d=s.value,h=i.checked,u=h?0:a.value??0;let p;t?p=(await this.managers.appChatInvitesManager.editExportedChatInvite({chatId:e,link:t.link,expireDate:c,requestNeeded:h,title:d,usageLimit:u})).invite:p=await this.managers.appChatInvitesManager.exportChatInvite({chatId:e,title:d,requestNeeded:h,usageLimit:u,expireDate:c}),this.eventListener.dispatchEvent("finish",p),this.close()},{listenerSetter:this.listenerSetter});let s;{const l=new Pe({caption:"LinkNameHelp"}),c=document.createElement("div");c.classList.add("input-wrapper"),s=new _t({label:"LinkNameHint",maxLength:32}),t?.title&&s.setOriginalValue(t.title),c.append(s.container),l.content.append(c),this.scrollable.append(l.container)}let i;if(await this.managers.appChatsManager.isBroadcast(e)){const l=new Pe({caption:"ApproveNewMembersDescription"}),c=new ve({titleLangKey:"ApproveNewMembers",checkboxField:i=new pt({toggle:!0})});l.content.append(c.container),this.scrollable.append(l.container)}let n;{const l=new Pe({name:"LimitByPeriod",caption:"TimeLimitHelp"}),c=n=new qh({generateStep:g=>{const f=yo(g instanceof Date?(g.getTime()/1e3|0)-Ms(!0):g,1);return[kl(f,!1),g]},generateSteps:g=>[...g.map(c.generateStep),["∞",void 0]],onValue:g=>{if(!g)u();else{let f;g instanceof Date?f=g:(f=new Date,f.setSeconds(f.getSeconds()+g)),u(f.getTime()/1e3)}},middleware:this.middlewareHelper.get()}),d=new ve({titleLangKey:"EditInvitation.ExpiryDate",titleRightSecondary:!0,clickable:()=>{let g;const f=c.value;f?g=new Date(f instanceof Date?f:Ms()+f*1e3):(g=new Date,g.setDate(g.getDate()+7)),new If({initDate:g,onPick:h,btnConfirmLangKey:"Save"}).show()},listenerSetter:this.listenerSetter}),h=g=>{const f=g-Ms(!0),y=Gv(p,f),v=m.slice();v[y.idx]=c.generateStep(new Date(g*1e3)),c.setSteps(v,y.idx)},u=g=>{g?d.titleRight.replaceChildren(ws(g)):d.titleRight.replaceChildren(M("EditInvitation.Never"))},p=[3600,86400,86400*7],m=c.generateSteps(p);c.setSteps(m,m.length-1),t&&t.expire_date&&t.expire_date>Ms(!0)&&h(t.expire_date),l.content.append(c.container,d.container),this.scrollable.append(l.container)}let a,r;{const l=r=new Pe({name:"LimitNumberOfUses",caption:"UsesLimitHelp"}),c=a=new qh({generateStep:w=>[""+w,w],generateSteps:w=>[...w.map(c.generateStep),["∞",void 0]],onValue:w=>{f(w)},middleware:this.middlewareHelper.get()}),d=new ve({titleLangKey:"EditInvitation.NumberOfUsers",titleRightSecondary:!0,clickable:!0,listenerSetter:this.listenerSetter,noRipple:!0}),h=new eI,{input:u}=h;this.listenerSetter.add(d.container)("mousedown",w=>{c.value||m(y[0]),Ns(w.target,u)||Zs(u)});const p=()=>{let w=h.value;const b=!w.trim();w=w.replace(/\D/g,"");const S=Kt(b?0:+w,y[0],9999);b||(h.value=""+S),g=!0,m(S)};this.listenerSetter.add(u)("input",p);const m=w=>{const b=Gv(y,w),S=v.slice();S[b.idx]=c.generateStep(w),c.setSteps(S,b.idx)};let g=!1;const f=w=>{if(g){g=!1;return}w?(h.value=""+w,d.titleRight.replaceChildren(u)):d.titleRight.replaceChildren(M("EditInvitation.Unlimited"))},y=[1,10,50,100],v=c.generateSteps(y);if(c.setSteps(v,v.length-1),t?.usage_limit){const w=Math.max(y[0],t.usage_limit-(t.usage||0));f(w),m(w)}l.content.append(c.container,d.container),this.scrollable.append(l.container)}i&&(this.listenerSetter.add(i.input)("change",()=>{r.container.classList.toggle("hide",i.checked)}),t&&(i.checked=t?.pFlags?.request_needed))}}function cg(o){return!(o.pFlags.revoked||o.expire_date&&o.expire_date<=Ms(!0)||o.usage_limit&&o.usage_limit<=(o.usage||0))}class tI extends xd{constructor(e){super({...e}),this.options=e,e.withSubtitle&&(this.subtitle=document.createElement("div"),this.subtitle.classList.add("invite-link-subtitle","hide"),this.container.append(this.subtitle))}setChatInvite(e){const t=typeof e=="string",s=typeof e=="string"?e:void 0;this.setUrl(t?"t.me/"+s:e.link),this.subtitle&&(!t&&e?.usage&&this.subtitle.replaceChildren(M("InviteLink.JoinedNew",[e.usage])),this.subtitle.classList.toggle("hide",t||!e?.usage));let i;t||(e.pFlags.revoked?(this.onButtonClick=()=>this.options.actions.deleteLink(),i="DeleteLink"):cg(e)||(this.onButtonClick=()=>this.options.actions.editLink(),i="InviteLinks.Reactivate")),i||(i="ShareLink",this.onButtonClick=void 0),this.buttonText.replaceChildren(M(i))}}class sd extends Xt{static getInitArgs(e,t){return{animationData:!t&&_s.loadAnimationFromURLManually("UtyanLinks"),invites:I.managers.appChatInvitesManager.getExportedChatInvites({chatId:e,adminId:t}),invitesRevoked:I.managers.appChatInvitesManager.getExportedChatInvites({chatId:e,adminId:t,revoked:!0}),adminsInvites:!t&&I.managers.appChatInvitesManager.getAdminsWithInvites(e),chatFull:I.managers.appProfileManager.getChatFull(e)}}async init({chatId:e,adminId:t,p:s=sd.getInitArgs(e,t)}){this.chatId=e,this.adminId=t,this.actions={};const i=[],n=this.middlewareHelper.get(),[a,r]=await Promise.all([this.managers.appChatsManager.getChat(this.chatId),s.chatFull]),l=ui(a);this.setTitle("InviteLinks"),this.container.classList.add("chat-folders-container","chat-discussion-container");let c,d;this.adminId||(c=document.createElement("div"),c.classList.add("sticker-container"),d=document.createElement("div"),d.classList.add("caption"),d.append(M("ChannelLinkInfo")));const h=A=>A.title?_e(A.title):vo(A.link.split("://").pop());let u,p,m,g,f;const y=this.menuButtons=[{icon:"copy",text:"CopyLink",onClick:()=>u.copyLink(p?.link),verify:()=>!p?.pFlags?.revoked},{icon:"forward",text:"ShareLink",onClick:()=>{const A=p?.link||u.url;u.shareLink(A)},verify:()=>p?cg(p):!0},{icon:"edit",text:"InviteLinks.Edit",onClick:this.actions.editLink=async()=>{const A=m,T=this.slider.createTab(zv);T.eventListener.addEventListener("finish",B=>{A.destroy(),A.row.container.replaceWith(_(B).container)}),await T.open({chatId:this.chatId,invite:p}),f&&this.slider.removeTabFromHistory(f)},verify:()=>p&&!p.pFlags.revoked},{icon:"delete",className:"danger",text:"RevokeLink",onClick:this.actions.revokeLink=async()=>{const A=m;await Ct({titleLangKey:"RevokeLink",descriptionLangKey:"RevokeAlert",button:{langKey:"RevokeButton",isDanger:!0}});const T=A?.invite||g,B=await this.managers.appChatInvitesManager.editExportedChatInvite({chatId:this.chatId,link:T.link,revoked:!0}),R=B.invite,O=B.new_invite;if(A)O&&A.row.container.replaceWith(_(O).container),S.content.prepend(A.row.container),A.update(R);else{const X=_(R);S.content.prepend(X.container),g=O,u.setChatInvite(g)}k(),f?.close()},verify:()=>p?!p.pFlags.revoked:!!g},{icon:"delete",className:"danger",text:"DeleteLink",onClick:this.actions.deleteLink=()=>{const A=m;this.managers.appChatInvitesManager.deleteExportedChatInvite(this.chatId,A.invite.link).then(()=>{A.destroy(!0),k(),f?.close()})},verify:()=>!!p?.pFlags?.revoked}];let v;{const A=v=new Pe({name:"InviteLink",caption:this.adminId?"ManageLinks.Admin.Permanent.Desc":void 0,captionArgs:this.adminId?await Promise.all([Oe({peerId:this.adminId.toPeerId(!1)}),Oe({peerId:this.chatId.toPeerId(!0)})]):void 0});u=new tI({buttons:y,listenerSetter:this.listenerSetter,actions:this.actions,withSubtitle:!0}),N(u.subtitle,()=>{C(g)},{listenerSetter:this.listenerSetter}),A.content.append(u.container)}let w;{const A=w=new Pe({name:this.adminId?"LinksCreatedByThisAdmin":"InviteLinks.Additional"});if(!this.adminId){const T=ze("btn-primary btn-transparent primary",{icon:"plus",text:"CreateNewLink"});N(T,()=>{const B=this.slider.createTab(zv);B.eventListener.addEventListener("finish",R=>{const O=_(R);g?A.content.prepend(O.container):A.content.firstElementChild.after(O.container)}),B.open({chatId:this.chatId})},{listenerSetter:this.listenerSetter}),A.content.append(T),A.content=A.generateContentElement()}}let b;if(!this.adminId){const A=b=new Pe({name:"LinksCreatedByOtherAdmins"}),T=s.adminsInvites.then(B=>{let{admins:R}=B;if(R=R.filter(F=>F.admin_id.toPeerId(!1)!==I.myId),!R.length){A.container.classList.add("hide");return}const O=Xe.createChatList(),X=[];return R.forEach(F=>{const H=F.admin_id.toPeerId(!1),{dom:G}=Xe.addDialogNew({peerId:H,container:O,rippleEnabled:!0,avatarSize:"abitbigger",append:!0,loadPromises:X,wrapOptions:{middleware:this.middlewareHelper.get()}});G.lastMessageSpan.append(M("InviteLinkCount",[F.invites_count]))}),N(O,F=>{const H=U(F.target,"chatlist-chat");if(!H)return;const G=H.dataset.peerId.toPeerId();this.slider.createTab(sd).open({chatId:this.chatId,adminId:G.toUserId()})},{listenerSetter:this.listenerSetter}),A.content.append(O),Promise.all(X)},()=>{A.container.remove()});i.push(T)}let S;{const A=S=new Pe({name:"RevokedLinks"}),T=ze("btn-primary btn-transparent danger",{icon:"delete",text:"DeleteAllRevokedLinks"});N(T,async()=>{await Ct({titleLangKey:"DeleteAllRevokedLinks",descriptionLangKey:"ManageLinks.DeleteAll.Confirm",button:{langKey:"Delete",isDanger:!0}});const B=jt(T,!0);await this.managers.appChatInvitesManager.deleteRevokedExportedChatInvites(this.chatId,this.adminId),B(),Array.from(A.content.children).forEach(R=>{L.get(R).destroy(!0)}),k()},{listenerSetter:this.listenerSetter}),A.content.append(T),A.content=A.generateContentElement()}this.scrollable.append(...[c,d,v.container,w.container,b?.container,S.container].filter(Boolean));const C=A=>{const T=f=this.slider.createTab(FP);T.eventListener.addEventListener("close",()=>{f=m=p=void 0}),T.open(this.chatId,A,this,m?.update)};N(this.scrollable.container,A=>{const T=U(A.target,"is-link");T&&(m=L.get(T),p=m.invite,C(p))},{listenerSetter:this.listenerSetter}),ln({buttons:y,listenTo:this.scrollable.container,findElement:A=>{const T=U(A.target,"is-link");return T&&(m=L.get(T),p=m.invite),T},onClose:()=>m=p=void 0,middleware:n,listenerSetter:this.listenerSetter});const P=c&&s.animationData.then(async A=>{const T=await A({container:c,loop:!0,autoplay:!0,width:120,height:120});return _s.waitForFirstFrame(T)}),L=new Map,E=new Set,_=A=>{const T=new Aw;T.title.replaceChildren(h(A)),T.container.classList.add("is-link"),!A.expire_date&&!A.pFlags.revoked&&T.container.classList.add("active");let B;const R=G=>{B?.(),L.delete(T.container),G&&T.container.remove()},O=G=>{G&&(A=X.invite=G);const z=[],q=A.usage||0,$=A.requested||0,se=Ms(!0),Y=A.expire_date,Q=Y&&Y<=se,he=q&&q>=A.usage_limit,le=Y?Math.max(0,Y-se):void 0;if(A.pFlags.revoked?(z.push(M("InviteLink.JoinedRevoked"),M("ExportedInvitation.Status.Revoked")),T.media.style.removeProperty("--color"),T.container.classList.remove("active","is-expired"),F&&(F.parentElement.remove(),F=void 0),B?.()):q?(z.push(M("InviteLink.JoinedNew",[q])),he?(z.push(M("InviteLinks.LimitReached")),T.container.classList.add("is-expired")):A.usage_limit?z.push(M("PeopleJoinedRemaining",[A.usage_limit-q])):$&&z.push(M("JoinRequests",[$]))):$?z.push(M("JoinRequests",[$])):A.usage_limit&&!Q?z.push(M("CanJoin",[A.usage_limit])):z.push(M(Q?"InviteLink.JoinedRevoked":"Chat.VoiceChat.JoinLink.Participants_ZeroValueHolder")),!A.pFlags.revoked&&Y&&(Q?(T.container.classList.add("is-expired"),z.push(M("ExportedInvitation.Status.Expired")),B?.()):z.push(M("InviteLink.Sticker.TimeLeft",[Qb(le)]))),!A.pFlags.revoked&&(Y&&!Q||A.usage_limit&&!he)){const re=A.usage_limit?q/A.usage_limit:void 0,ge=Y?1-le/(Y-(A.start_date||A.date)):void 0,be=Math.max(re??0,ge??0),Z=_n(Ls.getProperty("green-color")),de=_n(Ls.getProperty("danger-color")),Ze=oc(de,Z,be),Ne=$h(...Ze);if(Ne.s=Math.max(55,Ne.s),T.media.style.setProperty("--color",_L(Ne)),F&&(H??(H=F.getTotalLength()),F.style.strokeDasharray=`${H*(1-be)}, ${H}`,Q)){const pe=()=>{Be.parentElement.remove()},Be=F;F=void 0,setTimeout(pe,400)}}T.subtitle.replaceChildren(...mo(z," • "))},X={row:T,invite:A,update:O,destroy:R};L.set(T.container,X);let F,H=131.0966339111328;return(A.expire_date||A.usage_limit)&&cg(A)&&(A.expire_date&&(B=()=>{E.delete(O)},E.add(O),n.onDestroy(B)),T.media.insertAdjacentHTML("beforeend",`
<svg class="usernames-username-icon-svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 46 46">
<circle class="usernames-username-icon-circle" cx="23" cy="23" r="21"/>
</svg>
`),F=T.media.lastElementChild.firstElementChild),O(),T},k=()=>{S.container.classList.toggle("hide",!S.content.childElementCount)},x=Promise.all([s.invites,s.invitesRevoked]).then(([A,T])=>{this.adminId?g=A.invites[0]:l.length||(g=r.exported_invite),u.setChatInvite(g||l[0]),[[A,w],[T,S]].forEach(([O,X])=>{O.invites.forEach(F=>{if(g?.link===F.link)return;const H=_(F);X.content.append(H.container)})}),k();const R=setInterval(()=>{E.forEach(O=>O())},1e3);n.onDestroy(()=>{L.forEach(({destroy:O})=>O()),clearInterval(R)}),this.listenerSetter.add(I)("theme_changed",()=>{L.forEach(({update:O})=>O())})});return i.push(P,x),Promise.all(i)}}class Kv extends Dt{async _init(){this.listenerSetter.removeAll(),this.container.classList.add("edit-peer-container","edit-group-container"),this.setTitle("Edit");let[e,t,s,i,n,a,r,l,c,d,h,u,p,m,g]=await Promise.all([this.managers.appProfileManager.getChatFull(this.chatId,!0),this.managers.appChatsManager.getChat(this.chatId),this.managers.appChatsManager.isBroadcast(this.chatId),this.managers.appChatsManager.isChannel(this.chatId),this.managers.appChatsManager.hasRights(this.chatId,"change_type"),this.managers.appChatsManager.hasRights(this.chatId,"change_permissions"),this.managers.appChatsManager.hasRights(this.chatId,"manage_topics"),this.managers.appChatsManager.hasRights(this.chatId,"change_permissions"),this.managers.appChatsManager.hasRights(this.chatId,"change_info"),this.managers.appChatsManager.hasRights(this.chatId,"delete_chat"),this.managers.appChatsManager.hasRights(this.chatId,"post_messages"),this.managers.appChatsManager.hasRights(this.chatId,"invite_links"),this.managers.appChatsManager.hasRights(this.chatId,"invite_users"),this.managers.apiManager.getAppConfig(),this.managers.appReactionsManager.getAvailableReactions()]);this.scrollable.replaceChildren();const f={full:[],basic:[]},y=(b,S="basic")=>{f[S].push(b)};this.listenerSetter.add(I)("chat_update",async b=>{this.chatId===b&&(t=await this.managers.appChatsManager.getChat(this.chatId),f.basic.forEach(S=>S()))}),this.listenerSetter.add(I)("chat_full_update",async b=>{this.chatId===b&&(e=await this.managers.appProfileManager.getCachedFullChat(b)||e||await this.managers.appProfileManager.getChatFull(b),f.full.forEach(S=>S()))});const v=this.chatId.toPeerId(!0),w=!!t.admin_rights;{const b=new Pe({noDelimiter:!0,caption:"PeerInfo.SetAboutDescription"}),S=[],C=document.createElement("div");C.classList.add("input-wrapper"),this.chatNameInputField=new _t({label:s?"EnterChannelName":"CreateGroup.NameHolder",name:"chat-name",maxLength:255,required:!0,canBeEdited:c}),this.descriptionInputField=new _t({label:"DescriptionPlaceholder",name:"chat-description",maxLength:255,withLinebreaks:!0,canBeEdited:c}),this.chatNameInputField.setOriginalValue(t.title),this.descriptionInputField.setOriginalValue(e.about),C.append(this.chatNameInputField.container,this.descriptionInputField.container),S.push(this.chatNameInputField,this.descriptionInputField),this.editPeer=new kd({peerId:v,inputFields:S,listenerSetter:this.listenerSetter,popupOptions:{isForum:t.pFlags.forum},middleware:this.middlewareHelper.get()}),this.content.append(this.editPeer.nextBtn),c||(this.editPeer.avatarElem.node.classList.remove("avatar-placeholder"),this.editPeer.avatarEdit.container.replaceChildren(this.editPeer.avatarElem.node),this.editPeer.avatarEdit.container.classList.add("disable-hover")),b.content.append(this.editPeer.avatarEdit.container,C),this.scrollable.append(b.container)}{const b=new Pe({caption:!0});if(n){const S=new ve({titleLangKey:s?"ChannelType":"GroupType",clickable:()=>{const P=this.slider.createTab(wP);P.chatId=this.chatId,P.chatFull=e,P.open()},icon:"lock",listenerSetter:this.listenerSetter}),C=()=>{let P;const L=ui(t)[0];s?P=L?"TypePublic":"TypePrivate":P=L?"TypePublicGroup":"TypePrivateGroup",S.subtitle.replaceChildren(M(P))};C(),y(C),b.content.append(S.container)}if(u){const S=new ve({titleLangKey:"InviteLinks",navigationTab:{constructor:sd,slider:this.slider,getInitArgs:()=>({chatId:this.chatId,p:sd.getInitArgs(this.chatId)})},icon:"link",listenerSetter:this.listenerSetter,subtitle:!0}),C=()=>{S.subtitle.textContent="1"};C(),y(C,"full"),b.content.append(S.container)}if(p&&w){const S=new ve({titleLangKey:s?"SubscribeRequests":"MemberRequests",navigationTab:{constructor:Zm,getInitArgs:()=>this.chatId,slider:this.slider},icon:"adduser",listenerSetter:this.listenerSetter,subtitle:!0}),C=()=>{const P=e.requests_pending;S.subtitle.textContent=""+P,S.container.classList.toggle("hide",!P)};C(),y(C,"full"),b.content.append(S.container)}if(c&&w){const S=new ve({titleLangKey:"Reactions",icon:"reactions",navigationTab:{constructor:Qh,slider:this.slider,getInitArgs:()=>({chatId:this.chatId,p:Qh.getInitArgs(this.chatId)})},listenerSetter:this.listenerSetter}),C=g.filter(L=>!L.pFlags.inactive).length,P=()=>{const L=e.available_reactions??{_:"chatReactionsNone"};if(L._==="chatReactionsSome"){const E=L.reactions.length;E===C?dt(S.subtitle,M("ReactionsAll")):S.subtitle.textContent=E+"/"+C}else dt(S.subtitle,M(L._==="chatReactionsAll"?"ReactionsAll":"Checkbox.Disabled"))};P(),y(P,"full"),b.content.append(S.container)}if(a&&!s){const S=["send_stickers","send_polls","send_photos","send_videos","send_roundvideos","send_audios","send_voices","send_docs","send_plain","embed_links","invite_users","pin_messages","change_info"],C=new ve({titleLangKey:"ChannelPermissions",clickable:()=>{const L=this.slider.createTab(kP);L.chatId=this.chatId,L.open()},icon:"permissions",listenerSetter:this.listenerSetter}),P=()=>{C.subtitle.textContent=S.reduce((L,E)=>L+ +fa(t,E,t.default_banned_rights),0)+"/"+S.length};P(),y(P),b.content.append(C.container)}if(c&&w){const S=new ve({icon:"comments",titleLangKey:s?"PeerInfo.Discussion":"LinkedChannel",subtitle:!0,navigationTab:{constructor:Xh,getInitArgs:()=>({chatId:this.chatId,linkedChatId:e.linked_chat_id,p:Xh.getInitArgs()}),slider:this.slider},listenerSetter:this.listenerSetter}),C=async()=>{const P=e.linked_chat_id;let L;P?L=await Oe({peerId:P.toPeerId(!0)}):L=M("PeerInfo.Discussion.Add"),s||S.container.classList.toggle("hide",!P),S.subtitle.replaceChildren(L)};await C(),y(C,"full"),b.caption.replaceChildren(M("DiscussionInfo")),b.content.append(S.container)}if(r&&w&&(t.participants_count>=m.forum_upgrade_participants_min||t.pFlags.forum)&&!s){const S=new ve({checkboxField:new pt({toggle:!0}),titleLangKey:"Topics",clickable:P=>{if(e.linked_chat_id){Ee({langPackKey:"ChannelTopicsDiscussionForbidden"}),oe(P);return}},icon:"topics",listenerSetter:this.listenerSetter}),C=()=>{const P=!!t.pFlags.forum;this.editPeer.avatarElem.node.parentElement.classList.toggle("is-forum",P),S.checkboxField.setValueSilently(P)};this.listenerSetter.add(S.checkboxField.input)("change",P=>{if(!P.isTrusted)return;const L=this.managers.appChatsManager.toggleForum(this.chatId,S.checkboxField.checked);S.disableWithPromise(L)}),C(),y(C),y(C,"full"),b.caption.replaceChildren(M("ForumToggleDescription")),b.content.append(S.container)}b.caption.classList.toggle("hide",!b.caption.childElementCount),b.content.childElementCount&&this.scrollable.append(b.container),N(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0;const S=[],C=this.chatId;this.chatNameInputField.isValidToChange()&&S.push(this.managers.appChatsManager.editTitle(C,this.chatNameInputField.value)),this.descriptionInputField.isValidToChange()&&S.push(this.managers.appChatsManager.editAbout(C,this.descriptionInputField.value)),this.editPeer.uploadAvatar&&S.push(this.editPeer.uploadAvatar().then(P=>this.managers.appChatsManager.editPhoto(C,P))),Promise.race(S).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()})},{listenerSetter:this.listenerSetter})}{const b=new Pe({});if(l){const S=new ve({titleLangKey:"PeerInfo.Administrators",subtitle:!0,icon:"admin",navigationTab:{constructor:Yh,slider:this.slider,getInitArgs:()=>({chatId:this.chatId,p:Yh.getInitArgs(this.chatId)})},listenerSetter:this.listenerSetter}),C=()=>{S.subtitle.textContent=""+(e.admins_count||1)};C(),y(C,"full"),b.content.append(S.container)}{const S=new ve({titleLangKey:s?"PeerInfo.Subscribers":"GroupMembers",icon:"newgroup",clickable:()=>{this.slider.createTab(xP).open(this.chatId)},listenerSetter:this.listenerSetter,subtitle:!0}),C=()=>{const P=kw(e);S.subtitle.textContent=Ha(P)};C(),y(C,"full"),b.content.append(S.container)}if(a){const S=new ve({titleLangKey:"ChannelBlockedUsers",subtitle:!0,icon:"deleteuser",clickable:()=>{this.slider.createTab(AP).open(this.chatId)},listenerSetter:this.listenerSetter}),C=()=>{const P=e.kicked_count||0;P?S.subtitle.textContent=Ha(P):S.subtitle.replaceChildren(M("NoBlockedUsers"))};C(),y(C,"full"),b.content.append(S.container)}this.scrollable.append(b.container)}if(s&&h){const b=new Pe({caption:"ChannelSignMessagesInfo"}),S=new pt({text:"ChannelSignMessages",checked:!!t.pFlags.signatures});this.listenerSetter.add(S.input)("change",()=>{const C=S.toggleDisability(!0);this.managers.appChatsManager.toggleSignatures(this.chatId,S.checked).then(()=>{C()})}),y(()=>{S.setValueSilently(!!t.pFlags.signatures)}),b.content.append(rr(S).container),this.scrollable.append(b.container)}if(!s){const b=new Pe({});if(!s&&n){const S=new pt({text:"ChatHistory"});this.listenerSetter.add(S.input)("change",()=>{const P=S.toggleDisability(!0);this.managers.appChatsManager.togglePreHistoryHidden(this.chatId,!S.checked).then(()=>{P()})});const C=()=>{S.setValueSilently(i&&!e.pFlags.hidden_prehistory)};C(),y(C),b.content.append(rr(S).container)}b.content.childElementCount&&this.scrollable.append(b.container)}if(d){const b=new Pe({}),S=ze("btn-primary btn-transparent danger",{icon:"delete",text:s?"PeerInfo.DeleteChannel":"DeleteAndExitButton"});N(S,()=>{ee.createPopup(Hu,v,void 0,C=>{const P=jt([S],!0);C.then(()=>{this.close()},()=>{P()})})},{listenerSetter:this.listenerSetter}),b.content.append(S),this.scrollable.append(b.container)}i||this.listenerSetter.add(I)("dialog_migrate",({migrateFrom:b,migrateTo:S})=>{v===b&&(this.chatId=S.toChatId(),this._init())})}init(){return this._init()}}const Wv="https://t.me/";function sI(o={}){const e=document.createElement("a");e.classList.add("anchor-copy");let t,s="LinkCopied";if(o.mePath){const i=Wv+o.mePath;t=e.href=e.innerText=i}if(o.username){const i=Wv+o.username;e.href=i,t=e.innerText="@"+o.username,s="UsernameCopied"}return N(e,i=>{oe(i),Fs(t??e.href),Ee({langPackKey:s})}),e}class Xo{constructor(e,t){this.start=e,this.end=t}toString(){return Xo.timeToString(this.start)+" - "+Xo.timeToString(this.end)}static timeToString(e,t=!0){const s=e%60,i=(e-s)/60%24,n=new Date;n.setHours(i,s);const a=Ag(n).textContent;return e>di&&t?ke.format("BusinessHoursNextDay",!0,[a]):a}}const ey=class ey{static adaptWeeklyOpen(e,t){const s=Wi(e),i=new Array;for(let n=0;n<s.length;++n){const a=s[n];let r={...a};if(t!==0){const l=a.start_minute%di,c=l+(a.end_minute-a.start_minute);if(l===0&&(c===di||c===di-1)){r.start_minute=a.start_minute,r.end_minute=a.end_minute,i.push(r);continue}}r.start_minute=a.start_minute+t,r.end_minute=a.end_minute+t,i.push(r),r.start_minute<0?r.end_minute<0?(r.start_minute+=Qi,r.end_minute+=Qi):(r.start_minute=0,r={...a},r.start_minute=Qi+a.start_minute+t,r.end_minute=Qi-1,i.push(r)):r.end_minute>Qi&&r.start_minute>Qi&&(r.start_minute-=Qi,r.end_minute-=Qi)}return i.sort((n,a)=>n.start_minute-a.start_minute),i}static getDaysHours(e){const t=new Array(7);for(let s=0;s<t.length;++s)t[s]=[];for(let s=0;s<e.length;++s){const i=e[s],n=Math.floor(i.start_minute/di%7),a=i.start_minute%di,r=a+(i.end_minute-i.start_minute);t[n].push(new Xo(a,r))}for(let s=0;s<7;++s){const i=di*s,n=di*(s+1);let a=i;for(let l=0;l<e.length;++l){const c=e[l];c.start_minute<=a&&c.end_minute>=a&&(a=c.end_minute+1)}if(a>=n){const l=(7+s-1)%7;t[l].length&&t[l][t[l].length-1].end>=di&&(t[l][t[l].length-1].end=di-1),t[s].length=0,t[s].push(new Xo(0,di-1))}else{const l=(s+1)%7;if(t[s].length&&t[l].length){const c=t[s][t[s].length-1],d=t[l][0];c.end>di&&c.end-di+1===d.start&&(c.end=di-1,d.start=0)}}}return t}static is24x7(e){if(!e||!e.weekly_open.length)return!1;let t=0;for(let s=0;s<e.weekly_open.length;++s){const i=e.weekly_open[s];if(i.start_minute>t+1)return!1;t=i.end_minute}return t>=Qi-1}static isOpenNow(e){const t=new Date,s=(7+t.getDay()-1)%7,i=t.getHours(),n=t.getMinutes();let a=!1;const r=n+i*60+s*di;for(let l=0;l<e.length;++l){const c=e[l];if(r>=c.start_minute&&r<=c.end_minute||r+Qi>=c.start_minute&&r+Qi<=c.end_minute||r-Qi>=c.start_minute&&r-Qi<=c.end_minute){a=!0;break}}return{openNow:a,nowWeekday:s,nowHours:i,nowPeriodTime:r}}static isFull(e){if(!e||!e.length)return!1;let t=0;for(let s=0;s<e.length;++s){const i=e[s];if(t<i.start)return!1;t=i.end}return t===di-1||t===di}};ey.Period=Xo;let er=ey;function nm(o,e){const t=o.slice(e),s=o.slice(0,e);return t.concat(s)}const JA=ce("<span>"),e2=ce("<div class=business-hours-row><div class=business-hours-row-day></div><div class=business-hours-row-time>"),t2=ce("<div class=business-hours>");function s2(o){const[e,t]=ne(!1),[s,i]=ne(!1),[n,a]=ne(),[r,l]=ne(),[c,d]=ne(),[h,u]=ne(),p=new Ut;ut(()=>p.removeAll());const m=Tu();let g;const f=new ve({title:!0,titleRight:(()=>{const b=JA(),S=g;return typeof S=="function"?wt(S,b):g=b,D(b,(()=>{const C=K(()=>c()!==void 0);return()=>C()&&M(c()?"BusinessHoursProfileSwitchMy":"BusinessHoursProfileSwitchLocal")})()),Ve(()=>Ce(b,ot("business-hours-switch-time",c()===void 0&&"hide"))),b})(),subtitleLangKey:"BusinessHoursProfile",subtitleRight:!0,icon:"sending",clickable:b=>{if(Ns(b.target,g)){d(S=>!S),Rc(m,()=>{w()}),t(!0);return}s()||t(S=>!S)},contextMenu:{buttons:[{icon:"copy",text:"Copy",onClick:()=>{Fs(h()),Ee({langPackKey:"BusinessHoursCopied"})}}]},listenerSetter:p});ye($s(e,()=>{let b;e()&&!s()&&(b=f.container.querySelector(".business-hours").getBoundingClientRect().height),f.container.style.paddingBottom=b?`${10+b}px`:"",f.container.classList.toggle("is-expanded",e())},{defer:!0}));const v=()=>{const b=o.hours(),C=o.timezones()?.find(k=>k.id===b.timezone_id),L=-new Date().getTimezoneOffset(),E=C?C.utc_offset/60:0;return L-E},w=()=>{const b=o.hours();if(!b||!o.timezones())return;const S=er.is24x7(b);i(S);const C=b.weekly_open,P=v(),L=!!P,E=L?Et(c)??!1:!0,_=er.adaptWeeklyOpen(C,P),{openNow:k,nowPeriodTime:x,nowWeekday:A}=er.isOpenNow(_);d(L?E:void 0);const T=(se,Y)=>{if(er.isFull(se))return[ke.format("BusinessHoursProfileOpen",!0)];if(!Y&&!k&&!e()){let he=-1;for(let le=0;le<_.length;++le){const re=_[le];if(x<re.start_minute){he=re.start_minute;break}}if(he===-1&&_.length&&(he=_[0].start_minute),he===-1)return[ke.format("BusinessHoursProfileClose",!0)];{const le=he<x?he+(Qi-x):he-x;return le<60?[ke.format("BusinessHoursProfileOpensInMinutes",!0,[le])]:le<di?[ke.format("BusinessHoursProfileOpensInHours",!0,[Math.ceil(le/60)])]:[ke.format("BusinessHoursProfileOpensInDays",!0,[Math.ceil(le/di)])]}}const Q=se.map(he=>he.toString());return Q.length?Q:[ke.format("BusinessHoursProfileClose",!0)]},B=se=>nm(se,A).map(T),R=er.getDaysHours(C),O=B(R),X=er.getDaysHours(_),F=B(X),H=E?F:O;if(f.title.replaceChildren(M(k?"BusinessHoursProfileNowOpen":"BusinessHoursProfileNowClosed")),f.title.classList.toggle("green",k),f.title.classList.toggle("danger",!k),f.subtitleRight.textContent=S?ke.format("BusinessHoursProfileFullOpen",!0):H[0][0],S)return;const G=nm(kL(),A),z=H.map(se=>se.join("")).join("");if(Et(n)===z)return;const q=[];a(z);const $=H.map((se,Y)=>{const Q=G[Y];let he=Q+": ";const le=se;Y===0&&(se=se.slice(1));const re=j(ti,{each:se,children:(ge,be)=>(()=>{const Z=e2(),de=Z.firstChild,Ze=de.nextSibling;return D(de,()=>Y!==0&&be()===0?Q:""),D(Ze,ge),Z})()});return he+=le.join(", "),q.push(he),re});u(nm(q,-A).join(`
`)),l((()=>{const se=t2();return D(se,$),se})())};return ye(w),f.container.classList.add("business-hours-container"),j(_u,{get mount(){return f.container},get children(){return j(tp,{type:"cross-fade",get children(){return r()}})}}),f}class i2 extends Gu{constructor(e){super({...e,loadMore:(t,s,i)=>{if(this.peerId.isAnyChat()||!s)return Promise.resolve({count:0,items:[]});const n=t?.photoId;return this.managers.appPhotosManager.getUserPhotos(this.peerId,n,i).then(a=>{const r=a.photos.map(l=>({element:null,photoId:l}));return{count:a.count,items:r}})}}),this.loadedAllUp=!0,this.peerId=e.peerId}}function n2(o){const e=o.split(" ");if(e.length!==4){e[0]||(e[0]="0px");for(let t=e.length;t<4;++t)e[t]=e[t%2]||e[0]||"0px"}return e}function gh(o,e,t,s,i,n,a){return[o,",",e," ",t," ",s,",",i," ",n,",",a].join("")}function $o(o,e,t,s,i,n,a,r){const l=[];return l.push("M"+(o+t/2)+","+e),l.push("H"+(o+t-n)),n>0&&l.push("A"+gh(n,n,0,0,1,o+t,e+n)),l.push("V"+(e+s-a)),a>0&&l.push("A"+gh(a,a,0,0,1,o+t-a,e+s)),l.push("H"+(o+r)),r>0&&l.push("A"+gh(r,r,0,0,1,o+0,e+s-r)),l.push("V"+(e+i)),i>0&&l.push("A"+gh(i,i,0,0,1,o+i,e+0)),l.push("Z"),l.join(" ")}Ws.generatePathData=$o;function jv(o,e,t){return o>=e&&o<=t}function iI(o){const e=`/rtmp/${encodeURIComponent(JSON.stringify(o))}`;return Pi?`${e}?hls=playlist&t=${Date.now()}`:`${e}?t=${Date.now()}`}function qv(o){const e=fe.getChat(o);if(e._!=="channel")throw new Error("Not a channel");return e.username||e.usernames?.length?`https://t.me/${e.username||e.usernames[0]}?livestream`:`https://t.me/c/${e.id}?livestream`}const a2=.5,ea=1,fh=.5,yh=4,r2=200,o2=350,Bs="media-viewer";class Uf extends Si{constructor(e,t){super(!1),this.listLoader=e,this.author={},this.content={},this.buttons={},this.tempId=0,this.preloader=null,this.preloaderStreamable=null,this.isFirstOpen=!0,this.streamEnded=!1,this.zoomElements={},this.transform={x:0,y:0,scale:ea},this.lastTransform=this.transform,this.lastZoomCenter=this.transform,this.lastDragOffset=this.transform,this.lastDragDelta=this.transform,this.onSwipeFirst=l=>{this.lastDragOffset=this.lastDragDelta={x:0,y:0},this.lastTransform={...this.transform},(l?.type!=="wheel"||!this.ctrlKeyDown)&&(this.moversContainer.classList.add("no-transition"),this.zoomElements.rangeSelector.container.classList.remove("with-transition")),this.isGesturingNow=!0,this.lastGestureTime=Date.now(),this.clampZoomDebounced.clearTimeout(),!this.lastTransform.x&&!this.lastTransform.y&&!this.isZooming&&(this.initialContentRect=this.content.media.getBoundingClientRect())},this.onSwipeReset=l=>{this.moversContainer.classList.remove("no-transition"),this.zoomElements.rangeSelector.container.classList.add("with-transition"),this.clampZoomDebounced.clearTimeout(),l?.type==="mouseup"&&this.draggingType==="mousemove"&&(this.ignoreNextClick=!0);const{draggingType:c}=this;if(this.isZoomingNow=!1,this.isGesturingNow=!1,this.draggingType=void 0,!this.closing)if(this.transform.scale>ea){const d=Math.min(this.transform.scale,yh),h=d/this.transform.scale;let u=this.transform.x*h+(this.lastZoomCenter.x-h*this.lastZoomCenter.x),p=this.transform.y*h+(this.lastZoomCenter.y-h*this.lastZoomCenter.y);if(c&&c!=="wheel"&&this.lastTransform.scale===this.transform.scale){const f=Math.max(1,Date.now()-this.lastGestureTime),y=Math.abs(this.lastDragOffset.x)/f,v=Math.abs(this.lastDragOffset.y)/f;u-=Math.abs(this.lastDragOffset.x)*y*.1*-this.lastDragDelta.x,p-=Math.abs(this.lastDragOffset.y)*v*.1*-this.lastDragDelta.y}const[m]=this.calculateOffsetBoundaries({x:u,y:p,scale:d});this.lastTransform=m,this.setTransform(m)}else this.transform.scale<ea&&this.resetZoom()},this.onZoom=({initialCenterX:l,initialCenterY:c,zoom:d,zoomAdd:h,currentCenterX:u,currentCenterY:p,dragOffsetX:m,dragOffsetY:g,zoomFactor:f})=>{l||(l=lt.width/2),c||(c=lt.height/2),u||(u=lt.width/2),p||(p=lt.height/2),this.isZoomingNow=!0;const y=yh*3,v=h!==void 0?Kt(this.lastTransform.scale+h,fh,y):d??Kt(this.lastTransform.scale*f,fh,y),w=v/this.lastTransform.scale,b=Math.abs(Math.min(this.lastTransform.x,0)),S=Math.abs(Math.min(this.lastTransform.y,0));this.lastZoomCenter={x:u,y:p};const C=b+l,P=S+c,{scaleOffsetX:L,scaleOffsetY:E}=this.calculateScaleOffset({x:C,y:P,scale:w}),[_]=this.calculateOffsetBoundaries({x:this.lastTransform.x+L+m,y:this.lastTransform.y+E+g,scale:v});this.setTransform(_)},this.calculateOffsetBoundaries=({x:l,y:c,scale:d},h=0)=>{if(!this.initialContentRect)return[{x:l,y:c,scale:d},!0,!0];let u=!0,p=!0;const{minX:m,maxX:g,minY:f,maxY:y}=this.getZoomBoundaries(d,h);return u=jv(l,g,m),l=Kt(l,g,m),p=jv(c,y,f),c=Kt(c,y,f),[{x:l,y:c,scale:d},u,p]},this.setZoomValue=(l=this.transform.scale)=>{this.initialContentRect??(this.initialContentRect=this.content.media.getBoundingClientRect()),l===ea&&(this.transform.x=0,this.transform.y=0),this.moversContainer.style.transform=`translate3d(${this.transform.x.toFixed(3)}px, ${this.transform.y.toFixed(3)}px, 0px) scale(${l.toFixed(3)})`,this.zoomElements.btnOut.classList.toggle("inactive",l<=fh),this.zoomElements.btnIn.classList.toggle("inactive",l>=yh),this.toggleZoom(l!==ea)},this.onClick=l=>{const c=l.target;if(U(c,"popup"))return;if(this.ignoreNextClick){this.ignoreNextClick=void 0;return}if(this.setMoverAnimationPromise||c.tagName==="A")return;if(U(c,"admin-popup-container")||oe(l),Je){this.highlightSwitchersTimeout?clearTimeout(this.highlightSwitchersTimeout):this.wholeDiv.classList.add("highlight-switchers"),this.highlightSwitchersTimeout=window.setTimeout(()=>{this.wholeDiv.classList.remove("highlight-switchers"),this.highlightSwitchersTimeout=0},3e3);return}if(Ig(l))return;const d=this.isZooming&&!1,h=["admin-popup-container","ckin__player","media-viewer-buttons","media-viewer-author","media-viewer-caption","zoom-container"];d&&h.push("media-viewer-movers");const u=h.some(p=>!!U(c,p));if(!u&&this.live&&document.pictureInPictureEnabled){this.videoPlayer.requestPictureInPicture();return}(!u||!d&&(c.tagName==="IMG"||c.tagName==="image"))&&this.close()},this.onKeyDown=l=>{if(Li.overlaysActive>1)return;const c=l.key;let d=!0;c==="ArrowRight"?!this.isZooming&&this.buttons.next.click():c==="ArrowLeft"?!this.isZooming&&this.buttons.prev.click():c==="-"||c==="="?this.ctrlKeyDown&&this.addZoomStep(c==="="):d=!1,(l.ctrlKey||l.metaKey)&&(this.ctrlKeyDown=!0),d&&oe(l)},this.onKeyUp=l=>{Li.overlaysActive>1||l.ctrlKey||l.metaKey||(this.ctrlKeyDown=!1,this.isZooming&&this.setZoomValue())},this.managers=I.managers,this.middlewareHelper=xt(),this.log=ri("AMV"),this.preloader=new tn,this.preloaderStreamable=new tn({cancelable:!1,streamable:!0}),this.preloader.construct(),this.preloaderStreamable.construct(),this.lazyLoadQueue=new Kb,this.wholeDiv=document.createElement("div"),this.wholeDiv.classList.add(Bs+"-whole"),this.overlaysDiv=document.createElement("div"),this.overlaysDiv.classList.add("overlays"),this.overlayActive=!1;const s=document.createElement("div");s.classList.add(Bs);const i=this.topbar=document.createElement("div");i.classList.add(Bs+"-topbar",Bs+"-appear");const n=document.createElement("div");n.classList.add(Bs+"-topbar-left"),this.buttons["mobile-close"]=it("close",{onlyMobile:!0}),this.author.container=document.createElement("div"),this.author.container.classList.add(Bs+"-author","no-select");const a=document.createElement("div");a.classList.add(Bs+"-author-right"),this.author.nameEl=document.createElement("div"),this.author.nameEl.classList.add(Bs+"-name"),this.author.date=document.createElement("div"),this.author.date.classList.add(Bs+"-date"),a.append(this.author.nameEl,this.author.date),this.author.container.append(a);const r=document.createElement("div");r.classList.add(Bs+"-buttons"),t.concat(["download","zoomin","close"]).forEach(l=>{const c=it(l,{noRipple:!0});this.buttons[l]=c,r.append(c)}),this.zoomElements.container=document.createElement("div"),this.zoomElements.container.classList.add("zoom-container"),this.zoomElements.btnOut=it("zoomout",{noRipple:!0}),N(this.zoomElements.btnOut,()=>this.addZoomStep(!1)),this.zoomElements.btnIn=it("zoomin",{noRipple:!0}),N(this.zoomElements.btnIn,()=>this.addZoomStep(!0)),this.zoomElements.rangeSelector=new Td({step:.01,min:fh,max:yh,withTransition:!0},ea),this.zoomElements.rangeSelector.setListeners(),this.zoomElements.rangeSelector.setHandlers({onScrub:l=>{const c=l-this.transform.scale;this.addZoom(c),this.clampZoomDebounced?.clearTimeout()},onMouseDown:()=>{this.onSwipeFirst()},onMouseUp:()=>{this.onSwipeReset()}}),this.zoomElements.container.append(this.zoomElements.btnOut,this.zoomElements.rangeSelector.container,this.zoomElements.btnIn),Je||this.wholeDiv.append(this.zoomElements.container),this.content.main=document.createElement("div"),this.content.main.classList.add(Bs+"-content"),this.content.container=document.createElement("div"),this.content.container.classList.add(Bs+"-container"),this.content.media=document.createElement("div"),this.content.media.classList.add(Bs+"-media"),this.content.container.append(this.content.media),this.content.main.append(this.content.container),s.append(this.content.main),this.overlaysDiv.append(s),n.append(this.buttons["mobile-close"],this.author.container),i.append(n,r),this.buttons.prev=document.createElement("div"),this.buttons.prev.className=`${Bs}-switcher ${Bs}-switcher-left`,this.buttons.prev.append(Le("previous",`${Bs}-sibling-button`,`${Bs}-prev-button`)),this.buttons.next=document.createElement("div"),this.buttons.next.className=`${Bs}-switcher ${Bs}-switcher-right`,this.buttons.next.append(Le("next",`${Bs}-sibling-button`,`${Bs}-next-button`)),this.moversContainer=document.createElement("div"),this.moversContainer.classList.add(Bs+"-movers"),this.moversContainer.append(this.buttons.prev,this.buttons.next),this.wholeDiv.append(this.overlaysDiv,this.topbar,this.moversContainer),this.listLoader.onLoadedMore=()=>{this.buttons.prev.classList.toggle("hide",!this.listLoader.previous.length),this.buttons.next.classList.toggle("hide",!this.listLoader.next.length)},this.setNewMover()}get target(){return this.listLoader.current}set target(e){this.listLoader.current=e}setListeners(){N(this.buttons.download,this.onDownloadClick),[this.buttons.close,this.buttons["mobile-close"],this.preloaderStreamable.preloader].forEach(s=>{N(s,this.close.bind(this))}),[[-1,this.buttons.prev],[1,this.buttons.next]].forEach(([s,i])=>{i.addEventListener("click",n=>{oe(n),!this.setMoverPromise&&this.listLoader.go(s)})}),N(this.buttons.zoomin,()=>{this.isZooming?this.resetZoom():this.addZoomStep(!0)}),this.wholeDiv.addEventListener("click",this.onClick),this.listLoader.onJump=(s,i)=>{i?this.onNextClick(s):this.onPrevClick(s)};const e=(s,i)=>{const[n,a]=[s-this.lastDragOffset.x,i-this.lastDragOffset.y],[r,l,c]=this.calculateOffsetBoundaries({x:this.transform.x+n,y:this.transform.y+a,scale:this.transform.scale});return this.lastDragDelta={x:n,y:a},this.lastDragOffset={x:s,y:i},this.setTransform(r),{inBoundsX:l,inBoundsY:c}},t=ii(()=>{this.lastGestureTime=Date.now()},500,!1,!0);this.clampZoomDebounced=ii(()=>{this.onSwipeReset()},300,!1,!0),this.swipeHandler=new So({element:this.wholeDiv,onReset:this.onSwipeReset,onFirstSwipe:this.onSwipeFirst,onSwipe:(s,i,n,a)=>{if(wn())return;if(this.isZooming&&!this.isZoomingNow){t(),this.draggingType=n.type;const{inBoundsX:c,inBoundsY:d}=e(s,i);a?.(!c,!d);return}return this.isZoomingNow||!Je?void 0:Math.abs(s)/lt.width>.2||Math.abs(s)>125?(s>0?this.buttons.prev.click():this.buttons.next.click(),!0):Math.abs(i)/lt.height>.2||Math.abs(i)>125?(this.close(),!0):!1},onZoom:this.onZoom,onDoubleClick:({centerX:s,centerY:i})=>{if(this.isZooming)this.resetZoom();else{const n=ea+2;this.changeZoomByPosition(s,i,n)}},verifyTouchTarget:s=>!(wn()||Ns(s.target,this.zoomElements.container)||U(s.target,"ckin__controls")||U(s.target,"media-viewer-caption")||U(s.target,"media-viewer-topbar")&&s.type!=="wheel"),cursor:""})}changeZoomByPosition(e,t,s){const{scaleOffsetX:i,scaleOffsetY:n}=this.calculateScaleOffset({x:e,y:t,scale:s}),a=this.calculateOffsetBoundaries({x:i,y:n,scale:s})[0];this.setTransform(a)}setTransform(e){this.transform=e,this.changeZoom(e.scale)}calculateScaleOffset({x:e,y:t,scale:s}){return{scaleOffsetX:e-s*e,scaleOffsetY:t-s*t}}toggleZoom(e){const t=this.isZooming,s=e===void 0;if((this.zoomElements.rangeSelector.mousedown||this.ctrlKeyDown)&&(e=!0),e??(e=!t),t!==e){if(po(this.buttons.zoomin,e?"zoomout":"zoomin"),this.zoomElements.container.classList.toggle("is-visible",this.isZooming=e),this.wholeDiv.classList.toggle("is-zooming",e),s||!e){const i=e?this.transform.scale:ea;this.setZoomValue(i),this.zoomElements.rangeSelector.setProgress(i)}this.videoPlayer&&this.videoPlayer.lockControls(e?!1:void 0)}}addZoomStep(e){this.addZoom(a2*(e?1:-1))}resetZoom(){this.setTransform({x:0,y:0,scale:ea})}changeZoom(e=this.transform.scale){this.transform.scale=e,this.zoomElements.rangeSelector.setProgress(e),this.setZoomValue(e)}addZoom(e){this.lastTransform=this.transform,this.onZoom({zoomAdd:e,currentCenterX:0,currentCenterY:0,initialCenterX:0,initialCenterY:0,dragOffsetX:0,dragOffsetY:0}),this.lastTransform=this.transform,this.clampZoomDebounced()}getZoomBounce(){return this.isGesturingNow&&Je?50:0}getZoomBoundaries(e=this.transform.scale,t=0){if(!this.initialContentRect)return{minX:0,maxX:0,minY:0,maxY:0};const s=(lt.width-lt.width*e)/2,i=(lt.height-lt.height*e)/2,n=Math.max(-this.initialContentRect.left*e,s),a=lt.width-this.initialContentRect.right*e,r=Math.max(-this.initialContentRect.top*e+t,i),l=lt.height-this.initialContentRect.bottom*e;return{minX:n,maxX:a,minY:r,maxY:l}}setBtnMenuToggle(e){const t=ai({buttonOptions:{onlyMobile:!0},direction:"bottom-left",buttons:e});this.topbar.append(t)}close(e){if(this.disposeSolid?.(),e&&oe(e),this.closing)return this.setMoverAnimationPromise;if(this.setMoverAnimationPromise)return Promise.reject();this.closing=!0,this.swipeHandler?.removeListeners(),this.navigationItem&&ft.removeItem(this.navigationItem),this.lazyLoadQueue.clear(),this.author.avatarMiddlewareHelper?.destroy();const t=this.setMoverToTarget(this.target?.element,!0).then(({onAnimationEnd:s})=>s);return this.listLoader.reset(),this.listLoader.cleanup&&this.listLoader.cleanup(),this.setMoverPromise=null,this.tempId=-1,window.appMediaViewer===this&&(window.appMediaViewer=void 0),this.removeGlobalListeners(),t.finally(()=>{this.wholeDiv.remove(),this.toggleOverlay(!1),this.middlewareHelper.destroy()}),t}toggleOverlay(e){this.overlayActive!==e&&(this.overlayActive=e,Li.isDarkOverlayActive=e,gt.checkAnimations2(e))}toggleGlobalListeners(e){e?this.setGlobalListeners():this.removeGlobalListeners()}removeGlobalListeners(){window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}setGlobalListeners(){window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}setMediaTimestamp(e){this.videoPlayer?.setTimestamp(e)}async setMoverToTarget(e,t=!1,s=0){this.dispatchEvent("setMoverBefore");const i=this.content.mover;t||i.replaceChildren();const n=this.isZooming&&t?this.transform.scale:ea;this.removeCenterFromMover(i),t&&(i.offsetLeft,await Qn());const a=s!==0,r=st.isAvailable("animations")?a?o2:r2:0;let l,c;e&&(Uc(e)||e.classList.contains("grid-item")?(l=e,c=e.getBoundingClientRect()):e instanceof SVGImageElement||e.parentElement instanceof SVGForeignObjectElement?(l=U(e,"attachment"),c=l.getBoundingClientRect()):e.classList.contains("profile-avatars-avatar")&&(l=U(e,"profile-avatars-container"),c=l.getBoundingClientRect(),t&&e.getBoundingClientRect().left!==c.left&&(e=l=c=void 0))),e||(e=this.content.media),c||(l=e.parentElement,c=e.getBoundingClientRect());let d=!1;if(e===this.content.media)d=!0;else if(!e.classList.contains("profile-avatars-avatar")){const E=U(l,"scrollable"),_=go(l,E,!0);t&&_&&(_.overflow.vertical===2||_.overflow.horizontal===2)?(e=this.content.media,l=e.parentElement,c=e.getBoundingClientRect()):_&&(_.overflow.vertical===1||_.overflow.horizontal===1)&&(d=!0)}const h=this.content.media.getBoundingClientRect();let u="",p,m;a?(p=s===1?lt.width:-h.width,m=h.top):(p=c.left,m=c.top),u+=`translate3d(${p}px,${m}px,0) `;let g;if(e instanceof HTMLImageElement||e instanceof HTMLVideoElement||e.tagName==="DIV"){if(i.firstElementChild&&i.firstElementChild.classList.contains("media-viewer-aspecter")){g=i.firstElementChild;const E=g.querySelector(".ckin__player");if(E&&!d){const _=E.querySelector("video");_&&(_.pause(),E.replaceWith(_))}g.style.cssText||(i.classList.remove("active"),this.setFullAspect(g,h,c),i.offsetLeft,i.classList.add("active"))}else g=document.createElement("div"),g.classList.add("media-viewer-aspecter"),i.prepend(g);g.style.cssText=`width: ${c.width}px; height: ${c.height}px; transform: scale3d(${h.width/c.width}, ${h.height/c.height}, 1);`}i.style.width=h.width+"px",i.style.height=h.height+"px";const f=c.width/h.width,y=c.height/h.height;a||(u+=`scale3d(${f},${y},1) `);let v=window.getComputedStyle(l).getPropertyValue("border-radius");if(v=n2(v).map(E=>parseInt(E)/f+"px").join(" "),a||(i.style.borderRadius=v),t&&n!==1){const E=c.left-(lt.width*f-c.width)/2,_=c.top-(lt.height*y-c.height)/2;this.moversContainer.style.transform=`matrix(${f}, 0, 0, ${y}, ${E}, ${_})`}else i.style.transform=u;d&&(i.style.opacity="0");let b;const S=e.classList.contains("is-out"),C=this.setMoverAnimationPromise=Pt(),P={onAnimationEnd:C},L=setTimeout(()=>{!C.isFulfilled&&!C.isRejected&&C.resolve()},1e3);if(C.finally(()=>{this.dispatchEvent("setMoverAfter"),this.setMoverAnimationPromise===C&&(this.setMoverAnimationPromise=null),clearTimeout(L)}),t)return e instanceof SVGSVGElement&&(b=i.querySelector("path"),b&&this.sizeTailPath(b,h,f,r,!1,S,v)),this.toggleWholeActive(!1),setTimeout(()=>{i.style.borderRadius=v,i.firstElementChild&&(i.firstElementChild.style.borderRadius=v)},r/2),setTimeout(()=>{i.replaceChildren(),i.classList.remove("moving","active","hiding"),i.style.cssText="display: none;",C.resolve()},r),i.classList.remove("opening"),P;{let E,_;const k="video, img, .canvas-thumbnail",x=e.matches(k)?e.parentElement:e,A=Array.from(x.querySelectorAll(k));if(A.length){e=A.pop();const T=document.createElement("canvas"),B=T.getContext("2d");e instanceof HTMLImageElement?(T.width=e.naturalWidth,T.height=e.naturalHeight):e instanceof HTMLVideoElement?(T.width=e.videoWidth,T.height=e.videoHeight):e instanceof HTMLCanvasElement&&(T.width=e.width,T.height=e.height),T.className="canvas-thumbnail thumbnail media-photo",B.drawImage(e,0,0),this.live&&w0(B,0,0,T.width,T.height,8,2),e=T}if(e.tagName==="DIV"||Uc(e)){const B=Array.from(e.querySelectorAll("img")).pop();if(B)E=new Image,_=B.src,i.append(E);else{const R=e.querySelector(".avatar[data-color]");if(R){const O=R.cloneNode(!0);O.textContent="",g.append(O)}}}else if(e instanceof HTMLImageElement)E=new Image,_=e.src;else if(e instanceof HTMLVideoElement)E=hl({middleware:i.middlewareHelper.get()}),E.src=e.src;else if(e instanceof SVGSVGElement){const T=e.dataset.clipId,B=T+"-mv",{width:R,height:O}=h,X=document.createElementNS("http://www.w3.org/2000/svg","svg");X.setAttributeNS(null,"width",""+R),X.setAttributeNS(null,"height",""+O),X.setAttributeNS(null,"viewBox",`0 0 ${R} ${O}`),X.setAttributeNS(null,"preserveAspectRatio","xMidYMid meet"),X.insertAdjacentHTML("beforeend",e.firstElementChild.outerHTML.replace(T,B)),X.insertAdjacentHTML("beforeend",e.lastElementChild.outerHTML.replace(T,B));const F=X.firstElementChild,H=F.firstElementChild.firstElementChild;if(H instanceof SVGUseElement){let z=H.getAttributeNS(null,"transform");z=z.replace(/translate\((.+?), (.+?)\) scale\((.+?), (.+?)\)/,(se,Y,Q,he,le)=>(Y=+Y,Y!==2?Y=R-2/f:Y=2/f,Q=O,`translate(${Y}, ${Q}) scale(${+he/f}, ${+le/y})`)),H.setAttributeNS(null,"transform",z),b=F.firstElementChild.lastElementChild;let q;const $=v.split(" ").map(se=>parseInt(se));S?q=$o(0,0,R-9/f,O,...$):q=$o(9/f,0,R-9/f,O,...$),b.setAttributeNS(null,"d",q)}const G=X.lastElementChild;G.setAttributeNS(null,"width",""+h.width),G.setAttributeNS(null,"height",""+h.height),i.prepend(X)}else e instanceof HTMLCanvasElement&&(E=e);g&&(g.style.borderRadius=v,E&&g.append(E)),E=i.querySelector("video, img"),E instanceof HTMLImageElement&&(E.classList.add("thumbnail"),g||(E.style.width=h.width+"px",E.style.height=h.height+"px"),_&&await Ki(E,_)),i.style.display="",bs(()=>{i.classList.add(a?"moving":"active")})}return i.classList.add("opening"),await Qn(),i.style.transform=`translate3d(${h.left}px,${h.top}px,0) scale3d(1,1,1)`,d&&(i.style.opacity=""),g&&this.setFullAspect(g,h,c),setTimeout(()=>{i.style.borderRadius="",i.firstElementChild&&(i.firstElementChild.style.borderRadius="")},0),i.dataset.timeout=""+setTimeout(()=>{i.classList.remove("moving","opening"),g&&(i.querySelector("video"),i.classList.remove("active"),g.style.cssText="",i.offsetLeft),i.classList.add("center","no-transition"),i.classList.add("active"),delete i.dataset.timeout,C.resolve()},r),b&&this.sizeTailPath(b,h,f,r,!0,S,v),P}toggleWholeActive(e){e?this.wholeDiv.classList.add("active"):(this.wholeDiv.classList.add("backwards"),setTimeout(()=>{this.wholeDiv.classList.remove("active")},0))}setFullAspect(e,t,s){const i=t.width/t.height;let{width:n,height:a}=s;i>0?n=a*i:a=n*i,e.style.cssText=`width: ${n}px; height: ${a}px; transform: scale3d(${t.width/n}, ${t.height/a}, 1);`}sizeTailPath(e,t,s,i,n,a,r){const l=Date.now(),{width:c,height:d}=t;i=i/2;const h=r.split(" ").map(p=>parseInt(p)),u=()=>{const p=Date.now()-l;let m=i?p/i:1;m>1&&(m=1),n&&(m=1-m);const g=h.map(y=>y*m);let f;a?f=$o(0,0,c-9/s*m,d,...g):f=$o(9/s*m,0,c,d,...g),e.setAttributeNS(null,"d",f),p<i&&bs(u)};u()}removeCenterFromMover(e){if(e.classList.contains("center")){const t=this.content.media.getBoundingClientRect();e.style.transform=`translate3d(${t.left}px,${t.top}px,0)`,e.classList.remove("center"),e.offsetLeft,e.classList.remove("no-transition")}}moveTheMover(e,t=!0){const s=lt.width;this.removeCenterFromMover(e),e.classList.add("moving"),e.dataset.timeout&&clearTimeout(+e.dataset.timeout);const i=e.getBoundingClientRect(),n=e.style.transform.replace(/translate3d\((.+?),/,(a,r)=>{const l=t?-i.width:s;return a.replace(r,l+"px")});e.style.transform=n,setTimeout(()=>{e.middlewareHelper.destroy(),e.remove()},350)}setNewMover(){const e=document.createElement("div");return e.classList.add("media-viewer-mover"),e.style.display="none",e.middlewareHelper=this.middlewareHelper.get().create(),this.content.mover?this.content.mover.parentElement.append(e):this.moversContainer.append(e),this.content.mover=e}updateMediaSource(e,t,s){const i=e.tagName.toLowerCase()===s?e:e.querySelector(s);if(i&&!U(e,"document")){if(U(e,"attachment")){const n=e.parentElement.parentElement.querySelector(".preloader-container");if(n){if(s==="video"){n.classList.contains("manual")&&n.click();return}n.remove()}}i.getAttribute("src")!==t&&Kn(i,t),i.classList.contains("thumbnail")&&i.parentElement.classList.contains("media-container-aspecter")&&i.classList.remove("thumbnail")}}setAuthorInfo(e,t){const s=e.isPeerId();let i;if(s)i=Oe({peerId:e,dialog:!1,onlyFirstName:!1,plainText:!1});else{const l=i=document.createElement("span");l.append(_e(e)),l.classList.add("peer-title")}const n=this.author.avatarEl,a=this.author.avatarMiddlewareHelper,r=this.author.avatarEl=es({middleware:(this.author.avatarMiddlewareHelper=this.middlewareHelper.get().create()).get(),size:44,peerId:e||Tt,peerTitle:s?void 0:""+e});return r.node.classList.add(Bs+"-userpic"),Promise.all([r.readyThumbPromise,i]).then(([l,c])=>{dt(this.author.date,this.live?M("Rtmp.MediaViewer.Streaming"):ws(t)),dt(this.author.nameEl,c),n?.node&&n.node.parentElement?n.node.replaceWith(this.author.avatarEl.node):this.author.container.prepend(this.author.avatarEl.node),n&&(n.node.remove(),a.destroy())})}get mediaBoxSize(){const{width:e,height:t}=lt;return new Sm(e,t-120-($e.isMobile||this.live?0:120))}async _openMedia({media:e,mediaThumbnail:t,timestamp:s,fromId:i,fromRight:n,target:a,reverse:r=!1,prevTargets:l=[],nextTargets:c=[],message:d,mediaTimestamp:h,setupPlayer:u,onCanPlay:p,onMoverSet:m,onBuffering:g}){if(this.setMoverPromise)return this.setMoverPromise;const f=this.setAuthorInfo(i,s),y=e._==="inputGroupCall",v=e._==="document",w=v&&e.mime_type&&(["video","gif"].includes(e.type)||e.mime_type.indexOf("video/")===0);this.log("openMedia",e,i,l,c,y,v,w),this.live=y,this.isFirstOpen&&(this.isFirstOpen=!1,this.listLoader.setTargets(l,c,r),window.appMediaViewer=this),this.listLoader.next.length<10&&setTimeout(()=>{this.listLoader.load(!0)},0),this.buttons.prev.classList.toggle("hide",!this.listLoader.previous.length),this.buttons.next.classList.toggle("hide",!this.listLoader.next.length);const b=this.content.media,S=!a||a===b;S&&(a=b),this.target={element:a};const C=++this.tempId;b.firstElementChild&&b.replaceChildren(),n!==0?(this.moveTheMover(this.content.mover,n===1),this.setNewMover()):(this.navigationItem={type:"media",onPop:O=>{if(this.setMoverAnimationPromise)return!1;!O&&Ua&&this.wholeDiv.remove(),this.close()}},ft.pushItem(this.navigationItem),this.toggleOverlay(!0),this.setGlobalListeners(),await f,this.wholeDiv.parentElement||(document.body.append(this.wholeDiv),this.wholeDiv.offsetLeft),this.toggleWholeActive(!0));const L=this.content.mover,E=this.mediaBoxSize,_=y?new Sm(1080,608):void 0;let k=Promise.resolve();const x=jo(y?{boxWidth:E.width,boxHeight:E.height,element:b,size:_}:{photo:e,element:b,boxWidth:E.width,boxHeight:E.height,noZoom:!$e.isMobile,pushDocumentSize:!!(v&&e.w&&e.h)}).photoSize;if(S&&!y){const O=await this.managers.thumbsStorage.getCacheContext(e,x?.type);let X;if(O.downloaded)X=new Image,X.src=O.url;else{const F=Oc({photo:e,cacheContext:O,useBlur:!0,onlyStripped:!0});F&&(k=F.loadPromise,X=F.image)}X&&(X.classList.add("thumbnail"),b.append(X))}if(y)if(t){const O=new Image;O.classList.add("thumbnail"),b.append(O),await Ki(O,t,!1)}else{const O=es({middleware:this.middlewareHelper.get(),peerId:i.toPeerId(),size:"full"});O.node.classList.add("thumbnail-avatar"),b.append(O.node),await O.readyThumbPromise}const A=!!(v&&e.supportsStreaming),T=y?void 0:A?this.preloaderStreamable:this.preloader,B=(O=x?.type)=>y?{url:iI(e)}:this.managers.thumbsStorage.getCacheContext(e,O);let R;if(w||y){const O=L.middlewareHelper.get(),X=d&&e.type!=="gif",F=hl({pip:X||y,middleware:O});y&&(F.ignoreLeak=!0),(this.wholeDiv.classList.contains("no-forwards")||y)&&F.addEventListener("contextmenu",oe);const H=()=>this.setMoverToTarget(a,!1,n).then(({onAnimationEnd:G})=>{m?.();const z=L.firstElementChild&&L.firstElementChild.classList.contains("media-viewer-aspecter")?L.firstElementChild:L;L.querySelector("video")?.remove(),F.setAttribute("playsinline","true"),F.autoplay=!0,e._==="inputGroupCall"?F.autoplay=!0:e.type==="gif"?(F.muted=!0,F.autoplay=!0,F.loop=!0):e.duration<60&&(F.loop=!0),h!==void 0&&yi(F,h),z.append(F);const $=new Promise(he=>{F.addEventListener("canplay",he,{once:!0})}),se=()=>{y||(this.releaseSingleMedia=rt.setSingleMedia({media:F,message:d}))},Y=async()=>{if(e.type==="gif")return;const he=Promise.all([$,G]);if(!y&&(await he,this.tempId!==C))return;const le=!y;(this.videoPlayer=new nS({video:F,play:le,streamable:A,live:y,width:_?.width,height:_?.height,onPlaybackRateMenuToggle:ge=>{this.wholeDiv.classList.toggle("hide-caption",!!ge)},onPip:ge=>{const be=window.appMediaViewer;if(!ge&&be&&be!==this){this.releaseSingleMedia=void 0,this.close();return}this.moversContainer.lastElementChild.classList.toggle("in-pip",ge),this.toggleWholeActive(!ge),this.toggleOverlay(!ge),this.toggleGlobalListeners(!ge),this.navigationItem&&(ge?ft.removeItem(this.navigationItem):ft.pushItem(this.navigationItem)),X&&(ge?(this.releaseSingleMedia?.(!1),this.releaseSingleMedia=void 0,rt.setPictureInPicture(F)):se())},onPipClose:()=>{this.close()},listenKeyboardEvents:"always",useGlobalVolume:"auto"})).addEventListener("toggleControls",ge=>{this.wholeDiv.classList.toggle("has-video-controls",ge)}),this.addEventListener("setMoverBefore",()=>{this.wholeDiv.classList.remove("has-video-controls"),this.videoPlayer.cleanup(),this.videoPlayer=void 0},{once:!0}),this.isZooming?this.videoPlayer.lockControls(!1):y&&this.videoPlayer.lockControls(!0),u?.(this.videoPlayer,he)};if(A||y){let he=!1,le=!1;const re=be=>{le||(le=!0,g?.(),!be&&ge(),T?.attach(L,!0),F.parentElement.classList.add("is-buffering"))};G.then(()=>{F.readyState<F.HAVE_FUTURE_DATA&&re(!0)});const ge=()=>{he||(he=!0,F.addEventListener("canplay",()=>{he=!1,le=!1,p?.(),T?.detach(),F.parentElement.classList.remove("is-buffering"),this.isZooming||this.videoPlayer?.lockControls(void 0)},{once:!0}))};F.addEventListener("waiting",()=>{const be=F.networkState===F.NETWORK_LOADING,Z=F.readyState<F.HAVE_FUTURE_DATA;be&&Z&&re()}),this.wholeDiv.classList.contains("no-forwards")&&F.addEventListener("contextmenu",be=>{oe(be)}),ge()}const Q=async()=>{const he=A||y?Promise.resolve():cs.downloadMediaURL({media:e});return A||G.then(async()=>{(await B()).url||T?.attach(L,!0,he)}),Promise.all([he,y?void 0:G]).then(async()=>{if(this.tempId!==C){this.log.warn("media viewer changed video");return}const le=(await B()).url,re=be=>{if(Ob(be)||y)return;Ee({langPackKey:Oi?"Video.Unsupported.Mobile":"Video.Unsupported.Desktop"});const Z=F.error;Z&&Z.code!==4&&this.log.error("Error "+Z.code+"; details: "+Z.message),T?.detach()},ge=Wn(F);y||Bg(F,ge).catch(re),F.addEventListener("error",re,{once:!0}),O.onClean(()=>{F.removeEventListener("error",re)}),a instanceof SVGSVGElement?z.firstElementChild.lastElementChild.append(F):Kn(F,le),X&&(se(),this.addEventListener("setMoverBefore",()=>{this.releaseSingleMedia?.(),this.releaseSingleMedia=void 0},{once:!0})),this.updateMediaSource(a,le,"video"),y?Y():ge.then(()=>{Y()})}),he};this.lazyLoadQueue.unshift({load:Q})});R=k.then(H)}else{const O=()=>this.setMoverToTarget(a,!1,n).then(({onAnimationEnd:X})=>{const F=async()=>{const H=v?cs.downloadMediaURL({media:e}):cs.downloadMediaURL({media:e,thumb:x}),G=!v&&e.sizes.slice().filter($=>$.w);G&&G.sort(($,se)=>se.size-$.size);const z=G?.[0],q=!v&&z!==x&&cs.downloadMediaURL({media:e,thumb:z});return X.then(async()=>{(await B()).url||this.preloader.attachPromise(H)}),Promise.all([X,H]).then(async()=>{if(this.tempId!==C){this.log.warn("media viewer changed photo");return}const $=(await B()).url;if(a instanceof SVGSVGElement)this.updateMediaSource(a,$,"img"),this.updateMediaSource(L,$,"img"),$e.isMobile&&L.querySelectorAll("img").forEach(Y=>{Y.classList.remove("thumbnail")});else{const se=L.firstElementChild&&L.firstElementChild.classList.contains("media-viewer-aspecter")?L.firstElementChild:L,Y=["CANVAS","IMG"].includes(se.firstElementChild?.tagName)?se.firstElementChild:null;if(Y?.src!==$){const Q=new Image;Q.classList.add("thumbnail"),Kn(Q,$,()=>{bs(()=>{this.updateMediaSource(a,$,"img"),Y&&bs(()=>{Y.remove()}),se.append(Q)})},!1),q&&q.then(he=>{const le=new Image;le.classList.add("thumbnail"),Kn(le,he,()=>{bs(()=>{Q.replaceWith(le)})},!1)})}}}).catch($=>{this.log.error($),this.preloader.attach(L),this.preloader.setManual()}),H};this.lazyLoadQueue.unshift({load:F})});R=k.then(O)}return this.setMoverPromise=R.catch(()=>{this.setMoverAnimationPromise=null}).finally(()=>{this.setMoverPromise=null})}}class l2 extends Uf{constructor(e){super(new i2({peerId:e,managers:I.managers}),[]),this.onPrevClick=t=>{this.openMedia({photoId:t.photoId,target:t.element,fromRight:-1})},this.onNextClick=t=>{this.openMedia({photoId:t.photoId,target:t.element,fromRight:1})},this.onDownloadClick=()=>{cs.downloadToDisc({media:this.target.photo,queueId:me.chat.bubbles.lazyLoadQueue.queueId})},this.peerId=e,this.setBtnMenuToggle([{icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick}]),this.setListeners()}async openMedia({photoId:e,target:t,fromRight:s=0,prevTargets:i,nextTargets:n}){if(this.setMoverPromise)return this.setMoverPromise;const a=await this.managers.appPhotosManager.getPhoto(e),r=super._openMedia({media:a,timestamp:a.date,fromId:this.peerId,fromRight:s,target:t,reverse:!1,prevTargets:i,nextTargets:n});return this.target.photoId=a.id,this.target.photo=a,r}}async function c2(o,e,t,s,i,n){let a=await I.managers.appProfileManager.getFullPhoto(e);if(!t()||!a)return;const r=()=>Array.from(o.querySelectorAll("img")).find(c=>!c.classList.contains("emoji"))?o:null;if(e.isAnyChat()){const l=!!s,c="inputMessagesFilterChatPhotos";if(!s&&(s=await I.managers.appMessagesManager.getHistory({peerId:e,inputFilter:{_:c},offsetId:0,limit:1}).then(d=>{const h=d.history[0];return fe.getMessageByPeer(e,h)}),!t()))return;if(s){s.action.photo.id!==a.id&&(l||(s=await I.managers.appMessagesManager.generateFakeAvatarMessage(e,a)));const h=u=>u.map(p=>({element:p.element,mid:p.item.mid,peerId:p.item.peerId}));new ho().setSearchContext({peerId:e,inputFilter:{_:c}}).openMedia({message:s,target:r(),prevTargets:i?h(i):void 0,nextTargets:n?h(n):void 0});return}}if(a){!_g(s)&&s&&(a=await I.managers.appPhotosManager.getPhoto(s));const l=c=>c.map(d=>({element:d.element,photoId:d.item}));new l2(e).openMedia({photoId:a.id,target:r(),prevTargets:i?l(i):void 0,nextTargets:n?l(n):void 0})}}let d2;function nI(){return d2??(d2=ne())}function h2(o){const[e,t]=ne(),[s,i]=ne(),[n]=nI(),a=Ou(),r=xb(()=>o);return ye(()=>{const c=r()?.profile_color;if(!c){t(),i();return}const d=n()?.find(h=>h.color_id===c.color);t(a()&&d?.dark_colors?d.dark_colors:d?.colors),i(c.background_emoji_id)}),{colorSet:e,backgroundEmojiId:s}}const am=3,aI=!0,xs=class xs{constructor(e,t,s){this.scrollable=e,this.managers=t,this.setCollapsedOn=s,this.processItem=async m=>{const g=this.middlewareHelper.get(),f=document.createElement("div");f.classList.add(xs.BASE_CLASS+"-avatar","media-container","hide");const y=this.avatars.childElementCount===0;this.avatars.append(f);let v;m&&(v=typeof m!="object"?await this.managers.appPhotosManager.getPhoto(m):m.action.photo);const w=async()=>{const b=es({middleware:g,size:"full",isDialog:!1,isBig:!0});if(y&&b.node.classList.add("profile-avatars-avatar-first"),v){const C=Sn(v,420,420,!1);await fw(b,v,420,C)}else b.render({peerId:this.peerId}),await b.readyThumbPromise;f.append(b.node),f.classList.remove("hide")};return this.avatars.childElementCount<=am?await w():(this.intersectionObserver.observe(f),this.loadCallbacks.set(f,w)),this.addTab(),this.tabs.childElementCount===1&&f.classList.add("active"),m},this.container=document.createElement("div"),this.container.classList.add(xs.BASE_CLASS+"-container"),this.avatars=document.createElement("div"),this.avatars.classList.add(xs.BASE_CLASS+"-avatars"),this.gradient=document.createElement("div"),this.gradient.classList.add(xs.BASE_CLASS+"-gradient"),this.gradientTop=this.gradient.cloneNode(),this.gradientTop.classList.add(xs.BASE_CLASS+"-gradient-top"),this.info=document.createElement("div"),this.info.classList.add(xs.BASE_CLASS+"-info"),this.tabs=document.createElement("div"),this.tabs.classList.add(xs.BASE_CLASS+"-tabs"),this.arrowPrevious=document.createElement("div"),this.arrowPrevious.classList.add(xs.BASE_CLASS+"-arrow"),this.arrowPrevious.append(Le("avatarprevious",xs.BASE_CLASS+"-arrow-icon")),this.middlewareHelper=xt(),this.arrowNext=document.createElement("div"),this.arrowNext.classList.add(xs.BASE_CLASS+"-arrow",xs.BASE_CLASS+"-arrow-next"),this.arrowNext.append(Le("avatarnext",xs.BASE_CLASS+"-arrow-icon")),this.container.append(this.avatars,this.gradient,this.gradientTop,this.info,this.tabs,this.arrowPrevious,this.arrowNext),this.loadCallbacks=new Map,this.listenerSetter=new Ut;const i=()=>this.scrollable.scrollPosition!==0?(this.scrollable.scrollIntoViewNew({element:this.scrollable.firstElementChild,position:"start"}),!1):!0,n=1/3;let a=!1,r=!1;N(this.container,async m=>{if(r){oe(m);return}if(a){a=!1;return}if(!i()||this.hasNoPhoto)return;if(this.isCollapsed()&&this.unfold){if(U(m.target,"avatar")&&this.container.classList.contains("has-stories")){a=!0,fs(this.fakeAvatar.node);return}this.unfold(m);return}const g=this.container.getBoundingClientRect(),y=m.pageX,v=y-g.left;if(!this.listLoader.previous.length&&!this.listLoader.next.length||v>g.width*n&&v<g.width-g.width*n){const w=this.peerId,b=[];this.listLoader.previous.concat(this.listLoader.current,this.listLoader.next).forEach((L,E)=>{b.push({element:this.avatars.children[E],item:L})});const S=b.slice(0,this.listLoader.previous.length),C=b.slice(this.listLoader.previous.length+1),P=this.avatars.children[this.listLoader.previous.length];r=!0,c2(P,w,()=>w===this.peerId,this.listLoader.current,S,C),r=!1}else{const w=g.right-g.width/2,b=y>w;let S;this.listLoader.index===0&&!b?S=this.listLoader.count-1:this.listLoader.index===this.listLoader.count-1&&b?S=-(this.listLoader.count-1):S=b?1:-1,this.goWithoutTransition(S)}},{listenerSetter:this.listenerSetter});const l=()=>{a=!0,document.body.addEventListener(Je?"touchend":"click",m=>{a=!1},{once:!0})};let c=0,d=0,h=0,u=0;this.swipeHandler=new So({element:this.avatars,onSwipe:(m,g)=>{m*=-1,h=m;let f=d+m*-xs.SCALE;return f>0?f=0:f<u&&(f=u),this.avatars.style.transform=xs.TRANSLATE_TEMPLATE.replace("{x}",f+"px"),!1},verifyTouchTarget:m=>{if(i()){if(this.isCollapsed())return!1;if(this.container.classList.contains("is-single")||r)return!1}else return l(),oe(m),!1;return!0},onFirstSwipe:()=>{const m=this.avatars.getBoundingClientRect();c=m.width,u=-c*(this.tabs.childElementCount-1),d=m.left-this.container.getBoundingClientRect().left,this.avatars.style.transform=xs.TRANSLATE_TEMPLATE.replace("{x}",d+"px"),this.container.classList.add("is-swiping"),this.avatars.classList.add("no-transition"),this.avatars.offsetLeft},onReset:()=>{const m=Math.ceil(Math.abs(h)/(c/xs.SCALE))*(h>=0?1:-1);l(),this.avatars.classList.remove("no-transition"),bs(()=>{this.listLoader.go(m),this.container.classList.remove("is-swiping")})}}),this.intersectionObserver=new IntersectionObserver(m=>{m.forEach(g=>{g.isIntersecting&&this.loadNearestToTarget(g.target)})}),this.setCollapsed(!0);const p=e.onAdditionalScroll;e.onAdditionalScroll=()=>{p?.(),this.updateHeaderFilled()},this.middlewareHelper.onDestroy(()=>{e.onAdditionalScroll=p}),Jt(m=>{this.middlewareHelper.onDestroy(()=>{m(),this.unfold=void 0});const{folded:g,unfold:f,fold:y}=qC({container:()=>this.container,listenWheelOn:this.setCollapsedOn,scrollable:()=>e.container,disableHoverWhenFolded:!1});this.unfold=f,ye(()=>{if(this.hasNoPhoto&&!g()){y();return}this.setCollapsed(g())})})}goWithoutTransition(e){this.avatars.classList.add("no-transition"),this.avatars.offsetLeft,this.listLoader.go(e),bs(()=>{this.avatars.classList.remove("no-transition")})}async setPeer(e){this.peerId=e,this.middlewareHelper.clean();const t=await this.managers.appPeersManager.getPeerPhoto(e);if(!t&&!aI)return;this.hasNoPhoto=!t,await this.applyAppearance(),this.fakeAvatar&&this.fakeAvatar.node.remove(),this.fakeAvatar=es({peerId:e,isBig:!0,middleware:this.middlewareHelper.get(),size:120,withStories:!0,onStoriesStatus:i=>{this.container.classList.toggle("has-stories",i)},storyColors:{read:"rgba(255, 255, 255, .3)"}}),this.fakeAvatar.node.classList.add("profile-avatars-avatar-fake"),await this.fakeAvatar.readyThumbPromise,this.avatars.before(this.fakeAvatar.node);const s=this.listLoader=new Gu({loadCount:50,loadMore:(i,n,a)=>{if(!n)return Promise.resolve({count:void 0,items:[]});if(e.isUser()){const r=i;return this.managers.appPhotosManager.getUserPhotos(e,r,a).then(l=>({count:l.count,items:l.photos}))}else{const r=[];return s.current||r.push(this.managers.appProfileManager.getChatFull(e.toChatId())),r.push(this.managers.appMessagesManager.getHistory({peerId:e,offsetId:Number.MAX_SAFE_INTEGER,inputFilter:{_:"inputMessagesFilterChatPhotos"},limit:a,backLimit:0})),Promise.all(r).then(async l=>{const c=l.pop();let{messages:d,history:h}=c;if(d||(d=c.messages=h.map(u=>fe.getMessageByPeer(e,u))),Pw(c),!s.current){const u=l[0],p=ga(d,m=>m.action.photo.id===u.chat_photo.id);s.current=p||await this.managers.appMessagesManager.generateFakeAvatarMessage(this.peerId,u.chat_photo)}return{count:c.count,items:d}})}},processItem:this.processItem,onJump:(i,n)=>{const a=this.listLoader.index,r=100*xs.SCALE*a;this.avatars.style.transform=xs.TRANSLATE_TEMPLATE.replace("{x}",`-${r}%`),[this.tabs,this.avatars].forEach(l=>{const c=l.querySelector(".active");c&&c.classList.remove("active"),l.children[a].classList.add("active")}),this.loadNearestToTarget(this.avatars.children[a])}});t?._==="userProfilePhoto"&&(s.current=t.photo_id),await this.processItem(s.current),s.load(!0)}_applyAppearance(){const e=this.middlewareHelper.get(),t=(r,l)=>{if(this.emojiPatternCanvas?.remove(),this.emojiPatternCanvas=void 0,!r)return;const c=393,d=258,h=this.emojiPatternCanvas=document.createElement("canvas");h.classList.add("profile-avatars-pattern");const u=h.getContext("2d"),p=window.devicePixelRatio;h.width=c*p,h.height=d*p,h.style.width=`${c}px`,h.style.height=`${d}px`,l?(()=>{const C=h.width/2,P=h.height/2,L=140*p,E=u.createRadialGradient(C,P,0,C,P,L);E.addColorStop(0,"rgba(255, 255, 255, 0.18)"),E.addColorStop(1,"rgba(255, 255, 255, 0)"),u.fillStyle=E,u.beginPath(),u.arc(C,P,L,0,2*Math.PI),u.fill()})():h.style.mixBlendMode="unset";const g=Pt(),f=18,y=20,v=24,w=.16,b=.2,S=uS({docId:r,canvasWidth:c,canvasHeight:d,emojiSize:24,middleware:e,positions:[[307,155,f,w],[68,155,f,w],[317,95,f,w],[58,95,f,w],[292,52,f,w],[83,52,f,w],[213,195,f,b],[162,195,f,b],[273,204,f,w],[102,204,f,w],[253,163,y,b],[120,163,y,b],[258,75,f,b],[117,75,f,b],[269,113,v,b],[100,113,v,b],[230,44,y,b],[143,44,y,b],[187.5,34,f,b]],color:Ls.getProperty("primary-text-color"),onCacheStatus:C=>{C?S.then(g.resolve.bind(g)):g.resolve()}}).then(C=>{e()&&u.drawImage(C,0,0)});return this.container.prepend(this.emojiPatternCanvas),g},s=r=>{let l;if(r){const c=r.map(d=>Sb(d));c.length===1?l=c[0]:l=`linear-gradient(180deg, ${c.join(", ")})`}this.container.style.background=l,this.hasBackgroundColor=!!l},{colorSet:i,backgroundEmojiId:n}=h2(this.peerId),a=Pt();return ye(()=>{const r=i()?.bg_colors,l=n();s(r),this.setCollapsed(this.isCollapsed());const c=Ou();ye($s(c,()=>{const d=t(l,!!r);d?d.then(a.resolve.bind(a)):a.resolve()}))}),a}applyAppearance(){const e=this.middlewareHelper.get();return Jt(t=>(e.onDestroy(t),this._applyAppearance()))}addTab(){const e=document.createElement("div");e.classList.add(xs.BASE_CLASS+"-tab"),this.tabs.append(e),this.tabs.childElementCount===1&&e.classList.add("active"),this.container.classList.toggle("is-single",this.tabs.childElementCount<=1)}loadNearestToTarget(e){const t=Array.from(e.parentElement.children),s=t.indexOf(e);t.slice(Math.max(0,s-am),Math.min(t.length,s+am)).forEach(n=>{const a=this.loadCallbacks.get(n);a&&(a(),this.loadCallbacks.delete(n),this.intersectionObserver.unobserve(n))})}setCollapsed(e){!this.isCollapsed()&&e&&this.listLoader?.index&&this.goWithoutTransition(-this.listLoader.index),this.setCollapsedOn.classList.toggle("is-collapsed",e);const t=this.hasBackgroundColor||!e;this.setCollapsedOn.classList.contains("need-white")!==t&&(this.setCollapsedOn.classList.toggle("need-white",t),uw(this.info,t?"white":"primary-color")),this.updateHeaderFilled()}isCollapsed(){return this.setCollapsedOn.classList.contains("is-collapsed")}updateHeaderFilled(){this.setCollapsedOn.classList.toggle("header-filled",!this.hasBackgroundColor&&this.isCollapsed()&&this.scrollable.scrollPosition>=5||this.scrollable.scrollPosition>=240)}cleanup(){this.listenerSetter.removeAll(),this.swipeHandler.removeListeners(),this.intersectionObserver?.disconnect(),this.middlewareHelper.destroy()}};xs.BASE_CLASS="profile-avatars",xs.SCALE=No?2:1,xs.TRANSLATE_TEMPLATE=No?`translate3d({x}, 0, -1px) scale(${xs.SCALE})`:"translate({x}, 0)";let dg=xs;const Ya=(o,e)=>{kt(e.title,o||void 0),e.container.style.display=o?"":"none"};class rI{constructor(e,t,s,i=!0,n,a){this.managers=e,this.scrollable=t,this.listenerSetter=s,this.isDialog=i,this.setCollapsedOn=n,this.onPersonalChannel=a,No||this.scrollable.container.classList.add("no-parallax"),s||(this.listenerSetter=new Ut),this.middlewareHelper=xt()}init(){this.init=null,this.element=document.createElement("div"),this.element.classList.add("profile-content");const e=document.createElement("span");e.append(M("AccDescrChannel")),e.classList.add("personal-channel-name"),this.personalChannelCounter=document.createElement("span"),this.personalChannelCounter.classList.add("personal-channel-counter"),e.append(this.personalChannelCounter),this.personalChannelSection=new Pe({name:e}),Xe.setListClickListener({list:this.personalChannelSection.content,autonomous:!1,openInner:!0}),this.section=new Pe({noDelimiter:!0}),this.name=document.createElement("div"),this.name.classList.add("profile-name"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("profile-subtitle"),this.setCollapsedOn.classList.add("profile-container"),this.bio=new ve({title:" ",subtitle:!0,icon:"info",clickable:a=>{a.target.tagName!=="A"&&(Fs(this.bio.title.textContent),zs(ke.format("BioCopied",!0)))},listenerSetter:this.listenerSetter,contextMenu:{buttons:[{icon:"copy",text:"Text.CopyLabel_About",onClick:()=>{fs(this.bio.container)},verify:()=>!this.peerId.isUser()},{icon:"copy",text:"Text.CopyLabel_Bio",onClick:()=>{fs(this.bio.container)},verify:()=>this.peerId.isUser()},{icon:"premium_translate",text:"TranslateMessage",onClick:async()=>{I.premium?ee.createPopup(_C,{peerId:this.peerId,textWithEntities:{_:"textWithEntities",text:this.bioText,entities:[]},detectedLanguage:await this.bioLanguage}):Vt.show({feature:"translations"})},verify:async()=>!!await this.bioLanguage}]}}),this.bio.title.classList.add("pre-wrap"),this.username=new ve({title:" ",subtitleLangKey:"Username",icon:"username",clickable:()=>{Fs("@"+this.username.title.textContent),zs(ke.format("UsernameCopied",!0))},listenerSetter:this.listenerSetter,contextMenu:{buttons:[{icon:"copy",text:"Text.CopyLabel_Username",onClick:()=>{fs(this.username.container)}}]}}),this.phone=new ve({title:" ",subtitle:!0,icon:"phone",clickable:()=>{Fs(this.phone.title.textContent.replace(/\s/g,"")),zs(ke.format("PhoneCopied",!0))},listenerSetter:this.listenerSetter,contextMenu:{buttons:[{icon:"copy",text:"Text.CopyLabel_PhoneNumber",onClick:()=>{fs(this.phone.container)}},{icon:"info",text:"PeerInfo.Phone.AnonymousInfo",textArgs:[document.createElement("a")],onClick:()=>{ro("https://fragment.com/numbers")},separator:!0,secondary:!0,verify:async()=>{const{isAnonymous:a}=await this.managers.appUsersManager.getUserPhone(this.peerId.toUserId())||{};return a}}]}}),this.link=new ve({title:" ",subtitleLangKey:"SetUrlPlaceholder",icon:"link",clickable:()=>{const a="https://"+this.link.title.textContent;Fs(a);const r=a.includes("/c/");zs(ke.format(r?"LinkCopiedPrivateInfo":"LinkCopied",!0))},listenerSetter:this.listenerSetter,contextMenu:{buttons:[{icon:"copy",text:"Text.CopyLabel_ShareLink",onClick:()=>{fs(this.link.container)}}]}}),this.location=new ve({title:" ",subtitleLangKey:"ChatLocation",icon:"location"}),this.businessHours=Jt(a=>{this.middlewareHelper.onDestroy(a);const[r,l]=ne(),[c,d]=ne();return this.setBusinessHours=l,this.setTimezones=d,s2({hours:r,timezones:c})});const t=()=>{Fs(this._businessLocation.address),Ee({langPackKey:"BusinessLocationCopied"})};this.businessLocation=new ve({title:!0,subtitleLangKey:"BusinessProfileLocation",icon:"location",clickable:async()=>{const a=this._businessLocation;if(!a.geo_point){t();return}await Ct({descriptionLangKey:"Popup.OpenInGoogleMaps",button:{langKey:"Open"}}),ro(Lf(a.geo_point))},contextMenu:{buttons:[{icon:"copy",text:"Copy",onClick:t}]},listenerSetter:this.listenerSetter}),this.businessLocation.container.classList.add("business-location"),this.section.content.append(this.phone.container,this.username.container,this.location.container,this.bio.container,this.link.container,this.businessHours.container,this.businessLocation.container);const{listenerSetter:s}=this;this.isDialog&&(this.notifications=new ve({checkboxField:new pt({toggle:!0}),titleLangKey:"Notifications",icon:"unmute",listenerSetter:this.listenerSetter}),s.add(this.notifications.checkboxField.input)("change",a=>{a.isTrusted&&this.managers.appMessagesManager.togglePeerMute({peerId:this.peerId,threadId:this.threadId})}),s.add(I)("dialog_notify_settings",async a=>{if(this.peerId===a.peerId){const r=await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.peerId,respectType:!1,threadId:this.threadId});this.notifications.checkboxField.checked=!r}}),this.section.content.append(this.notifications.container)),this.element.append(this.personalChannelSection.container,this.section.container),No&&this.element.append(Ku()),s.add(I)("peer_typings",({peerId:a})=>{this.peerId===a&&this.setPeerStatus()}),s.add(I)("peer_bio_edit",a=>{a===this.peerId&&this.setMoreDetails(!0)});const i=async({peerId:a,threadId:r})=>this.peerId!==a?!1:!((this.peerId.isAnyChat()?await this.managers.appPeersManager.isForum(this.peerId):!1)&&this.threadId)||this.threadId===r;s.add(I)("peer_title_edit",async a=>{const r=this.middlewareHelper.get();if(await i(a)){if(!r())return;this.fillUsername().then(l=>{r()&&l?.()}),this.setMoreDetails(!0)}}),s.add(I)("user_update",a=>{this.peerId===a.toPeerId()&&this.setPeerStatus()}),s.add(I)("contacts_update",async a=>{this.peerId===a.toPeerId()&&(!(await this.managers.appUsersManager.getUser(a)).pFlags.self||!this.isDialog)&&this.fillUserPhone()}),s.add(I)("avatar_update",async a=>{await i(a)&&this.setAvatar()});const n=()=>{this.peerId.isUser()&&this.managers.appUsersManager.getApiUsers([this.peerId.toUserId()])};s.add(I)("premium_toggle",n),s.add(I)("privacy_update",a=>{a.key._==="privacyKeyStatusTimestamp"&&n()}),this.setPeerStatusInterval=window.setInterval(()=>this.setPeerStatus(),6e4)}async setPeerStatus(e=!1,t){const s=this.peerId,i=[];i.push(()=>{if(this.element.classList.toggle("is-me",s===I.myId),s.isUser()&&fe.getUser(s.toUserId()).status?.pFlags?.by_me){if(this.subtitle.querySelector(".show-when"))return;const l=M("StatusHiddenShow");l.classList.add("show-when"),N(l,c=>{oe(c),ee.createPopup(EC,s,"lastSeen")}),this.subtitle.append(l)}});let n=Promise.resolve();if(!(!s||I.myId===s&&this.isDialog)&&s!==Fg){const r=await this.managers.appPeersManager.isForum(this.peerId),l=this.middlewareHelper.get();r&&this.threadId?n=kS({peerId:s,wrapOptions:{middleware:l}}).then(({element:c})=>{this.subtitle.replaceChildren(c)}):n=me.setPeerStatus({peerId:s,element:this.subtitle,needClear:e,useWhitespace:!0,middleware:l,ignoreSelf:!this.isDialog}),n.then(c=>c&&i.unshift(c))}const a=()=>i.forEach(r=>r());return n.then(()=>{if(t)return a;a()})}cleanupHTML(){[this.bio,this.phone,this.username,this.location,this.link,this.businessHours,this.businessLocation,this.personalChannelSection].forEach(e=>{e.container.style.display="none"}),this.notifications&&(this.notifications.container.style.display="",this.notifications.checkboxField.checked=!0),this.clearSetMoreDetailsTimeout()}isSavedDialog(){return!!(this.peerId===I.myId&&this.threadId)}getDetailsForUse(){const{peerId:e,threadId:t}=this;return this.isSavedDialog()?{peerId:t,threadId:void 0}:{peerId:e,threadId:t}}canBeDetailed(){return this.peerId!==I.myId||!this.isDialog}async _setAvatar(){const e=this.middlewareHelper.get(),{peerId:t,threadId:s}=this.getDetailsForUse(),i=!!(s&&await this.managers.appPeersManager.isForum(t));if(!i&&(await this.managers.appPeersManager.getPeerPhoto(t)||aI)){const l=this.avatars;this.avatars=new dg(this.scrollable,this.managers,this.setCollapsedOn),await this.avatars.setPeer(t);const c=await this.fillName(e,this.setCollapsedOn.classList.contains("need-white"));return()=>{c(),this.avatars.info.append(this.name,this.subtitle),this.avatar&&this.avatar.node.remove(),this.avatar=void 0,l?l.container.replaceWith(this.avatars.container):this.element.prepend(this.avatars.container),No&&this.scrollable.container.classList.add("parallax"),this.section.content.classList.remove("has-simple-avatar")}}const n=es({middleware:e,size:120,isDialog:this.isDialog,peerId:t,threadId:i?s:void 0,wrapOptions:{customEmojiSize:vs(120,120),middleware:e},withStories:!0,meAsNotes:!!(t===I.myId&&this.threadId)});n.node.classList.add("profile-avatar","avatar-120");const[a]=await Promise.all([this.fillName(e,!1),n.readyThumbPromise]);return()=>{a(),No&&this.scrollable.container.classList.remove("parallax"),this.avatars&&(this.avatars.container.remove(),this.avatars.cleanup(),this.avatars=void 0),this.avatar&&this.avatar.node.remove(),this.avatar=n,this.section.content.classList.add("has-simple-avatar"),this.section.content.prepend(this.avatar.node,this.name,this.subtitle)}}setAvatar(e){const t=this._setAvatar();return e?t:t.then(s=>s())}getUsernamesAlso(e){const t=e.slice(1);if(t.length){const s=t.map(n=>sI({username:n}));return M("UsernameAlso",[pi(s,!1)])}}async fillUsername(){const{peerId:e}=this;if(e.isUser()&&this.canBeDetailed()){const t=await this.managers.appPeersManager.getPeerActiveUsernames(e),s=this.getUsernamesAlso(t);return()=>{this.username.subtitle.replaceChildren(s||M("Username")),Ya(t[0],this.username)}}}async fillUserPhone(){const{peerId:e}=this;if(e.isUser()&&this.canBeDetailed()){const{phone:t,isAnonymous:s}=await this.managers.appUsersManager.getUserPhone(e.toUserId())||{};return()=>{this.phone.subtitle.replaceChildren(M(s?"AnonymousNumber":"Phone")),Ya(t?Mf(t):void 0,this.phone)}}}async fillNotifications(){const e=this.notifications;if(e)if(this.canBeDetailed()){const t=await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.peerId,respectType:!1,threadId:this.threadId});return()=>{e.checkboxField.checked=!t}}else return()=>{e.container.style.display="none"}}async fillName(e,t){const{peerId:s}=this.getDetailsForUse(),[i]=await Promise.all([Oe({peerId:s,dialog:this.isDialog,withIcons:!this.threadId,threadId:this.threadId,wrapOptions:{middleware:e,textColor:t?"white":void 0},meAsNotes:!!(s===I.myId&&this.threadId)})]);return()=>{dt(this.name,i)}}async fillRows(e){return Promise.all([this.fillUsername(),this.fillUserPhone(),this.fillNotifications(),this.setMoreDetails(void 0,e),this.setPeerStatus(!0,!0)]).then(t=>()=>{t.forEach(s=>s?.())})}async fillProfileElements(){if(!this.cleaned)return;this.cleaned=!1,this.cleanupHTML();const e=Pt();this.middlewareHelper.get().onClean(()=>{e.reject()});const s=await Promise.all([this.setAvatar(!0),this.fillRows(e)]);return()=>{e.resolve(),s.forEach(i=>i?.())}}async _setMoreDetails(e,t,s,i){const n=this.middlewareHelper.get().create().get(),a=this.getMiddlewarePromise(),r=!!(this.threadId&&await a(this.managers.appPeersManager.isForum(e))),l=e.isUser()?await a(this.managers.appUsersManager.isPremium(e.toUserId())):void 0;if(r){let m="t.me/";const g=yn(this.threadId),f=await a(this.managers.appPeersManager.getPeerUsername(e));return f?m+=`${f}/${g}`:m+=`c/${e.toChatId()}/${g}`,()=>{Ya(m,this.link)}}const c=[];if(c.push(()=>{this.bio.subtitle.replaceChildren(M(e.isUser()?"UserBio":"Info")),Ya(t.about?Yt(t.about,{whitelistedDomains:l?void 0:s.whitelisted_domains}):void 0,this.bio),this.bioLanguage=kC(this.bioText=t.about)}),!e.isUser()){const m=await a(this.managers.appChatsManager.getChat(e.toChatId())),g=ui(m);let f;if(g.length)f=this.getUsernamesAlso(g),c.push(()=>Ya("t.me/"+g[0],this.link));else{const y=t.exported_invite;y?._==="chatInviteExported"&&c.push(()=>Ya(y.link.slice(y.link.indexOf("t.me/")),this.link))}c.push(()=>this.link.subtitle.replaceChildren(f||M("SetUrlPlaceholder")))}const d=t.location;d?._=="channelLocation"&&c.push(()=>Ya(d.address,this.location));const h=t.business_work_hours;h&&oa(()=>{this.setBusinessHours(h),this.setTimezones(i)}),c.push(()=>{this.businessHours.container.style.display=h?"":"none"});const u=t.business_location;if(this._businessLocation=u,u){const m=u.geo_point;if(c.push(()=>{Ya(_e(u.address),this.businessLocation),m||this.businessLocation.media?.remove()}),m){const g=this.businessLocation.createMedia("big");g.remove();const f=[];Ks({photo:jS(m,48,48,16),container:g,middleware:n,onRender:()=>{!n()||this._businessLocation!==u||this.businessLocation.container.append(g)},loadPromises:f}),await Promise.all(f)}}c.push(()=>{this.businessLocation.container.style.display=u?"":"none"});const p=t.personal_channel_id;if(p){const m=p.toPeerId(!0),g=t.personal_channel_message,f=fe.getChat(p),y=[],v=Xe.createChatList(),w=Xe.addDialogNew({peerId:m,container:v,rippleEnabled:!0,avatarSize:"abitbigger",append:!0,wrapOptions:{middleware:n},withStories:!0,loadPromises:y});w.container.classList.add("personal-channel");const b=k=>{const[x,A]=ne(),T=Hi(()=>pu({children:x,loading:K(()=>!x())}),k.element);return k.element.classList.add("skeleton-container"),k.middleware.onDestroy(T),A},C=!!fe.getMessageByPeer(m,g)&&!!1,L=this.managers.appMessagesManager.reloadMessages(m,g).then(async k=>{await Xe.setLastMessageN({dialog:{_:"dialog",peerId:m},lastMessage:k,dialogElement:w}),E?.(w.subtitle),_?.(w.dom.lastTimeSpan)});let E,_;if(!C){const k=w.subtitle.cloneNode(!0);w.subtitle.replaceWith(k),E=b({element:k,middleware:n});const x=w.dom.lastTimeSpan.cloneNode(!0);w.dom.lastTimeSpan.replaceWith(x),_=b({element:x,middleware:n})}C&&y.push(L),c.push(()=>{this.personalChannelCounter.replaceChildren(M("Subscribers",[Ha(f.participants_count)])),this.personalChannelSection.content.querySelector(".chatlist")?.remove(),this.personalChannelSection.content.append(v)}),await Promise.all(y)}return c.push(()=>{this.personalChannelSection.container.style.display=p?"":"none",this.onPersonalChannel?.(!!p)}),this.setMoreDetailsTimeout=window.setTimeout(()=>this.setMoreDetails(!0),6e4),()=>{c.forEach(m=>m())}}async setMoreDetails(e,t){this.clearSetMoreDetailsTimeout();const{peerId:s}=this,i=this.getMiddlewarePromise();if(!s||!this.canBeDetailed()||await i(this.managers.appPeersManager.isPeerRestricted(s)))return;const n=await i(Promise.all([this.managers.acknowledged.appProfileManager.getProfileByPeerId(s,e),this.managers.acknowledged.apiManager.getAppConfig(),this.managers.acknowledged.apiManager.getTimezonesList()])),a=n.map(l=>l.result),r=i(Promise.all(a)).then(async([l,c,d])=>{if(!await i(this.managers.appPeersManager.isPeerRestricted(s)))return i(this._setMoreDetails(s,l,c,d.timezones))});if(n.every(l=>l.cached)&&t)return r;(t||Promise.resolve()).then(()=>r).then(l=>{l?.()})}getMiddlewarePromise(){return so(this.middlewareHelper.get(),Ld("MIDDLEWARE"))}setPeer(e,t){this.peerId===e&&this.threadId===t||(this.init?.(),this.peerId=e,this.threadId=t,this.middlewareHelper.clean(),this.cleaned=!0)}clearSetMoreDetailsTimeout(){this.setMoreDetailsTimeout!==void 0&&(clearTimeout(this.setMoreDetailsTimeout),this.setMoreDetailsTimeout=void 0)}destroy(){this.peerId=this.threadId=void 0,this.clearSetMoreDetailsTimeout(),clearInterval(this.setPeerStatusInterval),this.avatars?.cleanup(),this.middlewareHelper.destroy()}}const Qv=64,u2=vs(Qv,Qv);class hg extends Dt{async init(e,t){this.colorIndex=0;const s=!t,i=t===Id;this.container.classList.add("edit-topic-container"),this.setTitle(s?"NewTopic":"ForumTopic.Title.Edit");const n=e.toChatId();t&&(this.topic=this.originalTopic=Wi(await this.managers.dialogsStorage.getForumTopic(e,t)));{const r=new Pe({name:i?"CreateGeneralTopicTitle":"CreateTopicTitle"}),l=this.iconDiv=document.createElement("div");l.classList.add("edit-topic-icon-container"),!t&&N(l,()=>{this.topic.icon_emoji_id||(this.colorIndex=(this.colorIndex+1)%ac.length,this.setIcon())},{listenerSetter:this.listenerSetter}),t&&l.classList.add("disable-hover");const c=document.createElement("div");c.classList.add("input-wrapper");const d=this.nameInputField=new _t({label:"ForumTopic.Name.Placeholder",withLinebreaks:!1,name:"topic-name",maxLength:70,required:!0});this.topic&&d.setOriginalValue(this.topic.title,!0);const h=this.confirmBtn=it("check btn-confirm blue hide",{noRipple:!0});this.header.append(h),N(h,()=>{const u=jt([h],!0);t?this.managers.appChatsManager.editForumTopic({chatId:n,topicId:t,title:d.value,iconEmojiId:this.topic.icon_emoji_id||0}).then(()=>{this.close()}).catch(p=>{console.error("edit topic error",p),u()}):this.managers.appChatsManager.createForumTopic({chatId:n,iconColor:ac[this.colorIndex],iconEmojiId:this.topic.icon_emoji_id,title:d.value}).then(p=>{this.close(),me.setInnerPeer({peerId:e,threadId:p})}).catch(p=>{console.error("create topic error",p),u()})},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(d.input)("input",()=>{this.validate(),this.setIcon(this.topic?.icon_emoji_id)}),c.append(d.container),r.content.append(l,c),this.scrollable.append(r.container)}const a=[];if(i){const r=new Pe({caption:"EditTopicHideInfo"}),l=new pt({checked:!this.topic.pFlags.hidden,text:"EditTopicHide"});this.listenerSetter.add(l.input)("change",()=>{const d=this.managers.appChatsManager.editForumTopic({chatId:n,topicId:t,hidden:!l.checked});c.disableWithPromise(d)});const c=new ve({checkboxField:l});r.content.append(c.container),this.scrollable.append(r.container)}else{const r=new Pe({});r.container.classList.add("edit-topic-emoticons-container");const l=new Un({managers:this.managers,isStandalone:!0,noRegularEmoji:!0,mainSets:()=>this.managers.appStickersManager.getLocalStickerSet("inputStickerSetEmojiDefaultTopicIcons").then(d=>d.documents.map(h=>h.id)),onClick:d=>{l.setActive(d.docId?d:{emoji:void 0,docId:void 0}),this.setIcon(d.docId)}});l.getContainerSize=()=>({width:Ii.rect.width,height:400}),this.middlewareHelper.onDestroy(()=>{l.destroy()}),l.container.classList.remove("tabs-tab"),this.emojiElement=document.createElement("span"),this.emojiElement.classList.add("super-emoji-topic-icon");const c=l.init().then(async()=>{const d=l.getCustomCategory(),h=this.topic?.icon_emoji_id;l.addEmojiToCategory({category:d,element:this.emojiElement,batch:!1,prepend:!0,active:!h}),h&&l.setActive({docId:h,emoji:""})});a.push(c),r.content.replaceWith(l.container),this.scrollable.append(r.container)}return Promise.all(a).then(()=>this.s())}validate(){let e=this.nameInputField.isValidToChange();!e&&this.originalTopic&&(e=this.topic.icon_emoji_id!==this.originalTopic.icon_emoji_id),this.confirmBtn.classList.toggle("hide",!e)}s(){return this.topic?.icon_color&&(this.colorIndex=ac.indexOf(this.topic.icon_color)),this.setIcon(this.topic?.icon_emoji_id,void 0,!0)}async setIcon(e,t=this.iconDiv,s){const i=this.nameInputField.value,n=t===this.iconDiv;if(n){const d={id:this.topic?.id,icon_color:ac[this.colorIndex],title:zg(i,!0).text||"A",icon_emoji_id:e},h=this.topic;if(this.topic=d,(s||!h||h.icon_color!==d.icon_color||h.title!==d.title)&&this.setIcon(void 0,this.emojiElement),Di(h,d)&&!s)return;this.validate()}const a=await Bu({topic:n?this.topic:{...this.topic,icon_emoji_id:void 0},customEmojiSize:u2,middleware:this.middlewareHelper.get()}),r=document.createElement("div");r.classList.add("edit-topic-icon"),r.append(a);const l=t.lastElementChild;t.append(r);const c=(d,h)=>{const u=[{opacity:"0",transform:"scale(0.8)"},{opacity:"1",transform:"scale(1)"}],p=d.animate(u,{duration:200,iterations:1,easing:"ease-in-out",fill:"forwards",direction:h?"normal":"reverse"});return new Promise(m=>{p.addEventListener("finish",()=>{m()},{once:!0})})};l&&c(l,!1).then(()=>l.remove()),c(r,!0)}}class Yv extends Dt{async init(e){const t=e.toUserId();this.container.classList.add("edit-profile-container"),this.setTitle("EditBot.Title");const s=[],[i,n,a]=await Promise.all([this.managers.apiManager.getLimit("bio"),this.managers.appUsersManager.getUser(t),this.managers.appProfileManager.getBotInfo(t)]);{const r=ml(this.scrollable,void 0),l=document.createElement("div");l.classList.add("input-wrapper"),this.firstNameInputField=new _t({label:"EditProfile.FirstNameLabel",name:"first-name",maxLength:70}),this.aboutInputField=new _t({label:"DescriptionPlaceholder",name:"bio",maxLength:i}),l.append(this.firstNameInputField.container,this.aboutInputField.container),s.push(this.firstNameInputField,this.aboutInputField),this.editPeer=new kd({peerId:e,inputFields:s,listenerSetter:this.listenerSetter,middleware:this.middlewareHelper.get()}),this.content.append(this.editPeer.nextBtn),r.append(this.editPeer.avatarEdit.container,l)}{const r=ml(this.scrollable,void 0,"EditBot.Buttons.Caption"),l=ze("btn-primary btn-transparent",{icon:"info",text:"EditBot.Buttons.Intro",asLink:!0}),c=ze("btn-primary btn-transparent",{icon:"botcom",text:"EditBot.Buttons.Commands",asLink:!0}),d=ze("btn-primary btn-transparent",{icon:"bots",text:"EditBot.Buttons.Settings",asLink:!0}),h="t.me/botfather?start="+Vc(n);[[l,"intro"],[c,"commands"],[d,""]].forEach(([p,m])=>{const g=cl(h+(m?"-"+m:""));p.href=g.url,p.setAttribute("onclick",g.onclick+"(this)")}),r.append(l,c,d)}{const r=new Pe({name:"EditAccount.Username",caption:!0}),l=document.createElement("div");l.classList.add("input-wrapper"),this.usernameInputField=new Jg({label:"Username",name:"username",plainText:!0,listenerSetter:this.listenerSetter,onChange:()=>{this.editPeer.handleChange();const{error:u}=this.usernameInputField,p=u?.type==="USERNAME_PURCHASE_AVAILABLE";d(p?this.usernameInputField.value:void 0)},availableText:"EditProfile.Username.Available",takenText:"EditProfile.Username.Taken",invalidText:"EditProfile.Username.Invalid"},this.managers),l.append(this.usernameInputField.container);const c=r.caption,{setUsername:d,element:h}=sf();c.append(M("EditBot.Username.Caption"),h),s.push(this.usernameInputField),r.content.append(l),this.scrollable.append(r.container)}{const r=new tf({peerId:e,peer:n,listenerSetter:this.listenerSetter,usernameInputField:this.usernameInputField,middleware:this.middlewareHelper.get()});this.scrollable.append(r.container)}N(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0;const r=[],l=this.managers.appProfileManager.setBotInfo(t,this.firstNameInputField.value,this.aboutInputField.value);r.push(l.then(()=>{this.close()},c=>{console.error("updateProfile error:",c)})),this.editPeer.uploadAvatar&&r.push(this.editPeer.uploadAvatar().then(c=>this.managers.appProfileManager.uploadProfilePhoto(c,t))),this.usernameInputField.isValidToChange()&&r.push(this.managers.appUsersManager.updateUsername(this.usernameInputField.value)),Promise.race(r).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter}),this.firstNameInputField.setOriginalValue(n.first_name,!0),this.aboutInputField.setOriginalValue(a.about,!0),this.usernameInputField.setOriginalValue(Vc(n),!0),this.editPeer.handleChange()}}const ec={};class co extends Dt{init(){this.init=null,this.container.classList.add("shared-media-container");const e=ze("btn-icon sidebar-close-button",{noRipple:!0});this.closeBtn.replaceWith(e),this.closeBtn=e;const t=document.createElement("div");t.classList.add("animated-close-icon"),e.append(t),this.isFirst&&t.classList.add("state-back");const s=()=>{const v=document.createElement("div");return v.className="transition slide-fade",v},i=s(),n=(v,w,b)=>{const S=document.createElement("div");S.classList.add("transition-item"),b??(b=this.title.cloneNode()),b.append(v);let C;if(w)S.append(b);else{const P=document.createElement("div");P.classList.add("sidebar-header__rows"),C=document.createElement("div"),C.classList.add("sidebar-header__subtitle"),P.append(b,C),S.append(P)}return{element:S,title:b,subtitle:C}};this.titleI18n=new ke.IntlElement;const a=n(this.titleI18n.element,!0,this.title);this.editBtn=it("edit");const r=this.btnMenu=ai({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[{icon:"message",text:"SavedViewAsMessages",onClick:()=>{me.toggleViewAsMessages(I.myId,!0)},verify:()=>this.peerId===I.myId&&this.isFirst}]});a.element.append(this.editBtn);let l;(v=>{v[v.Profile=0]="Profile",v[v.Media=1]="Media"})(l||(l={}));const c=n(M("PeerInfo.SharedMedia"));this.sharedMediaTitle=c.title;const d=s();c.subtitle.append(d);const h=[["savedDialogs","SavedDialogsTabCount"],["stories","StoriesCount"],["members","Members"],["media","MediaFiles"],["saved","SavedMessagesCount"],["files","Files"],["links","Links"],["music","MusicFiles"],["voice","Voice"],["groups","CommonGroups"],["similar","SimilarChannelsCount"]];d.append(...h.map(v=>{v[2]=new ke.IntlElement({key:"Loading"});const w=document.createElement("div");return w.classList.add("transition-item"),w.append(v[2].element),w})),i.append(...[a,c].map(({element:v})=>v)),this.header.append(i,r),this.noProfile||(this.profile=new rI(this.managers,this.scrollable,this.listenerSetter,!0,this.container),this.profile.init(),this.scrollable.append(this.profile.element));const u=56;this.scrollable.onAdditionalScroll=()=>{const v=this.searchSuper.nav.getBoundingClientRect();if(!v.width)return;const w=v.top-1;m(w<=u)};const p=(v=g.prevId()!==0)=>{let w=0;return v&&(w=1),w},m=v=>{t.classList.toggle("state-back",this.isFirst||v),this.searchSuper.container.classList.toggle("is-full-viewport",v),g(p(v)),v||this.searchSuper.cleanScrollPositions()},g=Na({content:i,type:"slide-fade",transitionTime:400,isHeavy:!1});g(this.profile?0:1);const f=Na({content:d,type:"slide-fade",transitionTime:400,isHeavy:!1});f(0),N(this.closeBtn,v=>{g.prevId()&&this.profile?(this.scrollable.scrollIntoViewNew({element:this.scrollable.container.querySelector(".profile-content"),position:"start"}),g(0),this.isFirst||(t.classList.remove("state-back"),this.container.classList.remove("header-filled"))):this.scrollable.isHeavyAnimationInProgress||this.slider.onCloseBtnClick()},{listenerSetter:this.listenerSetter}),N(this.editBtn,async()=>{let v;const{peerId:w,threadId:b}=this;b&&await this.managers.appPeersManager.isForum(w)?v=this.slider.createTab(hg):w.isAnyChat()?v=this.slider.createTab(Kv):await this.managers.appUsersManager.isBot(w)?v=this.slider.createTab(Yv):v=this.slider.createTab(Qm),v&&(v instanceof hg?v.open(w,this.threadId):v instanceof Yv?v.open(w):(v instanceof Kv?v.chatId=w.toChatId():v.peerId=w,v.open()))},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(I)("contacts_update",v=>{this.peerId===v.toPeerId(!1)&&this.toggleEditBtn()}),this.listenerSetter.add(I)("chat_update",v=>{this.peerId===v.toPeerId(!0)&&this.toggleEditBtn()}),this.listenerSetter.add(I)("history_multiappend",v=>{this.renderNewMessage(v)}),this.listenerSetter.add(I)("history_delete",({peerId:v,msgs:w})=>{this.deleteDeletedMessages(v,w)}),this.searchSuper=new $f({mediaTabs:[{name:"SharedMedia.SavedDialogs",type:"savedDialogs"},{name:"Stories",type:"stories"},{name:"PeerMedia.Members",type:"members"},{inputFilter:"inputMessagesFilterPhotoVideo",name:"SharedMediaTab2",type:"media"},{inputFilter:"inputMessagesFilterEmpty",name:"SharedMedia.Saved",type:"saved"},{inputFilter:"inputMessagesFilterDocument",name:"SharedFilesTab2",type:"files"},{inputFilter:"inputMessagesFilterUrl",name:"SharedLinksTab2",type:"links"},{inputFilter:"inputMessagesFilterMusic",name:"SharedMusicTab2",type:"music"},{inputFilter:"inputMessagesFilterRoundVoice",name:"SharedVoiceTab2",type:"voice"},{name:"ChatList.Filter.Groups",type:"groups"},{name:"SimilarChannels",type:"similar"}],scrollable:this.scrollable,onChangeTab:v=>{f(h.findIndex(b=>b[0]===v.type));const w=v.type==="members"&&st.isAvailable("animations")?250:0;setTimeout(()=>{y.classList.toggle("is-hidden",v.type!=="members")},w)},managers:this.managers,onLengthChange:(v,w)=>{const b=h.find(S=>S[0]===v);b&&b[2].compareAndUpdate({key:b[1],args:[w]})},openSavedDialogsInner:!this.isFirst,slider:this.slider}),this.searchSuper.scrollStartCallback=()=>{m(!0),this.container.classList.add("header-filled")},this.searchSuper.scrollOffset=56,this.profile?this.profile.element.append(this.searchSuper.container):this.scrollable.append(this.searchSuper.container);const y=Ei({icon:"addmember_filled"});this.content.append(y),N(y,()=>{Nw({peerId:this.peerId,slider:this.slider})},{listenerSetter:this.listenerSetter})}_renderNewMessage(e,t=e.peerId,s){const i=ec[t]?.[s];if(i)for(const n of this.searchSuper.mediaTabs){const a=n.inputFilter,r=i[a];if(!r)continue;let l;if(n.type==="saved"?l=[e].filter(d=>{const h=d.saved_peer_id;return h&&at(h)===this.searchSuper.searchContext.peerId&&!r.some(u=>u.mid===d.mid)}):l=this.searchSuper.filterMessagesByType([e],a),!l.length)continue;const c=l.filter(d=>!r.find(h=>h.mid===d.mid&&h.peerId===d.peerId)).map(d=>({mid:d.mid,peerId:d.peerId}));r.unshift(...c),(n.type==="saved"?this.peerId===s:this.peerId===t)&&this.searchSuper.usedFromHistory[a]!==-1&&this.threadId===s&&(this.searchSuper.usedFromHistory[a]+=l.length,this.searchSuper.performSearchResult(l,n,!1),this.searchSuper.setCounter(n.type,this.searchSuper.counters[n.type]+l.length))}}async renderNewMessage(e){if(this.init)return;const{peerId:t}=e,s=await this.managers.appPeersManager.isForum(t),i=ha(e,s);this._renderNewMessage(e),i&&this._renderNewMessage(e,void 0,i)}_deleteDeletedMessages(e,t,s,i){for(const n of s)for(const a of this.searchSuper.mediaTabs){const r=a.inputFilter,l=e[r];if(!l)continue;const c=a.type==="saved"?this.peerId===i:this.peerId===t&&this.threadId===i;c&&this.searchSuper.setCounter(a.type,this.searchSuper.counters[a.type]-s.length);const d=l.findIndex(h=>h.mid===n);if(d===-1&&l.splice(d,1),c){const h=this.searchSuper.tabs[r],u=h.querySelector(`[data-mid="${n}"][data-peer-id="${t}"]`);if(u){this.searchSuper.selection.isSelecting&&this.searchSuper.selection.toggleByElement(u);const p=h.querySelectorAll("[data-mid][data-peer-id]"),m=Array.from(p).indexOf(u);u.remove(),m!==-1&&this.searchSuper.usedFromHistory[r]>=m+1&&--this.searchSuper.usedFromHistory[r]}}}}deleteDeletedMessages(e,t){if(this.init)return;const s=ec[e];if(!s)return;const i=[...t.keys()];for(const n in s)this._deleteDeletedMessages(s[n],e,i,isNaN(+n)?void 0:+n);this.scrollable.onScroll()}async cleanupHTML(){const e=this.peerId.isAnyChat(),[t,s]=await Promise.all([e?this.searchSuper.canViewMembers():!1,e?this.managers.appChatsManager.hasRights(this.peerId.toChatId(),"invite_users"):!1]);return()=>{this.profile?.cleanupHTML(),this.editBtn.classList.add("hide"),this.searchSuper.cleanupHTML(!0),this.container.classList.toggle("can-add-members",t&&s)}}setLoadMutex(e){this.searchSuper.loadMutex=e}getHistoryStorage(e,t){var s;return(s=ec[e]??(ec[e]={}))[t]??(s[t]={})}setPeer(e,t){var i;if(this.peerId===e&&this.threadId===t)return!1;this.peerId=e,this.threadId=t,this.noProfile??(this.noProfile=e===I.myId),this.peerChanged=!0,this.init&&this.init();const s=this.getHistoryStorage(e,t);return s.inputMessagesFilterEmpty=(i=this.getHistoryStorage(I.myId,e)).inputMessagesFilterEmpty??(i.inputMessagesFilterEmpty=[]),this.searchSuper.setQuery({peerId:e,threadId:t,historyStorage:s}),this.profile?.setPeer(e,t),!0}async changeTitleKey(){const{peerId:e,threadId:t}=this,s=!!(e===I.myId&&t),i=s?t:e,[n,a,r,l]=await Promise.all([this.managers.appPeersManager.isForum(i),this.managers.appPeersManager.isBroadcast(i),this.managers.appPeersManager.isBot(i),Oe({peerId:e,threadId:s?void 0:t,meAsNotes:s&&t===I.myId,dialog:!0})]);return()=>{this.titleI18n.compareAndUpdate({key:r?"Profile.Info.Bot":a?"Profile.Info.Channel":t&&n?"Profile.Info.Topic":i.isUser()?"Profile.Info.User":"Profile.Info.Group"}),this.sharedMediaTitle.replaceChildren(l),this.btnMenu.classList.toggle("hide",!this.isFirst||s||e!==I.myId)}}async fillProfileElements(){if(!this.peerChanged)return;this.peerChanged=!1;const e=await Promise.all([this.cleanupHTML(),this.toggleEditBtn(!0),this.profile?.fillProfileElements(),this.changeTitleKey()]);return()=>{e.forEach(t=>{t?.()})}}async toggleEditBtn(e){const{peerId:t}=this;let s;if(t.isUser())s=t!==I.myId&&await this.managers.appUsersManager.canEdit(t.toUserId());else{const n=t.toChatId();this.threadId&&fe.isForum(t)?s=await this.managers.dialogsStorage.canManageTopic(await this.managers.dialogsStorage.getForumTopic(t,this.threadId)):s=!!fe.getChat(n).admin_rights||await this.managers.appChatsManager.hasRights(n,"change_info")}const i=()=>{this.editBtn.classList.toggle("hide",!s)};return e?i:i()}loadSidebarMedia(e,t){return this.searchSuper.load(e,t)}onOpenAfterTimeout(){super.onOpenAfterTimeout(),this.scrollable.onScroll()}onCloseAfterTimeout(){super.onCloseAfterTimeout(),this.destroyable&&(this.profile?.destroy(),this.searchSuper.destroy())}destroy(){this.destroyable=!0,this.onCloseAfterTimeout()}static async open(e,t,s){const i=e.createTab(co,!0);return i.noProfile=s,i.isFirst=!0,i.setPeer(t),(await i.fillProfileElements())(),await i.loadSidebarMedia(!0),i.open()}}const Lc="is-right-column-shown";class p2 extends Mw{constructor(){super({sidebarEl:document.getElementById("column-right"),canHideFirst:!0,navigationType:"right"}),this.isColumnProportionSet=!1}construct(e){this.managers=e,$e.addEventListener("changeScreen",(t,s)=>{s===hi.medium&&t!==hi.mobile&&this.toggleSidebar(!1)}),$e.addEventListener("resize",()=>{this.setColumnProportion()})}createSharedMediaTab(){const e=this.createTab(co,!1,!0);return e.slider=this,e}replaceSharedMediaTab(e){const t=this.sharedMediaTab;if(t){const s=this.historyTabIds.indexOf(t);this._selectTab.getFrom()===t.container&&this._selectTab.setFrom(e?.container),e?(s!==-1&&(this.historyTabIds[s]=e),t.container.classList.contains("active")&&e.container.classList.add("active"),t.container.replaceWith(e.container)):(s!==-1&&this.historyTabIds.splice(s,1),t.container.remove())}else this.tabsContainer.prepend(e.container);this.sharedMediaTab=e}onCloseTab(e,t,s){this.historyTabIds.length||this.toggleSidebar(!1,t),super.onCloseTab(e,t,s)}setColumnProportion(){const e=this.sidebarEl.previousElementSibling.scrollWidth,t=this.sidebarEl.scrollWidth/e;document.documentElement.style.setProperty("--right-column-proportion",""+t),document.documentElement.style.setProperty("--middle-column-width",e+"px"),document.documentElement.style.setProperty("--middle-column-width-value",""+e)}hide(){document.body.classList.remove(Lc),ft.removeByType("right")}toggleSidebar(e,t){const s=document.body.classList.contains(Lc);let i;if(e!==void 0?e?s||(i=!0):s&&(i=!0):i=!0,!i)return Promise.resolve();!s&&!this.historyTabIds.length&&this.sharedMediaTab.open(),this.isColumnProportionSet||(this.setColumnProportion(),this.isColumnProportionSet=!0);const n=me.selectTab(s?Ll.CHAT:Ll.PROFILE,t);return e?(document.body.classList.add(Lc),ft.findItemByType("right")||this.pushNavigationItem(this.sharedMediaTab)):this.hide(),n}}const oI=new p2;Ws.appSidebarRight=oI;const ls=oI;function Hf(o){return SS({...o,onSwipe:(e,t,s)=>{if(e*=-1,t*=-1,Math.abs(e)>50)return o.onSwipe(e,t,s),Sw(),!0}})}function m2(o){const e=i=>{oe(i)};let t=2;const s=()=>{--t||o.removeEventListener("touchmove",e,{capture:!0})};return o.addEventListener("touchmove",e,{capture:!0,passive:!1}),o.addEventListener("touchend",s,{once:!0}),s}function g2({inputFilter:o,messages:e,limit:t,savedReaction:s}){if(o==="inputMessagesFilterEmpty"&&!s)return e.slice(0,t);const i=[];if(!e.length)return i;let n=!0;const a={},r=[],l=[];switch(o){case"inputMessagesFilterPhotos":a.messageMediaPhoto=!0;break;case"inputMessagesFilterPhotoVideo":a.messageMediaPhoto=!0,a.messageMediaDocument=!0,r.push("video");break;case"inputMessagesFilterVideo":a.messageMediaDocument=!0,r.push("video");break;case"inputMessagesFilterDocument":a.messageMediaDocument=!0,r.push(void 0,"photo","pdf");break;case"inputMessagesFilterVoice":a.messageMediaDocument=!0,r.push("voice");break;case"inputMessagesFilterRoundVoice":a.messageMediaDocument=!0,r.push("round","voice");break;case"inputMessagesFilterRoundVideo":a.messageMediaDocument=!0,r.push("round");break;case"inputMessagesFilterMusic":a.messageMediaDocument=!0,r.push("audio");break;case"inputMessagesFilterUrl":a.url=!0;break;case"inputMessagesFilterChatPhotos":a.avatar=!0;break;case"inputMessagesFilterPinned":l.push("pinned");break;default:n=!1;break}if(!n&&!s?.length)return i;for(let c=0,d=e.length;c<d;++c){const h=e[c];if(!h)continue;let u=!n;if(l?.some(p=>h.pFlags[p]))u=!0;else if(h._==="message"){if(h.media&&a[h.media._]){const p=h.media.document;if(p&&r.length&&!r.includes(p.type))continue;u=!0}else if(a.url&&h.message){const p=["messageEntityTextUrl","messageEntityUrl"];(h.totalEntities.find(m=>p.includes(m._))||vu(h.message))&&(u=!0)}if(u&&s){const p=h.reactions?.results;u=p?s.every(m=>p.some(g=>en(g.reaction,m))):!1}}else a.avatar&&h.action&&["messageActionChannelEditPhoto","messageActionChatEditPhoto","messageActionChannelEditVideo","messageActionChatEditVideo"].includes(h.action._)&&(u=!0);if(u&&i.push(h)>=t)break}return i}const f2=ce("<div class=grid>");function y2(o){const[e,t]=Io(),[s,i]=ne(),[n,a]=ne(0),[r,l]=ne(),c=new Map;Ao(()=>{const u=j(ti,{get each(){return e.peer.stories},children:h});ye(()=>{const p=u(),m=p.length;a(m),i(p),o.onLengthChange?.(m)}),o.onLengthChange&&ye(()=>{o.onLengthChange(e.peer?.count)}),o.onReady?.()})(()=>e.ready),ye(()=>{const u=r();if(!u)return;const p=()=>{l(void 0)},m=K(()=>{const g=e.peer.stories[e.peer.index].id;return c.get(g)});Et(()=>{const g=e.peer,f=g.stories.findIndex(y=>y.id===u);t.set({peer:g,index:f})}),Od({onExit:p,target:m,splitByDays:!0})});const h=u=>{const{container:p,div:m,media:g,thumb:f}=Dd({peerId:e.peer.peerId,storyItem:u,forPreview:!0,noAspecter:!0,containerProps:{"data-mid":u.id,"data-peer-id":e.peer.peerId,class:"grid-item search-super-item",onClick:v=>{l(u.id)}},childrenClassName:"grid-item-media",noPlayButton:!0});let y;return ye(()=>{const v=f(),b=g()||v;if(b){if(c.set(u.id,b),ut(()=>{c.delete(u.id)}),n()===1){const S=u.media,C=S.photo||S.document,L=Oc({photo:C,cacheContext:{type:"x",url:"",downloaded:0},useBlur:!0,ignoreCache:!0,onlyStripped:!0}).image;b.parentElement.prepend(L),ut(()=>{L.remove()})}b.parentElement&&o.pinned&&u.pinnedIndex!==void 0?(y??(y=Le("pin2","grid-item-pin")),b.parentElement.append(y)):y&&y.remove()}}),o.selection?.isSelecting&&o.selection.toggleElementCheckbox(m,!0),p};return(()=>{const u=f2();return D(u,s),Ve(p=>{const m=n()===2,g=n()===1;return m!==p._v$&&u.classList.toggle("two",p._v$=m),g!==p._v$2&&u.classList.toggle("one",p._v$2=g),p},{_v$:void 0,_v$2:void 0}),u})()}function v2(o){const[,e]=Xn(o,["onReady","onLengthChange","selection"]);return j(Nf,Ai(e,{get children(){return j(y2,Ai(o,{get pinned(){return e.pinned}}))}}))}class b2{constructor(e,t,s,i){this.attachTo=e,this.searchSuper=t,this.listenerSetter=s,this.storiesPinned=i,this.onGotoClick=()=>{me.setInnerPeer({peerId:this.peerId,lastMsgId:this.mid,threadId:this.searchSuper.mediaTab.type==="saved"?this.searchSuper.searchContext.peerId:this.searchSuper.searchContext.threadId})},this.onForwardClick=()=>{this.searchSuper.selection.isSelecting?fs(this.searchSuper.selection.selectionForwardBtn):ee.createPopup(va,{[this.peerId]:[this.mid]})},this.onSelectClick=()=>{this.searchSuper.selection.toggleByElement(this.target)},this.onClearSelectionClick=()=>{this.searchSuper.selection.cancelSelection()},this.onDeleteClick=()=>{this.storyItem?this.searchSuper.selection.onDeleteStoriesClick([this.storyItem.id]):this.searchSuper.selection.isSelecting?fs(this.searchSuper.selection.selectionDeleteBtn):ee.createPopup(Rl,this.peerId,[this.mid],te.Chat)},this.onStoryTogglePinClick=a=>{this.searchSuper.selection.onPinClick([this.storyItem.id],a)},this.onStoryToggleToTopClick=a=>{this.searchSuper.selection.onPinToTopClick([this.storyItem.id],a)},this.managers=t.managers,za({element:e,callback:a=>{this.init&&(this.init(),this.init=null);let r;try{r=U(a.target,"search-super-item")}catch{}const l=!!U(a.target,"search-super-content-stories");if(!r)return;if(a instanceof MouseEvent&&a.preventDefault(),this.element.classList.contains("active"))return!1;a instanceof MouseEvent&&(a.cancelBubble=!0),(async()=>{this.target=r,this.peerId=r.dataset.peerId.toPeerId(),this.mid=+r.dataset.mid,this.isSelected=t.selection.isMidSelected(this.peerId,this.mid),this.message=l?void 0:await this.managers.appMessagesManager.getMessageByPeer(this.peerId,this.mid),this.storyItem=l?await this.managers.appStoriesManager.getStoryById(this.peerId,this.mid):void 0,this.noForwards=l||(t.selection.isSelecting?this.searchSuper.selection.selectionForwardBtn.classList.contains("hide"):!await this.managers.appMessagesManager.canForward(this.message)),this.selectedMessages=!l&&t.selection.isSelecting?await t.selection.getSelectedMessages():void 0,(await Promise.all(this.buttons.map(async h=>{let u;return this.searchSuper.selection.isSelecting&&!h.withSelection?u=!1:u=h.verify?!!await h.verify():!0,h.element.classList.toggle("hide",!u),u}))).some(h=>h)&&(r.classList.add("menu-open"),Tl(a,this.element),Js.openBtnMenu(this.element,()=>{r.classList.remove("menu-open")}))})()},listenerSetter:s})}init(){this.buttons=[{icon:"forward",text:"Forward",onClick:this.onForwardClick,verify:()=>!this.noForwards},{icon:"forward",text:"Message.Context.Selection.Forward",onClick:this.onForwardClick,verify:()=>this.searchSuper.selection.isSelecting&&!this.noForwards,withSelection:!0},{icon:"download",text:"MediaViewer.Context.Download",onClick:()=>ki.onDownloadClick(this.message,this.noForwards),verify:()=>!this.searchSuper.selection.isSelecting&&ki.canDownload(this.message,void 0,this.noForwards)},{icon:"download",text:"Message.Context.Selection.Download",onClick:()=>ki.onDownloadClick(this.selectedMessages,this.noForwards),verify:()=>this.searchSuper.selection.isSelecting&&ki.canDownload(this.selectedMessages,void 0,this.noForwards),withSelection:!0},{icon:"message",text:"Message.Context.Goto",onClick:this.onGotoClick,verify:()=>!this.storyItem,withSelection:!0},{icon:"archive",text:"Archive",onClick:()=>this.onStoryTogglePinClick(!1),verify:()=>this.storyItem&&this.storyItem.pFlags.pinned&&this.managers.appStoriesManager.hasRights(this.peerId,this.storyItem.id,"pin")},{icon:"unarchive",text:"Unarchive",onClick:()=>this.onStoryTogglePinClick(!0),verify:()=>this.storyItem&&!this.storyItem.pFlags.pinned&&this.managers.appStoriesManager.hasRights(this.peerId,this.storyItem.id,"pin")},{icon:"pin",text:"ChatList.Context.Pin",onClick:()=>this.onStoryToggleToTopClick(!0),verify:()=>this.storiesPinned&&this.storyItem&&this.storyItem.pinnedIndex===void 0&&this.managers.appStoriesManager.hasRights(this.peerId,this.storyItem.id,"pin")},{icon:"unpin",text:"ChatList.Context.Unpin",onClick:()=>this.onStoryToggleToTopClick(!1),verify:()=>this.storiesPinned&&this.storyItem&&this.storyItem.pinnedIndex!==void 0&&this.managers.appStoriesManager.hasRights(this.peerId,this.storyItem.id,"pin")},{icon:"select",text:"Message.Context.Select",onClick:this.onSelectClick,verify:()=>!this.isSelected&&(!this.storyItem||this.storyItem.pFlags.out),withSelection:!0},{icon:"select",text:"Message.Context.Selection.Clear",onClick:this.onClearSelectionClick,verify:()=>this.isSelected,withSelection:!0},{icon:"delete",className:"danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>this.storyItem?this.managers.appStoriesManager.hasRights(this.peerId,this.storyItem.id,"delete"):!this.searchSuper.selection.isSelecting&&this.managers.appMessagesManager.canDeleteMessage(this.message)},{icon:"delete",className:"danger",text:"Message.Context.Selection.Delete",onClick:this.onDeleteClick,verify:()=>this.searchSuper.selection.isSelecting&&this.searchSuper.selection.selectionDeleteBtn&&!this.searchSuper.selection.selectionDeleteBtn.classList.contains("hide"),withSelection:!0}],this.element=jn({buttons:this.buttons,listenerSetter:this.listenerSetter}),this.element.classList.add("search-contextmenu","contextmenu"),document.getElementById("page-chats").append(this.element)}}class $f{constructor(e){this.tabs={},this.prevTabId=-1,this.lazyLoadQueue=new Ga,this.middleware=xt(),this.historyStorage={},this.usedFromHistory={},this.nextRates={},this.loadPromises={},this.loaded={},this.loadedChats=!1,this.firstLoad=!0,this.log=ri("SEARCH-SUPER"),this.monthContainers={},this.mediaTabsMap=new Map,this.asChatList=!1,this.groupByMonth=!0,this.hideEmptyTabs=!0,this.showSender=!1,this.counters={},this.onTransitionStart=()=>{this.container.classList.add("sliding")},this.onTransitionEnd=()=>{this.container.classList.remove("sliding")},It(this,e),this.slider??(this.slider=ls),this.container=document.createElement("div"),this.container.classList.add("search-super"),this.listenerSetter=new Ut,this.searchContextMenu=new b2(this.container,this,this.listenerSetter,!this.storiesArchive),this.selection=new vT(this,this.managers,this.listenerSetter),this.storiesArchive&&(this.selection.isStoriesArchive=!0);const t=this.navScrollableContainer=document.createElement("div");t.classList.add("search-super-tabs-scrollable","menu-horizontal-scrollable","sticky");const s=this.navScrollable=new yr(t);s.container.classList.add("search-super-nav-scrollable");const i=this.nav=document.createElement("nav");i.classList.add("search-super-tabs","menu-horizontal-div"),this.tabsMenu=i,s.container.append(i);for(const r of this.mediaTabs){const l=document.createElement("div");l.classList.add("menu-horizontal-div-item");const c=document.createElement("span");c.classList.add("menu-horizontal-div-item-span");const d=document.createElement("i");c.append(r.menuTabName=M(r.name)),c.append(d),l.append(c),Ni(l),this.tabsMenu.append(l),this.mediaTabsMap.set(r.type,r),r.menuTab=l}this.tabsContainer=document.createElement("div"),this.tabsContainer.classList.add("search-super-tabs-container","tabs-container");let n;Je&&(this.swipeHandler=Hf({element:this.tabsContainer,onSwipe:(r,l,c)=>{r*=-1;const d=this.selectTab.prevId(),h=Array.from(this.tabsMenu.children);let u;if(r>0){for(let p=d+1;p<h.length;++p)if(!h[p].classList.contains("hide")){u=p;break}}else for(let p=d-1;p>=0;--p)if(!h[p].classList.contains("hide")){u=p;break}u!==void 0&&(n=m2(this.tabsContainer),this.selectTab(u))},verifyTouchTarget:r=>!U(r.target,"scrollable-x")}));for(const r of this.mediaTabs){const l=document.createElement("div");l.classList.add("search-super-tab-container","search-super-container-"+r.type,"tabs-tab");const c=document.createElement("div");c.classList.add("search-super-content-container","search-super-content-"+r.type),l.append(c),this.tabsContainer.append(l);const{inputFilter:d}=r;d&&(this.tabs[d]=c),r.contentTab=c}this.container.append(t,this.tabsContainer),this.searchGroupMedia=new Rr(!1,"messages",!0),this.scrollable.onScrolledBottom=()=>{this.mediaTab.contentTab&&this.canLoadMediaTab(this.mediaTab)&&this.load(!0,void 0,"bottom")},this.selectTab=Ml(this.tabsMenu,this.tabsContainer,(r,l,c)=>{if(this.prevTabId===r&&!this.skipScroll){this.scrollToStart();return}const d=this.mediaTabs[r];this.onChangeTab?.(d),this.selection&&(this.selection.isStories=d.type==="stories");const h=this.mediaTab;if(this.mediaTab=d,this.prevTabId!==-1&&c&&this.onTransitionStart(),this.skipScroll)this.skipScroll=!1;else{const u=this.container.offsetTop-(this.scrollOffset||0);let p=this.scrollable.scrollPosition;if(p<u&&(this.scrollToStart(),p=u),h.scroll={scrollTop:p,scrollHeight:this.scrollable.scrollSize},d.scroll===void 0){const m=this.container.getBoundingClientRect(),g=this.container.parentElement.getBoundingClientRect(),f=m.y-g.y;p>f&&(d.scroll={scrollTop:f,scrollHeight:0})}if(d.scroll){const m=h.scroll.scrollTop-d.scroll.scrollTop;m&&(d.contentTab.style.transform=`translateY(${m}px)`)}}this.prevTabId!==-1&&!d.contentTab.childElementCount&&this.load(!0),this.prevTabId=r},()=>{this.scrollable.onScroll(),this.mediaTab.scroll!==void 0&&(this.mediaTab.contentTab.style.transform="",this.scrollable.scrollPosition=this.mediaTab.scroll.scrollTop),n&&(n(),n=void 0),this.onTransitionEnd()},void 0,s,this.listenerSetter),N(this.tabsContainer,r=>{this.selection.isSelecting&&(KS(r),this.selection.toggleByElement(U(r.target,"search-super-item")))},{capture:!0,passive:!1,listenerSetter:this.listenerSetter});const a=async(r,l,c,d)=>{const h=U(d.target,r);if(!h)return;const u=+h.dataset.mid;if(!u){this.log.warn("no messageId by click on target:",h);return}const p=h.querySelector(".media-spoiler-container");if(p){MS({event:d,mediaSpoiler:p});return}const m=h.dataset.peerId.toPeerId(),g=Array.from(this.tabs[c].querySelectorAll("."+l)).map(w=>{const b=U(w,r);return{element:w,mid:+b.dataset.mid,peerId:b.dataset.peerId.toPeerId()}}),f=g.findIndex(w=>w.mid===u&&w.peerId===m),y=this.mediaTabs.find(w=>w.inputFilter===c),v=await this.managers.appMessagesManager.getMessageByPeer(m,u);new ho().setSearchContext(this.copySearchContext(c,this.nextRates[y.type])).openMedia({message:v,target:g[f].element,fromRight:0,reverse:!1,prevTargets:g.slice(0,f),nextTargets:g.slice(f+1)})};this.tabs.inputMessagesFilterPhotoVideo&&N(this.tabs.inputMessagesFilterPhotoVideo,a.bind(null,"grid-item","grid-item","inputMessagesFilterPhotoVideo"),{listenerSetter:this.listenerSetter}),this.tabs.inputMessagesFilterDocument&&N(this.tabs.inputMessagesFilterDocument,a.bind(null,"document-with-thumb","media-container","inputMessagesFilterDocument"),{listenerSetter:this.listenerSetter}),this.mediaTab=this.mediaTabs[0],Pg(()=>{this.lazyLoadQueue.lock()},()=>{this.lazyLoadQueue.unlockAndRefresh()},this.listenerSetter)}scrollToStart(){this.scrollable.scrollIntoViewNew({element:this.container,position:"start",startCallback:this.scrollStartCallback,getElementPosition:this.scrollOffset?({elementPosition:e})=>Math.max(0,e-this.scrollOffset):void 0})}setCounter(e,t){this.counters[e]=t,this.onLengthChange?.(e,t)}filterMessagesByType(e,t){return g2({inputFilter:t,messages:e,limit:e.length})}async processEmptyFilter({message:e,searchGroup:t,mediaTab:s}){const i=s.type==="saved";let n=e.peerId;i&&(n=e.fromId),n=await this.managers.appPeersManager.getPeerMigratedTo(n)||n;const a=this.middleware.get(),r=[],l=Xe.addDialogNew({peerId:n,container:t?.list||!1,avatarSize:"bigger",loadPromises:r,wrapOptions:{middleware:a},withStories:!0,meAsSaved:!i,autonomous:i,fromName:n?void 0:Rn(e.fwd_from)}),c=Xe.setLastMessageN({dialog:{_:"dialog",peerId:n},lastMessage:e,dialogElement:l,highlightWord:this.searchContext.query,noForwardIcon:i});return r.push(c),Promise.all(r).then(()=>{if(!t)return{element:l.container,message:e}})}async processPhotoVideoFilter({message:e,promises:t,middleware:s}){const i=Xs(e,!0),n=document.createElement("div");n.classList.add("grid-item");let a;const r=Sn(i,200,200);if(i._!=="photo"?a=(await qn({doc:i,message:e,container:n,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:s,onlyPreview:!0,withoutPreloader:!0,noPlayButton:!0,photoSize:r})).thumb:a=await Ks({photo:i,message:e,container:n,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:s,withoutPreloader:!0,noBlur:!0,size:r}),e.media.pFlags.spoiler){const l=await Rd({animationGroup:"chat",media:i,middleware:s,width:140,height:140,multiply:.3});n.append(l)}return[a.images.thumb,a.images.full].filter(Boolean).forEach(l=>{l.classList.add("grid-item-media")}),t.push(a.loadPromises.thumb),{element:n,message:e}}async processDocumentFilter({message:e,inputFilter:t}){const s=Xs(e,!0),i=this.showSender||["voice","round"].includes(s.type),n=await Yc({message:e,withTime:!i,fontWeight:400,voiceAsMusic:!0,showSender:i,searchContext:this.copySearchContext(t,this.nextRates.files),lazyLoadQueue:this.lazyLoadQueue,autoDownloadSize:0,getSize:()=>320});return["audio","voice","round"].includes(s.type)&&n.classList.add("audio-48"),{message:e,element:n}}async processUrlFilter({message:e,promises:t,middleware:s}){let i=e.media?.webpage;if(!i){const u=e.totalEntities?e.totalEntities.find(y=>y._==="messageEntityUrl"||y._==="messageEntityTextUrl"):null;let p,m,g;if(u)g=e.message.slice(u.offset,u.offset+u.length);else{const y=vu(e.message);if(!y)return;p=y[0]}u?._==="messageEntityTextUrl"?p=u.url:p=p||g,m=p;const f=e.message===p;p.match(/^(ftp|http|https):\/\//)||(m="https://"+p,p=p.includes("@")?p:"https://"+p),m=new URL(m).hostname,i={_:"webPage",pFlags:{},url:p,display_url:m,id:"",hash:0},f||(i.description=e.message)}if(i._==="webPageEmpty")return;const n=document.createElement("div");n.classList.add("preview"),i.photo?Ks({container:n,message:null,photo:i.photo,boxWidth:0,boxHeight:0,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue,middleware:s,size:Sn(i.photo,60,60,!1),loadPromises:t,noBlur:!0}):(n.classList.add("empty"),kt(n,Fu(i.title||i.display_url||i.description||i.url,!0)));const a=IS(i),r=CS(i),c=Ed(Yt(i.url||"")).firstElementChild,d=c instanceof HTMLAnchorElement;if(d)try{c.innerText=decodeURIComponent(c.href)}catch{}r.firstChild&&r.append(`
`),r.append(c),this.showSender&&r.append(`
`,await eu(e)),a.textContent||a.append(vo(i.display_url.split("/",1)[0]));const h=new ve({title:a,titleRight:uf(e),subtitle:r,havePadding:!0,clickable:!0,noRipple:!0,asLink:d});if(d){h.container.href=c.href;const u=c.getAttribute("onclick");u&&h.container.setAttribute("onclick",u),c.target==="_blank"&&Jr(h.container)}if(h.applyMediaElement(n,"big"),h.container.innerText.trim().length)return{message:e,element:h.container}}async performSearchResult(e,t,s=!0){const i=[],n=t.contentTab,a=[],r=this.middleware.get(),l=t.type==="saved";let c=t.inputFilter;await As();let d;c==="inputMessagesFilterPhotoVideo"&&this.searchContext.query.trim()?(c="inputMessagesFilterEmpty",d=this.searchGroupMedia,n.append(d.container)):c==="inputMessagesFilterEmpty"&&!l&&(d=this.searchGroups.messages);const h={elemsToAppend:i,inputFilter:c,message:void 0,middleware:r,promises:a,searchGroup:d,mediaTab:t};let u;switch(c){case"inputMessagesFilterEmpty":{u=this.processEmptyFilter;break}case"inputMessagesFilterPhotoVideo":{u=this.processPhotoVideoFilter;break}case"inputMessagesFilterVoice":case"inputMessagesFilterRoundVoice":case"inputMessagesFilterMusic":case"inputMessagesFilterDocument":{u=this.processDocumentFilter;break}case"inputMessagesFilterUrl":{u=this.processUrlFilter;break}}if(u){u=u.bind(this);const m=e.map(async f=>{try{return h.message=f,await u(h)}catch(y){this.log.error("error rendering filter",c,h,f,y)}}),g=(await Promise.all(m)).filter(Boolean);i.push(...g)}if(d&&d.list.childElementCount&&d.setActive(),this.loadMutex&&a.push(this.loadMutex),a.length&&(await Promise.all(a),!r()))return;const p=i.length;if(p){const m=s?"append":"prepend",g=this.groupByMonth&&!l,f=l?this.searchContext.peerId:void 0;if(i.forEach(y=>{const{element:v,message:w}=y;if(!w)debugger;const b=this.getMonthContainerByTimestamp(g?w.date:0,c);v.classList.add("search-super-item"),v.dataset.mid=""+w.mid,v.dataset.peerId=""+w.peerId,f&&(v.dataset.threadId=""+f),b.items[m](v),this.selection?.isSelecting&&this.selection.toggleElementCheckbox(v,!0)}),l){let y=n.querySelector(".chatlist");if(!y){y=Xe.createChatList({new:!0});const v=this.getMonthContainerByTimestamp(0,c).container;v.replaceWith(y),y.append(v),Xe.setListClickListener({list:y,onFound:()=>{if(this.selection.isSelecting)return!1},withContext:void 0,autonomous:!0,openInner:!0})}}}this.afterPerforming(c==="inputMessagesFilterEmpty"?1:p,n)}afterPerforming(e,t){if(!t)return;const s=t.parentElement;if(Array.from(s.children).slice(1).forEach(i=>{i.remove()}),!e&&!t.childElementCount){const i=document.createElement("div");i.innerText="Nothing interesting here yet...",i.classList.add("position-center","text-center","content-empty","no-select"),s.append(i)}}loadChats(){const e=new Set,t=this.middleware.get();for(const i in this.searchGroups){const n=this.searchGroups[i];this.tabs.inputMessagesFilterEmpty.append(n.container),n.clear()}const s=this.searchContext.query;if(s){const i=(a,r,l=!1)=>{a.map(c=>{if(e.has(c))return;e.add(c);const{dom:d}=Xe.addDialogNew({peerId:c,container:r.list,avatarSize:"abitbigger",autonomous:r.autonomous,wrapOptions:{middleware:t},withStories:!0});return{dom:d,peerId:c}}).filter(Boolean).forEach(async({dom:c,peerId:d})=>{const h=await this.managers.appPeersManager.getPeer(d);if(d===I.myId)c.lastMessageSpan.append(M("Presence.YourChat"));else{let u=await this.managers.appPeersManager.getPeerUsername(d);if(u)u="@"+u;else{const m=await this.managers.appUsersManager.getUser(d);m?.phone&&(u="+"+_l(m.phone).formatted)}const p=[u];(h.participants_count||h.participants)&&p.push(await da(d.toChatId())),c.lastMessageSpan.append(...pi(p.filter(Boolean),!1))}}),r.toggle()},n=a=>{if(t())return a};return Promise.all([this.managers.appUsersManager.getContactsPeerIds(s,!0,void 0,10).then(n).then(a=>{a&&i(a,this.searchGroups.contacts,!0)}),this.managers.appUsersManager.searchContacts(s,20).then(n).then(a=>{if(a&&(i(a.my_results,this.searchGroups.contacts,!0),i(a.results,this.searchGroups.globalContacts),this.searchGroups.globalContacts.container.classList.add("is-short"),this.searchGroups.globalContacts.nameEl.lastElementChild!==this.searchGroups.globalContacts.nameEl.firstElementChild&&this.searchGroups.globalContacts.nameEl.lastElementChild.remove(),this.searchGroups.globalContacts.list.childElementCount>3)){const r=document.createElement("div");r.classList.add("search-group__show-more");const l=new ke.IntlElement({key:"Separator.ShowMore"});r.append(l.element),this.searchGroups.globalContacts.nameEl.append(r),N(r,()=>{const c=this.searchGroups.globalContacts.container.classList.toggle("is-short");l.key=c?"Separator.ShowMore":"Separator.ShowLess",l.update()})}}),this.managers.dialogsStorage.getDialogs({query:s,offsetIndex:0,limit:20,filterId:0}).then(n).then(a=>{a&&i(a.dialogs.map(r=>r.peerId),this.searchGroups.contacts,!0)})])}else if(!this.searchContext.peerId&&!this.searchContext.minDate){const i=(n=!0)=>fe.getState().then(a=>{t()&&(this.searchGroups.recent.list.replaceChildren(),a.recentSearch.slice(0,20).forEach(async r=>{const{dom:l}=Xe.addDialogNew({peerId:r,container:this.searchGroups.recent.list,meAsSaved:!0,avatarSize:"abitbigger",autonomous:!0,wrapOptions:{middleware:t},withStories:!0});l.lastMessageSpan.append(await(r.isUser()?Promise.resolve(br(await this.managers.appUsersManager.getUser(r.toUserId()))):da(r.toChatId())))}),a.recentSearch.length?n&&this.searchGroups.recent.setActive():this.searchGroups.recent.clear())});return Promise.all([this.managers.appUsersManager.getTopPeers("correspondents").then(n=>{if(!t())return;n=n.slice(0,15);const a=n.findIndex(r=>r.id===I.myId);a!==-1&&(n=n.slice(),n.splice(a,1)),n.forEach(r=>{const{dom:l}=Xe.addDialogNew({peerId:r.id,container:this.searchGroups.people.list,onlyFirstName:!0,avatarSize:"bigger",autonomous:!1,noIcons:this.searchGroups.people.noIcons,wrapOptions:{middleware:t},withStories:!0});l.subtitleEl.remove()}),this.searchGroups.people.toggle()}),i()])}else return Promise.resolve()}async loadMembers({mediaTab:e}){const t=e.type==="members"?this.searchContext.peerId.toChatId():void 0,s=e.type==="groups"?this.searchContext.peerId.toUserId():void 0,i=this.middleware.get();let n;const a=async r=>{if(this.loadMutex&&(await this.loadMutex,!i()))return;let l=this.membersList,c=this.membersParticipantMap,d=this.membersMiddlewareHelper;if(!l&&(c=this.membersParticipantMap=new Map,d=this.membersMiddlewareHelper=xt(),l=this.membersList=new $c({lazyLoadQueue:this.lazyLoadQueue,rippleEnabled:!1,managers:this.managers,middleware:i}),N(l.list,p=>{if(U(p.target,"has-stories"))return;const m=Bi(p.target,Nl);if(!m)return;const g=m.dataset.peerId.toPeerId();let f=Promise.resolve();this.slider===ls&&$e.isMobile&&(f=this.slider.toggleSidebar(!1)),f.then(()=>{me.setInnerPeer({peerId:g})})}),e.contentTab.append(l.list),this.afterPerforming(1,e.contentTab),t)){const p=d.get();Qu({chatId:t,listenTo:l.list,participants:this.membersParticipantMap,slider:this.slider,middleware:p});const m=g=>{const f=gl(g.prev_participant||g.new_participant),y=l.has(f);(y||g.new_participant.pFlags?.left)&&(l.ranks.delete(f),l.delete(f),c.delete(f),this.setCounter(e.type,this.counters[e.type]-1)),(!g.prev_participant||y)&&g.new_participant&&(a([g.new_participant]),this.setCounter(e.type,this.counters[e.type]+1))};I.addEventListener("chat_participant",m),p.onClean(()=>{I.removeEventListener("chat_participant",m)})}const h=r.map(p=>{const m=s?p.id.toPeerId(!0):gl(p);if(!(t?m.isAnyChat():m.isUser()))return{peerId:m,rank:Zg(p),participant:p}}).filter(Boolean),u=await Zi(h,async({peerId:p})=>{const m=await this.managers.appPeersManager.getPeer(p);return!(!i()||!m||m.pFlags.deleted)});for(const{peerId:p,rank:m,participant:g}of u)m&&l.ranks.set(p,m),c.set(p,g),l.add(p)};if(s){const r=this.membersList?200:50;n=this.managers.appUsersManager.getCommonChats(s,r,this.nextRates[e.type]).then(l=>{if(!i())return;const c=l.count??l.chats.length;this.counters[e.type]||this.setCounter(e.type,c);const d=l.chats[l.chats.length-1];return this.nextRates[e.type]=d?.id,l.chats.length<r&&(this.loaded[e.type]=!0),a(l.chats)})}else if(await this.managers.appChatsManager.isChannel(t)){const r=this.membersList?200:50;n=this.managers.appProfileManager.getChannelParticipants({id:t,limit:r,offset:this.nextRates[e.type]}).then(l=>{if(!i())return;const c=e.contentTab.firstElementChild;return this.nextRates[e.type]=(c?c.childElementCount:0)+l.participants.length,l.participants.length<r&&(this.loaded[e.type]=!0),this.setCounter(e.type,l.count),a(l.participants)})}else n=this.managers.appProfileManager.getChatFull(t).then(r=>{if(!i())return;this.loaded[e.type]=!0;const l=r.participants;if(l._!=="chatParticipantsForbidden")return this.setCounter(e.type,l.participants.length),a(l.participants)});return n}async loadStories({mediaTab:e}){if(this._loadStories)return this._loadStories();const t=this.middleware.get(),s=Pt();return Jt(i=>{t.onClean(()=>{this._loadStories=void 0,i(),s.reject()});const n=v2({peerId:this.searchContext.peerId,pinned:!this.storiesArchive,archive:this.storiesArchive,onReady:()=>{s.resolve();const a=n();e.contentTab.append(typeof a=="function"?a():a),this.afterPerforming(1,e.contentTab)},onLoadCallback:a=>{this._loadStories=async()=>{const l=await a();t()&&l&&(this.loaded[e.type]=!0)}},onLengthChange:a=>{this.onStoriesLengthChange?.(a),this.setCounter(e.type,a)},selection:this.selection});this._loadStories()}),s}async loadSimilarChannels({mediaTab:e}){const t=this.middleware.get().create(),s=async(l,c)=>{const d=Xe.createChatList({new:!0}),h=l.map(async u=>{const p=[],{dom:m}=Xe.addDialogNew({peerId:u.id.toPeerId(!0),container:d,avatarSize:"abitbigger",autonomous:!1,wrapOptions:{middleware:c},loadPromises:p});return m.lastMessageSpan.append(await da(u.id,this.managers,u)),Promise.all(p)});return await Promise.all(h),d},i=l=>{const c=document.createElement("div");c.classList.add("similar-channels-paywall");const d=ze("btn-primary btn-color-primary",{icon:"premium_unlock",text:"UnlockSimilar"});d.classList.add("similar-channels-paywall-button");const h=()=>Vt.show(),u=ni(h);N(d,h),u.classList.add("primary");const p=M("SimilarChannels.Unlock",[u,l]);return p.classList.add("similar-channels-paywall-subtitle"),c.append(d,p),c};let n,a;const r=async l=>{if(a===l)return;t.clean();const c=t.get(),[d,h,u]=await Promise.all([this.managers.appChatsManager.getChannelRecommendations(this.searchContext.peerId.toChatId()),this.managers.apiManager.getLimit("recommendedChannels",!0),fe.isPremiumFeaturesHidden()]),p=await s(d.chats,c);if(!c())return;e.contentTab.replaceChildren(p),this.afterPerforming(1,e.contentTab),this.loaded[e.type]=!0;const m=d.count??d.chats.length;this.setCounter(e.type,m),!l&&!u&&(n||(n=i(h)),e.contentTab.append(n))};return I.addEventListener("premium_toggle",r),this.middleware.get().onClean(()=>{I.removeEventListener("premium_toggle",r)}),r(I.premium)}async loadSavedDialogs({mediaTab:e,middleware:t,side:s}){if(this._loadSavedDialogs)return this._loadSavedDialogs(s);const i=Xe.createChatList();Xe.setListClickListener({list:i,withContext:!0,openInner:this.openSavedDialogsInner});const n=new lR;n.scrollable=this.scrollable,n.sortedList=new Yf({managers:this.managers,log:this.log,list:i,indexKey:"index_0",virtualFilterId:I.myId});const a=async()=>(await this.managers.dialogsStorage.getDialogs({filterId:I.myId})).count;return(n.onAnyUpdate=async()=>{if(!t())return;const l=await a();this.setCounter(e.type,l)})(),e.contentTab.append(i),this.afterPerforming(1,e.contentTab),this._loadSavedDialogs=n.onChatsScroll.bind(n),t.onClean(()=>{n.destroy(),this._loadSavedDialogs=void 0}),n.onChatsScroll()}loadType(e){var h;const{mediaTab:t,justLoad:s,loadCount:i,middleware:n,side:a}=e,{type:r,inputFilter:l}=t;let c=this.loadPromises[r];if(c)return c;if(r==="members"||r==="groups"?c=this.loadMembers(e):r==="stories"?c=this.loadStories(e):r==="similar"?c=this.loadSimilarChannels(e):r==="savedDialogs"&&(c=this.loadSavedDialogs(e)),c)return this.loadPromises[r]=c.finally(()=>{n()&&(this.loadPromises[r]=null)});const d=(h=this.historyStorage)[l]??(h[l]=[]);return l==="inputMessagesFilterEmpty"&&!d.length&&r!=="saved"&&(this.loadedChats||(this.loadChats(),this.loadedChats=!0),!this.searchContext.query.trim()&&!this.searchContext.peerId&&!this.searchContext.minDate)?(this.loaded[r]=!0,Promise.resolve()):(c=this.loadPromises[r]=Promise.resolve().then(async()=>{var v;if(d.length&&this.usedFromHistory[l]<d.length&&!s){const w=[];let b=Math.max(0,this.usedFromHistory[l]),S=0;do{const C=d.slice(b,b+i);b+=C.length,S+=C.length;const P=C.map(L=>fe.getMessageByPeer(L.peerId,L.mid));w.push(...this.filterMessagesByType(P,l))}while(S<i&&b<d.length);return this.usedFromHistory[l]=b,this.performSearchResult(w,t).finally(()=>{setTimeout(()=>{this.scrollable.checkForTriggers()},0)})}const u=d[d.length-1],p=u?.mid||0,m=u?.peerId||Tt,g={...this.searchContext,inputFilter:{_:l},offsetId:p,offsetPeerId:m,limit:i,nextRate:(v=this.nextRates)[r]??(v[r]=0),...r==="saved"?{inputFilter:void 0,peerId:I.myId,threadId:this.searchContext.peerId}:{}},f=await this.managers.appMessagesManager.getHistory(g);let y=f.messages;if(!y&&f.history&&(y=f.history.map(w=>fe.getMessageByPeer(g.peerId,w))),d.push(...y.map(w=>({mid:w.mid,peerId:w.peerId}))),this.counters[r]||this.setCounter(r,f.count),!!n()&&((f.history.length<i||this.searchContext.folderId!==void 0&&!f.nextRate||f.isEnd.top)&&(this.loaded[r]=!0),this.nextRates[r]=f.nextRate,!s))return this.usedFromHistory[l]=d.length,this.loaded[r]||c.then(()=>{setTimeout(()=>{if(n()&&this.mediaTab===t){const w=this.load(!0,!0);w&&w.then(()=>{n()&&setTimeout(()=>{this.scrollable.checkForTriggers()},0)})}},0)}),this.performSearchResult(this.filterMessagesByType(y,l),t)}).catch(u=>{this.log.error("load error:",u)}).finally(()=>{this.loadPromises[r]=null}),c)}canLoadMediaTab(e){const t=e.inputFilter;return!this.loaded[e.type]||this.historyStorage[t]&&this.usedFromHistory[t]<this.historyStorage[t].length}async loadFirstTime(){const e=this.middleware.get(),{peerId:t,threadId:s}=this.searchContext;if(!this.hideEmptyTabs)return;const i=this.mediaTabs.filter(C=>C.inputFilter&&C.inputFilter!=="inputMessagesFilterEmpty"),n=i.map(C=>({_:C.inputFilter})),[a,r,l,c,d,h,u]=await Promise.all([this.managers.appMessagesManager.getSearchCounters(t,n,void 0,s),this.canViewSavedDialogs(),this.canViewSaved(),this.canViewMembers(),this.canViewGroups(),this.canViewStories(),this.canViewSimilar()]);if(!e()||this.loadMutex&&(await this.loadMutex,!e()))return;let p,m=0;i.forEach(C=>{const P=a.find(L=>L.filter._===C.inputFilter);C.menuTab.classList.toggle("hide",!P.count),C.menuTab.classList.remove("active"),this.setCounter(C.type,P.count),P.count&&(p===void 0&&(p=C),++m)});const g=this.mediaTabsMap.get("savedDialogs"),f=this.mediaTabsMap.get("saved"),y=this.mediaTabsMap.get("members"),v=this.mediaTabsMap.get("stories"),w=this.mediaTabsMap.get("groups"),b=this.mediaTabsMap.get("similar");if([[g,r],[f,l],[v,h],[y,c],[w,d],[b,u]].forEach(([C,P])=>{C&&(C.menuTab.classList.toggle("hide",!P),P&&++m)}),h){p=v;const C=M(t.isUser()?"Stories":"ProfileStories");v.menuTabName.replaceWith(v.menuTabName=C)}c&&(p=y),r&&(p=g),this.container.classList.toggle("hide",!p),this.container.parentElement.classList.toggle("search-empty",!p),p&&(this.skipScroll=!0,this.selectTab(this.mediaTabs.indexOf(p),!1),this.navScrollableContainer.classList.toggle("is-single",m<=1))}async load(e=!1,t=!1,s="bottom"){const i=this.searchContext.peerId;this.log("load",e,i,this.loadPromises);const n=this.middleware.get();if(this.firstLoad){if(await(this.loadFirstTimePromise??(this.loadFirstTimePromise=this.loadFirstTime())),!n())return;this.loadFirstTimePromise=void 0,this.firstLoad=!1}let a=e?[this.mediaTab]:this.mediaTabs.filter(c=>c!==this.mediaTab);if(a=a.filter(c=>this.canLoadMediaTab(c)),i.isUser()?ga(a,c=>c.type==="members"):$b(a,c=>c.type==="groups"),!a.length)return;const r=t?50:Math.round((lt.height/130|0)*3*1.25),l=a.map(c=>this.loadType({mediaTab:c,justLoad:t,loadCount:r,middleware:n,side:s}));return Promise.all(l).catch(c=>{this.log.error("Load error all promises:",c)})}getMonthContainerByTimestamp(e,t){const s=new Date(e*1e3);s.setHours(0,0,0),s.setDate(1);const i=s.getTime(),n=this.monthContainers[t]??(this.monthContainers[t]={});if(!(i in n)){const a=document.createElement("div");a.className="search-super-month";const r=document.createElement("div");r.classList.add("search-super-month-name");const l={month:"long"};s.getFullYear()!==new Date().getFullYear()&&(l.year="numeric");const c=new ke.IntlDateElement({date:s,options:l}).element;r.append(c),a.append(r);const d=document.createElement("div");d.classList.add("search-super-month-items"),a.append(r,d);const h=kb(n,"desc");let u=0;for(;u<h.length;++u){const p=h[u];if(i>p)break}n[i]={container:a,items:d},Ps(a,this.tabs[t],u)}return n[i]}async canViewSavedDialogs(){if(this.searchContext.peerId!==I.myId||this.searchContext.threadId||!this.mediaTabsMap.has("savedDialogs"))return!1;try{return await this.managers.dialogsStorage.getDialogs({filterId:I.myId}),!0}catch{return!1}}canViewSaved(){const{peerId:e,threadId:t}=this.searchContext;return t||I.myId===e?!1:this.managers.appMessagesManager.getHistory({peerId:I.myId,threadId:this.searchContext.peerId,limit:50}).then(s=>!!s.count).catch(()=>!1)}canViewMembers(){const{peerId:e}=this.searchContext;if(!e.isAnyChat()||!this.mediaTabsMap.has("members"))return Promise.resolve(!1);const s=e.toChatId();return Promise.all([this.managers.appChatsManager.isBroadcast(s),this.managers.appChatsManager.hasRights(s,"view_participants"),this.managers.appChatsManager.isForum(s)]).then(([i,n,a])=>!i&&n&&(!this.searchContext.threadId||!a))}async canViewGroups(){const{peerId:e}=this.searchContext;return!e.isUser()||!this.mediaTabsMap.has("groups")?!1:!!(await this.managers.appProfileManager.getProfile(e.toUserId())).common_chats_count}async canViewStories(){const{peerId:e,threadId:t}=this.searchContext;return!this.mediaTabsMap.has("stories")||t||e===I.myId&&!this.onStoriesLengthChange?!1:e.isUser()?(this.storiesArchive?this.managers.appStoriesManager.getStoriesArchive(e,1):this.managers.appStoriesManager.getPinnedStories(e,1)).then(({count:n})=>!!n).catch(()=>!1):!!(await this.managers.appProfileManager.getChatFull(e.toChatId())).pFlags.stories_pinned_available}async canViewSimilar(){const{peerId:e}=this.searchContext;if(e.isUser())return!1;try{return!!(await this.managers.appChatsManager.getChannelRecommendations(e.toChatId())).chats.length}catch{return!1}}cleanup(){this.loadPromises={},this.loaded={},this.loadedChats=!1,this.nextRates={},this.firstLoad=!0,this.prevTabId=-1,this.counters={},this.lazyLoadQueue.clear(),this.mediaTabs.forEach(e=>{const{inputFilter:t}=e;t&&(this.usedFromHistory[t]=-1)}),this.selection?.isSelecting&&this.selection.cancelSelection(),this.middleware.clean(),this.loadFirstTimePromise=void 0,this.cleanScrollPositions(),this.membersList=void 0,this.membersParticipantMap=void 0,this.membersMiddlewareHelper?.destroy(),this.membersMiddlewareHelper=void 0}cleanScrollPositions(){this.mediaTabs.forEach(e=>{e.scroll=void 0})}cleanupHTML(e=!1){this.mediaTabs.forEach(t=>{if(t.contentTab.replaceChildren(),this.hideEmptyTabs&&(this.container.classList.add("hide"),this.container.parentElement.classList.add("search-empty")),t.type!=="chats"&&!this.historyStorage[t.inputFilter]){const s=t.contentTab.parentElement;s.querySelector(".preloader")||rn(s,!0),s.querySelector(".content-empty")?.remove()}}),this.monthContainers={},this.searchGroupMedia.clear(),this.scrollable.scrollPosition=0}copySearchContext(e,t){const s=Wi(this.searchContext);return s.inputFilter={_:e},s.nextRate=t,s}setQuery({peerId:e,query:t,threadId:s,historyStorage:i,folderId:n,minDate:a,maxDate:r}){this.searchContext={peerId:e,query:t||"",inputFilter:{_:this.mediaTab.inputFilter},threadId:s,folderId:n,minDate:a,maxDate:r},this.historyStorage=i??{},this.cleanup()}destroy(){this.cleanup(),this.listenerSetter.removeAll(),this.scrollable.destroy(),this.swipeHandler?.removeListeners(),this.selection?.cleanup(),this.scrollStartCallback=this.onChangeTab=this.selectTab=this.searchContextMenu=this.swipeHandler=this.selection=void 0}}var ps=(o=>(o[o.Everybody=2]="Everybody",o[o.Contacts=1]="Contacts",o[o.Nobody=0]="Nobody",o))(ps||{});function lI(o){const e=[],t={users:[],chats:[]},s={users:[],chats:[]};return o.forEach(i=>{switch(i._){case"privacyValueAllowAll":e.push(ps.Everybody);break;case"privacyValueDisallowAll":e.push(ps.Nobody);break;case"privacyValueAllowContacts":e.push(ps.Contacts);break;case"privacyValueAllowChatParticipants":t.chats.push(...i.chats);break;case"privacyValueAllowUsers":t.users.push(...i.users);break;case"privacyValueDisallowChatParticipants":s.chats.push(...i.chats);break;case"privacyValueDisallowUsers":s.users.push(...i.users);break}}),{type:e[0],disallowPeers:s,allowPeers:t}}class Yn{constructor(e){this.options=e,this.onTabDestroy=async()=>{if(this.isLocked()||!this.options.inputKey)return;const r=[];switch(this.type){case ps.Everybody:r.push({_:"inputPrivacyValueAllowAll"});break;case ps.Contacts:r.push({_:"inputPrivacyValueAllowContacts"});break;case ps.Nobody:r.push({_:"inputPrivacyValueDisallowAll"});break}if(this.exceptions){const l=[["allow","inputPrivacyValueAllowChatParticipants","inputPrivacyValueAllowUsers"],["disallow","inputPrivacyValueDisallowChatParticipants","inputPrivacyValueDisallowUsers"]];for(const[c,d,h]of l){if(this.exceptions.get(c).row.container.classList.contains("hide"))continue;const u=this.peerIds[c];if(!u)continue;const p=this.splitPeersByType(u);p.chats.length&&r.push({_:d,chats:p.chats}),p.users.length&&r.push({_:h,users:await Promise.all(p.users.map(m=>I.managers.appUsersManager.getUserInput(m)))})}}I.managers.appPrivacyManager.setPrivacy(this.options.inputKey,r)},this.onRadioChange=r=>{r=+r,this.type=r,this.replaceCaption(),this.exceptions&&(this.exceptions.get("allow").row.container.classList.toggle("hide",this.type===ps.Everybody),this.exceptions.get("disallow").row.container.classList.toggle("hide",this.type===ps.Nobody)),this.options.onRadioChange&&this.options.onRadioChange(r)},e.captions&&e.captions.reverse();const t=e.managers;this.radioSection=new Pe({name:e.title,caption:!0}),this.radioRows=new Map;let s=[{type:ps.Everybody,langKey:"PrivacySettingsController.Everbody"},{type:ps.Contacts,langKey:"PrivacySettingsController.MyContacts"},{type:ps.Nobody,langKey:"PrivacySettingsController.Nobody"}];if(e.myContactsAndPremium){const r=s.find(l=>l.type===ps.Contacts);r.langKey="PrivacyMessagesContactsAndPremium"}e.skipTypes&&(s=s.filter(r=>!e.skipTypes.includes(r.type)));const i=Pd();s.forEach(({type:r,langKey:l})=>{const c=new ve({radioField:new _i({langKey:l,name:i,value:""+r}),clickable:d=>{c.radioField.locked&&(oe(d),Ee({langPackKey:e.premiumError,langPackArguments:[ni(()=>{bo(),Vt.show()})]}))},listenerSetter:e.tab.listenerSetter});this.radioRows.set(r,c)});const n=xl([...this.radioRows.values()],this.onRadioChange);if(this.radioSection.content.append(n),e.appendTo&&e.appendTo.append(this.radioSection.container),!e.noExceptions){const r=this.exceptionsSection=new Pe({name:"PrivacyExceptions",caption:"PrivacySettingsController.PeerInfo"});this.exceptions=new Map([["disallow",{titleLangKey:e.exceptionTexts[0],key:"disallow",row:null,icon:"deleteuser",subtitleLangKey:"PrivacySettingsController.AddUsers",clickable:!0}],["allow",{titleLangKey:e.exceptionTexts[1],key:"allow",row:null,icon:"adduser",subtitleLangKey:"PrivacySettingsController.AddUsers",clickable:!0}]]),this.exceptions.forEach(l=>{l.row=new ve(l),N(l.row.container,()=>{a.then(()=>{const c=this.peerIds[l.key];e.tab.slider.createTab(Yu).open({type:"privacy",skippable:!0,title:l.titleLangKey,placeholder:"PrivacyModal.Search.Placeholder",takeOut:d=>{c.length=0,c.push(...d),l.row.subtitle.replaceChildren(...this.generateStr(this.splitPeersByType(d))),this.onRadioChange(this.type)},selectedPeerIds:c})})},{listenerSetter:e.tab.listenerSetter}),r.content.append(l.row.container)}),e.appendTo&&e.appendTo.append(r.container)}const a=(e.inputKey?t.appPrivacyManager.getPrivacy(e.inputKey):Promise.resolve()).then(r=>{const l=r?lI(r):void 0,c=e.privacyType||l?.type;if(this.exceptions&&(this.peerIds={},["allow","disallow"].forEach(d=>{const h=[],u=d==="allow"?l.allowPeers:l.disallowPeers;h.push(...u.users.map(m=>m.toPeerId())),h.push(...u.chats.map(m=>m.toPeerId(!0))),this.peerIds[d]=h;const p=this.exceptions.get(d).row.subtitle;p.replaceChildren(),p.append(...this.generateStr(u))})),e.premiumOnly){const d=()=>{const h=this.isLocked();this.radioRows.forEach((u,p)=>{p!==ps.Everybody&&(u.radioField.locked=h)}),this.setRadio(this.isLocked()?ps.Everybody:c),this.exceptionsSection&&this.exceptionsSection.container.classList.toggle("hide",h)};d(),e.tab.listenerSetter.add(I)("premium_toggle",d)}else this.setRadio(this.isLocked()?ps.Everybody:c);e.tab.eventListener.addEventListener("destroy",this.onTabDestroy,{once:!0})})}isLocked(){return this.options.premiumOnly&&!I.premium}replaceCaption(e=this.isLocked()?this.options.premiumCaption:this.options.captions[this.type]){const t=this.radioSection.caption;e?e instanceof HTMLElement?dt(t,e):Zt(t,e):t.replaceChildren(),t.classList.toggle("hide",!e)}setRadio(e){const t=this.radioRows.get(e);this.onRadioChange(e),t.radioField.input.checked=!0}splitPeersByType(e){const t={users:[],chats:[]};return e.forEach(s=>{t[s.isAnyChat()?"chats":"users"].push(s.isAnyChat()?s.toChatId():s)}),t}generateStr(e){return!e.users.length&&!e.chats.length?[M("PrivacySettingsController.AddUsers")]:pi([e.users.length?M("Users",[e.users.length]):null,e.chats.length?M("Chats",[e.chats.length]):null].filter(Boolean),!1)}}class w2 extends Xt{async init(){this.container.classList.add("privacy-tab","privacy-phone-number"),this.setTitle("PrivacyPhone");const e="+"+(await this.managers.appUsersManager.getSelf()).phone,t=document.createElement("div");t.append(M("PrivacyPhoneInfo"),document.createElement("br"),document.createElement("br"),M("PrivacyPhoneInfo4"),document.createElement("br"),sI({mePath:e}));const s=new Yn({tab:this,title:"PrivacyPhoneTitle",inputKey:"inputPrivacyKeyPhoneNumber",captions:[t,t,""],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,onRadioChange:a=>{n.setRadio(ps.Everybody),n.radioSection.container.classList.toggle("hide",a!==ps.Nobody)},managers:this.managers}),i="PrivacyPhoneInfo3",n=new Yn({tab:this,title:"PrivacyPhoneTitle2",inputKey:"inputPrivacyKeyAddedByPhone",captions:[i,i,""],noExceptions:!0,skipTypes:[ps.Nobody],managers:this.managers});this.scrollable.container.insertBefore(n.radioSection.container,s.radioSection.container.nextSibling)}}class cI extends Dt{init(){this.container.classList.add("two-step-verification","two-step-verification-set"),this.setTitle("TwoStepVerificationPasswordSet");const e=new Pe({captionOld:"TwoStepVerificationPasswordSetInfo",noDelimiter:!0}),t="🥳",s=document.createElement("div");Sr({emoji:t,div:s,width:160,height:160}),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const a=ze("btn-primary btn-color-primary",{text:"TwoStepVerificationPasswordReturnSettings"});N(a,r=>{this.close()}),this.slider.sliceTabsUntilTab(Kf,this),n.append(a),i.append(n),this.scrollable.append(e.container)}}function vp(o){return!Ua||!o}class dI extends Dt{constructor(){super(...arguments),this.isFirst=!1}init(){this.container.classList.add("two-step-verification","two-step-verification-email-confirmation"),this.setTitle("TwoStepAuth.RecoveryTitle");const e=new Pe({captionOld:!0,noDelimiter:!0});Zt(e.caption,"TwoStepAuth.ConfirmEmailCodeDesc",[this.email]);const t="📬",s=document.createElement("div");Sr({div:s,width:160,height:160,emoji:t}),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const a=this.codeInputField=new S0({name:"recovery-email-code",label:"TwoStepAuth.RecoveryCode",length:this.length,onFill:h=>{d(!0),this.managers.passwordManager.confirmPasswordEmail(""+h).then(u=>{c()}).catch(u=>{switch(u.type){case"CODE_INVALID":a.input.classList.add("error"),dt(a.label,M("TwoStepAuth.RecoveryCodeInvalid"));break;case"EMAIL_HASH_EXPIRED":a.input.classList.add("error"),dt(a.label,M("TwoStepAuth.RecoveryCodeExpired"));break;default:console.error("confirm error",u);break}d(!1)})}}),r=ze("btn-primary btn-primary-transparent primary",{text:"TwoStepAuth.EmailCodeChangeEmail"}),l=ze("btn-primary btn-secondary btn-primary-transparent primary",{text:"ResendCode"}),c=()=>{this.slider.createTab(cI).open()},d=h=>{jt([a.input,r,l],h)};N(r,h=>{d(!0),this.managers.passwordManager.cancelPasswordEmail().then(u=>{this.slider.sliceTabsUntilTab(Vf,this),this.close()},()=>{d(!1)})}),N(l,h=>{d(!0);const u=rn(l);this.managers.passwordManager.resendPasswordEmail().then(p=>{u.remove(),d(!1)})}),n.append(a.container,r,l),i.append(n),this.scrollable.append(e.container)}onOpenAfterTimeout(){vp(this.isFirst)&&this.codeInputField.input.focus()}}class Vf extends Dt{constructor(){super(...arguments),this.isFirst=!1}init(){this.container.classList.add("two-step-verification","two-step-verification-email"),this.setTitle("RecoveryEmailTitle");const e=new Pe({captionOld:!0,noDelimiter:!0}),t="💌",s=document.createElement("div");Sr({div:s,width:160,height:160,emoji:t}),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const a=this.inputField=new _t({name:"recovery-email",label:"RecoveryEmail",plainText:!0});a.input.addEventListener("keypress",u=>{if(u.key==="Enter")return oe(u),d()}),a.input.addEventListener("input",u=>{a.input.classList.remove("error")});const r=ze("btn-primary btn-color-primary",{text:"Continue"}),l=ze("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),c=()=>{this.slider.createTab(cI).open()},d=()=>{const u=a.value.trim(),p=qw(u);if(!p||p[0].length!==u.length){a.input.classList.add("error");return}h(!0);const m=rn(r);this.managers.passwordManager.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:u}).then(g=>{c()},g=>{if(g.type.includes("EMAIL_UNCONFIRMED")){const f=+g.type.match(/^EMAIL_UNCONFIRMED_(\d+)/)[1],y=this.slider.createTab(dI);y.state=this.state,y.email=u,y.length=f,y.open()}else console.log("password set error",g);h(!1),m.remove()})};N(r,d);const h=u=>{u?(r.setAttribute("disabled","true"),l.setAttribute("disabled","true")):(r.removeAttribute("disabled"),l.removeAttribute("disabled"))};N(l,u=>{ee.createPopup(Ss,"popup-skip-email",{buttons:[{langKey:"Cancel",isCancel:!0},{langKey:"YourEmailSkip",callback:()=>{h(!0),rn(l),this.managers.passwordManager.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:""}).then(()=>{c()},m=>{h(!1)})},isDanger:!0}],titleLangKey:"YourEmailSkipWarning",descriptionLangKey:"YourEmailSkipWarningText"}).show()}),n.append(a.container,r,l),i.append(n),this.scrollable.append(e.container)}onOpenAfterTimeout(){vp(this.isFirst)&&this.inputField.input.focus()}}class S2 extends Dt{init(){this.container.classList.add("two-step-verification","two-step-verification-hint"),this.setTitle("TwoStepAuth.SetupHintTitle");const e=new Pe({noDelimiter:!0}),t="💡",s=document.createElement("div");Sr({div:s,width:160,height:160,emoji:t}),e.content.append(s);const i=document.createElement("div");i.classList.add("input-wrapper");const n=this.inputField=new _t({name:"hint",label:"TwoStepAuth.SetupHintPlaceholder"});n.input.addEventListener("keypress",h=>{if(h.key==="Enter")return oe(h),n.value?c():d()});const a=(h,u)=>{h&&oe(h);const p=u?n.value:void 0;if(p&&this.newPassword===p){zs(ke.format("PasswordAsHintError",!0));return}const m=this.slider.createTab(Vf);m.state=this.state,m.plainPassword=this.plainPassword,m.newPassword=this.newPassword,m.hint=p,m.open()},r=ze("btn-primary btn-color-primary",{text:"Continue"}),l=ze("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),c=h=>a(h,!0),d=h=>a(h,!1);N(r,c),N(l,d),i.append(n.container,r,l),e.content.append(i),this.scrollable.append(e.container)}onOpenAfterTimeout(){this.inputField.input.focus()}}class C2 extends Dt{init(){this.container.classList.add("two-step-verification","two-step-verification-enter-password","two-step-verification-re-enter-password"),this.setTitle("PleaseReEnterPassword");const e=new Pe({noDelimiter:!0}),t=document.createElement("div");t.classList.add("input-wrapper");const s=this.passwordInputField=new Gg({name:"re-enter-password",label:"PleaseReEnterPassword"}),i=new C0(s,157),n=ze("btn-primary btn-color-primary",{text:"Continue"});t.append(s.container,n),e.content.append(i.container,t),this.scrollable.append(e.container),s.input.addEventListener("keypress",l=>{if(s.input.classList.contains("error")&&s.setState(gn.Neutral),l.key==="Enter")return r()});const a=()=>this.newPassword!==s.value?(s.setError(),!1):!0,r=l=>{if(l&&oe(l),!a())return;const c=this.slider.createTab(S2);c.state=this.state,c.plainPassword=this.plainPassword,c.newPassword=this.newPassword,c.open()};return N(n,r),i.load()}onOpenAfterTimeout(){this.passwordInputField.input.focus()}}class ug extends Dt{constructor(){super(...arguments),this.isFirst=!0}init(){const e=!this.state.pFlags.has_password||this.plainPassword;this.container.classList.add("two-step-verification","two-step-verification-enter-password"),this.setTitle(e?"PleaseEnterFirstPassword":"PleaseEnterCurrentPassword");const t=new Pe({noDelimiter:!0}),s=document.createElement("div");s.classList.add("input-wrapper");const i=this.passwordInputField=new Gg({name:"enter-password",label:e?"PleaseEnterFirstPassword":this.state.hint?void 0:"LoginPassword",labelText:!e&&this.state.hint?_e(this.state.hint):void 0}),n=new m0(i,157),a=ze("btn-primary btn-color-primary"),r=new ke.IntlElement({key:"Continue"});a.append(r.element),s.append(i.container,a),t.content.append(n.container,s),this.scrollable.append(t.container),i.input.addEventListener("keypress",d=>{if(i.input.classList.contains("error")&&(i.input.classList.remove("error"),r.key="Continue",r.update()),d.key==="Enter")return c()});const l=()=>i.value.length?!0:(i.input.classList.add("error"),!1);let c;if(e)c=d=>{if(d&&oe(d),!l())return;const h=this.slider.createTab(C2);h.state=this.state,h.newPassword=i.value,h.plainPassword=this.plainPassword,h.open()};else{let d;const h=()=>(d||(d=window.setInterval(h,1e4)),this.managers.passwordManager.getState().then(p=>{this.state=p,this.state.hint?kt(i.label,_e(this.state.hint)):dt(i.label,M("LoginPassword"))}));c=p=>{if(!l()){oe(p);return}a.setAttribute("disabled","true"),r.key="PleaseWait",r.update();const m=rn(a),g=i.value;this.managers.passwordManager.check(i.value,this.state).then(f=>{if(console.log(f),f._==="auth.authorization"){clearInterval(d),n&&n.remove();const y=this.slider.createTab(hI);y.state=this.state,y.plainPassword=g,y.open(),this.slider.removeTabFromHistory(this)}},f=>{switch(a.removeAttribute("disabled"),i.input.classList.add("error"),f.type){default:r.key="PASSWORD_HASH_INVALID",r.update(),m.remove(),i.select();break}h()})},h()}return N(a,c),n.load()}onOpenAfterTimeout(){vp(this.isFirst)&&this.passwordInputField.input.focus()}}class hI extends Dt{init(){this.container.classList.add("two-step-verification","two-step-verification-main"),this.setTitle("TwoStepVerificationTitle");const e=new Pe({captionOld:!0,noDelimiter:!0}),t="🔐",s=document.createElement("div");Sr({div:s,width:168,height:168,emoji:t}),e.content.append(s);const i=e.generateContentElement();if(this.state.pFlags.has_password){Zt(e.caption,"TwoStepAuth.GenericHelp");const n=ze("btn-primary btn-transparent",{icon:"edit",text:"TwoStepAuth.ChangePassword"}),a=ze("btn-primary btn-transparent",{icon:"passwordoff",text:"TwoStepAuth.RemovePassword"}),r=ze("btn-primary btn-transparent",{icon:"email",text:this.state.pFlags.has_recovery?"TwoStepAuth.ChangeEmail":"TwoStepAuth.SetupEmail"});N(n,()=>{const l=this.slider.createTab(ug);l.state=this.state,l.plainPassword=this.plainPassword,l.open()}),N(a,()=>{ee.createPopup(Ss,"popup-disable-password",{buttons:[{langKey:"Disable",callback:()=>{this.managers.passwordManager.updateSettings({currentPassword:this.plainPassword}).then(()=>{this.slider.sliceTabsUntilTab(Kf,this),this.close()})},isDanger:!0}],titleLangKey:"TurnPasswordOffQuestionTitle",descriptionLangKey:"TurnPasswordOffQuestion"}).show()}),N(r,()=>{const l=this.slider.createTab(Vf);l.state=this.state,l.hint=this.state.hint,l.plainPassword=this.plainPassword,l.newPassword=this.plainPassword,l.isFirst=!0,l.open()}),i.append(n,a,r)}else{Zt(e.caption,"TwoStepAuth.SetPasswordHelp");const n=document.createElement("div");n.classList.add("input-wrapper");const a=ze("btn-primary btn-color-primary",{text:"TwoStepVerificationSetPassword"});n.append(a),i.append(n),N(a,r=>{const l=this.slider.createTab(ug);l.state=this.state,l.open()})}this.scrollable.append(e.container)}}class I2 extends Xt{init(e){this.container.classList.add("privacy-tab","privacy-last-seen"),this.setTitle("PrivacyLastSeen");const t=()=>i.type!==ps.Everybody||!!i.peerIds.disallow.length,s="PrivacySettingsController.LastSeenDescription",i=new Yn({tab:this,title:"LastSeenTitle",inputKey:"inputPrivacyKeyStatusTimestamp",captions:[s,s,s],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,onRadioChange:()=>{[n,a].forEach(r=>{r.container.classList.toggle("hide",!t())})},managers:this.managers});let n;{const r=n=new Pe({caption:"HideReadTimeInfo"}),l=new ve({titleLangKey:"HideReadTime",checkboxField:new pt({toggle:!0,checked:!!e.pFlags.hide_read_marks}),listenerSetter:this.listenerSetter});this.eventListener.addEventListener("destroy",()=>{const c=l.checkboxField.checked&&t();if(!!e.pFlags.hide_read_marks===c)return;const d=this.managers.appPrivacyManager.setGlobalPrivacySettings({_:"globalPrivacySettings",pFlags:{...e.pFlags,hide_read_marks:c||void 0}});return this.eventListener.dispatchEvent("privacy",d),d}),r.content.append(l.container),this.scrollable.append(r.container)}let a;{const r=a=new Pe({caption:!0}),l=()=>{const d=ze("btn-primary btn-transparent primary",{text:I.premium?"PrivacyLastSeenPremiumForPremium":"PrivacyLastSeenPremium"});return N(d,()=>{Vt.show()},{listenerSetter:this.listenerSetter}),d},c=()=>{r.content.replaceChildren(l()),r.caption.replaceChildren(M(I.premium?"PrivacyLastSeenPremiumInfoForPremium":"PrivacyLastSeenPremiumInfo"))};c(),this.listenerSetter.add(I)("premium_toggle",c),this.scrollable.append(r.container)}}}class L2 extends Xt{init(){this.container.classList.add("privacy-tab","privacy-profile-photo"),this.setTitle("PrivacyProfilePhoto");const e="PrivacySettingsController.ProfilePhoto.CustomHelp";new Yn({tab:this,title:"PrivacyProfilePhotoTitle",inputKey:"inputPrivacyKeyProfilePhoto",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,skipTypes:[ps.Nobody],managers:this.managers})}}class P2 extends Xt{init(){this.container.classList.add("privacy-tab","privacy-forward-messages"),this.setTitle("PrivacySettings.Forwards");const e="PrivacySettingsController.Forwards.CustomHelp";new Yn({tab:this,title:"PrivacyForwardsTitle",inputKey:"inputPrivacyKeyForwards",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers})}}class M2 extends Xt{init(){this.container.classList.add("privacy-tab","privacy-add-to-groups"),this.setTitle("PrivacySettings.Groups");const e="PrivacySettingsController.GroupDescription";new Yn({tab:this,title:"WhoCanAddMe",inputKey:"inputPrivacyKeyChatInvite",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers})}}class E2 extends Xt{init(){this.container.classList.add("privacy-tab","privacy-calls"),this.setTitle("PrivacySettings.VoiceCalls");const e="PrivacySettingsController.PhoneCallDescription";new Yn({tab:this,title:"WhoCanCallMe",inputKey:"inputPrivacyKeyPhoneCall",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers});{const t="PrivacySettingsController.P2p.Desc";new Yn({tab:this,title:"PrivacyP2PHeader",inputKey:"inputPrivacyKeyPhoneP2P",captions:[t,t,t],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers})}}}class uI extends Xt{init(){this.container.classList.add("active-sessions-container"),this.setTitle("SessionsTitle");const e=l=>{const c=new ve({title:[l.app_name,l.app_version].join(" "),subtitle:[l.ip,l.country].filter(Boolean).join(" - "),clickable:!0,titleRight:l.pFlags.current?void 0:Md(new Date(Math.max(l.date_active,l.date_created)*1e3))});return c.container.dataset.hash=""+l.hash,c.midtitle.textContent=[l.device_model,l.system_version||l.platform].filter(Boolean).join(", "),c},t=this.authorizations.slice();{const l=new Pe({name:"CurrentSession",caption:"ClearOtherSessionsHelp"}),c=ga(t,h=>h.pFlags.current),d=e(c);if(l.content.append(d.container),t.length){const h=ze("btn-primary btn-transparent danger",{icon:"stop",text:"TerminateAllSessions"});N(h,u=>{ee.createPopup(Ss,"revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{const p=jt([h],!0);this.managers.apiManager.invokeApi("auth.resetAuthorizations").then(m=>{h.remove(),s.container.remove()},i).finally(()=>{p()})}}],titleLangKey:"AreYouSureSessionsTitle",descriptionLangKey:"AreYouSureSessions"}).show()},{listenerSetter:this.listenerSetter}),l.content.append(h)}this.scrollable.append(l.container)}if(!t.length)return;const s=new Pe({name:"OtherSessions",caption:"SessionsListInfo"});t.forEach(l=>{s.content.append(e(l).container)}),this.scrollable.append(s.container);const i=l=>{l.type==="FRESH_RESET_AUTHORISATION_FORBIDDEN"&&zs(ke.format("RecentSessions.Error.FreshReset",!0))};let n;const a=()=>{const l=n.dataset.hash;ee.createPopup(Ss,"revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{this.managers.apiManager.invokeApi("account.resetAuthorization",{hash:l}).then(c=>{c&&n.remove()},i)}}],titleLangKey:"AreYouSureSessionTitle",descriptionLangKey:"TerminateSessionText"}).show()},r=this.menuElement=jn({buttons:[{icon:"stop",text:"Terminate",onClick:a}]});r.id="active-sessions-contextmenu",r.classList.add("contextmenu"),document.getElementById("page-chats").append(r),za({element:this.scrollable.container,callback:l=>{n=U(l.target,"row"),!(!n||n.dataset.hash==="0")&&(l instanceof MouseEvent&&l.preventDefault(),l instanceof MouseEvent&&(l.cancelBubble=!0),Tl(l,r),Js.openBtnMenu(r))},listenerSetter:this.listenerSetter}),N(this.scrollable.container,l=>{n=U(l.target,"row"),!(!n||n.dataset.hash==="0")&&a()},{listenerSetter:this.listenerSetter})}onCloseAfterTimeout(){return this.menuElement?.remove(),super.onCloseAfterTimeout()}}class _2 extends Dt{init(){this.container.classList.add("blocked-users-container"),this.setTitle("BlockedUsers");const e=new Pe({caption:"BlockedUsersInfo"});e.caption.parentElement.prepend(e.caption),this.scrollable.append(e.container);const t=Ei({icon:"add",className:"is-visible"});this.content.append(t),N(t,d=>{ee.createPopup(Es,{peerType:["contacts"],placeholder:"BlockModal.Search.Placeholder",onSelect:h=>{this.managers.appUsersManager.toggleBlock(h,!0)}})},{listenerSetter:this.listenerSetter});const s=Xe.createChatList();this.scrollable.container.classList.add("chatlist-container"),e.content.append(s);const i=async(d,h)=>{const u=Xe.addDialogNew({peerId:d,container:s,rippleEnabled:!0,avatarSize:"abitbigger",append:h,wrapOptions:{middleware:this.middlewareHelper.get()}});u.container.dialogElement=u;const{dom:p}=u,m=await this.managers.appUsersManager.getUser(d.toUserId());if(!m)return;const f=ui(m)[0];m.pFlags.bot?p.lastMessageSpan.append("@"+f):m.phone?p.lastMessageSpan.textContent=Mf(m.phone):p.lastMessageSpan.append(f?"@"+f:br(m))};for(const d of this.peerIds)i(d,!0);let n;const a=()=>{const d=n.dataset.peerId.toPeerId();this.managers.appUsersManager.toggleBlock(d,!1)},r=this.menuElement=jn({buttons:[{icon:"lockoff",text:"Unblock",onClick:a,options:{listenerSetter:this.listenerSetter}}]});r.id="blocked-users-contextmenu",r.classList.add("contextmenu"),document.getElementById("page-chats").append(r),za({element:this.scrollable.container,callback:d=>{n=Bi(d.target,Nl),n&&(d instanceof MouseEvent&&d.preventDefault(),d instanceof MouseEvent&&(d.cancelBubble=!0),Tl(d,r),Js.openBtnMenu(r))},listenerSetter:this.listenerSetter}),this.listenerSetter.add(I)("peer_block",d=>{const{peerId:h,blocked:u,blockedMyStoriesFrom:p}=d;if(p)return;const m=s.querySelector(`[data-peer-id="${h}"]`);u?m||i(h,!1):m&&m.dialogElement.remove()});const l=50;let c=!1;this.scrollable.onScrolledBottom=()=>{c||(c=!0,this.managers.appUsersManager.getBlocked(s.childElementCount,l).then(d=>{for(const h of d.peerIds)i(h,!0);(d.peerIds.length<l||s.childElementCount===d.count)&&(this.scrollable.onScrolledBottom=null),this.scrollable.checkForTriggers()}).finally(()=>{c=!1}))}}onOpenAfterTimeout(){this.scrollable.onScroll()}onCloseAfterTimeout(){return this.menuElement&&this.menuElement.remove(),super.onCloseAfterTimeout()}}function pI(o){return o=o[0].toUpperCase()+o.slice(1),o="input"+o,o}class k2 extends Xt{init(){this.container.classList.add("privacy-tab","privacy-voices"),this.setTitle("PrivacyVoiceMessages");const e="PrivacyVoiceMessagesInfo";new Yn({tab:this,title:"PrivacyVoiceMessagesTitle",inputKey:"inputPrivacyKeyVoiceMessages",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers,premiumOnly:!0,premiumCaption:M("Privacy.VoiceMessagesPremiumCaption",[ni(()=>{Vt.show()})]),premiumError:"PrivacySettings.Voice.PremiumError"})}}class T2 extends Xt{async init(e){this.container.classList.add("active-sessions-container"),this.setTitle("WebSessionsTitle");const t=async s=>{const i=s.bot_id.toPeerId(),n=new ve({title:await Oe({peerId:i}),subtitle:[s.ip,s.region].join(" - "),clickable:!0,titleRight:Md(new Date(Math.max(s.date_active,s.date_created)*1e3))}),a=n.createMedia("big"),r=es({middleware:this.middlewareHelper.get(),size:48,peerId:i});return await r.readyThumbPromise,a.append(r.node),n.container.dataset.hash=""+s.hash,n.container.dataset.peerId=""+i,n.midtitle.textContent=[s.domain,s.browser,s.platform].filter(Boolean).join(", "),n};{const s=new Pe({caption:"ClearOtherWebSessionsHelp"}),i=ze("btn-primary btn-transparent danger",{icon:"stop",text:"TerminateAllWebSessions"});N(i,async()=>{await Ct({descriptionLangKey:"AreYouSureWebSessions",button:{langKey:"Disconnect",isDanger:!0}}),jt([i],!0),this.managers.appSeamlessLoginManager.resetWebAuthorizations().then(()=>{this.close()})},{listenerSetter:this.listenerSetter}),s.content.append(i),this.scrollable.append(s.container)}{const s=new Pe({name:"OtherWebSessions",caption:"TerminateWebSessionInfo"}),i=await Promise.all(e.map(t));s.content.append(...i.map(a=>a.container));let n=i.length;N(s.content,async a=>{const r=U(a.target,"row");if(!r)return;await Ct({descriptionLangKey:"TerminateWebSessionText",descriptionLangArgs:[await Oe({peerId:r.dataset.peerId.toPeerId()})],button:{langKey:"Disconnect",isDanger:!0}});const l=r.dataset.hash;r.classList.add("is-disabled"),this.managers.appSeamlessLoginManager.resetWebAuthorization(l).then(()=>{--n?r.remove():this.close()})},{listenerSetter:this.listenerSetter}),this.scrollable.append(s.container)}}}class x2 extends Xt{init(){this.container.classList.add("privacy-tab","privacy-about"),this.setTitle("UserBio");const e="Privacy.BioCaption";new Yn({tab:this,title:"Privacy.Bio",inputKey:"inputPrivacyKeyAbout",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,skipTypes:[ps.Nobody],managers:this.managers})}}class A2 extends Xt{async init(e){this.container.classList.add("privacy-tab","privacy-messages"),this.setTitle("PrivacyMessages");const t=M("Privacy.MessagesInfo",[ni(()=>{Vt.show()})]),i=!(await this.managers.apiManager.getAppConfig()).new_noncontact_peers_require_premium_without_ownpremium,n=new Yn({tab:this,title:"PrivacyMessagesTitle",captions:[t,t,t],noExceptions:!0,appendTo:this.scrollable,managers:this.managers,skipTypes:[ps.Nobody],myContactsAndPremium:!0,premiumOnly:i,premiumCaption:t,premiumError:"PrivacySettings.Messages.PremiumError",privacyType:e.pFlags.new_noncontact_peers_require_premium?ps.Contacts:ps.Everybody});this.eventListener.addEventListener("destroy",()=>{const a=n.type===ps.Contacts;if(!!e.pFlags.new_noncontact_peers_require_premium===a)return;const r=this.managers.appPrivacyManager.setGlobalPrivacySettings({_:"globalPrivacySettings",pFlags:{...e.pFlags,new_noncontact_peers_require_premium:a||void 0}});return this.eventListener.dispatchEvent("privacy",r),r})}}class F2 extends Xt{static getInitArgs(e){return{appConfig:e.managers.apiManager.getAppConfig(),globalPrivacy:e.managers.appPrivacyManager.getGlobalPrivacySettings(),contentSettings:e.managers.apiManager.invokeApi("account.getContentSettings"),webAuthorizations:e.managers.appSeamlessLoginManager.getWebAuthorizations()}}async init(e){this.container.classList.add("dont-u-dare-block-me"),this.setTitle("PrivacySettings");const t="Loading",s=[];{const i=new Pe({noDelimiter:!0,caption:"SessionsInfo"});let n;const a=new ve({icon:"deleteuser",titleLangKey:"BlockedUsers",subtitleLangKey:t,clickable:()=>{const m=this.slider.createTab(_2);m.peerIds=n,m.open()},listenerSetter:this.listenerSetter});a.freezed=!0;let r;const l={icon:"lock",titleLangKey:"TwoStepVerification",subtitleLangKey:t,clickable:m=>{let g;r.pFlags.has_password?g=this.slider.createTab(ug):r.email_unconfirmed_pattern?(g=this.slider.createTab(dI),g.email=r.email_unconfirmed_pattern,g.length=6,g.isFirst=!0,this.managers.passwordManager.resendPasswordEmail()):g=this.slider.createTab(hI),g.state=r,g.open()},listenerSetter:this.listenerSetter},c=new ve(l);c.freezed=!0;const d=this.activeSessionsRow=new ve({icon:"activesessions",titleLangKey:"SessionsTitle",subtitleLangKey:t,clickable:()=>{const m=this.slider.createTab(uI);m.authorizations=this.authorizations,m.eventListener.addEventListener("destroy",()=>{this.updateActiveSessions()},{once:!0}),m.open()},listenerSetter:this.listenerSetter});d.freezed=!0;const h=this.websitesRow=new ve({icon:"mention",titleLangKey:"OtherWebSessions",subtitleLangKey:t,clickable:()=>{const m=this.slider.createTab(T2);m.eventListener.addEventListener("destroy",()=>{this.updateActiveWebsites()}),m.open(this.websites)},listenerSetter:this.listenerSetter});h.freezed=!0,i.content.append(a.container,c.container,d.container,h.container),this.scrollable.append(i.container);const u=m=>{m?dt(a.subtitle,M("PrivacySettingsController.UserCount",[m])):dt(a.subtitle,M("BlockedEmpty",[m]))};this.listenerSetter.add(I)("peer_block",()=>{p()});const p=()=>{this.managers.appUsersManager.getBlocked().then(m=>{a.freezed=!1,u(m.count),n=m.peerIds})};p(),this.managers.passwordManager.getState().then(m=>{r=m,dt(c.subtitle,M(m.pFlags.has_password?"PrivacyAndSecurity.Item.On":"PrivacyAndSecurity.Item.Off")),c.freezed=!1}),this.updateActiveSessions(),s.push(this.updateActiveWebsites(e.webAuthorizations))}{const i=await fe.isPremiumFeaturesHidden(),n=new Pe({name:"PrivacyTitle",caption:i?"GroupsAndChannelsHelp":"Privacy.MessagesCaption"});n.content.classList.add("privacy-navigation-container");const a={},r=async(w,b)=>{const S=await e.globalPrivacy,C=this.slider.createTab(w);C.open(S),C.eventListener.addEventListener("privacy",P=>{e.globalPrivacy=P,v(b)})},l=a.inputPrivacyKeyPhoneNumber=new ve({titleLangKey:"PrivacyPhoneTitle",subtitleLangKey:t,clickable:()=>{this.slider.createTab(w2).open()},listenerSetter:this.listenerSetter}),c=a.inputPrivacyKeyStatusTimestamp=new ve({titleLangKey:"LastSeenTitle",subtitleLangKey:t,clickable:()=>{r(I2,"inputPrivacyKeyStatusTimestamp")},listenerSetter:this.listenerSetter}),d=a.inputPrivacyKeyProfilePhoto=new ve({titleLangKey:"PrivacyProfilePhotoTitle",subtitleLangKey:t,clickable:()=>{this.slider.createTab(L2).open()},listenerSetter:this.listenerSetter}),h=a.inputPrivacyKeyAbout=new ve({titleLangKey:"Privacy.BioRow",subtitleLangKey:t,clickable:()=>{this.slider.createTab(x2).open()},listenerSetter:this.listenerSetter}),u=a.inputPrivacyKeyPhoneCall=new ve({titleLangKey:"WhoCanCallMe",subtitleLangKey:t,clickable:()=>{this.slider.createTab(E2).open()},listenerSetter:this.listenerSetter}),p=a.inputPrivacyKeyForwards=new ve({titleLangKey:"PrivacyForwardsTitle",subtitleLangKey:t,clickable:()=>{this.slider.createTab(P2).open()},listenerSetter:this.listenerSetter}),m=a.inputPrivacyKeyChatInvite=new ve({titleLangKey:"WhoCanAddMe",subtitleLangKey:t,clickable:()=>{this.slider.createTab(M2).open()},listenerSetter:this.listenerSetter}),g=w=>{const b=document.createDocumentFragment(),S=Le("star","privacy-premium-icon");b.append(M(w),S);const C=()=>{S.classList.toggle("hide",!I.premium)};return C(),this.listenerSetter.add(I)("premium_toggle",C),b};let f;i||(f=a.inputPrivacyKeyVoiceMessages=new ve({title:g("PrivacyVoiceMessagesTitle"),subtitleLangKey:t,clickable:()=>{this.slider.createTab(k2).open()},listenerSetter:this.listenerSetter}));let y;i||(y=a.new_noncontact_peers_require_premium=new ve({title:g("PrivacyMessagesTitle"),subtitleLangKey:t,clickable:()=>{r(A2,"new_noncontact_peers_require_premium")},listenerSetter:this.listenerSetter}));const v=w=>{const b=a[w];if(!b)return;const S={[ps.Everybody]:"PrivacySettingsController.Everbody",[ps.Contacts]:"PrivacySettingsController.MyContacts",[ps.Nobody]:"PrivacySettingsController.Nobody"};if(!w.startsWith("inputPrivacy")){e.globalPrivacy.then(C=>{const P=C.pFlags.new_noncontact_peers_require_premium?"Privacy.ContactsAndPremium":S[ps.Everybody];b.subtitle.replaceChildren(M(P))});return}this.managers.appPrivacyManager.getPrivacy(w).then(C=>{const P=lI(C),L=S[P.type],E=P.disallowPeers.users.length+P.disallowPeers.chats.length,_=P.allowPeers.users.length+P.allowPeers.chats.length,k=M(L);b.subtitle.replaceChildren(k),(E||_)&&b.subtitle.append(` (${[-E,_?"+"+_:0].filter(Boolean).join(", ")})`)})};n.content.append(...[l,c,d,h,u,p,m,f,y].filter(Boolean).map(w=>w.container)),this.scrollable.append(n.container);for(const w in a)v(w);I.addEventListener("privacy_update",w=>{v(pI(w.key._))})}{const i=new Pe({name:"NewChatsFromNonContacts",caption:"ArchiveAndMuteInfo"}),n=new pt({text:"ArchiveAndMute"}),a=new ve({checkboxField:n});i.content.append(a.container);let r,l;this.eventListener.addEventListener("destroy",async()=>{if(l=!0,!(r===void 0||r===n.checked))return this.managers.appPrivacyManager.setGlobalPrivacySettings({_:"globalPrivacySettings",pFlags:{...(await e.globalPrivacy).pFlags,archive_and_mute_new_noncontact_peers:n.checked||void 0}})},{once:!0});const c=Promise.all([e.appConfig,e.globalPrivacy]).then(([d,h])=>{if(l)return;const u=p=>{i.container.classList.toggle("hide",!p&&!d.autoarchive_setting_available)};this.listenerSetter.add(I)("premium_toggle",u),u(I.premium),r=!!h.pFlags.archive_and_mute_new_noncontact_peers,n.setValueSilently(r)});s.push(c),this.scrollable.append(i.container)}{const i=new Pe({name:"Privacy.SensitiveContent",caption:"PrivacyAndSecurity.SensitiveDesc"});i.container.classList.add("hide");const n=new pt({text:"PrivacyAndSecurity.SensitiveText"}),a=new ve({checkboxField:n});i.content.append(a.container);let r;this.eventListener.addEventListener("destroy",()=>{if(r===void 0)return;const c=a.checkboxField.checked;if(c!==r)return this.managers.apiManager.invokeApi("account.setContentSettings",{sensitive_enabled:c})},{once:!0});const l=e.contentSettings.then(c=>{c.pFlags.sensitive_can_change&&(r=!!c.pFlags.sensitive_enabled,n.setValueSilently(r),i.container.classList.remove("hide"))});s.push(l),this.scrollable.append(i.container)}{const i=new Pe({name:"PrivacyPayments",caption:"PrivacyPaymentsClearInfo"}),n=()=>{const r={titleLangKey:"PrivacyPaymentsClearAlertTitle",descriptionLangKey:"PrivacyPaymentsClearAlertText",button:{langKey:"Clear"},checkboxes:[{text:"PrivacyClearShipping",checked:!0},{text:"PrivacyClearPayment",checked:!0}]};Ct(r).then(()=>{const[l,c]=r.checkboxes.map(h=>h.checkboxField.checked),d=jt([a],!0);this.managers.appPaymentsManager.clearSavedInfo(l,c).then(()=>{!l&&!c||(d(),Ee({langPackKey:l&&c?"PrivacyPaymentsPaymentShippingCleared":l?"PrivacyPaymentsShippingInfoCleared":"PrivacyPaymentsPaymentInfoCleared"}))})},Wt)},a=ze("btn-primary btn-transparent",{icon:"delete",text:"PrivacyPaymentsClear"});this.listenerSetter.add(a)("click",n),i.content.append(a),this.scrollable.append(i.container)}{const i=new Pe({name:"FilterChats"}),n=()=>{ee.createPopup(Ss,"popup-delete-drafts",{buttons:[{langKey:"Delete",callback:()=>{const l=jt([a],!0);this.managers.appDraftsManager.clearAllDrafts().then(()=>{l()})},isDanger:!0}],titleLangKey:"AreYouSureClearDraftsTitle",descriptionLangKey:"AreYouSureClearDrafts"}).show()},a=ze("btn-primary btn-transparent",{icon:"delete",text:"PrivacyDeleteCloudDrafts"});this.listenerSetter.add(a)("click",n),i.content.append(a),this.scrollable.append(i.container)}return Promise.all(s)}updateActiveSessions(){return this.managers.apiManager.invokeApi("account.getAuthorizations").then(e=>{this.activeSessionsRow.freezed=!1,this.authorizations=e.authorizations,Zt(this.activeSessionsRow.subtitle,"Privacy.Devices",[this.authorizations.length])})}updateActiveWebsites(e=this.managers.appSeamlessLoginManager.getWebAuthorizations()){return e.then(t=>{this.websitesRow.freezed=!1,this.websites=t,Zt(this.websitesRow.subtitle,"Privacy.Websites",[this.websites.length]),this.websitesRow.container.classList.toggle("hide",!this.websites.length)})}}const En=class En{constructor(){this.hue=0,this.saturation=100,this.lightness=50,this.alpha=1,this.elements={},this.onGrabStart=()=>{document.documentElement.style.cursor=this.elements.boxDragger.style.cursor="grabbing"},this.onGrabEnd=()=>{document.documentElement.style.cursor=this.elements.boxDragger.style.cursor=""},this.container=document.createElement("div"),this.container.classList.add(En.BASE_CLASS);const e=`
<svg class="${En.BASE_CLASS+"-box"}" viewBox="0 0 380 198">
<defs>
<linearGradient id="color-picker-saturation" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#fff"></stop>
<stop offset="100%" stop-color="hsl(0,100%,50%)"></stop>
</linearGradient>
<linearGradient id="color-picker-brightness" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="rgba(0,0,0,0)"></stop>
<stop offset="100%" stop-color="#000"></stop>
</linearGradient>
<pattern id="color-picker-pattern" width="100%" height="100%">
<rect x="0" y="0" width="100%" height="100%" fill="url(#color-picker-saturation)"></rect>
<rect x="0" y="0" width="100%" height="100%" fill="url(#color-picker-brightness)"></rect>
</pattern>
</defs>
<rect rx="10" ry="10" x="0" y="0" width="380" height="198" fill="url(#color-picker-pattern)"></rect>
<svg class="${En.BASE_CLASS+"-dragger"} ${En.BASE_CLASS+"-box-dragger"}" x="0" y="0">
<circle r="11" fill="inherit" stroke="#fff" stroke-width="2"></circle>
</svg>
</svg>
<div class="${En.BASE_CLASS+"-sliders"}">
<svg class="${En.BASE_CLASS+"-color-slider"}" viewBox="0 0 380 24">
<defs>
<linearGradient id="hue" x1="100%" y1="0%" x2="0%" y2="0%">
<stop offset="0%" stop-color="#f00"></stop>
<stop offset="16.666%" stop-color="#f0f"></stop>
<stop offset="33.333%" stop-color="#00f"></stop>
<stop offset="50%" stop-color="#0ff"></stop>
<stop offset="66.666%" stop-color="#0f0"></stop>
<stop offset="83.333%" stop-color="#ff0"></stop>
<stop offset="100%" stop-color="#f00"></stop>
</linearGradient>
</defs>
<rect rx="4" ry="4" x="0" y="9" width="380" height="8" fill="url(#hue)"></rect>
<svg class="${En.BASE_CLASS+"-dragger"} ${En.BASE_CLASS+"-color-slider-dragger"}" x="0" y="13">
<circle r="11" fill="inherit" stroke="#fff" stroke-width="2"></circle>
</svg>
</svg>
</div>
`;this.container.innerHTML=e,this.elements.box=this.container.firstElementChild,this.elements.boxDragger=this.elements.box.lastElementChild,this.elements.saturation=this.elements.box.firstElementChild.firstElementChild,this.elements.sliders=this.elements.box.nextElementSibling,this.elements.hue=this.elements.sliders.firstElementChild,this.elements.hueDragger=this.elements.hue.lastElementChild,this.hexInputField=new _t({plainText:!0,label:"Appearance.Color.Hex"}),this.rgbInputField=new _t({plainText:!0,label:"Appearance.Color.RGB"});const t=document.createElement("div");t.className=En.BASE_CLASS+"-inputs",t.append(this.hexInputField.container,this.rgbInputField.container),this.container.append(t),this.hexInputField.input.addEventListener("input",()=>{let i=this.hexInputField.value.replace(/#/g,"").slice(0,6);const n=i.match(/([a-fA-F\d]+)/),a=n&&n[0].length===i.length&&[6].includes(i.length);this.hexInputField.setState(a?gn.Neutral:gn.Error),i="#"+i,this.hexInputField.setValueSilently(i),a&&this.setColor(i,!1,!0)});const s=/^(?:rgb)?\(?([01]?\d\d?|2[0-4]\d|25[0-5])(?:\W+)([01]?\d\d?|2[0-4]\d|25[0-5])\W+(?:([01]?\d\d?|2[0-4]\d|25[0-5])\)?)$/;this.rgbInputField.input.addEventListener("input",()=>{const i=this.rgbInputField.value.match(s);this.rgbInputField.setState(i?gn.Neutral:gn.Error),i&&this.setColor($h(+i[1],+i[2],+i[3]),!0,!1)}),this.attachBoxListeners(),this.attachHueListeners()}attachBoxListeners(){Rm(this.elements.box,()=>{this.onGrabStart(),this.boxRect=this.elements.box.getBoundingClientRect()},e=>{this.saturationHandler(e.x,e.y)},()=>{this.onGrabEnd()})}attachHueListeners(){Rm(this.elements.hue,()=>{this.onGrabStart(),this.hueRect=this.elements.hue.getBoundingClientRect()},e=>{this.hueHandler(e.x)},()=>{this.onGrabEnd()})}setColor(e,t=!0,s=!0){if(e===void 0)e={h:0,s:100,l:50,a:1};else if(typeof e=="string")if(e[0]==="#")e=kg(e);else{const c=e.match(/[.?\d]+/g);e=$h(+c[0],+c[1],+c[2],c[3]===void 0?1:+c[3])}this.boxRect=this.elements.box.getBoundingClientRect();const i=this.boxRect.width/100*e.s,n=100-e.l/(100-e.s/2)*100,a=this.boxRect.height/100*n;this.saturationHandler(this.boxRect.left+i,this.boxRect.top+a,!1),this.hueRect=this.elements.hue.getBoundingClientRect();const r=e.h/360,l=this.hueRect.left+this.hueRect.width*r;this.hueHandler(l,!1),this.hue=e.h,this.saturation=e.s,this.lightness=e.l,this.alpha=e.a,this.updatePicker(t,s)}getCurrentColor(){const e=TL(this.hue,this.saturation,this.lightness,this.alpha),t=xL(e),s=t.slice(0,-2);return{hsl:`hsl(${this.hue}, ${this.saturation}%, ${this.lightness}%)`,rgb:`rgb(${e[0]}, ${e[1]}, ${e[2]})`,hex:s,hsla:`hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, ${this.alpha})`,rgba:`rgba(${e[0]}, ${e[1]}, ${e[2]}, ${e[3]})`,hexa:t,rgbaArray:e}}updatePicker(e=!0,t=!0){const s=this.getCurrentColor();this.elements.boxDragger.setAttributeNS(null,"fill",s.hex),e&&(this.hexInputField.setValueSilently(s.hex),this.hexInputField.setState(gn.Neutral)),t&&(this.rgbInputField.setValueSilently(s.rgbaArray.slice(0,-1).join(", ")),this.rgbInputField.setState(gn.Neutral)),this.onChange&&this.onChange(s)}hueHandler(e,t=!0){const i=Kt(e-this.hueRect.left,0,this.hueRect.width)/this.hueRect.width;this.hue=Math.round(360*i);const n=`hsla(${this.hue}, 100%, 50%, ${this.alpha})`;this.elements.hueDragger.setAttributeNS(null,"x",i*100+"%"),this.elements.hueDragger.setAttributeNS(null,"fill",n),this.elements.saturation.lastElementChild.setAttributeNS(null,"stop-color",n),t&&this.updatePicker()}saturationHandler(e,t,s=!0){const i=this.boxRect.width,n=this.boxRect.height,a=Kt(e-this.boxRect.left,0,i),r=Kt(t-this.boxRect.top,0,n),l=a/i*100,c=r/n*100,d=this.elements.boxDragger;d.setAttributeNS(null,"x",l+"%"),d.setAttributeNS(null,"y",c+"%");const h=Kt(l,0,100),u=100-h/2,p=100-Kt(c,0,100),m=Kt(p/100*u,0,100);this.saturation=h,this.lightness=m,s&&this.updatePicker()}};En.BASE_CLASS="color-picker";let pg=En;class R2 extends Dt{constructor(){super(...arguments),this._applyColor=(e,t=!0)=>{if(t)this.colorPicker.setColor(e);else{const s=AL(e),i=this.theme.settings,n=Af(s),a={_:"wallPaperNoFile",id:0,pFlags:{},settings:{_:"wallPaperSettings",background_color:parseInt(e.slice(1),16),pFlags:{}}};i.wallpaper=a,i.highlightingColor=n,this.managers.appStateManager.pushToState("settings",I.settings),me.applyCurrentTheme({broadcastEvent:!0}),this.setActive()}},this.onColorChange=e=>{this.applyColor(e.hex,!1)}}init(){this.container.classList.add("background-container","background-color-container"),this.setTitle("SetColor"),this.theme=as.getTheme();const e=new Pe({});this.colorPicker=new pg,e.content.append(this.colorPicker.container),this.scrollable.append(e.container);const t=new Pe({}),s=this.grid=document.createElement("div");s.classList.add("grid"),["#E6EBEE","#B2CEE1","#008DD0","#C6E7CB","#C4E1A6","#60B16E","#CCD0AF","#A6A997","#7A7072","#FDD7AF","#FDB76E","#DD8851"].forEach(n=>{const a=document.createElement("div");a.classList.add("grid-item"),a.dataset.color=n.toLowerCase();const r=document.createElement("div");r.classList.add("grid-item-media"),r.style.backgroundColor=n,a.append(r),s.append(a)}),N(s,n=>{const a=U(n.target,"grid-item");if(!a||a.classList.contains("active"))return;const r=a.dataset.color;r&&this.applyColor(r)},{listenerSetter:this.listenerSetter}),t.content.append(s),this.scrollable.append(t.container),this.applyColor=ma(this._applyColor,16,!0)}setActive(){const e=this.grid.querySelector(".active"),i=this.theme.settings.wallpaper.settings.background_color,n=i?this.grid.querySelector(`.grid-item[data-color="${i}"]`):null;e!==n&&(e&&e.classList.remove("active"),n&&n.classList.add("active"))}onOpen(){setTimeout(()=>{const e=this.theme.settings,t=e?.wallpaper?.settings?.background_color,s=!!t&&e.wallpaper._==="wallPaperNoFile";s&&(this.colorPicker.onChange=this.onColorChange),this.colorPicker.setColor(t&&"#"+t.toString(16)||"#cccccc"),s||(this.colorPicker.onChange=this.onColorChange)},0)}onCloseAfterTimeout(){return this.colorPicker.onChange=void 0,this.colorPicker=void 0,super.onCloseAfterTimeout()}}function D2(o){const e=document.createElement("input");e.type="file",e.style.display="none",e.accept=o,document.body.append(e);const t=new Promise((s,i)=>{e.addEventListener("change",n=>{const a=n.target.files[0];if(!a){i("NO_FILE_SELECTED");return}s(a)},{once:!0})}).finally(()=>{e.remove()});return e.click(),t}const vh=(o,e=!0)=>!!(o?.settings?.pFlags?.blur&&(!e||!o.pFlags.pattern)),na=class na extends Dt{constructor(){super(...arguments),this.clicked=new Set,this.wallPapersByElement=new Map,this.elementsByKey=new Map,this.onUploadClick=()=>{D2("image/x-png,image/png,image/jpeg").then(async e=>{if(e.name.endsWith(".png")){const c=document.createElement("img"),d=URL.createObjectURL(e);await Ki(c,d,!1);const h="image/jpeg",{blob:u}=await fu({media:c,size:new Sm(c.naturalWidth,c.naturalHeight),mimeType:h});e=new File([u],e.name.replace(/\.png$/,".jpg"),{type:h})}const t=await this.managers.appDocsManager.prepareWallPaperUpload(e),s=this.managers.appDocsManager.uploadWallPaper(t.id),i=cs.getNewDeferredForUpload(e.name,s),n=Pt();n.addNotifyListener=i.addNotifyListener.bind(i),n.cancel=i.cancel,i.then(c=>{this.clicked.delete(a),this.elementsByKey.delete(a),this.wallPapersByElement.set(l,c);const d=this.getWallPaperKey(c);this.elementsByKey.set(d,l),this.setBackgroundDocument(c).then(n.resolve.bind(n),n.reject.bind(n))},n.reject.bind(n));const a=this.getWallPaperKey(t);n.catch(()=>{l.remove()});const r=new tn({isUpload:!0,cancelable:!0,tryAgainOnFail:!1}),{container:l}=await this.addWallPaper(t,!1);this.clicked.add(a),r.attach(l,!1,n)})},this.onResetClick=()=>{const e=Gr.settings.themes.find(t=>t.name===this.theme.name);e&&(++na.tempId,this.theme.settings=Wi(e.settings),this.managers.appStateManager.pushToState("settings",I.settings),me.applyCurrentTheme({broadcastEvent:!0}),this.blurCheckboxField.setValueSilently(vh(this.theme.settings?.wallpaper,!1)))},this.onGridClick=e=>{const t=U(e.target,"grid-item");if(!t)return;const s=this.wallPapersByElement.get(t);if(s._==="wallPaperNoFile"){this.setBackgroundDocument(s);return}const i=this.getWallPaperKey(s);if(this.clicked.has(i))return;this.clicked.add(i);const n=s.document,a=new tn({cancelable:!0,tryAgainOnFail:!1}),r=async()=>{const l=this.setBackgroundDocument(s);(!(await this.managers.thumbsStorage.getCacheContext(n)).url||vh(s))&&a.attach(t,!0,l)};a.construct(),N(t,l=>{a.preloader.parentElement?(a.onClick(l),a.detach()):r()},{listenerSetter:this.listenerSetter}),r()},this.setBackgroundDocument=async(e,t)=>(this.blurCheckboxField.isDisabled()||await this.changeWallPaperBlur(e,this.blurCheckboxField.checked),na.setBackgroundDocument(e,t)),this.setActive=()=>{const e=this.grid.querySelector(".active"),t=this.elementsByKey.get(this.getWallPaperKeyFromTheme(this.theme));e!==t&&(this.toggleBlurCheckbox(),e&&e.classList.remove("active"),t&&t.classList.add("active"))}}static getInitArgs(){return{backgrounds:I.managers.appThemesManager.getWallPapers()}}get theme(){return as.getTheme()}init(e=na.getInitArgs()){this.container.classList.add("background-container","background-image-container"),this.setTitle("ChatBackground");{const n=ml(this.scrollable),a=ze("btn-primary btn-transparent",{icon:"cameraadd",text:"ChatBackground.UploadWallpaper"}),r=ze("btn-primary btn-transparent",{icon:"colorize",text:"SetColor"}),l=ze("btn-primary btn-transparent",{icon:"favourites",text:"Appearance.Reset"});N(a,this.onUploadClick,{listenerSetter:this.listenerSetter}),N(r,()=>{this.slider.createTab(R2).open()},{listenerSetter:this.listenerSetter}),N(l,this.onResetClick,{listenerSetter:this.listenerSetter});const c=this.theme.settings?.wallpaper,d=this.blurCheckboxField=new pt({text:"ChatBackground.Blur",name:"blur",checked:vh(c,!1)});this.toggleBlurCheckbox(),this.listenerSetter.add(d.input)("change",async()=>{await this.changeWallPaperBlur(this.theme.settings.wallpaper,d.checked),setTimeout(()=>{const h=i.querySelector(".active");if(!h)return;const u=this.wallPapersByElement.get(h);u.pFlags.pattern||u._==="wallPaperNoFile"||this.setBackgroundDocument(u)},100)}),n.append(a,r,l,rr(d).container)}I.addEventListener("background_change",this.setActive);const t=e.backgrounds.then(n=>{const a=n.map(r=>this.addWallPaper(r));return Promise.all(a)}),s=ml(this.scrollable),i=this.grid=document.createElement("div");return i.classList.add("grid"),N(i,this.onGridClick,{listenerSetter:this.listenerSetter}),s.append(i),t}getWallPaperKey(e){return""+e.id}getWallPaperKeyFromTheme(e){return""+(this.getWallPaperKey(e.settings?.wallpaper)||"")}static addWallPaper(e,t=document.createElement("div")){const s=bm(e),i=e._==="wallPaper";if(i&&e.pFlags.pattern&&!s)return;const n=!!e.pFlags.dark;let a=i?e.document:void 0;i&&!a&&(a={_:"webDocumentNoProxy",attributes:[],size:1e5,url:"assets/img/pattern.svg",w:1440,h:2960,mime_type:"image/svg+xml"}),t.classList.add("background-item"),t.dataset.id=""+e.id;const r=document.createElement("div");r.classList.add("background-item-media");const l=[];let c,d;if(i){d=Sn(a,200,200),c=Ks({photo:a,message:null,container:r,withoutPreloader:!0,size:d,noFadeIn:e.pFlags.pattern}),e.pFlags.pattern&&r.classList.add("is-pattern");const h=c.then(async({loadPromises:u,images:p})=>(await u.thumb||u.full,p)).then(u=>(e.pFlags.pattern&&(n?(u.full.style.display="none",u.thumb&&(u.thumb.style.display="none")):e.settings?.intensity&&(u.full.style.opacity=""+Math.abs(e.settings.intensity)/100)),Dh.mutate(()=>{t.append(r)})));l.push(h)}else t.append(r);if(e.settings?.background_color){const{canvas:h}=Jc.create(s);if(h.classList.add("background-colors-canvas"),n&&i){const u=c.then(({loadPromises:p})=>p.full.then(async()=>{const m=await I.managers.thumbsStorage.getCacheContext(a,d.type);h.style.webkitMaskImage=`url(${m.url})`,h.style.opacity=""+(e.pFlags.dark?100+e.settings.intensity:e.settings.intensity)/100,r.append(h)}));l.push(u)}else r.append(h)}return{container:t,media:r,loadPromise:Promise.all(l)}}addWallPaper(e,t=!0){const s=na.addWallPaper(e);if(s){const{container:i,media:n}=s;i.classList.add("grid-item"),n.classList.add("grid-item-media");const a=this.getWallPaperKey(e);this.wallPapersByElement.set(i,e),this.elementsByKey.set(a,i),this.getWallPaperKeyFromTheme(this.theme)===a&&i.classList.add("active"),this.grid[t?"append":"prepend"](i)}return s&&s.loadPromise.then(()=>s)}async changeWallPaperBlur(e,t){(e.settings??(e.settings={_:"wallPaperSettings",pFlags:{}})).pFlags.blur=t||void 0,await this.managers.appStateManager.pushToState("settings",I.settings)}toggleBlurCheckbox(){const e=this.theme.settings?.wallpaper;this.blurCheckboxField.toggleDisability(!e||e._==="wallPaperNoFile"||!!e?.pFlags?.pattern)}};na.tempId=0,na.setBackgroundDocument=(e,t)=>{const s=++na.tempId,i=()=>s===na.tempId,n=e.document,a=Pt();let r;return n?(r=cs.downloadMediaURL({media:n,queueId:me.chat.bubbles?me.chat.bubbles.lazyLoadQueue.queueId:0}),a.addNotifyListener=r.addNotifyListener.bind(r),a.cancel=r.cancel):r=Promise.resolve(),r.then(async()=>{if(!i()){a.resolve();return}const l=!!t;t??(t=as.getTheme().settings);const c=h=>{let u;const p=bm(e);if(h&&!p)u=ax(h);else{const{canvas:g}=Jc.create(p);u=Promise.resolve(xf(g))}const m=e.slug;Promise.all([u,me.saveWallPaperToCache(m,h)]).then(([g])=>{if(!i()){a.resolve();return}const f=Af(Array.from(g));t.wallpaper=e,t.highlightingColor=f,l||I.managers.appStateManager.pushToState("settings",I.settings),me.applyCurrentTheme({slug:m,backgroundUrl:h,broadcastEvent:!0}).then(a.resolve.bind(a))})};if(!n){c();return}const d=await I.managers.thumbsStorage.getCacheContext(n);vh(e)?setTimeout(()=>{me.blurWallPaperImage(d.url).then(h=>{if(!i()){a.resolve();return}c(h)})},200):i()&&c(d.url)}),a};let Zo=na;function B2(o,e){return Bf(o,()=>(60-new Date().getSeconds())*1e3,e)}class mI extends Dt{init(){this.container.classList.add("power-saving-container"),this.setTitle("LiteMode.Title");const e=document.createElement("form");let t;{const r=t=new Pe({caption:"LiteMode.Info"});e.append(r.container)}const s=["all","video","gif",["stickers",["stickers_panel","stickers_chat"]],["effects",["effects_reactions","effects_premiumstickers","effects_emoji"]],["chat",["chat_background","chat_spoilers"]],"animations"];let i,n;{const r=new Pe({}),l=c=>{const d=Array.isArray(c),h=d?c[0]:c,u=d?Ln(c[1].map(l)):void 0,p=I.settings.liteMode[h];return[{key:h,text:h==="all"?"LiteMode.EnableText":`LiteMode.Key.${h}.Title`,checked:h==="all"?p:!p,nested:u,name:"power-saving-"+h},...u||[]]};i=Ln(s.map(l)),n=new qu({fields:i,listenerSetter:this.listenerSetter}),i.forEach((c,d)=>{const h=n.createField(c);if(!h)return;const{row:u,nodes:p}=h;(d===0?t:r).content.append(...p)}),N(r.content,()=>{I.settings.liteMode.all&&Ee({langPackKey:"LiteMode.DisableAlert"})},{listenerSetter:this.listenerSetter}),e.append(r.container)}const a=r=>{i.forEach(l=>{l.key!=="all"&&(l.nested&&n.setNestedCounter(l,r?0:void 0),l.checkboxField.input.classList.toggle("is-fake-disabled",r),l.row.toggleDisability(r))})};this.listenerSetter.add(e)("change",async()=>{const r={};i.forEach(c=>{const d=c.checkboxField.checked;r[c.key]=c.key==="all"?d:!d});const l=I.settings.liteMode.all;l!==r.all&&(a(!l),r.all&&await Hs(200)),await this.managers.appStateManager.setByKey(Gs("settings","liteMode"),I.settings.liteMode=r)}),a(I.settings.liteMode.all),this.scrollable.append(e)}}class gI{constructor(e,t,s,i,n,a=!0){const r="range-setting-selector";this.container=document.createElement("div"),this.container.classList.add(r);const l=document.createElement("div");l.classList.add(r+"-details");const c=document.createElement("div");c.classList.add(r+"-name"),Zt(c,e);const d=this.valueContainer=document.createElement("div");d.classList.add(r+"-value"),a&&(d.innerHTML=""+s),l.append(c,d),this.range=new Td({step:t,min:i,max:n},s),this.range.setListeners(),this.range.setHandlers({onScrub:h=>{this.onChange&&this.onChange(h),a&&(d.innerText=""+h)}}),this.container.append(l,this.range.container)}}class N2 extends Xt{static getInitArgs(){return{themes:I.managers.appThemesManager.getThemes()}}init(e){this.container.classList.add("general-settings-container"),this.setTitle("General");const t=ml.bind(null,this.scrollable),s=[];{const i=t("Settings"),n=new gI("TextSize",1,I.settings.messagesTextSize,12,20);n.onChange=m=>{I.managers.appStateManager.setByKey(Gs("settings","messagesTextSize"),m)};const a=ze("btn-primary btn-transparent",{icon:"image",text:"ChatBackground"}),r=Zo.getInitArgs();N(a,()=>{this.slider.createTab(Zo).open(r)});const l=()=>I.settings.liteMode.all?"Checkbox.Enabled":"Checkbox.Disabled",c=new ke.IntlElement,d=()=>{c.compareAndUpdate({key:l()}),h.setValueSilently(st.isAvailable("animations")),h.toggleDisability(st.isEnabled())},h=new pt({text:"EnableAnimations",name:"animations",stateKey:Gs("settings","liteMode","animations"),stateValueReverse:!0,checked:!1,listenerSetter:this.listenerSetter}),u=new ve({checkboxField:h,clickable:()=>{h.isDisabled()&&Ee({langPackKey:"LiteMode.DisableAlert"})},listenerSetter:this.listenerSetter}),p=new ve({icon:"animations",titleLangKey:"LiteMode.EnableText",titleRightSecondary:c.element,clickable:()=>{this.slider.createTab(mI).open()},listenerSetter:this.listenerSetter});d(),this.listenerSetter.add(I)("settings_updated",d),i.append(n.container,a,u.container,p.container)}{const i=t("ColorTheme"),n=new yr(null),a=n.container;a.classList.add("themes-container");const r=new Map;let l=as.getTheme(),c=as.isNight();const d=b=>{as.applyTheme(b.theme,b.container),b.container.querySelector(".background-item")?.remove();const C=b.wallPaperContainers[c?"baseThemeNight":"baseThemeClassic"];C&&b.container.prepend(C)};let h;N(a,async b=>{const S=U(b.target,"theme-container");if(!S)return;const C=a.querySelector(".active");C&&C.classList.remove("active");const P=r.get(S);if(S.classList.add("active"),await as.applyNewTheme(P.theme),h?.(-1),P.player&&st.isAvailable("animations"))if(Pi)P.player.paused&&P.player.restart();else{P.player.paused&&P.player.stop(!0),P.player.el[0].style.transform="scale(2)";const L=h=E=>{(P.player.maxFrame===E||E===-1)&&(P.player.el[0].style.transform="",P.player.removeEventListener("enterFrame",L),h===L&&(h=void 0))};setTimeout(()=>{h===L&&(P.player.play(),P.player.addEventListener("enterFrame",L))},250)}},{listenerSetter:this.listenerSetter});const u=new Set(["baseThemeClassic","baseThemeNight"]),p=e.themes.then(async b=>{const S=b.filter(L=>L.pFlags.default);S.unshift(FL);const C=S.map(async L=>{const E=document.createElement("div"),_={container:E,theme:L,wallPaperContainers:{}},k=L.settings.filter(O=>u.has(O.base_theme._)).map(O=>{const X=O.wallpaper,F=Zo.addWallPaper(X);return _.wallPaperContainers[O.base_theme._]=F.container,F});r.set(E,_),d(_),L.id===l.id&&E.classList.add("active");const x=L.emoticon,A=[];let T;if(x){T=document.createElement("div"),T.classList.add("theme-emoticon");const O=28*1.75;Sr({div:T,width:O,height:O,emoji:L.emoticon,managers:this.managers,loadPromises:A,middleware:this.middlewareHelper.get(),play:!1}).then(({render:X})=>X).then(X=>{_.player=X})}const B=document.createElement("div");B.classList.add("theme-bubble");const R=B.cloneNode();return R.classList.add("is-in"),B.classList.add("is-out"),A.push(...k.map(O=>O.loadPromise)),E.classList.add("theme-container"),await Promise.all(A),T&&E.append(T),E.append(R,B),E}),P=await Promise.all(C);n.append(...P)});s.push(p);const m=document.createElement("form");m.style.marginTop=".5rem";const g="theme",f=Gs("settings","theme"),y=new ve({radioField:new _i({langKey:"ThemeDay",name:g,value:"day",stateKey:f})}),v=new ve({radioField:new _i({langKey:"ThemeNight",name:g,value:"night",stateKey:f})}),w=new ve({radioField:new _i({langKey:"AutoNightSystemDefault",name:g,value:"system",stateKey:f})});this.listenerSetter.add(I)("settings_updated",({key:b,value:S,settings:C})=>{b===f&&I.dispatchEvent("theme_change")}),this.listenerSetter.add(I)("theme_changed",()=>{l=as.getTheme();const b=as.isNight();if(c===b)return;c=b;const S=a.querySelector(".active");S&&S.classList.remove("active");let C;r.forEach(P=>{d(P),P.theme.id===l.id&&(P.container.classList.add("active"),C=P.container)}),C&&n.scrollIntoViewNew({element:C,position:"center",axis:"x"})}),m.append(y.container,v.container,w.container),i.append(a,m)}{const i=t("General.Keyboard"),n=document.createElement("form"),a="send-shortcut",r=Gs("settings","sendShortcut"),l=new ve({radioField:new _i({langKey:"General.SendShortcut.Enter",name:a,value:"enter",stateKey:r}),subtitleLangKey:"General.SendShortcut.NewLine.ShiftEnter"}),c=new ve({radioField:new _i({name:a,value:"ctrlEnter",stateKey:r}),subtitleLangKey:"General.SendShortcut.NewLine.Enter"});Zt(c.radioField.main,"General.SendShortcut.CtrlEnter",[Zr?"⌘":"Ctrl"]),n.append(l.container,c.container),i.append(n)}if(Fb){const i=t("DistanceUnitsTitle"),n=document.createElement("form"),a="distance-unit",r=Gs("settings","distanceUnit"),l=new ve({radioField:new _i({langKey:"DistanceUnitsKilometers",name:a,value:"kilometers",stateKey:r})}),c=new ve({radioField:new _i({langKey:"DistanceUnitsMiles",name:a,value:"miles",stateKey:r})});n.append(l.container,c.container),i.append(n)}{const i=t("General.TimeFormat"),n=document.createElement("form"),a="time-format",r=Gs("settings","timeFormat"),l=[["h12","General.TimeFormat.h12"],["h23","General.TimeFormat.h23"]],c=l.map(([h,u])=>new ve({radioField:new _i({langKey:u,name:a,value:h,stateKey:r})})),d=B2(()=>{const h=new Date;l.forEach(([u],p)=>{const m=h.toLocaleTimeString("en-us-u-hc-"+u,{hour:"2-digit",minute:"2-digit"});c[p].subtitle.textContent=m})});this.eventListener.addEventListener("destroy",d),n.append(...c.map(h=>h.container)),i.append(n)}return Promise.all(s)}}class Xv extends Dt{constructor(){super(...arguments),this.renderResults=async e=>{await this.managers.appUsersManager.getContacts(),e.forEach(t=>{const s=Xe.addDialogNew({peerId:t,container:this.selector.list,rippleEnabled:!0,avatarSize:"abitbigger",wrapOptions:{middleware:this.middlewareHelper.get()}});s.container.dialogElement=s;const{dom:i}=s,n=this.selector.selected.has(t);i.containerEl.append(this.selector.checkbox(n));const a=[];this.dialogsByFilters.forEach((l,c)=>{if(l.has(t)){const d=document.createElement("span");kt(d,_e(c.title)),a.push(d)}}),pi(a,!1).forEach(l=>{i.lastMessageSpan.append(l)})})},this.onSelectChange=e=>{this.type==="included"&&(this.confirmBtn.style.display=e?"":"none")}}init(e,t,s){this.originalFilter=e,this.filter=Wi(this.originalFilter),this.type=t,this.editFolderTab=s,this.content.remove(),this.container.classList.add("included-chatlist-container"),this.confirmBtn=it("check btn-confirm blue",{noRipple:!0}),this.confirmBtn.style.display="none",this.header.append(this.confirmBtn),N(this.confirmBtn,async()=>{const n=this.selector.getSelected(),a=this.filter.pFlags;if(this.type==="included"&&a)for(const p in a)p.indexOf("exclude_")!==0&&delete a[p];else if(a)for(const p in a)p.indexOf("exclude_")===0&&delete a[p];const r=[];for(const p of n)p.isPeerId()?r.push(p.toPeerId()):this.filter.pFlags[p]=!0;let l;this.type==="included"?l=p=>r.includes(p):l=p=>!r.includes(p),bi(this.filter.pinnedPeerIds,(p,m)=>{l(p)||(this.filter.pinnedPeerIds.splice(m,1),this.filter.pinned_peers.splice(m,1))});const c=this.type==="included"?"excludePeerIds":"includePeerIds",d=this.type==="included"?"exclude_peers":"include_peers",h=this.filter[c],u=this.filter[d];h&&bi(h,(p,m)=>{r.includes(p)&&(h.splice(m,1),u.splice(m,1))}),this.filter[this.type==="included"?"includePeerIds":"excludePeerIds"]=r,this.filter[this.type==="included"?"include_peers":"exclude_peers"]=await Promise.all(r.map(p=>this.managers.appPeersManager.getInputPeerById(p))),this.editFolderTab.setFilter(this.filter,!1),this.close()},{listenerSetter:this.listenerSetter});const i=n=>{this.limit=I.premium?n.dialog_filters_chats_limit_premium:n.dialog_filters_chats_limit_default};return this.listenerSetter.add(I)("app_config",i),this.dialogsByFilters=new Map,Promise.all([this.managers.filtersStorage.getDialogFilters().then(async n=>{await Promise.all(n.filter(a=>!ra.has(a.id)).map(async a=>{const l=(await this.managers.dialogsStorage.getFolderDialogs(a.id)).map(c=>c.peerId);this.dialogsByFilters.set(a,new Set(l))}))}),this.managers.apiManager.getAppConfig().then(n=>{i(n)})])}onOpen(){this.confirmBtn.style.display=this.type==="excluded"?"":"none",this.setTitle(this.type==="included"?"FilterAlwaysShow":"FilterNeverShow");const e=this.filter,t=new Pe({noDelimiter:!0,name:"FilterChatTypes"});t.container.classList.add("folder-categories");let s;this.type==="excluded"?s={exclude_muted:{ico:"mute",text:"ChatList.Filter.MutedChats"},exclude_archived:{ico:"archive",text:"ChatList.Filter.Archive"},exclude_read:{ico:"readchats",text:"ChatList.Filter.ReadChats"}}:s={contacts:{ico:"newprivate",text:"ChatList.Filter.Contacts"},non_contacts:{ico:"noncontacts",text:"ChatList.Filter.NonContacts"},groups:{ico:"group",text:"ChatList.Filter.Groups"},broadcasts:{ico:"newchannel",text:"ChatList.Filter.Channels"},bots:{ico:"bots",text:"ChatList.Filter.Bots"}},this.selector=new Mi({middleware:this.middlewareHelper.get(),appendTo:this.container,onChange:this.onSelectChange,peerType:["dialogs"],renderResultsFunc:this.renderResults,placeholder:"Search",sectionNameLangPackKey:"FilterChats",managers:this.managers});const i=document.createDocumentFragment();for(const c in s){const d=ze("btn-primary btn-transparent folder-category-button",{icon:s[c].ico,text:s[c].text});d.dataset.peerId=c,d.append(this.selector.checkbox()),i.append(d)}t.content.append(i);const n=(this.type==="included"?e.includePeerIds:e.excludePeerIds).slice();this.selector.selected=new Set(n);let a=!1;const r=this.selector.add.bind(this.selector);this.selector.add=({key:c,title:d,scroll:h})=>this.selector.selected.size>=this.limit&&a&&!s[c]?(ua("folderPeers"),!1):r({key:c,title:s[c]?M(s[c].text):void 0,scroll:h,fallbackIcon:s[c]?.ico}),this.selector.scrollable.append(t.container,this.selector.scrollable.container.lastElementChild),this.selector.addInitial(n),a=!0;const l=e.pFlags;if(l)for(const c in l)s.hasOwnProperty(c)&&l[c]&&fs(t.content.querySelector(`[data-peer-id="${c}"]`))}onCloseAfterTimeout(){return this.selector&&(this.selector.container.remove(),this.selector=null),super.onCloseAfterTimeout()}}const O2=12;class Da extends Dt{constructor(){super(...arguments),this.flags={}}static getInitArgs(){return{animationData:_s.loadAnimationFromURLManually("Folders_2")}}static async deleteFolder(e){const t=await I.managers.filtersStorage.getFilter(e);if(t?._==="dialogFilterChatlist"&&!t.pFlags.has_my_invites){ee.createPopup(Cf,{filter:t,deleting:!0});return}return await Ct({titleLangKey:"ChatList.Filter.Confirm.Remove.Header",descriptionLangKey:t.pFlags.has_my_invites?"RemoveSharedFolder":"ChatList.Filter.Confirm.Remove.Text",button:{langKey:"Delete",isDanger:!0}}),I.managers.filtersStorage.updateDialogFilter({_:"dialogFilter",id:e},!0)}init(e=Da.getInitArgs()){this.container.classList.add("edit-folder-container"),this.caption=document.createElement("div"),this.caption.classList.add("caption"),this.caption.append(M("FilterIncludeExcludeInfo")),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container"),this.tempId=0,this.showMoreClicked={},this.confirmBtn=it("check btn-confirm hide blue");let t=!1;const s={icon:"delete",className:"danger",text:"FilterMenuDelete",onClick:()=>{t||Da.deleteFolder(this.filter.id).then(()=>{this.close()}).finally(()=>{t=!1})}};this.menuBtn=ai({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[s]}),this.menuBtn.classList.add("hide"),this.header.append(this.confirmBtn,this.menuBtn);const i=new Pe({}),n=document.createElement("div");n.classList.add("input-wrapper"),this.nameInputField=new _t({label:"FilterNameHint",maxLength:O2}),n.append(this.nameInputField.container),i.content.append(n);const a=(p,m,g,f,y)=>{const v=new Pe({name:m,caption:y,noDelimiter:!0});v.container.classList.add("folder-list",p);const w=v.generateContentElement();return w.classList.add("folder-categories"),g.forEach((b,S)=>{const C=ze("folder-category-button btn btn-primary btn-transparent"+(S===0?" primary":" disable-hover"),{icon:b.icon,text:b.text,noRipple:b.withRipple?void 0:!0});b.name&&(f[b.name]=C),w.append(C)}),v};this.includePeerIds=a("folder-list-included","FilterInclude",this.includePeerIdsButtons=[{icon:"add",text:"ChatList.Filter.Include.AddChat",withRipple:!0},{text:"ChatList.Filter.Contacts",icon:"newprivate",name:"contacts"},{text:"ChatList.Filter.NonContacts",icon:"noncontacts",name:"non_contacts"},{text:"ChatList.Filter.Groups",icon:"group",name:"groups"},{text:"ChatList.Filter.Channels",icon:"channel",name:"broadcasts"},{text:"ChatList.Filter.Bots",icon:"bots",name:"bots"}],this.flags,"FilterIncludeInfo"),this.excludePeerIds=a("folder-list-excluded","FilterExclude",this.excludePeerIdsButtons=[{icon:"minus",text:"FilterRemoveChats",withRipple:!0},{text:"ChatList.Filter.MutedChats",icon:"mute",name:"exclude_muted"},{text:"ChatList.Filter.Archive",icon:"archive",name:"exclude_archived"},{text:"ChatList.Filter.ReadChats",icon:"readchats",name:"exclude_read"}],this.flags,"FilterExcludeInfo"),this.inviteLinks=a("folder-list-links","InviteLinks",[{icon:"add",text:"SharedFolder.CreateLink",withRipple:!0}],{},"SharedFolder.Description"),this.scrollable.append(this.stickerContainer,this.caption,i.container,this.includePeerIds.container,this.excludePeerIds.container,this.inviteLinks.container),this.toggleExcludedPeers();const r=this.includePeerIds.container.querySelector(".folder-categories"),l=this.excludePeerIds.container.querySelector(".folder-categories");this.inviteLinksCreate=this.inviteLinks.container.querySelector(".btn"),N(r.querySelector(".btn"),()=>{this.slider.createTab(Xv).open(this.filter,"included",this)},{listenerSetter:this.listenerSetter}),N(l.querySelector(".btn"),()=>{this.slider.createTab(Xv).open(this.filter,"excluded",this)},{listenerSetter:this.listenerSetter});const c=p=>{if(this.nameInputField.input.classList.contains("error"))return;if(!this.nameInputField.value.trim()){this.nameInputField.input.classList.add("error");return}let m=Array.from(r.children).slice(1).reduce((f,y)=>f+ +!y.style.display,0);if(m+=this.filter.include_peers.length,!m){Ee({langPackKey:"EditFolder.Toast.ChooseChat"});return}this.confirmBtn.setAttribute("disabled","true");let g;return this.filter.id?(p&&(h=!0),g=this.managers.filtersStorage.updateDialogFilter(this.filter)):g=this.managers.filtersStorage.createDialogFilter(this.filter),g.then(f=>(p&&this.close(),f)).catch(f=>{throw h=!1,d&&(this.updateFilter(d),d=void 0),f.type==="DIALOG_FILTERS_TOO_MUCH"?ua("folders"):console.error("updateDialogFilter error:",f),f}).finally(()=>{this.confirmBtn.removeAttribute("disabled")})};N(this.confirmBtn,()=>{c(!0)},{listenerSetter:this.listenerSetter});let d,h=!1;this.listenerSetter.add(I)("filter_update",p=>{this.filter.id===p.id&&(h?d=p:this.updateFilter(p))}),this.listenerSetter.add(this.nameInputField.input)("input",()=>{this.filter.title=this.nameInputField.value,this.editCheckForChange()});const u=this.type==="edit"?[this.managers.filtersStorage.reloadMissingPeerIds(this.filter.id,"pinned_peers"),this.managers.filtersStorage.reloadMissingPeerIds(this.filter.id,"include_peers"),this.managers.filtersStorage.reloadMissingPeerIds(this.filter.id,"exclude_peers")]:[];return Promise.all([this.managers.apiManager.getLimit("chatlistInvites"),this.managers.apiManager.getLimit("chatlistInvites",!0),this.loadAnimationPromise=e.animationData.then(async p=>{const m=await p({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86});return this.animation=m,_s.waitForFirstFrame(m)}),...u]).then(([p,m])=>{this.type==="edit"?(this.setFilter(this.originalFilter,!0),this.onEditOpen()):(this.setInitFilter(),this.onCreateOpen()),this.managers.filtersStorage.getExportedInvites(this.filter.id).catch(g=>{if(g.type==="FILTER_NOT_SUPPORTED")return[];throw g}).then(g=>{console.log(g);const f="usernames",y=this.inviteLinks.generateContentElement(),v=new Map,w=new Map,b=()=>{this.inviteLinksCreate.classList.toggle("hide",v.size>=m)},S=_=>{const k=w.get(_.url);k&&(k.container.remove(),w.delete(_.url),v.delete(k.container),b())},C=(_,k)=>{const x=k.title&&k.title!==this.filter.title?_e(k.title):k.url.replace(/(.+?):\/\//,""),A=M("SharedFolder.Includes",[M("Chats",[k.peers.length])]);_.title.replaceChildren(x),_.subtitle.replaceChildren(A)},P=_=>{const k=new ve({title:!0,subtitle:!0,clickable:!0});C(k,_),k.container.classList.add(f+"-username","active");const x=k.createMedia("medium");x.classList.add(f+"-username-icon"),x.append(Le("link")),y.append(k.container),v.set(k.container,_),w.set(_.url,k),b()};let L;ln({buttons:[{icon:"copy",text:"CopyLink",onClick:()=>Fs(v.get(L).url)},{icon:"delete",className:"danger",text:"Delete",onClick:()=>{const _=v.get(L);this.managers.filtersStorage.deleteExportedInvite(this.filter.id,_.url).then(()=>{S(_)})}}],listenTo:y,listenerSetter:this.listenerSetter,findElement:_=>U(_.target,"row"),onOpen:(_,k)=>L=k}),N(this.inviteLinksCreate,async()=>{if(v.size>=p){ua("chatlistInvites");return}if(!this.filter.title){Ee({langPackKey:"SharedFolder.Toast.NeedName"});return}const _=this.filter.pFlags;if(_&&[this.includePeerIdsButtons,this.excludePeerIdsButtons].some(A=>A.some(T=>!!_[T.name]))){Ee({langPackKey:"SharedFolder.Toast.NoTypes"});return}if(this.filter.excludePeerIds?.length){Ee({langPackKey:"SharedFolder.Toast.NoExcluded"});return}const k=jt([this.inviteLinksCreate],!0);try{const x=c(!1);if(!(x instanceof Promise))throw"";const A=await x;this.updateFilter(A),this.type="edit",this.originalFilter=A,this.editCheckForChange()}catch{k();return}this.managers.filtersStorage.exportChatlistInvite({...this.filter,_:"dialogFilterChatlist",pFlags:this.filter._==="dialogFilter"?{has_my_invites:!0}:this.filter.pFlags}).then(x=>{k(),E(x.invite).finally(()=>{P(x.invite)})},x=>{if(k(),x.type==="INVITES_TOO_MUCH"||x.type==="FILTERS_TOO_MUCH"||x.type==="CHATLISTS_TOO_MUCH"){ua("chatlistInvites");return}else if(x.type==="PEERS_LIST_EMPTY"||x.type==="CHAT_ADMIN_REQUIRED"){E();return}throw x})},{listenerSetter:this.listenerSetter});const E=_=>{const k=w.get(_?.url),x=this.slider.createTab(of);return x.filter=this.filter,x.chatlistInvite=_,x.eventListener.addEventListener("delete",()=>{S(_)}),x.eventListener.addEventListener("edit",A=>{v.set(k.container,A),C(k,A)}),x.open()};N(y,_=>{const k=U(_.target,"row"),x=v.get(k);x&&E(x)},{listenerSetter:this.listenerSetter}),g.forEach(P)})})}onOpenAfterTimeout(){this.loadAnimationPromise.then(()=>{this.animation.autoplay=!0,this.animation.play()})}onCreateOpen(){this.setTitle("FilterNew"),this.menuBtn.classList.add("hide"),this.confirmBtn.classList.remove("hide");for(const e in this.flags)this.flags[e].style.display="none"}onEditOpen(){const e=++this.tempId;this.setTitle(this.type==="create"?"FilterNew":"FilterHeaderEdit"),this.type==="edit"&&(this.menuBtn.classList.remove("hide"),this.confirmBtn.classList.add("hide"));const t=this.filter;this.nameInputField.value=Au(t.title);const s=t.pFlags;for(const n in this.flags){const a=!!s?.[n];this.flags[n].style.display=a?"":"none"}const i=["includePeerIds","excludePeerIds"].map(async n=>{let a=t[n];if(!a)return;const r=this[n],l=Xe.createChatList({ignoreClick:!0}),c=async p=>!!await this.managers.appMessagesManager.getDialogOnly(p)||(p.isUser()?(await this.managers.appUsersManager.getUser(p.toUserId()))._==="user":!1),d=await Zi(a,p=>c(p));a.length=0,a.push(...d),a=a.slice();const h=async p=>{const m=a.splice(0,p),g=await Zi(m,async v=>v.isUser()?!0:!!await this.managers.appMessagesManager.getDialogOnly(v));if(e!==this.tempId)return;const f=[],y=g.map(v=>{const w=Xe.addDialogNew({peerId:v,rippleEnabled:!1,meAsSaved:!0,avatarSize:"small",loadPromises:f,autonomous:!0,wrapOptions:{middleware:this.middlewareHelper.get()}});w.container.dialogElement=w;const{dom:b}=w;return b.lastMessageSpan.parentElement.remove(),b.containerEl});await Promise.all(f),e===this.tempId&&(l.append(...y),u&&(a.length?(u.lastElementChild.replaceWith(M("FilterShowMoreChats",[a.length])),u.classList.remove("hide")):u.remove()))};let u;return a.length&&!this.showMoreClicked[n]&&(u=ze("folder-category-button btn btn-primary btn-transparent hide",{icon:"down"}),u.classList.add("load-more","rp-overflow"),N(u,()=>{this.showMoreClicked[n]=!0,h(1/0)},{listenerSetter:this.listenerSetter}),u.append(M("FilterShowMoreChats",[a.length]))),h(this.showMoreClicked[n]?1/0:4).then(()=>{if(e===this.tempId)return()=>{r.generateContentElement().append(l),u&&a.length&&r.generateContentElement().append(u)}})});return Promise.all(i).then(n=>{e===this.tempId&&(this.toggleExcludedPeers(),this.container&&Array.from(this.container.querySelectorAll(".chatlist, .load-more")).forEach(a=>a.parentElement.remove()),n.forEach(a=>a?.()))})}editCheckForChange(){if(this.type==="edit"){const e=!Di({...this.originalFilter,updatedTime:0,localId:0},{...this.filter,updatedTime:0,localId:0});this.confirmBtn.classList.toggle("hide",!e),this.menuBtn.classList.toggle("hide",e)}}setFilter(e,t){t?(this.originalFilter=e,this.filter=Wi(e)):(this.filter=e,this.onEditOpen(),this.editCheckForChange())}setInitFilter(e){e===void 0?(this.setFilter({_:"dialogFilter",id:0,title:"",pFlags:{},pinned_peers:[],include_peers:[],exclude_peers:[],pinnedPeerIds:[],includePeerIds:[],excludePeerIds:[]},!0),this.type="create"):(this.setFilter(e,!0),this.type="edit")}toggleExcludedPeers(){this.excludePeerIds.container.classList.toggle("hide",this.filter?._==="dialogFilterChatlist")}updateFilter(e){this.setFilter(e,!1)}}class bp extends Dt{constructor(){super(...arguments),this.filtersRendered={}}static getInitArgs(){return{animationData:_s.loadAnimationFromURLManually("Folders_1"),filters:I.managers.filtersStorage.getDialogFilters()}}async renderFolder(e,t,s,i){let n,a="";const r=[];if(e._==="dialogFilterSuggested")n=e.filter,a=e.description;else{n=e;const c=n.pFlags||{};if(Object.keys(c).length===1){let h;c.contacts?h="FilterAllContacts":c.non_contacts?h="FilterAllNonContacts":c.groups?h="FilterAllGroups":c.broadcasts?h="FilterAllChannels":c.bots&&(h="FilterAllBots"),h&&r.push(M(h))}if(!r.length){const h=await this.managers.dialogsStorage.getFolderDialogs(n.id);let u=0,p=0,m=0;await Promise.all(h.map(async g=>{await this.managers.appPeersManager.isAnyGroup(g.peerId)?++m:await this.managers.appPeersManager.isBroadcast(g.peerId)?++p:++u})),u&&r.push(M("Chats",[u])),p&&r.push(M("Channels",[p])),m&&r.push(M("Groups",[m]))}}if(s)n.id!==Ci&&dt(s.title,_e(n.title)),s.subtitle.textContent="",s.subtitle.append(...pi(r));else{const c=e._==="dialogFilterSuggested";if(s=new ve({title:n.id===Ci&&!c?M("FilterAllChats"):_e(n.title),subtitle:a,clickable:!0,buttonRightLangKey:c?"Add":void 0}),r.length&&s.subtitle.append(...pi(r)),!c){const d=n.id;if(!this.filtersRendered[n.id]&&n.id!==Ci){const h=Da.getInitArgs();N(s.container,async()=>{const u=await this.managers.filtersStorage.getFilter(d),p=this.slider.createTab(Da);p.setInitFilter(u),p.open(h)},{listenerSetter:this.listenerSetter})}this.filtersRendered[n.id]=s,s.makeSortable()}}const l=s.container;if(i){const c=n.localId;c!==void 0?Ps(l,l.parentElement||t,c):t&&t.append(l)}return s}init(e=bp.getInitArgs()){this.container.classList.add("chat-folders-container"),this.setTitle("ChatList.Filter.List.Title"),this.scrollable.container.classList.add("chat-folders"),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container");const t=document.createElement("div");t.classList.add("caption"),Nh({element:t,key:"ChatList.Filter.Header"}),this.createFolderBtn=ze("btn-primary btn-color-primary btn-control",{text:"ChatList.Filter.NewTitle",icon:"add"}),this.foldersSection=new Pe({name:"Filters"}),this.foldersSection.container.classList.add("hide"),this.list=document.createElement("div"),this.foldersSection.content.append(this.list),this.suggestedSection=new Pe({name:"FilterRecommended"}),this.suggestedSection.container.classList.add("hide"),this.scrollable.append(this.stickerContainer,t,this.createFolderBtn,this.foldersSection.container,this.suggestedSection.container),N(this.createFolderBtn,async()=>{await this.canCreateFolder()?this.slider.createTab(Da).open():ua("folders")},{listenerSetter:this.listenerSetter});const s=()=>{this.foldersSection.container.classList.toggle("hide",!Object.keys(this.filtersRendered).length)},i=[],n=e.filters.then(async a=>{for(const r of a)r.id!==Vi&&await this.renderFolder(r,this.list,void 0,!0);this.toggleAllChats(),s()});return i.push(n),this.listenerSetter.add(I)("filter_update",async a=>{const r=this.filtersRendered[a.id];r?await this.renderFolder(a,null,r):a.id!==Vi&&await this.renderFolder(a,this.list,void 0,!0),s(),this.getSuggestedFilters()}),this.listenerSetter.add(I)("filter_delete",a=>{const r=this.filtersRendered[a.id];r&&(this.getSuggestedFilters(),r.container.remove(),delete this.filtersRendered[a.id]),s()}),this.listenerSetter.add(I)("filter_order",a=>{a.filter(r=>!!this.filtersRendered[r]).forEach((r,l)=>{const d=this.filtersRendered[r].container;Ps(d,d.parentElement,l+1)})}),this.listenerSetter.add(I)("premium_toggle",()=>{this.toggleAllChats()}),this.loadAnimationPromise=e.animationData.then(async a=>{const r=await a({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86});return this.animation=r,_s.waitForFirstFrame(r)}),i.push(this.loadAnimationPromise),new ef({list:this.list,middleware:this.middlewareHelper.get(),onSort:(a,r)=>{let l=[];for(const c in this.filtersRendered){const d=this.filtersRendered[c],h=Ri(d.container);l[h]=+c}l=l.filter(c=>c!==void 0),I.premium||us(l,Ci),this.managers.filtersStorage.updateDialogFiltersOrder(l)},scrollable:this.scrollable}),this.getSuggestedFilters(),Promise.all(i)}onOpenAfterTimeout(){return this.loadAnimationPromise.then(()=>{this.animation.autoplay=!0,this.animation.play()}),super.onOpenAfterTimeout()}toggleAllChats(){this.filtersRendered[Ci].container.classList.toggle("hide",!I.premium)}async canCreateFolder(){const[e,t]=await Promise.all([this.managers.apiManager.getLimit("folders"),this.managers.filtersStorage.getDialogFilters()]);return t.filter(i=>!ra.has(i.id)).length<e}getSuggestedFilters(){return this.managers.filtersStorage.getSuggestedDialogsFilters().then(async e=>{this.suggestedSection.container.classList.toggle("hide",!e.length),Array.from(this.suggestedSection.content.children).slice(1).forEach(t=>t.remove());for(const t of e){const s=await this.renderFolder(t);this.suggestedSection.content.append(s.container);const i=s.buttonRight;N(i,async n=>{if(oe(n),!await this.canCreateFolder()){ua("folders");return}i.setAttribute("disabled","true");const a=t.filter;a.includePeerIds=[],a.excludePeerIds=[],a.pinnedPeerIds=[],this.managers.filtersStorage.createDialogFilter(a,!0).then(()=>{s.container.remove(),this.suggestedSection.container.classList.toggle("hide",this.suggestedSection.content.childElementCount===1)}).finally(()=>{i.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter})}})}}class U2 extends Xt{init(){this.container.classList.add("notifications-container"),this.setTitle("Telegram.NotificationSettingsViewController");const e=t=>{const s=new Pe({name:t.name}),i=new ve({checkboxField:new pt({text:t.typeText,checked:!0}),subtitleLangKey:"Loading",listenerSetter:this.listenerSetter,withCheckboxSubtitle:!0}),n=new ve({checkboxField:new pt({text:"MessagePreview",checked:!0}),subtitleLangKey:"Loading",listenerSetter:this.listenerSetter,withCheckboxSubtitle:!0});s.content.append(i.container,n.container),this.scrollable.append(s.container);const a={_:t.inputKey},r=this.managers.appNotificationsManager.getNotifySettings(a);(r instanceof Promise?r:Promise.resolve(r)).then(l=>{const c=async()=>{const d=await this.managers.appNotificationsManager.isMuted(l);return i.checkboxField.checked=!d,n.checkboxField.checked=l.show_previews,d};c(),this.eventListener.addEventListener("destroy",async()=>{const d=!i.checkboxField.checked,h=n.checkboxField.checked;if(d===await this.managers.appNotificationsManager.isMuted(l)&&h===l.show_previews)return;const u=Wi(l);u._="inputPeerNotifySettings",u.mute_until=d?Cb:0,u.show_previews=h,this.managers.appNotificationsManager.updateNotifySettings(a,u)},{once:!0}),this.listenerSetter.add(I)("notify_settings",d=>{const h=pI(d.peer._);t.inputKey===h&&(l=d.notify_settings,c())})})};e({name:"NotificationsPrivateChats",typeText:"NotificationsForPrivateChats",inputKey:"inputNotifyUsers"}),e({name:"NotificationsGroups",typeText:"NotificationsForGroups",inputKey:"inputNotifyChats"}),e({name:"NotificationsChannels",typeText:"NotificationsForChannels",inputKey:"inputNotifyBroadcasts"});{const t=new Pe({name:"NotificationsOther"}),s=new ve({checkboxField:new pt({text:"ContactJoined",checked:!0}),subtitleLangKey:"Loading",listenerSetter:this.listenerSetter,withCheckboxSubtitle:!0}),i=new ve({checkboxField:new pt({text:"Notifications.Sound",checked:!0,stateKey:Gs("settings","notifications","sound"),listenerSetter:this.listenerSetter}),subtitleLangKey:"Loading",listenerSetter:this.listenerSetter,withCheckboxSubtitle:!0});fe.getState().then(n=>{i.checkboxField.checked=n.settings.notifications.sound}),t.content.append(s.container,i.container),this.scrollable.append(t.container),this.managers.appNotificationsManager.getContactSignUpNotification().then(n=>{s.checkboxField.checked=n,this.eventListener.addEventListener("destroy",()=>{const a=s.checkboxField.checked;n!==a&&this.managers.appNotificationsManager.setContactSignUpNotification(!a)},{once:!0})})}}}function Zv(o){const[e,t]=o.signal??ne(o.checked),s=new pt({toggle:o.toggle});let i=!0;return ye(()=>{s.setValueSilently(e()),!i&&o.onChange&&Et(()=>o.onChange(e())),i=!1}),sn(s.input)("change",()=>{t(s.input.checked)}),s.label}class Jv extends Dt{static getInitArgs(){return{languages1:I.managers.apiManager.invokeApiCacheable("langpack.getLanguages",{lang_pack:"web"}),languages2:Promise.resolve([])}}init(e){this.header.classList.add("with-border"),this.container.classList.add("language-container"),this.setTitle("Telegram.LanguageViewController");const t=Jt(a=>{this.middlewareHelper.get().onDestroy(a);const[r,l]=El(),c=Du(),d=K(()=>{const u=r.translations.doNotTranslate;return u.length?u:[ke.langCodeNormalized()]});let h;return j(gs,{ref(u){const p=h;typeof p=="function"?p(u):h=u},name:"TranslateMessages",get caption(){return c()?"Translation.DoNotShow":"Language.TranslateMessages.Channel.Premium"},get captionArgs(){return[ni(()=>{Vt.show({feature:"translations"})})]},get children(){return[j(Ra,{get title(){return M("ShowTranslateButton")},get checkboxFieldToggle(){return j(Zv,{get checked(){return r.translations.showInMenu},toggle:!0,onChange:u=>{l("translations","showInMenu",u)}})}}),j(Ra,{get title(){return M("ShowTranslateChatButton")},get checkboxFieldToggle(){return j(Zv,{get checked(){return r.translations.enabled},toggle:!0,onChange:u=>{l("translations","enabled",u)}})},get fakeDisabled(){return!c()},clickable:u=>{c()||(u.preventDefault(),Vt.show({feature:"translations"}))}}),K(()=>K(()=>!!r.translations.enabled)()&&j(Ra,{get title(){return M("DoNotTranslate")},get titleRight(){return K(()=>d().length<3)()?pi(d().map(u=>M(`Language.${u}`)),!1):M("Languages",[d().length])},titleRightSecondary:!0,clickable:async()=>{const u=await Tf(!0,d());l("translations","doNotTranslate",u)}}))]}}),h}),s=new Pe({}),i=new Map,n=Promise.all([e.languages1,e.languages2]).then(([a,r])=>{const l=new Set,c=a.map(u=>u.lang_code),d=Pd();a.concat(r).forEach(u=>{if(l.has(u.lang_code))return;l.add(u.lang_code);const p=new ve({radioField:new _i({text:u.name,name:d,value:u.lang_code}),subtitle:u.native_name});i.set(u.lang_code,p)});const h=xl([...i.values()],u=>{ke.getLangPack(u,c.includes(u))});ke.getCacheLangPack().then(u=>{const p=i.get(u.lang_code);if(!p){console.error("no row",p,u);return}p.radioField.setValueSilently(!0)}),s.content.append(h)});return this.scrollable.append(t,s.container),n}}function Gf(o,e,t){const s=new Pe({name:e}),i=Gs("settings","autoDownload",o),n=new pt({text:"AutodownloadContacts",name:"contacts",stateKey:Gs(i,"contacts"),listenerSetter:t}),a=new pt({text:"AutodownloadPrivateChats",name:"private",stateKey:Gs(i,"private"),listenerSetter:t}),r=new pt({text:"AutodownloadGroupChats",name:"groups",stateKey:Gs(i,"groups"),listenerSetter:t}),l=new pt({text:"AutodownloadChannels",name:"channels",stateKey:Gs(i,"channels"),listenerSetter:t});return s.content.append(rr(n).container,rr(a).container,rr(r).container,rr(l).container),s}class H2 extends Xt{init(){this.setTitle("AutoDownloadPhotos");const e=Gf("photo","AutoDownloadPhotosTitle",this.listenerSetter);this.scrollable.append(e.container)}}class $2 extends Xt{init(){this.setTitle("AutoDownloadFiles");const e=ii(d=>{this.managers.appStateManager.setByKey(Gs("settings","autoDownloadNew","file_size_max"),d)},200,!1,!0),t=Gf("file","AutoDownloadFilesTitle",this.listenerSetter),s=512*1024,n=20*1024*1024-s,a=I.settings.autoDownloadNew.file_size_max,r=Math.sqrt(Math.sqrt((a-s)/n)),l=new ke.IntlElement({key:"AutodownloadSizeLimitUpTo",args:[Ta(a)]}),c=new gI("AutoDownloadMaxFileSize",.01,r,0,1,!1);c.onChange=d=>{const h=d**4*n+s|0;l.compareAndUpdate({args:[Ta(h)]}),e(h)},c.valueContainer.append(l.element),t.content.append(c.container),this.scrollable.append(t.container)}}class V2 extends Xt{init(){this.setTitle("AutoDownloadVideos");const e=Gf("video","AutoDownloadVideosTitle",this.listenerSetter);this.scrollable.append(e.container)}}const G2={contacts:"AutoDownloadContacts",private:"AutoDownloadPm",groups:"AutoDownloadGroups",channels:"AutoDownloadChannels"};class z2 extends Xt{init(){this.setTitle("DataSettings");{const e=new Pe({name:"AutomaticMediaDownload",caption:"AutoDownloadAudioInfo"}),t=new pt({text:"AutoDownloadMedia",name:"auto",checked:!I.settings.autoDownloadNew.pFlags.disabled,listenerSetter:this.listenerSetter}),s=new ve({checkboxField:t,listenerSetter:this.listenerSetter}),i=()=>{jt([d],Di(I.settings.autoDownload,Gr.settings.autoDownload)&&Di(I.settings.autoDownloadNew,Gr.settings.autoDownloadNew))},n=()=>{this.setAutoDownloadSubtitle(r,I.settings.autoDownload.photo),this.setAutoDownloadSubtitle(l,I.settings.autoDownload.video),this.setAutoDownloadSubtitle(c,I.settings.autoDownload.file,I.settings.autoDownloadNew.file_size_max)},a=u=>{const p=this.slider.createTab(u);p.open(),this.listenerSetter.add(p.eventListener)("destroy",()=>{n(),i()},{once:!0})},r=new ve({titleLangKey:"AutoDownloadPhotos",subtitle:"",clickable:()=>{a(H2)},listenerSetter:this.listenerSetter}),l=new ve({titleLangKey:"AutoDownloadVideos",subtitle:"",clickable:()=>{a(V2)},listenerSetter:this.listenerSetter}),c=new ve({titleLangKey:"AutoDownloadFiles",subtitle:"",clickable:()=>{a($2)},listenerSetter:this.listenerSetter}),d=ze("btn-primary btn-transparent primary",{icon:"delete",text:"ResetAutomaticMediaDownload"});N(d,()=>{Ct({titleLangKey:"ResetAutomaticMediaDownloadAlertTitle",descriptionLangKey:"ResetAutomaticMediaDownloadAlert",button:{langKey:"Reset"}}).then(()=>{const u=I.settings;u.autoDownloadNew=Wi(Gr.settings.autoDownloadNew),u.autoDownload=Wi(Gr.settings.autoDownload),I.settings=u,this.managers.appStateManager.setByKey("settings",u),n(),t.checked=!I.settings.autoDownloadNew.pFlags.disabled})});const h=()=>{const u=!t.checked,p=I.settings.autoDownloadNew;u?p.pFlags.disabled=!0:delete p.pFlags.disabled,[r,l,c].forEach(m=>{m.container.classList.toggle("is-disabled",u)}),this.managers.appStateManager.setByKey(Gs("settings","autoDownloadNew"),p),i()};t.input.addEventListener("change",h),h(),n(),e.content.append(s.container,r.container,l.container,c.container,d),this.scrollable.append(e.container)}}setAutoDownloadSubtitle(e,t,s){let i;const n=[],a=Object.keys(t),r=a.map(l=>t[l]?G2[l]:void 0).filter(Boolean);if(!r.length||s===0)i="AutoDownloadOff";else{const l=r.length===a.length;if(s!==void 0?(i=l?"AutoDownloadUpToOnAllChats":"AutoDownloadOnUpToFor",n.push(Ta(s))):i=l?"AutoDownloadOnAllChats":"AutoDownloadOnFor",!l){const c=document.createElement("span");c.append(...pi(r.map(d=>M(d)),!0,!1)),n.push(c)}}dt(e.subtitle,M(i,n))}}class K2 extends Dt{init(){return this.setTitle("DoubleTapSetting"),this.container.classList.add("quick-reaction-container"),Promise.all([this.managers.appReactionsManager.getQuickReaction(),this.managers.appReactionsManager.getAvailableReactions()]).then(([e,t])=>{t=t.filter(r=>!r.pFlags.inactive);const s=new Pe,i="quick-reaction",n=t.map(r=>{const l=new _i({name:i,text:r.title,value:r.reaction,alignRight:!0}),c=new ve({radioField:l,havePadding:!0});return l.main.classList.add("quick-reaction-title"),rf({row:c,doc:r.static_icon,size:"small"}),r.reaction===e.reaction&&l.setValueSilently(!0),c}),a=xl(n,r=>{this.managers.appReactionsManager.setDefaultReaction({_:"reactionEmoji",emoticon:r})});s.content.append(a),this.scrollable.append(s.container)})}}class zf extends Dt{static getInitArgs(){return{allStickers:I.managers.appStickersManager.getAllStickers(),quickReaction:I.managers.appReactionsManager.getQuickReaction()}}init(e){this.container.classList.add("stickers-emoji-container"),this.setTitle("StickersName");const t=[];{const s=new Pe({caption:"LoopAnimatedStickersInfo"}),i=new ve({icon:"lamp",titleLangKey:"Stickers.SuggestStickers",clickable:!0,listenerSetter:this.listenerSetter,titleRightSecondary:!0}),n={all:"SuggestStickersAll",installed:"SuggestStickersInstalled",none:"SuggestStickersNone"},a=()=>{i.titleRight.replaceChildren(M(n[I.settings.stickers.suggest]))};a();const r=h=>{if(I.settings.stickers.suggest!==h)return I.settings.stickers.suggest=h,a(),this.managers.appStateManager.setByKey(Gs("settings","stickers","suggest"),h)};ln({buttons:[{icon:"stickers_face",text:"SuggestStickersAll",onClick:r.bind(this,"all")},{icon:"newprivate",text:"SuggestStickersInstalled",onClick:r.bind(this,"installed")},{icon:"stop",text:"SuggestStickersNone",onClick:r.bind(this,"none")}],listenTo:i.container,middleware:this.middlewareHelper.get(),listenForClick:!0});const l=new ve({titleLangKey:"DoubleTapSetting",havePadding:!0,clickable:()=>{this.slider.createTab(K2).open()},listenerSetter:this.listenerSetter}),c=()=>{e.quickReaction.then(h=>h._==="availableReaction"?h.static_icon:this.managers.appEmojiManager.getCustomEmojiDocument(h.document_id)).then(h=>{rf({row:l,doc:h,size:"small"})})};c(),this.listenerSetter.add(I)("quick_reaction",()=>{e=zf.getInitArgs(),c()});const d=new ve({icon:"flip",titleLangKey:"InstalledStickers.LoopAnimated",checkboxField:new pt({name:"loop",stateKey:Gs("settings","stickers","loop"),listenerSetter:this.listenerSetter,toggle:!0}),listenerSetter:this.listenerSetter});s.content.append(l.container,i.container,d.container),this.scrollable.append(s.container)}{const s=new Pe({name:"Emoji"}),i=new ve({icon:"lamp",titleLangKey:"GeneralSettings.EmojiPrediction",checkboxField:new pt({name:"suggest-emoji",stateKey:Gs("settings","emoji","suggest"),listenerSetter:this.listenerSetter,toggle:!0}),listenerSetter:this.listenerSetter}),n=new ve({icon:"smile",titleLangKey:"GeneralSettings.BigEmoji",checkboxField:new pt({name:"emoji-big",stateKey:Gs("settings","emoji","big"),listenerSetter:this.listenerSetter,toggle:!0}),listenerSetter:this.listenerSetter});s.content.append(i.container,n.container),this.scrollable.append(s.container)}{const s=new Pe({name:"DynamicPackOrder",caption:"DynamicPackOrderInfo"}),i=new ve({titleLangKey:"DynamicPackOrder",icon:"replace",checkboxField:new pt({name:"dynamic-pack-order",stateKey:Gs("settings","stickers","dynamicPackOrder"),listenerSetter:this.listenerSetter,toggle:!0}),listenerSetter:this.listenerSetter});s.content.append(i.container),this.scrollable.append(s.container)}{const s=new Pe({name:"Telegram.InstalledStickerPacksController",caption:"StickersBotInfo"}),i={},n=s.generateContentElement(),a=new Ga,r=(c,d="append")=>{const h=new ve({title:_e(c.title),subtitleLangKey:"Stickers",subtitleLangArgs:[c.count],havePadding:!0,clickable:()=>{ee.createPopup(Cn,{id:c.id,access_hash:c.access_hash}).show()},listenerSetter:this.listenerSetter});h.container.dataset.id=""+c.id,h.makeSortable(),i[c.id]=h;const u=document.createElement("div");u.classList.add("row-media"),aS({set:c,container:u,group:"GENERAL-SETTINGS",lazyLoadQueue:a,width:36,height:36,autoplay:!0,middleware:this.middlewareHelper.get()}),h.container.append(u),n[d](h.container)},l=e.allStickers.then(c=>{const d=c.sets.map(h=>r(h));return Promise.all(d)});t.push(l),this.listenerSetter.add(I)("stickers_installed",c=>{i[c.id]||r(c,"prepend")}),this.listenerSetter.add(I)("stickers_deleted",c=>{i[c.id]&&(i[c.id].container.remove(),delete i[c.id])}),this.listenerSetter.add(I)("stickers_order",({type:c,order:d})=>{c==="stickers"&&d.forEach((h,u)=>{const p=i[h];p&&Ps(p.container,n,u)})}),this.listenerSetter.add(I)("stickers_top",c=>{const d=i[c];d&&Ps(d.container,n,0)}),new ef({list:n,middleware:this.middlewareHelper.get(),onSort:(c,d)=>{const h=Array.from(n.children).map(u=>u.dataset.id);this.managers.appStickersManager.reorderStickerSets(h)}}),this.scrollable.append(s.container)}return Promise.all(t)}}class Kf extends Dt{constructor(){super(...arguments),this.buttons={}}async init(){this.container.classList.add("settings-container"),this.setTitle("Settings");const e=ai({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[{icon:"logout",text:"EditAccount.Logout",onClick:()=>{ee.createPopup(Ss,"logout",{titleLangKey:"LogOut",descriptionLangKey:"LogOut.Description",buttons:[{langKey:"LogOut",callback:()=>{this.managers.apiManager.logOut()},isDanger:!0}]}).show()}}]});this.buttons.edit=it("edit"),this.header.append(this.buttons.edit,e),this.profile=new rI(this.managers,this.scrollable,this.listenerSetter,!1,this.container,y=>{let v=this.profile.element.lastElementChild;y&&(v=v.previousElementSibling),v.firstElementChild.append(s)}),this.profile.init(),this.profile.setPeer(I.myId);const t=this.profile.fillProfileElements(),s=Ei({icon:"cameraadd",className:"profile-change-avatar"});N(s,()=>{const y=document.createElement("canvas");ee.createPopup(yb).open(y,v=>{v().then(w=>this.managers.appProfileManager.uploadProfilePhoto(w))})},{listenerSetter:this.listenerSetter}),this.profile.element.lastElementChild.firstElementChild.append(s);const i=async()=>{const y=await this.managers.appUsersManager.getSelf();s.classList.toggle("hide",y.photo?._!=="userProfilePhoto")};i(),this.listenerSetter.add(I)("avatar_update",({peerId:y})=>{I.myId===y&&i()});const n=document.createElement("div");n.classList.add("profile-buttons");const a=(y,v,w,b)=>{if(!b){const S=w.getInitArgs;S&&(b=()=>[S(this)])}return{icon:y,text:v,tabConstructor:w,getInitArgs:b,args:b?.()}},l=[a("unmute","AccountSettings.Notifications",U2),a("data","DataSettings",z2),a("lock","AccountSettings.PrivacyAndSecurity",F2),a("settings","Telegram.GeneralSettingsViewController",N2),a("folder","AccountSettings.Filters",bp),a("stickers_face","StickersName",zf)].map(y=>{const{icon:v,text:w,tabConstructor:b,getInitArgs:S}=y;return new ve({titleLangKey:w,icon:v,clickable:async()=>{const C=y.args?await y.args:[],P=this.slider.createTab(b);P.open(...C),P instanceof Xt&&S&&P.eventListener.addEventListener("destroyAfter",L=>{y.args=L.then(()=>S())})},listenerSetter:this.listenerSetter})}),c=Jv.getInitArgs();l.push(this.devicesRow=new ve({titleLangKey:"Devices",titleRightSecondary:" ",icon:"activesessions",clickable:async()=>{this.authorizations||await this.updateActiveSessions();const y=this.slider.createTab(uI);y.authorizations=this.authorizations,y.eventListener.addEventListener("destroy",()=>{this.authorizations=void 0,this.updateActiveSessions(!0)},{once:!0}),y.open()},listenerSetter:this.listenerSetter}),this.languageRow=new ve({titleLangKey:"AccountSettings.Language",titleRightSecondary:M("LanguageName"),icon:"language",clickable:()=>{this.slider.createTab(Jv).open(c)},listenerSetter:this.listenerSetter})),n.append(...l.map(y=>y.container)),this.premiumRow=new ve({titleLangKey:"ActionGiftPremiumTitle",icon:"star",iconClasses:["row-icon-premium-color"],clickable:()=>{Vt.show()},listenerSetter:this.listenerSetter});const d=new ve({titleLangKey:"MenuTelegramStars",titleRightSecondary:!0,icon:"star",iconClasses:["row-icon-stars-color"],clickable:()=>{ee.createPopup(yu)},listenerSetter:this.listenerSetter});Jt(y=>{this.middlewareHelper.onDestroy(y);const v=fp();ye(()=>{d.titleRight.textContent=""+v(),d.container.classList.toggle("hide",!v())})});const h=new ve({titleLangKey:"GiftPremiumGifting",icon:"gift",clickable:()=>{me.initGifting()},listenerSetter:this.listenerSetter}),u=M("New");u.classList.add("row-title-badge"),h.title.append(u);const p=new Pe;p.content.append(n);let m;await fe.isPremiumPurchaseBlocked()||(m=new Pe,m.content.append(this.premiumRow.container,d.container,h.container)),this.scrollable.append(...[this.profile.element,p.container,m?.container].filter(Boolean));const g=()=>{f=jh.getInitArgs()};let f;N(this.buttons.edit,()=>{this.slider.createTab(jh).open(f)},{listenerSetter:this.listenerSetter}),g(),this.listenerSetter.add(I)("user_update",y=>{I.myId.toUserId()===y&&g()}),_s.loadLottieWorkers(),this.updateActiveSessions(),(await t)()}getAuthorizations(e){if(this.getAuthorizationsPromise&&!e)return this.getAuthorizationsPromise;const t=this.getAuthorizationsPromise=this.managers.apiManager.invokeApi("account.getAuthorizations").finally(()=>{this.getAuthorizationsPromise===t&&(this.getAuthorizationsPromise=void 0)});return t}updateActiveSessions(e){return this.getAuthorizations(e).then(t=>{this.authorizations=t.authorizations,this.devicesRow.titleRight.textContent=""+this.authorizations.length})}onCloseAfterTimeout(){return this.profile.destroy(),super.onCloseAfterTimeout()}}class W2 extends Dt{constructor(){super(...arguments),this.uploadAvatar=null}init(){this.container.classList.add("new-channel-container"),this.setTitle("NewChannel"),this.avatarEdit=new Yg(i=>{this.uploadAvatar=i});const e=new Pe({caption:"Channel.DescriptionHolderDescrpiton"}),t=document.createElement("div");t.classList.add("input-wrapper"),this.channelNameInputField=new _t({label:"EnterChannelName",maxLength:128}),this.channelDescriptionInputField=new _t({label:"DescriptionOptionalPlaceholder",maxLength:255,withLinebreaks:!0}),t.append(this.channelNameInputField.container,this.channelDescriptionInputField.container);const s=()=>{this.nextBtn.classList.toggle("is-visible",!!this.channelNameInputField.value.length&&!this.channelNameInputField.input.classList.contains("error")&&!this.channelDescriptionInputField.input.classList.contains("error"))};this.channelNameInputField.input.addEventListener("input",s),this.channelDescriptionInputField.input.addEventListener("input",s),this.nextBtn=Ei({icon:"arrow_next"}),N(this.nextBtn,()=>{const i=this.channelNameInputField.value,n=this.channelDescriptionInputField.value;this.nextBtn.disabled=!0,this.managers.appChatsManager.createChannel({title:i,about:n,broadcast:!0}).then(a=>{this.uploadAvatar&&this.uploadAvatar().then(r=>{this.managers.appChatsManager.editPhoto(a,r)}),me.setInnerPeer({peerId:a.toPeerId(!0)}),Ii.removeTabFromHistory(this),this.slider.createTab(Yu).open({type:"channel",skippable:!0,title:"GroupAddMembers",placeholder:"SendMessageTo",takeOut:r=>this.managers.appChatsManager.inviteToChannel(a,r)})})},{listenerSetter:this.listenerSetter}),this.content.append(this.nextBtn),e.content.append(this.avatarEdit.container,t),this.scrollable.append(e.container)}onCloseAfterTimeout(){return this.avatarEdit.clear(),this.uploadAvatar=null,this.channelNameInputField.value="",this.channelDescriptionInputField.value="",this.nextBtn.disabled=!1,super.onCloseAfterTimeout()}}class j2 extends ee{constructor(){super("popup-create-contact popup-send-photo popup-new-media",{closable:!0,withConfirm:"Add",title:"AddContactTitle"}),this.construct()}async construct(){N(this.btnConfirm,()=>{const d=this.managers.appUsersManager.importContact(s.value,i.value,n.value);d.then(()=>{this.hide()},h=>{h.type==="NO_USER"&&(Ee({langPackKey:"Contacts.PhoneNumber.NotRegistred"}),c.disabled=!1)}),c.lockWithPromise(d)},{listenerSetter:this.listenerSetter});const e=[],t=document.createElement("div");t.classList.add("name-fields");const s=new _t({label:"FirstName",name:"create-contact-name",maxLength:70,required:!0});s.container.classList.add("input-field-name");const i=new _t({label:"LastName",name:"create-contact-lastname",maxLength:70}),n=new Wb({required:!0});e.push(s,i,n);const a=()=>{const d=s.value+" "+i.value;c.avatarElem.render({peerTitle:d})};this.listenerSetter.add(s.input)("input",a),this.listenerSetter.add(i.input)("input",a),n.validate=()=>!!n.value.match(/\d/);const r=await this.managers.appUsersManager.getSelf(),l=_l(r.phone);l.code&&(n.value="+"+l.code.country_code);const c=new kd({inputFields:e,listenerSetter:this.listenerSetter,doNotEditAvatar:!0,nextBtn:this.btnConfirm,avatarSize:100,middleware:this.middlewareHelper.get()});t.append(s.container,i.container,c.avatarElem.node),this.container.append(t,n.container),this.show()}}class q2 extends Dt{init(){this.container.id="contacts-container";const e=Ei({icon:"add",className:"is-visible"});this.content.append(e),N(e,()=>{ee.createPopup(j2)},{listenerSetter:this.listenerSetter}),this.inputSearch=new wo({placeholder:"Search",onChange:s=>{this.openContacts(s)}}),this.listenerSetter.add(I)("contacts_update",async s=>{const i=await this.managers.appUsersManager.isContact(s),n=s.toPeerId();i?this.sortedUserList.add(n):this.sortedUserList.delete(n)}),this.title.replaceWith(this.inputSearch.container),this.middlewareHelperLoad=xt();const t=this.listsContainer=document.createElement("div");this.scrollable.append(t),this.openContacts()}createList(){const e=new $c({managers:this.managers,middleware:this.middlewareHelper.get()}),t=e.list;return t.id="contacts",t.classList.add("contacts-container"),Xe.setListClickListener({list:t,onFound:()=>{this.close()},withContext:void 0,autonomous:!0}),e}onClose(){this.middlewareHelperLoad.clean()}onOpenAfterTimeout(){Oi||!vp(!0)||this.inputSearch.input.focus()}openContacts(e){this.middlewareHelperLoad.clean();const t=this.middlewareHelperLoad.get();this.scrollable.onScrolledBottom=null,this.listsContainer.replaceChildren(),this.managers.appUsersManager.getContactsPeerIds(e,void 0,"online").then(s=>{if(!t())return;const i=this.sortedUserList=this.createList();let n=()=>{const a=lt.height/56*1.25|0;s.splice(0,a).forEach(l=>{i.add(l)}),s.length||(n=void 0,this.scrollable.onScrolledBottom=null)};n(),this.scrollable.onScrolledBottom=()=>{n?n():this.scrollable.onScrolledBottom=null},dt(this.listsContainer,i.list)})}}const La=class La extends Dt{init(){if(this.wasFilterId=Xe.filterId,this.container.id="chats-archived-container",this.setTitle("ArchivedChats"),this.header.classList.add("can-have-forum"),this.content.classList.add("can-have-forum"),!Xe.xds[La.filterId]){const{ul:s,scrollable:i}=Xe.l({title:void 0,id:La.filterId,localId:Vi});i.append(s)}const e=this.storiesListContainer=document.createElement("div");e.classList.add("stories-list"),this.header.after(e);const t=Xe.xds[La.filterId].scrollable;return this.scrollable.container.replaceWith(t.container),t.attachBorderListeners(this.container),Xe.setFilterIdAndChangeTab(La.filterId).then(({cached:s,renderPromise:i})=>{if(s)return i})}renderStories(){this.disposeStories=Hi(()=>YC({foldInto:this.header,setScrolledOn:this.container,getScrollable:()=>Xe.xds[La.filterId].scrollable.container,listenWheelOn:this.content,archive:!0,offsetX:-84}),this.storiesListContainer)}onOpenAfterTimeout(){this.renderStories(),Xe.xds[this.wasFilterId].clear()}onClose(){this.scrollable.onAdditionalScroll=void 0,Xe.setFilterIdAndChangeTab(this.wasFilterId)}onCloseAfterTimeout(){return this.disposeStories?.(),this.disposeStories=void 0,Xe.xds[La.filterId].clear(),super.onCloseAfterTimeout()}};La.filterId=Vi;let mg=La;class Q2 extends Dt{constructor(){super(...arguments),this.isLocationWatched=!1}parseDistance(e){return I.settings.distanceUnit==="miles"?e>1609.34?M("MilesAway",[Math.round(e/1609)]):M("FootsAway",[Math.round(e*3.281)]):e>=1e3?M("KMetersAway2",[e/1e3]):M("MetersAway2",[e])}startWatching(){!this.latestLocationSaved||this.isLocationWatched||(this.isLocationWatched=!0,zs("Your position is now being shared. Do not close the page or it will be suspended."),this.managers.appUsersManager.getLocated(this.latestLocationSaved.latitude,this.latestLocationSaved.longitude,this.latestLocationSaved.accuracy,!0,2147483647),navigator.geolocation.watchPosition(e=>{const t=e.coords.longitude!==this.latestLocationSaved.longitude,s=e.coords.latitude!==this.latestLocationSaved.latitude,i=this.calculateDistance(e.coords.latitude,e.coords.longitude,this.latestLocationSaved.latitude,this.latestLocationSaved.longitude)>100;(s||t)&&i&&(this.managers.appUsersManager.getLocated(e.coords.latitude,e.coords.longitude,e.coords.accuracy,!0,2147483647),this.latestLocationSaved={latitude:e.coords.latitude,longitude:e.coords.longitude,accuracy:e.coords.accuracy})}))}stopWatching(){this.isLocationWatched&&(this.isLocationWatched=!1,zs("The sharing of your position has been stopped. You will no longer be visible to other users."),this.managers.appUsersManager.getLocated(0,0,0,!1,0))}calculateDistance(e,t,s,i){const n=.017453292519943295;return 12742*Math.asin(Math.sqrt(.5-Math.cos((s-e)*n)+Math.cos(e*n)*Math.cos(s*n)*(1-Math.cos((i-t)*n)/2)))}}const Pc="is-left-column-shown";class Y2 extends Mw{constructor(){super({sidebarEl:document.getElementById("column-left"),navigationType:"left"}),this.searchGroups={}}construct(e){this.managers=e,this.inputSearch=new wo,this.inputSearch.input.placeholder=" ";const t=this.sidebarEl.querySelector(".item-main .sidebar-header");t.append(this.inputSearch.container);const s=()=>{this.createTab(Yu).open({type:"chat",skippable:!0,takeOut:w=>this.createTab(Ew).open({peerIds:w}),title:"GroupAddMembers",placeholder:"SendMessageTo"})},i=()=>{this.createTab(q2).open()};this.backBtn=this.sidebarEl.querySelector(".sidebar-back-button");const n={icon:"archive",text:"ArchivedChats",onClick:()=>{this.createTab(mg).open()},verify:async()=>{const w=await this.managers.dialogsStorage.getFolderDialogs(Vi,!1),b=await this.managers.appStoriesManager.hasArchive();return!!w.length||b||!await this.managers.dialogsStorage.isDialogsLoaded(Vi)}},a=new pt({toggle:!0,checked:as.getTheme().name==="night"});a.input.addEventListener("change",()=>{const S=U(a.label,"btn-menu-item").querySelector(".tgico").getBoundingClientRect();as.switchTheme(a.checked?"night":"day",{x:S.left+S.width/2,y:S.top+S.height/2})}),I.addEventListener("theme_changed",()=>{a.setValueSilently(as.getTheme().name==="night")});const l=[{icon:"savedmessages",text:"SavedMessages",onClick:()=>{setTimeout(()=>{me.setPeer({peerId:me.myId})},0)}},n,{icon:"stories",text:"MyStories.Title",onClick:()=>{this.createTab(Sl).open()},verify:()=>!RL},{icon:"user",text:"Contacts",onClick:i},Fb?{icon:"group",text:"PeopleNearby",onClick:()=>{this.createTab(Q2).open()}}:void 0,{icon:"settings",text:"Settings",onClick:()=>{this.createTab(Kf).open()}},{icon:"darkmode",text:"DarkMode",onClick:()=>{},checkboxField:a},{icon:"animations",text:"Animations",onClick:()=>{},checkboxField:new pt({toggle:!0,checked:st.isAvailable("animations"),stateKey:Gs("settings","liteMode","animations"),stateValueReverse:!0}),verify:()=>!st.isEnabled()},{icon:"animations",text:"LiteMode.Title",onClick:()=>{this.createTab(mI).open()},verify:()=>st.isEnabled()},{icon:"help",text:"TelegramFeatures",onClick:()=>{const w=ke.format("TelegramFeaturesUrl",!0);me.openUrl(w)}},{icon:"bug",text:"ReportBug",onClick:()=>{const w=document.createElement("a");Jr(w),w.href="https://bugs.telegram.org/?tag_ids=40&sort=time",document.body.append(w),w.click(),setTimeout(()=>{w.remove()},0)}},{icon:"char",className:"a",text:"ChatList.Menu.SwitchTo.A",onClick:()=>{Promise.all([mm.set({kz_version:"Z"}),mm.delete("tgme_sync")]).then(()=>{location.href="https://web.telegram.org/a/"})},verify:()=>rc.isMainDomain},{icon:"plusround",text:"PWA.Install",onClick:()=>{py()?.()},verify:()=>!!py()}].filter(Boolean),c=l.slice();this.toolsBtn=ai({direction:"bottom-right",buttons:l,onOpenBefore:async()=>{const w=await this.managers.appAttachMenuBotsManager.getAttachMenuBots(),b=c.slice(),S=w.filter(C=>C.pFlags.show_in_side_menu).map(C=>{const P=Df(C);return{regularText:_e(C.short_name),onClick:()=>{me.openWebApp({attachMenuBot:C,botId:C.bot_id,isSimpleWebView:!0,fromSideMenu:!0})},iconDoc:P?.icon,new:C.pFlags.side_menu_disclaimer_needed||C.pFlags.inactive}});b.splice(3,0,...S),l.splice(0,l.length,...b)},onOpen:(w,b)=>{const S=document.createElement("a");S.href="https://github.com/morethanwords/tweb/blob/master/CHANGELOG.md",Jr(S),S.classList.add("btn-menu-footer"),S.addEventListener(Go,L=>{L.stopPropagation(),Js.close()});const C=document.createElement("span");C.classList.add("btn-menu-footer-text"),C.textContent="Telegram Web"+rc.suffix+" "+rc.versionFull,S.append(C),b.classList.add("has-footer"),b.append(S);const P=b.querySelector(".a .btn-menu-item-icon");P&&(P.textContent="A"),n.element?.append(this.archivedCount)},noIcon:!0}),this.toolsBtn.classList.add("sidebar-tools-button","is-visible"),this.backBtn.parentElement.insertBefore(this.toolsBtn,this.backBtn),this.newBtnMenu=ai({direction:"top-left",buttons:[{icon:"newchannel",text:"NewChannel",onClick:()=>{this.createTab(W2).open()}},{icon:"newgroup",text:"NewGroup",onClick:s},{icon:"newprivate",text:"NewPrivateChat",onClick:i}],noIcon:!0}),this.newBtnMenu.className="btn-circle rp btn-corner z-depth-1 btn-menu-toggle animated-button-icon",this.newBtnMenu.tabIndex=-1;const d=["newchat_filled","close"];this.newBtnMenu.prepend(...d.map((w,b)=>Le(w,"animated-button-icon-icon","animated-button-icon-icon-"+(b===0?"first":"last")))),this.newBtnMenu.id="new-menu",t.nextElementSibling.append(this.newBtnMenu),this.updateBtn=document.createElement("div"),this.updateBtn.className="btn-circle rp btn-corner z-depth-1 btn-update is-hidden",this.updateBtn.tabIndex=-1,Ni(this.updateBtn),this.updateBtn.append(M("Update")),N(this.updateBtn,()=>{this.updateBtn.classList.contains("is-hidden")||location.reload()}),t.nextElementSibling.append(this.updateBtn),this.inputSearch.input.addEventListener("focus",()=>this.initSearch(),{once:!0}),this.archivedCount=bl("span",24,"gray"),this.archivedCount.classList.add("archived-count"),I.addEventListener("folder_unread",w=>{if(w.id===Vi){const b=w.unreadPeerIds.size;Qo(this.archivedCount,b?""+on(b,1):"")}});let h,u;const p=this.getMiddleware().create(),m=it(" sidebar-emoji-status",{noRipple:!0});N(m,()=>{const w=new Un({noRegularEmoji:!0,managers:I.managers,mainSets:()=>{const C=this.managers.appStickersManager.getLocalStickerSet("inputStickerSetEmojiDefaultStatuses").then(L=>L.documents.map(E=>E.id)),P=L=>L.statuses.map(E=>E.document_id).filter(Boolean);return[Promise.all([C,this.managers.appUsersManager.getRecentEmojiStatuses().then(P),this.managers.appUsersManager.getDefaultEmojiStatuses().then(P),this.managers.appEmojiManager.getRecentEmojis("custom")]).then(L=>$a(Ln(L)))]},onClick:async C=>{b.hideAndDestroy();const P=bb("star")===C.emoji;let L;P?L={_:"emojiStatusEmpty"}:(L={_:"emojiStatus",document_id:C.docId},u=!0),this.managers.appUsersManager.updateEmojiStatus(L)},canHaveEmojiTimer:!0}),b=new no({tabsToRender:[w],customParentElement:document.body,getOpenPosition:()=>{const C=m.getBoundingClientRect(),P=MC(C);return P.left=C.left+C.width/2,P.top=C.top+C.height/2,P}}),S="primary-color";b.setTextColor(S),b.addEventListener("closed",()=>{b.hideAndDestroy()}),b.onButtonClick(),w.initPromise.then(()=>{const C=Le("star","super-emoji-premium-icon");C.style.color=`var(--${S})`;const P=w.getCustomCategory();w.addEmojiToCategory({category:P,element:C,batch:!1,prepend:!0})})});const g=async w=>{const S=fe.getUser(I.myId.toUserId()).emoji_status;if(!S){m.replaceChildren(),po(m,"star");return}u&&wr.fireAroundAnimation({middleware:h?.get()||this.getMiddleware(),reaction:{_:"reactionCustomEmoji",document_id:S.document_id},sizes:{genericEffect:26,genericEffectSize:100,size:40,effectSize:80},stickerContainer:m,cache:m,textColor:"primary-color"}),u=!1;const C=await qb({wrapOptions:{middleware:w},emojiStatus:S,size:vs(24,24)});C.classList.replace("emoji-status","sidebar-emoji-status-emoji"),m.replaceChildren(C)},f=async w=>{p.clean();const b=p.get();if(w){if(await g((h=b.create()).get()),!b())return;t.append(m);const S=()=>{const C=h;g((h=b.create()).get()).finally(()=>{C.destroy()})};I.addEventListener("emoji_status_change",S),b.onClean(()=>{I.removeEventListener("emoji_status_change",S)})}else m.remove();Xe.resizeStoriesList?.()};me.addEventListener("premium_toggle",f),I.premium&&f(!0),this.managers.appUsersManager.getTopPeers("correspondents");const y={type:"global-search-focus",onPop:()=>(setTimeout(()=>{this.inputSearch.input.focus()},0),!1),noHistory:!0};ft.pushItem(y),fe.getState().then(w=>{if(!w.keepSigned)return;const S=setInterval(()=>{fetch("version",{cache:"no-cache"}).then(C=>C.status===200&&C.ok&&C.text()||Promise.reject()).then(C=>{C!==rc.versionFull&&(this.hasUpdate=!0,clearInterval(S),this.newBtnMenu.classList.contains("is-hidden")||this.updateBtn.classList.remove("is-hidden"))}).catch(Wt)},18e5)});const v=()=>{const w=this.rect=this.tabsContainer.getBoundingClientRect();document.documentElement.style.setProperty("--left-column-width",w.width+"px")};bs(v),$e.addEventListener("resize",v)}initSearch(){const e=this.sidebarEl.querySelector("#search-container"),t=new vi(e),s=()=>{fs(this.backBtn)};this.searchGroups={contacts:new Rr("SearchAllChatsShort","contacts",void 0,void 0,void 0,void 0,s),globalContacts:new Rr("GlobalSearch","contacts",void 0,void 0,void 0,void 0,s),messages:new Rr("SearchMessages","messages"),people:new Rr(!1,"contacts",!0,"search-group-people",!0,!1,s,!0),recent:new Rr("Recent","contacts",!0,"search-group-recent",!0,!0,s)};const i=this.searchSuper=new $f({mediaTabs:[{inputFilter:"inputMessagesFilterEmpty",name:"FilterChats",type:"chats"},{inputFilter:"inputMessagesFilterPhotoVideo",name:"SharedMediaTab2",type:"media"},{inputFilter:"inputMessagesFilterUrl",name:"SharedLinksTab2",type:"links"},{inputFilter:"inputMessagesFilterDocument",name:"SharedFilesTab2",type:"files"},{inputFilter:"inputMessagesFilterMusic",name:"SharedMusicTab2",type:"music"},{inputFilter:"inputMessagesFilterRoundVoice",name:"SharedVoiceTab2",type:"voice"}],scrollable:t,searchGroups:this.searchGroups,asChatList:!0,hideEmptyTabs:!1,showSender:!0,managers:this.managers});e.prepend(i.nav.parentElement.parentElement),t.append(i.container),(()=>{i.setQuery({peerId:"".toPeerId(),folderId:0}),i.selectTab(0),i.load(!0)})();const a=[];let r="".toPeerId(),l=0,c=0;const d=()=>{this.inputSearch.container.classList.toggle("is-picked-twice",a.length===2),this.inputSearch.container.classList.toggle("is-picked",!!a.length),a.forEach((L,E)=>{L.classList.remove("is-first","is-last"),L.classList.add(E===0?"is-first":"is-last")}),a.length?this.inputSearch.input.style.setProperty("--paddingLeft",a[a.length-1].getBoundingClientRect().right-this.inputSearch.input.getBoundingClientRect().left+"px"):this.inputSearch.input.style.removeProperty("--paddingLeft")},h=this.middlewareHelper.get().create(),u=document.createElement("div");u.classList.add("search-helper","hide"),u.addEventListener("click",L=>{const E=U(L.target,"selector-user");if(!E)return;const _=E.dataset.key;if(_.indexOf("date_")===0){const[k,x,A]=_.split("_");l=+x,c=+A}else r=_.toPeerId();E.addEventListener("click",()=>{m(E)}),this.inputSearch.container.append(E),this.inputSearch.onChange(this.inputSearch.value=""),a.push(E),d()}),i.nav.parentElement.append(u);const p=(L,E)=>Mi.renderEntity({key:L,title:E,middleware:h.get(),avatarSize:30,fallbackIcon:"calendarfilter"}).element,m=L=>{L.dataset.key.indexOf("date_")===0?l=c=0:r="".toPeerId(),L.middlewareHelper.destroy(),L.remove(),us(a,L),setTimeout(()=>{d(),this.inputSearch.onChange(this.inputSearch.value)},0)};this.inputSearch.onClear=()=>{a.forEach(L=>{m(L)}),u.replaceChildren(),g()};const g=(L=!u.firstElementChild)=>{u.classList.toggle("hide",L),i.nav.classList.toggle("hide",!L)},f=L=>{u.append(...L),g()};this.inputSearch.onChange=L=>{i.cleanupHTML(),i.setQuery({peerId:r,folderId:r?void 0:0,query:L,minDate:l,maxDate:c}),i.load(!0),h.clean(),g(!0);const E=[];if(!l&&L.trim()){const _=[];DL(L,_);const k=_.map(x=>p("date_"+x.minDate+"_"+x.maxDate,x.title));E.push(k)}if(!r&&L.trim()){const _=i.middleware.get(),k=Promise.all([this.managers.dialogsStorage.getDialogs({query:L}).then(({dialogs:x})=>x.map(A=>A.peerId)),this.managers.appUsersManager.getContactsPeerIds(L,!0)]).then(x=>_()?[...new Set(x[0].concat(x[1]).slice(0,20))].map(T=>p(T)):void 0);E.push(k)}Promise.all(E).then(_=>{u.replaceChildren();const k=Ln(_);f(k)})},i.tabs.inputMessagesFilterEmpty.addEventListener("mousedown",L=>{const E=Bi(L.target,Nl);if(!E)return;const _=U(E,"search-group");if(!_||_.classList.contains("search-group-recent")||_.classList.contains("search-group-people"))return;const k=E.getAttribute("data-peer-id").toPeerId();this.managers.appUsersManager.pushRecentSearch(k)},{capture:!0});const y=document.createElement("div");y.classList.add("search-group-scrollable"),y.append(this.searchGroups.people.list),this.searchGroups.people.container.append(y),new yr(y);let v=!0,w;const b=Na({content:e.parentElement,type:"zoom-fade",transitionTime:150,onTransitionStart:L=>{e.parentElement.parentElement.classList.toggle("is-search-active",L===1)},onTransitionEnd:L=>{w&&clearTimeout(w),L===0&&!v&&(i.selectTab(0,!1),this.inputSearch.onClearClick(),w=window.setTimeout(()=>{w=0,this.newBtnMenu.classList.remove("is-hidden"),this.hasUpdate&&this.updateBtn.classList.remove("is-hidden")},150)),v=!1}});b(0);const S="is-visible",C=()=>{this.toolsBtn.classList.remove(S),this.backBtn.classList.add(S),this.newBtnMenu.classList.add("is-hidden"),this.updateBtn.classList.add("is-hidden"),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!0);const L="global-search";!Ua&&!ft.findItemByType(L)&&ft.pushItem({onPop:()=>{s()},type:L}),b(1)};this.inputSearch.input.addEventListener("focus",C),C(),N(this.backBtn,L=>{this.toolsBtn.classList.add(S),this.backBtn.classList.remove(S),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!1),ft.removeByType("global-search"),b(0)});const P=it("close");this.searchGroups.recent.nameEl.append(P),P.addEventListener("click",()=>{Ct({descriptionLangKey:"Search.Confirm.ClearHistory",button:{langKey:"ClearButton",isDanger:!0}}).then(()=>this.managers.appUsersManager.clearRecentSearch().then(()=>{this.searchGroups.recent.clear()}))})}}const fI=new Y2;Ws.appSidebarLeft=fI;const Ii=fI;class rm{constructor(e,t){this.options=t,this.onDragOver=a=>{this.container.classList.add("is-dragover")},this.onDragLeave=a=>{this.container.classList.remove("is-dragover")},this.onDrop=a=>{this.options.onDrop(a)},this.container=document.createElement("div"),this.container.classList.add("drop","z-depth-1"),this.outlineWrapper=document.createElement("div"),this.outlineWrapper.classList.add("drop-outline-wrapper"),this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.classList.add("drop-outline"),this.path=document.createElementNS("http://www.w3.org/2000/svg","path"),this.path.classList.add("drop-outline-path");let s;t.icon&&(s=document.createElement("div"),s.classList.add("drop-icon"),s.append(Le(t.icon)),this.container.classList.add("has-icon"));const i=document.createElement("div");i.classList.add("drop-header"),i.append(M(t.header,t.headerArgs));let n;t.subtitle&&(n=document.createElement("div"),n.classList.add("drop-subtitle"),n.append(M(t.subtitle))),this.svg.append(this.path),this.outlineWrapper.append(this.svg),this.container.append(...[s,i,n,this.outlineWrapper].filter(Boolean)),e.append(this.container),this.container.addEventListener("dragover",this.onDragOver),this.container.addEventListener("dragleave",this.onDragLeave),this.container.addEventListener("drop",this.onDrop)}destroy(){delete this.options,this.container.remove(),this.container.removeEventListener("dragover",this.onDragOver),this.container.removeEventListener("dragleave",this.onDragLeave),this.container.removeEventListener("drop",this.onDrop)}setPath(){const e=this.outlineWrapper.getBoundingClientRect();this.svg.setAttributeNS(null,"preserveAspectRatio","none"),this.svg.setAttributeNS(null,"viewBox",`0 0 ${e.width} ${e.height}`),this.svg.setAttributeNS(null,"width",`${e.width}`),this.svg.setAttributeNS(null,"height",`${e.height}`);const t=10,s=e.width-t,i=e.height-t,n=t/2,a=$o(n,n,s,i,t,t,t,t);this.path.setAttributeNS(null,"d",a)}}function eb(o){o.forEach(e=>e.classList.add("no-transition")),Qn().then(()=>{o.forEach(e=>e.classList.remove("no-transition"))})}const X2=8.2,Z2=.8;class om{constructor(e){this.maxRadius=10,this.minRadius=0,this.N=e,this.radius=new Array(e+1),this.radiusNext=new Array(e+1),this.progress=new Array(e+1),this.speed=new Array(e+1);for(let t=0;t<=e;t++)this.generateBlob(this.radius,t),this.generateBlob(this.radiusNext,t),this.progress[t]=0}generateBlob(e,t){const{maxRadius:s,minRadius:i,speed:n}=this,a=s-i;e[t]=i+Math.random()*a,n[t]=.017+.003*Math.random()}generateNextBlob(){const{radius:e,radiusNext:t,progress:s,N:i}=this;for(let n=0;n<i;n++)this.generateBlob(e,n),this.generateBlob(t,n),s[n]=0}update(e,t){const{N:s,progress:i,speed:n,radius:a,radiusNext:r}=this;for(let l=0;l<=s;l++)i[l]+=n[l]*Z2+e*n[l]*X2*t,i[l]>=1&&(i[l]=0,a[l]=r[l],this.generateBlob(r,l))}draw(e,t,s,i,n,a,r,l){if(n.getContext){const c=n.getContext("2d");c.beginPath(),c.moveTo(s,i),c.lineTo(e,i);const{radius:d,radiusNext:h,N:u}=this;for(let p=0;p<=u;p++)if(p===0){const m=this.progress[p],g=d[p]*(1-m)+h[p]*m,f=(t-g)*l+r*(1-l);c.lineTo(e,f)}else{const m=this.progress[p-1],g=d[p-1]*(1-m)+h[p-1]*m,f=this.progress[p],y=d[p]*(1-f)+h[p]*f,v=(s-e)/u*(p-1),w=(s-e)/u*p,b=v+(w-v)/2,S=(t-g)*l+r*(1-l),C=(t-y)*l+r*(1-l);c.bezierCurveTo(b,S,b,C,w,C),p===u&&c.lineTo(s,i)}a(c),c.fill(),c.closePath()}}}class wu{constructor(e,t){this.type=e,this.state=t,this.createGradient()}createGradient(){this.shader=(e,t,s,i,n)=>{e.fillStyle=wu.getGradientFromType(e,this.type,this.state,t,s,i,n)}}update(e,t,s,i){}static createStates(e,t){return t.map(s=>[s,new wu(e,s)])}static getGradientFromType(e,t,s,i,n,a,r){const l=e.createLinearGradient(i,n,a,r),c=[[0,"#F05459"],[.4,"#766EE9"],[1,"#57A4FE"]],d=[[0,"#52CE5D"],[1,"#00B1C0"]],h=[[0,"#0976E3"],[1,"#2BCEFF"]],u=[[0,"#8599aa"],[1,"#8599aa"]],p=[[0,"#4588E3"],[.5,"#976FFF"],[1,"#E46ACE"]],g={group:[[[hs.MUTED_BY_ADMIN],c],[[hs.UNMUTED],d],[[hs.MUTED],h],[[hs.CONNECTING],u]],rtmp:[[[nn.PLAYING],p],[[nn.BUFFERING,nn.CONNECTING],u]]}[t];for(const[f,y]of g)if(f.includes(s)){for(const[v,w]of y)l.addColorStop(v,w);return l}}}class J2{constructor(){this.handleDevicePixelRatioChanged=t=>{this.setSize(),this.forceUpdate()},this.handleResize=()=>{this.resizeHandler&&(clearTimeout(this.resizeHandler),this.resizeHandler=null),this.resizing=!0,this.resizeCanvas(),this.resizeHandler=window.setTimeout(()=>{this.resizing=!1,this.invokeDraw()},250)},this.handleFocus=()=>{this.focused=!0,this.invokeDraw()},this.handleBlur=()=>{this.focused=!1},this.invokeDraw=()=>{this.raf||this.draw()},this.draw=(t=!1)=>{if(this.raf=null,!this.mounted)return;const{lbd:s,lbd1:i,lbd2:n,scale:a,left:r,top:l,right:c,bottom:d,currentState:h,previousState:u,focused:p,resizing:m,canvas:g}=this;if(!p&&!m&&this.progressToState>=1)return;let y=Date.now()-this.lastUpdateTime;y>20&&(y=17),this.animateToAmplitude!==this.amplitude&&(this.amplitude+=this.animateAmplitudeDiff*y,this.animateAmplitudeDiff>0?this.amplitude>this.animateToAmplitude&&(this.amplitude=this.animateToAmplitude):this.amplitude<this.animateToAmplitude&&(this.amplitude=this.animateToAmplitude)),this.animateToAmplitude!==this.amplitude2&&(this.amplitude2+=this.animateAmplitudeDiff2*y,this.animateAmplitudeDiff2>0?this.amplitude2>this.animateToAmplitude&&(this.amplitude2=this.animateToAmplitude):this.amplitude2<this.animateToAmplitude&&(this.amplitude2=this.animateToAmplitude)),u&&(this.progressToState+=y/250,this.progressToState>1&&(this.progressToState=1,this.previousState=null));const{amplitude:v,amplitude2:w,progressToState:b}=this,S=6*w*a,C=6*w*a;g.getContext("2d").clearRect(0,0,g.width,g.height),s.minRadius=0,s.maxRadius=(2+2*v)*a,i.minRadius=0,i.maxRadius=(3+9*v)*a,n.minRadius=0,n.maxRadius=(3+9*v)*a,s.update(v,.3),i.update(v,.7),n.update(v,.7);for(let L=0;L<2;L++){if(L===0&&!u)continue;let E=1,_;L===0?(E=1-b,_=u):(E=u?b:1,h.update(d-l,c-r,y,v),_=h);const k=A=>{A.globalAlpha=.3*E,_.shader(A,r,l,c,d)},x=A=>{A.globalAlpha=L===0?1:E,_.shader(A,r,l,c,d)};i.draw(r,l-S,c,d,g,k,l,1),n.draw(r,l-C,c,d,g,k,l,1),s.draw(r,l,c,d,g,x,l,1)}t||(this.raf=requestAnimationFrame(()=>this.draw()))},this.setCurrentState=(t,s,i)=>{const{currentState:n}=this;n?.state===s&&n.type===t||(this.type=t,this.previousState=i?n:null,this.currentState=this.states.get(s),this.progressToState=this.previousState?0:1)},this.focused=!0,this.resizing=!1,this.lastUpdateTime=Date.now(),this.amplitude=0,this.amplitude2=0;const e=[["group",[hs.UNMUTED,hs.MUTED,hs.MUTED_BY_ADMIN,hs.CONNECTING]],["rtmp",[nn.PLAYING,nn.BUFFERING,nn.CONNECTING]]];this.allStates=new Map(e.map(([t,s])=>[t,new Map(wu.createStates(t,s))])),this.type="group",this.previousState=null,this.currentState=this.states.get(hs.CONNECTING),this.progressToState=1}get states(){return this.allStates.get(this.type)}componentDidMount(){this.mounted||(this.mounted=!0,window.addEventListener("resize",this.handleResize),this.media=window.matchMedia("screen and (min-resolution: 2dppx)"),this.media.addEventListener("change",this.handleDevicePixelRatioChanged),this.setSize(),this.forceUpdate(),this.lbd=new om(3),this.lbd1=new om(7),this.lbd2=new om(8),this.setAmplitude(this.amplitude),this.draw())}componentWillUnmount(){this.mounted=!1,window.removeEventListener("resize",this.handleResize),this.media.removeEventListener("change",this.handleDevicePixelRatioChanged);const{canvas:e}=this;e.getContext("2d").clearRect(0,0,e.width,e.height)}setSize(){this.scale=window.devicePixelRatio,this.top=20*this.scale,this.right=(this.mounted?this.container.offsetWidth:1261)*this.scale,this.bottom=(this.mounted?this.container.offsetHeight:68)*this.scale,this.left=0*this.scale,this.setCanvasSize()}setCanvasSize(){this.canvas.width=this.right,this.canvas.height=this.bottom}resizeCanvas(){this.scale=window.devicePixelRatio,this.right=this.container.offsetWidth*this.scale,this.forceUpdate(),this.invokeDraw()}setAmplitude(e){const{amplitude:t}=this;this.animateToAmplitude=e,this.animateAmplitudeDiff=(e-t)/250,this.animateAmplitudeDiff2=(e-t)/120}forceUpdate(){this.setCanvasSize()}render(e){const t=this.container=document.createElement("div");t.classList.add(e);const s=this.canvas=document.createElement("canvas");return s.classList.add(e+"-canvas"),t.append(s),t}}class tb{constructor(e,t){this.item=e,It(this,t)}play(e){return this.item.playPart(this,e)}}class eF{constructor(e,t){this.icon=e,this.autoplay=!1,It(this,t),this.parts=this.parts.map(s=>this.createPart(s))}load(){let e=this.loadPromise;if(e)return e;const{container:t,canvas:s,width:i,height:n}=this.icon;return e=_s.loadAnimationAsAsset({container:t,canvas:s,width:i,height:n,group:"none",loop:!1,autoplay:this.autoplay??!1,initFrame:this.initFrame,skipFirstFrameRendering:this.initFrame===void 0,color:this.color},this.name).then(a=>_s.waitForFirstFrame(a)).then(a=>{this.player=a,this.onLoadForColor&&(this.onLoadForColor(),this.onLoadForColor=void 0),this.onLoadForPart&&(this.onLoadForPart(),this.onLoadForPart=void 0)}),this.loadPromise=e,this.icon.loadPromises.set(this.name,e),e}createPart(e){return new tb(this,e)}getPart(e){return e instanceof tb?e:typeof e=="string"?this.parts.find(t=>t.name===e):this.parts[e]}playPart(e,t){return this.icon.playPart(this,e,t)}}class yI{constructor(e){It(this,e),this.container||(this.container=document.createElement("div")),this.container.classList.add("rlottie-icon");const{width:t,height:s}=this;this.container.style.width=t+"px",this.container.style.height=s+"px";const i=this.canvas=document.createElement("canvas");i.classList.add("rlottie"),i.width=t,i.height=s,this.items=new Map,this.loadPromises=new Map}get loadPromise(){return Promise.all([...this.loadPromises.values()]).then(Wt)}getItem(e){return!e&&this.items.size===1?this.items.values().next().value:this.items.get(e)}add(e){const t=new eF(this,e);return this.items.set(e.name,t),t}playPart(e,t,s){if(!e.player){e.onLoadForPart=()=>{this.playPart(e,t,s)};return}const i=e.getPart(t);e.player.playPart({from:st.isAvailable("animations")&&!this.skipAnimation?i.startFrame:i.endFrame,to:i.endFrame,callback:s})}static generateEqualParts(e,t){return new Array(e).fill(0).map((s,i)=>{const n=i*t;return{startFrame:n,endFrame:n+t-1}})}}class Wf extends yI{constructor(e){super({width:e.width,height:e.height}),It(this,e)}load(e,t){if(this.loaded)return this.loadPromise;this.loaded=!0,this.partState=e,this.colorState=t;const s=this.getPart(e),i=t!==void 0&&this.getColor&&this.getColor(t),n=s.item;n.initFrame=s.endFrame,n.color=i;const a=[...this.items.values()].map(r=>r.load());return Promise.all(a).then(Wt)}setState(e,t,s){this.loaded||this.load(e,t);let i=!1,n=!1;return e!==void 0?i=this.setPartState(e,t,s):t!==void 0&&(n=this.setColorState(t)),i||n}setPartState(e,t,s){const{partState:i}=this;return i===e?t!==void 0?this.setColorState(t):!1:(t!==void 0&&this.setColorState(t,!1),this.partState=e,this.getPart(e,i).play(s),!0)}setColorState(e,t=!0){const{colorState:s}=this;if(s===e||!this.getColor)return!1;this.colorState=e;const i=this.getItem(),n=this.getColor(e,s),a=()=>{i.player.setColor(n,t)};return i.player?a():i.onLoadForColor=a,!0}destroy(){this.items.forEach(e=>{e.loadPromise.then(()=>{e.player.remove()})})}}class tF extends Wf{constructor(){super({width:36,height:36,getPart:(s,i)=>{const n=qf;let a;switch(s){case n.HAND:a=i===n.MUTED?"muted-to-hand":"unmuted-to-hand";break;case n.MUTED:a=i===n.HAND?"hand-to-muted":"mute";break;case n.UNMUTED:a="unmute";break}return this.getItem().getPart(a)}}),this.container.classList.add("group-call-microphone-icon"+"-container");const t=[{startFrame:0,endFrame:35,name:"hand-to-muted"},{startFrame:36,endFrame:68,name:"unmute"},{startFrame:69,endFrame:98,name:"mute"},{startFrame:99,endFrame:135,name:"muted-to-hand"},{startFrame:136,endFrame:172,name:"unmuted-to-hand"},{startFrame:173,endFrame:201,name:"scheduled-crossing"},{startFrame:202,endFrame:236,name:"scheduled-to-muted"},{startFrame:237,endFrame:273,name:"scheduled-to-hand"},{startFrame:274,endFrame:310,name:"scheduled-crossed-to-hand"},{startFrame:311,endFrame:343,name:"scheduled-uncrossing"},{startFrame:344,endFrame:375,name:"scheduled-to-muted"},{startFrame:376,endFrame:403,name:"play-to-muted"}];this.add({name:"voip_filled",parts:t})}}class vI extends Wf{constructor(e){super({width:32,height:32,getPart:(i,n)=>{const a=Bl;let r;switch(i){case a.HAND:r=3;break;case a.MUTED:r=n===a.HAND?0:2;break;case a.UNMUTED:r=1;break}return this.getItem().getPart(r)},getColor:e?(i,n)=>lF(i):void 0}),this.colored=e,this.container.classList.add("group-call-participant-muted-icon"+"-container");const s=yI.generateEqualParts(4,21);this.add({name:"voice_outlined2",parts:s})}setState(e){return super.setState(oF(e),e)}}const bh="group-call-participant-status";class bI{constructor(e){this.withIcons=e,this.container=document.createElement("div"),this.container.classList.add(bh+"-container")}setState(e,t){const s=Bl,i=this.withIcons.filter(l=>!!t[l]).map(l=>Le(`${l==="presentation"?"listscreenshare":"videocamera_filled"}`,bh+"-icon",bh+"-icon-"+l));let n,a;if(e===s.MUTED_FOR_ME)n=M("VoiceChat.Status.MutedForYou"),a="is-muted";else if(e===s.UNMUTED)n=M("VoiceChat.Status.Speaking"),a="is-speaking";else if(e===s.HAND)n=M("VoiceChat.Status.WantsSpeak"),a="is-waiting";else if(t.about&&!i.length){kt(this.container,_e(t.about));return}else n=M("VoiceChat.Status.Listening"),a="is-listening";const r=document.createElement("span");r.classList.add(bh,a),r.append(...i,n),dt(this.container,r)}}class sF extends Wu{constructor(e){super({getIndex:async t=>(await this.instance.getParticipantByPeerId(t.id)).date,onDelete:t=>{t.dom.listEl.remove(),this.onElementDestroy(t)},onUpdate:async t=>{const s=await this.instance.getParticipantByPeerId(t.id),i=PI(s);t.mutedIcon.setState(i),t.status.setState(i,s)},onSort:(t,s)=>{Ps(t.dom.listEl,this.list,s)},onElementCreate:t=>{const s=xt(),{dom:i}=Xe.addDialogNew({peerId:t.id,container:!1,avatarSize:this.avatarSize,autonomous:this.autonomous,meAsSaved:!1,rippleEnabled:this.rippleEnabled,wrapOptions:{lazyLoadQueue:this.lazyLoadQueue,middleware:s.get()}});i.listEl.classList.add("group-call-participant");const a=new vI(!0),r=new bI(["presentation","video"]);return dt(i.lastMessageSpan,r.container),i.listEl.append(a.container),t.mutedIcon=a,t.status=r,t.middlewareHelper=s,t.dom=i,t},updateElementWith:bs}),this.instance=e,this.avatarSize="abitbigger",this.rippleEnabled=!0,this.autonomous=!0,this.createChatListOptions={dialogSize:72},this.list=Xe.createChatList(this.createChatListOptions)}destroy(){super.clear(),this.elements.forEach(e=>{this.onElementDestroy(e)})}onElementDestroy(e){e.mutedIcon.destroy(),e.middlewareHelper.destroy()}}function wI(o){const e=document.createElement("canvas");e.classList.add("call-video-blur");const t=16;e.width=t,e.height=t;const s=e.getContext("2d",{alpha:!1});s.filter="blur(2px)";const i=()=>{s.drawImage(o,0,0,o.videoWidth,o.videoHeight,0,0,e.width,e.height)};return ll(()=>(i(),e.isConnected)),i(),e}const kr="group-call-participant-video";class iF{constructor(e,t,s){this.managers=e,this.instance=t,this.source=s,this.container=document.createElement("div"),this.container.classList.add(kr+"-container"),this.info=document.createElement("div"),this.info.classList.add(kr+"-info"),this.left=document.createElement("div"),this.left.classList.add(kr+"-info-left"),this.right=document.createElement("div"),this.right.classList.add(kr+"-info-right"),this.info.append(this.left,this.right),this.container.append(this.info)}setPinned(e){if(e){if(this.header)return}else{this.header&&(this.header.remove(),this.header=void 0);return}this.header=document.createElement("div"),this.header.classList.add(kr+"-header");const t=Le("pin","group-call-pin-icon");this.header.append(t),this.container.append(this.header)}setParticipant(e,t,s){let i;e.pFlags.self?(i=M("VoiceChat.Status.You"),i.classList.add("peer-title")):(this.peerTitle=new Rt({peerId:at(e.peer)}),i=this.peerTitle.element),this.groupCallParticipantMutedIcon=new vI(!1),this.groupCallParticipantStatus=new bI([t]),this.left.append(i,this.groupCallParticipantStatus.container),this.right.append(this.groupCallParticipantMutedIcon.container),s.classList.add(kr,"call-video"),s.paused&&wi(s);const n=wI(s);n.classList.add(kr+"-blur"),this.container.prepend(n,s),this.updateParticipant(e)}updateParticipant(e){const t=PI(e);this.groupCallParticipantMutedIcon.setState(t),this.groupCallParticipantStatus.setState(t,e)}destroy(){this.groupCallParticipantMutedIcon.destroy()}}class SI extends mf{constructor(e){super(),It(this,e);const t="group-call-participants-video",s=this.container=document.createElement("div");this.container.classList.add(t+"-container"),e.appendTo.append(s),this.participantsElements=new Map,this.containers=new Map;const{listenerSetter:i}=this;i.add(I)("group_call_participant",({groupCallId:n,participant:a})=>{this.instance.id===n&&this.updateParticipant(a)}),i.add(this.instance)("pinned",n=>{this.participantsElements.forEach(a=>{a.forEach(r=>{this.setElementDisplay(r,n)})})}),N(this.container,n=>{const a=U(n.target,"group-call-participant-video-container");if(!a)return;const r=this.containers.get(a);if(this.instance.pinnedSource===r.source){this.instance.unpinAll();return}this.instance.pinSource(r.source)},{listenerSetter:i}),this.setInstance(this.instance),this.setup({element:s,listenerSetter:i,showOnLeaveToClassName:"group-call-buttons"})}shouldDisplayElement(e,t){return this.displayPinned?!t||e.source===t:t&&e.source!==t}setElementDisplay(e,t){const s=this.shouldDisplayElement(e,t);e.container.classList.toggle("video-hidden",!s);const i=e.source===t;e.setPinned(i)}updateParticipant(e){const t=at(e.peer),s=["video","presentation"],i=s.some(a=>!!e[a]);let n=this.participantsElements.get(t);!i&&!n||(n||this.participantsElements.set(t,n=new Map),s.forEach(a=>{let r=n.get(a);const l=e[a];if(!!l==!!r){r&&r.updateParticipant(e);return}if(l){const c=this.instance.getVideoElementFromParticipantByType(e,a);if(!c)return;const{video:d,source:h}=c;r=new iF(this.managers,this.instance,h),this.containers.set(r.container,r),this.setElementDisplay(r,this.instance.pinnedSource),n.set(a,r),r.setParticipant(e,a,d),this.container.prepend(r.container)}else n.delete(a),r.container.remove(),n.size||(this.participantsElements.delete(t),this.containers.delete(r.container),r.destroy());this._onLengthChange()}))}_onLengthChange(){const e=this.container.childElementCount;this.container.dataset.length=""+e,this.container.dataset.layout=e<=2?"1":e===3?"3":"4",this.onLengthChange&&this.onLengthChange(e)}async setInstance(e){(await e.participants).forEach(t=>{this.updateParticipant(t)})}destroy(){this.containers.forEach(e=>{e.destroy()})}}class nF{constructor(e){this.onOpenProfileClick=()=>{const i=ee.getPopups(Su)[0];i&&i.hide(),me.setInnerPeer({peerId:this.targetPeerId})},this.toggleParticipantMuted=i=>{this.instance.editParticipant(this.participant,{muted:i})},this.buttons=[{icon:"gc_microphoneoff",text:"VoiceChat.MutePeer",verify:()=>this.canManageCall&&this.participant.pFlags.can_self_unmute,onClick:()=>this.toggleParticipantMuted(!0)},{icon:"gc_microphone",text:"VoiceChat.UnmutePeer",verify:()=>this.canManageCall&&!this.participant.pFlags.can_self_unmute,onClick:()=>this.toggleParticipantMuted(!1)},{icon:"gc_microphoneoff",text:"VoiceChat.MuteForMe",verify:()=>!this.canManageCall&&!this.participant.pFlags.muted_by_you,onClick:()=>this.toggleParticipantMuted(!0)},{icon:"gc_microphone",text:"VoiceChat.UnmuteForMe",verify:()=>!this.canManageCall&&this.participant.pFlags.muted_by_you,onClick:()=>this.toggleParticipantMuted(!1)},{icon:"newprivate",text:"VoiceChat.OpenProfile",verify:()=>!0,onClick:this.onOpenProfileClick},{icon:"deleteuser",className:"danger",text:"VoiceChat.RemovePeer",verify:()=>this.managers.appChatsManager.hasRights(this.chatId,"ban_users"),onClick:async()=>{Ct({peerId:this.targetPeerId,title:new Rt({peerId:this.targetPeerId}).element,descriptionLangKey:await this.managers.appChatsManager.isBroadcast(this.chatId)?"VoiceChat.RemovePeer.Confirm.Channel":"VoiceChat.RemovePeer.Confirm",descriptionLangArgs:[new Rt({peerId:this.targetPeerId}).element],button:{langKey:"VoiceChat.RemovePeer.Confirm.OK",isDanger:!0}}).then(()=>{this.managers.appChatsManager.kickFromChat(this.chatId,this.targetPeerId)},Wt)}}];const{listenerSetter:t}=e;this.managers=e.managers,this.instance=e.instance,this.chatId=this.instance.chatId,this.element=jn({buttons:this.buttons,listenerSetter:t}),this.element.classList.add("group-call-participant-menu","night"),za({element:e.onContextElement,callback:async i=>{const n=U(i.target,"group-call-participant");if(!n)return;this.element.parentElement!==s&&s.append(this.element),oe(i);const a=this.targetPeerId=n.dataset.peerId.toPeerId();this.participant=await this.instance.getParticipantByPeerId(a),!this.participant.pFlags.self&&(this.canManageCall=await this.managers.appChatsManager.hasRights(this.chatId,"manage_call"),await Zi(this.buttons,async r=>{const l=await r.verify(a);return r.element.classList.toggle("hide",!l),l}),Tl(i.touches?i.touches[0]:i,this.element,"right"),Js.openBtnMenu(this.element))},listenerSetter:t}),t.add(I)("group_call_participant",({groupCallId:i,participant:n})=>{if(this.instance.id===i){const a=at(n.peer);this.targetPeerId===a&&Js.close()}});let s=document.body;Eu(document.body,()=>{const i=wn();s=i?ee.getPopups(Su)[0].getContainer():document.body,i||Js.close()},t)}}class aF{constructor(e){It(this,e);const t="group-call-participants",s=new vi(void 0);s.container.classList.add(t+"-scrollable");const i=this.container=document.createElement("div");i.classList.add(t);const n=this.sortedList=new sF(this.instance),{instance:a,listenerSetter:r}=this;this.contextMenu=new nF({...e,onContextElement:n.list,listenerSetter:r,instance:a}),this.groupCallParticipantsVideo=new SI({...e,appendTo:s.container,displayPinned:!1}),s.append(n.list),i.append(s.container),e.appendTo.append(i),r.add(I)("group_call_participant",({groupCallId:l,participant:c})=>{this.instance.id===l&&this.updateParticipant(c)}),new nf({scrollable:s,getPromise:()=>this.managers.appGroupCallsManager.getGroupCallParticipants(this.instance.id).then(({participants:l,isEnd:c})=>(l.forEach(d=>{this.updateParticipant(d)}),c))}),this.setInstance(a)}updateParticipant(e){const t=at(e.peer),s=this.sortedList.has(t);if(e.pFlags.left){s&&this.sortedList.delete(t);return}if(!s){this.sortedList.add(t);return}this.sortedList.update(t)}async setInstance(e){(await e.participants).forEach(s=>{this.updateParticipant(s)})}destroy(){this.sortedList.destroy(),this.groupCallParticipantsVideo.destroy()}}class gg{constructor(e){this.appendTo=e,this.descriptionIntl=new ke.IntlElement({key:"VoiceChat.Status.Connecting"}),this.descriptionIntl.element.classList.add("group-call-description")}detach(){this.descriptionIntl.element.remove()}update(e){const{state:t}=e;let s,i;t===hs.CONNECTING?s="VoiceChat.Status.Connecting":(s="VoiceChat.Status.Members",i=[e.groupCall.participants_count]);const{descriptionIntl:n}=this;n.compareAndUpdate({key:s,args:i}),this.descriptionIntl.element.parentElement||this.appendTo.append(this.descriptionIntl.element)}}class CI{constructor(e){this.appendTo=e,this.peerTitle=new Rt({peerId:Tt})}update(e){const{peerTitle:t,appendTo:s}=this,i=e.groupCall,n=e.chatId.toPeerId(!0);i.title?kt(s,_e(i.title)):(t.options.peerId!==n&&(t.options.peerId=n,t.update()),t.element.parentElement!==s&&s.append(t.element))}}function II(o,e,t){const s=o+"-button",i=document.createElement("div");i.classList.add(s,"call-button","rp-overflow"),t.icon&&i.append(Le(t.icon)),t.noRipple||Ni(i),t.isDanger&&i.classList.add(s+"-red"),t.isConfirm&&i.classList.add(s+"-green"),t.callback&&N(i,t.callback,{listenerSetter:e});let n=i;if(t.text){const a=document.createElement("div");a.classList.add(s+"-container","call-button-container");const r=typeof t.text=="string"?M(t.text):t.text;r.classList.add(s+"-text","call-button-text"),a.append(i,r),n=a}return n}const fg="movable-element",lm=fg+"-resize-handler";class rF extends Si{constructor(e){super(!0),this.onResize=()=>{this.fixDimensions(),this.fixPosition(),this.setPosition()},It(this,e),this.top=this.left=this.width=this.height=0,this.element.classList.add(fg),this.addResizeHandlers(),this.setSwipeHandler(),$e.addEventListener("resize",this.onResize)}destroyElements(){this.element.classList.remove(fg),this.handlers&&this.handlers.forEach(e=>{e.remove()})}destroy(){$e.removeEventListener("resize",this.onResize),this.swipeHandler.removeListeners()}addResizeHandlers(){const e=["n","e","s","w","ne","se","sw","nw"];this.handlers=e.map(t=>{const s=document.createElement("div");return s.dataset.side=t,s.classList.add(lm,lm+"-side-"+t),this.element.append(s),s})}setSwipeHandler(){let e,t,s,i,n;const a=this.swipeHandler=new So({element:this.element,onSwipe:(r,l,c)=>{if(n){if(n.includes("e")||n.includes("w")){const d=n.includes("e")&&r>0||n.includes("w")&&r<0,h=Math.abs(r)*(d?1:-1),u=n.includes("e")?lt.width-t:s+t;this.width=Math.min(u,s+h)}if(n.includes("n")||n.includes("s")){const d=n.includes("s")&&l>0||n.includes("n")&&l<0,h=Math.abs(l)*(d?1:-1),u=n.includes("s")?lt.height-e:i+e;this.height=Math.min(u,i+h)}this.fixDimensions(),n.includes("w")&&(this.left=Math.min(t+s-this.minWidth,t+r)),n.includes("n")&&(this.top=Math.min(e+i-this.minHeight,e+l))}else this.top=e+l,this.left=t+r;this.fixPosition(),this.setPosition()},verifyTouchTarget:r=>{const l=r.target;if(this.verifyTouchTarget&&!this.verifyTouchTarget(r))return!1;const c=U(l,lm);return c?(n=c.dataset.side,a.setCursor("")):(n=void 0,a.setCursor("grabbing")),!0},onFirstSwipe:()=>{e=this.top,t=this.left,s=this.width,i=this.height}})}setPositionToCenter(){this.top=lt.height/2-this.height/2,this.left=lt.width/2-this.width/2,this.setPosition()}fixDimensions(){this.width=Kt(this.width,this.minWidth,lt.width),this.height=Kt(this.height,this.minHeight,lt.height)}fixPosition(){this.top=Kt(this.top,0,lt.height-this.height),this.left=Kt(this.left,0,lt.width-this.width)}setPosition(){this.element.style.top=this.top+"px",this.element.style.left=this.left+"px",this.element.style.right="auto",this.element.style.bottom="auto",this.element.style.width=this.width+"px",this.element.style.height=this.height+"px",this.dispatchEvent("resize")}get width(){return this._width}get height(){return this._height}set width(e){this._width=e}set height(e){this._height=e}get state(){const{top:e,left:t,width:s,height:i}=this;return{top:e,left:t,width:s,height:i}}set state(e){const{top:t,left:s,width:i,height:n}=e;this.top=t,this.left=s,this.width=i,this.height=n,this.onResize()}}var ol;class LI{constructor(e){ds(this,ol,void 0);It(this,e),this.toggleMovable(!Je),this.listenerSetter.add($e)("changeScreen",(t,s)=>{(s===hi.mobile||t===hi.mobile)&&this.toggleMovable(!Je)})}destroy(){const e=this.movable;e&&e.destroy()}get movable(){return Bt(this,ol)}get state(){return this.movable?this.movable.state:this.previousState}set state(e){this.previousState=e}toggleMovable(e){let{movable:t}=this;if(e){if(t)return;t=Ft(this,ol,new rF(this.movableOptions)),t.state=this.previousState,this.previousState.top===void 0&&t.setPositionToCenter(),this.onResize&&this.listenerSetter.add(t)("resize",this.onResize)}else{if(!t)return;this.previousState=t.state,t.destroyElements(),t.destroy(),Ft(this,ol,void 0)}}}ol=new WeakMap;function jf(o,e,t){return e.forEach(s=>{s.classList.toggle(o,t)}),()=>jf(o,e,!t)}var Bl=(o=>(o[o.UNMUTED=0]="UNMUTED",o[o.MUTED=1]="MUTED",o[o.MUTED_FOR_ME=2]="MUTED_FOR_ME",o[o.MUTED_BY_ADMIN=3]="MUTED_BY_ADMIN",o[o.HAND=4]="HAND",o))(Bl||{});function PI(o){const e=Bl;return o.pFlags.muted_by_you?e.MUTED_FOR_ME:o.raise_hand_rating!==void 0?e.HAND:o.pFlags.muted?o.pFlags.can_self_unmute?e.MUTED:e.MUTED_BY_ADMIN:e.UNMUTED}function oF(o){const e=Bl;switch(o){case e.MUTED_BY_ADMIN:case e.MUTED_FOR_ME:return e.MUTED;default:return o}}function lF(o){const e=Bl;let t;switch(o){case e.HAND:t="blue";break;case e.MUTED:case e.MUTED_FOR_ME:case e.MUTED_BY_ADMIN:t=o===e.MUTED?"secondary":"red";break;case e.UNMUTED:t="green";break}const s=Ls.getProperty("gc-"+t+"-text-color");return _n(s)}var qf=(o=>(o[o.HAND=0]="HAND",o[o.MUTED=1]="MUTED",o[o.UNMUTED=2]="UNMUTED",o))(qf||{});function cF(o,e){const t=qf;return e.pFlags.can_self_unmute?e.pFlags.muted?t.MUTED:t.UNMUTED:t.HAND}let sb={width:420,height:640};const ta="group-call";class Su extends ee{constructor(){super("popup-group-call",{body:!0,withoutOverlay:!0,closable:!0,title:!0}),this.onFullScreenClick=()=>{Sg(this.container)},this.onToggleControls=h=>{this.container.classList.toggle("show-controls",h),this.buttonsContainer.classList.toggle("show-controls",h)},this.toggleDisability=jf.bind(null,"btn-disabled"),this.onVideoClick=()=>{const h=this.toggleDisability([this.btnVideo],!0);this.instance.toggleVideoSharing().finally(()=>{h()})},this.onScreenClick=()=>{const h=this.toggleDisability([this.btnScreen],!0);this.instance.toggleScreenSharing().finally(()=>{h()})},this.onMuteClick=()=>{const h=this.instance.participant;h.pFlags.can_self_unmute?this.instance.toggleMuted():h.raise_hand_rating===void 0&&this.instance.changeRaiseHand(!0)},this.onLeaveClick=async()=>{const h=u=>{this.instance.hangUp(u)};await this.managers.appChatsManager.hasRights(this.instance.chatId,"manage_call")?ee.createPopup(Ss,"popup-end-video-chat",{titleLangKey:"VoiceChat.End.Title",descriptionLangKey:"VoiceChat.End.Text",checkboxes:[{text:"VoiceChat.End.Third"}],buttons:[{langKey:"VoiceChat.End.OK",callback:(u,p)=>{h(!!p.size)},isDanger:!0}]}).show():h(!1)},this.onFullScreenChange=()=>{this.toggleBigLayout();const h=wn(),{btnFullScreen:u,btnExitFullScreen:p}=this,m=this.container.classList.contains("is-full-screen");this.container.classList.toggle("is-full-screen",h),u&&u.classList.toggle("hide",h),p&&p.classList.toggle("hide",!h),this.btnClose.classList.toggle("hide",h),h!==m&&(gt.checkAnimations2(h),as.setThemeColor(h?"#000000":void 0))},this.toggleBigLayout=()=>{const h=wn(),u=this.movablePanel?.movable,p=(h||!!(u&&u.width>=680))&&!!this.videosCount,m=this.container.classList.contains("is-big-layout");let g;p&&!m&&(g=Array.from(this.buttonsContainer.children),g.forEach(f=>{f.style.opacity="0"}),this.buttonsContainer.offsetLeft),this.container.classList.toggle("is-big-layout",p),this.btnInvite.classList.toggle("hide",p),this.btnShowColumn.classList.toggle("hide",!p),g&&g.forEach(f=>{f.style.opacity=""})},this.toggleRightColumn=()=>{this.container.classList.toggle("is-right-column-shown")},this.videosCount=0,this.container.classList.add(ta,"night");const e=this.instance=zn.groupCall,{listenerSetter:t}=this;if(!Dg){const h=this.btnFullScreen=it("fullscreen"),u=this.btnFullScreen2=it("fullscreen "+ta+"-cfs"),p=this.btnExitFullScreen=it("smallscreen");N(h,this.onFullScreenClick,{listenerSetter:t}),N(u,this.onFullScreenClick,{listenerSetter:t}),N(p,()=>{kc()},{listenerSetter:t}),Eu(this.container,this.onFullScreenChange,t)}this.btnInvite=it("adduser");const s=this.btnShowColumn=it("rightpanel "+ta+"-only-big");N(s,this.toggleRightColumn,{listenerSetter:t});const i=document.createElement("div");i.classList.add(ta+"-header-info"),this.title.classList.add(ta+"-header-title");const n=document.createElement("div");n.classList.add(ta+"-header-subtitle"),i.append(this.title,n),this.header.classList.add(ta+"-header"),this.header.append(...[this.btnExitFullScreen,i,this.btnFullScreen,s].filter(Boolean));const a=this.header.cloneNode(!1),r=i.cloneNode(!1),l=this.title.cloneNode(!1);r.append(l);const c=it("rightpanel");a.append(...[c,r,this.btnFullScreen2].filter(Boolean)),N(c,this.toggleRightColumn,{listenerSetter:t}),this.body.prepend(a);const d=new vi(void 0);d.container.classList.add("group-call-big-video-container"),this.container.append(d.container),this.groupCallTitle=new CI(this.title),this.groupCallDescription=new gg(n),this.groupCallBodyHeaderDescription=new gg(l),this.constructButtons(),this.groupCallParticipantsVideo=new SI({appendTo:d.container,instance:e,listenerSetter:t,displayPinned:!0,onLengthChange:h=>{this.videosCount=h,this.toggleBigLayout()},managers:this.managers}),this.groupCallParticipants=new aF({appendTo:this.body,instance:e,listenerSetter:t,managers:this.managers}),this.movablePanel=new LI({listenerSetter:t,movableOptions:{minWidth:400,minHeight:480,element:this.element,verifyTouchTarget:h=>{const u=h.target;return!(U(u,"chatlist")||U(u,"group-call-button")||U(u,"btn-icon")||U(u,"group-call-participants-video-container")||wn())}},onResize:()=>this.toggleBigLayout(),previousState:sb}),t.add(e)("state",()=>{this.updateInstance()}),t.add(I)("group_call_update",h=>{this.instance?.id===h.id&&this.updateInstance()}),t.add(e)("pinned",()=>{this.setHasPinned()}),t.add(this.groupCallParticipantsVideo)("toggleControls",this.onToggleControls),this.addEventListener("close",()=>{const{movablePanel:h}=this;sb=h.state,this.groupCallParticipantsVideo.destroy(),this.groupCallParticipants.destroy(),this.groupCallMicrophoneIcon.destroy(),h.destroy()}),this.toggleRightColumn(),this.onFullScreenChange(),this.updateInstance()}constructButtons(){const e=this.buttonsContainer=document.createElement("div");e.classList.add(ta+"-buttons");const t=II.bind(null,ta,this.listenerSetter),s=this.btnVideo=t({callback:this.onVideoClick,icon:"videocamera_filled"}),i=this.btnScreen=t({callback:this.onScreenClick,icon:"sharescreen_filled"});i.classList.toggle("hide",!Cm);const n=t({noRipple:!0,callback:ma(this.onMuteClick,600,!0)});n.classList.add(ta+"-microphone-button");const a=this.groupCallMicrophoneIcon=new tF;n.append(a.container);const r=t({icon:"settings_filled"});r.classList.add("btn-disabled"),r.classList.toggle("hide",!Cm);const l=t({isDanger:!0,callback:this.onLeaveClick,icon:"close"});e.append(s,i,n,r,l),this.container.append(e)}getContainer(){return this.container}setHasPinned(){this.container.classList.toggle("has-pinned",!!this.instance.pinnedSource)}updateInstance(){if(this.instance.state===hs.CLOSED){this.container.classList.contains("is-full-screen")&&kc(),this.hide();return}const{participant:e,groupCall:t}=this.instance;if(!e)return;this.setTitle(),this.setDescription(),this.setHasPinned();const s=cF(t,e);this.container.dataset.micState=s===0?"hand":s===1?"muted":"unmuted",this.groupCallMicrophoneIcon.setState(s)}setTitle(){this.groupCallTitle.update(this.instance)}setDescription(){this.groupCallDescription.update(this.instance),this.groupCallBodyHeaderDescription.update(this.instance)}}var Ot=(o=>(o[o.CONNECTED=0]="CONNECTED",o[o.CONNECTING=1]="CONNECTING",o[o.EXCHANGING_KEYS=2]="EXCHANGING_KEYS",o[o.PENDING=3]="PENDING",o[o.REQUESTING=4]="REQUESTING",o[o.CLOSING=5]="CLOSING",o[o.CLOSED=6]="CLOSED",o))(Ot||{});class MI{constructor(e){this.appendTo=e,this.container=document.createElement("div"),this.container.classList.add("call-description")}detach(){this.interval!==void 0&&(clearInterval(this.interval),this.interval=void 0),this.container.remove(),this.state=void 0}update(e){const{connectionState:t}=e;if(this.state===t)return;this.state=t;let s;if(t===Ot.CONNECTED){s=document.createElement("span"),s.classList.add("call-description-duration");const i=()=>{s.innerText=Fi(e.duration,!0)};this.interval=window.setInterval(i,1e3),i()}else{let i;switch(t){case Ot.PENDING:i=e.isOutgoing?"Call.StatusRinging":"Call.StatusCalling";break;case Ot.REQUESTING:i="Call.StatusRequesting";break;case Ot.EXCHANGING_KEYS:i="VoipExchangingKeys";break;case Ot.CLOSED:i=e.connectedAt!==void 0?"Call.StatusEnded":"Call.StatusFailed";break;default:i="Call.StatusConnecting";break}s=M(i),this.interval!==void 0&&(clearInterval(this.interval),this.interval=void 0)}this.container.classList.toggle("has-duration",t===Ot.CONNECTED),dt(this.container,s),this.container.parentElement||this.appendTo.append(this.container)}}class yg extends Wf{constructor(e,t){super({width:36,height:36,getPart:s=>this.getItem().getPart(s?"unmute":"mute"),getColor:e?s=>s?[255,255,255]:[158,158,158]:void 0,skipAnimation:t}),this.add({name:"voice_mini",parts:[{startFrame:0,endFrame:35,name:"hand-to-muted"},{startFrame:36,endFrame:68,name:"unmute"},{startFrame:69,endFrame:98,name:"mute"},{startFrame:99,endFrame:135,name:"muted-to-hand"},{startFrame:136,endFrame:171,name:"unmuted-to-hand"}]})}}const Mn="call",EI=400,_I=580,kI={width:EI,height:_I};let ib={...kI};class vg extends ee{constructor(e){super("popup-call",{withoutOverlay:!0,closable:!0}),this.instance=e,this.onFullScreenClick=()=>{Sg(this.container)},this.onFullScreenChange=()=>{const m=wn(),{btnFullScreen:g,btnExitFullScreen:f}=this,y=this.container.classList.contains("is-full-screen");this.container.classList.toggle("is-full-screen",m),g&&g.classList.toggle("hide",m),f&&f.classList.toggle("hide",!m),this.btnClose.classList.toggle("hide",m),m!==y&&(gt.checkAnimations(m),as.setThemeColor(m?"#000000":void 0),this.resizeVideoContainers())},this.videoContainers={};const{container:t,listenerSetter:s}=this;t.classList.add(Mn,"night");const i=document.createElement("div");i.classList.add(Mn+"-avatar");const n=this.peerId=this.instance.interlocutorUserId.toPeerId(),{node:a}=es({middleware:this.middlewareHelper.get(),isBig:!0,peerId:n,size:"full"});i.append(a);const r=new Rt({peerId:n}).element;r.classList.add(Mn+"-title");const l=document.createElement("div");l.classList.add(Mn+"-subtitle"),this.description=new MI(l);const c=this.emojisSubtitle=document.createElement("div");c.classList.add(Mn+"-emojis"),t.append(i,r,l),Oi?this.header.append(c):(this.btnFullScreen=it("fullscreen"),this.btnExitFullScreen=it("smallscreen hide"),N(this.btnFullScreen,this.onFullScreenClick,{listenerSetter:s}),N(this.btnExitFullScreen,()=>kc(),{listenerSetter:s}),Eu(this.container,this.onFullScreenChange,s),this.header.prepend(this.btnExitFullScreen),this.header.append(this.btnFullScreen),t.append(c)),this.partyStates=document.createElement("div"),this.partyStates.classList.add(Mn+"-party-states"),this.partyMutedState=document.createElement("div"),this.partyMutedState.classList.add(Mn+"-party-state");const d=M("VoipUserMicrophoneIsOff",[new Rt({peerId:n,onlyFirstName:!0,limitSymbols:18}).element]);d.classList.add(Mn+"-party-state-text");const h=new yg(!1,!0);h.setState(!1,!1),this.partyMutedState.append(h.container,d),this.partyStates.append(this.partyMutedState),this.container.append(this.partyStates),this.makeButton=II.bind(null,Mn,this.listenerSetter),this.constructFirstButtons(),this.constructSecondButtons(),s.add(e)("state",()=>{this.updateInstance()}),s.add(e)("mediaState",()=>{this.updateInstance()}),this.movablePanel=new LI({listenerSetter:s,movableOptions:{minWidth:EI,minHeight:_I,element:this.element,verifyTouchTarget:m=>{const g=m.target;return!(U(g,"call-button")||U(g,"btn-icon")||wn())}},previousState:!this.instance.wasTryingToJoin&&!this.instance.isOutgoing?{...kI}:ib});const u=this.movablePanel.movable;u&&this.listenerSetter.add(u)("resize",()=>{this.resizeVideoContainers()});const p=this.controlsHover=new mf;p.setup({element:this.container,listenerSetter:this.listenerSetter,showOnLeaveToClassName:"call-buttons"}),p.showControls(!1),this.addEventListener("close",()=>{const{movablePanel:m}=this;ib=m.state,this.microphoneIcon.destroy(),m.destroy()}),this.updateInstance()}getCallInstance(){return this.instance}constructFirstButtons(){const e=this.firstButtonsRow=document.createElement("div");e.classList.add(Mn+"-buttons","is-first");const t=jf.bind(null,"btn-disabled"),s=this.btnVideo=this.makeButton({text:"Call.Camera",icon:"videocamera_filled",callback:()=>{const r=t([s,i],!0);this.instance.toggleVideoSharing().finally(r)}}),i=this.btnScreen=this.makeButton({text:"Call.Screen",icon:"sharescreen_filled",callback:()=>{const r=t([s,i],!0);this.instance.toggleScreenSharing().finally(r)}});Cm||(i.classList.add("hide"),this.container.classList.add("no-screen")),this.muteI18nElement=new ke.IntlElement({key:"Call.Mute"});const n=this.btnMute=this.makeButton({text:this.muteI18nElement.element,callback:()=>{this.instance.toggleMuted()}}),a=this.microphoneIcon=new yg(!0,!0);n.firstElementChild.append(a.container),e.append(s,i,n),this.container.append(e)}constructSecondButtons(){const e=this.secondButtonsRow=document.createElement("div");e.classList.add(Mn+"-buttons","is-second"),this.declineI18nElement=new ke.IntlElement({key:"Call.Decline"});const t=this.btnDecline=this.makeButton({text:this.declineI18nElement.element,icon:"endcall_filled",callback:()=>{this.instance.hangUp("phoneCallDiscardReasonHangup")},isDanger:!0}),s=this.btnAccept=this.makeButton({text:"Call.Accept",icon:"phone_filled",callback:()=>{this.instance.acceptCall()},isConfirm:!0});e.append(t,s),this.container.append(e)}createVideoContainer(e){const t=Mn+"-video",s=document.createElement("div");s.classList.add(t+"-container"),e.classList.add(t),e.paused&&wi(e),N(s,()=>{if(!s.classList.contains("small"))return;const n=Object.values(this.videoContainers).find(a=>!a.classList.contains("small"));n.classList.add("small"),n.style.cssText=s.style.cssText,s.classList.remove("small"),s.style.cssText="",this.resizeVideoContainers()});const i=wI(e);return i.classList.add(t+"-blur"),s.append(i,e),s}updateInstance(){const{instance:e}=this,{connectionState:t}=e;if(t===Ot.CLOSED){this.container.classList.contains("is-full-screen")&&kc(),this.btnVideo.classList.add("disabled"),this.hide();return}const s=!e.isOutgoing&&t===Ot.PENDING;this.declineI18nElement.compareAndUpdate({key:t===Ot.PENDING?"Call.Decline":"Call.End"}),this.btnAccept.classList.toggle("disable",!s),this.btnAccept.classList.toggle("hide-me",!s),this.container.classList.toggle("two-button-rows",s);const i=e.isMuted,n=()=>{this.btnMute.firstElementChild.classList.toggle("active",i)},a=this.microphoneIcon.getItem().player;this.microphoneIcon.setState(!i,!i,n),a||n(),this.muteI18nElement.compareAndUpdate({key:i?"VoipUnmute":"Call.Mute"});const r=e.isSharingVideo;this.btnVideo.firstElementChild.classList.toggle("active",r);const l=e.isSharingScreen;this.btnScreen.firstElementChild.classList.toggle("active",l);const c=e.getMediaState("output");bt({element:this.partyMutedState,className:"is-visible",forwards:!!c?.muted,duration:300});const d=this.videoContainers,h={...d};["input","output"].forEach(u=>{const p=e.getMediaState(u),m=e.getVideoElement(u),g=!!(m&&m.videoWidth&&m.videoHeight);m&&!g&&!m.dataset.hasPromise&&(m.dataset.hasPromise="1",Wn(m).then(()=>{delete m.dataset.hasPromise,this.updateInstance()}));const f=!!m&&g&&!!(p&&(p.videoState==="active"||p.screencastState==="active"));let y=d[u];f&&m&&!y&&(y=d[u]=this.createVideoContainer(m),this.container.append(y)),!f&&y&&(y.remove(),delete d[u])});{const u=d.input,p=d.output;Object.keys(h).length!==Object.keys(d).length&&u&&u.classList.toggle("small",!!p),p&&!u&&p.classList.remove("small")}this.resizeVideoContainers(),this.container.classList.toggle("no-video",!Object.keys(d).length),!this.emojisSubtitle.textContent&&t<Ot.EXCHANGING_KEYS&&Promise.resolve(e.getEmojisFingerprint()).then(u=>{dt(this.emojisSubtitle,_e(u.join("")))}),this.setDescription()}resizeVideoContainers(){Object.values(this.videoContainers).forEach(e=>{if(e.classList.contains("small")){const s=e.querySelector("video"),i=this.movablePanel.state,n=240,a=240,r=s.videoHeight>s.videoWidth,l=r?a:n,c=1/3*(wn()?65535:r?i.height:i.width),d=r?s.videoWidth/s.videoHeight:1,h=r?1:s.videoHeight/s.videoWidth;e.style.width=c*d+"px",e.style.height=c*h+"px",e.style.maxWidth=l*d+"px",e.style.maxHeight=l*h+"px"}else e.style.cssText=""})}setDescription(){this.description.update(this.instance)}}function TI(o){const e=uu(o,o.media[0]),t={"@type":"InitialSetup",fingerprints:[e.fingerprint],ufrag:e.ufrag,pwd:e.pwd,audio:void 0,video:void 0,screencast:void 0},s=i=>""+i;for(const i of o.media){const n=i.mediaType;if(n==="application"||!i.isSending)continue;const a=t[n==="video"&&t.video?"screencast":n]={},r=uu(o,i);a.ssrc=s(r.source),r.sourceGroups&&(a.ssrcGroups=r.sourceGroups.map(h=>({semantics:h.semantics,ssrcs:h.sources.map(s)})));const l=a.rtpExtensions=[];i.attributes.get("extmap").forEach(h=>{l.push({id:+h.key,uri:h.value})});const c=new Map,d=h=>{let u=c.get(h);return u||c.set(h,u={id:h}),u};i.attributes.get("rtpmap").forEach(h=>{const u=+h.key,p=d(u),m=h.value.split("/"),[g,f,y]=m;p.name=g,p.clockrate=+f,p.channels=y?+y:0}),i.attributes.get("rtcp-fb").forEach(h=>{const u=+h.key,p=d(u);p.feedbackTypes=h.lines.map(m=>{const g=m.split(" "),[f,y]=g;return{type:f,subtype:y||""}})}),i.attributes.get("fmtp").forEach(h=>{const u=+h.key,p=d(u),m=p.parameters={},g=h.value.split(";");for(const f of g){const[y,v]=f.split("=");m[y]=v}}),a.payloadTypes=Array.from(c.values())}return t}class dF extends dC{constructor(e){super(e)}async negotiateInternal(){const{connection:e,call:t}=this;if(!e.localDescription&&!e.remoteDescription&&!t.isOutgoing)return;let s;if(t.offerReceived){t.offerReceived=!1;const n=s=await e.createAnswer();this.log("[sdp] local",n.type,n.sdp),await e.setLocalDescription(n),this.log("[InitialSetup] send 2")}else{const n=s=await e.createOffer();this.log("[sdp] local",n.sdp),await e.setLocalDescription(n),t.offerSent=!0,this.log("[InitialSetup] send 0")}const i=TI(hu(s.sdp));t.sendCallSignalingData(i)}}let hF;function uF(){return hF??(hF=new eC(["call_busy.mp3","call_connect.mp3","call_end.mp3","call_incoming.mp3","call_outgoing.mp3","voip_failed.mp3"]))}const cm=45e3;class pF extends Si{construct(e){this.managers=e,this.log=ri("CC"),Fc&&(this.audioAsset=uF(),this.tempId=0,this.instances=new Map,this.sortedInstances=[],I.addEventListener("call_update",async t=>{let s=this.instances.get(t.id);switch(s&&s.setPhoneCall(t),t._){case"phoneCallDiscarded":{s&&s.hangUp(t.reason?._,!0);break}case"phoneCallAccepted":{s&&s.confirmCall();break}case"phoneCallRequested":{s||(s=this.createCallInstance({isOutgoing:!1,interlocutorUserId:t.admin_id}),s.overrideConnectionState(Ot.PENDING),s.setPhoneCall(t),s.setHangUpTimeout(cm,"phoneCallDiscardReasonMissed"));break}case"phoneCall":{if(!s||s.encryptionKey)break;const i=s.dh.g_a=t.g_a_or_b,n=s.dh,a=await fe.invokeCrypto("sha256",i);if(!b0(n.g_a_hash,a)){this.log.error("Incorrect g_a_hash",n.g_a_hash,a);break}const{key:r,key_fingerprint:l}=await this.managers.appCallsManager.computeKey(i,n.b,n.p);if(t.key_fingerprint!==l){this.log.error("Incorrect key fingerprint",t.key_fingerprint,l,i,n),s.hangUp("phoneCallDiscardReasonDisconnect");break}s.encryptionKey=r,s.joinCall();break}}}),I.addEventListener("call_signaling",({callId:t,data:s})=>{const i=this.instances.get(t);i?.id===t&&i.onUpdatePhoneCallSignalingData(s)}))}get currentCall(){return this.sortedInstances?.[0]}getCallByUserId(e){for(const[t,s]of this.instances)if(s.interlocutorUserId===e)return s}createCallInstance(e){const t=new Ah({managers:this.managers,...e});return t.addEventListener("state",s=>{const i=this.currentCall;s===Ot.CLOSED?(this.instances.delete(t.id),us(this.sortedInstances,t)):Yr(this.sortedInstances,t,"sortIndex"),s===Ot.EXCHANGING_KEYS&&(t.wasTryingToJoin=!0);const n=t.connectedAt!==void 0;s===Ot.EXCHANGING_KEYS||s===Ot.CONNECTING&&n?t.setHangUpTimeout(cm,"phoneCallDiscardReasonDisconnect"):t.clearHangUpTimeout(),(i===t||!i)&&(s===Ot.CLOSED?!t.isOutgoing&&!t.wasTryingToJoin?this.audioAsset.stopSound():t.wasTryingToJoin&&!n?this.audioAsset.playSound("voip_failed.mp3"):this.audioAsset.playSound(t.discardReason==="phoneCallDiscardReasonBusy"?"call_busy.mp3":"call_end.mp3"):s===Ot.PENDING?this.audioAsset.playSound(t.isOutgoing?"call_outgoing.mp3":"call_incoming.mp3",!0):s===Ot.EXCHANGING_KEYS?this.audioAsset.playSoundIfDifferent("call_connect.mp3"):s===Ot.CONNECTING?t.duration&&this.audioAsset.playSound("voip_connecting.mp3",!0):this.audioAsset.stopSound())}),t.addEventListener("id",(s,i)=>{i!==void 0&&this.instances.delete(i);const n=!!this.currentCall;this.instances.set(s,t),i===void 0&&this.dispatchEvent("instance",{instance:t,hasCurrent:n})}),t}async startCallInternal(e,t){this.log("p2pStartCallInternal",e,t);const s=await this.managers.appProfileManager.getProfile(e);if(!s)return;const{video_calls_available:i}=s.pFlags,n=this.createCallInstance({isOutgoing:!0,interlocutorUserId:e});n.requestInputSource(!0,!!(t&&i),!1),n.overrideConnectionState(Ot.REQUESTING),n.setPhoneCall({_:"phoneCallWaiting",access_hash:"",admin_id:Tt,date:Ms(!0),id:--this.tempId,participant_id:e,protocol:n.protocol,pFlags:{video:t||void 0}}),this.managers.appCallsManager.generateDh().then(async a=>(n.dh=a,this.managers.appCallsManager.requestCall(e,n.protocol,n.dh.g_a_hash,t&&i))).then(a=>{n.overrideConnectionState(Ot.PENDING),n.setPhoneCall(a),n.setHangUpTimeout(cm,"phoneCallDiscardReasonHangup")})}}const Yi=new pF;Ws&&(Ws.callsController=Yi);function mF(){return{_:"phoneCallProtocol",pFlags:{udp_p2p:!0,udp_reflector:!0},min_layer:92,max_layer:92,library_versions:["4.0.0"]}}function gF(o){const e=[];return o.connections.forEach(t=>{switch(t._){case"phoneConnectionWebrtc":{const{ip:s,ipv6:i,port:n,username:a,password:r}=t,l=[];t.pFlags.turn?(s&&l.push(`turn:${s}:${n}`),i&&l.push(`turn:[${i}]:${n}`)):t.pFlags.stun&&(s&&l.push(`stun:${s}:${n}`),i&&l.push(`stun:[${i}]:${n}`)),l.length>0&&e.push({urls:l,username:a,credential:r});break}}}),{iceServers:e,iceTransportPolicy:o.pFlags.p2p_allowed?"all":"relay"}}const bg=typeof window<"u"&&"crypto"in window?window.crypto.subtle:self.crypto.subtle;function fF(o){return bg.digest("SHA-256",u0(o)).then(e=>new Uint8Array(e))}const yF=128*1024*1024;class nb{constructor(e,t){this.isOutgoing=e,this.p2pKey=t,this.type="Signaling",this.counter=0,this.seqMap=new Map}concatSHA256(e){return fF(BL(...e))}async encryptPrepared(e){const t={counter:0,bytes:new Uint8Array(16+e.length)},s=(this.isOutgoing?0:8)+(this.type==="Signaling"?128:0),i=this.p2pKey,n=await this.concatSHA256([i.subarray(s+88,s+88+32),e]),a=t.bytes;for(let c=0;c<16;++c)a[c]=n[c+8];const r=await this.prepareAesKeyIv(i,a,s),l=await this.aesProcessCtr(e,e.length,r,!0);return t.bytes=new Uint8Array([...t.bytes.subarray(0,16),...l]),t}encryptRawPacket(e){const t=++this.counter,s=new ArrayBuffer(4);new DataView(s).setUint32(0,t>>>0,!1);const n=new Uint8Array([...new Uint8Array(s),...e]);return this.encryptPrepared(n)}async prepareAesKeyIv(e,t,s){const[i,n]=await Promise.all([this.concatSHA256([t.subarray(0,16),e.subarray(s,s+36)]),this.concatSHA256([e.subarray(40+s,40+s+36),t.subarray(0,16)])]);return{key:new Uint8Array([...i.subarray(0,8),...n.subarray(8,24),...i.subarray(24,32)]),iv:new Uint8Array([...n.subarray(0,4),...i.subarray(8,16),...n.subarray(24,28)])}}async aesProcessCtr(e,t,s,i=!0){const n=await bg.importKey("raw",s.key,{name:"AES-CTR"},!1,[i?"encrypt":"decrypt"]),a=await bg[i?"encrypt":"decrypt"]({name:"AES-CTR",counter:s.iv,length:s.iv.length*8},n,e);return new Uint8Array(a)}constTimeIsDifferent(e,t,s){let i=!0;for(let n=0;n<s;++n)e[n]!==t[n]&&(i=!1);return!i}async decryptRawPacket(e){if(e.length<21||e.length>yF)return;const{isOutgoing:t,type:s}=this,i=(t?8:0)+(s==="Signaling"?128:0),n=this.p2pKey,a=e.subarray(0,16),r=e.subarray(16),l=e.length-16,c=await this.prepareAesKeyIv(n,a,i),d=await this.aesProcessCtr(r,l,c,!1),h=await this.concatSHA256([n.subarray(88+i,88+i+32),d]);if(this.constTimeIsDifferent(h.subarray(8),a,16))return;const p=new DataView(d.buffer).getUint32(0);if(!this.seqMap.has(p))return this.seqMap.set(p,p),d.slice(4)}}class ab{static generateOffer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const r=[n,a],l=new Ym;l.add("v=0","o=- 1 2 IN IP4 127.0.0.1","s=-","t=0 0"),t&&t.forEach(d=>{const{hash:h,fingerprint:u,setup:p}=d;l.add(`a=fingerprint:${h} ${u}`,`a=setup:${p}`)}),s&&i&&l.add(`a=ice-ufrag:${s}`,`a=ice-pwd:${i}`),l.add("a=group:BUNDLE 0 1 2","a=extmap-allow-mixed","a=msid-semantic: WMS *");const c="stream"+r.map(d=>d.ssrc).join("_");for(let d=0;d<r.length;d++){const h=r[d],{type:u,ssrc:p,ssrcGroups:m,payloadTypes:g,rtpExtensions:f}=h;switch(u){case"audio":{l.add(`m=audio 56930 UDP/TLS/RTP/SAVPF ${g.map(y=>y.id).join(" ")}`,"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle",`a=mid:${d}`,"a=sendrecv",Tn(f)),p&&l.add(`a=msid:${c} audio${p}`),l.add("a=rtcp-mux",xn(g),An(u,p,m,c));break}case"video":{l.add(`m=video 61986 UDP/TLS/RTP/SAVPF ${g.map(y=>y.id).join(" ")}`,"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle",`a=mid:${d}`,"a=sendrecv",Tn(f)),p&&l.add(`a=msid:${c} video${p}`),l.add("a=rtcp-mux","a=rtcp-rsize",xn(g),An(u,p,m,c));break}}}return l.add(Il()),l.finalize()}static generateAnswer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const r=[n,a],l=new Ym;l.add("v=0","o=- 1 2 IN IP4 127.0.0.1","s=-","t=0 0"),t&&t.forEach(d=>{const{hash:h,fingerprint:u,setup:p}=d;l.add(`a=fingerprint:${h} ${u}`,`a=setup:${p}`)}),s&&i&&l.add(`a=ice-ufrag:${s}`,`a=ice-pwd:${i}`),l.add("a=group:BUNDLE 0 1 2","a=extmap-allow-mixed","a=msid-semantic: WMS *");const c="stream"+r.map(d=>d.ssrc).join("_");for(let d=0;d<r.length;d++){const h=r[d],{type:u,ssrc:p,ssrcGroups:m,payloadTypes:g,rtpExtensions:f}=h;switch(u){case"audio":{l.add(`m=audio 56930 UDP/TLS/RTP/SAVPF ${g.map(y=>y.id).join(" ")}`,"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle",`a=mid:${d}`,"a=sendrecv",Tn(f)),p&&l.add(`a=msid:${c} audio${p}`),l.add("a=rtcp-mux",xn(g),An(u,p,m,c));break}case"video":{l.add(`m=video 61986 UDP/TLS/RTP/SAVPF ${g.map(y=>y.id).join(" ")}`,"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle",`a=mid:${d}`,"a=sendrecv",Tn(f)),p&&l.add(`a=msid:${c} video${p}`),l.add("a=rtcp-mux","a=rtcp-rsize",xn(g),An(u,p,m,c));break}}}return l.add(Il()),l.finalize()}}class rb{static generateOffer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const r=[n,a];let l=`v=0
o=- 1 0 IN IP4 0.0.0.0
s=-
t=0 0`;t&&t.forEach(d=>{const{hash:h,fingerprint:u,setup:p}=d;l+=`
a=fingerprint:${h} ${u}
a=setup:${p}`}),s&&i&&(l+=`
a=ice-ufrag:${s}
a=ice-pwd:${i}`),l+=`
a=group:BUNDLE 0 1 2
a=ice-options:trickle
a=msid-semantic:WMS *`;const c="stream"+r.map(d=>d.ssrc).join("_");for(let d=0;d<r.length;d++){const h=r[d],{type:u,ssrc:p,ssrcGroups:m,payloadTypes:g,rtpExtensions:f}=h;switch(u){case"audio":{l+=`
m=audio 9 UDP/TLS/RTP/SAVPF ${g.map(y=>y.id).join(" ")}
c=IN IP4 0.0.0.0
a=mid:${d}
a=sendrecv`,l+=Tn(f),l+=`
a=rtcp-mux`,l+=xn(g),l+=An(u,p,m,c);break}case"video":{l+=`
m=video 9 UDP/TLS/RTP/SAVPF ${g.map(y=>y.id).join(" ")}
c=IN IP4 0.0.0.0
a=mid:${d}
a=sendrecv`,l+=Tn(f),l+=`
a=rtcp-mux
a=rtcp-rsize`,l+=xn(g),l+=An(u,p,m,c);break}}}return l+=Il(),l+=`
`,l}static generateAnswer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const r=[n,a];let l=`v=0
o=- 1 0 IN IP4 0.0.0.0
s=-
t=0 0`;t&&t.forEach(d=>{const{hash:h,fingerprint:u,setup:p}=d;l+=`
a=fingerprint:${h} ${u}
a=setup:${p}`}),s&&i&&(l+=`
a=ice-ufrag:${s}
a=ice-pwd:${i}`),l+=`
a=group:BUNDLE 0 1 2
a=ice-options:trickle
a=msid-semantic:WMS *`;const c="stream"+r.map(d=>d.ssrc).join("_");for(let d=0;d<r.length;d++){const h=r[d],{type:u,mid:p,ssrc:m,ssrcGroups:g,payloadTypes:f,dir:y,rtpExtensions:v}=h;switch(u){case"audio":{l+=`
m=audio 9 UDP/TLS/RTP/SAVPF ${f.map(w=>w.id).join(" ")}
c=IN IP4 0.0.0.0
a=mid:${d}
a=sendrecv`,l+=Tn(v),l+=`
a=rtcp-mux`,l+=xn(f),l+=An(u,m,g,c);break}case"video":{l+=`
m=video 9 UDP/TLS/RTP/SAVPF ${f.map(w=>w.id).join(" ")}
c=IN IP4 0.0.0.0
a=mid:${d}
a=sendrecv`,l+=Tn(v),l+=`
a=rtcp-mux
a=rtcp-rsize`,l+=xn(f),l+=An(u,m,g,c);break}}}return l+=Il(),l+=`
`,l}}class ob{static generateOffer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const r=[n,a];if(!r.length)return`v=0
o=- 1 2 IN IP4 127.0.0.1
s=-
t=0 0
a=msid-semantic: WMS
`;let l=`v=0
o=- 1 2 IN IP4 127.0.0.1
s=-
t=0 0`;t&&t.forEach(d=>{const{hash:h,fingerprint:u,setup:p}=d;l+=`
a=fingerprint:${h} ${u}
a=setup:${p}`}),s&&i&&(l+=`
a=ice-ufrag:${s}
a=ice-pwd:${i}`),l+=`
a=group:BUNDLE 0 1 2
a=extmap-allow-mixed
a=msid-semantic: WMS *`;const c="stream"+r.map(d=>d.ssrc).join("_");for(let d=0;d<r.length;d++){const h=r[d],{type:u,ssrc:p,ssrcGroups:m,payloadTypes:g,rtpExtensions:f}=h;switch(u){case"audio":{l+=`
m=audio 9 UDP/TLS/RTP/SAVPF ${g.map(y=>y.id).join(" ")}
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-options:trickle
a=mid:${d}
a=sendrecv`,l+=Tn(f),p&&(l+=`
a=msid:${c} audio${p}`),l+=`
a=rtcp-mux`,l+=xn(g),l+=An(u,p,m,c);break}case"video":{l+=`
m=video 9 UDP/TLS/RTP/SAVPF ${g.map(y=>y.id).join(" ")}
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-options:trickle
a=mid:${d}
a=sendrecv`,l+=Tn(f),p&&(l+=`
a=msid:${c} video${p}`),l+=`
a=rtcp-mux
a=rtcp-rsize`,l+=xn(g),l+=An(u,p,m,c);break}}}return l+=Il(),l+=`
`,l}static generateAnswer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const r=[n,a];if(!r.length)return`v=0
o=- 1 2 IN IP4 127.0.0.1
s=-
t=0 0
a=msid-semantic: WMS
`;let l=`v=0
o=- 1 2 IN IP4 127.0.0.1
s=-
t=0 0`;t&&t.forEach(d=>{const{hash:h,fingerprint:u,setup:p}=d;l+=`
a=fingerprint:${h} ${u}
a=setup:${p}`}),s&&i&&(l+=`
a=ice-ufrag:${s}
a=ice-pwd:${i}`),l+=`
a=group:BUNDLE 0 1 2
a=extmap-allow-mixed
a=msid-semantic: WMS *`;const c="stream"+r.map(d=>d.ssrc).join("_");for(let d=0;d<r.length;d++){const h=r[d],{type:u,ssrc:p,ssrcGroups:m,payloadTypes:g,rtpExtensions:f}=h;switch(u){case"audio":{l+=`
m=audio 9 UDP/TLS/RTP/SAVPF ${g.map(y=>y.id).join(" ")}
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-options:trickle
a=mid:${d}
a=sendrecv`,l+=Tn(f),p&&(l+=`
a=msid:${c} audio${p}`),l+=`
a=rtcp-mux`,l+=xn(g),l+=An(u,p,m,c);break}case"video":{l+=`
m=video 9 UDP/TLS/RTP/SAVPF ${g.map(y=>y.id).join(" ")}
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-options:trickle
a=mid:${d}
a=sendrecv`,l+=Tn(f),p&&(l+=`
a=msid:${c} video${p}`),l+=`
a=rtcp-mux
a=rtcp-rsize`,l+=xn(g),l+=An(u,p,m,c);break}}}return l+=Il(),l+=`
`,l}}function vF(o){if(!o||!o.startsWith("candidate:"))return;const e=o;o=o.substr(10);const[t,s,i,n,a,r,...l]=o.split(" "),c={sdpString:e,foundation:t,component:s,protocol:i,priority:n,address:{ip:a,port:r}};for(let d=0;d<l.length;d+=2)switch(l[d]){case"typ":{c.type=l[d+1];break}case"raddr":{c.relAddress||(c.relAddress={}),c.relAddress.ip=l[d+1];break}case"rport":{c.relAddress||(c.relAddress={}),c.relAddress.port=l[d+1];break}case"generation":{c.generation=l[d+1];break}case"tcptype":{c.tcpType=l[d+1];break}case"network-id":{c.networkId=l[d+1];break}case"network-cost":{c.networkCost=l[d+1];break}case"ufrag":{c.username=l[d+1];break}}return c}function lb(){return navigator.userAgent.toLowerCase().indexOf("firefox")>-1}function cb(){return navigator.userAgent.toLowerCase().indexOf("safari")>-1&&navigator.userAgent.toLowerCase().indexOf("chrome")===-1}function Tn(o){let e=[];for(let t=0;t<o.length;t++){const s=o[t],{id:i,uri:n}=s;console.log("[extmap] add",i,n),e.push(`a=extmap:${i} ${n}`)}return e.join(`
`)}function xn(o){let e=[];console.log("[SDP] addPayloadTypes",o);for(let t=0;t<o.length;t++){const s=o[t],{id:i,name:n,clockrate:a,channels:r,feedbackTypes:l,parameters:c}=s;if(e.push(`a=rtpmap:${i} ${n}/${a}${r?"/"+r:""}`),l&&l.forEach(d=>{const{type:h,subtype:u}=d;e.push(`a=rtcp-fb:${i} ${[h,u].join(" ")}`)}),c){const d=[];Object.getOwnPropertyNames(c).forEach(h=>{d.push(`${h}=${c[h]}`)}),e.push(`a=fmtp:${i} ${d.join(";")}`)}}return e.join(`
`)}function An(o,e,t,s){let i=[];return t&&t.length>0?t.forEach(n=>{n&&n.ssrcs.length>0&&(i.push(`a=ssrc-group:${n.semantics} ${n.ssrcs.join(" ")}`),n.ssrcs.forEach(a=>{i.push(`a=ssrc:${a} cname:stream${a}`,`a=ssrc:${a} msid:${s} ${o}${a}`,`a=ssrc:${a} mslabel:${o}${a}`,`a=ssrc:${a} label:${o}${a}`)}))}):e&&i.push(`a=ssrc:${e} cname:stream${e}`,`a=ssrc:${e} msid:${s} ${o}${e}`,`a=ssrc:${e} mslabel:${o}${e}`,`a=ssrc:${e} label:${o}${e}`),i.join(`
`)}function Il(o){return`m=application 9 UDP/DTLS/SCTP webrtc-datachannel
c=IN IP4 0.0.0.0
a=ice-options:trickle
a=mid:2
a=sctp-port:5000
a=max-message-size:262144`}class bF{static generateCandidate(e){if(!e)return null;const{sdpString:t,sdpMLineIndex:s,sdpMid:i,foundation:n,component:a,protocol:r,priority:l,address:c,type:d,relAddress:h,generation:u,tcpType:p,networkId:m,networkCost:g,username:f}=e;if(t)return{candidate:t,sdpMLineIndex:s,sdpMid:i};throw"no sdpString"}static generateOffer(e){return lb()?rb.generateOffer(e):cb()?ob.generateOffer(e):ab.generateOffer(e)}static generateAnswer(e){return lb()?rb.generateAnswer(e):cb()?ob.generateAnswer(e):ab.generateAnswer(e)}}class Ah extends cC{constructor(e){super(),this.log=ri("CALL"),this.protocol||(this.protocol=mF()),It(this,e),this.createdAt=Date.now(),this.offerReceived=!1,this.offerSent=!1,this.decryptQueue=[],this.candidates=[],this.addEventListener("state",n=>{this.log("state",Ot[n]),n===Ot.CLOSED&&this.cleanup()});const t=this.streamManager=new oo(aC);t.direction="sendrecv",t.types.push("screencast"),this.isOutgoing||(t.locked=!0,t.canCreateConferenceEntry=!1);let s={"@type":"MediaState",type:"input",lowBattery:!1,muted:!0,screencastState:"inactive",videoRotation:0,videoState:"inactive"};const i=this;s=new Proxy(s,{set:function(n,a,r){return n[a]=r,i.setMediaState(s),i.sendMediaState(),!0}}),this.mediaStates={input:s},this.sendMediaState=ii(this._sendMediaState.bind(this),0,!1,!0)}get connectionState(){const{_connectionState:e,connectionInstance:t}=this;if(e!==void 0)return e;if(t){const{iceConnectionState:s}=t.connection;return s==="closed"?Ot.CLOSED:s!=="connected"&&(!Pi||s!=="completed")?Ot.CONNECTING:Ot.CONNECTED}else return Ot.CONNECTING}get sortIndex(){const e=this.connectionState;let s=(Ot.CLOSED-e+1)*1e13;return s+=2147483647e3-(e===Ot.PENDING&&this.isOutgoing?0:this.createdAt),s}getVideoElement(e){if(e==="input")return this.elements.get("main");{const t=this.getMediaState("output");if(!t)return;const s=t.videoState==="active"?"video":t.screencastState==="active"?"screencast":void 0;if(!s)return;const i=this.description.findEntry(n=>n.type===s);return i?this.elements.get(""+i.recvEntry.source):void 0}}async startScreenSharingInternal(){try{this.wasStartingScreen=!0,this.wasStartingVideo=!1,this.streamManager.types=["audio","screencast"],await this.requestScreen()}catch(e){this.log.error("startScreenSharing error",e)}}async toggleScreenSharing(){return this.isSharingVideo&&await this.stopVideoSharing(),this.isSharingScreen?this.stopVideoSharing():this.startScreenSharingInternal()}async startVideoSharingInternal(){try{this.wasStartingScreen=!1,this.wasStartingVideo=!0,this.streamManager.types=["audio","video"],await this.requestInputSource(!1,!0,!1)}catch(e){this.log.error("startVideoSharing error",e)}}async stopVideoSharing(){const e=this.getMediaState("input");e.videoState=e.screencastState="inactive";const{streamManager:t,description:s}=this,i=t.inputStream.getVideoTracks()[0];i&&(hp(i),t.appendToConference(s))}async toggleVideoSharing(){return this.isSharingScreen&&await this.stopVideoSharing(),this.isSharingVideo?this.stopVideoSharing():this.startVideoSharingInternal()}getMediaState(e){return this.mediaStates[e]}setMediaState(e){this.mediaStates[e.type]=e,this.dispatchEvent("mediaState",e)}isSharingVideoType(e){try{return super.isSharingVideo&&!!(this.wasStartingScreen&&e==="screencast"||this.wasStartingVideo&&e==="video")}catch{return!1}}get isSharingVideo(){return this.isSharingVideoType("video")}get isSharingScreen(){return this.isSharingVideoType("screencast")}get isMuted(){return!this.streamManager.inputStream.getAudioTracks()[0]?.enabled}get isClosing(){const{connectionState:e}=this;return e===Ot.CLOSING||e===Ot.CLOSED}get description(){return this.connectionInstance?.description}setHangUpTimeout(e,t){this.clearHangUpTimeout(),this.hangUpTimeout=Oh.setTimeout(()=>{this.hangUpTimeout=void 0,this.hangUp(t)},e)}clearHangUpTimeout(){this.hangUpTimeout!==void 0&&(clearTimeout(this.hangUpTimeout),this.hangUpTimeout=void 0)}setPhoneCall(e){this.call=e;const{id:t}=e;if(this.id!==t){const s=this.id;this.id=t,this.dispatchEvent("id",t,s)}}async acceptCall(){const e=(await Promise.all(this.dispatchResultableEvent("acceptCallOverride")))[0]??!0;if(this.isClosing||!e)return;this.overrideConnectionState(Ot.EXCHANGING_KEYS);const t=this.call;this.requestInputSource(!0,!!t.pFlags.video,!1);const s=t.g_a_hash;this.managers.appCallsManager.generateDh().then(async i=>(this.dh={g_a_hash:s,b:i.a,g_b:i.g_a,g_b_hash:i.g_a_hash,p:i.p},this.managers.apiManager.invokeApi("phone.acceptCall",{peer:await this.managers.appCallsManager.getCallInput(this.id),protocol:this.protocol,g_b:this.dh.g_b}))).then(async i=>{await this.managers.appCallsManager.savePhonePhoneCall(i)}).catch(i=>{this.log.error("accept call error",i),this.hangUp("phoneCallDiscardReasonHangup")})}joinCall(){this.log("joinCall"),this.getEmojisFingerprint(),this.overrideConnectionState();const{isOutgoing:e,encryptionKey:t,streamManager:s}=this,i=gF(this.call);if(this.log("joinCall configuration",i),!i)return;const n=this.connectionInstance=new dF({call:this,streamManager:s,log:this.log.bindPrefix("connection")}),a=n.createPeerConnection(i);a.addEventListener("iceconnectionstatechange",()=>{const r=this.connectionState;this.connectedAt===void 0&&r===Ot.CONNECTED&&(this.connectedAt=Date.now()),this.dispatchEvent("state",r)}),a.addEventListener("negotiationneeded",()=>{n.negotiate()}),a.addEventListener("icecandidate",r=>{const{candidate:l}=r;a.log("onicecandidate",l),l?.candidate&&this.sendIceCandidate(l)}),a.addEventListener("track",r=>{const{track:l}=r;a.log("ontrack",l),this.onTrack(r)}),n.createDescription(),this.encryptor=new nb(e,t),this.decryptor=new nb(!e,t),this.log("currentCall",this),e&&n.appendStreamToConference(),this.createDataChannel(),this.processDecryptQueue()}createDataChannelEntry(){const e=this.description.createEntry("application");e.setDirection("sendrecv"),e.sendEntry=e.recvEntry=e}createDataChannel(){if(this.connectionInstance.dataChannel)return;const e=this.connectionInstance.createDataChannel({id:0,negotiated:!0});e.addEventListener("message",t=>{this.applyDataChannelData(JSON.parse(t.data))}),e.addEventListener("open",()=>{this.sendMediaState()})}applyDataChannelData(e){switch(e["@type"]){case"MediaState":{e.type="output",this.log("got output media state",e),this.setMediaState(e);break}default:this.log.error("unknown data channel data:",e);break}}_sendMediaState(){const{connectionInstance:e}=this;if(!e)return;const t={...this.getMediaState("input")};delete t.type,this.log("sendMediaState",t),e.sendDataChannelData(t)}async sendCallSignalingData(e){const t=JSON.stringify(e),s=new TextEncoder().encode(t),{bytes:i}=await this.encryptor.encryptRawPacket(s);this.log("sendCallSignalingData",this.id,t),await this.managers.apiManager.invokeApi("phone.sendSignalingData",{peer:await this.managers.appCallsManager.getCallInput(this.id),data:i})}sendIceCandidate(e){this.log("sendIceCandidate",e);const{candidate:t,sdpMLineIndex:s}=e;if(s!==0)return;const i=vF(t);this.sendCallSignalingData({"@type":"Candidates",candidates:[i]})}async confirmCall(){const{protocol:e,id:t,call:s}=this,i=this.dh;this.overrideConnectionState(Ot.EXCHANGING_KEYS);const{key:n,key_fingerprint:a}=await this.managers.appCallsManager.computeKey(s.g_b,i.a,i.p),r=await this.managers.apiManager.invokeApi("phone.confirmCall",{peer:await this.managers.appCallsManager.getCallInput(t),protocol:e,g_a:i.g_a,key_fingerprint:a});this.encryptionKey=n,await this.managers.appCallsManager.savePhonePhoneCall(r),this.joinCall()}getEmojisFingerprint(){return this.emojisFingerprint?this.emojisFingerprint:this.getEmojisFingerprintPromise?this.getEmojisFingerprintPromise:this.getEmojisFingerprintPromise=fe.invokeCrypto("get-emojis-fingerprint",this.encryptionKey,this.dh.g_a).then(e=>(this.getEmojisFingerprintPromise=void 0,this.emojisFingerprint=e.map(t=>Og(t))))}unlockStreamManager(){this.connectionInstance.streamManager.locked=!1,this.connectionInstance.appendStreamToConference()}async doTheMagic(){this.connectionInstance.appendStreamToConference();const e=this.connectionInstance.connection;let t=await e.createAnswer();this.log("[sdp] local",t.type,t.sdp),await e.setLocalDescription(t),e.getTransceivers().filter(l=>l.direction==="recvonly").forEach(l=>{const c=this.connectionInstance.description.getEntryByMid(l.mid);c.transceiver=c.recvEntry.transceiver=l,l.direction="sendrecv"});const s=!1,i=this.description,n=i.entries.map(l=>l.mid),a={type:"offer",sdp:i.generateSdp({bundle:n,entries:i.entries.filter(l=>n.includes(l.mid)),isAnswer:!s})};await e.setRemoteDescription(a),t=await e.createAnswer(),await e.setLocalDescription(t);const r=TI(hu(t.sdp));this.log("[InitialSetup] send 1"),this.sendCallSignalingData(r),this.unlockStreamManager()}overrideConnectionState(e){this._connectionState=e,this.dispatchEvent("state",this.connectionState)}get duration(){return this.connectedAt!==void 0?(Date.now()-this.connectedAt)/1e3|0:0}onInputStream(e){super.onInputStream(e);const t=e.getVideoTracks()[0];if(t){const s=this.getMediaState("input");!this.wasStartingScreen&&!this.wasStartingVideo&&(this.wasStartingVideo=!0),this.isSharingVideo?s.videoState="active":this.isSharingScreen&&(s.screencastState="active"),t.addEventListener("ended",()=>{this.stopVideoSharing()},{once:!0})}e.getAudioTracks().length&&this.onMutedChange()}onMutedChange(){const e=this.isMuted;this.dispatchEvent("muted",e);const t=this.getMediaState("input");t.muted=e}toggleMuted(){return this.requestAudioSource(!0).then(()=>{this.setMuted(),this.onMutedChange()})}async hangUp(e,t){if(!this.isClosing&&(this.discardReason=e,this.log("hangUp",e),this.overrideConnectionState(Ot.CLOSED),this.connectionInstance&&this.connectionInstance.closeConnectionAndStream(!0),e&&!t)){let s=!1;for(const i in this.mediaStates){const n=this.mediaStates[i];s=n.videoState==="active"||n.screencastState==="active"||s}await this.managers.appCallsManager.discardCall(this.id,this.duration,e,s)}}performCodec(e){const t=e.payloadTypes.map(i=>({...i,"rtcp-fbs":i.feedbackTypes}));return{"rtp-hdrexts":e.rtpExtensions,"payload-types":t}}setDataToDescription(e){this.description.setData({transport:{pwd:e.pwd,ufrag:e.ufrag,fingerprints:e.fingerprints,"rtcp-mux":!0},audio:this.performCodec(e.audio),video:e.video?this.performCodec(e.video):void 0,screencast:e.screencast?this.performCodec(e.screencast):void 0})}filterNotVP8(e){this.isOutgoing||[e.video,e.screencast].filter(Boolean).forEach(t=>{const s=t.payloadTypes,i=s.findIndex(r=>r.name==="VP8"),n=s[i],a=s.findIndex(r=>+r.parameters?.apt===n.id);t.payloadTypes=[s[i],s[a]]})}async applyCallSignalingData(e){this.log("applyCallSignalingData",this,e);const{connection:t,description:s}=this.connectionInstance;switch(e["@type"]){case"InitialSetup":{this.log("[sdp] InitialSetup",e),this.filterNotVP8(e),this.setDataToDescription(e);const i=c=>c.map(d=>({_:"groupCallParticipantVideoSourceGroup",semantics:d.semantics,sources:d.ssrcs.map(h=>+h)}));[Th("audio",+e.audio.ssrc),e.video?Th("video",i(e.video.ssrcGroups)):void 0,e.screencast?Th("screencast",i(e.screencast.ssrcGroups)):void 0].filter(Boolean).forEach(c=>{let d=s.getEntryBySource(c.source);if(d)return;const h=s.findFreeSendRecvEntry(c.type,!1);d=new mp(h.mid,c.type),d.setDirection("sendrecv"),h.recvEntry=d,s.setEntrySource(d,c.sourceGroups||c.source)}),this.createDataChannelEntry();const a=this.offerSent;this.offerSent=!1;const r=s.entries.map(c=>c.mid),l={type:a?"answer":"offer",sdp:s.generateSdp({bundle:r,entries:s.entries.filter(c=>r.includes(c.mid)),isAnswer:!a})};this.log("[sdp] remote",l.sdp),await t.setRemoteDescription(l),await this.tryToReleaseCandidates(),a||await this.doTheMagic();break}case"Candidates":{for(const i of e.candidates){const n=bF.generateCandidate(i);n.sdpMLineIndex=0;const a=new RTCIceCandidate(n);this.candidates.push(a)}await this.tryToReleaseCandidates();break}default:this.log.error("unrecognized signaling data",e)}}async tryToReleaseCandidates(){const{connectionInstance:e}=this;if(!e)return;const{connection:t}=e;if(t.remoteDescription){const s=this.candidates.map(i=>this.addIceCandidate(t,i));this.candidates.length=0,await Promise.all(s)}else this.log("[candidates] postpone")}async addIceCandidate(e,t){this.log("[candidate] start",t);try{await e.addIceCandidate(t),this.log("[candidate] add",t)}catch(s){this.log.error("[candidate] error",t,s)}}async processDecryptQueue(){const{encryptor:e}=this;if(!e){this.log.warn("got encrypted signaling data before the encryption key");return}if(!this.decryptQueue.length)return;const s=this.decryptQueue.slice();this.decryptQueue.length=0;for(const i of s){const n=await e.decryptRawPacket(i);if(!n)continue;const a=new TextDecoder().decode(n);try{const r=JSON.parse(a);this.log("[update] updateNewCallSignalingData",r),this.applyCallSignalingData(r)}catch{this.log.error("wrong signaling data",a),this.hangUp("phoneCallDiscardReasonDisconnect"),Yi.dispatchEvent("incompatible",this.interlocutorUserId)}}}onUpdatePhoneCallSignalingData(e){this.decryptQueue.push(e),this.processDecryptQueue()}}async function wF(o){const e=document.createElement("canvas");return e.width=o.videoWidth,e.height=o.videoHeight,e.getContext("2d").drawImage(o,0,0,e.width,e.height),new Promise((s,i)=>{e.toBlob(n=>{n?s(n):i(new Error("Failed to create blob"))})})}class SF extends ee{constructor(e){super("rtmp-output-popup",{overlayClosable:!0,title:!0,body:!0,buttons:[{langKey:"OK",callback:()=>{e.setSinkId(s)}}]}),this.video=e;const t=e.sinkId||"default";let s=t;this.title.append(M("Rtmp.OutputPopup.Title")),navigator.mediaDevices.enumerateDevices().then(i=>{const n=i.filter(r=>r.kind==="audiooutput"),a=Wh(n.map(r=>({textElement:_e(r.label),value:r.deviceId,checked:r.deviceId===t})),r=>{s=r});this._dispose=Hi(()=>j(gp,{name:"fade",mode:"outin",get children(){return j(an,{get when(){return n.length===0},fallback:a,get children(){return Wh([{textElement:M("Rtmp.OutputPopup.Default"),value:"",checked:!0}],r=>{})}})}}),this.body)})}cleanup(){this._dispose()}}const CF=o=>{const[,e]=Xn(o,["class","value"]),t=new _t(e);return ye($s(()=>o.class,(s,i)=>{t.container.classList.remove(i),t.container.classList.add(s)})),ye($s(()=>o.value,s=>{s!==t.value&&(t.value=s)})),t.container},IF="data:image/svg+xml,%3csvg%20width='168'%20height='64'%20viewBox='0%200%20168%2064'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='168'%20height='64'%20rx='10'%20fill='white'/%3e%3ccircle%20cx='35'%20cy='32'%20r='20'%20fill='%234E8EE5'/%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M35%2022C32.7909%2022%2031%2023.7909%2031%2026V31C31%2033.2091%2032.7909%2035%2035%2035C37.2091%2035%2039%2033.2091%2039%2031V26C39%2023.7909%2037.2091%2022%2035%2022ZM27.5%2030C28.0523%2030%2028.5%2030.4477%2028.5%2031C28.5%2034.5899%2031.4101%2037.5%2035%2037.5C38.5899%2037.5%2041.5%2034.5899%2041.5%2031C41.5%2030.4477%2041.9477%2030%2042.5%2030C43.0523%2030%2043.5%2030.4477%2043.5%2031C43.5%2035.3561%2040.2232%2038.9469%2036%2039.4418V41.5C36%2042.0523%2035.5523%2042.5%2035%2042.5C34.4477%2042.5%2034%2042.0523%2034%2041.5V39.4418C29.7768%2038.9469%2026.5%2035.3561%2026.5%2031C26.5%2030.4477%2026.9477%2030%2027.5%2030Z'%20fill='white'/%3e%3cpath%20d='M70%2026V36'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M77%2021V41'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M84%2024V38'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M91%2026V36'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M98%2021V41'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M105%2024V38'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M112%2026V36'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M119%2021V41'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M126%2024V38'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M133%2026V36'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M140%2021V41'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M147%2024V38'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3cpath%20d='M154%2026V36'%20stroke='%234E8EE5'%20stroke-width='4'%20stroke-linecap='round'/%3e%3c/svg%3e",LF=""+new URL("videoVertical-DfKAjRLf.svg",import.meta.url).href,PF=""+new URL("videoHorizontal-DFE8hxwc.svg",import.meta.url).href,MF=ce("<div><img><div>"),EF=ce("<div><div><img><img></div><div>"),_F=ce("<button>"),kF=ce("<div><div><div><br><br></div></div><div><div></div></div><div>"),Qs=(o="")=>`rtmp-record-popup${o}`;class TF extends ee{constructor(){super(Qs(),{overlayClosable:!0,closable:!0,title:!0,body:!0});Lr(this,"_onSubmit",t=>{this.forceHide(),this.managers.appGroupCallsManager.startRecording(Nt.currentCall.inputCall,t).catch(()=>{Ee({langPackKey:"Rtmp.RecordPopup.Failed"})})});this.title.append(M("Rtmp.RecordPopup.Title")),this._dispose=Hi(()=>{const t=this;return j(xF,{get onSubmit(){return t._onSubmit}})},this.body)}cleanup(){super.cleanup(),this._dispose()}}const db=40,xF=o=>{const[e,t]=ne(""),[s,i]=ne(!1),[n,a]=ne(!0),r=new pt({toggle:!0});r.input.addEventListener("change",()=>{i(r.checked)});const l=()=>{o.onSubmit({name:e(),recordVideo:s(),videoHorizontal:n()})};return(()=>{const c=kF(),d=c.firstChild,h=d.firstChild,u=h.firstChild;u.nextSibling;const p=d.nextSibling,m=p.firstChild,g=p.nextSibling;return D(d,j(CF,{get class(){return Qs("-config-name")},get value(){return e()},onRawInput:t,get labelText(){return M("Rtmp.RecordPopup.RecordingTitle").innerText},maxLength:db}),h),D(h,()=>M("Rtmp.RecordPopup.RecordingQuestion"),u),D(h,()=>M("Rtmp.RecordPopup.RecordingHint"),null),D(d,j(hP,{icon:"videocamera",get title(){return M("Rtmp.RecordPopup.AlsoRecordVideo")},checkboxField:r}),null),D(p,j(gp,{name:"fade",mode:"outin",get children(){return[j(an,{get when(){return!s()},get children(){const f=MF(),y=f.firstChild,v=y.nextSibling;return Ti(y,"src",IF),D(v,()=>M("Rtmp.RecordPopup.RecordAudioHint")),Ve(w=>{const b=Qs("-preview-wrap"),S=M("Rtmp.RecordPopup.RecordAudio").innerText,C=ot(Qs("-preview-img"),Qs("-preview-img_audio")),P=Qs("-preview-title");return b!==w._v$&&Ce(f,w._v$=b),S!==w._v$2&&Ti(y,"alt",w._v$2=S),C!==w._v$3&&Ce(y,w._v$3=C),P!==w._v$4&&Ce(v,w._v$4=P),w},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0}),f}}),j(an,{get when(){return s()},get children(){const f=EF(),y=f.firstChild,v=y.firstChild,w=v.nextSibling,b=y.nextSibling;return v.$$click=()=>a(!0),Ti(v,"src",PF),w.$$click=()=>a(!1),Ti(w,"src",LF),D(b,()=>M("Rtmp.RecordPopup.RecordVideoHint")),Ve(S=>{const C=Qs("-preview-wrap"),P=Qs("-preview-images"),L=M("Rtmp.RecordPopup.Horizontal").innerText,E={[Qs("-preview-img")]:!0,[Qs("-preview-img_videoH")]:!0,[Qs("-preview-img_active")]:n()},_=M("Rtmp.RecordPopup.Vertical").innerText,k={[Qs("-preview-img")]:!0,[Qs("-preview-img_videoV")]:!0,[Qs("-preview-img_active")]:!n()},x=Qs("-preview-title");return C!==S._v$5&&Ce(f,S._v$5=C),P!==S._v$6&&Ce(y,S._v$6=P),L!==S._v$7&&Ti(v,"alt",S._v$7=L),S._v$8=pa(v,E,S._v$8),_!==S._v$9&&Ti(w,"alt",S._v$9=_),S._v$10=pa(w,k,S._v$10),x!==S._v$11&&Ce(b,S._v$11=x),S},{_v$5:void 0,_v$6:void 0,_v$7:void 0,_v$8:void 0,_v$9:void 0,_v$10:void 0,_v$11:void 0}),f}})]}}),null),D(g,j(cp,{get children(){const f=_F();return f.$$click=l,D(f,()=>M("Rtmp.RecordPopup.ButtonRecord")),Ve(y=>{const v=e().length>db,w=Qs("-button");return v!==y._v$12&&(f.disabled=y._v$12=v),w!==y._v$13&&Ce(f,y._v$13=w),y},{_v$12:void 0,_v$13:void 0}),f}})),Ve(f=>{const y=Qs("-content"),v=Qs("-config"),w=Qs("-config-text"),b=Qs("-preview"),S=Qs("-preview-shadow");return y!==f._v$14&&Ce(c,f._v$14=y),v!==f._v$15&&Ce(d,f._v$15=v),w!==f._v$16&&Ce(h,f._v$16=w),b!==f._v$17&&Ce(p,f._v$17=b),S!==f._v$18&&Ce(m,f._v$18=S),f},{_v$14:void 0,_v$15:void 0,_v$16:void 0,_v$17:void 0,_v$18:void 0}),c})()};Ui(["click"]);const AF=ce('<div><div><div><svg xmlns=http://www.w3.org/2000/svg width=18 height=18 viewBox="0 0 18 18"fill=none><path d="M9.83591 16.9562C14.23 16.4944 17.4177 12.5579 16.9559 8.16382C16.494 3.76974 12.5575 0.582034 8.16345 1.04387C3.76938 1.50571 0.58167 5.4422 1.04351 9.83627"stroke=white stroke-width=2 stroke-linecap=round></path></svg><div></div></div><div>'),xo=(o="")=>`rtmp-player${o}`,FF=({peerId:o})=>{const[e,t]=ne(""),[s,i]=ne(""),[n,a]=ne(!0);return vr(()=>{I.managers.appGroupCallsManager.fetchRtmpUrl(o).then(async r=>{t(r.url),i(r.key),a(!1)}).catch(()=>{Ee({langPackKey:"Error.AnError"})})}),(()=>{const r=AF(),l=r.firstChild,c=l.firstChild,d=c.firstChild,h=d.nextSibling,u=c.nextSibling;return D(h,()=>M("Rtmp.MediaViewer.Failed.Title")),D(u,()=>M("Rtmp.MediaViewer.Failed.Description")),D(l,j(pC,{get key(){return s()},get url(){return e()},get loading(){return n()},contrast:!0}),null),Ve(p=>{const m=xo("-empty"),g=xo("-empty-text"),f=xo("-empty-header"),y=xo("-empty-loader"),v=xo("-empty-title"),w=xo("-empty-text-inner");return m!==p._v$&&Ce(r,p._v$=m),g!==p._v$2&&Ce(l,p._v$2=g),f!==p._v$3&&Ce(c,p._v$3=f),y!==p._v$4&&Ti(d,"class",p._v$4=y),v!==p._v$5&&Ce(h,p._v$5=v),w!==p._v$6&&Ce(u,p._v$6=w),p},{_v$:void 0,_v$2:void 0,_v$3:void 0,_v$4:void 0,_v$5:void 0,_v$6:void 0}),r})()},hb=15e3,mn=class mn extends Uf{constructor(e){super(new Gu({loadMore:async()=>({count:0,items:[]})}),e?["forward"]:[]),this.shareUrl=e,this.listenerSetter=new Ut,this.onForward=async()=>{const t=await Es.createSharingPicker2();I.managers.appMessagesManager.sendText({peerId:t,text:this.shareUrl}),Ee({langPackKey:"InviteLinkSentSingle",langPackArguments:[await Oe({peerId:t,dialog:!0})]})},this.rejoin=()=>{Nt.currentCall&&Nt.rejoinCall().catch(t=>{this.log.error("rejoinCall",t)}).then(()=>{this.rejoinInterval=window.setTimeout(this.rejoin,hb)})},this.showLoader=()=>{this.videoPlayer.video.parentElement.classList.add("is-buffering"),this.preloaderTemplate.parentElement||this.content.mover.querySelector("canvas.canvas-thumbnail, .thumbnail-avatar").after(this.preloaderTemplate,this.adminPanel),this.preloaderRtmp.attach(this.preloaderTemplate,!0),this.content.mover.querySelector(".controls-live").classList.remove("is-not-buffering"),Nt.currentCall.state=nn.BUFFERING},this.preloaderRtmp=new tn({cancelable:!1,rtmp:!0}),this.preloaderRtmp.construct(),this.preloaderTemplate=document.createElement("div"),this.preloaderTemplate.classList.add("preloader-template"),this.retryTempId=0,this.shareUrl&&this.setBtnMenuToggle([{icon:"forward",text:"Forward",onClick:this.onForward}]),this.buttons.download.classList.add("hide"),this.buttons.zoomin.classList.add("hide"),this.wholeDiv.classList.add("live"),this.setListeners()}setListeners(){super.setListeners(),N(this.buttons.forward,this.onForward,{listenerSetter:this.listenerSetter}),this.listenerSetter.add(fe.serviceMessagePort)("rtmpStreamDestroyed",e=>{Nt.currentCall?.call.id===e&&this.retryLoadStream(this.videoPlayer.video,"was destroyed")})}async openMedia(e){const t=e.peerId.toChatId();(!Nt.currentCall||Nt.currentCall.peerId!==e.peerId)&&(Nt.currentCall&&await Nt.leaveCall(),await Nt.joinCall(t)),mn.activeInstance=this,this.peerId=e.peerId;const s=fe.getChat(t);if(ui(s)[0])this.shareUrl=qv(this.peerId);else{const i=await this.managers.appProfileManager.getChatFull(t);this.shareUrl=i.exported_invite?.link}await this._openMedia({media:Nt.currentCall.inputCall,mediaThumbnail:e.peerId===mn.previousPeerId?mn.previousCapture:void 0,timestamp:0,fromId:e.peerId,fromRight:0,setupPlayer:(i,n)=>{const a=i.video,r=()=>Nt.currentCall;i.updateLiveViewersCount(r().call.participants_count),(!Pi||e.isAdmin)&&i.setupLiveMenu([{icon:"volume_up",text:"Rtmp.MediaViewer.Menu.OutputDevice",onClick:()=>ee.createPopup(SF,i.video).show(),verify:()=>typeof navigator.mediaDevices?.enumerateDevices=="function"&&!Pi},{icon:"radioon",text:"Rtmp.MediaViewer.Menu.StartRecording",verify:()=>r()?.admin&&!r().call.pFlags.record_video_active,onClick:()=>ee.createPopup(TF).show()},{icon:"radiooff",text:"Rtmp.MediaViewer.Menu.StopRecording",verify:()=>r()?.admin&&r().call.pFlags.record_video_active,onClick:()=>{this.managers.appGroupCallsManager.stopRecording(r().inputCall).catch(()=>{Ee({langPackKey:"Error.AnError"})})}},{icon:"settings",text:"Rtmp.MediaViewer.Menu.StreamSettings",verify:()=>r()?.admin,onClick:()=>{ee.createPopup(mC,{peerId:this.peerId,active:!0,onEndStream:()=>this.close(void 0,!0)}).show()}},{icon:"crossround",text:"Rtmp.MediaViewer.Menu.EndLiveStream",danger:!0,verify:()=>r()?.admin,onClick:()=>this.close(void 0,!0)}]);const l=()=>{!a.error&&!a.ended&&wi(a)};this.listenerSetter.add(a)("pause",l);const d=this.content.mover.querySelector("canvas.canvas-thumbnail, .thumbnail-avatar");a.after(d);const h=d.tagName==="CANVAS"?d:this.content.mover.querySelector("img");i.emptyPipVideoSource=h,n.then(()=>{i.dimBackground()})},onMoverSet:()=>{if(!e.isAdmin)return;const i=document.createElement("div");i.classList.add("admin-popup-container"),this.adminPanel=i,this.adminPanel.classList.add("admin-hidden"),this.disposeSolid=Hi(()=>FF({peerId:e.peerId}),this.adminPanel)},onCanPlay:()=>{const i=this.content.mover.querySelector("canvas.canvas-thumbnail, .thumbnail-avatar");this.streamEnded||this.preloaderRtmp.detach(),this.videoPlayer.liveEl.classList.add("is-not-buffering"),e.isAdmin&&bt({element:this.adminPanel,className:"is-not-buffering",forwards:!0,duration:300}),bt({element:i,className:"hide-thumbnail",forwards:!0,duration:300}),Nt.currentCall.state=nn.PLAYING},onBuffering:this.showLoader}),this.listenerSetter.add(Nt)("currentCallChanged",i=>{if(!i){this.close(void 0,!0);return}this.videoPlayer?.updateLiveViewersCount(i.call.participants_count)}),this.rejoinInterval=window.setTimeout(this.rejoin,hb)}toggleAdminPanel(e){e&&this.videoPlayer&&(this.videoPlayer.cancelFullScreen(),this.videoPlayer.inPip&&document.exitPictureInPicture()),this.videoPlayer?.lockControls(e?!0:void 0),bt({element:this.adminPanel,className:"admin-hidden",forwards:!e,duration:300})}retryLoadStream(e,t){const s=++this.retryTempId,i=this.log.bindPrefix(`retryLoadStream-${s}-${t}`),n=Nt.currentCall?.call.id;if(!n){this.close(void 0,!0);return}let a=!0,r=!0,l=0;const c=()=>s===this.retryTempId,d=()=>{c()&&(clearTimeout(this.retryTimeout),Nt.isCurrentCallDead(r).then(h=>{if(Nt.currentCall?.call.id!==n||!c())return;if(i("empty",h,a,r),r=h==="dying",h==="dead"||h==="dying"){a&&(this.showLoader(),Nt.currentCall?.admin&&this.toggleAdminPanel(!0),Pi&&fe.serviceMessagePort.invokeVoid("leaveRtmpCall",[Nt.currentCall.call.id,!1])),a=!1,this.retryTimeout=window.setTimeout(d,1e3);return}Nt.currentCall?.admin&&this.toggleAdminPanel(!1);const u=iI(Nt.currentCall.inputCall);e.getAttribute("src")!==u&&(e.src=u,e.load(),wi(e))}).catch(h=>{Nt.currentCall?.call.id!==n||!c()||(++l>5?(i.error(h),Ee({langPackKey:"Error.AnError"}),this.close(void 0,!0)):this.retryTimeout=window.setTimeout(d,1e3))}))};d()}async leaveCall(e=!1){Nt.leaveCall(e).catch(()=>{Ee({langPackKey:"Error.AnError"})})}async close(e,t=!1){const s=this.videoPlayer?.inPip;if(clearTimeout(this.retryTimeout),clearTimeout(this.rejoinInterval),++this.retryTempId,this.videoPlayer)try{const i=await wF(this.videoPlayer.video);mn.previousCapture&&URL.revokeObjectURL(mn.previousCapture),mn.previousCapture=URL.createObjectURL(i),mn.previousPeerId=this.peerId}catch{}super.close(e),mn.activeInstance=void 0,Nt.currentCall&&this.leaveCall(t),this.listenerSetter.removeAll(),s&&document.exitPictureInPicture()}static closeActivePip(e=!1){mn.activeInstance&&mn.activeInstance.videoPlayer?.inPip&&document.exitPictureInPicture()}static async getShareUrl(e){const t=fe.getChat(e);return ui(t)[0]?qv(e.toPeerId(!0)):(await I.managers.appProfileManager.getChatFull(e)).exported_invite?.link}};mn.previousPeerId=Tt;let Jo=mn;class RF{constructor(e,t){this.appendTo=e,this.appendLiveTo=t,this.descriptionIntl=new ke.IntlElement({key:"VoiceChat.Status.Connecting"}),this.descriptionIntl.element.classList.add("rtmp-description"),this.liveTextElement=M("Rtmp.MediaViewer.Live")}detach(){this.descriptionIntl.element.remove(),this.liveTextElement.remove()}update(e){let t,s;e.state!==nn.PLAYING?t="VoiceChat.Status.Connecting":(t="Rtmp.Watching",s=[Xg(e.call.participants_count)]);const{descriptionIntl:i}=this;i.compareAndUpdate({key:t,args:s}),this.descriptionIntl.element.parentElement||this.appendTo.append(this.descriptionIntl.element),this.liveTextElement.parentElement||this.appendLiveTo.append(this.liveTextElement)}}function DF(o,e){switch(o){case Ot.CLOSING:case Ot.CLOSED:return hs.CLOSED;case Ot.CONNECTED:return e?hs.MUTED:hs.UNMUTED;default:return hs.CONNECTING}}function BF(o){switch(o){case nn.CLOSED:return hs.CLOSED;case nn.CONNECTING:case nn.BUFFERING:return hs.CONNECTING;default:return hs.MUTED_BY_ADMIN}}const tc="topbar-call";class NF{constructor(e){this.managers=e,this.onState=()=>{this.updateInstance(this.instance)};const t=this.listenerSetter=new Ut;t.add(Yi)("instance",({instance:s})=>{this.instance||this.updateInstance(s)}),t.add(Yi)("accepting",s=>{this.instance!==s&&this.updateInstance(s)}),t.add(zn)("instance",s=>{this.updateInstance(s)}),t.add(I)("group_call_update",s=>{const i=zn.groupCall;i?.id===s.id&&this.updateInstance(i)}),t.add(Nt)("currentCallChanged",s=>{this.updateInstance(s)}),t.add(oo.ANALYSER_LISTENER)("amplitude",({amplitudes:s,type:i})=>{const{weave:n}=this;if(!s.length||!n)return;let a=0;for(let r=0;r<s.length;++r){const{type:l,value:c}=s[r];a=c>a?c:a}n.setAmplitude(a)})}clearCurrentInstance(){this.instance&&(this.center.replaceChildren(),this.currentDescription&&(this.currentDescription.detach(),this.currentDescription=void 0),this.instance=void 0,this.instanceListenerSetter.removeAll())}updateInstance(e){this.construct&&(this.construct(),this.construct=void 0);const t=[["group-call",Ar],["call",Ah],["rtmp",Nn]],s=this.instance!==e;s&&(this.clearCurrentInstance(),this.instance=e,this.instanceListenerSetter=new Ut,e&&(this.instanceListenerSetter.add(e)("state",this.onState),e instanceof Ar?this.currentDescription=this.groupCallDescription:e instanceof Ah?(this.currentDescription=this.callDescription,this.instanceListenerSetter.add(e)("muted",this.onState)):e instanceof Nn&&(this.currentDescription=this.rtmpDescription),t.forEach(([l,c])=>{const d=e instanceof c;this.container.classList.toggle(`is-${l}`,d),d&&document.documentElement.style.setProperty("--topbar-call-height",`var(--topbar-call-${l}-height)`)})));const i=e instanceof Nn?void 0:!e||this.instance.isMuted;let n;e?e instanceof Ar?n=e.state:e instanceof Nn?n=BF(e.state):n=DF(e.connectionState,i):n=hs.CLOSED;const{weave:a}=this;a.componentDidMount();const r=n===hs.CLOSED;(!document.body.classList.contains("is-calling")||s||r)&&(r&&a.setAmplitude(0),bt({element:document.body,className:"is-calling",forwards:!r,duration:250,onTransitionEnd:r?()=>{a.componentWillUnmount(),this.clearCurrentInstance()}:void 0})),!r&&(a.setCurrentState(e instanceof Nn?"rtmp":"group",e instanceof Nn?e.state:n,!0),this.setTitle(e),this.setDescription(e),this.muteButton.classList.toggle("hide",i===void 0),i!==void 0&&this.groupCallMicrophoneIconMini.setState(!i),this.endButton.classList.toggle("hide",e instanceof Nn))}setDescription(e){return this.currentDescription.update(e)}setTitle(e){if(e instanceof Nn)dt(this.center,new Rt({peerId:e.peerId}).element);else{if(e instanceof Ar)return this.groupCallTitle.update(e);dt(this.center,new Rt({peerId:e.interlocutorUserId.toPeerId()}).element)}}construct(){const{listenerSetter:e}=this,t=this.container=document.createElement("div");t.classList.add("sidebar-header",tc+"-container");const s=document.createElement("div");s.classList.add(tc+"-left");const i=this.groupCallMicrophoneIconMini=new yg,n=this.muteButton=it();n.append(i.container),s.append(n);const a=ma(()=>{this.instance.toggleMuted()},600,!0);N(n,u=>{oe(u),a()},{listenerSetter:e});const r=this.center=document.createElement("div");r.classList.add(tc+"-center"),this.groupCallTitle=new CI(r),this.groupCallDescription=new gg(s),this.callDescription=new MI(s),this.rtmpDescription=new RF(r,s);const l=document.createElement("div");l.classList.add(tc+"-right");const c=this.endButton=it("endcall_filled");l.append(c),N(c,u=>{oe(u);const{instance:p}=this;p&&(p instanceof Nn?Nt.leaveCall():p instanceof Ar?p.hangUp():p.hangUp("phoneCallDiscardReasonHangup"))},{listenerSetter:e}),N(t,()=>{if(this.instance instanceof Nn)Jo.closeActivePip();else if(this.instance instanceof Ar){if(ee.getPopups(Su).length)return;ee.createPopup(Su).show()}else if(this.instance instanceof Ah){if(ee.getPopups(vg).find(p=>p.getCallInstance()===this.instance))return;ee.createPopup(vg,this.instance).show()}},{listenerSetter:e}),t.append(s,r,l);const d=this.weave=new J2,h=d.render(tc+"-weave");t.prepend(h),document.getElementById("column-center").prepend(t),d.componentDidMount()}}const OF="assets/img/logo_filled_rounded.png",UF="assets/img/logo_plain.svg";class HF{constructor(){this.notificationsShown={},this.notificationIndex=0,this.notificationsCount=0,this.soundsPlayed={},this.vibrateSupport=NL,this.faviconElements=Array.from(document.head.querySelectorAll('link[rel="icon"], link[rel="alternate icon"]')),this.titleBackup=document.title,this.titleChanged=!1,this.stopped=!1,this.settings={},this.pushInited=!1,this.updateLocalSettings=()=>{const t=["notify_nodesktop","notify_volume","notify_novibrate","notify_nopreview","notify_nopush"].map(()=>{});Promise.all(t).then(s=>{if(this.settings.nodesktop=s[0],this.settings.volume=s[1]===void 0?.5:s[1],this.settings.novibrate=s[2],this.settings.nopreview=s[3],this.settings.nopush=s[4],this.pushInited){const i=!this.settings.nopush&&!this.settings.nodesktop&&pn.isAvailable||!1,n=this.registeredDevice!==!1;i!==n&&(i?pn.subscribe():pn.unsubscribe())}pn.setSettings(this.settings)}),fe.getState().then(s=>{this.settings.nosound=!s.settings.notifications.sound})},this.requestPermission=()=>{Notification.requestPermission(),window.removeEventListener("click",this.requestPermission)},this.clear=()=>{this.log.warn("clear");for(const e in this.notificationsShown){const t=this.notificationsShown[e];this.closeNotification(t)}this.notificationsShown={},this.notificationsCount=0,pn.hidePushNotifications()}}construct(e){this.managers=e,this.log=ri("NOTIFICATIONS"),this.notificationsQueue=new Kb(1),navigator.vibrate=navigator.vibrate||navigator.mozVibrate||navigator.webkitVibrate,this.setAppBadge=navigator.setAppBadge?.bind(navigator),this.setAppBadge?.(0),this.notificationsUiSupport="Notification"in window||"mozNotification"in navigator,this.notifySoundEl=document.createElement("div"),this.notifySoundEl.id="notify-sound",document.body.append(this.notifySoundEl),this.topMessagesDeferred=Pt(),ir.addEventListener("deactivated",()=>{this.stop()}),ir.addEventListener("activated",()=>{this.stopped&&this.start()}),xa.addEventListener("change",t=>{this.stopped||(t||this.clear(),this.toggleToggler())}),I.addEventListener("notification_reset",t=>{this.soundReset(t)}),I.addEventListener("notification_cancel",t=>{this.cancel(t)}),this.setAppBadge&&I.addEventListener("folder_unread",t=>{t.id===0&&this.setAppBadge(t.unreadUnmutedPeerIds.size)}),pn.addEventListener("push_init",t=>{this.pushInited=!0,!this.settings.nodesktop&&!this.settings.nopush?t?this.registerDevice(t):pn.subscribe():this.unregisterDevice(t)}),pn.addEventListener("push_subscribe",t=>{this.registerDevice(t)}),pn.addEventListener("push_unsubscribe",t=>{this.unregisterDevice(t)}),I.addEventListener("dialogs_multiupdate",()=>{this.topMessagesDeferred.resolve()},{once:!0}),pn.addEventListener("push_notification_click",t=>{if(t.action==="push_settings")return;if(t.action==="mute1d"){this.managers.apiManager.invokeApi("account.updateDeviceLocked",{period:86400}).then(()=>{});return}const s=t.custom&&t.custom.peerId.toPeerId();console.log("click",t,s),s&&this.topMessagesDeferred.then(async()=>{const i=s.isAnyChat()?s.toChatId():void 0;let n;if(i){if(!await this.managers.appChatsManager.hasChat(i))return;n=await this.managers.appChatsManager.isChannel(i)?i:void 0}!i&&!await this.managers.appUsersManager.hasUser(s.toUserId())||me.setInnerPeer({peerId:s,lastMsgId:await this.managers.appMessagesIdsManager.generateMessageId(+t.custom.msg_id,n)})})})}async buildNotificationQueue(e){this.notificationsQueue.push({load:()=>this.buildNotification(e)})}async buildNotification({message:e,fwdCount:t,peerReaction:s,peerTypeNotifySettings:i}){const n=e.peerId,a=n.isAnyChat(),r={},[l,c=!1,d]=await Promise.all([this.managers.appPeersManager.getPeerString(n),a&&this.managers.appPeersManager.isForum(n),fe.getPeer(n)]);let h,u=!1;if(i.show_previews)if(e._==="message"&&e.fwd_from&&t>1)h=ke.format("Notifications.Forwarded",!0,[t]);else{h=await hr({message:e,plain:!0});const b=s?.reaction;if(b&&b._!=="reactionEmpty"){let S=b.emoticon;S||(S=(await this.managers.appEmojiManager.getCustomEmojiDocument(b.document_id)).stickerEmojiRaw);const C="Notification.Contact.Reacted",P=[Wg(S),h];h=ke.format(C,!0,P)}else u=!0}else h=ke.format("Notifications.New",!0);s&&(r.noIncrement=!0,r.silent=!0);const p={plainText:!0,managers:this.managers},m=c?ha(e,c):void 0,g=s?at(s.peer_id):e.fromId,f=r.title=await ar({...p,peerId:n,threadId:m});if(c){const b=await ar({...p,peerId:n});r.title+=` (${b})`,u&&g!==e.peerId&&(h=await ar({...p,peerId:g})+": "+h)}else a&&g!==e.peerId&&(r.title=await ar({...p,peerId:g})+" @ "+r.title);r.title=vo(r.title),r.onclick=()=>{me.setInnerPeer({peerId:n,lastMsgId:e.mid,threadId:m})},r.message=h,r.key="msg"+e.mid,r.tag=l,r.silent=!0;const y=await this.managers.appPeersManager.getPeerPhoto(n);if(y){const b=await this.managers.appAvatarsManager.loadAvatar(n,y,"photo_small");if(!s&&(e=await this.managers.appMessagesManager.getMessageByPeer(e.peerId,e.mid),!e||!e.pFlags.unread))return;r.image=b}else{let{avatarCanvas:b,avatarContext:S}=this;if(this.avatarCanvas)S.clearRect(0,0,b.width,b.height);else{b=this.avatarCanvas=document.createElement("canvas"),S=this.avatarContext=b.getContext("2d");const _=54,k=1;b.dpr=k,b.width=b.height=_*k,this.avatarGradients={}}const C=km(d);let P=this.avatarGradients[C];if(!P){P=this.avatarGradients[C]=S.createLinearGradient(b.width/2,0,b.width/2,b.height);const _=Ls.getProperty(`peer-avatar-${C}-top`),k=Ls.getProperty(`peer-avatar-${C}-bottom`);P.addColorStop(0,_),P.addColorStop(1,k)}S.fillStyle=P,Dw(S,b.width/2,b.height/2,b.width/2),S.fill();const L=20*b.dpr,E=zg(f);S.font=`700 ${L}px ${dl}`,S.textBaseline="middle",S.textAlign="center",S.fillStyle="white",S.fillText(E.text,b.width/2,b.height*(window.devicePixelRatio>1,.5625)),r.image=b.toDataURL()}const v={custom:{msg_id:""+e.mid,peerId:""+n},description:"",loc_key:"",loc_args:[],mute:"",random_id:0,title:""};await this.notify(r,v)&&this.registeredDevice&&pn.ignorePushByMid(n,e.mid)}toggleToggler(e=xa.isIdle){if(Oi)return;const t=s=>{this.titleChanged=!1,document.title=this.titleBackup,this.setFavicon()};window.clearInterval(this.titleInterval),this.titleInterval=0,e?this.titleInterval=window.setInterval(()=>{const s=this.notificationsCount;if(!s)this.toggleToggler(!1);else if(this.titleChanged)t();else{this.titleChanged=!0,document.title=ke.format("Notifications.Count",!0,[s]);const i=document.createElement("canvas");i.width=32*window.devicePixelRatio,i.height=i.width;const n=i.getContext("2d");n.beginPath(),n.arc(i.width/2,i.height/2,i.width/2,0,2*Math.PI,!1),n.fillStyle="#3390ec",n.fill();let a=24,r=""+s;s<10?a=22:s<100?a=20:(r="99+",a=16),a*=window.devicePixelRatio,n.font=`700 ${a}px ${dl}`,n.textBaseline="middle",n.textAlign="center",n.fillStyle="white",n.fillText(r,i.width/2,i.height*.5625),this.setFavicon(i.toDataURL())}},1e3):t()}setFavicon(e){this.prevFavicon!==e&&(this.prevFavicon=e,this.faviconElements.forEach((t,s,i)=>{var a;const n=t.cloneNode();(a=n.dataset).href||(a.href=n.href),e??(e=n.dataset.href),n.href=e,t.replaceWith(i[s]=n)}))}async notify(e,t){if(this.log("notify",e,xa.isIdle,this.notificationsUiSupport,this.stopped),this.stopped)return;e.image||(e.image=OF),e.noIncrement||++this.notificationsCount,this.titleInterval||this.toggleToggler();const s=++this.notificationIndex,i=e.key||"k"+s;this.notificationsShown[i]=!0;const n=Ms();if(this.settings.volume>0&&!this.settings.nosound&&(this.testSound(this.settings.volume),this.soundsPlayed[e.tag]=n),!this.notificationsUiSupport||"Notification"in window&&Notification.permission!=="granted")return;if(this.settings.nodesktop){if(this.vibrateSupport&&!this.settings.novibrate){navigator.vibrate([200,100,200]);return}return}if(!("Notification"in window))return;let a;const r={badge:UF,icon:e.image||"",body:e.message||"",tag:e.tag||"",silent:e.silent||!1,data:t};try{if(e.tag)for(const l in this.notificationsShown){const c=this.notificationsShown[l];typeof c!="boolean"&&c.tag===e.tag&&(c.hidden=!0)}a=new Notification(e.title,r)}catch{try{const c=await navigator.serviceWorker.ready;await c.showNotification(e.title,r);const d=await c.getNotifications({tag:r.tag});a=d[d.length-1]}catch(c){this.log.error("creating push error",c,e,r)}if(!a){this.notificationsUiSupport=!1,pn.setLocalNotificationsDisabled();return}}return a.onclick=()=>{this.log("notification onclick"),a.close(),Rb.focus(),this.clear(),e.onclick?.()},a.onclose=()=>{this.log("notification onclose"),a.hidden||(delete this.notificationsShown[i],this.clear())},a.show?.(),this.notificationsShown[i]=a,Oi||setTimeout(()=>{this.hide(i)},8e3),!0}getLocalSettings(){return this.settings}hide(e){const t=this.notificationsShown[e];t&&this.closeNotification(t)}soundReset(e){delete this.soundsPlayed[e]}testSound(e){const t=Ms();if(this.nextSoundAt&&t<this.nextSoundAt&&this.prevSoundVolume===e)return;this.nextSoundAt=t+1e3,this.prevSoundVolume=e;const s="assets/audio/notification.mp3",i=document.createElement("audio");i.autoplay=!0,i.setAttribute("mozaudiochannel","notification"),i.volume=e,i.innerHTML=`
<source src="${s}" type="audio/mpeg" />
<embed hidden="true" autostart="true" loop="false" volume="${e*100}" src="${s}" />
`,this.notifySoundEl.append(i),i.addEventListener("ended",()=>{i.remove()},{once:!0})}cancel(e){const t=this.notificationsShown[e];this.log("cancel",e,t),t&&(this.notificationsCount>0&&--this.notificationsCount,this.closeNotification(t),delete this.notificationsShown[e])}closeNotification(e){try{typeof e!="boolean"&&e.close&&(this.log("close notification",e),e.hidden=!0,e.close())}catch{}}start(){if(this.log("start"),this.stopped=!1,this.updateLocalSettings(),I.addEventListener("settings_updated",this.updateLocalSettings),fe.getState().then(e=>{this.stopped||!e.keepSigned||pn.start()}),!this.notificationsUiSupport)return!1;"Notification"in window&&Notification.permission!=="granted"&&Notification.permission!=="denied"&&window.addEventListener("click",this.requestPermission);try{"onbeforeunload"in window&&window.addEventListener("beforeunload",this.clear)}catch{}}stop(){this.log("stop"),this.clear(),window.clearInterval(this.titleInterval),this.titleInterval=0,this.setFavicon(),this.stopped=!0}registerDevice(e){if(this.registeredDevice&&Di(this.registeredDevice,e))return!1;this.managers.apiManager.invokeApi("account.registerDevice",{token_type:e.tokenType,token:e.tokenValue,other_uids:[],app_sandbox:!1,secret:new Uint8Array}).then(()=>{this.log("registered device"),this.registeredDevice=e},t=>{t.handled=!0})}unregisterDevice(e){if(!this.registeredDevice)return!1;this.managers.apiManager.invokeApi("account.unregisterDevice",{token_type:e.tokenType,token:e.tokenValue,other_uids:[]}).then(()=>{this.registeredDevice=!1},t=>{t.handled=!0})}}const Fh=new HF;Ws&&(Ws.uiNotificationsManager=Fh);async function ub(o,e=!1){const t=[],s=async(i,n)=>{if(i.isDirectory){const a=i.createReader();await new Promise((r,l)=>{a.readEntries(async c=>{for(const d of c)await s(d,n);r()})})}else if(i)if(e)t.push(i.type);else{const a=n.getAsFile(),r=i instanceof File?i:i instanceof DataTransferItem?i.getAsFile():await new Promise((l,c)=>i.file(l,d=>l(a)));if(!r)return;t.push(r)}};if(o instanceof DragEvent&&o.dataTransfer.files&&!o.dataTransfer.items)for(let i=0;i<o.dataTransfer.files.length;i++){const n=o.dataTransfer.files[i];t.push(e?n.type:n)}else{const i=(o.dataTransfer||o.clipboardData||o.originalEvent.clipboardData).items,n=[];for(let a=0;a<i.length;++a){const r=i[a];if(r.kind==="file"){const l=(e?r:r.webkitGetAsEntry())||r.getAsFile();n.push(s(l,r))}}await Promise.all(n)}return t}const Xa="popup-gift-premium";class $F extends ee{constructor(e,t){super(Xa,{closable:!0,overlayClosable:!0,body:!0,scrollable:!0}),this.peerId=e,this.giftOptions=t,this.construct()}async construct(){const{peerId:e,giftOptions:t}=this,s=es({middleware:this.middlewareHelper.get(),size:100,peerId:e});s.node.classList.add(Xa+"-avatar");const i=document.createElement("span");Zt(i,"GiftTelegramPremiumTitle"),i.classList.add(Xa+"-title");const n=M("GiftTelegramPremiumDescription",[await Oe({peerId:e})]);n.classList.add(Xa+"-subtitle");const a=this.giftOptions.slice().sort((p,m)=>p.months-m.months)[0],r=p=>In(p,a.currency,!1,!0,!0),l=this.giftOptions.map((p,m)=>{let g=M("PricePerMonth",[r(+p.amount/p.months)]);if(p!==a){const w=document.createElement("span"),b=document.createElement("span");b.classList.add(Xa+"-discount");const S=+a.amount*p.months/a.months,C=Math.round((1-+p.amount/S)*100);b.textContent="-"+C+"%",w.append(b,g),g=w}const f=!(p.months%12),y=new pt({checked:m===0,round:!0,name:"gift-months",asRadio:!0}),v=new ve({title:M(f?"Years":"Months",[f?p.months/12:p.months]),checkboxField:y,clickable:!0,subtitle:g,rightTextContent:r(p.amount)});return v.container.classList.add(Xa+"-option"),v}),c=document.createElement("form");c.classList.add(Xa+"-options"),c.append(...l.map(p=>p.container));const d=new ke.IntlElement({key:"GiftSubscriptionFor",args:[r(t[0].amount)]}),h=()=>t[l.findIndex(p=>p.checkboxField.checked)];this.listenerSetter.add(c)("change",()=>{d.compareAndUpdate({args:[r(h().amount)]})});const u=ze(`btn-primary ${Xa}-confirm shimmer`);u.append(d.element),N(u,()=>{const p=h();me.openUrl(p.bot_url),this.hide()},{listenerSetter:this.listenerSetter}),this.scrollable.append(s.node,i,n,c,u),this.show()}}const VF=["allow-scripts","allow-same-origin","allow-popups","allow-forms","allow-modals","allow-storage-access-by-user-activation"].join(" ");class GF extends ee{constructor(e){super("popup-payment popup-payment-verification popup-web-app",{closable:!0,overlayClosable:!0,body:!0,footer:!0,title:_e(e.attachMenuBot?.short_name),onBackClick:()=>(this.telegramWebView.dispatchWebViewEvent("back_button_pressed",void 0),!1),isConfirmationNeededOnClose:()=>{if(this.isCloseConfirmationNeeded)return Ct({descriptionLangKey:"BotWebViewChangesMayNotBeSaved",button:{isDanger:!0,langKey:"BotWebViewCloseAnyway"}})}}),this.sendTheme=()=>{this.telegramWebView.dispatchWebViewEvent("theme_changed",{theme_params:this.getThemeParams()})},this.setHeaderColor=(n=this.lastHeaderColor)=>{this.lastHeaderColor=n;let a;const r=n.color;if(r){const l=_n(r),c=$L(l),d=HL(c),h=OL(c,2.5),u=UL([...d,h],l);a=r,this.title.style.color=`rgb(${d.join(",")})`,this.header.style.setProperty("--secondary-text-color",`rgb(${u.join(", ")})`),this.header.style.setProperty("--light-secondary-text-color",`rgba(${d.join(", ")}, ${.08})`),this.header.style.setProperty("--border-color",`rgba(${d.join(", ")}, ${.08})`)}else a=this.getThemeParams()[n.color_key],this.title.style.color="",this.header.style.removeProperty("--secondary-text-color"),this.header.style.removeProperty("--light-secondary-text-color"),this.header.style.removeProperty("--border-color");this.header.style.backgroundColor=a},this.setBodyColor=n=>{this.body.style.backgroundColor=n},this.switchInlineQuery=async({query:n,chat_types:a})=>{if((await this.managers.appUsersManager.getUser(this.webViewOptions.botId)).bot_inline_placeholder===void 0)return;this.forceHide();const l=me.chat;let c=l.peerId,d=l.threadId;if(a?.length){const h=await Es.createPicker(a,["send_inline"]);c!==h&&(c=h,d=void 0,await me.setInnerPeer({peerId:c}))}this.managers.appInlineBotsManager.switchInlineQuery(c,d,this.webViewOptions.botId,n)},this.setupMainButton=({is_visible:n,is_active:a,is_progress_visible:r,color:l,text:c,text_color:d})=>{n=n&&!!c?.trim(),c&&this.mainButton.replaceChildren(_e(c)),l&&as.applyAppColor({name:"primary-color",element:this.mainButton,hex:l,darkenAlpha:.04}),d&&(this.mainButton.style.color=d),this.footer.classList.toggle("is-visible",n)},this.setupBackButton=({is_visible:n})=>{this.btnCloseAnimatedIcon.classList.toggle("state-back",n)},this.setupSettingsButton=({is_visible:n})=>{this.showSettingsButton=n},this.openPopup=async({title:n,message:a,buttons:r})=>{const l={cancel:"Cancel",close:"Close",ok:"OK"};let c;const d=ee.createPopup(Ss,"popup-confirmation",{title:n?_e(n):void 0,description:_e(a),buttons:r.map(({type:u,text:p,id:m})=>{const g=l[u];return{langKey:g,text:g?void 0:_e(p),isCancel:!0,isDanger:u==="destructive",callback:()=>{c=m}}})}),h=new Promise(u=>{d.addEventListener("close",()=>{this.telegramWebView.dispatchWebViewEvent("popup_closed",{...c!==void 0?{button_id:c}:{}}),u()})});return d.show(),h},It(this,e);const t=this.webViewOptions.botId,s=t.toPeerId();console.log(this);const i=ai({listenerSetter:this.listenerSetter,buttons:[{icon:"settings",text:"BotSettings",onClick:()=>{this.telegramWebView.dispatchWebViewEvent("settings_button_pressed",void 0)},verify:()=>this.showSettingsButton},{icon:"bots",text:"BotWebViewOpenBot",onClick:()=>{this.forceHide(),me.setInnerPeer({peerId:s})},verify:()=>this.webViewOptions.peerId!==s},{icon:"rotate_left",text:"BotWebViewReloadPage",onClick:()=>{const n=()=>{const a=this.telegramWebView,r=this.createWebView();a.iframe.replaceWith(r.iframe),a.destroy(),r.onMount()};if(!this.readyResult?.reload_supported){n();return}this.reloadTimeout=window.setTimeout(()=>{this.reloadTimeout=void 0,n()},300),this.telegramWebView.dispatchWebViewEvent("reload_iframe",void 0)},verify:()=>!0},{icon:"delete",className:"danger",text:"BotWebViewDeleteBot",onClick:()=>{me.toggleBotInAttachMenu(t,!1).then(async n=>{this.attachMenuBot=n,this.forceHide()})},verify:()=>this.attachMenuBot&&!this.attachMenuBot.pFlags.inactive,separator:!0}],direction:"bottom-left"});if(this.title.after(i),this.mainButton=ze("btn-primary btn-color-primary",{noRipple:!0}),this.footer.append(this.mainButton),this.body.after(this.footer),N(this.mainButton,()=>{this.telegramWebView.dispatchWebViewEvent("main_button_pressed",void 0)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(I)("theme_changed",()=>{this.setHeaderColor(),this.sendTheme()}),this.listenerSetter.add(I)("attach_menu_bot",n=>{this.webViewOptions.botId===n.bot_id&&(this.attachMenuBot=n)}),this.webViewResultUrl._==="webViewResultUrl"){const n=this.webViewResultUrl.query_id;this.listenerSetter.add(I)("web_view_result_sent",a=>{n===a&&this.forceHide()})}this.d()}getThemeParams(){return as.getThemeParamsForWebView()}destroy(){return this.telegramWebView.destroy(),super.destroy()}debouncePopupMethod(e,t,s){let i=!1,n=!1;return async(...a)=>{if(i)return;const{lastDispatchedWebViewEvent:r}=this.telegramWebView;if(!n&&r?.type===t&&r.count>=3&&(n=!0,setTimeout(()=>{this.telegramWebView.lastDispatchedWebViewEvent===r&&(this.telegramWebView.lastDispatchedWebViewEvent.count=0),n=!1},3e3)),n){this.telegramWebView.dispatchWebViewEvent(t,s);return}i=!0;try{await e(...a)}finally{i=!1}}}createWebView(){const e=this.telegramWebView=new zw({url:this.webViewResultUrl.url,sandbox:VF,allow:"camera; microphone; geolocation;",onLoad:()=>{this.iconElement&&(this.iconElement.style.opacity="0"),e.iframe.style.opacity="1",e.iframe.classList.remove("disable-hover")}});return e.iframe.style.opacity="0",e.iframe.classList.add("disable-hover"),e.iframe.allowFullscreen=!0,e.addMultipleEventsListeners({iframe_ready:t=>{this.readyResult=t},iframe_will_reload:()=>{this.reloadTimeout&&(clearTimeout(this.reloadTimeout),this.reloadTimeout=void 0)},web_app_data_send:({data:t})=>{!this.webViewOptions.isSimpleWebView||this.webViewOptions.fromSwitchWebView||(this.forceHide(),this.managers.appAttachMenuBotsManager.sendWebViewData(this.webViewOptions.botId,this.webViewOptions.buttonText,t))},web_app_close:()=>{this.forceHide()},web_app_open_link:({url:t})=>{ro(t)},web_app_open_tg_link:({path_full:t})=>{me.openUrl("https://t.me"+t)},web_app_open_invoice:({slug:t})=>{const s={_:vt.INVOICE,slug:t};lp.processInvoiceLink(s).then(i=>{i.addEventListener("finish",n=>{e.dispatchWebViewEvent("invoice_closed",{slug:t,status:n})})})},web_app_request_theme:this.sendTheme,web_app_set_background_color:({color:t})=>this.setBodyColor(t),web_app_set_header_color:this.setHeaderColor,web_app_switch_inline_query:this.switchInlineQuery,web_app_setup_main_button:this.setupMainButton,web_app_setup_back_button:this.setupBackButton,web_app_setup_settings_button:this.setupSettingsButton,web_app_setup_closing_behavior:({need_confirmation:t})=>this.isCloseConfirmationNeeded=!!t,web_app_open_popup:this.debouncePopupMethod(this.openPopup,"popup_closed",{}),web_app_open_scan_qr_popup:()=>e.dispatchWebViewEvent("scan_qr_popup_closed",{}),web_app_read_text_from_clipboard:async({req_id:t})=>{const s={req_id:t};let i;if(this.attachMenuBot&&!this.attachMenuBot.pFlags.inactive)try{(await navigator.permissions.query({name:"clipboard-read"})).state==="granted"&&(i=await navigator.clipboard.readText())}catch(n){console.error("clipboard read error",n)}i!==void 0&&(s.data=i),e.dispatchWebViewEvent("clipboard_text_received",s)},web_app_request_write_access:this.debouncePopupMethod(async()=>{const t=this.webViewOptions.botId,s=await this.managers.appBotsManager.canSendMessage(t),i={status:"allowed"};if(!s)try{await Ct({titleLangKey:"WebApp.WriteAccess.Title",descriptionLangKey:"WebApp.WriteAccess.Description",descriptionLangArgs:[await Oe({peerId:t.toPeerId(!1)})],button:{langKey:"OK"}}),await this.managers.appBotsManager.allowSendMessage(t)}catch{i.status="cancelled"}e.dispatchWebViewEvent("write_access_requested",i)},"write_access_requested",{status:"cancelled"}),web_app_request_phone:this.debouncePopupMethod(async()=>{const t={status:"sent"};try{const s=this.webViewOptions.botId;await this.managers.appMessagesManager.unblockBot(s),await me.requestPhone(s.toPeerId(!1))}catch{t.status="cancelled"}e.dispatchWebViewEvent("phone_requested",t)},"phone_requested",{status:"cancelled"}),web_app_invoke_custom_method:async({req_id:t,method:s,params:i})=>{let n,a;try{n=await this.managers.appAttachMenuBotsManager.invokeWebViewCustomMethod(this.webViewOptions.botId,s,i)}catch(r){a=r}e.dispatchWebViewEvent("custom_method_invoked",{req_id:t,result:n&&JSON.parse(n.data),error:a?.type})}}),e.iframe.classList.add("payment-verification"),e}async d(){this.attachMenuBot||this.title.append(await Oe({peerId:this.webViewOptions.botId.toPeerId()}));let e=!1;this.iconElement=document.createElement("span");try{const s=this.attachMenuBot??await this.managers.appAttachMenuBotsManager.getAttachMenuBot(this.webViewOptions.botId),i=Df(s);i&&(await vw({element:this.iconElement,doc:i.icon,size:80,textColor:()=>"secondary-text-color",strokeWidth:()=>.5}),e=!0)}catch{}e?this.iconElement.classList.add("popup-web-app-icon"):this.iconElement=void 0;const t=this.createWebView();this.setBodyColor(this.getThemeParams().bg_color),this.setHeaderColor({color_key:"bg_color"}),this.body.prepend(...[this.iconElement,t.iframe].filter(Boolean)),this.show(),t.onMount(),this.webViewOptions.isSimpleWebView||setTimeout(()=>this.prolongWebView(),5e4)}prolongWebView(){this.managers.appAttachMenuBotsManager.prolongWebView({queryId:this.webViewResultUrl.query_id,...this.webViewOptions}).then(()=>{this.destroyed||setTimeout(()=>{this.destroyed||this.prolongWebView()},5e4)},e=>{this.destroyed||(e.type==="QUERY_ID_INVALID"?this.forceHide():console.error("web app prolong error",e))})}}function zF(){const o=[],e=window.getSelection();for(let t=0;t<e.rangeCount;++t){const s=e.getRangeAt(t);let{startContainer:i,endContainer:n}=s;for(n.nodeType!==n.TEXT_NODE&&(n=n.firstChild);i&&i!==n;)o.push(i.nodeType===n.TEXT_NODE?i:i.firstChild),i=i.nextSibling;o[o.length-1]!==n&&o.push(n)}return o.filter(t=>!!t)}var Ll=(o=>(o[o.CHATLIST=0]="CHATLIST",o[o.CHAT=1]="CHAT",o[o.PROFILE=2]="PROFILE",o))(Ll||{});class KF extends Si{constructor(){super(...arguments),this.columnEl=document.getElementById("column-center"),this.offline=!1,this.updateStatusInterval=0,this.setPeerPromise=null,this.chats=[],this.cacheStorage=new VL("cachedFiles"),this.onHashChange=e=>{try{this.onHashChangeUnsafe(e)}catch(t){this.log.error("hash change error",t)}},this.onHashChangeUnsafe=e=>{const t=location.hash;e||ft.replaceState();const s=t.split("?"),i=_b(t,s);if(this.log("hashchange",t,s[0],i),!!t){if(i.tgaddr){ft.replaceState(),this.openUrl(i.tgaddr);return}switch(s[0]){default:i.p=s[0].slice(1);case"#/im":{if(!Object.keys(i).length)break;const n=i.p,a=i.post!==void 0?+i.post:void 0,r=a||(i.message!==void 0?+i.message:void 0),l=i.thread!==void 0?+i.thread:void 0;switch(n[0]){case"@":{this.openUsername({userName:n,lastMsgId:r,threadId:l});break}default:{const c=a?n.toPeerId(!0):n.toPeerId();this.managers.appPeersManager.getPeer(c).then(d=>{this.op({peer:d,lastMsgId:r,threadId:l})});break}}}}}},this.setSettings=()=>{const{messagesTextSize:e}=I.settings;this.customEmojiSize=vs(e+4,e+4),document.documentElement.style.setProperty("--messages-text-size",e+"px"),!this.customEmojiSize||(document.querySelectorAll("middle-ellipsis-element").forEach(l=>{l.disconnectedCallback(),l.dataset.fontSize=""+e,l.title&&(l.textContent=l.title),l.connectedCallback()}),document.querySelectorAll(".chat custom-emoji-renderer-element").forEach(l=>{l.forceRenderAfterSize=!0})),document.body.classList.toggle("animation-level-0",!st.isAvailable("animations")),document.body.classList.toggle("animation-level-1",!1),document.body.classList.toggle("animation-level-2",st.isAvailable("animations")),this.chatsSelectTabDebounced=ii(()=>{this.chat.topbar.pinnedMessage?.setCorrectIndex(0),this.managers.apiFileManager.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)},st.isAvailable("animations")?250:0,!1,!0);const s=["stickers_chat","stickers_panel"],i=gt.setLoop(I.settings.stickers.loop),n=!!s.filter(a=>gt.setAutoplay(st.isAvailable(a),a)).length;(i||n)&&gt.checkAnimations2(!1);for(const a of this.chats)a.setAutoDownloadMedia();ke.setTimeFormat(I.settings.timeFormat),this.toggleChatGradientAnimation(this.chat)},this.onDocumentPaste=async(e,t)=>{const s=sg();if(e instanceof DragEvent){const n=e.dataTransfer.types;(n.contains?n.contains("Files"):n.indexOf("Files")>=0)&&oe(e)}const i=await ub(e);if(!(!await this.canDrag()&&!s)&&i.length){if(s){s.addFiles(i);return}const n=this.chat.input;n.willAttachType=t||(ka.has(i[0].type)?"media":"document"),ee.createPopup(pr,this.chat,i,n.willAttachType)}},this.onEmojiStickerClick=async({event:e,container:t,managers:s,peerId:i,middleware:n})=>{oe(e);const a=U(t,"bubble"),r=t.dataset.stickerEmoji,l=t.classList.contains("custom-emoji")?void 0:_s.getAnimation(t);if(l?.paused){const f=await s.appStickersManager.getAnimatedEmojiSoundDocument(r);if(f){const y=document.createElement("audio");y.style.display="none",t.parentElement.append(y);try{const v=await cs.downloadMediaURL({media:f});y.src=v,wi(y),await Wn(y,void 0,!0),y.addEventListener("ended",()=>{y.src="",y.remove()},{once:!0})}catch{}}l.autoplay=!0,l.restart()}if(!i.isUser()||!st.isAvailable("effects_emoji"))return!1;const c=t.activeAnimations??(t.activeAnimations=new Set);if(c.size>=3)return!0;const d=await s.appStickersManager.getAnimatedEmojiSticker(r,!0);if(!d)return!1;const h=t.emojiData??(t.emojiData={a:[],v:1}),u=t.sendInteractionThrottled??(t.sendInteractionThrottled=ma(()=>{if(!h.a.length)return;const y=h.a[0].t;h.a.forEach(S=>{S.t=(S.t-y)/1e3});const{peerId:v,threadId:w}=this.chat,b=U(t,"bubble");s.appMessagesManager.setTyping(v,{_:"sendMessageEmojiInteraction",msg_id:yn(+b.dataset.mid),emoticon:r,interaction:{_:"dataJSON",data:JSON.stringify(h)}},!0,w),h.a.length=0},1e3,!1)),p={};c.add(p);const m=a?a.classList.contains("is-out"):void 0,{animationDiv:g}=Dc({doc:d,middleware:n,side:m?"right":"left",size:360,target:t,play:!0,withRandomOffset:!0,onUnmount:()=>{c.delete(p)},scrollable:this.chat.bubbles.scrollable});return m!==void 0&&!m&&g.classList.add("reflect-x"),e.isTrusted&&(h.a.push({i:1,t:Date.now()}),u()),!0}}get myId(){return I.myId}get chat(){return this.chats[this.chats.length-1]}construct(e){this.managers=e,lp.construct(e);const{apiUpdatesManager:t}=e;t.attach(ke.lastRequestedLangCode),rt.construct(e),Fh.construct(e),Fh.start(),this.log=ri("IM",Gi.Log|Gi.Warn|Gi.Debug|Gi.Error),this.backgroundPromises={},Gr.settings.themes.forEach(l=>{const c=l.settings;if(!c)return;const{wallpaper:d}=c,h=d.slug;if(!h)return;const u="assets/img/"+h+".svg"+(Uh?"?1":"");this.setBackgroundUrlToCache({slug:h,url:u})}),this.selectTab(0),xa.addEventListener("change",l=>{this.offline=l,this.updateStatus(),l?clearInterval(this.updateStatusInterval):this.updateStatusInterval=window.setInterval(()=>this.updateStatus(),5e4)}),this.chatsContainer=document.createElement("div"),this.chatsContainer.classList.add("chats-container","tabs-container"),this.chatsContainer.dataset.animation="navigation",this.appendEmojiAnimationContainer($e.activeScreen),this.columnEl.append(this.chatsContainer),this.createNewChat(),this.chatsSelectTab(this.chat.container),ft.onHashChange=this.onHashChange,this.setSettings(),I.addEventListener("settings_updated",this.setSettings);const s=l=>{document.body.classList.contains("is-premium")!==l&&(document.body.classList.toggle("is-premium",l),this.dispatchEvent("premium_toggle",l))};I.addEventListener("premium_toggle",s),s(I.premium),this.managers.rootScope.getPremium().then(s),Pg(()=>{gt.setOnlyOnePlayableGroup("lock"),gt.checkAnimations2(!0)},()=>{gt.setOnlyOnePlayableGroup(),gt.checkAnimations2(!1)}),as.AppBackgroundTab=Zo,Uh&&fe.oldVersion&&GL(fe.oldVersion,"1.4.3")===-1?this.deleteFilesIterative(l=>l.headers.get("Content-Type")==="image/svg+xml").then(()=>{this.applyCurrentTheme({noSetTheme:!0})}):this.applyCurrentTheme({noSetTheme:!0}),$e.addEventListener("changeScreen",(l,c)=>{document.body.classList.contains(Pc)&&document.body.classList.contains(Lc)&&ls.toggleSidebar(!1),this.appendEmojiAnimationContainer(c)}),$e.addEventListener("resize",()=>{const l=this.chatsContainer.getBoundingClientRect();mu.resizeInstances(l.width,l.height).then(()=>{})});const i=l=>{this.saveChatPosition(l)},n=()=>{this.addEventListener("peer_changing",i,{once:!0})};this.addEventListener("peer_changed",n),I.addEventListener("theme_changed",()=>{this.applyCurrentTheme({broadcastEvent:!0,noSetTheme:!0,skipAnimation:!0})}),I.addEventListener("choosing_sticker",l=>{this.setChoosingStickerTyping(!l)}),I.addEventListener("peer_title_edit",({peerId:l,threadId:c})=>{this.chat?.peerId===l&&!c&&this.tabId!==void 0&&this.overrideHash(l)}),I.addEventListener("peer_typings",({peerId:l,typings:c})=>{const d=this.chat;if(!d||d.peerId!==l||Li.isOverlayActive||$e.activeScreen===hi.mobile&&this.tabId!==1)return;const h=c.find(u=>u.action._==="sendMessageEmojiInteraction");if(h?.action?._==="sendMessageEmojiInteraction"){const u=h.action,p=d.bubbles.getBubble(l,h.action.msg_id);if(p&&p.classList.contains("emoji-big")&&go(p,d.bubbles.scrollable.container)){const m=p.querySelector(".media-sticker-wrapper:not(.bubble-hover-reaction-sticker):not(.reaction-sticker)");JSON.parse(u.interaction.data).a.forEach(f=>{setTimeout(()=>{fs(m)},f.t*1e3)}),this.managers.appMessagesManager.setTyping(l,{_:"sendMessageEmojiInteractionSeen",emoticon:u.emoticon})}}}),I.addEventListener("message_error",({peerId:l,error:c})=>{if(c.type.includes("SLOWMODE_WAIT")){const d=+c.type.split("_").pop();Ct({titleLangKey:"Slowmode",peerId:l,descriptionLangKey:"SlowModeHint",descriptionLangArgs:[Yb(d)],button:{langKey:"OK",isCancel:!0}})}}),I.addEventListener("file_speed_limited",({increaseTimes:l,isUpload:c})=>{const{hide:d}=ap({icon:"premium_speed",title:M(c?"UploadSpeedLimited":"DownloadSpeedLimited"),textElement:M(c?"Chat.UploadLimit.Text":"Chat.DownloadLimit.Text",[ni(()=>{d(),Vt.show({feature:"faster_download"})}),l]),appendTo:this.chat.bubbles.container,from:"top",duration:1e4})});const a=l=>{const c=l==="version",d=ee.createPopup(ee,"popup-instance-deactivated",{overlayClosable:!0}),h=document.createElement("div");h.classList.add("instance-deactivated-container"),d.container.replaceWith(h);const u=document.createElement("div");u.classList.add("header"),u.append(M(c?"Deactivated.Version.Title":"Deactivated.Title"));const p=document.createElement("div");p.classList.add("subtitle"),p.append(M(c?"Deactivated.Version.Subtitle":"Deactivated.Subtitle")),h.append(u,p),document.body.classList.add("deactivated");const m=c?()=>{Rb.reload()}:()=>{document.body.classList.add("deactivated-backwards"),ir.activateInstance(),setTimeout(()=>{document.body.classList.remove("deactivated","deactivated-backwards")},333)};d.addEventListener("close",m),d.show()};ir.addEventListener("deactivated",a),ir.deactivatedReason&&a(ir.deactivatedReason),this.addEventListener("chat_changing",({to:l})=>{this.toggleChatGradientAnimation(l)}),I.addEventListener("service_notification",l=>{Ct({button:{langKey:"OK",isCancel:!0},description:Yt(l.message)})}),I.addEventListener("payment_sent",async({peerId:l,mid:c,receiptMessage:d})=>{const h=await this.managers.appMessagesManager.getMessageByPeer(l,c);if(!h)return;const u=d.action;Ee({langPackKey:"PaymentInfoHint",langPackArguments:[In(u.total_amount,u.currency),_e(h.media.title)]})}),window.onSpoilerClick=l=>{const c=U(l.target,"spoiler"),d=U(c,"spoilers-container")||c.parentElement,h="is-spoiler-visible",u=d.classList.contains(h);u||(oe(l),Go!=="click"&&window.addEventListener("click",oe,{capture:!0,once:!0}));const p=400/2,m=5e3,g=u?0:2;g&&d.classList.add("will-change");const f=d.dataset.spoilerTimeout;f!==null&&(clearTimeout(+f),delete d.dataset.spoilerTimeout),bt({element:d,className:h,forwards:!0,duration:p,onTransitionEnd:()=>{d.dataset.spoilerTimeout=""+window.setTimeout(()=>{bt({element:d,className:h,forwards:!1,duration:p,onTransitionEnd:()=>{d.classList.remove("will-change"),delete d.dataset.spoilerTimeout}})},m)},useRafs:g})},document.addEventListener("mousemove",l=>{const c=U(l.target,"media-sticker-wrapper");if(!c||c.classList.contains("custom-emoji")||U(l.target,"emoji-big"))return;gt.getAnimations(c)?.forEach(h=>{const{liteModeKey:u,animation:p}=h;!u||!p?.paused||st.isAvailable(u)||(p instanceof Ih?p.playOrRestart():p.play())})}),I.addEventListener("sticker_updated",({type:l,faved:c})=>{l==="faved"?Ee({langPackKey:c?"AddedToFavorites":"RemovedFromFavorites"}):c||Ee({langPackKey:"RemovedFromRecent"})}),I.addEventListener("gif_updated",({saved:l})=>{Ee({langPackKey:l?"GifSavedHint":"RemovedGIFFromFavorites"})}),fe.addEventListener("notificationBuild",async l=>{const c=await this.managers.appPeersManager.isForum(l.message.peerId),d=ha(l.message,c);this.chat.peerId===l.message.peerId&&this.chat.threadId===d&&!xa.isIdle||Fh.buildNotificationQueue(l)}),this.addEventListener("peer_changed",async({peerId:l})=>{document.body.classList.toggle("has-chat",!!l),Ep.textContent="",this.overrideHash(l),fe.updateTabState("chatPeerIds",this.chats.map(c=>c.peerId).filter(Boolean))}),Zd.setToCache("chatPositions",{}),(Fc||Ac)&&(this.topbarCall=new NF(e)),Fc&&(Yi.addEventListener("instance",({instance:l})=>{const c=ee.createPopup(vg,l);l.addEventListener("acceptCallOverride",()=>this.discardCurrentCall(l.interlocutorUserId.toPeerId(),"Call",void 0,l).then(()=>(Yi.dispatchEvent("accepting",l),!0)).catch(()=>!1)),c.addEventListener("close",()=>{const d=Yi.currentCall;d&&d!==l&&!l.wasTryingToJoin&&l.hangUp("phoneCallDiscardReasonBusy")},{once:!0}),c.show()}),Yi.addEventListener("incompatible",async l=>{Ee({langPackKey:"VoipPeerIncompatible",langPackArguments:[await Oe({peerId:l.toPeerId()})]})})),ir.activateInstance();const r=()=>{jL.setAuthorized(!0)};zL&&document.addEventListener("visibilitychange",()=>{if(document.hidden)return;Array.from(document.querySelectorAll("canvas")).forEach(c=>{const d=c.getContext("2d");if(!d)return;const h=d.fillStyle;d.fillStyle="transparent",d.fillRect(0,0,1,1),d.fillStyle=h})}),setInterval(r,xg),r(),this.managers.appReactionsManager.getSavedReactionTags().then(l=>{qc.splice(0,qc.length,...l)}),this.onHashChange(!0),this.attachKeydownListener(),this.attachCopyListener(),this.handleAutologinDomains(),this.handlePeerColors(),this.checkForShare(),this.init()}checkForShare(){const e=fe.share;e&&(fe.share=void 0,ee.createPopup(va,void 0,async(t,s)=>{if(await this.setPeer({peerId:t,threadId:s}),e.files?.length){const i=e.files.some(n=>ka.has(n.type));ee.createPopup(pr,this.chat,e.files,i?"media":"document")}else this.managers.appMessagesManager.sendText({peerId:t,text:e.text})}))}async confirmBotWebViewInner({botId:e,requestWriteAccess:t,showDisclaimer:s}){const i=e.toPeerId();if(s){const n={text:"WebApp.Disclaimer.Check",textArgs:[Yt(ke.format("WebAppDisclaimerUrl",!0))]};return Ct({titleLangKey:"TermsOfUse",descriptionLangKey:"BotWebAppDisclaimerSubtitle",checkbox:n,button:{langKey:"Continue",onlyWithCheckbox:n}})}return Ct({title:await Oe({peerId:i}),descriptionLangKey:"BotWebViewStartPermission",checkbox:t?{text:"OpenUrlOption2",textArgs:[await Oe({peerId:i})],checked:!0}:void 0,button:{langKey:"BotWebAppInstantViewOpen"},peerId:i})}async pushBotIdAsConfirmed(e){const t=await fe.getState();t.confirmedWebViews.push(e),await this.managers.appStateManager.pushToState("confirmedWebViews",t.confirmedWebViews)}async confirmBotWebView(e){const t=await fe.getState();if(e.ignoreConfirmedState||e.showDisclaimer||!t.confirmedWebViews.includes(e.botId)){const s=await this.confirmBotWebViewInner(e);return await this.pushBotIdAsConfirmed(e.botId),s}}async toggleBotInAttachMenu(e,t,s){return s??(s=await this.managers.appAttachMenuBotsManager.getAttachMenuBot(e)),!!s.pFlags.inactive==!t||(s.pFlags.inactive?(await this.confirmBotWebViewInner({botId:e,showDisclaimer:!0}),await this.pushBotIdAsConfirmed(e),await this.managers.appAttachMenuBotsManager.toggleBotInAttachMenu(e,!0,!0),delete s.pFlags.inactive,Ee({langPackKey:s.pFlags.show_in_attach_menu&&s.pFlags.show_in_side_menu?"BotAttachMenuShortcatAddedAttachAndSide":s.pFlags.show_in_attach_menu?"BotAttachMenuShortcatAddedAttach":"BotAttachMenuShortcatAddedSide",langPackArguments:[_e(s.short_name)]})):(await this.managers.appAttachMenuBotsManager.toggleBotInAttachMenu(e,!1),s.pFlags.inactive=!0,Ee({langPackKey:s.pFlags.show_in_attach_menu&&s.pFlags.show_in_side_menu?"WebApp.AttachRemove.SuccessAll":s.pFlags.show_in_attach_menu?"WebApp.AttachRemove.Success":"WebApp.AttachRemove.SuccessSide",langPackArguments:[_e(s.short_name)]}))),s}async openWebApp(e){if(e.botId??(e.botId=e.attachMenuBot?.bot_id),e.themeParams??(e.themeParams={_:"dataJSON",data:JSON.stringify(as.getThemeParamsForWebView())}),!e.attachMenuBot&&(e.fromAttachMenu||e.fromSideMenu))try{e.attachMenuBot=await this.managers.appAttachMenuBotsManager.getAttachMenuBot(e.botId)}catch{}if(!e.noConfirmation){const t=e.attachMenuBot;let s;e.fromSideMenu?t?.pFlags?.side_menu_disclaimer_needed?s=!0:await this.pushBotIdAsConfirmed(e.botId):s=fe.getUser(e.botId).pFlags.bot_attach_menu&&t?.pFlags?.inactive,s?await this.toggleBotInAttachMenu(e.botId,!0,t):await this.confirmBotWebView({botId:e.botId})}try{const t=await this.managers.appAttachMenuBotsManager.requestWebView(e);ee.createPopup(GF,{webViewResultUrl:t,webViewOptions:e,attachMenuBot:e.attachMenuBot})}catch(t){t.type==="PEER_ID_INVALID"&&e.attachMenuBot&&Ee({langPackKey:"BotAlreadyAddedToAttachMenu"})}}handleUrlAuth(e){const{peerId:t,mid:s,buttonId:i,url:n}=e,a=c=>{window.open(c,"_blank")},r=c=>{a(c.url)},l=async c=>{if(c._==="urlAuthResultRequest"){const d=document.createElement("b");d.append(c.domain);const h=await Oe({peerId:I.myId}),u=await Oe({peerId:c.bot.id.toPeerId()}),p={text:"OpenUrlOption1",textArgs:[d.cloneNode(!0),h],checked:!0},m=c.pFlags.request_write_access?{text:"OpenUrlOption2",textArgs:[u],checked:!0}:void 0,f=Ct({titleLangKey:"OpenUrlTitle",button:{langKey:"Open"},descriptionLangKey:"OpenUrlAlert2",descriptionLangArgs:[d],checkboxes:[p,m].filter(Boolean)});m&&p.checkboxField.input.addEventListener("change",()=>{const b=!p.checkboxField.checked;m.checkboxField.toggleDisability(b),b&&(m.checkboxField.checked=!1)});const[y,v]=await f;if(!y){a(n);return}const w=await this.managers.appSeamlessLoginManager.acceptUrlAuth(n,t,s,i,v);return l(w)}else c._==="urlAuthResultAccepted"?r(c):a(n)};return this.managers.appSeamlessLoginManager.requestUrlAuth(n,t,s,i).then(c=>{l(c)})}handleAutologinDomains(){let e,t;I.addEventListener("app_config",n=>e=n),I.addEventListener("config",n=>t=n),this.managers.apiManager.getAppConfig().then(n=>e=n),this.managers.apiManager.getConfig().then(n=>t=n);const s=n=>{var c;if(!e)return;const a=new URL(n.href);if(e.url_auth_domains?.includes(a.hostname)){this.handleUrlAuth({url:n.href}),oe();return}const r=t.autologin_token;if(!r||!e.autologin_domains)return;const l=(c=n.dataset).originalUrl??(c.originalUrl=n.href);e.autologin_domains.includes(a.hostname)&&(a.searchParams.set("autologin_token",r),n.href=a.toString(),setTimeout(()=>{n.href=l,delete n.dataset.originalUrl},0))},i=n=>{const a=U(n,"bubble");if(!a)return;const r=a.message;this.clickIfSponsoredMessage(r)};document.addEventListener("click",async n=>{const a=Bi(n.target,"A");a?.href&&s(a),a&&i(a);const r=Uc(n.target);r&&r.classList.contains("has-stories")&&!U(n.target,"stories-list")&&this.openStoriesFromAvatar(r)})}handlePeerColors(){let e;const t=(n=e)=>{const a=fe.getUser(I.myId.toUserId());z0(n.colors,a),e=n};I.addEventListener("theme_changed",()=>t()),this.managers.apiManager.getPeerColors().then(t);const[s,i]=nI();this.managers.apiManager.getPeerProfileColors().then(n=>{i(n.colors)})}clickIfSponsoredMessage(e){const t=e?.sponsoredMessage;t&&this.managers.appChatsManager.clickSponsoredMessage(e.peerId.toChatId(),t.random_id)}async openStoriesFromAvatar(e){const t=+e.dataset.storyId;mr({target:()=>e,peerId:e.dataset.peerId.toPeerId(),id:t||void 0})}getStackFromElement(e){const t=U(e,"bubble"),s=t&&U(t,"chat"),n=(s&&this.chats.find(l=>l.container===s))?.peerId,a=t&&+t.dataset.mid,r=t?.message||n&&fe.getMessageByPeer(n,a);return t?{peerId:n,mid:a,message:r,isOut:r?!!r.pFlags.out:void 0}:void 0}deleteFilesIterative(e){return this.cacheStorage.timeoutOperation(t=>{const s=performance.now();return t.keys().then(i=>{const n=i.map(a=>t.match(a).then(r=>e(r)));return Promise.all(n).then(a=>(a.map((r,l)=>{if(!r)return;const c=i[l];return t.delete(c)}),Promise.all(a.filter(Boolean))))}).then(()=>{this.log("deleted files",performance.now()-s)})})}toggleChatGradientAnimation(e){}appendEmojiAnimationContainer(e){const t=e===hi.mobile?this.columnEl:document.body;Ep.parentElement!==t&&t.append(Ep)}attachKeydownListener(){const e=new Set(["PageUp","PageDown","Meta","Control"]),t=s=>{const i=s.key,n=document.getSelection().isCollapsed;if(Li.isOverlayActive||e.has(i))return;const a=s.target,r=a.tagName==="INPUT"&&!["checkbox","radio"].includes(a.type)||a.isContentEditable,l=this.chat;if(!((i.startsWith("Arrow")||s.shiftKey&&i==="Shift")&&!n)){{if(s.code==="KeyC"&&(s.ctrlKey||s.metaKey)&&!r)return;if(s.altKey&&(i==="ArrowUp"||i==="ArrowDown"))oe(s),this.managers.dialogsStorage.getNextDialog(this.chat.peerId,i==="ArrowDown",Xe.filterId).then(c=>{c&&this.setPeer({peerId:c.peerId})});else if(i==="ArrowUp"&&this.chat.type!==te.Scheduled)if(!l.input.editMsgId&&l.input.isInputEmpty())this.managers.appMessagesManager.getFirstMessageToEdit(l.peerId,l.threadId).then(c=>{c&&(l.input.initMessageEditing(c.mid),oe(s))});else return;else if(i==="ArrowDown")return}l?.input?.messageInput&&a!==l.input.messageInput&&!r&&!Je&&(!$e.isMobile||this.tabId===1)&&!l.selection.isSelecting&&!l.input.recording&&l.input.messageInput.isContentEditable&&VC(l.input.messageInput,s)}};document.body.addEventListener("keydown",t)}attachCopyListener(){document.addEventListener("copy",e=>{zF().some(s=>{let i=s;if(s.nodeType!==s.ELEMENT_NODE&&(i=s.parentElement),!U(i,"no-forwards"))return!1;const n=U(i,"bubble");if(!n)return!1;e.preventDefault();const a=n.dataset.peerId.toPeerId(),r=fe.getChat(a.toChatId());return Ee({langPackKey:r.pFlags.broadcast?"CopyRestricted.Channel":"CopyRestricted.Group"}),!0})})}openUrl(e,t){const{url:s,onclick:i}=cl(e);if(!i){t&&ro(s);return}const n=document.createElement("a");return n.href=s,window[i](n)}async open(e){return this.op({...e,peer:await this.managers.appPeersManager.getPeer(e.peerId)})}async op(e){if(!e.peer)return;const t=e.peer._==="user",s=e.peer._==="channel";let i=e.peer.id.toPeerId(!t);const n=["commentId","lastMsgId","threadId"],a=s?e.peer.id:void 0,r=!!e.peer.pFlags.forum;await Promise.all(n.map(async u=>{e[u]&&(e[u]=await this.managers.appMessagesIdsManager.generateMessageId(e[u],a))}));const l=e.peer.migrated_to;if(l){const u=l.channel_id;e.peer=await this.managers.appChatsManager.getChat(u),i=u.toPeerId(!0)}let{commentId:c,threadId:d,lastMsgId:h}=e;if(!c&&!d&&!h&&r){Xe.toggleForumTabByPeerId(i,!0,!0);return}if(r&&h&&!d){const u=await this.managers.appMessagesManager.reloadMessages(i,h);u?d=e.threadId=ha(u,r):(d=e.threadId=h,h=e.lastMsgId=void 0)}return d?this.openThread({...e,peerId:i}):c?this.openComment({peerId:i,msgId:h,commentId:c}):this.setInnerPeer({...e,peerId:i})}openPremiumBot(){return this.managers.apiManager.getAppConfig().then(e=>this.openUsername({userName:e.premium_bot_username}))}openUsername(e){const{userName:t}=e;return this.managers.appUsersManager.resolveUsername(t).then(s=>this.op({peer:s,...e}),s=>{s.type==="USERNAME_NOT_OCCUPIED"?Ee({langPackKey:"NoUsernameFound"}):s.type==="USERNAME_INVALID"&&Ee({langPackKey:"Alert.UserDoesntExists"})})}async openThread(e){return await this.managers.appChatsManager.isForum(e.peerId.toChatId())?(await this.managers.dialogsStorage.getForumTopicOrReload(e.peerId,e.threadId),this.setInnerPeer(e)):this.managers.appMessagesManager.reloadMessages(e.peerId,e.threadId).then(async t=>(t||(e.lastMsgId=void 0),this.setInnerPeer({...e,type:te.Discussion})))}openComment(e){return this.managers.appMessagesManager.getDiscussionMessage(e.peerId,e.msgId).then(t=>this.openThread({peerId:t.peerId,lastMsgId:e.commentId,threadId:t.mid}))}async callUser(e,t){if(Yi.getCallByUserId(e))return;if((await this.managers.appProfileManager.getProfile(e)).pFlags.phone_calls_private){Oe({peerId:e.toPeerId()}).then(n=>Ct({descriptionLangKey:"Call.PrivacyErrorMessage",descriptionLangArgs:[n],button:{langKey:"OK",isCancel:!0}}));return}await this.discardCurrentCall(e.toPeerId(),"Call"),Yi.startCallInternal(e,t==="video")}discardCurrentCall(e,t,s,i,n){return zn.groupCall&&zn.groupCall!==s?this.discardGroupCallConfirmation(e,t):Yi.currentCall&&Yi.currentCall!==i?this.discardCallConfirmation(e,t):Nt.currentCall&&Nt.currentCall!==n?this.discardLiveConfirmation(e,t):Promise.resolve()}async discardAnyCallConfirmation(e,t,s,i){await Promise.all([Oe({peerId:e}),Oe({peerId:t})]).then(([n,a])=>Ct({titleLangKey:`Call.Confirm.Discard.${s}.Header`,descriptionLangKey:`Call.Confirm.Discard.${s}.To${i}.Text`,descriptionLangArgs:[n,a],button:{langKey:"OK"}}))}async discardGroupCallConfirmation(e,t){const s=zn.groupCall;s&&(await this.discardAnyCallConfirmation(s.chatId.toPeerId(!0),e,"Voice",t),zn.groupCall===s&&await s.hangUp())}async discardCallConfirmation(e,t){const s=Yi.currentCall;s&&(await this.discardAnyCallConfirmation(s.interlocutorUserId.toPeerId(!1),e,"Call",t),s.isClosing||await s.hangUp("phoneCallDiscardReasonDisconnect"))}async discardLiveConfirmation(e,t){const s=Nt.currentCall;s&&(await this.discardAnyCallConfirmation(s.chatId.toPeerId(!0),e,"Live",t),Nt.currentCall===s&&await Nt.leaveCall())}async joinGroupCall(e,t){const s=e.toChatId(),i=this.managers.appChatsManager.hasRights(s,"manage_call"),n=async()=>{const a=await this.managers.appProfileManager.getChatFull(s);let r;if(a.call)r=a.call;else{if(!i)return;r=await this.managers.appGroupCallsManager.createGroupCall(s)}zn.joinGroupCall(s,r.id,!0,!1)};if(t&&(await this.managers.appGroupCallsManager.getGroupCallFull(t))._==="groupCallDiscarded"){if(!i){Ee({langPackKey:"VoiceChat.Chat.Ended"});return}await Ct({descriptionLangKey:"VoiceChat.Chat.StartNew",button:{langKey:"VoiceChat.Chat.StartNew.OK"}})}await this.discardCurrentCall(e,"Voice"),n()}async joinLiveStream(e){await this.discardCurrentCall(e,"Live"),await Nt.joinCall(e.toChatId()).catch(t=>{console.error(t),Ee({langPackKey:"Error.AnError"})}),this.openLiveStreamPlayer(e)}async openLiveStreamPlayer(e){if(Jo.activeInstance)return;const t=await Jo.getShareUrl(e.toChatId());new Jo(t).openMedia({peerId:e,isAdmin:Nt.currentCall.admin})}setCurrentBackground(e=!1,t){const s=as.getTheme(),i=s.settings?.wallpaper?.slug;if(i){const n=Gr.settings.themes.find(a=>a.name===s.name);return Promise.resolve(this.getBackground({slug:i})).then(a=>this.setBackground(a,e,t),()=>(s.settings=Wi(n.settings),this.setCurrentBackground(!0)))}return this.setBackground("",e,t)}getWallPaperStorageUrl(e,t){return`backgrounds/${e}${t?"?blur":""}`}saveWallPaperToCache(e,t,s){if(!(!e||e===KL))return fetch(t).then(i=>Qf.cacheStorage.save(this.getWallPaperStorageUrl(e,s),i))}blurWallPaperImage(e){const{canvas:t,promise:s}=Nb(e,12,4);return s.then(()=>t.toDataURL())}setBackgroundUrlToCache({slug:e,url:t,blur:s}){this.backgroundPromises[this.getWallPaperStorageUrl(e,s)]=t}getBackground({slug:e,canDownload:t,blur:s}){var n;const i=this.getWallPaperStorageUrl(e,s);return(n=this.backgroundPromises)[i]||(n[i]=this.cacheStorage.getFile(i).then(a=>this.backgroundPromises[i]=URL.createObjectURL(a),t?async a=>{if(a.type!=="NO_ENTRY_FOUND")throw a;const r=await this.managers.appThemesManager.getWallPaperBySlug(e);let l=await cs.downloadMediaURL({media:r.document});return s&&(l=await this.blurWallPaperImage(l)),this.saveWallPaperToCache(e,l,s),this.backgroundPromises[i]=l}:void 0))}setBackground(e,t=!0,s){this.lastBackgroundUrl=e;const i=this.chats.map(n=>n.setBackgroundIfNotSet({url:e,skipAnimation:s}));return Promise.resolve(i[i.length-1]).then(()=>{t&&I.dispatchEvent("background_change")})}saveChatPosition(e){if(![te.Chat,te.Discussion,te.Saved].includes(e.type)||!e.peerId)return;const t=e.bubbles,s=e.peerId+(e.threadId?"_"+e.threadId:""),i=Zd.getFromCache("chatPositions");if(!(t.scrollable.getDistanceToEnd()<=16&&t.scrollable.loadedAll.bottom)&&t.getRenderedLength()&&!e.savedReaction&&t.getViewportSlice().invisibleBottom.length){t.sliceViewport(!0);const n=t.scrollable.scrollPosition,a={mids:t.getRenderedHistory("desc",!0).map(r=>Is(r).mid),top:n};i[s]=a,this.log("saved chat position:",a)}else delete i[s],this.log("deleted chat position");Zd.set({chatPositions:i},!0)}getChatSavedPosition(e){if(![te.Chat,te.Discussion,te.Saved].includes(e.type)||!e.peerId)return;const t=e.peerId+(e.threadId?"_"+e.threadId:""),s=Zd.getFromCache("chatPositions");return s&&s[t]}applyCurrentTheme({slug:e,backgroundUrl:t,broadcastEvent:s,noSetTheme:i,skipAnimation:n}={}){return t&&this.setBackgroundUrlToCache({slug:e,url:t}),!i&&as.setTheme(),this.setCurrentBackground(s===void 0?!!e:s,n)}chatsSelectTab(e,t){if(this.prevTab!==e){if(t===!1&&this.prevTab&&eb([e,this.prevTab].filter(Boolean)),this.prevTab){this.prevTab.classList.remove("active"),this.chatsSelectTabDebounced(),st.isAvailable("animations")&&t!==!1&&Xr(Hs(400),400);const s=Ri(this.prevTab);Ri(e)>s&&ft.pushItem({type:"chat",onPop:n=>{this.setPeer({},n),Dn()}})}e.classList.add("active"),this.prevTab=e}}init(){document.addEventListener("paste",this.onDocumentPaste,!0),Je||this.attachDragAndDropListeners(),Dl.getInstance().handleSelection()}attachDragAndDropListeners(){const e=[],t=[];let s=!1;const i=async(l,c)=>{if(c===s)return;const d=l.dataTransfer.types,h=d.contains?d.contains("Files"):d.indexOf("Files")>=0,u=sg(),p=await ub(l,!0);if(!h||!await this.canDrag()&&!u){n=0;return}const m=await pr.canSend({...this.chat.getMessageSendingParams(),onlyVisible:!0}),g=u?r:a,f=u?t:e;if(c&&!f.length){const y=h&&!p.length,[v,w]=ul(p,C=>ka.has(C)),[b,S]=ul(v,C=>Vh.has(C));if(m.send_docs?w.push(...v):w.length=0,m.send_photos||(b.forEach(C=>us(v,C)),b.length=0),m.send_videos||(S.forEach(C=>us(v,C)),S.length=0),this.log("drag files",p,v,w,b,S),u){u.appendDrops(g);const C=(m.send_docs?[w]:[b,S]).reduce((P,L)=>P+L.length,0);(C||y)&&f.push(new rm(g,{header:"Preview.Dragging.AddItems",headerArgs:[C],onDrop:P=>{i(P,!1),this.log("drop",P),this.onDocumentPaste(P,"document")}}))}else(w.length||y)&&f.push(new rm(g,{icon:"dragfiles",header:"Chat.DropTitle",subtitle:"Chat.DropAsFilesDesc",onDrop:C=>{i(C,!1),this.log("drop",C),this.onDocumentPaste(C,"document")}})),(v.length||y)&&f.push(new rm(g,{icon:"dragmedia",header:"Chat.DropTitle",subtitle:"Chat.DropQuickDesc",onDrop:C=>{i(C,!1),this.log("drop",C),this.onDocumentPaste(C,"media")}})),this.chat.container.append(g)}bt({element:g,className:"is-visible",forwards:c,duration:200,onTransitionEnd:()=>{c||(f.forEach(y=>{y.destroy()}),f.length=0)}}),c?f.forEach(y=>{y.setPath()}):n=0,document.body.classList.toggle("is-dragging",c),s=c};let n=0;document.body.addEventListener("dragenter",l=>{++n}),document.body.addEventListener("dragover",l=>{i(l,!0),oe(l)}),document.body.addEventListener("dragleave",l=>{--n===0&&i(l,!1)});const a=document.createElement("div");a.classList.add("drops-container");const r=a.cloneNode(!0)}async canDrag(){const e=this.chat,s=!(!e?.peerId||Li.isOverlayActive||!await e.canSend("send_media"));return s&&await this.chat.input.showSlowModeTooltipIfNeeded({element:this.chat.input.attachMenu})?!1:s}async overrideHash(e){let t;if(e){const s=await this.managers.appPeersManager.getPeerUsername(e);t=s?"@"+s:""+e}ft.overrideHash(t)}selectTab(e,t){t===!1&&eb([Ii.sidebarEl,this.columnEl,ls.sidebarEl]),document.body.classList.toggle(Pc,e===0);const s=this.tabId;s!==void 0&&(this.overrideHash(e>0?this.chat?.peerId:void 0),this.dispatchEvent("tab_changing",e)),this.log("selectTab",e,s);let i=st.isAvailable("animations")?Qn():Promise.resolve();if(s!==void 0&&s!==e&&st.isAvailable("animations")&&t!==!1&&$e.activeScreen!==hi.large){const a=($e.isMobile?250:200)+100;i=Hs(a),Xr(i,a)}this.tabId=e,Dn(),$e.isMobile&&s===2&&e<2&&ls.hide(),s!==void 0&&e>s&&(e<2||!ft.findItemByType("im"))&&ft.pushItem({type:"im",onPop:a=>{this.setPeer({},a)}});const n=window.onImTabChange;return n?.(e),i}updateStatus(){return this.managers.appUsersManager.updateMyOnlineStatus(this.offline)}createNewChat(){const e=new SC(this,this.managers,!0);return this.chatsContainer.append(e.container),this.chats.push(e),e}spliceChats(e,t=!0,s,i){if(e>=this.chats.length)return;const n=this.chat;this.chats.length>1&&t&&this.dispatchEvent("peer_changing",this.chat),i||(i=this.chats.splice(e,this.chats.length-e));const a=this.chat;this.dispatchEvent("chat_changing",{from:n,to:a});for(let r=0;r<i.length-1;++r)ft.removeByType("chat",!0);i.length>1&&i.slice(0,-1).forEach(r=>{r.container.remove()}),this.chatsSelectTab(a.container,s),t&&(this.dispatchEvent("peer_changed",a),ls.getTab(fC)?.close(),ls.replaceSharedMediaTab(a.sharedMediaTab)),i.forEach(r=>{r.beforeDestroy()}),setTimeout(()=>{i.forEach(r=>{r.destroy()})},350)}async setPeer(e={},t){e.peerId??(e.peerId=Tt),e.peerId=await this.managers.appPeersManager.getPeerMigratedTo(e.peerId)||e.peerId;const{peerId:s,lastMsgId:i,threadId:n}=e,a=this.chat,r=this.chats.indexOf(a),l=this.isSamePeer(a,e);if(s){if(r>0&&a.peerId&&!l){const c=this.chats.splice(1,this.chats.length-1);if(this.chat.peerId===s){this.spliceChats(0,!0,!0,c);return}else{const d=this.setPeer(e);return this.spliceChats(0,!1,!1,c),d}}}else if(r>0){this.spliceChats(r,void 0,t);return}else if($e.activeScreen===hi.medium){this.selectTab(+!this.tabId,t);return}if(l&&$e.activeScreen<=hi.medium&&document.body.classList.contains(Pc))return this.selectTab(1,t),!1;if(s||$e.activeScreen!==hi.mobile){const c=await a.setPeer(e),d=c?.cached?c.promise:Promise.resolve();s&&Promise.all([d,a.setBackgroundPromise]).then(()=>{setTimeout(()=>{setTimeout(()=>{this.chatsSelectTab(this.chat.container)},0),this.selectTab(1,t)},0)})}if(!s)return this.selectTab(0,t),!1}async setInnerPeer(e){let{peerId:t}=e;if(t===Tt||!t)return;t=e.peerId=await this.managers.appPeersManager.getPeerMigratedTo(t)||t,e.type||(e.threadId&&(e.peerId===I.myId?e.type=te.Saved:fe.isForum(e.peerId)||(e.type=te.Discussion)),e.type??(e.type=te.Chat));const s=this.chats.findIndex(a=>this.isSamePeer(a,e)||$e.activeScreen===hi.mobile&&this.tabId===0);if(s!==-1)return this.spliceChats(s+1),this.setPeer(e);const i=this.chat;let n=i;return i.inited&&(n=this.createNewChat()),this.dispatchEvent("chat_changing",{from:i,to:n}),this.setPeer(e)}openScheduled(e){this.setInnerPeer({peerId:e,type:te.Scheduled})}async toggleViewAsMessages(e,t){e===I.myId?WL("settings","savedAsForum",!t):await this.managers.appChatsManager.toggleViewForumAsMessages(e.toChatId(),t),this.selectTab(0),Xe.toggleForumTabByPeerId(e,!t,!1)}getTypingElement(e){const t=document.createElement("span");let s="peer-typing";switch(t.classList.add(s),t.dataset.action=e._,e._){case"sendMessageTypingAction":{s+="-text";for(let i=0;i<3;++i){const n=s+"-dot",a=document.createElement("span");a.className=n+(i===0?" "+n+"-first":i===2?" "+n+"-last":""),t.append(a)}break}case"sendMessageUploadAudioAction":case"sendMessageUploadDocumentAction":case"sendMessageUploadRoundAction":case"sendMessageUploadVideoAction":case"sendMessageUploadPhotoAction":{s+="-upload";break}case"sendMessageRecordAudioAction":case"sendMessageRecordRoundAction":case"sendMessageRecordVideoAction":{s+="-record";break}case"sendMessageEmojiInteractionSeen":case"sendMessageChooseStickerAction":{s+="-choosing-sticker";for(let i=0;i<2;++i){const n=document.createElement("div");n.className=s+"-eye",t.append(n)}break}}return t.classList.add(s),t}async getPeerTyping(e,t,s){const i=e.isUser();if(i&&await this.managers.appUsersManager.isBot(e))return;const n=await this.managers.appProfileManager.getPeerTypings(e,s);if(!n?.length)return;const a=n[0],r={private:{sendMessageTypingAction:"Peer.Activity.User.TypingText",sendMessageUploadAudioAction:"Peer.Activity.User.SendingFile",sendMessageUploadDocumentAction:"Peer.Activity.User.SendingFile",sendMessageUploadPhotoAction:"Peer.Activity.User.SendingPhoto",sendMessageUploadVideoAction:"Peer.Activity.User.SendingVideo",sendMessageUploadRoundAction:"Peer.Activity.User.SendingVideo",sendMessageRecordVideoAction:"Peer.Activity.User.RecordingVideo",sendMessageRecordAudioAction:"Peer.Activity.User.RecordingAudio",sendMessageRecordRoundAction:"Peer.Activity.User.RecordingVideo",sendMessageGamePlayAction:"Peer.Activity.User.PlayingGame",sendMessageChooseStickerAction:"Peer.Activity.User.ChoosingSticker",sendMessageEmojiInteractionSeen:"Peer.Activity.User.EnjoyingAnimations"},chat:{sendMessageTypingAction:"Peer.Activity.Chat.TypingText",sendMessageUploadAudioAction:"Peer.Activity.Chat.SendingFile",sendMessageUploadDocumentAction:"Peer.Activity.Chat.SendingFile",sendMessageUploadPhotoAction:"Peer.Activity.Chat.SendingPhoto",sendMessageUploadVideoAction:"Peer.Activity.Chat.SendingVideo",sendMessageUploadRoundAction:"Peer.Activity.Chat.SendingVideo",sendMessageRecordVideoAction:"Peer.Activity.Chat.RecordingVideo",sendMessageRecordAudioAction:"Peer.Activity.Chat.RecordingAudio",sendMessageRecordRoundAction:"Peer.Activity.Chat.RecordingVideo",sendMessageGamePlayAction:"Peer.Activity.Chat.PlayingGame",sendMessageChooseStickerAction:"Peer.Activity.Chat.ChoosingSticker",sendMessageEmojiInteractionSeen:"Peer.Activity.Chat.EnjoyingAnimations"},multi:{sendMessageTypingAction:"Peer.Activity.Chat.Multi.TypingText1",sendMessageUploadAudioAction:"Peer.Activity.Chat.Multi.SendingFile1",sendMessageUploadDocumentAction:"Peer.Activity.Chat.Multi.SendingFile1",sendMessageUploadPhotoAction:"Peer.Activity.Chat.Multi.SendingPhoto1",sendMessageUploadVideoAction:"Peer.Activity.Chat.Multi.SendingVideo1",sendMessageUploadRoundAction:"Peer.Activity.Chat.Multi.SendingVideo1",sendMessageRecordVideoAction:"Peer.Activity.Chat.Multi.RecordingVideo1",sendMessageRecordAudioAction:"Peer.Activity.Chat.Multi.RecordingAudio1",sendMessageRecordRoundAction:"Peer.Activity.Chat.Multi.RecordingVideo1",sendMessageGamePlayAction:"Peer.Activity.Chat.Multi.PlayingGame1",sendMessageChooseStickerAction:"Peer.Activity.Chat.Multi.ChoosingSticker1"}},l=i?r.private:n.length>1?r.multi:r.chat;let c=a.action;if(n.length>1){const g={};n.forEach(f=>{const y=f.action._;g[y]===void 0&&(g[y]=0),++g[y]}),Object.keys(g).length>1&&(c={_:"sendMessageTypingAction"})}const d=l[c._];if(!d)return;let h,u;if(e.isAnyChat()){const g=new Rt;h=g.update({peerId:a.userId.toPeerId(!1),onlyFirstName:!0}),u=[g.element,n.length-1],await h}t||(t=document.createElement("span"),t.classList.add("online","peer-typing-container")),t.classList.toggle("peer-typing-flex",c._==="sendMessageChooseStickerAction"||c._==="sendMessageEmojiInteractionSeen");let p=t.firstElementChild;if(p?p.dataset.action!==c._&&p.replaceWith(this.getTypingElement(c)):(p=this.getTypingElement(c),t.prepend(p)),c._==="sendMessageEmojiInteractionSeen"){u?u.pop():u=[];const g=Vg(_e(c.emoticon));u.push(g)}const m=M(d,u);return m.classList.add("peer-typing-description"),t.childElementCount>1?t.lastElementChild.replaceWith(m):t.append(m),t}async getChatStatus(e,t){const s=t?void 0:await this.getPeerTyping(e.toPeerId(!0));if(s)return{cached:!0,result:Promise.resolve(s)};const i=await this.managers.acknowledged.appProfileManager.getChatFull(e),n=async r=>{let[l,c]=await Promise.all([da(e,void 0,void 0,void 0,r),this.managers.acknowledged.appProfileManager.getOnlines(e)]);return{cached:c.cached,result:c.result.then(d=>{if(d>1){const h=document.createElement("span");h.append(...pi([l,M("OnlineCount",[Ha(d)])],!1)),l=h}return l})}},a=i.result.then(n);return{cached:i.cached?(await a).cached:i.cached,result:a.then(r=>r.result)}}async getUserStatus(e,t){const s={cached:!0,result:Promise.resolve(void 0)},i=await this.managers.appUsersManager.getUser(e);if(!i||i.pFlags.self&&!t)return s;const n=br(i);if(!i.pFlags.bot&&!i.pFlags.support){let a=await this.getPeerTyping(e.toPeerId());if(!a&&i.status?._==="userStatusOnline"&&(a=document.createElement("span"),a.classList.add("online"),a.append(n)),a)return s.result=Promise.resolve(a),s}return s.result=Promise.resolve(n),s}async getPeerStatus(e,t,s){if(!e)return;let i;return e.isAnyChat()?i=this.getChatStatus(e.toChatId(),s):i=this.getUserStatus(e.toUserId(),t),i}async setPeerStatus(e){const{peerId:t,element:s,needClear:i,useWhitespace:n,middleware:a,ignoreSelf:r,noTyping:l}=e;if(!i){const u=s.querySelector(".peer-typing-container");if(u&&await this.getPeerTyping(t,u))return}const c=await this.getPeerStatus(t,r,l);if(!a())return;const d=async()=>{const u=c&&await c.result;if(a())return()=>dt(s,u||h)},h=n?cf:"";if(!c||c.cached||i===void 0)return d();if(i)return()=>(s.textContent=h,d().then(u=>u?.()))}setChoosingStickerTyping(e){this.managers.appMessagesManager.setTyping(this.chat.peerId,{_:e?"sendMessageCancelAction":"sendMessageChooseStickerAction"},void 0,this.chat.threadId)}isSamePeer(e,t){return e.peerId===t.peerId&&e.threadId===t.threadId&&(typeof e.type!=typeof t.type||e.type===t.type)}giftPremium(e){this.managers.appProfileManager.getProfile(e.toUserId()).then(t=>{ee.createPopup($F,e,t.premium_gifts)})}requestPhone(e){return Ct({titleLangKey:"ShareYouPhoneNumberTitle",button:{langKey:"OK"},descriptionLangKey:"AreYouSureShareMyContactInfoBot"}).then(()=>this.managers.appMessagesManager.sendContact(e,I.myId))}setPeerColorToElement({peerId:e,element:t,messageHighlighting:s,colorAsOut:i,color:n}){const a="--peer-color-rgb",r="--peer-border-background",l=fe.getPeer(e);let c,d;if(s||i){const u=jg(l).length,p=s?"message-empty":"message-out";c=`var(--${p}-primary-color-rgb)`,d=`var(--${p}-peer-${Math.max(1,u)}-border-background)`}else{const h=n?.color??Nu(l);if(h===-1){t.style.removeProperty(a),t.style.removeProperty(r);return}c=`var(--peer-${h}-color-rgb)`,d=`var(--peer-${h}-border-background)`}t.style.setProperty(a,c),t.style.setProperty(r,d)}async initGifting(){const e=await this.managers.apiManager.getAppConfig(),s=(await this.managers.appUsersManager.resolveUsername(e.premium_bot_username)).id.toPeerId(!1);this.managers.appMessagesManager.sendText({peerId:s,text:"/gift"}),this.setInnerPeer({peerId:s})}}const Qf=new KF;Ws&&(Ws.appImManager=Qf);const me=Qf,Ud=(o,e)=>{const t=Bi(e.target,"A");if(!t||t.classList.contains("timestamp"))return;const s=U(e.target,"spoiler");if(t instanceof HTMLAnchorElement&&(!s||o.classList.contains("is-spoiler-visible"))){const i=t.getAttribute("onclick");return!i||i.includes("showMaskedAlert")?void 0:(oe(e),()=>{t.click()})}};class ho extends Uf{constructor(e){super(new zu({processItem:a=>{const r=this.searchContext.inputFilter._==="inputMessagesFilterDocument",{mid:l,peerId:c}=a,d=Xs(a,!0);if(d&&!(r&&!ho.isMediaCompatibleForDocumentViewer(d)))return{element:null,mid:l,peerId:c}}}),["delete","forward"]),this.local=e,this.onPrevClick=async a=>{this.openMedia({message:this.local?a.message:await this.getMessageByPeer(a.peerId,a.mid),index:a.index,target:a.element,fromRight:-1})},this.onNextClick=async a=>{this.openMedia({message:this.local?a.message:await this.getMessageByPeer(a.peerId,a.mid),index:a.index,target:a.element,fromRight:1})},this.onDeleteClick=()=>{const a=this.target;ee.createPopup(Rl,a.peerId,[a.mid],te.Chat,()=>{this.target={element:this.content.media},this.close()})},this.onForwardClick=()=>{const a=this.target;a.mid&&ee.createPopup(va,{[a.peerId]:[a.mid]},()=>this.close())},this.onAuthorClick=async a=>{let{mid:r,peerId:l,message:c}=this.target;if(r&&r!==Number.MAX_SAFE_INTEGER){const d=this.searchContext.threadId;c||(c=await this.getMessageByPeer(l,r)),this.close(a).then(async()=>{if($e.isMobile){const h=ls.getTab(co);h&&h.close()}me.setInnerPeer({peerId:c.peerId,lastMsgId:r,threadId:d})})}},this.onDownloadClick=()=>{const{message:a,index:r}=this.target,l=Xs(a,!0,r);l&&cs.downloadToDisc({media:l,queueId:me.chat.bubbles.lazyLoadQueue.queueId})},this.listLoader.onEmptied=()=>{this.close()},this.content.caption=document.createElement("div"),this.content.caption.classList.add(Bs+"-caption","spoilers-container");let t;const s=()=>{t&&clearTimeout(t),t=window.setTimeout(()=>{t=void 0,this.content.caption.classList.remove("is-focused")},800)};this.content.caption.addEventListener("touchstart",()=>{$e.isMobile&&(this.content.caption.classList.add("is-focused"),t&&(clearTimeout(t),t=void 0),document.addEventListener("touchend",s,{once:!0}))});const i=new vi(this.content.caption);i.onAdditionalScroll=s,this.wholeDiv.append(this.content.caption),N(this.buttons.delete,this.onDeleteClick);const n=[this.btnMenuForward={icon:"forward",text:"Forward",onClick:this.onForwardClick},this.btnMenuDownload={icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick},this.btnMenuDelete={icon:"delete",className:"danger",text:"Delete",onClick:this.onDeleteClick}];this.setBtnMenuToggle(n),this.setListeners()}get searchContext(){return this.listLoader.searchContext}setListeners(){super.setListeners(),N(this.buttons.forward,this.onForwardClick),N(this.author.container,this.onAuthorClick);const e=t=>{const s=Ud(this.content.caption,t);if(s)return this.close().then(()=>{this.content.caption.removeEventListener("click",e,{capture:!0}),s()}),!1};this.content.caption.addEventListener("click",e,{capture:!0})}getMessageByPeer(e,t){return this.searchContext.isScheduled?this.managers.appMessagesManager.getScheduledMessageByPeer(e,t):this.managers.appMessagesManager.getMessageByPeer(e,t)}setCaption(e){const t=e.message;let s;if(t){const i=Xs(e,!0);s=_d({peerId:e.peerId,message:e,middleware:this.content.mover.middlewareHelper.get(),richTextOptions:{maxMediaTimestamp:i?.type==="video"&&i.duration||void 0,textColor:"white"}})}kt(this.content.caption.firstElementChild,s),this.content.caption.classList.toggle("hide",!t)}setSearchContext(e){return this.listLoader.setSearchContext(e),this}async openMedia({message:e,index:t,target:s,fromRight:i=0,reverse:n=!1,prevTargets:a=[],nextTargets:r=[],mediaTimestamp:l}){if(this.setMoverPromise)return this.setMoverPromise;const c=e.mid,d=e.fwd_from&&!e.fromId?Rn(e.fwd_from):e.fromId,h=Xs(e,!0,t),u=await this.managers.appPeersManager.noForwards(e.peerId),p=e._==="messageService",m=p||!await this.managers.appMessagesManager.canForward(e),g=(p?u:m)||!PC(e);[[[this.buttons.forward,this.btnMenuForward],m],[[this.buttons.download,this.btnMenuDownload],g],[[this.buttons.delete,this.btnMenuDelete],!await this.managers.appMessagesManager.canDeleteMessage(e)]].forEach(([v,w])=>{v.forEach(b=>{b instanceof HTMLElement?b.classList.toggle("hide",w):b.verify=()=>!w})}),this.wholeDiv.classList.toggle("no-forwards",g),this.setCaption(e);const y=super._openMedia({media:h,timestamp:e.date,fromId:d,fromRight:i,target:s,reverse:n,prevTargets:a,nextTargets:r,message:e,mediaTimestamp:l});return this.target.mid=c,this.target.peerId=e.peerId,this.target.message=e,this.target.index=t,y}static isMediaCompatibleForDocumentViewer(e){return e._==="photo"||ka.has(e.mime_type)&&e.size<=fm}}function xI({periodOptions:o,onOption:e,checked:t=0,users:s=1,discountInTitle:i}){const n=o[0]._==="premiumGiftCodeOption",a=o.slice().sort((u,p)=>u.months-p.months)[0],r=u=>In(u,a.currency,!1,!0,!0),l=n?void 0:{12:"PremiumTierAnnual",6:"PremiumTierSemiannual",1:"PremiumTierMonthly"},c=o.map((u,p)=>{const m=+u.amount/(n?u.users:1);let g=l?M(l[u.months]||"Months",[u.months]):eo(u.months,!1),f;if(n?f=M("Multiplier",[r(m),s]):u!==a&&(f=M("PricePerMonth",[r(+u.amount/u.months)])),u!==a){const w=document.createElement("span"),b=document.createElement("span");b.classList.add("popup-gift-premium-discount");const S=+a.amount*u.months/a.months,C=Math.round((1-+u.amount/S)*100);b.textContent="-"+C+"%",w.append(b,i?g:f),i?g=w:f=w}const y=new pt({checked:p===t,round:!0,name:"premium-period",asRadio:!0}),v=new ve({title:g,checkboxField:y,clickable:!0,subtitle:f,rightTextContent:r(n?m*s:u.amount)});return v.container.classList.add("popup-gift-premium-option"),v}),d=document.createElement("form");d.classList.add("popup-gift-premium-options"),d.append(...c.map(u=>u.container));const h=()=>o[c.findIndex(u=>u.checkboxField.checked)];return d.addEventListener("change",()=>{e(h())}),e(h()),d}function AI(o){const e=o.gift;if(!e)return;let t,s;e._==="payments.checkedGiftCode"?t=at(e.from_id)||o.peerId:t=o.isOut?I.myId:o.peerId,s=o.isOut?o.peerId:I.myId,s||(s=I.myId);const i=s!==I.myId,n=e._!=="payments.checkedGiftCode"||!e.used_date;return{fromPeerId:t,toPeerId:s,isOutbound:i,isUnclaimed:n,gift:e}}class WF{constructor(e){this.options=e,this.onTabScroll=()=>{const{tab:t,options:s}=this,{scrollTop:i,scrollHeight:n}=t;s.header.classList.toggle("is-visible",i>100),s.header.classList.toggle("not-top",i>0),t.classList.toggle("not-bottom",n-i>t.offsetHeight)},this.initPremiumTab(e)}async initPremiumTab(e){const t=this.tab=document.createElement("div");t.append(e.header,e.body),t.classList.add("premium-promo-tab","not-bottom","scrollable","scrollable-y"),t.addEventListener("scroll",this.onTabScroll),e.body.append(...[this.createImageContainer(),await this.createHeading(),e.type==="premium"&&!e.isPremiumActive&&this.createOptionsForm(),this.createFeaturesContainer()].filter(Boolean)),e.container.classList.add("fixed-size")}async createHeading(){const e=document.createElement("div");e.classList.add("popup-premium-heading-text-container");const t=document.createElement("div");t.classList.add("popup-premium-heading-text-title");const s=document.createElement("div");s.classList.add("popup-premium-heading-text-description");const i={onlyFirstName:!0};let n,a;const r=AI(this.options);if(r){t.classList.add("smaller-text");const{fromPeerId:l,toPeerId:c,isOutbound:d,isUnclaimed:h,gift:u}=r,p=M("GiftMonths",[u.months]);if(d?n=M("GiftModal.Title.You",[await Oe({...i,peerId:c}),p]):n=M(l?"TelegramPremiumUserGiftedPremiumDialogTitleWithPlural":"TelegramPremiumUserGiftedPremiumDialogTitleWithPluralSomeone",[l&&await Oe({...i,peerId:l}),p].filter(Boolean)),d)a=M("TelegramPremiumUserGiftedPremiumOutboundDialogSubtitle",[await Oe({...i,peerId:c})]);else if(u._==="messageActionGiftPremium")a=M("TelegramPremiumUserGiftedPremiumDialogSubtitle");else{const m="https://t.me/giftcode/"+u.slug,g=new xd({button:!1,listenerSetter:this.options.listenerSetter,url:m});let f;h?f=M("GiftCode.ShareReceived",[ni(async()=>{this.close(),ya.shareGiftLink(m)})]):f=M("BoostingLinkUsed"),a=document.createElement("div"),a.append(f,g.container)}}else n=this.options.isPremiumActive?M("TelegramPremiumSubscribedTitle"):M("Premium.Boarding.Title"),a=this.options.isPremiumActive?M("TelegramPremiumSubscribedSubtitle"):M("Premium.Boarding.Info");return t.append(n),s.append(a),e.append(t,s),e}createFeaturesContainer(){const e=document.createElement("div");return e.classList.add("popup-premium-features-container"),e.append(...[...this.createFeatures(this.options.features,this.options.order),this.options.type==="premium"&&this.options.premiumPromo.status_text&&this.createStatusText()].filter(Boolean)),e}createImageContainer(){const e=document.createElement("div");e.classList.add("popup-premium-header-image-container");const t=document.createElement("img");return t.src=`assets/img/premium-star${window.devicePixelRatio>1?"@2x":""}.png`,t.classList.add("popup-premium-header-image"),e.append(t),e}createStatusText(){const e=document.createElement("div");e.classList.add("popup-premium-status-text");const t=Yt(this.options.premiumPromo.status_text,{entities:this.options.premiumPromo.status_entities});kt(e,t);const s=i=>{const n=Ud(e,i);n&&this.close(()=>{e.removeEventListener("click",s,{capture:!0}),n()})};return e.addEventListener("click",s,{capture:!0}),e}createOptionsForm(){return xI({periodOptions:this.options.premiumPromo.period_options,onOption:e=>{this.selectPeriod?.(e)}})}createFeatures(e,t){return t.map((s,i)=>{const n=e.find(l=>l.feature===s),a=new ve({titleLangKey:n.titleLangKey,titleLangArgs:n.titleLangArgs,subtitleLangKey:n.subtitleLangKey,subtitleLangArgs:n.subtitleLangArgs,clickable:async()=>{this.transition(1),await this.selectFeature(n.feature)}}),r=a.createMedia("small");if(r.classList.add("premium-promo-tab-icon"),r.append(Le(n.icon)),r.style.backgroundColor=_y[i],n.new){const l=M("New");l.classList.add("row-title-badge"),a.title.append(l),l.style.backgroundColor=_y[i]}return a.container})}}class jF{async construct(e){this.limits=document.createElement("div"),this.limits.classList.add("limits-list");const t=e.limits.map(async(i,n)=>{const[a,r]=i.limitType?await Promise.all([e.managers.apiManager.getLimit(i.limitType,!1),e.managers.apiManager.getLimit(i.limitType,!0)]):[],l=document.createElement("div");l.classList.add("limit-text-container"),n||l.classList.add("no-margin");const c=document.createElement("div");c.classList.add("limit");const d=document.createElement("div");d.classList.add("limit-title"),Zt(d,i.titleLangKey,i.titleLangArgs);const h=document.createElement("div");h.classList.add("limit-subtitle"),Zt(h,i.subtitleLangKey,i.subtitleLangArgs);const u=new Vu({limitFree:a??i.free,limitPremium:r??i.premium,color:i.backgroundColor});return l.append(d,h),c.append(l,u.container),c}),s=await Promise.all(t);return this.limits.append(...s),this.limits}}class qF{constructor(e){this.avatar=es({middleware:e.middleware,size:84,isBig:!0,withStories:!0,peerId:e.premiumPromo.users[0].id.toPeerId(!1)});const t=document.createElement("div");t.classList.add("story-features-list"),this.features=t,e.features.forEach(s=>{const i=document.createElement("div");i.classList.add("story-feature");const n=new ve({titleLangKey:s.titleLangKey,titleLangArgs:s.titleLangArgs,subtitleLangKey:s.subtitleLangKey,subtitleLangArgs:s.subtitleLangArgs,icon:s.icon,iconClasses:["row-icon-custom-color"],clickable:!1});n.container.style.setProperty("--custom-icon-color",s.iconColor),i.append(n.container),t.append(i)})}}class QF{constructor(e){this.initStickersCarousel(e)}cleanup(){this.destroyed=!0}assignVisibility(e,t){this.container.children[e].classList.add("visible"),this.container.children[this.activeStickerIndex].classList.add("active"),this.container.children[t].classList.add("visible")}runStickerAnimation(){Dc({doc:this.stickers[this.activeStickerIndex],middleware:this.stickersMiddlewareHelper.get(),side:"left",size:200*Ub,target:this.container.children[this.activeStickerIndex],play:!0,fullThumb:fo(this.stickers[this.activeStickerIndex]),relativeEffect:!0,loopEffect:!1,onUnmount:()=>{if(this.ignoreUnmount){this.ignoreUnmount=void 0;return}this.destroyed||this.previousSticker()}})}previousSticker(){const e=this.stickers.length;this.stickersMiddlewareHelper.clean(),Array.from(this.container.children).forEach(i=>i.classList.remove("top-sibling","active","bottom-sibling","visible")),this.activeStickerIndex-1<0?this.activeStickerIndex=e-1:--this.activeStickerIndex;const t=this.activeStickerIndex===0?e-1:this.activeStickerIndex-1,s=this.activeStickerIndex===e-1?0:this.activeStickerIndex+1;this.assignVisibility(t,s),this.assignSiblings(),this.runStickerAnimation()}nextSticker(){const e=this.stickers.length;this.stickersMiddlewareHelper.clean(),Array.from(this.container.children).forEach(i=>i.classList.remove("top-sibling","active","bottom-sibling","visible")),this.activeStickerIndex+1===e?this.activeStickerIndex=0:++this.activeStickerIndex;const t=this.activeStickerIndex-1<0?e-1:this.activeStickerIndex-1,s=this.activeStickerIndex===e-1?0:this.activeStickerIndex+1;this.assignVisibility(t,s),this.assignSiblings(),this.runStickerAnimation()}assignSiblings(){for(let t=-3;t<=3;++t){const s=(this.activeStickerIndex+t+this.stickers.length)%this.stickers.length,i=this.container.children[s];t<0?i.classList.add("top-sibling"):t>0&&i.classList.add("bottom-sibling")}}async initStickersCarousel(e){e.topSection.classList.add("no-padding");const t=await e.managers.appStickersManager.getPromoPremiumStickers();this.stickersMiddlewareHelper=xt(),this.lazyLoadQueue=new Ga,this.superStickerRenderer=new sp({regularLazyLoadQueue:this.lazyLoadQueue,group:"none",managers:e.managers,visibleRenderOptions:{withLock:!1,width:200,height:200}}),this.stickers=t,this.container=document.createElement("div"),this.container.classList.add("premium-stickers-carousel"),this.activeStickerIndex=Math.round(this.stickers.length/2),t.forEach((s,i)=>{const n=document.createElement("div");n.classList.add("premium-stickers-carousel-item");const a=this.superStickerRenderer.renderSticker(s);n.append(a),n.addEventListener("click",r=>{r.stopPropagation(),i!==this.activeStickerIndex&&(this.ignoreUnmount=!0,n.classList.contains("bottom-sibling")&&this.nextSticker(),n.classList.contains("top-sibling")&&this.previousSticker())}),this.container.append(n)}),this.assignVisibility(this.activeStickerIndex-1,this.activeStickerIndex+1),this.assignSiblings(),this.runStickerAnimation(),e.topSection.addEventListener("click",s=>{s.stopPropagation()}),e.topSection.append(this.container)}}class YF{constructor(e){this.scrollListener=t=>{const s=t.target,{scrollTop:i,scrollHeight:n}=s;s.classList.toggle("top-border",i>0),s.classList.toggle("bottom-border",n-i>s.clientHeight)},this.middleware=e.middleware,this.header=e.header,this.managers=e.managers,this.premiumPromo=e.premiumPromo,this.features=e.features,this.container=document.createElement("div"),this.container.classList.add("carousel-container"),this.carouselItems=this.features.map(t=>{const s=document.createElement("div");if(s.classList.add("carousel-item","tabs-tab"),t.videoPosition||t.type==="premium-stickers"){const i=document.createElement("div");i.classList.add("carousel-item-content-title");const n=document.createElement("div");n.classList.add("carousel-item-content-subtitle");const a=document.createElement("div");a.classList.add("carousel-item-content-bottom-section"),i.append(M(t.titleLangKey,t.titleLangArgs)),n.append(M(t.subtitleLangKey,t.subtitleLangArgs)),a.append(i),a.append(n),s.append(a)}return s}),this.header.classList.add("absolute"),this.carouselItemsContainer=document.createElement("div"),this.carouselItemsContainer.classList.add("carousel-items-container","tabs-container"),this.selectTab=Na({content:this.carouselItemsContainer,type:"premiumTabs",transitionTime:250,animateFirst:!1}),this.carouselItemsContainer.append(...this.carouselItems),this.container.append(this.carouselItemsContainer),this.features.forEach((t,s)=>{let i=this.carouselItems[s].querySelector(".carousel-item-content-top-section");if(i||(i=document.createElement("div"),i.classList.add("carousel-item-content-top-section"),this.carouselItems[s].prepend(i)),t.videoPosition){this.downloadVideo(s);let n=i.querySelector(".device-frame");if(!n){const a=document.createElement("img");a.classList.add("device-frame-image"),n=document.createElement("div"),n.classList.add("device-frame"),n.append(a),Kn(a,"assets/img/android-device.svg"),n.classList.toggle("bottom",t.videoPosition!=="top"),i.append(n)}}}),this.initCarouselControls(e)}cleanup(){this.premiumStickersCarousel?.cleanup()}ready(e){this.outerLayoutUpdater=e}async buildSlide(e){const t=this.features[e],s=this.carouselItems[e].querySelector(".carousel-item-content-top-section");if(s.removeEventListener("scroll",this.scrollListener),s.removeAttribute("style"),t.videoPosition)await this.appendVideo(e,this.carouselItems[e].querySelector(".device-frame"));else switch(t.type!=="premium-stickers"&&s.addEventListener("scroll",this.scrollListener),t.type){case"limits":{if(!!!s.querySelector(".limits-list")){const n=new jF,a=n.construct({limits:t.content,managers:this.managers}),r=n.limits;s.append(r),s.classList.add("scrollable","scrollable-y","no-scrollbar","bottom-border","top-margin"),await a}break}case"upgraded-stories":{if(!!!s.querySelector(".story-features-list")){const n=new qF({middleware:this.middleware,features:t.content,premiumPromo:this.premiumPromo}),a=document.createElement("div");a.classList.add("above-top-section"),a.prepend(n.avatar.node);const r=M(t.titleLangKey);r.classList.add("above-top-section-title"),a.append(r),this.carouselItems[e].prepend(a),this.carouselItems[e].classList.add("upgraded-stories"),s.append(n.features)}s.style.position="relative",s.classList.add("scrollable","scrollable-y","no-scrollbar","bottom-border");break}case"premium-stickers":{!!s.querySelector(".premium-stickers-carousel")||(this.premiumStickersCarousel=new QF({topSection:s,managers:this.managers}));break}}}async processSlideContent(e){let t=this.header.querySelector(".popup-title");const s=this.header.querySelector(".back-button"),i=!!this.features[e].headerLangKey;i&&(t.remove(),t=document.createElement("div"),t.classList.add("popup-title"),t.append(M(this.features[e].headerLangKey)),this.header.append(t)),this.header.classList.toggle("is-visible",!!i),i||this.header.classList.remove("not-top"),this.features[e].videoPosition||this.features[e].type==="premium-stickers"?(s.style.color="#ffffff",this.carouselItems[e].classList.remove("feature-background"),this.carouselItemsContainer.classList.remove("full")):(s.style.color="var(--secondary-text-color)",this.carouselItems[e].classList.add("feature-background"),this.carouselItemsContainer.classList.add("full")),await this.buildSlide(e)}async selectSlide(e){this.selectedFeature=e;const t=this.features.findIndex(i=>i.feature===e);await this.processSlideContent(t);const s=this.slideIndex;this.slideIndex=t,this.outerLayoutUpdater?.(this.features.find(i=>i.feature===e)),this.dots(e,t),this.selectTab(t,s!==void 0)}dots(e,t){const s=this.dotsContainer.querySelectorAll(".popup-premium-controls-dot");s.forEach(c=>{c.classList.remove("active"),c.style.transform=""}),this.dotsContainer.querySelector(`[data-feature=${e}]`)?.classList.add("active");const n=t/2-1<1?0:Math.ceil(t/2),a=this.features.length,r=a-1,l=Math.ceil(a/2)-1;if(n<1){const c=s[r-l+n];s[r-l+n-1].style.transform="scale(.75)",c&&(c.style.transform="scale(.5)")}else if(n>=1&&n<l){const c=s[r-l+n];s[n+1].style.transform="scale(.75)",s[n].style.transform="scale(.5)",s[r-l+n-1].style.transform="scale(.75)",c&&(c.style.transform="scale(.5)")}else s[n+1].style.transform="scale(.75)",s[n].style.transform="scale(.5)";this.dotsContainer.style.setProperty("--amount",""+a),this.dotsContainer.style.setProperty("--start",""+n)}initCarouselControls(e){this.controlsContainer=document.createElement("div"),this.controlsContainer.classList.add("popup-premium-controls"),this.dotsContainer=document.createElement("div"),this.dotsContainer.classList.add("popup-premium-controls-dots"),this.controlsContainer.append(this.dotsContainer),this.features.forEach((t,s)=>this.dotsContainer.append(this.createFeatureDot(e,t.feature,s))),N(this.dotsContainer,t=>{t.stopPropagation()},{listenerSetter:e.listenerSetter}),N(this.container,t=>{const s=this.container.getBoundingClientRect(),i=this.features.findIndex(r=>r.feature===this.selectedFeature),n=s.left+s.width/2<t.clientX?1:-1,a=this.features[i+n];a&&this.selectSlide(a.feature)},{listenerSetter:e.listenerSetter})}createFeatureDot(e,t,s){const i=document.createElement("div");return i.classList.add("popup-premium-controls-dot"),t===this.selectedFeature&&i.classList.add("active"),i.dataset.feature=t,N(i,n=>{oe(n),t!==this.selectedFeature&&this.selectSlide(t)},{listenerSetter:e.listenerSetter}),i}async downloadVideo(e,t,s=!1){const i=this.features[e].video;if(!i)return{video:void 0,loadPromise:new Promise(()=>{})};const n=await qn({doc:i,withoutPreloader:!0,noInfo:!0,noPlayButton:!0,middleware:this.middleware,...s&&{container:t}});return this.features[e].wrappedVideo=n}async appendVideo(e,t){if(this.features[e].builded)return;this.features[e].builded=!0;let s,i,n=this.features[e].wrappedVideo;n?.loaded||(s=document.createElement("div"),s.classList.add("shimmer"),i=Le("star","device-frame-preload-icon"),t.append(...[n?.thumb?.images?.thumb,s,i].filter(Boolean))),n?t.append(this.features[e].wrappedVideo.video):(n=await this.downloadVideo(e,t,!0),n.loadPromise.then(()=>{n.loaded=!0})),s&&n.loadPromise.then(()=>{s.remove(),i.remove()})}}class XF{constructor(e){this.backBtn=it("left popup-close back-button",{noRipple:!0}),this.initFeaturesTab(e)}cleanup(){this.featureCarousel?.cleanup()}initFeaturesTab(e){const t=document.createElement("div");t.classList.add("premium-feature-tab"),e.header.querySelector(".popup-close").replaceWith(this.backBtn),t.append(e.header),this.featureCarousel=new YF({...e,header:e.header}),t.append(this.featureCarousel.container,this.featureCarousel.controlsContainer),this.tab=t,N(this.backBtn,()=>{this.featureCarousel.slideIndex=void 0,this.transition(0)},{listenerSetter:e.listenerSetter})}setCarouselSlide(e){return this.featureCarousel.selectSlide(e)}}class Vt extends ee{constructor(e={}){super("popup-premium",{overlayClosable:!0,closable:!0,body:!0,title:"Premium.Boarding.Title"}),this.prepareArguments=async t=>{const[s,i]=await Promise.all([t._titleLangArgs,t._subtitleLangArgs].map(n=>n&&n(this.managers)));return{titleLangArgs:s,subtitleLangArgs:i}},this.selectFeature=async t=>{this.selectedFeature=this.props.features.find(s=>s.feature===t),await this.featureSlideTab.setCarouselSlide(t),this.updateActionLayout(this.selectedFeature)},this.updateActionLayout=t=>{if(!this.actionButtonText)return;if(this.props.type==="gift"){const{isOutbound:n,isUnclaimed:a}=this.giftDetails;!n&&a&&this.actionButtonText.compareAndUpdate({key:"GiftPremiumActivateForFree"});return}if(this.props.isPremiumActive)return;this.actionButtonText.compareAndUpdate({key:t?.actionTitleLangKey||"Premium.Boarding.Subscribe",args:[this.wrapCurrency(+this.option.amount/this.option.months)]});const s=this.actionButton.querySelector(".tgico"),i=t?.actionIcon&&Le(t.actionIcon,"row-icon","action-button-icon");i?s?s?.replaceWith(i):this.actionButton.append(i):s?.remove()},this.close=t=>{t&&this.addEventListener("closeAfterTimeout",t),this.hide()},It(this,e),this.initTabs()}cleanup(){super.cleanup(),this.featureSlideTab.cleanup(),this.promoSlideTab.tab.remove()}filterOrder(e,t){return(t||[]).filter(s=>{const i=!!Ty[s];if(!i){console.warn("premium feature is not implemented",s);const n=e.video_sections.indexOf(s);n!==-1&&(e.video_sections.splice(n,1),e.videos.splice(n,1))}return i})}async createFeatures(e,t){return Promise.all(t.map(async s=>{const i=Ty[s];let n=i.content;n&&(n=await Promise.all(n.map(async l=>({...await this.prepareArguments(l),...l}))));const a=e.videos[e.video_sections.indexOf(s)],r={...await this.prepareArguments(i),...i,content:n,video:a};return a&&(r.videoPosition??(r.videoPosition="bottom")),r}))}async initTabs(){const[e,t]=await Promise.all([this.managers.appPaymentsManager.getPremiumPromo(),this.managers.apiManager.getAppConfig()]),s=this.filterOrder(e,t.premium_promo_order),i=I.premium;this.props={order:s,features:await this.createFeatures(e,s),premiumPromo:e,managers:this.managers,middleware:this.middlewareHelper.get(),appConfig:t,isPremiumActive:i,gift:this.gift,peerId:this.peerId||this.stack?.peerId,isOut:this.isOut||this.stack?.isOut,type:this.gift?"gift":"premium",stack:this.stack,listenerSetter:this.listenerSetter},this.giftDetails=AI(this.props);const n=this.tabsContainer=document.createElement("div");n.classList.add("tabs-container","premium-tabs"),this.option=this.props.premiumPromo.period_options[0];const a=this.props.premiumPromo.period_options.slice().sort((c,d)=>c.months-d.months)[0];this.wrapCurrency=c=>In(c,a.currency,!1,!0,!0);const r=document.createElement("div");r.classList.add("popup-header-background"),this.header.prepend(r),this.createTransitionSlider(),this.createActionButton(),this.createPromoSlideTab(),this.createFeatureSlideTab();const l=[this.promoSlideTab.tab,this.featureSlideTab.tab].filter(Boolean);l.forEach(c=>{c.classList.add("tabs-tab","premium-tab")}),n.append(...l),this.container.append(...[n,this.actionButtonContainer].filter(Boolean)),this.actionButtonContainer||this.container.classList.add("no-button"),this.feature&&await this.selectFeature(this.feature),this.transition(this.feature?1:0),this.show()}createTransitionSlider(){this.transition=Na({content:this.tabsContainer,type:"navigation",transitionTime:150,animateFirst:!1,onTransitionEnd:e=>{this.selectedTab=e,e?this.featureSlideTab.featureCarousel.ready(this.updateActionLayout):this.updateActionLayout()}})}createActionButton(){if(this.props.type==="gift"&&(this.giftDetails.isOutbound||!this.giftDetails.isUnclaimed))return;this.actionButtonText=new ke.IntlElement({key:"OK"}),this.actionButtonContainer=document.createElement("div"),this.actionButtonContainer.classList.add("action-button-container"),this.actionButton=ze("btn-primary popup-gift-premium-confirm action-button shimmer"),this.actionButton.append(this.actionButtonText.element);let e;this.props.type==="gift"?e=()=>{const t=this.props.gift;ya.applyGiftCode(t.slug,this.actionButton,this)}:e=()=>{if(this.props.isPremiumActive){this.hide();return}this.buyPremium()},N(this.actionButton,e,{listenerSetter:this.listenerSetter,once:!0}),this.actionButtonContainer.append(this.actionButton)}createPromoSlideTab(){this.promoSlideTab=new WF({container:this.tabsContainer,header:this.header,body:this.body,...this.props}),this.promoSlideTab.transition=this.transition,this.promoSlideTab.selectFeature=this.selectFeature,this.promoSlideTab.selectPeriod=e=>{this.option=e,this.updateActionLayout()},this.promoSlideTab.close=this.close}createFeatureSlideTab(){this.featureSlideTab=new XF({header:this.header.cloneNode(!0),actionButtonContainer:this.actionButtonContainer,...this.props}),this.featureSlideTab.transition=this.transition}buyPremium(){this.close(()=>{me.openUrl(this.option.bot_url)})}static show(...e){ee.createPopup(Vt,...e)}}const ZF={pin:{title:"LimitReached",description:"LimitReachedPinDialogs",descriptionPremium:"LimitReachedPinDialogsPremium",descriptionLocked:"LimitReachedPinDialogsLocked",icon:"limit_pin"},folders:{title:"LimitReached",description:"LimitReachedFolders",descriptionPremium:"LimitReachedFoldersPremium",descriptionLocked:"LimitReachedFoldersLocked",icon:"limit_folders"},folderPeers:{title:"LimitReached",description:"LimitReachedChatInFolders",descriptionPremium:"LimitReachedChatInFoldersPremium",descriptionLocked:"LimitReachedChatInFoldersLocked",icon:"limit_folders"},chatlistInvites:{title:"LimitReached",description:"LimitReachedSharedFolderInvites",descriptionPremium:"LimitReachedSharedFolderInvitesPremium",descriptionLocked:"LimitReachedSharedFolderInvitesLocked",icon:"limit_link"},savedPin:{title:"LimitReached",description:"LimitReachedPinDialogs",descriptionPremium:"LimitReachedPinDialogsPremium",descriptionLocked:"LimitReachedPinDialogsLocked",icon:"limit_pin"}};class JF extends Ss{constructor(e,t){super("popup-limit",{buttons:e.isPremium===void 0?[{langKey:"LimitReached.Ok",isCancel:!0}]:e.isPremium?[{langKey:"OK",isCancel:!0}]:[{langKey:"IncreaseLimit",callback:()=>{Vt.show({feature:e.feature})},iconRight:"premium_double"},{langKey:"Cancel",isCancel:!0}],descriptionLangKey:e.isPremium===void 0?t.descriptionLocked:e.isPremium?t.descriptionPremium:t.description,descriptionLangArgs:e.isPremium?[e.limitPremium]:[e.limit,e.limitPremium],titleLangKey:t.title});const s=new Vu({limitPremium:e.limitPremium,hint:{icon:t.icon,content:""+(e.isPremium?e.limitPremium:e.limit)}});e.isPremium!==void 0?s.setProgress(e.isPremium?1:.5):s.container.querySelector(".limit-line")?.remove(),this.description.before(s.container),s._setHintActive()}}async function ua(o){const e="double_limits",t=ZF[o],[s,i,n]=await Promise.all([I.managers.apiManager.getAppConfig(),...[!1,!0].map(r=>I.managers.apiManager.getLimit(o,r))]),a=s.premium_purchase_blocked;new JF({isPremium:a?void 0:I.premium,limit:i,limitPremium:n,feature:e},t).show()}class eR{constructor(e){this.managers=e,this.onArchiveClick=async()=>{const t=await this.managers.appMessagesManager.getDialogOnly(this.peerId);t&&this.managers.appMessagesManager.editPeerFolders([t.peerId],+!t.folder_id)},this.onHideTopicClick=()=>{this.managers.appChatsManager.editForumTopic({chatId:this.peerId.toChatId(),topicId:this.threadId,hidden:!0})},this.onToggleTopicClick=()=>{this.managers.appChatsManager.editForumTopic({chatId:this.peerId.toChatId(),topicId:this.threadId,closed:!this.dialog.pFlags.closed})},this.onPinClick=()=>{const{peerId:t,filterId:s,threadId:i,dialog:n}=this,a=la(n);this.managers.appMessagesManager.toggleDialogPin({peerId:t,filterId:s,topicOrSavedId:i}).catch(async r=>{(r.type==="PINNED_DIALOGS_TOO_MUCH"||r.type==="PINNED_TOO_MUCH")&&(a?ua("savedPin"):i?this.managers.apiManager.getLimit("topicPin").then(l=>{Ee({langPackKey:"LimitReachedPinnedTopics",langPackArguments:[l]})}):ra.has(s)?ua("pin"):Ee({langPackKey:"PinFolderLimitReached"}))})},this.onUnmuteClick=()=>{this.managers.appMessagesManager.togglePeerMute({peerId:this.peerId,mute:!1,threadId:this.threadId})},this.onMuteClick=()=>{ee.createPopup(Cw,this.peerId,this.threadId)},this.onUnreadClick=async()=>{const{peerId:t,dialog:s}=this;s.unread_count?this.threadId?this.managers.appMessagesManager.readHistory(t,s.top_message,this.threadId):this.managers.appMessagesManager.markDialogUnread(t,!0):this.threadId||this.managers.appMessagesManager.markDialogUnread(t)},this.onDeleteClick=()=>{ee.createPopup(Hu,this.peerId,void 0,void 0,this.threadId)}}attach(e){ln({listenTo:e,buttons:this.getButtons(),appendTo:document.getElementById("page-chats"),onOpen:async(t,s)=>{this.li=s,s.classList.add("menu-open"),this.peerId=s.dataset.peerId.toPeerId(),this.threadId=+s.dataset.threadId||void 0,this.dialog=await this.managers.dialogsStorage.getAnyDialog(this.peerId,this.threadId),this.filterId=this.threadId?void 0:Xe.filterId,this.canManageTopics=Fa(this.dialog)?await this.managers.dialogsStorage.canManageTopic(this.dialog):void 0},onOpenBefore:async()=>{const t=this.threadId?"Delete":await this.managers.appPeersManager.getDeleteButtonText(this.peerId),s=this.buttons[this.buttons.length-1];s?.element&&s.element.lastChild.replaceWith(M(t))},onClose:()=>{this.li.classList.remove("menu-open"),this.li=this.peerId=this.dialog=this.filterId=this.threadId=this.canManageTopics=void 0},findElement:t=>Bi(t.target,Nl)})}getButtons(){return this.buttons??(this.buttons=[{icon:"newtab",text:"OpenInNewTab",onClick:e=>{Xe.openDialogInNewTab(this.li),oe(e)},verify:()=>qL},{icon:"topics",text:"TopicViewAsTopics",onClick:()=>{me.toggleViewAsMessages(this.peerId,!1)},verify:()=>!!(this.dialog&&this.dialog.pFlags.view_forum_as_messages)},{icon:"topics",text:"SavedViewAsChats",onClick:()=>{me.toggleViewAsMessages(this.peerId,!1)},verify:()=>this.peerId===I.myId&&!Tc.settings.savedAsForum&&!this.threadId},{icon:"message",text:"SavedViewAsMessages",onClick:()=>{me.toggleViewAsMessages(this.peerId,!0)},verify:()=>this.peerId===I.myId&&Tc.settings.savedAsForum&&!this.threadId},{icon:"unread",text:"MarkAsUnread",onClick:this.onUnreadClick,verify:async()=>!this.threadId&&!await this.managers.appMessagesManager.isDialogUnread(this.dialog)},{icon:"readchats",text:"MarkAsRead",onClick:this.onUnreadClick,verify:()=>this.managers.appMessagesManager.isDialogUnread(this.dialog)},{icon:"pin",text:"ChatList.Context.Pin",onClick:this.onPinClick,verify:async()=>la(this.dialog)?!this.dialog.pFlags.pinned:this.threadId&&!this.canManageTopics?!1:!(this.filterId!==void 0&&this.filterId>1?(await this.managers.appMessagesManager.getFilter(this.filterId)).pinnedPeerIds.includes(this.dialog.peerId):!!this.dialog.pFlags?.pinned)},{icon:"unpin",text:"ChatList.Context.Unpin",onClick:this.onPinClick,verify:async()=>la(this.dialog)?!!this.dialog.pFlags.pinned:this.threadId&&!this.canManageTopics?!1:this.filterId!==void 0&&this.filterId>1?(await this.managers.appMessagesManager.getFilter(this.filterId)).pinnedPeerIds.includes(this.dialog.peerId):!!this.dialog.pFlags?.pinned},{icon:"mute",text:"ChatList.Context.Mute",onClick:this.onMuteClick,verify:async()=>this.peerId!==I.myId&&!await this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.dialog.peerId,threadId:this.threadId})},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:this.onUnmuteClick,verify:()=>this.peerId!==I.myId&&this.managers.appNotificationsManager.isPeerLocalMuted({peerId:this.dialog.peerId,threadId:this.threadId})},{icon:"archive",text:"Archive",onClick:this.onArchiveClick,verify:()=>!this.threadId&&this.dialog.folder_id!==Vi&&this.peerId!==I.myId},{icon:"unarchive",text:"Unarchive",onClick:this.onArchiveClick,verify:()=>this.filterId===Vi&&this.peerId!==I.myId},void 0,{icon:"lock",text:"CloseTopic",onClick:this.onToggleTopicClick,verify:()=>this.canManageTopics&&!this.dialog.pFlags.closed},{icon:"lockoff",text:"RestartTopic",onClick:this.onToggleTopicClick,verify:()=>this.canManageTopics&&!!this.dialog.pFlags.closed},{icon:"folder",text:"FilterAddTo",onClick:()=>{},inner:async()=>({buttons:(await this.managers.filtersStorage.getDialogFilters()).map(t=>{const s=document.createElement("span");return s.append(_e(t.title)),{icon:"folder",textElement:s,onClick:()=>{}}})}),verify:()=>!1},{icon:"delete",className:"danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>this.threadId?la(this.dialog)?!0:this.canManageTopics?this.dialog.id!==Id:!1:!0}]),this.buttons=this.buttons.filter(Boolean)}}function tR(o,e,t){let s;if(typeof e=="string"?s=e:e?.pFlags.out&&(e.error?s="sendingerror":e.pFlags.is_outgoing?s="sending":e.pFlags.unread?s="check":s="checks"),!s){o.textContent="",o.classList.add("hide");return}const i=o.lastElementChild;if(i&&i.classList.contains(_a(s)))return;const n=Le(s,"sending-status-icon","sending-status-icon-"+s);o.append(n),o.classList.remove("hide"),i?.remove()}const Hd=window.devicePixelRatio,sc=20*Hd,pb=2.5*Hd,dm=2*Hd,sR=1*Hd,hm=3,mb=4,iR=12,gb=1e3;function nR(o=!1){const e=document.createElement("canvas");e.width=e.height=sc;const t=e.getContext("2d"),s=hm*dm+(hm-1)*pb,i=(sc-s)/2,n=Date.now();let a=!1;const r=()=>{if(e.isConnected)a||(a=e.isConnected);else if(a)return!1;const l=Date.now(),c=Iw((l-n)%gb,0,1,gb);t.clearRect(0,0,sc,sc),t.fillStyle=o&&!$e.isMobile?Ls.getProperty("primary-color"):"#fff";for(let d=0;d<hm;++d){const h=i+d*dm+d*pb;let u;c>=.5?u=d%2?2-c*2:(c-.5)*2:u=d%2?c*2:1-c*2;let p=mb+u*(iR-mb);p*=Hd;const m=(sc-p)/2;Eh(t,h,m,dm,p,sR)}return!0};return{canvas:e,startAnimation:()=>{ll(r),r()},setActive:l=>{o=l,r()}}}const Nl="A";function fb(o,e){o[e]?.reject();const s=o[e]=Pt();s.catch(()=>{}).finally(()=>{o[e]===s&&delete o[e]});const i=so(()=>o[e]===s);return{deferred:s,middleware:i}}const ic=22,Cu=250;class Yf extends Wu{constructor(e){super({getIndex:t=>this.managers.dialogsStorage.getDialogIndex(this.virtualFilterId??t.id,this.indexKey,this.virtualFilterId?t.id:void 0),onDelete:t=>{t.dialogElement.remove(),this.onListLengthChange?.()},onSort:(t,s)=>{const i=t.dom.listEl.parentElement!==this.list;Ps(t.dom.listEl,this.list,s),i&&this.onListLengthChange?.()},onElementCreate:async t=>{const s=[],i=ms.addListDialog({peerId:this.virtualFilterId??t.id,loadPromises:s,isBatch:!0,threadId:this.virtualFilterId?t.id:void 0,isMainList:this.indexKey==="index_0",controlled:!0,wrapOptions:void 0});return t.dom=i.dom,t.dialogElement=i,await Promise.all(s),t},updateElementWith:Db,log:e.log}),It(this,e),this.isSavedDialogs=this.virtualFilterId===I.myId}clear(){this.list.replaceChildren(),this.elements.forEach(e=>{e.dialogElement.destroy()}),super.clear()}}const aR={bigger:54,abitbigger:42,small:32},ty=class ty extends ve{constructor({peerId:e,rippleEnabled:t=!0,onlyFirstName:s=!1,meAsSaved:i=!0,avatarSize:n="bigger",autonomous:a,loadPromises:r,fromName:l,noIcons:c,threadId:d,wrapOptions:h={},isMainList:u,withStories:p,controlled:m}){super({clickable:!0,noRipple:!t,havePadding:!d,title:!0,titleRightSecondary:!0,subtitle:!0,subtitleRight:!0,noWrap:!0,asLink:!0}),this.subtitleRight.remove();const g=h?.middleware;this.middlewareHelper=g?h.middleware.create():m?xt():void 0;const f={...h};this.middlewareHelper&&(f.middleware=this.middlewareHelper.get());const y=!!d&&e===I.myId,v=!!d&&!y,w=y?d:e,b=v?void 0:es({middleware:this.middlewareHelper.get(),size:aR[n],lazyLoadQueue:f.lazyLoadQueue,isDialog:!!i,peerId:l?Tt:w,peerTitle:l,withStories:p,wrapOptions:f,meAsNotes:y});r?.push(b?.readyThumbPromise);const S=b?.node;S&&(S.classList.add("dialog-avatar"),this.applyMediaElement(S,n));const C=this.container,P=this.title;P.classList.add("user-title"),this.titleRow.classList.add("dialog-title");const L=!a&&me.chat&&me.isSamePeer(me.chat,{peerId:e,threadId:d,type:y?te.Saved:te.Chat}),E=new Rt,_=E.update({peerId:w,fromName:l,dialog:i,onlyFirstName:s,withIcons:!c,threadId:y?void 0:d,wrapOptions:{textColor:ms.getPrimaryColor(L),...f},meAsNotes:y});r?.push(_),P.append(E.element);const k=this.subtitle,x=this.container;x.classList.add("chatlist-chat","chatlist-chat-"+n),a||(x.href="#"+e),n==="bigger"?this.container.classList.add("row-big"):n==="small"&&this.container.classList.add("row-small"),x.dataset.peerId=""+e,d&&(x.dataset.threadId=""+d);const A=document.createElement("span");A.classList.add("message-status","sending-status");const T=document.createElement("span");T.classList.add("message-time");const B=this.titleRight;B.classList.add("dialog-title-details"),B.append(A,T),this.subtitleRow.classList.add("dialog-subtitle","has-multiple-badges");const R=this.dom={avatarEl:b,captionDiv:C,titleSpan:E.element,titleSpanContainer:P,statusSpan:A,lastTimeSpan:T,lastMessageSpan:k,containerEl:x,listEl:x,subtitleEl:this.subtitleRow};a||(x.dialogDom=R,u&&ms.forumTab?.peerId===e&&!d&&x.classList.add("is-forum-open")),L&&ms.setDialogActive(x,!0)}destroy(){this.middlewareHelper?.destroy()}remove(){this.destroy(),this.dom.listEl.remove()}createPinnedBadge(){if(this.dom.pinnedBadge)return;const e=this.dom.pinnedBadge=document.createElement("div");e.className=`dialog-subtitle-badge badge badge-icon badge-${ic} dialog-subtitle-badge-pinned`,e.append(Le("chatspinned")),this.dom.subtitleEl.append(e)}createUnreadBadge(){if(this.dom.unreadBadge)return;const e=this.dom.unreadBadge=document.createElement("div");e.className=`dialog-subtitle-badge badge badge-${ic} dialog-subtitle-badge-unread`,this.dom.subtitleEl.append(e)}createUnreadAvatarBadge(){if(this.dom.unreadAvatarBadge)return;const e=this.dom.unreadAvatarBadge=document.createElement("div");e.className=`dialog-subtitle-badge badge badge-${ic} avatar-badge`,this.dom.listEl.append(e)}createMentionsBadge(){if(this.dom.mentionsBadge)return;const e=this.dom.mentionsBadge=document.createElement("div");e.className=`dialog-subtitle-badge badge badge-${ic} mention mention-badge dialog-subtitle-badge-mention`,e.innerText="@",this.dom.subtitleEl.append(e)}createReactionsBadge(){if(this.dom.reactionsBadge)return;const e=this.dom.reactionsBadge=document.createElement("div");e.className=`dialog-subtitle-badge badge badge-${ic} reaction-badge dialog-subtitle-badge-reaction`,e.append(Le("reactions_filled")),this.dom.subtitleEl.append(e)}toggleBadgeByKey(e,t,s,i){bt({element:this.dom[e],className:"is-visible",forwards:t,duration:i?0:Cu,onTransitionEnd:t?void 0:()=>{this.dom[e].remove(),delete this.dom[e]},useRafs:!s||!ca(this.dom[e])?2:0})}};ty.BADGE_ORDER=["reactionsBadge","mentionsBadge","unreadBadge","pinnedBadge"];let wg=ty;class um extends Xt{constructor(){super(...arguments),this._close=()=>{this.slider?this.close():ms.toggleForumTab(void 0,this)},this.viewAsMessages=async()=>{const e=me.chat,t=this.peerId;this._close(),await this.managers.appChatsManager.toggleViewForumAsMessages(t.toChatId(),!0),me[e?.peerId===t?"setPeer":"setInnerPeer"](this.getOptionsForMessages())}}async toggle(e){this.init2&&await this.init2(),bt({element:this.container,className:"is-visible",forwards:e,duration:300,onTransitionEnd:e?void 0:()=>{this.onCloseAfterTimeout()},useRafs:this.firstTime?(this.firstTime=void 0,2):void 0})}init(e){It(this,e),this.log=ri("FORUM"),this.firstTime=!0,this.container.classList.add("topics-container");const t=!this.slider;t&&(this.closeBtn.replaceChildren(Le("close")),this.container.classList.add("active","is-floating"),N(this.closeBtn,this._close,{listenerSetter:this.listenerSetter})),this.rows=document.createElement("div"),this.rows.classList.add("sidebar-header__rows"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("sidebar-header__subtitle"),this.title.replaceWith(this.rows),this.rows.append(this.title,this.subtitle);const s=ms.createChatList();ms.setListClickListener({list:s,onFound:null,withContext:!0}),this.scrollable.append(s),this.xd=new rR(this.peerId,t?80:0),this.xd.scrollable=this.scrollable,this.xd.sortedList=new Yf({managers:this.managers,log:this.log,list:s,indexKey:"index_0",virtualFilterId:this.peerId}),this.xd.bindScrollable();const i=ai({listenerSetter:this.listenerSetter,direction:"bottom-left",buttons:[{icon:"add",text:"ForumTopic.Context.New",onClick:()=>{Ii.createTab(hg).open(this.peerId)},separatorDown:!0,verify:()=>this.managers.appChatsManager.hasRights(this.peerId.toChatId(),"manage_topics")},{icon:"info",text:"ForumTopic.Context.Info",onClick:()=>{co.open(Ii,this.peerId)}},{icon:"message",text:"ForumTopic.Context.ShowAsMessages",onClick:this.viewAsMessages,verify:()=>{const n=me.chat;return!n||!me.isSamePeer(n,this.getOptionsForMessages())}},{icon:"adduser",text:"ForumTopic.Context.AddMember",onClick:()=>{},verify:()=>!1},{icon:"logout",danger:!0,text:"LeaveMegaMenu",onClick:()=>{ee.createPopup(Hu,this.peerId,void 0,n=>{this._close()})},separator:!0,verify:async()=>!!await this.managers.appMessagesManager.getDialogOnly(this.peerId)}]});if(this.listenerSetter.add(I)("history_reload",n=>{this.peerId===n&&this.xd.fullReset()}),this.listenerSetter.add(I)("chat_update",n=>{if(this.peerId!==n.toPeerId(!0))return;fe.getChat(n).pFlags.forum||ms.toggleForumTab(void 0,this)}),Je&&Hf({element:this.container,onSwipe:()=>{ms.toggleForumTab(void 0,this)},middleware:this.middlewareHelper.get()}),this.header.append(i),!t)return this.init2()}async init2(){this.init2=void 0;const e=this.middlewareHelper.get(),t=this.peerId;this.managers.apiUpdatesManager.subscribeToChannelUpdates(this.peerId.toChatId()),e.onDestroy(()=>{this.managers.apiUpdatesManager.unsubscribeFromChannelUpdates(this.peerId.toChatId())});const s=Oe({peerId:t,dialog:!0,wrapOptions:{middleware:e}}),i=me.setPeerStatus({peerId:t,element:this.subtitle,needClear:!0,useWhitespace:!1,middleware:e,noTyping:!0});return Promise.all([s,i,this.xd.onChatsScroll().then(n=>n.cached?n.renderPromise:void 0)]).then(([n,a,r])=>{e()&&(this.title.append(n),a?.())})}onCloseAfterTimeout(){super.onCloseAfterTimeout(),this.xd.destroy()}getOptionsForMessages(){return{peerId:this.peerId,type:te.Chat}}}const nc=new Error("not implemented");class Xf{constructor(){this.onChatsRegularScroll=()=>{this.sliceTimeout&&clearTimeout(this.sliceTimeout),this.sliceTimeout=window.setTimeout(()=>{this.sliceTimeout=void 0,!(!this.sortedList.list.childElementCount||ms.processContact)&&Db(()=>{const e=".chatlist-chat",t=zb({overflowElement:this.scrollable.container,selector:e,extraMinLength:10}),s=t.visible,i=s[0],n=s[s.length-1],a=i?.element,r=n?.element;if(!a||!r)return;t.invisibleTop.length&&(this.scrollable.loadedAll.top=!1),t.invisibleBottom.length&&(this.scrollable.loadedAll.bottom=!1);const l=new Zu(this.scrollable,e,!!t.invisibleTop.length);l.save(),[...t.invisibleTop,...t.invisibleBottom].forEach(({element:c})=>{this.deleteDialogByKey(this.getDialogKeyFromElement(c))}),l.restore(),this.setOffsets()})},200)},this.log=ri("CL"),this.offsets={top:0,bottom:0},this.managers=I.managers,this.listenerSetter=new Ut}getOffsetIndex(e){return{index:this.scrollable.loadedAll[e]?0:this.offsets[e]}}isDialogMustBeInViewport(e){const t=this.getOffsetIndex("top"),s=this.getOffsetIndex("bottom");if(!t.index&&!s.index)return!0;const i=bn(e,this.indexKey);return(!t.index||i<=t.index)&&(!s.index||i>=s.index)}setIndexKey(e){this.indexKey=e,this.sortedList.indexKey=e}deleteDialogByKey(e){this.sortedList.delete(e)}deleteDialog(e){return this.deleteDialogByKey(this.getDialogKey(e))}updateDialog(e){const t=this.getDialogKey(e);if(this.isDialogMustBeInViewport(e)){if(!this.sortedList.has(t)&&this.loadedDialogsAtLeastOnce){this.sortedList.add(t);return}}else{this.deleteDialog(e);return}const s=this.getDialogElement(t);s&&(ms.setLastMessageN({dialog:e,dialogElement:s,setUnread:!0}),this.sortedList.update(t))}onChatsScrollTop(){return this.onChatsScroll("top")}onChatsScroll(e="bottom"){return this.loadDialogs(e)}createPlaceholder(){const e=this.placeholder=new Bw(this.placeholderOptions),t=this.getRectFromForPlaceholder();return e.attach({container:this.sortedList.list.parentElement,getRectFrom:t,onRemove:()=>{this.placeholder===e&&(this.placeholder=void 0)},blockScrollable:this.scrollable}),e}loadDialogs(e){const t=this.log.bindPrefix("load-"+zm(1e3,9999));if(t("try",e),this.loadDialogsPromise||this.loadDialogsRenderPromise)return this.loadDialogsPromise;if(this.scrollable.loadedAll[e])return Promise.resolve({cached:!0,renderPromise:Promise.resolve()});t.warn("start",e);const s=Ld("MIDDLEWARE"),i=Pt(),n=new Promise(async(r,l)=>{const c=this.sortedList.list;let d=this.placeholder;try{const u=await this.loadDialogsInner(e);if(!c.childElementCount&&!d&&(!this.loadedDialogsAtLeastOnce&&this.needPlaceholderAtFirstTime||!u.cached)){if(this.loadDialogsRenderPromise!==n)throw s;d=this.createPlaceholder(),i.resolve(!1)}const p=await u.result;if(this.loadDialogsRenderPromise!==n)throw s;i.resolve(u.cached),e==="bottom"?p.isEnd&&(this.scrollable.loadedAll[e]=!0):p.isTopEnd&&(this.scrollable.loadedAll[e]=!0);const m=p.dialogs.length;if(t(`will render ${m} dialogs`),m){const y=(e==="top"?p.dialogs.slice().reverse():p.dialogs).map(v=>this.sortedList.add(this.getDialogKey(v)));if(await Promise.all(y).catch(),this.loadDialogsRenderPromise!==n)throw s}const g=p.dialogs[e==="top"?0:m-1];g&&(this.offsets[e]=bn(g,this.indexKey)),this.loadedDialogsAtLeastOnce=!0,ms.onListLengthChange(),t("getDialogs",p,c.childElementCount),setTimeout(()=>{this.scrollable.onScroll()},0),d&&d.detach(c.childElementCount)}catch(h){h?.type!=="MIDDLEWARE"&&t.error(h),l(h),i.reject(h);return}r()}).finally(()=>{this.loadDialogsRenderPromise===n?(t("end"),this.loadDialogsRenderPromise=void 0):t("has been cleared")});this.loadDialogsRenderPromise=n;const a=this.loadDialogsPromise=i.then(r=>({cached:r,renderPromise:n})).finally(()=>{this.loadDialogsPromise===a&&(this.loadDialogsPromise=void 0)});return a}async setOffsets(){const e=this.sortedList.list,[t,s]=await Promise.all([this.getDialogFromElement(e.firstElementChild),this.getDialogFromElement(e.lastElementChild)]),{indexKey:i}=this;this.offsets.top=bn(t,i),this.offsets.bottom=bn(s,i)}getDialogKey(e){throw nc}getDialogKeyFromElement(e){throw nc}getRectFromForPlaceholder(){throw nc}getDialogFromElement(e){throw nc}loadDialogsInner(e){throw nc}async setTyping(e){const t=this.getDialogKey(e),s=this.getDialogDom(t);if(!s)return;const i=s.lastMessageSpan.querySelector(".peer-typing-container"),n=await me.getPeerTyping(e.peerId,i,Fa(e)?e.id:void 0);!i&&n&&(dt(s.lastMessageSpan,n),s.lastMessageSpan.classList.add("user-typing"))}unsetTyping(e){const t=this.getDialogKey(e),s=this.getDialogElement(t);s&&(s.dom.lastMessageSpan.classList.remove("user-typing"),ms.setLastMessageN({dialog:e,lastMessage:null,dialogElement:s,setUnread:null}))}getDialogDom(e){return this.sortedList.get(e)?.dom}getDialogElement(e){return this.sortedList.get(e)?.dialogElement}bindScrollable(){this.scrollable.container.addEventListener("scroll",this.onChatsRegularScroll),this.scrollable.onScrolledTop=this.onChatsScrollTop.bind(this),this.scrollable.onScrolledBottom=this.onChatsScroll.bind(this)}clear(){this.sortedList.clear(),this.placeholder?.remove()}reset(){this.scrollable.loadedAll.top=!0,this.scrollable.loadedAll.bottom=!1,this.offsets.top=this.offsets.bottom=0,this.loadDialogsRenderPromise=void 0,this.loadDialogsPromise=void 0}fullReset(){return this.reset(),this.clear(),this.onChatsScroll()}destroy(){this.clear(),this.scrollable.destroy(),this.listenerSetter.removeAll()}}class rR extends Xf{constructor(e,t){super(),this.peerId=e,this.paddingX=t,this.placeholderOptions={avatarSize:0,marginVertical:5,totalHeight:64},this.listenerSetter.add(I)("peer_typings",async({peerId:s,threadId:i,typings:n})=>{if(!i||this.peerId!==s)return;const a=await this.managers.dialogsStorage.getForumTopic(s,i);a&&(n.length?this.setTyping(a):this.unsetTyping(a))}),this.listenerSetter.add(I)("dialogs_multiupdate",s=>{for(const[i,{dialog:n,topics:a}]of s)i!==this.peerId||!a?.size||a.forEach(r=>{this.updateDialog(r)})}),this.listenerSetter.add(I)("dialog_unread",({dialog:s})=>{!Fa(s)||s.peerId!==this.peerId||ms.setUnreadMessagesN({dialog:s,dialogElement:this.getDialogElement(this.getDialogKey(s))})}),this.listenerSetter.add(I)("dialog_notify_settings",async s=>{if(s.peerId===this.peerId){if(lr(s)){const n=[...this.sortedList.getAll().entries()],a=n.map(([l])=>this.managers.dialogsStorage.getForumTopic(this.peerId,l)),r=await Promise.all(a);n.forEach(([l,c],d)=>{ms.setUnreadMessagesN({dialog:r[d],dialogElement:c.dialogElement})});return}ms.setUnreadMessagesN({dialog:s,dialogElement:this.getDialogElement(this.getDialogKey(s))})}}),this.listenerSetter.add(I)("dialog_drop",s=>{!Fa(s)||s.peerId!==this.peerId||this.deleteDialogByKey(this.getDialogKey(s))}),this.listenerSetter.add(I)("dialog_draft",({dialog:s,drop:i,peerId:n})=>{!Fa(s)||s.peerId!==this.peerId||(i?this.deleteDialog(s):this.updateDialog(s))})}isDialogMustBeInViewport(e){return e.pFlags.hidden?!1:super.isDialogMustBeInViewport(e)}getDialogKey(e){return e.id}getDialogKeyFromElement(e){return+e.dataset.threadId}getRectFromForPlaceholder(){return()=>{const e=Ii.rect,t=56;return{top:t,right:e.right,bottom:0,left:this.paddingX,width:e.width-this.paddingX,height:e.height-t}}}getDialogFromElement(e){return this.managers.dialogsStorage.getForumTopic(+e.dataset.peerId,+e.dataset.threadId)}async loadDialogsInner(e){const{indexKey:t}=this;let s=lt.height/64*1.25|0,i=0;const n=this.peerId,{index:a}=this.getOffsetIndex(e);if(i=a,a)if(e==="top"){const r=await this.managers.dialogsStorage.getFolderDialogs(n,!0),l=r.findIndex(d=>bn(d,t)<=a),c=Math.max(0,l-s);s=l-c,i=bn(r[c],t)+1}else i=a;return this.managers.acknowledged.dialogsStorage.getDialogs({offsetIndex:i,limit:s,filterId:n,skipMigrated:!!YL})}}class oR extends Xf{constructor(e){super(),this.filterId=e,this.needPlaceholderAtFirstTime=!0,this.listenerSetter.add(I)("peer_typings",async({peerId:t,typings:s})=>{const[i,n]=await Promise.all([this.managers.appMessagesManager.getDialogOnly(t),this.managers.appPeersManager.isForum(t)]);!i||n||(s.length?this.setTyping(i):this.unsetTyping(i))}),this.listenerSetter.add(I)("user_update",async t=>{if(!this.isActive)return;const s=t.toPeerId(),i=this.getDialogDom(s);if(!i)return;const a=(await this.managers.appUsersManager.getUserStatus(t))?._==="userStatusOnline";this.setOnlineStatus(i.avatarEl.node,a)}),this.listenerSetter.add(I)("chat_update",async t=>{const s=t.toPeerId(!0);this.processDialogForCallStatus(s)}),this.listenerSetter.add(I)("dialog_flush",({dialog:t})=>{!this.isActive||!t||this.updateDialog(t)}),this.listenerSetter.add(I)("dialogs_multiupdate",t=>{if(this.isActive)for(const[s,{dialog:i,topics:n}]of t)lr(i)&&(this.updateDialog(i),ms.processContact?.(s.toPeerId()))}),this.listenerSetter.add(I)("dialog_drop",t=>{!this.isActive||!lr(t)||(this.deleteDialogByKey(this.getDialogKey(t)),ms.processContact?.(t.peerId))}),this.listenerSetter.add(I)("dialog_unread",({dialog:t})=>{!this.isActive||!lr(t)||this.updateDialog(t)}),this.listenerSetter.add(I)("dialog_notify_settings",t=>{!this.isActive||!lr(t)||this.updateDialog(t)}),this.listenerSetter.add(I)("dialog_draft",({dialog:t,drop:s,peerId:i})=>{!this.isActive||Fa(t)||(s?this.deleteDialog(t):this.updateDialog(t),ms.processContact?.(i))}),this.listenerSetter.add(I)("filter_update",async t=>{if(this.isActive&&t.id===this.filterId&&!ra.has(t.id)){const s=await this.managers.dialogsStorage.getCachedDialogs(!0);await this.validateListForFilter();for(let i=0,n=s.length;i<n;++i){const a=s[i];this.updateDialog(a)}ms.filterId===this.filterId&&ms.fetchChatlistUpdates?.()}})}get isActive(){return ms.xd===this}getRectFromForPlaceholder(){return this.filterId===Vi?ms.chatsContainer:ms.folders.container}async loadDialogsInner(e){const{filterId:t,indexKey:s}=this;let i=lt.height/72*1.25|0,n=0;const a=ms.doNotRenderChatList,{index:r}=this.getOffsetIndex(e);if(r)if(e==="top"){const d=await this.managers.dialogsStorage.getFolderDialogs(t,!0),h=d.findIndex(p=>bn(p,s)<=r),u=Math.max(0,h-i);i=h-u,n=bn(d[u],s)+1}else n=r;const c=await this.managers.acknowledged.dialogsStorage.getDialogs({offsetIndex:n,limit:i,filterId:t,skipMigrated:!0});return a&&(c.result=Promise.reject(Ld("MIDDLEWARE"))),c}setOnlineStatus(e,t){const s="is-online",i=e.classList.contains(s);!i&&t&&e.classList.add(s),bt({element:e,className:"is-visible",forwards:t,duration:250,onTransitionEnd:t?void 0:()=>{e.classList.remove(s)},useRafs:t&&!i?2:0})}generateScrollable(e,t){const s=t.id,i=new vi(null,"CL",500);i.container.dataset.filterId=""+s;const n=Fw(t.localId),a=new Yf({managers:I.managers,log:this.log,list:e,indexKey:n,onListLengthChange:()=>{i.onSizeChange(),ms.onListLengthChange?.()}});return this.scrollable=i,this.sortedList=a,this.setIndexKey(n),this.bindScrollable(),i}testDialogForFilter(e){return!(ra.has(this.filterId)?this.filterId!==e.folder_id:bn(e,this.indexKey)===void 0)}isDialogMustBeInViewport(e){return e.migratedTo!==void 0||!this.testDialogForFilter(e)?!1:super.isDialogMustBeInViewport(e)}async validateListForFilter(){this.sortedList.getAll().forEach(async e=>{const t=await I.managers.appMessagesManager.getDialogOnly(e.id);this.testDialogForFilter(t)||this.deleteDialog(t)})}updateDialog(e){if(!this.testDialogForFilter(e)){this.getDialogElement(e.peerId)&&this.deleteDialog(e);return}return super.updateDialog(e)}setCallStatus(e,t){let{callIcon:s,listEl:i}=e;if(!s&&t){const{canvas:n,startAnimation:a}=e.callIcon=s=nR(i.classList.contains("active"));n.classList.add("dialog-group-call-icon"),i.append(n),a()}s&&bt({element:e.callIcon.canvas,className:"is-visible",forwards:t,duration:Cu,onTransitionEnd:t?void 0:()=>{e.callIcon.canvas.remove(),e.callIcon=void 0},useRafs:t?2:0})}processDialogForCallStatus(e,t){if(!Ac||(t||(t=this.getDialogDom(e)),!t))return;const s=fe.getChat(e.toChatId());this.setCallStatus(t,!!(s.pFlags.call_active&&s.pFlags.call_not_empty))}onChatsScroll(e="bottom"){return this.scrollable.loadedAll[e]&&ms.loadContacts?.(),this.log("onChatsScroll",e),super.onChatsScroll(e)}toggleAvatarUnreadBadges(e,t){if(!e){this.sortedList.getAll().forEach(i=>{const{dom:n,dialogElement:a}=i;n.unreadAvatarBadge&&a.toggleBadgeByKey("unreadAvatarBadge",!1,!1,!1)});return}const s=["unread","mention"];this.sortedList.getAll().forEach(i=>{const{dom:n,dialogElement:a}=i,r=n.unreadBadge?.textContent;if(!r||n.unreadBadge.classList.contains("backwards")||n.unreadBadge.classList.contains("dialog-pinned-icon"))return;const l=!!n.unreadAvatarBadge;a.createUnreadAvatarBadge(),a.toggleBadgeByKey("unreadAvatarBadge",!0,l),n.unreadAvatarBadge.textContent=r;const c=n.unreadAvatarBadge.classList,d=n.unreadBadge.classList;s.forEach(h=>{c.toggle(h,d.contains(h))})})}getDialogKey(e){return e.peerId}getDialogKeyFromElement(e){return+e.dataset.peerId}getDialogFromElement(e){return I.managers.appMessagesManager.getDialogOnly(e.dataset.peerId.toPeerId())}}class lR extends Xf{constructor(){super(),this.listenerSetter.add(I)("dialogs_multiupdate",e=>{let t=!1;for(const[s,{saved:i}]of e)i?.forEach(n=>{t=!0,this.updateDialog(n)});t&&this.onAnyUpdate?.()}),this.listenerSetter.add(I)("dialog_drop",e=>{la(e)&&(this.deleteDialogByKey(this.getDialogKey(e)),this.onAnyUpdate?.())})}getRectFromForPlaceholder(){return ms.chatsContainer}async loadDialogsInner(e){const{indexKey:t}=this;let s=lt.height/72*1.25|0,i=0;const n=I.myId,{index:a}=this.getOffsetIndex(e);if(i=a,a)if(e==="top"){const r=await this.managers.dialogsStorage.getFolderDialogs(n),l=r.findIndex(d=>bn(d,t)<=a),c=Math.max(0,l-s);s=l-c,i=bn(r[c],t)+1}else i=a;return this.managers.acknowledged.dialogsStorage.getDialogs({offsetIndex:i,limit:s,filterId:n,skipMigrated:!0})}getDialogKey(e){return e.savedPeerId}getDialogKeyFromElement(e){return+e.dataset.peerId}getDialogFromElement(e){return I.managers.dialogsStorage.getAnyDialog(e.dataset.peerId.toPeerId(),e.dataset.threadId.toPeerId())}}const cR=void 0;class dR{constructor(){this.chatsContainer=document.getElementById("chatlist-container"),this.log=ri("DIALOGS",Gi.Log|Gi.Error|Gi.Warn|Gi.Debug),this.folders={menu:document.getElementById("folders-tabs"),menuScrollContainer:null,container:document.getElementById("folders-container")},this.filtersRendered={},this.lastActiveElements=new Set,this.initedListeners=!1,this.xds={},this.onTabChange=()=>{const{filterId:e}=this;this.xd=this.xds[e],this.xd.reset(),this.cancelChatlistUpdatesFetching?.(),this.cancelChatlistUpdatesFetching=void 0,this.fetchChatlistUpdates=void 0;const t=this.xd.onChatsScroll();return ra.has(e)||Promise.all([this.managers.filtersStorage.getFilter(e),this.managers.apiManager.getAppConfig(),t.then(({renderPromise:s})=>s).catch(()=>{})]).then(([s,i])=>{if(s?._!=="dialogFilterChatlist"||this.filterId!==e)return;const n=(i.chatlist_update_period??3600)*1e3,a=this.filtersRendered[e];let r=a.topNotification&&!cR&&s.updatedTime||0,l=!1;this.fetchChatlistUpdates=()=>{if(r=Date.now(),l)return;l=!0,this.managers.filtersStorage.getChatlistUpdates(e).catch(()=>{}).then(d=>{if(this.filterId!==e||this.filtersRendered[e]!==a)return;const h=d?d.missing_peers.length:0;if(h){this.createTopNotification(a),a.topNotificationData={_:"chatlistUpdates",chatlistUpdates:d};const u=a.topNotification,p=M("ChatsNew",[h]);p.classList.add("primary");const m=M("ChatList.SharedFolder.Title",[p]);u.title.replaceChildren(m),u.subtitle.replaceChildren(M("ChatList.SharedFolder.Subtitle"))}this.toggleTopNotification(a,!!h)}).finally(()=>{l=!1})},this.cancelChatlistUpdatesFetching=Bf(this.fetchChatlistUpdates,()=>{const c=Date.now()-r;return n-c},!1)}),t},this._onListLengthChange=()=>{if(!this.xd.loadedDialogsAtLeastOnce||(this.checkIfPlaceholderNeeded(),this.filterId!==Ci))return;const e=this.chatList,t=e.childElementCount,s=e.parentElement.parentElement,i=e.parentElement.nextElementSibling,n=!!i.childElementCount;if(t>=10){n&&this.removeContactsPlaceholder();return}else if(n||!this.xd.scrollable.loadedAll.bottom)return;s.classList.add("with-contacts");const a=new Pe({name:"Contacts",noDelimiter:!0,fakeGradientDelimiter:!0});a.container.classList.add("hide"),this.managers.appUsersManager.getContactsPeerIds(void 0,void 0,"online").then(r=>{let l=!1;const c=()=>{l&&a.container.classList.toggle("hide",!d.list.childElementCount),this.updateContactsLength(!0)},d=new $c({avatarSize:"abitbigger",createChatListOptions:{dialogSize:48,new:!0},autonomous:!1,onListLengthChange:c,managers:this.managers,middleware:void 0});this.loadContacts=()=>{const u=lt.height/60|0;Zi(r.splice(0,u),this.verifyPeerIdForContacts).then(m=>{m.forEach(g=>{d.add(g)})}),r.length||(this.loadContacts=void 0)},this.loadContacts(),this.processContact=async u=>{if(u.isAnyChat())return;const p=await this.verifyPeerIdForContacts(u),m=d.has(u);!m&&p?d.add(u):m&&!p&&d.delete(u)};const h=d.list;h.classList.add("chatlist-new"),this.setListClickListener({list:h}),a.content.append(h),l=!0,c()}),i.append(a.container)},this.verifyPeerIdForContacts=async e=>{const[t,s]=await Promise.all([this.managers.appPeersManager.isContact(e),this.managers.appMessagesManager.getDialogOnly(e)]);return t&&!s}}start(){const e=this.managers=QL();this.contextMenu=new eR(e),this.stateMiddlewareHelper=xt(),this.folders.menuScrollContainer=this.folders.menu.parentElement,this.onListLengthChange=ii(this._onListLengthChange,100,!1,!0);const t=this.bottomPart=document.createElement("div");t.classList.add("connection-status-bottom"),t.append(this.folders.container),(this.storiesListContainer=document.createElement("div")).classList.add("stories-list"),this.forumsTabs=new Map,this.forumsSlider=document.createElement("div"),this.forumsSlider.classList.add("topics-slider"),this.chatsContainer.parentElement.parentElement.append(this.forumsSlider),Je&&Hf({element:this.folders.container,onSwipe:r=>{const l=n.prevId();n(r<0?l+1:l-1)},verifyTouchTarget:()=>!this.forumTab}),this.allChatsIntlElement=new ke.IntlElement({key:"FilterAllChatsShort"}),I.addEventListener("premium_toggle",async r=>{if(r)return;await this.managers.filtersStorage.isFilterIdAvailable(this.filterId)||n(Ri(this.filtersRendered[Ci].menu),!1)}),I.addEventListener("state_cleared",()=>{const r=ra.has(this.filterId);fe.getState().then(async l=>{this.xd.loadedDialogsAtLeastOnce=!1,this.showFiltersPromise=void 0,r&&(this.xd.clear(),this.onTabChange()),this.onStateLoaded(l)})}),this.setFilterId(Ci),this.addFilter({id:Ci,title:"",localId:Ci});const i=new yr(this.folders.menuScrollContainer);t.prepend(this.folders.menuScrollContainer);const n=this.selectTab=Ml(this.folders.menu,this.folders.container,async(r,l)=>{const c=r;if(r=+l.dataset.filterId||Ci,!(this.filterId===-1||ra.has(r)||await this.managers.filtersStorage.isFilterIdAvailable(r)))return ua("folders"),!1;const h=this.filterId;if(Ua||(c?this.filtersNavigationItem||(this.filtersNavigationItem={type:"filters",onPop:()=>{n(0),this.filtersNavigationItem=void 0}},ft.spliceItems(1,0,this.filtersNavigationItem)):this.filtersNavigationItem&&(ft.removeItem(this.filtersNavigationItem),this.filtersNavigationItem=void 0)),h===r)return;this.xds[r].clear();const u=this.setFilterIdAndChangeTab(r).then(({cached:p,renderPromise:m})=>{if(p)return m});if(h!==-1)return u},()=>{for(const r in this.xds)+r!==this.filterId&&this.xds[r].clear()},void 0,i);let a;ln({buttons:[{icon:"edit",text:"FilterEdit",onClick:()=>{this.managers.filtersStorage.getFilter(a).then(r=>{const l=Ii.createTab(Da);l.setInitFilter(r),l.open()})},verify:()=>a!==Ci},{icon:"edit",text:"FilterEditAll",onClick:()=>{Ii.createTab(bp).open()},verify:()=>a===Ci},{icon:"readchats",text:"MarkAllAsRead",onClick:()=>{this.managers.dialogsStorage.markFolderAsRead(a)},verify:async()=>!!(await this.managers.dialogsStorage.getFolderUnreadCount(a)).unreadCount},{icon:"delete",className:"danger",text:"Delete",onClick:()=>{Da.deleteFolder(a)},verify:()=>a!==Ci}],listenTo:this.folders.menu,findElement:r=>U(r.target,"menu-horizontal-div-item"),onOpen:(r,l)=>{a=+l.dataset.filterId}}),fe.getState().then(r=>(rt.setPlaybackParams(r.playbackParams),rt.addEventListener("playbackParams",l=>{this.managers.appStateManager.pushToState("playbackParams",l)}),this.onStateLoaded(r))),$e.addEventListener("resize",()=>{this.changeFiltersAllChatsKey()}),this.chatsContainer.append(t),setTimeout(()=>{_s.loadLottieWorkers()},200),ee.MANAGERS=I.managers=e,cs.construct(e),Ii.construct(e),ls.construct(e),zn.construct(e),Yi.construct(e),me.construct(e),vm&&Nt.construct(e),new Hc().construct(e,this.chatsContainer,Ii.inputSearch),this.xd=this.xds[this.filterId]}_renderStories(){return this.chatsContainer.parentElement.parentElement.firstElementChild.after(this.storiesListContainer),YC({foldInto:document.querySelector(".item-main .input-search input"),setScrolledOn:this.chatsContainer,getScrollable:()=>this.xd.scrollable.container,listenWheelOn:this.bottomPart,offsetX:-1,resizeCallback:e=>{this.resizeStoriesList=e}})}renderStories(){this.disposeStories=Hi(()=>this._renderStories(),this.storiesListContainer)}get chatList(){return this.xd.sortedList.list}setFilterId(e){this.filterId=e}async setFilterIdAndChangeTab(e){return this.setFilterId(e),this.onTabChange()}initListeners(){I.addEventListener("dialog_flush",({dialog:e})=>{e&&this.setFiltersUnreadCount()}),I.addEventListener("folder_unread",async e=>{if(e.id<0){const t=this.xd.getDialogElement(e.id);if(!t)return;this.setUnreadMessagesN({dialog:await this.managers.dialogsStorage.getDialogOnly(e.id),dialogElement:t})}else this.setFilterUnreadCount(e.id)}),I.addEventListener("contacts_update",e=>{this.processContact?.(e.toPeerId())}),me.addEventListener("peer_changed",({peerId:e,threadId:t,isForum:s})=>{const i={peerId:e,threadId:s||I.myId?t:void 0};for(const a of this.lastActiveElements){const r=+a.dataset.threadId||void 0,l=a.dataset.peerId.toPeerId();me.isSamePeer({peerId:l,threadId:r},i)||this.setDialogActive(a,!1)}Array.from(document.querySelectorAll(`[data-autonomous="0"] .chatlist-chat[data-peer-id="${e}"]`)).forEach(a=>{const r=+a.dataset.threadId||void 0;me.isSamePeer({peerId:e,threadId:r},i)&&this.setDialogActive(a,!0)})}),I.addEventListener("filter_update",async e=>{if(ra.has(e.id))return;if(!this.filtersRendered[e.id]){this.addFilter(e);return}const t=this.filtersRendered[e.id];kt(t.title,_e(e.title))}),I.addEventListener("filter_delete",e=>{const t=this.filtersRendered[e.id];t&&(t.container.remove(),t.menu.remove(),this.xds[e.id].destroy(),delete this.xds[e.id],delete this.filtersRendered[e.id],this.onFiltersLengthChange(),this.filterId===e.id&&this.selectTab(0,!1))}),I.addEventListener("filter_order",async e=>{e=e.slice(),us(e,Vi);const t=this.folders.menu,s=await Promise.all(e.map(async i=>{const[n,a]=await Promise.all([this.managers.dialogsStorage.getDialogIndexKeyByFilterId(i),this.managers.filtersStorage.getFilter(i)]);return{indexKey:n,filter:a}}));e.forEach((i,n)=>{const{indexKey:a,filter:r}=s[n],l=this.filtersRendered[i];this.xds[i].setIndexKey(a),Ps(l.menu,t,r.localId),Ps(l.container,this.folders.container,r.localId)})}),I.addEventListener("filter_joined",e=>{const t=this.filtersRendered[e.id];this.selectTab(t.menu)})}getTextColor(e){return e?"white":"secondary-text-color"}getPrimaryColor(e){return e?"white":"primary-color"}setDialogActiveStatus(e,t){e.classList.toggle("active",t),e.querySelectorAll(".custom-emoji-renderer").forEach(i=>{i.textColor=this.getTextColor(t)}),uw(e,this.getPrimaryColor(t))}setDialogActive(e,t){const s=e.dialogDom;this.setDialogActiveStatus(e,t),e.classList.toggle("is-forum-open",this.forumTab?.peerId===e.dataset.peerId.toPeerId()&&!e.dataset.threadId),t?this.lastActiveElements.add(e):this.lastActiveElements.delete(e),s?.callIcon&&s.callIcon.setActive(t)}async onStateLoaded(e){this.stateMiddlewareHelper.clean();const t=this.stateMiddlewareHelper.get(),s=e.filtersArr,i=s.length>ra.size;this.disposeStories?.(),this.disposeStories=this.resizeStoriesList=void 0;const n=c=>{for(const d of c)this.addFilter(d)};let a;i?n(s):a=this.managers.filtersStorage.getDialogFilters().then(n),this.doNotRenderChatList=!0;const r=this.xd.onChatsScroll(),l=so(t);try{await l(r)}catch{}i||this.selectTab(0,!1),a&&await l(a),this.renderStories(),this.doNotRenderChatList=void 0,this.filterId=-1,this.selectTab(0,!1),this.initedListeners||(this.initListeners(),this.initedListeners=!0),i&&this.showFiltersPromise&&await l(this.showFiltersPromise),this.managers.appNotificationsManager.getNotifyPeerTypeSettings(),await(await l(r)).renderPromise.catch(Wt),this.managers.appMessagesManager.fillConversations()}async setFilterUnreadCount(e){const t=this.filtersRendered[e]?.unread;if(!t)return;const{unreadUnmutedCount:s,unreadCount:i}=await this.managers.dialogsStorage.getFolderUnreadCount(e);t.classList.toggle("badge-gray",!s);const n=e===Ci?s:i;Qo(t,n?""+n:"")}setFiltersUnreadCount(){for(const e in this.filtersRendered)this.setFilterUnreadCount(+e)}l(e){const t=this.createChatList(),s=this.xds[e.id]=new oR(e.id),i=s.generateScrollable(t,e);return this.setListClickListener({list:t,onFound:null,withContext:!0}),{ul:t,xd:s,scrollable:i}}createTopNotification(e){if(e.topNotification)return;const t=e.topNotificationContainer=document.createElement("div");t.classList.add("chatlist-top-notification-container");const s=e.topNotification=new ve({title:!0,subtitle:!0,clickable:async()=>{const i=e.topNotificationData;i._==="chatlistUpdates"&&ee.createPopup(Cf,{chatlistInvite:{...i.chatlistUpdates,already_peers:[],_:"chatlists.chatlistInviteAlready",filter_id:e.id},updating:!0})},contextMenu:{buttons:[{icon:"hide",text:"HideAboveTheList",onClick:()=>{this.managers.filtersStorage.hideChatlistUpdates(e.id).then(()=>{this.filterId===e.id&&this.fetchChatlistUpdates?.()})},verify:()=>e.topNotificationData?._==="chatlistUpdates"}]},icon:"next"});s.container.classList.add("chatlist-top-notification"),t.append(s.container)}toggleTopNotification(e,t){if(!t&&!e.topNotification)return;let s=!0;t&&(s=!!e.topNotificationContainer.parentElement,s||e.scrollable.prepend(e.topNotificationContainer)),bt({element:e.topNotificationContainer,className:"is-visible",duration:250,forwards:t,useRafs:s?0:2,onTransitionEnd:t?void 0:()=>{e.topNotificationContainer.remove(),e.topNotification=e.topNotificationContainer=e.topNotificationData=void 0}})}addFilter(e){const{id:t}=e;if(t===Vi)return;const s=this.folders.menu,i=this.filtersRendered[t];if(i){Ps(i.menu,s,e.localId),Ps(i.container,this.folders.container,e.localId);return}const n=document.createElement("div");n.classList.add("menu-horizontal-div-item");const a=document.createElement("span");a.classList.add("menu-horizontal-div-item-span");const r=document.createElement("span");r.classList.add("text-super"),t===Ci?r.append(this.allChatsIntlElement.element):kt(r,_e(e.title));const l=bl("div",20,"primary"),c=document.createElement("i");a.append(r,l,c),Ni(n),n.append(a),n.dataset.filterId=""+t,Ps(n,s,e.localId);const{ul:d,scrollable:h}=this.l(e);h.container.classList.add("tabs-tab","chatlist-parts");const u=document.createElement("div");u.classList.add("chatlist-top");const p=document.createElement("div");p.classList.add("chatlist-bottom"),u.append(d),h.append(u,p);const m=h.container;Ps(h.container,this.folders.container,e.localId),this.filtersRendered[t]={id:t,menu:n,container:m,unread:l,title:r,scrollable:h},this.onFiltersLengthChange()}changeFiltersAllChatsKey(){const e=this.folders.menuScrollContainer.firstElementChild,t=e.scrollWidth>e.clientWidth?"FilterAllChatsShort":"FilterAllChats";this.allChatsIntlElement.compareAndUpdate({key:t})}onFiltersLengthChange(){let e=this.showFiltersPromise;return e??(e=this.showFiltersPromise=Hs(0).then(()=>{if(this.showFiltersPromise!==e)return;const s=Object.keys(this.filtersRendered).length>1,i=!this.folders.menuScrollContainer.classList.contains("hide");s!==i&&(this.folders.menuScrollContainer.classList.toggle("hide",!s),s&&!i&&this.setFiltersUnreadCount(),this.chatsContainer.classList.toggle("has-filters",s)),this.changeFiltersAllChatsKey(),this.showFiltersPromise=void 0}))}generateEmptyPlaceholder(e){const t="empty-placeholder",s=document.createElement("div");s.classList.add(t,t+"-"+e.classNameType);const i=document.createElement("div");i.classList.add(t+"-header"),Zt(i,e.title);const n=document.createElement("div");return n.classList.add(t+"-subtitle"),e.subtitle&&Zt(n,e.subtitle,e.subtitleArgs),s.append(i,n),{container:s,header:i,subtitle:n}}checkIfPlaceholderNeeded(){if(this.filterId===Vi)return;const e=this.chatList,t=e.parentElement;let s=Array.from(t.children).find(r=>r.matches(".empty-placeholder"));const i=this.xd.scrollable.loadedAll.bottom&&!e.childElementCount;if(i&&s)return;if(!i){s&&(t.classList.remove("with-placeholder"),s.remove());return}let n,a;if(this.filterId){n=this.generateEmptyPlaceholder({title:"FilterNoChatsToDisplay",subtitle:"FilterNoChatsToDisplayInfo",classNameType:a="folder"}),s=n.container;const r=document.createElement("div"),l="📂",c=128;Sr({div:r,emoji:l,width:c,height:c}),s.prepend(r);const d=ze("btn-primary btn-color-primary btn-control",{text:"FilterHeaderEdit",icon:"settings"});N(d,async()=>{const h=Ii.createTab(Da);h.setInitFilter(await this.managers.filtersStorage.getFilter(this.filterId)),h.open()}),s.append(d)}else{n=this.generateEmptyPlaceholder({title:"ChatList.Main.EmptyPlaceholder.Title",classNameType:a="dialogs"}),s=n.container;const r=document.createElement("img");r.classList.add("empty-placeholder-dialogs-icon"),this.emptyDialogsPlaceholderSubtitle=new ke.IntlElement({element:n.subtitle}),Promise.all([this.updateContactsLength(!1),Ki(r,"assets/img/EmptyChats.svg"),ym()]).then(([l])=>{s.classList.add("visible"),t.classList.toggle("has-contacts",!!l)}),s.prepend(r)}t.append(s),t.classList.add("with-placeholder"),t.dataset.placeholderType=a}updateContactsLength(e){return this.updateContactsLengthPromise??(this.updateContactsLengthPromise=this.managers.appUsersManager.getContacts().then(t=>{const s=this.emptyDialogsPlaceholderSubtitle;if(s){let i,n;t.length?(i="ChatList.Main.EmptyPlaceholder.Subtitle",n=[M("Contacts.Count",[t.length])]):(i="ChatList.Main.EmptyPlaceholder.SubtitleNoContacts",n=[]),s.compareAndUpdate({key:i,args:n})}return e&&this.chatList.parentElement.classList.toggle("has-contacts",!!t.length),this.updateContactsLengthPromise=void 0,t.length}))}removeContactsPlaceholder(){const e=this.chatList,t=e.parentElement.parentElement,s=e.parentElement.nextElementSibling;t.classList.remove("with-contacts"),s.replaceChildren(),this.loadContacts=void 0,this.processContact=void 0}async toggleForumTab(e,t=this.forumTab){if(!t&&!e)return;if(t){const l=this.xd.getDialogElement(t.peerId);l&&l.dom.listEl.classList.remove("is-forum-open")}t===e&&(e=void 0),t?.toggle(!1);const s=e?.toggle(!0);if(t===this.forumTab&&(this.forumTab=e),e){const l=this.xd.getDialogElement(e.peerId);l&&l.dom.listEl.classList.add("is-forum-open"),me.selectTab(Ll.CHATLIST)}s&&await s,e&&!this.forumNavigationItem?(this.forumNavigationItem={type:"forum",onPop:()=>{this.forumNavigationItem=void 0,this.toggleForumTab()}},ft.pushItem(this.forumNavigationItem)):!e&&this.forumNavigationItem&&(ft.removeItem(this.forumNavigationItem),this.forumNavigationItem=void 0);const i=!!e,n=s?2:void 0;this.xd.toggleAvatarUnreadBadges(i,n);const a=Pt(),r=300;bt({element:this.forumsSlider.parentElement,className:"is-forum-visible",duration:r,forwards:i,useRafs:n,onTransitionEnd:()=>{a.resolve()}}),Xr(a,r).then(()=>a.resolve())}async toggleForumTabByPeerId(e,t,s){if(e===I.myId){const h=Ii.getTab(co);t===!0||t===void 0&&!h?co.open(Ii,e,!0):(h?.peerId===e&&h.close(),me.setPeer({peerId:e}));return}const{managers:i}=this,n=Ii.getHistory(),a=n[n.length-1],r=await i.dialogsStorage.getDialogOnly(e);if(r&&!!r.pFlags.view_forum_as_messages){const h=me.chat?.peerId===e;me[h||!s?"setPeer":"setInnerPeer"]({type:te.Chat,peerId:e});return}let c;if(a){if(a instanceof um&&a.peerId===e&&t){Va(a.container);return}c=Ii.createTab(um),c.open({peerId:e,managers:i});return}c=this.forumsTabs.get(e);const d=this.forumTab&&this.forumTab===c;if(t??(t=!d),t===d){t&&Va(c.container);return}return t&&!c&&(c=new um(void 0),c.init({peerId:e,managers:i}),this.forumsTabs.set(e,c),this.forumsSlider.append(c.container),c.managers=this.managers,c.eventListener.addEventListener("destroy",()=>{this.forumsTabs.delete(e)})),this.toggleForumTab(c)}openDialogInNewTab(e){const t=e.dataset.peerId.toPeerId(),s=+e.dataset.mid||void 0,i=+e.dataset.threadId||void 0,n=new URLSearchParams;n.set("p",""+t),s&&n.set("message",""+s),i&&n.set("thread",""+i);const a=`#/im?${n.toString()}`;window.open(a,"_blank")}setListClickListener({list:e,onFound:t,withContext:s=!1,autonomous:i=!1,openInner:n=!1}){let a;const r=(n?me.setInnerPeer:me.setPeer).bind(me),l=c=>c.closest(".avatar.has-stories");e.dataset.autonomous=""+ +i,e.addEventListener("mousedown",c=>{if(c.button!==0||l(c.target))return;this.log("dialogs click list");const d=c.target,h=Bi(d,Nl);if(!h)return;const u=h.dataset.peerId.toPeerId(),p=+h.dataset.mid||void 0,m=+h.dataset.threadId||void 0;if(t?.(h)===!1)return;if(!!h.querySelector(".is-forum")&&!c.shiftKey&&!p){this.toggleForumTabByPeerId(u,void 0,!1);return}if(c.ctrlKey||c.metaKey){this.openDialogInNewTab(h),oe(c);return}i&&(a&&!(a===h)&&this.setDialogActiveStatus(a,!1),h&&(this.setDialogActiveStatus(h,!0),a=h,this.lastActiveElements.add(h))),(!m||p)&&this.xd.sortedList.list===e&&this.xd!==this.xds[Vi]&&this.toggleForumTab(),r({peerId:u,lastMsgId:p,threadId:m})},{capture:!0}),e.addEventListener("click",c=>{c.button===0&&oe(c);const d=l(c.target);d&&me.openStoriesFromAvatar(d)},{capture:!0}),s&&this.contextMenu.attach(e)}createChatList(e={}){const t=document.createElement("ul");return t.classList.add("chatlist"),e.new&&t.classList.add("chatlist-new"),e.dialogSize&&t.classList.add("chatlist-"+e.dialogSize),t}setLastMessageN(e){return this.setLastMessage(e).catch(s=>{s?.type!=="MIDDLEWARE"&&this.log.error("set last message error",s)})}getLastMessageForDialog(e,t){let s;const{peerId:i,draft:n}=e;if(!t&&(n?._==="draftMessage"&&(!i.isAnyChat()||Fa(e)||!fe.isForum(i))&&(s=n),t=e.topMessage,t?.mid!==e.top_message)){const a=fe.getMessageByPeer(i,e.top_message);a&&a.action?._!=="messageActionChannelJoined"&&(t=a)}return{lastMessage:t,draftMessage:s}}async setLastMessage({dialog:e,lastMessage:t,dialogElement:s,highlightWord:i,isBatch:n=!1,setUnread:a=!1,noForwardIcon:r}){if(!s&&(s=this.xd.getDialogElement(e.peerId),!s))return;const{dom:l}=s,{peerId:c}=e,d=la(e),{deferred:h,middleware:u}=fb(l,"setLastMessagePromise"),{draftMessage:p,lastMessage:m}=this.getLastMessageForDialog(e,t),g=a!==null&&!a;if(g||this.setUnreadMessagesN({dialog:e,dialogElement:s,isBatch:n,setLastMessagePromise:h}),!m&&!p){l.lastMessageSpan.replaceChildren(),l.lastTimeSpan.replaceChildren(),delete l.listEl.dataset.mid,h.resolve();return}g&&m&&(l.listEl.dataset.mid=""+m.mid,m.reply_to?.pFlags?.forum_topic&&(l.listEl.dataset.threadId=""+ha(m)));const f=!!m&&ew(m);{let y,v=[],w;if(p||(m?.fwdFromId&&!d&&!r?w="forward_filled":m?.reply_to?._==="messageReplyStoryHeader"&&(w="storyreply")),w){const E=Le(w,"dialog-subtitle-ico","dialog-subtitle-ico-"+w);v.push(E)}if(m&&!p&&!f){const E=Xs(m,!0),_=new Set(["video","gif","round"]);if(E&&(E._==="photo"||_.has(E.type))){const k=Sn(E,20,20);if(k._!=="photoSizeEmpty"&&(y=document.createElement("div"),y.classList.add("dialog-subtitle-media"),E.type==="round"&&y.classList.add("is-round"),v.push(Ks({photo:E,message:m,container:y,withoutPreloader:!0,size:k}).then(()=>y)),_.has(E.type))){const x=Le("play","dialog-subtitle-media-play");y.append(x)}}}if(p){const E=document.createElement("span");E.classList.add("danger"),E.append(M("Draft"),": "),v.unshift(E)}else if(c.isAnyChat()&&c!==m.fromId&&!m.action){const E=document.createElement("span");if(E.classList.add("primary-text"),m.fromId===I.myId)E.append(M("FromYou")),v.unshift(E);else{const _=u(Oe({peerId:m.fromId,onlyFirstName:!0})).then(k=>(E.prepend(k),E),Wt);v.unshift(_)}E.append(": ")}const b=!!y&&!!m?.message,S={textColor:this.getTextColor(l.listEl.classList.contains("active"))};let C,P;i&&m?.message?P=hr({...S,message:m,highlightWord:i,withoutMediaType:b}):p?P=hr({...S,message:p}):m?P=hr({...S,message:m,withoutMediaType:b}):C=document.createDocumentFragment(),P&&(C=await u(P)),v.length&&(v=await u(Promise.all(v))),l.lastMessageSpan.classList.toggle("dialog-subtitle-flex",!0);{const E=[...v,C].map((_,k,x)=>{const A=document.createElement("span");return A.classList.add("dialog-subtitle-span"),A.classList.add("dialog-subtitle-span-overflow"),k===x.length-1&&(A.classList.add("dialog-subtitle-span-last"),A.dir="auto"),A.append(_),A});l.lastMessageSpan.replaceChildren(...E)}}if(m||p){const y=p?Math.max(p.date,m?.date||0):m.date;dt(l.lastTimeSpan,Md(new Date(y*1e3)))}else l.lastTimeSpan.textContent="";h.resolve()}setUnreadMessagesN(e){return this.setUnreadMessages(e).catch(()=>{})}async setUnreadMessages({dialog:e,dialogElement:t,isBatch:s=!1,setLastMessagePromise:i}){const{dom:n}=t;if(!n)return;const a=Fa(e),r=la(e),{deferred:l,middleware:c}=fb(n,"setUnreadMessagePromise"),{peerId:d}=e,h=Promise.all([this.managers.appNotificationsManager.isPeerLocalMuted({peerId:d,respectType:!0,threadId:a?e.id:void 0}),r?void 0:this.getLastMessageForDialog(e),a||r?!!e.pFlags.pinned:this.managers.dialogsStorage.isDialogPinned(d,this.filterId),this.managers.appMessagesManager.isDialogUnread(e),d.isAnyChat()&&!a?this.managers.acknowledged.dialogsStorage.getForumUnreadCount(d,!0).then(se=>se.cached?se.result:(se.result.then(()=>{this.setUnreadMessagesN({dialog:e,dialogElement:t})}),{count:0,hasUnmuted:!1})).catch(()=>{}):void 0]);let[u,p,m,g,f]=await c(h);const y=n.listEl.classList.contains("is-muted")&&!n.listEl.classList.contains("backwards"),{count:v,hasUnmuted:w}=f||{},{draftMessage:b,lastMessage:S}=p||{};let C;!b&&S&&S.pFlags.out&&S.peerId!==I.myId&&(C=S);const P=v??(r?0:e.unread_count);if(v!==void 0&&(g=!!P),a&&!g&&(g=!yn(e.read_inbox_max_id)),i)try{await c(i)}catch{return}const L=s?0:Cu;n.listEl.classList.toggle("no-unmuted-topic",!u&&w!==void 0&&!w),u!==y&&(u&&!n.mutedIcon&&(n.mutedIcon=Le("nosound","dialog-muted-icon"),n.titleSpanContainer.append(n.mutedIcon)),bt({element:n.listEl,className:"is-muted",forwards:u,duration:L,onTransitionEnd:u?void 0:()=>{n.mutedIcon.remove(),delete n.mutedIcon}})),tR(n.statusSpan,a&&e.pFlags.closed?"premium_lock":C);const E=m,_=!!n.pinnedBadge;E&&t.createPinnedBadge();const k=g,x=!!n.unreadBadge;k&&t.createUnreadBadge();const A=this.xd!==this.xds[Vi]&&!a&&!!this.forumTab&&this.xd.getDialogElement(d)===t&&g,T=!!n.unreadAvatarBadge;A&&t.createUnreadAvatarBadge();const B=r?!1:e.unread_mentions_count&&(e.unread_mentions_count>1||e.unread_count>1),R=!!n.mentionsBadge;B&&t.createMentionsBadge();const O=r?!1:!!e.unread_reactions_count,X=!!n.reactionsBadge;O&&t.createReactionsBadge();const F=[E,k,B,O].filter(Boolean).length;if(bt({element:t.subtitleRow,className:"has-only-pinned-badge",forwards:E&&F===1,duration:s?0:Cu}),[["pinnedBadge",E,_],["unreadBadge",k,x],["unreadAvatarBadge",A,T],["mentionsBadge",B,R],["reactionsBadge",O,X]].forEach(([se,Y,Q])=>{n[se]&&t.toggleBadgeByKey(se,Y,Q,s)}),!k){l.resolve();return}let G=!0,z=!1,q;if(!r&&e.unread_mentions_count&&P===1?(q="@",z=!0):g?q=""+(P?on(P,1):" "):(q="",G=!1),a){const se=g&&q===" ";n.unreadBadge.classList.toggle("not-visited",se)}[n.unreadBadge&&[n.unreadBadge,q],n.unreadAvatarBadge&&[n.unreadAvatarBadge,q||void 0]].filter(Boolean).forEach(([se,Y])=>{Y!==void 0&&(se.innerText=q),se.classList.toggle("unread",G),se.classList.toggle("mention",z)}),l.resolve()}async getDialog(e,t){if(typeof e!="object"){let s;if(t){if(e===I.myId){if(s=await this.managers.dialogsStorage.getAnyDialog(e,t),!s)return{peerId:e||Tt,pFlags:{}}}else if(s=await this.managers.dialogsStorage.getForumTopic(e,t),!s)return{peerId:e||Tt,pFlags:{}}}else if(s=await this.managers.appMessagesManager.getDialogOnly(e),!s){const i=e||Tt;return{peerId:i,peer:await this.managers.appPeersManager.getOutputPeer(i),pFlags:{}}}return s}return e}addListDialog(e){e.autonomous=!1,e.withStories=!0;const t=this.addDialogNew(e);if(t){const{peerId:s}=e,n=this.getDialog(s,e.threadId).then(a=>{const r=[],l=s.isUser();return!l&&lr(a)&&r.push(this.xd.processDialogForCallStatus(s,t.dom)),s!==I.myId&&l&&r.push(this.managers.appUsersManager.getUserStatus(s.toUserId()).then(c=>{c?._==="userStatusOnline"&&this.xd.setOnlineStatus(t.dom.avatarEl.node,!0)})),r.push(this.setLastMessageN({dialog:a,dialogElement:t,isBatch:e.isBatch,setUnread:!0})),Promise.all(r)});e.loadPromises?.push(n)}return t}addDialogAndSetLastMessage(e){const{peerId:t,message:s,query:i}=e,n=this.addDialogNew({...e,...tS(s),peerId:t});return this.setLastMessageN({dialog:{_:"dialog",peerId:t},lastMessage:s,dialogElement:n,highlightWord:i}),s.peerId!==t&&(n.dom.listEl.dataset.peerId=""+s.peerId),n}addDialogNew(e){const t=new wg({autonomous:!!e.container,avatarSize:"bigger",...e});if(t.container.dialogElement=t,e.container){const s=e.append===!1?"prepend":"append";e.container[s](t.container)}return t}}const ms=new dR;Ws.appDialogsManager=ms;const Xe=ms;export{dR as AppDialogsManager,Nl as DIALOG_LIST_ELEMENT_TAG,wg as DialogElement,lR as Some4,Yf as SortedDialogList,Xe as default};
//# sourceMappingURL=appDialogsManager-DIyIdzjh.js.map