tweb/public/911.5ad2ede78b83a9191cd2.chunk.js
Eduard Kuzmenko 3cc5df683e Build
2022-08-22 13:05:40 +02:00

2 lines
999 KiB
JavaScript
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.

(this.webpackChunktweb=this.webpackChunktweb||[]).push([[911],{4494:(e,t,i)=>{"use strict";i.d(t,{Z:()=>a});var s=i(2325),n=i(1405);const a=(e,t={})=>{const i=document.createElement(t.asDiv?"div":"button");return i.className=e+(t.icon?" tgico-"+t.icon:""),t.noRipple||(t.rippleSquare&&i.classList.add("rp-square"),(0,n.Z)(i)),t.onlyMobile&&i.classList.add("only-handhelds"),t.disabled&&i.setAttribute("disabled","true"),t.text&&i.append((0,s.ag)(t.text)),i}},4489:(e,t,i)=>{"use strict";i.d(t,{Z:()=>n});var s=i(503);class n extends s.Z{constructor(e){super(Object.assign({plainText:!0},e));const t=this.input;t.type="tel",t.setAttribute("required",""),t.autocomplete="off";let i=0;this.input.addEventListener("input",(t=>{this.input.classList.remove("error"),this.setLabel();const s=this.value.replace(/\D/g,"").slice(0,e.length);this.setValueSilently(s);const n=this.value.length;if(n===e.length)e.onFill(this.value);else if(n===i)return;i=n}))}}},4425:(e,t,i)=>{"use strict";i.d(t,{Z:()=>n});var s=i(2384);class n{constructor(e,t){this.passwordInputField=e,this.size=t,this.needFrame=0,this.container=document.createElement("div"),this.container.classList.add("media-sticker-wrapper")}load(){return this.loadPromise?this.loadPromise:this.loadPromise=s.Z.loadAnimationAsAsset({container:this.container,loop:!1,autoplay:!1,width:this.size,height:this.size,noCache:!0},"TwoFactorSetupMonkeyPeek").then((e=>(this.animation=e,this.animation.addEventListener("enterFrame",(e=>{(1===this.animation.direction&&e>=this.needFrame||-1===this.animation.direction&&e<=this.needFrame)&&(this.animation.setSpeed(1),this.animation.pause())})),this.passwordInputField.onVisibilityClickAdditional=()=>{this.passwordInputField.passwordVisible?(this.animation.setDirection(1),this.animation.curFrame=0,this.needFrame=16,this.animation.play()):(this.animation.setDirection(-1),this.animation.curFrame=16,this.needFrame=0,this.animation.play())},s.Z.waitForFirstFrame(e))))}remove(){this.animation&&this.animation.remove()}}},3083:(e,t,i)=>{"use strict";i.d(t,{Z:()=>n});var s=i(2384);class n{constructor(e,t){this.inputField=e,this.size=t,this.max=45,this.needFrame=0,this.container=document.createElement("div"),this.container.classList.add("media-sticker-wrapper");const i=e.input;i.addEventListener("blur",(()=>{this.playAnimation(0)})),i.addEventListener("input",(t=>{this.playAnimation(e.value.length)}))}playAnimation(e){if(!this.animation)return;let t;(e=Math.min(e,30))?(t=Math.round(Math.min(this.max,e)*(165/this.max)+11.33),this.idleAnimation&&(this.idleAnimation.stop(!0),this.idleAnimation.canvas.style.display="none"),this.animation.canvas.style.display=""):t=0;const i=this.needFrame>t?-1:1;this.animation.setDirection(i),0!==this.needFrame&&0===t&&this.animation.setSpeed(7),this.needFrame=t,this.animation.play()}load(){return this.loadPromise?this.loadPromise:this.loadPromise=Promise.all([s.Z.loadAnimationAsAsset({container:this.container,loop:!0,autoplay:!0,width:this.size,height:this.size},"TwoFactorSetupMonkeyIdle").then((e=>(this.idleAnimation=e,this.inputField.value.length||e.play(),s.Z.waitForFirstFrame(e)))),s.Z.loadAnimationAsAsset({container:this.container,loop:!1,autoplay:!1,width:this.size,height:this.size},"TwoFactorSetupMonkeyTracking").then((e=>(this.animation=e,this.inputField.value.length||(this.animation.canvas.style.display="none"),this.animation.addEventListener("enterFrame",(e=>{(1===this.animation.direction&&e>=this.needFrame||-1===this.animation.direction&&e<=this.needFrame)&&(this.animation.setSpeed(1),this.animation.pause()),0===e&&0===this.needFrame&&this.idleAnimation&&(this.idleAnimation.canvas.style.display="",this.idleAnimation.play(),this.animation.canvas.style.display="none")})),s.Z.waitForFirstFrame(e))))])}remove(){this.animation&&this.animation.remove(),this.idleAnimation&&this.idleAnimation.remove()}}},6830:(e,t,i)=>{"use strict";i.d(t,{Z:()=>a});var s=i(3910),n=i(503);class a extends n.Z{constructor(e={}){super(Object.assign({plainText:!0},e)),this.passwordVisible=!1,this.onVisibilityClick=e=>{(0,s.Z)(e),this.passwordVisible=!this.passwordVisible,this.toggleVisible.classList.toggle("eye-hidden",this.passwordVisible),this.input.type=this.passwordVisible?"text":"password",this.onVisibilityClickAdditional&&this.onVisibilityClickAdditional()};const t=this.input;t.type="password",t.setAttribute("required",""),t.name="notsearch_password",t.autocomplete="off";const i=document.createElement("input");i.classList.add("stealthy"),i.tabIndex=-1,i.type="password",t.parentElement.prepend(i),t.parentElement.insertBefore(i.cloneNode(),t.nextSibling);const n=this.toggleVisible=document.createElement("span");n.classList.add("toggle-visible","tgico"),this.container.classList.add("input-field-password"),this.container.append(n),n.addEventListener("click",this.onVisibilityClick),n.addEventListener("touchend",this.onVisibilityClick)}}},279:(e,t,i)=>{"use strict";function s(e,t=!1){const i='\n <svg xmlns="http://www.w3.org/2000/svg" class="preloader-circular" viewBox="25 25 50 50">\n <circle class="preloader-path" cx="50" cy="50" r="20" fill="none" stroke-miterlimit="10"/>\n </svg>';if(t){const t=document.createElement("div");return t.classList.add("preloader"),t.innerHTML=i,e&&e.appendChild(t),t}return e.insertAdjacentHTML("beforeend",i),e.lastElementChild}function n(e,t="check"){return e.classList.remove("tgico-"+t),e.disabled=!0,s(e),()=>{e.innerHTML="",e.classList.add("tgico-"+t),e.removeAttribute("disabled")}}i.d(t,{p:()=>n,y:()=>s}),i(410).GO.putPreloader=s},1405:(e,t,i)=>{"use strict";i.d(t,{Z:()=>c});var s=i(8497),n=i(9674),a=i(5432),o=i(3512),r=i(5975);let l=0;function c(e,t=(()=>Promise.resolve()),i=null,c=!1,d=e){if(e.querySelector(".c-ripple"))return;e.classList.add("rp");const h=document.createElement("div");let u;h.classList.add("c-ripple"),e.classList.contains("rp-square")&&h.classList.add("is-square"),e[c?"prepend":"append"](h);const p=(e,s)=>{const o=Date.now(),r=document.createElement("div"),c=l++,d=1e3*+window.getComputedStyle(h).getPropertyValue("--ripple-duration").replace("s","");u=()=>{const e=Date.now()-o,t=()=>{n.Z.mutate((()=>{r.remove()})),i&&i(c)};if(e<d){const i=Math.max(d-e,d/2);setTimeout((()=>r.classList.add("hiding")),Math.max(i-d/2,0)),setTimeout(t,i)}else r.classList.add("hiding"),setTimeout(t,d/2);a.Z||window.removeEventListener("contextmenu",u),u=null,g=!1},t&&t(c),window.requestAnimationFrame((()=>{const t=h.getBoundingClientRect();r.classList.add("c-ripple__circle");const i=e-t.left,n=s-t.top,a=Math.sqrt(Math.pow(Math.abs(n-t.height/2)+t.height/2,2)+Math.pow(Math.abs(i-t.width/2)+t.width/2,2)),o=i-a/2,l=n-a/2;r.style.width=r.style.height=a+"px",r.style.left=o+"px",r.style.top=l+"px",h.append(r)}))},m=t=>t.target!==e&&(["BUTTON","A"].includes(t.target.tagName)||(0,s.Z)(t.target,"c-ripple")!==h)&&(d===e||!(0,r.Z)(t.target,d));let g=!1;if(a.Z){const e=()=>{u&&u()};d.addEventListener("touchstart",(t=>{if(!o.Z.settings.animationsEnabled)return;if(t.touches.length>1||g||m(t))return;g=!0;const{clientX:i,clientY:s}=t.touches[0];p(i,s),d.addEventListener("touchend",e,{once:!0}),window.addEventListener("touchmove",(t=>{t.cancelBubble=!0,t.stopPropagation(),e(),d.removeEventListener("touchend",e)}),{once:!0})}),{passive:!0})}else d.addEventListener("mousedown",(e=>{if(![0,2].includes(e.button))return;if(!o.Z.settings.animationsEnabled)return;if("0"===d.dataset.ripple||m(e))return;if(g)return void(g=!1);const{clientX:t,clientY:i}=e;p(t,i),window.addEventListener("mouseup",u,{once:!0,passive:!0}),window.addEventListener("contextmenu",u,{once:!0,passive:!0})}),{passive:!0})}},467:(e,t,i)=>{"use strict";i.d(t,{ST:()=>r,ZP:()=>l,gV:()=>c});var s=i(5813);const n=/[`~!@#$%^&*()\-_=+\[\]\\|{}'";:\/?.>,<]+/g,a=/^\s+|\s$/g,o={й:"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 r(e){return e.replace(n,"").replace(a,"")}function l(e,t=!0){return c(e,{clearBadChars:!0,latinize:t,ignoreCase:!0})}function c(e,t={}){const i=t.includeTag&&"%"===e.charAt(0),n=e;return t.clearBadChars&&(e=r(e)),t.latinize&&(e=function(e){return e.replace(/[^A-Za-z0-9]/g,(e=>{const t=s.Z[e];return null!=t?t:e}))}(e)),t.ignoreCase&&(e=e.toLowerCase()),i&&(e="%"+e),t.latinize&&(e+=""+function(e){return e.toLowerCase().replace(/[\wа-я]/g,(e=>{const t=o[e];return null!=t?t:e}))}(n)),e}},2614:(e,t,i)=>{"use strict";function s(e){const t=document.createElement("span");return"string"==typeof e?t.innerHTML=e:t.append(e),t}i.d(t,{Z:()=>s})},9674:(e,t,i)=>{"use strict";i.d(t,{Z:()=>l});var s=i(3035),n=i(3725),a=i(410),o=i(8487);const r=new class{constructor(){this.promises={},this.raf=s.T2.bind(null),this.scheduled=!1}do(e,t){let i=this.promises[e];return i||(this.scheduleFlush(),i=this.promises[e]=(0,n.Z)()),void 0!==t&&i.then((()=>t())),i}measure(e){return this.do("read",e)}mutate(e){return this.do("write",e)}mutateElement(e,t){const i=(0,o.Z)(e),s=i?this.mutate():Promise.resolve();return void 0!==t&&(i?t():s.then((()=>t()))),s}scheduleFlush(){this.scheduled||(this.scheduled=!0,this.raf((()=>{this.promises.read&&this.promises.read.resolve(),this.promises.write&&this.promises.write.resolve(),this.scheduled=!1,this.promises={}})))}};a.GO&&(a.GO.sequentialDom=r);const l=r},3911:(e,t,i)=>{"use strict";i.r(t),i.d(t,{AppDialogsManager:()=>pg,DIALOG_LIST_ELEMENT_TAG:()=>dg,default:()=>gg});var s=i(3512),n=i(2738),a=i(3910),o=i(2341),r=i(8497),l=i(4668),c=i(130),d=i(4755),h=i(3719),u=i(2312),p=i(5814),m=i(8805),g=i(5565),v=i(2325);class f{constructor(e,t,i=!0,s,n=!0,a=!0,o,r){this.name=e,this.type=t,this.clearable=i,this.autonomous=a,this.onFound=o,this.noIcons=r,this.list=gg.createChatList(),this.container=document.createElement("div"),s&&(this.container.className=s),e&&(this.nameEl=document.createElement("div"),this.nameEl.classList.add("search-group__name"),"string"==typeof e&&this.nameEl.append((0,v.ag)(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&&gg.setListClickListener(this.list,o,void 0,a)}clear(){this.container.style.display="none",this.clearable&&(this.list.innerHTML="")}setActive(){this.container.style.display=""}toggle(){this.list.childElementCount?this.setActive():this.clear()}}class y{constructor(e,t,i,s,n){this.container=e,this.searchInput=t,this.searchGroups=i,this.onSearch=s,this.noIcons=n,this.minMsgId=0,this.loadedCount=-1,this.foundCount=-1,this.searchPromise=null,this.searchTimeout=0,this.query="",this.listsContainer=null,this.threadId=0,this.scrollable=new m.ZP(this.container),this.listsContainer=this.scrollable.container;for(const e in this.searchGroups)this.listsContainer.append(this.searchGroups[e].container);this.searchGroups.messages&&this.scrollable.setVirtualContainer(this.searchGroups.messages.list),this.searchInput.onChange=e=>{this.query=e,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.minMsgId=0,this.loadedCount=-1,this.foundCount=-1;for(const e in this.searchGroups)this.searchGroups[e].clear();this.searchPromise=null}beginSearch(e,t=0,i=""){this.peerId=e,this.threadId=t,this.query!==i&&(this.searchInput.inputField.value=i),this.searchInput.input.focus()}searchMore(){if(this.searchPromise)return this.searchPromise;const e=this.query;if(!e.trim())return void(this.onSearch&&this.onSearch(0));if(-1!==this.foundCount&&this.loadedCount>=this.foundCount)return Promise.resolve();const t=this.minMsgId||0;return this.searchPromise=s.Z.managers.appMessagesManager.getSearch({peerId:this.peerId,query:e,inputFilter:{_:"inputMessagesFilterEmpty"},maxId:t,limit:20,threadId:this.threadId}).then((t=>{if(this.searchPromise=null,this.searchInput.value!==e)return;const{count:i,history:s}=t;s.length&&s[0].mid===this.minMsgId&&s.shift();const n=this.searchGroups.messages;s.forEach((t=>{try{const i=this.peerId?t.fromId:t.peerId;gg.addDialogAndSetLastMessage({peerId:i,container:this.scrollable,avatarSize:54,meAsSaved:!1,message:t,query:e,noIcons:this.noIcons})}catch(e){console.error("[appSearch] render search result",e)}})),n.toggle(),this.minMsgId=s.length&&s[s.length-1].mid,-1===this.loadedCount&&(this.loadedCount=0),this.loadedCount+=s.length,-1===this.foundCount&&(this.foundCount=i,n.nameEl&&(0,g.Z)(n.nameEl,(0,v.ag)(i?"Chat.Search.MessagesFound":"Chat.Search.NoMessagesFound",[i])),this.onSearch&&this.onSearch(this.foundCount))})).catch((e=>{console.error("search error",e),this.searchPromise=null}))}}var b=i(503);class w{constructor(e,t){this.prevValue="",this.timeout=0,this.onInput=()=>{if(!this.onChange)return;const e=this.value;e!==this.prevValue&&(this.prevValue=e,clearTimeout(this.timeout),this.timeout=window.setTimeout((()=>{this.onChange(e)}),200))},this.onClearClick=()=>{this.value="",this.onChange&&this.onChange(""),this.onClear&&this.onClear()},this.inputField=new b.Z({placeholder:e,plainText:!0}),this.container=this.inputField.container,this.container.classList.remove("input-field"),this.container.classList.add("input-search"),this.onChange=t,this.input=this.inputField.input,this.input.classList.add("input-search-input");const i=document.createElement("i");i.classList.add("tgico","tgico-search"),this.clearBtn=document.createElement("i"),this.clearBtn.classList.add("tgico","btn-icon","tgico-close"),this.input.addEventListener("input",this.onInput),this.clearBtn.addEventListener("click",this.onClearClick),this.container.append(i,this.clearBtn)}get value(){return this.inputField.value}set value(e){this.prevValue=e,clearTimeout(this.timeout),this.inputField.value=e}remove(){clearTimeout(this.timeout),this.input.removeEventListener("input",this.onInput),this.clearBtn.removeEventListener("click",this.onClearClick)}}var S=i(426),C=i(9818),L=i(3241),I=i(3699),M=i(4494);const E=(e,t={})=>(0,M.Z)("btn-icon",Object.assign({icon:e||void 0},t));class P{constructor(e,t){this._constructor(e,t)}_constructor(e,t=!0){this.slider=e,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=E("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 m.ZP(this.content,void 0,void 0,!0),this.container.append(this.header,this.content),this.slider&&this.slider.addTab(this),this.listenerSetter=new I.Z}close(){return this.slider.closeTab(this)}open(...e){return t=this,i=void 0,n=function*(){if(this.init)try{const e=this.init();this.init=null,e instanceof Promise&&(yield e)}catch(e){console.error("open tab error",e)}this.slider.selectTab(this)},new((s=void 0)||(s=Promise))((function(e,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,r)}l((n=n.apply(t,i||[])).next())}));var t,i,s,n}init(){}onCloseAfterTimeout(){var e;this.destroyable&&(this.slider.tabs.delete(this),this.container.remove(),this.scrollable.destroy(),null===(e=this.listenerSetter)||void 0===e||e.removeAll())}setTitle(e){this.title.innerHTML="",this.title.append((0,v.ag)(e))}}class k extends P{constructor(e){super(e),this.eventListener=new L.Z}onCloseAfterTimeout(){return this.eventListener.dispatchEvent("destroy"),this.eventListener.cleanup(),super.onCloseAfterTimeout()}}var T=i(1655),x=i(5953);class _{constructor(e){this.historyTabIds=[],this.canHideFirst=!1,this.onCloseBtnClick=()=>{C.Z.findItemByType(this.navigationType)?C.Z.back(this.navigationType):this.historyTabIds.length&&this.closeTab(this.historyTabIds[this.historyTabIds.length-1])},this.closeTab=(e,t,i)=>{if(void 0!==e&&this.historyTabIds[this.historyTabIds.length-1]!==e)return!1;const s=this.historyTabIds.pop();this.onCloseTab(s,t,i);const n=this.historyTabIds[this.historyTabIds.length-1];return this._selectTab(void 0!==n?n instanceof P?n.container:n:this.canHideFirst?-1:0,t),!0},(0,x.Z)(this,e),this.tabs||(this.tabs=new Map),this.tabsContainer=this.sidebarEl.querySelector(".sidebar-slider"),this._selectTab=(0,S.v)(this.tabsContainer,"navigation",250),this.canHideFirst||this._selectTab(0),Array.from(this.sidebarEl.querySelectorAll(".sidebar-close-button")).forEach((e=>{(0,n.fc)(e,this.onCloseBtnClick)}))}selectTab(e){if(this.historyTabIds[this.historyTabIds.length-1]===e)return!1;const t=e instanceof P?e:this.tabs.get(e);return t&&(t.onOpen&&t.onOpen(),t.onOpenAfterTimeout&&setTimeout((()=>{t.onOpenAfterTimeout()}),250)),C.Z.pushItem({type:this.navigationType,onPop:e=>(this.closeTab(void 0,e,!0),!0)}),this.historyTabIds.push(e),this._selectTab(e instanceof P?e.container:e),!0}removeTabFromHistory(e){(0,T.Z)(this.historyTabIds,e),this.onCloseTab(e,void 0)}sliceTabsUntilTab(e,t){for(let i=this.historyTabIds.length-1;i>=0;--i){const s=this.historyTabIds[i];if(s!==t){if(s instanceof e)break;this.removeTabFromHistory(s)}}}getTab(e){return this.historyTabIds.find((t=>t instanceof e))}isTabExists(e){return!!this.getTab(e)}onCloseTab(e,t,i){i||C.Z.removeByType(this.navigationType,!0);const s=e instanceof P?e:this.tabs.get(e);s&&(s.onClose&&s.onClose(),s.onCloseAfterTimeout&&setTimeout((()=>{s.onCloseAfterTimeout()}),280))}addTab(e){e.container.parentElement||(this.tabsContainer.append(e.container),e.closeBtn&&e.closeBtn.addEventListener("click",this.onCloseBtnClick))}createTab(e,t){const i=new e(t?void 0:this,!0);return i.managers=this.managers,i}}var A=i(1168),Z=i(6765);class F{constructor(e){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=document.createElement("span"),this.icon.classList.add("tgico","tgico-cameraadd"),this.container.append(this.canvas,this.icon),(0,n.fc)(this.container,(()=>{A.Z.createPopup(Z.Z).open(this.canvas,e)}))}clear(){this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height)}}const D=(e={})=>(0,M.Z)("btn-circle btn-corner z-depth-1"+(e.className?" "+e.className:""),e);var R=i(410);const B=["January","February","March","April","May","June","July","August","September","October","November","December"],N=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],U=86400,O=e=>{const t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())),i=t.getUTCDay()||7;t.setUTCDate(t.getUTCDate()+4-i);const s=new Date(Date.UTC(t.getUTCFullYear(),0,1));return Math.ceil(((t.getTime()-s.getTime())/U+1)/7)};function H(e){const t=new Date,i=t.getTime()/1e3|0,s=e.getTime()/1e3|0,n={};return i-s<U&&t.getDate()===e.getDate()?n.hour=n.minute="2-digit":t.getFullYear()!==e.getFullYear()?(n.year=n.day="numeric",n.month="2-digit"):i-s<604800&&O(t)===O(e)?n.weekday="short":(n.month="short",n.day="numeric"),new v.ZP.IntlDateElement({date:e,options:n}).element}function z(e,t={}){const i=new Date,s=new Date(1e3*e),n=i.getTime()/1e3,a=V(s);let o;return n-e<U&&i.getDate()===s.getDate()?o=(0,v.ag)(t.capitalize?"Date.Today":"Peer.Status.Today"):n-e<172800&&i.getDate()-1===s.getDate()?(o=(0,v.ag)(t.capitalize?"Yesterday":"Peer.Status.Yesterday"),t.capitalize&&(o.style.textTransform="capitalize")):o=i.getFullYear()!==s.getFullYear()?new v.ZP.IntlDateElement({date:s,options:{month:"short",day:"numeric",year:"numeric"}}).element:new v.ZP.IntlDateElement({date:s,options:{month:"short",day:"numeric"}}).element,{dateEl:o,timeEl:a}}function G(e){const{dateEl:t,timeEl:i}=z(e,{capitalize:!0}),s=document.createDocumentFragment();return s.append(t," ",(0,v.ag)("ScheduleController.at")," ",i),s}function V(e){return new v.ZP.IntlDateElement({date:e,options:{hour:"2-digit",minute:"2-digit"}}).element}R.GO&&(R.GO.formatDateAccordingToTodayNew=H);const K=(e,t={})=>{const i=t.monthAsNumber?".":" ",s=("0"+e.getHours()).slice(-2)+":"+("0"+e.getMinutes()).slice(-2)+(t.noSeconds?"":":"+("0"+e.getSeconds()).slice(-2));return(t.leadingZero?("0"+e.getDate()).slice(-2):e.getDate())+i+(t.monthAsNumber?("0"+(e.getMonth()+1)).slice(-2):B[e.getMonth()])+i+e.getFullYear()+(t.noTime?"":", "+s)},W=2013,$=new RegExp("20[0-9]{1,2}"),j=new RegExp("(\\w{3,}) ([0-9]{0,4})","i"),q=new RegExp("([0-9]{0,4}) (\\w{2,})","i"),Q=new RegExp("^([0-9]{1,4})(\\.| |/|\\-)([0-9]{1,4})$","i"),Y=new RegExp("^([0-9]{1,2})(\\.| |/|\\-)([0-9]{1,2})(\\.| |/|\\-)([0-9]{1,4})$","i"),J=[31,29,31,30,31,30,31,31,30,31,30,31];function X(e,t){const i=e.trim().toLowerCase();if(i.length<3)return;if(0==="today".indexOf(i)){const e=new Date,i=e.getFullYear(),s=e.getMonth(),n=e.getDate();e.setFullYear(i,s,n),e.setHours(0,0,0);const a=e.getTime();e.setFullYear(i,s,n+1),e.setHours(0,0,0);const o=e.getTime()-1;return void t.push({title:"Today",minDate:a,maxDate:o})}if(0==="yesterday".indexOf(i)){const e=new Date,i=e.getFullYear(),s=e.getMonth(),n=e.getDate();e.setFullYear(i,s,n),e.setHours(0,0,0);const a=e.getTime()-864e5;e.setFullYear(i,s,n+1),e.setHours(0,0,0);const o=e.getTime()-86400001;return void t.push({title:"Yesterday",minDate:a,maxDate:o})}const s=function(e){const t=new Date;if(e.length<=3)return-1;for(let i=0;i<7;i++)if(t.setDate(t.getDate()+1),0===ae(t.getTime()).toLowerCase().indexOf(e))return t.getDay();return-1}(i);if(s>=0){const e=new Date,i=e.getTime(),n=s-e.getDay();e.setDate(e.getDate()+n),e.getTime()>i&&e.setTime(e.getTime()-6048e5);const a=e.getFullYear(),o=e.getMonth(),r=e.getDate();e.setFullYear(a,o,r),e.setHours(0,0,0);const l=e.getTime();e.setFullYear(a,o,r+1),e.setHours(0,0,0);const c=e.getTime()-1;return void t.push({title:ae(l),minDate:l,maxDate:c})}let n;if(null===(n=Q.exec(i)))if(null===(n=Y.exec(i)))if(null===(n=$.exec(i))){if(null!==(n=j.exec(i))){const e=n[1],i=n[2],s=re(e);if(s>=0){const e=+i;if(e>0&&e<=31)return void te(t,e-1,s);if(e>=W)return void ee(t,s,e)}}if(null!==(n=q.exec(i))){const e=n[1],i=re(n[2]);if(i>=0){const s=+e;if(s>0&&s<=31)return void te(t,s-1,i);s>=W&&ee(t,i,s)}}}else{let e=+i;const s=(new Date).getFullYear();if(e<W){e=W;for(let i=s;i>=e;i--){const e=new Date;e.setFullYear(i,0,1),e.setHours(0,0,0);const s=e.getTime();e.setFullYear(i+1,0,1),e.setHours(0,0,0);const n=e.getTime()-1;t.push({title:""+i,minDate:s,maxDate:n})}}else if(e<=s){const i=new Date;i.setFullYear(e,0,1),i.setHours(0,0,0);const s=i.getTime();i.setFullYear(e+1,0,1),i.setHours(0,0,0);const n=i.getTime()-1;t.push({title:""+e,minDate:s,maxDate:n})}}else{const e=n[1],i=n[3],s=n[5];if(!n[2]===n[4])return;const a=parseInt(e),o=parseInt(i)-1;let r=parseInt(s);r>=10&&r<=99&&(r+=2e3);const l=(new Date).getFullYear();if(oe(a-1,o)&&r>=W&&r<=l){const e=new Date;e.setFullYear(r,o,a),e.setHours(0,0,0);const i=e.getTime();e.setFullYear(r,o,a+1),e.setHours(0,0,0);const s=e.getTime()-1;return void t.push({title:ne(i),minDate:i,maxDate:s})}}else{const e=n[1],i=n[3],s=parseInt(e),a=parseInt(i);if(s>0&&s<=31){if(a>=W&&s<=12)return void ee(t,s-1,a);a<=12&&te(t,s-1,a-1)}else s>=W&&a<=12&&ee(t,a-1,s)}}function ee(e,t,i){const s=(new Date).getFullYear(),n=Date.now();if(i>=W&&i<=s){const s=new Date;s.setFullYear(i,t,1),s.setHours(0,0,0);const a=s.getTime();if(a>n)return;s.setMonth(s.getMonth()+1);const o=s.getTime()-1;e.push({title:ie(a),minDate:a,maxDate:o})}}function te(e,t,i){if(oe(t,i)){const n=(new Date).getFullYear(),a=Date.now();for(let o=n;o>=W;o--){if(1===i&&28===t&&((s=o)%4!=0||s%100==0)&&s%400!=0)continue;const r=new Date;r.setFullYear(o,i,t+1),r.setHours(0,0,0);const l=r.getTime();if(l>a)continue;r.setFullYear(o,i,t+2),r.setHours(0,0,0);const c=r.getTime()-1;o===n?e.push({title:se(l),minDate:l,maxDate:c}):e.push({title:ne(l),minDate:l,maxDate:c})}}var s}function ie(e){const t=new Date(e);return B[t.getMonth()].slice(0,3)+" "+t.getFullYear()}function se(e){const t=new Date(e);return B[t.getMonth()].slice(0,3)+" "+t.getDate()}function ne(e){const t=new Date(e);return("0"+t.getDate()).slice(-2)+"."+("0"+(t.getMonth()+1)).slice(-2)+"."+t.getFullYear()}function ae(e){const t=new Date(e);return N[t.getDay()]}function oe(e,t){return t>=0&&t<12&&e>=0&&e<J[t]}function re(e){e=e.toLowerCase();for(let t=0;t<12;t++)if(0===B[t].toLowerCase().indexOf(e))return t;return-1}R.GO.fillTipDates=X;var le=i(1507);function ce(e){var t;if(!e)return document.createElement("span");let i,s;switch(e.id){case le.hj.toUserId():i="Peer.RepliesNotifications";break;case le.yF.toUserId():i="Peer.ServiceNotifications";break;default:if(e.pFlags.bot){i="Bot";break}if(e.pFlags.support){i="SupportStatus";break}switch(null===(t=e.status)||void 0===t?void 0:t._){case"userStatusRecently":i="Lately";break;case"userStatusLastWeek":i="WithinAWeek";break;case"userStatusLastMonth":i="WithinAMonth";break;case"userStatusOffline":{const t=e.status.was_online,n=new Date,a=(n.getTime()/1e3|0)-t;if(a<60)i="Peer.Status.justNow";else if(a<3600)i="Peer.Status.minAgo",s=[a/60|0];else if(a<86400&&n.getDate()===new Date(1e3*t).getDate())i="LastSeen.HoursAgo",s=[a/3600|0];else{i="Peer.Status.LastSeenAt";const{dateEl:e,timeEl:n}=z(t);s=[e,n]}break}case"userStatusOnline":i="Online";break;default:i="ALongTimeAgo"}}return(0,v.ag)(i,s)}class de extends P{constructor(){super(...arguments),this.uploadAvatar=null,this.isGeoChat=!1}init(){this.container.classList.add("new-group-container"),this.setTitle("NewGroup"),this.avatarEdit=new F((e=>{this.uploadAvatar=e}));const e=new Br({}),t=document.createElement("div");t.classList.add("input-wrapper"),this.groupNameInputField=new b.Z({label:"CreateGroup.NameHolder",maxLength:128}),this.groupLocationInputField=new b.Z({label:"ChatLocation",name:"location",canBeEdited:!1}),t.append(this.groupNameInputField.container,this.groupLocationInputField.container),this.listenerSetter.add(this.groupNameInputField.input)("input",(()=>{let e=!!this.groupNameInputField.value.length&&!this.groupNameInputField.input.classList.contains("error");this.isGeoChat&&(e=e&&!!this.userLocationCoords&&!!this.userLocationAddress),this.nextBtn.classList.toggle("is-visible",!!e)})),this.nextBtn=D({icon:"arrow_next"}),(0,n.fc)(this.nextBtn,(()=>{const e=this.groupNameInputField.value;let t;if(this.isGeoChat){if(!this.userLocationAddress||!this.userLocationCoords)return;t=this.managers.appChatsManager.createChannel({title:e,about:"",geo_point:Object.assign({_:"inputGeoPoint"},this.userLocationCoords),address:this.userLocationAddress,megagroup:!0}).then((e=>(this.uploadAvatar&&this.uploadAvatar().then((t=>{this.managers.appChatsManager.editPhoto(e,t)})),this.peerIds.length&&this.managers.appChatsManager.inviteToChannel(e,this.peerIds),e)))}else this.nextBtn.disabled=!0,t=this.managers.appChatsManager.createChat(e,this.peerIds.map((e=>e.toUserId()))).then((e=>(this.uploadAvatar&&this.uploadAvatar().then((t=>{this.managers.appChatsManager.editPhoto(e,t)})),e)));t&&t.then((e=>{Hr.removeTabFromHistory(this),Hr.selectTab(0),_m.setInnerPeer({peerId:e.toPeerId(!0)})}))}),{listenerSetter:this.listenerSetter});const i=new Br({name:"Members",nameArgs:[this.peerIds.length]}),s=this.list=gg.createChatList({new:!0});i.content.append(s),e.content.append(this.avatarEdit.container,t),this.content.append(this.nextBtn),this.scrollable.append(e.container,i.container)}onCloseAfterTimeout(){this.avatarEdit.clear(),this.uploadAvatar=null,this.groupNameInputField.value="",this.groupLocationInputField.container.classList.add("hide"),this.nextBtn.disabled=!1}open(e,t=!1){this.isGeoChat=t,this.peerIds=e;const i=super.open();return i.then((()=>(t?(this.setTitle("NearbyCreateGroup"),this.groupLocationInputField.container.classList.remove("hide"),this.groupLocationInputField.setValueSilently(v.ZP.format("Loading",!0)),this.startLocating()):this.groupLocationInputField.container.classList.add("hide"),Promise.all(this.peerIds.map((e=>{return t=this,i=void 0,n=function*(){const{dom:t}=gg.addDialogNew({peerId:e,container:this.list,rippleEnabled:!1,avatarSize:48});t.lastMessageSpan.append(ce(yield this.managers.appUsersManager.getUser(e)))},new((s=void 0)||(s=Promise))((function(e,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,r)}l((n=n.apply(t,i||[])).next())}));var t,i,s,n})))))),i}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((e=>e.json())).then((e=>{this.userLocationAddress=e.display_name,this.groupLocationInputField.setValueSilently(e.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.")}))}}var he=i(5003),ue=i(6008);class pe{constructor(e,t){this.items=new Map,this.locked=!1,this.observer=new IntersectionObserver((t=>{if(this.locked)return;const i=[];t.forEach((e=>{const t=e.target;if(this.items.get(t)===e.isIntersecting)return;this.items.set(t,e.isIntersecting);const s={target:t,visible:e.isIntersecting,entry:e};i.push(s)})),i.forEach((t=>{e(t)}))}),t)}getVisible(){const e=[];return this.items.forEach(((t,i)=>{t&&e.push(i)})),e}clearVisible(){const e=this.getVisible();for(const t of e)this.items.set(t,!1)}isVisible(e){return this.items.get(e)}disconnect(){this.observer.disconnect(),this.items.clear()}refresh(){this.observer.disconnect();const e=[...this.items.keys()];for(const t of e)this.observer.observe(t)}refreshVisible(){const e=this.getVisible();for(const t of e)this.observer.unobserve(t);for(const t of e)this.observer.observe(t)}observe(e){this.items.set(e,!1),this.observer.observe(e)}unobserve(e){this.observer.unobserve(e),this.items.delete(e)}unlock(){this.locked=!1}unlockAndRefresh(){this.unlock(),this.refresh()}lock(){this.locked=!0}}function me(e,t){const i=[];let s=-1;for(;-1!==(s=e.findIndex(t));)i.push(e.splice(s,1)[0]);return i}var ge=i(4064),ve=i(4421);class fe extends ve.Z{constructor(e){super(e),this.queue=[],this.inProcess=new Set}lock(){super.lock(),this.intersector.lock()}unlock(){super.unlock(),this.intersector.unlock()}unlockAndRefresh(){super.unlock(),this.intersector.unlockAndRefresh()}clear(){super.clear(),this.intersector.disconnect()}refresh(){this.intersector.refresh()}loadItem(e){return e.load(e.div)}addElement(e,t){if(this.queue.find((e=>e.div===t.div&&e.load===t.load)))return!1;for(const e of this.inProcess)if(e.div===t.div&&e.load===t.load)return!1;return this.queue[e](t),!0}setProcessQueueTimeout(){this.intersectorTimeout||(this.intersectorTimeout=window.setTimeout((()=>{this.intersectorTimeout=0,this.processQueue()}),0))}push(e){super.push(e)}unshift(e){super.unshift(e)}unobserve(e){me(this.queue,(t=>t.div===e)),this.intersector.unobserve(e)}}class ye extends fe{constructor(e){super(e),this.onVisibilityChange=({target:e,visible:t})=>{t&&(me(this.queue,(t=>t.div===e)).forEach((e=>{e.wasSeen=!0,this.queue.unshift(e)})),this.setProcessQueueTimeout())},this.intersector=new pe(this.onVisibilityChange)}getItem(){return(0,ge.Z)(this.queue,(e=>e.wasSeen))}processItem(e){const t=Object.create(null,{processItem:{get:()=>super.processItem}});return i=this,s=void 0,a=function*(){yield t.processItem.call(this,e),this.intersector.unobserve(e.div)},new((n=void 0)||(n=Promise))((function(e,t){function o(e){try{l(a.next(e))}catch(e){t(e)}}function r(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(o,r)}l((a=a.apply(i,s||[])).next())}));var i,s,n,a}addElement(e,t){return!!super.addElement(e,t)&&(this.intersector.observe(t.div),t.hasOwnProperty("wasSeen")||(t.wasSeen=!1),!0)}}var be=i(279),we=i(1405),Se=i(7530),Ce=i(9897);function Le(e,t=0,i=0,s=!1,n=!1){window.devicePixelRatio>1&&(t*=2,i*=2);let a={_:"photoSizeEmpty",type:""},o=e.sizes||e.thumbs;if(n&&o&&"photo"!==e._&&(o=o.concat({_:"photoSize",w:e.w,h:e.h,size:e.size,type:void 0})),null==o?void 0:o.length){for(let e=0,s=o.length;e<s;++e){const s=o[e];if(!("w"in s)&&!("h"in s))continue;a=s;const n=(0,Ce.Z)(s.w,s.h,t,i);if(n.width>=t||n.height>=i)break}s&&"photoSizeEmpty"===a._&&"photoStrippedSize"===o[0]._&&(a=o[0])}return a}function Ie(e,t){return e.reduce(((e,t)=>e+t),t)}var Me=i(3228);class Ee{constructor(e,t,i,s,n=t){this.sizes=e,this.maxWidth=t,this.minWidth=i,this.spacing=s,this.maxHeight=n,this.count=e.length,this.ratios=Ee.countRatios(e),this.proportions=Ee.countProportions(this.ratios),this.averageRatio=Ie(this.ratios,1)/this.count,this.maxSizeRatio=t/this.maxHeight}layout(){return this.count?this.count>=5||this.ratios.find((e=>e>2))?new Pe(this.ratios,this.averageRatio,this.maxWidth,this.minWidth,this.spacing).layout():2===this.count?this.layoutTwo():3===this.count?this.layoutThree():this.layoutFour():[]}layoutTwo(){return"ww"===this.proportions&&this.averageRatio>1.4*this.maxSizeRatio&&this.ratios[1]-this.ratios[0]<.2?this.layoutTwoTopBottom():"ww"===this.proportions||"qq"===this.proportions?this.layoutTwoLeftRightEqual():this.layoutTwoLeftRight()}layoutThree(){return"n"===this.proportions[0]?this.layoutThreeLeftAndOther():this.layoutThreeTopAndOther()}layoutFour(){return"w"===this.proportions[0]?this.layoutFourTopAndOther():this.layoutFourLeftAndOther()}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:11},{geometry:{x:0,y:t+this.spacing,width:e,height:t},sides:14}]}layoutTwoLeftRightEqual(){const e=(this.maxWidth-this.spacing)/2,t=Math.round(Math.min(e/this.ratios[0],Math.min(e/this.ratios[1],1*this.maxHeight)));return[{geometry:{x:0,y:0,width:e,height:t},sides:13},{geometry:{x:e+this.spacing,y:0,width:e,height:t},sides:7}]}layoutTwoLeftRight(){const e=Math.round(1.5*this.minWidth),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),i=this.maxWidth-t-this.spacing,s=Math.min(this.maxHeight,Math.round(Math.min(i/this.ratios[0],t/this.ratios[1])));return[{geometry:{x:0,y:0,width:i,height:s},sides:13},{geometry:{x:i+this.spacing,y:0,width:t,height:s},sides:7}]}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]))),i=e-t-this.spacing,s=Math.max(this.minWidth,Math.round(Math.min((this.maxWidth-this.spacing)/2,Math.min(t*this.ratios[2],i*this.ratios[1])))),n=Math.min(Math.round(e*this.ratios[0]),this.maxWidth-this.spacing-s);return[{geometry:{x:0,y:0,width:n,height:e},sides:13},{geometry:{x:n+this.spacing,y:0,width:s,height:i},sides:3},{geometry:{x:n+this.spacing,y:i+this.spacing,width:s,height:t},sides:6}]}layoutThreeTopAndOther(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],.66*(this.maxHeight-this.spacing))),i=(this.maxWidth-this.spacing)/2,s=Math.min(this.maxHeight-t-this.spacing,Math.round(Math.min(i/this.ratios[1],i/this.ratios[2]))),n=e-i-this.spacing;return[{geometry:{x:0,y:0,width:e,height:t},sides:11},{geometry:{x:0,y:t+this.spacing,width:i,height:s},sides:12},{geometry:{x:i+this.spacing,y:t+this.spacing,width:n,height:s},sides:6}]}layoutFourTopAndOther(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],.66*(this.maxHeight-this.spacing))),i=Math.round((this.maxWidth-2*this.spacing)/(this.ratios[1]+this.ratios[2]+this.ratios[3])),s=Math.max(this.minWidth,Math.round(Math.min(.4*(this.maxWidth-2*this.spacing),i*this.ratios[1]))),n=Math.round(Math.max(Math.max(1*this.minWidth,.33*(this.maxWidth-2*this.spacing)),i*this.ratios[3])),a=e-s-n-2*this.spacing,o=Math.min(this.maxHeight-t-this.spacing,i);return[{geometry:{x:0,y:0,width:e,height:t},sides:11},{geometry:{x:0,y:t+this.spacing,width:s,height:o},sides:12},{geometry:{x:s+this.spacing,y:t+this.spacing,width:a,height:o},sides:4},{geometry:{x:s+this.spacing+a+this.spacing,y:t+this.spacing,width:n,height:o},sides:6}]}layoutFourLeftAndOther(){const e=this.maxHeight,t=Math.round(Math.min(e*this.ratios[0],.6*(this.maxWidth-this.spacing))),i=Math.round((this.maxHeight-2*this.spacing)/(1/this.ratios[1]+1/this.ratios[2]+1/this.ratios[3])),s=Math.round(i/this.ratios[1]),n=Math.round(i/this.ratios[2]),a=e-s-n-2*this.spacing,o=Math.max(this.minWidth,Math.min(this.maxWidth-t-this.spacing,i));return[{geometry:{x:0,y:0,width:t,height:e},sides:13},{geometry:{x:t+this.spacing,y:0,width:o,height:s},sides:3},{geometry:{x:t+this.spacing,y:s+this.spacing,width:o,height:n},sides:2},{geometry:{x:t+this.spacing,y:s+n+2*this.spacing,width:o,height:a},sides:6}]}static countRatios(e){return e.map((e=>e.w/e.h))}static countProportions(e){return e.map((e=>e>1.2?"w":e<.8?"n":"q")).join("")}}class Pe{constructor(e,t,i,s,n,a=4*i/3){this.averageRatio=t,this.maxWidth=i,this.minWidth=s,this.spacing=n,this.maxHeight=a,this.ratios=Pe.cropRatios(e,t),this.count=e.length}static cropRatios(e,t){return e.map((e=>t>1.1?(0,Me.Z)(e,1,2.75):(0,Me.Z)(e,.6667,1)))}layout(){const e=new Array(this.count),t=[],i=(e,t)=>{const i=Ie(this.ratios.slice(e,e+t),0);return(this.maxWidth-(t-1)*this.spacing)/i},s=e=>{const s=[];let n=0;for(const t of e)s.push(i(n,t)),n+=t;t.push({lineCounts:e,heights:s})};for(let e=1;e!==this.count;++e){const t=this.count-e;e>3||t>3||s([e,t])}for(let e=1;e!==this.count-1;++e)for(let t=1;t!==this.count-e;++t){const i=this.count-e-t;e>3||t>(this.averageRatio<.85?4:3)||i>3||s([e,t,i])}for(let e=1;e!==this.count-1;++e)for(let t=1;t!==this.count-e;++t)for(let i=1;i!==this.count-e-t;++i){const n=this.count-e-t-i;e>3||t>3||i>3||n>3||s([e,t,i,n])}let n=null,a=0;for(const e of t){const{heights:t,lineCounts:i}=e,s=i.length,o=Ie(t,0)+this.spacing*(s-1),r=Math.min(...t),l=(Math.max(...t),r<this.minWidth?1.5:1),c=(()=>{for(let e=1;e!==s;++e)if(i[e-1]>i[e])return 1.5;return 1})(),d=Math.abs(o-this.maxHeight)*l*c;(!n||d<a)&&(n=e,a=d)}const o=n.lineCounts,r=n.heights,l=o.length;let c=0,d=0;for(let t=0;t!==l;++t){const i=o[t],s=r[t],n=Math.round(s);let a=0;for(let o=0;o!==i;++o){const r=0|(0===t?1:0)|(t===l-1?4:0)|(0===o?8:0)|(o===i-1?2:0),h=this.ratios[c],u=o===i-1?this.maxWidth-a:Math.round(h*s);e[c]={geometry:{x:a,y:d,width:u,height:n},sides:r},a+=u+this.spacing,++c}d+=n+this.spacing}return e}}function ke(e){const t=new Ee(e.items,e.maxWidth,e.minWidth,e.spacing,e.maxHeight).layout(),i=t.find((e=>2&e.sides)),s=i.geometry.width+i.geometry.x,n=t.find((e=>4&e.sides)),a=n.geometry.height+n.geometry.y,o=e.container;o.style.width=s+"px",o.style.height=a+"px";const r=o.children;t.forEach((({geometry:t,sides:i},n)=>{let l;if(l=r[n],l||(l=document.createElement("div"),o.append(l)),l.classList.add("album-item","grouped-item"),l.style.width=t.width/s*100+"%",l.style.height=t.height/a*100+"%",l.style.top=t.y/a*100+"%",l.style.left=t.x/s*100+"%",8&i&&1&i&&(l.style.borderTopLeftRadius="inherit"),8&i&&4&i&&(l.style.borderBottomLeftRadius="inherit"),2&i&&1&i&&(l.style.borderTopRightRadius="inherit"),2&i&&4&i&&(l.style.borderBottomRightRadius="inherit"),e.forMedia){const e=document.createElement("div");e.classList.add("album-item-media"),l.append(e)}}))}var Te=i(9674);const xe={},_e=(e,t)=>{e instanceof HTMLImageElement||e instanceof HTMLVideoElement?e.src=t:e instanceof SVGImageElement?e.setAttributeNS(null,"href",t):e.style.backgroundImage="url("+t+")"};function Ae(e,t,i,s=!0){if(!t)return console.error("renderImageFromUrl: no url?",e,t),void(i&&i());if(xe[t]&&s||e instanceof HTMLVideoElement)e&&_e(e,t),i&&i();else{const s=e instanceof HTMLImageElement,n=s?e:new Image;n.src=t,n.addEventListener("load",(()=>{!s&&e&&_e(e,t),xe[t]=!0,i&&i()}),{once:!0}),i&&n.addEventListener("error",(e=>{console.error("Render image from url failed:",e,t,n),i()}))}}function Ze(e,t,i){return new Promise((s=>{Ae(e,t,s,i)}))}function Fe(e,t,i,s,n=e,a){return s&&t.classList.add("fade-in"),new Promise((o=>{Ae(t,i,(()=>{Te.Z.mutateElement(e,(()=>{n.append(t),o(),s?t.addEventListener("animationend",(()=>{Te.Z.mutate((()=>{t.classList.remove("fade-in"),null==a||a.remove()}))}),{once:!0}):null==a||a.remove()}))}))}))}const De=(e,t,i,n,a,o,r)=>{const{timeout:l,raf:c}=e.dataset;if(void 0!==l&&clearTimeout(+l),void 0!==c&&(window.cancelAnimationFrame(+c),o||delete e.dataset.raf),o&&s.Z.settings.animationsEnabled&&n)return void(e.dataset.raf=""+window.requestAnimationFrame((()=>{delete e.dataset.raf,De(e,t,i,n,a,o-1,r)})));i&&t&&e.classList.add(t);const d=()=>{delete e.dataset.timeout,!i&&t&&e.classList.remove("backwards",t),e.classList.remove("animating"),null==a||a()};if(null==r||r(),!s.Z.settings.animationsEnabled||!n)return e.classList.remove("animating","backwards"),void d();e.classList.add("animating"),e.classList.toggle("backwards",!i),e.dataset.timeout=""+setTimeout(d,n)},Re=De;var Be=i(3035),Ne=i(8487);class Ue{constructor(e){this.tempId=0,this.detached=!0,this.promise=null,this.isUpload=!1,this.cancelable=!0,this.streamable=!1,this.tryAgainOnFail=!0,this.attachMethod="append",this.onClick=e=>{e&&(0,a.Z)(e),this.preloader.classList.contains("manual")?this.loadFunc&&this.loadFunc(e):this.promise&&this.promise.cancel&&this.promise.cancel()},e&&(0,x.Z)(this,e),this.isUpload&&(this.tryAgainOnFail=!1)}constructContainer(e={}){this.preloader||(this.preloader=document.createElement("div"),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.preloader.innerHTML=`\n <div class="you-spin-me-round">\n <svg xmlns="http://www.w3.org/2000/svg" class="preloader-circular" viewBox="${this.streamable?"25 25 50 50":"27 27 54 54"}">\n <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"/>\n </svg>\n </div>`,this.streamable?this.totalLength=118.61124420166016:this.totalLength=149.82473754882812,this.cancelable?(this.preloader.innerHTML+='\n <svg xmlns="http://www.w3.org/2000/svg" class="preloader-close" viewBox="0 0 24 24">\n <g fill="none" fill-rule="evenodd">\n <polygon points="0 0 24 0 24 24 0 24"/>\n <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"/>\n </g>\n </svg>\n <svg xmlns="http://www.w3.org/2000/svg" class="preloader-download" viewBox="0 0 24 24">\n <g fill="none" fill-rule="evenodd">\n <polygon points="0 0 24 0 24 24 0 24"/>\n <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"/>\n </g>\n </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&&(0,n.fc)(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,i=Date.now(),s=s=>{if(e.notify=e.notifyAll=null,t!==this.tempId)return;const n=Date.now()-i;if(!s&&this.cancelable){this.setProgress(100);const e=150;n<e?this.detach():setTimeout((()=>{t===this.tempId&&this.detach()}),e)}else this.tryAgainOnFail?(this.attach(this.preloader.parentElement),(0,Be.T2)((()=>{this.setManual()}))):this.detach();this.promise=e=null};e.then((()=>s(null))).catch((e=>s(e))),e.addNotifyListener&&e.addNotifyListener((e=>{if(t!==this.tempId)return;const i=e.done/e.total*100;this.setProgress(i)}))}attach(e,t=!1,i){this.construct&&this.construct(),this.preloader.parentElement&&this.preloader.classList.remove("manual"),this.detached=!1,i&&this.attachPromise(i);let s=0;(this.detached||this.preloader.parentElement!==e)&&(s=(0,Ne.Z)(this.preloader)?1:2,this.preloader.parentElement!==e&&e[this.attachMethod](this.preloader)),Re(this.preloader,"is-visible",!0,200,void 0,s),this.cancelable&&t&&this.setProgress(0)}detach(){var e;this.detached||(this.detached=!0,(null===(e=this.preloader)||void 0===e?void 0:e.parentElement)&&Re(this.preloader,"is-visible",!1,200,(()=>{this.preloader.remove()}),1))}setProgress(e){if(this.totalLength||(0,Ne.Z)(this.circle))if(0!==e)try{this.totalLength||(this.totalLength=this.circle.getTotalLength()),this.circle.style.strokeDasharray=Math.max(5,e/100*this.totalLength)+", "+this.totalLength}catch(e){}else this.circle.style.strokeDasharray=""}}var Oe=i(3725),He=i(8594);const ze=[];let Ge=!1;function Ve(e,t="push"){if(!e.items.length)return Promise.resolve([]);const i=e.promise=(0,Oe.Z)();return ze[t](e),Ke(),i}function Ke(){Ge||function(e){if(!e.items.length)return e.promise.resolve([]),Promise.resolve([]);const t=e.items.slice(),i=[];return new Promise(((s,n)=>{const a=()=>{return o=this,r=void 0,c=function*(){const o=performance.now();do{yield(0,He.e9)();const s=e.process.apply(e.context,t.shift());let a;if(s instanceof Promise)try{a=yield s}catch(e){return void n(e)}else a=s;i.push(a)}while(t.length>0&&performance.now()-o<6);t.length>0?(0,Be.T2)(a):s(i)},new((l=void 0)||(l=Promise))((function(e,t){function i(e){try{n(c.next(e))}catch(e){t(e)}}function s(e){try{n(c.throw(e))}catch(e){t(e)}}function n(t){var n;t.done?e(t.value):(n=t.value,n instanceof l?n:new l((function(e){e(n)}))).then(i,s)}n((c=c.apply(o,r||[])).next())}));var o,r,l,c};(0,Be.T2)(a)})).then(e.promise.resolve,e.promise.reject)}(ze.shift()).finally((()=>{Ge=!1,ze.length&&Ke()}))}var We=i(6663);let $e,je;function qe(e,t,i,s=document.createElement("canvas")){s.width=e.width,s.height=e.height;const n=s.getContext("2d",{alpha:!1});return We.Z?(n.filter=`blur(${t}px)`,n.drawImage(e,2*-t,2*-t,s.width+4*t,s.height+4*t)):(n.drawImage(e,0,0),je(n,0,0,s.width,s.height,t,i)),s}$e=We.Z?Promise.resolve():i.e(77).then(i.bind(i,7077)).then((e=>{je=e.default}));const Qe=new Map;function Ye(e,t=2,i=2){if(!e)throw"no dataUri for blur: "+e;Qe.size>150&&Qe.clear();const s=document.createElement("canvas");s.className="canvas-thumbnail";let n=Qe.get(e);if(n)s.width=n.canvas.width,s.height=n.canvas.height,n.promise.then((()=>{s.getContext("2d").drawImage(n.canvas,0,0,s.width,s.height)}));else{const a=new Promise((n=>{$e.then((()=>{const a=new Image;a.onload=()=>{Ve({items:[[a,t,i,s]],context:null,process:qe},"unshift").then((()=>{n()}))},a.src=e}))}));Qe.set(e,n={canvas:s,promise:a})}return Object.assign(Object.assign({},n),{canvas:s})}var Je=i(4762),Xe=i(3306);const et=(0,Xe.Z)("ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00"),tt=(0,Xe.Z)("ffd9");function it(e,t=!1){let i,s;return t?i=e instanceof Uint8Array?e:new Uint8Array(e):(i=new Uint8Array(et.concat(Array.from(e.slice(3)),tt)),i[164]=e[1],i[166]=e[2]),s=t?Je.IS_SAFARI?"image/png":"image/webp":"image/jpeg",function(e,t="image/jpeg"){return`data:${t};base64,${btoa(String.fromCharCode(...e))}`}(i,s)}function st(e,t,i=!1){return it(t.bytes,i)}function nt(e,t,i){const s=st(0,t,!1);let n,a;if(i){const e=Ye(s);n=e.canvas,a=e.promise}else n=new Image,a=Ze(n,s);return n.classList.add("thumbnail"),{image:n,loadPromise:a}}function at(e,t,i,s=!1){if(!t.downloaded||["video","gif"].includes(e.type)||s){if("document"===e._&&t.downloaded&&!s)return null;const n=e.sizes||e.thumbs,a=(null==n?void 0:n.length)?n.find((e=>"photoStrippedSize"===e._)):null;if(a&&"bytes"in a)return nt(0,a,i)}return null}var ot=i(9405),rt=i(3114);function lt(e,t,i,s,n=!0,a,o,r){const l=(0,rt.Z)(e);let c;r||(r=Le(e,i,s,void 0,o));const d="document"===e._;c=d||l?(0,ot.C)(e.w||r.w||512,e.h||r.h||512):(0,ot.C)(r.w||100,r.h||100);let h=(0,ot.C)(i,s);h=c=c.aspect(h,n);let u=!0;return(!d||["video","gif"].includes(e.type)||l)&&(h.width<200&&h.height<200&&(h=c=c.aspectCovered((0,ot.C)(200,200))),a&&(a.message||a.reply_to_mid||a.media.webpage||a.replies&&a.replies.pFlags.comments&&a.replies.channel_id.toChatId()!==le.IA)&&h.width<320&&(h=(0,ot.C)(320,h.height),u=!1),u&&h.width<120&&a&&(h=(0,ot.C)(120,h.height),u=!1)),t.style.width=h.width+"px",t.style.height=h.height+"px",{photoSize:r,size:c,isFit:u}}var ct=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};function dt({photo:e,message:t,container:i,boxWidth:n,boxHeight:a,withTail:o,isOut:r,lazyLoadQueue:l,middleware:c,size:h,withoutPreloader:p,loadPromises:m,autoDownloadSize:g,noBlur:v,noThumb:f,noFadeIn:y,blurAfter:b,managers:w=s.Z.managers}){return ct(this,void 0,void 0,(function*(){const S=(0,rt.Z)(e);if(!e.sizes&&!e.thumbs&&!S)return n&&a&&!h&&"document"===e._&&lt(e,i,n,a,void 0,t),{loadPromises:{thumb:Promise.resolve(),full:Promise.resolve()},images:{thumb:null,full:null},preloader:null,aspecter:null};let C=0===g;h||(void 0===n&&(n=d.Z.active.regular.width),void 0===a&&(a=d.Z.active.regular.height)),i.classList.add("media-container");let L,I,M=i,E=!0,P=Promise.resolve();const k="document"===e._&&"image/gif"===e.mime_type&&!h,T=new Image;if(n&&a&&!h){const s=lt(e,i,n,a,void 0,t,void 0,k?{_:"photoSize",w:e.w,h:e.h,size:e.size,type:"full"}:void 0);if(h=s.photoSize,E=s.isFit,I=yield w.thumbsStorage.getCacheContext(e,h.type),!E&&!S){M=document.createElement("div"),M.classList.add("media-container-aspecter"),M.style.width=s.size.width+"px",M.style.height=s.size.height+"px";const n=at(e,I,!v,!0);if(n){P=n.loadPromise;const e=n.image;e.classList.add("media-photo"),i.append(e)}else(yield dt({container:i,message:t,photo:e,boxWidth:0,boxHeight:0,size:h,lazyLoadQueue:l,isOut:r,loadPromises:m,middleware:c,withoutPreloader:p,withTail:o,autoDownloadSize:g,noBlur:v,noThumb:!0,blurAfter:!0,managers:w})).images.full.classList.add("media-photo","thumbnail");i.classList.add("media-container-fitted"),i.append(M)}}else h||(h=Le(e,n,a,!0)),I=yield w.thumbsStorage.getCacheContext(e,null==h?void 0:h.type);if(!f&&!S){const t=at(e,I,!v);t&&(P=Promise.all([P,t.loadPromise]),L=t.image,L.classList.add("media-photo"),M.append(L))}T.classList.add("media-photo");const x=(L||!I.downloaded)&&s.Z.settings.animationsEnabled&&!y;let _;const A=null==t?void 0:t.uploadingFileName;p||(I.downloaded&&!A||(_=new Ue({attachMethod:"prepend",isUpload:!!A})),A&&(_.attachPromise(u.Z.getUpload(A)),_.attach(i),C=void 0));const Z=e=>Fe(i,T,e,x,M,L),F=e=>ct(this,void 0,void 0,(function*(){if(!c||c()){if(b){const t=Ye(e,12);return t.promise.then((()=>Z(t.canvas.toDataURL())))}return Z(e)}}));let D;const R=h.w>=150&&h.h>=150||C,B=()=>ct(this,void 0,void 0,(function*(){C&&!p&&_&&(_.construct(),_.setManual());const t=(()=>{const t=k&&!h;return u.Z.downloadMediaURL({media:e,thumb:h,queueId:null==l?void 0:l.queueId,onlyCache:t?void 0:C})})(),s=yield w.thumbsStorage.getCacheContext(e,null==h?void 0:h.type);_&&!s.downloaded&&!p&&R&&_.attach(i,!1,t),C=void 0;const n=t.then(F);return n.catch((()=>{})),{download:t,render:n}}));return _&&_.setDownloadFunction(B),I.downloaded?P=D=(yield B()).render:l?l.push({div:i,load:()=>B().then((({download:e})=>e))}):D=(yield B()).render,m&&P&&m.push(P),yield P,{loadPromises:{thumb:P,full:D||Promise.resolve()},images:{thumb:L,full:T},preloader:_,aspecter:M}}))}var ht=i(5296);function ut(e={}){const t=document.createElement("video");return e.pip||(t.disablePictureInPicture=!0),t.setAttribute("playsinline","true"),t}var pt=i(925),mt=i(6724);function gt(e,t=!1){const i=parseInt(e+"",10),s=Math.floor(i/3600);let n=Math.floor((i-3600*s)/60),a=i-3600*s-60*n;return s&&(t=!0),n<10&&(n=t?"0"+n:n),a<10&&(a="0"+a),(s?s+":":"")+n+":"+a}var vt=i(3013),ft=i(319);const yt='Roboto, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif';let bt;function wt(e,t){if(!bt){const e=document.createElement("canvas");bt=e.getContext("2d",{alpha:!1}),bt.font=t}return bt.measureText(e).width}const St=new Map,Ct=new Set;let Lt=!1;function It(){Lt||(Lt=!0,(0,Be.T2)((()=>{Lt=!1,Ct.forEach(Et),Ct.clear()})))}function Mt(e){const t=e.dataset.sizeType;return t?d.Z.active[t].width:e.getBoundingClientRect().width}function Et(e){let t=St.get(e);const i=!t;let{text:s,textLength:n,from:a,multiplier:o,font:r,textWidth:l,elementWidth:c}=t||{};i&&(s=e.textContent,n=s.length,a=50,o=a>0&&a/100,r=`${e.dataset.fontWeight||"400"} 16px ${yt}`,l=wt(s,r),c=Mt(e),t={text:s,textLength:n,from:a,multiplier:o,font:r,textWidth:l,elementWidth:c},St.set(e,t));const d=Mt(e),h=i||c!==d;if(!i&&h&&(t.elementWidth=c=d),h)if(l>c){e.setAttribute("title",s);let i=s,n=c;for(;i.length>3;){const t=i.length,s=o&&(0,Me.Z)(o*t<<0,1,t-2)||Math.max(t+a-1,1),l=i.substr(0,s).replace(/\s*$/,""),d=i.substr(s+1).replace(/^\s*/,"");if(i=l+d,n=wt(i+"…",r),n<c){e.textContent=l+"…"+d;break}}t.elementWidth=Mt(e)}else e.removeAttribute("title")}window.addEventListener("resize",(()=>{for(const[e]of St)Ct.add(e);It()}),{capture:!0,passive:!0});class Pt extends HTMLElement{connectedCallback(){St.set(this,null),this.dataset.sizeType?Et(this):(Ct.add(this),It())}disconnectedCallback(){St.delete(this),Ct.delete(this)}}function kt(e){return function(e,t){let i,s=!1;return(...n)=>{i=n,s||(s=!0,e((()=>{s=!1,t(...i)})))}}(Be.T2,e)}function Tt(e,t="auto"){if(0===e)return(0,v.ag)("FileSize.B",[0]);const i="auto"===t,s=Math.floor(Math.log(e)/Math.log(1024)),n="auto"===t?Math.max(0,s-1):t,a=Math.max(0,n),o=(e/Math.pow(1024,s)).toFixed(a);return(0,v.ag)(["FileSize.B","FileSize.KB","FileSize.MB","FileSize.GB"][s],[i?o:parseFloat(o)])}function xt(e,t,i,s){const n=e=>{i({x:e.pageX,y:e.pageY,event:e})},a=t=>{document.removeEventListener("mousemove",n),e.addEventListener("mousedown",o,{once:!0}),s&&s({x:t.pageX,y:t.pageY,event:t})},o=i=>{0===i.button?(t({x:i.pageX,y:i.pageY,event:i}),n(i),document.addEventListener("mousemove",n),document.addEventListener("mouseup",a,{once:!0})):e.addEventListener("mousedown",o,{once:!0})};e.addEventListener("mousedown",o,{once:!0});const r=e=>{e.preventDefault(),i({x:e.touches[0].clientX,y:e.touches[0].clientY,isTouch:!0,event:e})},l=t=>{document.removeEventListener("touchmove",r),e.addEventListener("touchstart",c,{passive:!1,once:!0}),s&&s({x:t.touches[0].clientX,y:t.touches[0].clientY,isTouch:!0,event:t})},c=e=>{t({x:e.touches[0].clientX,y:e.touches[0].clientY,isTouch:!0,event:e}),r(e),document.addEventListener("touchmove",r,{passive:!1}),document.addEventListener("touchend",l,{passive:!1,once:!0})};return e.addEventListener("touchstart",c,{passive:!1,once:!0}),()=>{e.removeEventListener("mousedown",o),document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",a),e.removeEventListener("touchstart",c),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",l)}}customElements.define("middle-ellipsis-element",Pt);class _t{constructor(e,t=0){this.mousedown=!1,this.events={},this.withTransition=!1,this.useTransform=!1,this.vertical=!1,this.onMouseMove=e=>{this.scrub(e)},this.onMouseDown=e=>{var t;this.rect=this.container.getBoundingClientRect(),this.mousedown=!0,this.scrub(e),this.container.classList.add("is-focused"),(null===(t=this.events)||void 0===t?void 0:t.onMouseDown)&&this.events.onMouseDown(e)},this.onMouseUp=e=>{var t;this.mousedown=!1,this.container.classList.remove("is-focused"),(null===(t=this.events)||void 0===t?void 0:t.onMouseUp)&&this.events.onMouseUp(e)},this.onInput=()=>{var e;const t=+this.seek.value;this.setFilled(t),(null===(e=this.events)||void 0===e?void 0:e.onScrub)&&this.events.onScrub(t)},(0,x.Z)(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 i=this.seek=document.createElement("input");i.classList.add("progress-line__seek"),i.type="range",i.step=""+this.step,i.min=""+this.min,i.max=""+this.max,i.value=""+t,t&&this.setProgress(t);const s=""+this.step,n=s.indexOf(".");this.decimals=-1===n?0:s.length-n-1,this.container.append(this.filled,i)}get value(){return+this.seek.value}setHandlers(e){this.events=e}setListeners(){this.seek.addEventListener("input",this.onInput),this._removeListeners=xt(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=(0,Me.Z)(t,0,1),this.useTransform?this.filled.style.transform=`scaleX(${t})`:this.filled.style.width=100*t+"%"}scrub(e){var t;const i=this.vertical?this.rect.height:this.rect.width,s=(0,Me.Z)(this.vertical?-(e.y-this.rect.bottom):e.x-this.rect.left,0,i);let n=this.min+s/i*(this.max-this.min);return n-this.min<(this.max-this.min)/2&&(n-=this.step/10),n=+n.toFixed(this.decimals),n=(0,Me.Z)(n,this.min,this.max),this.setProgress(n),(null===(t=this.events)||void 0===t?void 0:t.onScrub)&&this.events.onScrub(n),n}removeListeners(){this._removeListeners&&(this._removeListeners(),this._removeListeners=null),this.seek.removeEventListener("input",this.onInput),this.events={}}}class At extends _t{constructor(e,t,i,s){super({step:1e3/60/1e3,min:0,max:1,withTransition:i,useTransform:s},0),this.progressRAF=0,this.onLoadedData=()=>{this.max=this.media.duration,this.seek.setAttribute("max",""+this.max)},this.onEnded=()=>{this.setProgress()},this.onPlay=()=>{const e=()=>{this.setProgress(),this.progressRAF=this.media.paused?0:window.requestAnimationFrame(e)};this.progressRAF&&window.cancelAnimationFrame(this.progressRAF),this.streamable&&this.setLoadProgress(),this.progressRAF=window.requestAnimationFrame(e)},this.onTimeUpdate=()=>{this.media.paused&&(this.setProgress(),this.streamable&&this.setLoadProgress())},this.onProgress=e=>{this.setLoadProgress()},e&&this.setMedia(e,t)}setMedia(e,t=!1){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(),this.setListeners(),this.setHandlers({onMouseDown:()=>{i=!this.media.paused,i&&this.media.pause()},onMouseUp:e=>{i&&this.media.play()}})}scrub(e){const t=super.scrub(e);return this.media.currentTime=t,t}setLoadProgress(){if(vt.Z.isSafariBuffering(this.media))return;const e=this.media.buffered,t=e.length,i=this.media.currentTime;let s=0,n=0;for(let a=0;a<t;++a){const t=e.start(a);i>=t&&t>=s&&(s=t,n=e.end(a))}const a=this.media.duration?n/this.media.duration:0;this.filledLoad.style.width=100*a+"%"}setSeekMax(){this.max=this.media.duration||0,this.max>0?this.onLoadedData():this.media.addEventListener("loadeddata",this.onLoadedData)}setProgress(){if(vt.Z.isSafariBuffering(this.media))return;const e=this.media.currentTime;super.setProgress(e)}setListeners(){super.setListeners(),this.media.addEventListener("ended",this.onEnded),this.media.addEventListener("play",this.onPlay),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("timeupdate",this.onTimeUpdate),this.streamable&&this.media.removeEventListener("progress",this.onProgress)),this.progressRAF&&(window.cancelAnimationFrame(this.progressRAF),this.progressRAF=0)}}var Zt=i(8115);function Ft(e){var t;return e.fromId?{peerId:e.fromId}:{fromName:null===(t=e.fwd_from)||void 0===t?void 0:t.from_name}}var Dt=i(8456),Rt=i(493);function Bt(e){const t=document.createElement("span");return t.classList.add("badge-fake"),(0,v.$d)(t,e?"ScamMessage":"FakeMessage"),t}function Nt(e){return t=this,i=void 0,a=function*(){const t=[],i=yield s.Z.managers.appPeersManager.getPeer(e);return i.pFlags.verified&&t.push(function(){const e=document.createElement("span");e.classList.add("verified-icon","tgico");const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttributeNS(null,"viewBox","0 0 26 26"),t.setAttributeNS(null,"width","26"),t.setAttributeNS(null,"height","26"),t.classList.add("verified-icon-svg");const i=document.createElementNS("http://www.w3.org/2000/svg","use");i.setAttributeNS(null,"href","#verified-icon-background"),i.classList.add("verified-icon-background");const s=document.createElementNS("http://www.w3.org/2000/svg","use");return s.setAttributeNS(null,"href","#verified-icon-check"),s.classList.add("verified-icon-check"),t.append(s,i),e.append(t),e}()),(i.pFlags.fake||i.pFlags.scam)&&t.push(Bt(i.pFlags.scam)),i.pFlags.premium&&t.push(function(){const e=document.createElement("span");return e.classList.add("premium-icon","tgico-star"),e}()),t},new((n=void 0)||(n=Promise))((function(e,s){function o(e){try{l(a.next(e))}catch(e){s(e)}}function r(e){try{l(a.throw(e))}catch(e){s(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(o,r)}l((a=a.apply(t,i||[])).next())}));var t,i,n,a}const Ut=new WeakMap;s.Z.addEventListener("peer_title_edit",(e=>{Array.from(document.querySelectorAll(`.peer-title[data-peer-id="${e}"]`)).forEach((e=>{const t=Ut.get(e);t&&t.update()}))}));class Ot{constructor(e){this.plainText=!1,this.onlyFirstName=!1,this.dialog=!1,this.element=document.createElement("span"),this.element.classList.add("peer-title"),this.element.setAttribute("dir","auto"),e&&this.update(e),Ut.set(this.element,this)}setOptions(e){if(e)for(const t in e){const i=e[t];"object"!=typeof i&&(this.element.dataset[t]=i?""+("boolean"==typeof i?+i:i):"0"),this[t]=i}}update(e){var t,i,n,a,o,r;return n=this,a=void 0,r=function*(){this.setOptions(e);let n,a=this.fromName;if(void 0!==a)return void 0!==this.limitSymbols&&(a=(0,Dt.Z)(a,this.limitSymbols,this.limitSymbols)),void(0,c.Z)(this.element,(0,Zt.Z)(a));if(null!==(t=this.peerId)&&void 0!==t||(this.peerId=le.NM),this.peerId===s.Z.myId&&this.dialog)(0,g.Z)(this.element,(0,v.ag)(this.onlyFirstName?"Saved":"SavedMessages"));else{const e=null!==(i=this.managers)&&void 0!==i?i:s.Z.managers,[t,a]=yield Promise.all([(0,Rt.Z)(this.peerId,this.plainText,this.onlyFirstName,this.limitSymbols,e),this.withIcons&&Nt(this.peerId)]);if(null==a?void 0:a.length){const e=document.createElement("span");e.classList.add("peer-title-inner"),n=!0,(0,c.Z)(e,t);const i=document.createDocumentFragment();i.append(e,...a),(0,c.Z)(this.element,i)}else(0,c.Z)(this.element,t)}this.hasInner!==n&&(this.hasInner=n,this.element.classList.toggle("with-icons",n))},new((o=void 0)||(o=Promise))((function(e,t){function i(e){try{l(r.next(e))}catch(e){t(e)}}function s(e){try{l(r.throw(e))}catch(e){t(e)}}function l(t){var n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o((function(e){e(n)}))).then(i,s)}l((r=r.apply(n,a||[])).next())}))}}function Ht(e){return t=this,i=void 0,a=function*(){const t=document.createElement("span");t.classList.add("sender-title");const i=e.fromId===s.Z.myId&&e.peerId!==s.Z.myId;if(t.append(i?(0,v.ag)("FromYou"):new Ot(Object.assign(Object.assign({},Ft(e)),{dialog:e.peerId===s.Z.myId})).element),(yield s.Z.managers.appPeersManager.isAnyGroup(e.peerId))||i){const i=new Ot({peerId:e.peerId}).element;t.append(" ➝ ",i)}return t},new((n=void 0)||(n=Promise))((function(e,s){function o(e){try{l(a.next(e))}catch(e){s(e)}}function r(e){try{l(a.throw(e))}catch(e){s(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(o,r)}l((a=a.apply(t,i||[])).next())}));var t,i,n,a}function zt(e){const t=document.createElement("span");return t.classList.add("sent-time"),t.append(H(new Date(1e3*e.date))),t}var Gt=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};function Vt(e=!0){const t=new Ue({cancelable:!0,tryAgainOnFail:e});return t.construct(),e||(t.circle.setAttributeNS(null,"r","23"),t.totalLength=143.58203125),t}s.Z.addEventListener("messages_media_read",(({mids:e,peerId:t})=>{e.forEach((e=>{const i=`[data-mid="${e}"][data-peer-id="${t}"]`;Array.from(document.querySelectorAll(`audio-element.is-unread${i}, .media-round.is-unread${i}`)).forEach((e=>{e.classList.remove("is-unread")}))}))}));const Kt=(e,t)=>{let i,s;const n=!e.classList.contains("search-super-item"),a=(0,r.Z)(e,n?"bubbles-inner":"tabs-tab");if(a){const t=':not([data-is-outgoing="1"])',o=`.audio:not(.is-voice)${t}`;let r;if(r=e.matches(o)?[o]:[`.audio.is-voice${t}`,`.media-round${t}`],n){const e=".bubble:not(.webpage) ";r=r.map((t=>e+t))}const l=r.join(", "),c=Array.from(a.querySelectorAll(l)),d=c.indexOf(e),h=c.map((e=>({peerId:e.dataset.peerId.toPeerId(),mid:+e.dataset.mid})));i=h.slice(0,d),s=h.slice(d+1)}return(s.length&&s[0].mid<t||i.length&&i[i.length-1].mid>t)&&([i,s]=[s.reverse(),i.reverse()]),[i,s]};class Wt extends HTMLElement{constructor(){super(...arguments),this.withTime=!1,this.voiceAsMusic=!1,this.showSender=!1,this.listenerSetter=new I.Z}render(){var e,t,i;return Gt(this,void 0,void 0,(function*(){this.classList.add("audio"),this.managers=s.Z.managers,this.dataset.mid=""+this.message.mid,this.dataset.peerId=""+this.message.peerId;const o=(0,Se.Z)(this.message),r="voice"===o.type,l=!this.voiceAsMusic&&r,h=this.message.pFlags.is_outgoing,p=null===(e=this.message)||void 0===e?void 0:e.uploadingFileName,m=gt(0|o.duration);this.innerHTML='\n <div class="audio-toggle audio-ico">\n <div class="audio-play-icon">\n <div class="part one" x="0" y="0" fill="#fff"></div>\n <div class="part two" x="0" y="0" fill="#fff"></div>\n </div>\n </div>';const g=this.firstElementChild,f=document.createElement("div");f.classList.add("audio-download"),"audio"!==o.type&&this.message&&this.message.pFlags.media_unread&&this.classList.add("is-unread"),p&&(this.classList.add("is-outgoing"),this.append(f));const y=yield l?function(e){return Gt(this,void 0,void 0,(function*(){e.classList.add("is-voice");const t=e.message,i=(0,Se.Z)(t);t.pFlags.out&&e.classList.add("is-out");let s=i.attributes.find((e=>"documentAttributeAudio"===e._)).waveform||new Uint8Array([]);s=function(e){e instanceof Uint8Array||(e=new Uint8Array(e));const t=8*e.length/5|0;if(!t)return new Uint8Array([]);let i;try{const s=new DataView(e.buffer);i=new Uint8Array(t);for(let e=0;e<t;e++){const t=5*e/8|0,n=5*e%8,a=s.getUint16(t,!0);i[e]=a>>n&31}}catch(e){i=new Uint8Array([])}return i}(s.slice(0,63));const{svg:o,container:r,availW:l}=function(e,t){const i=d.Z.isMobile?16:23,s=d.Z.isMobile?152:190,n=d.Z.isMobile?190:256,a=(0,Me.Z)(t/60*n,s,n),o=document.createElementNS("http://www.w3.org/2000/svg","svg");o.classList.add("audio-waveform-bars"),o.setAttributeNS(null,"width",""+a),o.setAttributeNS(null,"height",""+i),o.setAttributeNS(null,"viewBox",`0 0 ${a} ${i}`);const r=Math.max(...e),l=e.length?e.length:100,c=Math.min(a/4|0,l);let h=0;const u=i-4;let p="";for(let t=0,s=0,n=0;t<l;++t){const a=e[t]||0;if(n+c>=l){n=n+c-l,n<(c+1)/2&&h<a&&(h=a);const e=Math.max((h*u+(r+1)/2)/(r+1),4);p+=`\n <rect x="${s}" y="${i-e}" width="2" height="${e}" rx="1" ry="1"></rect>\n `,s+=4,h=n<(c+1)/2?0:a}else h<a&&(h=a),n+=c}const m=document.createElement("div");return m.classList.add("audio-waveform"),m.append(o),o.insertAdjacentHTML("beforeend",p),{svg:o,container:m,availW:a}}(s,i.duration),c=r.cloneNode(!0);c.classList.add("audio-waveform-fake"),r.classList.add("audio-waveform-background");const h=document.createElement("div");h.classList.add("audio-waveform-container"),h.append(r,c);const u=document.createElement("div");u.classList.add("audio-time"),e.append(h,u);let p=o;return()=>{let t=e.audio;const i=()=>{c.style.width=t.currentTime/t.duration*100+"%"};(!t.paused||t.currentTime>0&&t.currentTime!==t.duration)&&i();const s=kt(i);return e.addAudioListener("timeupdate",s),e.addAudioListener("ended",s),e.addAudioListener("play",(()=>{(0,ht.cK)((()=>!!t&&(i(),!t.paused)),e)})),e.readyPromise.then((()=>{let e=!1,i=!1;function s(e){let i;if(e instanceof MouseEvent)i=e.offsetX;else{const t=e.target.getBoundingClientRect();i=e.targetTouches[0].pageX-t.left}const s=i/l*t.duration;t.currentTime=s}p.addEventListener("mouseleave",(s=>{e&&(t.play(),e=!1),i=!1})),p.addEventListener("mousemove",(t=>{i=!0,e&&s(t)})),p.addEventListener("mousedown",(i=>{i.preventDefault(),0===i.button&&(t.paused||t.pause(),s(i),e=!0)})),p.addEventListener("mouseup",(s=>{i&&e&&(t.play(),e=!1)})),(0,n.fc)(p,(e=>{(0,a.Z)(e),t.paused||s(e)}))}),ft.Z),()=>{p.remove(),p=null,t=null}}}))}(this):function(e){var t;return Gt(this,void 0,void 0,(function*(){const i=e.withTime,s=e.message,n=(0,Se.Z)(s),a="voice"===n.type||"round"===n.type,o=document.createElement("div");o.classList.add("audio-description");const r=n.attributes.find((e=>"documentAttributeAudio"===e._));if(!a){const t=[];(null==r?void 0:r.performer)&&t.push((0,Zt.Z)(r.performer)),i?t.push(G(s.date)):t.length||t.push(Tt(n.size)),e.showSender&&t.push(yield Ht(s)),o.append(...(0,v.A1)(t," • "))}e.insertAdjacentHTML("beforeend",'\n <div class="audio-details">\n <div class="audio-title"></div>\n <div class="audio-subtitle"><div class="audio-time"></div></div>\n </div>');const l=e.querySelector(".audio-title"),d=new Pt;d.dataset.fontWeight=e.dataset.fontWeight,d.dataset.sizeType=e.dataset.sizeType,a?d.append(yield Ht(s)):(0,c.Z)(d,(0,Zt.Z)(null!==(t=null==r?void 0:r.title)&&void 0!==t?t:n.file_name)),l.append(d),e.showSender&&l.append(zt(s));const h=e.querySelector(".audio-subtitle");return h.append(o),()=>{let t=!1,i=new At(e.audio,n.supportsStreaming);e.addAudioListener("ended",(()=>{e.classList.remove("audio-show-progress"),h.lastChild.replaceWith(o),t=!1}));const s=()=>{t||(e.classList.add("audio-show-progress"),t=!0,i&&h.lastChild.replaceWith(i.container))};return e.addAudioListener("play",s),(!e.audio.paused||e.audio.currentTime>0)&&s(),()=>{i.removeListeners(),i.container.remove(),i=null}}}))}(this),b=this.querySelector(".audio-time");b.innerHTML=m;const w=this.onLoad=e=>{this.onLoad=void 0;const t=this.audio=vt.Z.addMedia(this.message,e),i=this.readyPromise=(0,Oe.Z)();this.audio.readyState>=this.audio.HAVE_CURRENT_DATA?i.resolve():this.addAudioListener("canplay",(()=>i.resolve()),{once:!0}),this.onTypeDisconnect=y();const s=()=>gt(0|t.currentTime)+(l?" / "+m:""),o=()=>{b.innerText=s(),g.classList.toggle("playing",!t.paused)};(!t.paused||t.currentTime>0&&t.currentTime!==t.duration)&&o();const r=(e,i=t.paused)=>{if(e&&(0,a.Z)(e),i){const e=!!this.searchContext;if(vt.Z.setSearchContext(this.searchContext||{peerId:le.NM,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1})){const[t,i]=e?Kt(this,this.message.mid):[];vt.Z.setTargets({peerId:this.message.peerId,mid:this.message.mid},t,i)}t.play().catch((()=>{}))}else t.pause()};return(0,n.fc)(g,(e=>r(e)),{listenerSetter:this.listenerSetter}),this.addAudioListener("ended",(()=>{g.classList.remove("playing"),b.innerText=m})),this.addAudioListener("timeupdate",(()=>{!t.currentTime&&t.paused||vt.Z.isSafariBuffering(t)||(b.innerText=s())})),this.addAudioListener("pause",(()=>{g.classList.remove("playing")})),this.addAudioListener("play",o),r};if(null===(t=o.thumbs)||void 0===t?void 0:t.length){const e=[],t=yield dt({photo:o,message:null,container:g,boxWidth:48,boxHeight:48,loadPromises:this.loadPromises,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue});g.style.width=g.style.height="",t.images.thumb&&e.push(t.images.thumb),t.images.full&&e.push(t.images.full),this.classList.add("audio-with-thumb"),e.forEach((e=>e.classList.add("audio-thumb")))}if(h)p&&(this.preloader=Vt(!1),this.preloader.attachPromise(u.Z.getUpload(p)),this.dataset.isOutgoing="1",this.preloader.attach(f,!1));else{let e=this.preloader;const t="audio"!==o.type;w(t);const s=t=>{if(this.audio.src)return;vt.Z.resolveWaitingForLoadMedia(this.message.peerId,this.message.mid,this.message.pFlags.is_scheduled);const i=()=>{t&&(vt.Z.willBePlayed(this.audio),Je.IS_SAFARI&&!this.audio.autoplay&&(this.audio.autoplay=!0))};if(i(),!e)if(o.supportsStreaming){let e;this.classList.add("corner-download");const t=()=>{const t=Vt(!1),s=(0,Oe.Z)();s.notifyAll({done:75,total:100}),s.catch((()=>{this.audio.pause(),vt.Z.willBePlayed(void 0)})),s.cancel=()=>{s.cancel=ft.Z;const e=new Error;e.type="CANCELED",s.reject(e)},t.attach(f,!1,s),e=this.addAudioListener("pause",(()=>{s.cancel()}),{once:!0}),i()},s=this.addAudioListener("play",t);this.readyPromise.then((()=>{this.listenerSetter.remove(s),this.listenerSetter.remove(e)}))}else{e=Vt(),t||(this.readyPromise=(0,Oe.Z)());const s=()=>{i();const s=u.Z.downloadMediaURL({media:o});return t||s.then((()=>{this.readyPromise.resolve()})),e.attach(f,!1,s),{download:s}};e.setDownloadFunction(s),s()}this.classList.contains("corner-download")?g.append(f):this.append(f),this.classList.add("downloading"),this.readyPromise.then((()=>{this.classList.remove("downloading"),f.classList.add("downloaded"),setTimeout((()=>{f.remove()}),200),vt.Z.willBePlayedMedia===this.audio&&(this.audio.play(),vt.Z.willBePlayed(void 0))}))};(null===(i=this.audio)||void 0===i?void 0:i.src)||(t?s(!1):(0,n.fc)(g,(()=>{s(!0)}),{once:!0,capture:!0,passive:!1,listenerSetter:this.listenerSetter}))}}))}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",Wt);var $t=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};let jt=0;function qt({doc:e,container:t,message:i,boxWidth:o,boxHeight:r,withTail:l,isOut:c,middleware:h,lazyLoadQueue:m,noInfo:g,group:v,onlyPreview:f,withoutPreloader:y,loadPromises:b,noPlayButton:w,size:S,searchContext:C,autoDownload:L,managers:I=s.Z.managers}){var M;return $t(this,void 0,void 0,(function*(){const E=null==L?void 0:L.video;let P=0===E;const k=!(o&&r),T=("video"!==e.type||e.size<=52428800&&!k)&&("gif"===e.type?s.Z.settings.autoPlay.gifs:s.Z.settings.autoPlay.videos);let x,_;if(!g){x=document.createElement("span"),x.classList.add("video-time"),t.append(x);let i=!1;"gif"!==e.type?(x.innerText=gt(e.duration,!1),w||"round"===e.type||(T&&!P?x.classList.add("tgico","can-autoplay"):i=!0)):(x.innerText="GIF",T||w||(i=!0,P=void 0)),i&&(_=document.createElement("span"),_.classList.add("video-play","tgico-largeplay","btn-circle","position-center"),t.append(_))}const A={};if("image/gif"===e.mime_type){const s=yield dt({photo:e,message:i,container:t,boxWidth:o,boxHeight:r,withTail:l,isOut:c,lazyLoadQueue:m,middleware:h,withoutPreloader:y,loadPromises:b,autoDownloadSize:E,size:S,managers:I});return A.thumb=s,A.loadPromise=s.loadPromises.full,A}let Z;const F=ut();if(F.classList.add("media-video"),F.muted=!0,"round"===e.type){const s=document.createElement("div");s.classList.add("media-round","z-depth-1"),s.dataset.mid=""+i.mid,s.dataset.peerId=""+i.peerId,s.message=i;const o=d.Z.active.round,r=o.width/2,l=3.5,c=r-2*l;s.innerHTML=`<svg class="progress-ring" width="${o.width}" height="${o.width}" style="transform: rotate(-90deg);">\n <circle class="progress-ring__circle" stroke="white" stroke-opacity="0.3" stroke-width="${l}" cx="${r}" cy="${r}" r="${c}" fill="transparent"/>\n </svg>`;const h=s.firstElementChild.firstElementChild;jt||(jt=2*Math.PI*c),h.style.strokeDasharray=jt+" "+jt,h.style.strokeDashoffset=""+jt,x.classList.add("tgico"),i.pFlags.media_unread&&s.classList.add("is-unread");const u=document.createElement("canvas");u.width=u.height=e.w,s.prepend(u,x),s.append(F),t.append(s);const p=u.getContext("2d"),m=()=>{const e=s.message,t=vt.Z.addMedia(e,!P),i=()=>{(_m.chat.setPeerPromise||Promise.resolve()).finally((()=>{(0,Ne.Z)(t)||(t.removeEventListener("play",c),t.removeEventListener("timeupdate",l),t.removeEventListener("pause",d),t.removeEventListener("ended",m))}))},o=()=>{p.drawImage(t,0,0);const e=jt-t.currentTime/t.duration*jt;return h.style.strokeDashoffset=""+e,!t.paused},r=()=>{t.duration&&((0,Ne.Z)(t)?(t.paused&&o(),x.innerText=gt(t.duration-t.currentTime,!1)):i())},l=(0,mt.Z)((()=>{(0,Be.T2)(r)}),1e3,!1),c=()=>{F.classList.add("hide"),s.classList.remove("is-paused"),(0,ht.cK)(o,u),Z&&Z.preloader&&Z.preloader.classList.contains("manual")&&Z.onClick()},d=()=>{(0,Ne.Z)(t)?s.classList.add("is-paused"):i()},m=()=>{F.classList.remove("hide"),s.classList.add("is-paused"),F.currentTime=0,x.innerText=gt(t.duration,!1),t.currentTime&&(t.currentTime=0)};t.addEventListener("play",c),t.addEventListener("timeupdate",l),t.addEventListener("pause",d),t.addEventListener("ended",m),(0,n.fc)(u,(i=>{if((0,a.Z)(i),Z&&!Z.detached&&Z.onClick(),t.paused){const i=!!C;if(vt.Z.setSearchContext(C||{peerId:le.NM,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1})){const[t,n]=i?Kt(s,e.mid):[];vt.Z.setTargets({peerId:e.peerId,mid:e.mid},t,n)}t.play()}else t.pause()})),t.paused?t.duration&&t.currentTime!==t.duration&&t.currentTime>0?(o(),r(),F.classList.add("hide")):d():c()};i.pFlags.is_outgoing?(s.onLoad=m,s.dataset.isOutgoing="1"):m()}else F.autoplay=!0;let D,R;if(i){if(D=yield dt({photo:e,message:i,container:t,boxWidth:o,boxHeight:r,withTail:l,isOut:c,lazyLoadQueue:m,middleware:h,withoutPreloader:!0,loadPromises:b,autoDownloadSize:null==L?void 0:L.photo,size:S,managers:I}),A.thumb=D,!T&&"gif"!==e.type||f)return A.loadPromise=D.loadPromises.full,A;if(l){const e=(D.images.thumb||D.images.full).parentElement;F.width=+e.getAttributeNS(null,"width"),F.height=+e.getAttributeNS(null,"height"),e.append(F)}}!F.parentElement&&t&&((null==D?void 0:D.aspecter)||t).append(F);const B=()=>$t(this,void 0,void 0,(function*(){return R=yield I.thumbsStorage.getCacheContext(e)}));yield B();const N=null==i?void 0:i.uploadingFileName;N?(Z=new Ue({attachMethod:"prepend",isUpload:!0}),Z.attachPromise(u.Z.getUpload(N)),Z.attach(t,!1),P=void 0):R.downloaded||e.supportsStreaming||y?e.supportsStreaming&&(Z=new Ue({cancelable:!1,attachMethod:"prepend"})):Z=new Ue({attachMethod:"prepend"});const U=(0,Oe.Z)();if(F.addEventListener("error",(e=>{4!==F.error.code&&console.error("Error "+F.error.code+"; details: "+F.error.message),Z&&!N&&Z.detach(),U.isFulfilled||U.resolve()}),{once:!0}),(0,pt.Z)(F).then((()=>{v&&p.Z.addAnimation(F,v),Z&&!N&&Z.detach(),U.resolve()})),"video"===e.type){const e=()=>{F.duration&&(x.innerText=gt(F.duration-F.currentTime,!1))},t=(0,mt.Z)((()=>{(0,Be.T2)(e)}),1e3,!1);F.addEventListener("timeupdate",t),_&&F.addEventListener("timeupdate",(()=>{Te.Z.mutateElement(_,(()=>{_.remove()}))}),{once:!0})}F.muted=!0,F.loop=!0,F.autoplay=!0;let O=P&&(null===(M=null==D?void 0:D.preloader)||void 0===M?void 0:M.loadFunc);const H=()=>$t(this,void 0,void 0,(function*(){Z&&P&&!y&&(Z.construct(),Z.setManual()),yield B();let s=Promise.resolve();if(Z&&!N||y)if(R.downloaded||e.supportsStreaming)e.supportsStreaming&&(P?s=Promise.reject():!R.downloaded&&Z&&(Z.attach(t,!1,null),F.addEventListener(Je.IS_SAFARI?"timeupdate":"canplay",(()=>{Z.detach()}),{once:!0})));else{const i=s=I.apiFileManager.downloadMediaURL({media:e,queueId:null==m?void 0:m.queueId,onlyCache:P});Z&&Z.attach(t,!1,i)}return!P&&O&&(O(),O=null),P=void 0,s.then((()=>$t(this,void 0,void 0,(function*(){!h||h()?("round"===e.type&&vt.Z.resolveWaitingForLoadMedia(i.peerId,i.mid,i.pFlags.is_scheduled),yield B(),Ae(F,R.url)):U.resolve()}))),(()=>{})),{download:s,render:U}}));return Z&&!N&&Z.setDownloadFunction(H),"gif"!==e.type||T?A.loadPromise=m?(m.push({div:t,load:()=>H().then((({render:e})=>e))}),Promise.resolve()):(yield H()).render:(0,n.fc)(t,(e=>{(0,a.Z)(e),_.remove(),H()}),{capture:!0,once:!0}),A}))}function Qt({messages:e,attachmentDiv:t,middleware:i,uploading:n,lazyLoadQueue:a,isOut:o,chat:r,loadPromises:l,autoDownload:c,managers:h=s.Z.managers}){const u=[];for(const t of e){const e=(0,Se.Z)(t),i="photo"===e._?Le(e,480,480):{w:e.w,h:e.h};u.push({size:i,media:e,message:t})}ke({container:t,items:u.map((e=>({w:e.size.w,h:e.size.h}))),maxWidth:d.Z.active.album.width,minWidth:100,spacing:2,forMedia:!0}),u.forEach(((e,s)=>{const{size:n,media:r,message:d}=e,u=t.children[s];u.dataset.mid=""+d.mid,u.dataset.peerId=""+d.peerId;const p=u.firstElementChild;let m;m="photo"===r._?dt({photo:r,message:d,container:p,boxWidth:0,boxHeight:0,isOut:o,lazyLoadQueue:a,middleware:i,size:n,loadPromises:l,autoDownloadSize:c.photo,managers:h}):qt({doc:d.media.document,container:p,message:d,boxWidth:0,boxHeight:0,withTail:!1,isOut:o,lazyLoadQueue:a,middleware:i,loadPromises:l,autoDownload:c,managers:h}),m&&l&&l.push(m)}))}d.Z.addEventListener("changeScreen",((e,t)=>{if(t===d._.mobile||e===d._.mobile){const e=Array.from(document.querySelectorAll(".media-round .progress-ring")),t=d.Z.active.round.width,i=t/2,s=i-7;jt=2*Math.PI*s,e.forEach((e=>{e.setAttributeNS(null,"width",""+t),e.setAttributeNS(null,"height",""+t);const n=e.firstElementChild;n.setAttributeNS(null,"cx",""+i),n.setAttributeNS(null,"cy",""+i),n.setAttributeNS(null,"r",""+s),n.style.strokeDasharray=jt+" "+jt,n.style.strokeDashoffset=""+jt}))}}));var Yt=i(467),Jt=i(1243),Xt=i(2491),ei=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};function ti({message:e,withTime:t,fontWeight:i,voiceAsMusic:a,showSender:r,searchContext:l,loadPromises:c,autoDownloadSize:d,lazyLoadQueue:h,sizeType:p,managers:m=s.Z.managers,cacheContext:g}){var f;return ei(this,void 0,void 0,(function*(){i||(i=500),p||(p="");const y=0===d,b=e.media.document||e.media.webpage.document,w=null==e?void 0:e.uploadingFileName;if("audio"===b.type||"voice"===b.type||"round"===b.type){const s=new Wt;return s.withTime=t,s.message=e,s.noAutoDownload=y,s.lazyLoadQueue=h,s.loadPromises=c,a&&(s.voiceAsMusic=a),l&&(s.searchContext=l),r&&(s.showSender=r),s.dataset.fontWeight=""+i,s.dataset.sizeType=p,yield s.render(),s}const S=b.file_name?b.file_name.split("."):"";let C="";C=S.length>1&&Array.isArray(S)?(0,Yt.ST)(S.pop().split(" ",1)[0].toLowerCase()):"file";const L=document.createElement("div");L.classList.add("document",`ext-${C}`),L.dataset.docId=""+b.id,L.doc=b;const I=document.createElement("div");let M;I.classList.add("document-ico");const E=!!g,P=()=>E?g:m.thumbsStorage.getCacheContext(b);g=yield P();let k=!1;if((null===(f=b.thumbs)||void 0===f?void 0:f.length)||e.pFlags.is_outgoing&&g.url&&"photo"===b.type){L.classList.add("document-with-thumb"),k=!0;const t=[];if(e.pFlags.is_outgoing&&["photo","video"].includes(b.type))I.innerHTML=`<img src="${g.url}">`,t.push(I.firstElementChild);else{performance.now();const e=yield dt({photo:b,message:null,container:I,boxWidth:54,boxHeight:54,loadPromises:c,withoutPreloader:!0,lazyLoadQueue:h,size:Le(b,54,54,!0),managers:m});I.style.width=I.style.height="",e.images.thumb&&t.push(e.images.thumb),e.images.full&&t.push(e.images.full)}t.forEach((e=>e.classList.add("document-thumb")))}else M=document.createElement("span"),M.classList.add("document-ico-text"),M.innerText=C,I.append(M);const T=b.file_name?(0,Xt.Z)(b.file_name):"Unknown.file";document.createElement("div").classList.add("document-description");const x=document.createElement("span"),_=[Tt(b.size)];if(t&&_.push(G(e.date)),r&&_.push(yield Ht(e)),!t&&!r){const e=document.createElement("span"),t=Tt(b.size);e.append(" / ",t),e.style.visibility="hidden",_.push(e)}L.innerHTML=`\n ${g.downloaded&&!w||!e.mid||!k?"":'<div class="document-download"></div>'}\n <div class="document-name"></div>\n <div class="document-size"></div>\n `;const A=L.querySelector(".document-name"),Z=new Pt;Z.dataset.fontWeight=""+i,Z.dataset.sizeType=p,Z.textContent=T,e.mid||L.classList.add("downloaded"),A.append(Z),r&&A.append(zt(e));const F=L.querySelector(".document-size");if(x.append(...(0,v.A1)(_," · ")),F.append(x),L.prepend(I),!w&&e.pFlags.is_outgoing&&!e.mid)return L;let D,R=null;const B=()=>{if(L.classList.remove("downloading"),b.size>le.Iw&&!w)return R.setManual(),R.attach(D),R.preloader.classList.add("manual"),void R.setDownloadFunction(U);if(b.size<=le.Iw&&L.classList.add("downloaded"),D){if(D!==I){const e=D;setTimeout((()=>{e.remove()}),200)}D=null}R&&(R=null)},N=e=>{L.classList.add("downloading");const t=document.createElement("span"),i=Tt(b.size);t.style.position="absolute",t.style.left="0",e.then(B,ft.Z).finally((()=>{x.style.visibility="",t.remove()}));const s=e=>Tt(e);let n=s(0);x.style.visibility="hidden",t.append(n," / ",i),x.parentElement.append(t),e.addNotifyListener((e=>{const t=s(e.done);n.replaceWith(t),n=t}))},U=e=>{var t;const i=!e||e.isTrusted,n=L.doc;let a;const r=_m.chat.bubbles?_m.chat.bubbles.lazyLoadQueue.queueId:void 0;if(i)if("pdf"===n.type){const e=!R||R.detached;a=u.Z.downloadMediaURL({media:n,queueId:r}),e&&a.then((()=>{setTimeout((()=>ei(this,void 0,void 0,(function*(){const e=(yield P()).url;window.open(e)}))),s.Z.settings.animationsEnabled?250:0)}))}else a=o.Z.has(n.mime_type)&&(null===(t=n.thumbs)||void 0===t?void 0:t.length)?u.Z.downloadMediaURL({media:n,queueId:r}):u.Z.downloadToDisc({media:n,queueId:r});else a=u.Z.downloadToDisc({media:n,queueId:r},!0);a.catch((()=>{L.classList.remove("downloading")})),D&&(R.attach(D,!0,a),N(a))},{fileName:O}=(0,Jt.Z)({media:b,downloadId:"1"});if(yield m.apiFileManager.isDownloading(O)){D=L.querySelector(".document-download")||I;const e=u.Z.downloadToDisc({media:b},!0);R=new Ue,R.attach(D,!1,e),R.setDownloadFunction(U),N(e)}else if(!g.downloaded||w)if(D=L.querySelector(".document-download")||I,R=new Ue({isUpload:!!w}),w){const e=u.Z.getUpload(w);R.attachPromise(e),R.attach(D),N(e)}else R.construct(),R.setManual(),R.attach(D),R.setDownloadFunction(U),void 0!==d&&d>=b.size&&(0,n.tH)(R.preloader);return(0,n.fc)(L,(e=>{R?R.onClick(e):U(e)})),L}))}s.Z.addEventListener("document_downloading",(e=>{Array.from(document.querySelectorAll(`.document[data-doc-id="${e}"]`)).forEach((e=>{e.querySelector(".preloader-container.manual")&&(0,n.tH)(e)}))}));var ii=i(3178),si=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))},ni=i(5269),ai=i(8938),oi=i(5471);const ri={};function li(e,t,i){return n=this,a=void 0,r=function*(){const n=e.id+"-"+i,{width:a,height:o}=t;let r=ri[n];if(r&&r.width>=a&&r.height>=o)return;r=ri[n]={width:a,height:o};const l=yield s.Z.managers.appDocsManager.getLottieCachedThumb(e.id,i);if(ri[n]!==r)return;if(l&&l.w>=a&&l.h>=o)return;const c=new Promise((e=>{t.toBlob((t=>e(t)))})),d=yield c;ri[n]===r&&(s.Z.managers.appDocsManager.saveLottiePreview(e.id,d,a,o,i),delete ri[n])},new((o=void 0)||(o=Promise))((function(e,t){function i(e){try{l(r.next(e))}catch(e){t(e)}}function s(e){try{l(r.throw(e))}catch(e){t(e)}}function l(t){var n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o((function(e){e(n)}))).then(i,s)}l((r=r.apply(n,a||[])).next())}));var n,a,o,r}var ci=i(2790),di=i(13),hi=i(2384),ui=i(7730),pi=i(671),mi=i(1656),gi=i(5432),vi=i(5975);class fi extends L.Z{constructor(e,t){super(!1),this.navigationType=e,this.withOverlay=t,this.onClick=e=>{var t;this.element&&(0,vi.Z)(e.target,this.element)||((null===(t=this.listenerOptions)||void 0===t?void 0:t.capture)&&(0,a.Z)(e),this.close())},this.listenerOptions=t?{}:{capture:!0}}close(){var e;this.element&&(null===(e=this.overlay)||void 0===e||e.remove(),this.element=void 0,this.dispatchEvent("toggle",!1)),gi.Z||window.removeEventListener("contextmenu",this.onClick,this.listenerOptions),document.removeEventListener(n.pf,this.onClick,this.listenerOptions),Je.IS_MOBILE_SAFARI||C.Z.removeByType(this.navigationType)}open(e){this.close(),Je.IS_MOBILE_SAFARI||C.Z.pushItem({type:this.navigationType,onPop:e=>{this.close()}}),this.element=e,!this.overlay&&this.withOverlay&&(this.overlay=document.createElement("div"),this.overlay.classList.add("btn-menu-overlay"),this.overlay.addEventListener(n.pf,(e=>{(0,a.Z)(e),this.onClick(e)}))),this.overlay&&this.element.parentElement.insertBefore(this.overlay,this.element),gi.Z||window.addEventListener("contextmenu",this.onClick,Object.assign(Object.assign({},this.listenerOptions),{once:!0})),document.addEventListener(n.pf,this.onClick,this.listenerOptions),this.dispatchEvent("toggle",!0)}}const yi=document.createElement("div");let bi;yi.classList.add("toast");const wi=new fi("toast");function Si(){wi.close(),yi.classList.remove("is-visible"),bi&&clearTimeout(+bi),bi=window.setTimeout((()=>{yi.remove(),bi=void 0}),200)}function Ci(e,t){wi.close(),(0,g.Z)(yi,e),yi.parentElement||(document.body.append(yi),yi.offsetLeft),yi.classList.add("is-visible"),bi&&clearTimeout(+bi),wi.open(yi),bi=window.setTimeout(Si,3e3),t&&wi.addEventListener("toggle",t,{once:!0})}function Li(e){Ci((0,v.ag)(e.langPackKey,e.langPackArguments),e.onClose)}wi.addEventListener("toggle",(e=>{e||Si()}));const Ii=new class extends fi{constructor(){super("menu",!0),this.onMouseMove=e=>{const t=this.element.getBoundingClientRect(),{clientX:i,clientY:s}=e,n=i>=t.right?i-t.right:t.left-i,a=s>=t.bottom?s-t.bottom:t.top-s;(n>=100||a>=100)&&this.close()},d.Z.addEventListener("resize",(()=>{this.element&&this.close()}))}isOpened(){return!!this.element}close(){this.element&&(this.element.classList.remove("active"),this.element.parentElement.classList.remove("menu-open")),super.close(),gi.Z||window.removeEventListener("mousemove",this.onMouseMove)}openBtnMenu(e,t){super.open(e),this.element.classList.add("active"),this.element.parentElement.classList.add("menu-open"),t&&this.addEventListener("toggle",t,{once:!0}),gi.Z||window.addEventListener("mousemove",this.onMouseMove)}},Mi=e=>{if(e.element)return e.element;const{icon:t,text:i,onClick:s,checkboxField:o,noCheckboxClickListener:l}=e,c=document.createElement("div");c.className="btn-menu-item rp-overflow"+(t?" tgico-"+t:"");let d=e.textElement;d||(d=e.textElement=i?(0,v.ag)(i,e.textArgs):document.createElement("span"),e.regularText&&(d.innerHTML=e.regularText)),d.classList.add("btn-menu-item-text"),c.append(d);const h=!!o||!!e.keepOpen;return s&&(0,n.fc)(c,(e=>{(0,a.Z)(e);const t=(0,r.Z)(e.target,"btn-menu");t&&!t.classList.contains("active")||!1!==s(e)&&(h||Ii.close(),o&&!l&&(o.checked="radio"===o.input.type||!o.checked))}),e.options),o&&c.append(o.label),e.element=c},Ei=(e,t)=>{const i=document.createElement("div");i.classList.add("btn-menu"),t&&e.forEach((e=>{e.options?e.options.listenerSetter=t:e.options={listenerSetter:t}}));const s=e.map(Mi);return i.append(...s),i};var Pi=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};function ki(e,t){return Pi(this,void 0,void 0,(function*(){const i=e.map(((e,i,s)=>Pi(this,void 0,void 0,(function*(){if(yield t(e,i,s))return e}))));return(yield Promise.all(i)).filter(Boolean)}))}var Ti=i(3624);function xi({pageX:e,pageY:t},i,s,n){const a=Array.from(i.children).find((e=>e.classList.contains("btn-menu-item")&&!e.classList.contains("hide")))||i,{scrollWidth:o}=a,{scrollHeight:r}=i,l=document.body.getBoundingClientRect(),c=l.width,h=l.height;let u=8,p=8,m=8,g=8;n&&(n.top&&n.top,n.right&&(p+=n.right),n.bottom&&(m+=n.bottom),n.left&&(g+=n.left)),s=d.Z.isMobile?"right":"left";let v="top";const f=h-r-m,y=c-o-p,b=g,w={x:{left:e,right:Math.min(y,e-o)},intermediateX:"right"===s?b:y,y:{top:t,bottom:t-r},intermediateY:f},S={left:w.x.left+o+p<=c,right:w.x.right>=g},C={top:w.y.top+r+m<=h,bottom:w.y.bottom-m>=m};{const e=S[s]?w.x[s]:(s="center",w.intermediateX);i.style.left=e+"px"}{const e=C[v]?w.y[v]:(v="center",w.intermediateY);i.style.top=e+"px"}return i.className=i.className.replace(/(top|center|bottom)-(left|center|right)/g,""),i.classList.add(("center"===v?v:"bottom")+"-"+("center"===s?s:"left"===s?"right":"left")),{width:o,height:r}}let _i=!1,Ai=0;function Zi(){Ai&&clearTimeout(Ai),Ai=window.setTimeout((()=>{Ai=0,_i=!1}),400),_i=!0}function Fi(e,t,i){const s=i?i.add(e):e.addEventListener.bind(e),n=i?i.removeManual.bind(i,e):e.removeEventListener.bind(e);if(Je.IS_APPLE&&gi.Z){let i;const o={capture:!0},r=()=>{clearTimeout(i),n("touchmove",r,o),n("touchend",r,o),n("touchcancel",r,o)};s("touchstart",(n=>{n.touches.length>1?r():(s("touchmove",r,o),s("touchend",r,o),s("touchcancel",r,o),i=window.setTimeout((()=>{_i?r():(t(n.touches[0]),r(),Ii.isOpened()&&e.addEventListener("touchend",a.Z,{once:!0}))}),400))}))}else s("contextmenu",gi.Z?i=>{t(i),Ii.isOpened()&&e.addEventListener("touchend",a.Z,{once:!0})}:t)}var Di=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Ri{constructor(e){this._disabled=!1,this.avatarSize=120,this.isChanged=()=>{if(this.uploadAvatar)return!0;let e=0,t=0,i=0;return this.inputFields.forEach((s=>{s.isValid()&&(s.isChanged()&&++e,s.required&&++i),s.required&&++t})),t===i&&e>0},this.handleChange=()=>{this.nextBtn.classList.toggle("is-visible",this.isChanged())},(0,x.Z)(this,e),this.nextBtn?this.nextBtn.classList.contains("btn-corner")||(this.handleChange=()=>{this.nextBtn.toggleAttribute("disabled",!this.isChanged()||this.disabled)}):this.nextBtn=D({icon:"check"}),e.withoutAvatar||(this.avatarElem=document.createElement("avatar-element"),this.avatarElem.classList.add("avatar-placeholder","avatar-"+this.avatarSize),this.avatarElem.updateWithOptions({peerId:this.peerId}),e.doNotEditAvatar||(this.avatarEdit=new F((e=>{this.uploadAvatar=e,this.handleChange(),this.avatarElem.remove()})),this.avatarEdit.container.append(this.avatarElem))),this.inputFields.forEach((e=>{this.listenerSetter.add(e.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 Bi(e,t){const i=document.createElement("form");return e.forEach((e=>{const{container:s,input:n}=e;i.append(s),n.addEventListener("change",(e=>{n.checked&&t(n.value,e)}))})),i}class Ni{constructor(e={}){this.freezed=!1,this.container=document.createElement(e.radioField||e.checkboxField?"label":"div"),this.container.classList.add("row"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("row-subtitle"),this.subtitle.setAttribute("dir","auto"),e.subtitle?"string"==typeof e.subtitle?(0,c.Z)(this.subtitle,e.subtitle):this.subtitle.append(e.subtitle):e.subtitleLangKey&&this.subtitle.append((0,v.ag)(e.subtitleLangKey,e.subtitleLangArgs)),this.container.append(this.subtitle);let t=!!e.havePadding;if(e.radioField||e.checkboxField){if(e.radioField&&(this.radioField=e.radioField,this.container.append(this.radioField.label),t=!0),e.checkboxField){this.checkboxField=e.checkboxField;const i=e.checkboxField.label.classList.contains("checkbox-field-toggle");if(i?(this.container.classList.add("row-with-toggle"),e.titleRight=this.checkboxField.label):(t=!0,this.container.append(this.checkboxField.label)),!e.noCheckboxSubtitle&&!i){const t=()=>{(0,g.Z)(this.subtitle,(0,v.ag)(this.checkboxField.input.checked?"Checkbox.Enabled":"Checkbox.Disabled"))};e.listenerSetter?e.listenerSetter.add(this.checkboxField.input)("change",t):this.checkboxField.input.addEventListener("change",t)}}(e.radioField||e.checkboxField).label.classList.add("disable-hover")}if(e.title||e.titleLangKey){let t;const i=e.titleRight||e.titleRightSecondary;if(i?(t=document.createElement("div"),t.classList.add("row-title-row"),this.container.append(t)):t=this.container,this.title=document.createElement("div"),this.title.classList.add("row-title"),this.title.setAttribute("dir","auto"),e.noWrap&&this.title.classList.add("no-wrap"),e.title?"string"==typeof e.title?this.title.innerHTML=e.title:this.title.append(e.title):this.title.append((0,v.ag)(e.titleLangKey)),t.append(this.title),i){const s=this.titleRight=document.createElement("div");s.classList.add("row-title","row-title-right"),e.titleRightSecondary&&s.classList.add("row-title-right-secondary"),"string"==typeof i?s.innerHTML=i:s.append(i),t.append(s)}}e.icon&&(t=!0,this.title.classList.add("tgico","tgico-"+e.icon),this.container.classList.add("row-with-icon")),t&&this.container.classList.add("row-with-padding"),e.navigationTab&&(e.clickable=()=>e.navigationTab.open()),(e.clickable||e.radioField||e.checkboxField)&&("function"==typeof e.clickable&&(0,n.fc)(this.container,(t=>{this.freezed||e.clickable(t)}),{listenerSetter:e.listenerSetter}),this.container.classList.add("row-clickable","hover-effect"),e.noRipple||(0,we.Z)(this.container,void 0,void 0,!0))}createMedia(e){this.container.classList.add("row-with-padding");const t=this.media=document.createElement("div");return t.classList.add("row-media"),e&&t.classList.add("row-media-"+e),this.container.append(t),t}}const Ui=(e,t)=>Bi(e.map((e=>({container:e.container,input:e.radioField.input}))),t);function Oi(e){navigator.clipboard?navigator.clipboard.writeText(e):function(e){var t=document.createElement("textarea");t.value=e,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t),t.focus(),t.select();try{document.execCommand("copy")}catch(e){}document.body.removeChild(t)}(e)}var Hi=i(144),zi=i(9750),Gi=i(3789);class Vi{constructor(e){const t=this.label=document.createElement("label");t.classList.add("radio-field"),e.alignRight&&t.classList.add("radio-field-right");const i=this.input=document.createElement("input");i.type="radio",i.name="input-radio-"+e.name,e.value&&(i.value=e.value,e.stateKey&&(Gi.Z.getState().then((t=>{i.checked=(0,zi.Z)(t,e.stateKey)===e.value})),i.addEventListener("change",(()=>{s.Z.managers.appStateManager.setByKey(e.stateKey,e.value)}))));const n=this.main=document.createElement("div");n.classList.add("radio-field-main"),e.text?n.innerHTML=e.text:e.langKey&&(0,v.$d)(n,e.langKey),t.append(i,n)}get checked(){return this.input.checked}set checked(e){this.setValueSilently(e);const t=new Event("change",{bubbles:!0,cancelable:!0});this.input.dispatchEvent(t)}setValueSilently(e){this.input.checked=e}}var Ki=i(5701);function Wi(e){return(e.length>=5&&e.length<=32||!e.length)&&/^[a-zA-Z0-9_]*$/.test(e)}class $i extends b.Z{constructor(e,t){super(e),this.managers=t,this.checkUsernameDebounced=(0,Ki.Z)(this.checkUsername.bind(this),150,!1,!0),e.listenerSetter.add(this.input)("input",(()=>{const e=this.getValue();if(e===this.originalValue||!e.length)return this.setState(b.I.Neutral),void(this.options.onChange&&this.options.onChange());Wi(e)?this.setState(b.I.Neutral):this.setError(this.options.invalidText),this.input.classList.contains("error")?this.options.onChange&&this.options.onChange():this.checkUsernameDebounced(e)}))}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){this.checkUsernamePromise||(this.options.peerId?this.checkUsernamePromise=this.managers.appChatsManager.checkUsername(this.options.peerId.toChatId(),e):this.checkUsernamePromise=this.managers.appUsersManager.checkUsername(e),this.checkUsernamePromise.then((t=>{this.getValue()===e&&(t?this.setState(b.I.Valid,this.options.availableText):this.setError(this.options.takenText))}),(t=>{this.getValue()===e&&"USERNAME_INVALID"===t.type&&this.setError(this.options.invalidText)})).then((()=>{this.checkUsernamePromise=void 0,this.options.onChange&&this.options.onChange();const t=this.getValue();t!==e&&this.isValidToChange()&&Wi(t)&&this.checkUsername(t)})))}}var ji=i(9807);class qi extends A.Z{constructor(e,t={}){if(super("popup-peer"+(e?" "+e:""),Object.assign(Object.assign({overlayClosable:!0},t),{title:!0,buttons:t.buttons&&(0,A.x)(t.buttons)})),this.className=e,t.peerId){const e=new Wm;e.classList.add("avatar-32"),e.updateWithOptions({isDialog:!0,peerId:t.peerId}),this.header.prepend(e)}t.noTitle||(t.titleLangKey||!t.title?this.title.append((0,v.ag)(t.titleLangKey||"AppName",t.titleLangArgs)):t.title instanceof HTMLElement?this.title.append(t.title):this.title.innerText=t.title||"");const i=document.createDocumentFragment();if(t.descriptionLangKey||t.description){const e=this.description=document.createElement("p");e.classList.add("popup-description"),t.descriptionLangKey?e.append((0,v.ag)(t.descriptionLangKey,t.descriptionLangArgs)):t.description&&(0,c.Z)(e,t.description),i.append(e)}t.checkboxes&&(this.container.classList.add("have-checkbox"),t.checkboxes.forEach((e=>{e.withRipple=!0;const t=new ji.Z(e);e.checkboxField=t,i.append(t.label)})),t.buttons.forEach((e=>{if(e.callback){const i=e.callback;e.callback=()=>{const e=new Set;t.checkboxes.forEach((t=>{t.checkboxField.checked&&e.add(t.text)})),i(e)}}}))),this.container.insertBefore(i,this.header.nextElementSibling)}}class Qi extends k{init(){return e=this,t=void 0,a=function*(){this.container.classList.add("edit-peer-container","group-type-container");const e=yield this.managers.appChatsManager.isBroadcast(this.chatId);this.setTitle(e?"ChannelType":"GroupType");const t=new Br({name:e?"ChannelType":"GroupType"}),i=(0,Hi.a)(),a=new Ni({radioField:new Vi({langKey:e?"ChannelPrivate":"MegaPrivate",name:i,value:"private"}),subtitleLangKey:e?"ChannelPrivateInfo":"MegaPrivateInfo"}),o=new Ni({radioField:new Vi({langKey:e?"ChannelPublic":"MegaPublic",name:i,value:"public"}),subtitleLangKey:e?"ChannelPublicInfo":"MegaPublicInfo"}),r=Ui([a,o],(e=>{const t=[c,u];"public"===e&&t.reverse(),t[0].container.classList.remove("hide"),t[1].container.classList.add("hide"),g()})),l=yield this.managers.appChatsManager.getChat(this.chatId);t.content.append(r);const c=new Br({}),d=new Ni({title:this.chatFull.exported_invite.link,subtitleLangKey:e?"ChannelPrivateLinkHelp":"MegaPrivateLinkHelp",clickable:()=>{Oi(this.chatFull.exported_invite.link),Ci(v.ZP.format("LinkCopied",!0))},listenerSetter:this.listenerSetter}),h=(0,M.Z)("btn-primary btn-transparent danger",{icon:"delete",text:"RevokeLink"});(0,n.fc)(h,(()=>{new qi("revoke-link",{buttons:[{langKey:"RevokeButton",callback:()=>{const e=(0,mi.Z)([h],!0);this.managers.appProfileManager.getChatInviteLink(this.chatId,!0).then((t=>{e(),d.title.innerHTML=t}))}}],titleLangKey:"RevokeLink",descriptionLangKey:"RevokeAlert"}).show()}),{listenerSetter:this.listenerSetter}),c.content.append(d.container,h);const u=new Br({caption:e?"Channel.UsernameAboutChannel":"Channel.UsernameAboutGroup",noDelimiter:!0}),p=document.createElement("div");p.classList.add("input-wrapper");const m="t.me/",g=()=>{const e=a.radioField.checked&&y!==m||f.isValidToChange()&&f.input.classList.contains("valid");b.classList.toggle("is-visible",e)},f=new $i({label:"SetUrlPlaceholder",name:"group-public-link",plainText:!0,listenerSetter:this.listenerSetter,availableText:"Link.Available",invalidText:"Link.Invalid",takenText:"Link.Taken",onChange:g,peerId:this.chatId.toPeerId(!0),head:m},this.managers),y=m+(l.username||"");p.append(f.container),u.content.append(p);const b=D({icon:"check",className:"is-visible"});this.content.append(b),(0,n.fc)(b,(()=>{(0,be.p)(b);const e=o.radioField.checked?f.getValue():"";this.managers.appChatsManager.migrateChat(this.chatId).then((t=>this.managers.appChatsManager.updateUsername(t,e))).then((()=>{this.close()}))}),{listenerSetter:this.listenerSetter}),(y!==m?o:a).radioField.checked=!0,f.setOriginalValue(y),this.scrollable.append(t.container,c.container,u.container);{const t=new Br({name:"SavingContentTitle",caption:e?"RestrictSavingContentInfoChannel":"RestrictSavingContentInfoGroup"}),i=new ji.Z({text:"RestrictSavingContent",withRipple:!0});this.listenerSetter.add(i.input)("change",(()=>{const e=i.toggleDisability(!0);this.managers.appChatsManager.toggleNoForwards(this.chatId,i.checked).then((()=>{e()}))}));const n=()=>{i.setValueSilently(!!l.pFlags.noforwards)};this.listenerSetter.add(s.Z)("chat_update",(e=>{this.chatId===e&&n()})),n(),t.content.append(i.label),this.scrollable.append(t.container)}},new((i=void 0)||(i=Promise))((function(s,n){function o(e){try{l(a.next(e))}catch(e){n(e)}}function r(e){try{l(a.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((a=a.apply(e,t||[])).next())}));var e,t,i,a}}class Yi{constructor(e){this.loading=!1,this.loaded=!1,(0,x.Z)(this,e),e.scrollable.onScrolledBottom=()=>{this.load()}}load(){return this.loaded?Promise.resolve():this.loading?this.promise:(this.loading=!0,void(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}))))}}var Ji=i(8479),Xi=i(7120),es=i(2946),ts=i(4789),is=i(8763),ss=i(1352);const ns=new class{constructor(){if(ss.kC)return;const e="visualViewport"in window?window.visualViewport:window,t=()=>{this.width=e.width||e.innerWidth,this.height=e.height||e.innerHeight};e.addEventListener("resize",t),t()}},as=ns;var os=i(6690),rs=i(2566);function ls(e,t=" "){const i=e.toString().split(".");return i[0]=i[0].replace(/\B(?=(\d{3})+(?!\d))/g,t),i.join(".")}function cs(e,t=s.Z.managers){var i,n,a,o,r,l;return a=this,o=void 0,l=function*(){const s=yield t.appChatsManager.getChat(e);if("chatForbidden"===s._)return(0,v.ag)("YouWereKicked");const a=yield t.appProfileManager.getCachedFullChat(e);let o;o=a?"channelFull"===a._?a.participants_count:null===(i=a.participants.participants)||void 0===i?void 0:i.length:s.participants_count||(null===(n=s.participants)||void 0===n?void 0:n.participants.length),o=o||1;const r=s.pFlags.broadcast?"Peer.Status.Subscribers":"Peer.Status.Member";return(0,v.ag)(r,[ls(o)])},new((r=void 0)||(r=Promise))((function(e,t){function i(e){try{n(l.next(e))}catch(e){t(e)}}function s(e){try{n(l.throw(e))}catch(e){t(e)}}function n(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r((function(e){e(n)}))).then(i,s)}n((l=l.apply(a,o||[])).next())}))}var ds=i(8493),hs=i(8050),us=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class ps{constructor(e){this.container=document.createElement("div"),this.list=gg.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=48,this.exceptSelf=!1,this.tempIds={},this.selfPresence="Presence.YourChat",this.needSwitchList=!1,this.onInput=()=>{const e=this.input.value;if(this.query!==e){(this.peerType.includes("contacts")||this.peerType.includes("dialogs"))&&(this.cachedContacts=null),this.peerType.includes("dialogs")&&(this.folderId=0,this.offsetIndex=0);for(const e in this.tempIds)++this.tempIds[e];this.list=gg.createChatList(),this.promise=null,this.loadedWhat={},this.query=e,this.renderedPeerIds.clear(),this.needSwitchList=!0,this.getMoreResults()}},this.checkForTriggers=()=>{this.scrollable.checkForTriggers()},(0,x.Z)(this,e),this.container.classList.add("selector");const t=(this.renderResultsFunc||this.renderResults).bind(this);if(this.renderResultsFunc=e=>us(this,void 0,void 0,(function*(){return this.needSwitchList&&(this.scrollable.splitUp.replaceWith(this.list),this.scrollable.setVirtualContainer(this.list),this.needSwitchList=!1),e=e.filter((e=>{const t=!this.renderedPeerIds.has(e);return t&&this.renderedPeerIds.add(e),t})),this.filterPeerTypeBy&&(e=yield ki(e,(e=>us(this,void 0,void 0,(function*(){if(e.isPeerId()&&!(yield this.managers.appPeersManager.getPeer(e)).deleted)for(const t of this.filterPeerTypeBy)if(yield this.managers.appPeersManager[t](e))return!0;return!0}))))),t(e)})),this.input=document.createElement("input"),this.input.classList.add("selector-search-input"),this.placeholder?(0,v.$d)(this.input,this.placeholder,void 0,"placeholder"):(0,v.$d)(this.input,"SendMessageTo",void 0,"placeholder"),this.input.type="text",this.multiSelect){const e=new Br({});e.innerContainer.classList.add("selector-search-section");const t=document.createElement("div");t.classList.add("selector-search-container"),this.selectedContainer=document.createElement("div"),this.selectedContainer.classList.add("selector-search"),this.selectedContainer.append(this.input),t.append(this.selectedContainer),this.selectedScrollable=new m.ZP(t),(0,n.fc)(this.selectedContainer,(e=>{if(this.freezed)return;let t=e.target;if(t=(0,r.Z)(t,"selector-user"),!t)return;const i=t.dataset.key,s=this.chatsContainer.querySelector('[data-peer-id="'+i+'"]');s?(0,n.tH)(s):this.remove(i.toPeerId())})),e.content.append(t),this.container.append(e.container)}this.chatsContainer.classList.add("chatlist-container");const i=new Br({name:this.sectionNameLangPackKey,noShadow:!0});i.content.append(this.list),this.chatsContainer.append(i.container),this.scrollable=new m.ZP(this.chatsContainer),this.scrollable.setVirtualContainer(this.list),(0,n.fc)(this.chatsContainer,(e=>{const t=(0,is.Z)(e.target,"data-peer-id");if((0,a.Z)(e),!t)return;if(this.freezed)return;let i=t.dataset.peerId;if(i=i.isPeerId()?i.toPeerId():i,!this.multiSelect)return void this.add(i);this.selected.has(i)?this.remove(i):this.add(i);const s=t.querySelector("input");s.checked=!s.checked}));const s=(0,Ki.Z)(this.onInput,200,!1,!0);this.input.addEventListener("input",s),this.scrollable.onScrolledBottom=()=>{this.getMoreResults()},this.scrollable.container.prepend(Ur()),this.container.append(this.chatsContainer),this.appendTo.append(this.container),setTimeout((()=>{const t=this.getMoreResults();e.onFirstRender&&t.then((()=>{e.onFirstRender()}))}),0)}renderSaved(){return us(this,void 0,void 0,(function*(){this.exceptSelf||this.offsetIndex||0!==this.folderId||!this.peerType.includes("dialogs")||this.query&&!(yield this.managers.appUsersManager.testSelfSearch(this.query))||(yield this.renderResultsFunc([s.Z.myId]))}))}getTempId(e){return void 0===this.tempIds[e]&&(this.tempIds[e]=0),++this.tempIds[e]}getMoreDialogs(){return us(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(this.loadedWhat.dialogs&&this.loadedWhat.archived)return;const e=as.height/72*1.25|0,t=this.getTempId("dialogs"),i=this.managers.appMessagesManager.getConversations(this.query,this.offsetIndex,e,this.folderId,!0);this.promise=i;const n=yield i;if(this.tempIds.dialogs!==t)return;this.promise=null;let a=n.dialogs;if(a.length){const e=(0,hs.Z)(a[a.length-1])||0;a=a.slice(),(0,ge.Z)(a,(e=>e.peerId===s.Z.myId)),this.chatRightsAction&&(a=yield ki(a,(e=>this.filterByRights(e.peerId)))),yield this.renderSaved(),this.offsetIndex=e}if(this.renderResultsFunc(a.map((e=>e.peerId))),n.isEnd){if(!this.loadedWhat.dialogs)return yield this.renderSaved(),this.loadedWhat.dialogs=!0,this.offsetIndex=0,this.folderId=1,this.getMoreDialogs();if(this.loadedWhat.archived=!0,!this.loadedWhat.contacts)return this.getMoreContacts()}}))}filterByRights(e){return us(this,void 0,void 0,(function*(){const t=yield this.managers.appPeersManager.getPeer(e);return e.isUser()?"send_messages"!==this.chatRightsAction||(0,ds.Z)(t):!!(0,Xi.Z)(t,this.chatRightsAction)||void 0}))}getMoreContacts(){return us(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(this.loadedWhat.contacts)return;const e=this.peerType.includes("contacts");if(!this.cachedContacts){const t=this.getTempId("contacts"),i=Promise.all([e?this.managers.appUsersManager.getContactsPeerIds(this.query):[],this.query?this.managers.appUsersManager.searchContacts(this.query):void 0]);this.promise=i;const[n,a]=yield i;if(this.tempIds.contacts!==t)return;if(a){let t=e?a.my_results.concat(a.results):a.my_results;this.chatRightsAction&&(t=yield ki(t,(e=>this.filterByRights(e)))),this.peerType.includes("dialogs")||(t=t.filter((e=>e.isUser()))),this.cachedContacts=(0,os.Z)(n.concat(t))}else this.cachedContacts=n.slice();(0,T.Z)(this.cachedContacts,s.Z.myId),this.promise=null}const t=as.height/72*1.25|0,i=this.cachedContacts.splice(0,t);this.renderResultsFunc(i),this.cachedContacts.length||(this.loadedWhat.contacts=!0)}))}getMoreChannelParticipants(){return us(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(this.loadedWhat.channelParticipants)return;const e=this.getTempId("channelParticipants"),t=this.managers.appProfileManager.getChannelParticipants(this.peerId.toChatId(),{_:"channelParticipantsSearch",q:this.query},50,this.list.childElementCount),i=yield t;if(this.tempIds.channelParticipants!==e)return;const n=i.participants.map((e=>(0,rs.Z)(e)));(0,T.Z)(n,s.Z.myId),this.renderResultsFunc(n),(this.list.childElementCount>=i.count||i.participants.length<50)&&(this.loadedWhat.channelParticipants=!0)}))}getMoreResults(){const e=(()=>{const e=[];return!this.peerType.includes("dialogs")||this.loadedWhat.archived||(e.push(this.getMoreDialogs()),this.loadedWhat.archived)?(!this.peerType.includes("contacts")&&!this.peerType.includes("dialogs")||this.loadedWhat.contacts||e.push(this.getMoreContacts()),this.peerType.includes("channelParticipants")&&!this.loadedWhat.channelParticipants&&e.push(this.getMoreChannelParticipants()),e):e})(),t=Promise.all(e);return e.length&&t.then(this.checkForTriggers),t}renderResults(e){return us(this,void 0,void 0,(function*(){!this.peerType.includes("dialogs")&&this.loadedWhat.contacts&&(e=yield ki(e,(e=>this.managers.appUsersManager.isNonContactUser(e)))),e.forEach((e=>us(this,void 0,void 0,(function*(){const{dom:t}=gg.addDialogNew({peerId:e,container:this.scrollable,rippleEnabled:this.rippleEnabled,avatarSize:this.avatarSize});if(this.multiSelect){const i=this.selected.has(e),s=new ji.Z;i&&(s.input.checked=!0),t.containerEl.prepend(s.label)}let i;i=e.isAnyChat()?yield cs(e.toChatId()):e===s.Z.myId?(0,v.ag)(this.selfPresence):ce(yield this.managers.appUsersManager.getUser(e.toUserId())),t.lastMessageSpan.append(i)}))))}))}add(e,t,i=!0){if(this.selected.add(e),!this.multiSelect)return void this.onChange(this.selected.size);this.query.trim()&&(this.input.value="",this.onInput());const s=document.createElement("div");s.classList.add("selector-user","scale-in");const n=new Wm;return n.classList.add("selector-user-avatar","tgico","avatar-32"),n.isDialog=!0,s.dataset.key=""+e,e.isPeerId()&&(void 0===t&&(t=new Ot({peerId:e.toPeerId(),dialog:!0}).element),n.updateWithOptions({peerId:e})),t&&("string"==typeof t?s.innerHTML=t:((0,g.Z)(s,t),s.append(t))),s.insertAdjacentElement("afterbegin",n),this.selectedContainer.insertBefore(s,this.input),this.onChange&&this.onChange(this.selected.size),i&&this.selectedScrollable.scrollIntoViewNew({element:this.input,position:"center"}),s}remove(e){if(!this.multiSelect)return;const t=this.selectedContainer.querySelector(`[data-key="${e}"]`);t.classList.remove("scale-in"),t.offsetWidth,t.classList.add("scale-out");const i=()=>{this.selected.delete(e),t.remove(),this.onChange&&this.onChange(this.selected.size)};s.Z.settings.animationsEnabled?t.addEventListener("animationend",i,{once:!0}):i()}getSelected(){return[...this.selected]}addInitial(e){e.forEach((e=>{this.add(e,void 0,!1)})),window.requestAnimationFrame((()=>{this.selectedScrollable.scrollIntoViewNew({element:this.input,position:"center",forceDirection:ts.f.Static})}))}}class ms extends A.Z{constructor(e){super("popup-forward",{closable:!0,overlayClosable:!0,body:!0,title:!0}),this.selector=new ps({appendTo:this.body,onChange:()=>{return t=this,i=void 0,n=function*(){const t=this.selector.getSelected(),i=t[t.length-1].toPeerId();if(e.onSelect){const t=e.onSelect(i);if(t instanceof Promise)try{yield t}catch(e){return}}this.selector=null,this.hide()},new((s=void 0)||(s=Promise))((function(e,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,r)}l((n=n.apply(t,i||[])).next())}));var t,i,s,n},peerType:e.peerTypes,onFirstRender:()=>{this.show(),this.selector.checkForTriggers(),gi.Z||this.selector.input.focus()},chatRightsAction:e.chatRightsAction,multiSelect:!1,rippleEnabled:!1,avatarSize:46,peerId:e.peerId,placeholder:e.placeholder,selfPresence:e.selfPresence,managers:this.managers}),this.title.append(this.selector.input)}}var gs=i(6848);class vs extends k{init(){return e=this,t=void 0,s=function*(){let e;this.container.classList.add("edit-peer-container","user-permissions-container"),this.setTitle("UserRestrictions");{const t=new Br({name:"UserRestrictionsCanDo"}),i=document.createElement("div");i.classList.add("chatlist-container"),t.content.insertBefore(i,t.title);const s=gg.createChatList({new:!0});i.append(s);const{dom:n}=gg.addDialogNew({peerId:this.userId.toPeerId(!1),container:s,rippleEnabled:!0,avatarSize:48});n.lastMessageSpan.append(ce(yield this.managers.appUsersManager.getUser(this.userId)));const a=new ys({chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:t.content,participant:"channelParticipantBanned"===this.participant._?this.participant:void 0},this.managers);e=()=>{const e=a.takeOut();"channelParticipantBanned"===this.participant._&&(0,gs.Z)(this.participant.banned_rights.pFlags,e.pFlags)||this.managers.appChatsManager.editBanned(this.chatId,this.participant,e)},this.eventListener.addEventListener("destroy",e,{once:!0}),this.scrollable.append(t.container)}{const t=new Br({});if("channelParticipantBanned"===this.participant._){const i=(0,M.Z)("btn-primary btn-transparent danger",{icon:"delete",text:"GroupPermission.Delete"});(0,n.fc)(i,(()=>{const t=(0,mi.Z)([i],!0);this.managers.appChatsManager.clearChannelParticipantBannedRights(this.chatId,this.participant).then((()=>{this.eventListener.removeEventListener("destroy",e),this.close()}),(()=>{t()}))}),{listenerSetter:this.listenerSetter}),t.content.append(i)}const i=(0,M.Z)("btn-primary btn-transparent danger",{icon:"deleteuser",text:"UserRestrictionsBlock"});(0,n.fc)(i,(()=>{(0,mi.Z)([i],!0),this.managers.appChatsManager.kickFromChannel(this.chatId,this.participant).then((()=>{this.eventListener.removeEventListener("destroy",e),this.close()}))}),{listenerSetter:this.listenerSetter}),t.content.append(i),this.scrollable.append(t.container)}},new((i=void 0)||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}));var e,t,i,s}}var fs=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class ys{constructor(e,t){this.options=e,this.managers=t,this.construct()}construct(){return fs(this,void 0,void 0,(function*(){this.v=[{flags:["send_messages"],text:"UserRestrictionsSend",exceptionText:"UserRestrictionsNoSend"},{flags:["send_media"],text:"UserRestrictionsSendMedia",exceptionText:"UserRestrictionsNoSendMedia"},{flags:["send_stickers","send_gifs"],text:"UserRestrictionsSendStickers",exceptionText:"UserRestrictionsNoSendStickers"},{flags:["send_polls"],text:"UserRestrictionsSendPolls",exceptionText:"UserRestrictionsNoSendPolls"},{flags:["embed_links"],text:"UserRestrictionsEmbedLinks",exceptionText:"UserRestrictionsNoEmbedLinks"},{flags:["invite_users"],text:"UserRestrictionsInviteUsers",exceptionText:"UserRestrictionsNoInviteUsers"},{flags:["pin_messages"],text:"UserRestrictionsPinMessages",exceptionText:"UserRestrictionsNoPinMessages"},{flags:["change_info"],text:"UserRestrictionsChangeInfo",exceptionText:"UserRestrictionsNoChangeInfo"}],this.toggleWith={send_messages:["send_media","send_stickers","send_polls","embed_links"]};const e=this.options,t=yield this.managers.appChatsManager.getChat(e.chatId),i=t.default_banned_rights,s=e.participant?function(e,t){if(e.default_banned_rights){t=(0,Ji.Z)(t);const i=e.default_banned_rights.pFlags;for(const e in i)t.pFlags[e]=i[e]}return t}(t,e.participant.banned_rights):i,a=e.participant?"UserRestrictionsDisabled":"EditCantEditPermissionsPublic";for(const o of this.v){const r=o.flags[0];o.checkboxField=new ji.Z({text:o.text,checked:(0,Xi.Z)(t,r,s),restriction:!0,withRipple:!0}),(e.participant&&i.pFlags[r]||t.username&&(o.flags.includes("pin_messages")||o.flags.includes("change_info")))&&(o.checkboxField.input.disabled=!0,(0,n.fc)(o.checkboxField.label,(e=>{Ci(v.ZP.format(a,!0))}),{listenerSetter:e.listenerSetter})),this.toggleWith[r]&&e.listenerSetter.add(o.checkboxField.input)("change",(()=>{o.checkboxField.checked||this.v.filter((e=>this.toggleWith[r].includes(e.flags[0]))).forEach((e=>{e.checkboxField.checked=!1}))})),e.appendTo.append(o.checkboxField.label)}}))}takeOut(){const e={_:"chatBannedRights",until_date:2147483647,pFlags:{}};for(const t of this.v)!t.checkboxField.checked&&t.flags.forEach((t=>{e.pFlags[t]=!0}));return e}}class bs extends k{init(){return fs(this,void 0,void 0,(function*(){let e;this.container.classList.add("edit-peer-container","group-permissions-container"),this.setTitle("ChannelPermissions");{const t=new Br({name:"ChannelPermissionsHeader"});e=new ys({chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:t.content},this.managers),this.eventListener.addEventListener("destroy",(()=>{this.managers.appChatsManager.editChatDefaultBannedRights(this.chatId,e.takeOut())}),{once:!0}),this.scrollable.append(t.container)}{const t=new Br({name:"PrivacyExceptions"}),i=new Ni({titleLangKey:"ChannelAddException",subtitleLangKey:"Loading",icon:"adduser",clickable:()=>{new ms({peerTypes:["channelParticipants"],onSelect:e=>{setTimeout((()=>{a(e)}),0)},placeholder:"ExceptionModal.Search.Placeholder",peerId:-this.chatId})},listenerSetter:this.listenerSetter}),a=e=>fs(this,void 0,void 0,(function*(){let t;try{t=yield this.managers.appProfileManager.getChannelParticipant(this.chatId,e)}catch(e){return void Ci("User is no longer participant")}const i=this.slider.createTab(vs);i.participant=t,i.chatId=this.chatId,i.userId=e,i.open()}));t.content.append(i.container);const o=t.generateContentElement();o.classList.add("chatlist-container");const r=gg.createChatList({new:!0});o.append(r),(0,n.fc)(r,(e=>{const t=(0,l.Z)(e.target,dg);if(!t)return;const i=t.dataset.peerId.toPeerId();a(i)}),{listenerSetter:this.listenerSetter});const c=(t,i)=>fs(this,void 0,void 0,(function*(){const s=i.banned_rights,n=(yield this.managers.appChatsManager.getChat(this.chatId)).default_banned_rights,a=[];e.v.forEach((e=>{const t=e.flags[0];s.pFlags[t]&&!n.pFlags[t]&&a.push(e.exceptionText)}));const o=t.querySelector(".user-last-message");a.length&&(o.innerHTML="",o.append(...(0,v.v_)(a.map((e=>(0,v.ag)(e))),!1))),o.classList.toggle("hide",!a.length)})),d=(e,t)=>{const{dom:i}=gg.addDialogNew({peerId:(0,es.Z)(e.peer),container:r,rippleEnabled:!0,avatarSize:48,append:t});c(i.listEl,e)},h=()=>{(0,g.Z)(i.subtitle,(0,v.ag)(p?"Permissions.ExceptionsCount":"Permissions.NoExceptions",[p]))};let u,p=0;const m=()=>(u=new Yi({scrollable:this.scrollable,getPromise:()=>this.managers.appProfileManager.getChannelParticipants(this.chatId,{_:"channelParticipantsBanned",q:""},50,r.childElementCount).then((e=>{for(const t of e.participants)d(t,!0);return p=e.count,h(),e.participants.length<50||e.count===r.childElementCount}))}),u.load());this.scrollable.append(t.container),(yield this.managers.appChatsManager.isChannel(this.chatId))?yield m():(h(),this.listenerSetter.add(s.Z)("dialog_migrate",(({migrateFrom:e,migrateTo:t})=>{this.chatId===e&&(this.chatId=t,m())})))}}))}onOpenAfterTimeout(){this.scrollable.onScroll()}}class ws{constructor(e,t,i){this.peerId=e,this.peerType=t,this.onSelect=i,this.construct()}construct(){return e=this,t=void 0,s=function*(){let{peerId:e,peerType:t,onSelect:i}=this;const s=new Ot({peerId:e}).element,n=A.Z.MANAGERS;void 0===t&&(t=yield n.appPeersManager.getDialogType(e));const a=(t,s=h&&!!t.size)=>{let a=n.appChatsManager.leave(e.toChatId());s&&(a=a.finally((()=>n.appMessagesManager.flushHistory(e)))),i&&i(a)},o=t=>{let s;if(e.isUser())s=n.appMessagesManager.flushHistory(e,!1,h?!!t.size:void 0);else{if(!t.size)return a(t);s=n.appChatsManager.delete(e.toChatId())}i&&i(s)};let r,l,c,d,h;switch(t){case"channel":(yield n.appChatsManager.hasRights(e.toChatId(),"delete_chat"))?(r="ChannelDeleteMenu",l="AreYouSureDeleteAndExitChannel",d=[{langKey:"ChannelDeleteMenu",isDanger:!0,callback:o}],h=[{text:"DeleteChannelForAll"}]):(r="LeaveChannelMenu",l="ChannelLeaveAlertWithName",c=[s],d=[{langKey:"LeaveChannel",isDanger:!0,callback:a}]);break;case"chat":r="DeleteChatUser",l="AreYouSureDeleteThisChatWithUser",c=[s],d=[{langKey:"DeleteChatUser",isDanger:!0,callback:o}],h=[{text:"DeleteMessagesOptionAlso",textArgs:[new Ot({peerId:e}).element]}];break;case"saved":r="DeleteChatUser",l="AreYouSureDeleteThisChatSavedMessages",d=[{langKey:"DeleteChatUser",isDanger:!0,callback:o}];break;case"megagroup":case"group":(yield n.appChatsManager.hasRights(e.toChatId(),"delete_chat"))?(r="DeleteMegaMenu",l="AreYouSureDeleteAndExit",d=[{langKey:"DeleteMegaMenu",isDanger:!0,callback:o}],h=[{text:"DeleteChat.DeleteGroupForAll"}]):(r="LeaveMegaMenu",l="AreYouSureDeleteAndExitName",c=[s],d=[{langKey:"DeleteChatUser",isDanger:!0,callback:e=>a(e,!0)}])}new qi("popup-delete-chat",{peerId:e,titleLangKey:r,descriptionLangKey:l,descriptionLangArgs:c,buttons:d,checkboxes:h}).show()},new((i=void 0)||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}));var e,t,i,s}}var Ss=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Cs extends k{init(){var e;return Ss(this,void 0,void 0,(function*(){this.setTitle("Reactions");const t=yield this.managers.appReactionsManager.getActiveAvailableReactions(),i=yield this.managers.appProfileManager.getChatFull(this.chatId);let s=null!==(e=i.available_reactions)&&void 0!==e?e:[];const n=new Set(s),a=new Br({caption:(yield this.managers.appChatsManager.isBroadcast(this.chatId))?"EnableReactionsChannelInfo":"EnableReactionsGroupInfo"}),o=new ji.Z({toggle:!0,checked:!!n.size}),r=new Ni({checkboxField:o,titleLangKey:"EnableReactions",listenerSetter:this.listenerSetter});a.content.append(r.container);const l=new Br({name:"AvailableReactions"}),c=t.map((e=>{const t=new ji.Z({toggle:!0,checked:n.has(e.reaction)});this.listenerSetter.add(t.input)("change",(()=>{t.checked?(n.add(e.reaction),o.checked||o.setValueSilently(!0)):(n.delete(e.reaction),!n.size&&o.checked&&o.setValueSilently(!1)),h()}));const i=new Ni({checkboxField:t,title:e.title,havePadding:!0,listenerSetter:this.listenerSetter});return Oa({row:i,doc:e.static_icon,size:"small"}),l.content.append(i.container),t}));this.listenerSetter.add(r.checkboxField.input)("change",(()=>{o.checked?c.every((e=>!e.checked))&&(c.forEach((e=>e.checked=!0)),h()):(c.forEach((e=>e.checked=!1)),h())}));const d=()=>Ss(this,void 0,void 0,(function*(){const e=Array.from(n);if([...e].sort().join()===[...s].sort().join())return;const t=yield this.managers.appProfileManager.getCachedFullChat(this.chatId);t&&(t.available_reactions=e),this.managers.appChatsManager.setChatAvailableReactions(this.chatId,e),s=e})),h=(0,Ki.Z)(d,3e3,!1,!0);this.eventListener.addEventListener("destroy",d,{once:!0}),this.scrollable.append(a.container,l.container)}))}}var Ls=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Is extends P{_init(){var e;return Ls(this,void 0,void 0,(function*(){this.listenerSetter.removeAll(),this.scrollable.container.innerHTML="",null!==(e=this.tempId)&&void 0!==e||(this.tempId=0);const t=++this.tempId;this.container.classList.add("edit-peer-container","edit-group-container"),this.setTitle("Edit");let i=yield this.managers.appProfileManager.getChatFull(this.chatId,!0);const a=yield this.managers.appChatsManager.getChat(this.chatId),o=yield this.managers.appChatsManager.isBroadcast(this.chatId),r=yield this.managers.appChatsManager.isChannel(this.chatId),l=[],c=e=>{l.push(e)};this.listenerSetter.add(s.Z)("chat_update",(e=>{this.chatId===e&&l.forEach((e=>e()))})),this.listenerSetter.add(s.Z)("chat_full_update",(e=>Ls(this,void 0,void 0,(function*(){this.chatId===e&&(i=(yield this.managers.appProfileManager.getCachedFullChat(e))||i)}))));const d=this.chatId.toPeerId(!0),h=yield this.managers.appChatsManager.hasRights(this.chatId,"change_type"),u=yield this.managers.appChatsManager.hasRights(this.chatId,"change_permissions");{const e=new Br({noDelimiter:!0}),r=[],l=document.createElement("div");if(l.classList.add("input-wrapper"),this.chatNameInputField=new b.Z({label:o?"EnterChannelName":"CreateGroup.NameHolder",name:"chat-name",maxLength:255,required:!0}),this.descriptionInputField=new b.Z({label:"DescriptionPlaceholder",name:"chat-description",maxLength:255}),this.chatNameInputField.setOriginalValue(a.title),this.descriptionInputField.setOriginalValue(i.about),l.append(this.chatNameInputField.container,this.descriptionInputField.container),r.push(this.chatNameInputField,this.descriptionInputField),this.editPeer=new Ri({peerId:d,inputFields:r,listenerSetter:this.listenerSetter}),this.content.append(this.editPeer.nextBtn),e.content.append(this.editPeer.avatarEdit.container,l),h){const t=new Ni({titleLangKey:o?"ChannelType":"GroupType",clickable:()=>{const e=this.slider.createTab(Qi);e.chatId=this.chatId,e.chatFull=i,e.open(),this.listenerSetter.add(e.eventListener)("destroy",s)},icon:"lock",listenerSetter:this.listenerSetter}),s=()=>{let e;t.subtitle.textContent="",e=o?a.username?"TypePublic":"TypePrivate":a.username?"TypePublicGroup":"TypePrivateGroup",t.subtitle.append((0,v.ag)(e))};s(),e.content.append(t.container)}if(h||u){const s=new Ni({titleLangKey:"Reactions",icon:"reactions",clickable:()=>{const e=this.slider.createTab(Cs);e.chatId=this.chatId,e.open().then((()=>{this.tempId===t&&this.listenerSetter.add(e.eventListener)("destroy",a)}))},listenerSetter:this.listenerSetter}),n=(yield this.managers.appReactionsManager.getAvailableReactions()).filter((e=>!e.pFlags.inactive)).length,a=()=>{var e;const t=null!==(e=i.available_reactions)&&void 0!==e?e:[];s.subtitle.innerHTML=t.length+"/"+n};a(),e.content.append(s.container)}if(u&&!o){const t=["send_messages","send_media","send_stickers","send_polls","embed_links","invite_users","pin_messages","change_info"],i=new Ni({titleLangKey:"ChannelPermissions",clickable:()=>{const e=this.slider.createTab(bs);e.chatId=this.chatId,e.open()},icon:"permissions",listenerSetter:this.listenerSetter}),n=()=>Ls(this,void 0,void 0,(function*(){const e=yield this.managers.appChatsManager.getChatTyped(this.chatId);i.subtitle.innerHTML=t.reduce(((t,i)=>t+ +(0,Xi.Z)(e,i,e.default_banned_rights)),0)+"/"+t.length}));n(),e.content.append(i.container),this.listenerSetter.add(s.Z)("chat_update",(e=>{this.chatId===e&&n()}))}if(this.scrollable.append(e.container),(0,n.fc)(this.editPeer.nextBtn,(()=>{this.editPeer.nextBtn.disabled=!0;const e=[],t=this.chatId;this.chatNameInputField.isValidToChange()&&e.push(this.managers.appChatsManager.editTitle(t,this.chatNameInputField.value)),this.descriptionInputField.isValidToChange()&&e.push(this.managers.appChatsManager.editAbout(t,this.descriptionInputField.value)),this.editPeer.uploadAvatar&&e.push(this.editPeer.uploadAvatar().then((e=>this.managers.appChatsManager.editPhoto(t,e)))),Promise.race(e).finally((()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()}))}),{listenerSetter:this.listenerSetter}),o&&(yield this.managers.appChatsManager.hasRights(this.chatId,"change_info"))){const t=new ji.Z({text:"PeerInfo.SignMessages",checked:!!a.pFlags.signatures,withRipple:!0});this.listenerSetter.add(t.input)("change",(()=>{const e=t.toggleDisability(!0);this.managers.appChatsManager.toggleSignatures(this.chatId,t.checked).then((()=>{e()}))})),c((()=>{t.setValueSilently(!!a.pFlags.signatures)})),e.content.append(t.label)}}if(!o){const e=new Br({});if(!o&&h){const t=new ji.Z({text:"ChatHistory",withRipple:!0});this.listenerSetter.add(t.input)("change",(()=>{const e=t.toggleDisability(!0);this.managers.appChatsManager.togglePreHistoryHidden(this.chatId,!t.checked).then((()=>{e()}))}));const s=()=>{t.setValueSilently(r&&!i.pFlags.hidden_prehistory)};s(),c(s),e.content.append(t.label)}e.content.childElementCount&&this.scrollable.append(e.container)}if(yield this.managers.appChatsManager.hasRights(this.chatId,"delete_chat")){const e=new Br({}),t=(0,M.Z)("btn-primary btn-transparent danger",{icon:"delete",text:o?"PeerInfo.DeleteChannel":"DeleteAndExitButton"});(0,n.fc)(t,(()=>{new ws(d,void 0,(e=>{const i=(0,mi.Z)([t],!0);e.then((()=>{this.close()}),(()=>{i()}))}))}),{listenerSetter:this.listenerSetter}),e.content.append(t),this.scrollable.append(e.container)}r||this.listenerSetter.add(s.Z)("dialog_migrate",(({migrateFrom:e,migrateTo:t})=>{d===e&&(this.chatId=t.toChatId(),this._init())}))}))}init(){return this._init()}}var Ms=i(6272);function Es(e){return"+"+(0,Ms.u)(e).formatted}var Ps=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class ks extends P{init(){return Ps(this,void 0,void 0,(function*(){this.container.classList.add("edit-peer-container","edit-contact-container");const e=!(yield this.managers.appUsersManager.isContact(this.peerId.toUserId()));this.setTitle(e?"AddContactTitle":"Edit");{const t=new Br({noDelimiter:!0}),i=[],a=document.createElement("div");if(a.classList.add("input-wrapper"),this.nameInputField=new b.Z({label:"FirstName",name:"contact-name",maxLength:70,required:!0}),this.lastNameInputField=new b.Z({label:"LastName",name:"contact-lastname",maxLength:70}),this.peerId){const t=yield this.managers.appUsersManager.getUser(this.peerId);e?(this.nameInputField.setDraftValue(t.first_name),this.lastNameInputField.setDraftValue(t.last_name)):(this.nameInputField.setOriginalValue(t.first_name),this.lastNameInputField.setOriginalValue(t.last_name))}if(a.append(this.nameInputField.container,this.lastNameInputField.container),i.push(this.nameInputField,this.lastNameInputField),this.editPeer=new Ri({peerId:this.peerId,inputFields:i,listenerSetter:this.listenerSetter,doNotEditAvatar:!0}),this.content.append(this.editPeer.nextBtn),this.peerId){const i=document.createElement("div");i.classList.add("avatar-edit"),i.append(this.editPeer.avatarElem);const n=new ji.Z({text:"Notifications"});n.input.addEventListener("change",(e=>{e.isTrusted&&this.managers.appMessagesManager.togglePeerMute(this.peerId)})),this.listenerSetter.add(s.Z)("notify_settings",(e=>Ps(this,void 0,void 0,(function*(){if("notifyPeer"!==e.peer._)return;const t=(0,es.Z)(e.peer.peer);if(this.peerId===t){const t=!(yield this.managers.appNotificationsManager.isMuted(e.notify_settings));t!==n.checked&&(n.checked=t)}}))));const o=document.createElement("div");o.classList.add("profile-name"),o.append(new Ot({peerId:this.peerId}).element);const r=document.createElement("div");if(r.classList.add("profile-subtitle"),r.append((0,v.ag)("EditContact.OriginalName")),t.content.append(i,o,r,a),e){const e=yield this.managers.appUsersManager.getUser(this.peerId),i=new Ni({icon:"phone",titleLangKey:e.phone?void 0:"MobileHidden",title:e.phone?Es(e.phone):void 0,subtitleLangKey:e.phone?"Phone":"MobileHiddenExceptionInfo",subtitleLangArgs:e.phone?void 0:[new Ot({peerId:this.peerId}).element]});t.content.append(i.container)}else{const e=new Ni({checkboxField:n,listenerSetter:this.listenerSetter}),i=!(yield this.managers.appNotificationsManager.isPeerLocalMuted(this.peerId,!1));n.checked=i,t.content.append(e.container)}}else t.content.append(a);this.scrollable.append(t.container),(0,n.fc)(this.editPeer.nextBtn,(()=>Ps(this,void 0,void 0,(function*(){this.editPeer.nextBtn.disabled=!0,this.managers.appUsersManager.addContact(this.peerId,this.nameInputField.value,this.lastNameInputField.value,(yield this.managers.appUsersManager.getUser(this.peerId)).phone).finally((()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()}))}))),{listenerSetter:this.listenerSetter})}if(!e){const e=new Br({}),t=(0,M.Z)("btn-primary btn-transparent danger",{icon:"delete",text:"PeerInfo.DeleteContact"});(0,n.fc)(t,(()=>{new qi("popup-delete-contact",{peerId:this.peerId,titleLangKey:"DeleteContact",descriptionLangKey:"AreYouSureDeleteContact",buttons:(0,A.x)([{langKey:"Delete",callback:()=>{const e=(0,mi.Z)([t],!0);this.managers.appUsersManager.deleteContacts([this.peerId]).then((()=>{this.close()}),(()=>{e()}))},isDanger:!0}])}).show()}),{listenerSetter:this.listenerSetter}),e.content.append(t),this.scrollable.append(e.container)}}))}}class Ts extends P{init(){this.container.classList.add("add-members-container"),this.nextBtn=D({icon:"arrow_next"}),this.content.append(this.nextBtn),this.scrollable.container.remove(),this.nextBtn.addEventListener("click",(()=>{const e=this.selector.getSelected().map((e=>e.toPeerId()));if(this.skippable)this.takeOut(e),this.close();else{const t=this.takeOut(e);t instanceof Promise?this.attachToPromise(t):void 0===t&&this.close()}}))}attachToPromise(e){const t=(0,be.p)(this.nextBtn,"arrow_next");e.then((()=>{this.close()}),(()=>{t()}))}open(e){const t=super.open();this.setTitle(e.title),this.peerType=e.type,this.takeOut=e.takeOut,this.skippable=e.skippable;const i="privacy"===this.peerType;return this.selector=new ps({appendTo:this.content,onChange:this.skippable?null:e=>{this.nextBtn.classList.toggle("is-visible",!!e)},peerType:[i?"dialogs":"contacts"],placeholder:e.placeholder,exceptSelf:i,filterPeerTypeBy:i?["isAnyGroup","isUser"]:void 0,managers:this.managers}),e.selectedPeerIds&&this.selector.addInitial(e.selectedPeerIds),this.nextBtn.classList.add("tgico-arrow_next"),this.nextBtn.innerHTML="",this.nextBtn.disabled=!1,this.nextBtn.classList.toggle("is-visible",this.skippable),t}}var xs=i(2365),_s=i(1708),As=i(6074);const Zs=["#fc5c51","#0fb297","#d09306","#3d72ed","#895dd5","#cd4073","#00c1a6","#fa790f"],Fs=["red","green","yellow","blue","violet","pink","cyan","orange"],Ds=[0,7,4,1,6,3,5];function Rs(e,t=!0){if(!e)return"";const i=Ds[Math.abs(+e)%7];return(t?Fs:Zs)[i]}function Bs(e,t=!1){if(!e)return"";const i=e.trim().split(" ");if(!i[0])return"";const s=[...i[0]][0];if(t||1===i.length)return(0,Zt.Z)(s);const n=[...i[i.length-1]][0];return(0,Zt.Z)(s+n)}var Ns=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};function Us(e,t,i,n,a=new Image,o=!1){return Ns(this,void 0,void 0,(function*(){const o=yield s.Z.managers.acknowledged.appAvatarsManager.loadAvatar(t,i,n),r=o.result,l=o.cached;let c,d,h;if(a.classList.add("avatar-photo"),l)d=()=>{(0,g.Z)(e,a),e.dataset.color=""};else{const o=s.Z.settings.animationsEnabled;o&&a.classList.add("fade-in");let r=!1;if("photo_big"===n){const s=yield Us(e,t,i,"photo_small");c=s.loadPromise,h=s.thumbImage}else if(i.stripped_thumb){h=new Image,e.classList.add("avatar-relative"),h.classList.add("avatar-photo","avatar-photo-thumbnail");const t=it(i.stripped_thumb);c=Ze(h,t).then((()=>{r||(0,g.Z)(e,h)}))}d=()=>{r=!0,h?e.append(a):(0,g.Z)(e,a),setTimeout((()=>{e.childElementCount&&Te.Z.mutateElement(a,(()=>{e.dataset.color="",o&&a.classList.remove("fade-in"),h&&h.remove()}))}),o?200:0)}}const u=r.then((e=>Ze(a,e))).then(d);return yield c||u,{cached:l,loadPromise:c||u,thumbImage:h}}))}function Os(e,t,i,s){(0,c.Z)(e,t),e.dataset.color=i,e.classList.remove("tgico-saved","tgico-deletedaccount","tgico-reply_filled"),s&&e.classList.add(s)}function Hs(e,t,i=!1,n="",a=!1,o){return Ns(this,void 0,void 0,(function*(){const r=s.Z.myId;if(t===r&&i)return void Os(e,"","","tgico-saved");const l=s.Z.managers;if(t!==le.NM&&t.isUser()){const i=yield l.appUsersManager.getUser(t);if(i&&i.pFlags&&i.pFlags.deleted)return void Os(e,"",Rs(t),"tgico-deletedaccount")}const c=o?"photo_big":"photo_small",d=yield l.appPeersManager.getPeerPhoto(t),h=!!d,u=!!e.firstElementChild&&!e.firstElementChild.classList.contains("emoji");if(!h||!u||!(yield l.appAvatarsManager.isAvatarCached(t,c))){let a="";if(!t||t===r&&i||(a=Rs(t)),t===le.hj)return void Os(e,"",a,"tgico-reply_filled");const o=yield n?Bs(n):function(e,t=s.Z.managers){var i,n,a,o,r;return n=this,a=void 0,r=function*(){const s=yield t.appPeersManager.getPeer(e);return Bs(null!==(i=s.title)&&void 0!==i?i:[s.first_name,s.last_name].filter(Boolean).join(" "))},new((o=void 0)||(o=Promise))((function(e,t){function i(e){try{l(r.next(e))}catch(e){t(e)}}function s(e){try{l(r.throw(e))}catch(e){t(e)}}function l(t){var n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o((function(e){e(n)}))).then(i,s)}l((r=r.apply(n,a||[])).next())}))}(t,l);Os(e,o,a,"")}return h?Us(e,t,d,c,void 0,a):void 0}))}const zs=e=>e.touches?e.touches[0]:e,Gs=window;let Vs=!1;Ii.addEventListener("toggle",(e=>{Vs=e}));class Ks{constructor(e){this.cursor="grabbing",this.cancelEvent=!0,this.listenerOptions=!1,this.hadMove=!1,this.xDown=null,this.yDown=null,this.reset=e=>{gi.Z?Gs.removeEventListener("touchmove",this.handleMove,{capture:!0}):(Gs.removeEventListener("mousemove",this.handleMove),this.setCursorTo.style.cursor=""),this.onReset&&this.hadMove&&this.onReset(),this.xDown=this.yDown=null,this.hadMove=!1},this.handleStart=e=>{return t=this,i=void 0,n=function*(){const t=zs(e);if(this.verifyTouchTarget&&!(yield this.verifyTouchTarget(e)))return this.reset();this.xDown=t.clientX,this.yDown=t.clientY,gi.Z?Gs.addEventListener("touchmove",this.handleMove,{passive:!1,capture:!0}):Gs.addEventListener("mousemove",this.handleMove,!1)},new((s=void 0)||(s=Promise))((function(e,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,r)}l((n=n.apply(t,i||[])).next())}));var t,i,s,n},this.handleMove=e=>{if(null===this.xDown||null===this.yDown||Vs)return void this.reset();this.cancelEvent&&(0,a.Z)(e);const t=zs(e),i=t.clientX,s=t.clientY,n=this.xDown-i,o=this.yDown-s;if(!this.hadMove){if(!n&&!o)return;this.hadMove=!0,gi.Z||this.setCursorTo.style.setProperty("cursor",this.cursor,"important"),this.onFirstSwipe&&this.onFirstSwipe()}const r=this.onSwipe(n,o,e);void 0!==r&&r&&this.reset()},(0,x.Z)(this,e),this.setCursorTo=this.element,this.setListeners()}setListeners(){gi.Z?(this.element.addEventListener("touchstart",this.handleStart,this.listenerOptions),Gs.addEventListener("touchend",this.reset)):(this.element.addEventListener("mousedown",this.handleStart,this.listenerOptions),Gs.addEventListener("mouseup",this.reset))}removeListeners(){gi.Z?(this.element.removeEventListener("touchstart",this.handleStart,this.listenerOptions),Gs.removeEventListener("touchend",this.reset)):(this.element.removeEventListener("mousedown",this.handleStart,this.listenerOptions),Gs.removeEventListener("mouseup",this.reset))}setCursor(e){this.cursor=e,!gi.Z&&this.hadMove&&this.setCursorTo.style.setProperty("cursor",this.cursor,"important")}}var Ws=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class $s{constructor(e,t){this.scrollable=e,this.managers=t,this.processItem=e=>Ws(this,void 0,void 0,(function*(){const t=document.createElement("div");let i;t.classList.add($s.BASE_CLASS+"-avatar","media-container","hide"),this.avatars.append(t),e&&(i="object"!=typeof e?yield this.managers.appPhotosManager.getPhoto(e):e.action.photo);const s=new Image;s.classList.add("avatar-photo"),s.draggable=!1;const n=()=>Ws(this,void 0,void 0,(function*(){if(i){const e=yield dt({container:t,photo:i,size:Le(i,420,420,!1),withoutPreloader:!0});[e.images.thumb,e.images.full].filter(Boolean).forEach((e=>{e.classList.add("avatar-photo")}))}else{const e=yield this.managers.appPeersManager.getPeerPhoto(this.peerId);yield Us(t,this.peerId,e,"photo_big",s)}t.classList.remove("hide")}));return this.avatars.childElementCount<=3?yield n():(this.intersectionObserver.observe(t),this.loadCallbacks.set(t,n)),this.addTab(),e})),this.container=document.createElement("div"),this.container.classList.add($s.BASE_CLASS+"-container"),this.avatars=document.createElement("div"),this.avatars.classList.add($s.BASE_CLASS+"-avatars"),this.gradient=document.createElement("div"),this.gradient.classList.add($s.BASE_CLASS+"-gradient"),this.info=document.createElement("div"),this.info.classList.add($s.BASE_CLASS+"-info"),this.tabs=document.createElement("div"),this.tabs.classList.add($s.BASE_CLASS+"-tabs"),this.arrowPrevious=document.createElement("div"),this.arrowPrevious.classList.add($s.BASE_CLASS+"-arrow","tgico-avatarprevious"),this.arrowNext=document.createElement("div"),this.arrowNext.classList.add($s.BASE_CLASS+"-arrow",$s.BASE_CLASS+"-arrow-next","tgico-avatarnext"),this.container.append(this.avatars,this.gradient,this.info,this.tabs,this.arrowPrevious,this.arrowNext),this.loadCallbacks=new Map,this.listenerSetter=new I.Z;const i=()=>0===this.scrollable.scrollTop||(this.scrollable.scrollIntoViewNew({element:this.scrollable.container.firstElementChild,position:"start"}),!1),s=1/3;let o=!1,r=!1;(0,n.fc)(this.container,(e=>Ws(this,void 0,void 0,(function*(){if(r)return void(0,a.Z)(e);if(o)return void(o=!1);if(!i())return;const t=this.container.getBoundingClientRect(),n=e.pageX,l=n-t.left;if(!this.listLoader.previous.length&&!this.listLoader.next.length||l>t.width*s&&l<t.width-t.width*s){const e=this.peerId,t=[];this.listLoader.previous.concat(this.listLoader.current,this.listLoader.next).forEach(((e,i)=>{t.push({element:this.avatars.children[i],item:e})}));const i=t.slice(0,this.listLoader.previous.length),s=t.slice(this.listLoader.previous.length+1),n=this.avatars.children[this.listLoader.previous.length];r=!0,Gm(n,e,(()=>e===this.peerId),this.listLoader.current,i,s),r=!1}else{const e=n>t.right-t.width/2;let i;this.avatars.classList.add("no-transition"),this.avatars.offsetLeft,i=0!==this.listLoader.index||e?this.listLoader.index===this.listLoader.count-1&&e?-(this.listLoader.count-1):e?1:-1:this.listLoader.count-1,this.listLoader.go(i),(0,Be.T2)((()=>{this.avatars.classList.remove("no-transition")}))}}))),{listenerSetter:this.listenerSetter});const l=()=>{o=!0,document.body.addEventListener(gi.Z?"touchend":"click",(e=>{o=!1}),{once:!0})};let c=0,d=0,h=0,u=0;this.swipeHandler=new Ks({element:this.avatars,onSwipe:(e,t)=>{h=e;let i=d+e*-$s.SCALE;return i>0?i=0:i<u&&(i=u),this.avatars.style.transform=$s.TRANSLATE_TEMPLATE.replace("{x}",i+"px"),!1},verifyTouchTarget:e=>i()?!this.container.classList.contains("is-single")&&!r:(l(),(0,a.Z)(e),!1),onFirstSwipe:()=>{const e=this.avatars.getBoundingClientRect();c=e.width,u=-c*(this.tabs.childElementCount-1),d=e.left-this.container.getBoundingClientRect().left,this.avatars.style.transform=$s.TRANSLATE_TEMPLATE.replace("{x}",d+"px"),this.container.classList.add("is-swiping"),this.avatars.classList.add("no-transition"),this.avatars.offsetLeft},onReset:()=>{const e=Math.ceil(Math.abs(h)/(c/$s.SCALE))*(h>=0?1:-1);l(),this.avatars.classList.remove("no-transition"),(0,Be.T2)((()=>{this.listLoader.go(e),this.container.classList.remove("is-swiping")}))}}),this.intersectionObserver=new IntersectionObserver((e=>{e.forEach((e=>{e.isIntersecting&&this.loadNearestToTarget(e.target)}))}))}setPeer(e){return Ws(this,void 0,void 0,(function*(){this.peerId=e;const t=yield this.managers.appPeersManager.getPeerPhoto(e);if(!t)return;const i=this.listLoader=new As.Z({loadCount:50,loadMore:(t,s,n)=>{if(!s)return Promise.resolve({count:void 0,items:[]});if(e.isUser()){const i=t;return this.managers.appPhotosManager.getUserPhotos(e,i,n).then((e=>({count:e.count,items:e.photos})))}{const t=[];return i.current||t.push(this.managers.appProfileManager.getChatFull(e.toChatId())),t.push(this.managers.appMessagesManager.getSearch({peerId:e,maxId:Number.MAX_SAFE_INTEGER,inputFilter:{_:"inputMessagesFilterChatPhotos"},limit:n,backLimit:0})),Promise.all(t).then((e=>Ws(this,void 0,void 0,(function*(){const t=e.pop();if((0,_s.Z)(t),!i.current){const s=e[0],n=(0,ge.Z)(t.history,(e=>e.action.photo.id===s.chat_photo.id));i.current=n||(yield this.managers.appMessagesManager.generateFakeAvatarMessage(this.peerId,s.chat_photo))}return{count:t.count,items:t.history}}))))}},processItem:this.processItem,onJump:(e,t)=>{const i=this.listLoader.index,s=100*$s.SCALE*i;this.avatars.style.transform=$s.TRANSLATE_TEMPLATE.replace("{x}",`-${s}%`);const n=this.tabs.querySelector(".active");n&&n.classList.remove("active"),this.tabs.children[i].classList.add("active"),this.loadNearestToTarget(this.avatars.children[i])}});"userProfilePhoto"===t._&&(i.current=t.photo_id),yield this.processItem(i.current),i.load(!0)}))}addTab(){const e=document.createElement("div");e.classList.add($s.BASE_CLASS+"-tab"),this.tabs.append(e),1===this.tabs.childElementCount&&e.classList.add("active"),this.container.classList.toggle("is-single",this.tabs.childElementCount<=1)}loadNearestToTarget(e){const t=Array.from(e.parentElement.children),i=t.indexOf(e);t.slice(Math.max(0,i-3),Math.min(t.length,i+3)).forEach((e=>{const t=this.loadCallbacks.get(e);t&&(t(),this.loadCallbacks.delete(e),this.intersectionObserver.unobserve(e))}))}cleanup(){var e;this.listenerSetter.removeAll(),this.swipeHandler.removeListeners(),null===(e=this.intersectionObserver)||void 0===e||e.disconnect()}}$s.BASE_CLASS="profile-avatars",$s.SCALE=xs.Z?2:1,$s.TRANSLATE_TEMPLATE=xs.Z?`translate3d({x}, 0, -1px) scale(${$s.SCALE})`:"translate({x}, 0)";function js(e){return t=this,i=void 0,n=function*(){const t=new Ot;return yield t.update(e),t.element},new((s=void 0)||(s=Promise))((function(e,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,r)}l((n=n.apply(t,i||[])).next())}));var t,i,s,n}var qs=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const Qs=(e,t)=>{(0,c.Z)(t.title,e||""),t.container.style.display=e?"":"none"};class Ys{constructor(e,t,i,n=!0){this.managers=e,this.scrollable=t,this.listenerSetter=i,this.isDialog=n,this.setPeerStatus=(e=!1)=>{const t=this.peerId;if(this.element.classList.toggle("is-me",t===s.Z.myId),t&&(s.Z.myId!==t||!this.isDialog))return _m.setPeerStatus(t,this.subtitle,e,!0,(()=>t===this.peerId),!this.isDialog).then((e=>{e&&e()}))},xs.Z||this.scrollable.container.classList.add("no-parallax"),i||(this.listenerSetter=new I.Z)}init(){this.init=null,this.element=document.createElement("div"),this.element.classList.add("profile-content"),this.section=new Br({noDelimiter:!0}),this.avatar=new Wm,this.avatar.classList.add("profile-avatar","avatar-120"),this.avatar.isDialog=this.isDialog,this.avatar.attachClickEvent(),this.name=document.createElement("div"),this.name.classList.add("profile-name"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("profile-subtitle"),this.bio=new Ni({title:" ",subtitleLangKey:"UserBio",icon:"info",clickable:e=>qs(this,void 0,void 0,(function*(){"A"!==e.target.tagName&&(Oi((yield this.managers.appProfileManager.getProfileByPeerId(this.peerId)).about),Ci(v.ZP.format("BioCopied",!0)))})),listenerSetter:this.listenerSetter}),this.bio.title.classList.add("pre-wrap"),this.username=new Ni({title:" ",subtitleLangKey:"Username",icon:"username",clickable:()=>qs(this,void 0,void 0,(function*(){Oi("@"+(yield this.managers.appPeersManager.getPeer(this.peerId)).username),Ci(v.ZP.format("UsernameCopied",!0))})),listenerSetter:this.listenerSetter}),this.phone=new Ni({title:" ",subtitleLangKey:"Phone",icon:"phone",clickable:()=>qs(this,void 0,void 0,(function*(){Oi("+"+(yield this.managers.appUsersManager.getUser(this.peerId)).phone),Ci(v.ZP.format("PhoneCopied",!0))})),listenerSetter:this.listenerSetter}),this.link=new Ni({title:" ",subtitleLangKey:"SetUrlPlaceholder",icon:"link",clickable:()=>{Oi(this.link.title.textContent),Ci(v.ZP.format("LinkCopied",!0))},listenerSetter:this.listenerSetter}),this.location=new Ni({title:" ",subtitleLangKey:"ChatLocation",icon:"location"}),this.section.content.append(this.phone.container,this.username.container,this.location.container,this.bio.container,this.link.container);const{listenerSetter:e}=this;this.isDialog&&(this.notifications=new Ni({checkboxField:new ji.Z({toggle:!0}),titleLangKey:"Notifications",icon:"unmute",listenerSetter:this.listenerSetter}),e.add(this.notifications.checkboxField.input)("change",(e=>{e.isTrusted&&this.managers.appMessagesManager.togglePeerMute(this.peerId)})),e.add(s.Z)("dialog_notify_settings",(e=>qs(this,void 0,void 0,(function*(){if(this.peerId===e.peerId){const e=yield this.managers.appNotificationsManager.isPeerLocalMuted(this.peerId,!1);this.notifications.checkboxField.checked=!e}})))),this.section.content.append(this.notifications.container)),this.element.append(this.section.container),xs.Z&&this.element.append(Ur()),e.add(s.Z)("peer_typings",(({peerId:e})=>{this.peerId===e&&this.setPeerStatus()})),e.add(s.Z)("peer_bio_edit",(e=>{e===this.peerId&&this.setMoreDetails(!0)})),e.add(s.Z)("peer_title_edit",(e=>{e===this.peerId&&this.fillUsername()})),e.add(s.Z)("user_update",(e=>{this.peerId===e.toPeerId()&&this.setPeerStatus()})),e.add(s.Z)("contacts_update",(e=>qs(this,void 0,void 0,(function*(){this.peerId===e.toPeerId()&&((yield this.managers.appUsersManager.getUser(e)).pFlags.self&&this.isDialog||this.fillUserPhone())})))),e.add(s.Z)("avatar_update",(e=>{this.peerId===e&&this.setAvatar()})),this.setPeerStatusInterval=window.setInterval(this.setPeerStatus,6e4)}cleanupHTML(){[this.bio,this.phone,this.username,this.location,this.link].forEach((e=>{e.container.style.display="none"})),this.notifications&&(this.notifications.container.style.display="",this.notifications.checkboxField.checked=!0),this.clearSetMoreDetailsTimeout()}canBeDetailed(){return this.peerId!==s.Z.myId||!this.isDialog}setAvatar(){return qs(this,void 0,void 0,(function*(){if(this.canBeDetailed()&&(yield this.managers.appPeersManager.getPeerPhoto(this.peerId))){const e=this.avatars;return this.avatars=new $s(this.scrollable,this.managers),yield this.avatars.setPeer(this.peerId),this.avatars.info.append(this.name,this.subtitle),this.avatar.remove(),e?e.container.replaceWith(this.avatars.container):this.element.prepend(this.avatars.container),void(xs.Z&&this.scrollable.container.classList.add("parallax"))}xs.Z&&this.scrollable.container.classList.remove("parallax"),this.avatars&&(this.avatars.container.remove(),this.avatars.cleanup(),this.avatars=void 0),yield this.avatar.updateWithOptions({peerId:this.peerId}),this.section.content.prepend(this.avatar,this.name,this.subtitle)}))}fillUsername(){return qs(this,void 0,void 0,(function*(){const{peerId:e}=this;if(e.isUser()&&this.canBeDetailed()){const t=yield this.managers.appPeersManager.getPeerUsername(e);return Qs(t,this.username)}}))}fillUserPhone(){return qs(this,void 0,void 0,(function*(){const{peerId:e}=this;if(e.isUser()&&this.canBeDetailed()){const t=yield this.managers.appUsersManager.getUser(e);return Qs(t.phone?Es(t.phone):void 0,this.phone)}}))}fillNotifications(){return qs(this,void 0,void 0,(function*(){const e=this.notifications;if(e)if(this.canBeDetailed()){const t=yield this.managers.appNotificationsManager.isPeerLocalMuted(this.peerId,!1);e.checkboxField.checked=!t}else(0,Be.T2)((()=>{e.container.style.display="none"}))}))}fillRows(){return qs(this,void 0,void 0,(function*(){const e=this.peerId;yield Promise.all([this.fillUsername(),this.fillUserPhone(),this.fillNotifications(),this.setMoreDetails(),(()=>qs(this,void 0,void 0,(function*(){const[t]=yield Promise.all([js({peerId:e,dialog:this.isDialog,withIcons:!0})]);(0,g.Z)(this.name,t)})))(),this.setPeerStatus(!0)])}))}fillProfileElements(){return qs(this,void 0,void 0,(function*(){this.cleaned&&(this.cleaned=!1,this.cleanupHTML(),yield Promise.all([this.setAvatar(),this.fillRows()]))}))}_setMoreDetails(e,t){return qs(this,void 0,void 0,(function*(){if(Qs(t.about?(0,ii.Z)(t.about):void 0,this.bio),!e.isUser()){const i=yield this.managers.appChatsManager.getChat(e.toChatId());if(i.username)Qs("https://t.me/"+i.username,this.link);else{const e=t.exported_invite;"chatInviteExported"===(null==e?void 0:e._)&&Qs(e.link,this.link)}}const i=t.location;"channelLocation"==(null==i?void 0:i._)&&Qs(i.address,this.location),this.setMoreDetailsTimeout=window.setTimeout((()=>this.setMoreDetails(!0)),6e4)}))}setMoreDetails(e){return qs(this,void 0,void 0,(function*(){this.clearSetMoreDetailsTimeout();const t=this.peerId,i=this.threadId;if(!t||(yield this.managers.appPeersManager.isRestricted(t))||!this.canBeDetailed())return;const s=yield this.managers.acknowledged.appProfileManager.getProfileByPeerId(t,e),n=s.result.then((e=>qs(this,void 0,void 0,(function*(){this.peerId!==t||this.threadId!==i||(yield this.managers.appPeersManager.isRestricted(t))||(yield this._setMoreDetails(t,e))}))));s.cached&&(yield n)}))}setPeer(e,t=0){this.peerId===e&&this.threadId===t||(this.init&&this.init(),this.peerId=e,this.threadId=t,this.cleaned=!0)}clearSetMoreDetailsTimeout(){void 0!==this.setMoreDetailsTimeout&&(clearTimeout(this.setMoreDetailsTimeout),this.setMoreDetailsTimeout=void 0)}destroy(){var e;this.clearSetMoreDetailsTimeout(),clearInterval(this.setPeerStatusInterval),null===(e=this.avatars)||void 0===e||e.cleanup()}}var Js=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const Xs={};class en extends P{constructor(e){super(e,!1),this.threadId=0}init(){this.container.classList.add("shared-media-container","profile-container");const e=(0,M.Z)("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);const i=document.createElement("div");i.className="transition slide-fade";const a=document.createElement("div");a.classList.add("transition-item"),this.title.append((0,v.ag)("Profile")),this.editBtn=E("edit"),a.append(this.title,this.editBtn);const o=document.createElement("div");o.classList.add("transition-item");const r=this.title.cloneNode();r.append((0,v.ag)("PeerInfo.SharedMedia")),o.append(r),i.append(a,o),this.header.append(i),this.profile=new Ys(this.managers,this.scrollable,this.listenerSetter),this.profile.init(),this.scrollable.append(this.profile.element),this.scrollable.onAdditionalScroll=()=>{const e=this.searchSuper.nav.getBoundingClientRect();if(!e.width)return;const t=e.top-1;l(t<=56)};const l=e=>{t.classList.toggle("state-back",e),this.searchSuper.container.classList.toggle("is-full-viewport",e),c(+e),e||this.searchSuper.cleanScrollPositions()},c=(0,S.v)(i,"slide-fade",400,null,!1);c(0),(0,n.fc)(this.closeBtn,(e=>{this.closeBtn.firstElementChild.classList.contains("state-back")?(this.scrollable.scrollIntoViewNew({element:this.scrollable.container.firstElementChild,position:"start"}),c(0),t.classList.remove("state-back")):this.scrollable.isHeavyAnimationInProgress||this.slider.onCloseBtnClick()}),{listenerSetter:this.listenerSetter}),(0,n.fc)(this.editBtn,(e=>{let t;t=this.peerId.isAnyChat()?this.slider.createTab(Is):this.slider.createTab(ks),t&&(t instanceof Is?t.chatId=this.peerId.toChatId():t.peerId=this.peerId,t.open())}),{listenerSetter:this.listenerSetter}),this.listenerSetter.add(s.Z)("contacts_update",(e=>{this.peerId===e&&this.toggleEditBtn()})),this.listenerSetter.add(s.Z)("chat_update",(e=>{this.peerId===e.toPeerId(!0)&&this.toggleEditBtn()})),this.listenerSetter.add(s.Z)("history_multiappend",(e=>{this.renderNewMessages(e)})),this.listenerSetter.add(s.Z)("history_delete",(({peerId:e,msgs:t})=>{this.deleteDeletedMessages(e,Array.from(t))})),this.listenerSetter.add(s.Z)("message_sent",(({message:e})=>{this.renderNewMessages(e)})),this.searchSuper=new uo({mediaTabs:[{inputFilter:"inputMessagesFilterEmpty",name:"PeerMedia.Members",type:"members"},{inputFilter:"inputMessagesFilterPhotoVideo",name:"SharedMediaTab2",type:"media"},{inputFilter:"inputMessagesFilterDocument",name:"SharedFilesTab2",type:"files"},{inputFilter:"inputMessagesFilterUrl",name:"SharedLinksTab2",type:"links"},{inputFilter:"inputMessagesFilterMusic",name:"SharedMusicTab2",type:"music"},{inputFilter:"inputMessagesFilterRoundVoice",name:"SharedVoiceTab2",type:"voice"}],scrollable:this.scrollable,onChangeTab:e=>{const t="members"===e.type&&s.Z.settings.animationsEnabled?250:0;setTimeout((()=>{d.classList.toggle("is-hidden","members"!==e.type)}),t)},managers:this.managers}),this.searchSuper.scrollStartCallback=()=>{l(!0)},this.profile.element.append(this.searchSuper.container);const d=D({icon:"addmember_filled"});this.content.append(d),(0,n.fc)(d,(()=>Js(this,void 0,void 0,(function*(){const e=this.peerId,t=this.peerId.toChatId(),i=yield this.managers.appChatsManager.isChannel(t),s=(t,s)=>{let n,a,o,r,l;if(t.length>1)n="AddMembersAlertTitle",a=[(0,v.ag)("Members",[t.length])],o="AddMembersAlertCountText",r=t.map((e=>{const t=document.createElement("b");return t.append(new Ot({peerId:e}).element),t})),i||(l=[{text:"AddMembersForwardMessages",checked:!0}]);else{n="AddOneMemberAlertTitle",o="AddMembersAlertNamesText";const e=document.createElement("b");e.append(new Ot({peerId:t[0]}).element),r=[e],i||(l=[{text:"AddOneMemberForwardMessages",textArgs:[new Ot({peerId:t[0]}).element],checked:!0}])}r.push(new Ot({peerId:e}).element),new qi("popup-add-members",{peerId:e,titleLangKey:n,descriptionLangKey:o,descriptionLangArgs:r,buttons:[{langKey:"Add",callback:s}],checkboxes:l}).show()},n=e=>{"USER_PRIVACY_RESTRICTED"===e.type&&Li({langPackKey:"InviteToGroupError"})};if(i){const e=this.slider.createTab(Ts);e.open({type:"channel",skippable:!1,takeOut:i=>(s(i,(()=>{const s=this.managers.appChatsManager.inviteToChannel(t,i);s.catch(n),e.attachToPromise(s)})),!1),title:"GroupAddMembers",placeholder:"SendMessageTo"})}else new ms({peerTypes:["contacts"],placeholder:"Search",onSelect:e=>{setTimeout((()=>{s([e],(i=>{this.managers.appChatsManager.addChatUser(t,e,i.size?void 0:0).catch(n)}))}),0)}})}))),{listenerSetter:this.listenerSetter})}renderNewMessages(e){return Js(this,void 0,void 0,(function*(){if(this.init)return;const{peerId:t}=e;if(Xs[t])for(const i of this.searchSuper.mediaTabs){const s=i.inputFilter,n=Xs[t][s];if(!n)continue;const a=this.searchSuper.filterMessagesByType([e],s).filter((e=>!n.find((t=>t.mid===e.mid&&t.peerId===e.peerId))));a.length&&(n.unshift(...a.map((e=>({mid:e.mid,peerId:e.peerId})))),this.peerId===t&&-1!==this.searchSuper.usedFromHistory[s]&&(this.searchSuper.usedFromHistory[s]+=a.length,this.searchSuper.performSearchResult(a,i,!1)))}}))}deleteDeletedMessages(e,t){if(!this.init&&Xs[e]){for(const i of t)for(const t of this.searchSuper.mediaTabs){const s=t.inputFilter,n=Xs[e][s];if(!n)continue;const a=n.findIndex((e=>e.mid===i));if(-1!==a&&(n.splice(a,1),this.peerId===e)){const t=this.searchSuper.tabs[s].querySelector(`[data-mid="${i}"][data-peer-id="${e}"]`);t&&(this.searchSuper.selection.isSelecting&&this.searchSuper.selection.toggleByElement(t),t.remove()),this.searchSuper.usedFromHistory[s]>=a+1&&--this.searchSuper.usedFromHistory[s]}}this.scrollable.onScroll()}}cleanupHTML(){return Js(this,void 0,void 0,(function*(){this.profile.cleanupHTML(),this.editBtn.classList.add("hide"),this.searchSuper.cleanupHTML(!0),this.container.classList.toggle("can-add-members",(yield this.searchSuper.canViewMembers())&&(yield this.managers.appChatsManager.hasRights(this.peerId.toChatId(),"invite_users")))}))}setLoadMutex(e){this.searchSuper.loadMutex=e}setPeer(e,t=0){var i;return(this.peerId!==e||this.threadId!==t)&&(this.peerId=e,this.threadId=t,this.peerChanged=!0,this.init&&(this.init(),this.init=null),this.searchSuper.setQuery({peerId:e,historyStorage:null!==(i=Xs[e])&&void 0!==i?i:Xs[e]={}}),this.profile.setPeer(e,t),!0)}fillProfileElements(){return Js(this,void 0,void 0,(function*(){this.peerChanged&&(this.peerChanged=!1,yield this.cleanupHTML(),yield this.toggleEditBtn(),yield this.profile.fillProfileElements())}))}toggleEditBtn(){return Js(this,void 0,void 0,(function*(){let e;e=this.peerId.isUser()?this.peerId!==s.Z.myId&&(yield this.managers.appUsersManager.isContact(this.peerId.toUserId())):yield this.managers.appChatsManager.hasRights(this.peerId.toChatId(),"change_info"),this.editBtn.classList.toggle("hide",!e)}))}loadSidebarMedia(e,t){this.searchSuper.load(e,t)}onOpenAfterTimeout(){this.scrollable.onScroll()}destroy(){this.destroyable=!0,this.onCloseAfterTimeout(),this.profile.destroy(),this.searchSuper.destroy()}}const tn="is-right-column-shown",sn=new class extends _{constructor(){super({sidebarEl:document.getElementById("column-right"),canHideFirst:!0,navigationType:"right"}),this.isColumnProportionSet=!1}construct(e){this.managers=e,d.Z.addEventListener("changeScreen",((e,t)=>{t===d._.medium&&e!==d._.mobile&&this.toggleSidebar(!1)})),d.Z.addEventListener("resize",(()=>{this.setColumnProportion()}))}createSharedMediaTab(){const e=this.createTab(en,!0);return e.slider=this,e}replaceSharedMediaTab(e){const t=this.sharedMediaTab;if(t){const i=this.historyTabIds.indexOf(t);this._selectTab.getFrom()===t.container&&this._selectTab.setFrom(e.container),e?(-1!==i&&(this.historyTabIds[i]=e),t.container.classList.contains("active")&&e.container.classList.add("active"),t.container.replaceWith(e.container)):(-1!==i&&this.historyTabIds.splice(i,1),t.container.remove())}else this.tabsContainer.prepend(e.container);this.sharedMediaTab=e}onCloseTab(e,t,i){this.historyTabIds.length||this.toggleSidebar(!1,t),super.onCloseTab(e,t,i)}setColumnProportion(){const e=this.sidebarEl.scrollWidth/this.sidebarEl.previousElementSibling.scrollWidth;document.documentElement.style.setProperty("--right-column-proportion",""+e)}toggleSidebar(e,t){const i=document.body.classList.contains(tn);let s;if(void 0!==e?e?i||(s=!0):i&&(s=!0):s=!0,!s)return Promise.resolve();i||this.historyTabIds.length||this.sharedMediaTab.open(),this.isColumnProportionSet||(this.setColumnProportion(),this.isColumnProportionSet=!0);const n=_m.selectTab(i?1:2,t);return document.body.classList.toggle(tn,e),n}};R.GO.appSidebarRight=sn;const nn=sn;class an{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 e=t.boundingClientRect,i=t.target.parentElement,s=t.rootBounds;e.bottom<s.top&&this.handler(!0,i),e.bottom>=s.top&&e.bottom<s.bottom&&this.handler(!1,i)}}),{threshold:0,root:this.container})}observeElements(){this.elementsObserver=new IntersectionObserver((e=>{const t=e.filter((e=>e.boundingClientRect.top<e.rootBounds.top)).sort(((e,t)=>e.boundingClientRect.top-t.boundingClientRect.top))[0];if(!t)return;const i=t.isIntersecting?t.target:t.target.nextElementSibling;this.handler(!0,i)}),{root:this.container})}addSentinel(e,t){const i=document.createElement("div");return i.classList.add("sticky_sentinel",t),e.appendChild(i)}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)}}var on=i(5418),rn=i(9976),ln=i(8799),cn=i(3447),dn=i(7746);function hn(e){return{_:"messageEntityEmoji",offset:0,length:e.length,unicode:(0,pi.w1)(e).join("-").replace(/-?fe0f/g,"")}}const un=new Set;function pn(e,t,i=!1,n=!1){var a;const o=document.createElement("span");let r;if(o.classList.add("super-emoji"),n&&!rn.Z?r=function(e){return(0,ii.Z)(e,{entities:[hn(e)]})}(e):(e=(0,dn.Z)(e),r=(0,Zt.Z)(e)),o.append(r),o.children.length>1){const e=o.firstElementChild;o.innerHTML="",o.append(e)}if("IMG"===(null===(a=o.firstElementChild)||void 0===a?void 0:a.tagName)){const e=o.firstElementChild,t=e.src;if(!un.has(t)){e.setAttribute("loading","lazy");const i=document.createElement("span");i.classList.add("emoji-placeholder"),s.Z.settings.animationsEnabled&&(e.style.opacity="0",i.style.opacity="1"),e.addEventListener("load",(()=>{(0,Be.T2)((()=>{s.Z.settings.animationsEnabled&&(e.style.opacity="",i.style.opacity=""),o.classList.remove("empty"),un.add(t)}))}),{once:!0}),o.append(i)}}i?t.prepend(o):t.appendChild(o)}function mn(e){return(0,r.Z)(e,"super-emoji")?3===e.nodeType?e.nodeValue:("SPAN"===e.tagName&&!e.classList.contains("emoji")&&e.firstElementChild&&(e=e.firstElementChild),e.getAttribute("alt")||e.innerText):""}class gn{constructor(e){this.managers=e,this.closeScrollTop=0,this.onContentClick=e=>{(0,a.Z)(e);const t=mn(e.target);t&&(_m.chat.input.onEmojiSelected(t,!1),gi.Z&&(0,ln.Z)())}}init(){this.content=document.getElementById("content-emoji");const e=["Emoji.SmilesAndPeople","Emoji.AnimalsAndNature","Emoji.FoodAndDrink","Emoji.TravelAndPlaces","Emoji.ActivityAndSport","Emoji.Objects","Emoji.Flags","Skin Tones"],t={},i=new Map([["Emoji.Recent",[]]]);for(const t in cn.Z){const s=""+cn.Z[t],n=e[+s[0]-1];if(!n)continue;let a=i.get(n);a||(a=[],i.set(n,a)),a[+s.slice(1)||0]=t}i.delete(e.pop()),i.forEach(((e,i)=>{const s=document.createElement("div");s.classList.add("emoji-category");const n=document.createElement("div");n.classList.add("category-title"),n.append((0,v.ag)(i));const a=document.createElement("div");a.classList.add("super-emojis"),s.append(n,a),e.forEach((e=>{pn((0,pi.zu)(e),a,!1)})),t[i]=s}));const a=this.menu=this.content.previousElementSibling,o=this.scroll=new m.ZP(this.content,"EMOJI"),r=(0,be.y)(this.content,!0);Promise.all([(0,on.Z)(200),this.managers.appEmojiManager.getRecentEmojis().then((e=>{const t=!!e.length,i=t?0:1;this.menu.children[0].classList.toggle("hide",!t),this.menu.children[i].classList.add("active");const s=zn.menuOnClick(a,o,void 0,i);return this.stickyIntersector=s.stickyIntersector,this.setMenuActive=s.setActive,e}))]).then((([i,s])=>{r.remove(),this.recentItemsDiv=t["Emoji.Recent"].querySelector(".super-emojis");for(const e of s)pn(e,this.recentItemsDiv);this.recentItemsDiv.parentElement.classList.toggle("hide",!this.recentItemsDiv.childElementCount),e.unshift("Emoji.Recent"),e.map((e=>{const i=t[e];return i||console.error("no div by category:",e),o.container.append(i),this.stickyIntersector.observeStickyHeaderChanges(i),i}))})),(0,n.fc)(this.content,this.onContentClick),this.init=null,s.Z.addEventListener("emoji_recent",(e=>{const t=Array.from(this.recentItemsDiv.children);for(let i=0,s=t.length;i<s;++i){const s=t[i];if(e===(0,dn.Z)(mn(s))){if(0===i)return;s.remove()}}pn(e,this.recentItemsDiv,!0),this.recentItemsDiv.parentElement.classList.remove("hide"),this.menu.children[0].classList.remove("hide"),this.closeScrollTop||this.setMenuActive(0)})),Vn.addEventListener("close",(()=>{this.closeScrollTop=this.scroll.scrollTop}))}onClose(){}}class vn extends fe{constructor(e,t){super(e),this.onVisibilityChange=t,this.intersector=new pe((e=>{const{target:t,visible:i}=e,s=me(this.queue,(e=>e.div===t));i&&s.length&&s.forEach((e=>{this.queue.unshift(e)})),this.onVisibilityChange&&this.onVisibilityChange(e),this.setProcessQueueTimeout()}))}observe(e){this.intersector.observe(e)}}var fn=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const yn=100;class bn{constructor(e,t,i,n=!0){this.element=e,this.group=t,this.scrollable=i,this.scrollPromise=Promise.resolve(),this.timeout=0,this.onScroll=()=>{this.timeout?clearTimeout(this.timeout):this.scrollPromise=(0,Oe.Z)(),this.timeout=window.setTimeout((()=>{this.timeout=0,this.scrollPromise.resolve()}),150)},this.processInvisibleDiv=e=>this.scrollPromise.then((()=>fn(this,void 0,void 0,(function*(){if(this.lazyLoadQueue.intersector.isVisible(e))return;const t=e.querySelector("video"),i=e.querySelector("img");i&&(i&&i.classList.remove("hide"),yield(0,Be.d1)()),!this.lazyLoadQueue.intersector.isVisible(e)&&t&&(t.remove(),t.src="",t.load(),p.Z.getAnimations(t).forEach((e=>{p.Z.checkAnimation(e,!0,!0)})))})))),this.managers=s.Z.managers,this.lazyLoadQueue=new vn(void 0,(({target:e,visible:t})=>{t?this.processVisibleDiv(e):this.processInvisibleDiv(e)})),n&&this.attach()}attach(){this.scrollable.container.addEventListener("scroll",this.onScroll)}detach(){this.clear(),this.scrollable.container.removeEventListener("scroll",this.onScroll)}clear(){this.lazyLoadQueue.clear()}processVisibleDiv(e){e.querySelector("video")||this.lazyLoadQueue.push({div:e,load:()=>{const t=e.dataset.docId;return Promise.all([this.managers.appDocsManager.getDoc(t),this.scrollPromise]).then((([t])=>fn(this,void 0,void 0,(function*(){const i=(yield qt({doc:t,container:e,lazyLoadQueue:null,group:this.group,noInfo:!0})).loadPromise;return i.finally((()=>{const t=e.querySelector("video");e.style.opacity="";const i=e.querySelector("img");i&&i.classList.add("hide"),t&&!t.parentElement&&setTimeout((()=>{t.src="",t.load(),p.Z.getAnimations(t).forEach((e=>{p.Z.checkAnimation(e,!0,!0)}))}),0),this.lazyLoadQueue.intersector.isVisible(e)||this.processInvisibleDiv(e)})),i}))))}})}add(e,t=this.element){let i=e.w,s=e.h;s<yn&&(i*=yn/s,s=yn);const n=Math.min(300,400,i),a=(0,Ce.Z)(i,s,n,yn),o=document.createElement("div");o.classList.add("gif","fade-in-transition"),o.style.width=a.width+"px",o.style.opacity="0",o.dataset.docId=""+e.id,t.append(o),this.lazyLoadQueue.observe(o)}}class wn{constructor(e){this.managers=e}init(){this.content=document.getElementById("content-gifs");const e=this.content.firstElementChild;(0,n.fc)(e,zn.onMediaClick);const t=new m.ZP(this.content,"GIFS"),i=new bn(e,Hn,t),s=(0,be.y)(this.content,!0);this.managers.appDocsManager.getGifs().then((e=>{e.forEach((e=>{i.add(e)})),s.remove()})),Vn.addLazyLoadQueueRepeat(i.lazyLoadQueue,i.processInvisibleDiv),this.init=null}onClose(){}}class Sn extends fe{constructor(e,t,i){super(e),this.onVisibilityChange=t,this._queue=new Map,this.intersector=new pe((e=>{const{target:t,visible:i}=e,s=me(this.queue,(e=>e.div===t));i&&(s.length?s:[this._queue.get(t)]).forEach((e=>{this.queue.unshift(e||this._queue.get(t))})),this.onVisibilityChange&&this.onVisibilityChange(e),this.setProcessQueueTimeout()}),i)}clear(){super.clear(),this._queue.clear()}observe(e){this._queue.set(e.div,e),this.intersector.observe(e.div)}}var Cn=i(2648);function Ln(e,t,i,s){return void 0===s&&(s=e.parentElement===t?(0,Cn.Z)(e):-1),s!==i&&(-1!==s&&s<i&&(i+=1),i?t.childElementCount>i?t.insertBefore(e,t.children[i]):t.append(e):t.prepend(e),!0)}function In(e){return new Promise(((t,i)=>{var s;const{button:n,checkbox:a}=e;n.callback=e=>{t(e?!!e.size:void 0)};const o=(0,A.x)(e.buttons||[n]),r=o.find((e=>e.isCancel));r.callback=()=>{i()},e.buttons=o,null!==(s=e.checkboxes)&&void 0!==s||(e.checkboxes=a&&[a]),new qi("popup-confirmation",e).show()}))}var Mn=i(7625);function En(e,t,i,s=e.getBoundingClientRect(),n=t.getBoundingClientRect()){let{top:a,right:o,bottom:r,left:l}=n;if(i){const e=t.querySelector(".sticky");e&&(a=e.getBoundingClientRect().bottom)}if(s.top>=r||s.bottom<=a||s.right<=l||s.left>=o)return null;const c={top:!1,right:!1,bottom:!1,left:!1,vertical:0,horizontal:0},d="visualViewport"in window?window.visualViewport:window,h=d.width||d.innerWidth,u=d.height||d.innerHeight;return{rect:{top:s.top<a&&0!==a?(c.top=!0,++c.vertical,a):s.top,right:s.right>o&&o!==h?(c.right=!0,++c.horizontal,o):s.right,bottom:s.bottom>r&&r!==u?(c.bottom=!0,++c.vertical,r):s.bottom,left:s.left<l&&0!==l?(c.left=!0,++c.horizontal,l):s.left},overflow:c}}window.getVisibleRect=En;var Pn=i(3772),kn=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};let Tn=!1;function xn({listenTo:e,listenerSetter:t,selector:i}){if(gi.Z)return;const o=(t,s)=>{const n=i||".media-sticker-wrapper",a=t.target.closest(n);return!a||s&&!(0,vi.Z)(a,e)?void 0:a},l=s.Z.managers;t.add(e)("mousedown",(e=>{if(Tn||e.buttons>1||0!==e.button)return;let t=o(e);if(!t)return;const i=t.dataset.docId;if(!i)return;const s="sticker-viewer",c="STICKER-VIEWER",d=p.Z.getOnlyOnePlayableGroup(),h=(0,Ti.k)();let u,m;const g=({mediaContainer:e,doc:t,middleware:i,lockGroups:a,isSwitching:o})=>kn(this,void 0,void 0,(function*(){const d=(0,di.Z)(t),h=e.getBoundingClientRect(),m=(0,ot.C)(t.w,t.h),g=d?280:360,v=(0,ot.C)(g,g),f=h.width===h.height?v:m.aspectFitted(v),y=(0,r.Z)(e,"bubble"),b=!y||y.classList.contains("is-out"),w=document.createElement("div");w.classList.add(s+"-transformer");const S=document.createElement("div");S.classList.add(s+"-sticker"),S.style.width=f.width+"px",S.style.height=f.height+"px";const C=document.createElement("div");if(C.classList.add(s+"-emoji"),C.append((0,Zt.Z)(t.stickerEmojiRaw)),d){const e=(g*Xn-g)/3*(b?1:-1);w.classList.add("has-effect"),w.style.setProperty("--translateX",`${e}px`),C.style.setProperty("--translateX",-e+"px")}const L=(0,r.Z)(e,"scrollable"),I=En(e,L,!0,h);(I.overflow.vertical||I.overflow.horizontal)&&S.classList.add("is-overflow");const M=e.getBoundingClientRect(),E=M.width/f.width,P=M.height/f.height,k=M.left-(as.width-M.width)/2,T=M.top-(as.height-M.height)/2;w.style.transform=`translate(${k}px, ${T}px) scale(${E}, ${P})`,o&&w.classList.add("is-switching"),w.append(S,C),u.append(w);const x=yield ta({doc:t,div:S,group:c,width:f.width,height:f.height,play:!1,loop:!0,middleware:i,managers:l,needFadeIn:!1,isOut:b,withThumb:!1,relativeEffect:!0,loopEffect:!0}).then((({render:e})=>e));if(!i())return;u.parentElement||document.body.append(u);const _=x instanceof Pn.Z?new Promise((e=>x.addEventListener("firstFrame",e,{once:!0}))):Promise.resolve();if(yield Promise.all([_,(0,Be.d1)()]),yield(0,on.Z)(0),i()){if(a&&(p.Z.setOnlyOnePlayableGroup(c),p.Z.checkAnimations(!0)),x instanceof Pn.Z){const t=hi.Z.getAnimation(e);x.curFrame=t.curFrame,x.play(),yield new Promise((e=>{let t=0;const i=()=>{2==++t&&(e(),x.removeEventListener("enterFrame",i))};x.addEventListener("enterFrame",i)})),x.pause()}else x instanceof HTMLVideoElement&&(x.currentTime=e.querySelector("video").currentTime);return{ready:()=>{(x instanceof Pn.Z||x instanceof HTMLVideoElement)&&x.play(),d&&(0,n.tH)(S)},transformer:w}}})),v=window.setTimeout((()=>kn(this,void 0,void 0,(function*(){document.removeEventListener("mousemove",y),u=document.createElement("div"),u.classList.add(s),Tn=!0;const e=h.get(),n=yield l.appDocsManager.getDoc(i);if(!e())return;let a;try{if(a=yield g({doc:n,mediaContainer:t,middleware:e,lockGroups:!0}),!a)return}catch(e){return}const{ready:o,transformer:r}=a;m=r,Re(u,"is-visible",!0,200,(()=>{e()&&o()})),document.addEventListener("mousemove",f)}))),125),f=e=>kn(this,void 0,void 0,(function*(){const i=o(e,!0);if(!i||t===i)return;const s=i.dataset.docId;if(!s)return;t=i,h.clean();const n=h.get(),a=yield l.appDocsManager.getDoc(s);if(!n())return;let r;try{if(r=yield g({doc:a,mediaContainer:t,middleware:n,isSwitching:!0}),!r)return}catch(e){return}const{ready:c,transformer:d}=r,u=m;Re(u,"is-switching",!0,200,(()=>{u.remove()})),m=d,Re(d,"is-switching",!1,200,(()=>{n()&&c()}))})),y=e=>{(0,vi.Z)(e.target,t)||(document.removeEventListener("mousemove",y),b())},b=()=>{clearTimeout(v),h.clean(),u&&(Re(u,"is-visible",!1,200,(()=>{u.remove(),p.Z.setOnlyOnePlayableGroup(d),p.Z.checkAnimations(!1),Tn=!1})),(0,n.fc)(document.body,a.Z,{capture:!0,once:!0})),document.removeEventListener("mousemove",f)};document.addEventListener("mousemove",y),document.addEventListener("mouseup",b,{once:!0})}))}var _n=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class An{constructor(e,t,i,s){this.regularLazyLoadQueue=e,this.group=t,this.managers=i,this.options=s,this.animated=new Set,this.checkAnimationContainer=(e,t)=>{p.Z.getAnimations(e).forEach((e=>{t?p.Z.checkAnimation(e,!1):p.Z.checkAnimation(e,!0,!0)}))},this.processVisible=e=>_n(this,void 0,void 0,(function*(){const t=e.dataset.docId,i=yield this.managers.appDocsManager.getDoc(t),s=d.Z.active.esgSticker.width,n=ta({doc:i,div:e,width:s,height:s,lazyLoadQueue:null,group:this.group,onlyThumb:!1,play:!0,loop:!0,withLock:!0}).then((({render:e})=>e));return n.then((()=>{this.checkAnimationContainer(e,this.lazyLoadQueue.intersector.isVisible(e))})),n})),this.processInvisible=e=>_n(this,void 0,void 0,(function*(){const t=e.dataset.docId,i=yield this.managers.appDocsManager.getDoc(t);this.checkAnimationContainer(e,!1),e.textContent="",this.renderSticker(i,e)})),this.lazyLoadQueue=new Sn(void 0,(({target:e,visible:t})=>{t||this.processInvisible(e)}),s)}clear(){this.lazyLoadQueue.clear()}renderSticker(e,t,i){return t||((t=document.createElement("div")).classList.add("grid-item","super-sticker"),t.dataset.docId=""+e.id,e.animated&&this.observeAnimated(t)),ta({doc:e,div:t,lazyLoadQueue:this.regularLazyLoadQueue,group:this.group,onlyThumb:e.animated,loadPromises:i}),t}observeAnimated(e){this.animated.add(e),this.lazyLoadQueue.observe({div:e,load:this.processVisible})}unobserveAnimated(e){this.animated.delete(e),this.lazyLoadQueue.unobserve(e)}}class Zn{constructor(e){this.managers=e,this.mounted=!1,this.categories={},this.categoriesMap=new Map,this.localCategories=[]}setFavedLimit(e){const t=s.Z.premium?e.stickers_faved_limit_premium:e.stickers_faved_limit_default;this.categories.faved.limit=t}createCategory(e,t){const i=document.createElement("div");i.classList.add("emoji-category","hide");const s=document.createElement("div");s.classList.add("category-items","super-stickers");const n=document.createElement("div");n.classList.add("category-title"),n.append(t);const a=E(void 0,{noRipple:!0});a.classList.add("menu-horizontal-div-item");const o=document.createElement("div");o.classList.add("menu-horizontal-div-item-padding"),a.append(o);const r={elements:{container:i,title:n,items:s,menuTab:a,menuTabPadding:o},set:e,items:[],id:""+e.id};return i.append(n,s),this.categories[e.id]=r,this.categoriesMap.set(i,r),this.categoriesIntersector.observe(i),this.stickyIntersector.observeStickyHeaderChanges(i),r}categoryAppendStickers(e,t){const{container:i}=e.elements;t.then((t=>{const s=this.isCategoryVisible(e);t.forEach((t=>{const i=this.superStickerRenderer.renderSticker(t);e.items.push({document:t,element:i}),s&&e.elements.items.append(i)})),this.setCategoryItemsHeight(e),i.classList.remove("hide")}))}isCategoryVisible(e){return this.categoriesIntersector.getVisible().includes(e.elements.container)}setCategoryItemsHeight(e){const t=this.content.getBoundingClientRect().width-10,i=d.Z.active.esgSticker.width,s=Math.floor(t/i),n=Math.ceil(e.items.length/s)*i;e.elements.items.style.minHeight=n+"px"}renderStickerSet(e,t=!1){return _n(this,void 0,void 0,(function*(){const i=this.createCategory(e,(0,Zt.Z)(e.title)),{menuTab:s,menuTabPadding:n,container:a}=i.elements,o=t?this.localCategories.filter((e=>e.mounted)).length:65535;Ln(s,this.menu,o);const r=this.managers.appStickersManager.getStickerSet(e);this.categoryAppendStickers(i,r.then((e=>e.documents))),Ln(a,this.scroll.container,o,-1),Ua({set:e,container:n,group:Hn,lazyLoadQueue:zn.lazyLoadQueue,width:32,height:32,autoplay:!1})}))}init(){this.content=document.getElementById("content-stickers");const e=this.content.previousElementSibling;this.menu=e.firstElementChild;const t=new m.v7(e);this.scroll=new m.ZP(this.content,"STICKERS"),this.scroll.onAdditionalScroll=()=>{o()};const i={root:Vn.getElement()};this.categoriesIntersector=new pe((({target:e,visible:t,entry:i})=>{const s=this.categoriesMap.get(e);t?s.elements.items.append(...s.items.map((({element:e})=>e))):s.elements.items.textContent=""}),i);const a=e=>{e.elements.items.textContent="",e.items.forEach((({element:e})=>this.superStickerRenderer.unobserveAnimated(e))),e.items.length=0};this.scroll.container.addEventListener("click",(e=>{const t=e.target;if((0,r.Z)(t,"category-title")){const e=(0,r.Z)(t,"emoji-category"),i=this.categoriesMap.get(e);if("recent"===i.set.id)return;new qn({id:i.set.id,access_hash:i.set.access_hash}).show()}else zn.onMediaClick(e)}));const o=(e=!1)=>{s.Z.dispatchEvent("choosing_sticker",!e)};Vn.addEventListener("closed",(()=>{o(!0)})),Vn.addEventListener("opened",(()=>{o()}));const{stickyIntersector:l,setActive:c}=zn.menuOnClick(this.menu,this.scroll,t);this.stickyIntersector=l;const h=(0,be.y)(this.content,!0),u=(e,t,i)=>{const s=this.createCategory({id:e},(0,v.ag)(t));return this.localCategories.push(s),s.elements.title.classList.add("disable-hover"),i&&s.elements.menuTab.classList.add("tgico-"+i),s.elements.menuTabPadding.remove(),this.toggleLocalCategory(s,!1),s},p=(e,t)=>{e.limit&&(t=t.slice(0,e.limit));const i=new Set(t.map((e=>e.id)));(0,Mn.Z)(e.items,(t=>{i.has(t.document.id)||this.deleteSticker(e,t.document,!0)})),this.toggleLocalCategory(e,!!t.length),(0,Mn.Z)(t,((t,i)=>{this.unshiftSticker(e,t,!0,i)})),this.spliceExceed(e),e.elements.container.classList.remove("hide")},g=u("faved","FavoriteStickers","saved");g.elements.menuTab.classList.add("active");const f=u("recent","Stickers.Recent","recent");f.limit=20;const y=E("close",{noRipple:!0});f.elements.title.append(y),(0,n.fc)(y,(()=>{In({titleLangKey:"ClearRecentStickersAlertTitle",descriptionLangKey:"ClearRecentStickersAlertMessage",button:{langKey:"Clear"}}).then((()=>{this.managers.appStickersManager.clearRecentStickers()}),ft.Z)}));const b=u("premium","PremiumStickersShort"),w=document.createElement("span");w.classList.add("tgico-star","color-premium"),b.elements.menuTab.append(w);const S=[Promise.all([this.managers.apiManager.getAppConfig(),this.managers.appStickersManager.getFavedStickersStickers()]).then((([e,t])=>{this.setFavedLimit(e),p(g,t)})),this.managers.appStickersManager.getRecentStickersStickers().then((e=>{p(f,e)})),this.managers.appStickersManager.getAllStickers().then((e=>{for(const t of e.sets)this.renderStickerSet(t)})),this.managers.appStickersManager.getPremiumStickers().then((e=>{const t=e.length;this.toggleLocalCategory(b,s.Z.premium&&!!t),this.categoryAppendStickers(b,Promise.resolve(e)),s.Z.addEventListener("premium_toggle",(e=>{this.toggleLocalCategory(this.categories.premium,e&&!!t)}))}))];Promise.race(S).finally((()=>{h.remove()})),Promise.all(S).finally((()=>{this.mounted=!0,o(),c(0)})),this.superStickerRenderer=new An(zn.lazyLoadQueue,Hn,this.managers,i);const C=this.superStickerRenderer.lazyLoadQueue;Vn.addLazyLoadQueueRepeat(C,this.superStickerRenderer.processInvisible),s.Z.addEventListener("stickers_installed",(e=>{!this.categories[e.id]&&this.mounted&&this.renderStickerSet(e,!0)})),s.Z.addEventListener("stickers_deleted",(({id:e})=>{const t=this.categories[e];t&&this.mounted&&(t.elements.container.remove(),t.elements.menuTab.remove(),this.categoriesIntersector.unobserve(t.elements.container),a(t),delete this.categories[e],this.categoriesMap.delete(t.elements.container))})),s.Z.addEventListener("sticker_updated",(({type:e,document:t,faved:i})=>{const s=this.categories["faved"===e?"faved":"recent"];s&&(i?this.unshiftSticker(s,t):this.deleteSticker(s,t))})),s.Z.addEventListener("stickers_updated",(({type:e,stickers:t})=>{if(this.mounted){const i=this.categories["faved"===e?"faved":"recent"];p(i,t)}})),s.Z.addEventListener("app_config",(e=>{this.setFavedLimit(e)}));const L=()=>{for(const[e,t]of this.categoriesMap)this.setCategoryItemsHeight(t)};d.Z.addEventListener("resize",L),Vn.addEventListener("opened",L),xn({listenTo:this.content,listenerSetter:new I.Z}),Wn({listenTo:this.content,verifyRecent:e=>!!(0,vi.Z)(e,this.categories.recent.elements.items),onOpen:()=>{Vn.setIgnoreMouseOut(!0)},onClose:()=>{Vn.setIgnoreMouseOut(!1)}}),this.init=null}toggleLocalCategory(e,t){if(t){let t=this.localCategories.indexOf(e);const i=this.localCategories.slice(0,t).filter((e=>!e.mounted));t-=i.length,Ln(e.elements.menuTab,this.menu,t),Ln(e.elements.container,this.scroll.container,t)}else e.elements.menuTab.remove(),e.elements.container.remove();e.mounted=t}onLocalCategoryUpdate(e){this.setCategoryItemsHeight(e),this.toggleLocalCategory(e,!!e.items.length)}deleteSticker(e,t,i){const s=(0,ge.Z)(e.items,(e=>e.document.id===t.id));s&&(s.element.remove(),i||this.onLocalCategoryUpdate(e))}spliceExceed(e){const{items:t,limit:i}=e;t.splice(i,t.length-i).forEach((({element:e})=>{e.remove()})),this.onLocalCategoryUpdate(e)}unshiftSticker(e,t,i,s){if(void 0!==s){const i=e.items[s];if(i&&i.document.id===t.id)return}let n=(0,ge.Z)(e.items,(e=>e.document.id===t.id));n||(n={element:this.superStickerRenderer.renderSticker(t),document:t}),e.items.unshift(n),e.elements.items.prepend(n.element),i||this.spliceExceed(e)}unshiftRecentSticker(e){this.managers.appStickersManager.saveRecentSticker(e.id)}deleteRecentSticker(e){this.managers.appStickersManager.saveRecentSticker(e.id,!0)}onClose(){}}const Fn="GIFS-SEARCH";class Dn extends P{constructor(){super(...arguments),this.nextOffset="",this.loadedAll=!1,this.onGifsClick=e=>{const t=(0,r.Z)(e.target,"gif");if(!t)return;const i=t.dataset.docId;_m.chat.input.sendMessageWithDocument(i)?d.Z.isMobile&&nn.onCloseBtnClick():console.warn("got no doc by id:",i)}}init(){this.container.id="search-gifs-container",this.inputSearch=new w("SearchGifsTitle",(e=>{this.reset(),this.search(e)})),this.title.replaceWith(this.inputSearch.container),this.gifsDiv=document.createElement("div"),this.gifsDiv.classList.add("gifs-masonry"),(0,n.fc)(this.gifsDiv,this.onGifsClick,{listenerSetter:this.listenerSetter}),this.scrollable.append(this.gifsDiv),this.masonry=new bn(this.gifsDiv,Fn,this.scrollable)}onClose(){this.scrollable.onScrolledBottom=()=>{}}onCloseAfterTimeout(){return this.reset(),this.gifsDiv.innerHTML="",p.Z.checkAnimations(void 0,Fn),this.inputSearch.remove(),super.onCloseAfterTimeout()}reset(){this.searchPromise=null,this.nextOffset="",this.loadedAll=!1,this.masonry.clear()}open(){const e=super.open();return nn.toggleSidebar(!0).then((()=>{this.search("",!0),this.scrollable.onScrolledBottom=()=>{this.search(this.inputSearch.value,!1)}})),e}search(e,t=!0){return i=this,s=void 0,a=function*(){if(!this.searchPromise&&!this.loadedAll){this.gifBotPeerId||(this.gifBotPeerId=(yield this.managers.appUsersManager.resolveUsername("gif")).id.toPeerId(!1));try{this.searchPromise=this.managers.appInlineBotsManager.getInlineResults(le.NM,this.gifBotPeerId,e,this.nextOffset);const{results:i,next_offset:s}=yield this.searchPromise;if(this.inputSearch.value!==e)return;this.searchPromise=null,this.nextOffset=s,t&&(this.gifsDiv.innerHTML=""),i.length?i.forEach((e=>{"botInlineMediaResult"===e._&&e.document&&this.masonry.add(e.document)})):this.loadedAll=!0,this.scrollable.onScroll()}catch(e){throw this.searchPromise=null,console.error("gifs loading error:",e),e}}},new((n=void 0)||(n=Promise))((function(e,t){function o(e){try{l(a.next(e))}catch(e){t(e)}}function r(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(o,r)}l((a=a.apply(i,s||[])).next())}));var i,s,n,a}}class Rn extends P{init(){this.container.id="stickers-container",this.container.classList.add("chatlist-container"),this.lazyLoadQueue=new ye,this.inputSearch=new w("StickersTab.SearchPlaceholder",(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),xn({listenTo:this.setsDiv,listenerSetter:this.listenerSetter}),(0,n.fc)(this.setsDiv,(e=>{const t=(0,r.Z)(e.target,"sticker-set-sticker");if(t){const e=t.dataset.docId;return void _m.chat.input.sendMessageWithDocument(e)}const i=(0,r.Z)(e.target,"sticker-set");if(!i)return;const s=i.dataset.stickerSet,n=i.dataset.access_hash,a=(0,r.Z)(e.target,"sticker-set-button");a?(e.preventDefault(),e.cancelBubble=!0,a.setAttribute("disabled","true"),this.managers.appStickersManager.getStickerSet({id:s,access_hash:n}).then((e=>{this.managers.appStickersManager.toggleStickerSet(e.set).then((t=>{t&&(a.textContent="",a.append((0,v.ag)(e.set.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),a.classList.toggle("gray",!!e.set.installed_date))})).finally((()=>{a.removeAttribute("disabled")}))}))):this.managers.appStickersManager.getStickerSet({id:s,access_hash:n}).then((e=>{new qn(e.set).show()}))}),{listenerSetter:this.listenerSetter})}onCloseAfterTimeout(){return this.setsDiv.innerHTML="",p.Z.checkAnimations(void 0,"STICKERS-SEARCH"),super.onCloseAfterTimeout()}renderSet(e){const t=document.createElement("div");t.classList.add("sticker-set");const i=document.createElement("div");i.classList.add("sticker-set-header");const s=document.createElement("div");s.classList.add("sticker-set-details"),s.innerHTML='<div class="sticker-set-name"></div>',(0,c.Z)(s.firstElementChild,(0,Zt.Z)(e.title));const n=document.createElement("div");n.classList.add("sticker-set-count"),n.append((0,v.ag)("Stickers",[e.count])),s.append(n);const a=document.createElement("button");a.classList.add("btn-primary","btn-color-primary","sticker-set-button"),a.append((0,v.ag)(e.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),e.installed_date&&a.classList.add("gray"),i.append(s,a);const o=document.createElement("div");o.classList.add("sticker-set-stickers");const r=Math.min(5,e.count);for(let e=0;e<r;++e){const e=document.createElement("div");e.classList.add("sticker-set-sticker"),o.append(e)}this.managers.appStickersManager.getStickerSet(e).then((e=>{for(let t=0;t<r;++t){const i=o.children[t],s=e.documents[t];"documentEmpty"!==s._&&ta({doc:s,div:i,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(i,o),this.setsDiv.append(t)}open(){const e=super.open();return nn.toggleSidebar(!0).then((()=>{this.renderFeatured()})),e}renderFeatured(){return this.managers.appStickersManager.getFeaturedStickers().then((e=>{this.inputSearch.value||(e=this.filterRendered("",e)).forEach((e=>{this.renderSet(e.set)}))}))}filterRendered(e,t){t=t.slice();const i=Array.from(this.setsDiv.children);return(0,Mn.Z)(i,(i=>{const s=i.dataset.stickerSet,n=t.findIndex((e=>e.set.id===s));-1!==n?t.splice(n,1):e&&i.dataset.title.toLowerCase().includes(e.toLowerCase())||i.remove()})),p.Z.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)).forEach((e=>{this.renderSet(e.set)}))})):this.renderFeatured()}}class Bn extends L.Z{constructor(e){super(!1),this.forceClose=!1,this.inited=!1,this.ignoreMouseOut=!1,this.onMouseOut=e=>{if(!this.isActive())return;if(clearTimeout(this.displayTimeout),this.ignoreMouseOut)return;const t=e.toElement;t&&(0,vi.Z)(t,this.element)||(this.displayTimeout=window.setTimeout((()=>{this.toggle(!1)}),200))},this.toggle=e=>{return t=this,i=void 0,n=function*(){const t=!!this.element.style.display&&void 0===e||e;if(this.init){if(!t)return;this.init(),this.init=null}if(t!==this.isActive())if(this.element.style.display&&void 0===e||e){const e=this.dispatchResultableEvent("open");yield Promise.all(e),this.element.style.display="",this.element.offsetLeft,this.element.classList.add("active"),clearTimeout(this.displayTimeout),this.displayTimeout=window.setTimeout((()=>{this.forceClose=!1,this.dispatchEvent("opened")}),gi.Z?0:200)}else this.dispatchEvent("close"),this.element.classList.remove("active"),clearTimeout(this.displayTimeout),this.displayTimeout=window.setTimeout((()=>{this.element.style.display="none",this.forceClose=!1,this.dispatchEvent("closed")}),gi.Z?0:200)},new((s=void 0)||(s=Promise))((function(e,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,r)}l((n=n.apply(t,i||[])).next())}));var t,i,s,n},(0,x.Z)(this,e)}attachButtonListener(e,t){let i=!0;gi.Z?(0,n.fc)(e,(()=>{i?(i=!1,this.toggle(!0)):this.toggle()}),{listenerSetter:t}):t.add(e)("mouseover",(s=>{i&&(t.add(e)("mouseout",(e=>{clearTimeout(this.displayTimeout),this.onMouseOut(e)})),i=!1),clearTimeout(this.displayTimeout),this.displayTimeout=window.setTimeout((()=>{this.toggle(!0)}),200)}))}init(){gi.Z||(this.element.onmouseout=this.onMouseOut,this.element.onmouseover=e=>{this.forceClose||clearTimeout(this.displayTimeout)})}isActive(){return this.element.classList.contains("active")}setIgnoreMouseOut(e){this.ignoreMouseOut=e}}var Nn,Un=i(3815),On=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const Hn="emoticons-dropdown";class zn extends Bn{constructor(){super({element:document.getElementById("emoji-dropdown")}),this.tabId=-1,this.onSelectTabClick=e=>{this.tabId!==e&&(p.Z.checkAnimations(!0,Hn),this.tabId=e,this.searchButton.classList.toggle("hide",0===this.tabId),this.deleteBtn.classList.toggle("hide",0!==this.tabId))},this.checkRights=()=>On(this,void 0,void 0,(function*(){const{peerId:e,threadId:t}=_m.chat,i=this.tabsEl.children,s=Array.from(i),[n,a]=yield Promise.all([this.managers.appMessagesManager.canSendToPeer(e,t,"send_stickers"),this.managers.appMessagesManager.canSendToPeer(e,t,"send_gifs")]);s[2].toggleAttribute("disabled",!n),s[3].toggleAttribute("disabled",!a);const o=this.tabsEl.querySelector(".active");!o||1===(0,Cn.Z)(o)||n&&a||this.selectTab(0,!1)})),this.addEventListener("open",(()=>On(this,void 0,void 0,(function*(){gi.Z&&(0,ln.Z)()&&(yield(0,on.Z)(100)),this.element.parentElement!==_m.chat.input.chatInput&&_m.chat.input.chatInput.append(this.element),this.savedRange=this.getGoodRange(),zn.lazyLoadQueue.lock(),p.Z.lockIntersectionGroup(Hn)})))),this.addEventListener("opened",(()=>{p.Z.unlockIntersectionGroup(Hn),zn.lazyLoadQueue.unlock(),zn.lazyLoadQueue.refresh()})),this.addEventListener("close",(()=>{zn.lazyLoadQueue.lock(),p.Z.lockIntersectionGroup(Hn),p.Z.checkAnimations(!0,Hn)})),this.addEventListener("closed",(()=>{p.Z.unlockIntersectionGroup(Hn),zn.lazyLoadQueue.unlock(),zn.lazyLoadQueue.refresh(),this.savedRange=void 0}))}init(){this.managers=s.Z.managers,this.emojiTab=new gn(this.managers),this.stickersTab=new Zn(this.managers),this.gifsTab=new wn(this.managers),this.tabs={0:this.emojiTab,1:this.stickersTab,2:this.gifsTab},this.container=this.element.querySelector(".emoji-container .tabs-container"),this.tabsEl=this.element.querySelector(".emoji-tabs"),this.selectTab=(0,ue.X)(this.tabsEl,this.container,this.onSelectTabClick,(()=>{const e=this.tabs[this.tabId];e.init&&e.init(),e.onCloseAfterTimeout&&e.onCloseAfterTimeout(),p.Z.checkAnimations(!1,Hn)})),this.searchButton=this.element.querySelector(".emoji-tabs-search"),this.searchButton.addEventListener("click",(()=>{1===this.tabId?nn.isTabExists(Rn)||nn.createTab(Rn).open():nn.isTabExists(Dn)||nn.createTab(Dn).open()})),this.deleteBtn=this.element.querySelector(".emoji-tabs-delete"),this.deleteBtn.addEventListener("click",(e=>{var t;const i=_m.chat.input.messageInput;(null===(t=i.lastChild)||void 0===t?void 0:t.tagName)?i.lastElementChild.remove():i.lastChild&&(i.lastChild.textContent.length?i.lastChild.textContent=i.lastChild.textContent.slice(0,-1):i.lastChild.remove());const s=new Event("input",{bubbles:!0,cancelable:!0});_m.chat.input.messageInput.dispatchEvent(s),(0,a.Z)(e)}));const e=Je.IS_APPLE_MOBILE,t=e?1:0;if(e&&this.tabsEl.children[1].classList.add("hide"),(0,n.tH)(this.tabsEl.children[t+1]),this.tabs[t].init&&this.tabs[t].init(),!gi.Z){let e,t=!1;const i=t=>{e=t};Un.Z.addEventListener("change",(s=>{s?t||(document.body.addEventListener("mousemove",i),t=!0):t&&(document.body.removeEventListener("mousemove",i),e&&this.onMouseOut(e))}))}return _m.addEventListener("peer_changed",this.checkRights),this.checkRights(),super.init()}getElement(){return this.element}static sendDocId(e,t,i){return On(this,void 0,void 0,(function*(){return(yield _m.chat.input.sendMessageWithDocument(e,void 0,t,i))?(Gn.container&&(Gn.forceClose=!0,Gn.toggle(!1)),!0):(console.warn("got no doc by id:",e),!1)}))}addLazyLoadQueueRepeat(e,t){this.addEventListener("close",(()=>{e.lock()})),this.addEventListener("closed",(()=>{const i=e.intersector.getVisible();for(const e of i)t(e);e.intersector.clearVisible()})),this.addEventListener("opened",(()=>{e.unlockAndRefresh()}))}getSavedRange(){return this.getGoodRange()||this.savedRange}getGoodRange(){const e=document.getSelection();if(e.rangeCount&&document.activeElement===_m.chat.input.messageInput)return e.getRangeAt(0)}}Nn=zn,zn.lazyLoadQueue=new ye,zn.menuOnClick=(e,t,i,s=0)=>{let n=-1;const a=t=>t!==s&&(e.children[s].classList.remove("active"),e.children[t].classList.add("active"),s=t,!0),o=new an(t.container,((s,o)=>{if(Math.abs(n-t.container.scrollTop)<=1)return;n=-1;const r=(0,Cn.Z)(o);!s&&r||(a(r),i&&i.scrollIntoViewNew({element:e.children[r],position:"center",axis:"x"}))}));return e.addEventListener("click",(e=>{let i=e.target;if(i=(0,r.Z)(i,"menu-horizontal-div-item"),!i)return;const s=(0,Cn.Z)(i);if(!a(s))return;const o=(t.splitUp||t.container).children[s].offsetTop+1;t.container.scrollTop=n=o})),{stickyIntersector:o,setActive:a}},zn.onMediaClick=(e,t=!1,i)=>On(void 0,void 0,void 0,(function*(){let s=e.target;if(s=(0,l.Z)(s,"DIV"),!s)return!1;const n=s.dataset.docId;return!!n&&Nn.sendDocId(n,t,i)}));const Gn=new zn;R.GO.emoticonsDropdown=Gn;const Vn=Gn;var Kn=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};function Wn(e){const{listenTo:t,isStickerPack:i,verifyRecent:n,appendTo:a,onOpen:o,onClose:l}=e;let c,d;const h=e=>Kn(this,void 0,void 0,(function*(){const t=yield s.Z.managers.acknowledged.appStickersManager.getFavedStickersStickers();if(!t.cached)return!1;const i=(yield t.result).some((e=>e.id===d.id));return e?!i:i}));return function({buttons:e,findElement:t,listenTo:i,appendTo:s,filterButtons:n,onOpen:a,onClose:o}){null!=s||(s=document.body);const r=new I.Z,l=new I.Z,c=(0,Ti.k)();let d;Fi(i,(e=>{const i=t(e);if(!i)return;let s=d;if((e instanceof MouseEvent||e.hasOwnProperty("preventDefault"))&&e.preventDefault(),s&&s.classList.contains("active"))return!1;(e instanceof MouseEvent||e.hasOwnProperty("cancelBubble"))&&(e.cancelBubble=!0),(()=>{Di(this,void 0,void 0,(function*(){yield null==a?void 0:a(i);const t=yield u();if(!t)return;s=t.element;const{cleanup:n,destroy:r}=t;xi(e,s),Ii.openBtnMenu(s,(()=>{null==o||o(),n(),setTimeout((()=>{r()}),300)}))}))})()}),r);const h=()=>{l.removeAll(),c.clean()},u=()=>Di(this,void 0,void 0,(function*(){h(),e.forEach((e=>e.element=void 0));const t=n||(e=>ki(e,(e=>{var t,i;return null===(i=null===(t=null==e?void 0:e.verify)||void 0===t?void 0:t.call(e))||void 0===i||i}))),i=yield t(e);if(!i.length)return;const a=d=Ei(i,l);return a.classList.add("contextmenu"),s.append(a),{element:a,cleanup:h,destroy:()=>{a.remove()}}}));return{element:d,destroy:()=>{h(),r.removeAll()}}}({listenTo:t,appendTo:a,findElement:e=>c=(0,r.Z)(e.target,"media-sticker-wrapper"),onOpen:()=>Kn(this,void 0,void 0,(function*(){return d=yield s.Z.managers.appDocsManager.getDoc(c.dataset.docId),null==o?void 0:o()})),onClose:l,buttons:[{icon:"stickers",text:"Context.ViewStickerSet",onClick:()=>new qn(d.stickerSetInput).show(),verify:()=>!i},{icon:"favourites",text:"AddToFavorites",onClick:()=>s.Z.managers.appStickersManager.faveSticker(d.id,!1),verify:()=>h(!0)},{icon:"favourites",text:"DeleteFromFavorites",onClick:()=>s.Z.managers.appStickersManager.faveSticker(d.id,!0),verify:()=>h(!1)},{icon:"delete",text:"DeleteFromRecent",onClick:()=>Vn.stickersTab.deleteRecentSticker(d),verify:()=>{var e;return null!==(e=null==n?void 0:n(c))&&void 0!==e&&e}},{icon:"mute",text:"Chat.Send.WithoutSound",onClick:()=>zn.sendDocId(d.id,!1,!0),verify:()=>!(!_m.chat.peerId||_m.chat.peerId===s.Z.myId)},{icon:"schedule",text:"Chat.Send.ScheduledMessage",onClick:()=>_m.chat.input.scheduleSending((()=>_m.chat.input.sendMessageWithDocument(d))),verify:()=>!!_m.chat.peerId}]})}var $n=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const jn="STICKERS-POPUP";class qn extends A.Z{constructor(e){super("popup-stickers",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,title:!0}),this.stickerSetInput=e,this.onStickersClick=e=>{const t=(0,r.Z)(e.target,"sticker-set-sticker");if(!t)return;const i=t.dataset.docId;_m.chat.input.sendMessageWithDocument(i)&&this.hide()},this.title.append((0,v.ag)("Loading")),this.addEventListener("close",(()=>{p.Z.setOnlyOnePlayableGroup(),s()}));const t=document.createElement("div");t.classList.add("sticker-set"),this.stickersDiv=document.createElement("div"),this.stickersDiv.classList.add("sticker-set-stickers","is-loading"),(0,n.fc)(this.stickersDiv,this.onStickersClick,{listenerSetter:this.listenerSetter}),(0,be.y)(this.stickersDiv,!0),this.stickersFooter=document.createElement("div"),this.stickersFooter.classList.add("sticker-set-footer"),t.append(this.stickersDiv);const i=(0,M.Z)("btn-primary btn-primary-transparent disable-hover",{noRipple:!0,text:"Loading"});this.stickersFooter.append(i),this.scrollable.append(t),this.body.append(this.stickersFooter);const{destroy:s}=Wn({listenTo:this.stickersDiv,isStickerPack:!0});xn({listenTo:this.stickersDiv,listenerSetter:this.listenerSetter}),this.loadStickerSet()}loadStickerSet(){return this.managers.appStickersManager.getStickerSet(this.stickerSetInput).then((e=>$n(this,void 0,void 0,(function*(){if(!e)return Li({langPackKey:"StickerSet.DontExist"}),void this.hide();let t;p.Z.setOnlyOnePlayableGroup(jn);const i=(0,v.ag)("Stickers",[e.set.count]);e.set.installed_date?(t=(0,M.Z)("btn-primary btn-primary-transparent danger",{noRipple:!0}),t.append((0,v.ag)("RemoveStickersCount",[i]))):(t=(0,M.Z)("btn-primary btn-color-primary",{noRipple:!0}),t.append((0,v.ag)("AddStickersCount",[i]))),(0,n.fc)(t,(()=>{const i=(0,mi.Z)([t],!0);this.managers.appStickersManager.toggleStickerSet(e.set).then((()=>{this.hide()})).catch((()=>{i()}))}));const s=new ye,a=yield Promise.all(e.documents.map((e=>$n(this,void 0,void 0,(function*(){if("documentEmpty"===e._)return;const t=document.createElement("div");t.classList.add("sticker-set-sticker");const i=d.Z.active.esgSticker.width;return yield ta({doc:e,div:t,lazyLoadQueue:s,group:jn,play:!0,loop:!0,width:i,height:i,withLock:!0}),t})))));(0,c.Z)(this.title,(0,Zt.Z)(e.set.title)),this.stickersFooter.classList.toggle("add",!e.set.installed_date),this.stickersFooter.textContent="",this.stickersFooter.append(t),this.stickersDiv.classList.remove("is-loading"),this.stickersDiv.innerHTML="",this.stickersDiv.append(...a.filter(Boolean)),this.scrollable.onAdditionalScroll()}))))}}var Qn=i(2131);function Yn({size:e,doc:t,middleware:i,target:s,side:n,skipRatio:a,play:o,managers:r,fullThumb:l,withRandomOffset:c,relativeEffect:d,loopEffect:h}){const u=document.createElement("div");let p;u.classList.add("emoji-animation"),u.style.width=e+"px",u.style.height=e+"px";const m=()=>{null==p||p.remove(),u.remove(),_m.chat.bubbles.scrollable.container.removeEventListener("scroll",w)},g=ta({div:u,doc:t,middleware:i,withThumb:!1,needFadeIn:!1,loop:!!h,width:e,height:e,play:o,group:"none",skipRatio:a,managers:r,fullThumb:l}).then((({render:e})=>e)).then((e=>((0,ai.Z)(e),p=e,p.addEventListener("enterFrame",(e=>{(h||e!==p.maxFrame)&&(0,Ne.Z)(s)||m()})),Qn.Z&&p.addEventListener("firstFrame",(()=>{navigator.vibrate(100)}),{once:!0}),p))),v=e=>{const t=Math.random()*e*2;return t>e?-t%e:t},f=c?v(16):0,y=c?v(4):0,b=()=>{if(!(0,Ne.Z)(s))return void m();const t=s.getBoundingClientRect(),i=t.width/200,a="center"===n?0:16*("right"===n?1:-1)*i,o="center"===n?0:0*i,r="right"===n?t.right:t.left,l=t.top,c=("center"===n?(t.width-e)/2:"right"===n?-e:0)+a+f,h=(t.height-e)/2+o+y,p=r+c,g=l+h;g<=-e||g>=as.height?m():d?("center"!==n?u.style[n]=-1*Math.abs(a)+"px":u.style.left=c+"px",u.style.top=h+"px"):(u.style.top=g+"px",u.style.left=p+"px")},w=kt(b);return _m.chat.bubbles.scrollable.container.addEventListener("scroll",w),b(),d?(u.classList.add("is-relative"),s.parentElement.append(u)):_m.emojiAnimationContainer.append(u),{animationDiv:u,stickerPromise:g}}var Jn=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const Xn=1.49,ea={};function ta({doc:e,div:t,middleware:i,lazyLoadQueue:o,group:l,play:c,onlyThumb:h,emoji:m,width:g,height:v,withThumb:f,loop:y,loadPromises:b,needFadeIn:w,needUpscale:S,skipRatio:C,static:L,managers:I=s.Z.managers,fullThumb:M,isOut:E,noPremium:P,withLock:k,relativeEffect:T,loopEffect:x}){var _;return Jn(this,void 0,void 0,(function*(){const A=e.sticker;if(1===A&&(L=!0),!g&&!v){const t=d.Z.active,i=m?t.emojiSticker:e.animated?t.animatedSticker:t.staticSticker,s=(0,ot.C)(e.w,e.h).aspectFitted(i);g=s.width,v=s.height}if(2===A&&hi.Z.loadLottieWorkers(),!A)throw console.error("wrong doc for wrapSticker!",e),new Error("wrong doc for wrapSticker!");let Z;t.dataset.docId=""+e.id,t.classList.add("media-sticker-wrapper");const F=(t=(null==Z?void 0:Z.type))=>Jn(this,void 0,void 0,(function*(){return Z=yield I.thumbsStorage.getCacheContext(e,t)})),D=!L&&(2===A||3===A),R=(0,di.Z)(e);void 0!==E&&R&&!E&&t.classList.add("reflect-x");const B=R&&k;if(B){t.classList.add("is-premium-sticker","tgico-premium_lock");const i=ea[e.id];i&&t.style.setProperty("--lock-url",`url(${i})`)}if(L&&1!==A){const t=Le(e,g,v,!1);yield F(t.type)}else yield F(null==M?void 0:M.type);const N=m?(0,pi.tB)(m):-1,U=Z.downloaded&&!w,O=D,H=2===A||3===A?yield I.appDocsManager.getLottieCachedThumb(e.id,N):void 0;let z=(0,Oe.Z)(),G=!1;if(((null===(_=e.thumbs)||void 0===_?void 0:_.length)||H)&&!t.firstElementChild&&(!U||O||h)&&!1!==f){let n,a=H||e.thumbs[0];const r=()=>{t.childElementCount||(n.classList.add("media-sticker","thumbnail"),Te.Z.mutateElement(t,(()=>{t.append(n),z.resolve()})))};if("url"in a)n=new Image,Ae(n,a.url,r),G=!0;else if("bytes"in a)if("photoPathSize"===a._)if(a.bytes.length){const i=function(e){let t="M";for(let i=0,s=e.length;i<s;++i){const s=e[i];s>=192?t+="AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,"[s-128-64]:(s>=128?t+=",":s>=64&&(t+="-"),t+=""+(63&s))}return t+="z",t}(a.bytes),n="http://www.w3.org/2000/svg",o=document.createElementNS(n,"svg");o.classList.add("rlottie-vector","media-sticker","thumbnail"),o.setAttributeNS(null,"viewBox",`0 0 ${e.w||512} ${e.h||512}`);const r=document.createElementNS(n,"path");r.setAttributeNS(null,"d",i),s.Z.settings.animationsEnabled&&r.setAttributeNS(null,"fill","url(#g)"),o.append(r),t.append(o)}else a=e.thumbs.find((e=>{var t;return null===(t=e.bytes)||void 0===t?void 0:t.length}))||a;else N<=0&&(n=new Image,ni.Z||e.pFlags.stickerThumbConverted||Z.url?(Ae(n,st(0,a,!0),r),G=!0):ui.Z.convert("main-"+e.id,a.bytes).then((s=>{I.appDocsManager.saveWebPConvertedStrippedThumb(e.id,s),a.bytes=s,e.pFlags.stickerThumbConverted=!0,i&&!i()||t.childElementCount||Ae(n,st(0,a,!0),r)})).catch((()=>{})));else if((2===A&&N<=0||3===A)&&(f||h)){const e=()=>Jn(this,void 0,void 0,(function*(){if(t.childElementCount||i&&!i())return;const e=()=>{t.childElementCount||i&&!i()||Ae(n,Z.url,r)};if(yield F(),Z.url)e();else{const t=nt(0,a,!0);n=t.image,t.loadPromise.then(e)}}));if(o&&h)return void o.push({div:t,load:e});e(),a.url&&(G=!0)}}if(b&&G&&b.push(z),h)return;const V=(0,oi.Z)("MIDDLEWARE"),K=()=>Jn(this,void 0,void 0,(function*(){if(i&&!i())throw V;if(2===A&&!L)return yield u.Z.downloadMedia({media:e,queueId:null==o?void 0:o.queueId,thumb:M}).then((o=>Jn(this,void 0,void 0,(function*(){if(i&&!i())throw V;const d=yield hi.Z.loadAnimationWorker({container:t,loop:y&&!m,autoplay:c,animationData:o,width:g,height:v,name:"doc"+e.id,needUpscale:S,skipRatio:C,toneIndex:N},l,i),h=B?()=>{var i,s;const n=null!==(i=ea[s=e.id])&&void 0!==i?i:ea[s]=function(e){var t;const i=e.getContext("2d"),s=20*(null!==(t=e.dpr)&&void 0!==t?t:1),n=s,a=s,o=(e.width-n)/2,r=e.height-a-0,l=i.getImageData(o,r,n,a).data;let c=0,d=0,h=0,u=0;for(let e=0;e<l.length;e+=4)c+=l[e],d+=l[e+1],h+=l[e+2],u+=l[e+3];const p=document.createElement("canvas");p.width=s,p.height=s;const m=p.getContext("2d"),g=new Uint8ClampedArray([255*c/u,255*d/u,255*h/u,255]),v=`rgba(${g[0]}, ${g[1]}, ${g[2]}, ${g[3]})`;return m.fillStyle=v,m.fillRect(0,0,p.width,p.height),m.fillStyle="rgba(112, 117, 121, 0.3)",m.fillRect(0,0,p.width,p.height),p.toDataURL("image/jpeg")}(d.canvas);t.style.setProperty("--lock-url",`url(${n})`)}:void 0;if(d.addEventListener("firstFrame",(()=>{const i=t.firstElementChild;!1!==w&&(w=(w||!i||"svg"===i.tagName)&&s.Z.settings.animationsEnabled);const n=()=>{i&&i!==d.canvas&&"DIV"!==i.tagName&&i.remove()};w?Te.Z.mutate((()=>{d.canvas.classList.add("fade-in"),i&&i.classList.add("fade-out"),d.canvas.addEventListener("animationend",(()=>{Te.Z.mutate((()=>{d.canvas.classList.remove("fade-in"),n()}))}),{once:!0})})):i&&Te.Z.mutate(n),!1!==f&&li(e,d.canvas,N),B&&h()}),{once:!0}),m){const e={a:[],v:1};let s;I.appStickersManager.preloadAnimatedEmojiStickerAnimation(m),(0,n.fc)(t,(n=>Jn(this,void 0,void 0,(function*(){(0,a.Z)(n);const o=hi.Z.getAnimation(t);if(o.paused){const e=yield I.appStickersManager.getAnimatedEmojiSoundDocument(m);if(e){const i=document.createElement("audio");i.style.display="none",t.parentElement.append(i);try{const t=yield u.Z.downloadMediaURL({media:e});i.src=t,i.play(),yield(0,pt.Z)(i,void 0,!0),i.addEventListener("ended",(()=>{i.src="",i.remove()}),{once:!0})}catch(e){}}o.autoplay=!0,o.restart()}if(!_m.chat.peerId.isUser())return;const l=yield I.appStickersManager.getAnimatedEmojiSticker(m,!0);if(!l)return;const{animationDiv:c}=Yn({doc:l,middleware:i,side:E?"right":"left",size:280,target:t,play:!0,withRandomOffset:!0});void 0===E||E||c.classList.add("reflect-x"),s||(s=(0,mt.Z)((()=>{if(!e.a.length)return;const i=e.a[0].t;e.a.forEach((e=>{e.t=(e.t-i)/1e3}));const s=(0,r.Z)(t,"bubble");I.appMessagesManager.setTyping(_m.chat.peerId,{_:"sendMessageEmojiInteraction",msg_id:(0,ci.Z)(+s.dataset.mid),emoticon:m,interaction:{_:"dataJSON",data:JSON.stringify(e)}},!0),e.a.length=0}),1e3,!1)),n.isTrusted&&(e.a.push({i:1,t:Date.now()}),s())}))))}return d}))));if(L||3===A){let n;L?n=new Image:(n=ut(),n.muted=!0,c&&(n.autoplay=!0),y&&(n.loop=!0));const a=t.firstElementChild!==n&&t.firstElementChild;return!1!==w&&(w=(w||!U||(L?a:!a||"svg"===a.tagName))&&s.Z.settings.animationsEnabled),n.classList.add("media-sticker"),w&&n.classList.add("fade-in"),new Promise(((s,r)=>Jn(this,void 0,void 0,(function*(){const c=()=>Jn(this,void 0,void 0,(function*(){if(i&&!i())return void r(V);const o=()=>{Te.Z.mutateElement(t,(()=>{if(t.append(n),a&&a.classList.add("fade-out"),3===A&&!function(e,t){const i=e.id+"-"+t;return!!ri[i]}(e,N)){(0,ai.Z)(n);const t=document.createElement("canvas");t.width=g*window.devicePixelRatio,t.height=v*window.devicePixelRatio,t.getContext("2d").drawImage(n,0,0,t.width,t.height),li(e,t,N)}3===A&&l&&p.Z.addAnimation(n,l),s(n),w&&n.addEventListener("animationend",(()=>{n.classList.remove("fade-in"),null==a||a.remove()}),{once:!0})}))};yield F(),L?Ae(n,Z.url,o):(n.src=Z.url,(0,pt.Z)(n).then(o))}));if(yield F(),Z.url)c();else{let t;if(2===A&&L){const i=Le(e,g,v,!1);t=u.Z.downloadMediaURL({media:e,thumb:i,queueId:null==o?void 0:o.queueId})}else t=u.Z.downloadMediaURL({media:e,queueId:null==o?void 0:o.queueId});t.then(c,r)}}))))}})),W=!o||U&&!D?K():(o.push({div:t,load:K}),Promise.resolve());return U&&L&&(z=W,b&&b.push(z)),2===A&&R&&void 0!==E&&!P&&function({container:e,doc:t,managers:i,middleware:s,isOut:o,width:r,loadPromise:l,relativeEffect:c,loopEffect:d}){i.appStickersManager.preloadSticker(t.id,!0);let h=!1;(0,n.fc)(e,(i=>Jn(this,void 0,void 0,(function*(){if((0,a.Z)(i),h){const e=document.createElement("a");return e.onclick=()=>{Si(),new qn(t.stickerSetInput).show()},void Li({langPackKey:"Sticker.Premium.Click.Info",langPackArguments:[e]})}h=!0,yield l;const{animationDiv:n,stickerPromise:u}=Yn({doc:t,middleware:s,side:o?"right":"left",size:r*Xn,target:e,play:!0,fullThumb:(0,di.Z)(t),relativeEffect:c,loopEffect:d});void 0===o||o||n.classList.add("reflect-x"),u.then((e=>{e.addEventListener("destroy",(()=>{h=!1}))}))}))))}({container:t,doc:e,managers:I,middleware:i,isOut:E,width:g,loadPromise:W,relativeEffect:T,loopEffect:x}),{render:W}}))}class ia extends P{init(){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)}open(e){const t=Object.create(null,{open:{get:()=>super.open}});return i=this,s=void 0,a=function*(){const i=t.open.call(this),s=yield this.managers.appPollsManager.getPoll(e.media.poll.id);this.setTitle(s.poll.pFlags.quiz?"PollResults.Title.Quiz":"PollResults.Title.Poll");const n=document.createElement("h3");(0,c.Z)(n,(0,Zt.Z)(s.poll.question));const a=s.results.results.map((e=>e.voters/s.results.total_voters*100));oa(a);const o=document.createDocumentFragment();return s.results.results.forEach(((t,i)=>{if(!t.voters)return;const n=document.createElement("hr"),r=s.poll.answers[i],l=document.createElement("div");l.classList.add("poll-results-answer");const d=document.createElement("div");(0,c.Z)(d,(0,Zt.Z)(r.text));const h=document.createElement("div");h.innerText=Math.round(a[i])+"%",l.append(d,h);const u=gg.createChatList();u.classList.add("poll-results-voters"),gg.setListClickListener(u,(()=>{nn.onCloseBtnClick()}),void 0,!0),u.style.minHeight=50*Math.min(t.voters,4)+"px",o.append(n,l,u);let p,m=4,g=!1,f=t.voters-4;const y=()=>{g||(g=!0,this.managers.appPollsManager.getVotes(e,r.option,p,m).then((e=>{e.votes.forEach((e=>{const{dom:t}=gg.addDialogNew({peerId:e.user_id.toPeerId(!1),container:u,rippleEnabled:!1,meAsSaved:!1,avatarSize:32});t.lastMessageSpan.parentElement.remove()})),p&&(f-=e.votes.length,b.lastElementChild.replaceWith((0,v.ag)("PollResults.LoadMore",[Math.min(20,f)]))),p=e.next_offset,m=20,f&&e.votes.length||b.remove()})).finally((()=>{g=!1})))};if(y(),f<=0)return;const b=document.createElement("div");b.classList.add("poll-results-more","show-more","rp-overflow"),b.addEventListener("click",y),(0,we.Z)(b);const w=document.createElement("div");w.classList.add("tgico-down"),b.append(w,(0,v.ag)("PollResults.LoadMore",[Math.min(20,f)])),o.append(b)})),this.resultsDiv.append(n,o),nn.toggleSidebar(!0).then((()=>{})),i},new((n=void 0)||(n=Promise))((function(e,t){function o(e){try{l(a.next(e))}catch(e){t(e)}}function r(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(o,r)}l((a=a.apply(i,s||[])).next())}));var i,s,n,a}}const sa="stacked-avatars";class na{constructor(e){this.lazyLoadQueue=e.lazyLoadQueue,this.avatarSize=e.avatarSize,this.container=document.createElement("div"),this.container.classList.add(sa),this.container.style.setProperty("--avatar-size",e.avatarSize+"px")}render(e,t){const i=this.container.children;(e=e.slice().reverse()).length>3&&(e=e.slice(-3)),e.forEach(((e,s)=>{let n=i[s];n||(n=document.createElement("div"),n.classList.add("stacked-avatars-avatar-container"));let a=n.firstElementChild;a||(a=new Wm,a.classList.add("avatar-"+this.avatarSize,"stacked-avatars-avatar"),a.updateOptions({isDialog:!1,loadPromises:t})),a.updateWithOptions({lazyLoadQueue:this.lazyLoadQueue,peerId:e}),a.parentNode||n.append(a),n.parentNode||this.container.append(n)})),Array.from(i).slice(e.length).forEach((e=>e.remove()))}}let aa=0;const oa=e=>{const t=e.reduce(((e,t)=>e+Math.round(t)),0);if(t>100){const i=t-100,s=e.length;for(let t=0;t<i;++t){let t=-1,i=1;for(let n=0;n<s;++n){const s=e[n]%1;s>=.5&&s<i&&(i=s,t=n)}if(-1===t)return;e[t]-=i}}else if(t<100){const i=100-t,s=e.length;for(let t=0;t<i;++t){let t=-1,i=0;for(let n=0;n<s;++n){const s=e[n]%1;s<.5&&s>i&&(i=s,t=n)}if(-1===t)return;e[t]+=1-i}}};s.Z.addEventListener("poll_update",(({poll:e,results:t})=>{Array.from(document.querySelectorAll(`poll-element[poll-id="${e.id}"]`)).forEach((i=>{i.isClosed=!!e.pFlags.closed,i.performResults(t,e.chosenIndexes)}))})),d.Z.addEventListener("resize",(()=>{ua.setMaxLength(),ua.resizePolls()})),d.Z.addEventListener("changeScreen",(()=>{ua.setMaxLength()}));const ra=(e,t,i)=>{e.classList.remove("active"),clearTimeout(i),setTimeout((()=>{t(),e.remove(),la===e&&ca===t&&da===i&&(la=ca=null,da=0)}),200)};let la,ca,da,ha=!1;class ua 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}static setMaxLength(){const e=as.width<=360?as.width-120:d.Z.active.poll.width;this.MAX_LENGTH=e+9+this.MAX_OFFSET+-13.7}static resizePolls(){this.MAX_LENGTH&&Array.from(document.querySelectorAll("poll-element.is-voted")).forEach((e=>{e.svgLines.forEach(((t,i)=>{e.setLineProgress(i,1)}))}))}render(){return e=this,t=void 0,o=function*(){aa||(aa=document.getElementById("poll-line").getTotalLength(),ua.setMaxLength());const{poll:e,results:t}=this.message.media;let i;this.message.pFlags.is_scheduled&&this.classList.add("disable-hover"),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?(i="Chat.Poll.Type.Closed",this.classList.add("is-closed")):i=this.isQuiz?this.isPublic?"Chat.Poll.Type.Quiz":"Chat.Poll.Type.AnonymousQuiz":this.isPublic?"Chat.Poll.Type.Public":"Chat.Poll.Type.Anonymous"),this.classList.toggle("is-multiple",this.isMultiple);const o=this.isMultiple?'<span class="poll-answer-selected tgico-check"></span>':"",r=e.answers.map(((e,t)=>`\n <div class="poll-answer" data-index="${t}">\n <div class="circle-hover">\n <div class="animation-ring"></div>\n <svg class="progress-ring">\n <circle class="progress-ring__circle" cx="13" cy="13" r="9"></circle>\n </svg>\n ${o}\n </div>\n <div class="poll-answer-percents"></div>\n <div class="poll-answer-text"></div>\n <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">\n <use href="#poll-line"></use>\n </svg>\n <span class="poll-answer-selected tgico"></span>\n </div>\n `)).join("");if(this.innerHTML=`\n <div class="poll-title"></div>\n <div class="poll-desc">\n <div class="poll-type"></div>\n <div class="poll-avatars"></div>\n </div>\n ${r}`,(0,c.Z)(this.firstElementChild,(0,Zt.Z)(e.question)),Array.from(this.querySelectorAll(".poll-answer-text")).forEach(((t,i)=>{(0,c.Z)(t,(0,Zt.Z)(e.answers[i].text))})),this.descDiv=this.firstElementChild.nextElementSibling,this.typeDiv=this.descDiv.firstElementChild,this.avatarsDiv=this.descDiv.lastElementChild,i&&this.typeDiv.append((0,v.ag)(i)),this.isQuiz&&(this.classList.add("is-quiz"),e.close_period&&e.close_date)){const t=document.createElement("div");t.classList.add("poll-time"),this.descDiv.append(t);const i=document.createElementNS("http://www.w3.org/2000/svg","svg");i.classList.add("poll-quiz-timer"),this.quizTimer=i;const n=2,a=7,o=2*Math.PI*a,r=document.createElementNS("http://www.w3.org/2000/svg","circle");r.classList.add("poll-quiz-timer-circle"),r.setAttributeNS(null,"cx","16"),r.setAttributeNS(null,"cy","16"),r.setAttributeNS(null,"r",""+a),r.setAttributeNS(null,"stroke-width",""+n),i.append(r),this.descDiv.append(i);const l=1e3*e.close_period,c=1e3*(e.close_date-(yield s.Z.managers.timeManager.getServerTimeOffset()));this.quizInterval=window.setInterval((()=>{const e=Date.now(),i=(c-e)/l,s=(c-e)/1e3+1|0;t.innerHTML=gt(s),s<=5&&(t.style.color="#ee545c",r.style.stroke="#ee545c"),r.style.strokeDashoffset=o+i*o,r.style.strokeDasharray=`${o} ${o}`,e>=c&&(clearInterval(this.quizInterval),t.innerHTML="",r.style.strokeDashoffset=o,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 l=document.createElement("div");l.classList.add("poll-footer"),this.viewResults=document.createElement("div"),this.viewResults.className="poll-footer-button poll-view-results hide",this.viewResults.append((0,v.ag)("Chat.Poll.ViewResults")),this.votersCountDiv=document.createElement("div"),this.votersCountDiv.className="poll-votes-count",l.append(this.viewResults,this.votersCountDiv),this.append(l),this.viewResults.addEventListener("click",(e=>{(0,a.Z)(e),nn.isTabExists(ia)||nn.createTab(ia).open(this.message)})),(0,we.Z)(this.viewResults),this.isMultiple&&(this.sendVoteBtn=document.createElement("div"),this.sendVoteBtn.classList.add("poll-footer-button","poll-send-vote"),this.sendVoteBtn.append((0,v.ag)("Chat.Poll.SubmitVote")),(0,we.Z)(this.sendVoteBtn),e.chosenIndexes.length||this.votersCountDiv.classList.add("hide"),(0,n.fc)(this.sendVoteBtn,(e=>{(0,a.Z)(e),this.chosingIndexes.length&&this.sendVotes(this.chosingIndexes).then((()=>{this.chosingIndexes.length=0,this.answerDivs.forEach((e=>{e.classList.remove("is-chosing")}))}))})),l.append(this.sendVoteBtn));const d=!(e.chosenIndexes.length||this.isClosed);d&&!this.isPublic||this.performResults(t,e.chosenIndexes,!1),d&&(this.setVotersCount(t),(0,n.fc)(this,this.clickHandler))},new((i=void 0)||(i=Promise))((function(s,n){function a(e){try{l(o.next(e))}catch(e){n(e)}}function r(e){try{l(o.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,r)}l((o=o.apply(e,t||[])).next())}));var e,t,i,o}initQuizHint(e){if(e.solution&&e.solution_entities){const t=document.createElement("div");if(t.classList.add("tgico-tip","poll-hint"),this.descDiv.append(t),(0,n.fc)(t,(i=>{(0,a.Z)(i),t.classList.add("active"),((e,t,i)=>{la&&ra(la,ca,da);const s=document.createElement("div");s.classList.add("quiz-hint");const n=document.createElement("div");n.classList.add("container","tgico");const a=document.createElement("div");a.classList.add("text"),n.append(a),s.append(n),(0,c.Z)(a,(0,ii.Z)(e,{entities:t})),_m.chat.bubbles.container.append(s),s.offsetLeft,s.classList.add("active"),la=s,ca=i,da=window.setTimeout((()=>{ra(s,i,da)}),gi.Z?5e3:7e3),ha||(ha=!0,_m.addEventListener("peer_changed",(()=>{la&&ra(la,ca,da)})))})(e.solution,e.solution_entities,(()=>{t.classList.remove("active")}))})),this.sentVote){const i=e.results.find((e=>e.pFlags.correct));i&&!i.pFlags.chosen&&(0,n.tH)(t)}}}clickHandler(e){const t=(0,r.Z)(e.target,"poll-answer");if(!t)return;(0,a.Z)(e);const i=+t.dataset.index;if(this.isMultiple){t.classList.toggle("is-chosing");const e=this.chosingIndexes.indexOf(i);-1!==e?this.chosingIndexes.splice(e,1):this.chosingIndexes.push(i)}else this.sendVotes([i])}sendVotes(e){if(this.sendVotePromise)return this.sendVotePromise;const t=this.answerDivs.filter(((t,i)=>e.includes(i)));return t.forEach((e=>{e.classList.add("is-voting")})),this.classList.add("disable-hover"),this.sentVote=!0,this.sendVotePromise=this.managers.appPollsManager.sendVote(this.message,e).then((()=>{t.forEach((e=>{e.classList.remove("is-voting")})),this.classList.remove("disable-hover")})).catch((()=>{this.sentVote=!1})).finally((()=>{this.sendVotePromise=null}))}performResults(e,t,i=!0){var a,o;if(s.Z.settings.animationsEnabled||(i=!1),this.isQuiz&&((null===(a=e.results)||void 0===a?void 0:a.length)||this.isClosed)){this.answerDivs.forEach(((t,i)=>{t.classList.toggle("is-correct",!!e.results[i].pFlags.correct)})),this.initQuizHint&&(this.initQuizHint(e),this.initQuizHint=null),this.quizInterval&&(clearInterval(this.quizInterval),this.quizInterval=0),(null===(o=this.quizTimer)||void 0===o?void 0:o.parentElement)&&this.quizTimer.remove();const t=this.descDiv.querySelector(".poll-time");t&&t.remove()}if(this.isClosed&&(this.classList.add("is-closed"),(0,g.Z)(this.typeDiv,(0,v.ag)("Chat.Poll.Type.Closed"))),(this.chosenIndexes.length!==t.length||this.isClosed)&&(this.isRetracted=this.chosenIndexes.length&&!t.length,this.chosenIndexes=t.slice(),this.isRetracted?(0,n.fc)(this,this.clickHandler):(0,n.EN)(this,this.clickHandler)),this.chosenIndexes.length||this.isRetracted||this.isClosed){const t=e.results.map((t=>e.total_voters?t.voters/e.total_voters*100:0));this.classList.toggle("no-transition",!i),i&&Re(this,"",!this.isRetracted,340),(0,Be.T2)((()=>{this.setResults(this.isRetracted?this.percents:t,this.chosenIndexes,i),this.percents=t,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 t=(e.recent_voters||[]).map((e=>e.toPeerId())),i=new na({avatarSize:16});i.render(t),(0,g.Z)(this.avatarsDiv,i.container)}if(this.isMultiple){const t=!!this.chosenIndexes.length,i=this.isClosed||t,s=!this.isPublic||!e.total_voters||!t&&!this.isClosed;this.sendVoteBtn.classList.toggle("hide",i),this.viewResults.classList.toggle("hide",s),this.votersCountDiv.classList.toggle("hide",!i||!s)}}setResults(e,t,i){this.svgLines.forEach((e=>e.style.display="")),this.answerDivs.forEach(((e,i)=>{e.classList.toggle("is-chosen",t.includes(i))}));const s=Math.max(...e);if(this.maxPercents=e.map((e=>e/s)),this.isRetracted)this.svgLines.forEach(((e,t)=>{this.setLineProgress(t,-1)}));else{const e=()=>{this.svgLines.forEach(((e,t)=>{this.setLineProgress(t,1)}))};i?(0,Be.T2)(e):e()}let n;e=e.slice(),oa(e);const a=t=>{e.forEach(((e,i)=>{const s=n(e,t);this.numberDivs[i].innerText=s+"%"}))};if(this.isRetracted)if(n=(e,t)=>Math.round(e/10*t),i)for(let e=9,t=0;e>=0;--e,++t)setTimeout((()=>{a(e)}),34*t);else a(0);else if(n=(e,t)=>Math.round(e/10*(t+1)),i)for(let e=0;e<10;++e)setTimeout((()=>{a(e)}),34*e);else a(9);if(this.isRetracted){i&&this.classList.add("is-retracting"),this.classList.remove("is-voted");const e=()=>{this.svgLines.forEach((e=>e.style.display="none"))};i?setTimeout((()=>{this.classList.remove("is-retracting"),e()}),340):e()}else this.classList.add("is-voted")}setVotersCount(e){const t=e.total_voters||0;let i;const s=[t];i=this.isClosed?this.isQuiz?t?"Chat.Quiz.TotalVotes":"Chat.Quiz.TotalVotesResultEmpty":t?"Chat.Poll.TotalVotes1":"Chat.Poll.TotalVotesResultEmpty":this.isQuiz?t?"Chat.Quiz.TotalVotes":"Chat.Quiz.TotalVotesEmpty":t?"Chat.Poll.TotalVotes1":"Chat.Poll.TotalVotesEmpty",(0,g.Z)(this.votersCountDiv,(0,v.ag)(i,s))}setLineProgress(e,t){const i=this.svgLines[e];-1===t?(i.style.strokeDasharray="",i.style.strokeDashoffset=""):(i.style.strokeDasharray=t*this.maxPercents[e]*ua.MAX_LENGTH+", 485.9",i.style.strokeDashoffset=""+t*ua.MAX_OFFSET)}}ua.MAX_OFFSET=-46.5,ua.MAX_LENGTH=0,customElements.define("poll-element",ua);var pa=i(2064);class ma{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"),this.title.setAttribute("dir","auto"),this.subtitle=document.createElement("div"),this.subtitle.classList.add(e+"-subtitle"),this.subtitle.setAttribute("dir","auto"),this.content.append(this.title,this.subtitle),this.container.append(this.border,this.content)}}function ga(e){if(e instanceof DocumentFragment)return e;const t=document.createElement("template");return e=e.trim(),t.innerHTML=e,t.content}const va=new Set(["all","web","webk"]),fa=new Set;function ya(e){return e.find((e=>va.has(e.platform)&&!fa.has(e.reason)))}function ba(e){return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function wa(e){return!(!e.restriction_reason||(t=e.restriction_reason,!ya(t)));var t}var Sa=i(1346),Ca=i(2614);const La={s:"Seconds",m:"Minutes",h:"Hours",d:"Days",w:"Weeks"};function Ia(e,t){const i=function(e,t=2){e||(e=1);const i=[],s=[{m:1,t:"s"},{m:60,t:"m"},{m:60,t:"h"},{m:24,t:"d"},{m:7,t:"w"}];let n=1;s.forEach(((t,a)=>{if(n*=t.m,e<n)return;const o=s[a===s.length-1?a:a+1].m;i.push({duration:e/n%o|0,type:t.t})}));const a=i.slice(-t).reverse();for(let e=a.length-1;e>=0;--e)0===a[e].duration&&a.splice(e,1);return a}(e,2);if(t){const e=i.map((e=>v.ZP.format(La[e.type],!0,[e.duration])));return(0,v.v_)(e,!1,t)}const s=i.map((e=>(0,v.ag)(La[e.type],[e.duration]))),n=document.createElement("span");return n.append(...(0,v.v_)(s,!1)),n}const Ma={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:"3672990"},AFN:{code:"AFN",title:"Afghan Afghani",symbol:"AFN",native:"؋",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"8893",max_amount:"88930176"},ALL:{code:"ALL",title:"Albanian Lek",symbol:"ALL",native:"Lek",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!1,exp:2,min_amount:"11408",max_amount:"114088432"},AMD:{code:"AMD",title:"Armenian Dram",symbol:"AMD",native:"դր.",thousands_sep:",",decimal_sep:".",symbol_left:!1,space_between:!0,exp:2,min_amount:"41129",max_amount:"411293180"},ARS:{code:"ARS",title:"Argentine Peso",symbol:"ARS",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,exp:2,min_amount:"12503",max_amount:"125036607"},AUD:{code:"AUD",title:"Australian Dollar",symbol:"AU$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"145",max_amount:"1451625"},AZN:{code:"AZN",title:"Azerbaijani Manat",symbol:"AZN",native:"ман.",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"171",max_amount:"1711164"},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:"187",max_amount:"1873042"},BDT:{code:"BDT",title:"Bangladeshi Taka",symbol:"BDT",native:"৳",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"9415",max_amount:"94154281"},BGN:{code:"BGN",title:"Bulgarian Lev",symbol:"BGN",native:"лв.",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"186",max_amount:"1869710"},BND:{code:"BND",title:"Brunei Dollar",symbol:"BND",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!1,exp:2,min_amount:"139",max_amount:"1399458"},BOB:{code:"BOB",title:"Bolivian Boliviano",symbol:"BOB",native:"Bs",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,exp:2,min_amount:"692",max_amount:"6926834"},BRL:{code:"BRL",title:"Brazilian Real",symbol:"R$",native:"R$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,exp:2,min_amount:"518",max_amount:"5182986"},CAD:{code:"CAD",title:"Canadian Dollar",symbol:"CA$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"129",max_amount:"1290450"},CHF:{code:"CHF",title:"Swiss Franc",symbol:"CHF",native:"CHF",thousands_sep:"'",decimal_sep:".",symbol_left:!1,space_between:!0,exp:2,min_amount:"95",max_amount:"954630"},CLP:{code:"CLP",title:"Chilean Peso",symbol:"CLP",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,exp:0,min_amount:"926",max_amount:"9268013"},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:"669",max_amount:"6692902"},COP:{code:"COP",title:"Colombian Peso",symbol:"COP",native:"$",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,exp:2,min_amount:"410927",max_amount:"4109270000"},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:"69166",max_amount:"691668622"},CZK:{code:"CZK",title:"Czech Koruna",symbol:"CZK",native:"Kč",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"2367",max_amount:"23674601"},DKK:{code:"DKK",title:"Danish Krone",symbol:"DKK",native:"kr",thousands_sep:"",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"712",max_amount:"7120540"},DOP:{code:"DOP",title:"Dominican Peso",symbol:"DOP",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"5497",max_amount:"54971796"},DZD:{code:"DZD",title:"Algerian Dinar",symbol:"DZD",native:"د.ج.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"14655",max_amount:"146557782"},EGP:{code:"EGP",title:"Egyptian Pound",symbol:"EGP",native:"ج.م.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"1879",max_amount:"18794601"},EUR:{code:"EUR",title:"Euro",symbol:"€",native:"€",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"95",max_amount:"957150"},GBP:{code:"GBP",title:"British Pound",symbol:"£",native:"£",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"82",max_amount:"822531"},GEL:{code:"GEL",title:"Georgian Lari",symbol:"GEL",native:"GEL",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"293",max_amount:"2939866"},GTQ:{code:"GTQ",title:"Guatemalan Quetzal",symbol:"GTQ",native:"Q",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"781",max_amount:"7811180"},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:"7845675"},HNL:{code:"HNL",title:"Honduran Lempira",symbol:"HNL",native:"L",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"2476",max_amount:"24763692"},HRK:{code:"HRK",title:"Croatian Kuna",symbol:"HRK",native:"kn",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"721",max_amount:"7210988"},HUF:{code:"HUF",title:"Hungarian Forint",symbol:"HUF",native:"Ft",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"37819",max_amount:"378197939"},IDR:{code:"IDR",title:"Indonesian Rupiah",symbol:"IDR",native:"Rp",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!1,exp:2,min_amount:"1490695",max_amount:"14906950000"},ILS:{code:"ILS",title:"Israeli New Sheqel",symbol:"₪",native:"₪",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"348",max_amount:"3480155"},INR:{code:"INR",title:"Indian Rupee",symbol:"₹",native:"₹",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"7894",max_amount:"78945050"},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:"133",max_amount:"1336303"},JMD:{code:"JMD",title:"Jamaican Dollar",symbol:"JMD",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"15175",max_amount:"151753529"},JPY:{code:"JPY",title:"Japanese Yen",symbol:"¥",native:"¥",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:0,min_amount:"136",max_amount:"1362010"},KES:{code:"KES",title:"Kenyan Shilling",symbol:"KES",native:"Ksh",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"11787",max_amount:"117879251"},KGS:{code:"KGS",title:"Kyrgyzstani Som",symbol:"KGS",native:"KGS",thousands_sep:" ",decimal_sep:"-",symbol_left:!1,space_between:!0,exp:2,min_amount:"7950",max_amount:"79509472"},KRW:{code:"KRW",title:"South Korean Won",symbol:"₩",native:"₩",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:0,min_amount:"1297",max_amount:"12971249"},KZT:{code:"KZT",title:"Kazakhstani Tenge",symbol:"KZT",native:"₸",thousands_sep:" ",decimal_sep:"-",symbol_left:!0,space_between:!1,exp:2,min_amount:"47177",max_amount:"471777437"},LBP:{code:"LBP",title:"Lebanese Pound",symbol:"LBP",native:"ل.ل.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"152338",max_amount:"1523381760"},LKR:{code:"LKR",title:"Sri Lankan Rupee",symbol:"LKR",native:"රු.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"36271",max_amount:"362713465"},MAD:{code:"MAD",title:"Moroccan Dirham",symbol:"MAD",native:"د.م.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"1018",max_amount:"10188182"},MDL:{code:"MDL",title:"Moldovan Leu",symbol:"MDL",native:"MDL",thousands_sep:",",decimal_sep:".",symbol_left:!1,space_between:!0,exp:2,min_amount:"1928",max_amount:"19284237"},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:"312408",max_amount:"3124087599"},MUR:{code:"MUR",title:"Mauritian Rupee",symbol:"MUR",native:"MUR",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"4614",max_amount:"46144273"},MVR:{code:"MVR",title:"Maldivian Rufiyaa",symbol:"MVR",native:"MVR",thousands_sep:",",decimal_sep:".",symbol_left:!1,space_between:!0,exp:2,min_amount:"1534",max_amount:"15349670"},MXN:{code:"MXN",title:"Mexican Peso",symbol:"MX$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"2015",max_amount:"20158770"},MYR:{code:"MYR",title:"Malaysian Ringgit",symbol:"MYR",native:"RM",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"440",max_amount:"4406499"},MZN:{code:"MZN",title:"Mozambican Metical",symbol:"MZN",native:"MTn",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"6383",max_amount:"63830365"},NGN:{code:"NGN",title:"Nigerian Naira",symbol:"NGN",native:"₦",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"41513",max_amount:"415132815"},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:"3612",max_amount:"36125609"},NOK:{code:"NOK",title:"Norwegian Krone",symbol:"NOK",native:"kr",thousands_sep:" ",decimal_sep:",",symbol_left:!0,space_between:!0,exp:2,min_amount:"990",max_amount:"9902585"},NPR:{code:"NPR",title:"Nepalese Rupee",symbol:"NPR",native:"नेरू",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"12731",max_amount:"127318435"},NZD:{code:"NZD",title:"New Zealand Dollar",symbol:"NZ$",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"160",max_amount:"1603695"},PAB:{code:"PAB",title:"Panamanian Balboa",symbol:"PAB",native:"B/.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"100",max_amount:"1007566"},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:"381",max_amount:"3818809"},PHP:{code:"PHP",title:"Philippine Peso",symbol:"PHP",native:"₱",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"5499",max_amount:"54994501"},PKR:{code:"PKR",title:"Pakistani Rupee",symbol:"PKR",native:"₨",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"20651",max_amount:"206515440"},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:"446",max_amount:"4466920"},PYG:{code:"PYG",title:"Paraguayan Guaraní",symbol:"PYG",native:"₲",thousands_sep:".",decimal_sep:",",symbol_left:!0,space_between:!0,exp:0,min_amount:"6909",max_amount:"69095662"},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:"3640988"},RON:{code:"RON",title:"Romanian Leu",symbol:"RON",native:"RON",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"473",max_amount:"4736501"},RSD:{code:"RSD",title:"Serbian Dinar",symbol:"RSD",native:"дин.",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"11252",max_amount:"112520089"},RUB:{code:"RUB",title:"Russian Ruble",symbol:"RUB",native:"руб.",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"5282",max_amount:"52825030"},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:"3752099"},SEK:{code:"SEK",title:"Swedish Krona",symbol:"SEK",native:"kr",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"1022",max_amount:"10224070"},SGD:{code:"SGD",title:"Singapore Dollar",symbol:"SGD",native:"$",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"139",max_amount:"1390698"},THB:{code:"THB",title:"Thai Baht",symbol:"฿",native:"฿",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"3529",max_amount:"35290499"},TJS:{code:"TJS",title:"Tajikistani Somoni",symbol:"TJS",native:"TJS",thousands_sep:" ",decimal_sep:";",symbol_left:!1,space_between:!0,exp:2,min_amount:"977",max_amount:"9773409"},TRY:{code:"TRY",title:"Turkish Lira",symbol:"TRY",native:"TL",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"1667",max_amount:"16673549"},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:"684",max_amount:"6847347"},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:"2973",max_amount:"29735499"},TZS:{code:"TZS",title:"Tanzanian Shilling",symbol:"TZS",native:"TSh",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:2,min_amount:"233200",max_amount:"2332000087"},UAH:{code:"UAH",title:"Ukrainian Hryvnia",symbol:"UAH",native:"₴",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!1,exp:2,min_amount:"2974",max_amount:"29741945"},UGX:{code:"UGX",title:"Ugandan Shilling",symbol:"UGX",native:"USh",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!1,exp:0,min_amount:"3788",max_amount:"37883728"},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:"3979",max_amount:"39794286"},UZS:{code:"UZS",title:"Uzbekistani Som",symbol:"UZS",native:"UZS",thousands_sep:" ",decimal_sep:",",symbol_left:!1,space_between:!0,exp:2,min_amount:"1094209",max_amount:"10942099215"},VND:{code:"VND",title:"Vietnamese Đồng",symbol:"₫",native:"₫",thousands_sep:".",decimal_sep:",",symbol_left:!1,space_between:!0,exp:0,min_amount:"23270",max_amount:"232700000"},YER:{code:"YER",title:"Yemeni Rial",symbol:"YER",native:"ر.ي.",thousands_sep:",",decimal_sep:".",symbol_left:!0,space_between:!0,exp:2,min_amount:"25024",max_amount:"250249914"},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:"1624",max_amount:"16246189"}};function Ea(e,t,i){const s=(e=+e)<0,n=Ma[t];if(!n)throw new Error("CURRENCY_WRAP_INVALID");const a=e/Math.pow(10,n.exp);let o=n.exp;"IRR"==t&&Math.floor(a)==a&&(o=0);let r=function(e,t,i,s){e=(e+"").replace(/[^0-9+\-Ee.]/g,"");var n=isFinite(+e)?+e:0,a=isFinite(+t)?Math.abs(t):0,o=void 0===s?",":s,r=void 0===i?".":i,l="";return l=(a?function(e,t){var i=Math.pow(10,t);return""+Math.round(e*i)/i}(n,a):""+Math.round(n)).split("."),l[0].length>3&&(l[0]=l[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,o)),(l[1]||"").length<a&&(l[1]=l[1]||"",l[1]+=new Array(a-l[1].length+1).join("0")),l.join(r)}(a,o,n.decimal_sep,n.thousands_sep);if(i)return r;let l,c=n.symbol;s&&!n.space_between&&n.symbol_left&&(c="-"+c,r=r.replace("-",""));const d=n.space_between?" ":"";return l=n.symbol_left?c+d+r:r+d+c,l}window.p=Ea;var Pa=i(3591);function ka(e){const t=e.action,{onclick:i,url:s}=(0,Pa.Z)(`tg://voicechat?chat_id=${e.peerId.toChatId()}&id=${t.call.id}&access_hash=${t.call.access_hash}`);if(!i)return document.createElement("span");const n=document.createElement("a");return n.href=s,n.setAttribute("onclick",i+"(this)"),n}var Ta=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};function xa(e,t){return Ta(this,void 0,void 0,(function*(){const i=document.createElement("i");return i.dataset.savedFrom=e.peerId+"_"+e.mid,i.dir="auto",i.append(yield Aa(e,void 0,void 0,t)),i}))}function _a(e,t){return i=this,n=void 0,o=function*(){try{return yield function(e,t){var i;return Ta(this,void 0,void 0,(function*(){const n=t?void 0:document.createElement("span"),a="action"in e&&e.action;if(a.message){const e=a.message;return t?(0,Xt.Z)(e):((0,c.Z)(n,(0,ii.Z)(e,{noLinebreaks:!0})),n)}{let o,r,l=a._;const c=s.Z.managers,d=(e,t)=>Ta(this,void 0,void 0,(function*(){return t?(0,Rt.Z)(e,t):new Ot({peerId:e}).element}));switch(a._){case"messageActionPhoneCall":l+="."+a.type,r=[Ia(a.duration,t)];break;case"messageActionGroupCall":l+="."+a.type,r=[],l.endsWith("You")||e.pFlags.post||r.push(d(e.fromId,t)),void 0!==a.duration?r.push(Ia(a.duration,t)):r.push(ka(e));break;case"messageActionInviteToGroupCall":{const i=[e.fromId,a.users[0].toPeerId()];let n="Chat.Service.VoiceChatInvitation";const l=s.Z.myId;i[0]===l?n+="ByYou":i[1]===l&&(n+="ForYou"),(0,T.Z)(i,l),o=n,r=i.map((e=>d(e,t))),r.push(ka(e));break}case"messageActionGroupCallScheduled":{const i=new Date,n=new Date(1e3*a.schedule_date),l=(n.getTime()-i.getTime())/864e5,h=new Date(i);h.setDate(h.getDate()+1);const u=yield c.appPeersManager.isBroadcast(e.peerId);o=u?"ChatList.Service.VoiceChatScheduled.Channel":"ChatList.Service.VoiceChatScheduled",r=[];const p=s.Z.myId;let m;e.fromId===p?o+="You":u||r.push(d(e.fromId,t));const g=[];l<1&&n.getDate()===i.getDate()?m="TodayAtFormattedWithToday":l<2&&n.getDate()===h.getDate()?m="Time.TomorrowAt":(m="formatDateAtTime",g.push(new v.ZP.IntlDateElement({date:n,options:{day:"2-digit",month:"2-digit",year:"2-digit"}}).element)),g.push(V(n));const f=(0,v.ag)(m,g);r.push(f);break}case"messageActionChatCreate":{const i=s.Z.myId;e.fromId===i?l+="You":r=[d(e.fromId,t)];break}case"messageActionPinMessage":{const i=e.peerId,s=yield c.appMessagesManager.getMessageByPeer(i,e.reply_to_mid);r=[d(e.fromId,t)],s?r.push(xa(s,t)):(o="ActionPinnedNoText",e.reply_to_mid&&c.appMessagesManager.fetchMessageReplyTo(e));break}case"messageActionChatJoinedByRequest":{const i=yield c.appPeersManager.isBroadcast(e.peerId);e.pFlags.out?o=i?"RequestToJoinChannelApproved":"RequestToJoinGroupApproved":(o=i?"ChatService.UserJoinedChannelByRequest":"ChatService.UserJoinedGroupByRequest",r=[d(e.fromId,t)]);break}case"messageActionContactSignUp":case"messageActionChatReturn":case"messageActionChatLeave":case"messageActionChatJoined":case"messageActionChatEditPhoto":case"messageActionChatDeletePhoto":case"messageActionChatEditVideo":case"messageActionChatJoinedByLink":case"messageActionChannelEditVideo":case"messageActionChannelDeletePhoto":r=[d(e.fromId,t)];break;case"messageActionChannelEditTitle":case"messageActionChatEditTitle":r=[],"messageActionChatEditTitle"===a._&&r.push(d(e.fromId,t)),r.push(t?a.title:(0,Ca.Z)((0,Zt.Z)(a.title)));break;case"messageActionChatDeleteUser":case"messageActionChatAddUsers":case"messageActionChatAddUser":{const i=a.users||[a.user_id];if(r=[d(e.fromId,t)],i.length>1){const e=(0,v.v_)(yield Promise.all(i.map((e=>d(e.toPeerId(),t)))),!1,t);if(t)r.push(...e);else{const t=document.createElement("span");t.append(...e),r.push(t)}}else r.push(d(i[0].toPeerId(),t));break}case"messageActionBotAllowed":{const e=(0,ii.Z)(a.domain,{entities:[{_:"messageEntityUrl",length:a.domain.length,offset:0}]});r=[(0,Ca.Z)(e)];break}case"messageActionPaymentSent":{const s=a.pFlags.recurring_init,n=a.pFlags.recurring_used;if(o=n?"Chat.Service.PaymentSentRecurringUsedNoTitle":s?"Chat.Service.PaymentSentRecurringInitNoTitle":"Chat.Service.PaymentSent1NoTitle",r=[Ea(a.total_amount,a.currency),d(e.peerId,t)],e.reply_to_mid){const a=yield c.appMessagesManager.getMessageByPeer((null===(i=e.reply_to)||void 0===i?void 0:i.reply_to_peer_id)?(0,es.Z)(e.reply_to.reply_to_peer_id):e.peerId,e.reply_to_mid);a?(o=n?"Chat.Service.PaymentSentRecurringUsed":s?"Chat.Service.PaymentSentRecurringInit":"Chat.Service.PaymentSent1",r.push(xa(a,t).then((e=>(e.classList.add("is-receipt-link"),e))))):c.appMessagesManager.fetchMessageReplyTo(e)}break}default:o=v.Hz[l]||`[${a._}]`}o||(o=v.Hz[l],void 0===o&&(o="["+l+"]"));const h=r&&(yield Promise.all(r));return t?v.ZP.format(o,!0,h):(0,v.$d)(n,o,h)}}))}(e,t)}catch(e){return console.error("wrapMessageActionTextNewUnsafe error:",e),t?"":document.createElement("span")}},new((a=void 0)||(a=Promise))((function(e,t){function s(e){try{l(o.next(e))}catch(e){t(e)}}function r(e){try{l(o.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof a?i:new a((function(e){e(i)}))).then(s,r)}l((o=o.apply(i,n||[])).next())}));var i,n,a,o}function Aa(e,t=e.message,i,n,a,o){return r=this,l=void 0,d=function*(){const r=[];let l=!1;const c=(e,t)=>{if(e){if(void 0===t&&l)return;t=n?v.ZP.format(e,!0):(0,v.ag)(e)}if(n)r.push(t);else{const e=document.createElement("i");"string"==typeof t?e.innerHTML=t:e.append(t),r.push(e)}},d=s.Z.managers.appMessagesManager,h=wa(e);let u=e.totalEntities;if(e.media&&!h){(0,ai.Z)(e);let s=!0;if(e.grouped_id){if(i){const t=yield d.getMidsByMessage(e);if(i.length===t.length){for(const e of t)if(!i.includes(e)){s=!1;break}}else s=!1}if(s){const i=yield d.getAlbumText(e.grouped_id);t=i.message,u=i.totalEntities,o||(c("AttachAlbum"),l=!0)}}else s=!1;if(!s&&!o||!t){const i=e.media;switch(i._){case"messageMediaPhoto":c("AttachPhoto");break;case"messageMediaDice":c(void 0,n?i.emoticon:(0,Zt.Z)(i.emoticon));break;case"messageMediaVenue":t=i.title,c("AttachLocation");break;case"messageMediaGeo":c("AttachLocation");break;case"messageMediaGeoLive":c("AttachLiveLocation");break;case"messageMediaPoll":const e="📊 "+(i.poll.question||"poll");c(void 0,n?e:(0,Zt.Z)(e));break;case"messageMediaContact":c("AttachContact");break;case"messageMediaGame":{const e="🎮 "+i.game.title;c(void 0,n?e:(0,Zt.Z)(e));break}case"messageMediaDocument":{const e=i.document;if("video"===e.type)c("AttachVideo");else if("voice"===e.type)c("AttachAudio");else if("gif"===e.type)c("AttachGif");else if("round"===e.type)c("AttachRound");else if("sticker"===e.type){const i=r.length;if(e.stickerEmojiRaw){const t=e.stickerEmojiRaw+" ";c(void 0,n?t:(0,Zt.Z)(t))}c("AttachSticker");const s=r.splice(i,2);if(n)r.push(s[0]+s[1]);else{const e=window.document.createElement("span");e.append(...s),r.push(e)}t=""}else if("audio"===e.type){const t=e.attributes.find((e=>"documentAttributeAudio"===e._&&(e.title||e.performer))),i="🎵 "+(t?[t.title,t.performer].filter(Boolean).join(" - "):e.file_name);c(void 0,n?i:(0,Zt.Z)(i))}else c(void 0,n?e.file_name:(0,Zt.Z)(e.file_name));break}case"messageMediaInvoice":c(void 0,n?i.title:(0,Zt.Z)(i.title));break;case"messageMediaUnsupported":c(v.nK)}}const a=r.length;for(let e=1;e<a;e+=2)r.splice(e,0,", ");t&&a&&r.push(", ")}if(e.action){const t=yield _a(e,n);t&&c(void 0,t)}if(h&&(t=ya(e.restriction_reason).text,u=[]),t)if(t=(0,Dt.Z)(t,100),u||(u=[]),n)r.push((0,Xt.Z)(t,u));else{if(a){a=a.trim();let e,i=!1;const s=new RegExp(ba(a),"gi");for(u=u.slice();null!==(e=s.exec(t));)u.push({_:"messageEntityHighlight",length:a.length,offset:e.index}),i=!0;i&&(0,Sa.Z)(u)}const e=(0,ii.Z)(t,{noLinebreaks:!0,entities:u,noLinks:!0,noTextFormat:!0});r.push(ga(e))}if(n)return r.join("");{const e=document.createDocumentFragment();return e.append(...r),e}},new((c=void 0)||(c=Promise))((function(e,t){function i(e){try{n(d.next(e))}catch(e){t(e)}}function s(e){try{n(d.throw(e))}catch(e){t(e)}}function n(t){var n;t.done?e(t.value):(n=t.value,n instanceof c?n:new c((function(e){e(n)}))).then(i,s)}n((d=d.apply(r,l||[])).next())}));var r,l,c,d}var Za=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const Fa=32;function Da(e){var t,i;return Za(this,void 0,void 0,(function*(){let{title:s,titleEl:n,subtitle:a,subtitleEl:o,mediaEl:r,message:l,loadPromises:c}=e;void 0!==s&&("string"==typeof s&&(s=(0,Dt.Z)(s,140),s=(0,Zt.Z)(s)),(0,g.Z)(n,s)),c||(c=[]);let d=l&&l.media,h=!1,u=!1;const p=r?Array.from(r.children).slice():[];let m;if(d&&r){if(o.textContent="",o.append(yield Aa(l,void 0,void 0,void 0,void 0,!0)),d.webpage&&(d=d.webpage),d.photo||d.document&&(null===(t=d.document.thumbs)||void 0===t?void 0:t.length)){m=_m.chat.bubbles.getMiddleware();const e=_m.chat.bubbles.lazyLoadQueue;if("sticker"===(null===(i=d.document)||void 0===i?void 0:i.type))h=!0,yield ta({doc:d.document,div:r,lazyLoadQueue:e,group:km,width:Fa,height:Fa,middleware:m,loadPromises:c});else{const t=d.photo||d.document;u="round"===t.type;try{yield dt({photo:t,container:r,boxWidth:Fa,boxHeight:Fa,size:Le(t,Fa,Fa),middleware:m,lazyLoadQueue:e,noBlur:!0,withoutPreloader:!0,loadPromises:c}),h=!0}catch(e){}}}}else l?(o.textContent="",o.append(yield Aa(l))):("string"==typeof a&&(a=(0,Dt.Z)(a,140),a=(0,Zt.Z)(a)),(0,g.Z)(o,a||""));return Promise.all(c).then((()=>{m&&!m()||(p.forEach((e=>e.remove())),r&&r.classList.toggle("is-round",u))})),h}))}class Ra extends ma{constructor(e){super(e,((e,t="",i)=>Za(this,void 0,void 0,(function*(){this.mediaEl||(this.mediaEl=document.createElement("div"),this.mediaEl.classList.add(this.className+"-media"));const s=yield Da({title:e,titleEl:this.title,subtitle:t,subtitleEl:this.subtitle,mediaEl:this.mediaEl,message:i});this.container.classList.toggle("is-media",s),s?this.content.prepend(this.mediaEl):this.mediaEl.remove()})))),this.className=e}}function Ba(e,t,i,s){const n=new Ra("reply"),a=n.fill(e,t,i);if(s){const e=Rs(s,!1),[t,i,a]=(0,pa.oo)(e);n.container.style.setProperty("--override-color",`${t}, ${i}, ${a}`),n.container.classList.add("is-overriding-color")}return{container:n.container,fillPromise:a}}var Na=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};function Ua({set:e,lazyLoadQueue:t,container:i,group:n,autoplay:a,width:o,height:r,managers:l=s.Z.managers}){var c;return Na(this,void 0,void 0,(function*(){if(null===(c=e.thumbs)||void 0===c?void 0:c.length)return i.classList.add("media-sticker-wrapper"),void t.push({div:i,load:()=>Na(this,void 0,void 0,(function*(){const t=yield l.appStickersManager.getStickerSetThumbDownloadOptions(e),s=u.Z.download(t);if(e.pFlags.animated&&!e.pFlags.videos)return s.then((t=>{hi.Z.loadAnimationWorker({container:i,loop:!0,autoplay:a,animationData:t,width:o,height:r,needUpscale:!0,name:"setThumb"+e.id},n)}));{let t;return e.pFlags.videos?(t=ut(),t.autoplay=!0,t.muted=!0,t.loop=!0):t=new Image,t.classList.add("media-sticker"),s.then((s=>{Ae(t,URL.createObjectURL(s),(()=>{i.append(t),e.pFlags.videos&&p.Z.addAnimation(t,n)}))}))}}))});const s=l.appStickersManager.getStickerSet(e),d=yield s;"documentEmpty"!==d.documents[0]._&&ta({doc:d.documents[0],div:i,group:n,lazyLoadQueue:t,managers:l,width:o,height:r})}))}function Oa({doc:e,row:t,size:i,managers:s}){const n=t.media,a=t.createMedia("small");n&&a.classList.add("hide");const o=n?[]:void 0,r="small"===i?32:48,l=ta({div:a,doc:e,width:r,height:r,loadPromises:o,managers:s}).then((({render:e})=>e));return o&&Promise.all(o).then((()=>{a.classList.remove("hide"),n.remove()})),l}var Ha=i(6519);class za{constructor(e){this.updateElementWith=e=>e(),this.updateListWith=e=>e(!0),this.middleware=(0,Ti.k)(),(0,x.Z)(this,e),this.elements=new Map,this.sorted=[]}clear(){this.middleware.clean(),this.elements.clear(),this.sorted.length=0}_updateList(){this.elements.forEach((e=>{this.update(e.id,!0)})),this.onSort&&this.sorted.forEach(((e,t)=>{this.onSort(e,t)}))}updateList(e){const t=this.middleware.get();this.updateListWith((i=>{if(!t()||void 0!==i&&!i)return e(!1);this._updateList(),e(!0)}))}has(e){return this.elements.has(e)}get(e){return this.elements.get(e)}getAll(){return this.elements}add(e,t=!1,i,s=t){let n=this.get(e);if(n)return n;const a={id:e,index:0};return n=this.onElementCreate(a,t),this.elements.set(e,n),this.update(e,s,n,i),n}delete(e,t){const i=this.elements.get(e);if(!i)return!1;this.elements.delete(e);const s=this.sorted.indexOf(i);if(-1!==s&&this.sorted.splice(s,1),this.onDelete)if(t)this.onDelete(i);else{const e=this.middleware.get();this.updateElementWith((()=>{e()&&this.onDelete(i)}))}return!0}update(e,t=!1,i=this.get(e),s){return n=this,a=void 0,r=function*(){if(!i)return;i.index=yield this.getIndex(i),this.onUpdate&&this.onUpdate(i);const e=(0,Ha.Z)(this.sorted,i,"index");if(!t&&this.onSort){const t=this.middleware.get();(s||this.updateElementWith)((()=>{t()&&this.onSort(i,e)}))}},new((o=void 0)||(o=Promise))((function(e,t){function i(e){try{l(r.next(e))}catch(e){t(e)}}function s(e){try{l(r.throw(e))}catch(e){t(e)}}function l(t){var n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o((function(e){e(n)}))).then(i,s)}l((r=r.apply(n,a||[])).next())}));var n,a,o,r}}var Ga=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Va extends za{constructor(e){let t;super({getIndex:e.getIndex||(e=>this.managers.appUsersManager.getUserStatusForSort(e.id)),onDelete:e=>{e.dom.listEl.remove(),this.onListLengthChange&&this.onListLengthChange()},onUpdate:e.onUpdate||(e=>Ga(this,void 0,void 0,(function*(){const t=ce(yield this.managers.appUsersManager.getUser(e.id));(0,g.Z)(e.dom.lastMessageSpan,t)}))),onSort:(e,t)=>{const i=e.dom.listEl.parentElement!==this.list;Ln(e.dom.listEl,this.list,t),i&&this.onListLengthChange&&this.onListLengthChange()},onElementCreate:e=>{const{dom:t}=gg.addDialogNew({peerId:e.id,container:!1,avatarSize:this.avatarSize,autonomous:this.autonomous,meAsSaved:!1,rippleEnabled:this.rippleEnabled,lazyLoadQueue:this.lazyLoadQueue});return e.dom=t,e},updateElementWith:Be.T2,updateListWith:e=>Ga(this,void 0,void 0,(function*(){return(0,Ne.Z)(this.list)?(yield(0,He.e9)(),(0,Ne.Z)(this.list)?void e(!0):e(!1)):e(!1)}))}),this.avatarSize=48,this.rippleEnabled=!0,this.autonomous=!0,(0,x.Z)(this,e),this.list=gg.createChatList(this.createChatListOptions);const i=()=>{t=window.setTimeout((()=>{this.updateList((e=>{e&&i()}))}),Va.SORT_INTERVAL)};i()}}Va.SORT_INTERVAL=3e4;var Ka=i(3444);function Wa(e){let t=!1;return new Ks(Object.assign(Object.assign({},e),{verifyTouchTarget:t=>!(0,r.Z)(t.target,"progress-line")&&!(0,Ka.Z)(t)&&(!e.verifyTouchTarget||e.verifyTouchTarget(t)),onSwipe:(i,s,n)=>{if(!t&&Math.abs(s)>20)return!0;if(Math.abs(i)>Math.abs(s))(0,a.Z)(n),t=!0;else if(!t&&Math.abs(s)>Math.abs(i))return!0;return e.onSwipe(i,s,n)},onReset:()=>{t=!1,e.onReset&&e.onReset()},cancelEvent:!1}))}function $a(e){return Wa(Object.assign(Object.assign({},e),{onSwipe:(t,i,s)=>{if(Math.abs(t)>50)return e.onSwipe(t,i,s),Zi(),!0}}))}class ja extends ms{constructor(e,t,i=!1){super({peerTypes:["dialogs","contacts"],onSelect:i?t:i=>{return s=this,n=void 0,o=function*(){if(t){const e=t(i);e instanceof Promise&&(yield e)}_m.setInnerPeer({peerId:i}),_m.chat.input.initMessagesForward(e)},new((a=void 0)||(a=Promise))((function(e,t){function i(e){try{l(o.next(e))}catch(e){t(e)}}function r(e){try{l(o.throw(e))}catch(e){t(e)}}function l(t){var s;t.done?e(t.value):(s=t.value,s instanceof a?s:new a((function(e){e(s)}))).then(i,r)}l((o=o.apply(s,n||[])).next())}));var s,n,a,o},placeholder:"ShareModal.Search.ForwardPlaceholder",chatRightsAction:"send_messages",selfPresence:"ChatYourSelf"})}}var qa=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Qa{constructor(e,t,i,s){this.peerId=e,this.mids=t,this.type=i,this.onConfirm=s,this.construct()}construct(){return qa(this,void 0,void 0,(function*(){let{peerId:e,mids:t,type:i,onConfirm:n}=this;const a=new Ot({peerId:e}).element,o=A.Z.MANAGERS;t=t.slice();const r=(s,a)=>{n&&n(),"scheduled"===i?o.appMessagesManager.deleteScheduledMessages(e,t):o.appMessagesManager.deleteMessages(e,t,!!s.size||a)},l=[{langKey:"Delete",isDanger:!0,callback:r}],c=[];let d,h,u,p;if(1===t.length?d="DeleteSingleMessagesTitle":(d="DeleteMessagesTitle",h=[(0,v.ag)("messages",[t.length])]),u=(yield o.appPeersManager.isMegagroup(e))?1===t.length?"AreYouSureDeleteSingleMessageMega":"AreYouSureDeleteFewMessagesMega":1===t.length?"AreYouSureDeleteSingleMessage":"AreYouSureDeleteFewMessages",e===s.Z.myId||"scheduled"===i);else if(e.isUser())c.push({text:"DeleteMessagesOptionAlso",textArgs:[a]});else{const i=yield o.appChatsManager.getChat(e.toChatId()),n=(0,Xi.Z)(i,"delete_messages");if("chat"===i._){const i=n?t.slice():yield ki(t,(t=>qa(this,void 0,void 0,(function*(){return(yield o.appMessagesManager.getMessageByPeer(e,t)).fromId===s.Z.myId}))));i.length&&(i.length===t.length?c.push({text:"DeleteForAll"}):(c.push({text:"DeleteMessagesOption"}),u="DeleteMessagesTextGroup",p=[(0,v.ag)("messages",[i.length])]))}else l[0].callback=e=>r(e,!0)}(0,A.x)(l),new qi("popup-delete-chat",{peerId:e,titleLangKey:d,titleLangArgs:h,descriptionLangKey:u,descriptionLangArgs:p,buttons:l,checkboxes:c}).show()}))}}class Ya extends qi{constructor(e,t,i){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:()=>{i&&i(),this.managers.appMessagesManager.sendScheduledMessages(e,t)}}]}),this.show()}}function Ja(){window.getSelection?window.getSelection().empty?window.getSelection().empty():window.getSelection().removeAllRanges&&window.getSelection().removeAllRanges():document.selection&&document.selection.empty()}var Xa=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const eo=e=>[...e.values()].reduce(((e,t)=>e+t.size),0);class to extends L.Z{constructor(e){super(!1),this.selectedMids=new Map,this.isSelecting=!1,this.onMouseDown=e=>{const t=(0,r.Z)(e.target,this.targetLookupClassName);if(0!==e.button)return;if(this.verifyTarget&&!this.verifyTarget(e,t))return;const i=new Map;let s,o=t;const l=(e,t=!0)=>{const n=+e.dataset.mid;if(!n||!e.dataset.peerId)return;const a=e.dataset.peerId.toPeerId();(0,Ne.Z)(o)||(o=e);let r=i.get(a);if(r||i.set(a,r=new Set),r.has(n))return;const c=this.isMidSelected(a,n);if(void 0===s&&(s=!c),r.add(n),s&&!c||!s&&c){const s=eo(i);if(this.toggleByElement&&t){s<2&&(0,vi.Z)(e,o)&&(o=e);const t=this.getElementsBetween(o,e);t.length&&t.forEach((e=>{l(e,!1)}))}if(this.selectedMids.size)this.toggleByElement&&this.toggleByElement(e);else if(2===s&&this.toggleByMid)for(const[e,t]of i)for(const i of t)this.toggleByMid(e,i)}};let c=!1;const d=e=>{c||(Ja(),c=!0);const t=this.getElementFromTarget(e.target);if(t)return this.verifyMouseMoveTarget&&!this.verifyMouseMoveTarget(e,t,s)?(this.listenerSetter.removeManual(this.listenElement,"mousemove",d),void this.listenerSetter.removeManual(document,"mouseup",h,u)):void l(t)},h=e=>{i.size&&(0,n.fc)(window,a.Z,{capture:!0,once:!0,passive:!1}),this.listenerSetter.removeManual(this.listenElement,"mousemove",d),Ja()},u={once:!0};this.listenerSetter.add(this.listenElement)("mousemove",d),this.listenerSetter.add(document)("mouseup",h,u)},this.getElementsBetween=(e,t)=>{if(e===t)return[];const i=e.getBoundingClientRect(),s=t.getBoundingClientRect(),n=(i.top-s.top||i.left-s.left)<0,a=(0,r.Z)(e,this.lookupBetweenParentClassName);if(!a)return[];const o=Array.from(a.querySelectorAll(this.lookupBetweenElementsQuery));let l=o.indexOf(e),c=o.indexOf(t);return n||([c,l]=[l,c]),o.slice(l+1,c)},this.cancelSelection=e=>Xa(this,void 0,void 0,(function*(){e&&(this.doNotAnimate=!0),this.onCancelSelection&&(yield this.onCancelSelection()),this.selectedMids.clear(),this.toggleSelection(),Ja(),e&&(this.doNotAnimate=void 0)})),(0,x.Z)(this,e),this.navigationType="multiselect-"+(0,Hi.a)()}attachListeners(e,t){if(this.listenElement&&this.listenerSetter.removeAll(),this.listenElement=e,this.listenerSetter=t,e)return gi.Z?(t.add(e)("touchend",(()=>{this.isSelecting&&(this.selectedText=window.getSelection?window.getSelection().toString():document.selection?document.selection.createRange().text:"")})),void Fi(e,(t=>{if(this.isSelecting||this.verifyTouchLongPress&&!this.verifyTouchLongPress())return;document.body.classList.add("no-select"),e.addEventListener("touchend",(e=>{(0,a.Z)(e),document.body.classList.remove("no-select")}),{once:!0,capture:!0}),Ja();const i=this.getElementFromTarget(t.target);i&&this.toggleByElement(i)}),t)):void 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 i=!!this.getCheckboxInputFromElement(e);if(t){if(i)return!1;const t=new ji.Z({name:e.dataset.mid,round:!0});this.isSelecting&&this.isElementShouldBeSelected(e)&&(t.input.checked=!0,e.classList.add("is-selected")),this.appendCheckbox(e,t)}else i&&(this.getCheckboxInputFromElement(e).parentElement.remove(),Re(e,"is-selected",!1,200));return!0}getCheckboxInputFromElement(e){var t;return"LABEL"===(null===(t=e.firstElementChild)||void 0===t?void 0:t.tagName)&&e.firstElementChild.firstElementChild}updateContainer(e=!1){return Xa(this,void 0,void 0,(function*(){const t=this.selectedMids.size;if(!t&&!e)return;let i=!t,s=!t;const n=!t;for(const[e,t]of this.selectedMids){const n=`${e}_${this.isScheduled?"scheduled":"history"}`,a=yield this.managers.appMessagesManager.cantForwardDeleteMids(n,Array.from(t));if(i=a.cantForward,s=a.cantDelete,i&&s)break}this.onUpdateContainer&&this.onUpdateContainer(i,s,n)}))}toggleSelection(e=!0,t=!1){const i=this.isSelecting,s=this.selectedMids.size;if(this.isSelecting=!!s||t,i===this.isSelecting)return!1;this.dispatchEvent("toggle",this.isSelecting),gi.Z||(this.listenElement.classList.toggle("no-select",this.isSelecting),i&&Ja()),(0,ln.Z)();const n=!!s||t;return this.onToggleSelection&&this.onToggleSelection(n,!this.doNotAnimate),Je.IS_MOBILE_SAFARI||(n?C.Z.pushItem({type:this.navigationType,onPop:()=>{this.cancelSelection()}}):C.Z.removeByType(this.navigationType)),t&&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),this.getCheckboxInputFromElement(e).checked=t,this.toggleSelection(),this.updateContainer(),Re(e,"is-selected",t,200)}isMidSelected(e,t){const i=this.selectedMids.get(e);return null==i?void 0:i.has(t)}length(){return eo(this.selectedMids)}toggleMid(e,t,i){let s=this.selectedMids.get(e);return i||void 0===i&&(null==s?void 0:s.has(t))?s&&(s.delete(t),s.size||this.selectedMids.delete(e)):(s||(s=new Set,this.selectedMids.set(e,s)),s.add(t)),!0}deleteSelectedMids(e,t){const i=this.selectedMids.get(e);i&&(t.forEach((e=>{i.delete(e)})),i.size||this.selectedMids.delete(e),this.updateContainer(),this.toggleSelection())}}class io extends to{constructor(e,t,i){super({managers:t,verifyTarget:(e,t)=>!!t&&this.isSelecting,getElementFromTarget:e=>(0,r.Z)(e,"search-super-item"),targetLookupClassName:"search-super-item",lookupBetweenParentClassName:"tabs-tab",lookupBetweenElementsQuery:".search-super-item"}),this.searchSuper=e,this.toggleByElement=e=>{const t=+e.dataset.mid,i=e.dataset.peerId.toPeerId();this.toggleMid(i,t)&&this.updateElementSelection(e,this.isMidSelected(i,t))},this.toggleByMid=(e,t)=>{const i=this.searchSuper.mediaTab.contentTab.querySelector(`.search-super-item[data-peer-id="${e}"][data-mid="${t}"]`);this.toggleByElement(i)},this.onUpdateContainer=(e,t,i)=>{const s=this.length();(0,g.Z)(this.selectionCountEl,(0,v.ag)("messages",[s])),this.selectionGotoBtn.classList.toggle("hide",1!==s),this.selectionForwardBtn.classList.toggle("hide",e),this.selectionDeleteBtn&&this.selectionDeleteBtn.classList.toggle("hide",t)},this.onToggleSelection=(e,t)=>{if(Re(this.searchSuper.navScrollableContainer,"is-selecting",e,t?200:0,(()=>{this.isSelecting||(this.selectionContainer.remove(),this.selectionContainer=this.selectionForwardBtn=this.selectionDeleteBtn=null,this.selectedText=void 0)})),Re(this.searchSuper.container,"is-selecting",e,200),this.isSelecting&&!this.selectionContainer){const e="search-super-selection";this.selectionContainer=document.createElement("div"),this.selectionContainer.classList.add(e+"-container");const t=E(`close ${e}-cancel`,{noRipple:!0});(0,n.fc)(t,(()=>this.cancelSelection()),{listenerSetter:this.listenerSetter,once:!0}),this.selectionCountEl=document.createElement("div"),this.selectionCountEl.classList.add(e+"-count"),this.selectionGotoBtn=E(`message ${e}-goto`);const i={listenerSetter:this.listenerSetter};(0,n.fc)(this.selectionGotoBtn,(()=>{const e=[...this.selectedMids.keys()][0],t=[...this.selectedMids.get(e)][0];this.cancelSelection(),_m.setInnerPeer({peerId:e,lastMsgId:t})}),i),this.selectionForwardBtn=E(`forward ${e}-forward`),(0,n.fc)(this.selectionForwardBtn,(()=>{const e={};for(const[t,i]of this.selectedMids)e[t]=Array.from(i).sort(((e,t)=>e-t));new ja(e,(()=>{this.cancelSelection()}))}),i),this.isPrivate&&(this.selectionDeleteBtn=E(`delete danger ${e}-delete`),(0,n.fc)(this.selectionDeleteBtn,(()=>{const e=[...this.selectedMids.keys()][0];new Qa(e,[...this.selectedMids.get(e)],"chat",(()=>{this.cancelSelection()}))}),i)),this.selectionContainer.append(...[t,this.selectionCountEl,this.selectionGotoBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean));const s=this.selectionContainer;s.style.opacity="0",this.searchSuper.navScrollableContainer.append(s),s.offsetLeft,s.style.opacity=""}},this.isPrivate=!e.showSender,this.attachListeners(e.container,i)}toggleSelection(e=!0,t=!1){const i=super.toggleSelection(e,t);return i&&e&&Array.from(this.searchSuper.tabsContainer.querySelectorAll(".search-super-item")).forEach((e=>{this.toggleElementCheckbox(e,this.isSelecting)})),i}}class so extends to{constructor(e,t,i,s){super({managers:s,getElementFromTarget:e=>(0,r.Z)(e,"grouped-item")||(0,r.Z)(e,"bubble"),verifyTarget:(e,t)=>!(!this.selectedMids.size&&!e.target.classList.contains("bubble")&&!e.target.classList.contains("document-selection")&&t),verifyMouseMoveTarget:(e,t,i)=>!(e.target!==t&&!e.target.classList.contains("document-selection")&&void 0===i&&!this.selectedMids.size),verifyTouchLongPress:()=>!this.chat.input.recording,targetLookupClassName:"bubble",lookupBetweenParentClassName:"bubbles-inner",lookupBetweenElementsQuery:".bubble:not(.is-multiple-documents), .grouped-item",isScheduled:"scheduled"===e.type}),this.chat=e,this.bubbles=t,this.input=i,this.toggleByElement=e=>{if(!this.canSelectBubble(e))return;const t=+e.dataset.mid;if(e.classList.contains("is-grouped")){if(!this.isGroupedBubbleSelected(e)){const t=this.selectedMids.get(this.chat.peerId);t&&this.getMidsFromGroupContainer(e).forEach((e=>t.delete(e)))}this.bubbles.getBubbleGroupedItems(e).map(this.toggleByElement)}else if(this.toggleMid(this.chat.peerId,t)){if(e.classList.contains("grouped-item")){const t=(0,r.Z)(e,"bubble"),i=this.isGroupedBubbleSelected(t),s=this.isGroupedMidsSelected(t);(s||i)&&this.updateElementSelection(t,s)}this.updateElementSelection(e,this.isMidSelected(this.chat.peerId,t))}},this.toggleByMid=(e,t)=>Xa(this,void 0,void 0,(function*(){const e=yield this.bubbles.getMountedBubble(t);e&&this.toggleByElement(e.bubble)})),this.onToggleSelection=(e,t)=>Xa(this,void 0,void 0,(function*(){const{needTranslateX:i,widthFrom:s,widthTo:a}=yield this.chat.input.center(t);Re(this.listenElement,"is-selecting",e,t?200:0,(()=>{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 o=s<a?void 0:2*i;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 e={listenerSetter:this.listenerSetter},t=E("close",{noRipple:!0});(0,n.fc)(t,(()=>this.cancelSelection()),{once:!0,listenerSetter:this.listenerSetter}),this.selectionCountEl=document.createElement("div"),this.selectionCountEl.classList.add("selection-container-count"),"scheduled"===this.chat.type?(this.selectionSendNowBtn=(0,M.Z)("btn-primary btn-transparent btn-short text-bold selection-container-send",{icon:"send2"}),this.selectionSendNowBtn.append((0,v.ag)("MessageScheduleSend")),(0,n.fc)(this.selectionSendNowBtn,(()=>{new Ya(this.chat.peerId,[...this.selectedMids.get(this.chat.peerId)],(()=>{this.cancelSelection()}))}),e)):(this.selectionForwardBtn=(0,M.Z)("btn-primary btn-transparent text-bold selection-container-forward",{icon:"forward"}),this.selectionForwardBtn.append((0,v.ag)("Forward")),(0,n.fc)(this.selectionForwardBtn,(()=>{const e={};for(const[t,i]of this.selectedMids)e[t]=Array.from(i).sort(((e,t)=>e-t));new ja(e,(()=>{this.cancelSelection()}))}),e)),this.selectionDeleteBtn=(0,M.Z)("btn-primary btn-transparent danger text-bold selection-container-delete",{icon:"delete"}),this.selectionDeleteBtn.append((0,v.ag)("Delete")),(0,n.fc)(this.selectionDeleteBtn,(()=>{new Qa(this.chat.peerId,[...this.selectedMids.get(this.chat.peerId)],this.chat.type,(()=>{this.cancelSelection()}))}),e);const i=this.selectionLeft=document.createElement("div");i.classList.add("selection-container-left"),i.append(t,this.selectionCountEl);const s=this.selectionRight=document.createElement("div");s.classList.add("selection-container-right"),s.append(...[this.selectionSendNowBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean)),void 0!==o&&(i.style.transform=`translateX(${-o}px)`,s.style.transform=`translateX(${o}px)`),this.selectionContainer.append(i,s),this.selectionInputWrapper.style.opacity="0",this.selectionInputWrapper.append(this.selectionContainer),this.input.inputContainer.append(this.selectionInputWrapper),this.selectionInputWrapper.offsetLeft,this.selectionInputWrapper.style.opacity="",i.style.transform="",s.style.transform=""}}else this.selectionLeft&&void 0!==o&&(this.selectionLeft.style.transform=`translateX(-${o}px)`,this.selectionRight.style.transform=`translateX(${o}px)`)})),this.onUpdateContainer=(e,t,i)=>{(0,g.Z)(this.selectionCountEl,(0,v.ag)("messages",[this.length()])),this.selectionSendNowBtn&&this.selectionSendNowBtn.toggleAttribute("disabled",i),this.selectionForwardBtn&&this.selectionForwardBtn.toggleAttribute("disabled",e),this.selectionDeleteBtn.toggleAttribute("disabled",t)},this.onCancelSelection=()=>Xa(this,void 0,void 0,(function*(){}))}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 i=super.toggleSelection(e,t);if(i&&e)for(const e in this.bubbles.bubbles){if(this.bubbles.skippedMids.has(+e))continue;const t=this.bubbles.bubbles[e];this.toggleElementCheckbox(t,this.isSelecting)}return i}toggleElementCheckbox(e,t){if(!this.canSelectBubble(e))return;const i=super.toggleElementCheckbox(e,t);return i&&e.classList.contains("is-grouped")&&this.bubbles.getBubbleGroupedItems(e).forEach((e=>this.toggleElementCheckbox(e,t))),i}isElementShouldBeSelected(e){const t=e.classList.contains("is-grouped");return super.isElementShouldBeSelected(e)&&(!t||this.isGroupedMidsSelected(e))}isGroupedBubbleSelected(e){const t=this.getCheckboxInputFromElement(e);return null==t?void 0:t.checked}getMidsFromGroupContainer(e){const t=this.chat.bubbles.getBubbleGroupedItems(e);return t.length||t.push(e),t.map((e=>+e.dataset.mid))}isGroupedMidsSelected(e){const t=this.getMidsFromGroupContainer(e),i=t.filter((e=>this.isMidSelected(this.chat.peerId,e)));return t.length===i.length}getCheckboxInputFromElement(e){return e.classList.contains("document-container")?e.querySelector("label input"):super.getCheckboxInputFromElement(e)}canSelectBubble(e){return!(e.classList.contains("service")||e.classList.contains("is-outgoing")||e.classList.contains("bubble-first")||e.classList.contains("avoid-selection"))}}var no=i(7401);function ao(e){const t=(0,Dt.Z)(e.description||"",150,180);return(0,ii.Z)(t)}function oo(e){let t=e.title||e.author||e.site_name||"";return t=(0,Dt.Z)(t,80,100),(0,ii.Z)(t,{noLinks:!0,noLinebreaks:!0})}var ro=i(2342),lo=i(6566),co=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class ho{constructor(e,t,i){this.attachTo=e,this.searchSuper=t,this.listenerSetter=i,this.onGotoClick=()=>{_m.setInnerPeer({peerId:this.peerId,lastMsgId:this.mid,threadId:this.searchSuper.searchContext.threadId})},this.onForwardClick=()=>{this.searchSuper.selection.isSelecting?(0,n.tH)(this.searchSuper.selection.selectionForwardBtn):new ja({[this.peerId]:[this.mid]})},this.onSelectClick=()=>{this.searchSuper.selection.toggleByElement(this.target)},this.onClearSelectionClick=()=>{this.searchSuper.selection.cancelSelection()},this.onDeleteClick=()=>{this.searchSuper.selection.isSelecting?(0,n.tH)(this.searchSuper.selection.selectionDeleteBtn):new Qa(this.peerId,[this.mid],"chat")},this.managers=t.managers;gi.Z||Fi(e,(e=>{let i;this.init&&(this.init(),this.init=null);try{i=(0,r.Z)(e.target,"search-super-item")}catch(e){}if(i){if(e instanceof MouseEvent&&e.preventDefault(),this.element.classList.contains("active"))return!1;e instanceof MouseEvent&&(e.cancelBubble=!0),(()=>{co(this,void 0,void 0,(function*(){this.target=i,this.peerId=i.dataset.peerId.toPeerId(),this.mid=+i.dataset.mid,this.isSelected=t.selection.isMidSelected(this.peerId,this.mid),yield Promise.all(this.buttons.map((e=>co(this,void 0,void 0,(function*(){let t;t=!(this.isSelected&&!e.withSelection)&&(!e.verify||(yield e.verify())),e.element.classList.toggle("hide",!t)}))))),i.classList.add("menu-open"),xi(e,this.element),Ii.openBtnMenu(this.element,(()=>{i.classList.remove("menu-open")}))}))})()}}),i)}init(){this.buttons=[{icon:"forward",text:"Forward",onClick:this.onForwardClick,verify:()=>co(this,void 0,void 0,(function*(){return this.managers.appMessagesManager.canForward(yield this.managers.appMessagesManager.getMessageByPeer(this.peerId,this.mid))}))},{icon:"forward",text:"Message.Context.Selection.Forward",onClick:this.onForwardClick,verify:()=>this.isSelected&&!this.searchSuper.selection.selectionForwardBtn.classList.contains("hide"),withSelection:!0},{icon:"message",text:"Message.Context.Goto",onClick:this.onGotoClick,withSelection:!0},{icon:"select",text:"Message.Context.Select",onClick:this.onSelectClick},{icon:"select",text:"Message.Context.Selection.Clear",onClick:this.onClearSelectionClick,verify:()=>this.isSelected,withSelection:!0},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>co(this,void 0,void 0,(function*(){return this.managers.appMessagesManager.canDeleteMessage(yield this.managers.appMessagesManager.getMessageByPeer(this.peerId,this.mid))}))},{icon:"delete danger",text:"Message.Context.Selection.Delete",onClick:this.onDeleteClick,verify:()=>this.isSelected&&!this.searchSuper.selection.selectionDeleteBtn.classList.contains("hide"),withSelection:!0}],this.element=Ei(this.buttons),this.element.classList.add("search-contextmenu","contextmenu"),document.getElementById("page-chats").append(this.element)}}class uo{constructor(e){this.tabs={},this.prevTabId=-1,this.lazyLoadQueue=new ye,this.middleware=(0,Ti.k)(),this.historyStorage={},this.usedFromHistory={},this.urlsToRevoke=[],this.loadMutex=Promise.resolve(),this.nextRates={},this.loadPromises={},this.loaded={},this.loadedChats=!1,this.firstLoad=!0,this.log=(0,he.kg)("SEARCH-SUPER"),this.monthContainers={},this.mediaTabsMap=new Map,this.asChatList=!1,this.groupByMonth=!0,this.hideEmptyTabs=!0,this.showSender=!1,this.onTransitionStart=()=>{this.container.classList.add("sliding")},this.onTransitionEnd=()=>{this.container.classList.remove("sliding")},(0,x.Z)(this,e),this.container=document.createElement("div"),this.container.classList.add("search-super"),this.listenerSetter=new I.Z,this.searchContextMenu=new ho(this.container,this,this.listenerSetter),this.selection=new io(this,this.managers,this.listenerSetter);const t=this.navScrollableContainer=document.createElement("div");t.classList.add("search-super-tabs-scrollable","menu-horizontal-scrollable","sticky");const i=this.navScrollable=new m.v7(t);i.container.classList.add("search-super-nav-scrollable");const s=this.nav=document.createElement("nav");s.classList.add("search-super-tabs","menu-horizontal-div"),this.tabsMenu=s,i.container.append(s);for(const e of this.mediaTabs){const t=document.createElement("div");t.classList.add("menu-horizontal-div-item");const i=document.createElement("span"),s=document.createElement("i");i.append((0,v.ag)(e.name)),i.append(s),t.append(i),(0,we.Z)(t),this.tabsMenu.append(t),this.mediaTabsMap.set(e.type,e),e.menuTab=t}let o;this.tabsContainer=document.createElement("div"),this.tabsContainer.classList.add("search-super-tabs-container","tabs-container"),gi.Z&&(this.swipeHandler=$a({element:this.tabsContainer,onSwipe:(e,t,i)=>{const s=this.selectTab.prevId(),n=Array.from(this.tabsMenu.children);let r;if(e>0){for(let e=s+1;e<n.length;++e)if(!n[e].classList.contains("hide")){r=e;break}}else for(let e=s-1;e>=0;--e)if(!n[e].classList.contains("hide")){r=e;break}void 0!==r&&(o=function(e){const t=e=>{(0,a.Z)(e)};let i=2;const s=()=>{--i||e.removeEventListener("touchmove",t,{capture:!0})};return e.addEventListener("touchmove",t,{capture:!0,passive:!1}),e.addEventListener("touchend",s,{once:!0}),s}(this.tabsContainer),this.selectTab(r))}}));for(const e of this.mediaTabs){const t=document.createElement("div");t.classList.add("search-super-container-"+e.type,"tabs-tab");const i=document.createElement("div");i.classList.add("search-super-content-"+e.type),t.append(i),this.tabsContainer.append(t),this.tabs[e.inputFilter]=i,e.contentTab=i}this.container.append(t,this.tabsContainer),this.searchGroupMedia=new f(!1,"messages",!0),this.scrollable.onScrolledBottom=()=>{this.mediaTab.contentTab&&this.canLoadMediaTab(this.mediaTab)&&this.load(!0)},this.selectTab=(0,ue.X)(this.tabsMenu,this.tabsContainer,((e,t,i)=>{if(this.prevTabId===e&&!this.skipScroll)return void this.scrollable.scrollIntoViewNew({element:this.container,position:"start",startCallback:this.scrollStartCallback});const s=this.mediaTabs[e];this.onChangeTab&&this.onChangeTab(s);const n=this.mediaTab;if(this.mediaTab=s,-1!==this.prevTabId&&i&&this.onTransitionStart(),this.skipScroll)this.skipScroll=!1;else{const e=this.container.offsetTop;let t=this.scrollable.scrollTop;if(t<e&&(this.scrollable.scrollIntoViewNew({element:this.container,position:"start",startCallback:this.scrollStartCallback}),t=e),n.scroll={scrollTop:t,scrollHeight:this.scrollable.scrollHeight},void 0===s.scroll){const e=this.container.getBoundingClientRect(),i=this.container.parentElement.getBoundingClientRect(),n=e.y-i.y;t>n&&(s.scroll={scrollTop:n,scrollHeight:0})}if(s.scroll){const e=n.scroll.scrollTop-s.scroll.scrollTop;e&&(s.contentTab.style.transform=`translateY(${e}px)`)}}-1===this.prevTabId||s.contentTab.childElementCount||this.load(!0),this.prevTabId=e}),(()=>{this.scrollable.onScroll(),void 0!==this.mediaTab.scroll&&(this.mediaTab.contentTab.style.transform="",this.scrollable.scrollTop=this.mediaTab.scroll.scrollTop),o&&(o(),o=void 0),this.onTransitionEnd()}),void 0,i,this.listenerSetter),(0,n.fc)(this.tabsContainer,(e=>{this.selection.isSelecting&&((0,a.Z)(e),this.selection.toggleByElement((0,r.Z)(e.target,"search-super-item")))}),{capture:!0,passive:!1,listenerSetter:this.listenerSetter});const l=(e,t,i,s)=>co(this,void 0,void 0,(function*(){const n=(0,r.Z)(s.target,e);if(!n)return;const a=+n.dataset.mid;if(!a)return void this.log.warn("no messageId by click on target:",n);const o=n.dataset.peerId.toPeerId(),l=Array.from(this.tabs[i].querySelectorAll("."+t)).map((t=>{const i=(0,r.Z)(t,e);return{element:t,mid:+i.dataset.mid,peerId:i.dataset.peerId.toPeerId()}})),c=l.findIndex((e=>e.mid===a&&e.peerId===o)),d=yield this.managers.appMessagesManager.getMessageByPeer(o,a);(new Rm).setSearchContext(this.copySearchContext(i)).openMedia(d,l[c].element,0,!1,l.slice(0,c),l.slice(c+1))}));(0,n.fc)(this.tabs.inputMessagesFilterPhotoVideo,l.bind(null,"grid-item","grid-item","inputMessagesFilterPhotoVideo"),{listenerSetter:this.listenerSetter}),(0,n.fc)(this.tabs.inputMessagesFilterDocument,l.bind(null,"document-with-thumb","media-container","inputMessagesFilterDocument"),{listenerSetter:this.listenerSetter}),this.mediaTab=this.mediaTabs[0],(0,He.ZP)((()=>{this.lazyLoadQueue.lock()}),(()=>{this.lazyLoadQueue.unlockAndRefresh()}),this.listenerSetter)}filterMessagesByType(e,t){return(0,lo.Z)(t,e,e.length)}processEmptyFilter({message:e,searchGroup:t}){const i=[],{dom:s}=gg.addDialogNew({peerId:e.peerId,container:t.list,avatarSize:54,loadPromises:i}),n=gg.setLastMessageN({dialog:{_:"dialog",peerId:e.peerId},lastMessage:e,dom:s,highlightWord:this.searchContext.query});return i.push(n),Promise.all(i)}processPhotoVideoFilter({message:e,promises:t,middleware:i}){return co(this,void 0,void 0,(function*(){const s=(0,Se.Z)(e),n=document.createElement("div");let a;n.classList.add("grid-item");const o=Le(s,200,200);return a="photo"!==s._?yield(yield qt({doc:s,message:e,container:n,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:i,onlyPreview:!0,withoutPreloader:!0,noPlayButton:!0,size:o})).thumb:yield dt({photo:s,message:e,container:n,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:i,withoutPreloader:!0,noBlur:!0,size:o}),[a.images.thumb,a.images.full].filter(Boolean).forEach((e=>{e.classList.add("grid-item-media")})),t.push(a.loadPromises.thumb),{element:n,message:e}}))}processDocumentFilter({message:e,inputFilter:t}){return co(this,void 0,void 0,(function*(){const i=(0,Se.Z)(e),s=this.showSender||["voice","round"].includes(i.type),n=yield ti({message:e,withTime:!s,fontWeight:400,voiceAsMusic:!0,showSender:s,searchContext:this.copySearchContext(t),lazyLoadQueue:this.lazyLoadQueue,autoDownloadSize:0});return["audio","voice","round"].includes(i.type)&&n.classList.add("audio-48"),{message:e,element:n}}))}processUrlFilter({message:e,promises:t,middleware:i}){var s;return co(this,void 0,void 0,(function*(){let n=null===(s=e.media)||void 0===s?void 0:s.webpage;if(!n){const t=e.totalEntities?e.totalEntities.find((e=>"messageEntityUrl"===e._||"messageEntityTextUrl"===e._)):null;let i,s,a;if(t)a=e.message.slice(t.offset,t.offset+t.length);else{const t=(0,ro.Z)(e.message);if(!t)return;i=t[0]}i="messageEntityTextUrl"===(null==t?void 0:t._)?t.url:i||a,s=i;const o=e.message===i;i.match(/^(ftp|http|https):\/\//)||(s="https://"+i,i=i.includes("@")?i:"https://"+i),s=new URL(s).hostname,n={_:"webPage",url:i,display_url:s,id:"",hash:0},o||(n.description=e.message)}const a=document.createElement("div");a.classList.add("preview","row-media"),n.photo?dt({container:a,message:null,photo:n.photo,boxWidth:0,boxHeight:0,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue,middleware:i,size:Le(n.photo,60,60,!1),loadPromises:t,noBlur:!0}):(a.classList.add("empty"),(0,c.Z)(a,Bs(n.title||n.display_url||n.description||n.url,!0)));const o=oo(n),r=ao(n),l=ga((0,ii.Z)(n.url||"")).firstElementChild;if(l instanceof HTMLAnchorElement)try{l.innerText=decodeURIComponent(l.href)}catch(e){}r.firstChild&&r.append("\n"),r.append(l),this.showSender&&r.append("\n",yield Ht(e)),o.textContent||o.append((0,Xt.Z)(n.display_url.split("/",1)[0]));const d=new Ni({title:o,titleRight:zt(e),subtitle:r,havePadding:!0,clickable:!0,noRipple:!0});if(d.container.append(a),d.container.innerText.trim().length)return{message:e,element:d.container}}))}performSearchResult(e,t,i=!0){return co(this,void 0,void 0,(function*(){const s=[],n=t.contentTab,a=[],o=this.middleware.get();let r,l=t.inputFilter;yield(0,He.e9)(),"inputMessagesFilterPhotoVideo"===l&&this.searchContext.query.trim()?(l="inputMessagesFilterEmpty",r=this.searchGroupMedia,n.append(r.container)):"inputMessagesFilterEmpty"===l&&(r=this.searchGroups.messages);const c={elemsToAppend:s,inputFilter:l,message:void 0,middleware:o,promises:a,searchGroup:r};let d;switch(l){case"inputMessagesFilterEmpty":d=this.processEmptyFilter;break;case"inputMessagesFilterPhotoVideo":d=this.processPhotoVideoFilter;break;case"inputMessagesFilterVoice":case"inputMessagesFilterRoundVoice":case"inputMessagesFilterMusic":case"inputMessagesFilterDocument":d=this.processDocumentFilter;break;case"inputMessagesFilterUrl":d=this.processUrlFilter}if(d){d=d.bind(this);const t=e.map((e=>co(this,void 0,void 0,(function*(){try{return c.message=e,yield d(c)}catch(t){this.log.error("error rendering filter",l,c,e,t)}})))),i=(yield Promise.all(t)).filter(Boolean);s.push(...i.filter(Boolean))}if(r&&r.list.childElementCount&&r.setActive(),this.loadMutex&&a.push(this.loadMutex),!a.length||(yield Promise.all(a),o())){if(s.length){const e=i?"append":"prepend";s.forEach((t=>{var i;const{element:s,message:n}=t,a=this.getMonthContainerByTimestamp(this.groupByMonth?n.date:0,l);s.classList.add("search-super-item"),s.dataset.mid=""+n.mid,s.dataset.peerId=""+n.peerId,a.items[e](s),(null===(i=this.selection)||void 0===i?void 0:i.isSelecting)&&this.selection.toggleElementCheckbox(s,!0)}))}this.afterPerforming("inputMessagesFilterEmpty"===l?1:e.length,n)}}))}afterPerforming(e,t){if(t){const i=t.parentElement;if(Array.from(i.children).slice(1).forEach((e=>{e.remove()})),!e&&!t.childElementCount){const e=document.createElement("div");e.innerText="Nothing interesting here yet...",e.classList.add("position-center","text-center","content-empty","no-select"),i.append(e)}}}loadChats(){const e=new Set,t=this.middleware.get();for(const e in this.searchGroups){const t=this.searchGroups[e];this.tabs.inputMessagesFilterEmpty.append(t.container),t.clear()}const i=this.searchContext.query;if(i){const a=(t,n,a=!1)=>{t.map((t=>{if(e.has(t))return;e.add(t);const{dom:i}=gg.addDialogNew({peerId:t,container:n.list,avatarSize:48,autonomous:n.autonomous});return{dom:i,peerId:t}})).forEach((({dom:e,peerId:t})=>co(this,void 0,void 0,(function*(){const n=yield this.managers.appPeersManager.getPeer(t);if(a&&(n.participants_count||n.participants)){const s=new RegExp(`(${ba(i)}|${ba((0,Yt.ZP)(i))})`,"gi");e.titleSpan.innerHTML=e.titleSpan.innerHTML.replace(s,"<i>$1</i>"),e.lastMessageSpan.append(yield cs(t.toChatId()))}else if(t===s.Z.myId)e.lastMessageSpan.append((0,v.ag)("Presence.YourChat"));else{let i=yield this.managers.appPeersManager.getPeerUsername(t);if(i)i="@"+i;else{const e=yield this.managers.appUsersManager.getUser(t);e&&e.phone&&(i="+"+(0,Ms.u)(e.phone).formatted)}e.lastMessageSpan.innerHTML="<i>"+i+"</i>"}})))),n.toggle()},o=e=>{if(t())return e};return Promise.all([this.managers.appUsersManager.getContactsPeerIds(i,!0).then(o).then((e=>{e&&a(e,this.searchGroups.contacts,!0)})),this.managers.appUsersManager.searchContacts(i,20).then(o).then((e=>{if(e&&(a(e.my_results,this.searchGroups.contacts,!0),a(e.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 e=document.createElement("div");e.classList.add("search-group__show-more");const t=new v.ZP.IntlElement({key:"Separator.ShowMore"});e.append(t.element),this.searchGroups.globalContacts.nameEl.append(e),(0,n.fc)(e,(()=>{const e=this.searchGroups.globalContacts.container.classList.toggle("is-short");t.key=e?"Separator.ShowMore":"Separator.ShowLess",t.update()}))}})),this.managers.appMessagesManager.getConversations(i,0,20,0).then(o).then((e=>{e&&a(e.dialogs.map((e=>e.peerId)),this.searchGroups.contacts,!0)}))])}if(this.searchContext.peerId||this.searchContext.minDate)return Promise.resolve();{const e=(e=!0)=>Gi.Z.getState().then((i=>{t()&&(this.searchGroups.recent.list.innerHTML="",i.recentSearch.slice(0,20).forEach((e=>co(this,void 0,void 0,(function*(){const{dom:t}=gg.addDialogNew({peerId:e,container:this.searchGroups.recent.list,meAsSaved:!0,avatarSize:48,autonomous:!0});t.lastMessageSpan.append(yield e.isUser()?ce(yield this.managers.appUsersManager.getUser(e.toUserId())):cs(e.toChatId()))})))),i.recentSearch.length?e&&this.searchGroups.recent.setActive():this.searchGroups.recent.clear())}));return Promise.all([this.managers.appUsersManager.getTopPeers("correspondents").then((e=>{if(!t())return;const i=e.findIndex((e=>e.id===s.Z.myId));-1!==i&&(e=e.slice()).splice(i,1),e.length&&e.forEach((e=>{gg.addDialogNew({peerId:e.id,container:this.searchGroups.people.list,onlyFirstName:!0,avatarSize:54,autonomous:!1,noIcons:this.searchGroups.people.noIcons})})),this.searchGroups.people.setActive()})),e()])}}loadMembers(e){return co(this,void 0,void 0,(function*(){const t=this.searchContext.peerId.toChatId(),i=this.middleware.get();let s;const a=t=>co(this,void 0,void 0,(function*(){if(!this.loadMutex||(yield this.loadMutex,i())){this.membersList||(this.membersList=new Va({lazyLoadQueue:this.lazyLoadQueue,rippleEnabled:!1,managers:this.managers}),(0,n.fc)(this.membersList.list,(e=>{const t=(0,l.Z)(e.target,dg);if(!t)return;const i=t.dataset.peerId.toPeerId();let s=Promise.resolve();d.Z.isMobile&&(s=nn.toggleSidebar(!1)),s.then((()=>{_m.setInnerPeer({peerId:i})}))})),e.contentTab.append(this.membersList.list),this.afterPerforming(1,e.contentTab));for(const e of t){const t=(0,rs.Z)(e);t.isAnyChat()||((yield this.managers.appUsersManager.getUser(t)).pFlags.deleted||this.membersList.add(t))}}}));if(yield this.managers.appChatsManager.isChannel(t)){const n=this.membersList?200:50;s=this.managers.appProfileManager.getChannelParticipants(t,void 0,n,this.nextRates[e.inputFilter]).then((t=>{if(!i())return;const s=e.contentTab.firstElementChild;return this.nextRates[e.inputFilter]=(s?s.childElementCount:0)+t.participants.length,t.participants.length<n&&(this.loaded[e.inputFilter]=!0),a(t.participants)}))}else s=this.managers.appProfileManager.getChatFull(t).then((t=>{if(!i())return;this.loaded[e.inputFilter]=!0;const s=t.participants;return"chatParticipantsForbidden"!==s._?a(s.participants):void 0}));return this.loadPromises[e.inputFilter]=s.finally((()=>{i()&&(this.loadPromises[e.inputFilter]=null)}))}))}loadType(e,t,i,s){var n;const a=e.inputFilter;if(this.loadPromises[a])return this.loadPromises[a];if("members"===e.type)return this.loadMembers(e);const o=null!==(n=this.historyStorage[a])&&void 0!==n?n:this.historyStorage[a]=[];if(!("inputMessagesFilterEmpty"!==a||o.length||(this.loadedChats||(this.loadChats(),this.loadedChats=!0),this.searchContext.query.trim()||this.searchContext.peerId||this.searchContext.minDate)))return this.loaded[a]=!0,Promise.resolve();const r=this.loadPromises[a]=Promise.resolve().then((()=>co(this,void 0,void 0,(function*(){var n,l;if(o.length&&this.usedFromHistory[a]<o.length&&!t){const t=[];let s=Math.max(0,this.usedFromHistory[a]),n=0;do{const e=o.slice(s,s+i);s+=e.length,n+=e.length;const r=yield Promise.all(e.map((e=>this.managers.appMessagesManager.getMessageByPeer(e.peerId,e.mid))));t.push(...this.filterMessagesByType(r,a))}while(n<i&&s<o.length);return this.usedFromHistory[a]=s,this.performSearchResult(t,e).finally((()=>{setTimeout((()=>{this.scrollable.checkForTriggers()}),0)}))}const c=o.length?o[o.length-1].mid:0,d=yield this.managers.appMessagesManager.getSearch(Object.assign(Object.assign({},this.searchContext),{inputFilter:{_:a},maxId:c,limit:i,nextRate:null!==(n=(l=this.nextRates)[a])&&void 0!==n?n:l[a]=0}));if(o.push(...d.history.map((e=>({mid:e.mid,peerId:e.peerId})))),s()&&((d.history.length<i||void 0!==this.searchContext.folderId&&!d.next_rate||d.history.length===d.count)&&(this.loaded[a]=!0),this.nextRates[a]=d.next_rate,!t))return this.usedFromHistory[a]=o.length,this.loaded[a]||r.then((()=>{setTimeout((()=>{if(s()&&this.mediaTab===e){const e=this.load(!0,!0);e&&e.then((()=>{s()&&setTimeout((()=>{this.scrollable.checkForTriggers()}),0)}))}}),0)})),this.performSearchResult(this.filterMessagesByType(d.history,a),e)})))).catch((e=>{this.log.error("load error:",e)})).finally((()=>{this.loadPromises[a]=null}));return r}canLoadMediaTab(e){const t=e.inputFilter;return!this.loaded[t]||this.historyStorage[t]&&this.usedFromHistory[t]<this.historyStorage[t].length}loadFirstTime(){return co(this,void 0,void 0,(function*(){const e=this.middleware.get(),t=this.searchContext.peerId;if(!this.hideEmptyTabs)return;const i=this.mediaTabs.filter((e=>"inputMessagesFilterEmpty"!==e.inputFilter)),s=i.map((e=>({_:e.inputFilter}))),[n,a]=yield Promise.all([this.managers.appMessagesManager.getSearchCounters(t,s),this.canViewMembers()]);if(!e())return;if(this.loadMutex&&(yield this.loadMutex,!e()))return;let o,r=0;i.forEach((e=>{const t=n.find((t=>t.filter._===e.inputFilter));e.menuTab.classList.toggle("hide",!t.count),e.menuTab.classList.remove("active"),t.count&&(void 0===o&&(o=e),++r)}));const l=this.mediaTabsMap.get("members");l.menuTab.classList.toggle("hide",!a),a&&(o=l),this.container.classList.toggle("hide",!o),this.container.parentElement.classList.toggle("search-empty",!o),o&&(this.skipScroll=!0,this.selectTab(this.mediaTabs.indexOf(o),!1),this.navScrollableContainer.classList.toggle("hide",r<=1))}))}load(e=!1,t=!1){var i;return co(this,void 0,void 0,(function*(){const s=this.searchContext.peerId;this.log("load",e,s,this.loadPromises);const n=this.middleware.get();if(this.firstLoad){if(yield null!==(i=this.loadFirstTimePromise)&&void 0!==i?i:this.loadFirstTimePromise=this.loadFirstTime(),!n())return;this.loadFirstTimePromise=void 0,this.firstLoad=!1}let a=e?[this.mediaTab]:this.mediaTabs.filter((e=>e!==this.mediaTab));if(a=a.filter((e=>this.canLoadMediaTab(e))),s.isUser()&&(0,ge.Z)(a,(e=>"members"===e.type)),!a.length)return;const o=t?50:Math.round(3*(as.height/130|0)*1.25),r=a.map((e=>this.loadType(e,t,o,n)));return Promise.all(r).catch((e=>{this.log.error("Load error all promises:",e)}))}))}getMonthContainerByTimestamp(e,t){var i;const s=new Date(1e3*e);s.setHours(0,0,0),s.setDate(1);const n=s.getTime(),a=null!==(i=this.monthContainers[t])&&void 0!==i?i:this.monthContainers[t]={};if(!(n in a)){const e=document.createElement("div");e.className="search-super-month";const i=document.createElement("div");i.classList.add("search-super-month-name");const o={month:"long"};s.getFullYear()!==(new Date).getFullYear()&&(o.year="numeric");const r=new v.ZP.IntlDateElement({date:s,options:o}).element;i.append(r),e.append(i);const l=document.createElement("div");l.classList.add("search-super-month-items"),e.append(i,l);const c=(0,no.Z)(a,"desc");let d=0;for(;d<c.length&&!(n>c[d]);++d);a[n]={container:e,items:l},Ln(e,this.tabs[t],d)}return a[n]}canViewMembers(){return Promise.all([this.searchContext.peerId.isAnyChat(),this.managers.appChatsManager.isBroadcast(this.searchContext.peerId.toChatId()),this.managers.appChatsManager.hasRights(this.searchContext.peerId.toChatId(),"view_participants")]).then((([e,t,i])=>e&&!t&&i))}cleanup(){var e;this.loadPromises={},this.loaded={},this.loadedChats=!1,this.nextRates={},this.firstLoad=!0,this.prevTabId=-1,this.lazyLoadQueue.clear(),this.mediaTabs.forEach((e=>{this.usedFromHistory[e.inputFilter]=-1})),(null===(e=this.selection)||void 0===e?void 0:e.isSelecting)&&this.selection.cancelSelection(),this.middleware.clean(),this.loadFirstTimePromise=void 0,this.cleanScrollPositions(),this.membersList=void 0}cleanScrollPositions(){this.mediaTabs.forEach((e=>{e.scroll=void 0}))}cleanupHTML(e=!1){this.urlsToRevoke.length&&(this.urlsToRevoke.forEach((e=>{URL.revokeObjectURL(e)})),this.urlsToRevoke.length=0),this.mediaTabs.forEach((e=>{if(e.contentTab.innerHTML="",this.hideEmptyTabs&&(this.container.classList.add("hide"),this.container.parentElement.classList.add("search-empty")),"chats"!==e.type&&!this.historyStorage[e.inputFilter]){const t=e.contentTab.parentElement;t.querySelector(".preloader")||(0,be.y)(t,!0);const i=t.querySelector(".content-empty");i&&i.remove()}})),this.monthContainers={},this.searchGroupMedia.clear(),this.scrollable.scrollTop=0}copySearchContext(e){const t=(0,Ji.Z)(this.searchContext);return t.inputFilter={_:e},t.nextRate=this.nextRates[e],t}setQuery({peerId:e,query:t,threadId:i,historyStorage:s,folderId:n,minDate:a,maxDate:o}){this.searchContext={peerId:e,query:t||"",inputFilter:{_:this.mediaTab.inputFilter},threadId:i,folderId:n,minDate:a,maxDate:o},this.historyStorage=null!=s?s:{},this.cleanup()}destroy(){var e,t;this.listenerSetter.removeAll(),this.scrollable.destroy(),null===(e=this.swipeHandler)||void 0===e||e.removeListeners(),null===(t=this.selection)||void 0===t||t.cleanup(),this.scrollStartCallback=void 0,this.onChangeTab=void 0,this.selectTab=void 0,this.searchContextMenu=void 0,this.swipeHandler=void 0,this.selection=void 0}}const po=(e,t,i,s)=>{((null==i?void 0:i.listenerSetter)?i.listenerSetter.add(e):e.addEventListener.bind(e))(n.pf,(i=>{if(!e.classList.contains("btn-menu-toggle"))return!1;const n=e.querySelector(".btn-menu");if((0,a.Z)(i),e.classList.contains("menu-open"))Ii.close();else{const e=t&&t(i),a=()=>{Ii.openBtnMenu(n,s)};e instanceof Promise?e.then(a):a()}}))},mo=(e={},t,i,s,n)=>{var a;e.asDiv=!0;const o=null!==(a=e.container)&&void 0!==a?a:E("more",e);o.classList.add("btn-menu-toggle");const r=Ei(i,e.listenerSetter);return r.classList.add(t),po(o,s,e,n),o.append(r),o};function go(e){const t=[],i={users:[],chats:[]},s={users:[],chats:[]};return e.forEach((e=>{switch(e._){case"privacyValueAllowAll":t.push(2);break;case"privacyValueDisallowAll":t.push(0);break;case"privacyValueAllowContacts":t.push(1);break;case"privacyValueAllowChatParticipants":i.chats.push(...e.chats);break;case"privacyValueAllowUsers":i.users.push(...e.users);break;case"privacyValueDisallowChatParticipants":s.chats.push(...e.chats);break;case"privacyValueDisallowUsers":s.users.push(...e.users)}})),{type:t[0],disallowPeers:s,allowPeers:i}}var vo;!function(e){e[e.Everybody=2]="Everybody",e[e.Contacts=1]="Contacts",e[e.Nobody=0]="Nobody"}(vo||(vo={}));const fo=vo;class yo{constructor(e){this.options=e,this.onRadioChange=e=>{e=+e,this.type=e;const t=this.options.captions[this.type],i=this.radioSection.caption;t?t instanceof HTMLElement?(0,g.Z)(i,t):(0,v.$d)(i,t):i.innerHTML="",i.classList.toggle("hide",!t),this.exceptions&&(this.exceptions.get("allow").row.container.classList.toggle("hide",this.type===fo.Everybody),this.exceptions.get("disallow").row.container.classList.toggle("hide",this.type===fo.Nobody)),this.options.onRadioChange&&this.options.onRadioChange(e)},e.captions&&e.captions.reverse();const t=e.managers;this.radioSection=new Br({name:e.title,caption:!0}),this.radioRows=new Map;let i=[{type:fo.Everybody,langKey:"PrivacySettingsController.Everbody"},{type:fo.Contacts,langKey:"PrivacySettingsController.MyContacts"},{type:fo.Nobody,langKey:"PrivacySettingsController.Nobody"}];e.skipTypes&&(i=i.filter((t=>!e.skipTypes.includes(t.type))));const s=(0,Hi.a)();i.forEach((({type:e,langKey:t})=>{const i=new Ni({radioField:new Vi({langKey:t,name:s,value:""+e})});this.radioRows.set(e,i)}));const n=Ui([...this.radioRows.values()],this.onRadioChange);if(this.radioSection.content.append(n),e.appendTo&&e.appendTo.append(this.radioSection.container),!e.noExceptions){const t=Nr(e.appendTo,"PrivacyExceptions","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((i=>{i.row=new Ni(i),i.row.container.addEventListener("click",(()=>{a.then((()=>{const t=this.peerIds[i.key];e.tab.slider.createTab(Ts).open({type:"privacy",skippable:!0,title:i.titleLangKey,placeholder:"PrivacyModal.Search.Placeholder",takeOut:e=>{t.length=0,t.push(...e),i.row.subtitle.innerHTML="",i.row.subtitle.append(...this.generateStr(this.splitPeersByType(e)))},selectedPeerIds:t})}))})),t.append(i.row.container)}))}const a=t.appPrivacyManager.getPrivacy(e.inputKey).then((i=>{const s=go(i);this.setRadio(s.type),this.exceptions&&(this.peerIds={},["allow","disallow"].forEach((e=>{const t=[],i="allow"===e?s.allowPeers:s.disallowPeers;t.push(...i.users.map((e=>e.toPeerId()))),t.push(...i.chats.map((e=>e.toPeerId(!0)))),this.peerIds[e]=t;const n=this.exceptions.get(e).row.subtitle;n.innerHTML="",n.append(...this.generateStr(i))}))),e.tab.eventListener.addEventListener("destroy",(()=>{return i=this,s=void 0,a=function*(){const i=[];switch(this.type){case fo.Everybody:i.push({_:"inputPrivacyValueAllowAll"});break;case fo.Contacts:i.push({_:"inputPrivacyValueAllowContacts"});break;case fo.Nobody:i.push({_:"inputPrivacyValueDisallowAll"})}if(this.exceptions){const e=[["allow","inputPrivacyValueAllowChatParticipants","inputPrivacyValueAllowUsers"],["disallow","inputPrivacyValueDisallowChatParticipants","inputPrivacyValueDisallowUsers"]];for(const[s,n,a]of e){if(this.exceptions.get(s).row.container.classList.contains("hide"))return;const e=this.peerIds[s];if(e){const s=this.splitPeersByType(e);s.chats.length&&i.push({_:n,chats:s.chats}),s.users.length&&i.push({_:a,users:yield Promise.all(s.users.map((e=>t.appUsersManager.getUserInput(e))))})}}}t.appPrivacyManager.setPrivacy(e.inputKey,i)},new((n=void 0)||(n=Promise))((function(e,t){function o(e){try{l(a.next(e))}catch(e){t(e)}}function r(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(o,r)}l((a=a.apply(i,s||[])).next())}));var i,s,n,a}),{once:!0})}))}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((e=>{t[e.isAnyChat()?"chats":"users"].push(e.isAnyChat()?e.toChatId():e)})),t}generateStr(e){return e.users.length||e.chats.length?(0,v.v_)([e.users.length?(0,v.ag)("Users",[e.users.length]):null,e.chats.length?(0,v.ag)("Chats",[e.chats.length]):null].filter(Boolean),!1):[(0,v.ag)("PrivacySettingsController.AddUsers")]}}class bo extends k{init(){return e=this,t=void 0,s=function*(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-phone-number"),this.setTitle("PrivacyPhone");const e="+"+(yield this.managers.appUsersManager.getSelf()).phone,t=document.createElement("div");t.append((0,v.ag)("PrivacyPhoneInfo"),document.createElement("br"),document.createElement("br"),(0,v.ag)("PrivacyPhoneInfo4"),document.createElement("br"),function(e={}){const t=document.createElement("a");if(t.classList.add("anchor-copy"),e.mePath){const i="https://t.me/"+e.mePath;t.href=t.innerText=i}return(0,n.fc)(t,(e=>{(0,a.Z)(e),Oi(t.href),Li({langPackKey:"LinkCopied"})})),t}({mePath:e}));const i=new yo({tab:this,title:"PrivacyPhoneTitle",inputKey:"inputPrivacyKeyPhoneNumber",captions:[t,t,""],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,onRadioChange:e=>{o.setRadio(fo.Everybody),o.radioSection.container.classList.toggle("hide",e!==fo.Nobody)},managers:this.managers}),s="PrivacyPhoneInfo3",o=new yo({tab:this,title:"PrivacyPhoneTitle2",inputKey:"inputPrivacyKeyAddedByPhone",captions:[s,s,""],noExceptions:!0,skipTypes:[fo.Nobody],managers:this.managers});this.scrollable.container.insertBefore(o.radioSection.container,i.radioSection.container.nextSibling)},new((i=void 0)||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}));var e,t,i,s}}function wo({emoji:e,div:t,width:i,height:n,managers:a=s.Z.managers}){return o=this,r=void 0,c=function*(){const s=yield a.appStickersManager.getAnimatedEmojiSticker(e);if(!s)throw t.classList.add("media-sticker-wrapper"),new Error("no sticker");return ta({doc:s,div:t,emoji:e,width:i,height:n,loop:!1,play:!0})},new((l=void 0)||(l=Promise))((function(e,t){function i(e){try{n(c.next(e))}catch(e){t(e)}}function s(e){try{n(c.throw(e))}catch(e){t(e)}}function n(t){var n;t.done?e(t.value):(n=t.value,n instanceof l?n:new l((function(e){e(n)}))).then(i,s)}n((c=c.apply(o,r||[])).next())}));var o,r,l,c}class So extends P{init(){this.container.classList.add("two-step-verification","two-step-verification-set"),this.setTitle("TwoStepVerificationPasswordSet");const e=new Br({captionOld:"TwoStepVerificationPasswordSetInfo",noDelimiter:!0}),t=document.createElement("div");wo({emoji:"🥳",div:t,width:160,height:160}),e.content.append(t);const i=e.generateContentElement(),s=document.createElement("div");s.classList.add("input-wrapper");const a=(0,M.Z)("btn-primary btn-color-primary",{text:"TwoStepVerificationPasswordReturnSettings"});(0,n.fc)(a,(e=>{this.close()})),this.slider.sliceTabsUntilTab(Ir,this),s.append(a),i.append(s),this.scrollable.container.append(e.container)}}var Co=i(4489);function Lo(e){return!Je.IS_MOBILE_SAFARI||!e}class Io extends P{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 Br({captionOld:!0,noDelimiter:!0});(0,v.$d)(e.caption,"TwoStepAuth.ConfirmEmailCodeDesc",[this.email]);const t=document.createElement("div");wo({div:t,width:160,height:160,emoji:"📬"}),e.content.append(t);const i=e.generateContentElement(),s=document.createElement("div");s.classList.add("input-wrapper");const a=this.codeInputField=new Co.Z({name:"recovery-email-code",label:"TwoStepAuth.RecoveryCode",length:this.length,onFill:e=>{c(!0),this.managers.passwordManager.confirmPasswordEmail(""+e).then((e=>{l()})).catch((e=>{switch(e.type){case"CODE_INVALID":a.input.classList.add("error"),(0,g.Z)(a.label,(0,v.ag)("TwoStepAuth.RecoveryCodeInvalid"));break;case"EMAIL_HASH_EXPIRED":a.input.classList.add("error"),(0,g.Z)(a.label,(0,v.ag)("TwoStepAuth.RecoveryCodeExpired"));break;default:console.error("confirm error",e)}c(!1)}))}}),o=(0,M.Z)("btn-primary btn-primary-transparent primary",{text:"TwoStepAuth.EmailCodeChangeEmail"}),r=(0,M.Z)("btn-primary btn-secondary btn-primary-transparent primary",{text:"ResendCode"}),l=()=>{this.slider.createTab(So).open()},c=e=>{(0,mi.Z)([a.input,o,r],e)};(0,n.fc)(o,(e=>{c(!0),this.managers.passwordManager.cancelPasswordEmail().then((e=>{this.slider.sliceTabsUntilTab(Po,this),this.close()}),(()=>{c(!1)}))})),(0,n.fc)(r,(e=>{c(!0);const t=(0,be.y)(r);this.managers.passwordManager.resendPasswordEmail().then((e=>{t.remove(),c(!1)}))})),s.append(a.container,o,r),i.append(s),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){Lo(this.isFirst)&&this.codeInputField.input.focus()}}var Mo=i(2423);function Eo(e){return e?e.match(Mo.E):null}class Po extends P{constructor(){super(...arguments),this.isFirst=!1}init(){this.container.classList.add("two-step-verification","two-step-verification-email"),this.setTitle("RecoveryEmailTitle");const e=new Br({captionOld:!0,noDelimiter:!0}),t=document.createElement("div");wo({div:t,width:160,height:160,emoji:"💌"}),e.content.append(t);const i=e.generateContentElement(),s=document.createElement("div");s.classList.add("input-wrapper");const o=this.inputField=new b.Z({name:"recovery-email",label:"RecoveryEmail",plainText:!0});o.input.addEventListener("keypress",(e=>{if("Enter"===e.key)return(0,a.Z)(e),d()})),o.input.addEventListener("input",(e=>{o.input.classList.remove("error")}));const r=(0,M.Z)("btn-primary btn-color-primary",{text:"Continue"}),l=(0,M.Z)("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),c=()=>{this.slider.createTab(So).open()},d=()=>{const e=o.value.trim(),t=Eo(e);if(!t||t[0].length!==e.length)return void o.input.classList.add("error");h(!0);const i=(0,be.y)(r);this.managers.passwordManager.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:e}).then((e=>{c()}),(t=>{if(t.type.includes("EMAIL_UNCONFIRMED")){const i=+t.type.match(/^EMAIL_UNCONFIRMED_(\d+)/)[1],s=this.slider.createTab(Io);s.state=this.state,s.email=e,s.length=i,s.open()}else console.log("password set error",t);h(!1),i.remove()}))};(0,n.fc)(r,d);const h=e=>{e?(r.setAttribute("disabled","true"),l.setAttribute("disabled","true")):(r.removeAttribute("disabled"),l.removeAttribute("disabled"))};(0,n.fc)(l,(e=>{new qi("popup-skip-email",{buttons:[{langKey:"Cancel",isCancel:!0},{langKey:"YourEmailSkip",callback:()=>{h(!0),(0,be.y)(l),this.managers.passwordManager.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:""}).then((()=>{c()}),(e=>{h(!1)}))},isDanger:!0}],titleLangKey:"YourEmailSkipWarning",descriptionLangKey:"YourEmailSkipWarningText"}).show()})),s.append(o.container,r,l),i.append(s),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){Lo(this.isFirst)&&this.inputField.input.focus()}}var ko=i(4425),To=i(6830),xo=i(3083);class _o extends P{init(){this.container.classList.add("two-step-verification","two-step-verification-hint"),this.setTitle("TwoStepAuth.SetupHintTitle");const e=new Br({noDelimiter:!0}),t=document.createElement("div");wo({div:t,width:160,height:160,emoji:"💡"}),e.content.append(t);const i=document.createElement("div");i.classList.add("input-wrapper");const s=this.inputField=new b.Z({name:"hint",label:"TwoStepAuth.SetupHintPlaceholder"});s.input.addEventListener("keypress",(e=>{if("Enter"===e.key)return(0,a.Z)(e),s.value?c():d()}));const o=(e,t)=>{e&&(0,a.Z)(e);const i=t?s.value:void 0;if(i&&this.newPassword===i)return void Ci(v.ZP.format("PasswordAsHintError",!0));const n=this.slider.createTab(Po);n.state=this.state,n.plainPassword=this.plainPassword,n.newPassword=this.newPassword,n.hint=i,n.open()},r=(0,M.Z)("btn-primary btn-color-primary",{text:"Continue"}),l=(0,M.Z)("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),c=e=>o(e,!0),d=e=>o(e,!1);(0,n.fc)(r,c),(0,n.fc)(l,d),i.append(s.container,r,l),e.content.append(i),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){this.inputField.input.focus()}}class Ao extends P{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 Br({noDelimiter:!0}),t=document.createElement("div");t.classList.add("input-wrapper");const i=this.passwordInputField=new To.Z({name:"re-enter-password",label:"PleaseReEnterPassword"}),s=new xo.Z(i,157),o=(0,M.Z)("btn-primary btn-color-primary",{text:"Continue"});t.append(i.container,o),e.content.append(s.container,t),this.scrollable.container.append(e.container),i.input.addEventListener("keypress",(e=>{if(i.input.classList.contains("error")&&i.setState(b.I.Neutral),"Enter"===e.key)return l()}));const r=()=>this.newPassword===i.value||(i.setError(),!1),l=e=>{if(e&&(0,a.Z)(e),!r())return;const t=this.slider.createTab(_o);t.state=this.state,t.plainPassword=this.plainPassword,t.newPassword=this.newPassword,t.open()};return(0,n.fc)(o,l),s.load()}onOpenAfterTimeout(){this.passwordInputField.input.focus()}}class Zo extends P{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 Br({noDelimiter:!0}),i=document.createElement("div");i.classList.add("input-wrapper");const s=this.passwordInputField=new To.Z({name:"enter-password",label:e?"PleaseEnterFirstPassword":this.state.hint?void 0:"LoginPassword",labelText:!e&&this.state.hint?(0,Zt.Z)(this.state.hint):void 0}),o=new ko.Z(s,157),r=(0,M.Z)("btn-primary btn-color-primary"),l=new v.ZP.IntlElement({key:"Continue"});r.append(l.element),i.append(s.container,r),t.content.append(o.container,i),this.scrollable.container.append(t.container),s.input.addEventListener("keypress",(e=>{if(s.input.classList.contains("error")&&(s.input.classList.remove("error"),l.key="Continue",l.update()),"Enter"===e.key)return h()}));const d=()=>!!s.value.length||(s.input.classList.add("error"),!1);let h;if(e)h=e=>{if(e&&(0,a.Z)(e),!d())return;const t=this.slider.createTab(Ao);t.state=this.state,t.newPassword=s.value,t.plainPassword=this.plainPassword,t.open()};else{let e;const t=()=>(e||(e=window.setInterval(t,1e4)),this.managers.passwordManager.getState().then((e=>{this.state=e,this.state.hint?(0,c.Z)(s.label,(0,Zt.Z)(this.state.hint)):(0,g.Z)(s.label,(0,v.ag)("LoginPassword"))})));h=i=>{if(!d())return void(0,a.Z)(i);r.setAttribute("disabled","true"),l.key="PleaseWait",l.update();const n=(0,be.y)(r),c=s.value;this.managers.passwordManager.check(s.value,this.state).then((t=>{if(console.log(t),"auth.authorization"===t._){clearInterval(e),o&&o.remove();const t=this.slider.createTab(Fo);t.state=this.state,t.plainPassword=c,t.open(),this.slider.removeTabFromHistory(this)}}),(e=>{r.removeAttribute("disabled"),s.input.classList.add("error"),e.type,l.key="PASSWORD_HASH_INVALID",l.update(),n.remove(),s.select(),t()}))},t()}return(0,n.fc)(r,h),o.load()}onOpenAfterTimeout(){Lo(this.isFirst)&&this.passwordInputField.input.focus()}}class Fo extends P{init(){this.container.classList.add("two-step-verification","two-step-verification-main"),this.setTitle("TwoStepVerificationTitle");const e=new Br({captionOld:!0,noDelimiter:!0}),t=document.createElement("div");wo({div:t,width:168,height:168,emoji:"🔐"}),e.content.append(t);const i=e.generateContentElement();if(this.state.pFlags.has_password){(0,v.$d)(e.caption,"TwoStepAuth.GenericHelp");const t=(0,M.Z)("btn-primary btn-transparent",{icon:"edit",text:"TwoStepAuth.ChangePassword"}),s=(0,M.Z)("btn-primary btn-transparent",{icon:"passwordoff",text:"TwoStepAuth.RemovePassword"}),a=(0,M.Z)("btn-primary btn-transparent",{icon:"email",text:this.state.pFlags.has_recovery?"TwoStepAuth.ChangeEmail":"TwoStepAuth.SetupEmail"});(0,n.fc)(t,(()=>{const e=this.slider.createTab(Zo);e.state=this.state,e.plainPassword=this.plainPassword,e.open()})),(0,n.fc)(s,(()=>{new qi("popup-disable-password",{buttons:[{langKey:"Disable",callback:()=>{this.managers.passwordManager.updateSettings({currentPassword:this.plainPassword}).then((()=>{this.slider.sliceTabsUntilTab(Ir,this),this.close()}))},isDanger:!0}],titleLangKey:"TurnPasswordOffQuestionTitle",descriptionLangKey:"TurnPasswordOffQuestion"}).show()})),(0,n.fc)(a,(()=>{const e=this.slider.createTab(Po);e.state=this.state,e.hint=this.state.hint,e.plainPassword=this.plainPassword,e.newPassword=this.plainPassword,e.isFirst=!0,e.open()})),i.append(t,s,a)}else{(0,v.$d)(e.caption,"TwoStepAuth.SetPasswordHelp");const t=document.createElement("div");t.classList.add("input-wrapper");const s=(0,M.Z)("btn-primary btn-color-primary",{text:"TwoStepVerificationSetPassword"});t.append(s),i.append(t),(0,n.fc)(s,(e=>{const t=this.slider.createTab(Zo);t.state=this.state,t.open()}))}this.scrollable.container.append(e.container)}}class Do extends k{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-last-seen"),this.setTitle("PrivacyLastSeen");const e="PrivacySettingsController.LastSeenDescription";new yo({tab:this,title:"LastSeenTitle",inputKey:"inputPrivacyKeyStatusTimestamp",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,managers:this.managers})}}class Ro extends k{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-profile-photo"),this.setTitle("PrivacyProfilePhoto");const e="PrivacySettingsController.ProfilePhoto.CustomHelp";new yo({tab:this,title:"PrivacyProfilePhotoTitle",inputKey:"inputPrivacyKeyProfilePhoto",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,skipTypes:[fo.Nobody],managers:this.managers})}}class Bo extends k{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-forward-messages"),this.setTitle("PrivacySettings.Forwards");const e="PrivacySettingsController.Forwards.CustomHelp";new yo({tab:this,title:"PrivacyForwardsTitle",inputKey:"inputPrivacyKeyForwards",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers})}}class No extends k{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-add-to-groups"),this.setTitle("PrivacySettings.Groups");const e="PrivacySettingsController.GroupDescription";new yo({tab:this,title:"WhoCanAddMe",inputKey:"inputPrivacyKeyChatInvite",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,skipTypes:[fo.Nobody],managers:this.managers})}}class Uo extends k{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-calls"),this.setTitle("PrivacySettings.VoiceCalls");const e="PrivacySettingsController.PhoneCallDescription";new yo({tab:this,title:"WhoCanCallMe",inputKey:"inputPrivacyKeyPhoneCall",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers});{const e="PrivacySettingsController.P2p.Desc";new yo({tab:this,title:"PrivacyP2PHeader",inputKey:"inputPrivacyKeyPhoneP2P",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,managers:this.managers})}}}class Oo extends k{init(){this.header.classList.add("with-border"),this.container.classList.add("active-sessions-container"),this.setTitle("SessionsTitle");const e=e=>{const t=new Ni({title:[e.app_name,e.app_version].join(" "),subtitle:[e.ip,e.country].join(" - "),clickable:!0,titleRight:e.pFlags.current?void 0:H(new Date(1e3*Math.max(e.date_active,e.date_created)))});t.container.dataset.hash=""+e.hash;const i=document.createElement("div");return i.classList.add("row-midtitle"),i.innerHTML=[e.device_model,e.system_version||e.platform].filter(Boolean).join(", "),t.subtitle.parentElement.insertBefore(i,t.subtitle),t},t=this.authorizations.slice();{const a=new Br({name:"CurrentSession",caption:"ClearOtherSessionsHelp"}),o=(0,ge.Z)(t,(e=>e.pFlags.current)),r=e(o);if(a.content.append(r.container),t.length){const e=(0,M.Z)("btn-primary btn-transparent danger",{icon:"stop",text:"TerminateAllSessions"});(0,n.fc)(e,(t=>{new qi("revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{const t=(0,mi.Z)([e],!0);this.managers.apiManager.invokeApi("auth.resetAuthorizations").then((t=>{e.remove(),i.container.remove()}),s).finally((()=>{t()}))}}],titleLangKey:"AreYouSureSessionsTitle",descriptionLangKey:"AreYouSureSessions"}).show()})),a.content.append(e)}this.scrollable.append(a.container)}if(!t.length)return;const i=new Br({name:"OtherSessions",caption:"SessionsListInfo"});t.forEach((t=>{i.content.append(e(t).container)})),this.scrollable.append(i.container);const s=e=>{"FRESH_RESET_AUTHORISATION_FORBIDDEN"===e.type&&Ci(v.ZP.format("RecentSessions.Error.FreshReset",!0))};let a;const o=()=>{const e=a.dataset.hash;new qi("revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{this.managers.apiManager.invokeApi("account.resetAuthorization",{hash:e}).then((e=>{e&&a.remove()}),s)}}],titleLangKey:"AreYouSureSessionTitle",descriptionLangKey:"TerminateSessionText"}).show()},l=this.menuElement=Ei([{icon:"stop",text:"Terminate",onClick:o}]);l.id="active-sessions-contextmenu",l.classList.add("contextmenu"),document.getElementById("page-chats").append(l),Fi(this.scrollable.container,(e=>{a=(0,r.Z)(e.target,"row"),a&&"0"!==a.dataset.hash&&(e instanceof MouseEvent&&e.preventDefault(),e instanceof MouseEvent&&(e.cancelBubble=!0),xi(e,l),Ii.openBtnMenu(l))})),(0,n.fc)(this.scrollable.container,(e=>{a=(0,r.Z)(e.target,"row"),a&&"0"!==a.dataset.hash&&o()}))}onCloseAfterTimeout(){return this.menuElement&&this.menuElement.remove(),super.onCloseAfterTimeout()}}class Ho extends P{init(){this.header.classList.add("with-border"),this.container.classList.add("blocked-users-container"),this.setTitle("BlockedUsers");const e=new Br({caption:"BlockedUsersInfo"});e.caption.parentElement.prepend(e.caption),this.scrollable.append(e.container);const t=D({icon:"add",className:"is-visible"});this.content.append(t),(0,n.fc)(t,(e=>{new ms({peerTypes:["contacts"],placeholder:"BlockModal.Search.Placeholder",onSelect:e=>{this.managers.appUsersManager.toggleBlock(e,!0)}})}),{listenerSetter:this.listenerSetter});const i=gg.createChatList();this.scrollable.container.classList.add("chatlist-container"),e.content.append(i);const a=(e,t)=>{return s=this,n=void 0,o=function*(){const{dom:s}=gg.addDialogNew({peerId:e,container:i,rippleEnabled:!0,avatarSize:48,append:t}),n=yield this.managers.appUsersManager.getUser(e);n.pFlags.bot?s.lastMessageSpan.append("@"+n.username):n.phone?s.lastMessageSpan.innerHTML=Es(n.phone):s.lastMessageSpan.append(n.username?"@"+n.username:ce(n))},new((a=void 0)||(a=Promise))((function(e,t){function i(e){try{l(o.next(e))}catch(e){t(e)}}function r(e){try{l(o.throw(e))}catch(e){t(e)}}function l(t){var s;t.done?e(t.value):(s=t.value,s instanceof a?s:new a((function(e){e(s)}))).then(i,r)}l((o=o.apply(s,n||[])).next())}));var s,n,a,o};for(const e of this.peerIds)a(e,!0);let o;const r=this.menuElement=Ei([{icon:"lockoff",text:"Unblock",onClick:()=>{const e=o.dataset.peerId.toPeerId();this.managers.appUsersManager.toggleBlock(e,!1)},options:{listenerSetter:this.listenerSetter}}]);r.id="blocked-users-contextmenu",r.classList.add("contextmenu"),document.getElementById("page-chats").append(r),Fi(this.scrollable.container,(e=>{o=(0,l.Z)(e.target,dg),o&&(e instanceof MouseEvent&&e.preventDefault(),e instanceof MouseEvent&&(e.cancelBubble=!0),xi(e,r),Ii.openBtnMenu(r))}),this.listenerSetter),this.listenerSetter.add(s.Z)("peer_block",(e=>{const{peerId:t,blocked:s}=e,n=i.querySelector(`[data-peer-id="${t}"]`);s?n||a(t,!1):n&&n.remove()}));let c=!1;this.scrollable.onScrolledBottom=()=>{c||(c=!0,this.managers.appUsersManager.getBlocked(i.childElementCount,50).then((e=>{for(const t of e.peerIds)a(t,!0);(e.peerIds.length<50||i.childElementCount===e.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 zo(e){return"input"+(e[0].toUpperCase()+e.slice(1))}class Go extends k{init(){this.header.classList.add("with-border"),this.container.classList.add("dont-u-dare-block-me"),this.setTitle("PrivacySettings");const e="Loading";{const t=new Br({noDelimiter:!0,caption:"SessionsInfo"});let i;const n=new Ni({icon:"deleteuser",titleLangKey:"BlockedUsers",subtitleLangKey:e,clickable:()=>{const e=this.slider.createTab(Ho);e.peerIds=i,e.open()},listenerSetter:this.listenerSetter});let a;n.freezed=!0;const o={icon:"lock",titleLangKey:"TwoStepVerification",subtitleLangKey:e,clickable:e=>{let t;a.pFlags.has_password?t=this.slider.createTab(Zo):a.email_unconfirmed_pattern?(t=this.slider.createTab(Io),t.email=a.email_unconfirmed_pattern,t.length=6,t.isFirst=!0,this.managers.passwordManager.resendPasswordEmail()):t=this.slider.createTab(Fo),t.state=a,t.open()},listenerSetter:this.listenerSetter},r=new Ni(o);r.freezed=!0;const l=this.activeSessionsRow=new Ni({icon:"activesessions",titleLangKey:"SessionsTitle",subtitleLangKey:e,clickable:()=>{const e=this.slider.createTab(Oo);e.authorizations=this.authorizations,e.eventListener.addEventListener("destroy",(()=>{this.updateActiveSessions()}),{once:!0}),e.open()},listenerSetter:this.listenerSetter});l.freezed=!0,t.content.append(n.container,r.container,l.container),this.scrollable.append(t.container);const c=e=>{e?(0,g.Z)(n.subtitle,(0,v.ag)("PrivacySettingsController.UserCount",[e])):(0,g.Z)(n.subtitle,(0,v.ag)("BlockedEmpty",[e]))};this.listenerSetter.add(s.Z)("peer_block",(()=>{d()}));const d=()=>{this.managers.appUsersManager.getBlocked().then((e=>{n.freezed=!1,c(e.count),i=e.peerIds}))};d(),this.managers.passwordManager.getState().then((e=>{a=e,(0,g.Z)(r.subtitle,(0,v.ag)(e.pFlags.has_password?"PrivacyAndSecurity.Item.On":"PrivacyAndSecurity.Item.Off")),r.freezed=!1})),this.updateActiveSessions()}{const t=new Br({name:"PrivacyTitle",caption:"GroupsAndChannelsHelp"});t.content.classList.add("privacy-navigation-container");const i={},n=i.inputPrivacyKeyPhoneNumber=new Ni({titleLangKey:"PrivacyPhoneTitle",subtitleLangKey:e,clickable:()=>{this.slider.createTab(bo).open()},listenerSetter:this.listenerSetter}),a=i.inputPrivacyKeyStatusTimestamp=new Ni({titleLangKey:"LastSeenTitle",subtitleLangKey:e,clickable:()=>{this.slider.createTab(Do).open()},listenerSetter:this.listenerSetter}),o=i.inputPrivacyKeyProfilePhoto=new Ni({titleLangKey:"PrivacyProfilePhotoTitle",subtitleLangKey:e,clickable:()=>{this.slider.createTab(Ro).open()},listenerSetter:this.listenerSetter}),r=i.inputPrivacyKeyPhoneCall=new Ni({titleLangKey:"WhoCanCallMe",subtitleLangKey:e,clickable:()=>{this.slider.createTab(Uo).open()},listenerSetter:this.listenerSetter}),l=i.inputPrivacyKeyForwards=new Ni({titleLangKey:"PrivacyForwardsTitle",subtitleLangKey:e,clickable:()=>{this.slider.createTab(Bo).open()},listenerSetter:this.listenerSetter}),c=i.inputPrivacyKeyChatInvite=new Ni({titleLangKey:"WhoCanAddMe",subtitleLangKey:e,clickable:()=>{this.slider.createTab(No).open()},listenerSetter:this.listenerSetter}),d=e=>{const t=i[e];t&&this.managers.appPrivacyManager.getPrivacy(e).then((e=>{const i=go(e),s=i.type===fo.Everybody?"PrivacySettingsController.Everbody":i.type===fo.Contacts?"PrivacySettingsController.MyContacts":"PrivacySettingsController.Nobody",n=i.disallowPeers.users.length+i.disallowPeers.chats.length,a=i.allowPeers.users.length+i.allowPeers.chats.length;t.subtitle.innerHTML="";const o=(0,v.ag)(s);t.subtitle.append(o),(n||a)&&t.subtitle.append(` (${[-n,a?"+"+a:0].filter(Boolean).join(", ")})`)}))};t.content.append(n.container,a.container,o.container,r.container,l.container,c.container),this.scrollable.append(t.container);for(const e in i)d(e);s.Z.addEventListener("privacy_update",(e=>{d(zo(e.key._))}))}const t=[];{const e=new Br({name:"NewChatsFromNonContacts",caption:"ArchiveAndMuteInfo"}),i=new ji.Z({text:"ArchiveAndMute"}),n=new Ni({checkboxField:i,noCheckboxSubtitle:!0});let a,o;e.content.append(n.container),this.eventListener.addEventListener("destroy",(()=>{o=!0,void 0!==a&&this.managers.appPrivacyManager.setGlobalPrivacySettings({_:"globalPrivacySettings",archive_and_mute_new_noncontact_peers:i.checked})}),{once:!0});const r=Promise.all([this.managers.apiManager.getAppConfig(),this.managers.appPrivacyManager.getGlobalPrivacySettings()]).then((([t,n])=>{if(o)return;const r=i=>{e.container.classList.toggle("hide",!i&&!t.autoarchive_setting_available)};this.listenerSetter.add(s.Z)("premium_toggle",r),r(s.Z.premium),a=n.archive_and_mute_new_noncontact_peers,i.setValueSilently(a)}));t.push(r),this.scrollable.append(e.container)}{const e=new Br({name:"Privacy.SensitiveContent",caption:"PrivacyAndSecurity.SensitiveDesc"});e.container.classList.add("hide");const i=new ji.Z({text:"PrivacyAndSecurity.SensitiveText"}),s=new Ni({checkboxField:i,noCheckboxSubtitle:!0});let n;e.content.append(s.container),this.eventListener.addEventListener("destroy",(()=>{if(void 0===n)return;const e=s.checkboxField.checked;e!==n&&this.managers.apiManager.invokeApi("account.setContentSettings",{sensitive_enabled:e})}),{once:!0});const a=this.managers.apiManager.invokeApi("account.getContentSettings").then((t=>{t.pFlags.sensitive_can_change&&(n=t.pFlags.sensitive_enabled,i.setValueSilently(n),e.container.classList.remove("hide"))}));t.push(a),this.scrollable.append(e.container)}{const e=new Br({name:"PrivacyPayments",caption:"PrivacyPaymentsClearInfo"}),t=()=>{const e={titleLangKey:"PrivacyPaymentsClearAlertTitle",descriptionLangKey:"PrivacyPaymentsClearAlertText",button:{langKey:"Clear"},checkboxes:[{text:"PrivacyClearShipping",checked:!0},{text:"PrivacyClearPayment",checked:!0}]};In(e).then((()=>{const[t,s]=e.checkboxes.map((e=>e.checkboxField.checked)),n=(0,mi.Z)([i],!0);this.managers.appPaymentsManager.clearSavedInfo(t,s).then((()=>{(t||s)&&(n(),Li({langPackKey:t&&s?"PrivacyPaymentsPaymentShippingCleared":t?"PrivacyPaymentsShippingInfoCleared":"PrivacyPaymentsPaymentInfoCleared"}))}))}),ft.Z)},i=(0,M.Z)("btn-primary btn-transparent",{icon:"delete",text:"PrivacyPaymentsClear"});this.listenerSetter.add(i)("click",t),e.content.append(i),this.scrollable.append(e.container)}{const e=new Br({name:"FilterChats"}),t=()=>{new qi("popup-delete-drafts",{buttons:[{langKey:"Delete",callback:()=>{const e=(0,mi.Z)([i],!0);this.managers.appDraftsManager.clearAllDrafts().then((()=>{e()}))},isDanger:!0}],titleLangKey:"AreYouSureClearDraftsTitle",descriptionLangKey:"AreYouSureClearDrafts"}).show()},i=(0,M.Z)("btn-primary btn-transparent",{icon:"delete",text:"PrivacyDeleteCloudDrafts"});this.listenerSetter.add(i)("click",t),e.content.append(i),this.scrollable.append(e.container)}return Promise.all(t)}updateActiveSessions(){this.managers.apiManager.invokeApi("account.getAuthorizations").then((e=>{this.activeSessionsRow.freezed=!1,this.authorizations=e.authorizations,(0,v.$d)(this.activeSessionsRow.subtitle,"Privacy.Devices",[this.authorizations.length])}))}}function Vo(e){const t=e.getContext("2d"),i=new Array(4).fill(0),s=t.getImageData(0,0,e.width,e.height).data,n=s.length/4;for(let e=0;e<s.length;e+=4)i[0]+=s[e],i[1]+=s[e+1],i[2]+=s[e+2],i[3]+=s[e+3];const a=new Uint8ClampedArray(4);return a[0]=i[0]/n,a[1]=i[1]/n,a[2]=i[2]/n,a[3]=i[3]/n,a}function Ko(e){let{h:t,s:i,l:s}=(0,pa.dI)(e[0],e[1],e[2]);return i>0&&(i=Math.min(100,i+5+.1*(100-i))),s=Math.max(0,.65*s),`hsla(${t}, ${i}%, ${s}%, .4)`}class Wo{constructor(){this._width=50,this._height=50,this._tails=90,this._scrollTails=50,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.onWheel=e=>{this._animatingToNextPosition||(this._scrollDelta+=e.deltaY,void 0===this._onWheelRAF&&(this._onWheelRAF=requestAnimationFrame(this.drawOnWheel)))},this.drawOnWheel=()=>{let e=this._scrollDelta/this._scrollTails;if(this._scrollDelta%=this._scrollTails,e=e>0?Math.floor(e):Math.ceil(e),e){this.changeTail(e);const t=this.curPosition(this._phase,this._tail);this.drawGradient(t)}this._onWheelRAF=void 0},this.drawNextPositionAnimated=()=>{const e=this._frames,t=e.shift();t&&this.drawImageData(t);const i=e.length;return i||(this._animatingToNextPosition=void 0),!!i};const e=this._tails/this._curve[this._curve.length-1];for(let t=0,i=this._curve.length;t<i;++t)this._curve[t]=this._curve[t]*e;this._incrementalCurve=this._curve.map(((e,t,i)=>{var s;return e-(null!==(s=i[t-1])&&void 0!==s?s:0)}))}hexToRgb(e){const t=(0,pa.oo)(e);return{r:t[0],g:t[1],b:t[2]}}getPositions(e){const t=this._positions.slice();for(;e>0;)t.push(t.shift()),--e;const i=[];for(let e=0;e<t.length;e+=2)i.push(t[e]);return i}getNextPositions(e,t,i){const s=this.getPositions(e);if(!i[0]&&1===i.length)return[s];const n=this.getPositions(++e%this._phases).map(((e,i)=>({x:(e.x-s[i].x)/t,y:(e.y-s[i].y)/t})));return i.map((e=>n.map(((t,i)=>({x:s[i].x+t.x*e,y:s[i].y+t.y*e})))))}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)}getGradientImageData(e){const t=this._hctx.createImageData(this._width,this._height),i=t.data;let s=0;for(let t=0;t<this._height;++t){const n=t/this._height-.5,a=n*n;for(let t=0;t<this._width;++t){const o=t/this._width-.5,r=.35*Math.sqrt(o*o+a),l=r*r*.8*8,c=Math.sin(l),d=Math.cos(l),h=Math.max(0,Math.min(1,.5+o*d-n*c)),u=Math.max(0,Math.min(1,.5+o*c+n*d));let p=0,m=0,g=0,v=0;for(let t=0;t<this._colors.length;t++){const i=h-e[t].x,s=u-e[t].y;let n=Math.max(0,.9-Math.sqrt(i*i+s*s));n*=n*n*n,p+=n,m+=n*this._colors[t].r/255,g+=n*this._colors[t].g/255,v+=n*this._colors[t].b/255}i[s++]=m/p*255,i[s++]=g/p*255,i[s++]=v/p*255,i[s++]=255}}return t}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,this._scrollDelta=0,void 0!==this._onWheelRAF&&(cancelAnimationFrame(this._onWheelRAF),this._onWheelRAF=void 0);const t=e.getAttribute("data-colors").split(",").reverse();this._colors=t.map((e=>this.hexToRgb(e))),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 e=this._colors[0];return this._ctx.fillStyle=`rgb(${e.r}, ${e.g}, ${e.b})`,void this._ctx.fillRect(0,0,this._width,this._height)}const e=this.curPosition(this._phase,this._tail);this.drawGradient(e)}toNextPosition(){var e;if(this._colors.length<2)return;const t=this._tail,i=this._tails;let s;const n=[];for(let a=0,o=this._incrementalCurve.length;a<o;++a){const o=this._incrementalCurve[a];let r=(null!==(e=n[a-1])&&void 0!==e?e:t)+o;+r.toFixed(2)>i&&void 0===s&&(s=a,r%=i),n.push(r)}[n.slice(0,s),void 0!==s?n.slice(s):[]].forEach(((e,t,s)=>{const n=e[e.length-1];if(void 0!==n&&n>i&&(e[e.length-1]=+n.toFixed(2)),this._tail=null!=n?n:0,!e.length)return;const a=this.getNextPositions(this._phase,i,e);t!==s.length-1&&++this._phase>=this._phases&&(this._phase-=this._phases);const o=a.map((e=>this.getGradientImageData(e)));this._frames.push(...o)})),this._animatingToNextPosition=!0,(0,ht.jt)(this.drawNextPositionAnimated)}scrollAnimate(e){this._colors.length<2&&e||(e&&!this._addedScrollListener?(document.addEventListener("wheel",this.onWheel),this._addedScrollListener=!0):!e&&this._addedScrollListener&&(document.removeEventListener("wheel",this.onWheel),this._addedScrollListener=!1))}cleanup(){this.scrollAnimate(!1)}static createCanvas(e){const t=document.createElement("canvas");return t.width=50,t.height=50,void 0!==e&&(t.dataset.colors=e),t}static create(e){const t=this.createCanvas(e),i=new Wo;return i.init(t),{gradientRenderer:i,canvas:t}}}var $o=i(6714);class jo{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(jo.BASE_CLASS);const e=`\n <svg class="${jo.BASE_CLASS+"-box"}" viewBox="0 0 380 198">\n <defs>\n <linearGradient id="color-picker-saturation" x1="0%" y1="0%" x2="100%" y2="0%">\n <stop offset="0%" stop-color="#fff"></stop>\n <stop offset="100%" stop-color="hsl(0,100%,50%)"></stop>\n </linearGradient>\n <linearGradient id="color-picker-brightness" x1="0%" y1="0%" x2="0%" y2="100%">\n <stop offset="0%" stop-color="rgba(0,0,0,0)"></stop>\n <stop offset="100%" stop-color="#000"></stop>\n </linearGradient>\n <pattern id="color-picker-pattern" width="100%" height="100%">\n <rect x="0" y="0" width="100%" height="100%" fill="url(#color-picker-saturation)"></rect>\n <rect x="0" y="0" width="100%" height="100%" fill="url(#color-picker-brightness)"></rect>\n </pattern>\n </defs>\n <rect rx="10" ry="10" x="0" y="0" width="380" height="198" fill="url(#color-picker-pattern)"></rect>\n <svg class="${jo.BASE_CLASS+"-dragger"} ${jo.BASE_CLASS+"-box-dragger"}" x="0" y="0">\n <circle r="11" fill="inherit" stroke="#fff" stroke-width="2"></circle>\n </svg>\n </svg>\n <div class="${jo.BASE_CLASS+"-sliders"}">\n <svg class="${jo.BASE_CLASS+"-color-slider"}" viewBox="0 0 380 24">\n <defs>\n <linearGradient id="hue" x1="100%" y1="0%" x2="0%" y2="0%">\n <stop offset="0%" stop-color="#f00"></stop>\n <stop offset="16.666%" stop-color="#f0f"></stop>\n <stop offset="33.333%" stop-color="#00f"></stop>\n <stop offset="50%" stop-color="#0ff"></stop>\n <stop offset="66.666%" stop-color="#0f0"></stop>\n <stop offset="83.333%" stop-color="#ff0"></stop>\n <stop offset="100%" stop-color="#f00"></stop>\n </linearGradient>\n </defs>\n <rect rx="4" ry="4" x="0" y="9" width="380" height="8" fill="url(#hue)"></rect>\n <svg class="${jo.BASE_CLASS+"-dragger"} ${jo.BASE_CLASS+"-color-slider-dragger"}" x="0" y="13">\n <circle r="11" fill="inherit" stroke="#fff" stroke-width="2"></circle>\n </svg>\n </svg>\n </div>\n `;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 b.Z({plainText:!0,label:"Appearance.Color.Hex"}),this.rgbInputField=new b.Z({plainText:!0,label:"Appearance.Color.RGB"});const t=document.createElement("div");t.className=jo.BASE_CLASS+"-inputs",t.append(this.hexInputField.container,this.rgbInputField.container),this.container.append(t),this.hexInputField.input.addEventListener("input",(()=>{let e=this.hexInputField.value.replace(/#/g,"").slice(0,6);const t=e.match(/([a-fA-F\d]+)/),i=t&&t[0].length===e.length&&[6].includes(e.length);this.hexInputField.setState(i?b.I.Neutral:b.I.Error),e="#"+e,this.hexInputField.setValueSilently(e),i&&this.setColor(e,!1,!0)}));const i=/^(?: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 e=this.rgbInputField.value.match(i);this.rgbInputField.setState(e?b.I.Neutral:b.I.Error),e&&this.setColor((0,pa.dI)(+e[1],+e[2],+e[3]),!0,!1)})),this.attachBoxListeners(),this.attachHueListeners()}attachBoxListeners(){xt(this.elements.box,(()=>{this.onGrabStart(),this.boxRect=this.elements.box.getBoundingClientRect()}),(e=>{this.saturationHandler(e.x,e.y)}),(()=>{this.onGrabEnd()}))}attachHueListeners(){xt(this.elements.hue,(()=>{this.onGrabStart(),this.hueRect=this.elements.hue.getBoundingClientRect()}),(e=>{this.hueHandler(e.x)}),(()=>{this.onGrabEnd()}))}setColor(e,t=!0,i=!0){if(void 0===e)e={h:0,s:100,l:50,a:1};else if("string"==typeof e)if("#"===e[0])e=(0,pa.cw)(e);else{const t=e.match(/[.?\d]+/g);e=(0,pa.dI)(+t[0],+t[1],+t[2],void 0===t[3]?1:+t[3])}this.boxRect=this.elements.box.getBoundingClientRect();const s=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+s,this.boxRect.top+a,!1),this.hueRect=this.elements.hue.getBoundingClientRect();const o=e.h/360,r=this.hueRect.left+this.hueRect.width*o;this.hueHandler(r,!1),this.hue=e.h,this.saturation=e.s,this.lightness=e.l,this.alpha=e.a,this.updatePicker(t,i)}getCurrentColor(){const e=(0,pa.Y6)(this.hue,this.saturation,this.lightness,this.alpha),t=(0,pa.t1)(e),i=t.slice(0,-2);return{hsl:`hsl(${this.hue}, ${this.saturation}%, ${this.lightness}%)`,rgb:`rgb(${e[0]}, ${e[1]}, ${e[2]})`,hex:i,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 i=this.getCurrentColor();this.elements.boxDragger.setAttributeNS(null,"fill",i.hex),e&&(this.hexInputField.setValueSilently(i.hex),this.hexInputField.setState(b.I.Neutral)),t&&(this.rgbInputField.setValueSilently(i.rgbaArray.slice(0,-1).join(", ")),this.rgbInputField.setState(b.I.Neutral)),this.onChange&&this.onChange(i)}hueHandler(e,t=!0){const i=(0,Me.Z)(e-this.hueRect.left,0,this.hueRect.width)/this.hueRect.width;this.hue=Math.round(360*i);const s=`hsla(${this.hue}, 100%, 50%, ${this.alpha})`;this.elements.hueDragger.setAttributeNS(null,"x",100*i+"%"),this.elements.hueDragger.setAttributeNS(null,"fill",s),this.elements.saturation.lastElementChild.setAttributeNS(null,"stop-color",s),t&&this.updatePicker()}saturationHandler(e,t,i=!0){const s=this.boxRect.width,n=this.boxRect.height,a=(0,Me.Z)(e-this.boxRect.left,0,s)/s*100,o=(0,Me.Z)(t-this.boxRect.top,0,n)/n*100,r=this.elements.boxDragger;r.setAttributeNS(null,"x",a+"%"),r.setAttributeNS(null,"y",o+"%");const l=(0,Me.Z)(a,0,100),c=100-l/2,d=100-(0,Me.Z)(o,0,100),h=(0,Me.Z)(d/100*c,0,100);this.saturation=l,this.lightness=h,i&&this.updatePicker()}}jo.BASE_CLASS="color-picker";class qo extends P{constructor(){super(...arguments),this._applyColor=(e,t=!0)=>{if(t)this.colorPicker.setColor(e);else{const t=(0,pa.Pi)(e),i=this.theme.background,n=Ko(t);i.id="2",i.intensity=0,i.slug="",i.color=e.toLowerCase(),i.highlightningColor=n,this.managers.appStateManager.pushToState("settings",s.Z.settings),_m.applyCurrentTheme(void 0,void 0,!0),this.setActive()}},this.onColorChange=e=>{this.applyColor(e.hex,!1)}}init(){this.header.classList.add("with-border"),this.container.classList.add("background-container","background-color-container"),this.setTitle("SetColor"),this.theme=$o.Z.getTheme();const e=new Br({});this.colorPicker=new jo,e.content.append(this.colorPicker.container),this.scrollable.append(e.container);const t=new Br({}),i=this.grid=document.createElement("div");i.classList.add("grid"),["#E6EBEE","#B2CEE1","#008DD0","#C6E7CB","#C4E1A6","#60B16E","#CCD0AF","#A6A997","#7A7072","#FDD7AF","#FDB76E","#DD8851"].forEach((e=>{const t=document.createElement("div");t.classList.add("grid-item"),t.dataset.color=e.toLowerCase();const s=document.createElement("div");s.classList.add("grid-item-media"),s.style.backgroundColor=e,t.append(s),i.append(t)})),(0,n.fc)(i,(e=>{const t=(0,r.Z)(e.target,"grid-item");if(!t||t.classList.contains("active"))return;const i=t.dataset.color;i&&this.applyColor(i)}),{listenerSetter:this.listenerSetter}),t.content.append(i),this.scrollable.append(t.container),this.applyColor=(0,mt.Z)(this._applyColor,16,!0)}setActive(){const e=this.grid.querySelector(".active"),t=this.theme.background,i=t.color?this.grid.querySelector(`.grid-item[data-color="${t.color}"]`):null;e!==i&&(e&&e.classList.remove("active"),i&&i.classList.add("active"))}onOpen(){setTimeout((()=>{const e=this.theme.background,t=(e.color||"").split(",")[0],i=!!t&&!e.slug;i&&(this.colorPicker.onChange=this.onColorChange),this.colorPicker.setColor(t||"#cccccc"),i||(this.colorPicker.onChange=this.onColorChange)}),0)}onCloseAfterTimeout(){return this.colorPicker.onChange=void 0,this.colorPicker=void 0,super.onCloseAfterTimeout()}}var Qo=i(236);function Yo(e){return new Promise((t=>{var i,s,n;const a=document.createElement("canvas"),o=null!==(i=e.size)&&void 0!==i?i:e.mediaSize.aspectFitted(e.boxSize);a.width=o.width*window.devicePixelRatio,a.height=o.height*window.devicePixelRatio,a.getContext("2d").drawImage(e.media,0,0,a.width,a.height),a.toBlob((e=>{t({blob:e,size:o})}),null!==(s=e.mimeType)&&void 0!==s?s:"image/jpeg",null!==(n=e.quality)&&void 0!==n?n:1)}))}var Jo=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Xo extends P{constructor(){super(...arguments),this.tempId=0,this.clicked=new Set,this.wallPapersByElement=new Map,this.elementsByKey=new Map,this.onUploadClick=()=>{(function(e){const t=document.createElement("input");t.type="file",t.style.display="none",t.accept=e,document.body.append(t);const i=new Promise(((e,i)=>{t.addEventListener("change",(t=>{const s=t.target.files[0];s?e(s):i("NO_FILE_SELECTED")}),{once:!0})})).finally((()=>{t.remove()}));return t.click(),i})("image/x-png,image/png,image/jpeg").then((e=>Jo(this,void 0,void 0,(function*(){if(e.name.endsWith(".png")){const t=document.createElement("img"),i=URL.createObjectURL(e);yield Ze(t,i,!1);const s="image/jpeg",{blob:n}=yield Yo({media:t,size:new ot.c(t.naturalWidth,t.naturalHeight),mimeType:s});e=new File([n],e.name.replace(/\.png$/,".jpg"),{type:s})}const t=yield this.managers.appDocsManager.prepareWallPaperUpload(e),i=this.managers.appDocsManager.uploadWallPaper(t.id),s=u.Z.getNewDeferredForUpload(e.name,i),n=(0,Oe.Z)();n.addNotifyListener=s.addNotifyListener,n.cancel=s.cancel,s.then((e=>{this.clicked.delete(a),this.elementsByKey.delete(a),this.wallPapersByElement.set(r,e);const t=this.getWallPaperKey(e);this.elementsByKey.set(t,r),this.setBackgroundDocument(e).then(n.resolve,n.reject)}),n.reject);const a=this.getWallPaperKey(t);n.catch((()=>{r.remove()}));const o=new Ue({isUpload:!0,cancelable:!0,tryAgainOnFail:!1}),r=this.addWallPaper(t,!1);this.clicked.add(a),o.attach(r,!1,n)}))))},this.onResetClick=()=>{const e=Qo.h.settings.themes.find((e=>e.name===this.theme.name));e&&(++this.tempId,this.theme.background=(0,Ji.Z)(e.background),this.managers.appStateManager.pushToState("settings",s.Z.settings),_m.applyCurrentTheme(void 0,void 0,!0),this.blurCheckboxField.setValueSilently(this.theme.background.blur))},this.onGridClick=e=>{const t=(0,r.Z)(e.target,"grid-item");if(!t)return;const i=this.wallPapersByElement.get(t);if("wallPaperNoFile"===i._)return void this.setBackgroundDocument(i);const s=this.getWallPaperKey(i);if(this.clicked.has(s))return;this.clicked.add(s);const a=i.document,o=new Ue({cancelable:!0,tryAgainOnFail:!1}),l=()=>Jo(this,void 0,void 0,(function*(){const e=this.setBackgroundDocument(i);(yield this.managers.thumbsStorage.getCacheContext(a)).url&&!this.theme.background.blur||o.attach(t,!0,e)}));o.construct(),(0,n.fc)(t,(e=>{o.preloader.parentElement?(o.onClick(e),o.detach()):l()}),{listenerSetter:this.listenerSetter}),l()},this.saveToCache=(e,t)=>{fetch(t).then((t=>{_m.cacheStorage.save("backgrounds/"+e,t)}))},this.setBackgroundDocument=e=>{const t=++this.tempId,i=()=>t===this.tempId,n=e.document,a=(0,Oe.Z)();let o;return n?(o=u.Z.downloadMediaURL({media:n,queueId:_m.chat.bubbles?_m.chat.bubbles.lazyLoadQueue.queueId:0}),a.addNotifyListener=o.addNotifyListener,a.cancel=o.cancel):o=Promise.resolve(),o.then((()=>Jo(this,void 0,void 0,(function*(){if(!i())return void a.resolve();const t=this.theme.background,o=n=>{let o;if(n&&!this.theme.background.color)o=function(e){const t=document.createElement("img");return new Promise((i=>{Ae(t,e,(()=>{i(function(e,t,i){const s=document.createElement("canvas"),n=t/i;return 1===n?(s.width=50,s.height=s.width/n):n>1?(s.height=50,s.width=s.height/n):s.width=s.height=50,s.getContext("2d").drawImage(e,0,0,t,i,0,0,s.width,s.height),Vo(s)}(t,t.naturalWidth,t.naturalHeight))}))}))}(n);else{const{canvas:t}=Wo.create(this.getColorsFromWallPaper(e));o=Promise.resolve(Vo(t))}o.then((o=>{var r,l,c;if(!i())return void a.resolve();const d=Ko(Array.from(o)),h=null!==(r=e.slug)&&void 0!==r?r:"";t.id=e.id,t.intensity=null!==(c=null===(l=e.settings)||void 0===l?void 0:l.intensity)&&void 0!==c?c:0,t.color=this.getColorsFromWallPaper(e),t.slug=h,t.highlightningColor=d,this.managers.appStateManager.pushToState("settings",s.Z.settings),h&&this.saveToCache(h,n),_m.applyCurrentTheme(h,n,!0).then(a.resolve)}))};if(!n)return void o();const r=yield this.managers.thumbsStorage.getCacheContext(n);t.blur?setTimeout((()=>{const{canvas:e,promise:t}=Ye(r.url,12,4);t.then((()=>{i()?o(e.toDataURL()):a.resolve()}))}),200):o(r.url)})))),a},this.setActive=()=>{const e=this.grid.querySelector(".active"),t=this.elementsByKey.get(this.getWallPaperKeyFromTheme(this.theme));e!==t&&(e&&e.classList.remove("active"),t&&t.classList.add("active"))}}get theme(){return $o.Z.getTheme()}init(){this.header.classList.add("with-border"),this.container.classList.add("background-container","background-image-container"),this.setTitle("ChatBackground");{const e=Nr(this.scrollable),i=(0,M.Z)("btn-primary btn-transparent",{icon:"cameraadd",text:"ChatBackground.UploadWallpaper"}),a=(0,M.Z)("btn-primary btn-transparent",{icon:"colorize",text:"SetColor"}),o=(0,M.Z)("btn-primary btn-transparent",{icon:"favourites",text:"Appearance.Reset"});(0,n.fc)(i,this.onUploadClick,{listenerSetter:this.listenerSetter}),(0,n.fc)(a,(()=>{this.slider.createTab(qo).open()}),{listenerSetter:this.listenerSetter}),(0,n.fc)(o,this.onResetClick,{listenerSetter:this.listenerSetter});const r=this.blurCheckboxField=new ji.Z({text:"ChatBackground.Blur",name:"blur",checked:this.theme.background.blur,withRipple:!0});this.listenerSetter.add(r.input)("change",(()=>Jo(this,void 0,void 0,(function*(){this.theme.background.blur=r.input.checked,yield this.managers.appStateManager.pushToState("settings",s.Z.settings),setTimeout((()=>{const e=t.querySelector(".active");if(!e)return;const i=this.wallPapersByElement.get(e);i.pFlags.pattern||"wallPaperNoFile"===i._||this.setBackgroundDocument(i)}),100)})))),e.append(i,a,o,r.label)}s.Z.addEventListener("background_change",this.setActive),this.managers.appDocsManager.getWallPapers().then((e=>{e.forEach((e=>{this.addWallPaper(e)}))}));const e=Nr(this.scrollable),t=this.grid=document.createElement("div");t.classList.add("grid"),(0,n.fc)(t,this.onGridClick,{listenerSetter:this.listenerSetter}),e.append(t)}getColorsFromWallPaper(e){return e.settings?[e.settings.background_color,e.settings.second_background_color,e.settings.third_background_color,e.settings.fourth_background_color].filter(Boolean).map((e=>"#"+e.toString(16))).join(","):""}getWallPaperKey(e){return""+e.id}getWallPaperKeyFromTheme(e){return""+e.background.id}addWallPaper(e,t=!0){const i=this.getColorsFromWallPaper(e),s="wallPaper"===e._;if(s&&e.pFlags.pattern&&!i)return;const n=!!e.pFlags.dark,a=s?e.document:void 0,o=document.createElement("div");o.classList.add("grid-item"),o.dataset.id=""+e.id;const r=this.getWallPaperKey(e);this.wallPapersByElement.set(o,e),this.elementsByKey.set(r,o);const l=document.createElement("div");let c,d;if(l.classList.add("grid-item-media"),s?(d=Le(a,200,200),c=dt({photo:a,message:null,container:l,withoutPreloader:!0,size:d,noFadeIn:e.pFlags.pattern}),e.pFlags.pattern&&l.classList.add("is-pattern"),c.then((({loadPromises:e,images:t})=>Jo(this,void 0,void 0,(function*(){return(yield e.thumb)||e.full,t})))).then((t=>{var i;e.pFlags.pattern&&(n?(t.full.style.display="none",t.thumb&&(t.thumb.style.display="none")):(null===(i=e.settings)||void 0===i?void 0:i.intensity)&&(t.full.style.opacity=""+Math.abs(e.settings.intensity)/100)),Te.Z.mutate((()=>{o.append(l)}))}))):o.append(l),e.settings&&void 0!==e.settings.background_color){const{canvas:t}=Wo.create(i);t.classList.add("background-colors-canvas"),n&&s?c.then((({loadPromises:i})=>{i.full.then((()=>Jo(this,void 0,void 0,(function*(){const i=yield this.managers.thumbsStorage.getCacheContext(a,d.type);t.style.webkitMaskImage=`url(${i.url})`,t.style.opacity=""+(e.pFlags.dark?100+e.settings.intensity:e.settings.intensity)/100,l.append(t)}))))})):l.append(t)}return this.getWallPaperKeyFromTheme(this.theme)===r&&o.classList.add("active"),this.grid[t?"append":"prepend"](o),o}}var er=i(6761);var tr=i(3731);class ir extends P{init(){return this.header.classList.add("with-border"),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((e=>!e.pFlags.inactive));const i=new Br,s=t.map((t=>{const i=new Vi({name:"quick-reaction",text:t.title,value:t.reaction,alignRight:!0}),s=new Ni({radioField:i,havePadding:!0});return i.main.classList.add("quick-reaction-title"),Oa({row:s,doc:t.static_icon,size:"small"}),t.reaction===e.reaction&&i.setValueSilently(!0),s})),n=Ui(s,(e=>{this.managers.appReactionsManager.setDefaultReaction(e)}));i.content.append(n),this.scrollable.append(i.container)}))}}class sr{constructor(e,t,i,s,n,a=!0){const o="range-setting-selector";this.container=document.createElement("div"),this.container.classList.add(o);const r=document.createElement("div");r.classList.add(o+"-details");const l=document.createElement("div");l.classList.add(o+"-name"),(0,v.$d)(l,e);const c=this.valueContainer=document.createElement("div");c.classList.add(o+"-value"),a&&(c.innerHTML=""+i),r.append(l,c),this.range=new _t({step:t,min:s,max:n},i),this.range.setListeners(),this.range.setHandlers({onScrub:e=>{this.onChange&&this.onChange(e),a&&(c.innerText=""+e)}}),this.container.append(r,this.range.container)}}class nr extends k{init(){this.header.classList.add("with-border"),this.container.classList.add("general-settings-container"),this.setTitle("General");const e=Nr.bind(null,this.scrollable);{const t=e("Settings"),i=new sr("TextSize",1,s.Z.settings.messagesTextSize,12,20);i.onChange=e=>{s.Z.managers.appStateManager.setByKey("settings.messagesTextSize",e)};const a=(0,M.Z)("btn-primary btn-transparent",{icon:"image",text:"ChatBackground"});(0,n.fc)(a,(()=>{this.slider.createTab(Xo).open()}));const o=new ji.Z({text:"EnableAnimations",name:"animations",stateKey:"settings.animationsEnabled",withRipple:!0,listenerSetter:this.listenerSetter});t.append(i.container,a,o.label)}{const t=e("General.Keyboard"),i=document.createElement("form"),s="send-shortcut",n="settings.sendShortcut",a=new Ni({radioField:new Vi({langKey:"General.SendShortcut.Enter",name:s,value:"enter",stateKey:n}),subtitleLangKey:"General.SendShortcut.NewLine.ShiftEnter"}),o=new Ni({radioField:new Vi({name:s,value:"ctrlEnter",stateKey:n}),subtitleLangKey:"General.SendShortcut.NewLine.Enter"});(0,v.$d)(o.radioField.main,"General.SendShortcut.CtrlEnter",[Je.IS_APPLE?"⌘":"Ctrl"]),i.append(a.container,o.container),t.append(i)}if(tr.Z){const t=e("DistanceUnitsTitle"),i=document.createElement("form"),s="distance-unit",n="settings.distanceUnit",a=new Ni({radioField:new Vi({langKey:"DistanceUnitsKilometers",name:s,value:"kilometers",stateKey:n})}),o=new Ni({radioField:new Vi({langKey:"DistanceUnitsMiles",name:s,value:"miles",stateKey:n})});i.append(a.container,o.container),t.append(i)}{const t=e("General.TimeFormat"),i=document.createElement("form"),s="time-format",n="settings.timeFormat",a=[["h12","General.TimeFormat.h12"],["h23","General.TimeFormat.h23"]],o=a.map((([e,t])=>new Ni({radioField:new Vi({langKey:t,name:s,value:e,stateKey:n})}))),r=function(e,t=!0){return function(e,t,i=!0){const s=e;let n;return i||(e=ft.Z),function i(){e(),n=er.Z.setTimeout(i,t())}(),e=s,()=>{clearTimeout(n)}}(e,(()=>1e3*(60-(new Date).getSeconds())),t)}((()=>{const e=new Date;a.forEach((([t],i)=>{const s=e.toLocaleTimeString("en-us-u-hc-"+t,{hour:"2-digit",minute:"2-digit"});o[i].subtitle.textContent=s}))}));this.eventListener.addEventListener("destroy",r),i.append(...o.map((e=>e.container))),t.append(i)}{const t=e("Emoji"),i=new ji.Z({text:"GeneralSettings.EmojiPrediction",name:"suggest-emoji",stateKey:"settings.emoji.suggest",withRipple:!0,listenerSetter:this.listenerSetter}),s=new ji.Z({text:"GeneralSettings.BigEmoji",name:"emoji-big",stateKey:"settings.emoji.big",withRipple:!0,listenerSetter:this.listenerSetter});t.append(i.label,s.label)}{const e=new Br({name:"Telegram.InstalledStickerPacksController",caption:"StickersBotInfo"}),t=new Ni({titleLangKey:"DoubleTapSetting",havePadding:!0,clickable:()=>{this.slider.createTab(ir).open()},listenerSetter:this.listenerSetter}),i=()=>{Promise.resolve(this.managers.appReactionsManager.getQuickReaction()).then((e=>{Oa({row:t,doc:e.static_icon,size:"small"})}))};i(),this.listenerSetter.add(s.Z)("quick_reaction",i);const n=new ji.Z({text:"Stickers.SuggestStickers",name:"suggest",stateKey:"settings.stickers.suggest",withRipple:!0,listenerSetter:this.listenerSetter}),a=new ji.Z({text:"InstalledStickers.LoopAnimated",name:"loop",stateKey:"settings.stickers.loop",withRipple:!0,listenerSetter:this.listenerSetter}),o={},r=e.generateContentElement(),l=new ye,c=(e,t="append")=>{const i=new Ni({title:(0,Zt.Z)(e.title),subtitleLangKey:"Stickers",subtitleLangArgs:[e.count],havePadding:!0,clickable:()=>{new qn({id:e.id,access_hash:e.access_hash}).show()},listenerSetter:this.listenerSetter});o[e.id]=i;const s=document.createElement("div");s.classList.add("row-media"),Ua({set:e,container:s,group:"GENERAL-SETTINGS",lazyLoadQueue:l,width:48,height:48,autoplay:!0}),i.container.append(s),r[t](i.container)};this.managers.appStickersManager.getAllStickers().then((e=>{(0,ai.Z)(e);for(const t of e.sets)c(t)})),this.listenerSetter.add(s.Z)("stickers_installed",(e=>{const t=e;o[t.id]||c(t,"prepend")})),this.listenerSetter.add(s.Z)("stickers_deleted",(e=>{const t=e;o[t.id]&&(o[t.id].container.remove(),delete o[t.id])})),e.content.append(t.container,n.label,a.label),this.scrollable.append(e.container)}}onOpen(){this.init&&(this.init(),this.init=null)}}class ar extends P{init(){return e=this,t=void 0,a=function*(){this.container.classList.add("edit-profile-container"),this.setTitle("EditAccount.Title");const e=[];{const t=Nr(this.scrollable,void 0,"Bio.Description"),i=document.createElement("div");i.classList.add("input-wrapper");const n=yield this.managers.apiManager.getAppConfig();this.firstNameInputField=new b.Z({label:"EditProfile.FirstNameLabel",name:"first-name",maxLength:70}),this.lastNameInputField=new b.Z({label:"Login.Register.LastName.Placeholder",name:"last-name",maxLength:64}),this.bioInputField=new b.Z({label:"EditProfile.BioLabel",name:"bio",maxLength:s.Z.premium?n.about_length_limit_premium:n.about_length_limit_default}),i.append(this.firstNameInputField.container,this.lastNameInputField.container,this.bioInputField.container);const a=document.createElement("div");a.classList.add("caption"),(0,v.XZ)({element:a,key:"Bio.Description"}),e.push(this.firstNameInputField,this.lastNameInputField,this.bioInputField),this.editPeer=new Ri({peerId:s.Z.myId,inputFields:e,listenerSetter:this.listenerSetter}),this.content.append(this.editPeer.nextBtn),t.append(this.editPeer.avatarEdit.container,i)}{const t=new Br({name:"EditAccount.Username",caption:!0}),i=document.createElement("div");i.classList.add("input-wrapper"),this.usernameInputField=new $i({label:"EditProfile.Username.Label",name:"username",plainText:!0,listenerSetter:this.listenerSetter,onChange:()=>{this.editPeer.handleChange(),this.setProfileUrl()},availableText:"EditProfile.Username.Available",takenText:"EditProfile.Username.Taken",invalidText:"EditProfile.Username.Invalid"},this.managers),i.append(this.usernameInputField.container);const s=t.caption;s.append((0,v.ag)("UsernameSettings.ChangeDescription")),s.append(document.createElement("br"),document.createElement("br"));const n=this.profileUrlContainer=document.createElement("div");n.classList.add("profile-url-container");const a=this.profileUrlAnchor=document.createElement("a");a.classList.add("profile-url"),a.href="#",a.target="_blank",n.append((0,v.ag)("UsernameHelpLink",[a])),s.append(n),e.push(this.usernameInputField),t.content.append(i),this.scrollable.append(t.container)}(0,n.fc)(this.editPeer.nextBtn,(()=>{this.editPeer.nextBtn.disabled=!0;const e=[];e.push(this.managers.appProfileManager.updateProfile(this.firstNameInputField.value,this.lastNameInputField.value,this.bioInputField.value).then((()=>{this.close()}),(e=>{console.error("updateProfile error:",e)}))),this.editPeer.uploadAvatar&&e.push(this.editPeer.uploadAvatar().then((e=>this.managers.appProfileManager.uploadProfilePhoto(e)))),this.usernameInputField.isValidToChange()&&e.push(this.managers.appUsersManager.updateUsername(this.usernameInputField.value)),Promise.race(e).finally((()=>{this.editPeer.nextBtn.removeAttribute("disabled")}))}),{listenerSetter:this.listenerSetter});const t=yield this.managers.appUsersManager.getSelf(),i=yield this.managers.appProfileManager.getProfile(t.id,!0);this.firstNameInputField.setOriginalValue(t.first_name,!0),this.lastNameInputField.setOriginalValue(t.last_name,!0),this.bioInputField.setOriginalValue(i.about,!0),this.usernameInputField.setOriginalValue(t.username,!0),this.setProfileUrl(),this.editPeer.handleChange()},new((i=void 0)||(i=Promise))((function(s,n){function o(e){try{l(a.next(e))}catch(e){n(e)}}function r(e){try{l(a.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((a=a.apply(e,t||[])).next())}));var e,t,i,a}setProfileUrl(){if(this.usernameInputField.input.classList.contains("error")||!this.usernameInputField.value.length)this.profileUrlContainer.style.display="none";else{this.profileUrlContainer.style.display="";const e="https://t.me/"+this.usernameInputField.value;this.profileUrlAnchor.innerText=e,this.profileUrlAnchor.href=e}}}var or=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class rr extends P{constructor(){super(...arguments),this.renderResults=e=>or(this,void 0,void 0,(function*(){yield this.managers.appUsersManager.getContacts(),e.forEach((e=>{const{dom:t}=gg.addDialogNew({peerId:e,container:this.selector.scrollable,rippleEnabled:!0,avatarSize:46}),i=this.selector.selected.has(e);t.containerEl.append(this.checkbox(i));const s=[];this.dialogsByFilters.forEach(((t,i)=>{if(t.has(e)){const e=document.createElement("span");(0,c.Z)(e,(0,Zt.Z)(i.title)),s.push(e)}})),(0,v.v_)(s,!1).forEach((e=>{t.lastMessageSpan.append(e)}))}))})),this.onSelectChange=e=>{"included"===this.type&&(this.confirmBtn.style.display=e?"":"none")}}init(){this.content.remove(),this.container.classList.add("included-chatlist-container"),this.confirmBtn=E("check btn-confirm blue",{noRipple:!0}),this.confirmBtn.style.display="none",this.header.append(this.confirmBtn),(0,n.fc)(this.confirmBtn,(()=>or(this,void 0,void 0,(function*(){const e=this.selector.getSelected();if("included"===this.type)for(const e in this.filter.pFlags)0!==e.indexOf("exclude_")&&delete this.filter.pFlags[e];else for(const e in this.filter.pFlags)0===e.indexOf("exclude_")&&delete this.filter.pFlags[e];const t=[];for(const i of e)i.isPeerId()?t.push(i.toPeerId()):this.filter.pFlags[i]=!0;let i;i="included"===this.type?e=>t.includes(e):e=>!t.includes(e),(0,Mn.Z)(this.filter.pinnedPeerIds,((e,t)=>{i(e)||(this.filter.pinnedPeerIds.splice(t,1),this.filter.pinned_peers.splice(t,1))}));const s="included"===this.type?"excludePeerIds":"includePeerIds",n="included"===this.type?"exclude_peers":"include_peers";(0,Mn.Z)(this.filter[s],((e,i)=>{t.includes(e)&&(this.filter[s].splice(i,1),this.filter[n].splice(i,1))})),this.filter["included"===this.type?"includePeerIds":"excludePeerIds"]=t,this.filter["included"===this.type?"include_peers":"exclude_peers"]=yield Promise.all(t.map((e=>this.managers.appPeersManager.getInputPeerById(e)))),this.editFolderTab.setFilter(this.filter,!1),this.close()}))),{listenerSetter:this.listenerSetter});const e=e=>{this.limit=s.Z.premium?e.dialog_filters_chats_limit_premium:e.dialog_filters_chats_limit_default};return this.listenerSetter.add(s.Z)("app_config",e),this.dialogsByFilters=new Map,Promise.all([this.managers.filtersStorage.getDialogFilters().then((e=>or(this,void 0,void 0,(function*(){yield Promise.all(e.filter((e=>!le.DZ.has(e.id))).map((e=>or(this,void 0,void 0,(function*(){const t=(yield this.managers.dialogsStorage.getFolderDialogs(e.id)).map((e=>e.peerId));this.dialogsByFilters.set(e,new Set(t))})))))})))),this.managers.apiManager.getAppConfig().then((t=>{e(t)}))])}checkbox(e){const t=new ji.Z({round:!0});return e&&(t.input.checked=e),t.label}onOpen(){this.init&&(this.init(),this.init=null),this.confirmBtn.style.display="excluded"===this.type?"":"none",this.setTitle("included"===this.type?"FilterAlwaysShow":"FilterNeverShow");const e=this.filter,t=new Br({noDelimiter:!0,name:"FilterChatTypes"});let i;t.container.classList.add("folder-categories"),i="excluded"===this.type?{exclude_muted:{ico:"mute",text:"ChatList.Filter.MutedChats"},exclude_archived:{ico:"archive",text:"ChatList.Filter.Archive"},exclude_read:{ico:"readchats",text:"ChatList.Filter.ReadChats"}}:{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"}};const s=document.createDocumentFragment();for(const e in i){const t=(0,M.Z)("btn-primary btn-transparent folder-category-button",{icon:i[e].ico,text:i[e].text});t.dataset.peerId=e,t.append(this.checkbox()),s.append(t)}t.content.append(s);const a=("included"===this.type?e.includePeerIds:e.excludePeerIds).slice();this.selector=new ps({appendTo:this.container,onChange:this.onSelectChange,peerType:["dialogs"],renderResultsFunc:this.renderResults,placeholder:"Search",sectionNameLangPackKey:"FilterChats",managers:this.managers}),this.selector.selected=new Set(a);let o=!1;const r=this.selector.add.bind(this.selector);this.selector.add=(e,t,s)=>{if(this.selector.selected.size>=this.limit&&o&&!i[e]){const t=this.selector.list.querySelector(`[data-peer-id="${e}"] [type="checkbox"]`);return t&&setTimeout((()=>{t.checked=!1}),0),void Ci(v.ZP.format("excluded"===this.type?"ChatList.Filter.Exclude.LimitReached":"ChatList.Filter.Include.LimitReached",!0))}const n=r(e,i[e]?(0,v.ag)(i[e].text):void 0,s);return i[e]&&n.querySelector("avatar-element").classList.add("tgico-"+i[e].ico),n},this.selector.scrollable.container.append(t.container,this.selector.scrollable.container.lastElementChild),this.selector.addInitial(a),o=!0;for(const s in e.pFlags)i.hasOwnProperty(s)&&e.pFlags[s]&&(0,n.tH)(t.content.querySelector(`[data-peer-id="${s}"]`))}onCloseAfterTimeout(){return this.selector&&(this.selector.container.remove(),this.selector=null),super.onCloseAfterTimeout()}open(e,t,i){return this.originalFilter=e,this.filter=(0,Ji.Z)(this.originalFilter),this.type=t,this.editFolderTab=i,super.open()}}var lr=i(1544),cr=i(3066),dr=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class hr extends P{constructor(){super(...arguments),this.flags={}}init(){this.container.classList.add("edit-folder-container"),this.caption=document.createElement("div"),this.caption.classList.add("caption"),this.caption.append((0,v.ag)("FilterIncludeExcludeInfo")),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container"),this.confirmBtn=E("check btn-confirm hide blue");const e={icon:"delete danger",text:"FilterMenuDelete",onClick:()=>{new qi("filter-delete",{titleLangKey:"ChatList.Filter.Confirm.Remove.Header",descriptionLangKey:"ChatList.Filter.Confirm.Remove.Text",buttons:[{langKey:"Delete",callback:()=>{e.element.setAttribute("disabled","true"),this.managers.filtersStorage.updateDialogFilter(this.filter,!0).then((e=>{e&&this.close()})).finally((()=>{e.element.removeAttribute("disabled")}))},isDanger:!0}]}).show()}};this.menuBtn=mo({listenerSetter:this.listenerSetter},"bottom-left",[e]),this.menuBtn.classList.add("hide"),this.header.append(this.confirmBtn,this.menuBtn);const t=new Br({}),i=document.createElement("div");i.classList.add("input-wrapper"),this.nameInputField=new b.Z({label:"FilterNameHint",maxLength:12}),i.append(this.nameInputField.container),t.content.append(i);const s=(e,t,i,s)=>{const n=new Br({name:t,noDelimiter:!0});n.container.classList.add("folder-list",e);const a=n.generateContentElement();return a.classList.add("folder-categories"),i.forEach((e=>{const t=(0,M.Z)("folder-category-button btn btn-primary btn-transparent",{icon:e.icon,text:e.text,noRipple:!e.withRipple||void 0});e.name&&(s[e.name]=t),a.append(t)})),n};this.includePeerIds=s("folder-list-included","FilterInclude",[{icon:"add primary",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),this.excludePeerIds=s("folder-list-excluded","FilterExclude",[{icon:"minus primary",text:"ChatList.Filter.Exclude.AddChat",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),this.scrollable.append(this.stickerContainer,this.caption,t.container,this.includePeerIds.container,this.excludePeerIds.container);const a=this.includePeerIds.container.querySelector(".folder-categories"),o=this.excludePeerIds.container.querySelector(".folder-categories");(0,n.fc)(a.querySelector(".btn"),(()=>{this.slider.createTab(rr).open(this.filter,"included",this)}),{listenerSetter:this.listenerSetter}),(0,n.fc)(o.querySelector(".btn"),(()=>{this.slider.createTab(rr).open(this.filter,"excluded",this)}),{listenerSetter:this.listenerSetter}),(0,n.fc)(this.confirmBtn,(()=>{if(this.nameInputField.input.classList.contains("error"))return;if(!this.nameInputField.value.trim())return void this.nameInputField.input.classList.add("error");let e,t=Array.from(a.children).slice(1).reduce(((e,t)=>e+ +!t.style.display),0);t+=this.filter.include_peers.length,t?(this.confirmBtn.setAttribute("disabled","true"),e=this.filter.id?this.managers.filtersStorage.updateDialogFilter(this.filter):this.managers.filtersStorage.createDialogFilter(this.filter),e.then((e=>{e&&this.close()})).catch((e=>{"DIALOG_FILTERS_TOO_MUCH"===e.type?Ci("Sorry, you can't create more folders."):console.error("updateDialogFilter error:",e)})).finally((()=>{this.confirmBtn.removeAttribute("disabled")}))):Ci("Please choose at least one chat for this folder.")}),{listenerSetter:this.listenerSetter}),this.listenerSetter.add(this.nameInputField.input)("input",(()=>{this.filter.title=this.nameInputField.value,this.editCheckForChange()}));const r="edit"===this.type?[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.loadAnimationPromise=hi.Z.loadAnimationAsAsset({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86},"Folders_2").then((e=>(this.animation=e,hi.Z.waitForFirstFrame(e)))),...r])}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"),this.nameInputField.value="";for(const e in this.flags)this.flags[e].style.display="none"}onEditOpen(){this.setTitle("create"===this.type?"FilterNew":"FilterHeaderEdit"),"edit"===this.type&&(this.menuBtn.classList.remove("hide"),this.confirmBtn.classList.add("hide"));const e=this.filter;this.nameInputField.value=(0,lr.Z)((0,cr.Z)(e.title));for(const t in this.flags)this.flags[t].style.display=e.pFlags[t]?"":"none";["includePeerIds","excludePeerIds"].forEach((t=>dr(this,void 0,void 0,(function*(){const i=this[t],s=gg.createChatList({ignoreClick:!0});let a=e[t];const o=e=>dr(this,void 0,void 0,(function*(){return!!(yield this.managers.appMessagesManager.getDialogOnly(e))||!!e.isUser()&&"user"===(yield this.managers.appUsersManager.getUser(e.toUserId()))._})),r=yield ki(a,(e=>o(e)));a.length=0,a.push(...r),a=a.slice();const l=e=>dr(this,void 0,void 0,(function*(){for(let t=0,i=Math.min(a.length,e);t<i;++t){const e=a.shift();if(!e.isUser()&&!(yield this.managers.appMessagesManager.getDialogOnly(e)))continue;const{dom:t}=gg.addDialogNew({peerId:e,container:s,rippleEnabled:!1,meAsSaved:!0,avatarSize:32});t.lastMessageSpan.parentElement.remove()}a.length?c.lastElementChild.replaceWith((0,v.ag)("FilterShowMoreChats",[a.length])):c&&c.remove()}));let c;if(i.generateContentElement().append(s),a.length){const e=i.generateContentElement();c=(0,M.Z)("folder-category-button btn btn-primary btn-transparent",{icon:"down"}),c.classList.add("load-more","rp-overflow"),(0,n.fc)(c,(()=>l(20)),{listenerSetter:this.listenerSetter}),c.append((0,v.ag)("FilterShowMoreChats",[a.length])),e.append(c)}l(4)}))))}editCheckForChange(){if("edit"===this.type){const e=!(0,gs.Z)(this.originalFilter,this.filter);this.confirmBtn.classList.toggle("hide",!e),this.menuBtn.classList.toggle("hide",e)}}setFilter(e,t){this.container&&Array.from(this.container.querySelectorAll("ul, .load-more")).forEach((e=>e.remove())),t?(this.originalFilter=e,this.filter=(0,Ji.Z)(e)):(this.filter=e,this.onEditOpen(),this.editCheckForChange())}open(e){return void 0===e?(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"),super.open().then((()=>{"edit"===this.type?(this.setFilter(this.originalFilter,!0),this.onEditOpen()):this.onCreateOpen()}))}}var ur=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class pr extends P{constructor(){super(...arguments),this.filtersRendered={}}renderFolder(e,t,i,s){return ur(this,void 0,void 0,(function*(){let a,o="";const r=[];if("dialogFilterSuggested"===e._)a=e.filter,o=e.description;else{if(a=e,1===Object.keys(a.pFlags).length){const e=a.pFlags;let t;e.contacts?t="FilterAllContacts":e.non_contacts?t="FilterAllNonContacts":e.groups?t="FilterAllGroups":e.broadcasts?t="FilterAllChannels":e.bots&&(t="FilterAllBots"),t&&r.push((0,v.ag)(t))}if(!r.length){const e=yield this.managers.dialogsStorage.getFolderDialogs(a.id);let t=0,i=0,s=0;yield Promise.all(e.map((e=>ur(this,void 0,void 0,(function*(){(yield this.managers.appPeersManager.isAnyGroup(e.peerId))?s++:(yield this.managers.appPeersManager.isBroadcast(e.peerId))?i++:t++}))))),t&&r.push((0,v.ag)("Chats",[t])),i&&r.push((0,v.ag)("Channels",[i])),s&&r.push((0,v.ag)("Groups",[s]))}}if(i)a.id!==le.J$&&(0,g.Z)(i.title,(0,Zt.Z)(a.title)),i.subtitle.textContent="",i.subtitle.append(...(0,v.v_)(r));else if(i=new Ni({title:a.id===le.J$?(0,v.ag)("FilterAllChats"):(0,Zt.Z)(a.title),subtitle:o,clickable:a.id!==le.J$}),r.length&&i.subtitle.append(...(0,v.v_)(r)),"dialogFilter"===e._){const e=a.id;this.filtersRendered[a.id]||a.id===le.J$||(0,n.fc)(i.container,(()=>ur(this,void 0,void 0,(function*(){this.slider.createTab(hr).open(yield this.managers.filtersStorage.getFilter(e))}))),{listenerSetter:this.listenerSetter}),this.filtersRendered[a.id]=i}const l=i.container;if(s){const e=a.localId;void 0!==e?Ln(l,l.parentElement||t,e):t&&t.append(l)}return l}))}init(){return ur(this,void 0,void 0,(function*(){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 e=document.createElement("div");e.classList.add("caption"),(0,v.XZ)({element:e,key:"ChatList.Filter.Header"}),this.createFolderBtn=(0,M.Z)("btn-primary btn-color-primary btn-control tgico",{text:"ChatList.Filter.NewTitle",icon:"add"}),this.foldersSection=new Br({name:"Filters"}),this.foldersSection.container.style.display="none",this.suggestedSection=new Br({name:"FilterRecommended"}),this.suggestedSection.container.style.display="none",this.scrollable.append(this.stickerContainer,e,this.createFolderBtn,this.foldersSection.container,this.suggestedSection.container),(0,n.fc)(this.createFolderBtn,(()=>ur(this,void 0,void 0,(function*(){(yield this.canCreateFolder())?this.slider.createTab(hr).open():Ci("Sorry, you can't create more folders.")}))),{listenerSetter:this.listenerSetter});const t=()=>{this.foldersSection.container.style.display=Object.keys(this.filtersRendered).length?"":"none"};return this.managers.filtersStorage.getDialogFilters().then((e=>ur(this,void 0,void 0,(function*(){for(const t of e)t.id!==le.Zi&&(yield this.renderFolder(t,this.foldersSection.content,void 0,!0));this.toggleAllChats(),t()})))),this.listenerSetter.add(s.Z)("filter_update",(e=>ur(this,void 0,void 0,(function*(){const i=this.filtersRendered[e.id];i?yield this.renderFolder(e,null,i):e.id!==le.Zi&&(yield this.renderFolder(e,this.foldersSection.content,void 0,!0)),t(),this.getSuggestedFilters()})))),this.listenerSetter.add(s.Z)("filter_delete",(e=>{const i=this.filtersRendered[e.id];i&&(this.getSuggestedFilters(),i.container.remove(),delete this.filtersRendered[e.id]),t()})),this.listenerSetter.add(s.Z)("filter_order",(e=>{e.filter((e=>!!this.filtersRendered[e])).forEach(((e,t)=>{const i=this.filtersRendered[e].container;Ln(i,i.parentElement,t+1)}))})),this.listenerSetter.add(s.Z)("premium_toggle",(()=>{this.toggleAllChats()})),this.loadAnimationPromise=hi.Z.loadAnimationAsAsset({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86},"Folders_1").then((e=>(this.animation=e,hi.Z.waitForFirstFrame(e)))),this.getSuggestedFilters(),this.loadAnimationPromise}))}onOpenAfterTimeout(){this.loadAnimationPromise.then((()=>{this.animation.autoplay=!0,this.animation.play()}))}toggleAllChats(){this.filtersRendered[le.J$].container.classList.toggle("hide",!s.Z.premium)}canCreateFolder(){return ur(this,void 0,void 0,(function*(){const[e,t]=yield Promise.all([this.managers.apiManager.getAppConfig(),this.managers.filtersStorage.getDialogFilters()]);return t.filter((e=>!le.DZ.has(e.id))).length<(s.Z.premium?e.dialog_filters_limit_premium:e.dialog_filters_limit_default)}))}getSuggestedFilters(){return this.managers.filtersStorage.getSuggestedDialogsFilters().then((e=>ur(this,void 0,void 0,(function*(){this.suggestedSection.container.style.display=e.length?"":"none",Array.from(this.suggestedSection.content.children).slice(1).forEach((e=>e.remove()));for(const t of e){const e=yield this.renderFolder(t),i=(0,M.Z)("btn-primary btn-color-primary",{text:"Add"});e.append(i),this.suggestedSection.content.append(e),(0,n.fc)(i,(s=>ur(this,void 0,void 0,(function*(){if((0,a.Z)(s),!(yield this.canCreateFolder()))return void Ci("Sorry, you can't create more folders.");i.setAttribute("disabled","true");const n=t.filter;n.includePeerIds=[],n.excludePeerIds=[],n.pinnedPeerIds=[],this.managers.filtersStorage.createDialogFilter(n,!0).then((t=>{t&&e.remove()})).finally((()=>{i.removeAttribute("disabled")}))}))),{listenerSetter:this.listenerSetter})}}))))}}var mr=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class gr extends k{init(){this.header.classList.add("with-border"),this.container.classList.add("notifications-container","with-border"),this.setTitle("Telegram.NotificationSettingsViewController");const e=e=>{const t=new Br({name:e.name}),i=new Ni({checkboxField:new ji.Z({text:e.typeText,checked:!0}),subtitleLangKey:"Loading",listenerSetter:this.listenerSetter}),n=new Ni({checkboxField:new ji.Z({text:"MessagePreview",checked:!0}),subtitleLangKey:"Loading",listenerSetter:this.listenerSetter});t.content.append(i.container,n.container),this.scrollable.append(t.container);const a={_:e.inputKey},o=this.managers.appNotificationsManager.getNotifySettings(a);(o instanceof Promise?o:Promise.resolve(o)).then((t=>{const o=()=>mr(this,void 0,void 0,(function*(){const e=yield this.managers.appNotificationsManager.isMuted(t);return i.checkboxField.checked=!e,n.checkboxField.checked=t.show_previews,e}));o(),this.eventListener.addEventListener("destroy",(()=>mr(this,void 0,void 0,(function*(){const e=!i.checkboxField.checked,s=n.checkboxField.checked;if(e===(yield this.managers.appNotificationsManager.isMuted(t))&&s===t.show_previews)return;const o=(0,Ji.Z)(t);o._="inputPeerNotifySettings",o.mute_until=e?le.rU:0,o.show_previews=s,this.managers.appNotificationsManager.updateNotifySettings(a,o)}))),{once:!0}),this.listenerSetter.add(s.Z)("notify_settings",(i=>{const s=zo(i.peer._);e.inputKey===s&&(t=i.notify_settings,o())}))}))};e({name:"NotificationsPrivateChats",typeText:"NotificationsForPrivateChats",inputKey:"inputNotifyUsers"}),e({name:"NotificationsGroups",typeText:"NotificationsForGroups",inputKey:"inputNotifyChats"}),e({name:"NotificationsChannels",typeText:"NotificationsForChannels",inputKey:"inputNotifyBroadcasts"});{const e=new Br({name:"NotificationsOther"}),t=new Ni({checkboxField:new ji.Z({text:"ContactJoined",checked:!0}),subtitleLangKey:"Loading",listenerSetter:this.listenerSetter}),i=new Ni({checkboxField:new ji.Z({text:"Notifications.Sound",checked:!0,stateKey:"settings.notifications.sound",listenerSetter:this.listenerSetter}),subtitleLangKey:"Loading",listenerSetter:this.listenerSetter});Gi.Z.getState().then((e=>{i.checkboxField.checked=e.settings.notifications.sound})),e.content.append(t.container,i.container),this.scrollable.append(e.container),this.managers.appNotificationsManager.getContactSignUpNotification().then((e=>{t.checkboxField.checked=e,this.eventListener.addEventListener("destroy",(()=>{const i=t.checkboxField.checked;e!==i&&this.managers.appNotificationsManager.setContactSignUpNotification(!i)}),{once:!0})}))}}}class vr extends P{init(){return e=this,t=void 0,s=function*(){this.header.classList.add("with-border"),this.container.classList.add("language-container"),this.setTitle("Telegram.LanguageViewController");const e=new Br({}),t=new Map,i=Promise.all([this.managers.apiManager.invokeApiCacheable("langpack.getLanguages",{lang_pack:"web"}),this.managers.apiManager.invokeApiCacheable("langpack.getLanguages",{lang_pack:"macos"})]).then((([i,s])=>{const n=new Set,a=i.map((e=>e.lang_code)),o=(0,Hi.a)();i.concat(s).forEach((e=>{if(n.has(e.lang_code))return;n.add(e.lang_code);const i=new Ni({radioField:new Vi({text:e.name,name:o,value:e.lang_code}),subtitle:e.native_name});t.set(e.lang_code,i)}));const r=Ui([...t.values()],(e=>{v.ZP.getLangPack(e,a.includes(e))}));v.ZP.getCacheLangPack().then((e=>{const i=t.get(e.lang_code);i?i.radioField.setValueSilently(!0):console.error("no row",i,e)})),e.content.append(r)}));return this.scrollable.append(e.container),i},new((i=void 0)||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}));var e,t,i,s}}function fr(e,t,i){const s=new Br({name:t}),n="settings.autoDownload."+e+".",a=new ji.Z({text:"AutodownloadContacts",name:"contacts",stateKey:n+"contacts",withRipple:!0,listenerSetter:i}),o=new ji.Z({text:"AutodownloadPrivateChats",name:"private",stateKey:n+"private",withRipple:!0,listenerSetter:i}),r=new ji.Z({text:"AutodownloadGroupChats",name:"groups",stateKey:n+"groups",withRipple:!0,listenerSetter:i}),l=new ji.Z({text:"AutodownloadChannels",name:"channels",stateKey:n+"channels",withRipple:!0,listenerSetter:i});return s.content.append(a.label,o.label,r.label,l.label),s}class yr extends k{init(){this.header.classList.add("with-border"),this.setTitle("AutoDownloadPhotos");const e=fr("photo","AutoDownloadPhotosTitle",this.listenerSetter);this.scrollable.append(e.container)}}class br extends k{init(){this.header.classList.add("with-border"),this.setTitle("AutoDownloadFiles");const e=(0,Ki.Z)((e=>{this.managers.appStateManager.setByKey("settings.autoDownloadNew.file_size_max",e)}),200,!1,!0),t=fr("file","AutoDownloadFilesTitle",this.listenerSetter),i=524288,n=20447232,a=s.Z.settings.autoDownloadNew.file_size_max,o=Math.sqrt(Math.sqrt((a-i)/n)),r=new v.ZP.IntlElement({key:"AutodownloadSizeLimitUpTo",args:[Tt(a)]}),l=new sr("AutoDownloadMaxFileSize",.01,o,0,1,!1);l.onChange=t=>{const s=Math.pow(t,4)*n+i|0;r.compareAndUpdate({args:[Tt(s)]}),e(s)},l.valueContainer.append(r.element),t.content.append(l.container),this.scrollable.append(t.container)}}class wr extends k{init(){this.header.classList.add("with-border"),this.setTitle("AutoDownloadVideos");const e=fr("video","AutoDownloadVideosTitle",this.listenerSetter);this.scrollable.append(e.container)}}const Sr={contacts:"AutoDownloadContacts",private:"AutoDownloadPm",groups:"AutoDownloadGroups",channels:"AutoDownloadChannels"};class Cr extends k{init(){return e=this,t=void 0,a=function*(){this.header.classList.add("with-border"),this.setTitle("DataSettings");{const e=new Br({name:"AutomaticMediaDownload",caption:"AutoDownloadAudioInfo"}),t=yield Gi.Z.getState(),i=new ji.Z({text:"AutoDownloadMedia",name:"auto",checked:!t.settings.autoDownloadNew.pFlags.disabled,withRipple:!0}),a=()=>{(0,mi.Z)([h],(0,gs.Z)(t.settings.autoDownload,Qo.h.settings.autoDownload)&&(0,gs.Z)(t.settings.autoDownloadNew,Qo.h.settings.autoDownloadNew))},o=()=>{this.setAutoDownloadSubtitle(l,t.settings.autoDownload.photo),this.setAutoDownloadSubtitle(c,t.settings.autoDownload.video),this.setAutoDownloadSubtitle(d,t.settings.autoDownload.file,t.settings.autoDownloadNew.file_size_max)},r=e=>{const t=new e(this.slider,!0);t.open(),this.listenerSetter.add(t.eventListener)("destroy",(()=>{o(),a()}),{once:!0})},l=new Ni({titleLangKey:"AutoDownloadPhotos",subtitle:"",clickable:()=>{r(yr)},listenerSetter:this.listenerSetter}),c=new Ni({titleLangKey:"AutoDownloadVideos",subtitle:"",clickable:()=>{r(wr)},listenerSetter:this.listenerSetter}),d=new Ni({titleLangKey:"AutoDownloadFiles",subtitle:"",clickable:()=>{r(br)},listenerSetter:this.listenerSetter}),h=(0,M.Z)("btn-primary btn-transparent primary",{icon:"delete",text:"ResetAutomaticMediaDownload"});(0,n.fc)(h,(()=>{In({titleLangKey:"ResetAutomaticMediaDownloadAlertTitle",descriptionLangKey:"ResetAutomaticMediaDownloadAlert",button:{langKey:"Reset"}}).then((()=>{const e=s.Z.settings;e.autoDownloadNew=(0,Ji.Z)(Qo.h.settings.autoDownloadNew),e.autoDownload=(0,Ji.Z)(Qo.h.settings.autoDownload),this.managers.appStateManager.setByKey("settings",e),o(),i.checked=!t.settings.autoDownloadNew.pFlags.disabled}))}));const u=()=>{const e=!i.checked,t=s.Z.settings;e?t.autoDownloadNew.pFlags.disabled=!0:delete t.autoDownloadNew.pFlags.disabled,[l,c,d].forEach((t=>{t.container.classList.toggle("is-disabled",e)})),this.managers.appStateManager.setByKey("settings",t),a()};i.input.addEventListener("change",u),u(),o(),e.content.append(i.label,l.container,c.container,d.container,h),this.scrollable.append(e.container)}{const e=new Br({name:"AutoplayMedia"}),t=new ji.Z({text:"AutoplayGIF",name:"gifs",stateKey:"settings.autoPlay.gifs",withRipple:!0,listenerSetter:this.listenerSetter}),i=new ji.Z({text:"AutoplayVideo",name:"videos",stateKey:"settings.autoPlay.videos",withRipple:!0,listenerSetter:this.listenerSetter});e.content.append(t.label,i.label),this.scrollable.append(e.container)}},new((i=void 0)||(i=Promise))((function(s,n){function o(e){try{l(a.next(e))}catch(e){n(e)}}function r(e){try{l(a.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((a=a.apply(e,t||[])).next())}));var e,t,i,a}setAutoDownloadSubtitle(e,t,i){let s;const n=[],a=Object.keys(t),o=a.map((e=>t[e]?Sr[e]:void 0)).filter(Boolean);if(o.length&&0!==i){const e=o.length===a.length;if(void 0!==i?(s=e?"AutoDownloadUpToOnAllChats":"AutoDownloadOnUpToFor",n.push(Tt(i))):s=e?"AutoDownloadOnAllChats":"AutoDownloadOnFor",!e){const e=document.createElement("span");e.append(...(0,v.v_)(o.map((e=>(0,v.ag)(e))),!0,!1)),n.push(e)}}else s="AutoDownloadOff";(0,g.Z)(e.subtitle,(0,v.ag)(s,n))}}var Lr=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Ir extends P{constructor(){super(...arguments),this.buttons={}}init(){return Lr(this,void 0,void 0,(function*(){this.container.classList.add("settings-container"),this.setTitle("Settings");const e=mo({listenerSetter:this.listenerSetter},"bottom-left",[{icon:"logout",text:"EditAccount.Logout",onClick:()=>{new qi("logout",{titleLangKey:"LogOut",descriptionLangKey:"LogOut.Description",buttons:[{langKey:"LogOut",callback:()=>{this.managers.apiManager.logOut()},isDanger:!0}]}).show()}}]);this.buttons.edit=E("edit"),this.header.append(this.buttons.edit,e),this.profile=new Ys(this.managers,this.scrollable,this.listenerSetter,!1),this.profile.init(),this.profile.setPeer(s.Z.myId);const t=this.profile.fillProfileElements(),i=(0,M.Z)("btn-circle btn-corner z-depth-1 profile-change-avatar",{icon:"cameraadd"});(0,n.fc)(i,(()=>{const e=document.createElement("canvas");A.Z.createPopup(Z.Z).open(e,(e=>{e().then((e=>this.managers.appProfileManager.uploadProfilePhoto(e)))}))}),{listenerSetter:this.listenerSetter}),this.profile.element.lastElementChild.firstElementChild.append(i);const a=()=>Lr(this,void 0,void 0,(function*(){var e;const t=yield this.managers.appUsersManager.getSelf();i.classList.toggle("hide","userProfilePhoto"!==(null===(e=t.photo)||void 0===e?void 0:e._))}));a(),this.listenerSetter.add(s.Z)("avatar_update",(e=>{s.Z.myId===e&&a()}));const o=document.createElement("div");o.classList.add("profile-buttons");const r=[["unmute","AccountSettings.Notifications",gr],["data","DataSettings",Cr],["lock","AccountSettings.PrivacyAndSecurity",Go],["settings","Telegram.GeneralSettingsViewController",nr],["folder","AccountSettings.Filters",pr]].map((([e,t,i])=>new Ni({titleLangKey:t,icon:e,clickable:()=>{this.slider.createTab(i).open()},listenerSetter:this.listenerSetter})));r.push(this.devicesRow=new Ni({titleLangKey:"Devices",titleRightSecondary:" ",icon:"activesessions",clickable:()=>Lr(this,void 0,void 0,(function*(){this.authorizations||(yield this.updateActiveSessions());const e=this.slider.createTab(Oo);e.authorizations=this.authorizations,e.eventListener.addEventListener("destroy",(()=>{this.authorizations=void 0,this.updateActiveSessions(!0)}),{once:!0}),e.open()})),listenerSetter:this.listenerSetter}),this.languageRow=new Ni({titleLangKey:"AccountSettings.Language",titleRightSecondary:(0,v.ag)("LanguageName"),icon:"language",clickable:()=>{this.slider.createTab(vr).open()},listenerSetter:this.listenerSetter})),o.append(...r.map((e=>e.container)));const l=new Br;l.content.append(o),this.scrollable.append(this.profile.element,l.container),(0,n.fc)(this.buttons.edit,(()=>{this.slider.createTab(ar).open()}),{listenerSetter:this.listenerSetter}),hi.Z.loadLottieWorkers(),this.updateActiveSessions(),yield 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((e=>{this.authorizations=e.authorizations,this.devicesRow.titleRight.textContent=""+this.authorizations.length}))}onCloseAfterTimeout(){return this.profile.destroy(),super.onCloseAfterTimeout()}}class Mr extends P{constructor(){super(...arguments),this.uploadAvatar=null}init(){this.container.classList.add("new-channel-container"),this.setTitle("NewChannel"),this.avatarEdit=new F((e=>{this.uploadAvatar=e}));const e=new Br({caption:"Channel.DescriptionHolderDescrpiton"}),t=document.createElement("div");t.classList.add("input-wrapper"),this.channelNameInputField=new b.Z({label:"EnterChannelName",maxLength:128}),this.channelDescriptionInputField=new b.Z({label:"DescriptionOptionalPlaceholder",maxLength:255}),t.append(this.channelNameInputField.container,this.channelDescriptionInputField.container);const i=()=>{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",i),this.channelDescriptionInputField.input.addEventListener("input",i),this.nextBtn=D({icon:"arrow_next"}),(0,n.fc)(this.nextBtn,(()=>{const e=this.channelNameInputField.value,t=this.channelDescriptionInputField.value;this.nextBtn.disabled=!0,this.managers.appChatsManager.createChannel({title:e,about:t,broadcast:!0}).then((e=>{this.uploadAvatar&&this.uploadAvatar().then((t=>{this.managers.appChatsManager.editPhoto(e,t)})),_m.setInnerPeer({peerId:e.toPeerId(!0)}),Hr.removeTabFromHistory(this),this.slider.createTab(Ts).open({type:"channel",skippable:!0,title:"GroupAddMembers",placeholder:"SendMessageTo",takeOut:t=>this.managers.appChatsManager.inviteToChannel(e,t)})}))}),{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()}}var Er=i(709);class Pr extends A.Z{constructor(){super("popup-create-contact popup-send-photo popup-new-media",{closable:!0,withConfirm:"Add",title:"AddContactTitle"}),this.construct()}construct(){return e=this,t=void 0,s=function*(){(0,n.fc)(this.btnConfirm,(()=>{const e=this.managers.appUsersManager.importContact(i.value,s.value,a.value);e.then((()=>{this.hide()}),(e=>{"NO_USER"===e.type&&(Li({langPackKey:"Contacts.PhoneNumber.NotRegistred"}),c.disabled=!1)})),c.lockWithPromise(e)}),{listenerSetter:this.listenerSetter});const e=[],t=document.createElement("div");t.classList.add("name-fields");const i=new b.Z({label:"FirstName",name:"create-contact-name",maxLength:70,required:!0}),s=new b.Z({label:"LastName",name:"create-contact-lastname",maxLength:70}),a=new Er.Z({required:!0});e.push(i,s,a);const o=()=>{const e=i.value+" "+s.value;c.avatarElem.peerTitle=e,c.avatarElem.update()};this.listenerSetter.add(i.input)("input",o),this.listenerSetter.add(s.input)("input",o),a.validate=()=>!!a.value.match(/\d/);const r=yield this.managers.appUsersManager.getSelf(),l=(0,Ms.u)(r.phone);l.code&&(a.value="+"+l.code.country_code);const c=new Ri({inputFields:e,listenerSetter:this.listenerSetter,doNotEditAvatar:!0,nextBtn:this.btnConfirm,avatarSize:100});t.append(i.container,s.container,c.avatarElem),this.container.append(t,a.container),this.show()},new((i=void 0)||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}));var e,t,i,s}}class kr extends P{init(){this.container.id="contacts-container";const e=D({icon:"add",className:"is-visible"});this.content.append(e),(0,n.fc)(e,(()=>{A.Z.createPopup(Pr)}),{listenerSetter:this.listenerSetter}),this.inputSearch=new w("Search",(e=>{this.openContacts(e)})),this.listenerSetter.add(s.Z)("contacts_update",(e=>{return t=this,i=void 0,n=function*(){const t=yield this.managers.appUsersManager.isContact(e),i=e.toPeerId();t?this.sortedUserList.add(i):this.sortedUserList.delete(i)},new((s=void 0)||(s=Promise))((function(e,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,r)}l((n=n.apply(t,i||[])).next())}));var t,i,s,n})),this.title.replaceWith(this.inputSearch.container),this.middleware=(0,Ti.k)()}createList(){const e=new Va({managers:this.managers}),t=e.list;return t.id="contacts",t.classList.add("contacts-container"),gg.setListClickListener(t,(()=>{this.close()}),void 0,!0),e}onClose(){this.middleware.clean()}onOpenAfterTimeout(){!Je.IS_MOBILE&&Lo(!0)&&this.inputSearch.input.focus()}openContacts(e){this.init&&(this.init(),this.init=null),this.middleware.clean();const t=this.middleware.get();this.scrollable.onScrolledBottom=null,this.scrollable.container.textContent="",this.managers.appUsersManager.getContactsPeerIds(e,void 0,"online").then((e=>{if(!t())return;const i=this.sortedUserList=this.createList();let s=()=>{const t=as.height/72*1.25|0;e.splice(0,t).forEach((e=>{i.add(e)})),e.length||(s=void 0,this.scrollable.onScrolledBottom=null)};s(),this.scrollable.onScrolledBottom=()=>{s?s():this.scrollable.onScrolledBottom=null},(0,g.Z)(this.scrollable.container,i.list)}))}open(){return this.openContacts(),super.open()}}class Tr extends P{init(){if(this.wasFilterId=gg.filterId,this.container.id="chats-archived-container",this.setTitle("ArchivedChats"),!gg.sortedLists[Tr.filterId]){const e=gg.createChatList();gg.generateScrollable(e,{title:void 0,id:Tr.filterId,localId:le.Zi}).container.append(e),gg.setListClickListener(e,null,!0)}const e=gg.scrollables[Tr.filterId];return this.scrollable.container.replaceWith(e.container),this.scrollable=e,gg.setFilterIdAndChangeTab(Tr.filterId).then((({cached:e,renderPromise:t})=>{if(e)return t}))}onOpenAfterTimeout(){gg.sortedLists[this.wasFilterId].clear()}onClose(){gg.setFilterIdAndChangeTab(this.wasFilterId)}onCloseAfterTimeout(){return gg.sortedLists[Tr.filterId].clear(),super.onCloseAfterTimeout()}}Tr.filterId=le.Zi;class xr extends P{constructor(){super(...arguments),this.isLocationWatched=!1}parseDistance(e){return"miles"===s.Z.settings.distanceUnit?e>1609.34?(0,v.ag)("MilesAway",[Math.round(e/1609)]):(0,v.ag)("FootsAway",[Math.round(3.281*e)]):e>=1e3?(0,v.ag)("KMetersAway2",[e/1e3]):(0,v.ag)("MetersAway2",[e])}open(){const e=super.open();return e.then((()=>{this.retryBtn.classList.remove("is-visible"),navigator.geolocation.getCurrentPosition((e=>{this.latestLocationSaved={latitude:e.coords.latitude,longitude:e.coords.longitude,accuracy:e.coords.accuracy},console.log(this.latestLocationSaved),this.managers.appUsersManager.getLocated(e.coords.latitude,e.coords.longitude,e.coords.accuracy).then((e=>{const t=e.updates[0].peers,i=t.sort(((e,t)=>e.distance-t.distance)),s=t.filter((e=>"peerChannel"==e.peer._)).length,n=t.filter((e=>"peerChannel"!=e.peer._)).length;null==i||i.forEach((e=>{const t=(0,es.Z)(e.peer),i=t.isUser()?this.peopleSection:this.chatsSection;this.locatedPeers.set(t,e),i.sortedList.add(t)})),this.errorCategory.classList.toggle("hide",!(!n&&!s)),this.errorCategory.innerHTML="No groups or channels found around you."}))}),(e=>{this.errorCategory.classList.remove("hide"),this.retryBtn.classList.add("is-visible"),this.retryBtn.addEventListener("click",this.open),e instanceof GeolocationPositionError?this.errorCategory.innerHTML="Location permission denied. Click below to retry.":this.errorCategory.innerHTML="An error has occurred. Please retry later clicking the button below."}))})),e}startWatching(){this.latestLocationSaved&&!this.isLocationWatched&&(this.isLocationWatched=!0,Ci("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,i=e.coords.latitude!==this.latestLocationSaved.latitude,s=this.calculateDistance(e.coords.latitude,e.coords.longitude,this.latestLocationSaved.latitude,this.latestLocationSaved.longitude)>100;(i||t)&&s&&(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,Ci("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,i,s){const n=.017453292519943295;return 12742*Math.asin(Math.sqrt(.5-Math.cos((i-e)*n)+Math.cos(e*n)*Math.cos(i*n)*(1-Math.cos((s-t)*n)/2)))}}var _r=i(4159),Ar=i(7487);function Zr(e,t=2){if(0===e)return"0";const i=t<0?0:t,s=Math.floor(Math.log(e)/Math.log(1e3));return parseFloat((e/Math.pow(1e3,s)).toFixed(i))+["","K","M","B","T"][s]}var Fr=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const Dr="is-left-column-shown",Rr="sidebar-left-section";class Br{constructor(e={}){var t;const i=this.container=document.createElement("div");i.classList.add(Rr+"-container");const s=this.innerContainer=document.createElement("div");if(s.classList.add(Rr),e.noShadow&&s.classList.add("no-shadow"),e.fakeGradientDelimiter)s.append(Ur()),s.classList.add("with-fake-delimiter");else if(e.noDelimiter)s.classList.add("no-delimiter");else{const e=document.createElement("hr");s.append(e)}const n=this.content=this.generateContentElement();if(e.name){const t=this.title=document.createElement("div");t.classList.add("sidebar-left-h2",Rr+"-name"),(0,v.XZ)({element:t,key:e.name,args:e.nameArgs}),n.append(t)}i.append(s);const a=null!==(t=e.caption)&&void 0!==t?t:e.captionOld;if(a){const t=this.caption=this.generateContentElement();t.classList.add(Rr+"-caption"),e.captionOld||i.append(t),!0!==a&&(0,v.XZ)({element:t,key:a,args:e.captionArgs})}}generateContentElement(){const e=document.createElement("div");return e.classList.add(Rr+"-content"),this.innerContainer.append(e),e}}const Nr=(e,t,i)=>{const s=new Br({name:t,caption:i});return e.append(s.container),s.content},Ur=()=>{const e=document.createElement("div");return e.classList.add("gradient-delimiter"),e},Or=new class extends _{constructor(){super({sidebarEl:document.getElementById("column-left"),navigationType:"left"}),this.searchGroups={}}construct(e){this.managers=e,this.inputSearch=new w("Search");const t=this.sidebarEl.querySelector(".item-main .sidebar-header");t.append(this.inputSearch.container);const i=()=>{this.createTab(kr).open()};this.backBtn=this.sidebarEl.querySelector(".sidebar-back-button");const a={icon:"archive",text:"ArchivedChats",onClick:()=>{this.createTab(Tr).open()},verify:()=>Fr(this,void 0,void 0,(function*(){return!!(yield this.managers.dialogsStorage.getFolderDialogs(1,!1)).length||!(yield this.managers.dialogsStorage.isDialogsLoaded(1))}))},o=new ji.Z({toggle:!0,checked:"night"===$o.Z.getTheme().name});o.input.addEventListener("change",(()=>Fr(this,void 0,void 0,(function*(){yield this.managers.appStateManager.setByKey("settings.theme",o.input.checked?"night":"day"),s.Z.dispatchEvent("theme_change")})))),s.Z.addEventListener("theme_change",(()=>{o.setValueSilently("night"===$o.Z.getTheme().name)}));const r=[{icon:"saved",text:"SavedMessages",onClick:()=>{setTimeout((()=>{_m.setPeer({peerId:_m.myId})}),0)}},a,{icon:"user",text:"Contacts",onClick:i},tr.Z?{icon:"group",text:"PeopleNearby",onClick:()=>{this.createTab(xr).open()}}:void 0,{icon:"settings",text:"Settings",onClick:()=>{this.createTab(Ir).open()}},{icon:"darkmode",text:"DarkMode",onClick:()=>{},checkboxField:o},{icon:"animations",text:"Animations",onClick:()=>{},checkboxField:new ji.Z({toggle:!0,checked:!0,stateKey:"settings.animationsEnabled"})},{icon:"help",text:"TelegramFeatures",onClick:()=>{const e=v.ZP.format("TelegramFeaturesUrl",!0);_m.openUrl(e)}},{icon:"bug",text:"ReportBug",onClick:()=>{const e=document.createElement("a");e.target="_blank",e.href="https://bugs.telegram.org/?tag_ids=40&sort=time",document.body.append(e),e.click(),setTimeout((()=>{e.remove()}),0)}},{icon:"char z",text:"ChatList.Menu.SwitchTo.Z",onClick:()=>{Promise.all([Ar.Z.set({kz_version:"Z"}),Ar.Z.delete("tgme_sync")]).then((()=>{location.href="https://web.telegram.org/z/"}))},verify:()=>_r.Z.isMainDomain},{icon:"char w",text:"ChatList.Menu.SwitchTo.Webogram",onClick:()=>{Ar.Z.delete("tgme_sync").then((()=>{location.href="https://web.telegram.org/?legacy=1"}))},verify:()=>_r.Z.isMainDomain}].filter(Boolean);this.toolsBtn=mo({},"bottom-right",r,(e=>Fr(this,void 0,void 0,(function*(){yield Promise.all(r.map((e=>Fr(this,void 0,void 0,(function*(){e.verify&&e.element.classList.toggle("hide",!(yield e.verify()))})))))})))),this.toolsBtn.classList.remove("tgico-more"),this.toolsBtn.classList.add("sidebar-tools-button","is-visible"),this.backBtn.parentElement.insertBefore(this.toolsBtn,this.backBtn);const l=this.toolsBtn.querySelector(".btn-menu"),c=document.createElement("a");c.href="https://github.com/morethanwords/tweb/blob/master/CHANGELOG.md",c.target="_blank",c.rel="noopener noreferrer",c.classList.add("btn-menu-footer"),c.addEventListener(n.pf,(e=>{e.stopPropagation(),Ii.close()}));const d=document.createElement("span");d.classList.add("btn-menu-footer-text"),d.innerHTML="Telegram Web"+_r.Z.suffix+" "+_r.Z.versionFull,c.append(d),l.classList.add("has-footer"),l.append(c),this.newBtnMenu=mo({},"top-left",[{icon:"newchannel",text:"NewChannel",onClick:()=>{this.createTab(Mr).open()}},{icon:"newgroup",text:"NewGroup",onClick:()=>{this.createTab(Ts).open({type:"chat",skippable:!1,takeOut:e=>{this.createTab(de).open(e)},title:"GroupAddMembers",placeholder:"SendMessageTo"})}},{icon:"newprivate",text:"NewPrivateChat",onClick:i}]),this.newBtnMenu.className="btn-circle rp btn-corner z-depth-1 btn-menu-toggle animated-button-icon",this.newBtnMenu.insertAdjacentHTML("afterbegin",'\n <span class="tgico tgico-newchat_filled"></span>\n <span class="tgico tgico-close"></span>\n '),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",(0,we.Z)(this.updateBtn),this.updateBtn.append((0,v.ag)("Update")),(0,n.fc)(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=document.createElement("span"),this.archivedCount.className="archived-count badge badge-24 badge-gray",a.element.append(this.archivedCount),s.Z.addEventListener("folder_unread",(e=>{if(1===e.id){const t=e.unreadPeerIds.size;this.archivedCount.innerText=""+Zr(t,1),this.archivedCount.classList.toggle("hide",!t)}})),this.managers.appUsersManager.getTopPeers("correspondents");const h={type:"global-search-focus",onPop:()=>(setTimeout((()=>{this.inputSearch.input.focus()}),0),!1),noHistory:!0};C.Z.pushItem(h),Gi.Z.getState().then((e=>{const t=setInterval((()=>{fetch("version",{cache:"no-cache"}).then((e=>200===e.status&&e.ok&&e.text()||Promise.reject())).then((e=>{e!==_r.Z.versionFull&&(this.hasUpdate=!0,clearInterval(t),this.newBtnMenu.classList.contains("is-hidden")||this.updateBtn.classList.remove("is-hidden"))})).catch(ft.Z)}),18e5)}))}initSearch(){const e=this.sidebarEl.querySelector("#search-container"),t=new m.ZP(e),i=()=>{(0,n.tH)(this.backBtn)};this.searchGroups={contacts:new f("SearchAllChatsShort","contacts",void 0,void 0,void 0,void 0,i),globalContacts:new f("GlobalSearch","contacts",void 0,void 0,void 0,void 0,i),messages:new f("SearchMessages","messages"),people:new f(!1,"contacts",!0,"search-group-people",!0,!1,i,!0),recent:new f("Recent","contacts",!0,"search-group-recent",!0,!0,i)};const s=this.searchSuper=new uo({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(s.nav.parentElement.parentElement),t.container.append(s.container),s.setQuery({peerId:"".toPeerId(),folderId:0}),s.selectTab(0),s.load(!0);const a=[];let o="".toPeerId(),c=0,d=0;const h=()=>{this.inputSearch.container.classList.toggle("is-picked-twice",2===a.length),this.inputSearch.container.classList.toggle("is-picked",!!a.length),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")},u=document.createElement("div");u.classList.add("search-helper"),u.addEventListener("click",(e=>{const t=(0,r.Z)(e.target,"selector-user");if(!t)return;const i=t.dataset.key;if(0===i.indexOf("date_")){const[e,t,s]=i.split("_");c=+t,d=+s}else o=i.toPeerId();t.addEventListener("click",(()=>{v(t)})),this.inputSearch.container.append(t),this.inputSearch.onChange(this.inputSearch.value=""),a.push(t),h()})),s.nav.parentElement.append(u);const p=(e,t)=>{const i=document.createElement("div");i.classList.add("selector-user");const s=new Wm;return s.classList.add("selector-user-avatar","tgico","avatar-30"),s.isDialog=!0,i.dataset.key=""+e,e.isPeerId()?(void 0===t&&(t=new Ot({peerId:e.toPeerId()}).element),s.updateWithOptions({peerId:e})):s.classList.add("tgico-calendarfilter"),t&&("string"==typeof t?i.innerHTML=t:((0,g.Z)(i,t),i.append(t))),i.insertAdjacentElement("afterbegin",s),i},v=e=>{0===e.dataset.key.indexOf("date_")?c=d=0:o="".toPeerId(),e.remove(),(0,T.Z)(a,e),setTimeout((()=>{h(),this.inputSearch.onChange(this.inputSearch.value)}),0)};this.inputSearch.onClear=()=>{a.forEach((e=>{v(e)}))},this.inputSearch.onChange=e=>{if(s.cleanupHTML(),s.setQuery({peerId:o,folderId:o?void 0:0,query:e,minDate:c,maxDate:d}),s.load(!0),u.innerHTML="",s.nav.classList.remove("hide"),!o&&e.trim()){const t=s.middleware.get();Promise.all([this.managers.appMessagesManager.getConversations(e).then((({dialogs:e})=>e.map((e=>e.peerId)))),this.managers.appUsersManager.getContactsPeerIds(e,!0)]).then((e=>{t()&&(new Set(e[0].concat(e[1])).forEach((e=>{u.append(p(e))})),s.nav.classList.toggle("hide",!!u.innerHTML))}))}if(!c&&e.trim()){const t=[];X(e,t),t.forEach((e=>{u.append(p("date_"+e.minDate+"_"+e.maxDate,e.title))})),s.nav.classList.toggle("hide",!!u.innerHTML)}},s.tabs.inputMessagesFilterEmpty.addEventListener("mousedown",(e=>{const t=(0,l.Z)(e.target,dg);if(!t)return;const i=(0,r.Z)(t,"search-group");if(!i||i.classList.contains("search-group-recent")||i.classList.contains("search-group-people"))return;const s=t.getAttribute("data-peer-id").toPeerId();this.managers.appUsersManager.pushRecentSearch(s)}),{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 m.v7(y);let b,w=!0;const L=(0,S.v)(e.parentElement,"zoom-fade",150,(e=>{b&&clearTimeout(b),0!==e||w||(s.selectTab(0,!1),this.inputSearch.onClearClick(),b=window.setTimeout((()=>{b=0,this.newBtnMenu.classList.remove("is-hidden"),this.hasUpdate&&this.updateBtn.classList.remove("is-hidden")}),150)),w=!1}));L(0);const I="is-visible",M=()=>{this.toolsBtn.classList.remove(I),this.backBtn.classList.add(I),this.newBtnMenu.classList.add("is-hidden"),this.updateBtn.classList.add("is-hidden"),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!0);const e="global-search";Je.IS_MOBILE_SAFARI||C.Z.findItemByType(e)||C.Z.pushItem({onPop:()=>{i()},type:e}),L(1)};this.inputSearch.input.addEventListener("focus",M),M(),(0,n.fc)(this.backBtn,(e=>{this.toolsBtn.classList.add(I),this.backBtn.classList.remove(I),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!1),C.Z.removeByType("global-search"),L(0)}));const P=E("close");this.searchGroups.recent.nameEl.append(P),P.addEventListener("click",(()=>{In({descriptionLangKey:"Search.Confirm.ClearHistory",button:{langKey:"ClearButton",isDanger:!0}}).then((()=>this.managers.appUsersManager.clearRecentSearch().then((()=>{this.searchGroups.recent.clear()}))))}))}};R.GO.appSidebarLeft=Or;const Hr=Or;class zr{constructor(e,t,i){this.container=document.createElement("div"),this.container.classList.add("bubbles-group"),this.chat=e,this.groups=t,this.items=[],this.dateTimestamp=i,this.offset=0}createAvatar(e){if(this.avatarLoadPromise)return this.avatarLoadPromise;if("messageService"===e._)return;this.avatarContainer=document.createElement("div"),this.avatarContainer.classList.add("bubbles-group-avatar-container"),++this.offset;const t=e.fwd_from,i=e.fwdFromId,n=e.from_id&&"peerChannel"===e.from_id._&&e.fromId===i,a=this.chat.peerId,o=this.avatar=new Wm;this.avatar.classList.add("bubbles-group-avatar","user-avatar","avatar-40");const r=(t&&(a===s.Z.myId||a===le.hj)||n?i:e.fromId)||le.NM,l=this.avatar.updateWithOptions({lazyLoadQueue:this.chat.bubbles.lazyLoadQueue,peerId:r,peerTitle:!i&&t&&t.from_name?t.from_name:void 0});return this.avatarLoadPromise=Promise.all([l,r&&r.isUser()?this.chat.managers.appUsersManager.getUser(r.toUserId()):void 0]).then((([e,t])=>{var i;return(null===(i=null==t?void 0:t.pFlags)||void 0===i?void 0:i.premium)&&o.classList.add("is-premium","tgico-star"),e})),this.avatarContainer.append(this.avatar),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 i=e[t-1].bubble;if(1===e.length)return void i.classList.add("is-group-first","is-group-last");i.classList.remove("is-group-last"),i.classList.add("is-group-first");for(let i=1,s=t-1;i<s;++i)e[i].bubble.classList.remove("is-group-last","is-group-first");const s=e[0].bubble;s.classList.remove("is-group-first"),s.classList.add("is-group-last")}insertItem(e){const{items:t}=this;(0,Ha.Z)(t,e,this.groups.sortGroupItemsKey),e.group=this,1===t.length&&this.groups.insertGroup(this)}removeItem(e){(0,T.Z)(this.items,e),this.items.length||(0,T.Z)(this.groups.groups,this),e.group=void 0}mount(e){if(!this.groups.groups.includes(this)||!this.items.length)return void(this.mounted&&this.onItemUnmount());const{offset:t,items:i}=this,{length:s}=i;(0,Mn.Z)(i,((e,i)=>{this.mountItem(e,s-1-i,t)})),e&&this.updateClassNames(),this.onItemMount()}mountItem(e,t=this.items.indexOf(e),i=this.offset){e.mounted||(Ln(e.bubble,this.container,i+t),e.mounted=!0)}unmountItem(e){e.mounted&&(e.bubble.remove(),e.mounted=!1,this.onItemUnmount())}onItemMount(){if(this.mounted)return;const e=this.chat.bubbles.getDateContainerByTimestamp(this.dateTimestamp/1e3),t=this.groups.groups.filter((e=>e.dateTimestamp===this.dateTimestamp)),i=t.length,s=t.indexOf(this),n=t.slice(s+1).reduce(((e,t)=>e+(t.mounted?0:1)),0);Ln(this.container,e.container,gc+i-1-s-n),this.mounted=!0}onItemUnmount(){this.mounted&&(this.items.length?this.updateClassNames():(this.container.remove(),this.chat.bubbles.deleteEmptyDateGroups(),this.mounted=!1))}}class Gr{constructor(e){this.chat=e,this.itemsArr=[],this.itemsMap=new Map,this.groups=[],this.newGroupDiff=121,this.sortItemsKey="scheduled"===e.type?"timestamp":"mid",this.sortGroupsKey="scheduled"===e.type?"lastTimestamp":"lastMid",this.sortGroupItemsKey="groupMid"}removeItem(e){e.group.removeItem(e),this.removeItemFromCache(e)}removeAndUnmountBubble(e){const t=this.getItemByBubble(e);if(!t)return;const i=this.itemsArr,s=i.indexOf(t),n=this.getSiblingsAtIndex(s,i),a=t.group;this.removeItem(t),a.unmountItem(t);const o=new Set;o.add(a);const[r,l]=n;if(r&&l&&this.canItemsBeGrouped(r,l)&&r.group!==l.group){const e=l.group;this.f(l.group.items),e.onItemUnmount(),o.add(r.group),this.groupUngrouped()}this.mountUnmountGroups(Array.from(o))}mountUnmountGroups(e){const[t,i]=function(e,t){const i=[],s=[];for(let t=0,a=e.length;t<a;++t){const a=e[t];(n=a,n.items.length?i:s).push(a)}var n;return[i,s]}(e);i.forEach((e=>{e.onItemUnmount()})),t.forEach((e=>{e.mount(!0)}))}f(e,t=0,i=e.length){for(;t<i;++t){const s=e[t];s.mounted=!1,s.group.removeItem(s),--i,--t}}getItemByBubble(e){return this.itemsMap.get(e)}getLastGroup(){return this.groups[0]}changeBubbleMid(e,t){const i=this.getItemByBubble(e);i&&(i.mid=t,(0,T.Z)(this.itemsArr,i),this.insertItemToArray(i,this.itemsArr))}changeItemBubble(e,t){this.itemsMap.delete(e.bubble),e.bubble=t,this.itemsMap.set(t,e)}changeBubbleByBubble(e,t){const i=this.getItemByBubble(e);i&&this.changeItemBubble(i,t)}canItemsBeGrouped(e,t){return t.fromId===e.fromId&&Math.abs(t.timestamp-e.timestamp)<=this.newGroupDiff&&e.dateTimestamp===t.dateTimestamp&&!e.single&&!t.single}getSiblingsAtIndex(e,t){return[t[e-1],t[e+1]]}findGroupSiblingByItem(e,t){t=t.slice();const i=this.insertItemToArray(e,t);return this.findGroupSiblingInItems(e,t,i)}findGroupSiblingInItems(e,t,i=t.indexOf(e),s=t.length){const n=t[i-1];let a;if((null==n?void 0:n.group)&&this.canItemsBeGrouped(e,n))a=n;else for(let n=i+1;n<s;++n){const i=t[n];if(!this.canItemsBeGrouped(e,i))break;i.group&&(a=i)}return a}addItemToGroup(e,t){t.insertItem(e),this.addItemToCache(e)}insertItemToArray(e,t){return(0,Ha.Z)(t,e,this.sortItemsKey)}insertGroup(e){return(0,Ha.Z)(this.groups,e,this.sortGroupsKey)}addItemToCache(e){this.insertItemToArray(e,this.itemsArr),this.itemsMap.set(e.bubble,e)}removeItemFromCache(e){(0,T.Z)(this.itemsArr,e),this.itemsMap.delete(e.bubble)}getMessageFromId(e){let t=e.viaBotId||e.fromId;return t===s.Z.myId&&e.peerId===s.Z.myId&&e.fwdFromId===t&&(t=t.toPeerId(!0)),t}createItem(e,t){const i=!("message"===t._||t.action&&hc.has(t.action._)),{mid:s,date:n}=t,{dateTimestamp:a}=this.chat.bubbles.getDateForDateContainer(n);return{mid:s,groupMid:"scheduled"===this.chat.type?+`${(1e3*n-a)/1e3}.${s}`:s,fromId:this.getMessageFromId(t),bubble:e,timestamp:n,dateTimestamp:a,mounted:!1,single:i,message:t}}splitSiblingsOnGrouping(e){const[t,i]=e,s=null==t?void 0:t.group;if(null==i||i.group,!s)return;const n=s.items,a=n.indexOf(t)+1,o=n.length;if(a===o)return;const r=[s];return this.f(n,a,o),r}prepareForGrouping(e,t){if(this.getItemByBubble(e))return;const i=this.createItem(e,t);this.addItemToCache(i)}groupUngrouped(){var e;const t=this.itemsArr,i=t.length,s=new Set;for(let n=0;n<i;++n){const a=t[n];if(a.group)continue;let o=!0;const r=this.getSiblingsAtIndex(n,t),l=this.findGroupSiblingInItems(a,t,n,i),c=null!==(e=null==l?void 0:l.group)&&void 0!==e?e:(o=!1,new zr(this.chat,this,a.dateTimestamp));if(s.add(c),c.insertItem(a),!o){const e=this.splitSiblingsOnGrouping(r);e&&e.forEach((e=>s.add(e)))}}return s}cleanup(){this.itemsArr=[],this.groups=[],this.itemsMap.clear()}}class Vr extends A.Z{constructor(e,t,i={}){if(super("popup-date-picker",Object.assign({body:!0,overlayClosable:!0,buttons:i.noButtons?[]:[{langKey:"JumpToDate",callback:()=>{this.onPick&&this.onPick(this.selectedDate.getTime()/1e3|0)}},{langKey:"Cancel",isCancel:!0}],title:!0},i)),this.onPick=t,this.options=i,this.onPrevClick=e=>{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=e=>{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=e=>{const t=e.target;if(!t.dataset.timestamp)return;if(this.selectedEl){if(this.selectedEl===t)return;this.selectedEl.classList.remove("active")}this.selectedEl=t,t.classList.add("active");const i=+t.dataset.timestamp;this.selectedDate=new Date(i),this.setTitle(),this.setTimeTitle()},this.minDate=i.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=document.createElement("button"),this.prevBtn.classList.add("btn-icon","tgico-down","date-picker-prev"),(0,n.fc)(this.prevBtn,this.onPrevClick,{listenerSetter:this.listenerSetter}),this.nextBtn=document.createElement("button"),this.nextBtn.classList.add("btn-icon","tgico-down","date-picker-next"),(0,n.fc)(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"),(0,n.fc)(this.monthsContainer,this.onDateClick,{listenerSetter:this.listenerSetter}),this.body.append(this.controlsDiv,this.monthsContainer),i.withTime){this.timeDiv=document.createElement("div"),this.timeDiv.classList.add("date-picker-time");const t=document.createElement("div");t.classList.add("date-picker-time-delimiter"),t.append(":");const i=(e,t,i,s)=>{const n=""+e;this.listenerSetter.add(t.input)("input",(a=>{let o=t.value.replace(/\D/g,"");o.length>2?o=o.slice(0,2):(1===o.length&&+o[0]>+n[0]||2===o.length&&+o>e)&&(2===o.length&&s&&s(+o[1]),o="0"+o[0]),t.setValueSilently(o),i(o.length)}))};this.hoursInputField=new b.Z({plainText:!0}),this.minutesInputField=new b.Z({plainText:!0}),i(23,this.hoursInputField,(e=>{2===e&&this.minutesInputField.input.focus(),this.setTimeTitle()}),(e=>{this.minutesInputField.value=(e+this.minutesInputField.value).slice(0,2)})),i(59,this.minutesInputField,(e=>{e||this.hoursInputField.input.focus(),this.setTimeTitle()})),this.selectedDate=e,e.setMinutes(e.getMinutes()+10),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,t,this.minutesInputField.container),(0,n.fc)(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 s=document.createElement("div");s.classList.add("popup-centerer"),s.append(this.container),this.element.append(s),e.setHours(0,0,0,0),this.selectedDate=e,this.maxDate=i.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"),i.noTitle&&(this.setTitle=()=>{}),this.setTimeTitle(),this.setTitle(),this.setMonth()}setTimeTitle(){if(this.btnConfirm&&this.selectedDate){let e;const t=[],i=new Date;i.setHours(0,0,0,0);const s={minute:"2-digit",hour:"2-digit"},n=new Date(this.selectedDate.getTime());if(n.setHours(+this.hoursInputField.value,+this.minutesInputField.value),this.selectedDate.getTime()===i.getTime())e="Schedule.SendToday";else{e="Schedule.SendDate";const s={month:"short",day:"numeric"};n.getFullYear()!==i.getFullYear()&&(s.year="numeric"),t.push(new v.ZP.IntlDateElement({date:n,options:s}).element)}t.push(new v.ZP.IntlDateElement({date:n,options:s}).element),this.btnConfirm.firstChild.replaceWith((0,v.ag)(e,t))}}setTitle(){this.title.textContent="",this.title.append(new v.ZP.IntlDateElement({date:this.selectedDate,options:{day:"numeric",month:"long",weekday:"short"}}).element)}renderElement(e,t=""){const i=document.createElement("button");return i.classList.add("btn-icon","date-picker-month-date"),e&&i.setAttribute("disabled","true"),t&&i.append(t),i}setMonth(){const e=new Date(this.selectedMonth),t={year:"numeric",month:this.timeDiv&&d.Z.isMobile?"short":"long"};this.monthTitle.textContent="",this.monthTitle.append(new v.ZP.IntlDateElement({date:e,options:t}).element),this.month&&this.month.remove(),this.month=document.createElement("div"),this.month.classList.add("date-picker-month");const i=new Date,s=i.getDay();1!==s&&i.setHours(-24*(s-1));for(let e=0;e<7;++e){const e=this.renderElement(!0,new v.ZP.IntlDateElement({date:i,options:{weekday:"narrow"}}).element);e.classList.remove("date-picker-month-date"),e.classList.add("date-picker-month-day"),this.month.append(e),i.setDate(i.getDate()+1)}let n=e.getDay()-1;-1===n&&(n=6);const a=new Date(e.getTime());a.setDate(a.getDate()-n-1);for(let e=0;e<n;++e)this.options.showOverflowMonths?(a.setDate(a.getDate()+1),this.month.append(this.renderElement(!0,""+a.getDate()))):this.month.append(this.renderElement(!0));do{const t=e.getDate(),i=this.renderElement(e>this.maxDate||e<this.minDate,""+t);i.dataset.timestamp=""+e.getTime(),e.getTime()===this.selectedDate.getTime()&&(this.selectedEl=i,i.classList.add("active")),this.month.append(i),e.setDate(t+1)}while(1!==e.getDate());const o=this.month.childElementCount%7;if(this.options.showOverflowMonths&&o)for(let t=o;t<7;++t)this.month.append(this.renderElement(!0,""+e.getDate())),e.setDate(e.getDate()+1);const r=Math.ceil(this.month.childElementCount/7);this.container.dataset.lines=""+r,this.monthsContainer.append(this.month)}}var Kr=i(6654);class Wr extends HTMLElement{constructor(){super(),this.classList.add("reaction"),this.managers=s.Z.managers}get reactionCount(){return this._reactionCount}set reactionCount(e){this._reactionCount=e}get count(){return this.reactionCount.count}init(e){this.type=e,this.classList.add("reaction-"+e)}setCanRenderAvatars(e){this.canRenderAvatars=e}render(e){const t=!!this.stickerContainer;t||(this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("reaction-sticker"),this.append(this.stickerContainer));const i=this.reactionCount;if(!e&&!t){const e=this.managers.appReactionsManager.getReaction(i.reaction);(0,Kr.Z)(e,(e=>{var t;e.center_icon||this.stickerContainer.classList.add("is-static"),e.pFlags.inactive&&this.classList.add("is-inactive");const i="inline"===this.type?14:22,s=this.wrapStickerPromise=ta({div:this.stickerContainer,doc:null!==(t=e.center_icon)&&void 0!==t?t:e.static_icon,width:i,height:i,static:!0,managers:this.managers}).then((({render:e})=>e)).finally((()=>{this.wrapStickerPromise===s&&(this.wrapStickerPromise=void 0)}))}))}}renderCounter(){var e;const t=this.reactionCount,i="inline"===this.type?2:4;if(t.count>=i||"block"===this.type&&!this.canRenderAvatars){this.counter||(this.counter=document.createElement("inline"===this.type?"i":"span"),this.counter.classList.add("reaction-counter"));const e=Zr(t.count);this.counter.textContent!==e&&(this.counter.textContent=e),this.counter.parentElement||this.append(this.counter)}else(null===(e=this.counter)||void 0===e?void 0:e.parentElement)&&(this.counter.remove(),this.counter=void 0)}renderAvatars(e){"inline"!==this.type&&(this.reactionCount.count>=4||!this.canRenderAvatars?this.stackedAvatars&&(this.stackedAvatars.container.remove(),this.stackedAvatars=void 0):(this.stackedAvatars||(this.stackedAvatars=new na({avatarSize:24}),this.append(this.stackedAvatars.container)),this.stackedAvatars.render(e.map((e=>(0,es.Z)(e.peer_id))))))}setIsChosen(e=!!this.reactionCount.pFlags.chosen){"inline"!==this.type&&(this.classList.contains("is-chosen")&&!this.classList.contains("backwards"))!==e&&Re(this,"is-chosen",e,this.isConnected?300:0)}fireAroundAnimation(){(0,Kr.Z)(this.managers.appReactionsManager.getReaction(this.reactionCount.reaction),(e=>{const t="inline"===this.type?28:40,i=document.createElement("div");i.classList.add("reaction-sticker-activate"),Promise.all([ta({div:i,doc:e.center_icon,width:t,height:t,withThumb:!1,needUpscale:!0,play:!1,skipRatio:1,group:"none",needFadeIn:!1,managers:this.managers}).then((({render:e})=>e)),Yn({doc:e.around_animation,size:80,target:this.stickerContainer,side:"center",skipRatio:1,play:!1,managers:this.managers}).stickerPromise]).then((([e,t])=>{const s=()=>{(0,Be.T2)((()=>{e.remove(),i.remove(),this.stickerContainer.classList.remove("has-animation")}))};e.addEventListener("enterFrame",(t=>{t===e.maxFrame&&(this.wrapStickerPromise?this.wrapStickerPromise.then((()=>{setTimeout(s,1e3)})):s())})),e.addEventListener("firstFrame",(()=>{this.stickerContainer.append(i),this.stickerContainer.classList.add("has-animation"),e.play(),t.play()}),{once:!0})}))}))}}customElements.define("reaction-element",Wr);const $r=new Map;class jr extends HTMLElement{constructor(){super(),this.classList.add("reactions"),this.sorted=[],this.managers=s.Z.managers}connectedCallback(){let e=$r.get(this.key);e||$r.set(this.key,e=new Set),e.add(this),this.onConnectCallback&&this.isConnected&&(this.onConnectCallback(),this.onConnectCallback=void 0)}disconnectedCallback(){const e=$r.get(this.key);e.delete(this),e.size||$r.delete(this.key)}getReactionCount(e){return this.sorted[this.sorted.indexOf(e)].reactionCount}getMessage(){return this.message}init(e,t,i){void 0!==this.key&&this.disconnectedCallback(),this.message=e,this.key=this.message.peerId+"_"+this.message.mid,this.isPlaceholder=i,this.type!==t&&(this.type=t,this.classList.add("reactions-"+t)),this.connectedCallback()}changeMessage(e){return this.init(e,this.type,this.isPlaceholder)}update(e,t){this.message=e,this.render(t)}render(e){const t=this.message.reactions,i=!(!t||!t.results.length);if(this.classList.toggle("has-no-reactions",!i),!i&&!this.sorted.length)return;const s=this.managers.appReactionsManager.getAvailableReactions(),n=i?s instanceof Promise?t.results:t.results.filter((e=>this.managers.appReactionsManager.isReactionActive(e.reaction))):[];(0,Mn.Z)(this.sorted,((e,t,i)=>{const s=e.reactionCount.reaction;n.some((e=>e.reaction===s))||(i.splice(t,1),e.remove())}));const a=n.reduce(((e,t)=>e+t.count),0),o=t&&!!t.pFlags.can_see_list&&a<4;if(this.sorted=n.map(((e,i)=>{const s=this.sorted.findIndex((t=>t.reactionCount.reaction===e.reaction));let n=-1!==s&&this.sorted[s];n||(n=new Wr,n.init(this.type)),Ln(n,this,i);const a=t.recent_reactions?t.recent_reactions.filter((t=>t.reaction===e.reaction)):[];return n.reactionCount=Object.assign({},e),n.setCanRenderAvatars(o),n.render(this.isPlaceholder),n.renderCounter(),n.renderAvatars(a),n.setIsChosen(),n})),!this.isPlaceholder&&(null==e?void 0:e.length)&&(this.isConnected?this.handleChangedResults(e):this.onConnectCallback=()=>{this.handleChangedResults(e)}),!this.sorted.length&&"block"===this.type){const e=this.parentElement;if(this.remove(),e.classList.contains("document-message")&&!e.childNodes.length)return void e.remove();const t=this.querySelector(".time");t&&e.append(t)}}handleChangedResults(e){this.message.peerId===_m.chat.peerId&&e.forEach((e=>{const t=this.sorted.find((t=>t.reactionCount.reaction===e.reaction));t&&t.fireAroundAnimation()}))}}customElements.define("reactions-element",jr);s.Z.addEventListener("replies_updated",(e=>{Array.from(document.querySelectorAll(`replies-element[data-post-key="${e.peerId}_${e.mid}"]`)).forEach((t=>{t.message=e,t.render()}))}));class qr extends HTMLElement{constructor(){super(),this.updated=!1,this.managers=s.Z.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("footer"===this.type){let t;this.firstElementChild&&(t=this.firstElementChild),(null==e?void 0:e.recent_repliers)?(t&&!t.classList.contains("replies-footer-avatars")&&(this.innerHTML="",t=null),this.stackedAvatars||(this.stackedAvatars=new na({lazyLoadQueue:this.lazyLoadQueue,avatarSize:30}),this.stackedAvatars.container.classList.add("replies-footer-avatars")),t=this.stackedAvatars.container,this.stackedAvatars.render(e.recent_repliers.map((e=>(0,es.Z)(e))),this.loadPromises)):(t&&!t.classList.contains("tgico-comments")&&(t.remove(),t=null),t||(t=document.createElement("span"),t.classList.add("tgico-comments"))),t.parentElement||this.prepend(t),this.text||(this.text=new v.ZP.IntlElement);const i=this.text;if(e?e.replies?i.compareAndUpdate({key:"Comments",args:[e.replies]}):i.compareAndUpdate({key:"LeaveAComment"}):i.compareAndUpdate({key:"ViewInChat"}),e){let t=!1;e.replies&&void 0!==e.read_max_id&&void 0!==e.max_id&&(t=e.read_max_id<e.max_id),this.classList.toggle("is-unread",t)}let s=this.children[1];if(!s){s=document.createElement("span"),s.classList.add("replies-footer-text");const e=document.createElement("span");e.classList.add("tgico-next");const t=document.createElement("div");(0,we.Z)(t),this.append(s,e,t)}(0,g.Z)(s,i.element)}else this.classList.add("bubble-beside-button"),this.innerHTML=`<span class="tgico-commentssticker"></span><span class="replies-beside-text">${(null==e?void 0:e.replies)?Zr(e.replies,0):""}</span>`;!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("replies-element",qr);const Qr=()=>{const e=document.createElement("i");return e.classList.add("edited"),(0,v.$d)(e,"EditedMessage"),e},Yr=()=>(0,v.ag)("SponsoredMessage");var Jr;!function(e){e.setTime=e=>{var t;const{chatType:i,message:s}=e,n=new Date(1e3*s.date),a=[];let o,r,l,d;const h=!!s.pFlags.sponsored,u=!("action"in s)&&!h;let p;const m=h?void 0:V(n);if(u){if(s.views){const e=s.post_author||(null===(t=s.fwd_from)||void 0===t?void 0:t.post_author),i=document.createElement("span");i.classList.add("post-views"),i.innerHTML=Zr(s.views,1);const n=document.createElement("i");if(n.classList.add("tgico-channelviews","time-icon"),a.push(i,n),e){const t=document.createElement("span");(0,c.Z)(t,(0,Zt.Z)(e)),t.insertAdjacentHTML("beforeend",",&nbsp;"),a.push(t)}}if(s.edit_date&&"scheduled"!==i&&!s.pFlags.edit_hide&&a.unshift(o=Qr()),"pinned"!==i&&s.pFlags.pinned){const e=document.createElement("i");e.classList.add("tgico-pinnedchat","time-icon"),a.unshift(e)}"peerUser"===s.peer_id._&&(p=!0,d=e.reactionsMessage,l=new jr,l.init(d,"inline",!0),l.render(),a.unshift(l))}else h&&a.push(r=Yr());m&&a.push(m);let g=h?void 0:K(n);u&&(g+=(s.edit_date&&!s.pFlags.edit_hide?`\nEdited: ${K(new Date(1e3*s.edit_date))}`:"")+(s.fwd_from?`\nOriginal: ${K(new Date(1e3*s.fwd_from.date))}`:""));const v=document.createElement("span");v.classList.add("time","tgico"),v.append(...a);const f=document.createElement("div");f.classList.add("inner","tgico"),g&&(f.title=g);let y=a;if(o&&(y[y.indexOf(o)]=Qr()),r&&(y[y.indexOf(r)]=Yr()),l){const e=y[y.indexOf(l)]=new jr;e.init(d,"inline"),e.render()}return y=y.map((e=>e instanceof HTMLElement&&!e.classList.contains("i18n")&&!e.classList.contains("reactions")?e.cloneNode(!0):e)),m&&(y[y.length-1]=V(n)),f.append(...y),v.append(f),v},e.renderReplies=({bubble:e,bubbleContainer:t,message:i,messageDiv:s,loadPromises:n,lazyLoadQueue:a})=>{const o=!e.classList.contains("sticker")&&!e.classList.contains("emoji-big")&&!e.classList.contains("round"),r=new qr;return r.message=i,r.type=o?"footer":"beside",r.loadPromises=n,r.lazyLoadQueue=a,r.init(),t.prepend(r),o},e.setReply=({chat:e,bubble:t,bubbleContainer:i,message:n})=>{return a=this,o=void 0,l=function*(){const a=!i;a&&(i=t.querySelector(".bubble-content"));const o=a?i.querySelector(".reply"):null;if(!n.reply_to_mid)return o&&o.remove(),void t.classList.remove("is-reply");const r=n.reply_to.reply_to_peer_id?(0,es.Z)(n.reply_to.reply_to_peer_id):e.peerId,l=yield s.Z.managers.appMessagesManager.getMessageByPeer(r,n.reply_to_mid);let c,d;if(l){const e=l.fwdFromId;d=n.fwdFromId&&n.fwdFromId===e?n.fwdFromId:l.fromId||e,c=new Ot({peerId:d,dialog:!1,onlyFirstName:!1,plainText:!1}).element}else s.Z.managers.appMessagesManager.fetchMessageReplyTo(n),e.bubbles.needUpdate.push({replyToPeerId:r,replyMid:n.reply_to_mid,mid:n.mid}),c=(0,v.ag)("Loading");const{container:h,fillPromise:u}=Ba(c,void 0,l,e.isAnyGroup?d:void 0);yield u,o?o.replaceWith(h):i.append(h),t.classList.add("is-reply")},new((r=void 0)||(r=Promise))((function(e,t){function i(e){try{n(l.next(e))}catch(e){t(e)}}function s(e){try{n(l.throw(e))}catch(e){t(e)}}function n(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r((function(e){e(n)}))).then(i,s)}n((l=l.apply(a,o||[])).next())}));var a,o,r,l}}(Jr||(Jr={}));var Xr=i(252);function el(e,t,i){const s=e.getBoundingClientRect(),n="center"===i?Math.ceil(s.left+(s.right-s.left)/2+1):Math.ceil(s.left+1),a="bottom"===t?Math.floor(s.top+s.height-1):Math.ceil(s.top+1);return document.elementFromPoint(n,a)}function tl(e){e.style.display="none",e.offsetLeft,e.style.display=""}R.GO.getElementByPoint=el;const il=2147483646;var sl,nl=i(993);class al extends A.Z{constructor(e,t){super("popup-join-chat-invite",{closable:!0,overlayClosable:!0,body:!0,buttons:(0,A.x)([{langKey:t.pFlags.request_needed?"RequestJoin.Button":t.pFlags.broadcast?"JoinByPeekChannelTitle":"JoinByPeekGroupTitle",callback:()=>{this.managers.appChatsManager.importChatInvite(e).then((e=>{const t=e.toPeerId(!0);_m.setInnerPeer({peerId:t})}),(e=>{"INVITE_REQUEST_SENT"===e.type&&Li({langPackKey:"RequestToJoinSent"})}))}}])}),this.hash=e,this.chatInvite=t,this.construct()}construct(){return e=this,t=void 0,s=function*(){this.header.remove();const{chatInvite:e,managers:t,hash:i}=this,s=new Wm;s.classList.add("avatar-100"),s.isDialog=!1,"photo"===e.photo._?(e.photo=yield t.appPhotosManager.savePhoto(e.photo),dt({container:s,message:null,photo:e.photo,boxHeight:100,boxWidth:100,withoutPreloader:!0}),s.style.width=s.style.height=""):Hs(s,le.NM,!1,e.title);const n=document.createElement("div");n.classList.add("chat-title"),(0,c.Z)(n,(0,Zt.Z)(e.title));const a=e.pFlags.broadcast,o=(0,v.ag)(a?"Subscribers":"Members",[ls(e.participants_count)]);if(o.classList.add("chat-participants-count"),this.body.append(s,n,o),e.pFlags.request_needed){const e=document.createElement("div");(0,v.$d)(e,a?"RequestToJoinChannelDescription":"RequestToJoinGroupDescription"),e.classList.add("chat-participants-count","request-caption"),this.body.append(e)}this.show()},new((i=void 0)||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}));var e,t,i,s}}!function(e){e[e.MESSAGE=0]="MESSAGE",e[e.PRIVATE_POST=1]="PRIVATE_POST",e[e.STICKER_SET=2]="STICKER_SET",e[e.JOIN_CHAT=3]="JOIN_CHAT",e[e.VOICE_CHAT=4]="VOICE_CHAT",e[e.USER_PHONE_NUMBER=5]="USER_PHONE_NUMBER",e[e.INVOICE=6]="INVOICE"}(sl||(sl={}));class ol{constructor(e,t,i){this.scrollable=e,this.query=t,this.reverse=i}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(),i=Array.from(e.querySelectorAll(this.query)),s=[];for(const n of i){const i=n.getBoundingClientRect();if(En(n,e,void 0,i,t))s.push({element:n,rect:i});else if(s.length)break}if(!s.length){const e=i[0];e&&s.push({element:e,rect:e.getBoundingClientRect()})}return s}replaceSaved(e,t){if(!this.elements)return;const i=this.elements.findIndex((({element:t})=>e===t));-1!==i&&(this.elements[i].element=t)}findAndSetElements(){this.elements=this.findElements()}save(){this.findAndSetElements(),this._save()}_save(){const{scrollTop:e,scrollHeight:t,clientHeight:i}=this.container;this.scrollHeight=t,this.scrollTop=e,this.clientHeight=i,this.scrollHeightMinusTop=this.reverse?t-e:e}onRestore(e){Je.IS_SAFARI&&e&&tl(this.container)}setScrollTop(e,t){this.scrollable.setScrollTopSilently(this.scrollTop=e),this.onRestore(t)}restore(e){var t;const{scrollTop:i,scrollHeight:s}=this.scrollable;if(this.scrollHeight=s,!this.elements.length)return void this._restore(e);let n;if(n=this.elements[this.elements.length-1],!(null===(t=null==n?void 0:n.element)||void 0===t?void 0:t.parentElement)&&(this.findAndSetElements(),n=this.elements[this.elements.length-1],!n))return void this._restore(e);const{element:a,rect:o}=n,r=a.getBoundingClientRect().bottom-o.bottom;this.setScrollTop(i+r,e)}_restore(e){const{scrollHeightMinusTop:t,scrollable:i}=this,s=this.scrollHeight,n=this.reverse?s-t:t;this.setScrollTop(n,e)}}R.GO&&(R.GO.ScrollSaver=ol);class rl{constructor(e){this.observing=new Map,this.observingQueue=new Map,this.freezedObservingNew=!1,this.observer=new IntersectionObserver((e=>{const t=this.observing;for(let i=0,s=e.length;i<s;++i){const s=e[i],n=t.get(s.target);for(const e of n)try{e(s)}catch(e){console.error("intersection process callback error:",e)}}}),e)}disconnect(){this.observing.clear(),this.observingQueue.clear(),this.observer.disconnect()}toggleObservingNew(e){if(this.freezedObservingNew===e)return;this.freezedObservingNew=e;const t=this.observingQueue;if(!e&&t.size){for(const[e,i]of t)for(const t of i)this.observe(e,t);t.clear()}}has(e,t,i=this.observing){const s=i.get(e);return!(!s||!s.has(t))}observe(e,t){if(this.freezedObservingNew&&this.has(e,t))return;const i=this.freezedObservingNew?this.observingQueue:this.observing;let s=i.get(e);s&&s.has(t)||(s||(s=new Set,i.set(e,s),i===this.observing&&this.observer.observe(e)),s.add(t))}unobserve(e,t){const i=this.freezedObservingNew&&!this.has(e,t)?this.observingQueue:this.observing,s=i.get(e);s&&(s.delete(t),s.size||(i.delete(e),this.observer.unobserve(e)))}}function ll(e){var t;if(!e)return!1;const i=null===(t=e.media)||void 0===t?void 0:t.document;return!(!e.pFlags.media_unread||!e.pFlags.mentioned||i&&["voice","round"].includes(i.type))}var cl=i(3781),dl=i(2586);function hl(e,t=""){return i=>{if(!(i instanceof Promise)){if(i instanceof Error)throw i;return i}return i.then((i=>{if(!e())throw t;return i}))}}var ul=i(2381);const pl=function(e){const t={},i={};return s=>{var n,a;const o="_"+s;return null!==(n=(a="string"==typeof s?t:i)[o])&&void 0!==n?n:a[o]=e(s)}};function ml(e){return e.replace(/\D/g,"")}const gl={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:/^(220[0-4])/},vl={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}},fl=pl(((e="")=>{const t=Object.keys(gl),i=ml(e);let s,n=0;return t.forEach((e=>{const t=gl[e],a=i.match(t);if(a){const t=a[0];t&&t.length>n&&(s=e,n=t.length)}})),s||"unknown"}));function yl(e=""){return"diners14"===(t=fl(e))?"diners":t;var t}var bl=i(2398),wl=i(7298);function Sl(e,t,i){const s=new Array(e);return s.fill(t),i?s.map(i):s}const Cl="".charCodeAt(0)-"0".charCodeAt(0),Ll=/[-]/g;function Il(e){return String.fromCharCode(e.charCodeAt(0)-Cl)}function Ml(e){return e.replace(Ll,Il)}function El(e,t){return{type:"optional",result:e,consumed:t}}function Pl(e,t,i){return{type:"required",result:e,consumed:t,partial:i}}function kl(e,t){return i=>{const s=new RegExp("^".concat(e.source.replace(/^\^/,""))),n=i.match(s),a=t?El:Pl;if(n){const e=n[0];return a(e,n.index+e.length)}return a("",i.length)}}const Tl=kl(/1[0-2]|0?[1-9]|0/),xl={digit:function(e){return kl(/[0-9]/)(Ml(e))},capitalCharacter:function(e){const t=kl(/\w/)(e);return t.result?Pl(t.result.toUpperCase(),t.consumed):t},month:e=>{const t=Tl(Ml(e)),i=ml(t.result);return["0","1"].includes(t.result)&&1===e.length||"0"===t.result&&e.length>=2?Pl(t.result,e.length,!0):Pl(1===i.length?"0"+i:i,t.consumed)},formattingCharacter:e=>t=>{const i=e===t[0]?1:0;return function(e,t){return{type:"formatting",result:e,consumed:t}}(e,i)},optionalPattern:e=>t=>{const i=kl(e,!0)(t);return i.result?i:El("",0)}},_l=xl.digit,Al=xl.capitalCharacter,Zl=xl.formattingCharacter(" "),Fl=xl.optionalPattern(/\d\d/),Dl=[_l,_l,_l,_l,Zl,_l,_l,_l,_l,_l,_l,Zl,_l,_l,_l,_l,_l],Rl=[_l,_l,_l,_l,Zl,_l,_l,_l,_l,_l,_l,Zl,_l,_l,_l,_l],Bl=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"]),Nl=pl((e=>{const t=[];for(let i=0,s=0;i<e;)4===s?(t.push(Zl),s=0):(t.push(_l),++i,++s);return t})),Ul={cardNumber:function(e){const t=fl(e);if("amex"===t)return Dl;if("diners14"===t)return Rl;const{minLength:i,maxLength:s}=vl[t],n=ml(e).length,a=Math.min(Math.max(i,n),s);return Nl(a)},cardExpiry:()=>[xl.month,xl.formattingCharacter("/"),_l,_l,Fl],cardCvc:e=>Ul.cardCvcFromBrand(fl(e)),cardCvcFromBrand:pl((e=>{const t=vl[e],{cvcMinLength:i,cvcMaxLength:s}=t,n=Sl(i||s,_l);if(i&&i<s){const e=s-i,t=xl.optionalPattern(/\d/);e&&n.push(...Sl(e,t))}return n})),postalCodeFromCountry:pl((e=>{switch(e){case"US":return Sl(5,_l);case"CA":return Je.IS_ANDROID?null:[Al,Al,Al,Zl,Al,Al,Al];default:const t=Sl(10,xl.optionalPattern(/\d/));return Bl.has(e)&&(t[0]=_l),t}}))},Ol=Ul;function Hl(e){return Ie(e.map((e=>e.length)),0)}const zl=new RegExp("","g");function Gl(e){return e?{type:"invalid",code:e}:null}function Vl(e,t={}){const{sanitized:i,minLength:s}=function(e){const t=ml(e),i=fl(e);return{sanitized:t,brand:i,minLength:vl[i].minLength}}(e);return function(e,t,i){return e.length>=t?function(e){const t="0".charCodeAt(0),i=e.length%2;let s=0;for(let n=e.length-1;n>=0;--n){const a=i===n%2;let o=e.charCodeAt(n)-t;a&&(o*=2),o>9&&(o-=9),s+=o}return!(s%10)}(e)||"mir"===fl(e)?null:Gl("invalid"):i?null:Gl("incomplete")}(i,s,t.ignoreIncomplete)}function Kl(e,t={}){const i=e.replace(zl,"").split(/ ?\/ ?/),[s,n=""]=i,[a,o]=[s,n].map((e=>+e)),r=2===n.length?o%100:o;return n.length<2||3===n.length?t.ignoreIncomplete?null:Gl("incomplete"):Gl(function(e,t,i){const s=new Date(Date.now()),n=e<100?s.getFullYear()%100:s.getFullYear(),a=s.getMonth()+1;return isNaN(e)||isNaN(t)?(null==i?void 0:i.ignoreIncomplete)?null:"incomplete":e-n<0?"invalid_expiry_year_past":e-n>50?"invalid_expiry_year":!(e-n)&&t<a?"invalid_expiry_month_past":null}(r,a,t))}var Wl=i(5431);const $l=new WeakMap;function jl(e,t){const i=document.createElement("iframe");return i.allow="payment",i.setAttribute("sandbox","allow-forms allow-scripts allow-same-origin allow-modals"),i.classList.add("payment-verification"),i.src=e,i.addEventListener("load",(()=>{$l.set(i.contentWindow,t)}),{once:!0}),i}window.addEventListener("message",(e=>{const t=$l.get(e.source);t&&t(JSON.parse(e.data))}));class ql extends A.Z{constructor(e){super("popup-payment popup-payment-verification",{closable:!0,overlayClosable:!0,body:!0,title:"Checkout.WebConfirmation.Title"}),this.url=e,this.d()}d(){const e=jl(this.url,(e=>{"web_app_open_tg_link"===e.eventType&&(this.dispatchEvent("finish"),this.hide(),_m.openUrl("https://t.me"+e.eventData.path_full))}));this.body.append(e),this.show()}}class Ql extends b.Z{constructor(e){super(e),this.options=e,this.onKeyDown=e=>{var t,i;this.lastKeyDown=e.key,null===(i=(t=this.options).onKeyDown)||void 0===i||i.call(t,e)},this.onInput=()=>{var e,t;const i=this.value,s="Backspace"===this.lastKeyDown&&(this.lastTransformed&&this.lastTransformed.value.length||0)-i.length==1,n=this.lastTransformed=function(e){const{value:t,getPattern:i,deleting:s,input:n}=e,a=!s&&!!t.length,o=function(e,t,i={},s){const n=e(t);if(!n)return{value:t,selection:null,autocorrectComplete:!!t};const a=n.length,o=[],r=[];let l=0,c=0,d=0===i.selectionStart?0:null,h=0===i.selectionEnd?0:null;const u=e=>{e>0&&(null===d&&c+1>=i.selectionStart&&(d=Hl(o)+(s?r.length:0)),null===h&&c+1>=i.selectionEnd&&(h=Hl(o)+(s?r.length:0)),c+=e)};for(;l<a;){const e=(0,n[l])(t.slice(c)),{type:i,result:a,consumed:d}=e;if("required"===i)if(a){if(o.push(...r,a),r.length=0,++l,e.partial){u(t.length-c);break}u(d)}else{if(!d)break;u(1)}else if("optional"===i)a&&(o.push(...r,a),r.length=0,u(d)),++l;else if("formatting"===i){if(!s&&c>=t.length)break;r.push(a),++l,u(d)}}return s&&o.push(...r),{value:o.join(""),selection:{selectionStart:null===d||t.length&&i.selectionStart===t.length?Hl(o):d,selectionEnd:null===h||t.length&&i.selectionEnd===t.length?Hl(o):h},autocorrectComplete:l===a}}(i,t,{selectionStart:n?n.selectionStart:0,selectionEnd:n?n.selectionEnd:0},a),{value:r,selection:l}=o;return{value:r,meta:{autocorrectComplete:o.autocorrectComplete,empty:!r},selection:l}}({value:i,getPattern:this.options.formatMethod,deleting:s,input:this.input}),a=n.value;a!==i&&(this.setValueSilently(a),n.selection&&(this.input.selectionStart=n.selection.selectionStart,this.input.selectionEnd=n.selection.selectionEnd)),this.validateNew(a,{ignoreIncomplete:!0}),null===(t=(e=this.options).onChange)||void 0===t||t.call(e,n)},this.onBlur=()=>{var e;const t=null===(e=this.lastTransformed)||void 0===e?void 0:e.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,t,i){var s,n,a,o,r;let l;if(void 0===e&&(e=null!==(n=null===(s=this.lastTransformed)||void 0===s?void 0:s.value)&&void 0!==n?n:""),void 0===t&&(t={}),l=this.options.validateMethod?null===(o=(a=this.options).validateMethod)||void 0===o?void 0:o.call(a,e,t):function(e,t,i={}){return e.meta.autocorrectComplete||i.ignoreIncomplete?null:Gl("incomplete")}(this.lastTransformed,0,t),null==l?void 0:l.code){const e=null===(r=this.options.errorKeys)||void 0===r?void 0:r[l.code];return!i&&this.setState(b.I.Error,e),!1}return!i&&this.setState(b.I.Neutral),!0}}function Yl(e,t){const i=()=>{const i=e.every((e=>"validateNew"in e?e.validateNew(void 0,void 0,!0):e.isValid()));t(i)};return e.forEach((e=>{if(e instanceof Ql){const t=e.options.onChange;e.options.onChange=(...e)=>{null==t||t(...e),i()},"update"in e&&e.update()}else e.input.addEventListener("input",i)})),{validate:i}}function Jl(e,t){let i,s;return(e||t)&&(e&&(i=new Wl.Z({noPhoneCodes:!0,onCountryChange:()=>{null==s||s.update()},required:!0,autocomplete:"country"})),t&&(s=new Ql({label:"PaymentShippingZipPlaceholder",plainText:!0,inputMode:"numeric",autocomplete:"postal-code",formatMethod:()=>{const{country:e}=i.getSelected(),t=null==e?void 0:e.iso2;return Ol.postalCodeFromCountry(t&&t.toUpperCase())}}))),{countryInputField:i,postcodeInputField:s}}const Xl=new Set(["stripe","smartglocal"]);class ec extends A.Z{constructor(e,t){if(super("popup-payment popup-payment-card",{closable:!0,overlayClosable:!0,body:!0,scrollable:Xl.has(e.native_provider),title:"PaymentCardInfo"}),this.paymentForm=e,this.savedCard=t,Xl.has(e.native_provider))this.d();else{const t=jl(e.url,(t=>{if("payment_form_submit"!==t.eventType)return;const i=t.eventData,s={title:i.title,save:!1};this.dispatchEvent("finish",{token:i.credentials,card:s}),this.hide(),e.pFlags.can_save_credentials&&In({titleLangKey:"PaymentCardSavePaymentInformation",descriptionLangKey:"PaymentCardSavePaymentInformationInfoLine1",button:{langKey:"Save"}}).then((()=>{s.save=!0}),ft.Z)}));this.body.append(t),this.show()}}d(){const e=this.savedCard,t=new Br({name:"PaymentInfo.Card.Title",noDelimiter:!0,noShadow:!0}),i=JSON.parse(this.paymentForm.native_params.data);let s,n,a=0;const o=new Ql({label:"PaymentCardNumber",plainText:!0,inputMode:"numeric",autocomplete:"cc-number",formatMethod:Ol.cardNumber,validateMethod:Vl,errorKeys:{invalid:"PaymentCard.Error.Invalid",incomplete:"PaymentCard.Error.Incomplete"},onChange:e=>{(e=>{if(s===e)return;const t=++a;s=e;const i=oc(e);if(!i)return void(n&&(n.remove(),n=void 0));const r=new Image;r.classList.add("input-field-icon"),Ze(r,i,!1).then((()=>{a===t&&(n?n.replaceWith(r):o.container.append(r),n=r)}))})(yl(e.value)),c.update()}});let r;i.need_cardholder_name&&(r=new b.Z({label:"Checkout.NewCard.CardholderNamePlaceholder",maxLength:255,required:!0,autocomplete:"cc-name"}));const l=new Ql({label:"SecureId.Identity.Placeholder.ExpiryDate",plainText:!0,inputMode:"numeric",autocomplete:"cc-exp",formatMethod:Ol.cardExpiry,validateMethod:Kl}),c=new Ql({labelText:"CVC",plainText:!0,inputMode:"numeric",autocomplete:"cc-csc",formatMethod:()=>Ol.cardCvc(o.value)}),d=[o,l,c,r].filter(Boolean);d.forEach((e=>{const t=t=>{if(!e.value&&"Backspace"===t.key){const t=d[d.indexOf(e)-1];t&&(0,bl.Z)(t.input,!0)}};if(e instanceof Ql){e.options.onKeyDown=t;const i=e.options.onChange;e.options.onChange=t=>{if(null==i||i(t),document.activeElement===e.input&&t.meta.autocorrectComplete)for(let t=d.indexOf(e),i=d.length;t<i;++t){const e=d[t];if(e instanceof Ql?!e.validateNew(void 0,void 0,!0):!e.value){(0,bl.Z)(e.input,!0);break}}}}else e.input.addEventListener("keydown",t)}));const h=document.createElement("div");let u;h.classList.add("input-fields-row"),h.append(l.container,c.container),t.content.append(...[o.container,h,null==r?void 0:r.container].filter(Boolean));const{countryInputField:p,postcodeInputField:m}=Jl(i.need_country,i.need_zip);(i.need_country||i.need_zip)&&(u=new Br({name:"PaymentInfo.Billing.Title",noDelimiter:!0,noShadow:!0}),u.content.append(...[p,m].filter(Boolean).map((e=>e.container))));const g=!!this.paymentForm.pFlags.can_save_credentials,v=new ji.Z({text:"PaymentCardSavePaymentInformation",checked:!!g}),f=new Ni({checkboxField:v,subtitleLangKey:g?"PaymentCardSavePaymentInformationInfoLine1":"Checkout.2FA.Text",noCheckboxSubtitle:!0});g||f.container.classList.add("is-disabled"),(u||t).content.append(f.container),this.scrollable.append(...[t,u].filter(Boolean).map((e=>e.container)));const y=rc({key:"PaymentInfo.Done",onClick:()=>{return e=this,t=void 0,n=function*(){const e={cardNumber:o.value,expiryFull:l.value,expiryMonth:l.value.split("/")[0],expiryYear:l.value.split("/")[1],cvc:c.value,cardholderName:null==r?void 0:r.value,country:null==p?void 0:p.value,zip:null==m?void 0:m.value,save:null==v?void 0:v.checked},t=this.paymentForm.native_provider;let s;if("stripe"===t){const t=new URL("https://api.stripe.com/v1/tokens");t.search=new URLSearchParams({"card[number]":e.cardNumber,"card[exp_month]":e.expiryMonth,"card[exp_year]":e.expiryYear,"card[cvc]":e.cvc,"card[address_zip]":e.zip,"card[address_country]":e.country,"card[name]":e.cardholderName}).toString();const n=yield fetch(t.toString(),{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Bearer ${i.publishable_key}`}});s=yield n.json()}else if("smartglocal"===t){const t={card:{number:e.cardNumber.replace(/[^\d]+/g,""),expiration_month:e.expiryMonth,expiration_year:e.expiryYear,security_code:e.cvc.replace(/[^\d]+/g,"")}},n="https://tgb.smart-glocal.com/cds/v1/tokenize/card",a=yield fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-PUBLIC-TOKEN":i.public_token},body:JSON.stringify(t)});s={type:"card",token:(yield a.json()).data.token}}this.dispatchEvent("finish",{token:s,card:e}),this.hide()},new((s=void 0)||(s=Promise))((function(i,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((n=n.apply(e,t||[])).next())}));var e,t,s,n}});Yl([o,r,l,c,p,m].filter(Boolean),(e=>{y.disabled=!e})),e&&(o.value=e.cardNumber,l.value=e.expiryFull,c.value=e.cvc,r&&(r.value=e.cardholderName),p&&(p.value=e.country),m&&(m.value=e.zip)),this.body.append(this.btnConfirmOnEnter=y),this.show(),o.validateNew(void 0,void 0,!0)||(0,bl.Z)(o.input)}}class tc extends A.Z{constructor(e,t){super("popup-payment popup-payment-card-confirmation",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,title:"Checkout.PasswordEntry.Title"});const i=new Br({noDelimiter:!0,noShadow:!0,caption:"Checkout.PasswordEntry.Text",captionArgs:[e]}),s=new To.Z({labelText:t.hint});i.content.append(s.container),this.scrollable.append(i.container);const n=()=>{a.disabled=!s.value,s.setState(b.I.Neutral)};s.input.addEventListener("input",n);const a=rc({key:"Checkout.PasswordEntry.Pay",onClick:()=>{return e=this,i=void 0,a=function*(){try{const e=yield this.managers.passwordManager.getInputCheckPassword(s.value,t),i=yield this.managers.apiManager.invokeApi("account.getTmpPassword",{password:e,period:60});this.dispatchEvent("finish",i),this.hide()}catch(e){throw"PASSWORD_HASH_INVALID"===e.type&&(e.handled=!0,s.setError("PASSWORD_HASH_INVALID")),e}},new((n=void 0)||(n=Promise))((function(t,s){function o(e){try{l(a.next(e))}catch(e){s(e)}}function r(e){try{l(a.throw(e))}catch(e){s(e)}}function l(e){var i;e.done?t(e.value):(i=e.value,i instanceof n?i:new n((function(e){e(i)}))).then(o,r)}l((a=a.apply(e,i||[])).next())}));var e,i,n,a}});this.body.append(this.btnConfirmOnEnter=a),n(),this.show(),(0,bl.Z)(s.input)}}class ic extends A.Z{constructor(e,t,i){super("popup-payment popup-payment-shipping",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,title:"PaymentShippingInfo"}),this.paymentForm=e,this.inputInvoice=t,this.focus=i,this.d()}d(){const e=this.paymentForm.invoice,t=this.paymentForm.saved_info;let i,s,n,a,o,r,l,c,d,h,u;if(e.pFlags.shipping_address_requested){i=new Br({name:"PaymentShippingAddress",noDelimiter:!0,noShadow:!0}),s=new b.Z({label:"PaymentShippingAddress1Placeholder",maxLength:64,required:!0}),n=new b.Z({label:"PaymentShippingAddress2Placeholder",maxLength:64}),a=new b.Z({label:"PaymentShippingCityPlaceholder",maxLength:64,required:!0}),o=new b.Z({label:"PaymentShippingStatePlaceholder",maxLength:64});const e=Jl(!0,!0);r=e.countryInputField,l=e.postcodeInputField,i.content.append(...[s,n,a,o,r,l].filter(Boolean).map((e=>e.container)))}if([e.pFlags.name_requested,e.pFlags.email_requested,e.pFlags.phone_requested].includes(!0)){c=new Br({name:"PaymentShippingReceiver",noDelimiter:!0,noShadow:!0});const t=()=>{const e=h.value,t=Eo(e);return!(!t||t[0].length!==e.length)},i=()=>!!u.value.match(/\d/);e.pFlags.name_requested&&(d=new b.Z({label:"PaymentShippingName",maxLength:256,required:!0})),e.pFlags.email_requested&&(h=new b.Z({label:"PaymentShippingEmailPlaceholder",maxLength:64,required:!0,validate:t})),e.pFlags.phone_requested&&(u=new Er.Z({required:!0,validate:i})),c.content.append(...[d,h,u].filter(Boolean).map((e=>e.container)))}const p=new ji.Z({text:"PaymentShippingSave",checked:!0}),m=new Ni({checkboxField:p,subtitleLangKey:"PaymentShippingSaveInfo",noCheckboxSubtitle:!0});(c||i).content.append(m.container),this.scrollable.append(...[i,c].filter(Boolean).map((e=>e.container)));const g=rc({key:"PaymentInfo.Done",onClick:()=>{return e=this,t=void 0,c=function*(){const e=r&&r.getSelected().country,t={_:"paymentRequestedInfo",shipping_address:e&&{_:"postAddress",street_line1:s.value,street_line2:n.value,city:a.value,state:o.value,country_iso2:null==e?void 0:e.iso2,post_code:l.value},name:null==d?void 0:d.value,email:null==h?void 0:h.value,phone:null==u?void 0:u.value};try{const e=yield this.managers.appPaymentsManager.validateRequestedInfo(this.inputInvoice,t,null==p?void 0:p.checked);this.dispatchEvent("finish",{shippingAddress:t,requestedInfo:e}),this.hide()}catch(e){const t={ADDRESS_STREET_LINE1_INVALID:s,ADDRESS_STREET_LINE2_INVALID:n,ADDRESS_COUNTRY_INVALID:r,ADDRESS_CITY_INVALID:a,ADDRESS_STATE_INVALID:o,ADDRESS_POSTCODE_INVALID:l,REQ_INFO_NAME_INVALID:d,REQ_INFO_EMAIL_INVALID:h,REQ_INFO_PHONE_INVALID:u}[e.type];throw t&&(t.setError(),e.handled=!0),e}},new((i=void 0)||(i=Promise))((function(s,n){function a(e){try{r(c.next(e))}catch(e){n(e)}}function o(e){try{r(c.throw(e))}catch(e){n(e)}}function r(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}r((c=c.apply(e,t||[])).next())}));var e,t,i,c}});if(this.body.append(this.btnConfirmOnEnter=g),t){const e=t.shipping_address;e&&(s.value=e.street_line1,n.value=e.street_line2,a.value=e.city,o.value=e.state,r.selectCountryByIso2(e.country_iso2),l.value=e.post_code),t.name&&d&&(d.value=t.name),t.email&&h&&(h.value=t.email),t.phone&&u&&(u.value=t.phone)}const{validate:v}=Yl([s,n,a,o,r,l,d,h,u].filter(Boolean),(e=>{g.disabled=!e}));let f;v(),this.show(),f=this.focus?{name:d,email:h,phone:u}[this.focus]:s,f&&(0,bl.Z)(f.input)}}class sc extends A.Z{constructor(e,t,i){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=i,this.d()}d(){const e=new Br({name:"PaymentCheckoutShippingMethod",noDelimiter:!0,noShadow:!0}),t=this.requestedInfo.shipping_options.map((e=>new Ni({radioField:new Vi({text:e.title,name:"shipping-method",value:e.id}),subtitle:Ea(Ie(e.prices.map((({amount:e})=>+e)),0),this.paymentForm.invoice.currency)})));let i;const s=Ui(t,(e=>{i=e}));this.shippingOption?t.find((e=>e.radioField.input.value===this.shippingOption.id)).radioField.checked=!0:t[0].radioField.checked=!0,e.content.append(s),this.scrollable.append(e.container);const n=rc({key:"PaymentInfo.Done",onClick:()=>{this.dispatchEvent("finish",this.requestedInfo.shipping_options.find((e=>e.id===i))),this.hide()}});this.body.append(this.btnConfirmOnEnter=n),this.show()}}var nc=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const ac=["amex","card","diners","discover","jcb","mastercard","visa","unionpay","mir","logo"];function oc(e){if(ac.includes(e))return`assets/img/${e}.svg`}function rc(e){var t,i;const s=null!==(t=e.textEl)&&void 0!==t?t:new v.ZP.IntlElement({key:null!==(i=e.key)&&void 0!==i?i:"PaymentInfo.Done"}),a=s.key,o=(0,M.Z)("btn-primary btn-color-primary payment-item-pay");return o.append(s.element),(0,n.fc)(o,(()=>nc(this,void 0,void 0,(function*(){const t=e.onClick();if(!(t instanceof Promise))return;const i=(0,be.y)(o),n=(0,mi.Z)([o],!0);s.compareAndUpdate({key:"PleaseWait"});try{yield t}catch(e){e.handled||console.error("payment button error",e),n(),s.compareAndUpdate({key:a}),i.remove()}})))),o}class lc extends A.Z{constructor(e,t,i){super("popup-payment",{closable:!0,overlayClosable:!0,body:!0,scrollable:!0,title:!0}),this.message=e,this.inputInvoice=t,this.paymentForm=i,this.tipButtonsMap=new Map,this.d()}d(){var e;return nc(this,void 0,void 0,(function*(){this.element.classList.add("is-loading"),this.show();let t=!1;const i=()=>{t||(t=!0,Me&&Me.hide(),this.hide())};let{paymentForm:a,message:o}=this;o&&this.listenerSetter.add(s.Z)("payment_sent",(({peerId:e,mid:t})=>{o.peerId===e&&o.mid===t&&i()}));const l=null==o?void 0:o.media,d=l?!!l.receipt_msg_id:"payments.paymentReceipt"===a._,h=l?l.pFlags.test:a.invoice.pFlags.test,u=l?l.photo:a.photo,p=l?l.title:a.title,m=l?l.description:a.description;(0,v.$d)(this.title,d?"PaymentReceipt":"PaymentCheckout"),h&&this.title.append(" (Test)");const f="payment-item",y=document.createElement("div");y.classList.add(f);const b=f+"-details",w=document.createElement("div");let S;w.classList.add(b),u&&(S=document.createElement("div"),S.classList.add(b+"-photo","media-container-contain"),dt({photo:u,container:S,boxWidth:100,boxHeight:100,size:{_:"photoSizeEmpty",type:""}}),w.append(S));const C=b+"-lines",L=document.createElement("div");L.classList.add(C);const I=document.createElement("div");I.classList.add(C+"-title");const E=document.createElement("div");E.classList.add(C+"-description");const P=document.createElement("div");P.classList.add(C+"-bot-name"),L.append(I,E,P),(0,c.Z)(I,(0,Zt.Z)(p)),(0,c.Z)(E,(0,Zt.Z)(m));const k=new Ot;P.append(k.element),w.append(L),y.append(w),this.scrollable.append(y);const T=document.createElement("div");T.classList.add(f+"-preloader-container"),(0,be.y)(T,!0),this.scrollable.container.append(T);const x=this.inputInvoice;a||(a=d?yield this.managers.appPaymentsManager.getPaymentReceipt(o.peerId,l.receipt_msg_id):yield this.managers.appPaymentsManager.getPaymentForm(x),this.paymentForm=a);let _=a.saved_info||a.info;const A=null===(e=a.saved_credentials)||void 0===e?void 0:e[0];let[Z,F,D]=yield Promise.all([!d&&_&&this.managers.appPaymentsManager.validateRequestedInfo(x,_),A&&this.managers.passwordManager.getState(),js({peerId:a.provider_id.toPeerId()})]);console.log(a,Z),yield k.update({peerId:a.bot_id.toPeerId()}),T.remove(),this.element.classList.remove("is-loading");const R=(e,t)=>Ea(e,N,t),{invoice:B}=a,N=B.currency,U=B.pFlags.recurring&&!d;yield k.update({peerId:a.bot_id.toPeerId()});const O=U?yield js({peerId:a.bot_id.toPeerId()}):void 0;T.remove(),this.element.classList.remove("is-loading");const H=()=>{const e=document.createElement("div");e.classList.add(z+"-price");const t=document.createElement("span"),i=document.createElement("span");return e.append(t,i),{label:e,left:t,right:i}},z=f+"-prices",G=document.createElement("div");G.classList.add(z);const V=e=>e.map((e=>{const{amount:t,label:i}=e,s=H();s.left.textContent=i;const n=R(t);return s.right.textContent=n,s.label})),K=V(B.prices);let W=()=>0,$=0;const j=()=>{const e=R(Y+W()+$);Q.right.textContent=e,q.compareAndUpdate({key:"PaymentCheckoutPay",args:[e]})},q=new v.ZP.IntlElement,Q=H();Q.label.classList.add("is-total"),(0,v.$d)(Q.left,"PaymentTransactionTotal");const Y=Ie(B.prices.map((({amount:e})=>+e)),0),J=void 0!==B.max_tip_amount&&!d||!!a.tip_amount;if(J){const e=f+"-tips",t=Ma[N];W=()=>+i().replace(/\D/g,"");const i=()=>c.value,s=()=>{const e=wt(i(),`500 16px ${yt}`);c.style.width=e+"px"},o=e=>{e=Math.min(+e,+B.max_tip_amount);const t=R(e,!0);c.value=t,document.activeElement===c&&(0,bl.Z)(c),b&&b();const i=this.tipButtonsMap.get(e);i&&i.classList.add("active"),s(),j()},l=H();(0,v.$d)(l.left,d?"PaymentTip":"PaymentTipOptional");const c=document.createElement("input");c.type="tel",c.classList.add("input-clear",e+"-input"),l.right.append(c),d?l.label.classList.add("disable-hover"):l.label.style.cursor="text",l.label.addEventListener("mousedown",(e=>{(0,vi.Z)(e.target,c)||(0,bl.Z)(c)}));const h=c instanceof HTMLInputElement?1:2,u=()=>{g?--g:(g=h,(0,bl.Z)(c))},p=()=>{setTimeout((()=>{g=h,(0,bl.Z)(c),document.addEventListener("selectionchange",u)}),0)},m=()=>{c.addEventListener("focus",p,{once:!0}),document.removeEventListener("selectionchange",u)};let g;c.addEventListener("focusout",m),m(),c.addEventListener("input",(()=>{o(W())}));const y=[t.symbol,t.space_between?" ":""];let b;if(t.symbol_left||y.reverse(),l.right[t.symbol_left?"prepend":"append"](y.join("")),K.push(l.label),d)o(a.tip_amount);else{const t=document.createElement("div");t.classList.add(e);const i=e+"-tip",s=B.suggested_tip_amounts.map((e=>{const t=(0,M.Z)(i,{noRipple:!0});return t.textContent=R(e),this.tipButtonsMap.set(+e,t),t}));b=()=>{const e=t.querySelector(".active");e&&e.classList.remove("active")},(0,n.fc)(t,(e=>{const t=(0,r.Z)(e.target,i);if(!t)return;let s=0;if(t.classList.contains("active"))t.classList.remove("active");else{b(),t.classList.add("active");for(const[e,i]of this.tipButtonsMap)if(i===t){s=e;break}}o(s)})),o(0),t.append(...s),K.push(t)}}else j();K.push(Q.label),G.append(...K),y.append(G);const X=(e,t)=>nc(this,void 0,void 0,(function*(){const i=document.createElement("img");i.classList.add("media-photo"),yield Ze(i,oc(t));let s=e.media;s?(0,g.Z)(s,i):(s=e.createMedia("small"),s.classList.add("media-container-cover"),s.append(i))})),ee=e=>{e.titleLangKey&&(e.subtitleLangKey=e.titleLangKey),e.noWrap=!0;const t=new Ni(e);return t.container.classList.add(f+"-row"),e.titleLangKey&&t.subtitle.classList.add("hide"),t},te=(e,t)=>{if(e.title.textContent=t,!t){const t=v.ZP.weakMap.get(e.subtitle.firstElementChild);e.title.append((0,v.ag)(t.key))}e.subtitle.classList.toggle("hide",!t)},ie=e=>{let t,i,s;"title"in e?(t=e.title.split(" ").shift(),i=e.title,s=e.icon):(t=yl(e.cardNumber),i=t+" *"+e.cardNumber.split(" ").pop()),oe.title.classList.remove("tgico","tgico-card_outline"),X(oe,s||t.toLowerCase()),te(oe,i)},se=()=>{new ec(a,ne).addEventListener("finish",(({token:e,card:t})=>{ae=e,ne=t,ie(t)}))};let ne,ae;const oe=ee({titleLangKey:"PaymentCheckoutMethod",clickable:d?void 0:se,icon:"card_outline"});oe.container.classList.add(f+"-method-row"),A?ie(A):a.credentials_title&&ie({title:a.credentials_title});const re=ee({title:D,subtitleLangKey:"PaymentCheckoutProvider"}),le=new Wm;let ce,de,he,ue,pe,me,ge,ve;le.classList.add("avatar-32"),re.createMedia("small").append(le),le.updateWithOptions({peerId:a.provider_id.toPeerId()});const fe=B.pFlags.shipping_address_requested?e=>{if(!e)return pe.subtitle.classList.add("hide"),void(0,g.Z)(pe.title,(0,v.ag)("PaymentShippingAddress"));const t=e.shipping_address;te(ce,[t.city,t.street_line1,t.street_line2].filter(Boolean).join(", ")),pe.container.classList.toggle("hide",!Z&&!d)}:void 0,ye=e=>{fe&&fe(e),de&&te(de,e.name),he&&te(he,e.email),ue&&te(ue,e.phone&&"+"+(0,Ms.u)(e.phone).formatted)};if(d||(ge=e=>{new ic(a,x,e).addEventListener("finish",(({shippingAddress:e,requestedInfo:t})=>{Z=t,_=a.saved_info=e,ye(e)}))}),B.pFlags.shipping_address_requested){const e=e=>{const i=new ol(this.scrollable,void 0,!0);if(i.save(),t&&t.forEach((e=>e.remove())),!e)return $=0,j(),i.restore(),void this.onContentUpdate();me=e,te(pe,e.title),$=Ie(e.prices.map((({amount:e})=>+e)),0),t=V(e.prices);let s=Q.label;J&&(s=s.previousElementSibling,d||(s=s.previousElementSibling)),t.forEach((e=>s.parentElement.insertBefore(e,s))),j(),i.restore(),this.onContentUpdate()};let t;ce=ee({icon:"location",titleLangKey:"PaymentShippingAddress",clickable:!d&&ge.bind(null,void 0)}),pe=ee({icon:"shipping",titleLangKey:"PaymentCheckoutShippingMethod",clickable:!d&&(ve=()=>{new sc(a,Z,me).addEventListener("finish",(t=>{e(t)}))})}),pe.container.classList.add("hide");const i=a.shipping;i&&e(i)}B.pFlags.name_requested&&(de=ee({icon:"newprivate",titleLangKey:"PaymentCheckoutName",clickable:!d&&ge.bind(null,"name")})),B.pFlags.email_requested&&(he=ee({icon:"mention",titleLangKey:"PaymentShippingEmailPlaceholder",clickable:!d&&ge.bind(null,"email")})),B.pFlags.phone_requested&&(ue=ee({icon:"phone",titleLangKey:"PaymentCheckoutPhoneNumber",clickable:!d&&ge.bind(null,"phone")})),_&&ye(_);const we=[oe,re,ce,pe,de,he,ue].filter(Boolean),Se=U&&new ji.Z({text:"Payments.Recurrent.Accept",textArgs:[(0,ii.Z)(B.recurring_terms_url),O]}),Ce=U&&ee({checkboxField:Se,noCheckboxSubtitle:!0}),Le=U?[document.createElement("hr"),Ce.container]:[];let Me,Ee;this.scrollable.append(...[document.createElement("hr"),...we.map((e=>e.container)),...Le].filter(Boolean));const Pe=()=>{ke.disabled=!(!Se||Se.checked)};let ke;ke=rc(d?{onClick:()=>this.hide(),key:"Done"}:{onClick:()=>{const e=B.pFlags.name_requested&&!(null==_?void 0:_.name)?"name":B.pFlags.email_requested&&!(null==_?void 0:_.email)?"email":B.pFlags.phone_requested&&!(null==_?void 0:_.phone)?"phone":void 0;if(B.pFlags.shipping_address_requested){if(!Z)return void ge();if(!me)return void ve()}else if(e)return void ge(e);return ne||Ee?Promise.resolve().then((()=>nc(this,void 0,void 0,(function*(){const e=Ee?{_:"inputPaymentCredentialsSaved",id:A.id,tmp_password:Ee.tmp_password}:{_:"inputPaymentCredentials",data:{_:"dataJSON",data:JSON.stringify(ae.token?ae:{type:ae.type,id:ae.id})},pFlags:{save:ne.save||void 0}};try{const s=yield this.managers.appPaymentsManager.sendPaymentForm(x,a.form_id,null==Z?void 0:Z.id,null==me?void 0:me.id,e,W());"payments.paymentResult"===s._?i():(Me=new ql(s.url),Me.addEventListener("finish",(()=>{Me=void 0,i()})),yield new Promise(((e,i)=>{Me.addEventListener("close",(()=>{if(Me=void 0,t)e();else{const e=new Error("payment not finished");e.handled=!0,i(e)}}))})))}catch(e){throw"BOT_PRECHECKOUT_TIMEOUT"===e.type?(Li({langPackKey:"Error.AnError"}),e.handled=!0):"TMP_PASSWORD_INVALID"===e.type&&(F=Ee=void 0,(0,n.tH)(ke),e.handled=!0),e}})))):A?void Promise.resolve(null!=F?F:this.managers.passwordManager.getState()).then((e=>{new tc(A.title,e).addEventListener("finish",(e=>{F=void 0,Ee=e,(0,n.tH)(ke);const t=e.valid_until-(0,wl.Z)(!0)-5;setTimeout((()=>{Ee===e&&(Ee=void 0)}),1e3*t)}))})):void se()},textEl:q}),Pe(),Se&&Se.input.addEventListener("change",Pe),this.body.append(this.btnConfirmOnEnter=ke),this.onContentUpdate()}))}}var cc=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const dc=new Set(["messageActionHistoryClear","messageActionChatCreate"]),hc=new Set;nl.Z&&hc.add("messageActionPhoneCall");const uc=void 0;let pc=uc,mc=0;const gc=3,vc=new Error("peer changed");function fc(e){return Math.max(...e)}class yc{constructor(e,t){let i;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.unreadedSeen=new Set,this.preloader=null,this.messagesQueuePromise=null,this.messagesQueue=[],this.messagesQueueOnRenderAdditional=null,this.firstUnreadBubble=null,this.middleware=(0,Ti.k)(),this.replyFollowHistory=[],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.unreadedObserverCallback=e=>{if(e.isIntersecting){const t=e.target,i=this.unreaded.get(t);this.onUnreadedInViewport(t,i)}},this.viewsObserverCallback=e=>{if(e.isIntersecting){const t=+e.target.dataset.mid;if(this.observer.unobserve(e.target,this.viewsObserverCallback),t)this.viewsMids.add(t),this.sendViewCountersDebounced();else{const{sponsoredMessage:e}=this;e&&e.random_id&&(delete e.random_id,this.managers.appChatsManager.viewSponsoredMessage(this.peerId.toChatId(),e.random_id))}}},this.stickerEffectObserverCallback=e=>{if(e.isIntersecting){this.observer.unobserve(e.target,this.stickerEffectObserverCallback);const t=e.target.querySelector(".attachment");(0,He.e9)().then((()=>{(0,Ne.Z)(t)&&(0,n.tH)(t)}))}},this.onBubblesMouseMove=e=>cc(this,void 0,void 0,(function*(){const t=(0,r.Z)(e.target,"bubble-content");if(t&&!this.chat.selection.isSelecting){const e=(0,r.Z)(t,"bubble");if(!this.chat.selection.canSelectBubble(e))return void this.unhoverPrevious();let{hoverBubble:i,hoverReaction:s}=this;if(e===i)return;if(this.unhoverPrevious(),i=this.hoverBubble=e,s=this.hoverReaction,s)s.dataset.loaded&&this.setHoverVisible(s,!0);else{s=this.hoverReaction=document.createElement("div"),s.classList.add("bubble-hover-reaction");const i=document.createElement("div");i.classList.add("bubble-hover-reaction-sticker"),s.append(i),t.append(s);let o=yield this.chat.getMessage(+e.dataset.mid);o=yield this.managers.appMessagesManager.getGroupsFirstMessage(o);const r=this.getMiddleware((()=>this.hoverReaction===s));Promise.all([this.managers.appReactionsManager.getAvailableReactionsByMessage(o),(0,on.Z)(400)]).then((([e])=>{const t=e[0];t?ta({div:i,doc:t.select_animation,width:18,height:18,needUpscale:!0,middleware:r,group:km,withThumb:!1,needFadeIn:!1}).then((({render:e})=>e)).then((e=>{(0,ai.Z)(e),e.addEventListener("firstFrame",(()=>{r()&&(s.dataset.loaded="1",this.setHoverVisible(s,!0))}),{once:!0}),(0,n.fc)(s,(e=>{(0,a.Z)(e),this.managers.appReactionsManager.sendReaction(o,t.reaction),this.unhoverPrevious()}),{listenerSetter:this.listenerSetter})}),ft.Z):s.remove()}))}}else this.unhoverPrevious()})),this.unhoverPrevious=()=>{const{hoverBubble:e,hoverReaction:t}=this;e&&(this.setHoverVisible(t,!1),this.hoverBubble=void 0,this.hoverReaction=void 0)},this.onBubblesClick=e=>cc(this,void 0,void 0,(function*(){var t;let i=e.target,s=null;try{s=(0,r.Z)(i,"bubble")}catch(e){}if(!s&&!this.chat.selection.isSelecting){const e=(0,r.Z)(i,"user-avatar");if(!e)return;const t=e.dataset.peerId.toPeerId();return void(t!==le.NM?this.chat.appImManager.setInnerPeer({peerId:t}):Ci(v.ZP.format("HidAccount",!0)))}if(s.classList.contains("is-date")&&(0,r.Z)(i,"bubble-content")){if(s.classList.contains("is-sticky")&&!this.chatInner.classList.contains("is-scrolling"))return;for(const e in this.dateMessages)if(this.dateMessages[e].div===s){A.Z.createPopup(Vr,new Date(+e),this.onDatePick).show();break}return}if(!gi.Z&&(0,r.Z)(i,"time"))return void this.chat.selection.toggleByElement(s);if(this.chat.selection.isSelecting&&e.isTrusted){if(s.classList.contains("service")&&void 0===s.dataset.mid)return;return(0,a.Z)(e),gi.Z&&this.chat.selection.selectedText?void(this.chat.selection.selectedText=void 0):void this.chat.selection.toggleByElement((0,r.Z)(i,"grouped-item")||s)}const o=(0,r.Z)(i,"contact");if(o)return void this.chat.appImManager.setInnerPeer({peerId:o.dataset.peerId.toPeerId()});const c=(0,r.Z)(i,"bubble-call");if(c)return void this.chat.appImManager.callUser(this.peerId.toUserId(),c.dataset.type);if((0,r.Z)(i,"is-buy")){(0,a.Z)(e);const t=yield this.chat.getMessage(+s.dataset.mid);if(!t)return;return void new lc(t,yield this.managers.appPaymentsManager.getInputInvoiceByPeerId(t.peerId,t.mid))}const d=(0,l.Z)(i,"REACTION-ELEMENT");if(d){if((0,a.Z)(e),d.classList.contains("is-inactive"))return;const t=d.parentElement,i=t.getReactionCount(d),s=t.getMessage();return void this.managers.appReactionsManager.sendReaction(s,i.reaction)}if((0,r.Z)(i,"replies")){const e=+s.dataset.mid;if(this.peerId===le.hj){const t=yield this.chat.getMessage(e),i=(0,es.Z)(t.reply_to.reply_to_peer_id),s=t.reply_to.reply_to_top_id,n=t.fwd_from.saved_from_msg_id;this.chat.appImManager.openThread(i,n,s)}else{const t=yield this.chat.getMessage(e),i=yield this.managers.appMessagesManager.getMessageWithReplies(t),s=i.replies;s&&this.managers.appMessagesManager.getDiscussionMessage(this.peerId,i.mid).then((e=>{this.chat.appImManager.setInnerPeer({peerId:s.channel_id.toPeerId(!0),type:"discussion",threadId:e.mid})}))}return}const h=(0,r.Z)(i,"is-via");if(h){const t=h.querySelector(".peer-title");if(i===t||(0,vi.Z)(i,t)){const i=t.innerText+" ";return this.managers.appDraftsManager.setDraft(this.peerId,this.chat.threadId,i),void(0,a.Z)(e)}}const u=(0,r.Z)(i,"peer-title")||(0,l.Z)(i,"AVATAR-ELEMENT")||(0,is.Z)(i,"data-saved-from");if(u&&u!==s){i=u||i;const e=i.dataset.peerId||i.getAttribute("peer")||i.peerId,t=i.dataset.savedFrom;if("string"==typeof e||t)if(t){const[e,n]=t.split("_");if(i.classList.contains("is-receipt-link")){const t=yield this.managers.appMessagesManager.getMessageByPeer(e.toPeerId(),+n);if(t){const e=yield this.managers.appPaymentsManager.getInputInvoiceByPeerId(this.peerId,+s.dataset.mid);new lc(t,e)}}else this.chat.appImManager.setInnerPeer({peerId:e.toPeerId(),lastMsgId:+n})}else{const t=e.toPeerId();t!==le.NM?this.chat.appImManager.setInnerPeer({peerId:t}):Ci(v.ZP.format("HidAccount",!0))}return}if(s.classList.contains("sticker")&&i.parentElement.classList.contains("attachment")){const e=+s.dataset.mid,i=null===(t=(yield this.chat.getMessage(e)).media)||void 0===t?void 0:t.document;return void((null==i?void 0:i.stickerSetInput)&&new qn(i.stickerSetInput).show())}const p=(0,r.Z)(i,"document-with-thumb");if("IMG"===i.tagName&&!i.classList.contains("emoji")&&!i.classList.contains("document-thumb")||i.classList.contains("album-item")||"VIDEO"===i.tagName&&!s.classList.contains("round")||p&&!p.querySelector(".preloader-container")||i.classList.contains("canvas-thumbnail")){const t=(0,r.Z)(i,"album-item")||(0,r.Z)(i,"document-container"),o=(t||s).querySelector(".preloader-container");if(o)return(0,n.tH)(o),void(0,a.Z)(e);(0,a.Z)(e);const l=+(t||s).dataset.mid,c=yield this.chat.getMessage(l);if(!c)return void this.log.warn("no message by messageId:",l);const d="webpage",h=s.classList.contains(d),u=p?e=>Rm.isMediaCompatibleForDocumentViewer(e):e=>"photo"===e._||["video","gif"].includes(e.type),m=[],g=h?[l]:(yield Promise.all(Object.keys(this.bubbles).map((e=>+e)).map((e=>cc(this,void 0,void 0,(function*(){const t=yield this.chat.getMessage(e),i=(0,Se.Z)(t);return i&&u(i)&&e})))))).filter(Boolean).sort(((e,t)=>e-t));g.forEach((e=>{let t;p?t=".document-container":(t=".album-item video, .album-item img, .preview video, .preview img, ",t+=this.bubbles[e].classList.contains("with-media-tail")?".bubble__media-container":".attachment video, .attachment img");const i=Array.from(this.bubbles[e].querySelectorAll(t)),s=new Set;if(p)i.forEach((e=>{m.push({element:e.querySelector(".document-ico"),mid:+e.dataset.mid,peerId:this.peerId})}));else{const t=!!this.bubbles[e].querySelector(".media-container-aspecter");i.forEach((i=>{if(t&&!(0,r.Z)(i,"media-container-aspecter"))return;const n=(0,r.Z)(i,"album-item"),a=n||i.parentElement;s.has(a)||(s.add(a),m.push({element:i,mid:n?+n.dataset.mid:e,peerId:this.peerId}))}))}})),m.sort(((e,t)=>e.mid-t.mid));const v=m.findIndex((e=>e.mid===l));return R.ZP&&this.log("open mediaViewer single with ids:",g,v,m),m[v]?void(new Rm).setSearchContext({threadId:this.chat.threadId,peerId:this.peerId,inputFilter:{_:p?"inputMessagesFilterDocument":"inputMessagesFilterPhotoVideo"},useSearch:"scheduled"!==this.chat.type&&!h,isScheduled:"scheduled"===this.chat.type}).openMedia(c,m[v].element,0,!0,m.slice(0,v),m.slice(v+1)):void this.log("no target for media viewer!",i)}if(-1===["IMG","DIV","SPAN"].indexOf(i.tagName)&&(i=(0,l.Z)(i,"DIV")),-1!==["DIV","SPAN"].indexOf(i.tagName)){if(i.classList.contains("goto-original")){const e=s.dataset.savedFrom,[t,i]=e.split("_");return void this.chat.appImManager.setInnerPeer({peerId:t.toPeerId(),lastMsgId:+i})}if(i.classList.contains("forward")){const e=+s.dataset.mid,t=yield this.managers.appMessagesManager.getMessageByPeer(this.peerId,e);return void new ja({[this.peerId]:yield this.managers.appMessagesManager.getMidsByMessage(t)})}let t=!1;try{t=!!(0,r.Z)(e.target,"reply")}catch(e){}if(t&&s.classList.contains("is-reply")){const e=+s.dataset.mid;this.replyFollowHistory.push(e);const t=yield this.chat.getMessage(e),i=t.reply_to.reply_to_peer_id?(0,es.Z)(t.reply_to.reply_to_peer_id):this.peerId,n=t.reply_to.reply_to_msg_id;this.chat.appImManager.setInnerPeer({peerId:i,lastMsgId:n,type:this.chat.type,threadId:this.chat.threadId})}}})),this.onScroll=(e,t,i)=>{var s,n;if(this.isHeavyAnimationInProgress){if(this.sliceViewportDebounced&&this.sliceViewportDebounced.clearTimeout(),this.scrolledDown&&!e)return}else this.chat.topbar.pinnedMessage&&this.chat.topbar.pinnedMessage.setCorrectIndexThrottled(this.scrollable.lastScrollDirection),this.sliceViewportDebounced&&this.sliceViewportDebounced(),this.setStickyDateManually();if(t&&t.distanceToEnd<300&&this.scrolledDown)return;const a=i?0:null!==(s=null==t?void 0:t.distanceToEnd)&&void 0!==s?s:this.scrollable.getDistanceToEnd();(0!==this.scrollable.lastScrollDirection&&a>0||t||i)&&(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+(null!==(n=null==t?void 0:t.duration)&&void 0!==n?n:0))),a<300&&(i||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.onDatePick=e=>{const t=this.peerId;this.managers.appMessagesManager.requestHistory(t,0,2,-1,e,this.chat.threadId).then((e=>{var i;(null===(i=null==e?void 0:e.messages)||void 0===i?void 0:i.length)?this.peerId===t&&this.chat.setMessageId(e.messages[0].mid):this.log.error("no history!")}))},this.log=this.chat.log,this.listenerSetter=new I.Z,this.constructBubbles(),this.bubbleGroups=new Gr(this.chat),this.preloader=new Ue({cancelable:!1}),this.lazyLoadQueue=new ye,this.lazyLoadQueue.queueId=++mc,this.listenerSetter.add(s.Z)("history_update",(({storageKey:e,sequential:t,message:i})=>cc(this,void 0,void 0,(function*(){if(this.chat.messagesStorageKey!==e||"scheduled"===this.chat.type)return;const{mid:n}=i,a=this.bubbles[n];if(!a)return;if(this.renderNewPromises.size&&(yield Promise.all(Array.from(this.renderNewPromises))),this.messagesQueuePromise&&(yield this.messagesQueuePromise),this.bubbles[n]!==a)return;const o=this.bubbleGroups.getItemByBubble(a);if(!o)return;if(o.mid===n)return;if(t){const e=o.group,r=this.bubbleGroups.createItem(a,i),l=this.bubbleGroups.itemsArr.slice();(0,T.Z)(l,o);const c=this.bubbleGroups.findGroupSiblingByItem(r,l);if(e===(null==c?void 0:c.group)||e===this.bubbleGroups.getLastGroup()&&1===e.items.length&&r.dateTimestamp===o.dateTimestamp||this.peerId===s.Z.myId&&t&&r.dateTimestamp===o.dateTimestamp)return void this.bubbleGroups.changeBubbleMid(a,n)}this.bubbleGroups.removeAndUnmountBubble(a);const{groups:r}=this.groupBubbles([{bubble:a,message:i}]);this.bubbleGroups.mountUnmountGroups(r),this.scrollingToBubble&&this.scrollToEnd()})))),this.listenerSetter.add(s.Z)("dialog_flush",(({peerId:e})=>{this.peerId===e&&this.deleteMessagesByIds(Object.keys(this.bubbles).map((e=>+e)))})),this.listenerSetter.add(s.Z)("message_sent",(e=>cc(this,void 0,void 0,(function*(){const{storageKey:t,tempId:i,tempMessage:n,mid:a,message:o}=e;if(this.chat.messagesStorageKey!==t)return;const l=this.bubbles,c=l[i];if(c){const e=l[i];l[a]=e,e.dataset.mid=""+a,delete l[i],(0,Be.T2)((()=>{const t=+e.dataset.mid;l[t]===e&&e.classList.contains("is-outgoing")&&(e.classList.remove("is-sending","is-outgoing"),e.classList.add(this.peerId===s.Z.myId&&"scheduled"!==this.chat.type||!this.unreadOut.has(t)?"is-read":"is-sent"))}))}if(this.unreadOut.has(i)&&(this.unreadOut.delete(i),this.unreadOut.add(a)),"scheduled"===this.chat.type&&(Date.now()/1e3|0)>=n.date-10&&this.deleteMessagesByIds([a]),!c)return;let d,h;const u=o.grouped_id;if(u){d=yield this.managers.appMessagesManager.getMessagesByAlbum(u);const e=d.map((({mid:e})=>e));if(!e.length||fc(e)!==a||l[a]!==c)return;if(l[a]!==c)return;h=Array.from(c.querySelectorAll(".grouped-item")).map((e=>+e.dataset.mid))}else d=[o],h=[i];const p=Array.from(c.querySelectorAll("reactions-element"));p.length&&p.forEach((e=>{e.changeMessage(o)})),d.forEach(((e,t)=>{var i,s,a,o,l;if(!e)return;const d=h[t],p=e.mid,m=c.querySelector(`.document-container[data-mid="${p}"]`)||c;if("message"!==e._)return;if(e.replies){const t=c.querySelector("replies-element");t&&(t.message=e,t.init())}const g=null!==(i=e.media)&&void 0!==i?i:{},v=g.document,f=g.poll,y=g.webpage;if(v){const t=m.querySelector(`.document-container[data-mid="${d}"] .document`);if(t){const i=(0,r.Z)(t,"document-container");!(null===(o=null===(a=null===(s=n.media)||void 0===s?void 0:s.document)||void 0===a?void 0:a.thumbs)||void 0===o?void 0:o.length)&&(null===(l=v.thumbs)||void 0===l?void 0:l.length)&&(0,He.e9)().then((()=>cc(this,void 0,void 0,(function*(){const i=t.querySelector(".time"),s=yield ti({message:e});t.replaceWith(s),i&&s.querySelector(".document").append(i)})))),i&&(i.dataset.mid=""+p)}const i=m.querySelector(`audio-element[data-mid="${d}"], .document[data-doc-id="${d}"], .media-round[data-mid="${d}"]`);i&&(i instanceof Wt||i.classList.contains("media-round")?(i.dataset.mid=""+e.mid,delete i.dataset.isOutgoing,i.message=e,i.onLoad(!0)):(i.dataset.docId=""+v.id,i.doc=v))}else if(f){const t=m.querySelector("poll-element");t&&(t.message=e,t.setAttribute("poll-id",""+f.id),t.setAttribute("message-id",""+p))}else y&&!m.querySelector(".web")&&(0,He.e9)().then((()=>{this.safeRenderMessage(e,!0,m),this.scrollToBubbleIfLast(m)}));if(u){const e=m.querySelector(`.grouped-item[data-mid="${d}"]`)||m;e&&(e.dataset.mid=""+p)}}))})))),this.listenerSetter.add(s.Z)("message_edit",(({storageKey:e,message:t})=>cc(this,void 0,void 0,(function*(){if(e!==this.chat.messagesStorageKey)return;const i=this.bubbles[t.mid];i&&(yield(0,He.e9)(),this.bubbles[t.mid]===i&&this.safeRenderMessage(t,!0,i))})))),this.listenerSetter.add(s.Z)("album_edit",(({peerId:e,messages:t,deletedMids:i})=>{if(e!==this.peerId)return;const s=t.map((({mid:e})=>e)),n=fc(s.concat(Array.from(i))),a=this.bubbles[n];if(!a)return;const o=fc(s),r=t.find((e=>e.mid===o));this.safeRenderMessage(r,!0,a)})),this.listenerSetter.add(s.Z)("peer_title_edit",(e=>cc(this,void 0,void 0,(function*(){var t;if(e.isUser()){const i=this.getMiddleware(),s=yield this.managers.appUsersManager.getUser(e.toUserId());if(!i())return;const n=null===(t=null==s?void 0:s.pFlags)||void 0===t?void 0:t.premium,a=this.bubbleGroups.groups.filter((t=>{var i;return(null===(i=t.avatar)||void 0===i?void 0:i.peerId)===e}));a.forEach((e=>{e.avatar.classList.toggle("is-premium",n),e.avatar.classList.toggle("tgico-star",n)}))}})))),"scheduled"!==this.chat.type&&this.listenerSetter.add(s.Z)("messages_reactions",(e=>cc(this,void 0,void 0,(function*(){let t;const i=e.map((({message:e,changedResults:t})=>cc(this,void 0,void 0,(function*(){if(this.peerId!==e.peerId)return;const i=yield this.getMountedBubble(e.mid,e);return i?{bubble:i.bubble,message:e,changedResults:t}:void 0}))));(yield Promise.all(i)).filter(Boolean).forEach((({bubble:e,message:i,changedResults:s})=>{t||(t=this.createScrollSaver(!1),t.save());const n=i.peerId+"_"+i.mid,a=$r.get(n);if(a)for(const e of a)e.update(i,s);else{if(!i.reactions||!i.reactions.results.length)return;this.appendReactionsElementToBubble(e,i,i,s)}})),t&&t.restore()})))),this.listenerSetter.add(s.Z)("messages_downloaded",(({peerId:e,mids:t})=>cc(this,void 0,void 0,(function*(){const i=this.getMiddleware();yield(0,He.e9)(),i()&&t.forEach((t=>{this.needUpdate;const i=[];(0,Mn.Z)(this.needUpdate,((s,n)=>{s.replyMid===t&&s.replyToPeerId===e&&(this.needUpdate.splice(n,1)[0],i.push(s))})),i.forEach((({mid:e,replyMid:t,replyToPeerId:i})=>cc(this,void 0,void 0,(function*(){const t=this.bubbles[e];if(!t)return;const i=yield this.chat.getMessage(e);Jr.setReply({chat:this.chat,bubble:t,message:i})}))))}))})))),xn({listenTo:this.scrollable.container,listenerSetter:this.listenerSetter,selector:".attachment.media-sticker-wrapper"}),(0,n.fc)(this.scrollable.container,this.onBubblesClick,{listenerSetter:this.listenerSetter}),this.listenerSetter.add(this.scrollable.container)("mousedown",(e=>{if(0!==e.button)return;const t=(0,l.Z)(e.target,"CODE");return t?((0,a.Z)(e),Oi(t.textContent),void Li({langPackKey:"TextCopied"})):void 0})),this.stickyIntersector=new an(this.scrollable.container,((e,t)=>{for(const i in this.dateMessages){const s=this.dateMessages[i];if(s.container===t){const t=s.div;t.classList.toggle("is-sticky",e),e&&(this.previousStickyDate=t);break}}this.previousStickyDate})),Je.IS_SAFARI||(this.sliceViewportDebounced=(0,Ki.Z)(this.sliceViewport.bind(this),3e3,!1,!0)),(0,He.ZP)((()=>{this.isHeavyAnimationInProgress=!0,this.lazyLoadQueue.lock(),i=this.getMiddleware()}),(()=>{this.isHeavyAnimationInProgress=!1,i&&i()&&(this.lazyLoadQueue.unlock(),this.lazyLoadQueue.refresh()),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"),this.setScroll(),e.append(this.scrollable.container)}attachContainerListeners(){const e=this.container;if(this.chat.contextMenu.attachTo(e),this.chat.selection.attachListeners(e,new I.Z),R.ZP&&this.listenerSetter.add(e)("dblclick",(e=>cc(this,void 0,void 0,(function*(){const t=(0,r.Z)(e.target,"grouped-item")||(0,r.Z)(e.target,"bubble");if(t){const e=+t.dataset.mid;this.log("debug message:",yield this.chat.getMessage(e)),this.highlightBubble(t)}})))),"pinned"!==this.chat.type&&"scheduled"!==this.chat.type)if(Je.IS_MOBILE){if(gi.Z){const t="is-gesturing-reply",i=64,s=.75*i;let n,a,o=!1;Wa({element:e,verifyTouchTarget:e=>cc(this,void 0,void 0,(function*(){return!(this.chat.selection.isSelecting||!(yield this.chat.canSend())||(n=(0,r.Z)(e.target,"bubble"),n&&(Re(n,t,!0,250),n.offsetLeft,a?(a.classList.remove("is-visible"),a.style.opacity=""):(a=document.createElement("span"),a.classList.add("tgico-reply_filled","bubble-gesture-reply-icon")),n.append(a)),!n))})),onSwipe:(e,t)=>{o=e>=s,o&&!a.classList.contains("is-visible")&&a.classList.add("is-visible"),a.style.opacity=""+Math.min(1,e/s);const r=-Math.max(0,Math.min(i,e));n.style.transform=`translateX(${r}px)`,Zi()},onReset:()=>{const e=n;Re(e,t,!1,250,(()=>{a.parentElement===e&&(a.classList.remove("is-visible"),a.remove())})),(0,Be.T2)((()=>{if(e.style.transform="",o){const{mid:t}=e.dataset;this.chat.input.initMessageReply(+t),o=!1}}))},listenerOptions:{capture:!0}})}}else this.listenerSetter.add(e)("dblclick",(e=>cc(this,void 0,void 0,(function*(){if(this.chat.selection.isSelecting||!(yield this.chat.canSend()))return;const t=e.target,i=t.classList.contains("bubble")?t:t.classList.contains("document-selection")?t.parentElement:null;if(i&&!i.classList.contains("bubble-first")){const e=+i.dataset.mid;if((yield this.chat.getMessage(e)).pFlags.is_outgoing)return;this.chat.input.initMessageReply(e)}}))))}constructPeerHelpers(){this.listenerSetter.add(s.Z)("history_append",(({storageKey:e,message:t})=>cc(this,void 0,void 0,(function*(){if(e===this.chat.messagesStorageKey&&(this.scrollable.loadedAll.bottom?this.renderNewMessage(t,!0):this.chat.setMessageId(),s.Z.settings.animationsEnabled)){const e=this.chat.gradientRenderer;e&&e.toNextPosition()}})))),this.listenerSetter.add(s.Z)("history_multiappend",(e=>{this.peerId===e.peerId&&this.renderNewMessage(e)})),this.listenerSetter.add(s.Z)("history_delete",(({peerId:e,msgs:t})=>{e===this.peerId&&this.deleteMessagesByIds(Array.from(t))})),this.listenerSetter.add(s.Z)("dialog_unread",(({peerId:e})=>{e===this.peerId&&(this.chat.input.setUnreadCount(),(0,He.e9)().then((()=>{this.updateUnreadByDialog()})))})),this.listenerSetter.add(s.Z)("dialogs_multiupdate",(e=>{e.has(this.peerId)&&this.chat.input.setUnreadCount()})),this.listenerSetter.add(s.Z)("dialog_notify_settings",(e=>{this.peerId===e.peerId&&this.chat.input.setUnreadCount()})),this.listenerSetter.add(s.Z)("chat_update",(e=>cc(this,void 0,void 0,(function*(){this.peerId===e.toPeerId(!0)&&this.chatInner.classList.contains("has-rights")!==(yield this.chat.canSend())&&(yield Promise.all([this.finishPeerChange(),this.chat.input.finishPeerChange()])).forEach((e=>e()))})))),this.listenerSetter.add(s.Z)("settings_updated",(({key:e})=>cc(this,void 0,void 0,(function*(){if("settings.emoji.big"===e){const e=this.getMiddleware(),t=(0,no.Z)(this.bubbles,"desc").map((e=>cc(this,void 0,void 0,(function*(){const t=this.bubbles[e];if(t.classList.contains("can-have-big-emoji"))return{bubble:t,message:yield this.chat.getMessage(e)}})))),i=yield Promise.all(t);if(!e())return;i.filter(Boolean).forEach((({bubble:e,message:t})=>{this.bubbles[t.mid]===e&&this.safeRenderMessage(t,!0,e)}))}})))),this.listenerSetter.add(s.Z)("messages_views",(e=>{(0,Be.T2)((()=>{let t;for(const{peerId:i,views:s,mid:n}of e){if(this.peerId!==i)continue;const e=this.bubbles[n];if(!e)continue;const a=Array.from(e.querySelectorAll(".post-views"));if(!a.length)continue;const o=Zr(s,1);let r=!1;a.forEach((e=>{(r||e.textContent!==o)&&(t||(t=this.createScrollSaver(!0),t.save()),r=!0,e.textContent=o)}))}t&&t.restore()}))})),this.observer=new rl({root:this.scrollable.container}),this.listenerSetter.add(this.chat.appImManager)("chat_changing",(({to:e})=>{const t=e!==this.chat,i=()=>{this.observer.toggleObservingNew(t)};t?i():setTimeout((()=>{i()}),400)})),this.sendViewCountersDebounced=(0,Ki.Z)((()=>{const e=[...this.viewsMids];this.viewsMids.clear(),this.managers.appMessagesManager.incrementMessageViews(this.peerId,e)}),1e3,!1,!0)}get peerId(){return this.chat.peerId}createScrollSaver(e=!0){return new ol(this.scrollable,".bubble:not(.is-date)",e)}createResizeObserver(){if(!("ResizeObserver"in window)||this.resizeObserver)return;const e=this.scrollable.container;let t=0,i=!1,s=!1,n=0,a=0,o=0;const r=()=>{const r=e.offsetHeight,l=this.scrollable.isScrolledDown;r===t||s&&l||(a+=t-r),a&&this.scrollable.setScrollTopSilently(this.scrollable.scrollTop+Math.round(a)),t=r,n=0,o=0,a=0,i=!1,s=!1},l=e=>{o&&window.cancelAnimationFrame(o),o=window.requestAnimationFrame(e?r:()=>{o=window.requestAnimationFrame(r)})},c=this.resizeObserver=new ResizeObserver((e=>{if(s)return void l(!1);const o=e[0].contentRect.height;if(!t)return void(t=o);const r=t-o;let c=r+a;const d=c%1;if(c-=d,!i&&(i=!0,r<0&&this.scrollable.isScrolledDown))return a=-r,s=!0,void l(!1);if(n+=c,c){const e=this.scrollable.scrollTop+c;this.scrollable.setScrollTopSilently(e)}l(!1),a=d,t=o}));c.observe(e)}destroyResizeObserver(){const e=this.resizeObserver;e&&(e.disconnect(),this.resizeObserver=void 0)}setReactionsHoverListeners(){this.listenerSetter.add(Ii)("toggle",this.unhoverPrevious),this.listenerSetter.add(Un.Z)("change",this.unhoverPrevious),this.listenerSetter.add(this.chat.selection)("toggle",this.unhoverPrevious),this.listenerSetter.add(this.container)("mousemove",this.onBubblesMouseMove)}setHoverVisible(e,t){Re(e,"is-visible",t,200,t?void 0:()=>{e.remove()},2)}setStickyDateManually(){}getRenderedLength(){return Object.keys(this.bubbles).length-this.skippedMids.size}onUnreadedInViewport(e,t){this.unreadedSeen.add(t),this.observer.unobserve(e,this.unreadedObserverCallback),this.unreaded.delete(e),this.readUnreaded()}readUnreaded(){if(this.readPromise)return;const e=this.getMiddleware();this.readPromise=dl.Z.getFocusPromise().then((()=>cc(this,void 0,void 0,(function*(){if(!e())return;let t=Math.max(...Array.from(this.unreadedSeen));if(this.scrollable.loadedAll.bottom){const e=Math.max(...Object.keys(this.bubbles).map((e=>+e)));t>=e&&(t=Math.max((yield this.chat.getHistoryMaxId())||0,t))}this.unreaded.forEach(((e,i)=>{e<=t&&this.onUnreadedInViewport(i,e)}));const i=[];for(const e of this.unreadedSeen)ll(yield this.chat.getMessage(e))&&i.push(e);return this.managers.appMessagesManager.readMessages(this.peerId,i),this.unreadedSeen.clear(),R.ZP&&this.log("will readHistory by maxId:",t),this.managers.appMessagesManager.readHistory(this.peerId,t,this.chat.threadId).catch((e=>{this.log.error("readHistory err:",e),this.managers.appMessagesManager.readHistory(this.peerId,t,this.chat.threadId)})).finally((()=>{e()&&(this.readPromise=void 0,this.unreadedSeen.size&&this.readUnreaded())}))}))))}constructPinnedHelpers(){this.listenerSetter.add(s.Z)("peer_pinned_messages",(e=>{const{peerId:t,mids:i,pinned:s}=e;t===this.peerId&&i&&(s||this.deleteMessagesByIds(i))}))}constructScheduledHelpers(){const e=()=>cc(this,void 0,void 0,(function*(){this.chat.topbar.setTitle((yield this.managers.appMessagesManager.getScheduledMessagesStorage(this.peerId)).size)}));this.listenerSetter.add(s.Z)("scheduled_new",(t=>{t.peerId===this.peerId&&(this.renderNewMessage(t),e())})),this.listenerSetter.add(s.Z)("scheduled_delete",(({peerId:t,mids:i})=>{t===this.peerId&&(this.deleteMessagesByIds(i),e())}))}onGoDownClick(){return cc(this,void 0,void 0,(function*(){if(!this.replyFollowHistory.length)return void this.chat.setMessageId();const e=this.getMiddleware(),t=this.replyFollowHistory.slice(),i=yield Promise.all(t.map((e=>this.chat.getMessage(e))));if(!e())return;t.forEach(((e,t)=>{const s=i[t],n=this.bubbles[e];let a=!0;if(n){const e=n.getBoundingClientRect();a=as.height/2>e.top}else s&&(a=!1);a&&this.replyFollowHistory.splice(this.replyFollowHistory.indexOf(e),1)})),this.replyFollowHistory.sort(((e,t)=>t-e));const s=this.replyFollowHistory.pop();this.chat.setMessageId(s)}))}getBubbleByPoint(e){let t=el(this.scrollable.container,e,"center");return t&&(t=(0,r.Z)(t,"bubble")),t}getGroupedBubble(e){return cc(this,void 0,void 0,(function*(){const t=yield this.managers.appMessagesManager.getMidsByAlbum(e);for(const e of t)if(this.bubbles[e]&&!this.skippedMids.has(e))return{bubble:this.bubbles[e],mid:e}}))}getBubbleGroupedItems(e){return Array.from(e.querySelectorAll(".grouped-item"))}getMountedBubble(e,t){return cc(this,void 0,void 0,(function*(){if(void 0===t&&(t=yield this.chat.getMessage(e)),!t)return;const i=t.grouped_id;if(i){const t=yield this.getGroupedBubble(i);if(t)return t.bubble=t.bubble.querySelector(`.document-container[data-mid="${e}"]`)||t.bubble,t}const s=this.bubbles[e];return s?{bubble:s,mid:e}:void 0}))}findNextMountedBubbleByMsgId(e,t){const i=(0,no.Z)(this.bubbles,t?"desc":"asc");let s;s=t?t=>t<e:t=>e<t;const n=i.find((e=>{var t;return!!s(e)&&!!(null===(t=this.bubbles[e])||void 0===t?void 0:t.parentElement)}));return this.bubbles[n]}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 i=Object.keys(this.bubbles).map((e=>+e)).filter((e=>e>0&&!this.skippedMids.has(e))).sort(((e,t)=>e-t));i.length||i.push(0),e?(R.ZP&&this.log("Will load more (up) history by id:",i[0],"maxId:",i[i.length-1],t),this.getHistory1(i[0],!0,void 0,void 0,t)):(R.ZP&&this.log("Will load more (down) history by id:",i[i.length-1],t),this.getHistory1(i[i.length-1],!1,!0,void 0,t))}setScroll(){this.scrollable&&this.destroyScrollable(),this.scrollable=new m.ZP(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),gi.Z}updateUnreadByDialog(){return cc(this,void 0,void 0,(function*(){const e=yield this.chat.getHistoryStorage(),t=this.peerId===s.Z.myId?e.readMaxId:e.readOutboxMaxId;for(const e of this.unreadOut)if(e>0&&e<=t){const t=this.bubbles[e];if(t){if(this.unreadOut.delete(e),t.classList.contains("is-outgoing"))continue;t.classList.remove("is-sent","is-sending","is-outgoing"),t.classList.add("is-read")}}}))}deleteMessagesByIds(e,t=!0,i){let s=!1;e.forEach((e=>{const t=this.bubbles[e];t&&(s=!0,delete this.bubbles[e],this.skippedMids.delete(e),this.firstUnreadBubble===t&&(this.firstUnreadBubble=null),this.bubbleGroups.removeAndUnmountBubble(t),this.observer&&(this.observer.unobserve(t,this.unreadedObserverCallback),this.unreaded.delete(t),this.observer.unobserve(t,this.viewsObserverCallback),this.viewsMids.delete(e),this.observer.unobserve(t,this.stickerEffectObserverCallback)),this.emptyPlaceholderBubble===t&&(this.emptyPlaceholderBubble=void 0))})),s&&(this.scrollable.ignoreNextScrollEvent(),t&&this.chat.selection.isSelecting&&this.chat.selection.deleteSelectedMids(this.peerId,e),p.Z.checkAnimations(!1,km),this.deleteEmptyDateGroups(),i||this.scrollable.onScroll())}setTopPadding(e=this.getMiddleware()){let t,i=!1;if(!this.isTopPaddingSet&&"scheduled"!==this.chat.type){const{clientHeight:e,scrollHeight:s}=this.scrollable.container;i=e===s,i&&(t=this.chatInner,t.style.paddingTop=e+"px",this.scrollable.setScrollTopSilently(s),this.isTopPaddingSet=!0)}return{isPaddingNeeded:i,unsetPadding:i?()=>{e()&&i&&(t.style.paddingTop="",this.isTopPaddingSet=!1)}:void 0}}renderNewMessage(e,t){const i=this._renderNewMessage(e,t);return this.renderNewPromises.add(i),i.catch(ft.Z).finally((()=>{this.renderNewPromises.delete(i)})),i}_renderNewMessage(e,t){return cc(this,void 0,void 0,(function*(){if(!this.scrollable.loadedAll.bottom){const t=this.chat.setPeerPromise;if(t){const i=this.getMiddleware();t.then((()=>cc(this,void 0,void 0,(function*(){if(!i())return;const t=yield this.chat.getMessage(e.mid);i()&&this.renderNewMessage(t)}))))}return}if(this.chat.threadId){const t=null==e?void 0:e.reply_to;if(!t||(t.reply_to_top_id||t.reply_to_msg_id)!==this.chat.threadId)return}if(this.bubbles[e.mid])return;t||(t=this.scrolledDown&&(!this.scrollingToBubble||this.scrollingToBubble===this.getLastBubble()||this.scrollingToBubble===this.chatInner));const i=this.getMiddleware(),{isPaddingNeeded:s,unsetPadding:n}=this.setTopPadding(i),a=this.performHistoryResult({history:[e]},!1);return t&&a.then((()=>{if(!i())return;let t;"scheduled"===this.chat.type&&(t=this.bubbles[e.mid]);const a=t?this.scrollToBubbleEnd(t):this.scrollToEnd();s&&a.then(n)})),a}))}getLastBubble(){var e;const t=this.bubbleGroups.getLastGroup();return null===(e=null==t?void 0:t.lastItem)||void 0===e?void 0:e.bubble}scrollToBubble(e,t,i,s){const n=(0,r.Z)(e,"bubble");let a;if(e.parentElement||this.log.error("element is not connected",n),n&&"end"!==t){const e=this.bubbleGroups.getItemByBubble(n);e.group.firstItem===e&&(0,Cn.Z)(e.group.container)===(this.stickyIntersector?gc:1)&&(a=e.group.container.parentElement)}const o=this.chat.input.messageInput&&this.chat.input.messageInput.classList.contains("is-changing-height")||this.chat.container.classList.contains("is-toggling-helper"),l=this.scrollable.scrollIntoViewNew({element:e,position:t,margin:4,forceDirection:i,forceDuration:s,axis:"y",getNormalSize:o?({rect:e})=>{let t=as.height;return t-=this.container.offsetTop,t-=d.Z.isMobile||as.height<570?58:78,t}:void 0,fallbackToElementStartWhenCentering:a,startCallback:e=>{this.onScroll(!0,e)}});return i===ts.f.Static&&(this.scrollable.lastScrollPosition=this.scrollable.scrollTop),l}scrollToEnd(){return this.scrollToBubbleEnd(this.chatInner)}scrollToBubbleEnd(e){return cc(this,void 0,void 0,(function*(){if(e){this.scrollingToBubble=e;const t=this.getMiddleware();if(yield this.scrollToBubble(e,"end",void 0,void 0),!t())return;this.scrollingToBubble=void 0}}))}scrollToBubbleIfLast(e){return cc(this,void 0,void 0,(function*(){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(1e3*e)){let i;const s=new Date;s.setHours(0,0,0,0);const n="scheduled"===this.chat.type;if(s.getTime()===t.getTime())i=(0,v.ag)(n?"Chat.Date.ScheduledForToday":"Date.Today");else if(n&&e===il)i=(0,v.ag)("MessageScheduledUntilOnline");else{const e={day:"numeric",month:"long"};t.getFullYear()!==s.getFullYear()&&(e.year="numeric"),i=new v.ZP.IntlDateElement({date:t,options:e}).element,n&&(i=(0,v.ag)("Chat.Date.ScheduledFor",[i]))}const a=document.createElement("div");a.className="bubble service is-date";const o=document.createElement("div");o.classList.add("bubble-content");const r=document.createElement("div");return r.classList.add("service-msg"),r.append(i),o.append(r),a.append(o),a}getDateForDateContainer(e){const t=new Date(1e3*e);return t.setHours(0,0,0),{date:t,dateTimestamp:t.getTime()}}getDateContainerByTimestamp(e){const{date:t,dateTimestamp:i}=this.getDateForDateContainer(e);if(!this.dateMessages[i]){const s=this.createDateBubble(e,t),n=this.createDateBubble(e,t);n.classList.add("is-fake");const a=document.createElement("section");a.className="bubbles-date-group",a.append(s,n),this.dateMessages[i]={div:s,container:a,firstTimestamp:t.getTime()};const o=(0,no.Z)(this.dateMessages,"asc"),r=o.length;let l,c=0;for(;c<o.length;++c){const e=o[c];if(l=this.dateMessages[e].container,i<e)break}c===r&&l&&(l=l.nextElementSibling),l?this.chatInner.insertBefore(a,l):this.chatInner.append(a),this.stickyIntersector&&this.stickyIntersector.observeStickyHeaderChanges(a),this.chatInner.parentElement&&this.container.classList.add("has-groups")}return this.dateMessages[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.bubbles={},this.setLoaded("top",!1,!1),this.setLoaded("bottom",!1,!1),(0,ht.Kx)(this.scrollable.container),(0,He.gp)(),void 0!==pc&&(pc=uc),this.skippedMids.clear(),this.dateMessages={},this.bubbleGroups.cleanup(),this.unreadOut.clear(),this.needUpdate.length=0,this.lazyLoadQueue.clear(),this.renderNewPromises.clear(),e&&(this.scrollable.container.textContent="",this.chatInner.textContent="",this.cleanupPlaceholders()),this.firstUnreadBubble=null,this.attachedUnreadBubble=!1,this.messagesQueue.length=0,this.messagesQueuePromise=null,this.getHistoryTopPromise=this.getHistoryBottomPromise=void 0,this.fetchNewPromise=void 0,this.getSponsoredMessagePromise=void 0,this.stickyIntersector&&this.stickyIntersector.disconnect(),this.observer&&(this.observer.disconnect(),this.unreaded.clear(),this.unreadedSeen.clear(),this.readPromise=void 0,this.viewsMids.clear()),this.middleware.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&&(e.remove(),this.emptyPlaceholderBubble===e&&(this.emptyPlaceholderBubble=void 0))}setPeer(e,t,i,s){var n;return cc(this,void 0,void 0,(function*(){const a=++this.setPeerTempId;if(!t)return this.cleanup(!0),this.preloader.detach(),null;const o=performance.now(),r=this.log.bindPrefix("setPeer");r.warn("start");const l=()=>this.setPeerTempId===a,c=hl(l,vc);e||(yield c(this.chat.onChangePeer(c)));const d=this.chat.type;("scheduled"===d||this.chat.isRestricted)&&(i=0);const h=yield c(this.chat.getHistoryStorage()),u="pinned"===d?yield c(this.managers.appMessagesManager.getPinnedMessagesMaxId(t)):null!==(n=h.maxId)&&void 0!==n?n:0,m=void 0!==i;let v,f,y,b=0;if(!m)if(e||(f=this.chat.appImManager.getChatSavedPosition(this.chat)),f);else if(u){b=yield c(this.managers.appMessagesManager.getReadMaxIdIfUnread(t,this.chat.threadId));const s=yield c(this.managers.appMessagesManager.getDialogOnly(t));if(!b||e||s&&1===s.unread_count)i=u;else{const e=h.history.findSliceOffset(b);e&&e.slice.isEnd(Xr.D.Bottom)&&(y=e.slice[e.offset-25]||e.slice[0]||b),v=!m,i=b}}const w=i!==u;if(void 0===s&&(yield c(this.chat.isStartButtonNeeded()))&&(s=le.gZ),e){const e=yield c(this.getMountedBubble(i));if(e)return m?(this.scrollToBubble(e.bubble,"center"),this.highlightBubble(e.bubble),this.chat.dispatchEvent("setPeer",i,!1)):u&&!w&&(this.scrollToEnd(),this.chat.dispatchEvent("setPeer",i,!0)),void 0!==s&&this.chat.input.setStartParam(s),null}else this.peerId&&(this.lazyLoadQueue.queueId=++mc,this.managers.apiFileManager.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)),this.replyFollowHistory.length=0,this.passEntities={messageEntityBotCommand:(yield c(this.managers.appPeersManager.isAnyGroup(t)))||this.chat.isBot};R.ZP&&r("setPeer peerId:",t,h,i,u);const S=null!=y?y:w||"scheduled"===d||this.chat.isRestricted?0:u;let C=0;if(e){const e=this.getBubbleByPoint("bottom");e&&(C=+e.dataset.mid),C<=0&&(C=Math.max(...Object.keys(this.bubbles).map((e=>+e))))}else this.isFirstLoad=!0,this.destroyResizeObserver();const L=this.chatInner,I=this.emptyPlaceholderBubble;this.cleanup();const M=this.chatInner=document.createElement("div");e?(M.className=L.className,M.classList.remove("disable-hover","is-scrolling")):M.classList.add("bubbles-inner"),this.lazyLoadQueue.lock();const E=e||u&&w||m,P=C>0&&(!i||C<i||i<0),k=!P&&e,T=!k&&P;let x;this.willScrollOnLoad=k||T,this.setPeerOptions={lastMsgId:i,topMessage:u},x=f?{promise:(0,He.e9)().then((()=>this.performHistoryResult({history:f.mids},!0))),cached:!0,waitPromise:Promise.resolve()}:yield c(this.getHistory1(i,!0,w,S)),this.setPeerCached=x.cached,r.warn("got history");const{promise:_,cached:A}=x;A||e||(yield c(this.chat.finishPeerChange(m,w,i,s)),this.scrollable.container.textContent="",this.preloader.attach(this.container)),p.Z.lockGroup(km);const Z=c(_).then((()=>cc(this,void 0,void 0,(function*(){r.warn("promise fulfilled");const n=E?yield c(i?this.getMountedBubble(i):{bubble:this.getLastBubble()}):void 0;A&&!e&&(r.warn("finishing peer change"),yield c(this.chat.finishPeerChange(m,w,i,s)),r.warn("finished peer change")),this.preloader.detach(),this.resolveLadderAnimation&&(this.resolveLadderAnimation(),this.resolveLadderAnimation=void 0),this.setPeerCached=void 0;const a=this.scrollable;if(a.lastScrollDirection=0,a.lastScrollPosition=0,(0,g.Z)(a.container,M),I&&this.cleanupPlaceholders(I),this.attachPlaceholderOnRender&&this.attachPlaceholderOnRender(),!m&&"chat"===this.chat.type&&this.chat.topbar.pinnedMessage&&this.chat.topbar.pinnedMessage.setCorrectIndex(0),this.container.classList.toggle("has-groups",!!Object.keys(this.dateMessages).length),r.warn("mounted chat",this.chatInner===M,this.chatInner.parentElement,performance.now()-o),p.Z.unlockGroup(km),p.Z.checkAnimations(!1,km),this.lazyLoadQueue.unlock(),f)a.setScrollTopSilently(f.top);else if(E){let t;if(k)a.setScrollTopSilently(99999);else if(T){const e=this.setTopPadding();e.isPaddingNeeded&&(t=e.unsetPadding),a.setScrollTopSilently(0)}let s,o=v&&this.firstUnreadBubble||(null==n?void 0:n.bubble);if((null==o?void 0:o.parentElement)||(o=this.findNextMountedBubbleByMsgId(i,!1)||this.findNextMountedBubbleByMsgId(i,!0)),o){const t=this.getLastBubble(),i=v?"start":w||m||t!==o?"center":"end";s="end"===i&&t===o&&e?this.scrollToEnd():this.scrollToBubble(o,i,e?void 0:ts.f.Static),!v&&m&&this.highlightBubble(o)}t&&(s||Promise.resolve()).then((()=>{t()}))}else a.setScrollTopSilently(99999);this.onRenderScrollSet(),this.onScroll();const l=Promise.all([Z,(0,He.e9)()]);if(l.then((()=>{a.checkForTriggers()})),this.chat.dispatchEvent("setPeer",i,!w),Promise.all([this.setFetchReactionsInterval(l),this.setFetchHistoryInterval({afterSetPromise:l,lastMsgId:i,samePeer:e,savedPosition:f,topMessage:u})]).then((()=>{r("scrolledAllDown:",a.loadedAll.bottom),a.loadedAll.bottom&&u&&!this.unreaded.size&&this.onScrolledAllDown()})),"chat"===d){const e=yield c(this.managers.appMessagesManager.getDialogOnly(t));(null==e?void 0:e.pFlags.unread_mark)&&this.managers.appMessagesManager.markDialogUnread(t,!0)}})))).catch((e=>{throw r.error("getHistory promise error:",e),l()||this.preloader.detach(),e}));return{cached:A,promise:Z}}))}setFetchReactionsInterval(e){return cc(this,void 0,void 0,(function*(){const t=this.getMiddleware();if(this.chat.isChannel){const i=()=>cc(this,void 0,void 0,(function*(){if(!t())return;const e=[];for(const t in this.bubbles){let i=yield this.chat.getMessage(+t);"message"===(null==i?void 0:i._)&&(i=yield this.managers.appMessagesManager.getGroupsFirstMessage(i),e.push(i.mid))}(e.length?this.managers.appReactionsManager.getMessagesReactions(this.peerId,e):Promise.resolve()).then((()=>{setTimeout(i,1e4)}))}));Promise.all([e,(0,He.e9)(),(0,on.Z)(500)]).then((()=>{i()}))}}))}setFetchHistoryInterval({lastMsgId:e,topMessage:t,afterSetPromise:i,savedPosition:s,samePeer:n}){return cc(this,void 0,void 0,(function*(){const e=this.getMiddleware(),t=this.peerId,a=yield this.managers.appMessagesManager.isFetchIntervalNeeded(t);if(!s&&!a)return;if(yield i,!e())return;if(this.setLoaded("bottom",!1),this.scrollable.checkForTriggers(),!a)return;const o=()=>{this.fetchNewPromise=new Promise((i=>cc(this,void 0,void 0,(function*(){e()&&(yield this.managers.appMessagesManager.isFetchIntervalNeeded(t))?this.managers.appMessagesManager.getNewHistory(t,this.chat.threadId).then((t=>{if(!e()||!t)return void i();const{isBottomEnd:s}=t;this.scrollable.loadedAll.bottom&&this.scrollable.loadedAll.bottom!==s&&(this.setLoaded("bottom",s),this.onScroll()),setTimeout(o,3e4),i()})):i()})))).finally((()=>{this.fetchNewPromise=void 0}))};n?setTimeout(o,3e4):o()}))}onScrolledAllDown(){return cc(this,void 0,void 0,(function*(){if("chat"===this.chat.type||"discussion"===this.chat.type){const e=yield this.chat.getHistoryMaxId();this.managers.appMessagesManager.readHistory(this.peerId,e,this.chat.threadId,!0)}}))}finishPeerChange(){return cc(this,void 0,void 0,(function*(){const[e,t,i]=yield Promise.all([this.chat.isChannel,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.classList.toggle("is-chat",i),this.chatInner.classList.toggle("is-channel",e),this.createResizeObserver()}}))}renderMessagesQueue(e){return this.messagesQueue.push(e),this.setMessagesQueuePromise()}setMessagesQueuePromise(){if(!this.messagesQueue.length)return Promise.resolve();if(this.messagesQueuePromise)return this.messagesQueuePromise;const e=this.getMiddleware(),t=this.log.bindPrefix("queue"),i=hl(e,vc),s=()=>cc(this,void 0,void 0,(function*(){var e;t("start");const n=this.messagesQueue.slice();this.messagesQueue.length=0;const a=n.map((e=>{const i=performance.now();return e.then((e=>{t("render message time",performance.now()-i,e)})),e}));let o=yield i(Promise.all(a));const r=e=>e.filter((e=>e&&this.bubbles[e.bubble.dataset.mid]===e.bubble));o=r(o),t("messages rendered");const l=null===(e=o[0])||void 0===e?void 0:e.reverse,{groups:c,avatarPromises:d}=this.groupBubbles(o.filter((e=>e.updatePosition))),h=o.reduce(((e,i)=>{const s=performance.now(),n=i.promises.slice(),a=n.map((e=>cc(this,void 0,void 0,(function*(){return yield e,performance.now()-s}))));return Promise.all(a).then((e=>{t.groupCollapsed("media message time",performance.now()-s,i,e),e.forEach(((e,i)=>{t("media message time",e,i,n[i])})),t.groupEnd()})),e.push(...i.promises),e}),[]);h.push(...d),t("media promises to call",h,o,this.isHeavyAnimationInProgress),yield i(Promise.all([...h,this.setUnreadDelimiter()])),yield i((0,Be.AD)()),t("media promises end"),o=r(o);const{restoreScroll:u,scrollSaver:p}=this.prepareToSaveScroll(l);this.messagesQueueOnRenderAdditional&&this.messagesQueueOnRenderAdditional(),this.ejectBubbles();for(const[e,t]of this.bubblesToReplace){if(p&&p.replaceSaved(t,e),!o.find((t=>t.bubble===e)))continue;const i=this.bubbleGroups.getItemByBubble(e);i.mounted=!1,c.includes(i.group)||c.push(i.group),this.bubblesToReplace.delete(e)}if(this.chat.selection.isSelecting&&o.forEach((({bubble:e})=>{this.chat.selection.toggleElementCheckbox(e,!0)})),o.forEach((({message:e,bubble:t,updatePosition:i})=>{e.pFlags.local&&i&&this.chatInner[e.pFlags.sponsored?"append":"prepend"](t)})),this.bubbleGroups.mountUnmountGroups(c),this.updatePlaceholderPosition&&this.updatePlaceholderPosition(),u&&u(),this.messagesQueue.length)return t("have new messages to render"),s();t("end")}));t("setting pause");const n=this.messagesQueuePromise=i((0,on.Z)(0)).then(s).finally((()=>{this.messagesQueuePromise===n&&(this.messagesQueuePromise=null)}));return n}ejectBubbles(){for(const e of this.bubblesToEject)e.remove();this.bubblesToEject.clear()}groupBubbles(e){let t;"scheduled"===this.chat.type&&(t=new Set,e.forEach((({bubble:e,message:i})=>{const s=this.bubbleGroups.getItemByBubble(e),n=null==s?void 0:s.group;n&&s.message.date!==i.date&&(this.bubbleGroups.removeItem(s),t.add(n))}))),e.forEach((({bubble:e,message:t})=>{this.bubbleGroups.prepareForGrouping(e,t)}));const i=this.bubbleGroups.groupUngrouped(),s=Array.from(i).map((e=>{if(e.avatar)return;const t=e.firstItem;return t&&this.chat.isAvatarNeeded(t.message)?e.createAvatar(t.message):void 0})).filter(Boolean);if(t)for(const e of t)i.add(e);return{groups:[...i],avatarPromises:s}}getMiddleware(e){return this.middleware.get(e)}safeRenderMessage(e,t,i,s=!0,n){return cc(this,void 0,void 0,(function*(){if(!e||this.renderingMessages.has(e.mid)||this.bubbles[e.mid]&&!i)return;const a=this.getMiddleware();let o;try{this.renderingMessages.add(e.mid);const r=document.createElement("div");r.dataset.mid=""+e.mid,r.dataset.peerId=""+e.peerId,r.dataset.timestamp=""+e.date,i&&(this.skippedMids.delete(e.mid),this.bubblesToEject.add(i),this.bubblesToReplace.delete(i),this.bubblesToReplace.set(r,i),this.bubbleGroups.changeBubbleByBubble(i,r)),i=this.bubbles[e.mid]=r;let l=this.renderMessage(e,t,i);n&&(l=n(l,i));const c=l.then((e=>e&&a()?Object.assign(Object.assign({},e),{updatePosition:s}):void 0));if(this.renderMessagesQueue(c.catch((()=>{}))),o=yield c,!a())return;o||this.skippedMids.add(+e.mid)}catch(e){this.log.error("renderMessage error:",e)}return a()?(this.renderingMessages.delete(e.mid),o):void 0}))}renderMessage(e,t=!1,i){var o,l,h;return cc(this,void 0,void 0,(function*(){const u="message"===e._,p=u&&e.grouped_id;let m,g;const f=p?yield this.managers.appMessagesManager.getMessagesByAlbum(p):void 0,y="pinned"!==this.chat.type;if(p&&y){m=f.map((e=>e.mid));const t=fc(m);if(e.mid!==t)return}u&&(g=p?f[0]:e);const b=this.chat.isOurMessage(e),w=document.createElement("div");w.classList.add("message");const S=document.createElement("div");S.classList.add("bubble-content-wrapper");const C=document.createElement("div");C.classList.add("bubble-content"),i.classList.add("bubble"),S.append(C),i.append(S);const L=!b&&!e.pFlags.out&&(e.pFlags.unread||ll(e));L&&this.observer&&(this.observer.observe(i,this.unreadedObserverCallback),this.unreaded.set(i,e.mid));const I=[],M={bubble:i,promises:I,message:e,reverse:t};if(!("messageService"!==e._||e.action&&hc.has(e.action._))){const t=e.action;if(t){const e=t._;if(dc.has(e)||v.Hz.hasOwnProperty(e)&&!v.Hz[e])return}i.className="bubble service",C.innerHTML="";const s=document.createElement("div");if(s.classList.add("service-msg"),t){let i;if("messageActionChannelMigrateFrom"===t._){const e=new Ot;i=e.update({peerId:t.chat_id.toPeerId(!0)}),s.append((0,v.ag)("ChatMigration.From",[e.element]))}else if("messageActionChatMigrateTo"===t._){const e=new Ot;i=e.update({peerId:t.channel_id.toPeerId(!0)}),s.append((0,v.ag)("ChatMigration.To",[e.element]))}else s.append(yield _a(e))}return C.append(s),e.pFlags.is_single&&i.classList.add("is-group-last"),M}let E,P,k=u&&e.media;if(u)if((null==k?void 0:k.document)&&!["video","gif"].includes(k.document.type));else if(p&&y){const e=(0,ul.Z)(f);E=e.message,P=e.totalEntities}else"sticker"!==(null===(o=null==k?void 0:k.document)||void 0===o?void 0:o.type)&&(E=e.message,P=e.totalEntities);else"messageActionPhoneCall"===e.action._&&(k={_:"messageMediaCall",action:e.action});const T=(0,ii.Z)(E,{entities:P,passEntities:this.passEntities});let x=!0,_=!1,A=!0;if(P&&!k){const e=P.filter((e=>"messageEntityEmoji"===e._)),t=E.length;if(e.reduce(((e,t)=>e+t.length),0)===t&&e.length<=3&&P.length===e.length){if(s.Z.settings.emoji.big){const t=yield this.managers.appStickersManager.getAnimatedEmojiSticker(E);if(1===e.length&&!k&&t)k={_:"messageMediaDocument",document:t};else{const t=document.createElement("div");t.classList.add("attachment"),(0,c.Z)(t,T),i.classList.add("emoji-"+e.length+"x"),C.append(t)}i.classList.add("is-message-empty","emoji-big"),_=!0,x=!1,A=!1}i.classList.add("can-have-big-emoji")}}A&&(0,c.Z)(w,T);const Z=Jr.setTime({chatType:this.chat.type,message:e,reactionsMessage:g});if(w.append(Z),C.prepend(w),u&&e.views){if(i.classList.add("channel-post"),!(null===(l=e.fwd_from)||void 0===l?void 0:l.saved_from_msg_id)&&"pinned"!==this.chat.type){const e=document.createElement("div");e.classList.add("bubble-beside-button","forward","tgico-forward_filled"),C.prepend(e),i.classList.add("with-beside-button")}!e.pFlags.is_outgoing&&this.observer&&this.observer.observe(i,this.viewsObserverCallback)}const F=u&&e.reply_markup;if(F&&"replyInlineMarkup"===F._&&F.rows&&F.rows.length){const t=F.rows,s=document.createElement("div");s.classList.add("reply-markup"),t.forEach((t=>{const i=t.buttons;if(!i||!i.length)return;const o=document.createElement("div");o.classList.add("reply-markup-row"),i.forEach((t=>{let i,s=(0,ii.Z)(t.text,{noLinks:!0,noLinebreaks:!0});switch(t._){case"keyboardButtonUrl":i=ga((0,ii.Z)(" ",{entities:[{_:"messageEntityTextUrl",length:1,offset:0,url:t.url}]})).firstElementChild,i.classList.add("is-link");break;case"keyboardButtonSwitchInline":i=document.createElement("button"),i.classList.add("is-switch-inline"),(0,n.fc)(i,(i=>{(0,a.Z)(i);const s=e.viaBotId||e.fromId;let n;n=t.pFlags.same_peer?Promise.resolve(this.peerId):this.managers.appInlineBotsManager.checkSwitchReturn(s).then((e=>e||new Promise(((e,t)=>{const i=new ja({[this.peerId]:[]},(t=>{e(t)}),!0);i.addEventListener("close",(()=>{t()}))})))),n.then((e=>{const i=this.peerId===e?this.chat.threadId:void 0;this.chat.appImManager.setInnerPeer({peerId:e}),this.managers.appInlineBotsManager.switchInlineQuery(e,i,s,t.query)}))}));break;case"keyboardButtonBuy":i=document.createElement("button"),i.classList.add("is-buy"),"messageMediaInvoice"===(null==k?void 0:k._)&&k.receipt_msg_id&&(s=(0,v.ag)("Message.ReplyActionButtonShowReceipt"));break;default:i=document.createElement("button")}i.classList.add("reply-markup-button","rp","tgico"),"string"==typeof s?i.insertAdjacentHTML("beforeend",s):i.append(s),(0,we.Z)(i),o.append(i)})),s.append(o)})),(0,n.fc)(s,(i=>{let s=i.target;if(s.classList.contains("reply-markup-button")||(s=(0,r.Z)(s,"reply-markup-button")),!s||s.classList.contains("is-link")||s.classList.contains("is-switch-inline")||s.classList.contains("is-buy"))return;(0,a.Z)(i);const n=(0,Cn.Z)(s),o=t[(0,Cn.Z)(s.parentElement)];if(!o.buttons||!o.buttons[n])return void this.log.warn("no such button",o,n,e);const l=o.buttons[n];this.managers.appInlineBotsManager.callbackButtonClick(this.peerId,e.mid,l).then((e=>{"string"==typeof e.message&&e.message.length&&Ci((0,ii.Z)(e.message,{noLinks:!0,noLinebreaks:!0}))}))})),x=!1,i.classList.add("with-reply-markup"),S.append(s)}const D=e.pFlags.is_outgoing;if(b){(e.pFlags.unread||D)&&this.unreadOut.add(e.mid);let t="";t=D?"is-sending":e.pFlags.unread||e.pFlags.is_scheduled?"is-sent":"is-read",i.classList.add(t)}D&&i.classList.add("is-outgoing");const R=u&&(yield this.managers.appMessagesManager.getMessageWithCommentReplies(e)),B=!!R&&e.mid>0;B&&i.classList.add("with-replies");const N=u&&e.fwd_from,U=u&&e.fwdFromId,O=this.chat.isOutMessage(e);let H=C;const z=!(e.viaBotId||e.fromId!==s.Z.myId&&e.pFlags.out);if(k){let t=document.createElement("div");t.classList.add("attachment"),E||i.classList.add("is-message-empty");let n=!1;switch(k._){case"messageMediaPhoto":{const s=k.photo;if(E||(x=!1),z&&i.classList.add("hide-name"),i.classList.add("photo"),y&&p&&1!==m.length){i.classList.add("is-album","is-grouped"),Qt({messages:f,attachmentDiv:t,middleware:this.getMiddleware(),isOut:b,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:I,autoDownload:this.chat.autoDownload});break}const n=!Je.IS_ANDROID&&x&&!B&&!1;n&&i.classList.add("with-media-tail"),dt({photo:s,message:e,container:t,withTail:n,isOut:O,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:I,autoDownloadSize:this.chat.autoDownload.photo});break}case"messageMediaWebPage":{n=!0;const t=k.webpage;if("webPage"!==t._)break;i.classList.add("webpage");const s=document.createElement("div");s.classList.add("web");const a=document.createElement("div");let o,r;a.classList.add("quote");const l=t.photo;(l||t.document)&&(o=document.createElement("div"),o.classList.add("preview-resizer"),r=document.createElement("div"),r.classList.add("preview"),o.append(r));const h=document.createElement("div");h.classList.add("quote-text");const u=t.document;if(u)if("gif"===u.type||"video"===u.type||"round"===u.type){const t="round"===u.type?d.Z.active.round:d.Z.active.webpage;"round"===u.type?(i.classList.add("round"),r.classList.add("is-round")):i.classList.add("video"),qt({doc:u,container:r,message:e,boxWidth:t.width,boxHeight:t.height,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),isOut:O,group:km,loadPromises:I,autoDownload:this.chat.autoDownload,noInfo:e.mid<0})}else{const t=yield ti({message:e,autoDownloadSize:this.chat.autoDownload.file,lazyLoadQueue:this.lazyLoadQueue,loadPromises:I,sizeType:"documentName",searchContext:{useSearch:!1,peerId:this.peerId,inputFilter:{_:"inputMessagesFilterEmpty"}}});r.append(t),r.classList.add("preview-with-document"),h.classList.add("has-document")}let p;if(o&&h.append(o),t.site_name){const e=ga((0,ii.Z)(t.url)).firstElementChild;e.classList.add("webpage-name");const i=document.createElement("strong");(0,c.Z)(i,(0,Zt.Z)(t.site_name)),e.textContent="",e.append(i),h.append(e),p=e}const m=oo(t);if(m.textContent){const e=document.createElement("div");e.classList.add("title");const t=document.createElement("strong");(0,c.Z)(t,m),e.append(t),h.append(e),p=e}const g=ao(t);if(g.textContent){const e=document.createElement("div");e.classList.add("text"),(0,c.Z)(e,g),h.append(e),p=e}if(a.append(h),l&&!u){i.classList.add("photo");const t=l.sizes[l.sizes.length-1];let s=!1;t.w===t.h&&p?(i.classList.add("is-square-photo"),s=!0,lt(l,r,48,48,!1)):t.h>t.w&&i.classList.add("is-vertical-photo"),dt({photo:l,message:e,container:r,boxWidth:s?0:d.Z.active.webpage.width,boxHeight:s?0:d.Z.active.webpage.height,isOut:O,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:I,withoutPreloader:s,autoDownloadSize:this.chat.autoDownload.photo})}s.append(a),w.insertBefore(s,Z);break}case"messageMediaDocument":{const s=k.document;if(s.sticker){i.classList.add("sticker"),x=!1,_=!0,s.animated&&i.classList.add("sticker-animated");const e=d.Z.active,n=i.classList.contains("emoji-big"),a=n?e.emojiSticker:s.animated?e.animatedSticker:e.staticSticker;lt(s,t,a.width,a.height),C.style.minWidth=t.style.width,C.style.minHeight=t.style.height,ta({doc:s,div:t,middleware:this.getMiddleware(),lazyLoadQueue:this.lazyLoadQueue,group:km,play:!0,loop:!0,emoji:n?E:void 0,withThumb:!0,loadPromises:I,isOut:O,noPremium:null===(h=null==k?void 0:k.pFlags)||void 0===h?void 0:h.nopremium}),(0,di.Z)(s)&&(L||D)&&this.observer.observe(i,this.stickerEffectObserverCallback)}else if("video"===s.type||"gif"===s.type||"round"===s.type){const n="round"===s.type;if(n&&(_=!0),!n&&E||(x=!1),z&&i.classList.add("hide-name"),i.classList.add(n?"round":"video"),y&&p&&1!==m.length)i.classList.add("is-album","is-grouped"),Qt({messages:f,attachmentDiv:t,middleware:this.getMiddleware(),isOut:b,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:I,autoDownload:this.chat.autoDownload});else{const a=!Je.IS_ANDROID&&!Je.IS_APPLE&&!n&&x&&!B&&!1;a&&i.classList.add("with-media-tail"),qt({doc:s,container:t,message:e,boxWidth:d.Z.active.regular.width,boxHeight:d.Z.active.regular.height,withTail:a,isOut:O,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),group:km,loadPromises:I,autoDownload:this.chat.autoDownload,searchContext:n?{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})}}else{const t=yield function({albumMustBeRenderedFull:e,message:t,bubble:i,messageDiv:s,chat:n,loadPromises:a,autoDownloadSize:o,lazyLoadQueue:r,searchContext:l,useSearch:d,sizeType:h,managers:u}){return si(this,void 0,void 0,(function*(){let d;const p=e?yield n.getMidsByMid(t.mid):[t.mid],m=p.map(((e,t)=>si(this,void 0,void 0,(function*(){const i=yield n.getMessage(e),s=yield ti({message:i,loadPromises:a,autoDownloadSize:o,lazyLoadQueue:r,searchContext:l,sizeType:h,managers:u}),m=document.createElement("div");m.classList.add("document-container"),m.dataset.mid=""+e,m.dataset.peerId=""+i.peerId;const g=document.createElement("div");if(g.classList.add("document-wrapper"),i.message){const e=document.createElement("div");e.classList.add("document-message");const t=(0,ii.Z)(i.message,{entities:i.totalEntities});(0,c.Z)(e,t),g.append(e)}if(p.length>1){const e=document.createElement("div");e.classList.add("document-selection"),m.append(e),m.classList.add("grouped-item"),0===t&&(d=g)}return g.append(s),m.append(g),m})))),g=yield Promise.all(m);return s.append(...g),p.length>1&&i.classList.add("is-multiple-documents","is-grouped"),d}))}({albumMustBeRenderedFull:y,message:e,bubble:i,messageDiv:w,chat:this.chat,loadPromises:I,autoDownloadSize:this.chat.autoDownload.file,lazyLoadQueue:this.lazyLoadQueue,searchContext:"voice"===s.type||"audio"===s.type?{peerId:this.peerId,inputFilter:{_:"voice"===s.type?"inputMessagesFilterRoundVoice":"inputMessagesFilterMusic"},threadId:this.chat.threadId,useSearch:!e.pFlags.is_scheduled,isScheduled:e.pFlags.is_scheduled}:void 0,sizeType:"documentName"});t&&(H=t);const a=w.lastElementChild.querySelector(".document-message, .document, .audio");a&&a.append(Z),i.classList.remove("is-message-empty"),w.classList.add((["photo","pdf"].includes(s.type)?"document":s.type||"document")+"-message"),n=!0}break}case"messageMediaCall":{const e=k.action,t=document.createElement("div");t.classList.add("bubble-call",e.pFlags.video?"tgico-videocamera":"tgico-phone");const s=e.pFlags.video?"video":"voice";t.dataset.type=s;const a=document.createElement("div");a.classList.add("bubble-call-title"),(0,v.$d)(a,O?e.pFlags.video?"CallMessageVideoOutgoing":"CallMessageOutgoing":e.pFlags.video?"CallMessageVideoIncoming":"CallMessageIncoming");const o=document.createElement("div");if(o.classList.add("bubble-call-subtitle"),void 0!==e.duration)o.append(Ia(e.duration));else{let t;switch(e.reason._){case"phoneCallDiscardReasonBusy":t="Call.StatusBusy";break;case"phoneCallDiscardReasonMissed":t="Chat.Service.Call.Missed";break;default:t="Chat.Service.Call.Cancelled"}o.classList.add("is-reason"),(0,v.$d)(o,t)}o.classList.add("tgico","arrow-"+(void 0!==e.duration?"green":"red")),t.append(a,o),n=!0,i.classList.remove("is-message-empty"),w.classList.add("call-message"),w.append(t);break}case"messageMediaContact":{const e=k,t=document.createElement("div");t.classList.add("contact"),t.dataset.peerId=""+e.user_id,n=!0;const s=document.createElement("div");s.className="contact-details";const a=document.createElement("div");a.className="contact-name",a.append((0,Zt.Z)([e.first_name,e.last_name].filter(Boolean).join(" ")));const o=document.createElement("div");o.className="contact-number",o.textContent=e.phone_number?"+"+(0,Ms.u)(e.phone_number).formatted:"Unknown phone number",t.append(s),s.append(a,o);const r=new Wm;r.updateWithOptions({lazyLoadQueue:this.lazyLoadQueue,peerId:e.user_id.toPeerId()}),r.classList.add("contact-avatar","avatar-54"),t.prepend(r),i.classList.remove("is-message-empty"),w.classList.add("contact-message"),w.append(t);break}case"messageMediaPoll":{i.classList.remove("is-message-empty");const t=function(e,t=s.Z.managers){const i=new ua;return i.message=e,i.managers=t,i.setAttribute("peer-id",""+e.peerId),i.setAttribute("poll-id",e.media.poll.id),i.setAttribute("message-id",""+e.mid),i.render(),i}(e);w.prepend(t),w.classList.add("poll-message");break}case"messageMediaInvoice":{const e=k.pFlags.test,s=k.photo,n=document.createElement(s?"span":"div"),a=document.createDocumentFragment(),o=(0,v.ag)(k.receipt_msg_id?"PaymentReceipt":e?"PaymentTestInvoice":"PaymentInvoice");o.classList.add("text-uppercase");const r=" ",l=document.createElement("span");if(l.classList.add("text-bold"),l.textContent=Ea(k.total_amount,k.currency)+r,a.append(l,o),e&&k.receipt_msg_id){const e=document.createElement("span");e.classList.add("text-uppercase","pre-wrap"),e.append(r+"(Test)"),a.append(e)}if((0,c.Z)(n,a),s){const e=d.Z.active.invoice;dt({photo:s,container:t,withTail:!1,isOut:O,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:I,boxWidth:e.width,boxHeight:e.height}),i.classList.add("photo"),n.classList.add("video-time"),t.append(n)}else t=void 0;const h=document.createElement("div");h.classList.add("bubble-primary-color"),(0,c.Z)(h,(0,Zt.Z)(k.title));const u=(0,Zt.Z)(k.description);w.prepend(...[h,!s&&n,u].filter(Boolean)),i.classList.remove("is-message-empty"),i.classList.add("is-invoice");break}default:t=void 0,i.classList.remove("is-message-empty"),w.append((0,v.ag)(v.nK),Z),this.log.warn("unrecognized media type:",k._,e)}!n&&t&&C.append(t)}_&&i.classList.add("just-media");let G="";const V=e.fromId!==s.Z.myId&&this.chat.isAnyGroup||e.viaBotId||e.pFlags.sponsored;if(V||N||e.reply_to_mid){let t,n;const a=e.from_id&&"peerChannel"===e.from_id._&&e.fromId===U,o=N&&!N.from_id;let r;if(e.viaBotId&&(n=document.createElement("span"),n.innerText="@"+(yield this.managers.appUsersManager.getUser(e.viaBotId)).username,n.classList.add("peer-title"),i.classList.add("must-have-name")),o?(t=document.createElement("span"),(0,c.Z)(t,(0,Zt.Z)(N.from_name)),t.classList.add("peer-title"),i.classList.add("hidden-profile")):t=new Ot({peerId:U||e.fromId}).element,e.reply_to_mid&&e.reply_to_mid!==this.chat.threadId&&u&&(yield Jr.setReply({chat:this.chat,bubble:i,bubbleContainer:C,message:e})),U||N)if(this.peerId===s.Z.myId||a||i.classList.add("forwarded"),e.savedFrom&&(G=e.savedFrom,t.dataset.savedFrom=G),r=document.createElement("div"),t.dataset.peerId=""+U,this.peerId!==s.Z.myId&&this.peerId!==le.hj&&!a||_){const e=[t];_&&e.unshift(document.createElement("br")),r.append((0,v.ag)("ForwardedFrom",[e]))}else r.style.color=Rs(U,!1),r.append(t);else if(!e.viaBotId)if(!_&&V){r=document.createElement("div"),r.append(t);const i=yield this.managers.appPeersManager.getPeer(e.fromId),s=null==i?void 0:i.pFlags;s&&(s.scam||s.fake)&&r.append(Bt(s.scam)),b||(r.style.color=Rs(e.fromId,!1)),r.dataset.peerId=""+e.fromId}else i.classList.add("hide-name");if(e.viaBotId){r?r.append(" "):r=document.createElement("div");const e=document.createElement("span");e.append((0,v.ag)("ViaBot")," ",n),e.classList.add("is-via"),r.append(e)}r&&(r.classList.add("name"),H.append(r))}else i.classList.add("hide-name");if("pinned"===this.chat.type&&(G=`${this.chat.peerId}_${e.mid}`),R&&R.mid===this.chat.threadId&&i.classList.add("is-thread-starter","is-group-last"),G&&("pinned"===this.chat.type||N.saved_from_msg_id)&&this.peerId!==le.hj){const e=document.createElement("div");e.classList.add("bubble-beside-button","goto-original","tgico-arrow_next"),C.append(e),i.dataset.savedFrom=G,i.classList.add("with-beside-button")}return i.classList.add(O?"is-out":"is-in"),B&&Jr.renderReplies({bubble:i,bubbleContainer:C,message:R,messageDiv:w,loadPromises:I,lazyLoadQueue:this.lazyLoadQueue})&&(x=!0),u&&this.appendReactionsElementToBubble(i,e,g),x&&(i.classList.add("can-have-tail"),C.append(bc())),M}))}appendReactionsElementToBubble(e,t,i,s){if(this.peerId.isUser())return;if(!(null==i?void 0:i.reactions)||!i.reactions.results.length)return;const n=new jr;if(n.init(i,"block"),n.render(s),e.classList.contains("is-message-empty"))e.querySelector(".bubble-content-wrapper").append(n);else{const s=e.querySelector(".message");if(e.classList.contains("is-multiple-documents")){const e=s.lastElementChild;let a=e.querySelector(".document-message"),o=a&&a.querySelector(".time");o||(o=Jr.setTime({chatType:this.chat.type,message:t,reactionsMessage:i})),n.append(o),a||(a=document.createElement("div"),a.classList.add("document-message"),e.querySelector(".document-wrapper").prepend(a)),a.append(n)}else{const t=Array.from(e.querySelectorAll(".time")).pop();n.append(t),s.append(n)}}}prepareToSaveScroll(e){if(!this.chatInner.parentElement)return{};const t=this.log.bindPrefix("prepareToSaveScroll");t("save");const i=this.createScrollSaver(e);if(i.save(),this.getRenderedLength()&&!this.chat.setPeerPromise){const e=this.getViewportSlice();this.deleteViewportSlice(e,!0)}return{restoreScroll:()=>{t("restore"),i.restore(e),this.onRenderScrollSet(i.getSaved())},scrollSaver:i}}performHistoryResult(e,t){return cc(this,void 0,void 0,(function*(){let i=e.history;i=i.slice(),this.needReflowScroll&&(tl(this.scrollable.container),this.needReflowScroll=!1);const s=yield Promise.all(i.map((e=>"number"==typeof e?this.chat.getMessage(e):e))),n=[];if(!this.scrollable.loadedAll.bottom||!this.scrollable.loadedAll.top){let t=e.isEnd;if(!t){const e=yield this.chat.getHistoryStorage(),s=e.history.first,n=e.history.last;t={top:!1,bottom:!1,both:!1},!s.isEnd(Xr.D.Bottom)||s.length&&!i.includes(s[0])||(t.bottom=!0),!n.isEnd(Xr.D.Top)||n.length&&!i.includes(n[n.length-1])||(t.top=!0)}if(!t.bottom&&this.setPeerOptions){const{lastMsgId:e,topMessage:i}=this.setPeerOptions;this.setPeerOptions=void 0,e&&!this.bubbles[i]&&e!==i||(t.bottom=!0)}t.top&&n.push(this.setLoaded("top",!0)),t.bottom&&n.push(this.setLoaded("bottom",!0))}yield Promise.all(n);const a=s.map((e=>e?e.pFlags.local?this.processLocalMessageRender(e):this.safeRenderMessage(e,t):void 0));yield Promise.all(a),yield this.messagesQueuePromise,this.scrollable.loadedAll.top&&this.messagesQueueOnRenderAdditional&&(this.messagesQueueOnRenderAdditional(),this.messagesQueueOnRenderAdditional&&this.messagesQueueOnRenderAdditional())}))}onRenderScrollSet(e){const t="has-sticky-dates";if(this.container.classList.contains(t)||this.preloader.detached&&(null!=e||(e={scrollHeight:this.scrollable.scrollHeight,clientHeight:this.scrollable.container.clientHeight}),e.scrollHeight===e.clientHeight))this.willScrollOnLoad=void 0;else{const e=this.getMiddleware(),i=()=>{e()&&this.container.classList.add(t)};this.willScrollOnLoad?i():setTimeout(i,600)}}requestHistory(e,t,i){return"chat"===this.chat.type||"discussion"===this.chat.type?this.managers.acknowledged.appMessagesManager.getHistory(this.peerId,e,t,i,this.chat.threadId):"pinned"===this.chat.type?this.managers.acknowledged.appMessagesManager.getSearch({peerId:this.peerId,inputFilter:{_:"inputMessagesFilterPinned"},maxId:e,limit:t,backLimit:i}).then((e=>({cached:e.cached,result:Promise.resolve(e.result).then((e=>({history:e.history.map((e=>e.mid))})))}))):"scheduled"===this.chat.type?this.managers.acknowledged.appMessagesManager.getScheduledMessages(this.peerId).then((e=>({cached:e.cached,result:Promise.resolve(e.result).then((e=>({history:e.slice().reverse()})))}))):void 0}animateAsLadder(e,t,i,s,n){return cc(this,void 0,void 0,(function*(){const a=this.log.bindPrefix("ladder");if(this.chat.setPeerPromise&&!this.resolveLadderAnimation)return a.warn("will be delayed"),void(this.resolveLadderAnimation=this.animateAsLadder.bind(this,e,t,i,s,n));if(!Object.keys(this.bubbles).length)return void a.warn("no bubbles");let o,r=(0,no.Z)(this.bubbles,"desc");i&&t.length&&(r=r.filter((e=>!t.includes(e)))),o=s?n||Math.max(...r):e||Math.max(...r);const l=r.slice(r.findIndex((e=>o>e))),c=i?[]:[o],d=i?[]:r.slice(0,r.findIndex((e=>o>=e))).reverse();R.ZP&&a("targeting mid:",o,n,e,l.map((e=>(0,ci.Z)(e))),d.map((e=>(0,ci.Z)(e))));const h=[];this.chatInner.classList.add("zoom-fading");const u=i?10:40,p=i?0:1,m=(e,t=0)=>{const i=(0,Oe.Z)();let s=0;return e.forEach(((n,o)=>{const r=this.bubbles[n];if(!r||this.skippedMids.has(n))return void a.warn("no bubble by mid:",n);s=(o+t||.1)*u;const l=r.lastElementChild,c=[l],d=this.bubbleGroups.getItemByBubble(r);if(d&&d.group.avatar&&d.group.lastItem===d&&c.push(d.group.avatar),c.forEach((e=>{e.classList.add("zoom-fade","can-zoom-fade"),e.style.transitionDelay=s+"ms"})),o===e.length-1){const e=t=>{t.target===l&&(i.resolve(),l.removeEventListener("transitionend",e))};l.addEventListener("transitionend",e)}h.push(...c)})),e.length||i.resolve(),{lastMsDelay:s,animationPromise:i}},g=m(l,p),v=m(c),f=m(d,p),y=[g.animationPromise,v.animationPromise,f.animationPromise],b=[g.lastMsDelay,v.lastMsDelay,f.lastMsDelay];let w;return this.onAnimateLadder&&(yield this.onAnimateLadder()),(0,Be.T2)((()=>{this.setStickyDateManually(),h.forEach((e=>{e.classList.remove("zoom-fade")}))})),(l.length||c.length||d.length)&&(w=Promise.all(y),(0,He.YW)(w,Math.max(...b)+200).then((()=>{(0,Be.T2)((()=>{h.forEach((e=>{e.style.transitionDelay="",e.classList.remove("can-zoom-fade")})),this.chatInner.classList.remove("zoom-fading")}))}))),w}))}renderEmptyPlaceholder(e,t,i,s){return cc(this,void 0,void 0,(function*(){const i="empty-bubble-placeholder";let o,r;if(t.classList.add(i,i+"-"+e),"group"===e?o=(0,v.ag)("GroupEmptyTitle1"):"saved"===e?o=(0,v.ag)("ChatYourSelfTitle"):"noMessages"===e||"greeting"===e?o=(0,v.ag)("NoMessages"):"noScheduledMessages"===e?o=(0,v.ag)("NoScheduledMessages"):"restricted"===e&&(o=document.createElement("span"),o.innerText=yield this.managers.appPeersManager.getRestrictionReasonText(this.peerId)),o.classList.add("center",i+"-title"),s.push(o),"group"===e)s.push((0,v.ag)("GroupEmptyTitle2")),r=[(0,v.ag)("GroupDescription1"),(0,v.ag)("GroupDescription2"),(0,v.ag)("GroupDescription3"),(0,v.ag)("GroupDescription4")];else if("saved"===e)r=[(0,v.ag)("ChatYourSelfDescription1"),(0,v.ag)("ChatYourSelfDescription2"),(0,v.ag)("ChatYourSelfDescription3"),(0,v.ag)("ChatYourSelfDescription4")];else if("greeting"===e){const e=(0,v.ag)("NoMessagesGreetingsDescription");e.classList.add("center",i+"-subtitle");const t=document.createElement("div");t.classList.add(i+"-sticker");const o=this.getMiddleware();yield this.managers.appStickersManager.getGreetingSticker().then((e=>cc(this,void 0,void 0,(function*(){if(!o())return;const i=[];return yield ta({doc:e,div:t,middleware:o,lazyLoadQueue:this.lazyLoadQueue,group:km,play:!0,loop:!0,withThumb:!0,loadPromises:i}),(0,n.fc)(t,(e=>{(0,a.Z)(e),zn.onMediaClick({target:e.target})})),Promise.all(i)})))),s.push(e,t)}r&&(s.push(...r.map((e=>{const t=document.createElement("span");return t.classList.add(i+"-list-item"),t.append(e),t}))),"group"===e?r.forEach((e=>{const t=document.createElement("span");t.classList.add("tgico-check"),e.prepend(t)})):"saved"===e&&r.forEach((e=>{const t=document.createElement("span");t.classList.add(i+"-list-bullet"),t.innerText="•",e.prepend(t)}))),s.length>1&&t.classList.add("has-description"),s.forEach((e=>e.classList.add(i+"-line")))}))}processLocalMessageRender(e,t){return cc(this,void 0,void 0,(function*(){const i=!!e.pFlags.sponsored,a=hl(this.getMiddleware());return this.safeRenderMessage(e,!i,void 0,i,(o=>cc(this,void 0,void 0,(function*(){const{bubble:r}=yield a(o);if(!r)return o;r.classList.add("is-group-last","is-group-first");const l=()=>{this.updatePlaceholderPosition===l&&(this.updatePlaceholderPosition=void 0),u[p](r)};i||(r.classList.add("bubble-first"),r.classList.remove("can-have-tail","is-in"));const c=[],d=this.chat.isBot;let h,u=this.container,p="append";if(this.chat.isRestricted)h=this.renderEmptyPlaceholder("restricted",r,e,c);else{if(i){let t,i,s,a;r.classList.add("avoid-selection");const l=this.sponsoredMessage=e.sponsoredMessage,c=(0,es.Z)(l.from_id);l.channel_post?(t="OpenChannelPost",i=(0,cl.Z)(l.channel_post)):l.start_param||d?(t="Chat.Message.ViewBot",s=l.start_param):t=(yield this.managers.appPeersManager.isAnyGroup(c))?"Chat.Message.ViewGroup":"Chat.Message.ViewChannel",a=l.chat_invite?()=>{new al(l.chat_invite_hash,l.chat_invite)}:l.chat_invite_hash?()=>{const e={_:sl.JOIN_CHAT,invite:l.chat_invite_hash};this.chat.appImManager.processInternalLink(e)}:()=>{this.chat.appImManager.setInnerPeer({peerId:c,lastMsgId:i,startParam:s})};const h=(0,M.Z)("btn-primary btn-primary-transparent bubble-view-button",{text:t});return this.observer.observe(h,this.viewsObserverCallback),a&&(0,n.fc)(h,a),r.querySelector(".bubble-content").prepend(h),o}if(d&&"message"===e._){const e=document.createElement("b");e.append((0,v.ag)("BotInfoTitle")),c.push(e,"\n\n"),u=this.chatInner,p="prepend"}else h=(yield a(this.managers.appPeersManager.isAnyGroup(this.peerId)))&&(yield a(this.managers.appPeersManager.getPeer(this.peerId))).pFlags.creator?this.renderEmptyPlaceholder("group",r,e,c):"scheduled"===this.chat.type?this.renderEmptyPlaceholder("noScheduledMessages",r,e,c):s.Z.myId===this.peerId?this.renderEmptyPlaceholder("saved",r,e,c):this.peerId.isUser()&&!d&&(yield a(this.chat.canSend()))&&"chat"===this.chat.type?this.renderEmptyPlaceholder("greeting",r,e,c):this.renderEmptyPlaceholder("noMessages",r,e,c)}h&&(yield h),c.length&&r.querySelector(".message, .service-msg").prepend(...c);const m=!!this.messagesQueueOnRenderAdditional,g=this.setPeerCached&&!m;if(g){const e=r.firstElementChild;e.classList.add("no-transition"),this.chat.setPeerPromise&&this.chat.setPeerPromise.catch(ft.Z).finally((()=>{e.classList.remove("no-transition")}))}if(void 0!==t||g||(t=!0),m||t?(this.updatePlaceholderPosition=l,this.onAnimateLadder=()=>{if(this.onAnimateLadder=void 0,!this.messagesQueuePromise)return(0,Be.AD)()}):this.chat.setPeerPromise?this.attachPlaceholderOnRender=()=>{this.attachPlaceholderOnRender=void 0,l()}:this.updatePlaceholderPosition=l,!m&&t){yield a((0,He.e9)());const t=(0,no.Z)(this.bubbles);(0,T.Z)(t,e.mid),this.animateAsLadder(e.mid,t,!1,0,0)}return this.emptyPlaceholderBubble=r,o}))))}))}generateLocalMessageId(e=0){const t=("scheduled"===this.chat.type?-1:0)+e,i=-Math.abs(t);return{id:i,mid:-Math.abs((0,cl.Z)(i))}}generateLocalFirstMessage(e,t,i=0){return cc(this,void 0,void 0,(function*(){const{id:s,mid:n}=this.generateLocalMessageId(i);let a={_:e?"messageService":"message",date:0,id:s,mid:n,peer_id:yield this.managers.appPeersManager.getOutputPeer(this.peerId),pFlags:{local:!0}};return e||(a.message=""),(0,ai.Z)(a),t&&t(a),a=(yield this.managers.appMessagesManager.saveMessages([a],{storage:new Map}))[0],a.mid=n,a}))}getViewportSlice(){return function({overflowElement:e,selector:t,extraSize:i}){const s=e.getBoundingClientRect(),n=Array.from(e.querySelectorAll(t)),a=[],o=[],r=[];let l=!1;for(const t of n){const i=t.getBoundingClientRect(),n=En(t,e,!1,i,s);let c;n?(l=!0,c=o):c=l?r:a,c.push({element:t,rect:i,visibleRect:n})}if(i&&o.length){const e=o[0].rect.top-i,t=o[o.length-1].rect.bottom+i;for(let t=a.length-1;t>=0;--t){const i=a[t];i.rect.top>=e&&(a.splice(t,1),o.unshift(i))}for(let e=0,i=r.length;e<i;++e){const s=r[e];s.rect.bottom<=t&&(r.splice(e--,1),--i,o.push(s))}}return{invisibleTop:a,visible:o,invisibleBottom:r}}({overflowElement:this.scrollable.container,selector:".bubbles-date-group .bubble:not(.is-date)",extraSize:2*Math.max(700,as.height)})}deleteViewportSlice(e,t){const{invisibleTop:i,invisibleBottom:s}=e,n=i.concat(s);if(!n.length)return;i.length&&(this.setLoaded("top",!1),this.getHistoryTopPromise=void 0),s.length&&(this.setLoaded("bottom",!1),this.getHistoryBottomPromise=void 0);const a=n.map((({element:e})=>+e.dataset.mid));let o;!!i.length==!!s.length||t||(o=this.createScrollSaver(!!i.length),o.save()),this.deleteMessagesByIds(a,!1,!0),o?o.restore():i.length&&(this.scrollable.lastScrollPosition=this.scrollable.scrollTop)}sliceViewport(e){if(Je.IS_SAFARI||this.isHeavyAnimationInProgress&&!e)return;const t=this.getViewportSlice();this.deleteViewportSlice(t)}setLoaded(e,t,i=!0){return cc(this,void 0,void 0,(function*(){if(this.scrollable.loadedAll[e]!==t)return this.log.bindPrefix("setLoaded")("change",e,t),this.scrollable.loadedAll[e]=t,this.scrollable.onScroll(),i?!this.chat.isRestricted&&("bottom"===e&&this.chat.isBroadcast&&this.toggleSponsoredMessage(t),"top"===e&&t&&this.chat.isBot)?this.renderBotPlaceholder():this.checkIfEmptyPlaceholderNeeded():void 0}))}toggleSponsoredMessage(e){return cc(this,void 0,void 0,(function*(){const t=this.log.bindPrefix("sponsored");t("checking");const{mid:i}=this.generateLocalMessageId(1);if(e){const e=this.getMiddleware((()=>this.scrollable.loadedAll.bottom&&!this.bubbles[i]&&this.getSponsoredMessagePromise===s)),s=this.getSponsoredMessagePromise=this.managers.appChatsManager.getSponsoredMessage(this.peerId.toChatId()).then((i=>cc(this,void 0,void 0,(function*(){const s=i.messages[0];if(!s)return void t("no message");const n=this.generateLocalFirstMessage(!1,(e=>{e.message=s.message,e.from_id=s.from_id,e.entities=s.entities,e.pFlags.sponsored=!0,e.sponsoredMessage=s}),1);return Promise.all([n,this.getHistoryTopPromise,this.messagesQueuePromise]).then((([i])=>{e()&&(t("rendering",i),this.performHistoryResult({history:[i]},!1))}))})))).finally((()=>{this.getSponsoredMessagePromise=void 0}))}else t("clearing rendered",i),this.deleteMessagesByIds([i]),this.getSponsoredMessagePromise=void 0}))}renderBotPlaceholder(){return cc(this,void 0,void 0,(function*(){const e=this.log.bindPrefix("bot placeholder"),t=this.getMiddleware(),i=yield this.managers.acknowledged.appProfileManager.getProfile(this.peerId.toUserId());e("getting profile, cached:",i.cached);const s=i.result.then((s=>cc(this,void 0,void 0,(function*(){var n;if(!t())return;if(!(null===(n=s.bot_info)||void 0===n?void 0:n.description))return e.warn("no description"),this.checkIfEmptyPlaceholderNeeded();const a=yield this.generateLocalFirstMessage(!1,(e=>{const t=s.bot_info;e.message=t.description,t.description_document&&(e.media={_:"messageMediaDocument",document:t.description_document}),t.description_photo&&(e.media={_:"messageMediaPhoto",photo:t.description_photo})}));return t()?(e("rendering"),{renderPromise:this.processLocalMessageRender(a,!i.cached).then((()=>{e("done")}))}):void 0}))));if(i.cached)return s}))}checkIfEmptyPlaceholderNeeded(){return cc(this,void 0,void 0,(function*(){if(this.scrollable.loadedAll.top&&this.scrollable.loadedAll.bottom&&void 0===this.emptyPlaceholderBubble&&(this.chat.isRestricted||!(yield this.chat.getHistoryStorage()).count||!Object.keys(this.bubbles).length||Object.keys(this.bubbles).length&&!this.getRenderedLength()||"scheduled"===this.chat.type&&!Object.keys(this.bubbles).length)){this.log("inject empty peer placeholder");const e=yield this.generateLocalFirstMessage(!0);return{renderPromise:this.processLocalMessageRender(e)}}}))}getHistory1(e,t,i,s,n){const a=this.getMiddleware(n?void 0:()=>(t?this.getHistoryTopPromise:this.getHistoryBottomPromise)===r),o=this.getHistory(e,t,i,s,n,a),r=o.then((e=>e&&(e.waitPromise||e.promise)));return t?this.getHistoryTopPromise=r:this.getHistoryBottomPromise=r,r.then((()=>{a()&&(t?this.getHistoryTopPromise=void 0:this.getHistoryBottomPromise=void 0,n||"chat"===this.chat.type&&setTimeout((()=>{t?this.loadMoreHistory(!0,!0):this.loadMoreHistory(!1,!0)}),0))})),o}getHistory(e=0,t=!1,i=!1,n=0,a=!1,o){return cc(this,void 0,void 0,(function*(){const r=this.peerId,l=this.chat.isBroadcast,c=Math.min(30,as.height/40|0);let d=l?20:Object.keys(this.bubbles).length>0?Math.max(35,c):c;if(void 0!==pc){if(!pc)return{cached:!1,promise:Promise.resolve(),waitPromise:Promise.resolve()};Object.keys(this.bubbles).length>0&&--pc}let h,u=0;if(i&&(u=d,t||(d=0)),n&&!i)if("pinned"===this.chat.type)h=[n];else{const t=(yield this.chat.getHistoryStorage()).history.slice;if(t.length<d&&!t.isEnd(Xr.D.Both)){h=t.slice();for(let e=h.length-1;e>=0;--e){const t=yield this.chat.getMessage(h[e]);if(!(null==t?void 0:t.grouped_id))break;h.splice(e,1)}e=h[h.length-1]||e}}let p,m=yield this.requestHistory(e,d,u);const g=(null==h?void 0:h.length)&&!m.cached,v=this.isFirstLoad&&u&&!m.cached||g;g&&(p=m.result,m={cached:!0,result:Promise.resolve({history:h})}),this.isFirstLoad=!1;const f=e=>cc(this,void 0,void 0,(function*(){var t;if(null===(t=e.isEnd)||void 0===t?void 0:t.top){if("discussion"===this.chat.type){const t=yield this.managers.appMessagesManager.getThreadServiceMessageId(this.peerId,this.chat.threadId);t&&e.history.push(t);const i=yield this.chat.getMidsByMid(this.chat.threadId);e.history.push(...i.reverse())}yield this.managers.appProfileManager.getProfileByPeerId(r)}})),y=e=>(0,He.e9)().then((()=>f(e))).then((()=>(!g&&n&&e.history.unshift(n),this.performHistoryResult(e,t)))),b=e=>{const t=Promise.resolve(e).then((e=>{if(o&&!o())throw vc;if(!a)return y(e);this.scrollable.onScroll()}),(e=>{throw this.log.error("getHistory error:",e),e}));return t};let w,S;if(m.cached){if(a)return this.scrollable.onScroll(),null;S=!0,w=y(yield m.result)}else S=!1,w=b(m.result);const C=g?b(p):w;if(v&&s.Z.settings.animationsEnabled){let i=g?2:1;this.messagesQueueOnRenderAdditional=()=>{this.log("messagesQueueOnRenderAdditional"),--i||(this.messagesQueueOnRenderAdditional=void 0,this.animateAsLadder(n,h,g,u,e).then((()=>{setTimeout((()=>{this.loadMoreHistory(t,!0)}),0)})))}}else this.messagesQueueOnRenderAdditional=void 0;return a?null:{cached:S,promise:w,waitPromise:C}}))}setUnreadDelimiter(){return cc(this,void 0,void 0,(function*(){if("chat"!==this.chat.type&&"discussion"!==this.chat.type)return;if(this.attachedUnreadBubble)return;const e=yield this.chat.getHistoryMaxId();let t=yield this.managers.appMessagesManager.getReadMaxIdIfUnread(this.peerId,this.chat.threadId);if(t&&(t=Object.keys(this.bubbles).filter((e=>!this.bubbles[e].classList.contains("is-out"))).map((e=>+e)).sort(((e,t)=>e-t)).find((e=>e>t)),t&&this.bubbles[t])){const i=this.bubbles[t];this.firstUnreadBubble&&this.firstUnreadBubble!==i&&(this.firstUnreadBubble.classList.remove("is-first-unread"),this.firstUnreadBubble=null),t!==e&&i.classList.add("is-first-unread"),this.firstUnreadBubble=i,this.attachedUnreadBubble=!0}}))}deleteEmptyDateGroups(){const e=this.stickyIntersector?gc:1;let t=!1;for(const i in this.dateMessages){const s=this.dateMessages[i];s.container.childElementCount===e&&(s.container.remove(),this.stickyIntersector&&this.stickyIntersector.unobserve(s.container,s.div),delete this.dateMessages[i],t=!0)}t&&(Object.keys(this.dateMessages).length||this.container.classList.remove("has-groups"),this.checkIfEmptyPlaceholderNeeded(),this.setStickyDateManually())}}function bc(){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 wc{constructor(e,t,i,s){this.peerId=e,this.mid=t,this.unpin=i,this.onConfirm=s,this.construct()}construct(){return e=this,t=void 0,n=function*(){const{peerId:e,mid:t,unpin:i,onConfirm:n}=this;let a,o,r;const l=[],c=[],d=A.Z.MANAGERS,h=yield d.appPeersManager.canPinMessage(e),u=(s,a,o)=>{setTimeout((()=>{let s;s=i&&!t?h?d.appMessagesManager.unpinAllMessages(e):d.appMessagesManager.hidePinnedMessages(e):d.appMessagesManager.updatePinnedMessage(e,t,i,o,a),n&&s.then(n)}),300)};if(i){let i="UnpinMessage";t?(a="UnpinMessageAlertTitle",o="Chat.Confirm.Unpin"):h?(a="Popup.Unpin.AllTitle",o="Chat.UnpinAllMessagesConfirmation",r=[""+((yield d.appMessagesManager.getPinnedMessagesCount(e))||1)]):(a="Popup.Unpin.HideTitle",o="Popup.Unpin.HideDescription",i="Popup.Unpin.Hide"),l.push({langKey:i,isDanger:!0,callback:u})}else{a="PinMessageAlertTitle";const t="PinMessage";e.isAnyChat()?(l.push({langKey:t,callback:e=>u(0,!1,!e.size)}),(yield d.appChatsManager.isBroadcast(e.toChatId()))?o="PinMessageAlertChannel":(o="PinMessageAlert",c.push({text:"PinNotify",checked:!0}))):(o="PinMessageAlertChat",e===s.Z.myId?l.push({langKey:t,callback:u}):(l.push({langKey:t,callback:e=>u(0,!e.size)}),c.push({text:"PinAlsoFor",textArgs:[new Ot({peerId:e}).element],checked:!0})))}(0,A.x)(l),new qi("popup-delete-chat",{peerId:e,titleLangKey:a,descriptionLangKey:o,descriptionLangArgs:r,buttons:l,checkboxes:c}).show()},new((i=void 0)||(i=Promise))((function(s,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n}}function Sc(e=window.getSelection()){if(!e||!e.rangeCount)return!0;const t=e.getRangeAt(0);return!t.toString()||!t.START_TO_END}function Cc(e,t,i){return s.Z.managers.appStickersManager.preloadAnimatedEmojiSticker(e).then((({doc:s})=>{if(s)return u.Z.downloadMedia({media:s}).then((n=>{return a=this,o=void 0,l=function*(){const a=d.Z.active.emojiSticker,o=(0,pi.tB)(e),r=yield hi.Z.loadAnimationWorker({container:void 0,animationData:n,width:null!=t?t:a.width,height:null!=i?i:a.height,name:"doc"+s.id,autoplay:!1,loop:!1,toneIndex:o},"none");r.addEventListener("firstFrame",(()=>{li(s,r.canvas,o),r.remove()}),{once:!0})},new((r=void 0)||(r=Promise))((function(e,t){function i(e){try{n(l.next(e))}catch(e){t(e)}}function s(e){try{n(l.throw(e))}catch(e){t(e)}}function n(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r((function(e){e(n)}))).then(i,s)}n((l=l.apply(a,o||[])).next())}));var a,o,r,l}))}))}class Lc extends qi{constructor(e,t,i,s){super("popup-report-messages-confirm",{noTitle:!0,descriptionLangKey:"ReportInfo",buttons:[{langKey:"ReportChat",callback:()=>{a.isValid()&&(s&&s(),this.managers.appMessagesManager.reportMessages(e,t,i,a.value).then((e=>{e&&Li({langPackKey:"ReportSentInfo"})})))}}],body:!0});const n=document.createElement("div");wo({div:n,emoji:Lc.STICKER_EMOJI,width:100,height:100}).then((({render:e})=>e)).finally((()=>{this.show()})),this.header.append(n);const a=new b.Z({label:"ReportHint",maxLength:512,placeholder:"ReportChatDescription"});a.input.addEventListener("input",(()=>{this.buttons[0].element.toggleAttribute("disabled",!a.isValid())})),this.body.append(a.container)}}Lc.STICKER_EMOJI="👮‍♀️";class Ic extends qi{constructor(e,t,i){super("popup-report-messages",{titleLangKey:"ChatTitle.ReportMessages",buttons:[],body:!0}),t=t.slice();const s=[["ReportChatSpam","inputReportReasonSpam"],["ReportChatViolence","inputReportReasonViolence"],["ReportChatChild","inputReportReasonChildAbuse"],["ReportChatPornography","inputReportReasonPornography"],["ReportChatOther","inputReportReasonOther"],["ReportChatPersonalDetails","inputReportReasonPersonalDetails"],["ReportChatIllegalDrugs","inputReportReasonIllegalDrugs"]];s.forEach((e=>{const t=(0,M.Z)("btn-primary btn-transparent",{text:e[0]});this.body.append(t)}));const a=Cc(Lc.STICKER_EMOJI);(0,n.fc)(this.body,(n=>{const o=(0,r.Z)(n.target,"btn-primary"),l=s[(0,Cn.Z)(o)][1];a.then((()=>{this.hide(),new Lc(e,t,l,i)}))}),{listenerSetter:this.listenerSetter}),this.body.style.margin="0 -1rem",this.buttonsEl.style.marginTop=".5rem",this.show()}}class Mc extends qi{constructor(){super("popup-sponsored",{titleLangKey:"Chat.Message.Sponsored.What",descriptionLangKey:"Chat.Message.Ad.Text",descriptionLangArgs:[(0,v.ag)("Chat.Message.Sponsored.Link")],buttons:[{langKey:"OK",isCancel:!0},{langKey:"Chat.Message.Ad.ReadMore",callback:()=>{window.open(v.ZP.format("Chat.Message.Sponsored.Link",!0))},isCancel:!0}],scrollable:!0}),this.scrollable.append(this.description),this.show()}}var Ec=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Pc extends A.Z{constructor(e){super("popup-reacted-list",{closable:!0,overlayClosable:!0,body:!0}),this.message=e,this.init()}init(){return Ec(this,void 0,void 0,(function*(){const e=yield this.managers.appMessagesManager.getGroupsFirstMessage(this.message),t=yield this.managers.appMessagesManager.canViewMessageReadParticipants(e),i=new jr,s=Object.assign(Object.assign({},e),{mid:0,id:0,reactions:Object.assign(Object.assign({_:"messageReactions",results:[]},e.reactions),{pFlags:{},recent_reactions:[]})});s.reactions.results=s.reactions.results.map((e=>Object.assign(Object.assign({},e),{pFlags:{}}))),i.init(s,"block"),i.render(),i.classList.add("no-stripe"),i.classList.remove("has-no-reactions"),i.append(this.btnClose),this.header.append(i);const n=document.createElement("div");n.classList.add("tabs-container"),n.dataset.animation="tabs";const a=new Map;let o=!1;if(s.reactions.results.length){const e=this.createFakeReaction("reactions",s.reactions.results.reduce(((e,t)=>e+t.count),0));i.prepend(e),s.reactions.results.unshift(e.reactionCount),o=!0}let r=!1;if(t)try{const t=yield this.managers.appMessagesManager.getMessageReadParticipants(e.peerId,e.mid);if(!t.length)throw"";const n=this.createFakeReaction("checks",t.length);i.prepend(n),s.reactions.results.unshift(n.reactionCount),r=!0}catch(e){}s.reactions.results.forEach((t=>{const i=new m.ZP(void 0);i.container.classList.add("tabs-tab");const s=new Br({noShadow:!0,noDelimiter:!0}),o=gg.createChatList({dialogSize:72});gg.setListClickListener(o,(()=>{this.hide()}),void 0,!1,!0),s.content.append(o),i.container.append(s.container);const r="checks"!==t.reaction,l="checks"===t.reaction;let c;["checks","reactions"].includes(t.reaction)&&(t.reaction=void 0);const d=new Yi({scrollable:i,getPromise:()=>Ec(this,void 0,void 0,(function*(){const i=yield this.managers.appMessagesManager.getMessageReactionsListAndReadParticipants(e,void 0,t.reaction,c,r,l);return c=i.nextOffset,yield Promise.all(i.combined.map((({peerId:e,reaction:t})=>Ec(this,void 0,void 0,(function*(){const{dom:i}=gg.addDialogNew({peerId:e,autonomous:!0,container:o,avatarSize:54,rippleEnabled:!1,meAsSaved:!1});if(t){const e=document.createElement("div");e.classList.add("reacted-list-reaction-icon"),ta({doc:(yield this.managers.appReactionsManager.getReactionCached(t)).static_icon,div:e,width:24,height:24}),i.listEl.append(e)}(0,g.Z)(i.lastMessageSpan,ce(yield this.managers.appUsersManager.getUser(e.toUserId())))}))))),!c}))});a.set(i.container,d),n.append(i.container)})),this.body.append(n);const l=(0,ue.X)(i,n,((e,t)=>{if(e===i.childElementCount-1)return!1;const s=i.children[e],n=l.prevId();-1!==n&&i.children[n].setIsChosen(!1),s.setIsChosen(!0),a.get(t).load()}),void 0,void 0,void 0,this.listenerSetter);l(0,!1),this.show()}))}createFakeReaction(e,t){const i=new Wr;i.init("block"),i.reactionCount={_:"reactionCount",count:t,reaction:e},i.setCanRenderAvatars(!1),i.renderCounter();const s=document.createElement("div");return s.classList.add("reaction-counter","reaction-sticker-icon","tgico-"+e),i.prepend(s),i}}const kc="btn-menu-reactions-reaction",Tc=!Je.IS_SAFARI;class xc{constructor(e,t,i){this.managers=e,this.type=t,this.onScroll=()=>{this.reactionsMap.forEach(((e,t)=>{this.onScrollProcessItem(t,e)}))},this.onMouseMove=e=>{var t;const i=(0,r.Z)(e.target,kc);if(!i)return;const s=this.reactionsMap.get(i);if(!s)return;if(!(null===(t=s.appear)||void 0===t?void 0:t.paused))return;const n=s.select;n&&n.paused&&(n.autoplay=!0,n.restart())};const s=this.widthContainer=document.createElement("div");s.classList.add("btn-menu-reactions-container"),s.classList.add("btn-menu-reactions-container-"+t);const a=this.container=document.createElement("div");a.classList.add("btn-menu-reactions");const o=this.scrollable="vertical"===t?new m.ZP(void 0):new m.v7(void 0);a.append(o.container),o.onAdditionalScroll=this.onScroll,o.setListeners(),o.container.classList.add("no-scrollbar"),this.reactionsMap=new Map,this.animationGroup=`CHAT-MENU-REACTIONS-${Date.now()}`,p.Z.setOverrideIdleGroup(this.animationGroup,!0),gi.Z||a.addEventListener("mousemove",this.onMouseMove),(0,n.fc)(a,(e=>{const t=(0,r.Z)(e.target,kc);if(!t)return;const i=this.reactionsMap.get(t);i&&this.managers.appReactionsManager.sendReaction(this.message,i.reaction)})),s.append(a),this.middleware=null!=i?i:(0,Ti.k)()}init(e){this.message=e;const t=this.middleware.get(),i=this.managers.appReactionsManager.getAvailableReactionsByMessage(e);(0,Kr.Z)(i,(e=>{if(!t()||!e.length)return;e.forEach((e=>{e.pFlags.premium&&!s.Z.premium||this.renderReaction(e)}));const n=()=>{this.container.classList.add("is-visible")};i instanceof Promise?(0,Be.T2)(n):n()}))}cleanup(){this.middleware.clean(),this.scrollable.removeListeners(),this.reactionsMap.clear(),p.Z.setOverrideIdleGroup(this.animationGroup,!1),p.Z.checkAnimations(!0,this.animationGroup,!0)}canUseAnimations(){return s.Z.settings.animationsEnabled&&!Je.IS_MOBILE}renderReaction(e){const t=document.createElement("div");t.classList.add(kc);const i=document.createElement("div");i.classList.add(kc+"-scale");const s=document.createElement("div");let n;s.classList.add(kc+"-appear"),this.canUseAnimations()&&(n=document.createElement("div"),n.classList.add(kc+"-select","hide"));const a={selectWrapper:n,appearWrapper:s,reaction:e.reaction};this.reactionsMap.set(t,a);const o=this.middleware.get(),r=26*(gi.Z?1:1.25),l={width:r,height:r,skipRatio:1,needFadeIn:!1,withThumb:!1,group:this.animationGroup,middleware:o};if(this.canUseAnimations()){let t=!0;ta(Object.assign({doc:e.appear_animation,div:s,play:!0},l)).then((({render:e})=>e)).then((e=>{(0,ai.Z)(e),a.appear=e,e.addEventListener("enterFrame",(o=>{e.maxFrame===o&&i.then((e=>{(0,ai.Z)(e),s.classList.add("hide"),n.classList.remove("hide"),t&&(a.select=e,t=!1)}),ft.Z)}))}),ft.Z);const i=ta(Object.assign({doc:e.select_animation,div:n},l)).then((({render:e})=>e)).then((e=>((0,ai.Z)(e),hi.Z.waitForFirstFrame(e)))).catch(ft.Z)}else delete l.needFadeIn,delete l.withThumb,ta(Object.assign({doc:e.static_icon,div:s},l));i.append(s),n&&i.append(n),t.append(i),this.scrollable.append(t)}onScrollProcessItem(e,t){const i=e.firstElementChild,s=En(e,this.scrollable.container);let n;if(s)if(s.overflow.left||s.overflow.right){const e=Math.abs(s.rect.left-s.rect.right);n="scale("+Math.min(Math.pow(e,2)/Math.pow(34,2),1)+")"}else n="";else{if(!t.appearWrapper.classList.contains("hide")||!t.appear)return;t.select&&t.select.stop(),t.appear.stop(),t.appear.autoplay=!0,t.appearWrapper.classList.remove("hide"),t.selectWrapper.classList.add("hide"),n=""}Tc&&(i.style.transform=n)}}var _c=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Ac{constructor(e,t){this.chat=e,this.managers=t,this.onContextMenu=e=>{let t,i;try{i=(0,r.Z)(e.target,"bubble-content-wrapper"),t=i?i.parentElement:(0,r.Z)(e.target,"bubble")}catch(e){}if(!t||t.classList.contains("bubble-first"))return;let s=this.element;if((e instanceof MouseEvent||e.hasOwnProperty("preventDefault"))&&e.preventDefault(),s&&s.classList.contains("active"))return!1;(e instanceof MouseEvent||e.hasOwnProperty("cancelBubble"))&&(e.cancelBubble=!0);let n=+t.dataset.mid;n&&(()=>{_c(this,void 0,void 0,(function*(){const a=this.isSponsored=n<0;if(this.isSelectable=this.chat.selection.canSelectBubble(t),this.peerId=this.chat.peerId,this.target=e.target,this.isTextSelected=!Sc(),this.isAnchorTarget="A"===this.target.tagName&&("_blank"===this.target.target||this.target.classList.contains("anchor-url")),this.isUsernameTarget="A"===this.target.tagName&&this.target.classList.contains("mention"),this.chat.selection.isSelecting&&!i){if(a)return;const e=yield this.chat.getMidsByMid(n);if(e.length>1){const t=this.chat.selection.isMidSelected(this.peerId,n)?n:e.find((e=>this.chat.selection.isMidSelected(this.peerId,e)));t&&(n=t)}}this.isOverBubble=!!i;const o=(0,r.Z)(this.target,"grouped-item");this.isTargetAGroupedItem=!!o,this.mid=o?+o.dataset.mid:n,this.isSelected=this.chat.selection.isMidSelected(this.peerId,this.mid),this.message=yield this.chat.getMessage(this.mid),this.noForwards=!a&&!(yield this.managers.appMessagesManager.canForward(this.message)),this.viewerPeerId=void 0,this.canOpenReactedList=void 0;const l=yield this.init();if(!l)return;s=l.element;const{cleanup:c,destroy:d,menuPadding:h,reactionsMenu:u,reactionsMenuPosition:p}=l;let m=!1;if(u){const e="is-visible";if(m=u.container.classList.contains(e),m&&u.container.classList.remove(e),"horizontal"===p){const e=s.offsetWidth,t=(e-8)/34%1,i=.65;if(t<i){const n=e+34*(i-t)|0;s.style.minWidth=n+"px"}}}const g=t.classList.contains("is-in")?"left":"right";xi(e.touches?e.touches[0]:e,s,g,h),u&&(u.widthContainer.style.top=s.style.top,u.widthContainer.style.left=s.style.left,u.widthContainer.style.setProperty("--menu-width",s["vertical"===p?"offsetHeight":"offsetWidth"]+"px"),s.parentElement.append(u.widthContainer),m&&u.container.offsetLeft),Ii.openBtnMenu(s,(()=>{u&&u.container.classList.remove("is-visible"),this.mid=0,this.peerId=void 0,this.target=null,this.viewerPeerId=void 0,this.canOpenReactedList=void 0,c(),setTimeout((()=>{d()}),300)})),m&&u.container.classList.add("is-visible")}))})()},this.onSendScheduledClick=()=>_c(this,void 0,void 0,(function*(){this.chat.selection.isSelecting?(0,n.tH)(this.chat.selection.selectionSendNowBtn):new Ya(this.peerId,yield this.chat.getMidsByMid(this.mid))})),this.onReplyClick=()=>{this.chat.input.initMessageReply(this.mid)},this.onFaveStickerClick=e=>{const t=this.message.media.document.id;this.managers.appStickersManager.faveSticker(t,e)},this.onEditClick=()=>{this.chat.input.initMessageEditing(this.mid)},this.onCopyClick=()=>_c(this,void 0,void 0,(function*(){if(Sc()){const e=this.chat.selection.isSelecting?[...this.chat.selection.selectedMids.get(this.peerId)].sort(((e,t)=>e-t)):[this.mid];Oi((yield Promise.all(e.map((e=>_c(this,void 0,void 0,(function*(){const t=yield this.chat.getMessage(e);return(null==t?void 0:t.message)?t.message+"\n":""})))))).join(""))}else document.execCommand("copy")})),this.onCopyAnchorLinkClick=()=>{Oi(this.target.href)},this.onCopyLinkClick=()=>_c(this,void 0,void 0,(function*(){let e;const{peerId:t,mid:i}=this,s=this.chat.threadId;"discussion"===this.chat.type&&(e=yield this.managers.appMessagesManager.getMessageByPeer(t,s));const n=yield this.managers.appPeersManager.getPeerUsername(e?e.fromId:t),a=(0,ci.Z)(i);let o,r="https://t.me/";n?(r+=n+"/"+(e?(0,ci.Z)(e.fwd_from.channel_post):a),e&&(r+="?comment="+a),o="LinkCopied"):(r+="c/"+t.toChatId()+"/"+a,e&&(r+="?thread="+(0,ci.Z)(e.mid)),o="LinkCopiedPrivateInfo"),Ci(v.ZP.format(o,!0)),Oi(r)})),this.onPinClick=()=>{new wc(this.peerId,this.mid)},this.onUnpinClick=()=>{new wc(this.peerId,this.mid,!0)},this.onRetractVote=()=>{this.managers.appPollsManager.sendVote(this.message,[])},this.onStopPoll=()=>{this.managers.appPollsManager.stopPoll(this.message)},this.onForwardClick=()=>_c(this,void 0,void 0,(function*(){if(this.chat.selection.isSelecting)(0,n.tH)(this.chat.selection.selectionForwardBtn);else{const e=this.peerId,t=this.isTargetAGroupedItem?[this.mid]:yield this.chat.getMidsByMid(this.mid);new ja({[e]:t})}})),this.onSelectClick=()=>{this.chat.selection.toggleByElement((0,r.Z)(this.target,"grouped-item")||(0,r.Z)(this.target,"bubble"))},this.onClearSelectionClick=()=>{this.chat.selection.cancelSelection()},this.onDeleteClick=()=>_c(this,void 0,void 0,(function*(){this.chat.selection.isSelecting?(0,n.tH)(this.chat.selection.selectionDeleteBtn):new Qa(this.peerId,this.isTargetAGroupedItem?[this.mid]:yield this.chat.getMidsByMid(this.mid),this.chat.type)})),this.listenerSetter=new I.Z,this.attachListenerSetter=new I.Z,this.middleware=(0,Ti.k)()}attachTo(e){this.attachListenerSetter.removeAll(),gi.Z?(0,n.fc)(e,(e=>{this.chat.selection.isSelecting||(this.chat.log("touchend",e),!e.target.closest([".name",".peer-title",".reply",".document","audio-element","avatar-element","a",".bubble-beside-button","replies-element","[data-saved-from]:not(.bubble)","poll-element",".attachment",".reply-markup-button"].join(", "))&&((0,a.Z)(e),this.onContextMenu(e)))}),{listenerSetter:this.attachListenerSetter}):Fi(e,this.onContextMenu,this.attachListenerSetter)}cleanup(){this.listenerSetter.removeAll(),this.reactionsMenu&&this.reactionsMenu.cleanup(),this.middleware.clean()}destroy(){this.cleanup(),this.attachListenerSetter.removeAll()}filterButtons(e){return _c(this,void 0,void 0,(function*(){return this.isSponsored?e.filter((e=>e.isSponsored)):ki(e,(e=>_c(this,void 0,void 0,(function*(){let t;return this.chat.selection.isSelecting&&!e.withSelection?t=!1:(this.isOverBubble||gi.Z,t=yield e.verify()),!!t}))))}))}setButtons(){const e=e=>_c(this,void 0,void 0,(function*(){var t;const i=null===(t=this.message.media)||void 0===t?void 0:t.document;if(!(null==i?void 0:i.sticker))return!1;const s=yield this.managers.acknowledged.appStickersManager.getFavedStickersStickers();if(!s.cached)return!1;const n=(yield s.result).some((e=>e.id===i.id));return e?!n:n}));this.buttons=[{icon:"send2",text:"MessageScheduleSend",onClick:this.onSendScheduledClick,verify:()=>"scheduled"===this.chat.type&&!this.message.pFlags.is_outgoing},{icon:"send2",text:"Message.Context.Selection.SendNow",onClick:this.onSendScheduledClick,verify:()=>"scheduled"===this.chat.type&&this.isSelected&&!this.chat.selection.selectionSendNowBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"schedule",text:"MessageScheduleEditTime",onClick:()=>{this.chat.input.scheduleSending((()=>{(0,ai.Z)(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(1e3*this.message.date))},verify:()=>"scheduled"===this.chat.type},{icon:"reply",text:"Reply",onClick:this.onReplyClick,verify:()=>_c(this,void 0,void 0,(function*(){return(yield this.chat.canSend())&&!this.message.pFlags.is_outgoing&&!!this.chat.input.messageInput&&"scheduled"!==this.chat.type}))},{icon:"favourites",text:"AddToFavorites",onClick:this.onFaveStickerClick.bind(this,!1),verify:()=>e(!0)},{icon:"favourites",text:"DeleteFromFavorites",onClick:this.onFaveStickerClick.bind(this,!0),verify:()=>e(!1)},{icon:"edit",text:"Edit",onClick:this.onEditClick,verify:()=>_c(this,void 0,void 0,(function*(){return(yield this.managers.appMessagesManager.canEditMessage(this.message,"text"))&&!!this.chat.input.messageInput}))},{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:"copy",text:"Message.Context.Selection.Copy",onClick:this.onCopyClick,verify:()=>_c(this,void 0,void 0,(function*(){if(!this.isSelected||this.noForwards)return!1;for(const[e,t]of this.chat.selection.selectedMids){const i=`${e}_${"scheduled"===this.chat.type?"scheduled":"history"}`;for(const e of t)if((yield this.managers.appMessagesManager.getMessageFromStorage(i,e)).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:()=>{Oi(this.target.innerHTML)},verify:()=>this.isUsernameTarget,withSelection:!0},{icon:"copy",text:"Text.Context.Copy.Hashtag",onClick:()=>{Oi(this.target.innerHTML)},verify:()=>this.target.classList.contains("anchor-hashtag"),withSelection:!0},{icon:"link",text:"MessageContext.CopyMessageLink1",onClick:this.onCopyLinkClick,verify:()=>_c(this,void 0,void 0,(function*(){return(yield this.managers.appPeersManager.isChannel(this.peerId))&&!this.message.pFlags.is_outgoing}))},{icon:"pin",text:"Message.Context.Pin",onClick:this.onPinClick,verify:()=>_c(this,void 0,void 0,(function*(){return!this.message.pFlags.is_outgoing&&"messageService"!==this.message._&&!this.message.pFlags.pinned&&(yield this.managers.appPeersManager.canPinMessage(this.peerId))&&"scheduled"!==this.chat.type}))},{icon:"unpin",text:"Message.Context.Unpin",onClick:this.onUnpinClick,verify:()=>_c(this,void 0,void 0,(function*(){return this.message.pFlags.pinned&&(yield this.managers.appPeersManager.canPinMessage(this.peerId))}))},{icon:"download",text:"MediaViewer.Context.Download",onClick:()=>{u.Z.downloadToDisc({media:this.message.media.document})},verify:()=>{var e;if(this.message.pFlags.is_outgoing)return!1;const t=null===(e=this.message.media)||void 0===e?void 0:e.document;if(!t)return!1;let i=!!gi.Z;const s=!t.type||!["gif","video"].includes(t.type);return s&&(i||(i=!!(0,r.Z)(this.target,"document")||!!(0,r.Z)(this.target,"audio")||!!(0,r.Z)(this.target,"media-sticker-wrapper"))),s&&i}},{icon:"checkretract",text:"Chat.Poll.Unvote",onClick:this.onRetractVote,verify:()=>{var e;const t=null===(e=this.message.media)||void 0===e?void 0:e.poll;return t&&t.chosenIndexes.length&&!t.pFlags.closed&&!t.pFlags.quiz}},{icon:"stop",text:"Chat.Poll.Stop",onClick:this.onStopPoll,verify:()=>_c(this,void 0,void 0,(function*(){var e;const t=null===(e=this.message.media)||void 0===e?void 0:e.poll;return(yield this.managers.appMessagesManager.canEditMessage(this.message,"poll"))&&t&&!t.pFlags.closed&&!this.message.pFlags.is_outgoing}))},{icon:"forward",text:"Forward",onClick:this.onForwardClick,verify:()=>!(this.noForwards||"scheduled"===this.chat.type||this.message.pFlags.is_outgoing&&this.message.fromId!==le.yF||"messageService"===this.message._)},{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:"flag",text:"ReportChat",onClick:()=>{new Ic(this.peerId,[this.mid])},verify:()=>_c(this,void 0,void 0,(function*(){return!this.message.pFlags.out&&"message"===this.message._&&!this.message.pFlags.is_outgoing&&(yield this.managers.appPeersManager.isChannel(this.peerId))})),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.chat.appImManager.setInnerPeer({peerId:this.viewerPeerId});else{if(!this.canOpenReactedList)return!1;new Pc(this.message)}},verify:()=>_c(this,void 0,void 0,(function*(){var e,t;return!this.peerId.isUser()&&(!!(null===(t=null===(e=this.message.reactions)||void 0===e?void 0:e.recent_reactions)||void 0===t?void 0:t.length)||(yield this.managers.appMessagesManager.canViewMessageReadParticipants(this.message)))})),notDirect:()=>!0},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>_c(this,void 0,void 0,(function*(){return this.managers.appMessagesManager.canDeleteMessage(this.message)}))},{icon:"delete 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:()=>{new Mc},verify:()=>!1,isSponsored:!0}]}init(){return _c(this,void 0,void 0,(function*(){this.cleanup(),this.setButtons();const e=yield this.filterButtons(this.buttons);if(!e.length)return;const t=this.element=Ei(e,this.listenerSetter);t.id="bubble-contextmenu",t.classList.add("contextmenu");const i=e.find((e=>!e.icon));if(i){const e=this.message.reactions,t=null==e?void 0:e.recent_reactions,s=!!(null==t?void 0:t.length),n=(yield this.managers.appMessagesManager.canViewMessageReadParticipants(this.message))?(yield this.managers.appPeersManager.getPeer(this.peerId)).participants_count:void 0,a=e?e.results.reduce(((e,t)=>e+t.count),0):void 0;i.element.classList.add("tgico-"+(s?"reactions":"checks"));const o=new v.ZP.IntlElement({key:s?void 0===n?"Chat.Context.ReactedFast":"Chat.Context.Reacted":"NobodyViewed",args:s?void 0===n?[a]:[n,n]:void 0,element:i.textElement});let r;r=s?void 0===n?(0,v.ag)("Chat.Context.ReactedFast",[a]):(0,v.ag)(t.length===n?"Chat.Context.ReactedFast":"Chat.Context.Reacted",[t.length,n]):(0,v.ag)("Loading"),r.classList.add("btn-menu-item-text-fake"),i.element.append(r);const l=22,c=3,d=1.125;o.element.style.visibility="hidden",o.element.style.paddingRight=s?d*Math.min(c,t.length)+"rem":"1rem";const h=this.middleware.get();this.managers.appMessagesManager.getMessageReactionsListAndReadParticipants(this.message).then((e=>{if(!h())return;r&&r.remove();const a=e.combined,u=void 0===n?e.reactionsCount:s?a.filter((e=>e.reaction)).length:a.length;let p;if(1===a.length)p=new Ot({peerId:a[0].peerId,onlyFirstName:!0,dialog:!1}).element,(!s||e.readParticipants.length<=1)&&(this.viewerPeerId=a[0].peerId);else if(s){const e=u===a.length||void 0===n;p=(0,v.ag)(e?"Chat.Context.ReactedFast":"Chat.Context.Reacted",e?[u]:[u,a.length])}else a.length?p=(0,v.ag)("MessageSeen",[a.length]):o.element.style.visibility="";if(p&&(p.style.paddingRight=d*Math.min(c,u)+"rem",p.classList.add("btn-menu-item-text-fake"),i.element.append(p)),a.length){const e=new na({avatarSize:l});e.render(t?t.map((e=>(0,es.Z)(e.peer_id))):a.map((e=>e.peerId))),i.element.append(e.container),this.canOpenReactedList=!0}}))}let s,n,a;if("message"===this.message._&&!this.chat.selection.isSelecting&&!this.message.pFlags.is_outgoing&&!this.message.pFlags.is_scheduled){a=Je.IS_APPLE||gi.Z?"horizontal":"vertical",n=this.reactionsMenu=new xc(this.managers,a,this.middleware),n.init(yield this.managers.appMessagesManager.getGroupsFirstMessage(this.message));const e=44,t=0,i=0;s="vertical"===a?{top:t,left:e}:{top:e,right:i,left:t}}return this.chat.container.append(t),{element:t,cleanup:()=>{this.cleanup(),n&&n.cleanup()},destroy:()=>{t.remove(),n&&n.widthContainer.remove()},menuPadding:s,reactionsMenu:n,reactionsMenuPosition:a}}))}}var Zc=i(4329),Fc=i.n(Zc),Dc=i(9043);class Rc{constructor(e){this.sendMenuButtons=[{icon:"mute",text:"Chat.Send.WithoutSound",onClick:e.onSilentClick,verify:()=>"schedule"===this.type},{icon:"schedule",text:"Chat.Send.ScheduledMessage",onClick:e.onScheduleClick,verify:()=>"schedule"===this.type},{icon:"schedule",text:"Chat.Send.SetReminder",onClick:e.onScheduleClick,verify:()=>"reminder"===this.type}],this.sendMenu=Ei(this.sendMenuButtons,e.listenerSetter),this.sendMenu.classList.add("menu-send",e.openSide),Fi(e.onContextElement,(t=>{e.onOpen&&!e.onOpen()||(this.sendMenuButtons.forEach((e=>{e.element.classList.toggle("hide",!e.verify())})),(0,a.Z)(t),Ii.openBtnMenu(this.sendMenu))}),e.listenerSetter)}setPeerId(e){this.type=e===s.Z.myId?"reminder":"schedule"}}var Bc=i(3735),Nc=i(1293),Uc=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Oc extends A.Z{constructor(e){super("popup-create-poll popup-new-media",{closable:!0,withConfirm:"Create",body:!0,title:"NewPoll"}),this.chat=e,this.tempId=0,this.onSubmitClick=()=>{this.send()},this.onInput=e=>{const t=e.target,i=(0,l.Z)(t,"LABEL"),s=(0,Nc.Z)(t);s||(t.parentElement.classList.add("is-filled"),i.classList.remove("hidden-widget"),i.firstElementChild.removeAttribute("disabled")),!i.nextElementSibling&&!s&&this.questions.childElementCount<10&&this.appendMoreField(),this.handleChange()},this.onDeleteClick=e=>{const t=e.target,i=(0,l.Z)(t,"LABEL"),s=(0,Cn.Z)(i);this.correctAnswers&&this.correctAnswers[0][0]===s&&(this.correctAnswers=void 0),i.remove(),this.optionInputFields.splice(s,1),this.optionInputFields.forEach(((e,t)=>{e.options.labelOptions.length=0,e.options.labelOptions.push(t+1),v.ZP.weakMap.get(e.label.firstElementChild).update()})),this.handleChange()},this.construct()}construct(){return Uc(this,void 0,void 0,(function*(){if(this.questionInputField=new b.Z({placeholder:"AskAQuestion",label:"AskAQuestion",name:"question",maxLength:255}),this.listenerSetter.add(this.questionInputField.input)("input",(()=>{this.handleChange()})),this.optionInputFields=[],"scheduled"!==this.chat.type){const e=new Rc({onSilentClick:()=>{this.chat.input.sendSilent=!0,this.send()},onScheduleClick:()=>{this.chat.input.scheduleSending((()=>{this.send()}))},openSide:"bottom-left",onContextElement:this.btnConfirm});e.setPeerId(this.chat.peerId),this.header.append(e.sendMenu)}this.header.append(this.questionInputField.container);const e=document.createElement("hr"),t=document.createElement("div");t.classList.add("caption"),(0,v.$d)(t,"PollOptions"),this.questions=document.createElement("form"),this.questions.classList.add("poll-create-questions");const i=document.createElement("div");i.classList.add("poll-create-settings");const s=document.createElement("div");s.classList.add("caption"),(0,v.$d)(s,"Settings"),(yield this.chat.managers.appPeersManager.isBroadcast(this.chat.peerId))||(this.anonymousCheckboxField=new ji.Z({text:"NewPoll.Anonymous",name:"anonymous"}),this.anonymousCheckboxField.input.checked=!0,i.append(this.anonymousCheckboxField.label)),this.multipleCheckboxField=new ji.Z({text:"NewPoll.MultipleChoice",name:"multiple"}),this.quizCheckboxField=new ji.Z({text:"NewPoll.Quiz",name:"quiz"}),this.listenerSetter.add(this.multipleCheckboxField.input)("change",(()=>{const e=this.multipleCheckboxField.input.checked;this.quizCheckboxField.input.toggleAttribute("disabled",e)})),this.listenerSetter.add(this.quizCheckboxField.input)("change",(()=>{const e=this.quizCheckboxField.input.checked;Array.from(this.questions.children).map((t=>{t.classList.toggle("radio-field",e)})),e||(this.correctAnswers=void 0,this.quizSolutionField.setValueSilently("")),a.forEach((t=>t.classList.toggle("hide",!e))),this.multipleCheckboxField.input.toggleAttribute("disabled",e),this.handleChange()})),i.append(this.multipleCheckboxField.label,this.quizCheckboxField.label);const a=[],o=document.createElement("div");o.classList.add("caption"),(0,v.$d)(o,"AccDescrQuizExplanation");const r=document.createElement("hr"),l=document.createElement("div");l.classList.add("poll-create-questions"),this.quizSolutionField=new b.Z({placeholder:"NewPoll.Explanation.Placeholder",label:"NewPoll.Explanation.Placeholder",name:"solution",maxLength:200}),this.listenerSetter.add(this.questionInputField.input)("input",(()=>{this.handleChange()}));const c=document.createElement("div");c.classList.add("subtitle"),(0,v.$d)(c,"AddAnExplanationInfo"),l.append(this.quizSolutionField.container,c),a.push(r,o,l),a.forEach((e=>e.classList.add("hide"))),this.body.parentElement.insertBefore(e,this.body),this.body.append(t,this.questions,document.createElement("hr"),s,i,...a),(0,n.fc)(this.btnConfirm,this.onSubmitClick,{listenerSetter:this.listenerSetter}),this.scrollable=new m.ZP(this.body),this.appendMoreField(),this.onEscape=()=>!this.getFilledAnswers().length,this.handleChange()}))}getFilledAnswers(){return Array.from(this.questions.children).map(((e,t)=>{const i=e.querySelector(".input-field-input");return i instanceof HTMLInputElement?i.value:(0,Bc.Z)(i,!1).value})).filter((e=>!!e.trim()))}validate(){var e;const t=this.questionInputField.value;if(!t)return!1;if(t.length>255)return!1;if(this.quizCheckboxField.input.checked&&!(null===(e=this.correctAnswers)||void 0===e?void 0:e.length))return!1;const i=this.getFilledAnswers();if(i.length<2)return!1;if(i.find((e=>e.length>100)))return!1;const{value:s}=(0,Bc.Z)(this.quizSolutionField.input,!1);return!(s.length>200)}handleChange(){const e=this.validate();this.btnConfirm.toggleAttribute("disabled",!e)}send(e=!1){return Uc(this,void 0,void 0,(function*(){const t=this.questionInputField.value,i=this.getFilledAnswers(),{value:s,entities:n}=(0,Bc.Z)(this.quizSolutionField.input);if("scheduled"===this.chat.type&&!e)return void this.chat.input.scheduleSending((()=>{this.send(!0)}));this.hide();const a={};this.anonymousCheckboxField&&!this.anonymousCheckboxField.input.checked&&(a.public_voters=!0),this.multipleCheckboxField.input.checked&&(a.multiple_choice=!0),this.quizCheckboxField.input.checked&&(a.quiz=!0);const o={_:"poll",pFlags:a,question:t,answers:i.map(((e,t)=>({_:"pollAnswer",text:e,option:new Uint8Array([t])}))),id:void 0},r=yield this.chat.managers.appPollsManager.getInputMediaPoll(o,this.correctAnswers,s,n);this.chat.managers.appMessagesManager.sendOther(this.chat.peerId,r,Object.assign({},this.chat.getMessageSendingParams())),"reply"===this.chat.input.helperType&&this.chat.input.clearHelper(),this.chat.input.onMessageSent(!1,!1)}))}appendMoreField(){const e=this.tempId++,t=this.questions.childElementCount+1,i=new b.Z({placeholder:"NewPoll.OptionsAddOption",label:"NewPoll.OptionLabel",labelOptions:[t],name:"question-"+e,maxLength:100});this.listenerSetter.add(i.input)("input",this.onInput);const s=new Vi({text:"",name:"question"});s.main.append(i.container),(0,n.fc)(i.input,a.Z,{listenerSetter:this.listenerSetter}),s.label.classList.add("hidden-widget"),s.input.disabled=!0,this.quizCheckboxField.input.checked||s.label.classList.remove("radio-field"),this.listenerSetter.add(s.input)("change",(()=>{if(s.input.checked){const e=(0,Cn.Z)(s.label);this.correctAnswers=[new Uint8Array([e])],this.handleChange()}}));const o=document.createElement("span");o.classList.add("btn-icon","tgico-close"),i.container.append(o),(0,n.fc)(o,this.onDeleteClick,{listenerSetter:this.listenerSetter,once:!0}),this.questions.append(s.label),this.scrollable.scrollIntoViewNew({element:this.questions.lastElementChild,position:"center"}),this.optionInputFields.push(i)}}function Hc(e){let t,i;return e instanceof HTMLVideoElement?(t=e.videoWidth,i=e.videoHeight):(t=e.naturalWidth,i=e.naturalHeight),Yo({media:e,mediaSize:(0,ot.C)(t,i),boxSize:(0,ot.C)(320,240),quality:.9})}function zc(e){const t=e.src;return fetch(t).then((e=>e.arrayBuffer())).then((e=>{const t=new Uint8Array(e);let i=0;for(let e=0,s=t.length;e<s;++e)if(33==t[e]&&249==t[e+1]&&4==t[e+2]&&0==t[e+7]){const s=t[e+5]<<8|255&t[e+4];i+=s<2?10:s}return i/1e3}))}var Gc=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};let Vc;function Kc(){return Vc}class Wc extends A.Z{constructor(e,t,i){super("popup-send-photo popup-new-media",{closable:!0,withConfirm:"Modal.Send",confirmShortcutIsSendShortcut:!0,body:!0,title:!0}),this.chat=e,this.files=t,this.onKeyDown=e=>{const t=e.target;if(t!==this.input){if("INPUT"===t.tagName||t.hasAttribute("contenteditable"))return;this.input.focus(),(0,bl.Z)(this.input)}},this.attachFile=e=>{const t=this.willAttach,i=this.shouldCompress(e.type),s={};s.file=e;const n=document.createElement("div");n.classList.add("popup-item"),s.itemDiv=n;const a=i?this.attachMedia(s,n):this.attachDocument(s,n);return t.sendFileDetails.push(s),a},this.construct(i)}construct(e){return Gc(this,void 0,void 0,(function*(){this.willAttach={type:e,sendFileDetails:[],group:!1};const t=yield this.managers.apiManager.getConfig();if(this.captionLengthMax=t.caption_length_max,(0,n.fc)(this.btnConfirm,(()=>this.send()),{listenerSetter:this.listenerSetter}),"scheduled"!==this.chat.type){const e=new Rc({onSilentClick:()=>{this.chat.input.sendSilent=!0,this.send()},onScheduleClick:()=>{this.chat.input.scheduleSending((()=>{this.send()}))},openSide:"bottom-left",onContextElement:this.btnConfirm,listenerSetter:this.listenerSetter});e.setPeerId(this.chat.peerId),this.header.append(e.sendMenu)}this.mediaContainer=document.createElement("div"),this.mediaContainer.classList.add("popup-photo");const i=new m.ZP(null);i.container.append(this.mediaContainer),this.inputField=new b.Z({placeholder:"PreviewSender.CaptionPlaceholder",label:"Caption",name:"photo-caption",maxLength:this.captionLengthMax,withLinebreaks:!0}),this.input=this.inputField.input,this.inputField.value=this.wasInputValue=this.chat.input.messageInputField.input.innerHTML,this.chat.input.messageInputField.value="",this.body.append(i.container),this.container.append(this.inputField.container),this.attachFiles(),this.addEventListener("close",(()=>{this.files=[],Vc=void 0})),Vc=this}))}appendDrops(e){this.body.append(e)}get type(){return this.willAttach.type}set type(e){this.willAttach.type=e}appendGroupCheckboxField(){var e;const t=this.files.length>1;t&&!this.groupCheckboxField?(this.groupCheckboxField=new ji.Z({text:"PreviewSender.GroupItems",name:"group-items"}),this.container.append(...[this.groupCheckboxField.label,null===(e=this.mediaCheckboxField)||void 0===e?void 0:e.label,this.inputField.container].filter(Boolean)),this.willAttach.group=!0,this.groupCheckboxField.setValueSilently(this.willAttach.group),this.listenerSetter.add(this.groupCheckboxField.input)("change",(()=>{const e=this.groupCheckboxField.checked;this.willAttach.group=e,this.attachFiles()}))):this.groupCheckboxField&&this.groupCheckboxField.label.classList.toggle("hide",!t)}appendMediaCheckboxField(){var e;const t=!!this.files.find((e=>o.Z.has(e.type)));t&&!this.mediaCheckboxField?(this.mediaCheckboxField=new ji.Z({text:"PreviewSender.CompressFile",name:"compress-items"}),this.container.append(...[null===(e=this.groupCheckboxField)||void 0===e?void 0:e.label,this.mediaCheckboxField.label,this.inputField.container].filter(Boolean)),this.mediaCheckboxField.setValueSilently("media"===this.willAttach.type),this.listenerSetter.add(this.mediaCheckboxField.input)("change",(()=>{const e=this.mediaCheckboxField.checked;this.willAttach.type=e?"media":"document",this.attachFiles()}))):this.mediaCheckboxField&&this.mediaCheckboxField.label.classList.toggle("hide",!t)}addFiles(e){const t=e.filter((e=>!this.files.find((t=>t.lastModified===e.lastModified&&t.name===e.name&&t.size===e.size))));t.length&&(this.files.push(...t),this.attachFiles())}send(e=!1){if("scheduled"===this.chat.type&&!e)return void this.chat.input.scheduleSending((()=>{this.send(!0)}));let t=this.inputField.value;if(t.length>this.captionLengthMax)return void Ci(v.ZP.format("Error.PreviewSender.CaptionTooLong",!0));this.hide();const i=this.willAttach;i.isMedia="media"===i.type||void 0;const{sendFileDetails:s,isMedia:n}=i,{peerId:a,input:o}=this.chat;s.forEach((e=>{e.itemDiv=void 0}));const{length:r}=s,l=this.chat.getMessageSendingParams();this.iterate((e=>{t&&e.length!==r&&(this.managers.appMessagesManager.sendText(a,t,Object.assign(Object.assign({},l),{clearDraft:!0})),t=void 0);const s=Object.assign(Object.assign({},i),{sendFileDetails:e});this.managers.appMessagesManager.sendAlbum(a,s.sendFileDetails.map((e=>e.file)),Object.assign(Object.assign(Object.assign({},l),{caption:t,isMedia:n,clearDraft:!0}),s)),t=void 0})),o.replyToMsgId=this.chat.threadId,o.onMessageSent()}attachMedia(e,t){return Gc(this,void 0,void 0,(function*(){t.classList.add("popup-item-media");const i=e.file;let s;if(i.type.startsWith("video/")){const n=ut(),a=document.createElement("source");a.src=e.objectURL=yield Gi.Z.invoke("createObjectURL",i),n.autoplay=!0,n.controls=!1,n.muted=!0,n.addEventListener("timeupdate",(()=>{n.pause()}),{once:!0}),s=(0,pt.Z)(n).then((()=>Gc(this,void 0,void 0,(function*(){e.width=n.videoWidth,e.height=n.videoHeight,e.duration=Math.floor(n.duration);const i=n.webkitAudioDecodedByteCount;void 0!==i&&(e.noSound=!i),t.append(n);const s=yield function(e){return new Promise(((t,i)=>{e.onseeked=()=>{e.onseeked=()=>{Hc(e).then(t),e.onseeked=void 0},e.currentTime=0},e.onerror=i,e.currentTime=Math.min(e.duration,1)}))}(n);e.thumb=Object.assign({url:yield Gi.Z.invoke("createObjectURL",s.blob)},s)})))),n.append(a)}else{const n=new Image;s=new Promise((s=>{n.onload=()=>{e.width=n.naturalWidth,e.height=n.naturalHeight,t.append(n),"image/gif"===i.type?(e.noSound=!0,Promise.all([zc(n).then((t=>{e.duration=Math.ceil(t)})),Hc(n).then((t=>Gc(this,void 0,void 0,(function*(){e.thumb=Object.assign({url:yield Gi.Z.invoke("createObjectURL",t.blob)},t)}))))]).then((()=>{s()}))):s()}})),n.src=e.objectURL=yield Gi.Z.invoke("createObjectURL",i)}return s}))}attachDocument(e,t){return Gc(this,void 0,void 0,(function*(){t.classList.add("popup-item-document");const i=e.file,s=i.type.startsWith("image/"),n=i.type.startsWith("audio/");(s||n||i.size<2e7)&&(e.objectURL=yield Gi.Z.invoke("createObjectURL",i));const a={_:"document",file:i,file_name:i.name||"",size:i.size,type:s?"photo":"doc"};let o;e.objectURL&&(o={url:e.objectURL,downloaded:i.size,type:"full"});const r=yield ti({message:{_:"message",pFlags:{is_outgoing:!0},mid:0,peerId:0,media:{_:"messageMediaDocument",document:a}},cacheContext:o});return new Promise((i=>{const n=()=>{t.append(r),i()};if(s){const t=new Image;t.src=e.objectURL,t.onload=()=>{e.width=t.naturalWidth,e.height=t.naturalHeight,n()},t.onerror=n}else n()}))}))}shouldCompress(e){return"media"===this.willAttach.type&&o.Z.has(e)}onRender(){this.element.classList.contains("active")||(this.listenerSetter.add(document.body)("keydown",this.onKeyDown),this.addEventListener("close",(()=>{this.wasInputValue&&(this.chat.input.messageInputField.value=this.wasInputValue)})),this.show())}setTitle(){const{willAttach:e,title:t,files:i}=this;let s;const n=[];if("document"===e.type)s="PreviewSender.SendFile",n.push(i.length);else{let e=0,t=0,a=0;i.forEach((i=>{i.type.startsWith("image/")?++e:i.type.startsWith("video/")?++t:++a})),[e,t,a].filter((e=>e>0)).length>1?(s="PreviewSender.SendFile",n.push(i.length)):e?(s="PreviewSender.SendPhoto",n.push(e)):t&&(s="PreviewSender.SendVideo",n.push(t))}(0,g.Z)(t,(0,v.ag)(s,n))}appendMediaToContainer(e,t){if(this.shouldCompress(t.file.type)){const i=(0,Ce.Z)(t.width,t.height,380,320);e.style.width=i.width+"px",e.style.height=i.height+"px"}this.mediaContainer.append(e)}iterate(e){const{sendFileDetails:t}=this.willAttach;if(!this.willAttach.group)return void t.forEach((t=>e([t])));const i=t.length;for(let s=0;s<i;){const n=t[s].file.type;let a=0;for(;a<10&&s<i;++s,++a){const e=t[s].file.type;if(this.shouldCompress(n)!==this.shouldCompress(e))break}e(t.slice(s-a,s))}}attachFiles(){const{files:e,willAttach:t,mediaContainer:i}=this;t.sendFileDetails.length=0,this.appendGroupCheckboxField(),this.appendMediaCheckboxField(),Promise.all(e.map(this.attachFile)).then((()=>{i.innerHTML="",e.length&&(this.setTitle(),this.iterate((e=>{if(this.shouldCompress(e[0].file.type)&&e.length>1){const t=document.createElement("div");t.classList.add("popup-item-album","popup-item"),t.append(...e.map((e=>e.itemDiv))),ke({container:t,items:e.map((e=>({w:e.width,h:e.height}))),maxWidth:380,minWidth:100,spacing:4}),i.append(t)}else e.forEach((e=>{this.appendMediaToContainer(e.itemDiv,e)}))})))})).then((()=>{this.onRender()}))}}const $c="keydown",jc="active",qc=["ArrowUp","ArrowDown"],Qc=["ArrowLeft","ArrowRight"];function Yc({list:e,type:t,onSelect:i,once:s,waitForKey:o}){let l=(null==o?void 0:o.length)?new Set(o):void 0;const c=new Set("xy"===t?qc.concat(Qc):"x"===t?Qc:qc);let d;const h=()=>d||e.querySelector(".active")||e.firstElementChild,u=(e,i)=>{if(d===e)return;let s=!1;d&&(s=!0,d.classList.remove(jc)),d=e,d&&(d.classList.add(jc),s&&v&&i&&(0,ts.Z)({container:v,element:d,position:"center",forceDuration:100,axis:"x"===t?"x":"y"}))},p=(t,i)=>{let s;return s=i?t.nextElementSibling||e.firstElementChild:t.previousElementSibling||e.lastElementChild,s};let m;m="xy"===t?(t,i)=>"ArrowUp"===i||"ArrowDown"===i?((t,i)=>{const s=i?"nextElementSibling":"previousElementSibling",n=i?"firstElementChild":"lastElementChild",a=t.getBoundingClientRect();let o=t[s]||e[n];for(;o!==t;){const t=o.getBoundingClientRect();if(t.x===a.x&&t.y!==a.y)break;o=o[s]||e[n]}return o})(t,"ArrowDown"===i):p(t,"ArrowRight"===i):(e,t)=>p(e,"ArrowRight"===t||"ArrowDown"===t);let g=i=>{const s=i.key;if(c.has(s)){if((0,a.Z)(i),e.childElementCount>1){let e=h();e=m(e,s),u(e,!0)}}else("Enter"===s||"xy"!==t&&"Tab"===s)&&((0,a.Z)(i),b(h()))};const v=(0,r.Z)(e,"scrollable");e.classList.add("navigable-list");const f=t=>{const i=(0,vi.Z)(t.target,e);i&&u(i,!1)},y=t=>{(0,a.Z)(t);const i=(0,vi.Z)(t.target,e);i&&(u(i,!1),b(h()))},b=e=>{return t=this,n=void 0,o=function*(){const t=yield i(e);(void 0!==t?!t:s)&&C()},new((a=void 0)||(a=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function r(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof a?i:new a((function(e){e(i)}))).then(s,r)}l((o=o.apply(t,n||[])).next())}));var t,n,a,o};let w=!1;const S=()=>{w||(w=!0,document.addEventListener($c,g,{capture:!0,passive:!1}),e.addEventListener("mousemove",f,{passive:!0}),(0,n.fc)(e,y))},C=()=>{w&&(w=!1,document.removeEventListener($c,g,{capture:!0}),e.removeEventListener("mousemove",f),(0,n.EN)(e,y))},L=()=>{l||u(e.firstElementChild,!1)};if(l){const e=g;g=t=>{l.has(t.key)&&((0,a.Z)(t),document.removeEventListener($c,g,{capture:!0}),g=e,document.addEventListener($c,g,{capture:!0,passive:!1}),l=void 0,L())}}else L();return S(),{attach:S,detach:C,resetTarget:L}}class Jc extends L.Z{constructor(e){super(!1),this.hidden=!0,this.onVisible=()=>{this.detach&&this.detach();const e=this.list,{attach:t,detach:i,resetTarget:s}=Yc({list:e,type:this.listType,onSelect:this.onSelect,once:!0,waitForKey:this.waitForKey});this.attach=t,this.detach=i,this.resetTarget=s,Je.IS_MOBILE||this.navigationItem||(this.navigationItem={type:"autocomplete-helper",onPop:()=>{this.navigationItem=void 0,this.toggle(!0)},noBlurOnPop:!0},C.Z.pushItem(this.navigationItem)),this.addEventListener("hidden",(()=>{this.resetTarget=void 0,this.attach=void 0,this.detach=void 0,e.innerHTML="",i(),this.navigationItem&&(C.Z.removeItem(this.navigationItem),this.navigationItem=void 0)}),{once:!0})},(0,x.Z)(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&&this.controller.addHelper(this)}toggleListNavigation(e){e?this.attach&&this.attach():this.detach&&this.detach()}attachNavigation(){this.addEventListener("visible",this.onVisible)}toggle(e,t=!1,i){if(this.init)return;if(void 0===e&&(e=this.container.classList.contains("is-visible")&&!this.container.classList.contains("backwards")),this.hidden===e)return void(e||this.dispatchEvent("visible"));this.hidden=e,e?(this.navigationItem&&(C.Z.removeItem(this.navigationItem),this.navigationItem=void 0),!t&&this.controller&&this.controller.hideOtherHelpers(),this.detach&&this.detach()):(this.controller&&this.controller.hideOtherHelpers(this),this.dispatchEvent("visible"));const n=this.controller||e?0:2;e&&this.dispatchEvent("hiding"),Re(this.container,"is-visible",!e,s.Z.settings.animationsEnabled&&!i?300:0,(()=>{this.hidden&&this.dispatchEvent("hidden")}),n)}}class Xc extends Jc{constructor(e,t,i){super({appendTo:e,controller:t,listType:"xy",onSelect:e=>{return t=this,i=void 0,n=function*(){return!(yield zn.onMediaClick({target:e},!0))},new((s=void 0)||(s=Promise))((function(e,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,r)}l((n=n.apply(t,i||[])).next())}));var t,i,s,n},waitForKey:["ArrowUp","ArrowDown"]}),this.managers=i,this.container.classList.add("stickers-helper"),this.addEventListener("visible",(()=>{setTimeout((()=>{this.scrollable.container.scrollTop=0}),0),s.Z.dispatchEvent("choosing_sticker",!0)})),this.addEventListener("hidden",(()=>{this.onChangeScreen&&(d.Z.removeEventListener("changeScreen",this.onChangeScreen),this.onChangeScreen=void 0,this.listenerSetter.removeAll(),this.listenerSetter=void 0),s.Z.dispatchEvent("choosing_sticker",!1)}))}checkEmoticon(e){const t=this.controller.getMiddleware();this.lazyLoadQueue&&this.lazyLoadQueue.clear(),Cc(e),this.managers.appStickersManager.getStickersByEmoticon(e).then((e=>{if(!t())return;this.init&&(this.init(),this.init=null);const i=this.list.cloneNode();let s;this.lazyLoadQueue.clear(),s=e.length?new Promise((t=>{const s=[];e.forEach((e=>{i.append(this.superStickerRenderer.renderSticker(e,void 0,s))})),Promise.all(s).finally(t)})):Promise.resolve(),s.then((()=>{this.list.replaceWith(i),this.list=i,this.onChangeScreen||(this.onChangeScreen=()=>{const e=this.list.childElementCount*d.Z.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=e+"px"},d.Z.addEventListener("changeScreen",this.onChangeScreen),this.listenerSetter=new I.Z,xn({listenTo:this.container,listenerSetter:this.listenerSetter})),this.onChangeScreen(),this.toggle(!e.length),this.scrollable.scrollTop=0}))}))}init(){this.list=document.createElement("div"),this.list.classList.add("stickers-helper-stickers","super-stickers"),this.container.append(this.list),this.scrollable=new m.ZP(this.container),this.lazyLoadQueue=new ye,this.superStickerRenderer=new An(this.lazyLoadQueue,km,this.managers)}}const ed=()=>{const e=new Date;return e.setHours(0,0,0,0),e},td=()=>{const e=new Date;return e.setFullYear(e.getFullYear()+1),e.setDate(e.getDate()-1),e};class id extends Vr{constructor(e,t,i){var s;if(super((s=e).getTime()>td().getTime()?new Date:s,t,{noButtons:!0,noTitle:!0,closable:!0,withConfirm:!0,minDate:ed(),maxDate:td(),withTime:!0,showOverflowMonths:!0,confirmShortcutIsSendShortcut:!0,title:!0}),this.element.classList.add("popup-schedule"),this.header.append(this.controlsDiv),this.title.replaceWith(this.monthTitle),this.body.append(this.btnConfirm),i){const e=(0,M.Z)("btn-primary btn-secondary btn-primary-transparent primary",{text:"Schedule.SendWhenOnline"});this.body.append(e),(0,n.fc)(e,(()=>{t(il),this.hide()}))}}}var sd=i(6299),nd=i(9041),ad=i(6875);function od(e,t=!0){const i=[],s=[],n=window.getSelection();let a,o;if(n&&n.rangeCount){const t=n.getRangeAt(0),i=t.startOffset;if(t.startContainer&&t.startContainer==t.endContainer&&i==t.endOffset){const s=i-1,n=e.childNodes;if(t.startContainer===e&&n[s]){a=n[s],o=0;for(let e=0;e<t.endOffset;++e){const t=n[e],i=t.nodeValue||t.alt;i&&(o+=i.length)}}else a=t.startContainer,o=i}}const r=t?[]:void 0;(0,nd.Z)(e,i,s,a,o,r),s.length&&i.push(s.join(""));let l=i.join("\n");const c=l.indexOf("");return-1!=c&&(l=l.substr(0,c)+l.substr(c+1)),l=l.replace(/\u00A0/g," "),r&&(0,ad.Z)(r),{value:l,entities:r,caretPos:c}}class rd extends Jc{constructor(e,t,i,s){super({appendTo:e,controller:t,listType:"x",onSelect:e=>{i.onEmojiSelected(mn(e),!0)}}),this.managers=s,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 m.v7(this.container),this.addEventListener("visible",(()=>{setTimeout((()=>{this.scrollable.container.scrollLeft=0}),0)}))}render(e,t){if(this.init){if(!e.length)return;this.init(),this.init=null}(e=e.slice(0,80)).length&&(this.list.innerHTML="",e.forEach((e=>{pn(e,this.list,!1,!0)}))),this.waitForKey=t?["ArrowUp","ArrowDown"]:void 0,this.toggle(!e.length)}checkQuery(e,t){const i=this.controller.getMiddleware();this.managers.appEmojiManager.getBothEmojiKeywords().then((()=>{return s=this,n=void 0,o=function*(){if(!i())return;const s=e.replace(/^:/,""),n=yield this.managers.appEmojiManager.searchEmojis(s);i()&&this.render(n,":"!==t)},new((a=void 0)||(a=Promise))((function(e,t){function i(e){try{l(o.next(e))}catch(e){t(e)}}function r(e){try{l(o.throw(e))}catch(e){t(e)}}function l(t){var s;t.done?e(t.value):(s=t.value,s instanceof a?s:new a((function(e){e(s)}))).then(i,r)}l((o=o.apply(s,n||[])).next())}));var s,n,a,o}))}}class ld extends Jc{constructor(e,t,i,s){super({appendTo:e,controller:t,listType:"y",onSelect:s}),this.className=i,this.container.classList.add(ld.BASE_CLASS,i)}init(){this.list=document.createElement("div"),this.list.classList.add(ld.BASE_CLASS+"-list",this.className+"-list"),this.container.append(this.list),this.scrollable=new m.ZP(this.container),this.addEventListener("visible",(()=>{setTimeout((()=>{this.scrollable.container.scrollTop=0}),0)}))}render(e,t){if(this.init){if(!e.length)return;this.init(),this.init=null}e.length&&(this.list.innerHTML="",e.forEach((e=>{const t=ld.listElement({className:this.className,peerId:e.peerId,name:e.name,description:e.description});this.list.append(t)}))),t||this.toggle(!e.length)}static listElement(e){const t=ld.BASE_CLASS_LIST_ELEMENT;e.className+="-list-element";const i=document.createElement("div");i.classList.add(t,e.className),i.dataset.peerId=""+e.peerId;const s=new Wm;s.classList.add("avatar-30",t+"-avatar",e.className+"-avatar"),s.updateWithOptions({isDialog:!1,peerId:e.peerId});const n=document.createElement("div");if(n.classList.add(t+"-name",e.className+"-name"),e.name?(0,c.Z)(n,(0,Zt.Z)(e.name)):n.append(new Ot({peerId:e.peerId,dialog:!1,onlyFirstName:!1,plainText:!1}).element),i.append(s,n),e.description){const s=document.createElement("div");s.classList.add(t+"-description",e.className+"-description"),(0,c.Z)(s,(0,Zt.Z)(e.description)),i.append(s)}return i}}ld.BASE_CLASS="autocomplete-peer-helper",ld.BASE_CLASS_LIST_ELEMENT=ld.BASE_CLASS+"-list-element";var cd=i(5082);function dd(e,t,i){const s=[].concat(t.bot_info);let n;void 0!==i&&(n=new cd.Z({ignoreCase:!0}));const a=new Map;let o;if(s.forEach((t=>{t.commands&&t.commands.forEach((({command:i,description:s},o)=>{const r="/"+i;a.set(i,{peerId:t.user_id?t.user_id.toPeerId(!1):e,command:i,name:r,description:s,index:o}),n&&n.indexObject(i,r)}))})),n){const e=n.search(i);o=Array.from(e).map((e=>a.get(e)))}else o=[...a.values()];return o=o.sort(((e,t)=>a.get(e.command).index-a.get(t.command).index)),o}class hd extends ld{constructor(e,t,i,s){super(e,t,"commands-helper",(e=>{const t=e.querySelector(`.${ld.BASE_CLASS_LIST_ELEMENT}-name`).innerHTML;return i.getReadyToSend((()=>{i.messageInput.innerHTML=t,i.sendMessage(!0)}))})),this.managers=s}checkQuery(e,t){return i=this,s=void 0,a=function*(){if(!(yield this.managers.appUsersManager.isBot(t)))return!1;const i=this.controller.getMiddleware();return this.managers.appProfileManager.getProfileByPeerId(t).then((s=>{if(!i())return;const n=dd(t,s,e);this.render(n)})),!0},new((n=void 0)||(n=Promise))((function(e,t){function o(e){try{l(a.next(e))}catch(e){t(e)}}function r(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(o,r)}l((a=a.apply(i,s||[])).next())}));var i,s,n,a}}class ud{constructor(){this.helpers=new Set,this.middleware=(0,Ti.k)()}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()}}var pd=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class md extends ld{constructor(e,t,i,s){super(e,t,"mentions-helper",(e=>{const t=e.dataset.peerId.toUserId();Promise.resolve(s.appUsersManager.getUser(t)).then((e=>{let t,s="";e.username?s="@"+e.username:(s=e.first_name||e.last_name,t={_:"messageEntityMentionName",length:s.length,offset:0,user_id:e.id}),s+=" ",i.insertAtCaret(s,t)}))})),this.managers=s}checkQuery(e,t,i){const s=e.trim();if(e.length!==s.length)return!1;const n=this.controller.getMiddleware();return this.managers.appProfileManager.getMentions(t&&t.toChatId(),s,i).then((e=>pd(this,void 0,void 0,(function*(){if(!n())return;const t=s.slice(1).toLowerCase(),i=e.map((e=>pd(this,void 0,void 0,(function*(){const i=yield this.managers.appUsersManager.getUser(e);if(!i.username||i.username.toLowerCase()!==t)return{peerId:e,description:i.username?"@"+i.username:void 0}}))));this.render((yield Promise.all(i)).filter(Boolean))})))),!0}}var gd=i(5494),vd=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class fd extends Bn{constructor(e){super({element:document.createElement("div")}),this.onBodyTouchStart=e=>{const t=e.touches[0].target;(0,vi.Z)(t,this.element)||t===this.btnHover||((0,a.Z)(e),this.toggle(!1))},(0,x.Z)(this,e),this.element.classList.add(fd.BASE_CLASS),this.element.style.display="none",this.attachButtonListener(this.btnHover,this.listenerSetter),this.listenerSetter.add(s.Z)("history_reply_markup",(({peerId:e})=>vd(this,void 0,void 0,(function*(){this.peerId===e&&(this.checkAvailability()&&this.isActive()&&(yield this.render()),(0,He.e9)().then((()=>{this.checkForceReply()})))}))))}init(){return this.appendTo.append(this.element),this.listenerSetter.add(this)("open",(()=>vd(this,void 0,void 0,(function*(){yield this.render(),gi.Z&&(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}))})))),(0,n.fc)(this.element,(e=>{const t=(0,r.Z)(e.target,"btn");if(!t)return;const i=t.dataset.type,{peerId:n}=this;"keyboardButtonRequestPhone"===i?In({titleLangKey:"ShareYouPhoneNumberTitle",button:{langKey:"OK"},descriptionLangKey:"AreYouSureShareMyContactInfoBot"}).then((()=>{this.managers.appMessagesManager.sendContact(n,s.Z.myId)})):this.managers.appMessagesManager.sendText(n,t.dataset.text),this.toggle(!1)}),{listenerSetter:this.listenerSetter}),super.init()}checkForceReply(){return vd(this,void 0,void 0,(function*(){const e=yield this.getReplyMarkup();"replyKeyboardForceReply"!==e._||e.pFlags.hidden||e.pFlags.used||(e.pFlags.used=!0,this.chatInput.initMessageReply(e.mid))}))}getReplyMarkup(){var e;return vd(this,void 0,void 0,(function*(){return null!==(e=(yield this.managers.appMessagesManager.getHistoryStorageTransferable(this.peerId)).replyMarkup)&&void 0!==e?e:{_:"replyKeyboardHide"}}))}render(e){return vd(this,void 0,void 0,(function*(){void 0===e&&(e=yield this.getReplyMarkup()),this.element.textContent="";for(const t of e.rows){const e=document.createElement("div");e.classList.add(fd.BASE_CLASS+"-row");for(const i of t.buttons){const t=document.createElement("button");t.classList.add(fd.BASE_CLASS+"-button","btn"),(0,c.Z)(t,(0,Zt.Z)(i.text)),t.dataset.text=i.text,t.dataset.type=i._,e.append(t)}this.element.append(e)}}))}checkAvailability(e){var t;return vd(this,void 0,void 0,(function*(){void 0===e&&(e=yield this.getReplyMarkup());const i="replyKeyboardHide"===e._||!(null===(t=e.rows)||void 0===t?void 0:t.length);return this.btnHover.classList.toggle("hide",i),i&&this.toggle(!1),!i}))}setPeer(e){this.peerId=e,this.checkAvailability(),this.checkForceReply()}}fd.BASE_CLASS="reply-keyboard";var yd=i(7084),bd=i(515);const wd="INLINE-HELPER";class Sd extends Jc{constructor(e,t,i,s){super({appendTo:e,controller:t,listType:"xy",waitForKey:["ArrowUp","ArrowDown"],onSelect:e=>{if(!e)return!1;const{peerId:t,botId:i,queryId:s}=this.list.dataset;return this.chat.input.getReadyToSend((()=>{const n=(0,bd.Z)(s,e.dataset.resultId);this.managers.appInlineBotsManager.sendInlineResult(t.toPeerId(),i,n,Object.assign(Object.assign({},this.chat.getMessageSendingParams()),{clearDraft:!0})),this.chat.input.onMessageSent(!0,!0)}))}}),this.chat=i,this.managers=s,this._checkQuery=(e,t,i)=>{return s=this,a=void 0,r=function*(){const s=this.controller.getMiddleware(),a=yield this.managers.appUsersManager.resolveUsername(t);if(!s())throw"PEER_CHANGED";if("user"!==a._)throw"NOT_A_BOT";const o=this.managers.appInlineBotsManager.getInlineResults(e,a.id,i).then((t=>{if(!s())throw"PEER_CHANGED";this.init&&(this.init(),this.init=null);const i=this.list.cloneNode();i.dataset.peerId=""+e,i.dataset.botId=""+a.id,i.dataset.queryId=""+t.query_id;const o=new bn(null,wd,this.scrollable,!1);this.lazyLoadQueue.clear(),this.superStickerRenderer.clear();const r=[],l=!!t.pFlags.gallery;for(const e of t.results){const t=document.createElement("div");t.classList.add("inline-helper-result"),t.dataset.resultId=e.id;const n=l?void 0:document.createElement("div");if(n&&(n.classList.add("inline-helper-result-preview"),t.append(n)),i.append(t),l)t.classList.add("grid-item");else{n.classList.add("empty"),(0,c.Z)(n,(0,Zt.Z)([...e.title.trim()][0]));const s=document.createElement("div");s.classList.add("inline-helper-result-title"),(0,c.Z)(s,(0,Zt.Z)(e.title));const a=document.createElement("div");a.classList.add("inline-helper-result-description"),(0,c.Z)(a,(0,ii.Z)(e.description,{noCommands:!0,noLinks:!0})),t.append(s,a);const o=document.createElement("div");o.classList.add("inline-helper-separator"),i.append(o)}if("botInlineResult"===e._){if(e.thumb&&0===e.thumb.mime_type.indexOf("image/")){let i;n?(i=document.createElement("div"),n.append(i)):i=t,i.classList.add("media-container"),l&&i.classList.add("no-border-radius"),this.lazyLoadQueue.push({div:t,load:()=>u.Z.download({dcId:4,location:{_:"inputWebFileLocation",access_hash:e.thumb.access_hash,url:e.thumb.url},size:e.thumb.size,mimeType:e.thumb.mime_type}).then((e=>{const t=new Image;t.classList.add("media-photo"),(0,yd.Z)(e).then((e=>{Fe(i,t,e,!0)}))}))})}}else{const i=e.document||e.photo;if(["sticker","gif"].includes(null==i?void 0:i.type)&&l)(0,ai.Z)(i),"gif"===i.type?o.add(i,t):"sticker"===i.type&&(t.classList.add("super-sticker"),this.superStickerRenderer.renderSticker(i,t,r),i.animated&&this.superStickerRenderer.observeAnimated(t));else if(i){const e=l?48:void 0;l&&t.classList.add("no-border-radius"),dt({photo:i,container:l?t:n,boxWidth:e,boxHeight:e,middleware:s,lazyLoadQueue:this.lazyLoadQueue,loadPromises:r})}}}return Promise.all(r).then((()=>{if(!s())return void o.clear();i.classList.toggle("is-gallery",l),i.classList.toggle("super-stickers",l),this.container.classList.toggle("is-gallery",l);const r=this.list.parentElement;if(r.textContent="",t.switch_pm){const i=(0,M.Z)("btn-primary btn-secondary btn-primary-transparent primary");(0,c.Z)(i,(0,Zt.Z)(t.switch_pm.text)),(0,n.fc)(i,(i=>{this.chat.appImManager.setInnerPeer({peerId:e}),this.managers.appInlineBotsManager.switchToPM(e,a.id,t.switch_pm.start_param)})),r.append(i)}r.append(this.list=i),this.gifsMasonry&&this.gifsMasonry.detach(),this.gifsMasonry=o,o.attach(),this.onChangeScreen||(this.onChangeScreen=()=>{if(this.list.classList.contains("is-gallery")){const e=this.list.childElementCount*d.Z.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=e+"px"}else this.list.style.width=""},d.Z.addEventListener("changeScreen",this.onChangeScreen)),this.onChangeScreen(),this.toggle(!t.results.length&&!t.switch_pm),this.scrollable.scrollTop=0}))}));return{user:a,renderPromise:o}},new((o=void 0)||(o=Promise))((function(e,t){function i(e){try{l(r.next(e))}catch(e){t(e)}}function n(e){try{l(r.throw(e))}catch(e){t(e)}}function l(t){var s;t.done?e(t.value):(s=t.value,s instanceof o?s:new o((function(e){e(s)}))).then(i,n)}l((r=r.apply(s,a||[])).next())}));var s,a,o,r},this.container.classList.add("inline-helper"),this.addEventListener("visible",(()=>{setTimeout((()=>{this.scrollable.container.scrollTop=0}),0)})),this.checkQuery=(0,Ki.Z)(this._checkQuery,200,!0,!0),this.addEventListener("hidden",(()=>{this.onChangeScreen&&(d.Z.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 m.ZP(this.container),this.lazyLoadQueue=new ye,this.superStickerRenderer=new An(this.lazyLoadQueue,wd,this.managers)}}var Cd=i(8090);class Ld extends ld{constructor(e,t,i){super(e,void 0,"bot-commands",(e=>{const i=e.querySelector(`.${ld.BASE_CLASS_LIST_ELEMENT}-name`).innerHTML;return t.getReadyToSend((()=>{t.messageInput.innerHTML=i,t.sendMessage(!0),this.toggle(!0)}))})),this.managers=i}setUserId(e,t){var i;if(this.userId!==e||!(null===(i=this.list)||void 0===i?void 0:i.childElementCount))return this.userId=e,(0,Kr.Z)(this.managers.appProfileManager.getProfile(e),(i=>{if(!t())return;const s=dd(e.toPeerId(!1),i),n=50*s.length+8+24;this.container.style.setProperty("--height",n+"px"),this.render(s)}));this.toggle(!1)}}var Id=i(6241),Md=i(6535),Ed=i(2821);function Pd(e){return t=this,i=void 0,n=function*(){return{cached:e.cached,result:e.cached?yield e.result:e.result}},new((s=void 0)||(s=Promise))((function(e,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,r)}l((n=n.apply(t,i||[])).next())}));var t,i,s,n}function kd(e){return e.then(Pd)}var Td=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class xd{constructor(e,t,i){this.managers=e,this.onReady=t,this.onChange=i,this.middleware=(0,Ti.k)(),this.listenerSetter=new I.Z,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","tgico-close");const e=[{text:"SendMessageAsTitle",onClick:void 0}];let t;const i=e=>{e&&(t=this.avatar);const i=this.avatar!==t,s=!e&&i?2:0;Re(this.closeBtn,"is-visible",e,300,void 0,s),i||Re(t,"is-visible",!e,300,void 0,s)};mo({noRipple:!0,listenerSetter:this.listenerSetter,container:this.container},"top-right",e,(()=>{i(!0)}),(()=>{i(!1)})),e[0].element.classList.add("btn-menu-item-header"),this.btnMenu=this.container.firstElementChild,this.btnMenu.classList.add("scrollable","scrollable-y"),this.container.append(this.closeBtn)}updateButtons(e){return Td(this,void 0,void 0,(function*(){const t=e.map(((e,t)=>Td(this,void 0,void 0,(function*(){const i=document.createElement("div"),n=document.createElement("div");return n.classList.add("btn-menu-item-subtitle"),e.isUser()?n.append((0,v.ag)("Chat.SendAs.PersonalAccount")):e===this.peerId?n.append((0,v.ag)("VoiceChat.DiscussionGroup")):n.append(yield cs(e.toChatId())),i.append(new Ot({peerId:e}).element,n),{onClick:t?()=>Td(this,void 0,void 0,(function*(){const t=this.peerId;this.changeSendAsPeerId(e);const i=this.middleware.get(),n=()=>{if(this.sendAsPeerId!==e||!i())return;const t=this.sendAsPeerIds.slice();(0,T.Z)(t,e),t.unshift(e),this.updateButtons(t)};s.Z.settings.animationsEnabled?setTimeout(n,250):n(),this.managers.appMessagesManager.saveDefaultSendAs(t,e)})):void 0,textElement:i}})))),i=yield Promise.all(t),n=Ei(i);i.forEach(((t,i)=>{const s=e[i],n=new Wm;n.classList.add("avatar-26","btn-menu-item-icon"),n.updateWithOptions({peerId:s}),i||n.classList.add("active"),t.element.prepend(n)})),Array.from(this.btnMenu.children).slice(1).forEach((e=>e.remove())),this.btnMenu.append(...Array.from(n.children))}))}updateAvatar(e,t){return Td(this,void 0,void 0,(function*(){const i=this.avatar;if(i&&i.peerId===e)return;i||(t=!0);const s=t?0:2,n=t?0:300,a=this.avatar=new Wm;a.classList.add("new-message-send-as-avatar","avatar-30"),yield a.updateWithOptions({isDialog:!1,peerId:e}),Re(a,"is-visible",!0,n,void 0,s),i&&Re(i,"is-visible",!1,n,(()=>{i.remove()}),s),this.container.append(a)}))}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((e=>e.default_send_as?(0,es.Z)(e.default_send_as):void 0))})))}updateManual(e){return Td(this,void 0,void 0,(function*(){const t=this.peerId;if(this.updatingPromise||!(yield this.managers.appPeersManager.isChannel(t)))return;const i=this.middleware.get((()=>!this.updatingPromise||this.updatingPromise===c)),{container:n}=this,a=t.toChatId(),o=(yield kd(this.getDefaultSendAs())).result,r=e;o instanceof Promise&&(e=void 0);const l=r&&!e,c=this.updatingPromise=(0,Kr.Z)(o,(t=>Td(this,void 0,void 0,(function*(){if(!i()||void 0===t)return;if(yield this.changeSendAsPeerId(t,e),!i())return;this.managers.appChatsManager.getSendAs(a).then((e=>{if(!i())return;const s=e.map((e=>(0,es.Z)(e)));this.sendAsPeerIds=s.slice(),(0,T.Z)(s,t),s.unshift(t),this.updateButtons(s)}));const o=()=>{this.onReady(n,e),this.addedListener||(this.listenerSetter.add(s.Z)("peer_full_update",(e=>{this.peerId===e&&this.update()})),this.addedListener=!0)};if(!l)return o;o()}))));return c.finally((()=>{this.updatingPromise===c&&(this.updatingPromise=void 0)})),l?void 0:c}))}update(e){return this.updateManual(e).then((e=>e&&e()))}setPeerId(e){this.middleware.clean(),this.updatingPromise=void 0,this.peerId=e}destroy(){this.container.remove(),this.setPeerId(),this.listenerSetter.removeAll()}}class _d extends b.Z{constructor(e){super(e),this.input.addEventListener("input",(()=>{this.inputFake.innerHTML=this.input.innerHTML,this.onFakeInput()})),e.placeholder&&(0,v.$d)(this.inputFake,e.placeholder,void 0,"placeholder"),this.input.classList.add("scrollable","scrollable-y"),this.inputFake=document.createElement("div"),this.inputFake.setAttribute("contenteditable","true"),this.inputFake.className=this.input.className+" input-field-input-fake"}onFakeInput(e=!0){const{scrollHeight:t}=this.inputFake,i=+this.input.style.height.replace("px","");if(i===t)return;const s=Math.round(50*Math.log(Math.abs(t-i)));this.input.style.transitionDuration=`${s}ms`,e&&(this.input.style.height=t?t+"px":"");const n="is-changing-height";Re(this.input,n,!0,s,(()=>{this.input.classList.remove(n)}))}setValueSilently(e,t){super.setValueSilently(e,t),this.inputFake.innerHTML=e,t||this.onFakeInput()}}var Ad=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const Zd="Posting media content isn't allowed in this group.";class Fd{constructor(e,t,i){this.chat=e,this.appImManager=t,this.managers=i,this.lastUrl="",this.lastTimeType=0,this.replyElements={},this.willSendWebPage=null,this.recording=!1,this.recordCanceled=!1,this.recordStartTime=0,this.lockRedo=!1,this.canRedoFromHTML="",this.undoHistory=[],this.executedHistory=[],this.canUndoFromHTML="",this.onCancelRecordClick=e=>{e&&(0,a.Z)(e),this.recordCanceled=!0,this.recorder.stop(),Dc.Z.setKeepAlive(!1)},this.onEmoticonsOpen=()=>{const e=gi.Z?"flip-icon":"active";this.btnToggleEmoticons.classList.toggle(e,!0)},this.onEmoticonsClose=()=>{const e=gi.Z?"flip-icon":"active";this.btnToggleEmoticons.classList.toggle(e,!1)},this.scheduleSending=(e=this.sendMessage.bind(this,!0),t=new Date)=>Ad(this,void 0,void 0,(function*(){const{peerId:i}=this.chat,n=this.chat.bubbles.getMiddleware(),a=s.Z.myId!==i&&i.isUser()&&(yield this.managers.appUsersManager.isUserOnlineVisible(i));new id(t,(t=>{n()&&(t<=10+(Date.now()/1e3|0)&&(t=void 0),this.scheduleDate=t,e(),"scheduled"!==this.chat.type&&t&&setTimeout((()=>{n()&&(A.Z.getPopups(qn).forEach((e=>e.hide())),this.appImManager.openScheduled(i))}),0))}),a).show()})),this.prepareDocumentExecute=()=>(this.executedHistory.push(this.messageInput.innerHTML),()=>this.canUndoFromHTML=this.messageInput.innerHTML),this.undoRedo=(e,t,i)=>{(0,a.Z)(e);let s=this.messageInput.innerHTML;if(s&&s!==i){this.lockRedo=!0;let e=0;do{document.execCommand(t,!1,null);const i=this.messageInput.innerHTML;if(s===i){if(++e>2)break}else e=0;s=i}while(s!==i);this.lockRedo=!1}},this.handleMarkdownShortcut=e=>{const t={KeyB:"bold",KeyI:"italic",KeyU:"underline",KeyS:"strikethrough",KeyM:"monospace",KeyP:"spoiler"};this.appImManager.markupTooltip&&(t.KeyK="link");const i=e.code,s=t[i];if(document.getSelection().toString().trim().length&&s&&("KeyK"===i?this.appImManager.markupTooltip.showLinkEditor():this.applyMarkdown(s),(0,a.Z)(e)),"KeyZ"===i){let t=this.messageInput.innerHTML;e.shiftKey?this.undoHistory.length&&(this.executedHistory.push(t),t=this.undoHistory.pop(),this.undoRedo(e,"redo",t),t=this.messageInput.innerHTML,this.canRedoFromHTML=this.undoHistory.length?t:"",this.canUndoFromHTML=t):!this.executedHistory.length||this.canUndoFromHTML&&t!==this.canUndoFromHTML||(this.undoHistory.push(t),t=this.executedHistory.pop(),this.undoRedo(e,"undo",t),this.canUndoFromHTML=this.canRedoFromHTML=this.messageInput.innerHTML)}},this.onMessageInput=e=>{var t;const{value:i,entities:s,caretPos:n}=od(this.messageInputField.input),a=(0,Ed.Z)(i,s,!0),o=(0,Id.Z)(s,(0,Md.Z)(a));this.canRedoFromHTML&&!this.lockRedo&&this.messageInput.innerHTML!==this.canRedoFromHTML&&(this.canRedoFromHTML="",this.undoHistory.length=0);const r=(!(null===(t=this.editMessage)||void 0===t?void 0:t.media)||"messageMediaWebPage"===this.editMessage.media._)&&o.filter((e=>"messageEntityUrl"===e._||"messageEntityTextUrl"===e._));if(r.length)for(const e of r){let t;if("messageEntityTextUrl"===e._)t=e.url;else if(t=i.slice(e.offset,e.offset+e.length),!t.includes("http://")&&!t.includes("https://"))continue;if(this.lastUrl!==t){this.lastUrl=t;const e=this.getWebPagePromise=this.managers.appWebPagesManager.getWebPage(t).then((i=>{this.getWebPagePromise===e&&(this.getWebPagePromise=void 0),this.lastUrl===t&&("webPage"===i._?(this.setTopInfo("webpage",(()=>{}),i.site_name||i.title||"Webpage",i.description||i.url||""),delete this.noWebPage,this.willSendWebPage=i):this.willSendWebPage&&this.onHelperCancel())}))}break}else this.lastUrl&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null,this.helperType?this.helperFunc():this.clearHelper());if(i.trim()){const e=Date.now();e-this.lastTimeType>=6e3&&(this.lastTimeType=e,this.managers.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageTypingAction"})),this.botCommands&&this.botCommands.toggle(!0)}else this.lastTimeType&&this.managers.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageCancelAction"}),this.appImManager.markupTooltip&&this.appImManager.markupTooltip.hide(),document.activeElement===this.messageInput&&setTimeout((()=>{document.activeElement===this.messageInput&&this.resetCurrentFontFormatting()}),0);this.botCommands&&this.updateBotCommandsToggle(),this.editMsgId||this.saveDraftDebounced(),this.checkAutocomplete(i,n,o),this.updateSendBtn()},this.onEmojiSelected=(e,t)=>{this.insertAtCaret(e,hn(e),t)},this.onBtnSendClick=e=>Ad(this,void 0,void 0,(function*(){if((0,a.Z)(e),!this.recorder||this.recording||!this.isInputEmpty()||this.forwarding||this.editMsgId)this.recording?Date.now()-this.recordStartTime<500?this.onCancelRecordClick():this.recorder.stop():this.sendMessage();else{if(this.chat.peerId.isAnyChat()&&!(yield this.chat.canSend("send_media")))return void Ci(Zd);this.chatInput.classList.add("is-locked"),(0,ln.Z)(),this.recorder.start().then((()=>{this.releaseMediaPlayback=vt.Z.setSingleMedia(),this.recordCanceled=!1,this.setRecording(!0),Dc.Z.setKeepAlive(!0);const e=()=>{new qi("popup-cancel-record",{titleLangKey:"DiscardVoiceMessageTitle",descriptionLangKey:"DiscardVoiceMessageDescription",buttons:[{langKey:"DiscardVoiceMessageAction",callback:()=>{(0,n.tH)(this.btnCancelRecord)}},{langKey:"Continue",isCancel:!0}]}).show()};this.recordingOverlayListener=this.listenerSetter.add(document.body)("mousedown",(t=>{(0,r.Z)(t.target,"chat-input")||(0,r.Z)(t.target,"popup-cancel-record")||((0,a.Z)(t),e())}),{capture:!0,passive:!1}),C.Z.pushItem(this.recordingNavigationItem={type:"voice",onPop:()=>(setTimeout((()=>{e()}),0),!1)}),this.recordStartTime=Date.now();const t=this.recorder.sourceNode,i=t.context.createAnalyser();t.connect(i),i.fftSize=32;const s=new Uint8Array(i.frequencyBinCount),o=255*s.length,l=()=>{if(!this.recording)return;i.getByteFrequencyData(s);let e=0;s.forEach((t=>{e+=t}));const t=Math.min(1,e/o+.36);this.recordRippleEl.style.transform=`scale(${t})`;const n=Date.now()-this.recordStartTime,a=n%1e3,r=gt(n/1e3)+","+("00"+Math.round(a/10)).slice(-2);this.recordTimeEl.innerText=r,(0,Be.T2)(l)};l()})).catch((e=>{switch(e.name){case"NotAllowedError":Ci("Please allow access to your microphone");break;case"NotReadableError":Ci(e.message);break;default:console.error("Recorder start error:",e,e.name,e.message),Ci(e.message)}this.setRecording(!1),this.chatInput.classList.remove("is-locked")}))}})),this.onHelperCancel=(e,t)=>Ad(this,void 0,void 0,(function*(){if(e&&(0,a.Z)(e),this.willSendWebPage){const e=this.lastUrl;let t=!1;if(this.helperType&&(yield this.helperFunc(),t=!0),this.lastUrl=e,this.noWebPage=!0,this.willSendWebPage=null,t)return}if("edit"===this.helperType&&!t){const e=this.editMessage,t=(0,Ed.Z)(this.messageInputField.value,[]);if(e.message!==t)return void new qi("discard-editing",{buttons:[{langKey:"Alert.Confirm.Discard",callback:()=>{this.onHelperCancel(void 0,!0)}}],descriptionLangKey:"Chat.Edit.Cancel.Text"}).show()}this.clearHelper(),this.updateSendBtn()})),this.onHelperClick=e=>{if((0,a.Z)(e),(0,r.Z)(e.target,"reply"))if("forward"===this.helperType){const{forwardElements:e}=this;e&&gi.Z&&!e.container.classList.contains("active")&&Ii.openBtnMenu(e.container)}else"reply"===this.helperType?this.chat.setMessageId(this.replyToMsgId):"edit"===this.helperType&&this.chat.setMessageId(this.editMsgId)},this.listenerSetter=new I.Z}construct(){this.chatInput=document.createElement("div"),this.chatInput.classList.add("chat-input","hide"),this.inputContainer=document.createElement("div"),this.inputContainer.classList.add("chat-input-container"),this.rowsWrapperWrapper=document.createElement("div"),this.rowsWrapperWrapper.classList.add("rows-wrapper-wrapper"),this.rowsWrapper=document.createElement("div"),this.rowsWrapper.classList.add("rows-wrapper","chat-input-wrapper"),this.rowsWrapperWrapper.append(this.rowsWrapper);const e=bc();this.rowsWrapper.append(e);const t=this.fakeRowsWrapper=document.createElement("div");t.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,t,i),this.chatInput.append(this.inputContainer),this.goDownBtn=D({icon:"arrow_down",className:"bubbles-corner-button bubbles-go-down hide"}),this.inputContainer.append(this.goDownBtn),(0,n.fc)(this.goDownBtn,(e=>{(0,a.Z)(e),this.chat.bubbles.onGoDownClick()}),{listenerSetter:this.listenerSetter});const s=this.controlContainer=document.createElement("div");s.classList.add("chat-input-control","chat-input-wrapper"),this.inputContainer.append(s)}constructPeerHelpers(){this.replyElements.container=document.createElement("div"),this.replyElements.container.classList.add("reply-wrapper"),this.replyElements.iconBtn=E(""),this.replyElements.cancelBtn=E("close reply-cancel",{noRipple:!0}),this.replyElements.container.append(this.replyElements.iconBtn,this.replyElements.cancelBtn);const e=()=>(r=!0,this.canToggleHideAuthor()),t=()=>{r=!1},i=this.forwardElements={};let r=!1;const l=[i.showSender={text:"Chat.Alert.Forward.Action.Show1",onClick:e,checkboxField:new ji.Z({checked:!0})},i.hideSender={text:"Chat.Alert.Forward.Action.Hide1",onClick:e,checkboxField:new ji.Z({checked:!1})},i.showCaption={text:"Chat.Alert.Forward.Action.ShowCaption",onClick:t,checkboxField:new ji.Z({checked:!0})},i.hideCaption={text:"Chat.Alert.Forward.Action.HideCaption",onClick:t,checkboxField:new ji.Z({checked:!1})},i.changePeer={text:"Chat.Alert.Forward.Action.Another",onClick:()=>{this.changeForwardRecipient()},icon:"replace"}],c=i.container=Ei(l,this.listenerSetter),d=Array.from(c.children);if([{elements:d.slice(0,2),onChange:(e,t)=>{const s=!!+e;r&&(this.forwardWasDroppingAuthor=!s);const n=this.replyElements.container.querySelector(".reply-title");if(n){const e=n.firstElementChild,t=v.ZP.weakMap.get(e),s=i.showSender.checkboxField.checked?"Chat.Accessory.Forward":"Chat.Accessory.Hidden";t.key=s,t.update()}}},{elements:d.slice(2,4),onChange:e=>{const t=!!+e;let s;s=t&&void 0!==this.forwardWasDroppingAuthor?this.forwardWasDroppingAuthor?i.hideSender:i.showSender:t?i.showSender:i.hideSender,s.checkboxField.checked=!0}}].forEach((e=>{const t=Bi(e.elements.map((e=>({container:e,input:e.querySelector("input")}))),e.onChange),i=document.createElement("hr");t.append(i),c.append(t)})),c.append(i.changePeer.element),gi.Z||(this.forwardHover=new Bn({element:c})),i.modifyArgs=l.slice(0,-1),this.replyElements.container.append(c),i.modifyArgs.forEach(((e,t)=>{const{input:i}=e.checkboxField;i.type="radio",i.name=t<2?"author":"caption",i.value=""+ +!(t%2)})),this.newMessageWrapper=document.createElement("div"),this.newMessageWrapper.classList.add("new-message-wrapper"),this.btnToggleEmoticons=E("none toggle-emoticons",{noRipple:!0}),this.inputMessageContainer=document.createElement("div"),this.inputMessageContainer.classList.add("input-message-container"),"chat"===this.chat.type){this.goDownUnreadBadge=document.createElement("span"),this.goDownUnreadBadge.classList.add("badge","badge-24","badge-primary"),this.goDownBtn.append(this.goDownUnreadBadge),this.goMentionBtn=D({icon:"mention",className:"bubbles-corner-button bubbles-go-mention"}),this.goMentionUnreadBadge=document.createElement("span"),this.goMentionUnreadBadge.classList.add("badge","badge-24","badge-primary"),this.goMentionBtn.append(this.goMentionUnreadBadge),this.inputContainer.append(this.goMentionBtn),(0,n.fc)(this.goMentionBtn,(e=>{(0,a.Z)(e);const t=this.chat.bubbles.getMiddleware();this.managers.appMessagesManager.goToNextMention(this.chat.peerId).then((e=>{t()&&e&&this.chat.setMessageId(e)}))}),{listenerSetter:this.listenerSetter}),this.btnScheduled=E("scheduled btn-scheduled float hide",{noRipple:!0}),(0,n.fc)(this.btnScheduled,(e=>{this.appImManager.openScheduled(this.chat.peerId)}),{listenerSetter:this.listenerSetter}),this.listenerSetter.add(s.Z)("scheduled_new",(({peerId:e})=>{this.chat.peerId===e&&this.btnScheduled.classList.remove("hide")})),this.listenerSetter.add(s.Z)("scheduled_delete",(({peerId:e})=>{this.chat.peerId===e&&this.managers.appMessagesManager.getScheduledMessages(this.chat.peerId).then((e=>{this.btnScheduled.classList.toggle("hide",!e.length)}))})),this.btnToggleReplyMarkup=E("botcom toggle-reply-markup float hide",{noRipple:!0}),this.replyKeyboard=new fd({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"))),this.botCommands=new Ld(this.rowsWrapper,this,this.managers),this.botCommandsToggle=document.createElement("div"),this.botCommandsToggle.classList.add("new-message-bot-commands");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.botCommandsToggle.append(e),(0,n.fc)(this.botCommandsToggle,(e=>{(0,a.Z)(e),t.classList.contains("state-back")?(this.botCommands.toggle(!0),t.classList.remove("state-back")):(this.botCommands.setUserId(this.chat.peerId.toUserId(),this.chat.bubbles.getMiddleware()),t.classList.add("state-back"))}),{listenerSetter:this.listenerSetter}),this.botCommands.addEventListener("visible",(()=>{t.classList.add("state-back")})),this.botCommands.addEventListener("hiding",(()=>{t.classList.remove("state-back")}))}this.attachMenuButtons=[{icon:"image",text:"Chat.Input.Attach.PhotoOrVideo",onClick:()=>{this.fileInput.value="";const e=[...o.Z].join(", ");this.fileInput.setAttribute("accept",e),this.willAttachType="media",this.fileInput.click()},verify:()=>this.chat.canSend("send_media")},{icon:"document",text:"Chat.Input.Attach.Document",onClick:()=>{this.fileInput.value="",this.fileInput.removeAttribute("accept"),this.willAttachType="document",this.fileInput.click()},verify:()=>this.chat.canSend("send_media")},{icon:"poll",text:"Poll",onClick:()=>{A.Z.createPopup(Oc,this.chat).show()},verify:e=>e.isAnyChat()&&this.chat.canSend("send_polls")}],this.attachMenu=mo({noRipple:!0,listenerSetter:this.listenerSetter},"top-left",this.attachMenuButtons),this.attachMenu.classList.add("attach-file","tgico-attach"),this.attachMenu.classList.remove("tgico-more"),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.rowsWrapper.append(this.replyElements.container),this.autocompleteHelperController=new ud,this.stickersHelper=new Xc(this.rowsWrapper,this.autocompleteHelperController,this.managers),this.emojiHelper=new rd(this.rowsWrapper,this.autocompleteHelperController,this,this.managers),this.commandsHelper=new hd(this.rowsWrapper,this.autocompleteHelperController,this,this.managers),this.mentionsHelper=new md(this.rowsWrapper,this.autocompleteHelperController,this,this.managers),this.inlineHelper=new Sd(this.rowsWrapper,this.autocompleteHelperController,this.chat,this.managers),this.rowsWrapper.append(this.newMessageWrapper),this.btnCancelRecord=E("delete btn-circle z-depth-1 btn-record-cancel"),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=E("none btn-circle z-depth-1 btn-send animated-button-icon"),this.btnSend.insertAdjacentHTML("afterbegin",'\n <span class="tgico tgico-send"></span>\n <span class="tgico tgico-schedule"></span>\n <span class="tgico tgico-check"></span>\n <span class="tgico tgico-microphone_filled"></span>\n '),this.btnSendContainer.append(this.recordRippleEl,this.btnSend),"scheduled"!==this.chat.type&&(this.sendMenu=new Rc({onSilentClick:()=>{this.sendSilent=!0,this.sendMessage()},onScheduleClick:()=>{this.scheduleSending(void 0)},listenerSetter:this.listenerSetter,openSide:"top-left",onContextElement:this.btnSend,onOpen:()=>!this.isInputEmpty()||!!Object.keys(this.forwarding).length}),this.btnSendContainer.append(this.sendMenu.sendMenu)),this.inputContainer.append(this.btnCancelRecord,this.btnSendContainer),Vn.attachButtonListener(this.btnToggleEmoticons,this.listenerSetter),this.listenerSetter.add(Vn)("open",this.onEmoticonsOpen),this.listenerSetter.add(Vn)("close",this.onEmoticonsClose),this.attachMessageInputField(),this.listenerSetter.add(s.Z)("settings_updated",(()=>{(this.stickersHelper||this.emojiHelper)&&(this.previousQuery="",this.checkAutocomplete()),this.messageInputField&&this.messageInputField.onFakeInput()})),this.listenerSetter.add(s.Z)("draft_updated",(({peerId:e,threadId:t,draft:i,force:s})=>{this.chat.threadId===t&&this.chat.peerId===e&&this.setDraft(i,!0,s)})),this.listenerSetter.add(this.appImManager)("peer_changing",(e=>{this.chat===e&&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)})),"scheduled"===this.chat.type?this.listenerSetter.add(s.Z)("scheduled_delete",(({peerId:e,mids:t})=>{this.chat.peerId===e&&t.includes(this.editMsgId)&&this.onMessageSent()})):(this.listenerSetter.add(s.Z)("history_delete",(({peerId:e,msgs:t})=>{this.chat.peerId===e&&(t.has(this.editMsgId)&&this.onMessageSent(),this.replyToMsgId&&t.has(this.replyToMsgId)&&this.clearHelper("reply"))})),this.listenerSetter.add(s.Z)("dialogs_multiupdate",(e=>{e.has(this.chat.peerId)&&(this.startParam===le.gZ?this.setStartParam():this.center(!0))})));try{this.recorder=new(Fc())({encoderSampleRate:48e3,monitorGain:0,numberOfChannels:1,recordingGain:1,reuseWorker:!0})}catch(e){console.error("Recorder constructor error:",e)}this.updateSendBtn(),this.listenerSetter.add(this.fileInput)("change",(e=>{const t=e.target.files;t.length&&(A.Z.createPopup(Wc,this.chat,Array.from(t).slice(),this.willAttachType),this.fileInput.value="")}),!1),(0,n.fc)(this.btnSend,this.onBtnSendClick,{listenerSetter:this.listenerSetter,touchMouseDown:!0}),this.recorder&&((0,n.fc)(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=e=>{if(this.releaseMediaPlayback&&(this.releaseMediaPlayback(),this.releaseMediaPlayback=void 0),this.recordingOverlayListener&&(this.listenerSetter.remove(this.recordingOverlayListener),this.recordingOverlayListener=void 0),this.recordingNavigationItem&&(C.Z.removeItem(this.recordingNavigationItem),this.recordingNavigationItem=void 0),this.recordCanceled)return;const{peerId:t,threadId:i}=this.chat,s=this.replyToMsgId,n=(Date.now()-this.recordStartTime)/1e3|0,a=new Blob([e],{type:"audio/ogg"});Dc.Z.decode(e,!0).then((e=>{Dc.Z.setKeepAlive(!1),this.managers.appMessagesManager.sendFile(t,a,{isVoiceMessage:!0,isMedia:!0,duration:n,waveform:e.waveform,objectURL:e.url,replyToMsgId:s,threadId:i,clearDraft:!0}),this.onMessageSent(!1,!0)}))}),(0,n.fc)(this.replyElements.cancelBtn,this.onHelperCancel,{listenerSetter:this.listenerSetter}),(0,n.fc)(this.replyElements.container,this.onHelperClick,{listenerSetter:this.listenerSetter}),this.saveDraftDebounced=(0,Ki.Z)((()=>this.saveDraft()),2500,!1,!0),this.botStartBtn=(0,M.Z)("btn-primary btn-transparent text-bold chat-input-control-button"),this.botStartBtn.append((0,v.ag)("BotStart")),(0,n.fc)(this.botStartBtn,(()=>{const{startParam:e}=this;if(void 0===e)return;const t=this.toggleBotStartBtnDisability=(0,mi.Z)([this.botStartBtn],!0),i=this.chat.peerId,s=this.chat.bubbles.getMiddleware((()=>this.chat.peerId===i&&this.startParam===e&&this.toggleBotStartBtnDisability===t));this.managers.appMessagesManager.startBot(i.toUserId(),void 0,e).then((()=>{s()&&(t(),this.toggleBotStartBtnDisability=void 0,this.setStartParam())}))}),{listenerSetter:this.listenerSetter}),this.controlContainer.append(this.botStartBtn)}constructPinnedHelpers(){this.pinnedControlBtn=(0,M.Z)("btn-primary btn-transparent text-bold chat-input-control-button",{icon:"unpin"}),this.controlContainer.append(this.pinnedControlBtn),this.listenerSetter.add(this.pinnedControlBtn)("click",(()=>{const e=this.chat.peerId;new wc(e,0,!0,(()=>{this.chat.appImManager.setPeer();const e=this.chat.appImManager.chat;e.topbar.pinnedMessage&&e.topbar.pinnedMessage.pinnedMessageContainer.toggle(!0)}))})),this.chatInput.classList.add("type-pinned")}_center(e,t){if(!e&&!this.inputContainer.classList.contains("is-centering"))return;if(e===this.fakeWrapperTo)return;const i=e||this.fakeWrapperTo,s=!!e,n=this.fakeWrapperTo;let a,o="",r="";const l=i.getBoundingClientRect(),c=this.fakeRowsWrapper.getBoundingClientRect(),d=c.width,h=l.width;if(d!==h){const e=h/d,t=(d-h)/2;if(a=l.left-c.left-t,s&&(o=`translateX(${a}px) scaleX(${e})`,e<1)){const t=12;r=t+t*(1-e)+"px"}}this.fakeWrapperTo=e;const u=t?200:0;return Re(this.inputContainer,"is-centering",s,u),Re(this.rowsWrapperWrapper,"is-centering-to-control",!!(s&&e&&e.classList.contains("chat-input-control")),u),this.rowsWrapper.style.transform=o,this.rowsWrapper.style.borderRadius=r,{transform:o,borderRadius:r,needTranslateX:n&&(e&&e.classList.contains("chat-input-control")&&n===this.fakeSelectionWrapper||n.classList.contains("chat-input-control"))?-.5*a:a,widthFrom:d,widthTo:h}}center(e=!1){return Ad(this,void 0,void 0,(function*(){return this._center(yield this.getNeededFakeContainer(),e)}))}setStartParam(e){this.startParam!==e&&(this.startParam=e,this.center(!0))}getNeededFakeContainer(e=this.startParam){return Ad(this,void 0,void 0,(function*(){return this.chat.selection.isSelecting?this.fakeSelectionWrapper:void 0!==e||!(yield this.chat.canSend())||"pinned"===this.chat.type||(yield this.chat.isStartButtonNeeded())?this.controlContainer:void 0}))}getReadyToSend(e){return"scheduled"===this.chat.type?(this.scheduleSending(e),!0):(e(),!1)}setUnreadCount(){return Ad(this,void 0,void 0,(function*(){if(!this.goDownUnreadBadge)return;const e=yield this.managers.appMessagesManager.getDialogOnly(this.chat.peerId),t=null==e?void 0:e.unread_count;if(this.goDownUnreadBadge.innerText=""+(t||""),this.goDownUnreadBadge.classList.toggle("badge-gray",yield this.managers.appNotificationsManager.isPeerLocalMuted(this.chat.peerId,!0)),this.goMentionUnreadBadge&&"chat"===this.chat.type){const t=!(!(null==e?void 0:e.unread_mentions_count)||!e.unread_count);this.goMentionUnreadBadge.innerText=t?""+e.unread_mentions_count:"",this.goMentionBtn.classList.toggle("is-visible",t)}}))}saveDraft(){if(!this.chat.peerId||this.editMsgId||"scheduled"===this.chat.type)return;const{value:e,entities:t}=(0,Bc.Z)(this.messageInputField.input);let i;(e.length||this.replyToMsgId)&&(i={_:"draftMessage",date:(0,wl.Z)(!0),message:e,entities:t.length?t:void 0,pFlags:{no_webpage:this.noWebPage},reply_to_msg_id:this.replyToMsgId}),this.managers.appDraftsManager.syncDraft(this.chat.peerId,this.chat.threadId,i)}destroy(){this.listenerSetter.removeAll()}cleanup(e=!0){this.chat.peerId||(this.chatInput.classList.add("hide"),this.goDownBtn.classList.add("hide")),Ja(),this.lastTimeType=0,this.startParam=void 0,this.toggleBotStartBtnDisability&&(this.toggleBotStartBtnDisability(),this.toggleBotStartBtnDisability=void 0),this.messageInput&&(this.clearInput(),e&&this.clearHelper())}setDraft(e,t=!0,i=!1){return Ad(this,void 0,void 0,(function*(){if(!i&&!(0,Nc.Z)(this.messageInput)||"scheduled"===this.chat.type)return!1;if(!e&&!(e=yield this.managers.appDraftsManager.getDraft(this.chat.peerId,this.chat.threadId)))return i&&(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((()=>{(0,Be.T2)((()=>{this.onMessageSent()}))}))),!1;const s=function(e){const t=(0,Md.Z)(e.message),i=e.entities||[],s=(0,Id.Z)(i.slice(),t);return(0,lr.Z)((0,cr.Z)(e.message,{entities:s}))}(e);return(this.messageInputField.value!==s||this.replyToMsgId!==e.reply_to_msg_id)&&(t&&this.clearHelper(),this.noWebPage=e.pFlags.no_webpage,e.reply_to_msg_id&&this.initMessageReply(e.reply_to_msg_id),this.setInputValue(s,t,t),!0)}))}createSendAs(){if(this.sendAsPeerId=void 0,"chat"===this.chat.type||"discussion"===this.chat.type){let e=!0;this.sendAs=new xd(this.managers,((e,t)=>{let i=0;e.parentElement||(this.newMessageWrapper.prepend(e),i=2),this.updateOffset("as",!0,t,i)}),(t=>{this.sendAsPeerId=t,e?e=!1:this.getPlaceholderKey().then((e=>{this.updateMessageInputPlaceholder(e)}))}))}else this.sendAs=void 0;return this.sendAs}finishPeerChange(e){return Ad(this,void 0,void 0,(function*(){const t=this.chat.peerId,{forwardElements:i,btnScheduled:s,replyKeyboard:n,sendMenu:a,goDownBtn:o,chatInput:r,botCommandsToggle:l}=this,c=this.sendAs,d=this.createSendAs(),[h,u,p,m,g,f,y,b,w]=yield Promise.all([this.managers.appPeersManager.isBroadcast(t),this.managers.appPeersManager.canPinMessage(t),this.managers.appPeersManager.isBot(t),this.chat.canSend(),this.getNeededFakeContainer(e),kd(this.managers.acknowledged.appProfileManager.getProfileByPeerId(t)),s?kd(this.managers.acknowledged.appMessagesManager.getScheduledMessages(t)):void 0,d?(d.setPeerId(this.chat.peerId),d.updateManual(!0)):void 0,this.filterAttachMenuButtons()]),S=this.messageInput?yield this.getPlaceholderKey():void 0;return()=>{if(r.classList.remove("hide"),o.classList.toggle("is-broadcast",h),o.classList.remove("hide"),this.goDownUnreadBadge&&this.setUnreadCount(),"pinned"===this.chat.type&&r.classList.toggle("can-pin",u),i&&(this.forwardWasDroppingAuthor=!1,i.showCaption.checkboxField.setValueSilently(!0),i.showSender.checkboxField.setValueSilently(!0)),s&&y){s.classList.add("hide");const e=this.chat.bubbles.getMiddleware();(0,Kr.Z)(y.result,(t=>{e()&&t&&s.classList.toggle("hide",!t.length)}))}if(this.newMessageWrapper&&this.updateOffset(null,!1,!0),l&&(this.hasBotCommands=void 0,this.botCommands.toggle(!0,void 0,!0),this.updateBotCommandsToggle(!0),l.remove(),p)){const e=this.chat.bubbles.getMiddleware(),t=f.result;(0,Kr.Z)(t,(i=>{e()&&this.updateBotCommands(i,!(t instanceof Promise))}))}c&&c.destroy(),b&&b(),n&&n.setPeer(t),a&&a.setPeerId(t),this.messageInput?this.updateMessageInput(m,S,w):this.pinnedControlBtn&&this.pinnedControlBtn.append((0,v.ag)(u?"Chat.Input.UnpinAll":"Chat.Pinned.DontShow")),this.startParam=e,this._center(g,!1)}}))}updateOffset(e,t,i,s){e?this.newMessageWrapper.dataset.offset=e:delete this.newMessageWrapper.dataset.offset,Re(this.newMessageWrapper,"has-offset",t,i?0:300,void 0,s)}updateBotCommands(e,t){var i,s;this.hasBotCommands=!!(null===(s=null===(i=e.bot_info)||void 0===i?void 0:i.commands)||void 0===s?void 0:s.length),this.updateBotCommandsToggle(t)}updateBotCommandsToggle(e){const{botCommandsToggle:t,hasBotCommands:i}=this,s=!!i&&this.isInputEmpty();if(!i){if(!t.parentElement)return;t.remove()}const n=s,a=t.parentElement?0:2;t.parentElement||this.newMessageWrapper.prepend(t),this.updateOffset("commands",n,e,a)}getPlaceholderKey(){return Ad(this,void 0,void 0,(function*(){const{peerId:e,threadId:t}=this.chat;let i;return i=t?"Comment":(yield this.managers.appPeersManager.isBroadcast(e))?"ChannelBroadcast":void 0!==this.sendAsPeerId&&this.sendAsPeerId!==s.Z.myId||(yield this.managers.appMessagesManager.isAnonymousSending(e))?"SendAnonymously":"Message",i}))}updateMessageInputPlaceholder(e){const t=v.ZP.weakMap.get(this.messageInput);t&&t.compareAndUpdate({key:e})}filterAttachMenuButtons(){if(!this.attachMenuButtons)return;const{peerId:e,threadId:t}=this.chat;return ki(this.attachMenuButtons,(i=>i.verify(e,t)))}updateMessageInput(e,t,i){const{chatInput:s,attachMenu:n,messageInput:a}=this,{peerId:o,threadId:r}=this.chat;s.classList.contains("is-hidden")!==!e&&(s.classList.add("no-transition"),s.classList.toggle("is-hidden",!e),s.offsetLeft,s.classList.remove("no-transition")),this.updateMessageInputPlaceholder(t),this.attachMenuButtons&&this.attachMenuButtons.forEach((e=>{e.element.classList.toggle("hide",!i.includes(e))})),e?(a.setAttribute("contenteditable","true"),this.setDraft(void 0,!1),a.innerHTML||this.messageInputField.onFakeInput()):a.removeAttribute("contenteditable"),n&&(n.toggleAttribute("disabled",!i.length),n.classList.toggle("btn-disabled",!i.length)),this.updateSendBtn()}attachMessageInputField(){const e=this.messageInputField;this.messageInputField=new _d({placeholder:"Message",name:"message",withLinebreaks:!0}),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.messageInput.classList.add("no-scrollbar"),this.attachMessageInputListeners(),Cd.T&&(0,Cd.Z)(this.messageInput),e?(e.input.replaceWith(this.messageInputField.input),e.inputFake.replaceWith(this.messageInputField.inputFake)):this.inputMessageContainer.append(this.messageInputField.input,this.messageInputField.inputFake)}attachMessageInputListeners(){this.listenerSetter.add(this.messageInput)("keydown",(e=>{const t=e.key;if((0,sd.Z)(e))(0,a.Z)(e),this.sendMessage();else if(e.ctrlKey||e.metaKey)this.handleMarkdownShortcut(e);else if(("PageUp"===t||"PageDown"===t)&&!e.shiftKey)if(e.preventDefault(),"PageUp"===t){const e=document.createRange(),t=window.getSelection();e.setStart(this.messageInput.childNodes[0]||this.messageInput,0),e.collapse(!0),t.removeAllRanges(),t.addRange(e)}else(0,bl.Z)(this.messageInput)})),gi.Z&&(0,n.fc)(this.messageInput,(e=>{this.appImManager.selectTab(1),Vn.toggle(!1)}),{listenerSetter:this.listenerSetter}),this.listenerSetter.add(this.messageInput)("input",this.onMessageInput),this.listenerSetter.add(this.messageInput)("keyup",(()=>{this.checkAutocomplete()})),"chat"!==this.chat.type&&"discussion"!==this.chat.type||this.listenerSetter.add(this.messageInput)("focusin",(()=>{this.chat.bubbles.scrollable.loadedAll.bottom&&this.managers.appMessagesManager.readAllHistory(this.chat.peerId,this.chat.threadId)}))}applyMarkdown(e,t){const i={bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",monospace:()=>document.execCommand("fontName",!1,"var(--font-monospace)"),link:t?()=>document.execCommand("createLink",!1,t):()=>document.execCommand("unlink",!1,null),spoiler:()=>document.execCommand("fontName",!1,"spoiler")};if(!i[e])return!1;const s=i[e],n=this.prepareDocumentExecute(),a=[];a.push(document.execCommand("styleWithCSS",!1,"true"));const o=e=>{let t=!1;const i=window.getSelection();if(!i.isCollapsed){const s=i.getRangeAt(0),n=nd.o[e],a=s.commonAncestorContainer;(a.parentNode.matches(n.match)||a instanceof HTMLElement&&a.matches(n.match))&&(t=!0)}return t};return"monospace"===e||"spoiler"===e?o(e)?a.push(this.resetCurrentFontFormatting()):(("monospace"===e||o("monospace"))&&a.push(this.resetCurrentFormatting()),a.push("function"==typeof s?s():document.execCommand(s,!1,null))):(o("monospace")&&a.push(this.resetCurrentFormatting()),a.push("function"==typeof s?s():document.execCommand(s,!1,null))),a.push(document.execCommand("styleWithCSS",!1,"false")),n(),this.appImManager.markupTooltip&&this.appImManager.markupTooltip.setActiveMarkupButton(),!0}resetCurrentFormatting(){return document.execCommand("removeFormat",!1,null)}resetCurrentFontFormatting(){return document.execCommand("fontName",!1,"Roboto")}insertAtCaret(e,t,i=!0){const{value:s,caretPos:n,entities:a}=od(this.messageInput),o=n>=0?n:s.length,r=s.substr(0,o),l=s.substr(o),c=i?r.match(Fd.AUTO_COMPLETE_REG_EXP):null,d=c?c.index+(c[0].length-c[2].length):r.length,h=r.slice(0,d)+e+l,u=(0,Md.Z)(s);(0,Id.Z)(a,u);const p=t?Math.max(t.length,e.length):e.length,m=[];t&&(m.push(t),t.offset=d);const g=c?p-c[2].length:p;a.forEach((e=>{e.offset>=d&&(e.offset+=g)})),(0,Id.Z)(a,m);{const e={_:"messageEntityCaret",offset:d+p,length:0};let t=0;for(let i=a.length;t<i&&!(a[t].offset>e.offset);++t);a.splice(t,0,e)}const v=(0,lr.Z)((0,cr.Z)(h,{entities:a}));this.messageInputField.setValueSilently(v);const f=this.messageInput.querySelector(".composer-sel");f&&(function(e){const t=e;if(1===(e=e.previousSibling).nodeType){const i=document.createTextNode("");e.parentNode.insertBefore(i,t.nextSibling&&t.nextSibling.nodeType!==e.nodeType?t.nextSibling:t),e=i}if(window.getSelection&&document.createRange){const t=document.createRange();e&&(t.setStartAfter(e),t.insertNode(e),t.setStart(e,e.nodeValue.length)),t.collapse(!0);const i=window.getSelection();i.removeAllRanges(),i.addRange(t)}}(f),f.remove()),this.onMessageInput()}checkAutocomplete(e,t,i){return Ad(this,void 0,void 0,(function*(){if(void 0===e){const s=od(this.messageInputField.input,!0);e=s.value,t=s.caretPos,i=s.entities}if(-1===t&&(t=e.length),void 0===i){const t=(0,Ed.Z)(e,i,!0);i=(0,Id.Z)(i,(0,Md.Z)(t))}if(e=e.slice(0,t),this.previousQuery===e)return;this.previousQuery=e;const n=e.match(Fd.AUTO_COMPLETE_REG_EXP);let a;if(n){const t=i[0];let o=n[2];const r=o[0];if(this.stickersHelper&&s.Z.settings.stickers.suggest&&(yield this.chat.canSend("send_stickers"))&&"messageEntityEmoji"===(null==t?void 0:t._)&&t.length===e.length&&!t.offset)a=this.stickersHelper,this.stickersHelper.checkEmoticon(e);else if("@"===r){const e=this.chat.threadId?(0,ci.Z)(this.chat.threadId):void 0;(yield this.mentionsHelper.checkQuery(o,this.chat.peerId.isUser()?le.NM:this.chat.peerId,e))&&(a=this.mentionsHelper)}else n[1]||"/"!==r?s.Z.settings.emoji.suggest&&(o=o.replace(/^\s*/,""),e.match(/^\s*:(.+):\s*$/)||e.match(/:[;!@#$%^&*()-=|]/)||!o||(a=this.emojiHelper,this.emojiHelper.checkQuery(o,r))):(yield this.commandsHelper.checkQuery(o,this.chat.peerId))&&(a=this.commandsHelper)}a=this.checkInlineAutocomplete(e,a),this.autocompleteHelperController.hideOtherHelpers(a)}))}checkInlineAutocomplete(e,t){let i=!1;if(!t){const s=e.match(/^@([a-zA-Z\\d_]{3,32})\s/);if(s){const n=s[1],a=e.slice(s[0].length);i=s[0].length===e.length,t=this.inlineHelper,this.btnPreloader?Re(this.btnPreloader,"show",!0,400):(this.btnPreloader=E("none btn-preloader float show disable-hover",{noRipple:!0}),(0,be.y)(this.btnPreloader,!0),this.inputMessageContainer.parentElement.insertBefore(this.btnPreloader,this.inputMessageContainer.nextSibling)),this.inlineHelper.checkQuery(this.chat.peerId,n,a).then((({user:e,renderPromise:t})=>{i&&e.bot_inline_placeholder&&(this.messageInput.dataset.inlinePlaceholder=e.bot_inline_placeholder),t.then((()=>{Re(this.btnPreloader,"show",!1,400)}))})).catch(ft.Z)}}return i||delete this.messageInput.dataset.inlinePlaceholder,t!==this.inlineHelper&&this.btnPreloader&&Re(this.btnPreloader,"show",!1,400),t}setRecording(e){this.recording!==e&&(Re(this.chatInput,"is-recording",e,200),this.recording=e,this.updateSendBtn())}changeForwardRecipient(){if(this.helperWaitingForward)return;this.helperWaitingForward=!0;const e=(0,Ji.Z)(this.forwarding),t=this.helperFunc;this.clearHelper(),this.updateSendBtn();let i=!1;new ja(e,(()=>{i=!0})).addEventListener("close",(()=>{this.helperWaitingForward=!1,i||t()}))}clearInput(e=!0,t=!0,i=""){return Ad(this,void 0,void 0,(function*(){if(document.activeElement===this.messageInput&&Je.IS_MOBILE_SAFARI){const e=document.createElement("input");document.body.append(e),(0,gd.Z)(e),this.messageInputField.setValueSilently(i),(0,gd.Z)(this.messageInput),e.remove()}else this.messageInputField.setValueSilently(i);gi.Z||(this.canRedoFromHTML="",this.undoHistory.length=0,this.executedHistory.length=0,this.canUndoFromHTML="");let s=!1;e&&(s=yield this.setDraft(void 0,!1)),!s&&t&&this.onMessageInput()}))}isInputEmpty(){return(0,Nc.Z)(this.messageInput)}updateSendBtn(){let e;const t=this.isInputEmpty();e=this.editMsgId?"edit":!this.recorder||this.recording||!t||this.forwarding?"scheduled"===this.chat.type?"schedule":"send":"record",["send","record","edit","schedule"].forEach((t=>{this.btnSend.classList.toggle(t,e===t)})),this.btnScheduled&&this.btnScheduled.classList.toggle("show",t),this.btnToggleReplyMarkup&&this.btnToggleReplyMarkup.classList.toggle("show",t)}onMessageSent(e=!0,t){"scheduled"!==this.chat.type&&this.managers.appMessagesManager.readAllHistory(this.chat.peerId,this.chat.threadId,!0),this.scheduleDate=void 0,this.sendSilent=void 0;const i=this.messageInputField.value;(0,Md.Z)(i).filter((e=>"messageEntityEmoji"===e._)).forEach((e=>{const t=(0,pi.zu)(e.unicode);this.managers.appEmojiManager.pushRecentEmoji(t)})),e&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null,this.clearInput()),(t||e)&&this.clearHelper(),this.updateSendBtn()}sendMessage(e=!1){const{editMsgId:t,chat:i}=this;if("scheduled"===i.type&&!e&&!t)return void this.scheduleSending();const{peerId:s}=i,{noWebPage:n}=this,a=this.chat.getMessageSendingParams(),{value:o,entities:r}=(0,Bc.Z)(this.messageInputField.input);if(t){const e=this.editMessage;if(!o.trim()&&!e.media)return void new Qa(s,[t],i.type);this.managers.appMessagesManager.editMessage(e,o,{entities:r,noWebPage:n}),this.onMessageSent()}else o.trim()&&(this.managers.appMessagesManager.sendText(s,o,Object.assign(Object.assign({entities:r},a),{noWebPage:n,webPage:this.getWebPagePromise?void 0:this.willSendWebPage,clearDraft:!0})),"scheduled"===this.chat.type?this.onMessageSent(!0):this.onMessageSent(!1,!1));if(this.forwarding){const e=(0,Ji.Z)(this.forwarding);for(const t in e)this.managers.appMessagesManager.forwardMessages(s,t.toPeerId(),e[t],Object.assign(Object.assign({},a),{dropAuthor:this.forwardElements&&this.forwardElements.hideSender.checkboxField.checked,dropCaptions:this.isDroppingCaptions()}));o||this.onMessageSent()}}sendMessageWithDocument(e,t=!1,i=!1,n=!1){var a;return Ad(this,void 0,void 0,(function*(){const o="sticker"===(e=yield this.managers.appDocsManager.getDoc(e)).type?"send_stickers":"gif"===e.type?"send_gifs":"send_media";return this.chat.peerId.isAnyChat()&&!(yield this.chat.canSend(o))?(Ci(Zd),!1):"scheduled"!==this.chat.type||t?!(!e||(0,di.Z)(e)&&!s.Z.premium||(this.managers.appMessagesManager.sendFile(this.chat.peerId,e,Object.assign(Object.assign({},this.chat.getMessageSendingParams()),{isMedia:!0,clearDraft:i||void 0,silent:n})),this.onMessageSent(i,!0),"sticker"===e.type&&(null===(a=Vn.stickersTab)||void 0===a||a.unshiftRecentSticker(e)),0)):(this.scheduleSending((()=>this.sendMessageWithDocument(e,!0,i,n))),!1)}))}canToggleHideAuthor(){const{forwardElements:e}=this;if(!e)return!1;const t=e.hideCaption.checkboxField;return!t.checked||(0,l.Z)(t.label,"FORM").classList.contains("hide")}isDroppingCaptions(){return!this.canToggleHideAuthor()}initMessageEditing(e){return Ad(this,void 0,void 0,(function*(){const t=yield this.chat.getMessage(e);let i=(0,lr.Z)((0,cr.Z)(t.message,{entities:t.totalEntities}));const s=()=>Ad(this,void 0,void 0,(function*(){const n=yield Aa(t,void 0,[t.mid]);this.setTopInfo("edit",s,(0,v.ag)("AccDescrEditing"),n,i,t),this.editMsgId=e,this.editMessage=t,i=void 0}));s()}))}initMessagesForward(e){const t=()=>Ad(this,void 0,void 0,(function*(){const i=Object.keys(e).map((e=>e.toPeerId())),n=new Set;let a=0,o=0;const r=i.map((t=>Ad(this,void 0,void 0,(function*(){const i=e[t],s=i.map((e=>Ad(this,void 0,void 0,(function*(){var i;const s=yield this.managers.appMessagesManager.getMessageByPeer(t,e);!(null===(i=s.fwd_from)||void 0===i?void 0:i.from_name)||s.fromId||s.fwdFromId?n.add("P"+s.fromId):n.add("N"+s.fwd_from.from_name),s.media&&s.message&&++o}))));yield Promise.all(s),a+=i.length}))));yield Promise.all(r);const c=n.size>2,d=[...n].map((e=>{const t=e[0];if(e=e.slice(1),"P"===t){const t=e.toPeerId();return t===s.Z.myId?(0,v.ag)("Chat.Accessory.Forward.You"):new Ot({peerId:t,dialog:!1,onlyFirstName:c}).element}return c?e.split(" ")[0]:e})),{forwardElements:h}=this;(0,l.Z)(h.showCaption.checkboxField.label,"FORM").classList.toggle("hide",!o);const u=h.hideCaption.checkboxField.checked;o&&u?h.hideSender.checkboxField.setValueSilently(!0):void 0!==this.forwardWasDroppingAuthor&&(this.forwardWasDroppingAuthor?h.hideSender:h.showSender).checkboxField.setValueSilently(!0);const p=h.showSender.checkboxField.checked?"Chat.Accessory.Forward":"Chat.Accessory.Hidden",m=(0,v.ag)(p,[a]),g=document.createDocumentFragment();let f,y;if(d.length<3?g.append(...(0,v.v_)(d,!1)):g.append(d[0],(0,v.ag)("AndOther",[d.length-1])),1===i.length){const t=i[0],s=e[t];if(f=yield this.managers.appMessagesManager.getMessageByPeer(t,s[0]),y=!!f.grouped_id,y){const e=yield this.managers.appMessagesManager.getMidsByMessage(f);(e.length!==a||e.find((e=>!s.includes(e))))&&(y=!1)}}const b=document.createDocumentFragment();if(y||1===a){const t=e[i[0]],s=yield Aa(f,void 0,t);b.append(g,": ",s)}else b.append((0,v.ag)("Chat.Accessory.Forward.From"),": ",g);const w=this.setTopInfo("forward",t,m,b);h.modifyArgs.forEach(((e,t)=>{const s=e.textElement,n=v.ZP.weakMap.get(s);n.args=[t<2?i.length:o],n.update()})),this.forwardHover&&this.forwardHover.attachButtonListener(w,this.listenerSetter),this.forwarding=e}));t()}initMessageReply(e){return Ad(this,void 0,void 0,(function*(){if(this.replyToMsgId===e)return;let t=yield this.chat.getMessage(e);const i=()=>{let s;t?s=new Ot({peerId:t.fromId,dialog:!1}).element:(s=(0,v.ag)("Loading"),this.managers.appMessagesManager.wrapSingleMessage(this.chat.peerId,e).then((s=>{this.replyToMsgId===e&&(t=s,t?i():this.clearHelper("reply"))}))),this.setTopInfo("reply",i,s,t&&t.message,void 0,t),this.replyToMsgId=e};i()}))}clearHelper(e){"edit"===this.helperType&&"edit"!==e&&this.clearInput(),e&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null),"reply"!==e&&(this.replyToMsgId=void 0,this.forwarding=void 0),this.editMsgId=this.editMessage=void 0,this.helperType=this.helperFunc=void 0,this.chat.container.classList.contains("is-helper-active")&&(C.Z.removeByType("input-helper"),this.chat.container.classList.remove("is-helper-active"),this.t())}t(){const e="is-toggling-helper";Re(this.chat.container,e,!0,150,(()=>{this.chat.container.classList.remove(e)}))}setInputValue(e,t=!0,i=!0){e||(e=""),t?this.clearInput(!1,!1,e):this.messageInputField.setValueSilently(e),(0,Be.T2)((()=>{i&&(0,bl.Z)(this.messageInput),this.onMessageInput(),this.messageInput.scrollTop=this.messageInput.scrollHeight}))}setTopInfo(e,t,i="",s="",n,a){if(this.willSendWebPage&&"reply"===e)return;"webpage"!==e&&(this.clearHelper(e),this.helperType=e,this.helperFunc=t);const o=this.replyElements.container,r=o.lastElementChild.previousElementSibling,l=r.classList.contains("reply");this.replyElements.iconBtn.replaceWith(this.replyElements.iconBtn=E(("webpage"===e?"link":e)+" active reply-icon",{noRipple:!0}));const{container:c}=Ba(i,s,a);return l?r.replaceWith(c):o.insertBefore(c,o.lastElementChild),"webpage"===e&&(c.style.cursor="default"),this.chat.container.classList.contains("is-helper-active")||(this.chat.container.classList.add("is-helper-active"),this.t()),Je.IS_MOBILE||C.Z.pushItem({type:"input-helper",onPop:()=>{this.onHelperCancel()}}),void 0!==n&&this.setInputValue(n),setTimeout((()=>{this.updateSendBtn()}),0),c}}Fd.AUTO_COMPLETE_REG_EXP=/(\s|^)((?:(?:@|^\/)\S*)|(?::|^[^:@\/])(?!.*[:@\/]).*)$/;const Dd="pinned-container";class Rd{constructor(e){this.floating=!1,(0,x.Z)(this,e);const{divAndCaption:t,className:i}=this;t.container.classList.add(Dd,"hide"),t.title.classList.add(Dd+"-title"),t.subtitle.classList.add(Dd+"-subtitle"),t.content.classList.add(Dd+"-content"),this.btnClose=document.createElement("button"),this.btnClose.classList.add(Dd+"-close",`pinned-${i}-close`,"btn-icon","tgico-close"),this.wrapper=document.createElement("div"),this.wrapper.classList.add(Dd+"-wrapper"),(0,we.Z)(this.wrapper),this.wrapperUtils=document.createElement("div"),this.wrapperUtils.classList.add(Dd+"-wrapper-utils"),this.wrapperUtils.append(this.btnClose),this.wrapper.append(...Array.from(t.container.children),this.wrapperUtils),t.container.append(this.wrapper),this.attachOnCloseEvent(this.btnClose)}attachOnCloseEvent(e){(0,n.fc)(e,(e=>{(0,a.Z)(e),((this.onClose?this.onClose():null)||Promise.resolve(!0)).then((e=>{e&&this.toggle(!0)}))}),{listenerSetter:this.listenerSetter})}toggle(e){const t=this.divAndCaption.container.classList.contains("hide");if(void 0===e)e=!t;else if(e===t)return;const i=(this.floating||d.Z.isMobile)&&!e;this.divAndCaption.container.classList.toggle("is-floating",i),this.divAndCaption.container.classList.toggle("hide",e),this.topbar.container.classList.toggle("is-pinned-floating",i),this.topbar.container.classList.toggle(`is-pinned-${this.className}-shown`,!e),this.topbar.setFloating(),this.topbar.setUtilsWidth()}isVisible(){return!this.divAndCaption.container.classList.contains("hide")}isFloating(){return this.divAndCaption.container.classList.contains("is-floating")}fill(e,t,i){this.divAndCaption.container.dataset.peerId=""+i.peerId,this.divAndCaption.container.dataset.mid=""+i.mid,this.divAndCaption.fill(e,t,i),this.topbar.setUtilsWidth()}}class Bd extends _t{constructor(e,t=!1){super({step:.01,min:0,max:1,vertical:t},1),this.listenerSetter=e,this.vertical=t,this.onMuteClick=e=>{e&&(0,a.Z)(e),vt.Z.muted=!vt.Z.muted},this.setVolume=()=>{const{volume:e,muted:t}=vt.Z;let i;i=!e||t?0:e>.5?3:e>0&&e<.25?1:2,Bd.ICONS.forEach((e=>this.icon.classList.remove("tgico-"+e))),this.icon.classList.add("tgico-"+Bd.ICONS[i]),this.mousedown||this.setProgress(t?0:e)},this.setListeners(),this.setHandlers({onScrub:e=>{const t=Math.max(Math.min(e,1),0);vt.Z.muted=!1,vt.Z.volume=t}});const i="player-volume",s=this.btn=document.createElement("div");s.classList.add("btn-icon",i);const o=this.icon=document.createElement("span");o.classList.add(i+"__icon"),s.append(o,this.container),(0,n.fc)(o,this.onMuteClick,{listenerSetter:this.listenerSetter}),this.listenerSetter.add(vt.Z)("playbackParams",this.setVolume),this.setVolume()}}Bd.ICONS=["volume_off","volume_mute","volume_down","volume_up"];class Nd extends Rd{constructor(e,t,i){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"audio",divAndCaption:new ma("pinned-audio",((e,t)=>{(0,g.Z)(this.divAndCaption.title,e),(0,g.Z)(this.divAndCaption.subtitle,t)})),onClose:()=>{vt.Z.stop()},floating:!0}),this.topbar=e,this.chat=t,this.managers=i,this.onPlaybackParams=e=>{this.fasterEl.classList.toggle("active",e.playbackRate>1),this.repeatEl.classList.remove("tgico-audio_repeat","tgico-audio_repeat_single"),this.repeatEl.classList.add(e.loop?"tgico-audio_repeat_single":"tgico-audio_repeat"),this.repeatEl.classList.toggle("active",e.loop||e.round)},this.onPause=()=>{this.toggleEl.classList.remove("flip-icon")},this.onStop=()=>{this.toggle(!0)},this.onMediaPlay=({doc:e,message:t,media:i,playbackParams:s})=>{var n,a;let o,r;const l="voice"!==e.type&&"round"!==e.type;if(l){const t=e.attributes.find((e=>"documentAttributeAudio"===e._));o=(0,Zt.Z)(null!==(a=null==t?void 0:t.title)&&void 0!==a?a:e.file_name),r=(null==t?void 0:t.performer)?(0,Zt.Z)(t.performer):(0,v.ag)("AudioUnknownArtist")}else o=new Ot({peerId:t.fromId,fromName:null===(n=t.fwd_from)||void 0===n?void 0:n.from_name}).element,r=G(t.date);this.fasterEl.classList.toggle("hide",l),this.repeatEl.classList.toggle("hide",!l),this.onPlaybackParams(s),this.volumeSelector.setVolume(),this.progressLine.setMedia(i),this.fill(o,r,t),this.toggleEl.classList.toggle("flip-icon",!i.paused),this.toggle(!1)},this.divAndCaption.border.remove();const s=E("fast_rewind active",{noRipple:!0}),o=E("fast_forward active",{noRipple:!0}),r=(e,t)=>{(0,n.fc)(e,(e=>{(0,a.Z)(e),t()}),{listenerSetter:this.topbar.listenerSetter})};r(s,(()=>{vt.Z.previous()})),r(o,(()=>{vt.Z.next()})),this.toggleEl=E("",{noRipple:!0}),this.toggleEl.classList.add("active","pinned-audio-ico","tgico"),r(this.toggleEl,(()=>{vt.Z.toggle()})),this.wrapper.prepend(this.wrapper.firstElementChild,s,this.toggleEl,o),this.volumeSelector=new Bd(this.listenerSetter,!0);const l=document.createElement("div");l.classList.add("progress-line-container"),l.append(this.volumeSelector.container);const c=document.createElement("div");c.classList.add("pinned-audio-volume-tunnel"),this.volumeSelector.btn.classList.add("pinned-audio-volume","active"),this.volumeSelector.btn.prepend(c),this.volumeSelector.btn.append(l),this.repeatEl=E("audio_repeat",{noRipple:!0}),r(this.repeatEl,(()=>{const e=vt.Z.getPlaybackParams();e.round?e.loop?(vt.Z.round=!1,vt.Z.loop=!1):vt.Z.loop=!vt.Z.loop:vt.Z.round=!0}));const d=this.fasterEl=E("playback_2x",{noRipple:!0});r(d,(()=>{vt.Z.playbackRate=d.classList.contains("active")?1:1.75})),this.wrapperUtils.prepend(this.volumeSelector.btn,d,this.repeatEl);const h=document.createElement("div");h.classList.add("pinned-audio-progress-wrapper"),this.progressLine=new At(void 0,void 0,!0,!0),this.progressLine.container.classList.add("pinned-audio-progress"),h.append(this.progressLine.container),this.wrapper.insertBefore(h,this.wrapperUtils),this.topbar.listenerSetter.add(vt.Z)("play",this.onMediaPlay),this.topbar.listenerSetter.add(vt.Z)("pause",this.onPause),this.topbar.listenerSetter.add(vt.Z)("stop",this.onStop),this.topbar.listenerSetter.add(vt.Z)("playbackParams",this.onPlaybackParams);const u=vt.Z.getPlayingDetails();u&&(this.onMediaPlay(u),this.onPlaybackParams(u.playbackParams))}destroy(){this.progressLine&&this.progressLine.removeListeners()}}var Ud;!function(e){e[e.ONE=32]="ONE",e[e.TWO=15]="TWO",e[e.THREE=10]="THREE",e[e.FOUR=8]="FOUR",e[e.MORE=8]="MORE"}(Ud||(Ud={}));const Od="pinned-message-border";class Hd{constructor(){this.drawRect=(e,t,i,s,n)=>`M${e},${t+n}a${n},${n},0,0,1,${i},0v${s-2*n}a${n},${n},0,0,1,${-i},0Z`,this.getClipPath=(e,t,i)=>{let s="";if(2===i)s=this.drawRect(0,0,2,t,1)+this.drawRect(0,t+2,2,t,1);else for(let e=0;e<i;++e)s+=this.drawRect(0,(t+1)*e,2,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",s),this.clipPath},this.getBarHeight=(e,t)=>{let i;return e<=1?i=Ud.ONE:2===e?i=Ud.TWO:3===e?i=Ud.THREE:4===e?i=Ud.FOUR:e>3&&(i=Ud.MORE),i},this.getMarkHeight=(e,t)=>{let i;return e<=1?i=Ud.ONE:2===e?i=Ud.TWO:3===e?i=Ud.THREE:4===e?i=Ud.FOUR:e>3&&(i=Ud.MORE),i},this.getMarkTranslateY=(e,t,i)=>1===i?0:2===i?e?t+1:0:3===i?e?1===e?t+1:2*t+2+1:0:(t+1)*e,this.getTrackTranslateY=(e,t,i,s)=>t<=4||e<=1?0:e>=t-2?s-Ud.ONE-i:(e-2)*i+1*e,this.getTrackHeight=(e,t)=>e<=3?Ud.ONE:t*e+1*(e-1)}render(e,t){if(this.border||(this.border=document.createElement("div"),this.border.classList.add(Od),this.wrapper=document.createElement("div"),this.border.append(this.wrapper)),1===e)return this.count!==e&&(this.wrapper.className=Od+"-wrapper-1",this.border.classList.remove(Od+"-mask"),this.wrapper.innerHTML=this.wrapper.style.cssText=""),this.border;const i=this.getBarHeight(e,t),s=this.getMarkHeight(e,t),n=this.getTrackHeight(e,i),a=`clipPath_${e}`,o=this.getClipPath(a,i,e),r=this.getMarkTranslateY(t,i,e),l=this.getTrackTranslateY(t,e,i,n);return this.border.classList.toggle(Od+"-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=Od+"-wrapper",this.wrapper.style.cssText=`clip-path: url(#${a}); width: 2px; height: ${n}px; transform: translateY(-${l}px);`,this.svg||(this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.setAttributeNS(null,"height","0"),this.svg.setAttributeNS(null,"width","0"),this.defs=document.createElementNS("http://www.w3.org/2000/svg","defs"),this.defs.append(o),this.svg.append(this.defs),this.mark=document.createElement("div"),this.mark.classList.add(Od+"-mark")),this.svg.parentElement||this.wrapper.append(this.svg,this.mark),this.mark.style.cssText=`height: ${s}px; transform: translateY(${r}px);`,this.count=e,this.index=t,this.border}}var zd=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Gd{constructor(){this.rows={},this.container=document.createElement("div"),this.container.className=Gd.BASE_CLASS}getRow(e,t=!1){if(this.rows[e])return this.rows[e].element;const i=document.createElement("div"),s=!Object.keys(this.rows).length&&!t;return i.className=Gd.BASE_CLASS+"-row"+(s?"":" is-hiding hide"),this.rows[e]={element:i,new:!0},this.container.append(i),i}clearRow(e){this.rows[e]&&(this.rows[e].element.remove(),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)}),Gd.DURATION)}setNewRow(e,t=!1){const i=this.rows[e];i.new&&(t?(i.element.classList.remove("hide"),i.element.offsetLeft):i.element.classList.remove("is-hiding","hide"),delete i.new),this.clearRows(e)}animate(e,t,i=e>t,s=!1){if(e===t)return this.setNewRow(e);const n=this.rows[e],a=this.rows[t];if(!a&&!s)return this.setNewRow(e);const o=["from-top","from-bottom"];i||o.reverse(),n.element.classList.add(o[0]),n.element.classList.remove(o[1]),a&&(a.element.classList.add(o[1]),a.element.classList.remove(o[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)}}Gd.DURATION=200,Gd.BASE_CLASS="animated-super";class Vd{constructor(e=!1){this.reverse=e,this.decimals=[],this.previousNumber=0,this.container=document.createElement("div"),this.container.className=Vd.BASE_CLASS}getDecimal(e){if(this.decimals[e])return this.decimals[e];const t=document.createElement("div");t.className=Vd.BASE_CLASS+"-decimal";const i=document.createElement("div");i.className=Vd.BASE_CLASS+"-decimal-placeholder";const s=new Gd;return s.container.className=Vd.BASE_CLASS+"-decimal-wrapper",t.append(i,s.container),this.container.append(t),this.decimals[e]={container:t,placeholder:i,animatedSuper:s}}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((e=>{e.container.remove()}))}),Gd.DURATION))}hideLeft(e){const t=(""+e).length;this.decimals.slice(t).forEach((t=>{const i=+t.placeholder.innerText||0;t.animatedSuper.getRow(Vd.EMPTY_INDEX,!0),t.animatedSuper.animate(Vd.EMPTY_INDEX,i,this.reverse?e<this.previousNumber:e>this.previousNumber,!0)})),this.clear(e)}setCount(e){const t=Array.from(""+this.previousNumber).map((e=>+e));Array.from(""+e).map((e=>+e)).forEach(((i,s)=>{var n;const a=this.getDecimal(s),o=a.animatedSuper.getRow(i,!0),r=null!==(n=t[s])&&void 0!==n?n:Vd.EMPTY_INDEX;o.innerText=a.placeholder.innerText=""+i,a.animatedSuper.animate(i,r,this.reverse?e<this.previousNumber:e>this.previousNumber,!0)})),this.hideLeft(e),this.previousNumber=e}}Vd.EMPTY_INDEX=-1,Vd.BASE_CLASS="animated-counter";class Kd{constructor(e,t,i){this.topbar=e,this.chat=t,this.managers=i,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.scrollDownListenerSetter=null,this.hidden=!1,this.getCurrentIndexPromise=null,this.listenerSetter=new I.Z,this.log=(0,he.kg)("PM"),this.debug=!0,this.isStatic=!1;const o=new Ra("pinned-message");this.pinnedMessageContainer=new Rd({topbar:e,chat:t,listenerSetter:this.listenerSetter,className:"message",divAndCaption:o,onClose:()=>zd(this,void 0,void 0,(function*(){return(yield i.appPeersManager.canPinMessage(this.chat.peerId))?new wc(this.chat.peerId,this.pinnedMid,!0):new wc(this.chat.peerId,0,!0),!1}))}),this.pinnedMessageBorder=new Hd,o.border.replaceWith(this.pinnedMessageBorder.render(1,0)),this.animatedSubtitle=new Gd,o.subtitle.append(this.animatedSubtitle.container),this.animatedMedia=new Gd,this.animatedMedia.container.classList.add("pinned-message-media-container"),o.content.prepend(this.animatedMedia.container),this.animatedCounter=new Vd(!0),o.title.append((0,v.ag)("PinnedMessage")," ",this.animatedCounter.container);const r=this.pinnedMessageContainer.btnClose.cloneNode(!0);this.pinnedMessageContainer.attachOnCloseEvent(r),o.container.prepend(r),this.btnOpen=E("pinlist pinned-container-close pinned-message-pinlist",{noRipple:!0}),this.pinnedMessageContainer.wrapperUtils.prepend(this.btnOpen),(0,n.fc)(this.btnOpen,(e=>{(0,a.Z)(e),this.topbar.openPinned(!0)}),{listenerSetter:this.listenerSetter}),this.listenerSetter.add(s.Z)("peer_pinned_messages",(({peerId:e})=>{e===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(s.Z)("peer_pinned_hidden",(({peerId:e})=>{e===this.chat.peerId&&this.pinnedMessageContainer.toggle(this.hidden=!0)})),this.setPinnedMessage=(0,Ki.Z)((()=>this._setPinnedMessage()),100,!0,!0),this.setCorrectIndexThrottled=(0,mt.Z)(this.setCorrectIndex.bind(this),100,!1),this.isStatic="discussion"===this.chat.type}destroy(){this.pinnedMessageContainer.divAndCaption.container.remove(),this.pinnedMessageContainer.toggle(!0),this.listenerSetter.removeAll(),this.unsetScrollDownListener(!1)}setCorrectIndex(e){if(this.isStatic)return;if(this.locked||this.hidden)return;if((this.loadedBottom||this.loadedTop)&&!this.count)return;const t=this.chat.bubbles.getBubbleByPoint("bottom");if(!t)return;const i=t.dataset.mid;t&&void 0!==i&&this.testMid(+i,e)}testMid(e,t){if(this.isStatic)return;if(this.hidden)return;let i=this.mids.findIndex((t=>t<=e));if(-1===i||this.isNeededMore(i)){if(!(this.loadedTop&&e<this.mids[this.mids.length-1]))return void(this.getCurrentIndexPromise||(this.getCurrentIndexPromise=this.getCurrentIndex(e,void 0!==t)));i=this.mids.length-1+this.offsetIndex}else i+=this.offsetIndex;if(this.pinnedIndex!==i){if(this.waitForScrollBottom&&void 0!==t&&(0===this.pinnedIndex||this.pinnedIndex>i))return;this.pinnedIndex=i,this.pinnedMid=this.mids.find((t=>t<=e))||this.mids[this.mids.length-1],this.setPinnedMessage()}}isNeededMore(e){return this.count>Kd.LOAD_COUNT&&(!this.loadedBottom&&e<=Kd.LOAD_OFFSET||!this.loadedTop&&this.count-1-e<=Kd.LOAD_OFFSET)}getCurrentIndex(e,t=!0){return zd(this,void 0,void 0,(function*(){if(!this.loading){this.loading=!0;try{const i=this.debug?this.log.bindPrefix("getCurrentIndex"):void 0;i&&i("start",e,t);let s=!1;const n=[this.managers.appMessagesManager.getSearch({peerId:this.chat.peerId,inputFilter:{_:"inputMessagesFilterPinned"},maxId:e,limit:Kd.LOAD_COUNT,backLimit:Kd.LOAD_COUNT}).then((e=>(s=!0,e)))];if(!this.pinnedMaxMid){const e=this.managers.appMessagesManager.getPinnedMessage(this.chat.peerId).then((e=>{e.maxId&&(this.pinnedMaxMid=e.maxId,!s&&t&&(this.mids=[this.pinnedMaxMid],this.count=e.count,this.pinnedIndex=0,this.pinnedMid=this.mids[0],this.setPinnedMessage()))}));n.push(e)}const a=(yield Promise.all(n))[0];let o=a.history.findIndex((t=>t.mid<=e));-1===o&&(o=a.history.length),this.offsetIndex=a.offset_id_offset?a.offset_id_offset-o:0,this.mids=a.history.map((e=>e.mid)).slice(),this.count=a.count,this.count||this.pinnedMessageContainer.toggle(!0),this.loadedTop=this.offsetIndex+this.mids.length===this.count,this.loadedBottom=!this.offsetIndex,i&&i("result",e,a,o,this.offsetIndex,this.loadedTop,this.loadedBottom)}catch(e){this.log.error("getCurrentIndex error",e)}this.loading=!1,this.locked?this.testMid(e):t&&this.setCorrectIndex(0),this.getCurrentIndexPromise=null}}))}setScrollDownListener(){this.waitForScrollBottom=!0,this.scrollDownListenerSetter||(this.scrollDownListenerSetter=new I.Z,function(e,t,i,s){if(gi.Z){let t;const n={passive:!0};s.add(e)("touchstart",(i=>{i.touches.length>1?o():(t=i.touches[0].clientY,s.add(e)("touchmove",a,n),s.add(e)("touchend",o,n))}),n);const a=e=>{const s=e.touches[0].clientY,n=s<t;!n||i(),t=s},o=()=>{s.removeManual(e,"touchmove",a,n),s.removeManual(e,"touchend",o,n)}}else s.add(e)("wheel",(e=>{const t=e.deltaY>0;!t||i()}),{passive:!0})}(this.chat.bubbles.scrollable.container,0,(()=>{this.unsetScrollDownListener()}),this.scrollDownListenerSetter))}unsetScrollDownListener(e=!0){this.waitForScrollBottom=!1,this.scrollDownListenerSetter&&(this.scrollDownListenerSetter.removeAll(),this.scrollDownListenerSetter=null),e&&this.setCorrectIndex(0)}handleFollowingPinnedMessage(){return zd(this,void 0,void 0,(function*(){this.locked=!0,this.debug&&this.log("handleFollowingPinnedMessage");try{this.setScrollDownListener();const e=this.chat.setPeerPromise;e instanceof Promise&&(yield e),yield(0,He.e9)(),this.getCurrentIndexPromise&&(yield 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){return zd(this,void 0,void 0,(function*(){(yield this.chat.getMessage(e))&&(this.chat.setMessageId(e),(this.chat.setPeerPromise||Promise.resolve()).then((()=>{this.handleFollowingPinnedMessage(),this.testMid(this.pinnedIndex>=this.count-1?this.pinnedMaxMid:e-1)})))}))}_setPinnedMessage(){return zd(this,void 0,void 0,(function*(){const e=this.count;if(e){const t=this.pinnedIndex,i=yield this.chat.getMessage(this.pinnedMid),s=0===t;this.animatedCounter.container.classList.toggle("is-last",s),s||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),o=this.animatedMedia.getRow(t);o.classList.add("pinned-message-media");const r=[],l=yield Da({title:void 0,titleEl:null,subtitle:i.message,subtitleEl:a,message:i,mediaEl:o,loadPromises:r});yield Promise.all(r),this.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-media",l),this.animatedSubtitle.animate(t,this.wasPinnedIndex),l?(this.animatedMedia.animate(t,this.wasPinnedMediaIndex),this.wasPinnedMediaIndex=t):this.animatedMedia.clearRows(),this.pinnedMessageBorder.render(e,e-t-1),this.wasPinnedIndex=t,this.pinnedMessageContainer.divAndCaption.container.dataset.mid=""+i.mid}else this.pinnedMessageContainer.toggle(!0),this.wasPinnedIndex=0;this.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-many",this.count>1)}))}}Kd.LOAD_COUNT=50,Kd.LOAD_OFFSET=5;var Wd=i(6818);const $d=[{time:3600,langKey:"ChatList.Mute.1Hour"},{time:14400,langKey:"ChatList.Mute.4Hours"},{time:28800,langKey:"ChatList.Mute.8Hours"},{time:86400,langKey:"ChatList.Mute.1Day"},{time:259200,langKey:"ChatList.Mute.3Days"},{time:-1,langKey:"ChatList.Mute.Forever"}];class jd extends qi{constructor(e){super("popup-mute",{peerId:e,titleLangKey:"Notifications",buttons:[{langKey:"ChatList.Context.Mute",callback:()=>{this.managers.appMessagesManager.mutePeer(e,-1===i?le.rU:(0,wl.Z)(!0)+i)}}],body:!0});const t=$d.map((e=>new Ni({radioField:new Vi({langKey:e.langKey,name:"mute-time",value:""+e.time})})));let i;const s=Ui(t,(e=>{i=+e}));this.body.append(s),t[t.length-1].radioField.checked=!0,this.show()}}class qd{constructor(e){this.assets=e,this.tempId=0}playSound(e,t=!1){++this.tempId,this.assetName=e;try{const i=this.createAudio();i.autoplay=!0,i.src="assets/audio/"+e,i.loop=t,i.play()}catch(t){console.error("playSound",e,t)}}playSoundIfDifferent(e,t){this.assetName!==e&&this.playSound(e,t)}createAudio(){let{audio:e}=this;return e||(e=this.audio=new Audio,e.play(),e)}stopSound(){this.audio&&this.audio.pause()}cancelDelayedPlay(){++this.tempId}playSoundWithTimeout(e,t,i){const s=++this.tempId;setTimeout((()=>{this.tempId===s&&this.playSound(e,t)}),i)}}let Qd;function Yd(){const e={channelCount:2};return["noiseSuppression","echoCancellation","autoGainControl"].forEach((t=>{(function(e){var t;return(!!(null===(t=null===navigator||void 0===navigator?void 0:navigator.mediaDevices)||void 0===t?void 0:t.getSupportedConstraints()))[e]})(t)&&(e[t]=!0)})),e}function Jd(e){const t={video:{width:{max:1920},height:{max:1080},frameRate:{max:30}}};return e||(t.audio=!0),t}function Xd(e){return t=this,i=void 0,n=function*(){const t=yield navigator.mediaDevices.getDisplayMedia(e);return t.getVideoTracks()[0].contentHint="text",t},new((s=void 0)||(s=Promise))((function(e,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,r)}l((n=n.apply(t,i||[])).next())}));var t,i,s,n}function eh(e,t){return i=this,s=void 0,a=function*(){const i=yield navigator.mediaDevices.getUserMedia(e);return i.getTracks().forEach((e=>{e.enabled=!t})),i},new((n=void 0)||(n=Promise))((function(e,t){function o(e){try{l(a.next(e))}catch(e){t(e)}}function r(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(o,r)}l((a=a.apply(i,s||[])).next())}));var i,s,n,a}window.getStream=eh;function th(){const e={main:{},screen:{}};return t=>{return i=this,s=void 0,a=function*(){const{isScreen:i,constraints:s}=t,n=e[i?"screen":"main"];let a=n[s.audio?"audio":"video"];a||(a=(i?Xd:eh)(s,t.muted),s.audio&&!n.audio&&(n.audio=a.finally((()=>n.audio=void 0))),s.video&&!n.video&&(n.video=a.finally((()=>n.video=void 0))));try{return yield a}catch(e){throw e}},new((n=void 0)||(n=Promise))((function(e,t){function o(e){try{l(a.next(e))}catch(e){t(e)}}function r(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(o,r)}l((a=a.apply(i,s||[])).next())}));var i,s,n,a}}window.getStreamCached=th;var ih=i(6669);function sh(e){e.stop(),(0,ih.Z)(e,"ended")}class nh{constructor(e="\r\n"){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 ah(e){return e<<0}function oh(e){return e>>>0}function rh(e){return"screencast"===e?"video":e}function lh(e){return"application"===e?"DTLS/SCTP":"UDP/TLS/RTP/SAVPF"}function ch(e,t="9",i){const s=lh(e);return`m=${rh(e)} ${t} ${s} ${i.join(" ")}`}class dh extends nh{addCandidate(e){return this.add(function(e){const t=[];return t.push("a=candidate:"),t.push(`${e.foundation} ${e.component} ${e.protocol.toUpperCase()} ${e.priority} ${e.ip} ${e.port} typ ${e.type}`),void 0!==e["rel-addr"]&&t.push(` raddr ${e["rel-addr"]} rport ${e["rel-port"]}`),t.push(` generation ${e.generation}`),t.join("")}(e))}addHeader(e,t){const i=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 ${i}`,"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 t of e.fingerprints)this.add(`a=fingerprint:${t.hash} ${t.fingerprint}`,`a=setup:${t.setup}`);if(!t&&e.candidates)for(const t of e.candidates)this.addCandidate(t);return this}addSsrc(e){let t="stream",{type:i,sourceGroups:s}=e;const n=oh(e.source);t+=n,i+=n;const a=e=>{this.add(`a=ssrc:${e} cname:${t}`,`a=ssrc:${e} msid:${t} ${i}`,`a=ssrc:${e} mslabel:${t}`,`a=ssrc:${e} label:${i}`)};return(()=>{this.add(`a=msid:${t} ${i}`)})(),(null==s?void 0:s.length)?s.forEach((e=>{if(e.sources.length){const t=e.sources.map(oh);this.add(`a=ssrc-group:${e.semantics} ${t.join(" ")}`),t.forEach(a)}})):a(n),this}addSsrcEntry(e,t,i){const s=(...e)=>this.add(...e),{type:n,mid:a,direction:o,port:r}=e,l=t.transport,c="application"===n,d=c?void 0:t[n],h="inactive"===o;if(e.shouldBeSkipped(i))return s(`m=${rh(n)} 0 ${lh(n)} 0`,"c=IN IP4 0.0.0.0","a=inactive",`a=mid:${a}`);const u=c?[{id:5e3}]:d["payload-types"],p=u.map((e=>e.id));s(ch(n,r,p),"c=IN IP4 0.0.0.0",`a=rtcp:${r} IN IP4 0.0.0.0`),l["rtcp-mux"]&&s("a=rtcp-mux"),s(`a=mid:${a}`);let m=o;if("sendrecv"===o||!i||h||c||(m="sendonly"===o?"recvonly":"sendonly"),s(`a=${m}`),this.addTransport(l),c)s(`a=sctpmap:${u[0].id} webrtc-datachannel 256`);else{const e=d["rtp-hdrexts"];(null==e?void 0:e.length)&&e.forEach((e=>{s(`a=extmap:${e.id} ${e.uri}`)})),u.forEach((e=>{s(`a=rtpmap:${e.id} ${e.name}/${e.clockrate}${e.channels&&e.channels>1?`/${e.channels}`:""}`);const t=e.parameters;if(Array.isArray(t))t.length&&console.error("parameters is array???",t);else if(t&&Object.keys(t).length){const i=[];for(const e in t)i.push(`${e}=${t[e]}`);s(`a=fmtp:${e.id} ${i.join(";")}`)}const i=e["rtcp-fbs"];(null==i?void 0:i.length)&&i.forEach((t=>{s(`a=rtcp-fb:${e.id} ${t.type}${t.subtype?" "+t.subtype:""}`)}))}))}return!e.source||"sendonly"!==m&&"sendrecv"!==m||this.addSsrc(e),this}addConference(e){const{conference:t,entries:i,bundle:s,isAnswer:n}=e;this.addHeader(t.sessionId,s),Je.IS_FIREFOX&&this.addTransport(t.transport);for(const e of i)this.addSsrcEntry((n?e.recvEntry||e.sendEntry:e.sendEntry||e.recvEntry)||e,t,n);return this}static fromConference(e){return(new dh).addConference(e).finalize()}}class hh{constructor(e,t){const i=this.streamSource=e.createMediaStreamSource(t),s=this.analyser=e.createAnalyser();this.gain=e.createGain(),s.minDecibels=-100,s.maxDecibels=-30,s.smoothingTimeConstant=.05,s.fftSize=1024,i.connect(s)}}class uh{constructor(e){this.interval=e,this.getAmplitude=e=>{const{streamAnalyser:t,stream:i,track:s,source:n,type:a}=e,o=t.analyser;if(!o)return;const r=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(r);const l=function(e,t=3){if(!e)return 0;const{length:i}=e;let s=0;for(let t=0;t<i;++t)s+=e[t]*e[t];const n=Math.sqrt(s/i)/255;return Math.min(1,n*t)}(r);return{type:a,source:n,stream:i,track:s,value:l}},this.analyse=()=>{const e=this.counter%3==0,t=e?this.items:this.items.filter((e=>"input"===e.type)),i=t.filter((e=>"audio"===e.kind)),s=i.slice(0,50).map(this.getAmplitude);++this.counter>=1e3&&(this.counter=0),uh.ANALYSER_LISTENER.dispatchEvent("amplitude",{amplitudes:s,type:e?"all":"input"})},this.context=new(window.AudioContext||window.webkitAudioContext),this.items=[],this.outputStream=new MediaStream,this.inputStream=new MediaStream,this.counter=0,this.log=(0,he.kg)("SM"),this.direction="sendonly",this.canCreateConferenceEntry=!0,this.types=["audio","video"]}addStream(e,t){e.getTracks().forEach((i=>{this.addTrack(e,i,t)}))}addTrack(e,t,i){this.log("addTrack",i,t,e);const{context:s,items:n,inputStream:a,outputStream:o}=this,r=t.kind,l=uh.getSource(e,i);switch(i){case"input":a?a.addTrack(t):this.inputStream=e;break;case"output":for(let e=0;e<n.length;++e){const{track:t,type:i,source:s}=n[e];if(s===l&&"input"===i){n.splice(e,1),o.removeTrack(t);break}}"video"!==r&&o.addTrack(t)}this.finalizeAddingTrack({type:i,source:l,stream:e,track:t,kind:r,streamAnalyser:"audio"===r?new hh(s,e):void 0}),"audio"===r&&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=>"input"===t.type&&t.kind===e))}static getSource(e,t){return"input"===t?e.source||e.id:""+ah(+e.id.substring(6))}removeTrack(e){this.log("removeTrack",e);const{items:t}=this;let i=!1;for(let s=0,n=t.length;!i&&s<n;++s){const{track:n,type:a}=t[s];switch(a){case"output":n===e&&(t.splice(s,1),this.outputStream.removeTrack(e),i=!0);break;case"input":n===e&&(t.splice(s,1),this.inputStream.removeTrack(e),i=!0)}}"audio"===e.kind&&this.interval&&this.changeTimer()}replaceInputAudio(e,t){this.removeTrack(t),this.addStream(e,"input")}changeTimer(){void 0!==this.timer&&clearInterval(this.timer),this.items.length&&(this.timer=window.setInterval(this.analyse,this.interval))}appendToConference(e){if(this.locked)return;const{inputStream:t,direction:i,canCreateConferenceEntry:s}=this,n={direction:i,streams:[t]},a=this.types.map((e=>[e,n])),o=t.getTracks();for(const[t,n]of a){let a=e.findEntry((e=>e.direction===i&&e.type===t));if(!a){if(!s)continue;a=e.createEntry(t)}let{transceiver:r}=a;r||(r=a.createTransceiver(e.connection,n)),a.direction!==r.direction&&(r.direction=a.direction);const l=rh(t),c=o.findIndex((e=>e.kind===l)),d=-1!==c?o.splice(c,1)[0]:void 0,h=r.sender;h.track!==d&&h.replaceTrack(d).catch((e=>{this.log.error(e)}))}}stop(){try{this.inputStream.getTracks().concat(this.outputStream.getTracks()).forEach((e=>{sh(e)}))}catch(e){this.log.error(e)}}}uh.ANALYSER_LISTENER=new L.Z;class ph extends L.Z{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=th()}get isSharingAudio(){return!!this.streamManager.hasInputTrackKind("audio")}get isSharingVideo(){return!!this.streamManager.hasInputTrackKind("video")}fixSafariAudio(){this.audio.play().catch(ft.Z)}requestAudioSource(e){return this.requestInputSource(!0,!1,e)}requestInputSource(e,t,i){const{streamManager:s}=this;if(s){const i=!e||this.isSharingAudio,s=!t||this.isSharingVideo;if(i&&s)return Promise.resolve()}const n={audio:e&&Yd(),video:t&&{width:{min:1280,max:1920},height:{min:720,max:1080},frameRate:{min:24,max:30}}};return this.getStream({constraints:n,muted:i}).then((e=>{this.onInputStream(e)}))}requestScreen(){return this.getStream({isScreen:!0,constraints:Jd(!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 i=e.getVideoTracks()[0];this.tryAddTrack({stream:e,track:i,type:"input",source:t||"main"})}tryAddTrack({stream:e,track:t,type:i,source:s}){s||(s=uh.getSource(e,i)),this.log("tryAddTrack",e,t,i,s);const n="output"===i,{player:a,elements:o,streamManager:r}=this,l=t.kind,c="video"===l,d=c?s:l;let h=o.get(d);c&&t.addEventListener("ended",(()=>{this.log("[track] onended"),o.delete(d)}),{once:!0}),n&&r.addTrack(e,t,i);const u=c?e:r.outputStream;if(h)h.paused&&h.play().catch(ft.Z),h.srcObject=u;else{if(h=document.createElement(l),h.autoplay=!0,h.srcObject=u,h.volume=1,"undefined"!==h.sinkId){const{outputDeviceId:e}=this;e&&h.setSinkId(e)}c?(h.setAttribute("playsinline","true"),h.muted=!0):a.appendChild(h),o.set(d,h)}return s}setMuted(e){this.streamManager.inputStream.getAudioTracks().forEach((t=>{"audio"===(null==t?void 0:t.kind)&&(t.enabled=void 0===e?!t.enabled:!e)}))}onInputStream(e){if(this.isClosing)e.getTracks().forEach((e=>{sh(e)}));else{e.getVideoTracks().length&&this.saveInputVideoStream(e,"main");const{streamManager:t,description:i}=this;t.addStream(e,"input"),i&&t.appendToConference(i)}}}class mh{constructor(e,t){this.mid=e,this.type=t,this.port="9"}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(null==t?void 0:t.direction)&&this.setDirection(t.direction),this.transceiver=e.addTransceiver(rh(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&&"inactive"===this.direction}}function gh(e,t,i){let s;if(Array.isArray(t)){if(!t[0])return;s=t,t=s[0].sources[0]}return{endpoint:i,type:e,source:t,sourceGroups:s}}class vh{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(0,x.Z)(this,e)}createEntry(e){const t=""+ ++this.maxSeenId,i=new mh(t,e);return this.entries.push(i),this.entriesByMid.set(t,i),i}deleteEntry(e){(0,T.Z)(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 i=this.entriesByPeerId.get(t);i||this.entriesByPeerId.set(t,i=new Set),i.add(e)}findEntry(e){return this.entries.find(e)}findFreeSendRecvEntry(e,t){let i=this.entries.find((i=>"sendrecv"===i.direction&&i.type===e&&!(t?i.sendEntry:i.recvEntry)));return i||(i=this.createEntry(e),i.setDirection("sendrecv")),i}getEntryByMid(e){return this.entriesByMid.get(e)}getEntryBySource(e){return this.entriesBySource.get(e)}getEntriesByPeerId(e){return this.entriesByPeerId.get(e)}generateSdp(e){return dh.fromConference(Object.assign({conference:this},e))}}class fh{constructor(e){var t;(0,x.Z)(this,e),this.log||(this.log=(null===(t=this.connection)||void 0===t?void 0:t.log)||(0,he.kg)("CALL-CONNECTION-BASE")),this.sources={}}createPeerConnection(e){return this.connection||(this.connection=function(e,t){t||(t=(0,he.kg)("RTCPeerConnection")),t("constructor");const i=new RTCPeerConnection(e);return i.addEventListener("track",(e=>{t("ontrack",e)})),i.addEventListener("signalingstatechange",(()=>{t("onsignalingstatechange",i.signalingState)})),i.addEventListener("connectionstatechange",(()=>{t("onconnectionstatechange",i.connectionState)})),i.addEventListener("negotiationneeded",(()=>{t("onnegotiationneeded",i.signalingState)})),i.addEventListener("icecandidate",(e=>{t("onicecandidate",e)})),i.addEventListener("iceconnectionstatechange",(()=>{t("oniceconnectionstatechange",i.iceConnectionState)})),i.addEventListener("datachannel",(()=>{t("ondatachannel")})),i.log=t,{connection:i}}(e,this.log.bindPrefix("connection")).connection)}createDataChannel(e){return this.dataChannel||(this.dataChannel=function(e,t,i){i||(i=(0,he.kg)("RTCDataChannel"));const s=e.createDataChannel("data",t);return s.addEventListener("message",(e=>{i("onmessage",e)})),s.addEventListener("open",(()=>{i("onopen")})),s.addEventListener("close",(()=>{i("onclose")})),s.log=i,s}(this.connection,e,this.log.bindPrefix("data")))}createDescription(){return this.description||(this.description=new vh(this.connection))}appendStreamToConference(){return this.streamManager.appendToConference(this.description)}closeConnection(){const{connection:e}=this;if(e)try{e.log("close"),e.close()}catch(e){this.log.error(e)}}closeConnectionAndStream(e){this.closeConnection(),e&&this.streamManager.stop()}negotiate(){return this.negotiating||(this.negotiating=this.negotiateInternal().finally((()=>{this.negotiating=void 0})))}sendDataChannelData(e){"open"===this.dataChannel.readyState&&this.dataChannel.send(JSON.stringify(e))}}var yh,bh,wh=function(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i},Sh=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Ch{constructor(e,t){yh.set(this,void 0),bh.set(this,void 0),wh(this,yh,e,"f"),wh(this,bh,t,"f")}get session(){return Sh(this,yh,"f")}get media(){return Sh(this,bh,"f")}get bundle(){const e=this.session.lines.find((e=>{var t;return"group"===(null===(t=e.parsed)||void 0===t?void 0:t.key)}));return e.value.split(" ").slice(1)}toString(){return this.session.lines.concat(...this.media.map((e=>e.lines))).map((e=>e.toString())).join("\r\n")+"\r\n"}}function Lh(e,t,i){const s=e.split(t),n=[];for(;i>0&&s.length;)n.push(s.shift()),--i;return s.length&&n.push(s.join(t)),n}yh=new WeakMap,bh=new WeakMap;var Ih,Mh,Eh,Ph=function(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i},kh=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Th{constructor(e,t){Ih.set(this,void 0),Mh.set(this,void 0),Eh.set(this,void 0),Ph(this,Ih,new Set,"f"),Ph(this,Mh,e,"f"),Ph(this,Eh,t,"f")}generate(){const e=kh(this,Mh,"f"),t=kh(this,Eh,"f"),i=kh(this,Ih,"f"),s=t-e+1;let n=Math.floor(e+s*Math.random()),a=0;for(;i.has(n);)if(n<t?++n:n=e,++a>=s)return null;return i.add(n),n}add(e){kh(this,Ih,"f").add(e)}}Ih=new WeakMap,Mh=new WeakMap,Eh=new WeakMap;var xh,_h,Ah=function(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i},Zh=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Fh{constructor(e,t){xh.set(this,void 0),_h.set(this,void 0),Ah(this,xh,e,"f"),Ah(this,_h,t,"f")}get key(){return Zh(this,xh,"f")}get value(){return Zh(this,_h,"f")}}xh=new WeakMap,_h=new WeakMap;var Dh,Rh,Bh,Nh,Uh=function(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i},Oh=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Hh{constructor(e,t,i,s){Dh.set(this,void 0),Rh.set(this,void 0),Bh.set(this,void 0),Nh.set(this,void 0),Uh(this,Dh,e,"f"),Uh(this,Rh,t,"f"),Uh(this,Bh,i,"f"),Uh(this,Nh,s,"f")}get type(){return Oh(this,Dh,"f")}get port(){return Oh(this,Rh,"f")}get protocol(){return Oh(this,Bh,"f")}get ids(){return Oh(this,Nh,"f")}toString(){return this.type+" "+this.port+" "+this.protocol+" "+this.ids.join(" ")}}Dh=new WeakMap,Rh=new WeakMap,Bh=new WeakMap,Nh=new WeakMap;var zh,Gh,Vh,Kh,Wh=function(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i},$h=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class jh{constructor(e,t){if(zh.set(this,void 0),Gh.set(this,void 0),Vh.set(this,void 0),Kh.set(this,void 0),Wh(this,zh,e,"f"),"string"==typeof t){if(Wh(this,Gh,t,"f"),"m"===e){const e=t.split(" ");Wh(this,Vh,new Hh(e[0],e[1],e[2],e.slice(3)),"f")}else if("a"===e){const e=Lh(t,":",1);t=e[0],Wh(this,Kh,1===e.length?new Fh(t,null):new Fh(t,e[1]),"f")}}else t instanceof Hh?(Wh(this,Vh,t,"f"),Wh(this,Gh,t.toString(),"f")):t instanceof Fh&&(Wh(this,Kh,t,"f"),Wh(this,Gh,t.value?`${t.key}:${t.value}`:t.key,"f"))}get key(){return $h(this,zh,"f")}get value(){return $h(this,Gh,"f")}get parsed(){return $h(this,Kh,"f")}get mediaLineParts(){return $h(this,Vh,"f")}toString(){return`${this.key}=${this.value}`}}zh=new WeakMap,Gh=new WeakMap,Vh=new WeakMap,Kh=new WeakMap;var qh,Qh,Yh,Jh,Xh,eu,tu=function(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i},iu=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class su{constructor(e,t,i=":",s=!1){qh.set(this,void 0),Qh.set(this,void 0),Yh.set(this,void 0),Jh.set(this,void 0),Xh.set(this,void 0),eu.set(this,void 0),tu(this,qh,e,"f"),tu(this,Qh,t,"f"),tu(this,Yh,i,"f"),tu(this,Xh,s,"f"),tu(this,Jh,s?new Map:null,"f"),tu(this,eu,s?[]:null,"f")}get lines(){return iu(this,Qh,"f")}get value(){return iu(this,Xh,"f")||!this.lines.length?null:this.lines[0]}get exists(){return!iu(this,Xh,"f")}get key(){return iu(this,qh,"f")}get keys(){return su.fill(this),iu(this,eu,"f")}forEach(e){su.fill(this),iu(this,Jh,"f").forEach(e)}get(e){return su.fill(this),iu(this,Jh,"f").get(e)||new su(e,[],":",!0)}static fill(e){if(null!==iu(e,Jh,"f"))return;const t=new Map;e.lines.forEach((i=>{const[s,n]=Lh(i,iu(e,Yh,"f"),1),a=t.get(s)||[];t.set(s,[...a,n||""])}));const i=tu(e,Jh,su.makeAttributes(t),"f");tu(e,eu,Array.from(i.keys()),"f")}static makeAttributes(e){const t=new Map;return e.forEach(((e,i)=>{t.set(i,new su(i,e))})),t}}qh=new WeakMap,Qh=new WeakMap,Yh=new WeakMap,Jh=new WeakMap,Xh=new WeakMap,eu=new WeakMap;var nu,au,ou=function(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i},ru=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class lu{constructor(e){nu.set(this,void 0),au.set(this,void 0),ou(this,nu,e,"f"),ou(this,au,new Map,"f"),lu.fillAttributes(this)}get(e){return ru(this,au,"f").get(e)||new su(e,[]," ",!0)}static fillAttributes(e){const t=new Map;ru(e,nu,"f").forEach((e=>{if("a"===e.key){const{key:i,value:s}=e.parsed;let n=t.get(i);n||(n=[],t.set(i,n)),n.push(s||"")}})),t.forEach(((t,i)=>{ru(e,au,"f").set(i,new su(i,t," ",!1))}))}}nu=new WeakMap,au=new WeakMap;var cu,du,hu,uu,pu=function(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i},mu=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class gu{constructor(e){cu.set(this,void 0),du.set(this,void 0),hu.set(this,void 0),uu.set(this,void 0),pu(this,cu,e,"f"),pu(this,du,e[0],"f"),pu(this,hu,pu(this,uu,null,"f"),"f")}get lines(){return mu(this,cu,"f")}get mediaLine(){return mu(this,du,"f")}get mediaLineParts(){return mu(this,du,"f").mediaLineParts}get mediaType(){return this.mediaLineParts.type}get direction(){if(!mu(this,uu,"f")){const e=this.attributes;let t;t=e.get("sendonly").exists?"sendonly":e.get("recvonly").exists?"recvonly":e.get("inactive").exists?"inactive":"sendrecv",pu(this,uu,t,"f")}return mu(this,uu,"f")}get isSending(){return"sendrecv"===this.direction||"sendonly"===this.direction}get isReceiving(){return"sendrecv"===this.direction||"recvonly"===this.direction}get attributes(){return mu(this,hu,"f")||pu(this,hu,new lu(this.lines),"f"),mu(this,hu,"f")}get mid(){return this.attributes.get("mid").value}lookupAttributeKeys(e){const t={};for(const i in e){const s=this.attributes.get(i),n=!e[i];t[i]=s?n?s.lines:s.value:n?[]:void 0}return t}}cu=new WeakMap,du=new WeakMap,hu=new WeakMap,uu=new WeakMap;var vu,fu,yu=function(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i},bu=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class wu{constructor(e){vu.set(this,void 0),fu.set(this,void 0),yu(this,vu,e,"f"),yu(this,fu,e.filter((e=>"o"===e.key)).map((e=>e.value.split(" ")[1]))[0],"f")}get lines(){return bu(this,vu,"f")}get sessionId(){return bu(this,fu,"f")}}function Su(e){function t(){i?n.push(new gu(s)):i=new wu(s)}let i=null,s=[];const n=[];return e.split(/\r?\n/).forEach((e=>{if(!function(e){return/^[\s\xa0]*$/.test(e)}(e)){const i=Cu(e);"m"===i.key&&(t(),s=[]),s.push(i)}})),t(),new Ch(i,n)}function Cu(e){const t=Lh(e,"=",1);return new jh(t[0],t[1])}function Lu(e,t){const i=t.lookupAttributeKeys({"ice-ufrag":!0,"ice-pwd":!0,fingerprint:!0,setup:!0,ssrc:!0,mid:!0,"ssrc-group":!1});if(!i.fingerprint){const t=e.session.lines.find((e=>{var t;return"fingerprint"===(null===(t=e.parsed)||void 0===t?void 0:t.key)}));i.fingerprint=t.parsed.value}const s=function(e){const t=e.map((e=>{const[t,...i]=e.split(" ");return{_:"groupCallParticipantVideoSourceGroup",semantics:t,sources:i.map((e=>ah(+e)))}}));return t.length?t:void 0}(i["ssrc-group"]),[n,a]=i.fingerprint.split(" ",2),o=i.ssrc&&ah(+i.ssrc.split(" ",1)[0]);return{raw:i,ufrag:i["ice-ufrag"],pwd:i["ice-pwd"],fingerprint:{fingerprint:a,setup:i.setup,hash:n},source:o,sourceGroups:s,mid:i.mid}}vu=new WeakMap,fu=new WeakMap;var Iu,Mu=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Eu extends fh{constructor(e){super(e),this.negotiateThrottled=(0,mt.Z)(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()}invokeJoinGroupCall(e,t,i){return Mu(this,void 0,void 0,(function*(){const{groupCall:n,description:a}=this,o=n.id,r=t.map((t=>{const i=function(e,t){const i=Lu(e,t),s=t.mediaType,n={source:i.source,sourceGroups:i.sourceGroups,type:s};i.fingerprint.setup="active";const a={fingerprints:[i.fingerprint],pwd:i.pwd,ssrc:i.source,"ssrc-groups":i.sourceGroups||[],ufrag:i.ufrag};return{params:{_:"dataJSON",data:JSON.stringify(a)},source:i.source,media:t,sourceGroups:i.sourceGroups,entry:n}}(e,t);return this.sources[i.entry.type]=i.entry,i})),l=r.find((e=>"audio"===e.media.mediaType)),c=r.find((e=>"video"===e.media.mediaType));let{source:d,params:h}=l||{};const u=c||l,p={audio:l,video:c};if(a.entries.forEach((e=>{if("sendonly"===e.direction){const t=p[e.type];if(!t)return;a.setEntrySource(e,t.sourceGroups||t.source),a.setEntryPeerId(e,s.Z.myId)}})),h!==u.params){const e=JSON.parse(u.params.data);d?e.ssrc=d:delete e.ssrc,h={_:"dataJSON",data:JSON.stringify(e)}}const m=yield this.managers.appGroupCallsManager.joinGroupCall(o,h,i),g=JSON.parse(m.params.data);return g.audio=g.audio||n.connections.main.description.audio,a.setData(g),function(e,t){["audio","video"].filter((e=>t[e])).map((e=>[t[e],e])).forEach((([t,i])=>{const s=e.find((e=>e.mediaType===i));if(!s)return;const n=(e=>{const t={};return e.attributes.get("extmap").forEach((e=>{const i=e.key.split("/",1)[0];t[i]=e.value})),t})(s);(0,Mn.Z)(t["rtp-hdrexts"],((e,t,s)=>{n[e.id]!==e.uri&&(s.splice(t,1),console.log("[sdp] filtered extmap:",e,t,i))}))}))}(t,g),g}))}negotiateInternal(){return Mu(this,void 0,void 0,(function*(){const{connection:e,description:t}=this,i="new"===e.iceConnectionState&&!t.getEntryByMid("0").source,s=this.log.bindPrefix("startNegotiation");s("start");const n=yield e.createOffer({iceRestart:!1});i&&this.dataChannel&&t.createEntry("application").setDirection("sendrecv");const{sdp:a,offer:o}=function(e){const{offer:t,data:i}=e,s=Su(t.sdp);let n=!1;if(e.skipAddingMulticast||(n=function(e){let t;return e.media.forEach(((i,s)=>{if("video"===i.mediaType&&i.isSending&&!i.attributes.get("ssrc-group").get("SIM").exists){t||(t=new Th(2,4294967295));const n=i.attributes.get("ssrc-group").get("FID").value.split(" "),a=i.lines;n.forEach((e=>t.add(+e)));const o=[n[0],t.generate(),t.generate()],r=[n[1],t.generate(),t.generate()];a.push(Cu("a=ssrc-group:SIM "+o.join(" ")));const l=i.attributes.get("ssrc").get(n[0]).lines;o.forEach(((e,t)=>{const i=r[t];t>0&&(a.push(Cu("a=ssrc-group:FID "+e+" "+i)),l.forEach((t=>{a.push(Cu("a=ssrc:"+e+" "+t))})),l.forEach((e=>{a.push(Cu("a=ssrc:"+i+" "+e))})))})),e.media[s]=new gu(a)}})),!!t}(s)||n),(0,Mn.Z)(s.media,((e,t,a)=>{if(e.isSending)return;if("application"===e.mediaType)return;const o=e.mediaLine,r=o.mediaLineParts,l=(r.ids,o.toString()),c=i[e.mediaType]["payload-types"].map((e=>""+e.id));if(l!==ch(e.mediaType,void 0,c)){const o=Lu(s,e),l=Object.assign({},i);l.transport=(0,Ji.Z)(l.transport),l.transport.ufrag=o.ufrag,l.transport.pwd=o.pwd,l.transport.fingerprints=[o.fingerprint],l.transport.candidates=[];const c=new mh(o.mid,r.type);c.setPort(r.port),o.source&&c.setSource(o.sourceGroups||o.source),c.setDirection(e.direction);const d=Su((new dh).addSsrcEntry(c,l).finalize()).media[0];a[t]=d,n=!0}})),n){const e=s.toString();t.sdp=e}return{offer:t,sdp:s}}({offer:n,data:t});s("[sdp] setLocalDescription",o.sdp),yield e.setLocalDescription(o);const r=a.media.filter((e=>"application"!==e.mediaType&&e.isSending));if(i)try{yield this.invokeJoinGroupCall(a,r,this.options)}catch(e){this.log.error("[tdweb] joinGroupCall error",e)}const l=[],c=a.bundle;(0,Mn.Z)(c,((e,i,s)=>{const n=t.getEntryByMid(e);n.shouldBeSkipped(!0)&&(s.splice(i,1),l.push(n))}));const d=a.media.map((e=>{const i=e.mid;let s=t.getEntryByMid(i);return s||(s=new mh(i,e.mediaType),s.setDirection("inactive")),s})),h={type:"answer",sdp:t.generateSdp({bundle:c,entries:d,isAnswer:!0})};l.forEach((e=>{t.deleteEntry(e)})),s(`[sdp] setRemoteDescription signaling=${e.signalingState} ice=${e.iceConnectionState} gathering=${e.iceGatheringState} connection=${e.connectionState}`,h.sdp),yield e.setRemoteDescription(h),s("end")}))}negotiate(){let e=this.negotiating;return e||(e=super.negotiate(),this.updateConstraints&&e.then((()=>{this.maybeUpdateRemoteVideoConstraints(),this.updateConstraints=!1})),"presentation"===this.options.type&&e.then((()=>{this.connection.getTransceivers().find((e=>{var t,i;"video"===(null===(i=null===(t=e.sender)||void 0===t?void 0:t.track)||void 0===i?void 0:i.kind)&&e.sender.setParameters(Object.assign(Object.assign({},e.sender.getParameters()),{degradationPreference:"maintain-resolution"}))}))})),e)}maybeUpdateRemoteVideoConstraints(){if("open"!==this.dataChannel.readyState)return;this.log("maybeUpdateRemoteVideoConstraints");const e={colibriClass:"ReceiverVideoConstraints",constraints:{},defaultConstraints:{maxHeight:0},onStageEndpoints:[]};for(const t of this.description.entries){if("recvonly"!==t.direction||"video"!==t.type)continue;const{endpoint:i}=t;e.onStageEndpoints.push(i),e.constraints[i]={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()}}!function(e){e[e.UNMUTED=0]="UNMUTED",e[e.MUTED=1]="MUTED",e[e.MUTED_BY_ADMIN=2]="MUTED_BY_ADMIN",e[e.CONNECTING=3]="CONNECTING",e[e.CLOSED=4]="CLOSED"}(Iu||(Iu={}));const Pu=Iu;var ku=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Tu extends ph{constructor(e){super(),(0,x.Z)(this,e),this.log||(this.log=(0,he.kg)("GROUP-CALL")),this.connections||(this.connections={}),this.isSpeakingMap||(this.isSpeakingMap=new Map),this.pinnedSources=[],this.participantsSsrcs=new Map,this.hadAutoPinnedSources=new Set,this.dispatchPinnedThrottled=(0,mt.Z)((()=>{this.dispatchEvent("pinned",this.pinnedSource)}),0,!1),this.addEventListener("state",(e=>{e===Pu.CLOSED&&this.cleanup()}))}get connectionState(){return this.connections.main.connection.iceConnectionState}get state(){const{connectionState:e}=this;if("closed"===e)return Pu.CLOSED;if("connected"===e||Je.IS_SAFARI&&"completed"===e){const{participant:e}=this;return e.pFlags.can_self_unmute?e.pFlags.muted?Pu.MUTED:Pu.UNMUTED:Pu.MUTED_BY_ADMIN}return Pu.CONNECTING}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!==Pu.UNMUTED}get isClosing(){const{state:e}=this;return e===Pu.CLOSED}get streamManager(){return this.connections.main.streamManager}get description(){return this.connections.main.description}pinSource(e){(0,T.Z)(this.pinnedSources,e),this.pinnedSources.push(e),this.dispatchPinnedThrottled()}unpinSource(e){this.hadAutoPinnedSources.delete(e),(0,T.Z)(this.pinnedSources,e),this.dispatchPinnedThrottled()}unpinAll(){this.pinnedSources.length=0,this.dispatchPinnedThrottled()}getParticipantByPeerId(e){return ku(this,void 0,void 0,(function*(){return le.NM===e?this.participant:(yield this.participants).get(e)}))}toggleMuted(){return this.requestAudioSource(!0).then((()=>this.changeUserMuted(le.NM)))}changeUserMuted(e,t){return ku(this,void 0,void 0,(function*(){const i=yield this.getParticipantByPeerId(e);return le.NM===e&&i.pFlags.can_self_unmute&&(t=void 0===t?!i.pFlags.muted:t),this.editParticipant(i,{muted:t})}))}getElement(e){return super.getElement(e)}getVideoElementFromParticipantByType(e,t){let i;i=e.pFlags.self?"video"===t?"main":"presentation":e[t].source_groups[0].sources[0];const s=this.getElement(i);if(!s)return;const n=s.cloneNode();return n.srcObject=s.srcObject,{video:n,source:i}}createConnectionInstance(e){return this.connections[e.type]=new Eu(Object.assign({groupCall:this,log:this.log.bindPrefix(e.type),managers:this.managers},e))}changeRaiseHand(e){return this.editParticipant(this.participant,{raiseHand:e})}startScreenSharingInternal(){return ku(this,void 0,void 0,(function*(){try{const e="presentation",t=yield Xd(Jd()),i=new uh,s=this.createConnectionInstance({streamManager:i,type:e,options:{type:e}});s.createPeerConnection().addEventListener("negotiationneeded",(()=>{s.negotiate()})),t.getVideoTracks()[0].addEventListener("ended",(()=>{this.connections.presentation&&this.stopScreenSharing()}),{once:!0}),s.createDescription(),s.addInputVideoStream(t)}catch(e){this.log.error("start screen sharing error",e)}}))}startScreenSharing(){var e;return null!==(e=this.startScreenSharingPromise)&&void 0!==e?e: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()}startVideoSharingInternal(){return ku(this,void 0,void 0,(function*(){const e={video:{width:{min:1280,max:1920},height:{min:720,max:1080},frameRate:{min:24,max:30}}};try{const t=yield eh(e,!1);this.connections.main.addInputVideoStream(t),yield this.editParticipant(this.participant,{videoPaused:!1,videoStopped:!1})}catch(t){this.log.error("startVideoSharing error",t,e)}}))}startVideoSharing(){var e;return null!==(e=this.startVideoSharingPromise)&&void 0!==e?e:this.startVideoSharingPromise=this.startVideoSharingInternal().finally((()=>{this.startVideoSharingPromise=void 0}))}stopVideoSharing(){return ku(this,void 0,void 0,(function*(){const e=this.connections.main,t=e.streamManager.inputStream.getVideoTracks()[0];t&&(sh(t),e.streamManager.appendToConference(e.description),yield this.editParticipant(this.participant,{videoStopped:!0}))}))}toggleVideoSharing(){return this.isSharingVideo?this.stopVideoSharing():this.startVideoSharing()}hangUp(e=!1,t=!1,i=!1){return ku(this,void 0,void 0,(function*(){for(const e in this.connections)this.connections[e].closeConnectionAndStream(!t);if(this.dispatchEvent("state",this.state),!i&&!t){const t=e||(this.joined?this.connections.main.sources.audio.source:void 0);this.managers.appGroupCallsManager.hangUp(this.id,t)}}))}tryAddTrack(e){const{description:t}=this,i=super.tryAddTrack(e);if("output"===e.type){const e=t.getEntryBySource(+i);this.getParticipantByPeerId(e.peerId).then((e=>{e&&s.Z.dispatchEvent("group_call_participant",{groupCallId:this.id,participant:e})}))}return i}editParticipant(e,t){return ku(this,void 0,void 0,(function*(){if(Object.keys(t).length){if(e){const s=e.pFlags.self;if(s&&void 0!==t.muted&&!this.isSharingAudio&&(delete t.muted,!Object.keys(t).length))return;const n=t.muted;void 0!==n&&e.pFlags.self&&(n?e.pFlags.muted=!0:e.pFlags.can_self_unmute&&delete e.pFlags.muted),void 0!==t.raiseHand&&(t.raiseHand?e.raise_hand_rating="1":delete e.raise_hand_rating),s&&(void 0!==t.videoStopped&&(t.videoStopped?delete e.video:e.video=(i=this.connections.main.sources.video)&&{_:"groupCallParticipantVideo",pFlags:{},endpoint:"",source_groups:i.sourceGroups,audio_source:undefined}),!e.pFlags.muted&&e.pFlags.can_self_unmute&&this.setMuted(!1),this.dispatchEvent("state",this.state))}var i;return this.managers.appGroupCallsManager.editParticipant(this.id,e,t)}}))}onParticipantUpdate(e,t){const i=this.connections.main,{connection:s,description:n}=i,a=(0,es.Z)(e.peer),o=!!e.pFlags.left,r=this.participantsSsrcs.get(a)||[];if(e.presentation&&!o){const{source:t}=_u(0,"video",e.presentation.source_groups,e.presentation.endpoint);this.hadAutoPinnedSources.has(t)||(this.hadAutoPinnedSources.add(t),this.pinSource(e.pFlags.self?"presentation":t))}if(e.pFlags.self){this.participant=e,i.sources.audio.source!==e.source&&this.hangUp();let s=!1;return e.pFlags.can_self_unmute?e.pFlags.muted&&(s=!0):(this.stopScreenSharing(),this.stopVideoSharing(),s=!0),s&&this.setMuted(!0),void(t!==a&&this.dispatchEvent("state",this.state))}const l=o?[]:function(e){var t,i;return[_u(0,"audio",e.source),(null===(t=e.video)||void 0===t?void 0:t.audio_source)&&_u(0,"audio",e.video.audio_source),e.video&&_u(0,"video",e.video.source_groups,e.video.endpoint),(null===(i=e.presentation)||void 0===i?void 0:i.audio_source)&&_u(0,"audio",e.presentation.audio_source),e.presentation&&_u(0,"video",e.presentation.source_groups,e.presentation.endpoint)].filter(Boolean)}(e);o?this.participantsSsrcs.delete(a):this.participantsSsrcs.set(a,l);const c=new Set;r.forEach((e=>{const t=e.source;if(!l.find((e=>e.source===t))){this.unpinSource(t);const e=n.getEntryBySource(t);e&&"inactive"!==e.direction&&(e.setDirection("inactive"),c.add(e.type))}})),l.forEach((e=>{let t=n.getEntryBySource(e.source);t?"inactive"===t.direction&&(t.setDirection(t.originalDirection),c.add(t.type)):(t=n.createEntry(e.type),n.setEntrySource(t,e.sourceGroups||e.source),n.setEntryPeerId(t,a),"video"===e.type&&t.setEndpoint(e.endpoint),t.createTransceiver(s,{direction:"recvonly"}),c.add(t.type))})),c.size&&(c.has("video")&&(i.updateConstraints=!0),i.negotiateThrottled())}}var xu=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};function _u(e,t,i,s){return gh(t,i,s)}class Au extends L.Z{construct(e){this.managers=e,this.audioAsset=null!=Qd?Qd:Qd=new qd(["group_call_connect.mp3","group_call_end.mp3","group_call_start.mp3","voip_onallowtalk.mp3"]),this.log=(0,he.kg)("GCC"),s.Z.addEventListener("group_call_update",(e=>{const{currentGroupCall:t}=this;(null==t?void 0:t.id)===e.id&&(t.groupCall=e,"groupCallDiscarded"===e._&&t.hangUp(!1,!1,!0))})),s.Z.addEventListener("group_call_participant",(({groupCallId:e,participant:t})=>{const{currentGroupCall:i}=this;(null==i?void 0:i.id)===e&&i.onParticipantUpdate(t)}))}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()}joinGroupCall(e,t,i=!0,s,n){return xu(this,void 0,void 0,(function*(){let a;return this.audioAsset.createAudio(),this.log(`joinGroupCall chatId=${e} id=${t} muted=${i} rejoin=${s}`),a=s?this.currentGroupCall.connections.main.streamManager:yield function(e,t){return i=this,s=void 0,a=function*(){const i={audio:Yd(),video:t&&{width:{min:1280,max:1920},height:{min:720,max:1080},frameRate:{min:24,max:30}}},s=new uh(100);try{const t=yield eh(i,e);s.addStream(t,"input")}catch(e){console.error("joinGroupCall getStream error",e,i),s.inputStream=new MediaStream}return s},new((n=void 0)||(n=Promise))((function(e,t){function o(e){try{l(a.next(e))}catch(e){t(e)}}function r(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(o,r)}l((a=a.apply(i,s||[])).next())}));var i,s,n,a}(i,n),this.joinGroupCallInternal(e,t,a,i,s,n)}))}joinGroupCallInternal(e,t,i,n,a=!1,o){return xu(this,void 0,void 0,(function*(){const r=this.log.bindPrefix("joinGroupCallInternal");r("start",t);const l="main";let{currentGroupCall:c}=this;if(!c||!a){c=new Tu({chatId:e,id:t,managers:this.managers}),c.fixSafariAudio(),c.addEventListener("state",(e=>{this.currentGroupCall===c&&e===Pu.CLOSED&&(this.setCurrentGroupCall(null),this.stopConnectingSound(),this.audioAsset.playSound("group_call_end.mp3"),s.Z.dispatchEvent("chat_update",c.chatId))})),c.groupCall=yield this.managers.appGroupCallsManager.getGroupCallFull(t);const d=c.createConnectionInstance({streamManager:i,type:l,options:{type:l,isMuted:n,joinVideo:o,rejoin:a}}),h=d.createPeerConnection();return h.addEventListener("negotiationneeded",(()=>{d.negotiate()})),h.addEventListener("track",(e=>{r("ontrack",e),c.onTrack(e)})),h.addEventListener("iceconnectionstatechange",(()=>{c.dispatchEvent("state",c.state);const{iceConnectionState:e}=h;switch("disconnected"===e||"checking"===e||"new"===e?this.startConnectingSound():this.stopConnectingSound(),e){case"checking":case"completed":case"disconnected":case"new":break;case"closed":case"failed":c.hangUp();break;case"connected":c.joined||(c.joined=!0,this.audioAsset.playSound("group_call_start.mp3"),this.managers.appGroupCallsManager.getGroupCallParticipants(t))}})),d.createDescription(),d.createDataChannel(),d.appendStreamToConference(),this.setCurrentGroupCall(c),r("set currentGroupCall",t,c),this.startConnectingSound(),d.negotiate()}c.handleUpdateGroupCallParticipants=!1,c.updatingSdp=!1,r("update currentGroupCall",t,c)}))}}const Zu=new Au;R.GO&&(R.GO.groupCallController=Zu);const Fu=Zu;var Du=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Ru{constructor(e,t,i){this.chat=e,this.appSidebarRight=t,this.managers=i,this.verifyButtons=e=>{const t=!!e||!(!this.btnMore||!this.btnMore.classList.contains("menu-open"));e&&(0,a.Z)(e),(()=>{Du(this,void 0,void 0,(function*(){const e=yield this.managers.appPeersManager.getDeleteButtonText(this.peerId);t&&this.menuButtons[this.menuButtons.length-1].element.lastChild.replaceWith((0,v.ag)(e));const i=this.buttonsToVerify.concat(t?this.menuButtons:[]);(yield Promise.all(i.map((e=>Du(this,void 0,void 0,(function*(){return{result:yield e.verify(),button:e}})))))).forEach((({button:e,result:t})=>{e.element.classList.toggle("hide",!t)}))}))})()},this.verifyVideoChatButton=e=>Du(this,void 0,void 0,(function*(){var t;if(!Wd.Z||this.peerId.isUser())return!1;const i=Fu.groupCall,s=this.peerId.toChatId();if((null==i?void 0:i.chatId)===s)return!1;if(e&&((yield this.managers.appPeersManager.isBroadcast(this.peerId))&&"group"===e||(yield this.managers.appPeersManager.isAnyGroup(this.peerId))&&"broadcast"===e))return!1;const n=yield this.managers.appChatsManager.getChatTyped(s);return(null===(t=n.pFlags)||void 0===t?void 0:t.call_active)||(0,Xi.Z)(n,"manage_call")})),this.verifyCallButton=e=>Du(this,void 0,void 0,(function*(){if(!nl.Z||!this.peerId.isUser())return!1;const t=this.peerId.toUserId(),i=yield this.managers.appProfileManager.getCachedFullUser(t);return!!i&&!!("voice"===e?i.pFlags.phone_calls_available:i.pFlags.video_calls_available)})),this.onJoinGroupCallClick=()=>{this.chat.appImManager.joinGroupCall(this.peerId)},this.onMuteClick=()=>{new jd(this.peerId)},this.onResize=()=>{this.setUtilsWidth(!0),this.setFloating()},this.onChangeScreen=(e,t)=>{this.container.classList.toggle("is-pinned-floating",d.Z.isMobile),this.pinnedMessage&&this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-floating",t===d._.mobile),this.onResize()},this.setUtilsWidth=(e=!1)=>{this.setUtilsRAF&&window.cancelAnimationFrame(this.setUtilsRAF),Je.IS_SAFARI&&e&&this.chatUtils.classList.add("hide"),this.setUtilsRAF=window.requestAnimationFrame((()=>{Je.IS_SAFARI&&e&&this.chatUtils.classList.remove("hide");const t=this.chatUtils.getBoundingClientRect().width;this.chat.log("utils width:",t),this.container.style.setProperty("--utils-width",t+"px"),this.setUtilsRAF=0}))},this.setFloating=()=>{const e=[this.chatAudio,this.pinnedMessage&&this.pinnedMessage.pinnedMessageContainer].filter(Boolean).reduce(((e,t)=>{const i=t.isFloating();return this.container.classList.toggle(`is-pinned-${t.className}-floating`,i),t.isVisible()?e+ +i:e}),0);this.container.dataset.floating=""+e},this.setPeerStatusManual=(e=!1)=>Du(this,void 0,void 0,(function*(){if(!this.subtitle)return;const t=this.peerId;return this.chat.appImManager.setPeerStatus(t,this.subtitle,e,!1,(()=>t===this.peerId))})),this.setPeerStatus=e=>this.setPeerStatusManual(e).then((e=>{e&&e()})),this.listenerSetter=new I.Z,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=E("left sidebar-close-button",{noRipple:!0}),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=document.createElement("div");e.classList.add("person");const t=document.createElement("div");t.classList.add("content");const i=document.createElement("div");i.classList.add("top"),this.title=document.createElement("div"),this.title.classList.add("user-title"),i.append(this.title);const s=document.createElement("div");s.classList.add("bottom"),this.subtitle&&s.append(this.subtitle),t.append(i,s),this.avatarElement&&e.append(this.avatarElement),e.append(t),this.chatInfo.append(e),this.chatUtils=document.createElement("div"),this.chatUtils.classList.add("chat-utils"),this.chatAudio=new Nd(this,this.chat,this.managers),this.menuButtons.length&&(this.btnMore=mo({listenerSetter:this.listenerSetter},"bottom-left",this.menuButtons,this.verifyButtons)),this.chatUtils.append(...[this.pinnedMessage?this.pinnedMessage.pinnedMessageContainer.divAndCaption.container:null,this.btnJoin,this.btnPinned,this.btnCall,this.btnGroupCall,this.btnMute,this.btnSearch,this.btnMore].filter(Boolean)),this.pushButtonToVerify(this.btnCall,this.verifyCallButton.bind(this,"voice")),this.pushButtonToVerify(this.btnGroupCall,this.verifyVideoChatButton),this.chatInfoContainer.append(this.btnBack,this.chatInfo,this.chatUtils),this.container.append(this.chatInfoContainer),this.chatAudio&&this.container.append(this.chatAudio.divAndCaption.container),this.listenerSetter.add(window)("resize",this.onResize),this.listenerSetter.add(d.Z)("changeScreen",this.onChangeScreen),(0,n.fc)(this.container,(e=>{const t=(0,r.Z)(e.target,"pinned-container");if((0,ln.Z)(),t){if((0,a.Z)(e),(0,r.Z)(e.target,"progress-line"))return;const i=+t.dataset.mid;if(t.classList.contains("pinned-message"))this.pinnedMessage.followPinnedMessage(i);else{const e=t.dataset.peerId.toPeerId(),s=vt.Z.getSearchContext();this.chat.appImManager.setInnerPeer({peerId:e,lastMsgId:i,type:s.isScheduled?"scheduled":s.threadId?"discussion":void 0,threadId:s.threadId})}}else d.Z.activeScreen===d._.medium&&document.body.classList.contains(Dr)?o():(0,l.Z)(e.target,"AVATAR-ELEMENT")?this.appSidebarRight.toggleSidebar(!document.body.classList.contains(tn)):this.appSidebarRight.toggleSidebar(!0)}),{listenerSetter:this.listenerSetter});const o=e=>{if(e&&(0,a.Z)(e),d.Z.activeScreen===d._.medium&&document.body.classList.contains(Dr))this.chat.appImManager.setPeer({peerId:this.peerId});else{const e=0===this.chat.appImManager.chats.indexOf(this.chat);C.Z.back(e?"im":"chat")}};(0,n.fc)(this.btnBack,o,{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:()=>d.Z.isMobile},{icon:"mute",text:"ChatList.Context.Mute",onClick:this.onMuteClick,verify:()=>Du(this,void 0,void 0,(function*(){return"chat"===this.chat.type&&s.Z.myId!==this.peerId&&!(yield this.managers.appNotificationsManager.isPeerLocalMuted(this.peerId,!1))}))},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:()=>{this.managers.appMessagesManager.togglePeerMute(this.peerId)},verify:()=>Du(this,void 0,void 0,(function*(){return"chat"===this.chat.type&&s.Z.myId!==this.peerId&&(yield this.managers.appNotificationsManager.isPeerLocalMuted(this.peerId,!1))}))},{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:()=>Du(this,void 0,void 0,(function*(){const e=yield this.managers.appProfileManager.getCachedFullChat(this.peerId.toChatId());return"chat"===this.chat.type&&!!(null==e?void 0: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:"select",text:"Chat.Menu.SelectMessages",onClick:()=>{const e=this.chat.selection;e.toggleSelection(!0,!0),Gi.Z.getState().then((t=>{if(t.chatContextMenuHintWasShown)return;const i=e.toggleByElement.bind(e);e.toggleByElement=t=>Du(this,void 0,void 0,(function*(){this.managers.appStateManager.pushToState("chatContextMenuHintWasShown",!0),Ci((0,v.ag)("Chat.Menu.Hint")),e.toggleByElement=i,e.toggleByElement(t)}))}))},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:()=>{if(!this.appSidebarRight.isTabExists(ks)){const e=this.appSidebarRight.createTab(ks);e.peerId=this.peerId,e.open(),this.appSidebarRight.toggleSidebar(!0)}},verify:()=>Du(this,void 0,void 0,(function*(){return this.peerId.isUser()&&!(yield this.managers.appPeersManager.isContact(this.peerId))}))},{icon:"forward",text:"ShareContact",onClick:()=>{const e=this.peerId;new ms({peerTypes:["dialogs","contacts"],onSelect:t=>new Promise(((i,s)=>{new qi("",{titleLangKey:"SendMessageTitle",descriptionLangKey:"SendContactToGroupText",descriptionLangArgs:[new Ot({peerId:t,dialog:!0}).element],buttons:[{langKey:"Send",callback:()=>{i(),this.managers.appMessagesManager.sendContact(t,e),this.chat.appImManager.setInnerPeer({peerId:t})}},{langKey:"Cancel",callback:()=>{s()},isCancel:!0}],peerId:t,overlayClosable:!0}).show()})),placeholder:"ShareModal.Search.Placeholder",chatRightsAction:"send_messages",selfPresence:"ChatYourSelf"})},verify:()=>Du(this,void 0,void 0,(function*(){return s.Z.myId!==this.peerId&&this.peerId.isUser()&&(yield this.managers.appPeersManager.isContact(this.peerId))&&!!(yield this.managers.appUsersManager.getUser(this.peerId.toUserId())).phone}))},{icon:"lock",text:"BlockUser",onClick:()=>{new qi("",{peerId:this.peerId,titleLangKey:"BlockUser",descriptionLangKey:"AreYouSureBlockContact2",descriptionLangArgs:[new Ot({peerId:this.peerId}).element],buttons:[{langKey:"BlockUser",isDanger:!0,callback:()=>{this.managers.appUsersManager.toggleBlock(this.peerId,!0).then((e=>{e&&Li({langPackKey:"UserBlocked"})}))}}]}).show()},verify:()=>Du(this,void 0,void 0,(function*(){var e;if(!this.peerId.isUser())return!1;const t=yield this.managers.appProfileManager.getCachedFullUser(this.peerId.toUserId());return this.peerId!==s.Z.myId&&t&&!(null===(e=t.pFlags)||void 0===e?void 0:e.blocked)}))},{icon:"lockoff",text:"Unblock",onClick:()=>{this.managers.appUsersManager.toggleBlock(this.peerId,!1).then((e=>{e&&Li({langPackKey:"UserUnblocked"})}))},verify:()=>Du(this,void 0,void 0,(function*(){var e;const t=yield this.managers.appProfileManager.getCachedFullUser(this.peerId.toUserId());return!!(null===(e=null==t?void 0:t.pFlags)||void 0===e?void 0:e.blocked)}))},{icon:"delete danger",text:"Delete",onClick:()=>{new ws(this.peerId)},verify:()=>Du(this,void 0,void 0,(function*(){return"chat"===this.chat.type&&!!(yield this.managers.appMessagesManager.getDialogOnly(this.peerId))}))}],this.btnSearch=E("search"),this.attachClickEvent(this.btnSearch,(e=>{this.chat.initSearch()}),!0)}attachClickEvent(e,t,i){(0,n.fc)(e,(e=>{(0,a.Z)(e),!i&&(0,ln.Z)(),t(e)}),{listenerSetter:this.listenerSetter})}onCallClick(e){this.chat.appImManager.callUser(this.peerId.toUserId(),e)}constructAvatar(){const e=new Wm;return e.isDialog=!0,e.classList.add("avatar-42","person-avatar"),e}get peerId(){return this.chat.peerId}constructPeerHelpers(){return this.avatarElement=this.constructAvatar(),this.subtitle=document.createElement("div"),this.subtitle.classList.add("info"),this.pinnedMessage=new Kd(this,this.chat,this.managers),this.btnJoin=(0,M.Z)("btn-primary btn-color-primary chat-join hide"),this.btnCall=E("phone"),this.btnGroupCall=E("videochat"),this.btnPinned=E("pinlist"),this.btnMute=E("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.onMuteClick),this.attachClickEvent(this.btnJoin,(()=>Du(this,void 0,void 0,(function*(){const e=this.chat.bubbles.getMiddleware();this.btnJoin.setAttribute("disabled","true");const t=this.peerId.toChatId();let i;i=(yield this.managers.appChatsManager.isChannel(t))?this.managers.appChatsManager.joinChannel(t):this.managers.appChatsManager.addChatUser(t,s.Z.myId),i.finally((()=>{e()&&this.btnJoin.removeAttribute("disabled")}))})))),this.listenerSetter.add(s.Z)("chat_update",(e=>Du(this,void 0,void 0,(function*(){var t;if(this.peerId===e.toPeerId(!0)){const i=yield this.managers.appChatsManager.getChat(e);this.btnJoin.classList.toggle("hide",!(null===(t=null==i?void 0:i.pFlags)||void 0===t?void 0:t.left)),this.setUtilsWidth(),this.verifyButtons()}})))),this.listenerSetter.add(s.Z)("dialog_notify_settings",(e=>{e.peerId===this.peerId&&this.setMutedState()})),this.listenerSetter.add(s.Z)("peer_typings",(({peerId:e})=>{this.peerId===e&&this.setPeerStatus()})),this.listenerSetter.add(s.Z)("user_update",(e=>{this.peerId===e.toPeerId()&&this.setPeerStatus()})),this.listenerSetter.add(s.Z)("peer_full_update",(e=>{this.peerId===e&&this.verifyButtons()})),this.pinnedMessage&&this.chat.addEventListener("setPeer",((e,t)=>{const i=this.chat.bubbles.getMiddleware();Gi.Z.getState().then((s=>{i()&&(this.pinnedMessage.hidden=!!s.hiddenPinnedMessages[this.chat.peerId],t?(this.pinnedMessage.unsetScrollDownListener(),this.pinnedMessage.testMid(e,0)):this.pinnedMessage.locked||(this.pinnedMessage.handleFollowingPinnedMessage(),this.pinnedMessage.testMid(e)))}))})),this.setPeerStatusInterval=window.setInterval(this.setPeerStatus,6e4),this}constructPinnedHelpers(){this.listenerSetter.add(s.Z)("peer_pinned_messages",(({peerId:e,mids:t})=>{e===this.peerId&&t&&this.setTitle()}))}constructDiscussionHelpers(){this.pinnedMessage=new Kd(this,this.chat,this.managers)}openPinned(e){this.chat.appImManager.setInnerPeer({peerId:this.peerId,lastMsgId:e?+this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.dataset.mid:0,type:"pinned"})}destroy(){this.listenerSetter.removeAll(),window.clearInterval(this.setPeerStatusInterval),this.pinnedMessage&&this.pinnedMessage.destroy(),this.chatAudio&&this.chatAudio.destroy(),delete this.chatAudio,delete this.pinnedMessage}cleanup(){this.chat.peerId||this.container.classList.add("hide")}finishPeerChange(e){return Du(this,void 0,void 0,(function*(){const e=this.peerId;let t;this.avatarElement&&(t=this.constructAvatar());const[i,s,n,a,o,r,l]=yield Promise.all([this.managers.appPeersManager.isBroadcast(e),this.managers.appPeersManager.isAnyChat(e),e.isAnyChat()?this.managers.appChatsManager.getChat(e.toChatId()):void 0,t?t.updateWithOptions({peerId:e}):void 0,this.setTitleManual(),this.setPeerStatusManual(!0),Gi.Z.getState()]);return()=>{var a;if(this.btnMute&&this.btnMute.classList.toggle("hide",!i),this.btnJoin&&(s?((0,g.Z)(this.btnJoin,(0,v.ag)(i?"Chat.Subscribe":"ChannelJoin")),this.btnJoin.classList.toggle("hide",!(null===(a=null==n?void 0:n.pFlags)||void 0===a?void 0:a.left))):this.btnJoin.classList.add("hide")),t&&(this.avatarElement.replaceWith(t),this.avatarElement=t),this.setUtilsWidth(),this.verifyButtons(),this.pinnedMessage)if("chat"===this.chat.type){if(this.chat.wasAlreadyUsed){const e=new Kd(this,this.chat,this.managers);this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.replaceWith(e.pinnedMessageContainer.divAndCaption.container),this.pinnedMessage.destroy(),this.pinnedMessage=e}this.pinnedMessage.hidden=!!l.hiddenPinnedMessages[e]}else"discussion"===this.chat.type&&(this.pinnedMessage.pinnedMid=this.chat.threadId,this.pinnedMessage.count=1,this.pinnedMessage.pinnedIndex=0,this.pinnedMessage._setPinnedMessage());o(),r&&r(),this.setMutedState(),this.container.classList.remove("hide")}}))}setTitleManual(e){return Du(this,void 0,void 0,(function*(){const t=this.peerId,i=()=>this.peerId===t;let n;if("pinned"===this.chat.type)n=void 0===e?(0,v.ag)("Loading"):(0,v.ag)("PinnedMessagesCount",[e]),void 0===e&&this.managers.appMessagesManager.getSearchCounters(t,[{_:"inputMessagesFilterPinned"}],!1).then((e=>{if(!i())return;const t=e[0].count;if(this.setTitle(t),!t){this.chat.appImManager.setPeer();const e=this.chat.appImManager.chat;e.topbar.pinnedMessage&&e.topbar.pinnedMessage.pinnedMessageContainer.toggle(!0)}}));else if("scheduled"===this.chat.type)n=(0,v.ag)(t===s.Z.myId?"Reminders":"ScheduledMessages");else if("discussion"===this.chat.type){if(void 0===e){const i=yield this.managers.acknowledged.appMessagesManager.getHistory(t,0,1,0,this.chat.threadId);if(i.cached){const t=yield i.result;e=t.count}else i.result.then((e=>this.setTitle(e.count)))}n=void 0===e?(0,v.ag)("Loading"):(0,v.ag)("Chat.Title.Comments",[e])}else if("chat"===this.chat.type&&([n]=yield Promise.all([js({peerId:t,dialog:!0,withIcons:!0})]),!i()))return;return()=>{(0,g.Z)(this.title,n)}}))}setTitle(e){this.setTitleManual(e).then((e=>e()))}setMutedState(){return Du(this,void 0,void 0,(function*(){if(!this.btnMute)return;const e=this.peerId,t=yield this.managers.appNotificationsManager.isPeerLocalMuted(e,!1);(yield this.managers.appPeersManager.isBroadcast(e))?(this.btnMute.classList.remove("tgico-mute","tgico-unmute"),this.btnMute.classList.add(t?"tgico-unmute":"tgico-mute"),this.btnMute.style.display=""):this.btnMute.style.display="none"}))}}class Bu extends P{constructor(){super(...arguments),this.threadId=0,this.query=""}onOpenAfterTimeout(){this.appSearch.beginSearch(this.peerId,this.threadId,this.query)}init(){this.container.id="search-private-container",this.container.classList.add("chatlist-container"),this.inputSearch=new w("Search"),this.title.replaceWith(this.inputSearch.container),this.btnPickDate=E("calendar sidebar-header-right"),this.header.append(this.btnPickDate);const e=document.createElement("div");e.classList.add("chatlist-container"),this.scrollable.container.replaceWith(e),this.appSearch=new y(e,this.inputSearch,{messages:new f("Chat.Search.PrivateSearch","messages")})}open(e,t,i,s){const a=super.open();return this.peerId?this.appSearch.beginSearch(this.peerId,this.threadId,s):(this.query=s,this.peerId=e,this.threadId=t,this.onDatePick=i,this.btnPickDate.classList.toggle("hide",!this.onDatePick),this.onDatePick&&(0,n.fc)(this.btnPickDate,(()=>{A.Z.createPopup(Vr,new Date,this.onDatePick).show()})),s&&this.appSearch.searchInput.inputField.setValueSilently(s),nn.toggleSidebar(!0)),a}}class Nu{constructor(e,t,i){this.topbar=e,this.chat=t,this.foundCount=0,this.selectedIndex=0,this.onDateClick=e=>{(0,a.Z)(e),A.Z.createPopup(Vr,new Date,this.chat.bubbles.onDatePick).show()},this.onResultsClick=e=>{const t=(0,l.Z)(e.target,dg);t&&this.selectResult(t)},this.onFooterClick=e=>{this.foundCount&&(this.chat.bubbles.container.classList.toggle("search-results-active"),this.results.classList.toggle("active"))},this.onUpClick=e=>{(0,a.Z)(e),this.selectResult(this.searchGroup.list.children[this.selectedIndex+1])},this.onDownClick=e=>{(0,a.Z)(e),this.selectResult(this.searchGroup.list.children[this.selectedIndex-1])},this.element=document.createElement("div"),this.element.classList.add("sidebar-header","chat-search","chatlist-container"),this.backBtn=document.createElement("button"),this.backBtn.classList.add("btn-icon","tgico-left","sidebar-close-button"),(0,we.Z)(this.backBtn);const s=this.listenerSetter=new I.Z,o=(e,t)=>{(0,n.fc)(e,t,{listenerSetter:s})};o(this.backBtn,(()=>{this.destroy()})),this.inputSearch=new w("Search"),this.results=document.createElement("div"),this.results.classList.add("chat-search-results","chatlist-container"),this.searchGroup=new f(!1,"messages",void 0,"",!1),o(this.searchGroup.list,this.onResultsClick),this.appSearch=new y(this.results,this.inputSearch,{messages:this.searchGroup},(e=>{this.foundCount=e,this.foundCount?this.selectResult(this.searchGroup.list.children[0]):((0,g.Z)(this.foundCountEl,this.inputSearch.value?(0,v.ag)("NoResult"):""),this.results.classList.remove("active"),this.chat.bubbles.container.classList.remove("search-results-active"),this.upBtn.setAttribute("disabled","true"),this.downBtn.setAttribute("disabled","true"))})),this.appSearch.beginSearch(this.chat.peerId,this.chat.threadId),this.chat.bubbles.container.append(this.results),this.footer=document.createElement("div"),this.footer.classList.add("chat-search-footer"),o(this.footer,this.onFooterClick),(0,we.Z)(this.footer),this.foundCountEl=document.createElement("span"),this.foundCountEl.classList.add("chat-search-count"),this.dateBtn=document.createElement("button"),this.dateBtn.classList.add("btn-icon","tgico-calendar"),this.controls=document.createElement("div"),this.controls.classList.add("chat-search-controls"),this.upBtn=document.createElement("button"),this.upBtn.classList.add("btn-icon","tgico-up"),this.downBtn=document.createElement("button"),this.downBtn.classList.add("btn-icon","tgico-down"),this.upBtn.setAttribute("disabled","true"),this.downBtn.setAttribute("disabled","true"),o(this.dateBtn,this.onDateClick),o(this.upBtn,this.onUpClick),o(this.downBtn,this.onDownClick),this.controls.append(this.upBtn,this.downBtn),this.footer.append(this.foundCountEl,this.dateBtn,this.controls),this.topbar.container.parentElement.insertBefore(this.footer,t.input.chatInput),this.element.append(this.backBtn,this.inputSearch.container),this.topbar.container.classList.add("hide-pinned"),this.topbar.container.parentElement.append(this.element),this.inputSearch.input.focus(),i&&this.setQuery(i),Je.IS_MOBILE_SAFARI||(this.navigationItem={type:"mobile-search",onPop:()=>{this.destroy()}},C.Z.pushItem(this.navigationItem))}destroy(){this.topbar.container.classList.remove("hide-pinned"),this.element.remove(),this.inputSearch.remove(),this.results.remove(),this.footer.remove(),this.listenerSetter.removeAll(),this.chat.bubbles.container.classList.remove("search-results-active"),this.chat.search=void 0,C.Z.removeItem(this.navigationItem)}setQuery(e){this.inputSearch.inputField.value=e}selectResult(e){if(this.setPeerPromise)return this.setPeerPromise;const t=e.dataset.peerId.toPeerId(),i=+e.dataset.mid||void 0,s=(0,Cn.Z)(e);s===this.foundCount-1?this.upBtn.setAttribute("disabled","true"):this.upBtn.removeAttribute("disabled"),s?this.downBtn.removeAttribute("disabled"):this.downBtn.setAttribute("disabled","true"),this.results.classList.remove("active"),this.chat.bubbles.container.classList.remove("search-results-active");const n=this.chat.setPeer(t,i);this.setPeerPromise=(n instanceof Promise?n:Promise.resolve(n)).then((()=>{this.selectedIndex=s,(0,g.Z)(this.foundCountEl,(0,v.ag)("Of",[s+1,this.foundCount]));const e=this.searchGroup.list.childElementCount;this.selectedIndex>=e-6&&this.appSearch.searchMore()})).finally((()=>{this.setPeerPromise=null}))}}class Uu{constructor(){this.canvases=new Set}static getInstance(e){let t=this.INSTANCES.find((t=>(0,gs.Z)(t.options,e)));return t||(t=new Uu,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.img=document.createElement("img");return t.crossOrigin="anonymous",this.renderImageFromUrlPromise=Ze(t,e,!1).then((()=>t))}cleanup(e){this.canvases.delete(e),this.canvases.size||((0,T.Z)(Uu.INSTANCES,this),this.objectUrl&&URL.revokeObjectURL(this.objectUrl))}fillCanvas(e){const t=e.getContext("2d"),{width:i,height:s}=e,n=this.img;let a=n.width,o=n.height,r=1480*e.dpr;+e.dataset.originalHeight!==s&&(r*=.875),a*=r/o,o=r,this.options.mask?(t.fillStyle="#000",t.fillRect(0,0,i,s),t.globalCompositeOperation="destination-out"):t.globalCompositeOperation="source-over";const l=e=>{for(let s=0;s<i;s+=a)t.drawImage(n,s,e,a,o)},c=s/2-o/2;if(l(c),c>0){let e=c;do{l(e-=o)}while(e>=0)}const d=s-1;for(let e=c+o;e<d;e+=o)l(e)}setCanvasDimensions(e){const t=Math.min(2,window.devicePixelRatio),i=this.options.width*t;let s=this.options.height*t;e.dpr=t,e.dataset.originalHeight=""+s,d.Z.activeScreen===d._.large&&(s*=1.5),e.width=i,e.height=s}createCanvas(){const e=document.createElement("canvas");return this.canvases.add(e),this.setCanvasDimensions(e),e}resize(e,t){this.init(Object.assign(Object.assign({},this.options),{width:e,height:t}));const i=[];for(const e of this.canvases)this.setCanvasDimensions(e),i.push(this.renderToCanvas(e));return Promise.all(i)}static resizeInstances(e,t){return Promise.all(this.INSTANCES.map((i=>i.resize(e,t))))}}Uu.INSTANCES=[];var Ou=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Hu extends L.Z{constructor(e,t){super(),this.appImManager=e,this.managers=t,this.type="chat",this.container=document.createElement("div"),this.container.classList.add("chat","tabs-tab"),this.backgroundEl=document.createElement("div"),this.backgroundEl.classList.add("chat-background"),this.log=(0,he.kg)("CHAT",he.v9.Log|he.v9.Warn|he.v9.Debug|he.v9.Error),this.peerId=le.NM,this.container.append(this.backgroundEl),this.appImManager.chatsContainer.append(this.container),this.backgroundTempId=0,this.sharedMediaTabs=[]}setBackground(e,t){const i=$o.Z.getTheme();let n;if(i.background.color&&!i.background.slug&&!i.background.intensity&&"grabbing"===document.documentElement.style.cursor&&this.gradientRenderer&&!this.patternRenderer)return this.gradientCanvas.dataset.colors=i.background.color,this.gradientRenderer.init(this.gradientCanvas),Promise.resolve();const a=++this.backgroundTempId,o=this.gradientRenderer,r=this.patternRenderer,l=(this.gradientCanvas,this.patternCanvas);this.gradientRenderer=this.patternRenderer=this.gradientCanvas=this.patternCanvas=void 0;const c=i.background.intensity&&i.background.intensity/100,d=!!c&&c<0;let h,u,p,m=null==n?void 0:n.firstElementChild;if(!n)if(n=document.createElement("div"),n.classList.add("chat-background-item"),e)if(c){n.classList.add("is-pattern");const t=this.appImManager.chatsContainer.getBoundingClientRect();h=this.patternRenderer=Uu.getInstance({url:e,width:t.width,height:t.height,mask:d}),m=this.patternCanvas=h.createCanvas(),m.classList.add("chat-background-item-canvas","chat-background-item-pattern-canvas"),d&&n.classList.add("is-dark")}else i.background.slug&&n.classList.add("is-image");else i.background.color&&n.classList.add("is-color");const g=i.background.color;if(g){const{canvas:e,gradientRenderer:t}=Wo.create(g);p=this.gradientRenderer=t,u=this.gradientCanvas=e,u.classList.add("chat-background-item-canvas","chat-background-item-color-canvas"),s.Z.settings.animationsEnabled&&p.scrollAnimate(!0)}h&&(d?u:m).style.setProperty("--opacity-max",""+Math.abs(c));const v=new Promise((i=>{const s=()=>{if(this.backgroundTempId!==a)return h&&h.cleanup(m),void(p&&p.cleanup());const e=this.backgroundEl.lastElementChild;if(e===n)return void i();const s=[u,m].filter(Boolean);s.length&&n.append(...s),this.backgroundEl.append(n),Re(n,"is-visible",!0,t?0:200,e?()=>{r&&r.cleanup(l),o&&o.cleanup(),e.remove()}:null,2),i()};h?h.renderToCanvas(m).then((()=>{this.backgroundTempId===a&&s()})):e?Ae(n,e,s):s()}));return this.setBackgroundPromise=Promise.race([(0,on.Z)(500),v])}setType(e){this.type=e}init(){this.topbar=new Ru(this,nn,this.managers),this.bubbles=new yc(this,this.managers),this.input=new Fd(this,this.appImManager,this.managers),this.contextMenu=new Ac(this,this.managers),this.selection=new so(this,this.bubbles,this.input,this.managers),"chat"===this.type?(this.topbar.constructUtils(),this.topbar.constructPeerHelpers()):"pinned"===this.type?this.topbar.constructPinnedHelpers():"discussion"===this.type&&(this.topbar.constructUtils(),this.topbar.constructDiscussionHelpers()),this.topbar.construct(),this.input.construct(),"chat"===this.type?(this.bubbles.constructPeerHelpers(),this.input.constructPeerHelpers()):"pinned"===this.type?(this.bubbles.constructPinnedHelpers(),this.input.constructPinnedHelpers()):"scheduled"===this.type?(this.bubbles.constructScheduledHelpers(),this.input.constructPeerHelpers()):"discussion"===this.type&&(this.bubbles.constructPeerHelpers(),this.input.constructPeerHelpers()),"scheduled"===this.type||gi.Z||this.bubbles.setReactionsHoverListeners(),this.bubbles.attachContainerListeners(),this.container.classList.add("type-"+this.type),this.container.append(this.topbar.container,this.bubbles.container,this.input.chatInput),this.bubbles.listenerSetter.add(s.Z)("dialog_migrate",(({migrateFrom:e,migrateTo:t})=>{this.peerId===e&&this.setPeer(t)})),this.bubbles.listenerSetter.add(s.Z)("dialog_drop",(e=>{e.peerId===this.peerId&&this.appImManager.setPeer()}))}beforeDestroy(){this.bubbles.cleanup()}cleanupBackground(){++this.backgroundTempId,this.patternRenderer&&(this.patternRenderer.cleanup(this.patternCanvas),this.patternRenderer=void 0),this.gradientRenderer&&(this.gradientRenderer.cleanup(),this.gradientRenderer=void 0)}destroy(){this.topbar.destroy(),this.bubbles.destroy(),this.input.destroy(),this.contextMenu&&this.contextMenu.destroy(),this.selection&&this.selection.attachListeners(void 0,void 0),this.cleanupBackground(),delete this.topbar,delete this.bubbles,delete this.input,delete this.selection,delete this.contextMenu,this.container.remove()}cleanup(e=!0){this.input.cleanup(e),this.topbar.cleanup(),this.selection.cleanup()}onChangePeer(e){return Ou(this,void 0,void 0,(function*(){const{peerId:t}=this,i=nn.getTab(Bu);i&&i.close();const[s,n,a,o,r,l,c,d]=yield e(Promise.all([this.managers.appPeersManager.noForwards(t),this.managers.appPeersManager.isRestricted(t),this._isAnyGroup(t),this.setAutoDownloadMedia(),this.managers.appPeersManager.isMegagroup(t),this.managers.appPeersManager.isBroadcast(t),this.managers.appPeersManager.isChannel(t),this.managers.appPeersManager.isBot(t)]));this.noForwards=s,this.isRestricted=n,this.isAnyGroup=a,this.isMegagroup=r,this.isBroadcast=l,this.isChannel=c,this.isBot=d,this.container.classList.toggle("no-forwards",this.noForwards),this.sharedMediaTab=nn.createSharedMediaTab(),this.sharedMediaTabs.push(this.sharedMediaTab),this.sharedMediaTab.setPeer(t,this.threadId),this.input.clearHelper(),this.selection.cleanup()}))}setPeer(e,t,i){e?this.inited||(this.init&&(this.init(),this.init=null),this.inited=!0):this.inited=void 0;const s=this.peerId===e;if(s){if(this.setPeerPromise)return}else this.appImManager.dispatchEvent("peer_changing",this),this.peerId=e||le.NM,this.messagesStorageKey=`${this.peerId}_${"scheduled"===this.type?"scheduled":"history"}`;if(!e)return nn.toggleSidebar(!1),this.cleanup(!0),this.bubbles.setPeer(!1,e),this.appImManager.dispatchEvent("peer_changed",e),nn.replaceSharedMediaTab(),this.destroySharedMediaTab(),void(this.sharedMediaTab=void 0);this.peerChanged=s;const n=this.bubbles.setPeer(s,e,t,i),a=this.setPeerPromise=n.then((e=>e.promise)).catch(ft.Z).finally((()=>{this.setPeerPromise===a&&(this.setPeerPromise=null)}));return n}destroySharedMediaTab(e=this.sharedMediaTab){(0,T.Z)(this.sharedMediaTabs,e),e.destroy()}setAutoDownloadMedia(){return Ou(this,void 0,void 0,(function*(){this.autoDownload=yield function(e){return t=this,i=void 0,a=function*(){let t,i=0,n=0,a=0;const o=s.Z.settings,r=s.Z.managers.appPeersManager;return!o.autoDownloadNew.pFlags.disabled&&e&&(t=e.isUser()?(yield r.isContact(e))?"contacts":"private":(yield r.isBroadcast(e))?"channels":"groups",o.autoDownload.photo[t]&&(i=o.autoDownloadNew.photo_size_max),o.autoDownload.video[t]&&(n=o.autoDownloadNew.video_size_max),o.autoDownload.file[t]&&(a=o.autoDownloadNew.file_size_max)),{photo:i,video:n,file:a}},new((n=void 0)||(n=Promise))((function(e,s){function o(e){try{l(a.next(e))}catch(e){s(e)}}function r(e){try{l(a.throw(e))}catch(e){s(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(o,r)}l((a=a.apply(t,i||[])).next())}));var t,i,n,a}(this.peerId)}))}setMessageId(e){return this.setPeer(this.peerId,e)}finishPeerChange(e,t,i,s){return Ou(this,void 0,void 0,(function*(){if(this.peerChanged)return;const t=this.peerId;this.peerChanged=!0,this.wasAlreadyUsed=!0;const i=this.bubbles.getMiddleware();this.cleanup(!1);const n=this.sharedMediaTab;n.loadSidebarMedia(!0);const a=Promise.all([this.topbar.finishPeerChange(e),this.bubbles.finishPeerChange(),this.input.finishPeerChange(s)]),[o]=yield Promise.all([a,n.fillProfileElements()]);i()&&(o.forEach((e=>{e()})),nn.replaceSharedMediaTab(n),this.sharedMediaTabs.filter((e=>e!==n)).forEach((e=>this.destroySharedMediaTab(e))),this.log.setPrefix("CHAT-"+t+"-"+this.type),this.appImManager.dispatchEvent("peer_changed",t))}))}getMessage(e){return this.managers.appMessagesManager.getMessageFromStorage(this.messagesStorageKey,e)}getMidsByMid(e){return Ou(this,void 0,void 0,(function*(){return this.managers.appMessagesManager.getMidsByMessage(yield this.getMessage(e))}))}getHistoryStorage(e){return this.managers.appMessagesManager.getHistoryStorageTransferable(this.peerId,e?void 0:this.threadId).then((e=>Object.assign(Object.assign({},e),{history:Xr.Z.fromJSON(e.historySerialized)})))}getHistoryMaxId(){return this.getHistoryStorage().then((e=>e.maxId))}_isAnyGroup(e){return Ou(this,void 0,void 0,(function*(){return e===s.Z.myId||e===le.hj||(yield this.managers.appPeersManager.isAnyGroup(e))}))}initSearch(e){if(this.peerId)if(d.Z.isMobile)this.search?this.search.setQuery(e):this.search=new Nu(this.topbar,this,e);else{let t=nn.getTab(Bu);t||(t=nn.createTab(Bu)),t.open(this.peerId,this.threadId,this.bubbles.onDatePick,e)}}canSend(e){return 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)]).then((([e,t,i])=>e&&!t&&!i.history.length))}getMessageSendingParams(){return{threadId:this.threadId,replyToMsgId:this.input.replyToMsgId,scheduleDate:this.input.scheduleDate,sendSilent:this.input.sendSilent,sendAsPeerId:this.input.sendAsPeerId}}isOurMessage(e){return e.fromId===s.Z.myId||!!e.pFlags.out&&this.isMegagroup}isOutMessage(e){const t=e.fwd_from;return!(!this.isOurMessage(e)||t&&this.peerId===s.Z.myId)}isAvatarNeeded(e){return this.isAnyGroup&&!this.isOutMessage(e)}}var zu=i(6637);class Gu{constructor(e){this.appImManager=e,this.buttons={},this.addedListener=!1,this.waitingForMouseUp=!1,this.mouseUpCounter=0,this.onMouseUpSingle=e=>{if(this.waitingForMouseUp=!1,gi.Z){if(e&&(0,a.Z)(e),0!=this.mouseUpCounter++)return void this.hide();this.resetSelection(this.savedRange)}this.show()}}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"),t.classList.add("markup-tooltip-tools"),["bold","italic","underline","strikethrough","monospace","spoiler","link"].forEach((t=>{const i=E(t,{noRipple:!0});e.append(this.buttons[t]=i),"link"!==t?i.addEventListener("mousedown",(e=>{(0,a.Z)(e),this.appImManager.chat.input.applyMarkdown(t),this.cancelClosening()})):(0,n.fc)(i,(e=>{(0,a.Z)(e),this.showLinkEditor(),this.cancelClosening()}))})),this.linkBackButton=E("left",{noRipple:!0}),this.linkInput=document.createElement("input"),(0,v.$d)(this.linkInput,"MarkupTooltip.LinkPlaceholder",void 0,"placeholder"),this.linkInput.classList.add("input-clear"),this.linkInput.addEventListener("keydown",(e=>{const t=!this.linkInput.value.length||!!(0,ro.Z)(this.linkInput.value);"Enter"===e.key&&(t?this.applyLink(e):(this.linkInput.classList.contains("error")&&(this.linkInput.classList.remove("error"),this.linkInput.offsetLeft),this.linkInput.classList.add("error")))})),this.linkInput.addEventListener("input",(e=>{const t=this.isLinkValid();this.linkInput.classList.toggle("is-valid",t),this.linkInput.classList.remove("error")})),this.linkBackButton.addEventListener("mousedown",(e=>{(0,a.Z)(e),this.container.classList.remove("is-link"),this.resetSelection(),this.setTooltipPosition(),this.cancelClosening()})),this.linkApplyButton=E("check markup-tooltip-link-apply",{noRipple:!0}),this.linkApplyButton.addEventListener("mousedown",(e=>{this.applyLink(e)}));const i=document.createElement("div");i.classList.add("markup-tooltip-link-apply-container");const s=document.createElement("span"),o=document.createElement("span"),r=document.createElement("span");s.classList.add("markup-tooltip-delimiter"),o.classList.add("markup-tooltip-delimiter"),r.classList.add("markup-tooltip-delimiter"),e.insertBefore(s,this.buttons.link),i.append(r,this.linkApplyButton),t.append(this.linkBackButton,o,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();if(this.savedRange=t.getRangeAt(0),e.classList.contains("active")){const e=this.savedRange.startContainer.parentElement;this.linkInput.value=e.href}else this.linkInput.value="";this.setTooltipPosition(!0),setTimeout((()=>{this.linkInput.focus()}),200),this.linkInput.classList.toggle("is-valid",this.isLinkValid())}applyLink(e){(0,a.Z)(e),this.resetSelection();let t=this.linkInput.value;t&&!(0,zu.Z)(t)&&(t="https://"+t),this.appImManager.chat.input.applyMarkdown("link",t),setTimeout((()=>{this.hide()}),0)}isLinkValid(){return!this.linkInput.value.length||!!(0,ro.Z)(this.linkInput.value)}resetSelection(e=this.savedRange){const t=window.getSelection();t.removeAllRanges(),t.addRange(e),this.appImManager.chat.input.messageInput.focus()}hide(){this.init||(this.container.classList.remove("is-visible"),document.removeEventListener("mouseup",this.onMouseUpSingle),this.waitingForMouseUp=!1,C.Z.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=function(){const e=[],t=window.getSelection();for(let i=0;i<t.rangeCount;++i){const s=t.getRangeAt(i);let{startContainer:n,endContainer:a}=s;for(3!==a.nodeType&&(a=a.firstChild);n&&n!==a;)e.push(3===n.nodeType?n:n.firstChild),n=n.nextSibling;e[e.length-1]!==a&&e.push(a)}return e.filter((e=>!!e))}(),t=[...new Set(e.map((e=>e.parentNode)))],i=new Set;return t.forEach((e=>{for(const t in nd.o){const s=nd.o[t];e.closest(s.match+", [contenteditable]")!==this.appImManager.chat.input.messageInput&&i.add(this.buttons[t])}})),[...i]}setActiveMarkupButton(){const e=this.getActiveMarkupButton();for(const t in this.buttons){const i=this.buttons[t];i.classList.toggle("active",e.includes(i))}}setTooltipPosition(e=!1){const t=document.getSelection().getRangeAt(0),i=document.body.getBoundingClientRect(),s=t.getBoundingClientRect(),n=this.appImManager.chat.input.rowsWrapper.getBoundingClientRect();this.container.style.maxWidth=n.width+"px";const a=En(void 0,this.appImManager.chat.input.messageInput,!1,s).rect.top+-1*i.top,o=(this.container.classList.contains("is-link")?this.wrapper.lastElementChild:this.wrapper.firstElementChild).getBoundingClientRect(),r=a-o.height-8,l=n.left,c=n.left+n.width-Math.min(n.width,o.width);let d;if(e){const e=this.container.getBoundingClientRect();d=(0,Me.Z)(e.left,l,c)}else{const e=s.left+(s.width-o.width)/2;d=(0,Me.Z)(e,l,c)}this.container.style.transform=`translate3d(${d}px, ${r}px, 0)`}show(){if(this.init&&(this.init(),this.init=null),Sc())return void this.hide();if(void 0!==this.hideTimeout&&clearTimeout(this.hideTimeout),this.container.classList.contains("is-visible"))return;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"),Je.IS_MOBILE||C.Z.pushItem({type:"markup",onPop:()=>{this.hide()}})}setMouseUpEvent(){this.waitingForMouseUp||(this.waitingForMouseUp=!0,document.addEventListener("mouseup",this.onMouseUpSingle,{once:!0}))}cancelClosening(){gi.Z&&!Je.IS_APPLE&&(document.removeEventListener("mouseup",this.onMouseUpSingle),document.addEventListener("mouseup",(e=>{(0,a.Z)(e),this.mouseUpCounter=1,this.waitingForMouseUp=!1,this.setMouseUpEvent()}),{once:!0}))}handleSelection(){this.addedListener||(this.addedListener=!0,document.addEventListener("selectionchange",(e=>{if(document.activeElement===this.linkInput)return;const t=this.appImManager.chat.input.messageInput;if(document.activeElement!==t)return void this.hide();const i=document.getSelection();if(Sc(i))this.hide();else if(gi.Z)if(Je.IS_APPLE)this.show(),this.setTooltipPosition();else{if(2===this.mouseUpCounter)return void(this.mouseUpCounter=0);this.savedRange=i.getRangeAt(0),this.setMouseUpEvent()}else this.container&&this.container.classList.contains("is-visible")?this.setTooltipPosition():t.matches(":active")?this.setMouseUpEvent():this.show()})))}}function Vu(e,t,i,s,n,a,o){return[e,",",t," ",i," ",s,",",n," ",a,",",o].join("")}function Ku(e,t,i,s,n,a,o,r){const l=[];return l.push("M"+(e+i/2)+","+t),l.push("H"+(e+i-a)),a>0&&l.push("A"+Vu(a,a,0,0,1,e+i,t+a)),l.push("V"+(t+s-o)),o>0&&l.push("A"+Vu(o,o,0,0,1,e+i-o,t+s)),l.push("H"+(e+r)),r>0&&l.push("A"+Vu(r,r,0,0,1,e+0,t+s-r)),l.push("V"+(t+n)),n>0&&l.push("A"+Vu(n,n,0,0,1,e+n,t+0)),l.push("Z"),l.join(" ")}R.GO.generatePathData=Ku;class Wu{constructor(e,t){let i;this.options=t,this.onDragOver=e=>{this.container.classList.add("is-dragover")},this.onDragLeave=e=>{this.container.classList.remove("is-dragover")},this.onDrop=e=>{this.options.onDrop(e)},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"),t.icon&&(i=document.createElement("div"),i.classList.add("drop-icon","tgico-"+t.icon));const s=document.createElement("div");let n;s.classList.add("drop-header"),s.append((0,v.ag)(t.header,t.headerArgs)),t.subtitle&&(n=document.createElement("div"),n.classList.add("drop-subtitle"),n.append((0,v.ag)(t.subtitle))),this.svg.append(this.path),this.outlineWrapper.append(this.svg),this.container.append(...[this.outlineWrapper,i,s,n].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,i=Ku(5,5,e.width-t,e.height-t,t,t,t,t);this.path.setAttributeNS(null,"d",i)}}var $u=i(7922);function ju(e){e.forEach((e=>e.classList.add("no-transition"))),(0,Be.d1)().then((()=>{e.forEach((e=>e.classList.remove("no-transition")))}))}var qu=i(490),Qu=i(5228);class Yu{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:i,minRadius:s,speed:n}=this,a=i-s;e[t]=s+Math.random()*a,n[t]=.017+.003*Math.random()}generateNextBlob(){const{radius:e,radiusNext:t,progress:i,N:s}=this;for(let n=0;n<s;n++)this.generateBlob(e,n),this.generateBlob(t,n),i[n]=0}update(e,t){const{N:i,progress:s,speed:n,radius:a,radiusNext:o}=this;for(let r=0;r<=i;r++)s[r]+=.8*n[r]+e*n[r]*8.2*t,s[r]>=1&&(s[r]=0,a[r]=o[r],this.generateBlob(o,r))}draw(e,t,i,s,n,a,o,r){if(n.getContext){const l=n.getContext("2d");l.beginPath(),l.moveTo(i,s),l.lineTo(e,s);const{radius:c,radiusNext:d,N:h}=this;for(let n=0;n<=h;n++)if(0===n){const i=this.progress[n],s=(t-(c[n]*(1-i)+d[n]*i))*r+o*(1-r);l.lineTo(e,s)}else{const a=this.progress[n-1],u=c[n-1]*(1-a)+d[n-1]*a,p=this.progress[n],m=(i-e)/h*(n-1),g=(i-e)/h*n,v=m+(g-m)/2,f=(t-u)*r+o*(1-r),y=(t-(c[n]*(1-p)+d[n]*p))*r+o*(1-r);l.bezierCurveTo(v,f,v,y,g,y),n===h&&l.lineTo(i,s)}a(l),l.fill(),l.closePath()}}}class Ju{constructor(e){this.stateId=e,this.createGradient(e)}createGradient(e){this.shader=(t,i,s,n,a)=>{t.fillStyle=Ju.getGradientFromType(t,e,i,s,n,a)}}static getGradientFromType(e,t,i,s,n,a){const o=e.createLinearGradient(i,s,n,a);return t===Pu.MUTED_BY_ADMIN?(o.addColorStop(0,"#F05459"),o.addColorStop(.4,"#766EE9"),o.addColorStop(1,"#57A4FE")):t===Pu.UNMUTED?(o.addColorStop(0,"#52CE5D"),o.addColorStop(1,"#00B1C0")):t===Pu.MUTED?(o.addColorStop(0,"#0976E3"),o.addColorStop(1,"#2BCEFF")):t===Pu.CONNECTING&&(o.addColorStop(0,"#8599aa"),o.addColorStop(1,"#8599aa")),o}update(e,t,i,s){}}class Xu{constructor(){this.handleDevicePixelRatioChanged=e=>{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=(e=!1)=>{if(this.raf=null,!this.mounted)return;const{lbd:t,lbd1:i,lbd2:s,scale:n,left:a,top:o,right:r,bottom:l,currentState:c,previousState:d,focused:h,resizing:u,canvas:p}=this;if(!h&&!u&&this.progressToState>=1)return;let m=Date.now()-this.lastUpdateTime;m>20&&(m=17),this.animateToAmplitude!==this.amplitude&&(this.amplitude+=this.animateAmplitudeDiff*m,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*m,this.animateAmplitudeDiff2>0?this.amplitude2>this.animateToAmplitude&&(this.amplitude2=this.animateToAmplitude):this.amplitude2<this.animateToAmplitude&&(this.amplitude2=this.animateToAmplitude)),d&&(this.progressToState+=m/250,this.progressToState>1&&(this.progressToState=1,this.previousState=null));const{amplitude:g,amplitude2:v,progressToState:f}=this,y=6*v*n,b=6*v*n;p.getContext("2d").clearRect(0,0,p.width,p.height),t.minRadius=0,t.maxRadius=(2+2*g)*n,i.minRadius=0,i.maxRadius=(3+9*g)*n,s.minRadius=0,s.maxRadius=(3+9*g)*n,t.update(g,.3),i.update(g,.7),s.update(g,.7);for(let e=0;e<2;e++){if(0===e&&!d)continue;let n=1,h=null;0===e?(n=1-f,h=d):(n=d?f:1,c.update(l-o,r-a,m,g),h=c);const u=e=>{e.globalAlpha=.3*n,h.shader(e,a,o,r,l)},v=t=>{t.globalAlpha=0===e?1:n,h.shader(t,a,o,r,l)};i.draw(a,o-y,r,l,p,u,o,1),s.draw(a,o-b,r,l,p,u,o,1),t.draw(a,o,r,l,p,v,o,1)}e||(this.raf=requestAnimationFrame((()=>this.draw())))},this.setCurrentState=(e,t)=>{const{currentState:i,states:s}=this;(null==i?void 0:i.stateId)!==e&&(this.previousState=t?i:null,this.currentState=s.get(e),this.progressToState=this.previousState?0:1)},this.focused=!0,this.resizing=!1,this.lastUpdateTime=Date.now(),this.amplitude=0,this.amplitude2=0,this.states=new Map([[Pu.UNMUTED,new Ju(Pu.UNMUTED)],[Pu.MUTED,new Ju(Pu.MUTED)],[Pu.MUTED_BY_ADMIN,new Ju(Pu.MUTED_BY_ADMIN)],[Pu.CONNECTING,new Ju(Pu.CONNECTING)]]),this.previousState=null,this.currentState=this.states.get(Pu.CONNECTING),this.progressToState=1}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 Yu(3),this.lbd1=new Yu(7),this.lbd2=new Yu(8),this.setAmplitude(this.amplitude),this.draw())}componentWillUnmount(){this.mounted=!1,window.removeEventListener("resize",this.handleResize),this.media.addEventListener("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 i=this.canvas=document.createElement("canvas");return i.classList.add(e+"-canvas"),t.append(i),t}}const ep=new class{constructor(){this.cache={},s.Z.addEventListener("theme_change",(()=>{this.computedStyle=void 0;const e=this.cache;this.cache={};for(const t in e)this.getProperty(t)}))}getProperty(e){let t=this.cache[e];return t||(this.computedStyle||(this.computedStyle=window.getComputedStyle(document.documentElement)),t=this.computedStyle.getPropertyValue("--"+e).trim(),this.cache[e]=t)}},tp=ep;class ip{constructor(e,t){this.item=e,(0,x.Z)(this,t)}play(e){return this.item.playPart(this,e)}}class sp{constructor(e,t){this.icon=e,this.autoplay=!1,(0,x.Z)(this,t),this.parts=this.parts.map((e=>this.createPart(e)))}load(){var e;let t=this.loadPromise;if(t)return t;const{container:i,canvas:s,width:n,height:a}=this.icon;return t=hi.Z.loadAnimationAsAsset({container:i,canvas:s,width:n,height:a,group:"none",loop:!1,autoplay:null!==(e=this.autoplay)&&void 0!==e&&e,initFrame:this.initFrame,skipFirstFrameRendering:void 0===this.initFrame,color:this.color,inverseColor:this.inverseColor},this.name).then((e=>hi.Z.waitForFirstFrame(e))).then((e=>{this.player=e,this.onLoadForColor&&(this.onLoadForColor(),this.onLoadForColor=void 0),this.onLoadForPart&&(this.onLoadForPart(),this.onLoadForPart=void 0)})),this.loadPromise=t,this.icon.loadPromises.set(this.name,t),t}createPart(e){return new ip(this,e)}getPart(e){return e instanceof ip?e:"string"==typeof e?this.parts.find((t=>t.name===e)):this.parts[e]}playPart(e,t){return this.icon.playPart(this,e,t)}}class np{constructor(e){(0,x.Z)(this,e),this.container||(this.container=document.createElement("div")),this.container.classList.add("rlottie-icon");const{width:t,height:i}=this;this.container.style.width=t+"px",this.container.style.height=i+"px";const s=this.canvas=document.createElement("canvas");s.classList.add("rlottie"),s.width=t,s.height=i,this.items=new Map,this.loadPromises=new Map}get loadPromise(){return Promise.all([...this.loadPromises.values()]).then(ft.Z)}getItem(e){return e||1!==this.items.size?this.items.get(e):this.items.values().next().value}add(e){const t=new sp(this,e);return this.items.set(e.name,t),t}playPart(e,t,i){if(!e.player)return void(e.onLoadForPart=()=>{this.playPart(e,t,i)});const n=e.getPart(t);e.player.playPart({from:s.Z.settings.animationsEnabled&&!this.skipAnimation?n.startFrame:n.endFrame,to:n.endFrame,callback:i})}static generateEqualParts(e,t){return new Array(e).fill(0).map(((e,i)=>{const s=i*t;return{startFrame:s,endFrame:s+t-1}}))}}class ap extends np{constructor(e){super({width:e.width,height:e.height}),(0,x.Z)(this,e)}load(e,t){if(this.loaded)return this.loadPromise;this.loaded=!0,this.partState=e,this.colorState=t;const i=this.getPart(e),s=void 0!==t&&this.getColor&&this.getColor(t),n=i.item;n.initFrame=i.endFrame,n.color=s;const a=[...this.items.values()].map((e=>e.load()));return Promise.all(a).then(ft.Z)}setState(e,t,i){this.loaded||this.load(e,t);let s=!1,n=!1;return void 0!==e?s=this.setPartState(e,t,i):void 0!==t&&(n=this.setColorState(t)),s||n}setPartState(e,t,i){const{partState:s}=this;return s===e?void 0!==t&&this.setColorState(t):(void 0!==t&&this.setColorState(t,!1),this.partState=e,this.getPart(e,s).play(i),!0)}setColorState(e,t=!0){const{colorState:i}=this;if(i===e||!this.getColor)return!1;this.colorState=e;const s=this.getItem(),n=this.getColor(e,i),a=()=>{s.player.setColor(n,t)};return s.player?a():s.onLoadForColor=a,!0}destroy(){this.items.forEach((e=>{e.loadPromise.then((()=>{e.player.remove()}))}))}}class op extends ap{constructor(){super({width:36,height:36,getPart:(e,t)=>{const i=Zp;let s;switch(e){case i.HAND:s=t===i.MUTED?"muted-to-hand":"unmuted-to-hand";break;case i.MUTED:s=t===i.HAND?"hand-to-muted":"mute";break;case i.UNMUTED:s="unmute"}return this.getItem().getPart(s)}}),this.container.classList.add("group-call-microphone-icon-container"),this.add({name:"voip_filled",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: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"}]})}}var rp=i(6733);class lp extends ap{constructor(e){super({width:32,height:32,getPart:(e,t)=>{const i=Ap;let s;switch(e){case i.HAND:s=3;break;case i.MUTED:s=t===i.HAND?0:2;break;case i.UNMUTED:s=1}return this.getItem().getPart(s)},getColor:e?(e,t)=>function(e){const t=Ap;let i;switch(e){case t.HAND:i="blue";break;case t.MUTED:case t.MUTED_FOR_ME:case t.MUTED_BY_ADMIN:i=e===t.MUTED?"secondary":"red";break;case t.UNMUTED:i="green"}const s=tp.getProperty("gc-"+i+"-text-color");return(0,pa.oo)(s)}(e):void 0}),this.colored=e,this.container.classList.add("group-call-participant-muted-icon-container");const t=np.generateEqualParts(4,21);this.add({name:"voice_outlined2",parts:t})}setState(e){return super.setState(function(e){const t=Ap;switch(e){case t.MUTED_BY_ADMIN:case t.MUTED_FOR_ME:return t.MUTED;default:return e}}(e),e)}}const cp="group-call-participant-status";class dp{constructor(e){this.withIcons=e,this.container=document.createElement("div"),this.container.classList.add(cp+"-container")}setState(e,t){const i=Ap,s=this.withIcons.filter((e=>!!t[e])).map((e=>{const t="tgico-"+("presentation"===e?"listscreenshare":"videocamera_filled"),i=document.createElement("i");return i.classList.add(cp+"-icon",cp+"-icon-"+e,t),i}));let n,a;if(e===i.MUTED_FOR_ME)n=(0,v.ag)("VoiceChat.Status.MutedForYou"),a="is-muted";else if(e===i.UNMUTED)n=(0,v.ag)("VoiceChat.Status.Speaking"),a="is-speaking";else if(e===i.HAND)n=(0,v.ag)("VoiceChat.Status.WantsSpeak"),a="is-waiting";else{if(t.about&&!s.length)return void(0,c.Z)(this.container,(0,Zt.Z)(t.about));n=(0,v.ag)("VoiceChat.Status.Listening"),a="is-listening"}const o=document.createElement("span");o.classList.add(cp,a),o.append(...s,n),(0,g.Z)(this.container,o)}}var hp=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class up extends za{constructor(e){super({getIndex:e=>hp(this,void 0,void 0,(function*(){return(yield this.instance.getParticipantByPeerId(e.id)).date})),onDelete:e=>{e.dom.listEl.remove(),this.onElementDestroy(e)},onUpdate:e=>hp(this,void 0,void 0,(function*(){const t=yield this.instance.getParticipantByPeerId(e.id),i=Fp(t);e.mutedIcon.setState(i),e.status.setState(i,t)})),onSort:(e,t)=>{Ln(e.dom.listEl,this.list,t)},onElementCreate:e=>{const{dom:t}=gg.addDialogNew({peerId:e.id,container:!1,avatarSize:this.avatarSize,autonomous:this.autonomous,meAsSaved:!1,rippleEnabled:this.rippleEnabled,lazyLoadQueue:this.lazyLoadQueue});t.listEl.classList.add("group-call-participant");const i=new lp(!0),s=new dp(["presentation","video"]);return(0,g.Z)(t.lastMessageSpan,s.container),t.listEl.append(i.container),e.mutedIcon=i,e.status=s,e.dom=t,e},updateElementWith:Be.T2}),this.instance=e,this.avatarSize=54,this.rippleEnabled=!0,this.autonomous=!0,this.createChatListOptions={dialogSize:72},this.list=gg.createChatList(this.createChatListOptions)}destroy(){this.elements.forEach((e=>{this.onElementDestroy(e)}))}onElementDestroy(e){e.mutedIcon.destroy()}}class pp extends L.Z{constructor(){super(!1),this.hideControls=(e=!1)=>{if(e)return void(this.hideControlsTimeout||(this.hideControlsTimeout=window.setTimeout(this.hideControls,3e3)));clearTimeout(this.hideControlsTimeout),this.hideControlsTimeout=0;const t=this.element.classList.contains("show-controls");if(!1!==this.controlsLocked){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")||!1===this.controlsLocked||(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(void 0===e)t?this.hideControls():this.showControls();else{if(e===t)return;!1===e?this.hideControls():this.showControls()}},this.hideControlsTimeout=0}setup(e){(0,x.Z)(this,e);const{listenerSetter:t,element:i}=this;gi.Z?t.add(i)("click",(e=>{this.ignoreClickClassName&&(0,r.Z)(e.target,this.ignoreClickClassName)||this.toggleControls()})):(t.add(i)("mousemove",(()=>{this.showControls()})),t.add(i)("mouseenter",(()=>{this.showControls(!1)})),t.add(i)("mouseleave",(e=>{e.relatedTarget&&this.showOnLeaveToClassName&&(0,r.Z)(e.relatedTarget,this.showOnLeaveToClassName)?this.showControls(!1):this.hideControls()})))}lockControls(e){this.controlsLocked=e,this.element.classList.toggle("disable-hover",!1===e),this.toggleControls(e)}}function mp(e){const t=document.createElement("canvas");t.classList.add("call-video-blur"),t.width=16,t.height=16;const i=t.getContext("2d",{alpha:!1});i.filter="blur(2px)";const s=()=>{i.drawImage(e,0,0,e.videoWidth,e.videoHeight,0,0,t.width,t.height)};return(0,ht.jt)((()=>(s(),t.isConnected))),s(),t}const gp="group-call-participant-video";class vp{constructor(e,t,i){this.managers=e,this.instance=t,this.source=i,this.container=document.createElement("div"),this.container.classList.add(gp+"-container"),this.info=document.createElement("div"),this.info.classList.add(gp+"-info"),this.left=document.createElement("div"),this.left.classList.add(gp+"-info-left"),this.right=document.createElement("div"),this.right.classList.add(gp+"-info-right"),this.info.append(this.left,this.right),this.container.append(this.info)}setPinned(e){if(!e)return void(this.header&&(this.header.remove(),this.header=void 0));if(this.header)return;this.header=document.createElement("div"),this.header.classList.add(gp+"-header");const t=document.createElement("i");t.classList.add("group-call-pin-icon","tgico-pin"),this.header.append(t),this.container.append(this.header)}setParticipant(e,t,i){let s;e.pFlags.self?(s=(0,v.ag)("VoiceChat.Status.You"),s.classList.add("peer-title")):(this.peerTitle=new Ot({peerId:(0,es.Z)(e.peer)}),s=this.peerTitle.element),this.groupCallParticipantMutedIcon=new lp(!1),this.groupCallParticipantStatus=new dp([t]),this.left.append(s,this.groupCallParticipantStatus.container),this.right.append(this.groupCallParticipantMutedIcon.container),i.classList.add(gp,"call-video"),i.paused&&i.play();const n=mp(i);n.classList.add(gp+"-blur"),this.container.prepend(n,i),this.updateParticipant(e)}updateParticipant(e){const t=Fp(e);this.groupCallParticipantMutedIcon.setState(t),this.groupCallParticipantStatus.setState(t,e)}destroy(){this.groupCallParticipantMutedIcon.destroy()}}class fp extends pp{constructor(e){super(),(0,x.Z)(this,e);const t=this.container=document.createElement("div");this.container.classList.add("group-call-participants-video-container"),e.appendTo.append(t),this.participantsElements=new Map,this.containers=new Map;const{listenerSetter:i}=this;i.add(s.Z)("group_call_participant",(({groupCallId:e,participant:t})=>{this.instance.id===e&&this.updateParticipant(t)})),i.add(this.instance)("pinned",(e=>{this.participantsElements.forEach((t=>{t.forEach((t=>{this.setElementDisplay(t,e)}))}))})),(0,n.fc)(this.container,(e=>{const t=(0,r.Z)(e.target,"group-call-participant-video-container");if(!t)return;const i=this.containers.get(t);this.instance.pinnedSource!==i.source?this.instance.pinSource(i.source):this.instance.unpinAll()}),{listenerSetter:i}),this.setInstance(this.instance),this.setup({element:t,listenerSetter:i,showOnLeaveToClassName:"group-call-buttons"})}shouldDisplayElement(e,t){return this.displayPinned?!t||e.source===t:t&&e.source!==t}setElementDisplay(e,t){const i=this.shouldDisplayElement(e,t);e.container.classList.toggle("video-hidden",!i);const s=e.source===t;e.setPinned(s)}updateParticipant(e){const t=(0,es.Z)(e.peer),i=["video","presentation"],s=i.some((t=>!!e[t]));let n=this.participantsElements.get(t);(s||n)&&(n||this.participantsElements.set(t,n=new Map),i.forEach((i=>{let s=n.get(i);const a=e[i];if(!!a!=!!s){if(a){const t=this.instance.getVideoElementFromParticipantByType(e,i);if(!t)return;const{video:a,source:o}=t;s=new vp(this.managers,this.instance,o),this.containers.set(s.container,s),this.setElementDisplay(s,this.instance.pinnedSource),n.set(i,s),s.setParticipant(e,i,a),this.container.prepend(s.container)}else n.delete(i),s.container.remove(),n.size||(this.participantsElements.delete(t),this.containers.delete(s.container),s.destroy());this._onLengthChange()}else s&&s.updateParticipant(e)})))}_onLengthChange(){const e=this.container.childElementCount;this.container.dataset.length=""+e,this.container.dataset.layout=e<=2?"1":3===e?"3":"4",this.onLengthChange&&this.onLengthChange(e)}setInstance(e){return t=this,i=void 0,n=function*(){(yield e.participants).forEach((e=>{this.updateParticipant(e)}))},new((s=void 0)||(s=Promise))((function(e,a){function o(e){try{l(n.next(e))}catch(e){a(e)}}function r(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,r)}l((n=n.apply(t,i||[])).next())}));var t,i,s,n}destroy(){this.containers.forEach((e=>{e.destroy()}))}}var yp=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class bp{constructor(e){this.onOpenProfileClick=()=>{const e=A.Z.getPopups(Bp)[0];e&&e.hide(),_m.setInnerPeer({peerId:this.targetPeerId})},this.toggleParticipantMuted=e=>{this.instance.editParticipant(this.participant,{muted:e})},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 danger",text:"VoiceChat.RemovePeer",verify:()=>this.managers.appChatsManager.hasRights(this.chatId,"ban_users"),onClick:()=>yp(this,void 0,void 0,(function*(){In({peerId:this.targetPeerId,title:new Ot({peerId:this.targetPeerId}).element,descriptionLangKey:(yield this.managers.appChatsManager.isBroadcast(this.chatId))?"VoiceChat.RemovePeer.Confirm.Channel":"VoiceChat.RemovePeer.Confirm",descriptionLangArgs:[new Ot({peerId:this.targetPeerId}).element],button:{langKey:"VoiceChat.RemovePeer.Confirm.OK",isDanger:!0}}).then((()=>{this.managers.appChatsManager.kickFromChat(this.chatId,this.targetPeerId)}),ft.Z)}))}];const{listenerSetter:t}=e;this.managers=e.managers,this.instance=e.instance,this.chatId=this.instance.chatId,this.element=Ei(this.buttons,t),this.element.classList.add("group-call-participant-menu","night"),Fi(e.onContextElement,(e=>yp(this,void 0,void 0,(function*(){const t=(0,r.Z)(e.target,"group-call-participant");if(!t)return;this.element.parentElement!==i&&i.append(this.element),(0,a.Z)(e);const s=this.targetPeerId=t.dataset.peerId.toPeerId();this.participant=yield this.instance.getParticipantByPeerId(s),this.participant.pFlags.self||(this.canManageCall=yield this.managers.appChatsManager.hasRights(this.chatId,"manage_call"),yield ki(this.buttons,(e=>yp(this,void 0,void 0,(function*(){const t=yield e.verify(s);return e.element.classList.toggle("hide",!t),t})))),xi(e.touches?e.touches[0]:e,this.element,"right"),Ii.openBtnMenu(this.element))}))),t),t.add(s.Z)("group_call_participant",(({groupCallId:e,participant:t})=>{if(this.instance.id===e){const e=(0,es.Z)(t.peer);this.targetPeerId===e&&Ii.close()}}));let i=document.body;(0,rp.Ms)(document.body,(()=>{const e=(0,rp.rB)();i=e?A.Z.getPopups(Bp)[0].getContainer():document.body,e||Ii.close()}),t)}}class wp{constructor(e){(0,x.Z)(this,e);const t="group-call-participants",i=new m.ZP(void 0);i.container.classList.add(t+"-scrollable");const n=this.container=document.createElement("div");n.classList.add(t);const a=this.sortedList=new up(this.instance),{instance:o,listenerSetter:r}=this;this.contextMenu=new bp(Object.assign(Object.assign({},e),{onContextElement:a.list,listenerSetter:r,instance:o})),this.groupCallParticipantsVideo=new fp(Object.assign(Object.assign({},e),{appendTo:i.container,displayPinned:!1})),i.append(a.list),n.append(i.container),e.appendTo.append(n),r.add(s.Z)("group_call_participant",(({groupCallId:e,participant:t})=>{this.instance.id===e&&this.updateParticipant(t)})),new Yi({scrollable:i,getPromise:()=>this.managers.appGroupCallsManager.getGroupCallParticipants(this.instance.id).then((({participants:e,isEnd:t})=>(e.forEach((e=>{this.updateParticipant(e)})),t)))}),this.setInstance(o)}updateParticipant(e){const t=(0,es.Z)(e.peer),i=this.sortedList.has(t);e.pFlags.left?i&&this.sortedList.delete(t):i?this.sortedList.update(t):this.sortedList.add(t)}setInstance(e){return yp(this,void 0,void 0,(function*(){(yield e.participants).forEach((e=>{this.updateParticipant(e)}))}))}destroy(){this.sortedList.destroy(),this.groupCallParticipantsVideo.destroy()}}class Sp{constructor(e){this.appendTo=e,this.descriptionIntl=new v.ZP.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 i,s;t===Pu.CONNECTING?i="VoiceChat.Status.Connecting":(i="VoiceChat.Status.Members",s=[e.groupCall.participants_count]);const{descriptionIntl:n}=this;n.compareAndUpdate({key:i,args:s}),this.descriptionIntl.element.parentElement||this.appendTo.append(this.descriptionIntl.element)}}class Cp{constructor(e){this.appendTo=e,this.peerTitle=new Ot({peerId:0})}update(e){const{peerTitle:t,appendTo:i}=this,s=e.groupCall,n=e.chatId.toPeerId(!0);s.title?(0,c.Z)(i,(0,Zt.Z)(s.title)):(t.peerId!==n&&(t.peerId=n,t.update()),t.element.parentElement!==i&&i.append(t.element))}}var Lp=i(2820);function Ip(e,t,i){const s=e+"-button",a=document.createElement("div");a.classList.add(s,"call-button","rp-overflow"),i.icon&&a.classList.add("tgico-"+i.icon),i.noRipple||(0,we.Z)(a),i.isDanger&&a.classList.add(s+"-red"),i.isConfirm&&a.classList.add(s+"-green"),i.callback&&(0,n.fc)(a,i.callback,{listenerSetter:t});let o=a;if(i.text){const e=document.createElement("div");e.classList.add(s+"-container","call-button-container");const t="string"==typeof i.text?(0,v.ag)(i.text):i.text;t.classList.add(s+"-text","call-button-text"),e.append(a,t),o=e}return o}const Mp="movable-element",Ep="movable-element-resize-handler";class Pp extends L.Z{constructor(e){super(!0),this.onResize=()=>{this.fixDimensions(),this.fixPosition(),this.setPosition()},(0,x.Z)(this,e),this.top=this.left=this.width=this.height=0,this.element.classList.add(Mp),this.addResizeHandlers(),this.setSwipeHandler(),d.Z.addEventListener("resize",this.onResize)}destroyElements(){this.element.classList.remove(Mp),this.handlers&&this.handlers.forEach((e=>{e.remove()}))}destroy(){d.Z.removeEventListener("resize",this.onResize),this.swipeHandler.removeListeners()}addResizeHandlers(){this.handlers=["n","e","s","w","ne","se","sw","nw"].map((e=>{const t=document.createElement("div");return t.dataset.side=e,t.classList.add(Ep,Ep+"-side-"+e),this.element.append(t),t}))}setSwipeHandler(){let e,t,i,s,n;const a=this.swipeHandler=new Ks({element:this.element,onSwipe:(a,o,r)=>{if(a*=-1,o*=-1,n){if(n.includes("e")||n.includes("w")){const e=n.includes("e")&&a>0||n.includes("w")&&a<0,s=Math.abs(a)*(e?1:-1),o=n.includes("e")?as.width-t:i+t;this.width=Math.min(o,i+s)}if(n.includes("n")||n.includes("s")){const t=n.includes("s")&&o>0||n.includes("n")&&o<0,i=Math.abs(o)*(t?1:-1),a=n.includes("s")?as.height-e:s+e;this.height=Math.min(a,s+i)}this.fixDimensions(),n.includes("w")&&(this.left=Math.min(t+i-this.minWidth,t+a)),n.includes("n")&&(this.top=Math.min(e+s-this.minHeight,e+o))}else this.top=e+o,this.left=t+a;this.fixPosition(),this.setPosition()},verifyTouchTarget:e=>{const t=e.target;if(this.verifyTouchTarget&&!this.verifyTouchTarget(e))return!1;const i=(0,r.Z)(t,Ep);return i?(n=i.dataset.side,a.setCursor("")):(n=void 0,a.setCursor("grabbing")),!0},onFirstSwipe:()=>{e=this.top,t=this.left,i=this.width,s=this.height}})}setPositionToCenter(){this.top=as.height/2-this.height/2,this.left=as.width/2-this.width/2,this.setPosition()}fixDimensions(){this.width=(0,Me.Z)(this.width,this.minWidth,as.width),this.height=(0,Me.Z)(this.height,this.minHeight,as.height)}fixPosition(){this.top=(0,Me.Z)(this.top,0,as.height-this.height),this.left=(0,Me.Z)(this.left,0,as.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:i,height:s}=this;return{top:e,left:t,width:i,height:s}}set state(e){const{top:t,left:i,width:s,height:n}=e;this.top=t,this.left=i,this.width=s,this.height=n,this.onResize()}}var kp,Tp=function(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i};class xp{constructor(e){kp.set(this,void 0),(0,x.Z)(this,e),this.toggleMovable(!gi.Z),this.listenerSetter.add(d.Z)("changeScreen",((e,t)=>{t!==d._.mobile&&e!==d._.mobile||this.toggleMovable(!gi.Z)}))}destroy(){const e=this.movable;e&&e.destroy()}get movable(){return function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)}(this,kp,"f")}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=Tp(this,kp,new Pp(this.movableOptions),"f"),t.state=this.previousState,void 0===this.previousState.top&&t.setPositionToCenter(),this.onResize&&this.listenerSetter.add(t)("resize",this.onResize)}else{if(!t)return;this.previousState=t.state,t.destroyElements(),t.destroy(),Tp(this,kp,void 0,"f")}}}function _p(e,t,i){return t.forEach((t=>{t.classList.toggle(e,i)})),()=>_p(e,t,!i)}kp=new WeakMap;var Ap,Zp;function Fp(e){const t=Ap;return e.pFlags.muted_by_you?t.MUTED_FOR_ME:void 0!==e.raise_hand_rating?t.HAND:e.pFlags.muted?e.pFlags.can_self_unmute?t.MUTED:t.MUTED_BY_ADMIN:t.UNMUTED}!function(e){e[e.UNMUTED=0]="UNMUTED",e[e.MUTED=1]="MUTED",e[e.MUTED_FOR_ME=2]="MUTED_FOR_ME",e[e.MUTED_BY_ADMIN=3]="MUTED_BY_ADMIN",e[e.HAND=4]="HAND"}(Ap||(Ap={})),function(e){e[e.HAND=0]="HAND",e[e.MUTED=1]="MUTED",e[e.UNMUTED=2]="UNMUTED"}(Zp||(Zp={}));let Dp={width:420,height:640};const Rp="group-call";class Bp extends A.Z{constructor(){super("popup-group-call",{body:!0,withoutOverlay:!0,closable:!0,title:!0}),this.onFullScreenClick=()=>{(0,rp.Dj)(this.container)},this.onToggleControls=e=>{this.container.classList.toggle("show-controls",e),this.buttonsContainer.classList.toggle("show-controls",e)},this.toggleDisability=_p.bind(null,"btn-disabled"),this.onVideoClick=()=>{const e=this.toggleDisability([this.btnVideo],!0);this.instance.toggleVideoSharing().finally((()=>{e()}))},this.onScreenClick=()=>{const e=this.toggleDisability([this.btnScreen],!0);this.instance.toggleScreenSharing().finally((()=>{e()}))},this.onMuteClick=()=>{const e=this.instance.participant;e.pFlags.can_self_unmute?this.instance.toggleMuted():void 0===e.raise_hand_rating&&this.instance.changeRaiseHand(!0)},this.onLeaveClick=()=>{return e=this,t=void 0,s=function*(){const e=e=>{this.instance.hangUp(e)};(yield this.managers.appChatsManager.hasRights(this.instance.chatId,"manage_call"))?new qi("popup-end-video-chat",{titleLangKey:"VoiceChat.End.Title",descriptionLangKey:"VoiceChat.End.Text",checkboxes:[{text:"VoiceChat.End.Third"}],buttons:[{langKey:"VoiceChat.End.OK",callback:t=>{e(!!t.size)},isDanger:!0}]}).show():e(!1)},new((i=void 0)||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}));var e,t,i,s},this.onFullScreenChange=()=>{this.toggleBigLayout();const e=(0,rp.rB)(),{btnFullScreen:t,btnExitFullScreen:i}=this,s=this.container.classList.contains("is-full-screen");this.container.classList.toggle("is-full-screen",e),t&&t.classList.toggle("hide",e),i&&i.classList.toggle("hide",!e),this.btnClose.classList.toggle("hide",e),e!==s&&(p.Z.checkAnimations(e),$o.Z.setThemeColor(e?"#000000":void 0))},this.toggleBigLayout=()=>{var e;const t=(0,rp.rB)(),i=null===(e=this.movablePanel)||void 0===e?void 0:e.movable,s=(t||!!(i&&i.width>=680))&&!!this.videosCount,n=this.container.classList.contains("is-big-layout");let a;s&&!n&&(a=Array.from(this.buttonsContainer.children),a.forEach((e=>{e.style.opacity="0"})),this.buttonsContainer.offsetLeft),this.container.classList.toggle("is-big-layout",s),this.btnInvite.classList.toggle("hide",s),this.btnShowColumn.classList.toggle("hide",!s),a&&a.forEach((e=>{e.style.opacity=""}))},this.toggleRightColumn=()=>{this.container.classList.toggle("is-right-column-shown")},this.videosCount=0,this.container.classList.add(Rp,"night");const e=this.instance=Fu.groupCall,{listenerSetter:t}=this;if(!Je.IS_APPLE_MOBILE){const e=this.btnFullScreen=E("fullscreen"),i=this.btnFullScreen2=E("fullscreen group-call-cfs"),s=this.btnExitFullScreen=E("smallscreen");(0,n.fc)(e,this.onFullScreenClick,{listenerSetter:t}),(0,n.fc)(i,this.onFullScreenClick,{listenerSetter:t}),(0,n.fc)(s,(()=>{(0,rp.C8)()}),{listenerSetter:t}),(0,rp.Ms)(this.container,this.onFullScreenChange,t)}this.btnInvite=E("adduser");const i=this.btnShowColumn=E("rightpanel group-call-only-big");(0,n.fc)(i,this.toggleRightColumn,{listenerSetter:t});const a=document.createElement("div");a.classList.add("group-call-header-info"),this.title.classList.add("group-call-header-title");const o=document.createElement("div");o.classList.add("group-call-header-subtitle"),a.append(this.title,o),this.header.classList.add("group-call-header"),this.header.append(...[this.btnExitFullScreen,a,this.btnFullScreen,i].filter(Boolean));const l=this.header.cloneNode(!1),c=a.cloneNode(!1),d=this.title.cloneNode(!1);c.append(d);const h=E("rightpanel");l.append(...[h,c,this.btnFullScreen2].filter(Boolean)),(0,n.fc)(h,this.toggleRightColumn,{listenerSetter:t}),this.body.prepend(l);const u=new m.ZP(void 0);u.container.classList.add("group-call-big-video-container"),this.container.append(u.container),this.groupCallTitle=new Cp(this.title),this.groupCallDescription=new Sp(o),this.groupCallBodyHeaderDescription=new Sp(d),this.constructButtons(),this.groupCallParticipantsVideo=new fp({appendTo:u.container,instance:e,listenerSetter:t,displayPinned:!0,onLengthChange:e=>{this.videosCount=e,this.toggleBigLayout()},managers:this.managers}),this.groupCallParticipants=new wp({appendTo:this.body,instance:e,listenerSetter:t,managers:this.managers}),this.movablePanel=new xp({listenerSetter:t,movableOptions:{minWidth:400,minHeight:480,element:this.element,verifyTouchTarget:e=>{const t=e.target;return!((0,r.Z)(t,"chatlist")||(0,r.Z)(t,"group-call-button")||(0,r.Z)(t,"btn-icon")||(0,r.Z)(t,"group-call-participants-video-container")||(0,rp.rB)())}},onResize:()=>this.toggleBigLayout(),previousState:Dp}),t.add(e)("state",(()=>{this.updateInstance()})),t.add(s.Z)("group_call_update",(e=>{var t;(null===(t=this.instance)||void 0===t?void 0:t.id)===e.id&&this.updateInstance()})),t.add(e)("pinned",(()=>{this.setHasPinned()})),t.add(this.groupCallParticipantsVideo)("toggleControls",this.onToggleControls),this.addEventListener("close",(()=>{const{movablePanel:e}=this;Dp=e.state,this.groupCallParticipantsVideo.destroy(),this.groupCallParticipants.destroy(),this.groupCallMicrophoneIcon.destroy(),e.destroy()})),this.toggleRightColumn(),this.onFullScreenChange(),this.updateInstance()}constructButtons(){const e=this.buttonsContainer=document.createElement("div");e.classList.add("group-call-buttons");const t=Ip.bind(null,Rp,this.listenerSetter),i=this.btnVideo=t({callback:this.onVideoClick,icon:"videocamera_filled"}),s=this.btnScreen=t({callback:this.onScreenClick,icon:"sharescreen_filled"});s.classList.toggle("hide",!Lp.Z);const n=t({noRipple:!0,callback:(0,mt.Z)(this.onMuteClick,600,!0)});n.classList.add("group-call-microphone-button");const a=this.groupCallMicrophoneIcon=new op;n.append(a.container);const o=t({icon:"settings_filled"});o.classList.add("btn-disabled"),o.classList.toggle("hide",!Lp.Z);const r=t({isDanger:!0,callback:this.onLeaveClick,icon:"close"});e.append(i,s,n,o,r),this.container.append(e)}getContainer(){return this.container}setHasPinned(){this.container.classList.toggle("has-pinned",!!this.instance.pinnedSource)}updateInstance(){if(this.instance.state===Pu.CLOSED)return this.container.classList.contains("is-full-screen")&&(0,rp.C8)(),void this.hide();const{participant:e,groupCall:t}=this.instance;if(!e)return;this.setTitle(),this.setDescription(),this.setHasPinned();const i=function(e,t){const i=Zp;return t.pFlags.can_self_unmute?t.pFlags.muted?i.MUTED:i.UNMUTED:i.HAND}(0,e);this.container.dataset.micState=i===Zp.HAND?"hand":i===Zp.MUTED?"muted":"unmuted",this.groupCallMicrophoneIcon.setState(i)}setTitle(){this.groupCallTitle.update(this.instance)}setDescription(){this.groupCallDescription.update(this.instance),this.groupCallBodyHeaderDescription.update(this.instance)}}var Np;!function(e){e[e.CONNECTED=0]="CONNECTED",e[e.CONNECTING=1]="CONNECTING",e[e.EXCHANGING_KEYS=2]="EXCHANGING_KEYS",e[e.PENDING=3]="PENDING",e[e.REQUESTING=4]="REQUESTING",e[e.CLOSING=5]="CLOSING",e[e.CLOSED=6]="CLOSED"}(Np||(Np={}));const Up=Np;class Op{constructor(e){this.appendTo=e,this.container=document.createElement("div"),this.container.classList.add("call-description")}detach(){void 0!==this.interval&&(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;let i;if(this.state=t,t===Up.CONNECTED){i=document.createElement("span"),i.classList.add("call-description-duration");const t=()=>{i.innerText=gt(e.duration,!0)};this.interval=window.setInterval(t,1e3),t()}else{let s;switch(t){case Up.PENDING:s=e.isOutgoing?"Call.StatusRinging":"Call.StatusCalling";break;case Up.REQUESTING:s="Call.StatusRequesting";break;case Up.EXCHANGING_KEYS:s="VoipExchangingKeys";break;case Up.CLOSED:s=void 0!==e.connectedAt?"Call.StatusEnded":"Call.StatusFailed";break;default:s="Call.StatusConnecting"}i=(0,v.ag)(s),void 0!==this.interval&&(clearInterval(this.interval),this.interval=void 0)}this.container.classList.toggle("has-duration",t===Up.CONNECTED),(0,g.Z)(this.container,i),this.container.parentElement||this.appendTo.append(this.container)}}class Hp extends ap{constructor(e,t){super({width:36,height:36,getPart:e=>this.getItem().getPart(e?"unmute":"mute"),getColor:e?e=>e?[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 zp="call",Gp={width:400,height:580};let Vp=Object.assign({},Gp);class Kp extends A.Z{constructor(e){super("popup-call",{withoutOverlay:!0,closable:!0}),this.instance=e,this.onFullScreenClick=()=>{(0,rp.Dj)(this.container)},this.onFullScreenChange=()=>{const e=(0,rp.rB)(),{btnFullScreen:t,btnExitFullScreen:i}=this,s=this.container.classList.contains("is-full-screen");this.container.classList.toggle("is-full-screen",e),t&&t.classList.toggle("hide",e),i&&i.classList.toggle("hide",!e),this.btnClose.classList.toggle("hide",e),e!==s&&(p.Z.checkAnimations(e),$o.Z.setThemeColor(e?"#000000":void 0),this.resizeVideoContainers())},this.videoContainers={};const{container:t,listenerSetter:i}=this;t.classList.add(zp,"night");const s=document.createElement("div");s.classList.add("call-avatar");const a=this.peerId=this.instance.interlocutorUserId.toPeerId(),o=new Wm;o.classList.add("avatar-full"),o.updateWithOptions({isBig:!0,peerId:a}),s.append(o);const l=new Ot({peerId:a}).element;l.classList.add("call-title");const c=document.createElement("div");c.classList.add("call-subtitle"),this.description=new Op(c);const d=this.emojisSubtitle=document.createElement("div");d.classList.add("call-emojis"),t.append(s,l,c),Je.IS_MOBILE?this.header.append(d):(this.btnFullScreen=E("fullscreen"),this.btnExitFullScreen=E("smallscreen hide"),(0,n.fc)(this.btnFullScreen,this.onFullScreenClick,{listenerSetter:i}),(0,n.fc)(this.btnExitFullScreen,(()=>(0,rp.C8)()),{listenerSetter:i}),(0,rp.Ms)(this.container,this.onFullScreenChange,i),this.header.prepend(this.btnExitFullScreen),this.header.append(this.btnFullScreen),t.append(d)),this.partyStates=document.createElement("div"),this.partyStates.classList.add("call-party-states"),this.partyMutedState=document.createElement("div"),this.partyMutedState.classList.add("call-party-state");const h=(0,v.ag)("VoipUserMicrophoneIsOff",[new Ot({peerId:a,onlyFirstName:!0,limitSymbols:18}).element]);h.classList.add("call-party-state-text");const u=new Hp(!1,!0);u.setState(!1,!1),this.partyMutedState.append(u.container,h),this.partyStates.append(this.partyMutedState),this.container.append(this.partyStates),this.makeButton=Ip.bind(null,zp,this.listenerSetter),this.constructFirstButtons(),this.constructSecondButtons(),i.add(e)("state",(()=>{this.updateInstance()})),i.add(e)("mediaState",(()=>{this.updateInstance()})),this.movablePanel=new xp({listenerSetter:i,movableOptions:{minWidth:400,minHeight:580,element:this.element,verifyTouchTarget:e=>{const t=e.target;return!((0,r.Z)(t,"call-button")||(0,r.Z)(t,"btn-icon")||(0,rp.rB)())}},previousState:this.instance.wasTryingToJoin||this.instance.isOutgoing?Vp:Object.assign({},Gp)});const m=this.movablePanel.movable;m&&this.listenerSetter.add(m)("resize",(()=>{this.resizeVideoContainers()}));const g=this.controlsHover=new pp;g.setup({element:this.container,listenerSetter:this.listenerSetter,showOnLeaveToClassName:"call-buttons"}),g.showControls(!1),this.addEventListener("close",(()=>{const{movablePanel:e}=this;Vp=e.state,this.microphoneIcon.destroy(),e.destroy()})),this.updateInstance()}getCallInstance(){return this.instance}constructFirstButtons(){const e=this.firstButtonsRow=document.createElement("div");e.classList.add("call-buttons","is-first");const t=_p.bind(null,"btn-disabled"),i=this.btnVideo=this.makeButton({text:"Call.Camera",icon:"videocamera_filled",callback:()=>{const e=t([i,s],!0);this.instance.toggleVideoSharing().finally(e)}}),s=this.btnScreen=this.makeButton({text:"Call.Screen",icon:"sharescreen_filled",callback:()=>{const e=t([i,s],!0);this.instance.toggleScreenSharing().finally(e)}});Lp.Z||(s.classList.add("hide"),this.container.classList.add("no-screen")),this.muteI18nElement=new v.ZP.IntlElement({key:"Call.Mute"});const n=this.btnMute=this.makeButton({text:this.muteI18nElement.element,callback:()=>{this.instance.toggleMuted()}}),a=this.microphoneIcon=new Hp(!0,!0);n.firstElementChild.append(a.container),e.append(i,s,n),this.container.append(e)}constructSecondButtons(){const e=this.secondButtonsRow=document.createElement("div");e.classList.add("call-buttons","is-second"),this.declineI18nElement=new v.ZP.IntlElement({key:"Call.Decline"});const t=this.btnDecline=this.makeButton({text:this.declineI18nElement.element,icon:"endcall_filled",callback:()=>{this.instance.hangUp("phoneCallDiscardReasonHangup")},isDanger:!0}),i=this.btnAccept=this.makeButton({text:"Call.Accept",icon:"phone_filled",callback:()=>{this.instance.acceptCall()},isConfirm:!0});e.append(t,i),this.container.append(e)}createVideoContainer(e){const t=document.createElement("div");t.classList.add("call-video-container"),e.classList.add("call-video"),e.paused&&e.play(),(0,n.fc)(t,(()=>{if(!t.classList.contains("small"))return;const e=Object.values(this.videoContainers).find((e=>!e.classList.contains("small")));e.classList.add("small"),e.style.cssText=t.style.cssText,t.classList.remove("small"),t.style.cssText="",this.resizeVideoContainers()}));const i=mp(e);return i.classList.add("call-video-blur"),t.append(i,e),t}updateInstance(){const{instance:e}=this,{connectionState:t}=e;if(t===Up.CLOSED)return this.container.classList.contains("is-full-screen")&&(0,rp.C8)(),this.btnVideo.classList.add("disabled"),void this.hide();const i=!e.isOutgoing&&t===Up.PENDING;this.declineI18nElement.compareAndUpdate({key:t===Up.PENDING?"Call.Decline":"Call.End"}),this.btnAccept.classList.toggle("disable",!i),this.btnAccept.classList.toggle("hide-me",!i),this.container.classList.toggle("two-button-rows",i);const s=e.isMuted,n=()=>{this.btnMute.firstElementChild.classList.toggle("active",s)},a=this.microphoneIcon.getItem().player;this.microphoneIcon.setState(!s,!s,n),a||n(),this.muteI18nElement.compareAndUpdate({key:s?"VoipUnmute":"Call.Mute"});const o=e.isSharingVideo;this.btnVideo.firstElementChild.classList.toggle("active",o);const r=e.isSharingScreen;this.btnScreen.firstElementChild.classList.toggle("active",r);const l=e.getMediaState("output");Re(this.partyMutedState,"is-visible",!!(null==l?void 0:l.muted),300);const c=this.videoContainers,d=Object.assign({},c);["input","output"].forEach((t=>{const i=e.getMediaState(t),s=e.getVideoElement(t),n=!!(s&&s.videoWidth&&s.videoHeight);!s||n||s.dataset.hasPromise||(s.dataset.hasPromise="1",(0,pt.Z)(s).then((()=>{delete s.dataset.hasPromise,this.updateInstance()})));const a=!!s&&n&&!(!i||"active"!==i.videoState&&"active"!==i.screencastState);let o=c[t];a&&s&&!o&&(o=c[t]=this.createVideoContainer(s),this.container.append(o)),!a&&o&&(o.remove(),delete c[t])}));{const e=c.input,t=c.output;Object.keys(d).length!==Object.keys(c).length&&e&&e.classList.toggle("small",!!t),t&&!e&&t.classList.remove("small")}this.resizeVideoContainers(),this.container.classList.toggle("no-video",!Object.keys(c).length),!this.emojisSubtitle.textContent&&t<Up.EXCHANGING_KEYS&&Promise.resolve(e.getEmojisFingerprint()).then((e=>{(0,g.Z)(this.emojisSubtitle,(0,Zt.Z)(e.join("")))})),this.setDescription()}resizeVideoContainers(){Object.values(this.videoContainers).forEach((e=>{if(e.classList.contains("small")){const t=e.querySelector("video"),i=this.movablePanel.state,s=240,n=240,a=t.videoHeight>t.videoWidth,o=a?n:s,r=1/3*((0,rp.rB)()?65535:a?i.height:i.width),l=a?t.videoWidth/t.videoHeight:1,c=a?1:t.videoHeight/t.videoWidth;e.style.width=r*l+"px",e.style.height=r*c+"px",e.style.maxWidth=o*l+"px",e.style.maxHeight=o*c+"px"}else e.style.cssText=""}))}setDescription(){this.description.update(this.instance)}}function Wp(e){const t=Lu(e,e.media[0]),i={"@type":"InitialSetup",fingerprints:[t.fingerprint],ufrag:t.ufrag,pwd:t.pwd,audio:void 0,video:void 0,screencast:void 0},s=e=>""+e;for(const t of e.media){const n=t.mediaType;if("application"===n||!t.isSending)continue;const a=i["video"===n&&i.video?"screencast":n]={},o=Lu(e,t);a.ssrc=s(o.source),o.sourceGroups&&(a.ssrcGroups=o.sourceGroups.map((e=>({semantics:e.semantics,ssrcs:e.sources.map(s)}))));const r=a.rtpExtensions=[];t.attributes.get("extmap").forEach((e=>{r.push({id:+e.key,uri:e.value})}));const l=new Map,c=e=>{let t=l.get(e);return t||l.set(e,t={id:e}),t};t.attributes.get("rtpmap").forEach((e=>{const t=+e.key,i=c(t),s=e.value.split("/"),[n,a,o]=s;i.name=n,i.clockrate=+a,i.channels=o?+o:0})),t.attributes.get("rtcp-fb").forEach((e=>{const t=+e.key;c(t).feedbackTypes=e.lines.map((e=>{const t=e.split(" "),[i,s]=t;return{type:i,subtype:s||""}}))})),t.attributes.get("fmtp").forEach((e=>{const t=+e.key,i=c(t).parameters={},s=e.value.split(";");for(const e of s){const[t,s]=e.split("=");i[t]=s}})),a.payloadTypes=Array.from(l.values())}return i}class $p extends fh{constructor(e){super(e)}negotiateInternal(){return e=this,t=void 0,s=function*(){const{connection:e,call:t}=this;if(!e.localDescription&&!e.remoteDescription&&!t.isOutgoing)return;let i;if(t.offerReceived){t.offerReceived=!1;const s=i=yield e.createAnswer();this.log("[sdp] local",s.type,s.sdp),yield e.setLocalDescription(s),this.log("[InitialSetup] send 2")}else{const s=i=yield e.createOffer();this.log("[sdp] local",s.sdp),yield e.setLocalDescription(s),t.offerSent=!0,this.log("[InitialSetup] send 0")}const s=Wp(Su(i.sdp));t.sendCallSignalingData(s)},new((i=void 0)||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}));var e,t,i,s}}let jp;var qp=i(4484),Qp=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const Yp=45e3;class Jp extends L.Z{construct(e){this.managers=e,this.log=(0,he.kg)("CC"),nl.Z&&(this.audioAsset=null!=jp?jp:jp=new qd(["call_busy.mp3","call_connect.mp3","call_end.mp3","call_incoming.mp3","call_outgoing.mp3","voip_failed.mp3"]),this.tempId=0,this.instances=new Map,this.sortedInstances=[],s.Z.addEventListener("call_update",(e=>Qp(this,void 0,void 0,(function*(){var t;let i=this.instances.get(e.id);switch(i&&i.setPhoneCall(e),e._){case"phoneCallDiscarded":i&&i.hangUp(null===(t=e.reason)||void 0===t?void 0:t._,!0);break;case"phoneCallAccepted":i&&i.confirmCall();break;case"phoneCallRequested":i||(i=this.createCallInstance({isOutgoing:!1,interlocutorUserId:e.admin_id}),i.overrideConnectionState(Up.PENDING),i.setPhoneCall(e),i.setHangUpTimeout(Yp,"phoneCallDiscardReasonMissed"));break;case"phoneCall":{if(!i||i.encryptionKey)break;const t=i.dh.g_a=e.g_a_or_b,s=i.dh,n=yield Gi.Z.invokeCrypto("sha256",t);if(!(0,qp.Z)(s.g_a_hash,n)){this.log.error("Incorrect g_a_hash",s.g_a_hash,n);break}const{key:a,key_fingerprint:o}=yield this.managers.appCallsManager.computeKey(t,s.b,s.p);if(e.key_fingerprint!==o){this.log.error("Incorrect key fingerprint",e.key_fingerprint,o,t,s),i.hangUp("phoneCallDiscardReasonDisconnect");break}i.encryptionKey=a,i.joinCall();break}}})))),s.Z.addEventListener("call_signaling",(({callId:e,data:t})=>{const i=this.instances.get(e);(null==i?void 0:i.id)===e&&i.onUpdatePhoneCallSignalingData(t)})))}get currentCall(){return this.sortedInstances[0]}getCallByUserId(e){for(const[t,i]of this.instances)if(i.interlocutorUserId===e)return i}createCallInstance(e){const t=new vm(Object.assign({managers:this.managers},e));return t.addEventListener("state",(e=>{const i=this.currentCall;e===Up.CLOSED?(this.instances.delete(t.id),(0,T.Z)(this.sortedInstances,t)):(0,Ha.Z)(this.sortedInstances,t,"sortIndex"),e===Up.EXCHANGING_KEYS&&(t.wasTryingToJoin=!0);const s=void 0!==t.connectedAt;e===Up.EXCHANGING_KEYS||e===Up.CONNECTING&&s?t.setHangUpTimeout(Yp,"phoneCallDiscardReasonDisconnect"):t.clearHangUpTimeout(),i!==t&&i||(e===Up.CLOSED?t.isOutgoing||t.wasTryingToJoin?t.wasTryingToJoin&&!s?this.audioAsset.playSound("voip_failed.mp3"):this.audioAsset.playSound("phoneCallDiscardReasonBusy"===t.discardReason?"call_busy.mp3":"call_end.mp3"):this.audioAsset.stopSound():e===Up.PENDING?this.audioAsset.playSound(t.isOutgoing?"call_outgoing.mp3":"call_incoming.mp3",!0):e===Up.EXCHANGING_KEYS?this.audioAsset.playSoundIfDifferent("call_connect.mp3"):e===Up.CONNECTING?t.duration&&this.audioAsset.playSound("voip_connecting.mp3",!0):this.audioAsset.stopSound())})),t.addEventListener("id",((e,i)=>{void 0!==i&&this.instances.delete(i);const s=!!this.currentCall;this.instances.set(e,t),void 0===i&&this.dispatchEvent("instance",{instance:t,hasCurrent:s})})),t}startCallInternal(e,t){return Qp(this,void 0,void 0,(function*(){this.log("p2pStartCallInternal",e,t);const i=yield this.managers.appProfileManager.getProfile(e);if(!i)return;const{video_calls_available:s}=i.pFlags,n=this.createCallInstance({isOutgoing:!0,interlocutorUserId:e});n.requestInputSource(!0,!(!t||!s),!1),n.overrideConnectionState(Up.REQUESTING),n.setPhoneCall({_:"phoneCallWaiting",access_hash:"",admin_id:le.NM,date:(0,wl.Z)(!0),id:--this.tempId,participant_id:e,protocol:n.protocol,pFlags:{video:t||void 0}}),this.managers.appCallsManager.generateDh().then((i=>Qp(this,void 0,void 0,(function*(){return n.dh=i,this.managers.appCallsManager.requestCall(e,n.protocol,n.dh.g_a_hash,t&&s)})))).then((e=>{n.overrideConnectionState(Up.PENDING),n.setPhoneCall(e),n.setHangUpTimeout(Yp,"phoneCallDiscardReasonHangup")}))}))}}const Xp=new Jp;R.GO&&(R.GO.callsController=Xp);const em=Xp;var tm=i(4903);const im="undefined"!=typeof window&&"crypto"in window?window.crypto.subtle:self.crypto.subtle;var sm=i(3692),nm=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class am{constructor(e,t){this.isOutgoing=e,this.p2pKey=t,this.type="Signaling",this.counter=0,this.seqMap=new Map}concatSHA256(e){return t=(0,tm.Z)(...e),im.digest("SHA-256",(0,sm.Z)(t)).then((e=>new Uint8Array(e)));var t}encryptPrepared(e){return nm(this,void 0,void 0,(function*(){const t={counter:0,bytes:new Uint8Array(16+e.length)},i=(this.isOutgoing?0:8)+("Signaling"===this.type?128:0),s=this.p2pKey,n=yield this.concatSHA256([s.subarray(i+88,i+88+32),e]),a=t.bytes;for(let e=0;e<16;++e)a[e]=n[e+8];const o=yield this.prepareAesKeyIv(s,a,i),r=yield this.aesProcessCtr(e,e.length,o,!0);return t.bytes=new Uint8Array([...t.bytes.subarray(0,16),...r]),t}))}encryptRawPacket(e){const t=++this.counter,i=new ArrayBuffer(4);new DataView(i).setUint32(0,t>>>0,!1);const s=new Uint8Array([...new Uint8Array(i),...e]);return this.encryptPrepared(s)}prepareAesKeyIv(e,t,i){return nm(this,void 0,void 0,(function*(){const[s,n]=yield Promise.all([this.concatSHA256([t.subarray(0,16),e.subarray(i,i+36)]),this.concatSHA256([e.subarray(40+i,40+i+36),t.subarray(0,16)])]);return{key:new Uint8Array([...s.subarray(0,8),...n.subarray(8,24),...s.subarray(24,32)]),iv:new Uint8Array([...n.subarray(0,4),...s.subarray(8,16),...n.subarray(24,28)])}}))}aesProcessCtr(e,t,i,s=!0){return nm(this,void 0,void 0,(function*(){const t=yield im.importKey("raw",i.key,{name:"AES-CTR"},!1,[s?"encrypt":"decrypt"]),n=yield im[s?"encrypt":"decrypt"]({name:"AES-CTR",counter:i.iv,length:8*i.iv.length},t,e);return new Uint8Array(n)}))}constTimeIsDifferent(e,t,i){let s=!0;for(let n=0;n<i;++n)e[n]!==t[n]&&(s=!1);return!s}decryptRawPacket(e){return nm(this,void 0,void 0,(function*(){if(e.length<21||e.length>134217728)return;const{isOutgoing:t,type:i}=this,s=(t?8:0)+("Signaling"===i?128:0),n=this.p2pKey,a=e.subarray(0,16),o=e.subarray(16),r=e.length-16,l=yield this.prepareAesKeyIv(n,a,s),c=yield this.aesProcessCtr(o,r,l,!1),d=yield this.concatSHA256([n.subarray(88+s,88+s+32),c]);if(this.constTimeIsDifferent(d.subarray(8),a,16))return;const h=new DataView(c.buffer).getUint32(0);return this.seqMap.has(h)?void 0:(this.seqMap.set(h,h),c.slice(4))}))}}class om{static generateOffer(e){const{fingerprints:t,ufrag:i,pwd:s,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a],r=new nh;r.add("v=0","o=- 1 2 IN IP4 127.0.0.1","s=-","t=0 0"),t&&t.forEach((e=>{const{hash:t,fingerprint:i,setup:s}=e;r.add(`a=fingerprint:${t} ${i}`,`a=setup:${s}`)})),i&&s&&r.add(`a=ice-ufrag:${i}`,`a=ice-pwd:${s}`),r.add("a=group:BUNDLE 0 1 2","a=extmap-allow-mixed","a=msid-semantic: WMS *");const l="stream"+o.map((e=>e.ssrc)).join("_");for(let e=0;e<o.length;e++){const t=o[e],{type:i,ssrc:s,ssrcGroups:n,payloadTypes:a,rtpExtensions:c}=t;switch(i){case"audio":r.add(`m=audio 56930 UDP/TLS/RTP/SAVPF ${a.map((e=>e.id)).join(" ")}`,"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle",`a=mid:${e}`,"a=sendrecv",hm(c)),s&&r.add(`a=msid:${l} audio${s}`),r.add("a=rtcp-mux",um(a),pm(i,s,n,l));break;case"video":r.add(`m=video 61986 UDP/TLS/RTP/SAVPF ${a.map((e=>e.id)).join(" ")}`,"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle",`a=mid:${e}`,"a=sendrecv",hm(c)),s&&r.add(`a=msid:${l} video${s}`),r.add("a=rtcp-mux","a=rtcp-rsize",um(a),pm(i,s,n,l))}}return r.add("m=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:2\na=sctp-port:5000\na=max-message-size:262144"),r.finalize()}static generateAnswer(e){const{fingerprints:t,ufrag:i,pwd:s,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a],r=new nh;r.add("v=0","o=- 1 2 IN IP4 127.0.0.1","s=-","t=0 0"),t&&t.forEach((e=>{const{hash:t,fingerprint:i,setup:s}=e;r.add(`a=fingerprint:${t} ${i}`,`a=setup:${s}`)})),i&&s&&r.add(`a=ice-ufrag:${i}`,`a=ice-pwd:${s}`),r.add("a=group:BUNDLE 0 1 2","a=extmap-allow-mixed","a=msid-semantic: WMS *");const l="stream"+o.map((e=>e.ssrc)).join("_");for(let e=0;e<o.length;e++){const t=o[e],{type:i,ssrc:s,ssrcGroups:n,payloadTypes:a,rtpExtensions:c}=t;switch(i){case"audio":r.add(`m=audio 56930 UDP/TLS/RTP/SAVPF ${a.map((e=>e.id)).join(" ")}`,"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle",`a=mid:${e}`,"a=sendrecv",hm(c)),s&&r.add(`a=msid:${l} audio${s}`),r.add("a=rtcp-mux",um(a),pm(i,s,n,l));break;case"video":r.add(`m=video 61986 UDP/TLS/RTP/SAVPF ${a.map((e=>e.id)).join(" ")}`,"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle",`a=mid:${e}`,"a=sendrecv",hm(c)),s&&r.add(`a=msid:${l} video${s}`),r.add("a=rtcp-mux","a=rtcp-rsize",um(a),pm(i,s,n,l))}}return r.add("m=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:2\na=sctp-port:5000\na=max-message-size:262144"),r.finalize()}}class rm{static generateOffer(e){const{fingerprints:t,ufrag:i,pwd:s,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a];let r="v=0\no=- 1 0 IN IP4 0.0.0.0\ns=-\nt=0 0";t&&t.forEach((e=>{const{hash:t,fingerprint:i,setup:s}=e;r+=`\na=fingerprint:${t} ${i}\na=setup:${s}`})),i&&s&&(r+=`\na=ice-ufrag:${i}\na=ice-pwd:${s}`),r+="\na=group:BUNDLE 0 1 2\na=ice-options:trickle\na=msid-semantic:WMS *";const l="stream"+o.map((e=>e.ssrc)).join("_");for(let e=0;e<o.length;e++){const t=o[e],{type:i,ssrc:s,ssrcGroups:n,payloadTypes:a,rtpExtensions:c}=t;switch(i){case"audio":r+=`\nm=audio 9 UDP/TLS/RTP/SAVPF ${a.map((e=>e.id)).join(" ")}\nc=IN IP4 0.0.0.0\na=mid:${e}\na=sendrecv`,r+=hm(c),r+="\na=rtcp-mux",r+=um(a),r+=pm(i,s,n,l);break;case"video":r+=`\nm=video 9 UDP/TLS/RTP/SAVPF ${a.map((e=>e.id)).join(" ")}\nc=IN IP4 0.0.0.0\na=mid:${e}\na=sendrecv`,r+=hm(c),r+="\na=rtcp-mux\na=rtcp-rsize",r+=um(a),r+=pm(i,s,n,l)}}return r+="m=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:2\na=sctp-port:5000\na=max-message-size:262144",r+="\n",r}static generateAnswer(e){const{fingerprints:t,ufrag:i,pwd:s,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a];let r="v=0\no=- 1 0 IN IP4 0.0.0.0\ns=-\nt=0 0";t&&t.forEach((e=>{const{hash:t,fingerprint:i,setup:s}=e;r+=`\na=fingerprint:${t} ${i}\na=setup:${s}`})),i&&s&&(r+=`\na=ice-ufrag:${i}\na=ice-pwd:${s}`),r+="\na=group:BUNDLE 0 1 2\na=ice-options:trickle\na=msid-semantic:WMS *";const l="stream"+o.map((e=>e.ssrc)).join("_");for(let e=0;e<o.length;e++){const t=o[e],{type:i,mid:s,ssrc:n,ssrcGroups:a,payloadTypes:c,dir:d,rtpExtensions:h}=t;switch(i){case"audio":r+=`\nm=audio 9 UDP/TLS/RTP/SAVPF ${c.map((e=>e.id)).join(" ")}\nc=IN IP4 0.0.0.0\na=mid:${e}\na=sendrecv`,r+=hm(h),r+="\na=rtcp-mux",r+=um(c),r+=pm(i,n,a,l);break;case"video":r+=`\nm=video 9 UDP/TLS/RTP/SAVPF ${c.map((e=>e.id)).join(" ")}\nc=IN IP4 0.0.0.0\na=mid:${e}\na=sendrecv`,r+=hm(h),r+="\na=rtcp-mux\na=rtcp-rsize",r+=um(c),r+=pm(i,n,a,l)}}return r+="m=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:2\na=sctp-port:5000\na=max-message-size:262144",r+="\n",r}}class lm{static generateOffer(e){const{fingerprints:t,ufrag:i,pwd:s,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a];if(!o.length)return"v=0\no=- 1 2 IN IP4 127.0.0.1\ns=-\nt=0 0\na=msid-semantic: WMS\n";let r="v=0\no=- 1 2 IN IP4 127.0.0.1\ns=-\nt=0 0";t&&t.forEach((e=>{const{hash:t,fingerprint:i,setup:s}=e;r+=`\na=fingerprint:${t} ${i}\na=setup:${s}`})),i&&s&&(r+=`\na=ice-ufrag:${i}\na=ice-pwd:${s}`),r+="\na=group:BUNDLE 0 1 2\na=extmap-allow-mixed\na=msid-semantic: WMS *";const l="stream"+o.map((e=>e.ssrc)).join("_");for(let e=0;e<o.length;e++){const t=o[e],{type:i,ssrc:s,ssrcGroups:n,payloadTypes:a,rtpExtensions:c}=t;switch(i){case"audio":r+=`\nm=audio 9 UDP/TLS/RTP/SAVPF ${a.map((e=>e.id)).join(" ")}\nc=IN IP4 0.0.0.0\na=rtcp:9 IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:${e}\na=sendrecv`,r+=hm(c),s&&(r+=`\na=msid:${l} audio${s}`),r+="\na=rtcp-mux",r+=um(a),r+=pm(i,s,n,l);break;case"video":r+=`\nm=video 9 UDP/TLS/RTP/SAVPF ${a.map((e=>e.id)).join(" ")}\nc=IN IP4 0.0.0.0\na=rtcp:9 IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:${e}\na=sendrecv`,r+=hm(c),s&&(r+=`\na=msid:${l} video${s}`),r+="\na=rtcp-mux\na=rtcp-rsize",r+=um(a),r+=pm(i,s,n,l)}}return r+="m=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:2\na=sctp-port:5000\na=max-message-size:262144",r+="\n",r}static generateAnswer(e){const{fingerprints:t,ufrag:i,pwd:s,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a];if(!o.length)return"v=0\no=- 1 2 IN IP4 127.0.0.1\ns=-\nt=0 0\na=msid-semantic: WMS\n";let r="v=0\no=- 1 2 IN IP4 127.0.0.1\ns=-\nt=0 0";t&&t.forEach((e=>{const{hash:t,fingerprint:i,setup:s}=e;r+=`\na=fingerprint:${t} ${i}\na=setup:${s}`})),i&&s&&(r+=`\na=ice-ufrag:${i}\na=ice-pwd:${s}`),r+="\na=group:BUNDLE 0 1 2\na=extmap-allow-mixed\na=msid-semantic: WMS *";const l="stream"+o.map((e=>e.ssrc)).join("_");for(let e=0;e<o.length;e++){const t=o[e],{type:i,ssrc:s,ssrcGroups:n,payloadTypes:a,rtpExtensions:c}=t;switch(i){case"audio":r+=`\nm=audio 9 UDP/TLS/RTP/SAVPF ${a.map((e=>e.id)).join(" ")}\nc=IN IP4 0.0.0.0\na=rtcp:9 IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:${e}\na=sendrecv`,r+=hm(c),s&&(r+=`\na=msid:${l} audio${s}`),r+="\na=rtcp-mux",r+=um(a),r+=pm(i,s,n,l);break;case"video":r+=`\nm=video 9 UDP/TLS/RTP/SAVPF ${a.map((e=>e.id)).join(" ")}\nc=IN IP4 0.0.0.0\na=rtcp:9 IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:${e}\na=sendrecv`,r+=hm(c),s&&(r+=`\na=msid:${l} video${s}`),r+="\na=rtcp-mux\na=rtcp-rsize",r+=um(a),r+=pm(i,s,n,l)}}return r+="m=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:2\na=sctp-port:5000\na=max-message-size:262144",r+="\n",r}}function cm(){return navigator.userAgent.toLowerCase().indexOf("firefox")>-1}function dm(){return navigator.userAgent.toLowerCase().indexOf("safari")>-1&&-1===navigator.userAgent.toLowerCase().indexOf("chrome")}function hm(e){let t=[];for(let i=0;i<e.length;i++){const s=e[i],{id:n,uri:a}=s;console.log("[extmap] add",n,a),t.push(`a=extmap:${n} ${a}`)}return t.join("\n")}function um(e){let t=[];console.log("[SDP] addPayloadTypes",e);for(let i=0;i<e.length;i++){const s=e[i],{id:n,name:a,clockrate:o,channels:r,feedbackTypes:l,parameters:c}=s;if(t.push(`a=rtpmap:${n} ${a}/${o}${r?"/"+r:""}`),l&&l.forEach((e=>{const{type:i,subtype:s}=e;t.push(`a=rtcp-fb:${n} ${[i,s].join(" ")}`)})),c){const e=[];Object.getOwnPropertyNames(c).forEach((t=>{e.push(`${t}=${c[t]}`)})),t.push(`a=fmtp:${n} ${e.join(";")}`)}}return t.join("\n")}function pm(e,t,i,s){let n=[];return i&&i.length>0?i.forEach((t=>{t&&t.ssrcs.length>0&&(n.push(`a=ssrc-group:${t.semantics} ${t.ssrcs.join(" ")}`),t.ssrcs.forEach((t=>{n.push(`a=ssrc:${t} cname:stream${t}`,`a=ssrc:${t} msid:${s} ${e}${t}`,`a=ssrc:${t} mslabel:${e}${t}`,`a=ssrc:${t} label:${e}${t}`)})))})):t&&n.push(`a=ssrc:${t} cname:stream${t}`,`a=ssrc:${t} msid:${s} ${e}${t}`,`a=ssrc:${t} mslabel:${e}${t}`,`a=ssrc:${t} label:${e}${t}`),n.join("\n")}class mm{static generateCandidate(e){if(!e)return null;const{sdpString:t,sdpMLineIndex:i,sdpMid:s,foundation:n,component:a,protocol:o,priority:r,address:l,type:c,relAddress:d,generation:h,tcpType:u,networkId:p,networkCost:m,username:g}=e;if(t)return{candidate:t,sdpMLineIndex:i,sdpMid:s};throw"no sdpString"}static generateOffer(e){return cm()?rm.generateOffer(e):dm()?lm.generateOffer(e):om.generateOffer(e)}static generateAnswer(e){return cm()?rm.generateAnswer(e):dm()?lm.generateAnswer(e):om.generateAnswer(e)}}var gm=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class vm extends ph{constructor(e){super(),this.log=(0,he.kg)("CALL"),this.protocol||(this.protocol={_:"phoneCallProtocol",pFlags:{udp_p2p:!0,udp_reflector:!0},min_layer:92,max_layer:92,library_versions:["4.0.0"]}),(0,x.Z)(this,e),this.createdAt=Date.now(),this.offerReceived=!1,this.offerSent=!1,this.decryptQueue=[],this.candidates=[],this.addEventListener("state",(e=>{this.log("state",Up[e]),e===Up.CLOSED&&this.cleanup()}));const t=this.streamManager=new uh(100);t.direction="sendrecv",t.types.push("screencast"),this.isOutgoing||(t.locked=!0,t.canCreateConferenceEntry=!1);let i={"@type":"MediaState",type:"input",lowBattery:!1,muted:!0,screencastState:"inactive",videoRotation:0,videoState:"inactive"};const s=this;i=new Proxy(i,{set:function(e,t,n){return e[t]=n,s.setMediaState(i),s.sendMediaState(),!0}}),this.mediaStates={input:i},this.sendMediaState=(0,Ki.Z)(this._sendMediaState.bind(this),0,!1,!0)}get connectionState(){const{_connectionState:e,connectionInstance:t}=this;if(void 0!==e)return e;if(t){const{iceConnectionState:e}=t.connection;return"closed"===e?Up.CLOSED:"connected"===e||Je.IS_SAFARI&&"completed"===e?Up.CONNECTED:Up.CONNECTING}return Up.CONNECTING}get sortIndex(){const e=this.connectionState;let t=1e13*(Up.CLOSED-e+1);return t+=2147483647e3-(e===Up.PENDING&&this.isOutgoing?0:this.createdAt),t}getVideoElement(e){if("input"===e)return this.elements.get("main");{const e=this.getMediaState("output");if(!e)return;const t="active"===e.videoState?"video":"active"===e.screencastState?"screencast":void 0;if(!t)return;const i=this.description.findEntry((e=>e.type===t));if(!i)return;return this.elements.get(""+i.recvEntry.source)}}startScreenSharingInternal(){return gm(this,void 0,void 0,(function*(){try{this.wasStartingScreen=!0,this.wasStartingVideo=!1,this.streamManager.types=["audio","screencast"],yield this.requestScreen()}catch(e){this.log.error("startScreenSharing error",e)}}))}toggleScreenSharing(){return gm(this,void 0,void 0,(function*(){return this.isSharingVideo&&(yield this.stopVideoSharing()),this.isSharingScreen?this.stopVideoSharing():this.startScreenSharingInternal()}))}startVideoSharingInternal(){return gm(this,void 0,void 0,(function*(){try{this.wasStartingScreen=!1,this.wasStartingVideo=!0,this.streamManager.types=["audio","video"],yield this.requestInputSource(!1,!0,!1)}catch(e){this.log.error("startVideoSharing error",e)}}))}stopVideoSharing(){return gm(this,void 0,void 0,(function*(){const e=this.getMediaState("input");e.videoState=e.screencastState="inactive";const{streamManager:t,description:i}=this,s=t.inputStream.getVideoTracks()[0];s&&(sh(s),t.appendToConference(i))}))}toggleVideoSharing(){return gm(this,void 0,void 0,(function*(){return this.isSharingScreen&&(yield 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&&"screencast"===e||this.wasStartingVideo&&"video"===e)}catch(e){return!1}}get isSharingVideo(){return this.isSharingVideoType("video")}get isSharingScreen(){return this.isSharingVideoType("screencast")}get isMuted(){const e=this.streamManager.inputStream.getAudioTracks()[0];return!(null==e?void 0:e.enabled)}get isClosing(){const{connectionState:e}=this;return e===Up.CLOSING||e===Up.CLOSED}get description(){var e;return null===(e=this.connectionInstance)||void 0===e?void 0:e.description}setHangUpTimeout(e,t){this.clearHangUpTimeout(),this.hangUpTimeout=er.Z.setTimeout((()=>{this.hangUpTimeout=void 0,this.hangUp(t)}),e)}clearHangUpTimeout(){void 0!==this.hangUpTimeout&&(clearTimeout(this.hangUpTimeout),this.hangUpTimeout=void 0)}setPhoneCall(e){this.call=e;const{id:t}=e;if(this.id!==t){const e=this.id;this.id=t,this.dispatchEvent("id",t,e)}}acceptCall(){var e;return gm(this,void 0,void 0,(function*(){const t=null===(e=(yield Promise.all(this.dispatchResultableEvent("acceptCallOverride")))[0])||void 0===e||e;if(this.isClosing||!t)return;this.overrideConnectionState(Up.EXCHANGING_KEYS);const i=this.call;this.requestInputSource(!0,!!i.pFlags.video,!1);const s=i.g_a_hash;this.managers.appCallsManager.generateDh().then((e=>gm(this,void 0,void 0,(function*(){return this.dh={g_a_hash:s,b:e.a,g_b:e.g_a,g_b_hash:e.g_a_hash,p:e.p},this.managers.apiManager.invokeApi("phone.acceptCall",{peer:yield this.managers.appCallsManager.getCallInput(this.id),protocol:this.protocol,g_b:this.dh.g_b})})))).then((e=>gm(this,void 0,void 0,(function*(){yield this.managers.appCallsManager.savePhonePhoneCall(e)})))).catch((e=>{this.log.error("accept call error",e),this.hangUp("phoneCallDiscardReasonHangup")}))}))}joinCall(){this.log("joinCall"),this.getEmojisFingerprint(),this.overrideConnectionState();const{isOutgoing:e,encryptionKey:t,streamManager:i}=this,s=function(e){const t=[];return e.connections.forEach((e=>{switch(e._){case"phoneConnectionWebrtc":{const{ip:i,ipv6:s,port:n,username:a,password:o}=e,r=[];e.pFlags.turn?(i&&r.push(`turn:${i}:${n}`),s&&r.push(`turn:[${s}]:${n}`)):e.pFlags.stun&&(i&&r.push(`stun:${i}:${n}`),s&&r.push(`stun:[${s}]:${n}`)),r.length>0&&t.push({urls:r,username:a,credential:o});break}}})),{iceServers:t,iceTransportPolicy:e.pFlags.p2p_allowed?"all":"relay"}}(this.call);if(this.log("joinCall configuration",s),!s)return;const n=this.connectionInstance=new $p({call:this,streamManager:i,log:this.log.bindPrefix("connection")}),a=n.createPeerConnection(s);a.addEventListener("iceconnectionstatechange",(()=>{const e=this.connectionState;void 0===this.connectedAt&&e===Up.CONNECTED&&(this.connectedAt=Date.now()),this.dispatchEvent("state",e)})),a.addEventListener("negotiationneeded",(()=>{n.negotiate()})),a.addEventListener("icecandidate",(e=>{const{candidate:t}=e;a.log("onicecandidate",t),(null==t?void 0:t.candidate)&&this.sendIceCandidate(t)})),a.addEventListener("track",(e=>{const{track:t}=e;a.log("ontrack",t),this.onTrack(e)})),n.createDescription(),this.encryptor=new am(e,t),this.decryptor=new am(!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",(e=>{this.applyDataChannelData(JSON.parse(e.data))})),e.addEventListener("open",(()=>{this.sendMediaState()}))}applyDataChannelData(e){"MediaState"===e["@type"]?(e.type="output",this.log("got output media state",e),this.setMediaState(e)):this.log.error("unknown data channel data:",e)}_sendMediaState(){const{connectionInstance:e}=this;if(!e)return;const t=Object.assign({},this.getMediaState("input"));delete t.type,this.log("sendMediaState",t),e.sendDataChannelData(t)}sendCallSignalingData(e){return gm(this,void 0,void 0,(function*(){const t=JSON.stringify(e),i=(new TextEncoder).encode(t),{bytes:s}=yield this.encryptor.encryptRawPacket(i);this.log("sendCallSignalingData",this.id,t),yield this.managers.apiManager.invokeApi("phone.sendSignalingData",{peer:yield this.managers.appCallsManager.getCallInput(this.id),data:s})}))}sendIceCandidate(e){this.log("sendIceCandidate",e);const{candidate:t,sdpMLineIndex:i}=e;if(0!==i)return;const s=function(e){if(!e||!e.startsWith("candidate:"))return;const t=e;e=e.substr("candidate:".length);const[i,s,n,a,o,r,...l]=e.split(" "),c={sdpString:t,foundation:i,component:s,protocol:n,priority:a,address:{ip:o,port:r}};for(let e=0;e<l.length;e+=2)switch(l[e]){case"typ":c.type=l[e+1];break;case"raddr":c.relAddress||(c.relAddress={}),c.relAddress.ip=l[e+1];break;case"rport":c.relAddress||(c.relAddress={}),c.relAddress.port=l[e+1];break;case"generation":c.generation=l[e+1];break;case"tcptype":c.tcpType=l[e+1];break;case"network-id":c.networkId=l[e+1];break;case"network-cost":c.networkCost=l[e+1];break;case"ufrag":c.username=l[e+1]}return c}(t);this.sendCallSignalingData({"@type":"Candidates",candidates:[s]})}confirmCall(){return gm(this,void 0,void 0,(function*(){const{protocol:e,id:t,call:i}=this,s=this.dh;this.overrideConnectionState(Up.EXCHANGING_KEYS);const{key:n,key_fingerprint:a}=yield this.managers.appCallsManager.computeKey(i.g_b,s.a,s.p),o=yield this.managers.apiManager.invokeApi("phone.confirmCall",{peer:yield this.managers.appCallsManager.getCallInput(t),protocol:e,g_a:s.g_a,key_fingerprint:a});this.encryptionKey=n,yield this.managers.appCallsManager.savePhonePhoneCall(o),this.joinCall()}))}getEmojisFingerprint(){return this.emojisFingerprint?this.emojisFingerprint:this.getEmojisFingerprintPromise?this.getEmojisFingerprintPromise:this.getEmojisFingerprintPromise=Gi.Z.invokeCrypto("get-emojis-fingerprint",this.encryptionKey,this.dh.g_a).then((e=>(this.getEmojisFingerprintPromise=void 0,this.emojisFingerprint=e.map((e=>(0,pi.zu)(e))))))}unlockStreamManager(){this.connectionInstance.streamManager.locked=!1,this.connectionInstance.appendStreamToConference()}doTheMagic(){return gm(this,void 0,void 0,(function*(){this.connectionInstance.appendStreamToConference();const e=this.connectionInstance.connection;let t=yield e.createAnswer();this.log("[sdp] local",t.type,t.sdp),yield e.setLocalDescription(t),e.getTransceivers().filter((e=>"recvonly"===e.direction)).forEach((e=>{const t=this.connectionInstance.description.getEntryByMid(e.mid);t.transceiver=t.recvEntry.transceiver=e,e.direction="sendrecv"}));const i=this.description,s=i.entries.map((e=>e.mid)),n={type:"offer",sdp:i.generateSdp({bundle:s,entries:i.entries.filter((e=>s.includes(e.mid))),isAnswer:!0})};yield e.setRemoteDescription(n),t=yield e.createAnswer(),yield e.setLocalDescription(t);const a=Wp(Su(t.sdp));this.log("[InitialSetup] send 1"),this.sendCallSignalingData(a),this.unlockStreamManager()}))}overrideConnectionState(e){this._connectionState=e,this.dispatchEvent("state",this.connectionState)}get duration(){return void 0!==this.connectedAt?(Date.now()-this.connectedAt)/1e3|0:0}onInputStream(e){super.onInputStream(e);const t=e.getVideoTracks()[0];if(t){const e=this.getMediaState("input");this.wasStartingScreen||this.wasStartingVideo||(this.wasStartingVideo=!0),this.isSharingVideo?e.videoState="active":this.isSharingScreen&&(e.screencastState="active"),t.addEventListener("ended",(()=>{this.stopVideoSharing()}),{once:!0})}e.getAudioTracks().length&&this.onMutedChange()}onMutedChange(){const e=this.isMuted;this.dispatchEvent("muted",e),this.getMediaState("input").muted=e}toggleMuted(){return this.requestAudioSource(!0).then((()=>{this.setMuted(),this.onMutedChange()}))}hangUp(e,t){return gm(this,void 0,void 0,(function*(){if(!this.isClosing&&(this.discardReason=e,this.log("hangUp",e),this.overrideConnectionState(Up.CLOSED),this.connectionInstance&&this.connectionInstance.closeConnectionAndStream(!0),e&&!t)){let t=!1;for(const e in this.mediaStates){const i=this.mediaStates[e];t="active"===i.videoState||"active"===i.screencastState||t}yield this.managers.appCallsManager.discardCall(this.id,this.duration,e,t)}}))}performCodec(e){const t=e.payloadTypes.map((e=>Object.assign(Object.assign({},e),{"rtcp-fbs":e.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((e=>{const t=e.payloadTypes,i=t.findIndex((e=>"VP8"===e.name)),s=t[i],n=t.findIndex((e=>{var t;return+(null===(t=e.parameters)||void 0===t?void 0:t.apt)===s.id}));e.payloadTypes=[t[i],t[n]]}))}applyCallSignalingData(e){return gm(this,void 0,void 0,(function*(){this.log("applyCallSignalingData",this,e);const{connection:t,description:i}=this.connectionInstance;switch(e["@type"]){case"InitialSetup":{this.log("[sdp] InitialSetup",e),this.filterNotVP8(e),this.setDataToDescription(e);const s=e=>e.map((e=>({_:"groupCallParticipantVideoSourceGroup",semantics:e.semantics,sources:e.ssrcs.map((e=>+e))})));[gh("audio",+e.audio.ssrc),e.video?gh("video",s(e.video.ssrcGroups)):void 0,e.screencast?gh("screencast",s(e.screencast.ssrcGroups)):void 0].filter(Boolean).forEach((e=>{let t=i.getEntryBySource(e.source);if(t)return;const s=i.findFreeSendRecvEntry(e.type,!1);t=new mh(s.mid,e.type),t.setDirection("sendrecv"),s.recvEntry=t,i.setEntrySource(t,e.sourceGroups||e.source)})),this.createDataChannelEntry();const n=this.offerSent;this.offerSent=!1;const a=i.entries.map((e=>e.mid)),o={type:n?"answer":"offer",sdp:i.generateSdp({bundle:a,entries:i.entries.filter((e=>a.includes(e.mid))),isAnswer:!n})};this.log("[sdp] remote",o.sdp),yield t.setRemoteDescription(o),yield this.tryToReleaseCandidates(),n||(yield this.doTheMagic());break}case"Candidates":for(const t of e.candidates){const e=mm.generateCandidate(t);e.sdpMLineIndex=0;const i=new RTCIceCandidate(e);this.candidates.push(i)}yield this.tryToReleaseCandidates();break;default:this.log.error("unrecognized signaling data",e)}}))}tryToReleaseCandidates(){return gm(this,void 0,void 0,(function*(){const{connectionInstance:e}=this;if(!e)return;const{connection:t}=e;if(t.remoteDescription){const e=this.candidates.map((e=>this.addIceCandidate(t,e)));this.candidates.length=0,yield Promise.all(e)}else this.log("[candidates] postpone")}))}addIceCandidate(e,t){return gm(this,void 0,void 0,(function*(){this.log("[candidate] start",t);try{yield e.addIceCandidate(t),this.log("[candidate] add",t)}catch(e){this.log.error("[candidate] error",t,e)}}))}processDecryptQueue(){return gm(this,void 0,void 0,(function*(){const{encryptor:e}=this;if(!e)return void this.log.warn("got encrypted signaling data before the encryption key");if(!this.decryptQueue.length)return;const t=this.decryptQueue.slice();this.decryptQueue.length=0;for(const i of t){const t=yield e.decryptRawPacket(i);if(!t)continue;const s=(new TextDecoder).decode(t);try{const e=JSON.parse(s);this.log("[update] updateNewCallSignalingData",e),this.applyCallSignalingData(e)}catch(e){this.log.error("wrong signaling data",s),this.hangUp("phoneCallDiscardReasonDisconnect"),em.dispatchEvent("incompatible",this.interlocutorUserId)}}}))}onUpdatePhoneCallSignalingData(e){this.decryptQueue.push(e),this.processDecryptQueue()}}class fm{constructor(e){this.managers=e,this.onState=()=>{this.updateInstance(this.instance)};const t=this.listenerSetter=new I.Z;t.add(em)("instance",(({instance:e})=>{this.instance||this.updateInstance(e)})),t.add(em)("accepting",(e=>{this.instance!==e&&this.updateInstance(e)})),t.add(Fu)("instance",(e=>{this.updateInstance(e)})),t.add(s.Z)("group_call_update",(e=>{const t=Fu.groupCall;(null==t?void 0:t.id)===e.id&&this.updateInstance(t)})),t.add(uh.ANALYSER_LISTENER)("amplitude",(({amplitudes:e,type:t})=>{const{weave:i}=this;if(!e.length||!i)return;let s=0;for(let t=0;t<e.length;++t){const{type:i,value:n}=e[t];s=n>s?n:s}i.setAmplitude(s)}))}clearCurrentInstance(){this.instance&&(this.center.textContent="",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=this.instance!==e;t&&(this.clearCurrentInstance(),this.instance=e,this.instanceListenerSetter=new I.Z,this.instanceListenerSetter.add(e)("state",this.onState),e instanceof Tu?this.currentDescription=this.groupCallDescription:(this.currentDescription=this.callDescription,this.instanceListenerSetter.add(e)("muted",this.onState)),this.container.classList.toggle("is-call",!(e instanceof Tu)));const i=this.instance.isMuted,s=e instanceof Tu?e.state:function(e,t){switch(e){case Up.CLOSING:case Up.CLOSED:return Pu.CLOSED;case Up.CONNECTED:return t?Pu.MUTED:Pu.UNMUTED;default:return Pu.CONNECTING}}(e.connectionState,i),{weave:n}=this;n.componentDidMount();const a=s===Pu.CLOSED;(!document.body.classList.contains("is-calling")||t||a)&&(a&&n.setAmplitude(0),Re(document.body,"is-calling",!a,250,a?()=>{n.componentWillUnmount(),this.clearCurrentInstance()}:void 0)),a||(n.setCurrentState(s,!0),this.setTitle(e),this.setDescription(e),this.groupCallMicrophoneIconMini.setState(!i))}setDescription(e){return this.currentDescription.update(e)}setTitle(e){if(e instanceof Tu)return this.groupCallTitle.update(e);(0,g.Z)(this.center,new Ot({peerId:e.interlocutorUserId.toPeerId()}).element)}construct(){const{listenerSetter:e}=this,t=this.container=document.createElement("div");t.classList.add("sidebar-header","topbar-call-container");const i=document.createElement("div");i.classList.add("topbar-call-left");const s=this.groupCallMicrophoneIconMini=new Hp,o=E();o.append(s.container),i.append(o);const r=(0,mt.Z)((()=>{this.instance.toggleMuted()}),600,!0);(0,n.fc)(o,(e=>{(0,a.Z)(e),r()}),{listenerSetter:e});const l=this.center=document.createElement("div");l.classList.add("topbar-call-center"),this.groupCallTitle=new Cp(l),this.groupCallDescription=new Sp(i),this.callDescription=new Op(i);const c=document.createElement("div");c.classList.add("topbar-call-right");const d=E("endcall_filled");c.append(d),(0,n.fc)(d,(e=>{(0,a.Z)(e);const{instance:t}=this;t&&(t instanceof Tu?t.hangUp():t.hangUp("phoneCallDiscardReasonHangup"))}),{listenerSetter:e}),(0,n.fc)(t,(()=>{if(this.instance instanceof Tu){if(A.Z.getPopups(Bp).length)return;(new Bp).show()}else if(this.instance instanceof vm){if(A.Z.getPopups(Kp).find((e=>e.getCallInstance()===this.instance)))return;new Kp(this.instance).show()}}),{listenerSetter:e}),t.append(i,l,c);const h=this.weave=new Xu,u=h.render("topbar-call-weave");t.prepend(u),document.getElementById("column-center").prepend(t),h.componentDidMount()}}var ym=i(6009),bm=i(6702),wm=i(1722),Sm=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const Cm=new class{constructor(){this.notificationsShown={},this.notificationIndex=0,this.notificationsCount=0,this.soundsPlayed={},this.vibrateSupport=Qn.Z,this.faviconEl=document.head.querySelector('link[rel="icon"]'),this.titleBackup=document.title,this.titleChanged=!1,this.stopped=!1,this.settings={},this.pushInited=!1,this.updateLocalSettings=()=>{const e=["notify_nodesktop","notify_volume","notify_novibrate","notify_nopreview","notify_nopush"].map((()=>{}));Promise.all(e).then((e=>{if(this.settings.nodesktop=e[0],this.settings.volume=void 0===e[1]?.5:e[1],this.settings.novibrate=e[2],this.settings.nopreview=e[3],this.settings.nopush=e[4],this.pushInited){const e=!this.settings.nopush&&!this.settings.nodesktop&&bm.default.isAvailable||!1;e!==(!1!==this.registeredDevice)&&(e?bm.default.subscribe():bm.default.unsubscribe())}bm.default.setSettings(this.settings)})),Gi.Z.getState().then((e=>{this.settings.nosound=!e.settings.notifications.sound}))},this.requestPermission=()=>{Notification.requestPermission(),window.removeEventListener("click",this.requestPermission)}}construct(e){this.managers=e,navigator.vibrate=navigator.vibrate||navigator.mozVibrate||navigator.webkitVibrate,this.setAppBadge=navigator.setAppBadge&&navigator.setAppBadge.bind(navigator),this.setAppBadge&&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=(0,Oe.Z)(),qu.Z.addEventListener("deactivated",(()=>{this.stop()})),qu.Z.addEventListener("activated",(()=>{this.stopped&&this.start()})),dl.Z.addEventListener("change",(e=>{this.stopped||(e||this.clear(),this.toggleToggler())})),s.Z.addEventListener("notification_reset",(e=>{this.soundReset(e)})),s.Z.addEventListener("notification_cancel",(e=>{this.cancel(e)})),this.setAppBadge&&s.Z.addEventListener("folder_unread",(e=>{0===e.id&&this.setAppBadge(e.unreadUnmutedPeerIds.size)})),bm.default.addEventListener("push_init",(e=>{this.pushInited=!0,this.settings.nodesktop||this.settings.nopush?this.unregisterDevice(e):e?this.registerDevice(e):bm.default.subscribe()})),bm.default.addEventListener("push_subscribe",(e=>{this.registerDevice(e)})),bm.default.addEventListener("push_unsubscribe",(e=>{this.unregisterDevice(e)})),s.Z.addEventListener("dialogs_multiupdate",(()=>{this.topMessagesDeferred.resolve()}),{once:!0}),bm.default.addEventListener("push_notification_click",(e=>{if("push_settings"===e.action)return;if("mute1d"===e.action)return void this.managers.apiManager.invokeApi("account.updateDeviceLocked",{period:86400}).then((()=>{}));const t=e.custom&&e.custom.peerId.toPeerId();console.log("click",e,t),t&&this.topMessagesDeferred.then((()=>Sm(this,void 0,void 0,(function*(){e.custom.channel_id&&!(yield this.managers.appChatsManager.hasChat(e.custom.channel_id))||t.isUser()&&!(yield this.managers.appUsersManager.hasUser(t))||_m.setInnerPeer({peerId:t,lastMsgId:(0,cl.Z)(+e.custom.msg_id)})}))))}))}buildNotification({message:e,fwdCount:t,peerReaction:i,peerTypeNotifySettings:s}){return Sm(this,void 0,void 0,(function*(){const n=e.peerId,a=n.isAnyChat(),o={},r=yield this.managers.appPeersManager.getPeerString(n);let l;if(s.show_previews){if("message"===e._&&e.fwd_from&&t>1)l=v.ZP.format("Notifications.Forwarded",!0,[t]);else if(l=yield Aa(e,void 0,void 0,!0),i){const e="Notification.Contact.Reacted",t=[(0,dn.Z)(i.reaction),l];l=v.ZP.format(e,!0,t)}}else l=v.ZP.format("Notifications.New",!0);i&&(o.noIncrement=!0,o.silent=!0);const c=i?(0,es.Z)(i.peer_id):e.fromId;o.title=yield(0,Rt.Z)(n,!0,void 0,void 0,this.managers),a&&c!==e.peerId&&(o.title=(yield(0,Rt.Z)(c,!0,void 0,void 0,this.managers))+" @ "+o.title),o.title=(0,Xt.Z)(o.title),o.onclick=()=>{_m.setInnerPeer({peerId:n,lastMsgId:e.mid})},o.message=l,o.key="msg"+e.mid,o.tag=r,o.silent=!0;const d=yield this.managers.appPeersManager.getPeerPhoto(n);d?this.managers.appAvatarsManager.loadAvatar(n,d,"photo_small").then((t=>{(e.pFlags.unread||i)&&(o.image=t,this.notify(o))})):this.notify(o)}))}toggleToggler(e=dl.Z.isIdle){if(Je.IS_MOBILE)return;const t=e=>{this.titleChanged=!1,document.title=this.titleBackup,this.setFavicon()};window.clearInterval(this.titleInterval),this.titleInterval=0,e?this.titleInterval=window.setInterval((()=>{const e=this.notificationsCount;if(e)if(this.titleChanged)t();else{this.titleChanged=!0,document.title=v.ZP.format("Notifications.Count",!0,[e]);const t=document.createElement("canvas");t.width=32*window.devicePixelRatio,t.height=t.width;const i=t.getContext("2d");i.beginPath(),i.arc(t.width/2,t.height/2,t.width/2,0,2*Math.PI,!1),i.fillStyle="#3390ec",i.fill();let s=24,n=""+e;e<10?s=22:e<100?s=20:(n="99+",s=16),s*=window.devicePixelRatio,i.font=`700 ${s}px ${yt}`,i.textBaseline="middle",i.textAlign="center",i.fillStyle="white",i.fillText(n,t.width/2,.5625*t.height),this.setFavicon(t.toDataURL())}else this.toggleToggler(!1)}),1e3):t()}setFavicon(e="assets/img/favicon.ico"){if(this.prevFavicon===e)return;const t=this.faviconEl.cloneNode();t.href=e,this.faviconEl.parentNode.replaceChild(t,this.faviconEl),this.faviconEl=t,this.prevFavicon=e}notify(e){if(this.stopped)return;e.image||(e.image="assets/img/logo_filled_rounded.png"),e.noIncrement||++this.notificationsCount,this.titleInterval||this.toggleToggler();const t=++this.notificationIndex,i=e.key||"k"+t;this.notificationsShown[i]=!0;const s=(0,wl.Z)();if(this.settings.volume>0&&!this.settings.nosound&&(this.testSound(this.settings.volume),this.soundsPlayed[e.tag]=s),!this.notificationsUiSupport||"Notification"in window&&"granted"!==Notification.permission)return!1;if(this.settings.nodesktop)return this.vibrateSupport&&!this.settings.novibrate?void navigator.vibrate([200,100,200]):void 0;let n;if("Notification"in window){try{if(e.tag)for(const t in this.notificationsShown){const i=this.notificationsShown[t];"boolean"!=typeof i&&i.tag===e.tag&&(i.hidden=!0)}n=new Notification(e.title,{icon:e.image||"",body:e.message||"",tag:e.tag||"",silent:e.silent||!1})}catch(e){return this.notificationsUiSupport=!1,void bm.default.setLocalNotificationsDisabled()}n.onclick=()=>{n.close(),wm.Z.focus(),this.clear(),e.onclick&&e.onclick()},n.onclose=()=>{n.hidden||(delete this.notificationsShown[i],this.clear())},n.show&&n.show(),this.notificationsShown[i]=n,Je.IS_MOBILE||setTimeout((()=>{this.hide(i)}),8e3)}}getLocalSettings(){return this.settings}hide(e){const t=this.notificationsShown[e];if(t&&"boolean"!=typeof t)try{t.close&&(t.hidden=!0,t.close())}catch(e){}}soundReset(e){delete this.soundsPlayed[e]}testSound(e){const t=(0,wl.Z)();if(this.nextSoundAt&&t<this.nextSoundAt&&this.prevSoundVolume===e)return;this.nextSoundAt=t+1e3,this.prevSoundVolume=e;const i="assets/audio/notification.mp3",s=document.createElement("audio");s.autoplay=!0,s.setAttribute("mozaudiochannel","notification"),s.volume=e,s.innerHTML=`\n <source src="${i}" type="audio/mpeg" />\n <embed hidden="true" autostart="true" loop="false" volume="${100*e}" src="${i}" />\n `,this.notifySoundEl.append(s),s.addEventListener("ended",(()=>{s.remove()}),{once:!0})}cancel(e){const t=this.notificationsShown[e];if(t){this.notificationsCount>0&&--this.notificationsCount;try{"boolean"!=typeof t&&t.close&&(t.hidden=!0,t.close())}catch(e){}delete this.notificationsShown[e]}}clear(){for(const e in this.notificationsShown){const t=this.notificationsShown[e];try{"boolean"!=typeof t&&t.close&&t.close()}catch(e){}}this.notificationsShown={},this.notificationsCount=0,bm.default.hidePushNotifications()}start(){if(this.updateLocalSettings(),s.Z.addEventListener("settings_updated",this.updateLocalSettings),bm.default.start(),!this.notificationsUiSupport)return!1;"Notification"in window&&"granted"!==Notification.permission&&"denied"!==Notification.permission&&window.addEventListener("click",this.requestPermission);try{"onbeforeunload"in window&&window.addEventListener("beforeunload",this.clear)}catch(e){}}stop(){this.clear(),window.clearInterval(this.titleInterval),this.titleInterval=0,this.setFavicon(),this.stopped=!0}registerDevice(e){if(this.registeredDevice&&(0,gs.Z)(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.registeredDevice=e}),(e=>{e.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}),(e=>{e.handled=!0}))}};R.GO&&(R.GO.uiNotificationsManager=Cm);const Lm=Cm;var Im=i(5936),Mm=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};function Em(e,t=!1){return Mm(this,void 0,void 0,(function*(){const i=[],s=(e,n)=>Mm(this,void 0,void 0,(function*(){if(e.isDirectory){const t=e.createReader();yield new Promise(((e,i)=>{t.readEntries((t=>Mm(this,void 0,void 0,(function*(){for(const e of t)yield s(e,n);e()}))))}))}else if(e)if(t)i.push(e.type);else{const t=n.getAsFile(),s=e instanceof File?e:e instanceof DataTransferItem?e.getAsFile():yield new Promise(((i,s)=>e.file(i,(e=>i(t)))));if(!s)return;i.push(s)}}));if(e instanceof DragEvent&&e.dataTransfer.files&&!e.dataTransfer.items)for(let s=0;s<e.dataTransfer.files.length;s++){const n=e.dataTransfer.files[s];i.push(t?n.type:n)}else{const i=(e.dataTransfer||e.clipboardData||e.originalEvent.clipboardData).items,n=[];for(let e=0;e<i.length;++e){const a=i[e];if("file"===a.kind){const e=(t?a:a.webkitGetAsEntry())||a.getAsFile();n.push(s(e,a))}}yield Promise.all(n)}return i}))}var Pm=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const km="chat";class Tm extends L.Z{constructor(){super(...arguments),this.columnEl=document.getElementById("column-center"),this.offline=!1,this.updateStatusInterval=0,this.setPeerPromise=null,this.tabId=-1,this.chats=[],this.cacheStorage=new Im.Z("cachedFiles"),this.onHashChange=e=>{const t=location.hash;e||C.Z.replaceState();const i=t.split("?"),s=this.parseUriParams(t,i);if(this.log("hashchange",t,i[0],s),t)if(s.tgaddr){const{onclick:e}=(0,Pa.Z)(s.tgaddr);if(e){const t=document.createElement("a");t.href=s.tgaddr,window[e](t)}}else{"#/im"!==i[0]&&(s.p=i[0].slice(1));{const e=s.p,t=void 0!==s.post?(0,cl.Z)(+s.post):void 0;"@"===e[0]?this.openUsername({userName:e,lastMsgId:t}):this.setInnerPeer({peerId:t?e.toPeerId(!0):e.toPeerId(),lastMsgId:t})}}},this.setSettings=()=>{document.documentElement.style.setProperty("--messages-text-size",s.Z.settings.messagesTextSize+"px"),document.body.classList.toggle("animation-level-0",!s.Z.settings.animationsEnabled),document.body.classList.toggle("animation-level-1",!1),document.body.classList.toggle("animation-level-2",s.Z.settings.animationsEnabled),this.chatsSelectTabDebounced=(0,Ki.Z)((()=>{const e=this.chat.topbar;e.pinnedMessage&&e.pinnedMessage.setCorrectIndex(0),this.managers.apiFileManager.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)}),s.Z.settings.animationsEnabled?250:0,!1,!0),hi.Z.setLoop(s.Z.settings.stickers.loop),p.Z.checkAnimations(!1);for(const e of this.chats)e.setAutoDownloadMedia();v.ZP.setTimeFormat(s.Z.settings.timeFormat),this.toggleChatGradientAnimation(this.chat)},this.onDocumentPaste=(e,t)=>Pm(this,void 0,void 0,(function*(){const i=Kc();if(e instanceof DragEvent){const t=e.dataTransfer.types;(t.contains?t.contains("Files"):t.indexOf("Files")>=0)&&(0,a.Z)(e)}const s=yield Em(e);if(((yield this.canDrag())||i)&&s.length){if(i)return void i.addFiles(s);const e=this.chat.input;e.willAttachType=t||(o.Z.has(s[0].type)?"media":"document"),A.Z.createPopup(Wc,this.chat,s,e.willAttachType)}}))}get myId(){return s.Z.myId}get chat(){return this.chats[this.chats.length-1]}construct(e){this.managers=e;const{apiUpdatesManager:t}=e;t.attach(v.ZP.lastRequestedLangCode),vt.Z.construct(e),Lm.construct(e),Lm.start(),this.log=(0,he.kg)("IM",he.v9.Log|he.v9.Warn|he.v9.Debug|he.v9.Error),this.backgroundPromises={},Qo.h.settings.themes.forEach((e=>{if(e.background.slug){const t="assets/img/"+e.background.slug+".svg"+(Je.IS_FIREFOX?"?1":"");this.backgroundPromises[e.background.slug]=Promise.resolve(t)}})),this.selectTab(0),dl.Z.addEventListener("change",(e=>{this.offline=e,this.updateStatus(),e?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.emojiAnimationContainer=document.createElement("div"),this.emojiAnimationContainer.classList.add("emoji-animation-container"),this.appendEmojiAnimationContainer(d.Z.activeScreen),this.columnEl.append(this.chatsContainer),this.createNewChat(),this.chatsSelectTab(this.chat.container),C.Z.onHashChange=this.onHashChange,this.setSettings(),s.Z.addEventListener("settings_updated",this.setSettings);const i=e=>{document.body.classList.toggle("is-premium",e)};s.Z.addEventListener("premium_toggle",i),i(s.Z.premium),(0,He.ZP)((()=>{p.Z.setOnlyOnePlayableGroup("lock"),p.Z.checkAnimations(!0)}),(()=>{p.Z.setOnlyOnePlayableGroup(),p.Z.checkAnimations(!1)})),Je.IS_FIREFOX&&Gi.Z.oldVersion&&-1===(0,ym.Z)(Gi.Z.oldVersion,"1.4.3")?this.deleteFilesIterative((e=>"image/svg+xml"===e.headers.get("Content-Type"))).then((()=>{this.applyCurrentTheme()})):this.applyCurrentTheme(),d.Z.addEventListener("changeScreen",((e,t)=>{document.body.classList.contains(Dr)&&document.body.classList.contains(tn)&&nn.toggleSidebar(!1),this.appendEmojiAnimationContainer(t)})),d.Z.addEventListener("resize",(()=>{const e=this.chatsContainer.getBoundingClientRect();Uu.resizeInstances(e.width,e.height).then((()=>{}))})),this.addEventListener("peer_changing",(e=>{this.saveChatPosition(e)})),s.Z.addEventListener("theme_change",(()=>{this.applyCurrentTheme()})),s.Z.addEventListener("choosing_sticker",(e=>{this.setChoosingStickerTyping(!e)})),s.Z.addEventListener("peer_typings",(({peerId:e,typings:t})=>{var i;const s=this.chat;if(!s||s.peerId!==e||Un.Z.isOverlayActive||d.Z.activeScreen===d._.mobile&&1!==this.tabId)return;const a=t.find((e=>"sendMessageEmojiInteraction"===e.action._));if("sendMessageEmojiInteraction"===(null===(i=null==a?void 0:a.action)||void 0===i?void 0:i._)){const t=a.action,i=s.bubbles.bubbles[(0,cl.Z)(a.action.msg_id)];if(i&&i.classList.contains("emoji-big")&&i.classList.contains("sticker")&&En(i,s.bubbles.scrollable.container)){const s=i.querySelector(".media-sticker-wrapper:not(.bubble-hover-reaction-sticker):not(.reaction-sticker)");JSON.parse(t.interaction.data).a.forEach((e=>{setTimeout((()=>{(0,n.tH)(s)}),1e3*e.t)})),this.managers.appMessagesManager.setTyping(e,{_:"sendMessageEmojiInteractionSeen",emoticon:t.emoticon})}}}));const o=e=>{const t="version"===e,i=new A.Z("popup-instance-deactivated",{overlayClosable:!0}),s=document.createElement("div");s.classList.add("instance-deactivated-container"),i.container.replaceWith(s);const n=document.createElement("div");n.classList.add("header"),n.append((0,v.ag)(t?"Deactivated.Version.Title":"Deactivated.Title"));const a=document.createElement("div");a.classList.add("subtitle"),a.append((0,v.ag)(t?"Deactivated.Version.Subtitle":"Deactivated.Subtitle")),s.append(n,a),document.body.classList.add("deactivated");const o=t?()=>{wm.Z.reload()}:()=>{document.body.classList.add("deactivated-backwards"),qu.Z.activateInstance(),setTimeout((()=>{document.body.classList.remove("deactivated","deactivated-backwards")}),333)};i.addEventListener("close",o),i.show()};qu.Z.addEventListener("deactivated",o),qu.Z.deactivatedReason&&o(qu.Z.deactivatedReason),this.addEventListener("chat_changing",(({to:e})=>{this.toggleChatGradientAnimation(e)})),s.Z.addEventListener("service_notification",(e=>{In({button:{langKey:"OK",isCancel:!0},description:(0,ii.Z)(e.message)})})),s.Z.addEventListener("payment_sent",(({peerId:e,mid:t,receiptMessage:i})=>Pm(this,void 0,void 0,(function*(){const s=yield this.managers.appMessagesManager.getMessageByPeer(e,t);if(!s)return;const n=i.action;Li({langPackKey:"PaymentInfoHint",langPackArguments:[Ea(n.total_amount,n.currency),(0,Zt.Z)(s.media.title)]})})))),window.onSpoilerClick=e=>{const t=(0,r.Z)(e.target,"spoiler"),i=(0,r.Z)(t,"message")||t.parentElement,s="is-spoiler-visible",o=i.classList.contains(s);o||((0,a.Z)(e),"click"!==n.pf&&window.addEventListener("click",a.Z,{capture:!0,once:!0}));const l=o?0:2;l&&i.classList.add("will-change");const c=i.dataset.spoilerTimeout;null!==c&&(clearTimeout(+c),delete i.dataset.spoilerTimeout),Re(i,s,!0,200,(()=>{i.dataset.spoilerTimeout=""+window.setTimeout((()=>{Re(i,s,!1,200,(()=>{i.classList.remove("will-change"),delete i.dataset.spoilerTimeout}))}),5e3)}),l)},s.Z.addEventListener("sticker_updated",(({type:e,faved:t})=>{"faved"===e?Li({langPackKey:t?"AddedToFavorites":"RemovedFromFavorites"}):t||Li({langPackKey:"RemovedFromRecent"})})),Gi.Z.addEventListener("notificationBuild",(e=>{(this.chat.peerId!==e.message.peerId||dl.Z.isIdle)&&Lm.buildNotification(e)})),this.addEventListener("peer_changed",(e=>Pm(this,void 0,void 0,(function*(){document.body.classList.toggle("has-chat",!!e),this.emojiAnimationContainer.textContent="",this.overrideHash(e),Gi.Z.updateTabState("chatPeerIds",this.chats.map((e=>e.peerId)).filter(Boolean))})))),$u.Z.setToCache("chatPositions",{}),(nl.Z||Wd.Z)&&(this.topbarCall=new fm(e)),nl.Z&&(em.addEventListener("instance",(({instance:e})=>{const t=new Kp(e);e.addEventListener("acceptCallOverride",(()=>this.discardCurrentCall(e.interlocutorUserId.toPeerId(),void 0,e).then((()=>(em.dispatchEvent("accepting",e),!0))).catch((()=>!1)))),t.addEventListener("close",(()=>{const t=em.currentCall;t&&t!==e&&!e.wasTryingToJoin&&e.hangUp("phoneCallDiscardReasonBusy")}),{once:!0}),t.show()})),em.addEventListener("incompatible",(e=>{Li({langPackKey:"VoipPeerIncompatible",langPackArguments:[new Ot({peerId:e.toPeerId()}).element]})}))),qu.Z.activateInstance();const l=()=>{Qu.default.setAuthorized(!0)};setInterval(l,U),l(),this.addAnchorListener({name:"showMaskedAlert",callback:(e,t)=>{const i=t.href,s=t.cloneNode(!0);s.className="anchor-url",s.innerText=i,s.removeAttribute("onclick"),new qi("popup-masked-url",{titleLangKey:"OpenUrlTitle",descriptionLangKey:"OpenUrlAlert2",descriptionLangArgs:[s],buttons:[{langKey:"Open",callback:()=>{s.click()}}]}).show()}}),this.addAnchorListener({name:"execBotCommand",callback:({uriParams:e})=>{const{command:t,bot:i}=e;this.managers.appMessagesManager.sendText(this.chat.peerId,"/"+t+(i?"@"+i:""))}}),this.addAnchorListener({name:"searchByHashtag",callback:({uriParams:e})=>{const{hashtag:t}=e;t&&this.chat.initSearch("#"+t+" ")}}),this.addAnchorListener({name:"addstickers",callback:({pathnameParams:e})=>{const t={_:sl.STICKER_SET,set:e[1]};this.processInternalLink(t)}}),this.addAnchorListener({name:"invoice",callback:({pathnameParams:e})=>{const t={_:sl.INVOICE,slug:e.length>1?e[1]:e[0].slice(1)};this.processInternalLink(t)}}),this.addAnchorListener({name:"joinchat",callback:({pathnameParams:e})=>{const t={_:sl.JOIN_CHAT,invite:e[1]||decodeURIComponent(e[0]).slice(1)};this.processInternalLink(t)}}),Wd.Z&&this.addAnchorListener({name:"voicechat",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(sl.VOICE_CHAT,e);this.processInternalLink(t)}}),this.addAnchorListener({name:"im",callback:({pathnameParams:e,uriParams:t})=>Pm(this,void 0,void 0,(function*(){let i;i=Mo.kO.test(e[0])?{_:sl.USER_PHONE_NUMBER,phone:e[0].slice(1)}:"c"===e[0]?{_:sl.PRIVATE_POST,channel:e[1],post:e[2],thread:"thread"in t&&t.thread,comment:t.comment}:{_:sl.MESSAGE,domain:e[0],post:e[1],comment:t.comment,start:"start"in t?t.start:void 0},this.processInternalLink(i)}))}),this.addAnchorListener({name:"resolve",protocol:"tg",callback:({uriParams:e})=>{let t;e.phone?t=this.makeLink(sl.USER_PHONE_NUMBER,e):"telegrampassport"===e.domain||(t=this.makeLink(sl.MESSAGE,e)),this.processInternalLink(t)}}),this.addAnchorListener({name:"privatepost",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(sl.PRIVATE_POST,e);this.processInternalLink(t)}}),this.addAnchorListener({name:"addstickers",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(sl.STICKER_SET,e);this.processInternalLink(t)}}),this.addAnchorListener({name:"invoice",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(sl.INVOICE,e);this.processInternalLink(t)}}),["joinchat","join"].forEach((e=>{this.addAnchorListener({name:e,protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(sl.JOIN_CHAT,e);this.processInternalLink(t)}})})),this.onHashChange(!0),this.attachKeydownListener()}deleteFilesIterative(e){return this.cacheStorage.timeoutOperation((t=>{const i=performance.now();return t.keys().then((i=>{const s=i.map((i=>t.match(i).then((t=>e(t)))));return Promise.all(s).then((e=>(e.map(((e,s)=>{if(!e)return;const n=i[s];return t.delete(n)})),Promise.all(e.filter(Boolean)))))})).then((()=>{this.log("deleted files",performance.now()-i)}))}))}toggleChatGradientAnimation(e){this.chats.forEach((t=>{t.gradientRenderer&&t.gradientRenderer.scrollAnimate(s.Z.settings.animationsEnabled&&t===e)}))}appendEmojiAnimationContainer(e){const t=e===d._.mobile?this.columnEl:document.body;this.emojiAnimationContainer.parentElement!==t&&t.append(this.emojiAnimationContainer)}attachKeydownListener(){const e=new Set(["PageUp","PageDown","Meta","Control"]);document.body.addEventListener("keydown",(t=>{var i;const s=t.key;if(Un.Z.isOverlayActive||e.has(s))return;const n=t.target,o=this.chat;if("KeyC"!==t.code||!t.ctrlKey&&!t.metaKey||"INPUT"===n.tagName){if(!t.altKey||"ArrowUp"!==s&&"ArrowDown"!==s){if("ArrowUp"===s&&"scheduled"!==this.chat.type){if(o.input.editMsgId||!o.input.isInputEmpty())return;this.managers.appMessagesManager.getFirstMessageToEdit(o.peerId,o.threadId).then((e=>{e&&(o.input.initMessageEditing(e.mid),(0,a.Z)(t))}))}else if("ArrowDown"===s)return}else(0,a.Z)(t),this.managers.dialogsStorage.getNextDialog(this.chat.peerId,"ArrowDown"===s,gg.filterId).then((e=>{e&&this.setPeer({peerId:e.peerId})}));if((null===(i=null==o?void 0:o.input)||void 0===i?void 0:i.messageInput)&&t.target!==o.input.messageInput&&"INPUT"!==n.tagName&&!n.hasAttribute("contenteditable")&&!gi.Z&&(!d.Z.isMobile||1===this.tabId)&&!o.selection.isSelecting&&!o.input.recording){o.input.messageInput.focus(),(0,bl.Z)(o.input.messageInput);const e=new KeyboardEvent(t.type,t);o.input.messageInput.dispatchEvent(e)}}}))}makeLink(e,t){return Object.assign({_:e},t)}processInternalLink(e){return Pm(this,void 0,void 0,(function*(){switch(null==e?void 0:e._){case sl.MESSAGE:{const t=e.post?(0,cl.Z)(+e.post):void 0,i=e.comment?(0,cl.Z)(+e.comment):void 0;this.openUsername({userName:e.domain,lastMsgId:t,commentId:i,startParam:e.start});break}case sl.PRIVATE_POST:{const t=e.channel.toChatId(),i=t.toPeerId(!0);if((yield this.managers.appChatsManager.getChat(t)).deleted)try{yield this.managers.appChatsManager.resolveChannel(t)}catch(e){throw Li({langPackKey:"LinkNotFound"}),e}const s=(0,cl.Z)(+e.post),n=e.thread?(0,cl.Z)(+e.thread):void 0;n?this.openThread(i,s,n):this.setInnerPeer({peerId:i,lastMsgId:s,threadId:n});break}case sl.STICKER_SET:new qn({id:e.set}).show();break;case sl.JOIN_CHAT:this.managers.appChatsManager.checkChatInvite(e.invite).then((t=>{t.chat&&this.managers.appChatsManager.saveApiChat(t.chat,!0),"chatInviteAlready"!==t._&&"chatInvitePeek"!==t._?new al(e.invite,t):this.setInnerPeer({peerId:t.chat.id.toPeerId(!0)})}),(e=>{"INVITE_HASH_EXPIRED"===e.type&&Ci((0,v.ag)("InviteExpired"))}));break;case sl.VOICE_CHAT:Wd.Z&&this.joinGroupCall(e.chat_id.toPeerId(!0),e.id);break;case sl.USER_PHONE_NUMBER:this.managers.appUsersManager.resolvePhone(e.phone).then((e=>{this.setInnerPeer({peerId:e.id.toPeerId(!1)})})).catch((e=>{"PHONE_NOT_OCCUPIED"===e.type&&Li({langPackKey:"Alert.UserDoesntExists"})}));break;case sl.INVOICE:this.managers.appPaymentsManager.getInputInvoiceBySlug(e.slug).then((e=>{this.managers.appPaymentsManager.getPaymentForm(e).then((t=>{new lc(void 0,e,t)}))}));break;default:this.log.warn("Not supported internal link:",e)}}))}openUrl(e){const{url:t,onclick:i}=(0,Pa.Z)(e),s=document.createElement("a");s.href=t,window[i](s)}addAnchorListener(e){window[(e.protocol?e.protocol+"_":"")+e.name]=t=>{(0,a.Z)(null);const i=t.href;let s,n;e.noPathnameParams||(s=new URL(t.href).pathname.split("/").slice(1)),e.noUriParams||(n=this.parseUriParams(i));const o=e.callback({pathnameParams:s,uriParams:n},t);return void 0===o&&o}}parseUriParams(e,t=e.split("?")){const i={};return t[1]?(t[1].split("&").forEach((e=>{i[e.split("=")[0]]=decodeURIComponent(e.split("=")[1])})),i):i}openUsername(e){const{userName:t,lastMsgId:i,threadId:s,commentId:n,startParam:a}=e;return this.managers.appUsersManager.resolveUsername(t).then((e=>{const t="user"===e._,o=e.id.toPeerId(!t);return s?this.openThread(o,i,s):n?this.openComment(o,i,n):this.setInnerPeer({peerId:o,lastMsgId:i,startParam:a})}),(e=>{"USERNAME_NOT_OCCUPIED"===e.type?Li({langPackKey:"NoUsernameFound"}):"USERNAME_INVALID"===e.type&&Li({langPackKey:"Alert.UserDoesntExists"})}))}openThread(e,t,i){return this.managers.appMessagesManager.wrapSingleMessage(e,i).then((s=>(s?this.managers.appMessagesManager.generateThreadServiceStartMessage(s):t=void 0,this.setInnerPeer({peerId:e,lastMsgId:t,threadId:i,type:"discussion"}))))}openComment(e,t,i){return this.managers.appMessagesManager.getDiscussionMessage(e,t).then((e=>this.openThread(e.peerId,i,e.mid)))}callUser(e,t){return Pm(this,void 0,void 0,(function*(){em.getCallByUserId(e)||((yield this.managers.appProfileManager.getProfile(e)).pFlags.phone_calls_private?In({descriptionLangKey:"Call.PrivacyErrorMessage",descriptionLangArgs:[new Ot({peerId:e.toPeerId()}).element],button:{langKey:"OK",isCancel:!0}}):(yield this.discardCurrentCall(e.toPeerId()),em.startCallInternal(e,"video"===t)))}))}discardCurrentCall(e,t,i){return Fu.groupCall&&Fu.groupCall!==t?this.discardGroupCallConfirmation(e):em.currentCall&&em.currentCall!==i?this.discardCallConfirmation(e):Promise.resolve()}discardCallConfirmation(e){return Pm(this,void 0,void 0,(function*(){const t=em.currentCall;t&&(yield In({titleLangKey:"Call.Confirm.Discard.Call.Header",descriptionLangKey:e.isUser()?"Call.Confirm.Discard.Call.ToCall.Text":"Call.Confirm.Discard.Call.ToVoice.Text",descriptionLangArgs:[new Ot({peerId:t.interlocutorUserId.toPeerId(!1)}).element,new Ot({peerId:e}).element],button:{langKey:"OK"}}),t.isClosing||(yield t.hangUp("phoneCallDiscardReasonDisconnect")))}))}discardGroupCallConfirmation(e){return Pm(this,void 0,void 0,(function*(){const t=Fu.groupCall;t&&(yield In({titleLangKey:"Call.Confirm.Discard.Voice.Header",descriptionLangKey:e.isUser()?"Call.Confirm.Discard.Voice.ToCall.Text":"Call.Confirm.Discard.Voice.ToVoice.Text",descriptionLangArgs:[new Ot({peerId:t.chatId.toPeerId(!0)}).element,new Ot({peerId:e}).element],button:{langKey:"OK"}}),Fu.groupCall===t&&(yield t.hangUp()))}))}joinGroupCall(e,t){return Pm(this,void 0,void 0,(function*(){const i=e.toChatId(),s=this.managers.appChatsManager.hasRights(i,"manage_call");if(t&&"groupCallDiscarded"===(yield this.managers.appGroupCallsManager.getGroupCallFull(t))._){if(!s)return void Li({langPackKey:"VoiceChat.Chat.Ended"});yield In({descriptionLangKey:"VoiceChat.Chat.StartNew",button:{langKey:"VoiceChat.Chat.StartNew.OK"}})}(()=>{Pm(this,void 0,void 0,(function*(){const e=yield this.managers.appProfileManager.getChatFull(i);let t;if(e.call)t=e.call;else{if(!s)return;t=yield this.managers.appGroupCallsManager.createGroupCall(i)}Fu.joinGroupCall(i,t.id,!0,!1)}))})()}))}setCurrentBackground(e=!1){const t=$o.Z.getTheme();if(t.background.slug){const i=Qo.h.settings.themes.find((e=>e.name===t.name));return this.getBackground(t.background.slug).then((t=>this.setBackground(t,e)),(()=>(t.background=(0,Ji.Z)(i.background),this.setCurrentBackground(!0))))}return this.setBackground("",e)}getBackground(e){return this.backgroundPromises[e]?this.backgroundPromises[e]:this.backgroundPromises[e]=this.cacheStorage.getFile("backgrounds/"+e).then((e=>URL.createObjectURL(e)))}setBackground(e,t=!0){this.lastBackgroundUrl=e;const i=this.chats.map((t=>t.setBackground(e)));return i[i.length-1].then((()=>{t&&s.Z.dispatchEvent("background_change")}))}saveChatPosition(e){if(!["chat","discussion"].includes(e.type)||!e.peerId)return;const t=e.bubbles,i=e.peerId+(e.threadId?"_"+e.threadId:""),s=$u.Z.getFromCache("chatPositions");if(t.scrollable.getDistanceToEnd()<=16&&t.scrollable.loadedAll.bottom||!t.getRenderedLength())delete s[i],this.log("deleted chat position");else{t.sliceViewport(!0);const e=t.scrollable.scrollTop,n={mids:(0,no.Z)(t.bubbles,"desc").filter((e=>!t.skippedMids.has(e))),top:e};s[i]=n,this.log("saved chat position:",n)}$u.Z.set({chatPositions:s},!0)}getChatSavedPosition(e){if(!["chat","discussion"].includes(e.type)||!e.peerId)return;const t=e.peerId+(e.threadId?"_"+e.threadId:""),i=$u.Z.getFromCache("chatPositions");return i&&i[t]}applyCurrentTheme(e,t,i){return t&&(this.backgroundPromises[e]=Promise.resolve(t)),$o.Z.setTheme(),this.setCurrentBackground(void 0===i?!!e:i)}chatsSelectTab(e,t){if(this.prevTab!==e){if(!1===t&&this.prevTab&&ju([e,this.prevTab].filter(Boolean)),this.prevTab){this.prevTab.classList.remove("active"),this.chatsSelectTabDebounced(),s.Z.settings.animationsEnabled&&!1!==t&&(0,He.YW)((0,on.Z)(400),400);const i=(0,Cn.Z)(this.prevTab);(0,Cn.Z)(e)>i&&C.Z.pushItem({type:"chat",onPop:e=>{this.setPeer({},e),(0,ln.Z)()}})}e.classList.add("active"),this.prevTab=e}}init(){document.addEventListener("paste",this.onDocumentPaste,!0),gi.Z||this.attachDragAndDropListeners(),this.markupTooltip=new Gu(this),this.markupTooltip.handleSelection()}attachDragAndDropListeners(){const e=[],t=[];let i=!1;const s=(a,c)=>Pm(this,void 0,void 0,(function*(){if(c===i)return;const d=a.dataTransfer.types,h=d.contains?d.contains("Files"):d.indexOf("Files")>=0,u=Kc(),p=yield Em(a,!0);if(!h||!(yield this.canDrag())&&!u)return void(n=0);const m=u?l:r,g=u?t:e;if(c&&!g.length){const e=h&&!p.length,t=p.filter((e=>o.Z.has(e))).length;this.log("drag files",p),u?(u.appendDrops(m),(p.length||e)&&g.push(new Wu(m,{header:"Preview.Dragging.AddItems",headerArgs:[p.length],onDrop:e=>{s(e,!1),this.log("drop",e),this.onDocumentPaste(e,"document")}}))):((p.length||e)&&g.push(new Wu(m,{icon:"dragfiles",header:"Chat.DropTitle",subtitle:"Chat.DropAsFilesDesc",onDrop:e=>{s(e,!1),this.log("drop",e),this.onDocumentPaste(e,"document")}})),(t||e)&&g.push(new Wu(m,{icon:"dragmedia",header:"Chat.DropTitle",subtitle:"Chat.DropQuickDesc",onDrop:e=>{s(e,!1),this.log("drop",e),this.onDocumentPaste(e,"media")}})),this.chat.container.append(m))}Re(m,"is-visible",c,200,(()=>{c||(g.forEach((e=>{e.destroy()})),g.length=0)})),c?g.forEach((e=>{e.setPath()})):n=0,document.body.classList.toggle("is-dragging",c),i=c}));let n=0;document.body.addEventListener("dragenter",(e=>{n++})),document.body.addEventListener("dragover",(e=>{s(e,!0),(0,a.Z)(e)})),document.body.addEventListener("dragleave",(e=>{n--,0===n&&s(e,!1)}));const r=document.createElement("div");r.classList.add("drops-container");const l=r.cloneNode(!0)}canDrag(){return Pm(this,void 0,void 0,(function*(){const e=this.chat;return!(!(null==e?void 0:e.peerId)||Un.Z.isOverlayActive||!(yield e.canSend("send_media")))}))}overrideHash(e){return Pm(this,void 0,void 0,(function*(){let t;if(e){const i=yield this.managers.appPeersManager.getPeerUsername(e);t=i?"@"+i:""+e}C.Z.overrideHash(t)}))}selectTab(e,t){var i;!1===t&&ju([Hr.sidebarEl,this.columnEl,nn.sidebarEl]),document.body.classList.toggle(Dr,0===e);const n=this.tabId;-1!==n&&this.overrideHash(e>0?null===(i=this.chat)||void 0===i?void 0:i.peerId:void 0),this.log("selectTab",e,n);let a=s.Z.settings.animationsEnabled?(0,Be.d1)():Promise.resolve();if(-1!==n&&n!==e&&s.Z.settings.animationsEnabled&&!1!==t&&d.Z.activeScreen!==d._.large){const e=100+(d.Z.isMobile?250:200);a=(0,on.Z)(e),(0,He.YW)(a,e)}this.tabId=e,(0,ln.Z)(),d.Z.isMobile&&2===n&&e<2&&document.body.classList.remove(tn),-1!==n&&e>n&&(e<2||!C.Z.findItemByType("im"))&&C.Z.pushItem({type:"im",onPop:e=>{this.setPeer({},e)}});const o=window.onImTabChange;return o&&o(e),a}updateStatus(){return this.managers.appUsersManager.updateMyOnlineStatus(this.offline)}createNewChat(){const e=new Hu(this,this.managers);return this.chats.length&&e.setBackground(this.lastBackgroundUrl,!0),this.chats.push(e),e}spliceChats(e,t=!0,i,s){if(e>=this.chats.length)return;const n=this.chat;this.chats.length>1&&t&&this.dispatchEvent("peer_changing",this.chat),s||(s=this.chats.splice(e,this.chats.length-e));const a=this.chat;this.dispatchEvent("chat_changing",{from:n,to:a});for(let e=0;e<s.length-1;++e)C.Z.removeByType("chat",!0);if(s.length>1&&s.slice(0,-1).forEach((e=>{e.container.remove()})),this.chatsSelectTab(a.container,i),t){this.dispatchEvent("peer_changed",a.peerId);const e=nn.getTab(Bu);e&&e.close(),nn.replaceSharedMediaTab(a.sharedMediaTab)}s.forEach((e=>{e.beforeDestroy()})),setTimeout((()=>{s.forEach((e=>{e.destroy()}))}),350)}setPeer(e={},t){var i;return Pm(this,void 0,void 0,(function*(){this.init&&(this.init(),this.init=null),null!==(i=e.peerId)&&void 0!==i||(e.peerId=le.NM);const{peerId:s,lastMsgId:n}=e,a=this.chat,o=this.chats.indexOf(a);if(s){if(o>0&&a.peerId&&a.peerId!==s){const t=this.chats.splice(1,this.chats.length-1);if(this.chat.peerId===s)return void this.spliceChats(0,!0,!0,t);{const i=this.setPeer(e);return this.spliceChats(0,!1,!1,t),i}}}else{if(o>0)return void this.spliceChats(o,void 0,t);if(d.Z.activeScreen===d._.medium)return void this.selectTab(+!this.tabId,t)}if(s===a.peerId&&d.Z.activeScreen<=d._.medium&&document.body.classList.contains(Dr))return this.selectTab(1,t),!1;if(s||d.Z.activeScreen!==d._.mobile){const i=yield a.setPeer(s,n,e.startParam),o=(null==i?void 0:i.cached)?i.promise:Promise.resolve();s&&Promise.all([o,a.setBackgroundPromise]).then((()=>{setTimeout((()=>{setTimeout((()=>{this.chatsSelectTab(this.chat.container)}),0),this.selectTab(1,t)}),0)}))}return s?void 0:(this.selectTab(0,t),!1)}))}setInnerPeer(e){var t;const{peerId:i}=e;if(i===le.NM||!i)return;e.threadId&&(e.type="discussion");const s=null!==(t=e.type)&&void 0!==t?t:e.type="chat",n=this.chats.findIndex((e=>e.peerId===i&&e.type===s));if(-1!==n)return this.spliceChats(n+1),this.setPeer(e);const a=this.chat;let o=a;return a.inited&&(o=this.createNewChat()),s&&(o.setType(s),e.threadId&&(o.threadId=e.threadId)),this.dispatchEvent("chat_changing",{from:a,to:o}),this.setPeer(e)}openScheduled(e){this.setInnerPeer({peerId:e,type:"scheduled"})}getTypingElement(e){const t=document.createElement("span");let i="peer-typing";switch(t.classList.add(i),t.dataset.action=e._,e._){case"sendMessageTypingAction":i+="-text";for(let e=0;e<3;++e){const e=document.createElement("span");e.className=i+"-dot",t.append(e)}break;case"sendMessageUploadAudioAction":case"sendMessageUploadDocumentAction":case"sendMessageUploadRoundAction":case"sendMessageUploadVideoAction":case"sendMessageUploadPhotoAction":i+="-upload";break;case"sendMessageRecordAudioAction":case"sendMessageRecordRoundAction":case"sendMessageRecordVideoAction":i+="-record";break;case"sendMessageEmojiInteractionSeen":case"sendMessageChooseStickerAction":i+="-choosing-sticker";for(let e=0;e<2;++e){const e=document.createElement("div");e.className=i+"-eye",t.append(e)}}return t.classList.add(i),t}getPeerTyping(e,t){return Pm(this,void 0,void 0,(function*(){const i=e.isUser();if(i&&(yield this.managers.appUsersManager.isBot(e)))return;const s=yield this.managers.appProfileManager.getPeerTypings(e);if(!(null==s?void 0:s.length))return;const n=s[0],a={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"}},o=i?a.private:s.length>1?a.multi:a.chat;let r=n.action;if(s.length>1){const e={};s.forEach((t=>{const i=t.action._;void 0===e[i]&&(e[i]=0),++e[i]})),Object.keys(e).length>1&&(r={_:"sendMessageTypingAction"})}const l=o[r._];if(!l)return;let c,d;if(e.isAnyChat()){const e=new Ot;c=e.update({peerId:n.userId.toPeerId(!1),onlyFirstName:!0}),d=[e.element,s.length-1],yield c}t||(t=document.createElement("span")).classList.add("online","peer-typing-container"),t.classList.toggle("peer-typing-flex","sendMessageChooseStickerAction"===r._||"sendMessageEmojiInteractionSeen"===r._);let h=t.firstElementChild;if(h?h.dataset.action!==r._&&h.replaceWith(this.getTypingElement(r)):(h=this.getTypingElement(r),t.prepend(h)),"sendMessageEmojiInteractionSeen"===r._){d?d.pop():d=[];const e=(0,Ca.Z)((0,Zt.Z)(r.emoticon));d.push(e)}const u=(0,v.ag)(l,d);return u.classList.add("peer-typing-description"),t.childElementCount>1?t.lastElementChild.replaceWith(u):t.append(u),t}))}getChatStatus(e){return Pm(this,void 0,void 0,(function*(){const t=yield this.getPeerTyping(e.toPeerId(!0));if(t)return{cached:!0,result:Promise.resolve(t)};const i=yield this.managers.acknowledged.appProfileManager.getChatFull(e),s=Promise.resolve(i.result).then((t=>Pm(this,void 0,void 0,(function*(){var i,s;const n=t.participants_count||(null===(s=null===(i=t.participants)||void 0===i?void 0:i.participants)||void 0===s?void 0:s.length)||1;let a=yield cs(e);if(n<2)return a;const o=yield this.managers.appProfileManager.getOnlines(e);if(o>1){const e=document.createElement("span");e.append(...(0,v.v_)([a,(0,v.ag)("OnlineCount",[ls(o)])],!1)),a=e}return a}))));return{cached:i.cached,result:s}}))}getUserStatus(e,t){var i;return Pm(this,void 0,void 0,(function*(){const s={cached:!0,result:Promise.resolve(void 0)},n=yield this.managers.appUsersManager.getUser(e);if(!n||n.pFlags.self&&!t)return s;const a=ce(n);if(!n.pFlags.bot){let t=yield this.getPeerTyping(e.toPeerId());if(t||"userStatusOnline"!==(null===(i=n.status)||void 0===i?void 0:i._)||(t=document.createElement("span"),t.classList.add("online"),t.append(a)),t)return s.result=Promise.resolve(t),s}return s.result=Promise.resolve(a),s}))}getPeerStatus(e,t){return Pm(this,void 0,void 0,(function*(){if(!e)return;let i;return i=e.isAnyChat()?this.getChatStatus(e.toChatId()):this.getUserStatus(e.toUserId(),t),i}))}setPeerStatus(e,t,i,s,n,a){return Pm(this,void 0,void 0,(function*(){if(!i){const i=t.querySelector(".peer-typing-container");if(i&&(yield this.getPeerTyping(e,i)))return}const o=yield this.getPeerStatus(e,a);if(!n())return;const r=()=>Pm(this,void 0,void 0,(function*(){const e=o&&(yield o.result);if(n())return()=>(0,g.Z)(t,e||l)})),l=s?"":"";return!o||o.cached?yield r():i?()=>(t.textContent=l,r().then((e=>e&&e()))):void 0}))}setChoosingStickerTyping(e){this.managers.appMessagesManager.setTyping(this.chat.peerId,{_:e?"sendMessageCancelAction":"sendMessageChooseStickerAction"})}}const xm=new Tm;R.GO&&(R.GO.appImManager=xm);const _m=xm;class Am extends pp{constructor({video:e,play:t=!1,streamable:i=!1,duration:s,onPlaybackRackMenuToggle:n,onPip:a,onPipClose:o}){if(super(),this.video=e,this.wrapper=document.createElement("div"),this.wrapper.classList.add("ckin__player"),this.onPlaybackRackMenuToggle=n,this.onPip=a,this.onPipClose=o,this.listenerSetter=new I.Z,this.setup({element:this.wrapper,listenerSetter:this.listenerSetter,canHideControls:()=>!(this.video.paused||this.playbackRateButton&&this.playbackRateButton.classList.contains("menu-open")),showOnLeaveToClassName:"media-viewer-caption",ignoreClickClassName:"ckin__controls"}),e.parentNode.insertBefore(this.wrapper,e),this.wrapper.appendChild(e),this.skin="default",this.stylePlayer(s),this.setBtnMenuToggle(),"default"===this.skin){const t=this.wrapper.querySelector(".default__controls.ckin__controls");this.progress=new At(e,i),t.prepend(this.progress.container)}t&&e.play().catch((t=>{"NotAllowedError"===t.name&&(e.muted=!0,e.autoplay=!0,e.play())})).finally((()=>{this.wrapper.classList.toggle("is-playing",!this.video.paused)}))}stylePlayer(e){const{wrapper:t,video:i,skin:s,listenerSetter:o}=this;t.classList.add(s);const r=this.buildControls();let l;if(t.insertAdjacentHTML("beforeend",r),"default"===s){this.playbackRateButton=this.wrapper.querySelector(".playback-rate"),this.pipButton=this.wrapper.querySelector(".pip");const e=t.querySelectorAll(".toggle"),s=t.querySelector(".fullscreen"),r=t.querySelector("#time-elapsed");l=t.querySelector("#time-duration"),l.textContent=gt(0|i.duration);const c=new Bd(o),d=t.querySelector(".left-controls");if(c.btn.classList.remove("btn-icon"),d.insertBefore(c.btn,r.parentElement),Array.from(e).forEach((e=>{(0,n.fc)(e,(()=>{this.togglePlay()}),{listenerSetter:this.listenerSetter})})),this.pipButton){(0,n.fc)(this.pipButton,(()=>{this.video.requestPictureInPicture()}),{listenerSetter:this.listenerSetter});const e=e=>{this.wrapper.style.visibility=e?"hidden":"",this.onPip&&this.onPip(e)},t=20,s=(0,Ki.Z)(e,t,!1,!0);o.add(i)("enterpictureinpicture",(()=>{s(!0),o.add(i)("leavepictureinpicture",(()=>{const e=o.add(i)("pause",(()=>{clearTimeout(s),this.onPipClose&&this.onPipClose()}),{once:!0}),s=setTimeout((()=>{o.remove(e)}),t)}),{once:!0})})),o.add(i)("leavepictureinpicture",(()=>{s(!1)}))}gi.Z||((0,n.fc)(i,(()=>{this.togglePlay()}),{listenerSetter:this.listenerSetter}),o.add(document)("keydown",(e=>{if(Un.Z.overlaysActive>1||document.pictureInPictureElement===i)return;const{key:s,code:n}=e;let o=!0;if("KeyF"===n)this.toggleFullScreen();else if("KeyM"===n)vt.Z.muted=!vt.Z.muted;else if("Space"===n)this.togglePlay();else if(!e.altKey||"Equal"!==n&&"Minus"!==n)!t.classList.contains("ckin__fullscreen")||"ArrowLeft"!==s&&"ArrowRight"!==s?o=!1:"ArrowLeft"===s?vt.Z.seekBackward({action:"seekbackward"}):vt.Z.seekForward({action:"seekforward"});else{const e="Equal"===n?1:-1,t=vt.Z.playbackRate,i=Am.PLAYBACK_RATES.indexOf(t)+e;i>=0&&i<Am.PLAYBACK_RATES.length&&(vt.Z.playbackRate=Am.PLAYBACK_RATES[i])}return o?((0,a.Z)(e),!1):void 0}))),o.add(i)("dblclick",(()=>{gi.Z||this.toggleFullScreen()})),(0,n.fc)(s,(()=>{this.toggleFullScreen()}),{listenerSetter:this.listenerSetter}),(0,rp.Ms)(t,this.onFullScreen.bind(this,s),o),o.add(i)("timeupdate",(()=>{r.textContent=gt(0|i.currentTime)})),o.add(i)("play",(()=>{t.classList.add("played"),gi.Z||o.add(i)("play",(()=>{this.hideControls(!0)}))}),{once:!0}),o.add(i)("pause",(()=>{this.showControls(!1)})),o.add(vt.Z)("playbackParams",(()=>{this.setPlaybackRateIcon()}))}o.add(i)("play",(()=>{t.classList.add("is-playing")})),o.add(i)("pause",(()=>{t.classList.remove("is-playing")})),i.duration||e?l.textContent=gt(Math.round(i.duration||e)):(0,pt.Z)(i).then((()=>{l.textContent=gt(Math.round(i.duration))}))}togglePlay(){this.video[this.video.paused?"play":"pause"]()}buildControls(){const e=this.skin;if("default"===e)return`\n <button class="${e}__button--big toggle tgico" title="Toggle Play"></button>\n <div class="${e}__gradient-bottom ckin__controls"></div>\n <div class="${e}__controls ckin__controls">\n <div class="bottom-controls">\n <div class="left-controls">\n <button class="btn-icon ${e}__button toggle tgico" title="Toggle Video"></button>\n <div class="time">\n <time id="time-elapsed">0:00</time>\n <span> / </span>\n <time id="time-duration">0:00</time>\n </div>\n </div>\n <div class="right-controls">\n <button class="btn-icon ${e}__button btn-menu-toggle playback-rate night" title="Playback Rate"></button>\n ${!Je.IS_MOBILE&&document.pictureInPictureEnabled?`<button class="btn-icon ${e}__button pip tgico-pip" title="Picture-in-Picture"></button>`:""}\n <button class="btn-icon ${e}__button fullscreen tgico-fullscreen" title="Full Screen"></button>\n </div>\n </div>\n </div>`}setBtnMenuToggle(){const e=Am.PLAYBACK_RATES.map(((e,t)=>({regularText:e+"x",onClick:()=>{vt.Z.playbackRate=e}}))),t=Ei(e);t.classList.add("top-left"),po(this.playbackRateButton,this.onPlaybackRackMenuToggle?()=>{this.onPlaybackRackMenuToggle(!0)}:void 0,void 0,this.onPlaybackRackMenuToggle?()=>{this.onPlaybackRackMenuToggle(!1)}:void 0),this.playbackRateButton.append(t),this.setPlaybackRateIcon()}setPlaybackRateIcon(){const e=this.playbackRateButton;Am.PLAYBACK_RATES_ICONS.forEach((t=>{t="tgico-"+t,e.classList.remove(t)}));let t=Am.PLAYBACK_RATES.indexOf(vt.Z.playbackRate);-1===t&&(t=Am.PLAYBACK_RATES.indexOf(1)),e.classList.add("tgico-"+Am.PLAYBACK_RATES_ICONS[t])}toggleFullScreen(){const e=this.wrapper;if(Je.IS_APPLE_MOBILE){const e=this.video;return e.webkitEnterFullscreen(),void e.enterFullscreen()}(0,rp.rB)()?(0,rp.C8)():(0,rp.Dj)(e)}onFullScreen(e){const t=(0,rp.rB)();this.wrapper.classList.toggle("ckin__fullscreen",t),t?(e.classList.remove("tgico-fullscreen"),e.classList.add("tgico-smallscreen"),e.setAttribute("title","Exit Full Screen")):(e.classList.remove("tgico-smallscreen"),e.classList.add("tgico-fullscreen"),e.setAttribute("title","Full Screen"))}cleanup(){super.cleanup(),this.listenerSetter.removeAll(),this.progress.removeListeners(),this.onPlaybackRackMenuToggle=this.onPip=void 0}}Am.PLAYBACK_RATES=[.5,1,1.5,2],Am.PLAYBACK_RATES_ICONS=["playback_05","playback_1x","playback_15","playback_2x"];var Zm=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Fm extends L.Z{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.pageEl=document.getElementById("page-chats"),this.zoomElements={},this.zoomSwipeStartX=0,this.zoomSwipeStartY=0,this.zoomSwipeX=0,this.zoomSwipeY=0,this.setZoomValue=(e=this.zoomElements.rangeSelector.value)=>{1===e&&(this.zoomSwipeX=0,this.zoomSwipeY=0),this.moversContainer.style.transform=`matrix(${e}, 0, 0, ${e}, ${this.zoomSwipeX}, ${this.zoomSwipeY})`,this.zoomElements.btnOut.classList.toggle("inactive",.5===e),this.zoomElements.btnIn.classList.toggle("inactive",4===e),this.toggleZoom(1!==e)},this.onClick=e=>{if(this.setMoverAnimationPromise)return;const t=e.target;if("A"===t.tagName)return;if((0,a.Z)(e),gi.Z)return this.highlightSwitchersTimeout?clearTimeout(this.highlightSwitchersTimeout):this.wholeDiv.classList.add("highlight-switchers"),void(this.highlightSwitchersTimeout=window.setTimeout((()=>{this.wholeDiv.classList.remove("highlight-switchers"),this.highlightSwitchersTimeout=0}),3e3));const i=this.isZooming();let s=null;const n=["ckin__player","media-viewer-buttons","media-viewer-author","media-viewer-caption","zoom-container"];i&&n.push("media-viewer-movers"),n.find((e=>{try{if(s=(0,r.Z)(t,e),s)return!0}catch(e){return!1}})),s&&(i||"IMG"!==t.tagName&&"image"!==t.tagName)||this.close()},this.onKeyDown=e=>{if(Un.Z.overlaysActive>1)return;const t=e.key;let i=!0;"ArrowRight"===t?this.buttons.next.click():"ArrowLeft"===t?this.buttons.prev.click():"-"===t||"="===t?this.ctrlKeyDown&&this.changeZoom("="===t):i=!1,(e.ctrlKey||e.metaKey)&&(this.ctrlKeyDown=!0),i&&(0,a.Z)(e)},this.onKeyUp=e=>{Un.Z.overlaysActive>1||e.ctrlKey||e.metaKey||(this.ctrlKeyDown=!1,this.isZooming()&&this.setZoomValue())},this.onWheel=e=>{if(!(Un.Z.overlaysActive>1||(0,r.Z)(e.target,"media-viewer-caption")&&!this.ctrlKeyDown)&&((0,a.Z)(e),this.ctrlKeyDown)){const t=e.deltaY<0;this.changeZoom(!!t)}},this.managers=s.Z.managers,this.log=(0,he.kg)("AMV"),this.preloader=new Ue,this.preloaderStreamable=new Ue({cancelable:!1,streamable:!0}),this.preloader.construct(),this.preloaderStreamable.construct(),this.lazyLoadQueue=new ve.Z,this.wholeDiv=document.createElement("div"),this.wholeDiv.classList.add("media-viewer-whole"),this.overlaysDiv=document.createElement("div"),this.overlaysDiv.classList.add("overlays");const i=document.createElement("div");i.classList.add("media-viewer");const o=this.topbar=document.createElement("div");o.classList.add("media-viewer-topbar","media-viewer-appear");const l=document.createElement("div");l.classList.add("media-viewer-topbar-left"),this.buttons["mobile-close"]=E("close",{onlyMobile:!0}),this.author.container=document.createElement("div"),this.author.container.classList.add("media-viewer-author","no-select");const c=document.createElement("div");this.author.avatarEl=new Wm,this.author.avatarEl.classList.add("media-viewer-userpic","avatar-44"),this.author.nameEl=document.createElement("div"),this.author.nameEl.classList.add("media-viewer-name"),this.author.date=document.createElement("div"),this.author.date.classList.add("media-viewer-date"),c.append(this.author.nameEl,this.author.date),this.author.container.append(this.author.avatarEl,c);const d=document.createElement("div");d.classList.add("media-viewer-buttons"),t.concat(["download","zoom","close"]).forEach((e=>{const t=E(e,{noRipple:!0});this.buttons[e]=t,d.append(t)})),this.buttons.zoom.classList.add("zoom-in"),this.zoomElements.container=document.createElement("div"),this.zoomElements.container.classList.add("zoom-container"),this.zoomElements.btnOut=E("zoomout",{noRipple:!0}),(0,n.fc)(this.zoomElements.btnOut,(()=>this.changeZoom(!1))),this.zoomElements.btnIn=E("zoomin",{noRipple:!0}),(0,n.fc)(this.zoomElements.btnIn,(()=>this.changeZoom(!0))),this.zoomElements.rangeSelector=new _t({step:.5,min:.5,max:4,withTransition:!0},1),this.zoomElements.rangeSelector.setListeners(),this.zoomElements.rangeSelector.setHandlers({onScrub:this.setZoomValue,onMouseUp:()=>this.setZoomValue()}),this.zoomElements.container.append(this.zoomElements.btnOut,this.zoomElements.rangeSelector.container,this.zoomElements.btnIn),this.wholeDiv.append(this.zoomElements.container),this.content.main=document.createElement("div"),this.content.main.classList.add("media-viewer-content"),this.content.container=document.createElement("div"),this.content.container.classList.add("media-viewer-container"),this.content.media=document.createElement("div"),this.content.media.classList.add("media-viewer-media"),this.content.container.append(this.content.media),this.content.main.append(this.content.container),i.append(this.content.main),this.overlaysDiv.append(i),l.append(this.buttons["mobile-close"],this.author.container),o.append(l,d),this.buttons.prev=document.createElement("div"),this.buttons.prev.className="media-viewer-switcher media-viewer-switcher-left",this.buttons.prev.innerHTML='<span class="tgico-down media-viewer-prev-button"></span>',this.buttons.next=document.createElement("div"),this.buttons.next.className="media-viewer-switcher media-viewer-switcher-right",this.buttons.next.innerHTML='<span class="tgico-down media-viewer-next-button"></span>',this.moversContainer=document.createElement("div"),this.moversContainer.classList.add("media-viewer-movers"),this.wholeDiv.append(this.overlaysDiv,this.buttons.prev,this.buttons.next,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(){(0,n.fc)(this.buttons.download,this.onDownloadClick),[this.buttons.close,this.buttons["mobile-close"],this.preloaderStreamable.preloader].forEach((e=>{(0,n.fc)(e,this.close.bind(this))})),[[-1,this.buttons.prev],[1,this.buttons.next]].forEach((([e,t])=>{t.addEventListener("click",(t=>{(0,a.Z)(t),this.setMoverPromise||this.listLoader.go(e)}))})),(0,n.fc)(this.buttons.zoom,(()=>{this.isZooming()?this.toggleZoom(!1):this.changeZoom(!0)})),this.wholeDiv.addEventListener("click",this.onClick),this.listLoader.onJump=(e,t)=>{t?this.onNextClick(e):this.onPrevClick(e)},gi.Z&&new Ks({element:this.wholeDiv,onSwipe:(e,t)=>{if(!(0,rp.rB)())return Math.abs(e)/as.width>.2||e>125?(e<0?this.buttons.prev.click():this.buttons.next.click(),!0):(Math.abs(t)/as.height>.2||t>125)&&(this.close(),!0)},verifyTouchTarget:e=>"INPUT"!==e.target.tagName&&!(0,r.Z)(e.target,"media-viewer-caption")})}toggleZoom(e){const t=this.isZooming();if((this.zoomElements.rangeSelector.mousedown||this.ctrlKeyDown)&&(e=!0),t===e)return;void 0===e&&(e=!t),this.buttons.zoom.classList.toggle("zoom-in",!e),this.zoomElements.container.classList.toggle("is-visible",e);const i=e?this.zoomElements.rangeSelector.value:1;if(this.setZoomValue(i),this.zoomElements.rangeSelector.setProgress(i),this.videoPlayer&&this.videoPlayer.lockControls(!e&&void 0),e){if(this.zoomSwipeHandler)this.zoomSwipeHandler.setListeners();else{let e,t;const i=-1;this.zoomSwipeHandler=new Ks({element:this.moversContainer,onFirstSwipe:()=>{e=t=0,this.moversContainer.classList.add("no-transition")},onSwipe:(s,n)=>{[s,n]=[s*i,n*i],this.zoomSwipeX+=s-e,this.zoomSwipeY+=n-t,[e,t]=[s,n],this.setZoomValue()},onReset:()=>{this.moversContainer.classList.remove("no-transition")},cursor:"move"})}this.zoomElements.rangeSelector.setProgress(i)}else e||this.zoomSwipeHandler.removeListeners()}changeZoom(e){this.zoomElements.rangeSelector.addProgress(.5*(e?1:-1)),this.setZoomValue()}isZooming(){return this.zoomElements.container.classList.contains("is-visible")}setBtnMenuToggle(e){const t=mo({onlyMobile:!0},"bottom-left",e);this.topbar.append(t)}close(e){var t;if(e&&(0,a.Z)(e),this.setMoverAnimationPromise)return Promise.reject();this.navigationItem&&C.Z.removeItem(this.navigationItem),this.lazyLoadQueue.clear();const i=this.setMoverToTarget(null===(t=this.target)||void 0===t?void 0:t.element,!0).then((({onAnimationEnd:e})=>e));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(),this.zoomSwipeHandler=void 0,i.finally((()=>{this.wholeDiv.remove(),this.toggleOverlay(!1)})),i}toggleOverlay(e){Un.Z.isOverlayActive=e,p.Z.checkAnimations(e)}toggleGlobalListeners(e){e?this.setGlobalListeners():this.removeGlobalListeners()}removeGlobalListeners(){this.zoomSwipeHandler&&this.zoomSwipeHandler.removeListeners(),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),window.removeEventListener("wheel",this.onWheel,{capture:!0})}setGlobalListeners(){this.isZooming()&&this.zoomSwipeHandler.setListeners(),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp),gi.Z||window.addEventListener("wheel",this.onWheel,{passive:!1,capture:!0})}setMoverToTarget(e,t=!1,i=0){return Zm(this,void 0,void 0,(function*(){this.dispatchEvent("setMoverBefore");const n=this.content.mover;t||(n.innerHTML="");const a=this.isZooming()&&t?this.zoomElements.rangeSelector.value:1;this.removeCenterFromMover(n);const o=0!==i,l=s.Z.settings.animationsEnabled?o?350:200:0;let c,d;e&&(e instanceof Wm||e.classList.contains("grid-item")?(c=e,d=e.getBoundingClientRect()):e instanceof SVGImageElement||e.parentElement instanceof SVGForeignObjectElement?(c=(0,r.Z)(e,"attachment"),d=c.getBoundingClientRect()):e.classList.contains("profile-avatars-avatar")&&(c=(0,r.Z)(e,"profile-avatars-container"),d=c.getBoundingClientRect(),t&&e.getBoundingClientRect().left!==d.left&&(e=c=d=void 0))),e||(e=this.content.media),d||(c=e.parentElement,d=e.getBoundingClientRect());let h=!1;if(e!==this.content.media&&!e.classList.contains("profile-avatars-avatar")){const i=En(c,(0,r.Z)(c,"scrollable"),!0);!t||i&&2!==i.overflow.vertical&&2!==i.overflow.horizontal?!i||1!==i.overflow.vertical&&1!==i.overflow.horizontal||(h=!0):(c=(e=this.content.media).parentElement,d=e.getBoundingClientRect())}const u=this.content.media.getBoundingClientRect();let p,m,g,v="";if(o?(p=1===i?as.width:-u.width,m=u.top):(p=d.left,m=d.top),v+=`translate3d(${p}px,${m}px,0) `,e instanceof HTMLImageElement||e instanceof HTMLVideoElement||"DIV"===e.tagName){if(n.firstElementChild&&n.firstElementChild.classList.contains("media-viewer-aspecter")){g=n.firstElementChild;const e=g.querySelector(".ckin__player");if(e){const t=e.firstElementChild;g.append(t),e.remove()}g.style.cssText||(n.classList.remove("active"),this.setFullAspect(g,u,d),n.offsetLeft,n.classList.add("active"))}else g=document.createElement("div"),g.classList.add("media-viewer-aspecter"),n.prepend(g);g.style.cssText=`width: ${d.width}px; height: ${d.height}px; transform: scale3d(${u.width/d.width}, ${u.height/d.height}, 1);`}n.style.width=u.width+"px",n.style.height=u.height+"px";const f=d.width/u.width,y=d.height/u.height;o||(v+=`scale3d(${f},${y},1) `);let b=window.getComputedStyle(c).getPropertyValue("border-radius");const w=function(e){const t=e.split(" ");if(4!==t.length){t[0]||(t[0]="0px");for(let e=t.length;e<4;++e)t[e]=t[e%2]||t[0]||"0px"}return t}(b);if(b=w.map((e=>parseInt(e)/f+"px")).join(" "),o||(n.style.borderRadius=b),t&&1!==a){const e=as.width/2-d.width/2,t=as.height/2-d.height/2,i=d.left-e,s=d.top-t;this.moversContainer.style.transform=`matrix(${f}, 0, 0, ${y}, ${i}, ${s})`}else n.style.transform=v;let S;h&&(n.style.opacity="0");const C=e.classList.contains("is-out"),L=this.setMoverAnimationPromise=(0,Oe.Z)(),I={onAnimationEnd:L},M=setTimeout((()=>{L.isFulfilled||L.isRejected||L.resolve()}),1e3);if(L.finally((()=>{this.dispatchEvent("setMoverAfter"),this.setMoverAnimationPromise===L&&(this.setMoverAnimationPromise=null),clearTimeout(M)})),t)return e instanceof SVGSVGElement&&(S=n.querySelector("path"),S&&this.sizeTailPath(S,u,f,l,!1,C,b)),e.classList.contains("media-viewer-media")&&n.classList.add("hiding"),this.toggleWholeActive(!1),setTimeout((()=>{n.style.borderRadius=b,n.firstElementChild&&(n.firstElementChild.style.borderRadius=b)}),l/2),setTimeout((()=>{n.innerHTML="",n.classList.remove("moving","active","hiding"),n.style.cssText="display: none;",L.resolve()}),l),n.classList.remove("opening"),I;{let t,i;if(e instanceof HTMLVideoElement){const t=Array.from(e.parentElement.querySelectorAll("img"));t.length&&(e=t.pop())}if("DIV"===e.tagName||"AVATAR-ELEMENT"===e.tagName){const s=Array.from(e.querySelectorAll("img")).pop();s&&(t=new Image,i=s.src,n.append(t))}else if(e instanceof HTMLImageElement)t=new Image,i=e.src;else if(e instanceof HTMLVideoElement)t=ut(),t.src=e.src;else if(e instanceof SVGSVGElement){const t=e.dataset.clipId,i=t+"-mv",{width:s,height:a}=u,o=document.createElementNS("http://www.w3.org/2000/svg","svg");o.setAttributeNS(null,"width",""+s),o.setAttributeNS(null,"height",""+a),o.setAttributeNS(null,"viewBox",`0 0 ${s} ${a}`),o.setAttributeNS(null,"preserveAspectRatio","xMidYMid meet"),o.insertAdjacentHTML("beforeend",e.firstElementChild.outerHTML.replace(t,i)),o.insertAdjacentHTML("beforeend",e.lastElementChild.outerHTML.replace(t,i));const r=o.firstElementChild,l=r.firstElementChild.firstElementChild;if(l instanceof SVGUseElement){let e,t=l.getAttributeNS(null,"transform");t=t.replace(/translate\((.+?), (.+?)\) scale\((.+?), (.+?)\)/,((e,t,i,n,o)=>`translate(${t=2!=(t=+t)?s-2/f:2/f}, ${a}) scale(${+n/f}, ${+o/y})`)),l.setAttributeNS(null,"transform",t),S=r.firstElementChild.lastElementChild;const i=b.split(" ").map((e=>parseInt(e)));e=C?Ku(0,0,s-9/f,a,...i):Ku(9/f,0,s-9/f,a,...i),S.setAttributeNS(null,"d",e)}const c=o.lastElementChild;c.setAttributeNS(null,"width",""+u.width),c.setAttributeNS(null,"height",""+u.height),n.prepend(o)}g&&(g.style.borderRadius=b,t&&g.append(t)),t=n.querySelector("video, img"),t instanceof HTMLImageElement&&(t.classList.add("thumbnail"),g||(t.style.width=u.width+"px",t.style.height=u.height+"px"),i&&(yield Ze(t,i))),n.style.display="",(0,Be.T2)((()=>{n.classList.add(o?"moving":"active")}))}return n.classList.add("opening"),yield(0,Be.d1)(),n.style.transform=`translate3d(${u.left}px,${u.top}px,0) scale3d(1,1,1)`,h&&(n.style.opacity=""),g&&this.setFullAspect(g,u,d),setTimeout((()=>{n.style.borderRadius="",n.firstElementChild&&(n.firstElementChild.style.borderRadius="")}),0),n.dataset.timeout=""+setTimeout((()=>{n.classList.remove("moving","opening"),g&&(n.querySelector("video"),n.classList.remove("active"),g.style.cssText="",n.offsetLeft),n.classList.add("center","no-transition"),n.classList.add("active"),delete n.dataset.timeout,L.resolve()}),l),S&&this.sizeTailPath(S,u,f,l,!0,C,b),I}))}toggleWholeActive(e){e?this.wholeDiv.classList.add("active"):(this.wholeDiv.classList.add("backwards"),setTimeout((()=>{this.wholeDiv.classList.remove("active")}),0))}setFullAspect(e,t,i){const s=t.width/t.height;let{width:n,height:a}=i;s>0?n=a*s:a=n*s,e.style.cssText=`width: ${n}px; height: ${a}px; transform: scale3d(${t.width/n}, ${t.height/a}, 1);`}sizeTailPath(e,t,i,s,n,a,o){const r=Date.now(),{width:l,height:c}=t;s/=2;const d=o.split(" ").map((e=>parseInt(e))),h=()=>{const t=Date.now()-r;let o=s?t/s:1;o>1&&(o=1),n&&(o=1-o);const u=d.map((e=>e*o));let p;p=a?Ku(0,0,l-9/i*o,c,...u):Ku(9/i*o,0,l,c,...u),e.setAttributeNS(null,"d",p),t<s&&(0,Be.T2)(h)};h()}removeCenterFromMover(e){if(e.classList.contains("center")){const t=this.content.media.getBoundingClientRect();e.style.transform=`translate3d(${t.left}px,${t.top}px,0)`,e.classList.remove("center"),e.offsetLeft,e.classList.remove("no-transition")}}moveTheMover(e,t=!0){const i=as.width;this.removeCenterFromMover(e),e.classList.add("moving"),e.dataset.timeout&&clearTimeout(+e.dataset.timeout);const s=e.getBoundingClientRect(),n=e.style.transform.replace(/translate3d\((.+?),/,((e,n)=>{const a=t?-s.width:i;return e.replace(n,a+"px")}));e.style.transform=n,setTimeout((()=>{e.remove()}),350)}setNewMover(){const e=document.createElement("div");return e.classList.add("media-viewer-mover"),e.style.display="none",this.content.mover?this.content.mover.parentElement.append(e):this.moversContainer.append(e),this.content.mover=e}updateMediaSource(e,t,i){const s=e.tagName.toLowerCase()===i?e:e.querySelector(i);if(s&&!(0,r.Z)(e,"document")){if((0,r.Z)(e,"attachment")){const t=e.parentElement.parentElement.querySelector(".preloader-container");if(t){if("video"===i)return void(t.classList.contains("manual")&&t.click());t.remove()}}Ae(s,t),s.classList.contains("thumbnail")&&s.parentElement.classList.contains("media-container-aspecter")&&s.classList.remove("thumbnail")}}setAuthorInfo(e,t){const i=e.isPeerId();let s;if(i)s=js({peerId:e,dialog:!1,onlyFirstName:!1,plainText:!1});else{const t=s=document.createElement("span");t.append((0,Zt.Z)(e)),t.classList.add("peer-title")}const n=this.author.avatarEl,a=this.author.avatarEl=n.cloneNode();return Promise.all([this.author.avatarEl.updateWithOptions({peerId:e||le.NM,peerTitle:i?void 0:""+e}),s]).then((([e,i])=>{this.author.avatarEl===a&&((0,g.Z)(this.author.date,G(t)),(0,g.Z)(this.author.nameEl,i),n.replaceWith(this.author.avatarEl))}))}_openMedia(e,t,i,s,n,o=!1,r=[],l=[],c){return Zm(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;const h=this.setAuthorInfo(i,t),p="document"===e._,m=p&&e.mime_type&&(["video","gif"].includes(e.type)||0===e.mime_type.indexOf("video/"));this.isFirstOpen&&(this.isFirstOpen=!1,this.listLoader.setTargets(r,l,o),window.appMediaViewer=this),this.listLoader.next.length<10&&setTimeout((()=>{this.listLoader.load(!0)}),0),this.buttons.prev.classList.toggle("hide",!this.listLoader.previous.length),this.buttons.next.classList.toggle("hide",!this.listLoader.next.length);const g=this.content.media,v=!n||n===g;v&&(n=g),this.target={element:n};const f=++this.tempId;g.firstElementChild&&(g.innerHTML=""),0!==s?(this.moveTheMover(this.content.mover,1===s),this.setNewMover()):(this.toggleOverlay(!0),this.setGlobalListeners(),yield h,this.wholeDiv.parentElement||(this.pageEl.insertBefore(this.wholeDiv,document.getElementById("main-columns")),this.wholeDiv.offsetLeft),this.toggleWholeActive(!0),Je.IS_MOBILE_SAFARI||(this.navigationItem={type:"media",onPop:e=>{if(this.setMoverAnimationPromise)return!1;this.close()}},C.Z.pushItem(this.navigationItem)));const y=this.content.mover,b=as.width;let w=0;const S=as.height;S<1e6&&!d.Z.isMobile&&(w=120);const L=S-120-w;let I=Promise.resolve();const M=lt(e,g,b,L,!d.Z.isMobile,void 0,!!(p&&e.w&&e.h)).photoSize;if(v){const t=yield this.managers.thumbsStorage.getCacheContext(e,M.type);let i;if(t.downloaded)i=new Image,i.src=t.url;else{const s=at(e,t,!0);s&&(I=s.loadPromise,i=s.image)}i&&(i.classList.add("thumbnail"),g.append(i))}const E=!(!p||!e.supportsStreaming),P=E?this.preloaderStreamable:this.preloader,k=()=>this.managers.thumbsStorage.getCacheContext(e,null==M?void 0:M.type);let T;if(m){const t=c&&"gif"!==e.type,i=ut({pip:t}),o=()=>this.setMoverToTarget(n,!1,s).then((({onAnimationEnd:s})=>{const o=y.firstElementChild&&y.firstElementChild.classList.contains("media-viewer-aspecter")?y.firstElementChild:y,r=y.querySelector("video");r&&r.remove(),i.setAttribute("playsinline","true"),i.addEventListener("timeupdate",(()=>{this.tempId!==f&&i.pause()})),this.addEventListener("setMoverAfter",(()=>{i.src="",i.load()}),{once:!0}),Je.IS_SAFARI&&(i.autoplay=!0),"gif"===e.type?(i.muted=!0,i.autoplay=!0,i.loop=!0):e.duration<60&&(i.loop=!0),o.append(i);const l=new Promise((e=>{i.addEventListener("canplay",e,{once:!0})})),d=()=>{"gif"!==e.type&&(i.dataset.ckin="default",i.dataset.overlay="1",Promise.all([l,s]).then((()=>{this.tempId===f&&((this.videoPlayer=new Am({video:i,play:!0,streamable:E,onPlaybackRackMenuToggle:e=>{this.wholeDiv.classList.toggle("hide-caption",!!e)},onPip:e=>{const s=window.appMediaViewer;if(!e&&s&&s!==this)return this.releaseSingleMedia=void 0,void this.close();this.moversContainer.lastElementChild.classList.toggle("hiding",e),this.toggleWholeActive(!e),this.toggleOverlay(!e),this.toggleGlobalListeners(!e),this.navigationItem&&(e?C.Z.removeItem(this.navigationItem):C.Z.pushItem(this.navigationItem)),t&&(e?(this.releaseSingleMedia(!1),this.releaseSingleMedia=void 0,vt.Z.setPictureInPicture(i)):this.releaseSingleMedia=vt.Z.setSingleMedia(i,c))},onPipClose:()=>{this.close()}})).addEventListener("toggleControls",(e=>{this.wholeDiv.classList.toggle("has-video-controls",e)})),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))})))};if(E){s.then((()=>{i.readyState<i.HAVE_FUTURE_DATA&&P.attach(y,!0)}));const e=()=>{i.addEventListener("canplay",(()=>{P.detach(),i.parentElement.classList.remove("is-buffering")}),{once:!0})};i.addEventListener("waiting",(()=>{const t=i.networkState===i.NETWORK_LOADING,s=i.readyState<i.HAVE_FUTURE_DATA;t&&s&&(e(),P.attach(y,!0),i.parentElement.classList.add("is-buffering"))})),this.wholeDiv.classList.contains("no-forwards")&&i.addEventListener("contextmenu",(e=>{(0,a.Z)(e)})),e()}this.lazyLoadQueue.unshift({load:()=>Zm(this,void 0,void 0,(function*(){const a=E?Promise.resolve():u.Z.downloadMediaURL({media:e});return E||s.then((()=>Zm(this,void 0,void 0,(function*(){(yield k()).url||P.attach(y,!0,a)})))),Promise.all([a,s]).then((()=>Zm(this,void 0,void 0,(function*(){if(this.tempId!==f)return void this.log.warn("media viewer changed video");const e=(yield k()).url;i.addEventListener("error",(()=>{4!==i.error.code&&this.log.error("Error "+i.error.code+"; details: "+i.error.message),P&&P.detach()}),{once:!0}),n instanceof SVGSVGElement?o.firstElementChild.lastElementChild.append(i):Ae(i,e),t&&(this.releaseSingleMedia=vt.Z.setSingleMedia(i,c),this.addEventListener("setMoverBefore",(()=>{this.releaseSingleMedia&&(this.releaseSingleMedia(),this.releaseSingleMedia=void 0)}),{once:!0})),this.updateMediaSource(n,e,"video"),d()})))),a}))})}));T=I.then(o)}else{const t=()=>this.setMoverToTarget(n,!1,s).then((({onAnimationEnd:t})=>{this.lazyLoadQueue.unshift({load:()=>Zm(this,void 0,void 0,(function*(){const i=p?u.Z.downloadMediaURL({media:e}):u.Z.downloadMediaURL({media:e,thumb:M});return t.then((()=>Zm(this,void 0,void 0,(function*(){(yield k()).url||this.preloader.attachPromise(i)})))),Promise.all([t,i]).then((()=>Zm(this,void 0,void 0,(function*(){var e;if(this.tempId!==f)return void this.log.warn("media viewer changed photo");const t=(yield k()).url;if(n instanceof SVGSVGElement){if(this.updateMediaSource(n,t,"img"),this.updateMediaSource(y,t,"img"),d.Z.isMobile){const e=y.querySelectorAll("img");e&&e.length&&e.forEach((e=>{e.classList.remove("thumbnail")}))}}else{const i=y.firstElementChild&&y.firstElementChild.classList.contains("media-viewer-aspecter")?y.firstElementChild:y,s="IMG"===(null===(e=i.firstElementChild)||void 0===e?void 0:e.tagName)?i.firstElementChild:null;if(!s||s.src!==t){const e=new Image;e.classList.add("thumbnail"),Ae(e,t,(()=>{this.updateMediaSource(n,t,"img"),s&&(0,Be.T2)((()=>{s.remove()})),i.append(e)}))}}})))).catch((e=>{this.log.error(e),this.preloader.attach(y),this.preloader.setManual()})),i}))})}));T=I.then(t)}return this.setMoverPromise=T.catch((()=>{this.setMoverAnimationPromise=null})).finally((()=>{this.setMoverPromise=null}))}))}}var Dm=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Rm extends Fm{constructor(){let e;super(new h.Z({processItem:e=>{const t="inputMessagesFilterDocument"===this.searchContext.inputFilter._,{mid:i,peerId:s}=e,n=(0,Se.Z)(e);if(n&&(!t||Rm.isMediaCompatibleForDocumentViewer(n)))return{element:null,mid:i,peerId:s}}}),["delete","forward"]),this.onPrevClick=e=>Dm(this,void 0,void 0,(function*(){this.openMedia(yield this.getMessageByPeer(e.peerId,e.mid),e.element,-1)})),this.onNextClick=e=>Dm(this,void 0,void 0,(function*(){this.openMedia(yield this.getMessageByPeer(e.peerId,e.mid),e.element,1)})),this.onDeleteClick=()=>{const e=this.target;new Qa(e.peerId,[e.mid],"chat",(()=>{this.target={element:this.content.media},this.close()}))},this.onForwardClick=()=>{const e=this.target;e.mid&&new ja({[e.peerId]:[e.mid]},(()=>this.close()))},this.onAuthorClick=e=>Dm(this,void 0,void 0,(function*(){const{mid:t,peerId:i}=this.target;if(t&&t!==Number.MAX_SAFE_INTEGER){const s=this.searchContext.threadId,n=yield this.getMessageByPeer(i,t);this.close(e).then((()=>Dm(this,void 0,void 0,(function*(){if(d.Z.isMobile){const e=nn.getTab(en);e&&e.close()}_m.setInnerPeer({peerId:n.peerId,lastMsgId:t,type:s?"discussion":void 0,threadId:s})}))))}})),this.onDownloadClick=()=>Dm(this,void 0,void 0,(function*(){const{peerId:e,mid:t}=this.target,i=yield this.getMessageByPeer(e,t),s=(0,Se.Z)(i);s&&u.Z.downloadToDisc({media:s,queueId:_m.chat.bubbles.lazyLoadQueue.queueId})})),this.listLoader.onEmptied=()=>{this.close()},this.content.caption=document.createElement("div"),this.content.caption.classList.add("media-viewer-caption","message");const t=()=>{e&&clearTimeout(e),e=window.setTimeout((()=>{e=void 0,this.content.caption.classList.remove("is-focused")}),800)};this.content.caption.addEventListener("touchstart",(()=>{d.Z.isMobile&&(this.content.caption.classList.add("is-focused"),e&&(clearTimeout(e),e=void 0),document.addEventListener("touchend",t,{once:!0}))})),new m.ZP(this.content.caption).onAdditionalScroll=t,this.wholeDiv.append(this.content.caption),(0,n.fc)(this.buttons.delete,this.onDeleteClick);const i=[this.btnMenuForward={icon:"forward",text:"Forward",onClick:this.onForwardClick},this.btnMenuDownload={icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick},this.btnMenuDelete={icon:"delete danger",text:"Delete",onClick:this.onDeleteClick}];this.setBtnMenuToggle(i),this.setListeners()}get searchContext(){return this.listLoader.searchContext}setListeners(){super.setListeners(),(0,n.fc)(this.buttons.forward,this.onForwardClick),(0,n.fc)(this.author.container,this.onAuthorClick);const e=t=>{const i=(0,l.Z)(t.target,"A"),s=(0,r.Z)(t.target,"spoiler");if(i instanceof HTMLAnchorElement&&(!s||this.content.caption.classList.contains("is-spoiler-visible"))){const s=i.getAttribute("onclick");if(!s||s.includes("showMaskedAlert"))return;return(0,a.Z)(t),this.close().then((()=>{this.content.caption.removeEventListener("click",e,{capture:!0}),i.click()})),!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 i="";t&&(i=(0,ii.Z)(t,{entities:e.totalEntities})),(0,c.Z)(this.content.caption.firstElementChild,i),this.content.caption.classList.toggle("hide",!t)}setSearchContext(e){return this.listLoader.setSearchContext(e),this}openMedia(e,t,i=0,s=!1,n=[],a=[]){const o=Object.create(null,{_openMedia:{get:()=>super._openMedia}});return Dm(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;const r=e.mid,l=e.fwd_from&&!e.fromId?e.fwd_from.from_name:e.fromId,c=(0,Se.Z)(e),d="messageService"===e._||!this.managers.appMessagesManager.canForward(e);[this.buttons.forward,this.btnMenuForward.element].forEach((e=>{e.classList.toggle("hide",d)})),this.wholeDiv.classList.toggle("no-forwards",d);const h=d;[this.buttons.download,this.btnMenuDownload.element].forEach((e=>{e.classList.toggle("hide",h)}));const u=this.managers.appMessagesManager.canDeleteMessage(e);[this.buttons.delete,this.btnMenuDelete.element].forEach((e=>{e.classList.toggle("hide",!u)})),this.setCaption(e);const p=o._openMedia.call(this,c,e.date,l,i,t,s,n,a,e);return this.target.mid=r,this.target.peerId=e.peerId,p}))}static isMediaCompatibleForDocumentViewer(e){return"photo"===e._||o.Z.has(e.mime_type)}}class Bm extends As.Z{constructor(e){super(Object.assign(Object.assign({},e),{loadMore:(e,t,i)=>{if(this.peerId.isAnyChat()||!t)return Promise.resolve({count:0,items:[]});const s=null==e?void 0:e.photoId;return this.managers.appPhotosManager.getUserPhotos(this.peerId,s,i).then((e=>{const t=e.photos.map((e=>({element:null,photoId:e})));return{count:e.count,items:t}}))}})),this.loadedAllUp=!0,this.peerId=e.peerId}}var Nm=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class Um extends Fm{constructor(e){super(new Bm({peerId:e,managers:s.Z.managers}),[]),this.onPrevClick=e=>{this.openMedia(e.photoId,e.element,-1)},this.onNextClick=e=>{this.openMedia(e.photoId,e.element,1)},this.onDownloadClick=()=>Nm(this,void 0,void 0,(function*(){u.Z.downloadToDisc({media:yield this.managers.appPhotosManager.getPhoto(this.target.photoId),queueId:_m.chat.bubbles.lazyLoadQueue.queueId})})),this.peerId=e,this.setBtnMenuToggle([{icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick}]),this.setListeners()}openMedia(e,t,i=0,s,n){const a=Object.create(null,{_openMedia:{get:()=>super._openMedia}});return Nm(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;const o=yield this.managers.appPhotosManager.getPhoto(e),r=a._openMedia.call(this,o,o.date,this.peerId,i,t,!1,s,n);return this.target.photoId=o.id,r}))}}var Om=i(5880),Hm=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const zm=e=>{Array.from(document.querySelectorAll('avatar-element[data-peer-id="'+e+'"]')).forEach((e=>{e.update()}))};function Gm(e,t,i,n,a,o){return Hm(this,void 0,void 0,(function*(){let r=yield s.Z.managers.appProfileManager.getFullPhoto(t);if(!i()||!r)return;const l=()=>Array.from(e.querySelectorAll("img")).find((e=>!e.classList.contains("emoji")))?e:null;if(t.isAnyChat()){const e=!!n,c="inputMessagesFilterChatPhotos";if(!n&&(n=yield s.Z.managers.appMessagesManager.getSearch({peerId:t,inputFilter:{_:c},maxId:0,limit:1}).then((e=>e.history[0])),!i()))return;if(n){n.action.photo.id!==r.id&&(e||(n=s.Z.managers.appMessagesManager.generateFakeAvatarMessage(t,r)));const i=e=>e.map((e=>({element:e.element,mid:e.item.mid,peerId:e.item.peerId})));return void(new Rm).setSearchContext({peerId:t,inputFilter:{_:c}}).openMedia(n,l(),void 0,void 0,a?i(a):void 0,o?i(o):void 0)}}if(r){!(0,Om.Z)(n)&&n&&(r=yield s.Z.managers.appPhotosManager.getPhoto(n));const e=e=>e.map((e=>({element:e.element,photoId:e.item})));new Um(t).openMedia(r.id,l(),void 0,a?e(a):void 0,o?e(o):void 0)}}))}s.Z.addEventListener("avatar_update",zm),s.Z.addEventListener("peer_title_edit",(e=>Hm(void 0,void 0,void 0,(function*(){(yield s.Z.managers.appAvatarsManager.isAvatarCached(e))||zm(e)}))));const Vm=new Map,Km=new Set;class Wm extends HTMLElement{constructor(){super(...arguments),this.addedToQueue=!1}disconnectedCallback(){const e=Vm.get(this.peerId);e&&e.has(this)&&(e.delete(this),e.size||Vm.delete(this.peerId)),this.lazyLoadQueue&&this.lazyLoadQueue.unobserve(this)}attachClickEvent(){let e=!1;(0,n.fc)(this,(t=>Hm(this,void 0,void 0,(function*(){if((0,a.Z)(t),e)return;const i=this.peerId;e=!0,yield Gm(this,this.peerId,(()=>this.peerId===i)),e=!1}))))}updateOptions(e){for(const t in e)this[t]=e[t]}updateWithOptions(e){const t=this.peerId;this.updateOptions(e);const i=this.peerId;if(t!==i){if(this.peerId=i,this.dataset.peerId=""+i,t){const e=Vm.get(t);e&&(e.delete(this),e.size||Vm.delete(t))}return this.update()}}r(e=!1){const t=Hs(this,this.peerId,this.isDialog,this.peerTitle,e,this.isBig);return this.loadPromises&&(this.loadPromises.push(t),t.finally((()=>{this.loadPromises=void 0}))),t}update(){if(this.lazyLoadQueue){if(!Km.has(this.peerId)){if(this.addedToQueue)return;this.addedToQueue=!0;let e=Vm.get(this.peerId);return e||(e=new Set,Vm.set(this.peerId,e)),e.add(this),this.lazyLoadQueue.push({div:this,load:()=>(Km.add(this.peerId),this.update())}),this.r(!0)}this.addedToQueue&&this.lazyLoadQueue.unobserve(this)}Km.add(this.peerId);const e=this.r();this.addedToQueue&&e.finally((()=>{this.addedToQueue=!1}));const t=Vm.get(this.peerId);if(t){t.delete(this);const e=Array.from(t);Vm.delete(this.peerId);for(let t=0,i=e.length;t<i;++t)e[t].update()}return e}}customElements.define("avatar-element",Wm);var $m=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};class jm{constructor(e){this.managers=e,this.onArchiveClick=()=>$m(this,void 0,void 0,(function*(){const e=yield this.managers.appMessagesManager.getDialogOnly(this.selectedId);e&&this.managers.appMessagesManager.editPeerFolders([e.peerId],+!e.folder_id)})),this.onPinClick=()=>{this.managers.appMessagesManager.toggleDialogPin(this.selectedId,this.filterId).catch((e=>$m(this,void 0,void 0,(function*(){if("PINNED_DIALOGS_TOO_MUCH"===e.type)if(this.filterId>=1)Li({langPackKey:"PinFolderLimitReached"});else{const e=yield this.managers.apiManager.getConfig();new qi("pinned-dialogs-too-much",{buttons:[{langKey:"OK",isCancel:!0},{langKey:"FiltersSetupPinAlert",callback:()=>{Hr.createTab(pr).open()}}],descriptionLangKey:"PinToTopLimitReached2",descriptionLangArgs:[(0,v.ag)("Chats",[e.pinned_dialogs_count_max])]}).show()}}))))},this.onUnmuteClick=()=>{this.managers.appMessagesManager.togglePeerMute(this.selectedId,!1)},this.onMuteClick=()=>{new jd(this.selectedId)},this.onUnreadClick=()=>$m(this,void 0,void 0,(function*(){const e=this.selectedId,t=yield this.managers.appMessagesManager.getDialogOnly(e);t&&(t.unread_count?(this.managers.appMessagesManager.readHistory(e,t.top_message),this.managers.appMessagesManager.markDialogUnread(e,!0)):this.managers.appMessagesManager.markDialogUnread(e))})),this.onDeleteClick=()=>{new ws(this.selectedId)},this.onContextMenu=e=>{this.init&&(this.init(),this.init=null);let t=null;try{t=(0,l.Z)(e.target,dg)}catch(e){}if(t){if(e instanceof MouseEvent&&e.preventDefault(),this.element.classList.contains("active"))return!1;e instanceof MouseEvent&&(e.cancelBubble=!0),(()=>{$m(this,void 0,void 0,(function*(){this.filterId=gg.filterId,this.selectedId=t.dataset.peerId.toPeerId(),this.dialog=yield this.managers.appMessagesManager.getDialogOnly(this.selectedId),yield Promise.all(this.buttons.map((e=>$m(this,void 0,void 0,(function*(){const t=yield e.verify();e.element.classList.toggle("hide",!t)}))))),this.buttons[this.buttons.length-1].element.lastChild.replaceWith((0,v.ag)(yield this.managers.appPeersManager.getDeleteButtonText(this.selectedId))),t.classList.add("menu-open"),xi(e,this.element),Ii.openBtnMenu(this.element,(()=>{t.classList.remove("menu-open"),this.selectedId=this.dialog=this.filterId=void 0}))}))})()}}}init(){this.buttons=[{icon:"unread",text:"MarkAsUnread",onClick:this.onUnreadClick,verify:()=>$m(this,void 0,void 0,(function*(){return!(yield 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:()=>$m(this,void 0,void 0,(function*(){var e;return!(this.filterId>1?(yield this.managers.appMessagesManager.getFilter(this.filterId)).pinnedPeerIds.includes(this.dialog.peerId):null===(e=this.dialog.pFlags)||void 0===e?void 0:e.pinned)}))},{icon:"unpin",text:"ChatList.Context.Unpin",onClick:this.onPinClick,verify:()=>$m(this,void 0,void 0,(function*(){var e;return this.filterId>1?(yield this.managers.appMessagesManager.getFilter(this.filterId)).pinnedPeerIds.includes(this.dialog.peerId):!!(null===(e=this.dialog.pFlags)||void 0===e?void 0:e.pinned)}))},{icon:"mute",text:"ChatList.Context.Mute",onClick:this.onMuteClick,verify:()=>$m(this,void 0,void 0,(function*(){return this.selectedId!==s.Z.myId&&!(yield this.managers.appNotificationsManager.isPeerLocalMuted(this.dialog.peerId))}))},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:this.onUnmuteClick,verify:()=>$m(this,void 0,void 0,(function*(){return this.selectedId!==s.Z.myId&&(yield this.managers.appNotificationsManager.isPeerLocalMuted(this.dialog.peerId))}))},{icon:"archive",text:"Archive",onClick:this.onArchiveClick,verify:()=>0===this.filterId&&this.selectedId!==s.Z.myId},{icon:"unarchive",text:"Unarchive",onClick:this.onArchiveClick,verify:()=>1===this.filterId&&this.selectedId!==s.Z.myId},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>!0}],this.element=Ei(this.buttons),this.element.id="dialogs-contextmenu",this.element.classList.add("contextmenu"),document.getElementById("page-chats").append(this.element)}}var qm,Qm=i(9174);class Ym{constructor(e,t){this.managers=e,this.hadConnect=!1,this.connecting=!1,this.timedOut=!1,this.updating=!1,this.setConnectionStatus=()=>{Promise.all([Ar.Z.get("dc"),s.Z.managers.rootScope.getConnectionStatus()]).then((([e,t])=>{e||(e=_r.Z.baseDcId),this.setFirstConnectionTimeout&&(clearTimeout(this.setFirstConnectionTimeout),this.setFirstConnectionTimeout=0);const i=t["NET-"+e],s=i&&i.status===Qm.Q.Connected;this.connecting&&s&&this.managers.apiUpdatesManager.forceGetDifference(),s&&!this.hadConnect&&(this.hadConnect=!0),this.timedOut=i&&i.status===Qm.Q.TimedOut,this.connecting=!s,this.retryAt=i&&i.retryAt,R.ZP&&this.log("connecting",this.connecting),this.setState()}))},this.setStatusText=(e,t)=>{this.currentLangPackKey!==e&&(this.currentLangPackKey=e,(0,g.Z)(this.statusEl,(0,v.ag)(e,t)),this.statusPreloader.attach(this.statusEl))},this.setState=()=>{if(qu.Z.deactivatedReason)return;const e=Ym.CHANGE_STATE_DELAY;if(this.connecting)if(this.timedOut){const e=this.getA("ConnectionStatus.ForceReconnect",(()=>this.managers.networkerFactory.forceReconnect()));this.setStatusText("ConnectionStatus.TimedOut",[e])}else if(this.hadConnect)if(void 0!==this.retryAt){const e=document.createElement("span"),t=this.retryAt,i=()=>{const i=Date.now();e.innerText=""+Math.round((t-i)/1e3),i>t&&clearInterval(s)},s=setInterval(i,1e3);i();const n=this.getA("ConnectionStatus.Reconnect",(()=>this.managers.networkerFactory.forceReconnectTimeout()));this.setStatusText("ConnectionStatus.ReconnectIn",[e,n])}else this.setStatusText("ConnectionStatus.Reconnecting");else this.setStatusText("ConnectionStatus.Waiting");else this.updating&&this.setStatusText("Updating");R.ZP&&this.log("setState",this.connecting||this.updating),window.requestAnimationFrame((()=>{this.setStateTimeout&&clearTimeout(this.setStateTimeout),this.setStateTimeout=window.setTimeout((()=>{Re(this.statusContainer,"is-shown",this.connecting||this.updating,200),this.setStateTimeout=0,R.ZP&&this.log("setState: isShown:",this.connecting||this.updating)}),e)}))},this.log=(0,he.kg)("CS",void 0,void 0),this.statusContainer=document.createElement("div"),this.statusContainer.classList.add("connection-status"),this.statusEl=(0,M.Z)("btn-primary bg-warning connection-status-button",{noRipple:!0}),this.statusPreloader=new Ue({cancelable:!1}),this.statusPreloader.constructContainer({color:"transparent",bold:!0}),this.statusContainer.append(this.statusEl),t.prepend(this.statusContainer),s.Z.addEventListener("connection_status_change",(e=>{this.setConnectionStatus()})),s.Z.addEventListener("state_synchronizing",(e=>{e||(this.updating=!0,R.ZP&&this.log("updating",this.updating),this.setState())})),s.Z.addEventListener("state_synchronized",(e=>{R.ZP&&this.log("state_synchronized",e),e||(this.updating=!1,R.ZP&&this.log("updating",this.updating),this.setState())})),this.setFirstConnectionTimeout=window.setTimeout(this.setConnectionStatus,Ym.CHANGE_STATE_DELAY+1e3)}getA(e,t){const i=document.createElement("a");return i.classList.add("force-reconnect"),i.append((0,v.ag)(e)),(0,n.fc)(i,(e=>{(0,a.Z)(e),t()})),i}}function Jm(e,t,i,s){return e>=s?t+i:-i/2*(Math.cos(Math.PI*e/s)-1)+t}function Xm(e,t,i,s,n,a,o,r){const l=e.canvas.dpr;if(l&&(t*=l,i*=l,s*=l,n*=l),"number"==typeof a)l&&(a*=l),a={tl:a,tr:a,br:a,bl:a};else{const e={tl:0,tr:0,br:0,bl:0};for(const t in e)a[t]=a[t]?l?a[t]*l:a[t]:e[t]}e.beginPath(),e.moveTo(t+a.tl,i),e.lineTo(t+s-a.tr,i),e.quadraticCurveTo(t+s,i,t+s,i+a.tr),e.lineTo(t+s,i+n-a.br),e.quadraticCurveTo(t+s,i+n,t+s-a.br,i+n),e.lineTo(t+a.bl,i+n),e.quadraticCurveTo(t,i+n,t,i+n-a.bl),e.lineTo(t,i+a.tl),e.quadraticCurveTo(t,i,t+a.tl,i),e.closePath(),o&&e.fill(),r&&e.stroke()}Ym.CHANGE_STATE_DELAY=1e3,function(e){e[e.Error=-1]="Error",e[e.Pending=0]="Pending",e[e.Sent=1]="Sent",e[e.Read=2]="Read"}(qm||(qm={}));const eg=window.devicePixelRatio,tg=20*eg,ig=2.5*eg,sg=2*eg,ng=1*eg;var ag=i(3385),og=i(2554);class rg{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];return"glow"===e?this.animateGlow():"slide"===e?this.animateSlide():void console.log("unknown animation type: "+String(e))}animateGlow(){var e=68;return()=>{var t=this.diffTime/(1e3/60)*10;return this.paused?Date.now()-this.pausedTime>800&&(e=68,this.cycleAnimation(),this.paused=!1):(e=parseInt(""+(e+t)))>=255&&(this.paused=!0,this.pausedTime=Date.now()),"rgb("+e+","+e+","+e+")"}}animateSlide(){var e,t,i,s=this.ctx.createLinearGradient(0,0,this.canvas.width,0),n=this.inc*(this.diffTime/(1e3/60));if(this.paused){if(Date.now()-this.pausedTime>this.pauseInterval)return this.lightSource=-.6,this.cycleAnimation(),this.paused=!1,this.animateSlide()}else this.lightSource+=n,this.lightSource>1+this.lightSpread&&(this.paused=!0,this.pausedTime=Date.now());i=(0,Me.Z)(this.lightSource,0,1),e=(0,Me.Z)(this.lightSource-this.lightSpread,0,1),t=(0,Me.Z)(this.lightSource+this.lightSpread,0,1);const a=tp.getProperty("background-color-true"),o=tp.getProperty("surface-color");return s.addColorStop(e,a),s.addColorStop(i,o),s.addColorStop(t,a),s}settings(e={}){var t,i,s,n,a,o;this.canvas=null!==(t=e.canvas)&&void 0!==t?t:document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),this.font=null!==(i=e.font)&&void 0!==i?i:this.font,this.lightSpread=null!==(s=e.lightSpread)&&void 0!==s?s:this.lightSpread,this.inc=null!==(n=e.inc)&&void 0!==n?n:this.inc,this.animations=null!==(a=e.animations)&&void 0!==a?a:this.animations,this.text=null!==(o=e.text)&&void 0!==o?o: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 lg{constructor(){this.onThemeChange=()=>{this.stopAnimation(),this.startAnimation()},this.onResize=()=>{const{canvas:e}=this,{width:t,height:i,dpr:s}=e;this.updateCanvasSize(),e.width===t&&e.height===i&&e.dpr===s||(this.stopAnimation(),this.startAnimation())},this.shimmer=new rg,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=54,this.marginVertical=9,this.lineHeight=10,this.lineBorderRadius=6,this.lineMarginVertical=8,this.statusWidth=24}attach({container:e,rect:t,getRectFrom:i,onRemove:s,blockScrollable:n}){const{canvas:a}=this;this.onRemove=s,this.getRectFrom=i||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(),s.Z.settings.animationsEnabled||this.remove())}remove(){this.stopAnimation(),this.canvas.parentElement&&(this.canvas.remove(),this.onRemove&&(this.onRemove(),this.onRemove=void 0),this.blockScrollable&&(this.blockScrollable.container.style.overflowY="",this.blockScrollable=void 0))}updateCanvasSize(e=this.getRectFrom.getBoundingClientRect()){const{canvas:t}=this,i=t.dpr=window.devicePixelRatio;t.width=e.width*i,t.height=e.height*i,t.style.width=e.width+"px",t.style.height=e.height+"px"}renderDetachAnimationFrame(){const{canvas:e,ctx:t,detachTime:i,length:n,availableLength:a}=this;if(!i)return;if(!s.Z.settings.animationsEnabled)return void this.remove();const{width:o}=e;t.globalCompositeOperation="destination-out";const r=Date.now()-i;let l=!0;for(let e=0;e<n;++e){const i=r-(a<n&&e>=a?15*(a-1):15*e);if(i<=0){l=!1;continue}const s=Jm(i,0,1,150);t.beginPath(),t.rect(0,this.dialogHeight*e,o,this.dialogHeight),t.fillStyle=`rgba(0, 0, 0, ${s})`,t.fill(),s<1&&(l=!1)}t.globalCompositeOperation="source-over",l&&this.remove()}renderFrame(){this.shimmer.on(),this.renderDetachAnimationFrame()}startAnimation(){const{canvas:e,shimmer:t}=this,i=++this.tempId,n=this.createPattern();t.settings({canvas:e,fillStyle:n});const a=()=>this.tempId===i;this.renderFrame(),(0,ht.jt)((()=>!!a()&&(s.Z.settings.animationsEnabled&&this.renderFrame(),a()))),s.Z.addEventListener("theme_change",this.onThemeChange),d.Z.addEventListener("resize",this.onResize)}stopAnimation(){++this.tempId,s.Z.removeEventListener("theme_change",this.onThemeChange),d.Z.removeEventListener("resize",this.onResize)}createPattern(){const{canvas:e,ctx:t}=this,i=document.createElement("canvas"),s=i.getContext("2d"),n=e.dpr;i.dpr=n,i.width=e.width,i.height=e.height,s.fillStyle=tp.getProperty("surface-color"),s.fillRect(0,0,i.width,i.height),s.fillStyle="#000",s.globalCompositeOperation="destination-out";const a=this.dialogHeight=(this.avatarSize+2*this.marginVertical)*n,o=this.length=Math.ceil(e.height/a);for(let e=0;e<o;++e)this.drawChat(s,e,e*a);return t.createPattern(i,"no-repeat")}drawChat(e,t,i){let s=this.generatedValues[t];s||(s=this.generatedValues[t]={firstLineWidth:40+100*Math.random(),secondLineWidth:120+130*Math.random(),statusWidth:24+16*Math.random()});const{firstLineWidth:n,secondLineWidth:a,statusWidth:o}=s,{canvas:r}=e,{dpr:l}=r;i/=l;const{avatarSize:c,marginVertical:d,lineHeight:h,lineBorderRadius:u,lineMarginVertical:p}=this;let m=17;(function(e,t,i,s,n,a){(function(e,t,i,s,n,a){const o=e.canvas.dpr;o&&(t*=o,i*=o,s*=o),e.beginPath(),e.arc(t,i,s,0,2*Math.PI,!1),e.closePath(),n&&e.fill(),a&&e.stroke()})(e,t+s,i+s,s,n,a)})(e,m,i+d,c/2,!0),m+=c+10,Xm(e,m,i+d+p,n,h,u,!0),Xm(e,m,i+d+c-h-p,a,h,u,!0),Xm(e,r.width/l-24-o,i+d+p,o,h,u,!0)}}var cg=function(e,t,i,s){return new(i||(i=Promise))((function(n,a){function o(e){try{l(s.next(e))}catch(e){a(e)}}function r(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}l((s=s.apply(e,t||[])).next())}))};const dg="A";function hg(e,t){const i=e[t];i&&i.reject();const s=e[t]=(0,Oe.Z)();s.catch((()=>{})).finally((()=>{e[t]===s&&delete e[t]}));const n=hl((()=>e[t]===s));return{deferred:s,middleware:n}}class ug extends za{constructor(e,t,i,s){super({getIndex:t=>e.dialogsStorage.getDialogIndex(t.id,this.indexKey),onDelete:e=>{e.dom.listEl.remove(),this.onListLengthChange&&this.onListLengthChange()},onSort:(e,t)=>{const i=e.dom.listEl.parentElement!==this.list;Ln(e.dom.listEl,this.list,t),i&&this.onListLengthChange&&this.onListLengthChange()},onElementCreate:(e,t)=>{const i=t?[]:void 0,{dom:s}=mg.addListDialog({peerId:e.id,loadPromises:i,isBatch:t});return e.dom=s,(null==i?void 0:i.length)&&(e.loadPromises=i,Promise.all(i).finally((()=>{delete e.loadPromises}))),e},updateElementWith:Be.TR}),this.managers=e,this.list=t,this.indexKey=i,this.onListLengthChange=s}clear(){this.list.textContent="",super.clear()}}class pg{constructor(){this.chatsContainer=document.getElementById("chatlist-container"),this.scroll=null,this.log=(0,he.kg)("DIALOGS",he.v9.Log|he.v9.Error|he.v9.Warn|he.v9.Debug),this.placeholders={},this.sortedLists={},this.scrollables={},this.folders={menu:document.getElementById("folders-tabs"),menuScrollContainer:null,container:document.getElementById("folders-container")},this.filtersRendered={},this.lastActiveElements=new Set,this.offsets={top:0,bottom:0},this.initedListeners=!1,this.loadedDialogsAtLeastOnce=!1,this.onTabChange=()=>(this.scroll=this.scrollables[this.filterId],this.scroll.loadedAll.top=!0,this.scroll.loadedAll.bottom=!1,this.offsets.top=this.offsets.bottom=0,this.loadDialogsRenderPromise=void 0,this.loadDialogsPromise=void 0,this.sortedList=this.sortedLists[this.filterId],this.onChatsScroll()),this._onListLengthChange=()=>{if(!this.loadedDialogsAtLeastOnce)return;if(this.checkIfPlaceholderNeeded(),this.filterId!==le.J$)return;const e=this.chatList,t=e.childElementCount,i=e.parentElement.parentElement,s=e.parentElement.nextElementSibling,n=!!s.childElementCount;if(t>=10)return void(n&&this.removeContactsPlaceholder());if(n)return;i.classList.add("with-contacts");const a=new Br({name:"Contacts",noDelimiter:!0,fakeGradientDelimiter:!0});a.container.classList.add("hide"),this.managers.appUsersManager.getContactsPeerIds(void 0,void 0,"online").then((e=>{let t=!1;const i=()=>{t&&a.container.classList.toggle("hide",!s.list.childElementCount),this.updateContactsLength(!0)},s=new Va({avatarSize:42,createChatListOptions:{dialogSize:48,new:!0},autonomous:!1,onListLengthChange:i,managers:this.managers});this.loadContacts=()=>{const t=as.height/60|0;ki(e.splice(0,t),this.verifyPeerIdForContacts).then((e=>{e.forEach((e=>{s.add(e)}))})),e.length||(this.loadContacts=void 0)},this.loadContacts(),this.processContact=e=>cg(this,void 0,void 0,(function*(){if(e.isAnyChat())return;const t=yield this.verifyPeerIdForContacts(e),i=s.has(e);!i&&t?s.add(e):i&&!t&&s.delete(e)}));const n=s.list;n.classList.add("chatlist-new"),this.setListClickListener(n),a.content.append(n),t=!0,i()})),s.append(a.container)},this.verifyPeerIdForContacts=e=>cg(this,void 0,void 0,(function*(){return(yield this.managers.appPeersManager.isContact(e))&&!(yield this.managers.appMessagesManager.getDialogOnly(e))})),this.onChatsRegularScroll=()=>{this.sliceTimeout&&clearTimeout(this.sliceTimeout),this.sliceTimeout=window.setTimeout((()=>{this.sliceTimeout=void 0,this.chatList.childElementCount&&!this.processContact&&(0,Be.TR)((()=>{const e=performance.now(),t=this.scroll.scrollTop,i=this.chatList.firstElementChild,s=this.scroll.container.getBoundingClientRect(),n=i.getBoundingClientRect(),a=Array.from(this.scroll.splitUp.children);let o=this.scroll.splitUp.offsetTop;o&&t<o&&(o-=t);const r=s.y+o,c=s.y,d=(0,l.Z)(document.elementFromPoint(Math.ceil(n.x),Math.ceil(r+1)),i.tagName),h=(0,l.Z)(document.elementFromPoint(Math.ceil(n.x),Math.floor(c+s.height-1)),i.tagName);if(!d||!h)return;const u=d.getBoundingClientRect().y-r,p=[],m=a.indexOf(d),g=a.indexOf(h),v=Je.IS_SAFARI?[]:a.slice(0,Math.max(0,m-10)),f=a.slice(g+10);v.length&&(this.scroll.loadedAll.top=!1),f.length&&(this.scroll.loadedAll.bottom=!1),p.push(...v),p.push(...f),p.forEach((e=>{const t=e.dataset.peerId.toPeerId();this.deleteDialog(t)})),this.setOffsets(),this.scroll.scrollTop=d.offsetTop-u,this.log("slice time",performance.now()-e)}))}),200)},this.onChatsScrollTop=()=>this.onChatsScroll("top"),this.onChatsScroll=(e="bottom")=>(this.scroll.loadedAll[e]&&this.loadContacts&&this.loadContacts(),this.log("onChatsScroll",e),this.loadDialogs(e));const e=this.managers=(0,og.Z)();this.contextMenu=new jm(e),this.folders.menuScrollContainer=this.folders.menu.parentElement,this.onListLengthChange=(0,Ki.Z)(this._onListLengthChange,100,!1,!0);const t=document.createElement("div");t.classList.add("connection-status-bottom"),t.append(this.folders.container),gi.Z&&$a({element:this.folders.container,onSwipe:e=>{const t=n.prevId();n(e>0?t+1:t-1)}}),this.allChatsIntlElement=new v.ZP.IntlElement({key:"FilterAllChatsShort"}),s.Z.addEventListener("premium_toggle",(e=>cg(this,void 0,void 0,(function*(){e||(yield this.managers.filtersStorage.isFilterIdAvailable(this.filterId))||n((0,Cn.Z)(this.filtersRendered[le.J$].menu),!1)})))),s.Z.addEventListener("state_cleared",(()=>{const e=le.DZ.has(this.filterId);Gi.Z.getState().then((t=>cg(this,void 0,void 0,(function*(){this.loadedDialogsAtLeastOnce=!1,e&&(this.sortedList.clear(),this.onTabChange()),this.onStateLoaded(t)}))))})),this.setFilterId(le.J$,le.J$),this.addFilter({id:le.J$,title:"",localId:le.J$});const i=new m.v7(this.folders.menuScrollContainer);t.prepend(this.folders.menuScrollContainer);const n=this.selectTab=(0,ue.X)(this.folders.menu,this.folders.container,((e,t)=>cg(this,void 0,void 0,(function*(){const i=e;if(e=+t.dataset.filterId||le.J$,!le.DZ.has(e)&&!(yield this.managers.filtersStorage.isFilterIdAvailable(e)))return!1;const s=this.filterId;if(Je.IS_MOBILE_SAFARI||(i?this.filtersNavigationItem||(this.filtersNavigationItem={type:"filters",onPop:()=>{n(0),this.filtersNavigationItem=void 0}},C.Z.spliceItems(1,0,this.filtersNavigationItem)):this.filtersNavigationItem&&(C.Z.removeItem(this.filtersNavigationItem),this.filtersNavigationItem=void 0)),s===e)return;this.sortedLists[e].clear();const a=this.setFilterIdAndChangeTab(e).then((({cached:e,renderPromise:t})=>{if(e)return t}));return-1!==s?a:void 0}))),(()=>{for(const e in this.sortedLists)if(+e!==this.filterId){this.sortedLists[e].clear();const t=this.placeholders[e];t&&t.remove()}}),void 0,i);Gi.Z.getState().then((e=>(vt.Z.setPlaybackParams(e.playbackParams),vt.Z.addEventListener("playbackParams",(e=>{this.managers.appStateManager.pushToState("playbackParams",e)})),this.onStateLoaded(e)))),d.Z.addEventListener("resize",(()=>{this.changeFiltersAllChatsKey()})),new Ym(this.managers,this.chatsContainer),this.chatsContainer.append(t),setTimeout((()=>{hi.Z.loadLottieWorkers()}),200),A.Z.MANAGERS=s.Z.managers=e,u.Z.construct(e),Hr.construct(e),nn.construct(e),Fu.construct(e),em.construct(e),_m.construct(e),this.sortedList=this.sortedLists[this.filterId],this.scroll=this.scrollables[this.filterId]}get chatList(){return this.sortedList.list}setFilterId(e,t){this.filterId=e,this.indexKey=(0,ag.Z)(le.DZ.has(e)?e:t)}setFilterIdAndChangeTab(e){return cg(this,void 0,void 0,(function*(){return this.filterId=e,this.indexKey=yield this.managers.dialogsStorage.getDialogIndexKeyByFilterId(e),this.onTabChange()}))}setOnlineStatus(e,t){const i="is-online",s=e.classList.contains(i);!s&&t&&e.classList.add(i),Re(e,"is-visible",t,250,t?void 0:()=>{e.classList.remove(i)},t&&!s?2:0)}initListeners(){s.Z.addEventListener("user_update",(e=>cg(this,void 0,void 0,(function*(){var t;const i=e.toPeerId(),n=this.getDialogDom(i);if(n&&i!==s.Z.myId&&!(yield this.managers.appUsersManager.isBot(e))){const i="userStatusOnline"===(null===(t=(yield this.managers.appUsersManager.getUser(e)).status)||void 0===t?void 0:t._);this.setOnlineStatus(n.avatarEl,i)}})))),s.Z.addEventListener("chat_update",(e=>cg(this,void 0,void 0,(function*(){const t=e.toPeerId(!0),i=yield this.managers.appMessagesManager.getDialogOnly(t);i&&this.processDialogForCallStatus(i)})))),s.Z.addEventListener("folder_unread",(e=>{this.setFilterUnreadCount(e.id)})),s.Z.addEventListener("contacts_update",(e=>{this.processContact&&this.processContact(e.toPeerId())})),s.Z.addEventListener("dialog_flush",(({dialog:e})=>{e&&(this.setLastMessageN({dialog:e,setUnread:!0}),this.validateDialogForFilter(e),this.setFiltersUnreadCount())})),s.Z.addEventListener("dialogs_multiupdate",(e=>{for(const[t,i]of e)this.updateDialog(i),this.processContact&&this.processContact(t.toPeerId()),this.validateDialogForFilter(i)})),s.Z.addEventListener("dialog_drop",(({peerId:e})=>{this.deleteDialog(e),this.processContact&&this.processContact(e)})),s.Z.addEventListener("dialog_unread",(({dialog:e})=>{e&&(this.setUnreadMessagesN({dialog:e}),this.validateDialogForFilter(e))})),s.Z.addEventListener("dialog_notify_settings",(e=>{this.validateDialogForFilter(e),this.setUnreadMessagesN({dialog:e})})),s.Z.addEventListener("dialog_draft",(({dialog:e,drop:t,peerId:i})=>{t?this.sortedList.delete(i):this.updateDialog(e),this.processContact&&this.processContact(i)})),_m.addEventListener("peer_changed",(e=>{for(const t of this.lastActiveElements)t.dataset.peerId.toPeerId()!==e&&this.setDialogActive(t,!1);Array.from(document.querySelectorAll(`[data-autonomous="0"] .chatlist-chat[data-peer-id="${e}"]`)).forEach((e=>{this.setDialogActive(e,!0)}))})),s.Z.addEventListener("filter_update",(e=>cg(this,void 0,void 0,(function*(){if(le.DZ.has(e.id))return;if(!this.filtersRendered[e.id])return void this.addFilter(e);if(e.id===this.filterId){const e=yield this.managers.dialogsStorage.getCachedDialogs(!0);yield this.validateListForFilter();for(let t=0,i=e.length;t<i;++t){const i=e[t];this.updateDialog(i)}}const t=this.filtersRendered[e.id];(0,c.Z)(t.title,(0,Zt.Z)(e.title))})))),s.Z.addEventListener("filter_delete",(e=>{const t=this.filtersRendered[e.id];t&&(t.container.remove(),t.menu.remove(),delete this.sortedLists[e.id],delete this.scrollables[e.id],delete this.filtersRendered[e.id],this.onFiltersLengthChange(),this.filterId===e.id&&this.selectTab(0,!1))})),s.Z.addEventListener("filter_order",(e=>cg(this,void 0,void 0,(function*(){e=e.slice(),(0,T.Z)(e,le.Zi);const t=this.folders.menu,i=yield Promise.all(e.map((e=>cg(this,void 0,void 0,(function*(){return{indexKey:yield this.managers.dialogsStorage.getDialogIndexKeyByFilterId(e),filter:yield this.managers.filtersStorage.getFilter(e)}})))));e.forEach(((e,s)=>{const{indexKey:n,filter:a}=i[s],o=this.filtersRendered[e];this.sortedLists[e].indexKey=n,Ln(o.menu,t,a.localId),Ln(o.container,this.folders.container,a.localId)})),this.indexKey=yield this.managers.dialogsStorage.getDialogIndexKeyByFilterId(this.filterId)})))),s.Z.addEventListener("peer_typings",(({peerId:e,typings:t})=>cg(this,void 0,void 0,(function*(){const i=yield this.managers.appMessagesManager.getDialogOnly(e);i&&(t.length?this.setTyping(i):this.unsetTyping(i))}))))}setDialogActive(e,t){const i=e.dialogDom;e.classList.toggle("active",t),t?this.lastActiveElements.add(e):this.lastActiveElements.delete(e),(null==i?void 0:i.callIcon)&&i.callIcon.setActive(t)}onStateLoaded(e){return cg(this,void 0,void 0,(function*(){const t=e.filtersArr,i=t.length>le.DZ.size,s=e=>{for(const t of e)this.addFilter(t)};let n;i?s(t):n=this.managers.filtersStorage.getDialogFilters().then(s);const a=this.onChatsScroll();yield a,this.loadDialogsRenderPromise=void 0,n&&(yield n),this.filterId=-1,this.selectTab(0,!1),this.initedListeners||(this.initListeners(),this.initedListeners=!0),i&&this.showFiltersPromise&&(yield this.showFiltersPromise),this.managers.appNotificationsManager.getNotifyPeerTypeSettings(),yield(yield a).renderPromise.catch(ft.Z),this.managers.appMessagesManager.fillConversations()}))}getOffsetIndex(e){return{index:this.scroll.loadedAll[e]?0:this.offsets[e]}}isDialogMustBeInViewport(e){if(void 0!==e.migratedTo||!this.testDialogForFilter(e))return!1;const t=this.getOffsetIndex("top"),i=this.getOffsetIndex("bottom");if(!t.index&&!i.index)return!0;const s=(0,hs.Z)(e,this.indexKey);return(!t.index||s<=t.index)&&(!i.index||s>=i.index)}deleteDialog(e){this.sortedList.delete(e)}updateDialog(e){if(!this.isDialogMustBeInViewport(e))return void this.deleteDialog(e.peerId);if(!this.sortedList.has(e.peerId))return void this.sortedList.add(e.peerId);const t=this.getDialogDom(e.peerId);t&&(this.setLastMessageN({dialog:e,dom:t,setUnread:!0}),this.sortedList.update(e.peerId))}setFilterUnreadCount(e){var t;return cg(this,void 0,void 0,(function*(){if(e===le.J$)return;const i=null===(t=this.filtersRendered[e])||void 0===t?void 0:t.unread;if(!i)return;const{unreadUnmutedCount:s,unreadCount:n}=yield this.managers.dialogsStorage.getFolderUnreadCount(e);i.classList.toggle("badge-gray",!s),i.innerText=n?""+n:""}))}setFiltersUnreadCount(){for(const e in this.filtersRendered)this.setFilterUnreadCount(+e)}validateListForFilter(){return cg(this,void 0,void 0,(function*(){this.sortedList.getAll().forEach((e=>cg(this,void 0,void 0,(function*(){const t=yield this.managers.appMessagesManager.getDialogOnly(e.id);this.testDialogForFilter(t)||this.deleteDialog(e.id)}))))}))}validateDialogForFilter(e){this.getDialogDom(e.peerId)&&(this.testDialogForFilter(e)||this.deleteDialog(e.peerId))}testDialogForFilter(e){return!(!e||(le.DZ.has(this.filterId)?this.filterId!==e.folder_id:void 0===(0,hs.Z)(e,this.indexKey)))}generateScrollable(e,t){const i=t.id,s=new m.ZP(null,"CL",500);s.container.addEventListener("scroll",this.onChatsRegularScroll),s.container.dataset.filterId=""+i,s.onScrolledTop=this.onChatsScrollTop,s.onScrolledBottom=this.onChatsScroll,s.setVirtualContainer(e);const n=new ug(this.managers,e,(0,ag.Z)(t.localId),this.onListLengthChange);return this.scrollables[i]=s,this.sortedLists[i]=n,s}addFilter(e){if(e.id===le.Zi)return;const t=this.folders.menu,i=this.filtersRendered[e.id];if(i)return Ln(i.menu,t,e.localId),void Ln(i.container,this.folders.container,e.localId);const s=document.createElement("div");s.classList.add("menu-horizontal-div-item");const n=document.createElement("span"),a=document.createElement("span");a.classList.add("text-super"),e.id===le.J$?a.append(this.allChatsIntlElement.element):(0,c.Z)(a,(0,Zt.Z)(e.title));const o=document.createElement("div");o.classList.add("badge","badge-20","badge-primary");const r=document.createElement("i");n.append(a,o,r),(0,we.Z)(s),s.append(n),s.dataset.filterId=""+e.id,Ln(s,t,e.localId);const l=this.createChatList(),d=this.generateScrollable(l,e);d.container.classList.add("tabs-tab","chatlist-parts");const h=document.createElement("div");h.classList.add("chatlist-top");const u=document.createElement("div");u.classList.add("chatlist-bottom"),h.append(l),d.container.append(h,u);const p=d.container;Ln(d.container,this.folders.container,e.localId),this.setListClickListener(l,null,!0),this.filtersRendered[e.id]={menu:s,container:p,unread:o,title:a},this.onFiltersLengthChange()}changeFiltersAllChatsKey(){const e=this.folders.menuScrollContainer.firstElementChild,t=e.scrollWidth>e.clientWidth?"FilterAllChatsShort":"FilterAllChats";this.allChatsIntlElement.compareAndUpdate({key:t})}onFiltersLengthChange(){return this.showFiltersPromise||(this.showFiltersPromise=new Promise((e=>{window.setTimeout((()=>{const t=Object.keys(this.filtersRendered).length>1,i=!this.folders.menuScrollContainer.classList.contains("hide");t!==i&&(this.folders.menuScrollContainer.classList.toggle("hide",!t),t&&!i&&this.setFiltersUnreadCount(),this.chatsContainer.classList.toggle("has-filters",t)),this.changeFiltersAllChatsKey(),this.showFiltersPromise=void 0,e()}),0)}))),this.showFiltersPromise}loadDialogs(e){if(this.log.warn("load",e),this.loadDialogsPromise||this.loadDialogsRenderPromise)return this.loadDialogsPromise;if(this.scroll.loadedAll[e])return Promise.resolve({cached:!0,renderPromise:Promise.resolve()});const t=(0,Oe.Z)(),i=new Promise(((s,n)=>cg(this,void 0,void 0,(function*(){const{chatList:a,filterId:o,indexKey:r}=this;let l=as.height/72*1.25|0,c=0;const{index:d}=this.getOffsetIndex(e);if(d)if("top"===e){const e=yield this.managers.dialogsStorage.getFolderDialogs(o,!0),t=e.findIndex((e=>(0,hs.Z)(e,r)<=d)),i=Math.max(0,t-l);l=t-i,c=(0,hs.Z)(e[i],r)+1}else c=d;let h=this.placeholders[o];try{const s=this.managers.acknowledged.appMessagesManager.getConversations("",c,l,o,!0);if(!(a.childElementCount||h||this.loadedDialogsAtLeastOnce&&(yield s).cached)){h=this.placeholders[o]=new lg;const e=o===le.Zi?this.chatsContainer:this.folders.container;h.attach({container:a.parentElement,getRectFrom:e,onRemove:()=>{delete this.placeholders[o]},blockScrollable:this.scroll}),t.resolve(!1)}const d=yield s,u=yield d.result;if(this.loadDialogsRenderPromise!==i)return n(),void t.reject();if(t.resolve(d.cached),"bottom"===e?u.isEnd&&(this.scroll.loadedAll[e]=!0):u.isTopEnd&&(this.scroll.loadedAll[e]=!0),this.loadedDialogsAtLeastOnce=!0,u.dialogs.length){const s="top"===e?u.dialogs.slice().reverse():u.dialogs,a=[],o=[],r=e=>{o.push(e)};if(s.forEach((e=>{const t=this.sortedList.add(e.peerId,!0,r,!1);t.loadPromises&&a.push(...t.loadPromises)})),a.push((0,Be.AD)()),yield Promise.all(a).finally(),this.loadDialogsRenderPromise!==i)return n(),void t.reject();o.forEach((e=>e()))}else this.onListLengthChange();const p=u.dialogs["top"===e?0:u.dialogs.length-1];p&&(this.offsets[e]=(0,hs.Z)(p,r)),this.log.debug("getDialogs "+l+" dialogs by offset:",c,u,a.childElementCount),setTimeout((()=>{this.scroll.onScroll()}),0)}catch(e){this.log.error(e)}h&&h.detach(a.childElementCount),s()})))).finally((()=>{this.loadDialogsRenderPromise===i&&(this.loadDialogsRenderPromise=void 0,this.loadDialogsPromise=void 0)}));return this.loadDialogsRenderPromise=i,this.loadDialogsPromise=t.then((e=>({cached:e,renderPromise:i})))}generateEmptyPlaceholder(e){const t="empty-placeholder",i=document.createElement("div");i.classList.add(t,t+"-"+e.classNameType);const s=document.createElement("div");s.classList.add(t+"-header"),(0,v.$d)(s,e.title);const n=document.createElement("div");return n.classList.add(t+"-subtitle"),e.subtitle&&(0,v.$d)(n,e.subtitle,e.subtitleArgs),i.append(s,n),{container:i,header:s,subtitle:n}}checkIfPlaceholderNeeded(){if(this.filterId===le.Zi)return;const e=this.chatList,t=e.parentElement;let i=Array.from(t.children).find((e=>e.matches(".empty-placeholder")));const s=this.scroll.loadedAll.bottom&&!e.childElementCount;if(s&&i)return;if(!s)return void(i&&(t.classList.remove("with-placeholder"),i.remove()));let a,o;if(this.filterId){a=this.generateEmptyPlaceholder({title:"FilterNoChatsToDisplay",subtitle:"FilterNoChatsToDisplayInfo",classNameType:o="folder"}),i=a.container;const e=document.createElement("div"),t=128;wo({div:e,emoji:"📂",width:t,height:t}),i.prepend(e);const s=(0,M.Z)("btn-primary btn-color-primary btn-control tgico",{text:"FilterHeaderEdit",icon:"settings"});(0,n.fc)(s,(()=>cg(this,void 0,void 0,(function*(){Hr.createTab(hr).open(yield this.managers.filtersStorage.getFilter(this.filterId))})))),i.append(s)}else{a=this.generateEmptyPlaceholder({title:"ChatList.Main.EmptyPlaceholder.Title",classNameType:o="dialogs"}),i=a.container;const e=document.createElement("img");e.classList.add("empty-placeholder-dialogs-icon"),this.emptyDialogsPlaceholderSubtitle=new v.ZP.IntlElement({element:a.subtitle}),Promise.all([this.updateContactsLength(!1),Ze(e,"assets/img/EmptyChats.svg"),(0,Be.AD)()]).then((([e])=>{i.classList.add("visible"),t.classList.toggle("has-contacts",!!e)})),i.prepend(e)}t.append(i),t.classList.add("with-placeholder"),t.dataset.placeholderType=o}updateContactsLength(e){return this.updateContactsLengthPromise?this.updateContactsLengthPromise:this.updateContactsLengthPromise=this.managers.appUsersManager.getContacts().then((t=>{const i=this.emptyDialogsPlaceholderSubtitle;if(i){let e,s;t.length?(e="ChatList.Main.EmptyPlaceholder.Subtitle",s=[(0,v.ag)("Contacts.Count",[t.length])]):(e="ChatList.Main.EmptyPlaceholder.SubtitleNoContacts",s=[]),i.compareAndUpdate({key:e,args:s})}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,i=e.parentElement.nextElementSibling;t.classList.remove("with-contacts"),i.innerHTML="",this.loadContacts=void 0,this.processContact=void 0}setOffsets(){return cg(this,void 0,void 0,(function*(){const e=this.chatList,t=yield this.getDialogFromElement(e.firstElementChild),i=yield this.getDialogFromElement(e.lastElementChild),s=this.indexKey;this.offsets.top=(0,hs.Z)(t,s),this.offsets.bottom=(0,hs.Z)(i,s)}))}getDialogFromElement(e){return this.managers.appMessagesManager.getDialogOnly(e.dataset.peerId.toPeerId())}setListClickListener(e,t,i=!1,s=!1,n=!1){let o;const r=(n?_m.setInnerPeer:_m.setPeer).bind(_m);e.dataset.autonomous=""+ +s,e.addEventListener("mousedown",(e=>{if(0!==e.button)return;this.log("dialogs click list");const i=e.target,n=(0,l.Z)(i,dg);if(!n)return;const c=n.dataset.peerId.toPeerId();if(e.ctrlKey||e.metaKey)return window.open(n.href||"#"+c,"_blank"),void(0,a.Z)(e);if(s){const e=o===n;o&&!e&&o.classList.remove("active"),n&&(n.classList.add("active"),o=n,this.lastActiveElements.add(n))}if(n){t&&t();const e=+n.dataset.mid||void 0;r({peerId:c,lastMsgId:e})}else r()}),{capture:!0}),e.addEventListener("click",(e=>{0===e.button&&(0,a.Z)(e)}),{capture:!0}),R.ZP&&e.addEventListener("dblclick",(e=>{const t=(0,l.Z)(e.target,dg);if(t){const e=t.dataset.peerId.toPeerId();this.log("debug dialog:",this.managers.appMessagesManager.getDialogByPeerId(e))}})),i&&Fi(e,this.contextMenu.onContextMenu)}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.dialog,e.lastMessage,e.dom,e.highlightWord,e.isBatch,e.setUnread).catch(ft.Z)}setLastMessage(e,t,i,n,a=!1,o=!1){var r;return cg(this,void 0,void 0,(function*(){if(!i&&!(i=this.getDialogDom(e.peerId)))return;const{deferred:l,middleware:c}=hg(i,"setLastMessagePromise");let d;if(!t&&("draftMessage"===(null===(r=e.draft)||void 0===r?void 0:r._)&&(d=e.draft),!(t=e.topMessage)||t.mid!==e.top_message)){const i=this.managers.appMessagesManager.getMessageByPeer(e.peerId,e.top_message);t=yield c(i)}if(o&&this.setUnreadMessagesN({dialog:e,dom:i,isBatch:a,setLastMessagePromise:l}),!t)return i.lastMessageSpan.textContent="",i.lastTimeSpan.textContent="",delete i.listEl.dataset.mid,void l.resolve();const h=e.peerId,u=t&&wa(t);{let e;const a=[];if(t&&!d&&!u){const i=(0,Se.Z)(t),s=new Set(["video","gif","round"]);if(i&&("photo"===i._||s.has(i.type))){const n=Le(i,20,20);if("photoSizeEmpty"!==n._&&(e=document.createElement("div"),e.classList.add("dialog-subtitle-media"),"round"===i.type&&e.classList.add("is-round"),a.push(dt({photo:i,message:t,container:e,withoutPreloader:!0,size:n}).then((()=>e))),s.has(i.type))){const t=document.createElement("span");t.classList.add("tgico-play"),e.append(t)}}}if(d){const e=document.createElement("b");e.classList.add("danger"),e.append((0,v.ag)("Draft"),": "),a.unshift(e)}else if(h.isAnyChat()&&h!==t.fromId&&!t.action){const e=document.createElement("b");if(t.fromId===s.Z.myId)e.append((0,v.ag)("FromYou")),a.unshift(e);else{const i=c(js({peerId:t.fromId,onlyFirstName:!0})).then((t=>(e.prepend(t),e)),ft.Z);a.unshift(i)}e.append(": ")}const o=!!e&&!!(null==t?void 0:t.message);let r;if(r=n&&t.message?yield c(Aa(t,void 0,void 0,!1,n,o)):d?yield c(Aa(d)):t?yield c(Aa(t,void 0,void 0,!1,void 0,o)):document.createDocumentFragment(),a.length){const e=yield c(Promise.all(a));r.prepend(...e)}(0,g.Z)(i.lastMessageSpan,r)}if(t||d){const e=d?Math.max(d.date,t.date||0):t.date;(0,g.Z)(i.lastTimeSpan,H(new Date(1e3*e)))}else i.lastTimeSpan.textContent="";null===o||o||(i.listEl.dataset.mid=""+t.mid),l.resolve()}))}setUnreadMessagesN(e){return this.setUnreadMessages(e.dialog,e.dom,e.isBatch,e.setLastMessagePromise).catch((()=>{}))}setUnreadMessages(e,t=this.getDialogDom(e.peerId),i=!1,n){var a;return cg(this,void 0,void 0,(function*(){if(!t)return;const{deferred:o,middleware:r}=hg(t,"setUnreadMessagePromise"),l=yield r(this.managers.appNotificationsManager.isPeerLocalMuted(e.peerId,!0)),c=t.listEl.classList.contains("is-muted");let d;if("draftMessage"!==(null===(a=e.draft)||void 0===a?void 0:a._)){const t=yield r(this.managers.appMessagesManager.getMessageByPeer(e.peerId,e.top_message));t&&t.pFlags.out&&t.peerId!==s.Z.myId&&(d=t)}const h=yield r(this.managers.filtersStorage.getFilter(this.filterId));let u;u=h?-1!==h.pinnedPeerIds.indexOf(e.peerId):!!e.pFlags.pinned;const p=yield r(this.managers.appMessagesManager.isDialogUnread(e)),m=u||p;if(n)try{yield r(n)}catch(e){}const g=i?0:200;l!==c&&Re(t.listEl,"is-muted",l,g),function(e,t,i){let s;if((null==t?void 0:t.pFlags.out)&&(s=t.pFlags.is_outgoing?"sending":t.pFlags.unread?"check":"checks"),!s)return void(e.textContent="");const n="tgico-"+s,a=e.lastElementChild;if(a&&a.classList.contains(n))return;const o=document.createElement("i");o.classList.add("sending-status-icon",n),e.append(o),a&&a.remove()}(t.statusSpan,d);const v=(0,Ne.Z)(t.unreadBadge);m&&!v&&t.subtitleEl.append(t.unreadBadge);const f=e.unread_mentions_count&&(e.unread_mentions_count>1||e.unread_count>1),y=t.mentionsBadge&&(0,Ne.Z)(t.mentionsBadge);if(f&&(t.mentionsBadge||(t.mentionsBadge=document.createElement("div"),t.mentionsBadge.className="dialog-subtitle-badge badge badge-24 mention mention-badge",t.mentionsBadge.innerText="@",t.subtitleEl.insertBefore(t.mentionsBadge,t.lastMessageSpan.nextSibling))),Re(t.unreadBadge,"is-visible",m,g,m?void 0:()=>{t.unreadBadge.remove()},v?0:2),t.mentionsBadge&&Re(t.mentionsBadge,"is-visible",f,g,f?void 0:()=>{t.mentionsBadge.remove(),delete t.mentionsBadge},y?0:2),!m)return void o.resolve();u?t.unreadBadge.classList.add("tgico-chatspinned","tgico"):t.unreadBadge.classList.remove("tgico-chatspinned","tgico");let b=!0,w=!1;e.unread_mentions_count&&1===e.unread_count?(t.unreadBadge.innerText="@",w=!0):p?t.unreadBadge.innerText=""+(e.unread_count||" "):(t.unreadBadge.innerText="",b=!1),t.unreadBadge.classList.toggle("unread",b),t.unreadBadge.classList.toggle("mention",w),o.resolve()}))}getDialogDom(e){const t=this.sortedList.get(e);return null==t?void 0:t.dom}getDialog(e){return cg(this,void 0,void 0,(function*(){if("object"!=typeof e){const t=yield this.managers.appMessagesManager.getDialogOnly(e);if(!t){const t=e||le.NM;return{peerId:t,peer:yield this.managers.appPeersManager.getOutputPeer(t),pFlags:{}}}return t}return e}))}setCallStatus(e,t){let{callIcon:i,listEl:s}=e;if(!i&&t){const{canvas:t,startAnimation:n}=e.callIcon=i=function(e=!1){const t=document.createElement("canvas");t.width=t.height=tg;const i=t.getContext("2d"),s=(tg-(3*sg+2*ig))/2,n=Date.now();let a=!1;const o=()=>{if(t.isConnected)a||(a=t.isConnected);else if(a)return!1;const o=Jm((Date.now()-n)%1e3,0,1,1e3);i.clearRect(0,0,tg,tg),i.fillStyle=e&&!d.Z.isMobile?tp.getProperty("primary-color"):"#fff";for(let e=0;e<3;++e){let t;t=o>=.5?e%2?2-2*o:2*(o-.5):e%2?2*o:1-2*o;let n=4+8*t;n*=eg,Xm(i,s+e*sg+e*ig,(tg-n)/2,sg,n,ng,!0)}return!0};return{canvas:t,startAnimation:()=>{(0,ht.jt)(o),o()},setActive:t=>{e=t,o()}}}(s.classList.contains("active"));t.classList.add("dialog-group-call-icon"),s.append(t),n()}i&&Re(e.callIcon.canvas,"is-visible",t,200,t?void 0:()=>{e.callIcon.canvas.remove(),e.callIcon=void 0},t?2:0)}addListDialog(e){e.autonomous=!1;const t=this.addDialogNew(e);if(t){const i=this.getDialog(e.peerId).then((i=>{const{peerId:n}=i,a=[];return n.isUser()||a.push(this.processDialogForCallStatus(i,t.dom)),n!==s.Z.myId&&n.isUser()&&a.push(this.managers.appUsersManager.getUser(n).then((e=>{var i;"userStatusOnline"===(null===(i=e.status)||void 0===i?void 0:i._)&&this.setOnlineStatus(t.dom.avatarEl,!0)}))),a.push(this.setLastMessageN({dialog:i,dom:t.dom,isBatch:e.isBatch,setUnread:!0})),Promise.all(a)}));e.loadPromises&&e.loadPromises.push(i)}return t}processDialogForCallStatus(e,t){return cg(this,void 0,void 0,(function*(){if(!Wd.Z)return;if(t||(t=this.getDialogDom(e.peerId)),!t)return;const i=yield this.managers.appChatsManager.getChat(e.peerId.toChatId());this.setCallStatus(t,!(!i.pFlags.call_active||!i.pFlags.call_not_empty))}))}addDialogAndSetLastMessage(e){const{peerId:t,message:i,query:s}=e,n=this.addDialogNew(Object.assign(Object.assign(Object.assign({},e),Ft(i)),{peerId:t}));return this.setLastMessage({_:"dialog",peerId:t},i,n.dom,s),i.peerId!==t&&(n.dom.listEl.dataset.peerId=""+i.peerId),n}addDialogNew(e){return this.addDialog(e.peerId,e.container,e.rippleEnabled,e.onlyFirstName,e.meAsSaved,e.append,e.avatarSize,e.autonomous,e.lazyLoadQueue,e.loadPromises,e.fromName,e.noIcons)}addDialog(e,t,i=!0,s=!1,n=!0,a=!0,o=54,r=!!t,l,c,d,h){var u;const p=new Wm;p.classList.add("dialog-avatar","avatar-"+o),p.updateWithOptions({loadPromises:c,lazyLoadQueue:l,isDialog:!!n,peerId:e,peerTitle:d});const m=document.createElement("div");m.classList.add("user-caption");const g=document.createElement("span");g.classList.add("user-title");const v=new Ot,f=v.update({peerId:e,fromName:d,dialog:n,onlyFirstName:s,plainText:!1,withIcons:!h});c&&c.push(f),g.append(v.element),g.classList.add("tgico");const y=document.createElement("span");y.classList.add("user-last-message"),y.setAttribute("dir","auto");const b=document.createElement(dg);b.classList.add("chatlist-chat"),r||(b.href="#"+e),i&&(0,we.Z)(b),b.append(p,m),b.dataset.peerId=""+e;const w=document.createElement("span");w.classList.add("message-status","sending-status");const S=document.createElement("span");S.classList.add("message-time");const C=document.createElement("div");C.className="dialog-subtitle-badge badge badge-24";const L=document.createElement("p");L.classList.add("dialog-title");const I=document.createElement("span");I.classList.add("dialog-title-details"),I.append(w,S),L.append(g,I);const M=document.createElement("p");M.classList.add("dialog-subtitle"),M.append(y),m.append(L,M);const E={avatarEl:p,captionDiv:m,titleSpan:v.element,titleSpanContainer:g,statusSpan:w,lastTimeSpan:S,unreadBadge:C,lastMessageSpan:y,containerEl:b,listEl:b,subtitleEl:M};return t&&t[a?"append":"prepend"](b),r||(b.dialogDom=E,(null===(u=_m.chat)||void 0===u?void 0:u.peerId)===e&&this.setDialogActive(b,!0)),{dom:E}}setTyping(e){return cg(this,void 0,void 0,(function*(){const t=this.getDialogDom(e.peerId);if(!t)return;const i=t.lastMessageSpan.querySelector(".peer-typing-container"),s=yield _m.getPeerTyping(e.peerId,i);!i&&s&&((0,g.Z)(t.lastMessageSpan,s),t.lastMessageSpan.classList.add("user-typing"))}))}unsetTyping(e){const t=this.getDialogDom(e.peerId);t&&(t.lastMessageSpan.classList.remove("user-typing"),this.setLastMessageN({dialog:e,lastMessage:null,dom:t,setUnread:null}))}}const mg=new pg;R.GO.appDialogsManager=mg;const gg=mg},4329:function(e){"undefined"!=typeof self&&self,e.exports=function(e){var t={};function i(s){if(t[s])return t[s].exports;var n=t[s]={i:s,l:!1,exports:{}};return e[s].call(n.exports,n,n.exports,i),n.l=!0,n.exports}return i.m=e,i.c=t,i.d=function(e,t,s){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(i.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)i.d(s,n,function(t){return e[t]}.bind(null,n));return s},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=0)}([function(e,t,i){"use strict";(function(t){var i=t.AudioContext||t.webkitAudioContext,s=function(e){if(!s.isRecordingSupported())throw new Error("Recording is not supported in this browser");e||(e={}),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},e),this.encodedSamplePosition=0};s.isRecordingSupported=function(){return i&&t.navigator&&t.navigator.mediaDevices&&t.navigator.mediaDevices.getUserMedia&&t.WebAssembly},s.prototype.clearStream=function(){this.stream&&(this.stream.getTracks?this.stream.getTracks().forEach((function(e){e.stop()})):this.stream.stop(),delete this.stream),this.audioContext&&this.closeAudioContext&&(this.audioContext.close(),delete this.audioContext)},s.prototype.encodeBuffers=function(e){if("recording"===this.state){for(var t=[],i=0;i<e.numberOfChannels;i++)t[i]=e.getChannelData(i);this.encoder.postMessage({command:"encode",buffers:t})}},s.prototype.initAudioContext=function(e){return e&&e.context?(this.audioContext=e.context,this.closeAudioContext=!1):(this.audioContext=new i,this.closeAudioContext=!0),this.audioContext},s.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=e=>{this.encodeBuffers(e.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)},s.prototype.initSourceNode=function(e){return e&&e.context?t.Promise.resolve(e):t.navigator.mediaDevices.getUserMedia({audio:this.config.mediaTrackConstraints}).then((e=>(this.stream=e,this.audioContext.createMediaStreamSource(e))))},s.prototype.loadWorker=function(){this.encoder||(this.encoder=new t.Worker(this.config.encoderPath))},s.prototype.initWorker=function(){var e=(this.config.streamPages?this.streamPage:this.storePage).bind(this);return this.recordedPages=[],this.totalLength=0,this.loadWorker(),new Promise(((t,i)=>{var s=i=>{switch(i.data.message){case"ready":t();break;case"page":this.encodedSamplePosition=i.data.samplePosition,e(i.data.page);break;case"done":this.encoder.removeEventListener("message",s),this.finish()}};this.encoder.addEventListener("message",s),this.encoder.postMessage(Object.assign({command:"init",originalSampleRate:this.audioContext.sampleRate,wavSampleRate:this.audioContext.sampleRate},this.config))}))},s.prototype.pause=function(e){if("recording"===this.state){if(this.state="paused",e&&this.config.streamPages){var t=this.encoder;return new Promise(((e,i)=>{var s=i=>{"flushed"===i.data.message&&(t.removeEventListener("message",s),this.onpause(),e())};t.addEventListener("message",s),t.postMessage({command:"flush"})}))}return this.onpause(),Promise.resolve()}},s.prototype.resume=function(){"paused"===this.state&&(this.state="recording",this.onresume())},s.prototype.setRecordingGain=function(e){this.config.recordingGain=e,this.recordingGainNode&&this.audioContext&&this.recordingGainNode.gain.setTargetAtTime(e,this.audioContext.currentTime,.01)},s.prototype.setMonitorGain=function(e){this.config.monitorGain=e,this.monitorGainNode&&this.audioContext&&this.monitorGainNode.gain.setTargetAtTime(e,this.audioContext.currentTime,.01)},s.prototype.start=function(e){if("inactive"===this.state)return this.initAudioContext(e),this.initAudioGraph(),this.encodedSamplePosition=0,this.initWorker().then((()=>this.initSourceNode(e))).then((e=>{this.sourceNode=e,this.state="recording",this.onstart(),this.encoder.postMessage({command:"getHeaderPages"}),this.sourceNode.connect(this.monitorGainNode),this.sourceNode.connect(this.recordingGainNode)}))},s.prototype.stop=function(){if("inactive"!==this.state){this.state="inactive",this.monitorGainNode.disconnect(),this.scriptProcessorNode.disconnect(),this.recordingGainNode.disconnect(),this.sourceNode.disconnect(),this.clearStream();var e=this.encoder;return new Promise((t=>{var i=s=>{"done"===s.data.message&&(e.removeEventListener("message",i),t())};e.addEventListener("message",i),e.postMessage({command:"done"}),this.config.reuseWorker||e.postMessage({command:"close"})}))}return Promise.resolve()},s.prototype.destroyWorker=function(){"inactive"===this.state&&this.encoder&&(this.encoder.postMessage({command:"close"}),delete this.encoder)},s.prototype.storePage=function(e){this.recordedPages.push(e),this.totalLength+=e.length},s.prototype.streamPage=function(e){this.ondataavailable(e)},s.prototype.finish=function(){if(!this.config.streamPages){var e=new Uint8Array(this.totalLength);this.recordedPages.reduce((function(t,i){return e.set(i,t),t+i.length}),0),this.ondataavailable(e)}this.onstop(),this.config.reuseWorker||delete this.encoder},s.prototype.ondataavailable=function(){},s.prototype.onpause=function(){},s.prototype.onresume=function(){},s.prototype.onstart=function(){},s.prototype.onstop=function(){},e.exports=s}).call(this,i(1))},function(e,t){var i;i=function(){return this}();try{i=i||new Function("return this")()}catch(e){"object"==typeof window&&(i=window)}e.exports=i}])}}]);
//# sourceMappingURL=911.5ad2ede78b83a9191cd2.chunk.js.map