tweb/public/664.22c6afb6ed739f8b3773.ch...

2 lines
778 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.webpackChunktweb=this.webpackChunktweb||[]).push([[664],{4489:(e,t,s)=>{"use strict";s.d(t,{Z:()=>n});var i=s(503);class n extends i.Z{constructor(e){super(Object.assign({plainText:!0},e));const t=this.input;t.type="tel",t.setAttribute("required",""),t.autocomplete="off";let s=0;this.input.addEventListener("input",(t=>{this.input.classList.remove("error"),this.setLabel();const i=this.value.replace(/\D/g,"").slice(0,e.length);this.setValueSilently(i);const n=this.value.length;if(n===e.length)e.onFill(this.value);else if(n===s)return;s=n}))}}},4425:(e,t,s)=>{"use strict";s.d(t,{Z:()=>n});var i=s(2897);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=i.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())},i.Z.waitForFirstFrame(e))))}remove(){this.animation&&this.animation.remove()}}},3083:(e,t,s)=>{"use strict";s.d(t,{Z:()=>n});var i=s(2897);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 s=e.input;s.addEventListener("blur",(()=>{this.playAnimation(0)})),s.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 s=this.needFrame>t?-1:1;this.animation.setDirection(s),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([i.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(),i.Z.waitForFirstFrame(e)))),i.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")})),i.Z.waitForFirstFrame(e))))])}remove(){this.animation&&this.animation.remove(),this.idleAnimation&&this.idleAnimation.remove()}}},6830:(e,t,s)=>{"use strict";s.d(t,{Z:()=>a});var i=s(3910),n=s(503);class a extends n.Z{constructor(e={}){super(Object.assign({plainText:!0},e)),this.passwordVisible=!1,this.onVisibilityClick=e=>{(0,i.d)(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 s=document.createElement("input");s.classList.add("stealthy"),s.tabIndex=-1,s.type="password",t.parentElement.prepend(s),t.parentElement.insertBefore(s.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)}}},4903:(e,t,s)=>{"use strict";function i(...e){const t=e.reduce(((e,t)=>e+(t.byteLength||t.length)),0),s=new Uint8Array(t);let i=0;return e.forEach((e=>{s.set(e instanceof ArrayBuffer?new Uint8Array(e):e,i),i+=e.byteLength||e.length})),s}s.d(t,{Z:()=>i})},4484:(e,t,s)=>{"use strict";function i(e,t){const s=e.length;if(s!==t.length)return!1;for(let i=0;i<s;++i)if(e[i]!==t[i])return!1;return!0}s.d(t,{Z:()=>i})},2664:(e,t,s)=>{"use strict";s.r(t),s.d(t,{AppDialogsManager:()=>cd,default:()=>pd});var i=s(7223),n=s(8209),a=s(3512),o=s(6440),r=s(3714),l=s(2738),d=s(3910),c=s(9256),h=s(1174),p=s(5844);const u=[...h.Z].concat([...p.Z]),g=new Set(u);function m(e,t){e.setAttribute("dir","auto"),e.innerHTML=t}var v=s(4755),f=s(9492),b=s(7625);function y(e){(0,b.Z)(e.history,((t,s,i)=>{t.action.photo||(i.splice(s,1),void 0!==e.count&&--e.count)}))}var w=s(5953);class S{constructor(e){this.previous=[],this.next=[],this.reverse=!1,this.loadCount=50,this.loadWhenLeft=20,this.loadedAllUp=!1,this.loadedAllDown=!1,(0,w.Z)(this,e)}setTargets(e,t,s){this.previous=e,this.next=t,this.reverse=s}get index(){return void 0!==this.count?this.previous.length:-1}reset(e=!1){this.current=void 0,this.previous=[],this.next=[],this.loadedAllUp=this.loadedAllDown=e,this.loadPromiseUp=this.loadPromiseDown=null}go(e,t=!0){let s,i;if(e>0){if(s=this.next.splice(0,e),i=s.pop(),!i)return;this.previous.push(this.current,...s)}else{if(s=this.previous.splice(this.previous.length+e,-e),i=s.shift(),!i)return;this.next.unshift(...s,this.current)}return this.next.length<this.loadWhenLeft&&this.load(!this.reverse),this.previous.length<this.loadWhenLeft&&this.load(this.reverse),this.current=i,t&&this.onJump&&this.onJump(i,e>0),this.current}load(e){if(e&&this.loadedAllDown)return Promise.resolve();if(!e&&this.loadedAllUp)return Promise.resolve();if(e&&this.loadPromiseDown)return this.loadPromiseDown;if(!e&&this.loadPromiseUp)return this.loadPromiseUp;let t;t=e?this.reverse?this.previous[0]:this.next[this.next.length-1]:this.reverse?this.next[this.next.length-1]:this.previous[0];const s=this.loadMore(t,e,this.loadCount).then((t=>{e&&this.loadPromiseDown!==s||!e&&this.loadPromiseUp!==s||(t.items.length<this.loadCount&&(e?this.loadedAllDown=!0:this.loadedAllUp=!0),void 0===this.count&&(this.count=t.count||t.items.length),(e?t.items.forEach.bind(t.items):b.Z.bind(null,t.items))((t=>{const s=this.processItem?this.processItem(t):t;s&&(e?this.reverse?this.previous.unshift(s):this.next.push(s):this.reverse?this.next.push(s):this.previous.unshift(s))})),this.onLoadedMore&&this.onLoadedMore())}),(()=>{})).then((()=>{e?this.loadPromiseDown=null:this.loadPromiseUp=null}));return e?this.loadPromiseDown=s:this.loadPromiseUp=s,s}}class C extends S{constructor(e={}){super(Object.assign(Object.assign({},e),{loadMore:(e,t,s)=>{var n;const a=t?0:s;let o=null===(n=this.current)||void 0===n?void 0:n.mid;return e&&(o=e.mid),t||(o=f.Z.incrementMessageId(o,1)),i.Z.getSearch(Object.assign(Object.assign({},this.searchContext),{peerId:this.searchContext.peerId||(null==e?void 0:e.peerId),maxId:o,limit:a?0:s,backLimit:a})).then((e=>("inputMessagesFilterChatPhotos"===this.searchContext.inputFilter._&&y(e),e.next_rate&&(this.searchContext.nextRate=e.next_rate),{count:e.count,items:e.history})))},processItem:t=>{if(this.filterMids([t.mid]).length)return e.processItem(t)}})),this.onHistoryDelete=({peerId:e,msgs:t})=>{const s=s=>s.peerId===e&&t.has(s.mid),i=(e,t,i)=>{s(e)&&i.splice(t,1)};(0,b.Z)(this.previous,i),(0,b.Z)(this.next,i),this.current&&s(this.current)&&this.onEmptied&&this.onEmptied()},this.onHistoryMultiappend=e=>{if(void 0!==this.searchContext.folderId)return;if(!this.loadedAllUp||this.loadPromiseUp)return;const t=e[this.searchContext.peerId];if(!t)return;const s=Array.from(t).sort(((e,t)=>e-t)),i=this.filterMids(s).map((e=>this.processItem(e))).filter(Boolean);i.length&&this.next.push(...i)},this.onMessageSent=({message:e})=>{this.onHistoryMultiappend({[e.peerId]:new Set([e.mid])})},a.default.addEventListener("history_delete",this.onHistoryDelete),a.default.addEventListener("history_multiappend",this.onHistoryMultiappend),a.default.addEventListener("message_sent",this.onMessageSent)}filterMids(e){const t=this.searchContext.isScheduled?i.Z.getScheduledMessagesStorage(this.searchContext.peerId):i.Z.getMessagesStorage(this.searchContext.peerId);return i.Z.filterMessagesByInputFilter(this.searchContext.inputFilter._,e,t,e.length)}setSearchContext(e){this.searchContext=e,void 0!==this.searchContext.folderId&&(this.loadedAllUp=!0,void 0===this.searchContext.nextRate&&(this.loadedAllDown=!0)),"inputMessagesFilterChatPhotos"===this.searchContext.inputFilter._&&(this.loadedAllUp=!0),this.searchContext.useSearch||(this.loadedAllDown=this.loadedAllUp=!0)}reset(){super.reset(),this.searchContext=void 0}cleanup(){this.reset(),a.default.removeEventListener("history_delete",this.onHistoryDelete),a.default.removeEventListener("history_multiappend",this.onHistoryMultiappend),a.default.removeEventListener("message_sent",this.onMessageSent),this.onEmptied=void 0}}var L=s(1592),I=s(5814),M=s(4687),E=s(5555),P=s(8805),T=s(5565),k=s(4727);class x{constructor(e,t,s=!0,i,n=!0,a=!0,o){this.name=e,this.type=t,this.clearable=s,this.autonomous=a,this.onFound=o,this.list=pd.createChatList(),this.container=document.createElement("div"),i&&(this.container.className=i),e&&(this.nameEl=document.createElement("div"),this.nameEl.classList.add("search-group__name"),"string"==typeof e&&this.nameEl.append((0,k.i18n)(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&&pd.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 A{constructor(e,t,s,i){this.container=e,this.searchInput=t,this.searchGroups=s,this.onSearch=i,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 P.ZP(this.container),this.listsContainer=this.scrollable.container;for(let 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(let e in this.searchGroups)this.searchGroups[e].clear();this.searchPromise=null}beginSearch(e,t=0,s=""){this.peerId=e,this.threadId=t,this.query!==s&&(this.searchInput.inputField.value=s),this.searchInput.input.focus()}searchMore(){if(this.searchPromise)return this.searchPromise;const e=this.query;if(!e.trim())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=i.Z.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:s,history:i}=t;i.length&&i[0].mid===this.minMsgId&&i.shift();const n=this.searchGroups.messages;i.forEach((t=>{try{const s=this.peerId?t.fromId:t.peerId;pd.addDialogAndSetLastMessage({peerId:s,container:this.scrollable,drawStatus:!1,avatarSize:54,meAsSaved:!1,message:t,query:e})}catch(e){console.error("[appSearch] render search result",e)}})),n.toggle(),this.minMsgId=i.length&&i[i.length-1].mid,-1===this.loadedCount&&(this.loadedCount=0),this.loadedCount+=i.length,-1===this.foundCount&&(this.foundCount=s,n.nameEl&&(0,T.Z)(n.nameEl,(0,k.i18n)(s?"Chat.Search.MessagesFound":"Chat.Search.NoMessagesFound",[s])),this.onSearch&&this.onSearch(this.foundCount))})).catch((e=>{console.error("search error",e),this.searchPromise=null}))}}var _=s(503);class Z{constructor(e,t){this.prevValue="",this.timeout=0,this.onInput=()=>{if(!this.onChange)return;let 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 _.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 s=document.createElement("i");s.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(s,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 D=s(426),F=s(9818),R=s(3241),B=s(3699),U=s(4494);const N=(e,t={})=>(0,U.Z)("btn-icon",Object.assign({icon:e||void 0},t));class O{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=N("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 P.ZP(this.content,void 0,void 0,!0),this.container.append(this.header,this.content),this.slider.addTab(this),this.listenerSetter=new B.Z}close(){return this.slider.closeTab(this)}open(...e){return t=this,s=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((i=void 0)||(i=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 s;t.done?e(t.value):(s=t.value,s instanceof i?s:new i((function(e){e(s)}))).then(o,r)}l((n=n.apply(t,s||[])).next())}));var t,s,i,n}init(){}onCloseAfterTimeout(){this.destroyable&&(this.slider.tabs.delete(this),this.container.remove()),this.listenerSetter&&this.listenerSetter.removeAll()}setTitle(e){this.title.innerHTML="",this.title.append((0,k.i18n)(e))}}class H extends O{constructor(e){super(e),this.eventListener=new R.Z}onCloseAfterTimeout(){return this.eventListener.dispatchEvent("destroy"),this.eventListener.cleanup(),super.onCloseAfterTimeout()}}var z=s(1655);class V{constructor(e){this.historyTabIds=[],this.canHideFirst=!1,this.onCloseBtnClick=()=>{F.Z.findItemByType(this.navigationType)?F.Z.back(this.navigationType):this.historyTabIds.length&&this.closeTab(this.historyTabIds[this.historyTabIds.length-1])},this.closeTab=(e,t,s)=>{if(void 0!==e&&this.historyTabIds[this.historyTabIds.length-1]!==e)return!1;const i=this.historyTabIds.pop();this.onCloseTab(i,t,s);const n=this.historyTabIds[this.historyTabIds.length-1];return this._selectTab(void 0!==n?n instanceof O?n.container:n:this.canHideFirst?-1:0,t),!0},(0,w.Z)(this,e),this.tabs||(this.tabs=new Map),this.tabsContainer=this.sidebarEl.querySelector(".sidebar-slider"),this._selectTab=(0,D.v)(this.tabsContainer,"navigation",250),this.canHideFirst||this._selectTab(0),Array.from(this.sidebarEl.querySelectorAll(".sidebar-close-button")).forEach((e=>{(0,l.fc)(e,this.onCloseBtnClick)}))}selectTab(e){if(this.historyTabIds[this.historyTabIds.length-1]===e)return!1;const t=e instanceof O?e:this.tabs.get(e);return t&&(t.onOpen&&t.onOpen(),t.onOpenAfterTimeout&&setTimeout((()=>{t.onOpenAfterTimeout()}),250)),F.Z.pushItem({type:this.navigationType,onPop:e=>(this.closeTab(void 0,e,!0),!0)}),this.historyTabIds.push(e),this._selectTab(e instanceof O?e.container:e),!0}removeTabFromHistory(e){(0,z.Z)(this.historyTabIds,e),this.onCloseTab(e,void 0)}sliceTabsUntilTab(e,t){for(let s=this.historyTabIds.length-1;s>=0;--s){const i=this.historyTabIds[s];if(i!==t){if(i instanceof e)break;this.removeTabFromHistory(i)}}}getTab(e){return this.historyTabIds.find((t=>t instanceof e))}isTabExists(e){return!!this.getTab(e)}onCloseTab(e,t,s){s||F.Z.removeByType(this.navigationType,!0);const i=e instanceof O?e:this.tabs.get(e);i&&(i.onClose&&i.onClose(),i.onCloseAfterTimeout&&setTimeout((()=>{i.onCloseAfterTimeout()}),250))}addTab(e){e.container.parentElement||(this.tabsContainer.append(e.container),e.closeBtn&&e.closeBtn.addEventListener("click",this.onCloseBtnClick))}}var j=s(8138),G=s(6765);class K{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,l.fc)(this.container,(()=>{(new G.Z).open(this.canvas,e)}))}clear(){this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height)}}const W=(e={})=>(0,U.Z)("btn-circle btn-corner z-depth-1"+(e.className?" "+e.className:""),e);class q extends O{constructor(){super(...arguments),this.uploadAvatar=null,this.isGeoChat=!1}init(){this.container.classList.add("new-group-container"),this.setTitle("NewGroup"),this.avatarEdit=new K((e=>{this.uploadAvatar=e}));const e=new Mn({}),t=document.createElement("div");t.classList.add("input-wrapper"),this.groupNameInputField=new _.Z({label:"CreateGroup.NameHolder",maxLength:128}),this.groupLocationInputField=new _.Z({label:"ChatLocation",name:"location",canBeEdited:!1}),t.append(this.groupNameInputField.container,this.groupLocationInputField.container),this.groupNameInputField.input.addEventListener("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=W({icon:"arrow_next"}),this.nextBtn.addEventListener("click",(()=>{const e=this.groupNameInputField.value;if(this.isGeoChat){if(!this.userLocationAddress||!this.userLocationCoords)return;j.Z.createChannel({title:e,about:"",geo_point:Object.assign({_:"inputGeoPoint"},this.userLocationCoords),address:this.userLocationAddress,megagroup:!0}).then((e=>{this.uploadAvatar&&this.uploadAvatar().then((t=>{j.Z.editPhoto(e,t)})),this.peerIds.length&&j.Z.inviteToChannel(e,this.peerIds),xn.removeTabFromHistory(this),xn.selectTab(0)}))}else this.nextBtn.disabled=!0,j.Z.createChat(e,this.peerIds.map((e=>e.toUserId()))).then((e=>{this.uploadAvatar&&this.uploadAvatar().then((t=>{j.Z.editPhoto(e,t)})),xn.removeTabFromHistory(this),xn.selectTab(0)}))}));const s=new Mn({name:"Members",nameArgs:[this.peerIds.length]}),i=this.list=pd.createChatList({new:!0});s.content.append(i),e.content.append(this.avatarEdit.container,t),this.content.append(this.nextBtn),this.scrollable.append(e.container,s.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 s=super.open();return s.then((()=>{t?(this.setTitle("NearbyCreateGroup"),this.groupLocationInputField.container.classList.remove("hide"),this.groupLocationInputField.setValueSilently(k.default.format("Loading",!0)),this.startLocating()):this.groupLocationInputField.container.classList.add("hide"),this.peerIds.forEach((e=>{const{dom:t}=pd.addDialogNew({dialog:e,container:this.list,drawStatus:!1,rippleEnabled:!1,avatarSize:48});t.lastMessageSpan.append(E.Z.getUserStatusString(e))}))})),s}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 $=s(5003),Q=s(8598),Y=s(6008),X=s(1425),J=s(6858),ee=s(1405),te=s(671),se=s(3725),ie=s(632),ne=s(4762),ae=s(2897),oe=s(3689),re=s(410),le=s(7309),de=s(6669),ce=s(5432),he=s(6056),pe=s(8479),ue=s(6848);const ge=(()=>{try{return ne.IS_SAFARI&&+navigator.userAgent.match(/ Version\/(\d+)/)[1]<14}catch(e){return!1}})(),me=new class{constructor(){if(this.media=new Map,this.scheduled=new Map,this.mediaDetails=new Map,this.waitingMediaForLoad=new Map,this.waitingScheduledMediaForLoad=new Map,this.waitingDocumentsForLoad={},this._volume=1,this._muted=!1,this._playbackRate=1,this.playbackRates={voice:1,video:1,audio:1},this.seekBackward=e=>{const t=this.playingMedia;t&&(t.currentTime=Math.max(0,t.currentTime-(e.seekOffset||10)))},this.seekForward=e=>{const t=this.playingMedia;t&&(t.currentTime=Math.min(t.duration,t.currentTime+(e.seekOffset||10)))},this.seekTo=e=>{const t=this.playingMedia;t&&(t.currentTime=e.seekTime)},this.onMediaDocumentLoad=e=>{const t=this.mediaDetails.get(e),s=L.Z.getDoc(t.docId);"audio"===s.type&&s.supportsStreaming&&ge&&this.handleSafariStreamable(e);const i=le.Z.getCacheContext(s);e.src=i.url,this.playingMedia===e&&(e.playbackRate=this.playbackRate);const n=this.waitingDocumentsForLoad[s.id];n&&(n.delete(e),n.size||delete this.waitingDocumentsForLoad[s.id])},this.onPlay=e=>{const t=e.target,s=this.mediaDetails.get(t),{peerId:i,mid:n}=s,o=this.getMessageByMedia(t);if(this.playingMedia!==t){this.stop();const e=e=>e.mid===n&&e.peerId===i;if(!this.listLoader.current||!e(this.listLoader.current)){let t,s=this.listLoader.previous.findIndex(e);-1!==s?t=-(this.listLoader.previous.length-s):(s=this.listLoader.next.findIndex(e),-1!==s&&(t=s+1)),-1!==s?t&&this.listLoader.go(t,!1):this.setTargets({peerId:i,mid:n})}this.setMedia(t,o)}setTimeout((()=>{this.playingMedia===t&&a.default.dispatchEvent("media_play",this.getPlayingDetails())}),0)},this.onPause=e=>{a.default.dispatchEvent("media_pause")},this.onEnded=e=>{e.isTrusted&&(this.onPause(e),this.next()||(this.stop(),a.default.dispatchEvent("media_stop")))},this.play=()=>this.toggle(!0),this.pause=()=>this.toggle(!1),this.stop=()=>{const e=this.playingMedia;if(!e)return!1;e.paused||e.pause(),e.currentTime=0,(0,de.Z)(e,"ended");const t=this.mediaDetails.get(e);if(null==t?void 0:t.clean){e.src="";const s=t.peerId,i=t.isScheduled?this.scheduled:this.media,n=i.get(s);n&&(n.delete(t.mid),n.size||i.delete(s)),e.remove(),this.mediaDetails.delete(e)}return this.playingMedia=void 0,this.playingMediaType=void 0,!0},this.playItem=e=>{const{peerId:t,mid:s}=e,i=this.searchContext.isScheduled;this.getMedia(t,s,i).play(),setTimeout((()=>{this.resolveWaitingForLoadMedia(t,s,i)}),0)},this.next=()=>!this.lockedSwitchers&&this.listLoader.go(1),this.previous=()=>{const e=this.playingMedia;return e&&(e.currentTime>5||!this.listLoader.previous.length)?(e.currentTime=0,void this.toggle(!0)):!this.lockedSwitchers&&this.listLoader.go(-1)},this.container=document.createElement("div"),this.container.style.cssText="display: none;",document.body.append(this.container),navigator.mediaSession){const e={play:this.play,pause:this.pause,stop:this.stop,seekbackward:this.seekBackward,seekforward:this.seekForward,seekto:this.seekTo,previoustrack:this.previous,nexttrack:this.next};for(const t in e)try{navigator.mediaSession.setActionHandler(t,e[t])}catch(e){console.warn("MediaSession action is not supported:",t)}}a.default.addEventListener("document_downloaded",(e=>{const t=this.waitingDocumentsForLoad[e.id];if(t)for(const e of t)this.onMediaDocumentLoad(e)}));const e={};["volume","muted","playbackRate"].forEach((t=>{const s="_"+t;e[t]={get:()=>this[s],set:e=>{this[s]!==e&&(this[s]=e,this.playingMedia&&(this.playingMedia[t]=e),"playbackRate"===t&&void 0!==this.playingMediaType&&(this.playbackRates[this.playingMediaType]=e),this.dispatchPlaybackParams())}}})),Object.defineProperties(this,e)}dispatchPlaybackParams(){const{volume:e,muted:t,playbackRate:s}=this;a.default.dispatchEvent("media_playback_params",{volume:e,muted:t,playbackRate:s})}addMedia(e,t,s){const{peerId:n,mid:o}=e,r=e.pFlags.is_scheduled?this.scheduled:this.media;let l=r.get(e.peerId);l||r.set(e.peerId,l=new Map);let d=l.get(o);if(d)return d;const c=i.Z.getMediaFromMessage(e);l.set(o,d=document.createElement("round"===c.type||"video"===c.type?"video":"audio")),"round"===c.type&&d.setAttribute("playsinline","true");const h={peerId:n,mid:o,docId:c.id,clean:s,isScheduled:e.pFlags.is_scheduled};this.mediaDetails.set(d,h),d.volume=1,this.container.append(d),d.addEventListener("play",this.onPlay),d.addEventListener("pause",this.onPause),d.addEventListener("ended",this.onEnded),"audio"!==c.type&&(null==e?void 0:e.pFlags.media_unread)&&e.fromId!==a.default.myId&&d.addEventListener("timeupdate",(()=>{i.Z.readMessages(n,[o])}),{once:!0});const p=(0,se.b)();if(t)p.resolve();else{const t=e.pFlags.is_scheduled?this.waitingScheduledMediaForLoad:this.waitingMediaForLoad;let s=t.get(n);s||t.set(n,s=new Map),s.set(o,p)}return p.then((()=>{const e=le.Z.getCacheContext(c);if(c.supportsStreaming||e.url)this.onMediaDocumentLoad(d);else{let e=this.waitingDocumentsForLoad[c.id];e||(e=this.waitingDocumentsForLoad[c.id]=new Set),e.add(d),L.Z.downloadDoc(c)}})),d}getMedia(e,t,s){const i=(s?this.scheduled:this.media).get(e);return null==i?void 0:i.get(t)}handleSafariStreamable(e){e.addEventListener("play",(()=>{const t=e.currentTime;e.addEventListener("progress",(()=>{e.currentTime=e.duration-1,e.addEventListener("progress",(()=>{e.currentTime=t,e.paused||e.play()}),{once:!0})}),{once:!0})}))}resolveWaitingForLoadMedia(e,t,s){const i=s?this.waitingScheduledMediaForLoad:this.waitingMediaForLoad,n=i.get(e);if(!n)return;const a=n.get(t);a&&(a.resolve(),n.delete(t),n.size||i.delete(e))}isSafariBuffering(e){return!!e.safariBuffering}setSafariBuffering(e,t){e.safariBuffering=t}setNewMediadata(e,t=this.playingMedia){var s,n,a,l,d;return n=this,a=void 0,d=function*(){yield(0,he.xD)(t,void 0,!1);const n=i.Z.getMediaFromMessage(e),a=[],l="voice"===n.type||"round"===n.type;let d="",h="";if(null===(s=n.thumbs)||void 0===s?void 0:s.length){const s=n.thumbs[n.thumbs.length-1];if(!s.bytes){const i=le.Z.getCacheContext(n,s.type);i.url?a.push({src:i.url,sizes:`${s.w}x${s.h}`,type:"image/jpeg"}):r.Z.preloadPhoto(n,s).then((()=>{this.playingMedia===t&&i.url&&this.setNewMediadata(e)}))}}else if(l){const s=e.fromId||e.peerId,i=o.Z.getPeerPhoto(s);if(i){const n=c.Z.loadAvatar(s,i,"photo_small");if(n.cached){const e=yield n.loadPromise;a.push({src:e,sizes:"160x160",type:"image/jpeg"})}else n.loadPromise.then((s=>{this.playingMedia===t&&s&&this.setNewMediadata(e)}))}d=o.Z.getPeerTitle(s,!0,!1),h=k.default.format("voice"===n.type?"AttachAudio":"AttachRound",!0)}if(!l){const e=n.attributes.find((e=>"documentAttributeAudio"===e._));d=e&&e.title||n.file_name,h=e&&e.performer}a.length||(ne.IS_APPLE?ce.IS_TOUCH_SUPPORTED?a.push({src:"assets/img/apple-touch-icon-precomposed.png",sizes:"180x180",type:"image/png"}):a.push({src:"assets/img/apple-touch-icon.png",sizes:"180x180",type:"image/png"}):[72,96,144,192,256,384,512].forEach((e=>{const t=`${e}x${e}`;a.push({src:`assets/img/android-chrome-${t}.png`,sizes:t,type:"image/png"})})));const p=new MediaMetadata({title:d,artist:h,artwork:a});navigator.mediaSession.metadata=p},new((l=void 0)||(l=Promise))((function(e,t){function s(e){try{o(d.next(e))}catch(e){t(e)}}function i(e){try{o(d.throw(e))}catch(e){t(e)}}function o(t){var n;t.done?e(t.value):(n=t.value,n instanceof l?n:new l((function(e){e(n)}))).then(s,i)}o((d=d.apply(n,a||[])).next())}))}getMessageByMedia(e){const t=this.mediaDetails.get(e),{peerId:s,mid:n}=t;return t.isScheduled?i.Z.getScheduledMessageByPeer(s,n):i.Z.getMessageByPeer(s,n)}getPlayingDetails(){const{playingMedia:e}=this;if(!e)return;const t=this.getMessageByMedia(e);return{doc:i.Z.getMediaFromMessage(t),message:t,media:e}}toggle(e){return!!this.playingMedia&&(void 0===e&&(e=this.playingMedia.paused),this.playingMedia.paused===e&&(e?this.playingMedia.play():this.playingMedia.pause(),!0))}willBePlayed(e){this.willBePlayedMedia=e}setSearchContext(e){return!(0,ue.Z)(this.searchContext,e)&&(this.searchContext=(0,pe.Z)(e),!0)}getSearchContext(){return this.searchContext}setTargets(e,t,s){this.listLoader?this.listLoader.reset():this.listLoader=new C({loadCount:10,loadWhenLeft:5,processItem:e=>(this.addMedia(e,!1),{peerId:e.peerId,mid:e.mid}),onJump:(e,t)=>{this.playItem(e)},onEmptied:()=>{a.default.dispatchEvent("media_stop"),this.stop()}});const i=void 0===this.searchContext.folderId;t?this.listLoader.setTargets(t,s,i):this.listLoader.reverse=i,this.listLoader.setSearchContext(this.searchContext),this.listLoader.current=e,this.listLoader.load(!0),this.listLoader.load(!1)}getPlaybackMediaTypeFromMessage(e){const t=i.Z.getMediaFromMessage(e);let s="audio";return(null==t?void 0:t.type)&&("voice"===t.type||"round"===t.type?s="voice":"video"===t.type&&(s="video")),s}setMedia(e,t){const s=this.getPlaybackMediaTypeFromMessage(t);this._playbackRate=this.playbackRates[s],this.playingMedia=e,this.playingMediaType=s,this.playingMedia.volume=this.volume,this.playingMedia.muted=this.muted,this.playingMedia.playbackRate=this.playbackRate,"mediaSession"in navigator&&this.setNewMediadata(t)}setSingleMedia(e,t){const s=this.playingMedia,i=this.pause();return this.willBePlayed(void 0),e?this.setMedia(e,t):this.playingMedia=void 0,this.toggleSwitchers(!1),()=>{this.toggleSwitchers(!0),s&&(this.mediaDetails.get(s)?this.setMedia(s,this.getMessageByMedia(s)):this.next()||this.previous()),e&&this.playingMedia===e&&this.stop(),i&&this.play()}}toggleSwitchers(e){this.lockedSwitchers=!e}};re.GO.appMediaPlaybackController=me;const ve=me;var fe=s(1964);function be(e,t,s,i){const n=e=>{s({x:e.pageX,y:e.pageY,event:e})},a=t=>{document.removeEventListener("mousemove",n),e.addEventListener("mousedown",o,{once:!0}),i&&i({x:t.pageX,y:t.pageY,event:t})},o=s=>{0===s.button?(t({x:s.pageX,y:s.pageY,event:s}),n(s),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(),s({x:e.touches[0].clientX,y:e.touches[0].clientY,isTouch:!0,event:e})},l=t=>{document.removeEventListener("touchmove",r),e.addEventListener("touchstart",d,{passive:!1,once:!0}),i&&i({x:t.touches[0].clientX,y:t.touches[0].clientY,isTouch:!0,event:t})},d=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",d,{passive:!1,once:!0}),()=>{e.removeEventListener("mousedown",o),document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",a),e.removeEventListener("touchstart",d),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",l)}}var ye=s(3228);class we{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,w.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 s=this.seek=document.createElement("input");s.classList.add("progress-line__seek"),s.type="range",s.step=""+this.step,s.min=""+this.min,s.max=""+this.max,s.value=""+t,t&&this.setProgress(t);const i=""+this.step,n=i.indexOf(".");this.decimals=-1===n?0:i.length-n-1,this.container.append(this.filled,s)}get value(){return+this.seek.value}setHandlers(e){this.events=e}setListeners(){this.seek.addEventListener("input",this.onInput),this._removeListeners=be(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,ye.Z)(t,0,1),this.useTransform?this.filled.style.transform=`scaleX(${t})`:this.filled.style.width=100*t+"%"}scrub(e){var t;const s=this.vertical?this.rect.height:this.rect.width,i=(0,ye.Z)(this.vertical?-(e.y-this.rect.bottom):e.x-this.rect.left,0,s);let n=this.min+i/s*(this.max-this.min);return n-this.min<(this.max-this.min)/2&&(n-=this.step/10),n=+n.toFixed(this.decimals),n=(0,ye.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={}}}const Se=e=>{if(e.element)return e.element;const{icon:t,text:s,onClick:i,checkboxField:n,noCheckboxClickListener:a}=e,o=document.createElement("div");o.className="btn-menu-item rp-overflow"+(t?" tgico-"+t:""),(0,ee.ripple)(o);let r=e.textElement;r||(r=e.textElement=s?(0,k.i18n)(s,e.textArgs):document.createElement("span"),e.regularText&&(r.innerHTML=e.regularText)),r.classList.add("btn-menu-item-text"),o.append(r);const c=!!n||!!e.keepOpen;return i&&(0,l.fc)(o,(e=>{(0,d.d)(e),!1!==i(e)&&(c||(0,J.UR)(),n&&!a&&(n.checked="radio"===n.input.type||!n.checked))}),e.options),n&&o.append(n.label),e.element=o},Ce=(e,t)=>{const s=document.createElement("div");s.classList.add("btn-menu"),t&&e.forEach((e=>{e.options?e.options.listenerSetter=t:e.options={listenerSetter:t}}));const i=e.map(Se);return s.append(...i),s},Le=(e,t,s,i)=>{((null==s?void 0:s.listenerSetter)?s.listenerSetter.add(e):e.addEventListener.bind(e))(l.pf,(s=>{if(!e.classList.contains("btn-menu-toggle"))return!1;const n=e.querySelector(".btn-menu");(0,d.d)(s),e.classList.contains("menu-open")?(0,J.UR)():(t&&t(s),(0,J.YP)(n,i))}))},Ie=(e={},t,s,i,n)=>{var a;e.asDiv=!0;const o=null!==(a=e.container)&&void 0!==a?a:N("more",e);o.classList.add("btn-menu-toggle");const r=Ce(s,e.listenerSetter);return r.classList.add(t),Le(o,i,e,n),o.append(r),o};var Me=s(8497);class Ee extends R.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,w.Z)(this,e);const{listenerSetter:t,element:s}=this;ce.IS_TOUCH_SUPPORTED?t.add(s)("click",(e=>{this.ignoreClickClassName&&(0,Me.Z)(e.target,this.ignoreClickClassName)||this.toggleControls()})):(t.add(s)("mousemove",(()=>{this.showControls()})),t.add(s)("mouseenter",(()=>{this.showControls(!1)})),t.add(s)("mouseleave",(e=>{e.relatedTarget&&this.showOnLeaveToClassName&&(0,Me.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)}}var Pe=s(6733);class Te extends we{constructor(e,t,s,i){super({step:1e3/60/1e3,min:0,max:1,withTransition:s,useTransform:i},0),this.progressRAF=0,this.onLoadedData=()=>{this.max=this.media.duration,this.seek.setAttribute("max",""+this.max)},this.onEnded=()=>{this.setProgress()},this.onPlay=()=>{let 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 s=!1;this.setSeekMax(),this.setListeners(),this.setHandlers({onMouseDown:()=>{s=!this.media.paused,s&&this.media.pause()},onMouseUp:e=>{s&&this.media.play()}})}scrub(e){const t=super.scrub(e);return this.media.currentTime=t,t}setLoadProgress(){if(ve.isSafariBuffering(this.media))return;const e=this.media.buffered,t=e.length,s=this.media.currentTime;let i=0,n=0;for(let a=0;a<t;++a){const t=e.start(a);s>=t&&t>=i&&(i=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(ve.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)}}class ke extends we{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,d.d)(e),ve.muted=!ve.muted},this.setVolume=()=>{const{volume:e,muted:t}=ve;let s;s=!e||t?0:e>.5?3:e>0&&e<.25?1:2,ke.ICONS.forEach((e=>this.icon.classList.remove("tgico-"+e))),this.icon.classList.add("tgico-"+ke.ICONS[s]),this.mousedown||this.setProgress(t?0:e)},this.setListeners(),this.setHandlers({onScrub:e=>{const t=Math.max(Math.min(e,1),0);ve.muted=!1,ve.volume=t}});const s="player-volume",i=this.btn=document.createElement("div");i.classList.add("btn-icon",s);const n=this.icon=document.createElement("span");n.classList.add(s+"__icon"),i.append(n,this.container),(0,l.fc)(n,this.onMuteClick,{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.default)("media_playback_params",this.setVolume),this.setVolume()}}ke.ICONS=["volume_off","volume_mute","volume_down","volume_up"];class xe extends Ee{constructor({video:e,play:t=!1,streamable:s=!1,duration:i,onPlaybackRackMenuToggle:n}){if(super(),this.video=e,this.wrapper=document.createElement("div"),this.wrapper.classList.add("ckin__player"),this.onPlaybackRackMenuToggle=n,this.listenerSetter=new B.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(i),this.setBtnMenuToggle(),"default"===this.skin){const t=this.wrapper.querySelector(".default__controls.ckin__controls");this.progress=new Te(e,s),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:s,skin:i,listenerSetter:n}=this;t.classList.add(i);const o=this.buildControls();let r;if(t.insertAdjacentHTML("beforeend",o),"default"===i){this.playbackRateButton=this.wrapper.querySelector(".playback-rate");const e=t.querySelectorAll(".toggle"),i=t.querySelector(".fullscreen"),o=t.querySelector("#time-elapsed");r=t.querySelector("#time-duration"),r.innerHTML=String(0|s.duration).toHHMMSS();const l=new ke(n),c=t.querySelector(".left-controls");l.btn.classList.remove("btn-icon"),c.insertBefore(l.btn,o.parentElement),Array.from(e).forEach((e=>{n.add(e)("click",(()=>{this.togglePlay()}))})),ce.IS_TOUCH_SUPPORTED||(n.add(s)("click",(()=>{this.togglePlay()})),n.add(document)("keydown",(e=>{if(a.default.overlaysActive>1)return;const{key:s,code:i}=e;let n=!0;if("KeyF"===i)this.toggleFullScreen();else if("KeyM"===i)ve.muted=!ve.muted;else if("Space"===i)this.togglePlay();else if(!e.altKey||"Equal"!==i&&"Minus"!==i)!t.classList.contains("ckin__fullscreen")||"ArrowLeft"!==s&&"ArrowRight"!==s?n=!1:"ArrowLeft"===s?ve.seekBackward({action:"seekbackward"}):ve.seekForward({action:"seekforward"});else{const e="Equal"===i?1:-1,t=ve.playbackRate,s=xe.PLAYBACK_RATES.indexOf(t)+e;s>=0&&s<xe.PLAYBACK_RATES.length&&(ve.playbackRate=xe.PLAYBACK_RATES[s])}return n?((0,d.d)(e),!1):void 0}))),n.add(s)("dblclick",(()=>{ce.IS_TOUCH_SUPPORTED||this.toggleFullScreen()})),n.add(i)("click",(()=>{this.toggleFullScreen()})),(0,Pe.Ms)(t,this.onFullScreen.bind(this,i),n),n.add(s)("timeupdate",(()=>{o.innerHTML=String(0|s.currentTime).toHHMMSS()})),n.add(s)("play",(()=>{t.classList.add("played"),ce.IS_TOUCH_SUPPORTED||n.add(s)("play",(()=>{this.hideControls(!0)}))}),{once:!0}),n.add(s)("pause",(()=>{this.showControls(!1)})),n.add(a.default)("media_playback_params",(()=>{this.setPlaybackRateIcon()}))}n.add(s)("play",(()=>{t.classList.add("is-playing")})),n.add(s)("pause",(()=>{t.classList.remove("is-playing")})),s.duration||e?r.innerHTML=String(Math.round(s.duration||e)).toHHMMSS():(0,he.xD)(s).then((()=>{r.innerHTML=String(Math.round(s.duration)).toHHMMSS()}))}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 <button class="btn-icon ${e}__button fullscreen tgico-fullscreen" title="Full Screen"></button>\n </div>\n </div>\n </div>`}setBtnMenuToggle(){const e=xe.PLAYBACK_RATES.map(((e,t)=>({regularText:e+"x",onClick:()=>{ve.playbackRate=e}}))),t=Ce(e);t.classList.add("top-left"),Le(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;xe.PLAYBACK_RATES_ICONS.forEach((t=>{t="tgico-"+t,e.classList.remove(t)}));let t=xe.PLAYBACK_RATES.indexOf(ve.playbackRate);-1===t&&(t=xe.PLAYBACK_RATES.indexOf(1)),e.classList.add("tgico-"+xe.PLAYBACK_RATES_ICONS[t])}toggleFullScreen(){const e=this.wrapper;if(ne.IS_APPLE_MOBILE){const e=this.video;return e.webkitEnterFullscreen(),void e.enterFullscreen()}(0,Pe.rB)()?(0,Pe.C8)():(0,Pe.Dj)(e)}onFullScreen(e){const t=(0,Pe.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"))}removeListeners(){super.cleanup(),this.listenerSetter.removeAll(),this.progress.removeListeners(),this.onPlaybackRackMenuToggle=void 0}}xe.PLAYBACK_RATES=[.5,1,1.5,2],xe.PLAYBACK_RATES_ICONS=["playback_05","playback_1x","playback_15","playback_2x"];var Ae=s(3251),_e=s(319),Ze=s(2614),De=s(3035);function Fe(e){return function(e,t){let s,i=!1;return(...n)=>{s=n,i||(i=!0,e((()=>{i=!1,t(...s)})))}}(De.T2,e)}var Re=s(1507);function Be(e,t=2){if(0===e)return(0,k.i18n)("FileSize.B",[0]);const s=t<0?0:t,i=Math.floor(Math.log(e)/Math.log(1024));return(0,k.i18n)(["FileSize.B","FileSize.KB","FileSize.MB","FileSize.GB"][i],[parseFloat((e/Math.pow(1024,i)).toFixed(s))])}var Ue=s(5296);function Ne(e=!0){const t=new fe.Z({cancelable:!0,tryAgainOnFail:e});return t.construct(),e||(t.circle.setAttributeNS(null,"r","23"),t.totalLength=143.58203125),t}a.default.addEventListener("messages_media_read",(({mids:e,peerId:t})=>{e.forEach((e=>{const s=`[data-mid="${e}"][data-peer-id="${t}"]`;Array.from(document.querySelectorAll(`audio-element.is-unread${s}, .media-round.is-unread${s}`)).forEach((e=>{e.classList.remove("is-unread")}))}))}));const Oe=e=>{let t,s;const i=!e.classList.contains("search-super-item"),n=(0,Me.Z)(e,i?"bubbles-inner":"tabs-tab");if(n){const a=':not([data-is-outgoing="1"])',o=`.audio:not(.is-voice)${a}`;let r;if(r=e.matches(o)?[o]:[`.audio.is-voice${a}`,`.media-round${a}`],i){const e=".bubble:not(.webpage) ";r=r.map((t=>e+t))}const l=r.join(", "),d=Array.from(n.querySelectorAll(l)),c=d.indexOf(e),h=d.map((e=>({peerId:e.dataset.peerId.toPeerId(),mid:+e.dataset.mid})));t=h.slice(0,c),s=h.slice(c+1)}return[t,s]};class He extends HTMLElement{constructor(){super(...arguments),this.withTime=!1,this.voiceAsMusic=!1,this.showSender=!1,this.listenerSetter=new B.Z}render(){var e,t;this.classList.add("audio"),this.dataset.mid=""+this.message.mid,this.dataset.peerId=""+this.message.peerId;const s=i.Z.getMediaFromMessage(this.message),n="voice"===s.type,a=!this.voiceAsMusic&&n,o=this.message.pFlags.is_outgoing,r=o&&this.preloader,c=String(0|s.duration).toHHMMSS();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 h=this.firstElementChild,p=document.createElement("div");p.classList.add("audio-download"),"audio"!==s.type&&this.message&&this.message.pFlags.media_unread&&this.classList.add("is-unread"),r&&(this.classList.add("is-outgoing"),this.append(p));const u=a?function(e){e.classList.add("is-voice");const t=e.message,s=i.Z.getMediaFromMessage(t);t.pFlags.out&&e.classList.add("is-out");let n=s.attributes.find((e=>"documentAttributeAudio"===e._)).waveform||new Uint8Array([]);n=function(e){e instanceof Uint8Array||(e=new Uint8Array(e));const t=8*e.length/5|0;if(!t)return new Uint8Array([]);let s;try{const i=new DataView(e.buffer);s=new Uint8Array(t);for(let e=0;e<t;e++){const t=5*e/8|0,n=5*e%8,a=i.getUint16(t,!0);s[e]=a>>n&31}}catch(e){s=new Uint8Array([])}return s}(n.slice(0,63));const{svg:a,container:o,availW:r}=function(e,t){const s=v.ZP.isMobile?16:23,i=v.ZP.isMobile?152:190,n=v.ZP.isMobile?190:256,a=(0,ye.Z)(t/60*n,i,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",""+s),o.setAttributeNS(null,"viewBox",`0 0 ${a} ${s}`);const r=Math.max(...e),l=e.length?e.length:100,d=Math.min(a/4|0,l);let c=0;const h=s-4;let p="";for(let t=0,i=0,n=0;t<l;++t){const a=e[t]||0;if(n+d>=l){n=n+d-l,n<(d+1)/2&&c<a&&(c=a);const e=Math.max((c*h+(r+1)/2)/(r+1),4);p+=`\n <rect x="${i}" y="${s-e}" width="2" height="${e}" rx="1" ry="1"></rect>\n `,i+=4,c=n<(d+1)/2?0:a}else c<a&&(c=a),n+=d}const u=document.createElement("div");return u.classList.add("audio-waveform"),u.append(o),o.insertAdjacentHTML("beforeend",p),{svg:o,container:u,availW:a}}(n,s.duration),c=o.cloneNode(!0);c.classList.add("audio-waveform-fake"),o.classList.add("audio-waveform-background");const h=document.createElement("div");h.classList.add("audio-waveform-container"),h.append(o,c);const p=document.createElement("div");p.classList.add("audio-time"),e.append(h,p);let u=a;return()=>{let t=e.audio;const s=()=>{c.style.width=t.currentTime/t.duration*100+"%"};(!t.paused||t.currentTime>0&&t.currentTime!==t.duration)&&s();const i=Fe(s);return e.addAudioListener("timeupdate",i),e.addAudioListener("ended",i),e.addAudioListener("play",(()=>{(0,Ue.cK)((()=>(s(),!t.paused)),e)})),e.readyPromise.then((()=>{let e=!1,s=!1;function i(e){let s;if(e instanceof MouseEvent)s=e.offsetX;else{const t=e.target.getBoundingClientRect();s=e.targetTouches[0].pageX-t.left}const i=s/r*t.duration;t.currentTime=i}u.addEventListener("mouseleave",(i=>{e&&(t.play(),e=!1),s=!1})),u.addEventListener("mousemove",(t=>{s=!0,e&&i(t)})),u.addEventListener("mousedown",(s=>{s.preventDefault(),0===s.button&&(t.paused||t.pause(),i(s),e=!0)})),u.addEventListener("mouseup",(i=>{s&&e&&(t.play(),e=!1)})),(0,l.fc)(u,(e=>{(0,d.d)(e),t.paused||i(e)}))}),_e.Z),()=>{u.remove(),u=null,t=null}}}(this):function(e){const t=e.withTime,s=e.message,n=i.Z.getMediaFromMessage(s),a="voice"===n.type||"round"===n.type,o=document.createElement("div");if(o.classList.add("audio-description"),!a){const a=[];n.audioPerformer&&a.push((0,Ze.Z)(n.audioPerformer)),t?a.push((0,ie.OD)(s.date)):a.length||a.push(Be(n.size)),e.showSender&&a.push(i.Z.wrapSenderToPeer(s)),o.append(...(0,k.joinElementsWith)(a," • "))}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 r=e.querySelector(".audio-title"),l=new Ae.I;l.dataset.fontWeight=e.dataset.fontWeight,a?l.append(i.Z.wrapSenderToPeer(s)):l.innerHTML=n.audioTitle||n.fileName,r.append(l),e.showSender&&r.append(i.Z.wrapSentTime(s));const d=e.querySelector(".audio-subtitle");return d.append(o),()=>{let t=!1,s=new Te(e.audio,n.supportsStreaming);e.addAudioListener("ended",(()=>{e.classList.remove("audio-show-progress"),d.lastChild.replaceWith(o),t=!1}));const i=()=>{t||(e.classList.add("audio-show-progress"),t=!0,s&&d.lastChild.replaceWith(s.container))};return e.addAudioListener("play",i),(!e.audio.paused||e.audio.currentTime>0)&&i(),()=>{s.removeListeners(),s.container.remove(),s=null}}}(this),g=this.querySelector(".audio-time");g.innerHTML=c;const m=this.onLoad=e=>{this.onLoad=void 0;const t=this.audio=ve.addMedia(this.message,e),s=this.readyPromise=(0,se.b)();this.audio.readyState>=this.audio.HAVE_CURRENT_DATA?s.resolve():this.addAudioListener("canplay",(()=>s.resolve()),{once:!0}),this.onTypeDisconnect=u();const i=()=>String(0|t.currentTime).toHHMMSS()+(a?" / "+c:""),n=()=>{g.innerText=i(),h.classList.toggle("playing",!t.paused)};(!t.paused||t.currentTime>0&&t.currentTime!==t.duration)&&n();const o=(e,s=t.paused)=>{if(e&&(0,d.d)(e),s){const e=!!this.searchContext;if(ve.setSearchContext(this.searchContext||{peerId:Re.NM,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1})){const[t,s]=e?Oe(this):[];ve.setTargets({peerId:this.message.peerId,mid:this.message.mid},t,s)}t.play().catch((()=>{}))}else t.pause()};return(0,l.fc)(h,(e=>o(e)),{listenerSetter:this.listenerSetter}),this.addAudioListener("ended",(()=>{h.classList.remove("playing"),g.innerText=c})),this.addAudioListener("timeupdate",(()=>{!t.currentTime&&t.paused||ve.isSafariBuffering(t)||(g.innerText=i())})),this.addAudioListener("pause",(()=>{h.classList.remove("playing")})),this.addAudioListener("play",n),o};if(null===(e=s.thumbs)||void 0===e?void 0:e.length){const e=[],t=Ss({photo:s,message:null,container:h,boxWidth:48,boxHeight:48,loadPromises:this.loadPromises,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue});h.style.width=h.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(o)r&&(this.dataset.isOutgoing="1",this.preloader.attach(p,!1));else{let e=this.preloader;const i="audio"!==s.type;m(i);const n=t=>{if(this.audio.src)return;ve.resolveWaitingForLoadMedia(this.message.peerId,this.message.mid,this.message.pFlags.is_scheduled);const i=()=>{t&&(ve.willBePlayed(this.audio),ne.IS_SAFARI&&!this.audio.autoplay&&(this.audio.autoplay=!0))};if(i(),!e)if(s.supportsStreaming){let e;this.classList.add("corner-download");const t=()=>{const t=Ne(!1),s=(0,se.b)();s.notifyAll({done:75,total:100}),s.catch((()=>{this.audio.pause(),ve.willBePlayed(void 0)})),s.cancel=()=>{s.cancel=_e.Z;const e=new Error;e.type="CANCELED",s.reject(e)},t.attach(p,!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=Ne(),t||(this.readyPromise=(0,se.b)());const n=()=>{i();const n=L.Z.downloadDoc(s);return t||n.then((()=>{this.readyPromise.resolve()})),e.attach(p,!1,n),{download:n}};e.setDownloadFunction(n),n()}this.classList.contains("corner-download")?h.append(p):this.append(p),this.classList.add("downloading"),this.readyPromise.then((()=>{this.classList.remove("downloading"),p.classList.add("downloaded"),setTimeout((()=>{p.remove()}),200),ve.willBePlayedMedia===this.audio&&(this.audio.play(),ve.willBePlayed(void 0))}))};(null===(t=this.audio)||void 0===t?void 0:t.src)||(i?n(!1):(0,l.fc)(h,(()=>{n(!0)}),{once:!0,capture:!0,passive:!1,listenerSetter:this.listenerSetter}))}}get addAudioListener(){return this.listenerSetter.add(this.audio)}disconnectedCallback(){this.isConnected||(this.onTypeDisconnect&&(this.onTypeDisconnect(),this.onTypeDisconnect=null),this.readyPromise&&this.readyPromise.reject(),this.listenerSetter.removeAll(),this.listenerSetter=null,this.preloader=null)}}customElements.define("audio-element",He);var ze=s(8456);class Ve{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)}}const je=32;function Ge(e){var t,s;let{title:n,titleEl:a,subtitle:o,subtitleEl:l,mediaEl:d,message:c,loadPromises:h}=e;void 0!==n&&("string"==typeof n&&(n=(0,ze.Z)(n,140),n=Q.o.wrapEmojiText(n)),(0,T.Z)(a,n)),h||(h=[]);let p=c&&c.media,u=!1,g=!1;const m=d?Array.from(d.children).slice():[];let v;if(p&&d){if(l.textContent="",l.append(i.Z.wrapMessageForReply(c,void 0,void 0,void 0,void 0,!0)),p.webpage&&(p=p.webpage),p.photo||p.document&&(null===(t=p.document.thumbs)||void 0===t?void 0:t.length)){v=Ol.chat.bubbles.getMiddleware();const e=Ol.chat.bubbles.lazyLoadQueue;if("sticker"===(null===(s=p.document)||void 0===s?void 0:s.type))u=!0,Is({doc:p.document,div:d,lazyLoadQueue:e,group:Bl,width:je,height:je,middleware:v,loadPromises:h});else{const t=p.photo||p.document;g="round"===t.type;try{Ss({photo:t,container:d,boxWidth:je,boxHeight:je,size:r.Z.choosePhotoSize(t,je,je),middleware:v,lazyLoadQueue:e,noBlur:!0,withoutPreloader:!0,loadPromises:h}),u=!0}catch(e){}}}}else c?(l.textContent="",l.append(i.Z.wrapMessageForReply(c))):("string"==typeof o&&(o=(0,ze.Z)(o,140),o=Q.o.wrapEmojiText(o)),(0,T.Z)(l,o||""));return Promise.all(h).then((()=>{v&&!v()||(m.forEach((e=>e.remove())),d&&d.classList.toggle("is-round",g))})),u}class Ke extends Ve{constructor(e){super(e,((e,t="",s)=>{this.mediaEl||(this.mediaEl=document.createElement("div"),this.mediaEl.classList.add(this.className+"-media"));const i=Ge({title:e,titleEl:this.title,subtitle:t,subtitleEl:this.subtitle,mediaEl:this.mediaEl,message:s});this.container.classList.toggle("is-media",i),i?this.content.prepend(this.mediaEl):this.mediaEl.remove()})),this.className=e}}function We(e,t){return e.reduce(((e,t)=>e+t),t)}class qe{constructor(e,t,s,i,n=t){this.sizes=e,this.maxWidth=t,this.minWidth=s,this.spacing=i,this.maxHeight=n,this.count=e.length,this.ratios=qe.countRatios(e),this.proportions=qe.countProportions(this.ratios),this.averageRatio=We(this.ratios,1)/this.count,this.maxSizeRatio=t/this.maxHeight}layout(){return this.count?this.count>=5||this.ratios.find((e=>e>2))?new $e(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),s=this.maxWidth-t-this.spacing,i=Math.min(this.maxHeight,Math.round(Math.min(s/this.ratios[0],t/this.ratios[1])));return[{geometry:{x:0,y:0,width:s,height:i},sides:13},{geometry:{x:s+this.spacing,y:0,width:t,height:i},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]))),s=e-t-this.spacing,i=Math.max(this.minWidth,Math.round(Math.min((this.maxWidth-this.spacing)/2,Math.min(t*this.ratios[2],s*this.ratios[1])))),n=Math.min(Math.round(e*this.ratios[0]),this.maxWidth-this.spacing-i);return[{geometry:{x:0,y:0,width:n,height:e},sides:13},{geometry:{x:n+this.spacing,y:0,width:i,height:s},sides:3},{geometry:{x:n+this.spacing,y:s+this.spacing,width:i,height:t},sides:6}]}layoutThreeTopAndOther(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],.66*(this.maxHeight-this.spacing))),s=(this.maxWidth-this.spacing)/2,i=Math.min(this.maxHeight-t-this.spacing,Math.round(Math.min(s/this.ratios[1],s/this.ratios[2]))),n=e-s-this.spacing;return[{geometry:{x:0,y:0,width:e,height:t},sides:11},{geometry:{x:0,y:t+this.spacing,width:s,height:i},sides:12},{geometry:{x:s+this.spacing,y:t+this.spacing,width:n,height:i},sides:6}]}layoutFourTopAndOther(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],.66*(this.maxHeight-this.spacing))),s=Math.round((this.maxWidth-2*this.spacing)/(this.ratios[1]+this.ratios[2]+this.ratios[3])),i=Math.max(this.minWidth,Math.round(Math.min(.4*(this.maxWidth-2*this.spacing),s*this.ratios[1]))),n=Math.round(Math.max(Math.max(1*this.minWidth,.33*(this.maxWidth-2*this.spacing)),s*this.ratios[3])),a=e-i-n-2*this.spacing,o=Math.min(this.maxHeight-t-this.spacing,s);return[{geometry:{x:0,y:0,width:e,height:t},sides:11},{geometry:{x:0,y:t+this.spacing,width:i,height:o},sides:12},{geometry:{x:i+this.spacing,y:t+this.spacing,width:a,height:o},sides:4},{geometry:{x:i+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))),s=Math.round((this.maxHeight-2*this.spacing)/(1/this.ratios[1]+1/this.ratios[2]+1/this.ratios[3])),i=Math.round(s/this.ratios[1]),n=Math.round(s/this.ratios[2]),a=e-i-n-2*this.spacing,o=Math.max(this.minWidth,Math.min(this.maxWidth-t-this.spacing,s));return[{geometry:{x:0,y:0,width:t,height:e},sides:13},{geometry:{x:t+this.spacing,y:0,width:o,height:i},sides:3},{geometry:{x:t+this.spacing,y:i+this.spacing,width:o,height:n},sides:2},{geometry:{x:t+this.spacing,y:i+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 $e{constructor(e,t,s,i,n,a=4*s/3){this.averageRatio=t,this.maxWidth=s,this.minWidth=i,this.spacing=n,this.maxHeight=a,this.ratios=$e.cropRatios(e,t),this.count=e.length}static cropRatios(e,t){return e.map((e=>t>1.1?(0,ye.Z)(e,1,2.75):(0,ye.Z)(e,.6667,1)))}layout(){let e=new Array(this.count),t=[];const s=(e,t)=>{const s=We(this.ratios.slice(e,e+t),0);return(this.maxWidth-(t-1)*this.spacing)/s},i=e=>{let i=[],n=0;for(let t of e)i.push(s(n,t)),n+=t;t.push({lineCounts:e,heights:i})};for(let e=1;e!==this.count;++e){const t=this.count-e;e>3||t>3||i([e,t])}for(let e=1;e!==this.count-1;++e)for(let t=1;t!==this.count-e;++t){const s=this.count-e-t;e>3||t>(this.averageRatio<.85?4:3)||s>3||i([e,t,s])}for(let e=1;e!==this.count-1;++e)for(let t=1;t!==this.count-e;++t)for(let s=1;s!==this.count-e-t;++s){const n=this.count-e-t-s;e>3||t>3||s>3||n>3||i([e,t,s,n])}let n=null,a=0;for(const e of t){const{heights:t,lineCounts:s}=e,i=s.length,o=We(t,0)+this.spacing*(i-1),r=Math.min(...t),l=(Math.max(...t),r<this.minWidth?1.5:1),d=(()=>{for(let e=1;e!==i;++e)if(s[e-1]>s[e])return 1.5;return 1})(),c=Math.abs(o-this.maxHeight)*l*d;(!n||c<a)&&(n=e,a=c)}const o=n.lineCounts,r=n.heights,l=o.length;let d=0,c=0;for(let t=0;t!==l;++t){const s=o[t],i=r[t],n=Math.round(i);let a=0;for(let o=0;o!==s;++o){const r=0|(0===t?1:0)|(t===l-1?4:0)|(0===o?8:0)|(o===s-1?2:0),h=this.ratios[d],p=o===s-1?this.maxWidth-a:Math.round(h*i);e[d]={geometry:{x:a,y:c,width:p,height:n},sides:r},a+=p+this.spacing,++d}c+=n+this.spacing}return e}}var Qe=s(7995),Ye=s(8045);class Xe{constructor(e){this._disabled=!1,this.avatarSize=120,this.isChanged=()=>{if(this.uploadAvatar)return!0;let e=0,t=0,s=0;return this.inputFields.forEach((i=>{i.isValid()&&(i.isChanged()&&++e,i.required&&++s),i.required&&++t})),t===s&&e>0},this.handleChange=()=>{this.nextBtn.classList.toggle("is-visible",this.isChanged())},(0,w.Z)(this,e),this.nextBtn?this.nextBtn.classList.contains("btn-corner")||(this.handleChange=()=>{this.nextBtn.toggleAttribute("disabled",!this.isChanged()||this.disabled)}):this.nextBtn=W({icon:"check"}),e.withoutAvatar||(this.avatarElem=document.createElement("avatar-element"),this.avatarElem.classList.add("avatar-placeholder","avatar-"+this.avatarSize),this.avatarElem.setAttribute("peer",""+this.peerId),e.doNotEditAvatar||(this.avatarEdit=new K((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 Je(e,t){const s=document.createElement("form");return e.forEach((e=>{const{container:i,input:n}=e;s.append(i),n.addEventListener("change",(e=>{n.checked&&t(n.value,e)}))})),s}class et{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?m(this.subtitle,e.subtitle):this.subtitle.append(e.subtitle):e.subtitleLangKey&&this.subtitle.append((0,k.i18n)(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 s=e.checkboxField.label.classList.contains("checkbox-field-toggle");s?(this.container.classList.add("row-with-toggle"),e.titleRight=this.checkboxField.label):(t=!0,this.container.append(this.checkboxField.label)),e.noCheckboxSubtitle||s||this.checkboxField.input.addEventListener("change",(()=>{(0,T.Z)(this.subtitle,(0,k.i18n)(this.checkboxField.input.checked?"Checkbox.Enabled":"Checkbox.Disabled"))}))}(e.radioField||e.checkboxField).label.classList.add("disable-hover")}if(e.title||e.titleLangKey){let t;const s=e.titleRight||e.titleRightSecondary;if(s?(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.title?"string"==typeof e.title?this.title.innerHTML=e.title:this.title.append(e.title):this.title.append((0,k.i18n)(e.titleLangKey)),t.append(this.title),s){const i=this.titleRight=document.createElement("div");i.classList.add("row-title","row-title-right"),e.titleRightSecondary&&i.classList.add("row-title-right-secondary"),"string"==typeof s?i.innerHTML=s:i.append(s),t.append(i)}}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&&this.container.addEventListener("click",(t=>{this.freezed||e.clickable(t)})),this.container.classList.add("row-clickable","hover-effect"),e.noRipple||(0,ee.ripple)(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 tt=(e,t)=>Je(e.map((e=>({container:e.container,input:e.radioField.input}))),t);function st(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 it=s(144),nt=s(9750);class at{constructor(e){const t=this.label=document.createElement("label");t.classList.add("radio-field"),e.alignRight&&t.classList.add("radio-field-right");const s=this.input=document.createElement("input");s.type="radio",s.name="input-radio-"+e.name,e.value&&(s.value=e.value,e.stateKey&&(M.default.getState().then((t=>{s.checked=(0,nt.Z)(t,e.stateKey)===e.value})),s.addEventListener("change",(()=>{M.default.setByKey(e.stateKey,e.value)}))));const i=this.main=document.createElement("div");i.classList.add("radio-field-main"),e.text?i.innerHTML=e.text:e.langKey&&(0,k._i18n)(i,e.langKey),t.append(s,i)}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}}const ot=document.createElement("div");function rt(e){(0,T.Z)(ot,e),document.body.append(ot),ot.dataset.timeout&&clearTimeout(+ot.dataset.timeout),ot.dataset.timeout=""+setTimeout((()=>{ot.remove(),delete ot.dataset.timeout}),3e3)}function lt(e){rt((0,k.i18n)(e.langPackKey))}function dt(e,t,s=!0,i=!0){let n,a,o,r,l=!1;return(...d)=>(a||(a=new Promise(((e,t)=>(o=e,r=t)))),n?(clearTimeout(n),l=!0,r(),a=new Promise(((e,t)=>(o=e,r=t)))):s&&(o(e(...d)),l=!1),n=setTimeout((()=>{!i||s&&!l||o(e(...d)),n=a=o=r=void 0,l=!1}),t),a.catch((()=>{})),a)}ot.classList.add("toast");var ct=s(9518);class ht extends _.Z{constructor(e){super(e),this.checkUsernameDebounced=dt(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(_.I.Neutral,this.options.label),void(this.options.onChange&&this.options.onChange());Q.Z.isUsernameValid(e)?this.setState(_.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=ct.Z.invokeApi("channels.checkUsername",{channel:j.Z.getChannelInput(this.options.peerId.toChatId()),username:e}):this.checkUsernamePromise=ct.Z.invokeApi("account.checkUsername",{username:e}),this.checkUsernamePromise.then((t=>{this.getValue()===e&&(t?this.setState(_.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()&&Q.Z.isUsernameValid(t)&&this.checkUsername(t)})))}}var pt=s(1168),ut=s(9807);class gt extends pt.Z{constructor(e,t={}){if(super("popup-peer"+(e?" "+e:""),t.buttons&&(0,pt.x)(t.buttons),Object.assign({overlayClosable:!0},t)),this.className=e,t.peerId){let e=new Yl;e.setAttribute("dialog","1"),e.setAttribute("peer",""+t.peerId),e.classList.add("avatar-32"),this.header.prepend(e)}t.noTitle||(t.titleLangKey||!t.title?this.title.append((0,k.i18n)(t.titleLangKey||"AppName",t.titleLangArgs)):t.title instanceof HTMLElement?this.title.append(t.title):this.title.innerText=t.title||"");const s=document.createDocumentFragment();if(t.descriptionLangKey||t.description){const e=this.description=document.createElement("p");e.classList.add("popup-description"),t.descriptionLangKey?e.append((0,k.i18n)(t.descriptionLangKey,t.descriptionLangArgs)):t.description&&(e.innerHTML=t.description),s.append(e)}t.checkboxes&&(this.container.classList.add("have-checkbox"),t.checkboxes.forEach((e=>{e.withRipple=!1;const t=new ut.Z(e);e.checkboxField=t,s.append(t.label)})),t.buttons.forEach((e=>{if(e.callback){const s=e.callback;e.callback=()=>{const e=new Set;t.checkboxes.forEach((t=>{t.checkboxField.checked&&e.add(t.text)})),s(e)}}}))),this.container.insertBefore(s,this.header.nextElementSibling)}}var mt=s(1656);class vt extends H{init(){this.container.classList.add("edit-peer-container","group-type-container");const e=j.Z.isBroadcast(this.chatId);this.setTitle(e?"ChannelType":"GroupType");const t=new Mn({name:e?"ChannelType":"GroupType"}),s=(0,it.a)(),i=new et({radioField:new at({langKey:e?"ChannelPrivate":"MegaPrivate",name:s,value:"private"}),subtitleLangKey:e?"ChannelPrivateInfo":"MegaPrivateInfo"}),o=new et({radioField:new at({langKey:e?"ChannelPublic":"MegaPublic",name:s,value:"public"}),subtitleLangKey:e?"ChannelPublicInfo":"MegaPublicInfo"}),r=tt([i,o],(e=>{const t=[c,u];"public"===e&&t.reverse(),t[0].container.classList.remove("hide"),t[1].container.classList.add("hide"),v()})),d=j.Z.getChat(this.chatId);t.content.append(r);const c=new Mn({}),h=new et({title:this.chatFull.exported_invite.link,subtitleLangKey:e?"ChannelPrivateLinkHelp":"MegaPrivateLinkHelp",clickable:()=>{st(this.chatFull.exported_invite.link),rt(k.default.format("LinkCopied",!0))}}),p=(0,U.Z)("btn-primary btn-transparent danger",{icon:"delete",text:"RevokeLink"});(0,l.fc)(p,(()=>{new gt("revoke-link",{buttons:[{langKey:"RevokeButton",callback:()=>{const e=(0,mt.Z)([p],!0);n.default.getChatInviteLink(this.chatId,!0).then((t=>{e(),h.title.innerHTML=t}))}}],titleLangKey:"RevokeLink",descriptionLangKey:"RevokeAlert"}).show()}),{listenerSetter:this.listenerSetter}),c.content.append(h.container,p);const u=new Mn({caption:e?"Channel.UsernameAboutChannel":"Channel.UsernameAboutGroup",noDelimiter:!0}),g=document.createElement("div");g.classList.add("input-wrapper");const m="t.me/",v=()=>{const e=i.radioField.checked&&b!==m||f.isValidToChange()&&f.input.classList.contains("valid");y.classList.toggle("is-visible",e)},f=new ht({label:"SetUrlPlaceholder",name:"group-public-link",plainText:!0,listenerSetter:this.listenerSetter,availableText:"Link.Available",invalidText:"Link.Invalid",takenText:"Link.Taken",onChange:v,peerId:this.chatId.toPeerId(!0),head:m}),b=m+(d.username||"");g.append(f.container),u.content.append(g);const y=W({icon:"check",className:"is-visible"});this.content.append(y),(0,l.fc)(y,(()=>{(0,J.px)(y);const e=o.radioField.checked?f.getValue():"";j.Z.migrateChat(this.chatId).then((t=>j.Z.updateUsername(t,e))).then((()=>{this.close()}))}),{listenerSetter:this.listenerSetter}),(b!==m?o:i).radioField.checked=!0,f.setOriginalValue(b),this.scrollable.append(t.container,c.container,u.container);{const t=new Mn({name:"SavingContentTitle",caption:e?"RestrictSavingContentInfoChannel":"RestrictSavingContentInfoGroup"}),s=new ut.Z({text:"RestrictSavingContent",withRipple:!0});this.listenerSetter.add(s.input)("change",(()=>{const e=s.toggleDisability(!0);j.Z.toggleNoForwards(this.chatId,s.checked).then((()=>{e()}))}));const i=()=>{s.setValueSilently(!!d.pFlags.noforwards)};this.listenerSetter.add(a.default)("chat_update",(e=>{this.chatId===e&&i()})),i(),t.content.append(s.label),this.scrollable.append(t.container)}}}var ft=s(4668);class bt{constructor(e){this.loading=!1,this.loaded=!1,(0,w.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 yt=s(4789),wt=s(8763),St=s(1431),Ct=s(241),Lt=s(6690),It=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Mt{constructor(e){this.container=document.createElement("div"),this.list=pd.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(let e in this.tempIds)++this.tempIds[e];this.list=pd.createChatList(),this.promise=null,this.loadedWhat={},this.query=e,this.renderedPeerIds.clear(),this.needSwitchList=!0,this.getMoreResults()}},this.checkForTriggers=()=>{this.scrollable.checkForTriggers()},(0,w.Z)(this,e),this.container.classList.add("selector");const t=(this.renderResultsFunc||this.renderResults).bind(this);if(this.renderResultsFunc=e=>(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=e.filter((e=>!(e.isPeerId()&&!o.Z.getPeer(e).deleted)||this.filterPeerTypeBy.find((t=>o.Z[t](e)))))),t(e)),this.input=document.createElement("input"),this.input.classList.add("selector-search-input"),this.placeholder?(0,k._i18n)(this.input,this.placeholder,void 0,"placeholder"):(0,k._i18n)(this.input,"SendMessageTo",void 0,"placeholder"),this.input.type="text",this.multiSelect){const e=new Mn({});e.innerContainer.classList.add("selector-search-section");let 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 P.ZP(t),(0,l.fc)(this.selectedContainer,(e=>{if(this.freezed)return;let t=e.target;if(t=(0,Me.Z)(t,"selector-user"),!t)return;const s=t.dataset.key,i=this.chatsContainer.querySelector('[data-peer-id="'+s+'"]');i?i.click():this.remove(s.toPeerId())})),e.content.append(t),this.container.append(e.container)}this.chatsContainer.classList.add("chatlist-container");const s=new Mn({name:this.sectionNameLangPackKey,noShadow:!0});s.content.append(this.list),this.chatsContainer.append(s.container),this.scrollable=new P.ZP(this.chatsContainer),this.scrollable.setVirtualContainer(this.list),(0,l.fc)(this.chatsContainer,(e=>{const t=(0,wt.Z)(e.target,"data-peer-id");if((0,d.d)(e),!t)return;if(this.freezed)return;let s=t.dataset.peerId;if(s=s.isPeerId()?s.toPeerId():s,!this.multiSelect)return void this.add(s);this.selected.has(s)?this.remove(s):this.add(s);const i=t.querySelector("input");i.checked=!i.checked}));const i=dt(this.onInput,200,!1,!0);this.input.addEventListener("input",i),this.scrollable.onScrolledBottom=()=>{this.getMoreResults()},this.scrollable.container.prepend(Pn()),this.container.append(this.chatsContainer),this.appendTo.append(this.container),setTimeout((()=>{let t=this.getMoreResults();e.onFirstRender&&t.then((()=>{e.onFirstRender()}))}),0)}renderSaved(){this.exceptSelf||this.offsetIndex||0!==this.folderId||!this.peerType.includes("dialogs")||this.query&&!E.Z.testSelfSearch(this.query)||this.renderResultsFunc([a.default.myId])}getTempId(e){return void 0===this.tempIds[e]&&(this.tempIds[e]=0),++this.tempIds[e]}getMoreDialogs(){return It(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(this.loadedWhat.dialogs&&this.loadedWhat.archived)return;const e=Ct.Z.height/72*1.25|0,t=this.getTempId("dialogs"),s=i.Z.getConversations(this.query,this.offsetIndex,e,this.folderId,!0).promise;this.promise=s;const n=yield s;if(this.tempIds.dialogs!==t)return;this.promise=null;let o=n.dialogs;if(o.length){const e=o[o.length-1].index||0;o=o.slice(),o.findAndSplice((e=>e.peerId===a.default.myId)),this.chatRightsAction&&(o=o.filter((e=>this.filterByRights(e.peerId)))),this.renderSaved(),this.offsetIndex=e}if(this.renderResultsFunc(o.map((e=>e.peerId))),n.isEnd){if(!this.loadedWhat.dialogs)return 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 e.isUser()&&("send_messages"!==this.chatRightsAction||E.Z.canSendToUser(e))||j.Z.hasRights(e.toChatId(),this.chatRightsAction)}getMoreContacts(){return It(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"),s=Promise.all([e?E.Z.getContactsPeerIds(this.query):[],this.query?E.Z.searchContacts(this.query):void 0]);this.promise=s;let[i,n]=yield s;if(this.tempIds.contacts!==t)return;if(n){let t=e?n.my_results.concat(n.results):n.my_results;this.chatRightsAction&&(t=t.filter((e=>this.filterByRights(e)))),this.peerType.includes("dialogs")||(t=t.filter((e=>e.isUser()))),this.cachedContacts=(0,Lt.Z)(i.concat(t))}else this.cachedContacts=i.slice();(0,z.Z)(this.cachedContacts,a.default.myId),this.promise=null}const t=Ct.Z.height/72*1.25|0,s=this.cachedContacts.splice(0,t);this.renderResultsFunc(s),this.cachedContacts.length||(this.loadedWhat.contacts=!0)}))}getMoreChannelParticipants(){return It(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(this.loadedWhat.channelParticipants)return;const e=this.getTempId("channelParticipants"),t=n.default.getChannelParticipants(this.peerId.toChatId(),{_:"channelParticipantsSearch",q:this.query},50,this.list.childElementCount),s=yield t;if(this.tempIds.channelParticipants!==e)return;const i=s.participants.map((e=>j.Z.getParticipantPeerId(e)));(0,z.Z)(i,a.default.myId),this.renderResultsFunc(i),(this.list.childElementCount>=s.count||s.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){!this.peerType.includes("dialogs")&&this.loadedWhat.contacts&&(e=e.filter((e=>E.Z.isNonContactUser(e)))),e.forEach((e=>{const{dom:t}=pd.addDialogNew({dialog:e,container:this.scrollable,drawStatus:!1,rippleEnabled:this.rippleEnabled,avatarSize:this.avatarSize});if(this.multiSelect){const s=this.selected.has(e),i=new ut.Z;s&&(i.input.checked=!0),t.containerEl.prepend(i.label)}let s;s=e.isAnyChat()?n.default.getChatMembersString(e.toChatId()):e===a.default.myId?(0,k.i18n)(this.selfPresence):E.Z.getUserStatusString(e),t.lastMessageSpan.append(s)}))}add(e,t,s=!0){if(this.selected.add(e),!this.multiSelect)return void this.onChange(this.selected.size);this.query.trim()&&(this.input.value="",this.onInput());const i=document.createElement("div");i.classList.add("selector-user","scale-in");const n=document.createElement("avatar-element");return n.classList.add("selector-user-avatar","tgico"),n.setAttribute("dialog","1"),n.classList.add("avatar-32"),i.dataset.key=""+e,e.isPeerId()&&(void 0===t&&(t=new St.Z({peerId:e.toPeerId(),dialog:!0}).element),n.setAttribute("peer",""+e)),t&&("string"==typeof t?i.innerHTML=t:((0,T.Z)(i,t),i.append(t))),i.insertAdjacentElement("afterbegin",n),this.selectedContainer.insertBefore(i,this.input),this.onChange&&this.onChange(this.selected.size),s&&this.selectedScrollable.scrollIntoViewNew({element:this.input,position:"center"}),i}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 s=()=>{this.selected.delete(e),t.remove(),this.onChange&&this.onChange(this.selected.size)};a.default.settings.animationsEnabled?t.addEventListener("animationend",s,{once:!0}):s()}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:yt.f.Static})}))}}class Et extends pt.Z{constructor(e){super("popup-forward",null,{closable:!0,overlayClosable:!0,body:!0}),this.selector=new Mt({appendTo:this.body,onChange:()=>{return t=this,s=void 0,n=function*(){const t=this.selector.getSelected(),s=t[t.length-1].toPeerId();if(e.onSelect){const t=e.onSelect(s);if(t instanceof Promise)try{yield t}catch(e){return}}this.selector=null,this.hide()},new((i=void 0)||(i=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 s;t.done?e(t.value):(s=t.value,s instanceof i?s:new i((function(e){e(s)}))).then(o,r)}l((n=n.apply(t,s||[])).next())}));var t,s,i,n},peerType:e.peerTypes,onFirstRender:()=>{this.show(),this.selector.checkForTriggers(),ce.IS_TOUCH_SUPPORTED||this.selector.input.focus()},chatRightsAction:e.chatRightsAction,multiSelect:!1,rippleEnabled:!1,avatarSize:46,peerId:e.peerId,placeholder:e.placeholder,selfPresence:e.selfPresence}),this.title.append(this.selector.input)}}class Pt extends H{init(){let e;this.container.classList.add("edit-peer-container","user-permissions-container"),this.setTitle("UserRestrictions");{const t=new Mn({name:"UserRestrictionsCanDo"}),s=document.createElement("div");s.classList.add("chatlist-container"),t.content.insertBefore(s,t.title);const i=pd.createChatList({new:!0});s.append(i);const{dom:n}=pd.addDialogNew({dialog:this.userId.toPeerId(!1),container:i,drawStatus:!1,rippleEnabled:!0,avatarSize:48});n.lastMessageSpan.append(E.Z.getUserStatusString(this.userId));const a=new kt({chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:t.content,participant:"channelParticipantBanned"===this.participant._?this.participant:void 0});e=()=>{const e=a.takeOut();"channelParticipantBanned"===this.participant._&&(0,ue.Z)(this.participant.banned_rights.pFlags,e.pFlags)||j.Z.editBanned(this.chatId,this.participant,e)},this.eventListener.addEventListener("destroy",e,{once:!0}),this.scrollable.append(t.container)}{const t=new Mn({});if("channelParticipantBanned"===this.participant._){const s=(0,U.Z)("btn-primary btn-transparent danger",{icon:"delete",text:"GroupPermission.Delete"});(0,l.fc)(s,(()=>{const t=(0,mt.Z)([s],!0);j.Z.clearChannelParticipantBannedRights(this.chatId,this.participant).then((()=>{this.eventListener.removeEventListener("destroy",e),this.close()}),(()=>{t()}))}),{listenerSetter:this.listenerSetter}),t.content.append(s)}const s=(0,U.Z)("btn-primary btn-transparent danger",{icon:"deleteuser",text:"UserRestrictionsBlock"});(0,l.fc)(s,(()=>{(0,mt.Z)([s],!0),j.Z.kickFromChannel(this.chatId,this.participant).then((()=>{this.eventListener.removeEventListener("destroy",e),this.close()}))}),{listenerSetter:this.listenerSetter}),t.content.append(s),this.scrollable.append(t.container)}}}var Tt=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class kt{constructor(e){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 t=j.Z.getChat(e.chatId),s=t.default_banned_rights,i=e.participant?j.Z.combineParticipantBannedRights(e.chatId,e.participant.banned_rights):s,n=e.participant?"UserRestrictionsDisabled":"EditCantEditPermissionsPublic";for(const a of this.v){const o=a.flags[0];a.checkboxField=new ut.Z({text:a.text,checked:j.Z.hasRights(e.chatId,o,i),restriction:!0,withRipple:!0}),(e.participant&&s.pFlags[o]||t.username&&(a.flags.includes("pin_messages")||a.flags.includes("change_info")))&&(a.checkboxField.input.disabled=!0,(0,l.fc)(a.checkboxField.label,(e=>{rt(k.default.format(n,!0))}),{listenerSetter:e.listenerSetter})),this.toggleWith[o]&&e.listenerSetter.add(a.checkboxField.input)("change",(()=>{a.checkboxField.checked||this.v.filter((e=>this.toggleWith[o].includes(e.flags[0]))).forEach((e=>{e.checkboxField.checked=!1}))})),e.appendTo.append(a.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 xt extends H{init(){return Tt(this,void 0,void 0,(function*(){let e;this.container.classList.add("edit-peer-container","group-permissions-container"),this.setTitle("ChannelPermissions");{const t=new Mn({name:"ChannelPermissionsHeader"});e=new kt({chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:t.content}),this.eventListener.addEventListener("destroy",(()=>{j.Z.editChatDefaultBannedRights(this.chatId,e.takeOut())}),{once:!0}),this.scrollable.append(t.container)}{const t=new Mn({name:"PrivacyExceptions"}),s=new et({titleLangKey:"ChannelAddException",subtitleLangKey:"Loading",icon:"adduser",clickable:()=>{new Et({peerTypes:["channelParticipants"],onSelect:e=>{setTimeout((()=>{i(e)}),0)},placeholder:"ExceptionModal.Search.Placeholder",peerId:-this.chatId})}}),i=e=>Tt(this,void 0,void 0,(function*(){let t;try{t=yield n.default.getChannelParticipant(this.chatId,e)}catch(e){return void rt("User is no longer participant")}const s=new Pt(this.slider);s.participant=t,s.chatId=this.chatId,s.userId=e,s.open()}));t.content.append(s.container);const r=t.generateContentElement();r.classList.add("chatlist-container");const d=pd.createChatList({new:!0});r.append(d),(0,l.fc)(d,(e=>{const t=(0,ft.Z)(e.target,"LI");if(!t)return;const s=t.dataset.peerId.toPeerId();i(s)}),{listenerSetter:this.listenerSetter});const c=(t,s)=>{const i=s.banned_rights,n=j.Z.getChat(this.chatId).default_banned_rights,a=[];e.v.forEach((e=>{const t=e.flags[0];i.pFlags[t]&&!n.pFlags[t]&&a.push(e.exceptionText)}));const o=t.querySelector(".user-last-message");a.length&&(o.innerHTML="",o.append(...(0,k.join)(a.map((e=>(0,k.i18n)(e))),!1))),o.classList.toggle("hide",!a.length)},h=(e,t)=>{const{dom:s}=pd.addDialogNew({dialog:o.Z.getPeerId(e.peer),container:d,drawStatus:!1,rippleEnabled:!0,avatarSize:48,append:t});c(s.listEl,e)};this.listenerSetter.add(a.default)("updateChannelParticipant",(e=>{var t,s,i;const n="channelParticipantBanned"===(null===(t=e.new_participant)||void 0===t?void 0:t._)&&!e.new_participant.banned_rights.pFlags.view_messages,a=d.querySelector(`[data-peer-id="${e.user_id}"]`);n?(a?c(a,e.new_participant):h(e.new_participant,!1),"channelParticipantBanned"!==(null===(s=e.prev_participant)||void 0===s?void 0:s._)&&++g):(a&&a.remove(),"channelParticipantBanned"===(null===(i=e.prev_participant)||void 0===i?void 0:i._)&&--g),p()}));const p=()=>{(0,T.Z)(s.subtitle,(0,k.i18n)(g?"Permissions.ExceptionsCount":"Permissions.NoExceptions",[g]))};let u,g=0;const m=()=>(u=new bt({scrollable:this.scrollable,getPromise:()=>n.default.getChannelParticipants(this.chatId,{_:"channelParticipantsBanned",q:""},50,d.childElementCount).then((e=>{for(const t of e.participants)h(t,!0);return g=e.count,p(),e.participants.length<50||e.count===d.childElementCount}))}),u.load());this.scrollable.append(t.container),j.Z.isChannel(this.chatId)?yield m():(p(),this.listenerSetter.add(a.default)("dialog_migrate",(({migrateFrom:e,migrateTo:t})=>{this.chatId===e&&(this.chatId=t,m())})))}}))}onOpenAfterTimeout(){this.scrollable.onScroll()}}class At{constructor(e,t=o.Z.getDialogType(e),s){const n=new St.Z({peerId:e}).element,a=(t,n=p&&!!t.size)=>{let a=j.Z.leave(e.toChatId());n&&(a=a.finally((()=>i.Z.flushHistory(e)))),s&&s(a)},r=t=>{let n;if(e.isUser())n=i.Z.flushHistory(e,!1,p?!!t.size:void 0);else{if(!t.size)return a(t);n=j.Z.delete(e.toChatId())}s&&s(n)};let l,d,c,h,p;switch(t){case"channel":j.Z.hasRights(e.toChatId(),"delete_chat")?(j.Z.deleteChannel,l="ChannelDeleteMenu",d="AreYouSureDeleteAndExitChannel",h=[{langKey:"ChannelDeleteMenu",isDanger:!0,callback:r}],p=[{text:"DeleteChannelForAll"}]):(l="LeaveChannelMenu",d="ChannelLeaveAlertWithName",c=[n],h=[{langKey:"LeaveChannel",isDanger:!0,callback:a}]);break;case"chat":l="DeleteChatUser",d="AreYouSureDeleteThisChatWithUser",c=[n],h=[{langKey:"DeleteChatUser",isDanger:!0,callback:r}],p=[{text:"DeleteMessagesOptionAlso",textArgs:[new St.Z({peerId:e}).element]}];break;case"saved":l="DeleteChatUser",d="AreYouSureDeleteThisChatSavedMessages",h=[{langKey:"DeleteChatUser",isDanger:!0,callback:r}];break;case"megagroup":case"group":j.Z.hasRights(e.toChatId(),"delete_chat")?(l="DeleteMegaMenu",d="AreYouSureDeleteAndExit",h=[{langKey:"DeleteMegaMenu",isDanger:!0,callback:r}],p=[{text:"DeleteChat.DeleteGroupForAll"}]):(l="LeaveMegaMenu",d="AreYouSureDeleteAndExitName",c=[n],h=[{langKey:"DeleteChatUser",isDanger:!0,callback:e=>a(e,!0)}])}new gt("popup-delete-chat",{peerId:e,titleLangKey:l,descriptionLangKey:d,descriptionLangArgs:c,buttons:h,checkboxes:p}).show()}}var _t=s(6689);class Zt extends H{init(){var e,t,s,i,a;return t=this,s=void 0,a=function*(){this.setTitle("Reactions");const t=yield _t.Z.getActiveAvailableReactions(),s=yield n.default.getChatFull(this.chatId);let i=null!==(e=s.available_reactions)&&void 0!==e?e:[];const a=new Set(i),o=new Mn({caption:j.Z.isBroadcast(this.chatId)?"EnableReactionsChannelInfo":"EnableReactionsGroupInfo"}),r=new ut.Z({toggle:!0,checked:!!a.size}),l=new et({checkboxField:r,titleLangKey:"EnableReactions"});o.content.append(l.container);const d=new Mn({name:"AvailableReactions"}),c=t.map((e=>{const t=new ut.Z({toggle:!0,checked:a.has(e.reaction)});this.listenerSetter.add(t.input)("change",(()=>{t.checked?(a.add(e.reaction),r.checked||r.setValueSilently(!0)):(a.delete(e.reaction),!a.size&&r.checked&&r.setValueSilently(!1)),p()}));const s=new et({checkboxField:t,title:e.title,havePadding:!0});return Es({row:s,doc:e.static_icon,size:"small"}),d.content.append(s.container),t}));this.listenerSetter.add(l.checkboxField.input)("change",(()=>{r.checked?c.every((e=>!e.checked))&&(c.forEach((e=>e.checked=!0)),p()):(c.forEach((e=>e.checked=!1)),p())}));const h=()=>{const e=Array.from(a);if([...e].sort().join()===[...i].sort().join())return;const t=n.default.getCachedFullChat(this.chatId);t&&(t.available_reactions=e),j.Z.setChatAvailableReactions(this.chatId,e),i=e},p=dt(h,3e3,!1,!0);this.eventListener.addEventListener("destroy",h,{once:!0}),this.scrollable.append(o.container,d.container)},new((i=void 0)||(i=Promise))((function(e,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(t){var s;t.done?e(t.value):(s=t.value,s instanceof i?s:new i((function(e){e(s)}))).then(o,r)}l((a=a.apply(t,s||[])).next())}))}}class Dt extends O{_init(){var e,t,s,i,o;return t=this,s=void 0,o=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 s=yield n.default.getChatFull(this.chatId,!0);const i=j.Z.getChat(this.chatId),o=j.Z.isBroadcast(this.chatId),r=j.Z.isChannel(this.chatId),d=[],c=e=>{d.push(e)};this.listenerSetter.add(a.default)("chat_update",(e=>{this.chatId===e&&d.forEach((e=>e()))})),this.listenerSetter.add(a.default)("chat_full_update",(e=>{this.chatId===e&&(s=n.default.getCachedFullChat(e)||s)}));const h=this.chatId.toPeerId(!0),p=j.Z.hasRights(this.chatId,"change_type"),u=j.Z.hasRights(this.chatId,"change_permissions");{const e=new Mn({noDelimiter:!0}),n=[],r=document.createElement("div");if(r.classList.add("input-wrapper"),this.chatNameInputField=new _.Z({label:o?"EnterChannelName":"CreateGroup.NameHolder",name:"chat-name",maxLength:255,required:!0}),this.descriptionInputField=new _.Z({label:"DescriptionPlaceholder",name:"chat-description",maxLength:255}),this.chatNameInputField.setOriginalValue(i.title),this.descriptionInputField.setOriginalValue(s.about),r.append(this.chatNameInputField.container,this.descriptionInputField.container),n.push(this.chatNameInputField,this.descriptionInputField),this.editPeer=new Xe({peerId:h,inputFields:n,listenerSetter:this.listenerSetter}),this.content.append(this.editPeer.nextBtn),e.content.append(this.editPeer.avatarEdit.container,r),p){const t=new et({titleLangKey:o?"ChannelType":"GroupType",clickable:()=>{const e=new vt(this.slider);e.chatId=this.chatId,e.chatFull=s,e.open(),this.listenerSetter.add(e.eventListener)("destroy",n)},icon:"lock"}),n=()=>{let e;t.subtitle.textContent="",e=o?i.username?"TypePublic":"TypePrivate":i.username?"TypePublicGroup":"TypePrivateGroup",t.subtitle.append((0,k.i18n)(e))};n(),e.content.append(t.container)}if(p||u){const i=new et({titleLangKey:"Reactions",icon:"reactions",clickable:()=>{const e=new Zt(this.slider);e.chatId=this.chatId,e.open().then((()=>{this.tempId===t&&this.listenerSetter.add(e.eventListener)("destroy",a)}))}}),n=(yield _t.Z.getAvailableReactions()).filter((e=>!e.pFlags.inactive)).length,a=()=>{var e;const t=null!==(e=s.available_reactions)&&void 0!==e?e:[];i.subtitle.innerHTML=t.length+"/"+n};a(),e.content.append(i.container)}if(u&&!o){const t=["send_messages","send_media","send_stickers","send_polls","embed_links","invite_users","pin_messages","change_info"],s=new et({titleLangKey:"ChannelPermissions",clickable:()=>{const e=new xt(this.slider);e.chatId=this.chatId,e.open()},icon:"permissions"}),n=()=>{s.subtitle.innerHTML=t.reduce(((e,t)=>e+ +j.Z.hasRights(this.chatId,t,i.default_banned_rights)),0)+"/"+t.length};n(),e.content.append(s.container),this.listenerSetter.add(a.default)("chat_update",(e=>{this.chatId===e&&n()}))}if(this.scrollable.append(e.container),(0,l.fc)(this.editPeer.nextBtn,(()=>{this.editPeer.nextBtn.disabled=!0;let e=[];const t=this.chatId;this.chatNameInputField.isValidToChange()&&e.push(j.Z.editTitle(t,this.chatNameInputField.value)),this.descriptionInputField.isValidToChange()&&e.push(j.Z.editAbout(t,this.descriptionInputField.value)),this.editPeer.uploadAvatar&&e.push(this.editPeer.uploadAvatar().then((e=>j.Z.editPhoto(t,e)))),Promise.race(e).finally((()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()}))}),{listenerSetter:this.listenerSetter}),o&&j.Z.hasRights(this.chatId,"change_info")){const t=new ut.Z({text:"PeerInfo.SignMessages",checked:!!i.pFlags.signatures,withRipple:!0});this.listenerSetter.add(t.input)("change",(()=>{const e=t.toggleDisability(!0);j.Z.toggleSignatures(this.chatId,t.checked).then((()=>{e()}))})),c((()=>{t.setValueSilently(!!i.pFlags.signatures)})),e.content.append(t.label)}}if(!o){const e=new Mn({});if(!o&&p){const t=new ut.Z({text:"ChatHistory",withRipple:!0});this.listenerSetter.add(t.input)("change",(()=>{const e=t.toggleDisability(!0);j.Z.togglePreHistoryHidden(this.chatId,!t.checked).then((()=>{e()}))}));const i=()=>{t.setValueSilently(r&&!s.pFlags.hidden_prehistory)};i(),c(i),e.content.append(t.label)}e.content.childElementCount&&this.scrollable.append(e.container)}if(j.Z.hasRights(this.chatId,"delete_chat")){const e=new Mn({}),t=(0,U.Z)("btn-primary btn-transparent danger",{icon:"delete",text:o?"PeerInfo.DeleteChannel":"DeleteAndExitButton"});(0,l.fc)(t,(()=>{new At(h,void 0,(e=>{const s=(0,mt.Z)([t],!0);e.then((()=>{this.close()}),(()=>{s()}))}))}),{listenerSetter:this.listenerSetter}),e.content.append(t),this.scrollable.append(e.container)}r||this.listenerSetter.add(a.default)("dialog_migrate",(({migrateFrom:e,migrateTo:t})=>{h===e&&(this.chatId=t.toChatId(),this._init())}))},new((i=void 0)||(i=Promise))((function(e,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(t){var s;t.done?e(t.value):(s=t.value,s instanceof i?s:new i((function(e){e(s)}))).then(a,r)}l((o=o.apply(t,s||[])).next())}))}init(){return this._init()}}var Ft=s(9090);class Rt extends O{init(){this.container.classList.add("edit-peer-container","edit-contact-container");const e=!E.Z.isContact(this.peerId.toUserId());this.setTitle(e?"AddContactTitle":"Edit");{const t=new Mn({noDelimiter:!0}),s=[],n=document.createElement("div");if(n.classList.add("input-wrapper"),this.nameInputField=new _.Z({label:"FirstName",name:"contact-name",maxLength:70,required:!0}),this.lastNameInputField=new _.Z({label:"LastName",name:"contact-lastname",maxLength:70}),this.peerId){const t=E.Z.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(n.append(this.nameInputField.container,this.lastNameInputField.container),s.push(this.nameInputField,this.lastNameInputField),this.editPeer=new Xe({peerId:this.peerId,inputFields:s,listenerSetter:this.listenerSetter,doNotEditAvatar:!0}),this.content.append(this.editPeer.nextBtn),this.peerId){const s=document.createElement("div");s.classList.add("avatar-edit"),s.append(this.editPeer.avatarElem);const r=new ut.Z({text:"Notifications"});r.input.addEventListener("change",(e=>{e.isTrusted&&i.Z.togglePeerMute(this.peerId)})),this.listenerSetter.add(a.default)("notify_settings",(e=>{if("notifyPeer"!==e.peer._)return;const t=o.Z.getPeerId(e.peer.peer);if(this.peerId===t){const t=!Ft.Z.isMuted(e.notify_settings);t!==r.checked&&(r.checked=t)}}));const l=document.createElement("div");l.classList.add("profile-name"),l.append(new St.Z({peerId:this.peerId}).element);const d=document.createElement("div");if(d.classList.add("profile-subtitle"),d.append((0,k.i18n)("EditContact.OriginalName")),t.content.append(s,l,d,n),e){const e=E.Z.getUser(this.peerId),s=new et({icon:"phone",titleLangKey:e.phone?void 0:"MobileHidden",title:e.phone?E.Z.formatUserPhone(e.phone):void 0,subtitleLangKey:e.phone?"Phone":"MobileHiddenExceptionInfo",subtitleLangArgs:e.phone?void 0:[new St.Z({peerId:this.peerId}).element]});t.content.append(s.container)}else{const e=new et({checkboxField:r}),s=!Ft.Z.isPeerLocalMuted(this.peerId,!1);r.checked=s,t.content.append(e.container)}}else t.content.append(n);this.scrollable.append(t.container),(0,l.fc)(this.editPeer.nextBtn,(()=>{this.editPeer.nextBtn.disabled=!0,E.Z.addContact(this.peerId,this.nameInputField.value,this.lastNameInputField.value,E.Z.getUser(this.peerId).phone).finally((()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()}))}),{listenerSetter:this.listenerSetter})}if(!e){const e=new Mn({}),t=(0,U.Z)("btn-primary btn-transparent danger",{icon:"delete",text:"PeerInfo.DeleteContact"});(0,l.fc)(t,(()=>{new gt("popup-delete-contact",{peerId:this.peerId,titleLangKey:"DeleteContact",descriptionLangKey:"AreYouSureDeleteContact",buttons:(0,pt.x)([{langKey:"Delete",callback:()=>{const e=(0,mt.Z)([t],!0);E.Z.deleteContacts([this.peerId]).then((()=>{this.close()}),(()=>{e()}))},isDanger:!0}])}).show()}),{listenerSetter:this.listenerSetter}),e.content.append(t),this.scrollable.append(e.container)}}}class Bt extends O{init(){this.container.classList.add("add-members-container"),this.nextBtn=W({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,J.px)(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 s="privacy"===this.peerType;return this.selector=new Mt({appendTo:this.content,onChange:this.skippable?null:e=>{this.nextBtn.classList.toggle("is-visible",!!e)},peerType:[s?"dialogs":"contacts"],placeholder:e.placeholder,exceptSelf:s,filterPeerTypeBy:s?["isAnyGroup","isUser"]:void 0}),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}}const Ut=!ne.IS_FIREFOX&&!1;var Nt=s(6654);function Ot(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttributeNS(null,"viewBox","0 0 24 24"),e.setAttributeNS(null,"width","24"),e.setAttributeNS(null,"height","24"),e.classList.add("verified-icon");const t=document.createElementNS("http://www.w3.org/2000/svg","use");t.setAttributeNS(null,"href","#verified-background"),t.classList.add("verified-background");const s=document.createElementNS("http://www.w3.org/2000/svg","use");return s.setAttributeNS(null,"href","#verified-check"),s.classList.add("verified-check"),e.append(t,s),e}const Ht=e=>e.touches?e.touches[0]:e,zt=window;let Vt=!1;a.default.addEventListener("context_menu_toggle",(e=>{Vt=e}));class jt{constructor(e){this.cursor="grabbing",this.cancelEvent=!0,this.listenerOptions=!1,this.hadMove=!1,this.xDown=null,this.yDown=null,this.reset=e=>{ce.IS_TOUCH_SUPPORTED?zt.removeEventListener("touchmove",this.handleMove,{capture:!0}):(zt.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=>{const t=Ht(e);if(this.verifyTouchTarget&&!this.verifyTouchTarget(e))return this.reset();this.xDown=t.clientX,this.yDown=t.clientY,ce.IS_TOUCH_SUPPORTED?zt.addEventListener("touchmove",this.handleMove,{passive:!1,capture:!0}):zt.addEventListener("mousemove",this.handleMove,!1)},this.handleMove=e=>{if(null===this.xDown||null===this.yDown||Vt)return void this.reset();this.cancelEvent&&(0,d.d)(e);const t=Ht(e),s=t.clientX,i=t.clientY,n=this.xDown-s,a=this.yDown-i;if(!this.hadMove){if(!n&&!a)return;this.hadMove=!0,ce.IS_TOUCH_SUPPORTED||this.setCursorTo.style.setProperty("cursor",this.cursor,"important"),this.onFirstSwipe&&this.onFirstSwipe()}const o=this.onSwipe(n,a,e);void 0!==o&&o&&this.reset()},(0,w.Z)(this,e),this.setCursorTo=this.element,this.setListeners()}setListeners(){ce.IS_TOUCH_SUPPORTED?(this.element.addEventListener("touchstart",this.handleStart,this.listenerOptions),zt.addEventListener("touchend",this.reset)):(this.element.addEventListener("mousedown",this.handleStart,this.listenerOptions),zt.addEventListener("mouseup",this.reset))}removeListeners(){ce.IS_TOUCH_SUPPORTED?(this.element.removeEventListener("touchstart",this.handleStart,this.listenerOptions),zt.removeEventListener("touchend",this.reset)):(this.element.removeEventListener("mousedown",this.handleStart,this.listenerOptions),zt.removeEventListener("mouseup",this.reset))}setCursor(e){this.cursor=e,!ce.IS_TOUCH_SUPPORTED&&this.hadMove&&this.setCursorTo.style.setProperty("cursor",this.cursor,"important")}}class Gt{constructor(e){this.scrollable=e,this.processItem=e=>{const t=document.createElement("div");let s;t.classList.add(Gt.BASE_CLASS+"-avatar","media-container"),e&&(s="object"!=typeof e?r.Z.getPhoto(e):e.action.photo);const i=new Image;i.classList.add("avatar-photo"),i.draggable=!1;const n=()=>{if(s){const e=Ss({container:t,photo:s,size:r.Z.choosePhotoSize(s,420,420,!1),withoutPreloader:!0});[e.images.thumb,e.images.full].filter(Boolean).forEach((e=>{e.classList.add("avatar-photo")}))}else{const e=o.Z.getPeerPhoto(this.peerId);c.Z.putAvatar(t,this.peerId,e,"photo_big",i)}};return this.avatars.childElementCount<=3?n():(this.intersectionObserver.observe(t),this.loadCallbacks.set(t,n)),this.avatars.append(t),this.addTab(),e},this.container=document.createElement("div"),this.container.classList.add(Gt.BASE_CLASS+"-container"),this.avatars=document.createElement("div"),this.avatars.classList.add(Gt.BASE_CLASS+"-avatars"),this.gradient=document.createElement("div"),this.gradient.classList.add(Gt.BASE_CLASS+"-gradient"),this.info=document.createElement("div"),this.info.classList.add(Gt.BASE_CLASS+"-info"),this.tabs=document.createElement("div"),this.tabs.classList.add(Gt.BASE_CLASS+"-tabs"),this.arrowPrevious=document.createElement("div"),this.arrowPrevious.classList.add(Gt.BASE_CLASS+"-arrow","tgico-avatarprevious"),this.arrowNext=document.createElement("div"),this.arrowNext.classList.add(Gt.BASE_CLASS+"-arrow",Gt.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 B.Z;const t=()=>0===this.scrollable.scrollTop||(this.scrollable.scrollIntoViewNew({element:this.scrollable.container.firstElementChild,position:"start"}),!1),s=1/3;let i=!1,n=!1;(0,l.fc)(this.container,(e=>{return a=this,o=void 0,l=function*(){if(n)return void(0,d.d)(e);if(i)return void(i=!1);if(!t())return;const a=this.container.getBoundingClientRect(),o=e.pageX,r=o-a.left;if(!this.listLoader.previous.length&&!this.listLoader.next.length||r>a.width*s&&r<a.width-a.width*s){const e=this.peerId,t=[];this.listLoader.previous.concat(this.listLoader.current,this.listLoader.next).forEach(((e,s)=>{t.push({element:this.avatars.children[s],item:e})}));const s=t.slice(0,this.listLoader.previous.length),i=t.slice(this.listLoader.previous.length+1),a=this.avatars.children[this.listLoader.previous.length];n=!0,ql(a,e,(()=>e===this.peerId),this.listLoader.current,s,i),n=!1}else{const e=o>a.right-a.width/2;let t;this.avatars.classList.add("no-transition"),this.avatars.offsetLeft,t=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(t),(0,De.T2)((()=>{this.avatars.classList.remove("no-transition")}))}},new((r=void 0)||(r=Promise))((function(e,t){function s(e){try{n(l.next(e))}catch(e){t(e)}}function i(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(s,i)}n((l=l.apply(a,o||[])).next())}));var a,o,r,l}),{listenerSetter:this.listenerSetter});const a=()=>{i=!0,document.body.addEventListener(ce.IS_TOUCH_SUPPORTED?"touchend":"click",(e=>{i=!1}),{once:!0})};let h=0,p=0,u=0,g=0;this.swipeHandler=new jt({element:this.avatars,onSwipe:(e,t)=>{u=e;let s=p+e*-Gt.SCALE;return s>0?s=0:s<g&&(s=g),this.avatars.style.transform=Gt.TRANSLATE_TEMPLATE.replace("{x}",s+"px"),!1},verifyTouchTarget:e=>t()?!this.container.classList.contains("is-single")&&!n:(a(),(0,d.d)(e),!1),onFirstSwipe:()=>{const e=this.avatars.getBoundingClientRect();h=e.width,g=-h*(this.tabs.childElementCount-1),p=e.left-this.container.getBoundingClientRect().left,this.avatars.style.transform=Gt.TRANSLATE_TEMPLATE.replace("{x}",p+"px"),this.container.classList.add("is-swiping"),this.avatars.classList.add("no-transition"),this.avatars.offsetLeft},onReset:()=>{const e=Math.ceil(Math.abs(u)/(h/Gt.SCALE))*(u>=0?1:-1);a(),this.avatars.classList.remove("no-transition"),(0,De.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){this.peerId=e;const t=o.Z.getPeerPhoto(e);if(!t)return;const s=this.listLoader=new S({loadCount:50,loadMore:(t,a,o)=>{if(!a)return Promise.resolve({count:void 0,items:[]});if(e.isUser()){const i=t||s.current;return r.Z.getUserPhotos(e,i,o).then((e=>({count:e.count,items:e.photos})))}{const t=[];return s.current||t.push(Promise.resolve(n.default.getChatFull(e.toChatId()))),t.push(i.Z.getSearch({peerId:e,maxId:Number.MAX_SAFE_INTEGER,inputFilter:{_:"inputMessagesFilterChatPhotos"},limit:o,backLimit:0})),Promise.all(t).then((e=>{const t=e.pop();if(y(t),!s.current){const n=e[0],a=t.history.findAndSplice((e=>e.action.photo.id===n.chat_photo.id));s.current=a||i.Z.generateFakeAvatarMessage(this.peerId,n.chat_photo)}return{count:t.count,items:t.history}}))}},processItem:this.processItem,onJump:(e,t)=>{const s=this.listLoader.index,i=100*Gt.SCALE*s;this.avatars.style.transform=Gt.TRANSLATE_TEMPLATE.replace("{x}",`-${i}%`);const n=this.tabs.querySelector(".active");n&&n.classList.remove("active"),this.tabs.children[s].classList.add("active"),this.loadNearestToTarget(this.avatars.children[s])}});"userProfilePhoto"===t._&&(s.current=t.photo_id),this.processItem(s.current),s.load(!0)}addTab(){const e=document.createElement("div");e.classList.add(Gt.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),s=t.indexOf(e);t.slice(Math.max(0,s-3),Math.min(t.length,s+3)).forEach((e=>{const t=this.loadCallbacks.get(e);t&&(t(),this.loadCallbacks.delete(e),this.intersectionObserver.unobserve(e))}))}cleanup(){this.listenerSetter.removeAll(),this.swipeHandler.removeListeners()}}Gt.BASE_CLASS="profile-avatars",Gt.SCALE=Ut?2:1,Gt.TRANSLATE_TEMPLATE=Ut?`translate3d({x}, 0, -1px) scale(${Gt.SCALE})`:"translate({x}, 0)";let Kt=(e,t)=>{t.title.innerHTML=e||"",t.container.style.display=e?"":"none"};class Wt{constructor(e,t,s=!0){this.scrollable=e,this.listenerSetter=t,this.isDialog=s,this.setPeerStatus=(e=!1)=>{const t=this.peerId;!t||a.default.myId===t&&this.isDialog||Ol.setPeerStatus(this.peerId,this.subtitle,e,!0,(()=>t===this.peerId),!this.isDialog)},Ut||this.scrollable.container.classList.add("no-parallax"),t||(this.listenerSetter=new B.Z)}init(){this.init=null,this.element=document.createElement("div"),this.element.classList.add("profile-content"),this.section=new Mn({noDelimiter:!0}),this.avatar=new Yl,this.avatar.classList.add("profile-avatar","avatar-120"),this.avatar.setAttribute("dialog",""+ +this.isDialog),this.avatar.setAttribute("clickable",""),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 et({title:" ",subtitleLangKey:"UserBio",icon:"info",clickable:e=>{"A"!==e.target.tagName&&Promise.resolve(n.default.getProfileByPeerId(this.peerId)).then((e=>{st(e.about),rt(k.default.format("BioCopied",!0))}))}}),this.bio.title.classList.add("pre-wrap"),this.username=new et({title:" ",subtitleLangKey:"Username",icon:"username",clickable:()=>{st("@"+o.Z.getPeer(this.peerId).username),rt(k.default.format("UsernameCopied",!0))}}),this.phone=new et({title:" ",subtitleLangKey:"Phone",icon:"phone",clickable:()=>{st("+"+E.Z.getUser(this.peerId).phone),rt(k.default.format("PhoneCopied",!0))}}),this.link=new et({title:" ",subtitleLangKey:"SetUrlPlaceholder",icon:"link",clickable:()=>{st(this.link.title.textContent),rt(k.default.format("LinkCopied",!0))}}),this.location=new et({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 et({checkboxField:new ut.Z({toggle:!0}),titleLangKey:"Notifications",icon:"unmute"}),e.add(this.notifications.checkboxField.input)("change",(e=>{e.isTrusted&&i.Z.togglePeerMute(this.peerId)})),e.add(a.default)("dialog_notify_settings",(e=>{if(this.peerId===e.peerId){const e=Ft.Z.isPeerLocalMuted(this.peerId,!1);this.notifications.checkboxField.checked=!e}})),this.section.content.append(this.notifications.container)),this.element.append(this.section.container),Ut&&this.element.append(Pn()),e.add(a.default)("peer_typings",(({peerId:e})=>{this.peerId===e&&this.setPeerStatus()})),e.add(a.default)("peer_bio_edit",(e=>{e===this.peerId&&this.setMoreDetails(!0)})),e.add(a.default)("peer_title_edit",(e=>{e===this.peerId&&this.fillUsername()})),e.add(a.default)("user_update",(e=>{this.peerId===e.toPeerId()&&this.setPeerStatus()})),e.add(a.default)("contacts_update",(e=>{this.peerId===e.toPeerId()&&(E.Z.getUser(e).pFlags.self&&this.isDialog||this.fillUserPhone())})),e.add(a.default)("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.setMoreDetailsTimeout&&(window.clearTimeout(this.setMoreDetailsTimeout),this.setMoreDetailsTimeout=0)}canBeDetailed(){return this.peerId!==a.default.myId||!this.isDialog}setAvatar(){if(this.canBeDetailed()&&o.Z.getPeerPhoto(this.peerId)){const e=this.avatars;return this.avatars=new Gt(this.scrollable),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(Ut&&this.scrollable.container.classList.add("parallax"))}Ut&&this.scrollable.container.classList.remove("parallax"),this.avatars&&(this.avatars.container.remove(),this.avatars.cleanup(),this.avatars=void 0),this.avatar.setAttribute("peer",""+this.peerId),this.section.content.prepend(this.avatar,this.name,this.subtitle)}fillUsername(){const{peerId:e}=this;if(e.isUser()&&this.canBeDetailed()){const t=o.Z.getPeerUsername(e);Kt(t,this.username)}}fillUserPhone(){const{peerId:e}=this;if(e.isUser()&&this.canBeDetailed()){const t=E.Z.getUser(e);Kt(t.phone?E.Z.formatUserPhone(t.phone):void 0,this.phone)}}fillNotifications(){const e=this.notifications;if(e)if(this.canBeDetailed()){const t=Ft.Z.isPeerLocalMuted(this.peerId,!1);e.checkboxField.checked=!t}else(0,De.T2)((()=>{e.container.style.display="none"}))}fillRows(){var e;const t=this.peerId;this.fillUsername(),this.fillUserPhone(),this.fillNotifications(),this.setMoreDetails(),(0,T.Z)(this.name,new St.Z({peerId:t,dialog:this.isDialog}).element);const s=o.Z.getPeer(t);(null===(e=null==s?void 0:s.pFlags)||void 0===e?void 0:e.verified)&&this.name.append(Ot()),this.setPeerStatus(!0)}fillProfileElements(){this.cleaned&&(this.cleaned=!1,this.cleanupHTML(),this.setAvatar(),this.fillRows())}setMoreDetails(e){this.setMoreDetailsTimeout&&(window.clearTimeout(this.setMoreDetailsTimeout),this.setMoreDetailsTimeout=0);const t=this.peerId,s=this.threadId;t&&!o.Z.isRestricted(t)&&this.canBeDetailed()&&(0,Nt.Z)(n.default.getProfileByPeerId(t,e),(e=>{if(this.peerId!==t||this.threadId!==s||o.Z.isRestricted(t))return;if(Kt(e.about?Q.Z.wrapRichText(e.about):void 0,this.bio),!t.isUser()){const s=j.Z.getChat(t.toChatId());if(s.username)Kt("https://t.me/"+s.username,this.link);else{const t=e.exported_invite;t&&Kt(t.link,this.link)}}const i=e.location;"channelLocation"==(null==i?void 0:i._)&&Kt(i.address,this.location),this.setMoreDetailsTimeout=window.setTimeout((()=>this.setMoreDetails(!0)),6e4)}))}setPeer(e,t=0){this.peerId===e&&this.threadId===t||(this.init&&this.init(),this.peerId=e,this.threadId=t,this.cleaned=!0)}}class qt extends O{constructor(e){super(e,!1),this.threadId=0,this.historiesStorage={}}init(){this.container.classList.add("shared-media-container","profile-container");const e=(0,U.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 s=document.createElement("div");s.className="transition slide-fade";const i=document.createElement("div");i.classList.add("transition-item"),this.title.append((0,k.i18n)("Profile")),this.editBtn=N("edit"),i.append(this.title,this.editBtn);const n=document.createElement("div");n.classList.add("transition-item");const o=this.title.cloneNode();o.append((0,k.i18n)("PeerInfo.SharedMedia")),n.append(o),s.append(i,n),this.header.append(s),this.profile=new Wt(this.scrollable),this.profile.init(),this.scrollable.append(this.profile.element),this.scrollable.onAdditionalScroll=()=>{const e=this.searchSuper.nav.getBoundingClientRect();if(!e.width)return;const s=e.top-1<=56;t.classList.toggle("state-back",s),this.searchSuper.container.classList.toggle("is-full-viewport",s),r(+s),s||this.searchSuper.cleanScrollPositions()};const r=(0,D.v)(s,"slide-fade",400,null,!1);r(0),(0,l.fc)(this.closeBtn,(e=>{this.closeBtn.firstElementChild.classList.contains("state-back")?(this.scrollable.scrollIntoViewNew({element:this.scrollable.container.firstElementChild,position:"start"}),r(0),t.classList.remove("state-back")):this.scrollable.isHeavyAnimationInProgress||this.slider.onCloseBtnClick()})),(0,l.fc)(this.editBtn,(e=>{let t;t=this.peerId.isAnyChat()?new Dt(this.slider):new Rt(this.slider),t&&(t instanceof Dt?t.chatId=this.peerId.toChatId():t.peerId=this.peerId,t.open())})),a.default.addEventListener("contacts_update",(e=>{this.peerId===e&&this.toggleEditBtn()})),a.default.addEventListener("chat_update",(e=>{this.peerId===e.toPeerId(!0)&&this.toggleEditBtn()})),a.default.addEventListener("history_multiappend",(e=>{for(const t in e)this.renderNewMessages(t.toPeerId(),Array.from(e[t]))})),a.default.addEventListener("history_delete",(({peerId:e,msgs:t})=>{this.deleteDeletedMessages(e,Array.from(t))})),a.default.addEventListener("message_sent",(({message:e})=>{this.renderNewMessages(e.peerId,[e.mid])})),this.searchSuper=new si({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=>{let t="members"===e.type&&a.default.settings.animationsEnabled?250:0;setTimeout((()=>{d.classList.toggle("is-hidden","members"!==e.type)}),t)}}),this.profile.element.append(this.searchSuper.container);const d=W({icon:"addmember_filled"});this.content.append(d),d.addEventListener("click",(()=>{const e=this.peerId,t=this.peerId.toChatId(),s=j.Z.isChannel(t),i=(t,i)=>{let n,a,o,r,l;if(t.length>1)n="AddMembersAlertTitle",a=[(0,k.i18n)("Members",[t.length])],o="AddMembersAlertCountText",r=t.map((e=>{const t=document.createElement("b");return t.append(new St.Z({peerId:e}).element),t})),s||(l=[{text:"AddMembersForwardMessages",checked:!0}]);else{n="AddOneMemberAlertTitle",o="AddMembersAlertNamesText";const e=document.createElement("b");e.append(new St.Z({peerId:t[0]}).element),r=[e],s||(l=[{text:"AddOneMemberForwardMessages",textArgs:[new St.Z({peerId:t[0]}).element],checked:!0}])}r.push(new St.Z({peerId:e}).element),new gt("popup-add-members",{peerId:e,titleLangKey:n,descriptionLangKey:o,descriptionLangArgs:r,buttons:[{langKey:"Add",callback:i}],checkboxes:l}).show()},n=e=>{"USER_PRIVACY_RESTRICTED"===e.type&&lt({langPackKey:"InviteToGroupError"})};if(s){const e=new Bt(this.slider);e.open({type:"channel",skippable:!1,takeOut:s=>(i(s,(()=>{const i=j.Z.inviteToChannel(t,s);i.catch(n),e.attachToPromise(i)})),!1),title:"GroupAddMembers",placeholder:"SendMessageTo"})}else new Et({peerTypes:["contacts"],placeholder:"Search",onSelect:e=>{setTimeout((()=>{i([e],(s=>{j.Z.addChatUser(t,e,s.size?void 0:0).catch(n)}))}),0)}})}))}renderNewMessages(e,t){if(!this.init&&this.historiesStorage[e]){t=t.slice().reverse();for(const s of this.searchSuper.mediaTabs){const n=s.inputFilter,a=this.searchSuper.filterMessagesByType(t.map((t=>i.Z.getMessageByPeer(e,t))),n);if(a.length){const t=this.historiesStorage[e][n];t&&t.unshift(...a.map((e=>({mid:e.mid,peerId:e.peerId})))),this.peerId===e&&-1!==this.searchSuper.usedFromHistory[n]&&(this.searchSuper.usedFromHistory[n]+=a.length,this.searchSuper.performSearchResult(a,s,!1))}}}}deleteDeletedMessages(e,t){if(!this.init&&this.historiesStorage[e]){for(const s of t)for(const t of this.searchSuper.mediaTabs){const i=t.inputFilter,n=this.historiesStorage[e][i];if(!n)continue;const a=n.findIndex((e=>e.mid===s));if(-1!==a){if(n.splice(a,1),this.peerId===e){const t=this.searchSuper.tabs[i].querySelector(`div[data-mid="${s}"][data-peer-id="${e}"]`);t&&(this.searchSuper.selection.isSelecting&&this.searchSuper.selection.toggleByElement(t),t.remove()),this.searchSuper.usedFromHistory[i]>=a+1&&this.searchSuper.usedFromHistory[i]--}break}}this.scrollable.onScroll()}}cleanupHTML(){this.profile.cleanupHTML(),this.editBtn.classList.add("hide"),this.searchSuper.cleanupHTML(!0),this.container.classList.toggle("can-add-members",this.searchSuper.canViewMembers()&&j.Z.hasRights(this.peerId.toChatId(),"invite_users"))}setLoadMutex(e){this.searchSuper.loadMutex=e}setPeer(e,t=0){var s;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!==(s=this.historiesStorage[e])&&void 0!==s?s:this.historiesStorage[e]={}}),this.profile.setPeer(e,t),!0)}fillProfileElements(){this.peerChanged&&(this.peerChanged=!1,this.cleanupHTML(),this.profile.fillProfileElements(),this.toggleEditBtn())}toggleEditBtn(){let e;e=this.peerId.isUser()?this.peerId!==a.default.myId&&E.Z.isContact(this.peerId.toUserId()):j.Z.hasRights(this.peerId.toChatId(),"change_info"),this.editBtn.classList.toggle("hide",!e)}loadSidebarMedia(e,t=!1){this.searchSuper.load(e,t)}onOpenAfterTimeout(){this.scrollable.onScroll()}}const $t="is-right-column-shown",Qt=new class extends V{constructor(){super({sidebarEl:document.getElementById("column-right"),canHideFirst:!0,navigationType:"right"}),this.isColumnProportionSet=!1,v.ZP.addEventListener("changeScreen",((e,t)=>{t===v._G.medium&&e!==v._G.mobile&&this.toggleSidebar(!1)})),v.ZP.addEventListener("resize",(()=>{this.setColumnProportion()})),this.sharedMediaTab=new qt(this)}onCloseTab(e,t,s){this.historyTabIds.length||this.toggleSidebar(!1,t),super.onCloseTab(e,t,s)}setColumnProportion(){const e=this.sidebarEl.scrollWidth/this.sidebarEl.previousElementSibling.scrollWidth;document.documentElement.style.setProperty("--right-column-proportion",""+e)}toggleSidebar(e,t){const s=document.body.classList.contains($t);let i;if(void 0!==e?e?s||(i=!0):s&&(i=!0):i=!0,!i)return Promise.resolve();s||this.historyTabIds.length||this.sharedMediaTab.open(),this.isColumnProportionSet||(this.setColumnProportion(),this.isColumnProportionSet=!0);const n=Ol.selectTab(s?1:2,t);return document.body.classList.toggle($t,e),n}};re.GO.appSidebarRight=Qt;const Yt=Qt;class Xt extends O{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=super.open(),s=Qe.Z.getPoll(e.media.poll.id);this.setTitle(s.poll.pFlags.quiz?"PollResults.Title.Quiz":"PollResults.Title.Poll");const i=document.createElement("h3");i.innerHTML=s.poll.rQuestion;const n=s.results.results.map((e=>e.voters/s.results.total_voters*100));ts(n);const a=document.createDocumentFragment();return s.results.results.forEach(((t,i)=>{if(!t.voters)return;const o=document.createElement("hr"),r=s.poll.answers[i],l=document.createElement("div");l.classList.add("poll-results-answer");const d=document.createElement("div");d.innerHTML=Q.o.wrapEmojiText(r.text);const c=document.createElement("div");c.innerText=Math.round(n[i])+"%",l.append(d,c);const h=pd.createChatList();h.classList.add("poll-results-voters"),pd.setListClickListener(h,(()=>{Yt.onCloseBtnClick()}),void 0,!0),h.style.minHeight=50*Math.min(t.voters,4)+"px",a.append(o,l,h);let p,u=4,g=!1,m=t.voters-4;const v=()=>{g||(g=!0,Qe.Z.getVotes(e,r.option,p,u).then((e=>{e.votes.forEach((e=>{const{dom:t}=pd.addDialogNew({dialog:e.user_id.toPeerId(!1),container:h,drawStatus:!1,rippleEnabled:!1,meAsSaved:!1,avatarSize:32});t.lastMessageSpan.parentElement.remove()})),p&&(m-=e.votes.length,f.lastElementChild.replaceWith((0,k.i18n)("PollResults.LoadMore",[Math.min(20,m)]))),p=e.next_offset,u=20,m&&e.votes.length||f.remove()})).finally((()=>{g=!1})))};if(v(),m<=0)return;const f=document.createElement("div");f.classList.add("poll-results-more","show-more","rp-overflow"),f.addEventListener("click",v),(0,ee.ripple)(f);const b=document.createElement("div");b.classList.add("tgico-down"),f.append(b,(0,k.i18n)("PollResults.LoadMore",[Math.min(20,m)])),a.append(f)})),this.resultsDiv.append(i,a),Yt.toggleSidebar(!0).then((()=>{})),t}}var Jt=s(9099);let es=0;const ts=e=>{const t=e.reduce(((e,t)=>e+Math.round(t)),0);if(t>100){const s=t-100,i=e.length;for(let t=0;t<s;++t){let t=-1,s=1;for(let n=0;n<i;++n){let i=e[n]%1;i>=.5&&i<s&&(s=i,t=n)}if(-1===t)return;e[t]-=s}}else if(t<100){const s=100-t,i=e.length;for(let t=0;t<s;++t){let t=-1,s=0;for(let n=0;n<i;++n){let i=e[n]%1;i<.5&&i>s&&(s=i,t=n)}if(-1===t)return;e[t]+=1-s}}};a.default.addEventListener("poll_update",(({poll:e,results:t})=>{Array.from(document.querySelectorAll(`poll-element[poll-id="${e.id}"]`)).forEach((s=>{s.isClosed=!!e.pFlags.closed,s.performResults(t,e.chosenIndexes)}))})),a.default.addEventListener("peer_changed",(()=>{is&&ss(is,ns,as)})),v.ZP.addEventListener("resize",(()=>{os.setMaxLength(),os.resizePolls()})),v.ZP.addEventListener("changeScreen",(()=>{os.setMaxLength()}));const ss=(e,t,s)=>{e.classList.remove("active"),clearTimeout(s),setTimeout((()=>{t(),e.remove(),is===e&&ns===t&&as===s&&(is=ns=null,as=0)}),200)};let is,ns,as;class os extends HTMLElement{constructor(){super(),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=Ct.Z.width<=360?Ct.Z.width-120:v.ZP.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,s)=>{e.setLineProgress(s,1)}))}))}render(){es||(es=document.getElementById("poll-line").getTotalLength(),os.setMaxLength());const e=this.message.media.poll.id,{poll:t,results:s}=Qe.Z.getPoll(e);let i;this.message.pFlags.is_scheduled&&this.classList.add("disable-hover"),t.pFlags&&(this.isPublic=!!t.pFlags.public_voters,this.isQuiz=!!t.pFlags.quiz,this.isClosed=!!t.pFlags.closed,this.isMultiple=!!t.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 n=this.isMultiple?'<span class="poll-answer-selected tgico-check"></span>':"",a=t.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 ${n}\n </div>\n <div class="poll-answer-percents"></div>\n <div class="poll-answer-text">${Q.o.wrapEmojiText(e.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">${t.rQuestion}</div>\n <div class="poll-desc">\n <div class="poll-type"></div>\n <div class="poll-avatars"></div>\n </div>\n ${a}`,this.descDiv=this.firstElementChild.nextElementSibling,this.typeDiv=this.descDiv.firstElementChild,this.avatarsDiv=this.descDiv.lastElementChild,i&&this.typeDiv.append((0,k.i18n)(i)),this.isQuiz&&(this.classList.add("is-quiz"),t.close_period&&t.close_date)){const e=document.createElement("div");e.classList.add("poll-time"),this.descDiv.append(e);const s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.classList.add("poll-quiz-timer"),this.quizTimer=s;const i=2,n=7,a=2*Math.PI*n,o=document.createElementNS("http://www.w3.org/2000/svg","circle");o.classList.add("poll-quiz-timer-circle"),o.setAttributeNS(null,"cx","16"),o.setAttributeNS(null,"cy","16"),o.setAttributeNS(null,"r",""+n),o.setAttributeNS(null,"stroke-width",""+i),s.append(o),this.descDiv.append(s);const r=1e3*t.close_period,l=1e3*(t.close_date-Ye.Z.serverTimeOffset);this.quizInterval=window.setInterval((()=>{const t=Date.now(),s=(l-t)/r,i=(l-t)/1e3+1|0;e.innerHTML=String(i).toHHMMSS(),i<=5&&(e.style.color="#ee545c",o.style.stroke="#ee545c"),o.style.strokeDashoffset=a+s*a,o.style.strokeDasharray=`${a} ${a}`,t>=l&&(clearInterval(this.quizInterval),e.innerHTML="",o.style.strokeDashoffset=a,this.quizInterval=0,setTimeout((()=>{Qe.Z.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 o=document.createElement("div");o.classList.add("poll-footer"),this.viewResults=document.createElement("div"),this.viewResults.className="poll-footer-button poll-view-results hide",this.viewResults.append((0,k.i18n)("Chat.Poll.ViewResults")),this.votersCountDiv=document.createElement("div"),this.votersCountDiv.className="poll-votes-count",o.append(this.viewResults,this.votersCountDiv),this.append(o),this.viewResults.addEventListener("click",(e=>{(0,d.d)(e),Yt.isTabExists(Xt)||new Xt(Yt).open(this.message)})),(0,ee.ripple)(this.viewResults),this.isMultiple&&(this.sendVoteBtn=document.createElement("div"),this.sendVoteBtn.classList.add("poll-footer-button","poll-send-vote"),this.sendVoteBtn.append((0,k.i18n)("Chat.Poll.SubmitVote")),(0,ee.ripple)(this.sendVoteBtn),t.chosenIndexes.length||this.votersCountDiv.classList.add("hide"),(0,l.fc)(this.sendVoteBtn,(e=>{(0,d.d)(e),this.chosingIndexes.length&&this.sendVotes(this.chosingIndexes).then((()=>{this.chosingIndexes.length=0,this.answerDivs.forEach((e=>{e.classList.remove("is-chosing")}))}))})),o.append(this.sendVoteBtn));const r=!(t.chosenIndexes.length||this.isClosed);r&&!this.isPublic||this.performResults(s,t.chosenIndexes,!1),r&&(this.setVotersCount(s),(0,l.fc)(this,this.clickHandler))}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,l.fc)(t,(s=>{(0,d.d)(s),t.classList.add("active"),((e,t,s)=>{is&&ss(is,ns,as);const i=document.createElement("div");i.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),i.append(n),a.innerHTML=Q.o.wrapRichText(e,{entities:t}),Ol.chat.bubbles.bubblesContainer.append(i),i.offsetLeft,i.classList.add("active"),is=i,ns=s,as=window.setTimeout((()=>{ss(i,s,as)}),ce.IS_TOUCH_SUPPORTED?5e3:7e3)})(e.solution,e.solution_entities,(()=>{t.classList.remove("active")}))})),this.sentVote){const s=e.results.find((e=>e.pFlags.correct));s&&!s.pFlags.chosen&&t.click()}}}clickHandler(e){const t=(0,Me.Z)(e.target,"poll-answer");if(!t)return;(0,d.d)(e);const s=+t.dataset.index;if(this.isMultiple){t.classList.toggle("is-chosing");const e=this.chosingIndexes.indexOf(s);-1!==e?this.chosingIndexes.splice(e,1):this.chosingIndexes.push(s)}else this.sendVotes([s])}sendVotes(e){if(this.sendVotePromise)return this.sendVotePromise;const t=this.answerDivs.filter(((t,s)=>e.includes(s)));return t.forEach((e=>{e.classList.add("is-voting")})),this.classList.add("disable-hover"),this.sentVote=!0,this.sendVotePromise=Qe.Z.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,s=!0){var i,n;if(a.default.settings.animationsEnabled||(s=!1),this.isQuiz&&((null===(i=e.results)||void 0===i?void 0:i.length)||this.isClosed)){this.answerDivs.forEach(((t,s)=>{t.classList.toggle("is-correct",!!e.results[s].pFlags.correct)})),this.initQuizHint&&(this.initQuizHint(e),this.initQuizHint=null),this.quizInterval&&(clearInterval(this.quizInterval),this.quizInterval=0),(null===(n=this.quizTimer)||void 0===n?void 0:n.parentElement)&&this.quizTimer.remove();const t=this.descDiv.querySelector(".poll-time");t&&t.remove()}if(this.isClosed&&(this.classList.add("is-closed"),(0,T.Z)(this.typeDiv,(0,k.i18n)("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,l.fc)(this,this.clickHandler):(0,l.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",!s),s&&(0,Jt.Z)(this,"",!this.isRetracted,340),(0,De.T2)((()=>{this.setResults(this.isRetracted?this.percents:t,this.chosenIndexes,s),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));let t="";(e.recent_voters||[]).forEach(((e,s)=>{const i=0===s?"":`style="transform: translateX(-${3*s}px);"`;t+=`<avatar-element class="avatar-16 poll-avatar" dialog="0" peer="${e.toPeerId()}" ${i}></avatar-element>`})),this.avatarsDiv.innerHTML=t}if(this.isMultiple){const t=!!this.chosenIndexes.length,s=this.isClosed||t,i=!this.isPublic||!e.total_voters||!t&&!this.isClosed;this.sendVoteBtn.classList.toggle("hide",s),this.viewResults.classList.toggle("hide",i),this.votersCountDiv.classList.toggle("hide",!s||!i)}}setResults(e,t,s){this.svgLines.forEach((e=>e.style.display="")),this.answerDivs.forEach(((e,s)=>{e.classList.toggle("is-chosen",t.includes(s))}));const i=Math.max(...e);if(this.maxPercents=e.map((e=>e/i)),this.isRetracted)this.svgLines.forEach(((e,t)=>{this.setLineProgress(t,-1)}));else{const e=()=>{this.svgLines.forEach(((e,t)=>{this.setLineProgress(t,1)}))};s?(0,De.T2)(e):e()}let n;e=e.slice(),ts(e);const a=t=>{e.forEach(((e,s)=>{const i=n(e,t);this.numberDivs[s].innerText=i+"%"}))};if(this.isRetracted)if(n=(e,t)=>Math.round(e/10*t),s)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)),s)for(let e=0;e<10;++e)setTimeout((()=>{a(e)}),34*e);else a(9);if(this.isRetracted){s&&this.classList.add("is-retracting"),this.classList.remove("is-voted");const e=()=>{this.svgLines.forEach((e=>e.style.display="none"))};s?setTimeout((()=>{this.classList.remove("is-retracting"),e()}),340):e()}else this.classList.add("is-voted")}setVotersCount(e){const t=e.total_voters||0;let s,i=[t];s=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,T.Z)(this.votersCountDiv,(0,k.i18n)(s,i))}setLineProgress(e,t){const s=this.svgLines[e];-1===t?(s.style.strokeDasharray="",s.style.strokeDashoffset=""):(s.style.strokeDasharray=t*this.maxPercents[e]*os.MAX_LENGTH+", 485.9",s.style.strokeDashoffset=""+t*os.MAX_OFFSET)}}os.MAX_OFFSET=-46.5,os.MAX_LENGTH=0,customElements.define("poll-element",os);var rs=s(6740),ls=s(9674),ds=s(3847),cs=s(8487),hs=s(467),ps=s(6705),us=s(5269),gs=s(8938),ms=s(6724),vs=s(2131),fs=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};let bs=0;function ys({doc:e,container:t,message:s,boxWidth:i,boxHeight:n,withTail:o,isOut:r,middleware:c,lazyLoadQueue:h,noInfo:p,group:u,onlyPreview:g,withoutPreloader:m,loadPromises:f,noPlayButton:b,size:y,searchContext:w,autoDownload:S}){var C,M;const E=null==S?void 0:S.video;let P=0===E;const T=!(i&&n),k=("video"!==e.type||e.size<=52428800&&!T)&&("gif"===e.type?a.default.settings.autoPlay.gifs:a.default.settings.autoPlay.videos);let x,A;if(!p){x=document.createElement("span"),x.classList.add("video-time"),t.append(x);let s=!1;"gif"!==e.type?(x.innerText=(e.duration+"").toHHMMSS(!1),b||"round"===e.type||(k&&!P?x.classList.add("tgico","can-autoplay"):s=!0)):(x.innerText="GIF",k||b||(s=!0,P=void 0)),s&&(A=document.createElement("span"),A.classList.add("video-play","tgico-largeplay","btn-circle","position-center"),t.append(A))}let _,Z={};if("image/gif"===e.mime_type){const a=Ss({photo:e,message:s,container:t,boxWidth:i,boxHeight:n,withTail:o,isOut:r,lazyLoadQueue:h,middleware:c,withoutPreloader:m,loadPromises:f,autoDownloadSize:E,size:y});return Z.thumb=a,Z.loadPromise=a.loadPromises.full,Z}const D=document.createElement("video");if(D.classList.add("media-video"),D.setAttribute("playsinline","true"),D.muted=!0,"round"===e.type){const i=document.createElement("div");i.classList.add("media-round","z-depth-1"),i.dataset.mid=""+s.mid,i.dataset.peerId=""+s.peerId,i.message=s;const n=v.ZP.active.round,a=n.width/2,o=3.5,r=a-2*o;i.innerHTML=`<svg class="progress-ring" width="${n.width}" height="${n.width}" style="transform: rotate(-90deg);">\n <circle class="progress-ring__circle" stroke="white" stroke-opacity="0.3" stroke-width="${o}" cx="${a}" cy="${a}" r="${r}" fill="transparent"/>\n </svg>`;const c=i.firstElementChild.firstElementChild;bs||(bs=2*Math.PI*r),c.style.strokeDasharray=bs+" "+bs,c.style.strokeDashoffset=""+bs,x.classList.add("tgico"),s.pFlags.media_unread&&i.classList.add("is-unread");const h=document.createElement("canvas");h.width=h.height=e.w,i.prepend(h,x),i.append(D),t.append(i);const p=h.getContext("2d"),u=()=>{const e=i.message,t=ve.addMedia(e,!P),s=()=>{(Ol.chat.setPeerPromise||Promise.resolve()).finally((()=>{(0,cs.Z)(t)||(t.removeEventListener("play",r),t.removeEventListener("timeupdate",o),t.removeEventListener("pause",u),t.removeEventListener("ended",g))}))},n=()=>{p.drawImage(t,0,0);const e=bs-t.currentTime/t.duration*bs;return c.style.strokeDashoffset=""+e,!t.paused},a=()=>{t.duration&&((0,cs.Z)(t)?(t.paused&&n(),x.innerText=(t.duration-t.currentTime+"").toHHMMSS(!1)):s())},o=Fe(a),r=()=>{D.classList.add("hide"),i.classList.remove("is-paused"),(0,Ue.cK)(n,h),_&&_.preloader&&_.preloader.classList.contains("manual")&&_.onClick()},u=()=>{(0,cs.Z)(t)?i.classList.add("is-paused"):s()},g=()=>{D.classList.remove("hide"),i.classList.add("is-paused"),D.currentTime=0,x.innerText=(""+t.duration).toHHMMSS(!1),t.currentTime&&(t.currentTime=0)};t.addEventListener("play",r),t.addEventListener("timeupdate",o),t.addEventListener("pause",u),t.addEventListener("ended",g),(0,l.fc)(h,(s=>{if((0,d.d)(s),_&&!_.detached&&_.onClick(),t.paused){const s=!!w;if(ve.setSearchContext(w||{peerId:Re.NM,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1})){const[t,n]=s?Oe(i):[];ve.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?(n(),a(),D.classList.add("hide")):u():r()};s.pFlags.is_outgoing?(i.onLoad=u,i.dataset.isOutgoing="1"):u()}else D.autoplay=!0;let F;if(s){if(F=Ss({photo:e,message:s,container:t,boxWidth:i,boxHeight:n,withTail:o,isOut:r,lazyLoadQueue:h,middleware:c,withoutPreloader:!0,loadPromises:f,autoDownloadSize:null==S?void 0:S.photo,size:y}),Z.thumb=F,!k&&"gif"!==e.type||g)return Z.loadPromise=F.loadPromises.full,Z;if(o){const e=(F.images.thumb||F.images.full).parentElement;D.width=+e.getAttributeNS(null,"width"),D.height=+e.getAttributeNS(null,"height"),e.append(D)}}else{const t=L.Z.getThumb(e,!1);t&&t.promise.then((()=>{D.poster=t.cacheContext.url}))}!D.parentElement&&t&&((null==F?void 0:F.aspecter)||t).append(D);const R=le.Z.getCacheContext(e),B=!!(null===(C=null==s?void 0:s.media)||void 0===C?void 0:C.preloader);B?(_=s.media.preloader,_.attach(t,!1),P=void 0):R.downloaded||e.supportsStreaming||m?e.supportsStreaming&&(_=new fe.Z({cancelable:!1,attachMethod:"prepend"})):_=new fe.Z({attachMethod:"prepend"});const U=(0,se.b)();D.addEventListener("error",(e=>{4!==D.error.code&&console.error("Error "+D.error.code+"; details: "+D.error.message),_&&!B&&_.detach(),U.isFulfilled||U.resolve()}),{once:!0}),(0,he.xD)(D).then((()=>{u&&I.Z.addAnimation(D,u),_&&!B&&_.detach(),U.resolve()})),"video"===e.type&&(D.addEventListener("timeupdate",(()=>{x.innerText=(D.duration-D.currentTime+"").toHHMMSS(!1)})),A&&D.addEventListener("timeupdate",(()=>{A.remove()}),{once:!0})),D.muted=!0,D.loop=!0,D.autoplay=!0;let N=P&&(null===(M=null==F?void 0:F.preloader)||void 0===M?void 0:M.loadFunc);const O=()=>{_&&P&&!m&&(_.construct(),_.setManual());let i=Promise.resolve();if(_&&!B||m)if(R.downloaded||e.supportsStreaming)e.supportsStreaming&&(P?i=Promise.reject():!R.downloaded&&_&&(_.attach(t,!1,null),D.addEventListener(ne.IS_SAFARI?"timeupdate":"canplay",(()=>{_.detach()}),{once:!0})));else{const s=i=L.Z.downloadDoc(e,null==h?void 0:h.queueId,P);_&&_.attach(t,!1,s)}return!P&&N&&(N(),N=null),P=void 0,i.then((()=>{!c||c()?("round"===e.type&&ve.resolveWaitingForLoadMedia(s.peerId,s.mid,s.pFlags.is_scheduled),(0,rs.ZP)(D,R.url)):U.resolve()}),(()=>{})),{download:i,render:U}};return _&&!B&&_.setDownloadFunction(O),"gif"!==e.type||k?Z.loadPromise=h?(h.push({div:t,load:()=>O().render}),Promise.resolve()):O().render:(0,l.fc)(t,(e=>{(0,d.d)(e),A.remove(),O()}),{capture:!0,once:!0}),Z}function ws({message:e,withTime:t,fontWeight:s,voiceAsMusic:n,showSender:o,searchContext:d,loadPromises:c,autoDownloadSize:h,lazyLoadQueue:p}){var u,m;s||(s=500);const v=0===h,f=e.media.document||e.media.webpage.document,b=e.pFlags.is_outgoing&&(null===(u=e.media)||void 0===u?void 0:u.preloader);if("audio"===f.type||"voice"===f.type||"round"===f.type){const i=new He;return i.withTime=t,i.message=e,i.noAutoDownload=v,i.lazyLoadQueue=p,i.loadPromises=c,n&&(i.voiceAsMusic=n),d&&(i.searchContext=d),o&&(i.showSender=o),b&&(i.preloader=e.media.preloader),i.dataset.fontWeight=""+s,i.render(),i}let y=f.file_name?f.file_name.split("."):"",w="";w=y.length>1&&Array.isArray(y)?(0,hs.ST)(y.pop().split(" ",1)[0].toLowerCase()):"file";let S=document.createElement("div");S.classList.add("document",`ext-${w}`),S.dataset.docId=""+f.id;const C=document.createElement("div");C.classList.add("document-ico");const I=le.Z.getCacheContext(f);if((null===(m=f.thumbs)||void 0===m?void 0:m.length)||e.pFlags.is_outgoing&&I.url&&"photo"===f.type){S.classList.add("document-with-thumb");let t=[];if(e.pFlags.is_outgoing)C.innerHTML=`<img src="${I.url}">`,t.push(C.firstElementChild);else{const e=Ss({photo:f,message:null,container:C,boxWidth:54,boxHeight:54,loadPromises:c,withoutPreloader:!0,lazyLoadQueue:p,size:r.Z.choosePhotoSize(f,54,54,!0)});C.style.width=C.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 C.innerText=w;let M=f.fileName||"Unknown.file";document.createElement("div").classList.add("document-description");const E=[Be(f.size)];t&&E.push((0,ie.OD)(e.date)),o&&E.push(i.Z.wrapSenderToPeer(e)),S.innerHTML=`\n ${I.downloaded&&!b?"":'<div class="document-download"></div>'}\n <div class="document-name"></div>\n <div class="document-size"></div>\n `;const P=S.querySelector(".document-name"),T=new Ae.I;if(T.dataset.fontWeight=""+s,T.innerHTML=M,P.append(T),o&&P.append(i.Z.wrapSentTime(e)),S.querySelector(".document-size").append(...(0,k.joinElementsWith)(E," · ")),S.prepend(C),!b&&e.pFlags.is_outgoing)return S;let x,A=null;const _=()=>{if(x){x.classList.add("downloaded");const e=x;setTimeout((()=>{e.remove()}),200),x=null}A&&(A=null)},Z=e=>{var t;const s=!e||e.isTrusted,i=L.Z.getDoc(S.dataset.docId);let n;const o=Ol.chat.bubbles?Ol.chat.bubbles.lazyLoadQueue.queueId:void 0;if(s)if("pdf"===i.type){const e=L.Z.downloading.has(i.id)||I.downloaded;n=L.Z.downloadDoc(i,o),e&&n.then((()=>{setTimeout((()=>{const e=le.Z.getCacheContext(i).url;window.open(e)}),a.default.settings.animationsEnabled?250:0)}))}else n=g.has(i.mime_type)&&(null===(t=i.thumbs)||void 0===t?void 0:t.length)?L.Z.downloadDoc(i,o):L.Z.saveDocFile(i,o);else n=L.Z.downloadDoc(i,o);return x&&(n.then(_),A.attach(x,!0,n)),{download:n}};return L.Z.downloading.has(f.id)?(x=S.querySelector(".document-download"),A=new fe.Z,A.attach(x,!1,L.Z.downloading.get(f.id))):I.downloaded&&!b||(x=S.querySelector(".document-download"),A=e.media.preloader,A?(A.attach(x),e.media.promise.then(_)):(A=new fe.Z,A.construct(),A.setManual(),A.attach(x),A.setDownloadFunction(Z),void 0!==h&&h>=f.size&&(0,l.tH)(A.preloader))),(0,l.fc)(S,(e=>{A?A.onClick(e):Z(e)})),S}function Ss({photo:e,message:t,container:s,boxWidth:i,boxHeight:n,withTail:o,isOut:l,lazyLoadQueue:d,middleware:c,size:h,withoutPreloader:p,loadPromises:u,autoDownloadSize:g,noBlur:m,noThumb:f,noFadeIn:b,blurAfter:y}){var w;if(!e.sizes&&!e.thumbs)return i&&n&&!h&&"document"===e._&&r.Z.setAttachmentSize(e,s,i,n,void 0,t),{loadPromises:{thumb:Promise.resolve(),full:Promise.resolve()},images:{thumb:null,full:null},preloader:null,aspecter:null};let S=0===g;h||(void 0===i&&(i=v.ZP.active.regular.width),void 0===n&&(n=v.ZP.active.regular.height)),s.classList.add("media-container");let C,I,M,E=s,P=!0,T=Promise.resolve();const k="document"===e._&&"image/gif"===e.mime_type&&!h;if(I=new Image,i&&n&&!h){const a=r.Z.setAttachmentSize(e,s,i,n,void 0,t,void 0,k?{_:"photoSize",w:e.w,h:e.h,size:e.size,type:"full"}:void 0);if(h=a.photoSize,P=a.isFit,M=le.Z.getCacheContext(e,h.type),!P){E=document.createElement("div"),E.classList.add("media-container-aspecter"),E.style.width=a.size.width+"px",E.style.height=a.size.height+"px";const i=r.Z.getStrippedThumbIfNeeded(e,M,!m,!0);if(i){T=i.loadPromise;const e=i.image;e.classList.add("media-photo"),s.append(e)}else Ss({container:s,message:t,photo:e,boxWidth:0,boxHeight:0,size:h,lazyLoadQueue:d,isOut:l,loadPromises:u,middleware:c,withoutPreloader:p,withTail:o,autoDownloadSize:g,noBlur:m,noThumb:!0,blurAfter:!0}).images.full.classList.add("media-photo","thumbnail");s.classList.add("media-container-fitted"),s.append(E)}}else h||(h=r.Z.choosePhotoSize(e,i,n,!0)),M=le.Z.getCacheContext(e,null==h?void 0:h.type);if(!f){const t=r.Z.getStrippedThumbIfNeeded(e,M,!m);t&&(T=Promise.all([T,t.loadPromise]),C=t.image,C.classList.add("media-photo"),E.append(C))}I.classList.add("media-photo");const x=(C||!M.downloaded)&&a.default.settings.animationsEnabled&&!b;let A;(null===(w=null==t?void 0:t.media)||void 0===w?void 0:w.preloader)&&!p?(A=t.media.preloader,A.attach(s),S=void 0):M.downloaded||(A=new fe.Z({attachMethod:"prepend"}));const _=e=>Cs(s,I,e,x,E,C),Z=()=>c&&!c()?Promise.resolve():y?(0,ps.Z)(M.url,12).then((e=>_(e))):_(M.url);let D;const F=h.w>=150&&h.h>=150||S,R=()=>{S&&!p&&A&&(A.construct(),A.setManual());const t=k&&!h?L.Z.downloadDoc(e,null==d?void 0:d.queueId):r.Z.preloadPhoto(e,h,null==d?void 0:d.queueId,S);A&&!M.downloaded&&!p&&F&&A.attach(s,!1,t),S=void 0;const i=t.then(Z);return i.catch((()=>{})),{download:t,render:i}};return A&&A.setDownloadFunction(R),M.downloaded?T=D=R().render:d?d.push({div:s,load:()=>R().download}):D=R().render,u&&T&&u.push(T),{loadPromises:{thumb:T,full:D||Promise.resolve()},images:{thumb:C,full:I},preloader:A,aspecter:E}}function Cs(e,t,s,i,n=e,a){return i&&t.classList.add("fade-in"),new Promise((o=>{(0,rs.ZP)(t,s,(()=>{ls.Z.mutateElement(e,(()=>{n.append(t),(0,De.T2)((()=>{o()})),i&&t.addEventListener("animationend",(()=>{ls.Z.mutate((()=>{t.classList.remove("fade-in"),a&&a.remove()}))}),{once:!0})}))}))}))}function Ls({size:e,doc:t,middleware:s,target:i,side:n,skipRatio:a,play:o}){const r=document.createElement("div");r.classList.add("emoji-animation"),r.style.width=e+"px",r.style.height=e+"px";const l=Is({div:r,doc:t,middleware:s,withThumb:!1,needFadeIn:!1,loop:!1,width:e,height:e,play:o,group:"none",skipRatio:a}).then((e=>((0,gs.Z)(e),e.addEventListener("enterFrame",(t=>{t===e.maxFrame&&(e.remove(),r.remove(),Ol.chat.bubbles.scrollable.container.removeEventListener("scroll",g))})),vs.Z&&e.addEventListener("firstFrame",(()=>{navigator.vibrate(100)}),{once:!0}),e))),d=e=>{const t=Math.random()*e*2;return t>e?-t%e:t},c=d(16),h=d(4),p=e/8*("right"===n?1:-1),u=()=>{if(!(0,cs.Z)(i))return;const t=i.getBoundingClientRect(),s=("right"===n?t.right:t.left)+("center"===n?(t.width-e)/2:("right"===n?-e:0)+p+c),a=t.top+(t.height-e)/2+("center"===n?0:h);r.style.top=a+"px",r.style.left=s+"px"},g=Fe(u);return Ol.chat.bubbles.scrollable.container.addEventListener("scroll",g),u(),Ol.emojiAnimationContainer.append(r),{animationDiv:r,stickerPromise:l}}function Is({doc:e,div:t,middleware:s,lazyLoadQueue:n,group:o,play:c,onlyThumb:h,emoji:p,width:u,height:g,withThumb:m,loop:v,loadPromises:b,needFadeIn:y,needUpscale:w,skipRatio:S,static:C}){var M;const E=e.sticker;if(1===E&&(C=!0),u||(u=p?void 0:200),g||(g=p?void 0:200),2===E&&ae.Z.loadLottieWorkers(),!E)throw console.error("wrong doc for wrapSticker!",e),new Error("wrong doc for wrapSticker!");let P;if(t.dataset.docId=""+e.id,t.classList.add("media-sticker-wrapper"),C&&1!==E){const t=r.Z.choosePhotoSize(e,u,g,!1);P=le.Z.getCacheContext(e,t.type)}else P=le.Z.getCacheContext(e);const T=p?(0,te.tB)(p):-1,k=P.downloaded&&!y,x=!C&&(2===E||3===E),A=x;let _=(0,se.b)(),Z=!1;if(((null===(M=e.thumbs)||void 0===M?void 0:M.length)||e.stickerCachedThumbs)&&!t.firstElementChild&&(!k||A||h)&&!1!==m){let i,a=e.stickerCachedThumbs&&e.stickerCachedThumbs[T]||e.thumbs[0];const o=()=>{t.childElementCount||(i.classList.add("media-sticker","thumbnail"),ls.Z.mutateElement(t,(()=>{t.append(i),_.resolve()})))};if("url"in a)i=new Image,(0,rs.ZP)(i,a.url,o),Z=!0;else if("bytes"in a){if("photoPathSize"===a._)if(a.bytes.length){const s=r.Z.getPathFromPhotoPathSize(a);t.innerHTML=`<svg class="rlottie-vector media-sticker thumbnail" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 ${e.w||512} ${e.h||512}" xml:space="preserve">\n <path d="${s}"/>\n </svg>`}else a=e.thumbs.find((e=>{var t;return null===(t=e.bytes)||void 0===t?void 0:t.length}))||a;a&&"photoPathSize"!==a._&&T<=0&&(i=new Image,us.Z||e.pFlags.stickerThumbConverted||P.url?((0,rs.ZP)(i,r.Z.getPreviewURLFromThumb(e,a,!0),o),Z=!0):oe.Z.convert(""+e.id,a.bytes).then((n=>{a.bytes=n,e.pFlags.stickerThumbConverted=!0,s&&!s()||t.childElementCount||(0,rs.ZP)(i,r.Z.getPreviewURLFromThumb(e,a,!0),o)})).catch((()=>{})))}else if((2===E&&T<=0||3===E)&&(m||h)){i=new Image;const r=()=>{if(t.childElementCount||s&&!s())return;const n=()=>{t.childElementCount||s&&!s()||(0,rs.ZP)(i,P.url,o)};return P.url?(n(),Promise.resolve()):L.Z.getThumbURL(e,a).promise.then(n)};if(n&&h)return n.push({div:t,load:r}),Promise.resolve();r(),a.url&&(Z=!0)}}if(b&&Z&&b.push(_),h)return Promise.resolve();const D=()=>fs(this,void 0,void 0,(function*(){if(!s||s()){if(2===E&&!C)return yield L.Z.downloadDoc(e,null==n?void 0:n.queueId).then((n=>fs(this,void 0,void 0,(function*(){if(s&&!s())throw new Error("wrapSticker 2 middleware");let r=yield ae.Z.loadAnimationWorker({container:t,loop:v&&!p,autoplay:c,animationData:n,width:u,height:g,name:"doc"+e.id,needUpscale:w,skipRatio:S,toneIndex:T},o,s);if(r.addEventListener("firstFrame",(()=>{const s=t.firstElementChild;!1!==y&&(y=(y||!s||"svg"===s.tagName)&&a.default.settings.animationsEnabled);const i=()=>{s&&s!==r.canvas&&s.remove()};y?ls.Z.mutate((()=>{r.canvas.classList.add("fade-in"),s&&s.classList.add("fade-out"),r.canvas.addEventListener("animationend",(()=>{ls.Z.mutate((()=>{r.canvas.classList.remove("fade-in"),i()}))}),{once:!0})})):s&&ls.Z.mutate(i),!1!==m&&L.Z.saveLottiePreview(e,r.canvas,T)}),{once:!0}),p){const e={a:[],v:1};let n;ds.Z.preloadAnimatedEmojiStickerAnimation(p),(0,l.fc)(t,(a=>fs(this,void 0,void 0,(function*(){(0,d.d)(a);const o=ae.Z.getAnimation(t);if(o.paused){const e=ds.Z.getAnimatedEmojiSoundDocument(p);if(e){const s=document.createElement("audio");s.style.display="none",t.parentElement.append(s);try{yield L.Z.downloadDoc(e);const t=le.Z.getCacheContext(e);s.src=t.url,s.play(),yield(0,he.xD)(s,void 0,!0),s.addEventListener("ended",(()=>{s.src="",s.remove()}),{once:!0})}catch(e){}}o.autoplay=!0,o.restart()}if(!Ol.chat.peerId.isUser())return;const r=ds.Z.getAnimatedEmojiSticker(p,!0);if(!r)return;const l=(0,Me.Z)(t,"bubble"),c=l.classList.contains("is-out"),{animationDiv:h}=Ls({doc:r,middleware:s,side:c?"right":"left",size:280,target:t,play:!0});l&&(c?h.classList.add("is-out"):h.classList.add("is-in")),n||(n=(0,ms.Z)((()=>{if(!e.a.length)return;const s=e.a[0].t;e.a.forEach((e=>{e.t=(e.t-s)/1e3}));const n=(0,Me.Z)(t,"bubble");i.Z.setTyping(Ol.chat.peerId,{_:"sendMessageEmojiInteraction",msg_id:f.Z.getServerMessageId(+n.dataset.mid),emoticon:p,interaction:{_:"dataJSON",data:JSON.stringify(e)}},!0),e.a.length=0}),1e3,!1)),a.isTrusted&&(e.a.push({i:1,t:Date.now()}),n())}))))}return r}))));if(C||3===E){let i;C?i=new Image:(i=document.createElement("video"),i.setAttribute("playsinline","true"),i.muted=!0,c&&(i.autoplay=!0,i.loop=!0));const l=t.firstElementChild!==i&&t.firstElementChild;return!1!==y&&(y=(y||!k||(C?l:!l||"svg"===l.tagName))&&a.default.settings.animationsEnabled),i.classList.add("media-sticker"),y&&i.classList.add("fade-in"),new Promise(((a,d)=>{const c=()=>{if(s&&!s())return a();const n=()=>{ls.Z.mutateElement(t,(()=>{if(t.append(i),l&&l.classList.add("fade-out"),3===E&&!L.Z.isSavingLottiePreview(e,T)){(0,gs.Z)(i);const t=document.createElement("canvas");t.width=u*window.devicePixelRatio,t.height=g*window.devicePixelRatio,t.getContext("2d").drawImage(i,0,0,t.width,t.height),L.Z.saveLottiePreview(e,t,T)}3===E&&o&&I.Z.addAnimation(i,o),a(),y&&i.addEventListener("animationend",(()=>{i.classList.remove("fade-in"),l&&l.remove()}),{once:!0})}))};C?(0,rs.ZP)(i,P.url,n):(i.src=P.url,(0,he.xD)(i).then(n))};if(P.url)c();else{let t;if(2===E&&C){const s=r.Z.choosePhotoSize(e,u,g,!1);t=L.Z.getThumbURL(e,s).promise}else t=L.Z.downloadDoc(e,null==n?void 0:n.queueId);t.then(c,a)}}))}}})),F=!n||k&&!x?D():(n.push({div:t,load:D}),Promise.resolve());return k&&C&&(_=F,b&&b.push(_)),F}function Ms({set:e,lazyLoadQueue:t,container:s,group:i,autoplay:n,width:a,height:o}){var r;return fs(this,void 0,void 0,(function*(){if(null===(r=e.thumbs)||void 0===r?void 0:r.length)return s.classList.add("media-sticker-wrapper"),void t.push({div:s,load:()=>{const t=ds.Z.getStickerSetThumbDownloadOptions(e),r=le.Z.download(t);if(e.pFlags.animated&&!e.pFlags.videos)return r.then((t=>{ae.Z.loadAnimationWorker({container:s,loop:!0,autoplay:n,animationData:t,width:a,height:o,needUpscale:!0,name:"setThumb"+e.id},i)}));{let t;return e.pFlags.videos?(t=document.createElement("video"),t.setAttribute("playsinline","true"),t.autoplay=!0,t.muted=!0,t.loop=!0):t=new Image,t.classList.add("media-sticker"),r.then((e=>{(0,rs.ZP)(t,URL.createObjectURL(e),(()=>{s.append(t)}))}))}}});const l=ds.Z.getStickerSet(e),d=yield l;"documentEmpty"!==d.documents[0]._&&Is({doc:d.documents[0],div:s,group:i,lazyLoadQueue:t})}))}function Es({doc:e,row:t,size:s}){const i=t.media,n=t.createMedia("small");i&&n.classList.add("hide");const a=i?[]:void 0,o="small"===s?32:48,r=Is({div:n,doc:e,width:o,height:o,loadPromises:a});return a&&Promise.all(a).then((()=>{n.classList.remove("hide"),i.remove()})),r}function Ps(e,t,s){const i=new Ke("reply");return i.fill(e,t,s),i.container}function Ts(e){const t=new qe(e.items,e.maxWidth,e.minWidth,e.spacing,e.maxHeight).layout(),s=t.find((e=>2&e.sides)),i=s.geometry.width+s.geometry.x,n=t.find((e=>4&e.sides)),a=n.geometry.height+n.geometry.y,o=e.container;o.style.width=i+"px",o.style.height=a+"px";const r=o.children;t.forEach((({geometry:t,sides:s},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/i*100+"%",l.style.height=t.height/a*100+"%",l.style.top=t.y/a*100+"%",l.style.left=t.x/i*100+"%",8&s&&1&s&&(l.style.borderTopLeftRadius="inherit"),8&s&&4&s&&(l.style.borderBottomLeftRadius="inherit"),2&s&&1&s&&(l.style.borderTopRightRadius="inherit"),2&s&&4&s&&(l.style.borderBottomRightRadius="inherit"),e.forMedia){const e=document.createElement("div");e.classList.add("album-item-media"),l.append(e)}}))}function ks({groupId:e,attachmentDiv:t,middleware:s,uploading:n,lazyLoadQueue:a,isOut:o,chat:l,loadPromises:d,autoDownload:c}){const h=[],p=i.Z.getMidsByAlbum(e);for(const e of p){const t=l.getMessage(e),s=t.media.photo||t.media.document,i="photo"===s._?r.Z.choosePhotoSize(s,480,480):{w:s.w,h:s.h};h.push({size:i,media:s,message:t})}Ts({container:t,items:h.map((e=>({w:e.size.w,h:e.size.h}))),maxWidth:v.ZP.active.album.width,minWidth:100,spacing:2,forMedia:!0}),h.forEach(((e,i)=>{const{size:n,media:r,message:l}=e,h=t.children[i];h.dataset.mid=""+l.mid,h.dataset.peerId=""+l.peerId;const p=h.firstElementChild;"photo"===r._?Ss({photo:r,message:l,container:p,boxWidth:0,boxHeight:0,isOut:o,lazyLoadQueue:a,middleware:s,size:n,loadPromises:d,autoDownloadSize:c.photo}):ys({doc:l.media.document,container:p,message:l,boxWidth:0,boxHeight:0,withTail:!1,isOut:o,lazyLoadQueue:a,middleware:s,loadPromises:d,autoDownload:c})}))}v.ZP.addEventListener("changeScreen",((e,t)=>{if(t===v._G.mobile||e===v._G.mobile){const e=Array.from(document.querySelectorAll(".media-round .progress-ring")),t=v.ZP.active.round.width,s=t/2,i=s-7;bs=2*Math.PI*i,e.forEach((e=>{e.setAttributeNS(null,"width",""+t),e.setAttributeNS(null,"height",""+t);const n=e.firstElementChild;n.setAttributeNS(null,"cx",""+s),n.setAttributeNS(null,"cy",""+s),n.setAttributeNS(null,"r",""+i),n.style.strokeDasharray=bs+" "+bs,n.style.strokeDashoffset=""+bs}))}})),a.default.addEventListener("download_start",(e=>{Array.from(document.querySelectorAll(`.document[data-doc-id="${e}"]`)).forEach((e=>{e.querySelector(".preloader-container.manual")&&(0,l.tH)(e)}))}));var xs=s(8594),As=s(3624),_s=s(2648);function Zs(e,t,s,i){return void 0===i&&(i=e.parentElement===t?(0,_s.Z)(e):-1),i!==s&&(-1!==i&&i<s&&(s+=1),s?t.childElementCount>s?t.insertBefore(e,t.children[s]):t.append(e):t.prepend(e),!0)}var Ds=s(6519);class Fs{constructor(e){this.updateElementWith=e=>e(),this.updateListWith=e=>e(!0),this.middleware=(0,As.k)(),(0,w.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((s=>{if(!t()||void 0!==s&&!s)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,s,i=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,i,n,s),n}delete(e,t){const s=this.elements.get(e);if(!s)return!1;this.elements.delete(e);const i=this.sorted.indexOf(s);if(-1!==i&&this.sorted.splice(i,1),this.onDelete)if(t)this.onDelete(s);else{const e=this.middleware.get();this.updateElementWith((()=>{e()&&this.onDelete(s)}))}return!0}update(e,t=!1,s=this.get(e),i){if(!s)return;s.index=this.getIndex(s),this.onUpdate&&this.onUpdate(s);const n=(0,Ds.Z)(this.sorted,s,"index");if(!t&&this.onSort){const e=this.middleware.get();(i||this.updateElementWith)((()=>{e()&&this.onSort(s,n)}))}}}class Rs extends Fs{constructor(e={}){let t;super({getIndex:e.getIndex||(e=>E.Z.getUserStatusForSort(e.id)),onDelete:e=>{e.dom.listEl.remove(),this.onListLengthChange&&this.onListLengthChange()},onUpdate:e.onUpdate||(e=>{const t=E.Z.getUserStatusString(e.id);(0,T.Z)(e.dom.lastMessageSpan,t)}),onSort:(e,t)=>{const s=e.dom.listEl.parentElement!==this.list;Zs(e.dom.listEl,this.list,t),s&&this.onListLengthChange&&this.onListLengthChange()},onElementCreate:e=>{const{dom:t}=pd.addDialogNew({dialog:e.id,container:!1,drawStatus:!1,avatarSize:this.avatarSize,autonomous:this.autonomous,meAsSaved:!1,rippleEnabled:this.rippleEnabled,lazyLoadQueue:this.lazyLoadQueue});return e.dom=t,e},updateElementWith:De.T2,updateListWith:e=>{return t=this,s=void 0,n=function*(){return(0,cs.Z)(this.list)?(yield(0,xs.e9)(),(0,cs.Z)(this.list)?void e(!0):e(!1)):e(!1)},new((i=void 0)||(i=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 s;t.done?e(t.value):(s=t.value,s instanceof i?s:new i((function(e){e(s)}))).then(o,r)}l((n=n.apply(t,s||[])).next())}));var t,s,i,n}}),this.avatarSize=48,this.rippleEnabled=!0,this.autonomous=!0,(0,w.Z)(this,e),this.list=pd.createChatList(this.createChatListOptions);const s=()=>{t=window.setTimeout((()=>{this.updateList((e=>{e&&s()}))}),Rs.SORT_INTERVAL)};s()}}Rs.SORT_INTERVAL=3e4;var Bs=s(3444);function Us(e){let t=!1;return new jt(Object.assign(Object.assign({},e),{verifyTouchTarget:t=>!(0,Me.Z)(t.target,"progress-line")&&!(0,Bs.Z)(t)&&(!e.verifyTouchTarget||e.verifyTouchTarget(t)),onSwipe:(s,i,n)=>{if(!t&&Math.abs(i)>20)return!0;if(Math.abs(s)>Math.abs(i))(0,d.d)(n),t=!0;else if(!t&&Math.abs(i)>Math.abs(s))return!0;return e.onSwipe(s,i,n)},onReset:()=>{t=!1,e.onReset&&e.onReset()},cancelEvent:!1}))}function Ns(e){return Us(Object.assign(Object.assign({},e),{onSwipe:(t,s,i)=>{if(Math.abs(t)>50)return e.onSwipe(t,s,i),(0,J.s3)(),!0}}))}var Os=s(6272);class Hs extends Et{constructor(e,t,s=!1){super({peerTypes:["dialogs","contacts"],onSelect:s?t:s=>{return i=this,n=void 0,o=function*(){if(t){const e=t(s);e instanceof Promise&&(yield e)}Ol.setInnerPeer({peerId:s}),Ol.chat.input.initMessagesForward(e)},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},placeholder:"ShareModal.Search.ForwardPlaceholder",chatRightsAction:"send_messages",selfPresence:"ChatYourSelf"})}}class zs{constructor(e,t,s,n){const r=new St.Z({peerId:e}).element;t=t.slice();const l=(a,o)=>{n&&n(),"scheduled"===s?i.Z.deleteScheduledMessages(e,t):i.Z.deleteMessages(e,t,!!a.size||o)};let d,c,h,p,u,g=[];if(1===t.length?d="DeleteSingleMessagesTitle":(d="DeleteMessagesTitle",c=[(0,k.i18n)("messages",[t.length])]),h=o.Z.isMegagroup(e)?1===t.length?"AreYouSureDeleteSingleMessageMega":"AreYouSureDeleteFewMessagesMega":1===t.length?"AreYouSureDeleteSingleMessage":"AreYouSureDeleteFewMessages",u=[{langKey:"Delete",isDanger:!0,callback:l}],e===a.default.myId||"scheduled"===s);else if(e.isUser())g.push({text:"DeleteMessagesOptionAlso",textArgs:[r]});else{const s=j.Z.getChat(e.toChatId()),n=j.Z.hasRights(e.toChatId(),"delete_messages");if("chat"===s._){const s=n?t.slice():t.filter((t=>i.Z.getMessageByPeer(e,t).fromId===a.default.myId));s.length&&(s.length===t.length?g.push({text:"DeleteForAll"}):(g.push({text:"DeleteMessagesOption"}),h="DeleteMessagesTextGroup",p=[(0,k.i18n)("messages",[s.length])]))}else u[0].callback=e=>l(e,!0)}(0,pt.x)(u),new gt("popup-delete-chat",{peerId:e,titleLangKey:d,titleLangArgs:c,descriptionLangKey:h,descriptionLangArgs:p,buttons:u,checkboxes:g}).show()}}var Vs=s(5705);class js{constructor(e,t,s){let n,a,o=[];n=`Send Message${t.length>1?"s":""} Now`,a=t.length>1?"Send "+t.length+" messages now?":"Send message now?",o.push({langKey:"Send",callback:()=>{s&&s(),i.Z.sendScheduledMessages(e,t)}}),new gt("popup-delete-chat",{peerId:e,title:n,description:a,buttons:o}).show()}}var Gs=s(8799);function Ks(){window.getSelection?window.getSelection().empty?window.getSelection().empty():window.getSelection().removeAllRanges&&window.getSelection().removeAllRanges():document.selection&&document.selection.empty()}var Ws=s(5975);const qs=e=>[...e.values()].reduce(((e,t)=>e+t.size),0);class $s extends R.Z{constructor(e){if(super(!1),this.selectedMids=new Map,this.isSelecting=!1,this.cancelSelection=e=>{e&&(this.doNotAnimate=!0),this.onCancelSelection&&this.onCancelSelection(),this.selectedMids.clear(),this.toggleSelection(),Ks(),e&&(this.doNotAnimate=void 0)},(0,w.Z)(this,e),this.navigationType="multiselect-"+(0,it.a)(),ce.IS_TOUCH_SUPPORTED)return this.listenerSetter.add(this.listenElement)("touchend",(()=>{this.isSelecting&&(this.selectedText=window.getSelection?window.getSelection().toString():document.selection?document.selection.createRange().text:"")})),void(0,J.Eo)(this.listenElement,(e=>{if(this.isSelecting||this.verifyTouchLongPress&&!this.verifyTouchLongPress())return;document.body.classList.add("no-select"),this.listenElement.addEventListener("touchend",(e=>{(0,d.d)(e),document.body.classList.remove("no-select")}),{once:!0,capture:!0}),Ks();const t=this.getElementFromTarget(e.target);t&&this.toggleByElement(t)}),this.listenerSetter);const t=(e,t)=>{if(e===t)return[];const s=e.getBoundingClientRect(),i=t.getBoundingClientRect(),n=(s.top-i.top||s.left-i.left)<0,a=(0,Me.Z)(e,this.lookupBetweenParentClassName);if(!a)return[];const o=Array.from(a.querySelectorAll(this.lookupBetweenElementsQuery));let r=o.indexOf(e),l=o.indexOf(t);return n||([l,r]=[r,l]),o.slice(r+1,l)};this.listenerSetter.add(this.listenElement)("mousedown",(e=>{const s=(0,Me.Z)(e.target,this.targetLookupClassName);if(0!==e.button)return;if(this.verifyTarget&&!this.verifyTarget(e,s))return;const i=new Map;let n,a=s;const o=(e,s=!0)=>{const r=+e.dataset.mid;if(!r||!e.dataset.peerId)return;const l=e.dataset.peerId.toPeerId();(0,cs.Z)(a)||(a=e);let d=i.get(l);if(d||i.set(l,d=new Set),!d.has(r)){const c=this.isMidSelected(l,r);if(void 0===n&&(n=!c),d.add(r),n&&!c||!n&&c){const n=qs(i);if(this.toggleByElement&&s){n<2&&(0,Ws.Z)(e,a)&&(a=e);const s=t(a,e);s.length&&s.forEach((e=>{o(e,!1)}))}if(this.selectedMids.size)this.toggleByElement&&this.toggleByElement(e);else if(2===n&&this.toggleByMid)for(const[e,t]of i)for(const s of t)this.toggleByMid(e,s)}}};let r=!1;const c=e=>{r||(Ks(),r=!0);const t=this.getElementFromTarget(e.target);if(t)return this.verifyMouseMoveTarget&&!this.verifyMouseMoveTarget(e,t,n)?(this.listenerSetter.removeManual(this.listenElement,"mousemove",c),void this.listenerSetter.removeManual(document,"mouseup",h,p)):void o(t)},h=e=>{i.size&&(0,l.fc)(window,d.d,{capture:!0,once:!0,passive:!1}),this.listenerSetter.removeManual(this.listenElement,"mousemove",c),Ks()},p={once:!0};this.listenerSetter.add(this.listenElement)("mousemove",c),this.listenerSetter.add(document)("mouseup",h,p)}))}isElementShouldBeSelected(e){return this.isMidSelected(e.dataset.peerId.toPeerId(),+e.dataset.mid)}appendCheckbox(e,t){e.prepend(t.label)}toggleElementCheckbox(e,t){const s=!!this.getCheckboxInputFromElement(e);if(t){if(s)return!1;const t=new ut.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 s&&this.getCheckboxInputFromElement(e).parentElement.remove();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){const t=this.selectedMids.size;if(!t&&!e)return;let s=!t,i=!t,n=!t;for(const[e,t]of this.selectedMids){const n=this.isScheduled?this.appMessagesManager.getScheduledMessagesStorage(e):this.appMessagesManager.getMessagesStorage(e);for(const e of t){const t=this.appMessagesManager.getMessageFromStorage(n,e);if(s||(s=!this.appMessagesManager.canForward(t)),i||(i=!this.appMessagesManager.canDeleteMessage(t)),s&&i)break}if(s&&i)break}this.onUpdateContainer&&this.onUpdateContainer(s,i,n)}toggleSelection(e=!0,t=!1){const s=this.isSelecting,i=this.selectedMids.size;if(this.isSelecting=!!i||t,s===this.isSelecting)return!1;this.dispatchEvent("toggle",this.isSelecting),ce.IS_TOUCH_SUPPORTED||(this.listenElement.classList.toggle("no-select",this.isSelecting),s&&Ks()),(0,Gs.Z)();const n=!!i||t;return this.onToggleSelection&&this.onToggleSelection(n,!this.doNotAnimate),ne.IS_MOBILE_SAFARI||(n?F.Z.pushItem({type:this.navigationType,onPop:()=>{this.cancelSelection()}}):F.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(),(0,Jt.Z)(e,"is-selected",t,200)}isMidSelected(e,t){const s=this.selectedMids.get(e);return null==s?void 0:s.has(t)}length(){return qs(this.selectedMids)}toggleMid(e,t,s){let i=this.selectedMids.get(e);if(s||void 0===s&&(null==i?void 0:i.has(t)))i&&(i.delete(t),i.size||this.selectedMids.delete(e));else{if(a.default.config.forwarded_count_max-this.length()-1<0)return rt(k.default.format("Chat.Selection.LimitToast",!0)),!1;i||(i=new Set,this.selectedMids.set(e,i)),i.add(t)}return!0}deleteSelectedMids(e,t){const s=this.selectedMids.get(e);s&&(t.forEach((e=>{s.delete(e)})),s.size||this.selectedMids.delete(e),this.updateContainer(),this.toggleSelection())}}class Qs extends $s{constructor(e,t){super({appMessagesManager:t,listenElement:e.container,listenerSetter:new B.Z,verifyTarget:(e,t)=>!!t&&this.isSelecting,getElementFromTarget:e=>(0,Me.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,s=e.dataset.peerId.toPeerId();this.toggleMid(s,t)&&this.updateElementSelection(e,this.isMidSelected(s,t))},this.toggleByMid=(e,t)=>{const s=this.searchSuper.mediaTab.contentTab.querySelector(`.search-super-item[data-peer-id="${e}"][data-mid="${t}"]`);this.toggleByElement(s)},this.onUpdateContainer=(e,t,s)=>{const i=this.length();(0,T.Z)(this.selectionCountEl,(0,k.i18n)("messages",[i])),this.selectionGotoBtn.classList.toggle("hide",1!==i),this.selectionForwardBtn.classList.toggle("hide",e),this.selectionDeleteBtn&&this.selectionDeleteBtn.classList.toggle("hide",t)},this.onToggleSelection=(e,t)=>{if((0,Jt.Z)(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)})),(0,Jt.Z)(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=N(`close ${e}-cancel`,{noRipple:!0});this.listenerSetter.add(t)("click",(()=>this.cancelSelection()),{once:!0}),this.selectionCountEl=document.createElement("div"),this.selectionCountEl.classList.add(e+"-count"),this.selectionGotoBtn=N(`message ${e}-goto`);const s={listenerSetter:this.listenerSetter};(0,l.fc)(this.selectionGotoBtn,(()=>{const e=[...this.selectedMids.keys()][0],t=[...this.selectedMids.get(e)][0];this.cancelSelection(),a.default.dispatchEvent("history_focus",{peerId:e,mid:t})}),s),this.selectionForwardBtn=N(`forward ${e}-forward`),(0,l.fc)(this.selectionForwardBtn,(()=>{const e={};for(const[t,s]of this.selectedMids)e[t]=Array.from(s).sort(((e,t)=>e-t));new Hs(e,(()=>{this.cancelSelection()}))}),s),this.isPrivate&&(this.selectionDeleteBtn=N(`delete danger ${e}-delete`),(0,l.fc)(this.selectionDeleteBtn,(()=>{const e=[...this.selectedMids.keys()][0];new zs(e,[...this.selectedMids.get(e)],"chat",(()=>{this.cancelSelection()}))}),s)),this.selectionContainer.append(...[t,this.selectionCountEl,this.selectionGotoBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean));const i=this.selectionContainer;i.style.opacity="0",this.searchSuper.navScrollableContainer.append(i),i.offsetLeft,i.style.opacity=""}},this.isPrivate=!e.showSender}toggleSelection(e=!0,t=!1){const s=super.toggleSelection(e,t);return s&&e&&Array.from(this.searchSuper.tabsContainer.querySelectorAll(".search-super-item")).forEach((e=>{this.toggleElementCheckbox(e,this.isSelecting)})),s}}class Ys extends $s{constructor(e,t,s,i){super({appMessagesManager:i,listenElement:t.bubblesContainer,listenerSetter:t.listenerSetter,getElementFromTarget:e=>(0,Me.Z)(e,"grouped-item")||(0,Me.Z)(e,"bubble"),verifyTarget:(e,t)=>!(!this.selectedMids.size&&!e.target.classList.contains("bubble")&&!e.target.classList.contains("document-selection")&&t),verifyMouseMoveTarget:(e,t,s)=>!(e.target!==t&&!e.target.classList.contains("document-selection")&&void 0===s&&!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=s,this.toggleByElement=e=>{if(!this.canSelectBubble(e))return;const t=+e.dataset.mid;if(e.classList.contains("is-grouped")){if(!this.isGroupedBubbleSelected(e)){const e=this.selectedMids.get(this.bubbles.peerId);e&&this.chat.getMidsByMid(t).forEach((t=>e.delete(t)))}this.bubbles.getBubbleGroupedItems(e).forEach(this.toggleByElement)}else if(this.toggleMid(this.bubbles.peerId,t)){if(e.classList.contains("grouped-item")){const s=(0,Me.Z)(e,"bubble"),i=this.isGroupedBubbleSelected(s),n=this.isGroupedMidsSelected(t);(n||i)&&this.updateElementSelection(s,n)}this.updateElementSelection(e,this.isMidSelected(this.bubbles.peerId,t))}},this.toggleByMid=(e,t)=>{const s=this.bubbles.getMountedBubble(t);s&&this.toggleByElement(s.bubble)},this.onToggleSelection=(e,t)=>{const{needTranslateX:s,widthFrom:i,widthTo:n}=this.chat.input.center(t);(0,Jt.Z)(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 a=i<n?void 0:2*s;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=N("close",{noRipple:!0});(0,l.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,U.Z)("btn-primary btn-transparent btn-short text-bold selection-container-send",{icon:"send2"}),this.selectionSendNowBtn.append((0,k.i18n)("MessageScheduleSend")),(0,l.fc)(this.selectionSendNowBtn,(()=>{new js(this.bubbles.peerId,[...this.selectedMids.get(this.bubbles.peerId)],(()=>{this.cancelSelection()}))}),e)):(this.selectionForwardBtn=(0,U.Z)("btn-primary btn-transparent text-bold selection-container-forward",{icon:"forward"}),this.selectionForwardBtn.append((0,k.i18n)("Forward")),(0,l.fc)(this.selectionForwardBtn,(()=>{const e={};for(const[t,s]of this.selectedMids)e[t]=Array.from(s).sort(((e,t)=>e-t));new Hs(e,(()=>{this.cancelSelection()}))}),e)),this.selectionDeleteBtn=(0,U.Z)("btn-primary btn-transparent danger text-bold selection-container-delete",{icon:"delete"}),this.selectionDeleteBtn.append((0,k.i18n)("Delete")),(0,l.fc)(this.selectionDeleteBtn,(()=>{new zs(this.bubbles.peerId,[...this.selectedMids.get(this.bubbles.peerId)],this.chat.type,(()=>{this.cancelSelection()}))}),e);const s=this.selectionLeft=document.createElement("div");s.classList.add("selection-container-left"),s.append(t,this.selectionCountEl);const i=this.selectionRight=document.createElement("div");i.classList.add("selection-container-right"),i.append(...[this.selectionSendNowBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean)),void 0!==a&&(s.style.transform=`translateX(${-a}px)`,i.style.transform=`translateX(${a}px)`),this.selectionContainer.append(s,i),this.selectionInputWrapper.style.opacity="0",this.selectionInputWrapper.append(this.selectionContainer),this.input.inputContainer.append(this.selectionInputWrapper),this.selectionInputWrapper.offsetLeft,this.selectionInputWrapper.style.opacity="",s.style.transform="",i.style.transform=""}}else this.selectionLeft&&void 0!==a&&(this.selectionLeft.style.transform=`translateX(-${a}px)`,this.selectionRight.style.transform=`translateX(${a}px)`)},this.onUpdateContainer=(e,t,s)=>{(0,T.Z)(this.selectionCountEl,(0,k.i18n)("messages",[this.length()])),this.selectionSendNowBtn&&this.selectionSendNowBtn.toggleAttribute("disabled",s),this.selectionForwardBtn&&this.selectionForwardBtn.toggleAttribute("disabled",e),this.selectionDeleteBtn.toggleAttribute("disabled",t)},this.onCancelSelection=()=>{for(const[e,t]of this.selectedMids)for(const e of t){const t=this.bubbles.getMountedBubble(e);t&&this.toggleByElement(t.bubble)}}}appendCheckbox(e,t){t.label.classList.add("bubble-select-checkbox"),e.classList.contains("document-container")?e.querySelector(".document, audio-element").append(t.label):super.appendCheckbox(e,t)}toggleSelection(e=!0,t=!1){const s=super.toggleSelection(e,t);if(s&&e)for(const e in this.bubbles.bubbles){const t=this.bubbles.bubbles[e];this.toggleElementCheckbox(t,this.isSelecting)}return s}toggleElementCheckbox(e,t){if(!this.canSelectBubble(e))return;const s=super.toggleElementCheckbox(e,t);return s&&e.classList.contains("is-grouped")&&this.bubbles.getBubbleGroupedItems(e).forEach((e=>this.toggleElementCheckbox(e,t))),s}isElementShouldBeSelected(e){const t=e.classList.contains("is-grouped");return super.isElementShouldBeSelected(e)&&(!t||this.isGroupedMidsSelected(+e.dataset.mid))}isGroupedBubbleSelected(e){const t=this.getCheckboxInputFromElement(e);return null==t?void 0:t.checked}isGroupedMidsSelected(e){const t=this.chat.getMidsByMid(e),s=t.filter((e=>this.isMidSelected(this.bubbles.peerId,e)));return t.length===s.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 Xs=s(7401),Js=s(3738),ei=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class ti{constructor(e,t){this.attachTo=e,this.searchSuper=t,this.onGotoClick=()=>{a.default.dispatchEvent("history_focus",{peerId:this.peerId,mid:this.mid,threadId:this.searchSuper.searchContext.threadId})},this.onForwardClick=()=>{this.searchSuper.selection.isSelecting?(0,l.tH)(this.searchSuper.selection.selectionForwardBtn):new Hs({[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,l.tH)(this.searchSuper.selection.selectionDeleteBtn):new zs(this.peerId,[this.mid],"chat")};ce.IS_TOUCH_SUPPORTED||(0,J.Eo)(e,(e=>{let s;this.init&&(this.init(),this.init=null);try{s=(0,Me.Z)(e.target,"search-super-item")}catch(e){}if(s){if(e instanceof MouseEvent&&e.preventDefault(),this.element.classList.contains("active"))return!1;e instanceof MouseEvent&&(e.cancelBubble=!0),this.target=s,this.peerId=s.dataset.peerId.toPeerId(),this.mid=+s.dataset.mid,this.isSelected=t.selection.isMidSelected(this.peerId,this.mid),this.buttons.forEach((e=>{let t;t=!(this.isSelected&&!e.withSelection)&&(!e.verify||e.verify()),e.element.classList.toggle("hide",!t)})),s.classList.add("menu-open"),(0,J.oy)(e,this.element),(0,J.YP)(this.element,(()=>{s.classList.remove("menu-open")}))}}))}init(){this.buttons=[{icon:"forward",text:"Forward",onClick:this.onForwardClick,verify:()=>i.Z.canForward(i.Z.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:()=>i.Z.canDeleteMessage(i.Z.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=Ce(this.buttons),this.element.classList.add("search-contextmenu","contextmenu"),document.getElementById("page-chats").append(this.element)}}class si{constructor(e){this.tabs={},this.prevTabId=-1,this.lazyLoadQueue=new X.ZP,this.middleware=(0,As.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,$.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,w.Z)(this,e),this.container=document.createElement("div"),this.container.classList.add("search-super"),this.searchContextMenu=new ti(this.container,this),this.selection=new Qs(this,i.Z);const t=this.navScrollableContainer=document.createElement("div");t.classList.add("search-super-tabs-scrollable","menu-horizontal-scrollable","sticky");const s=this.navScrollable=new P.v7(t);s.container.classList.add("search-super-nav-scrollable");const n=this.nav=document.createElement("nav");n.classList.add("search-super-tabs","menu-horizontal-div"),this.tabsMenu=n,s.container.append(n);for(const e of this.mediaTabs){const t=document.createElement("div");t.classList.add("menu-horizontal-div-item");const s=document.createElement("span"),i=document.createElement("i");s.append((0,k.i18n)(e.name)),s.append(i),t.append(s),(0,ee.ripple)(t),this.tabsMenu.append(t),this.mediaTabsMap.set(e.type,e),e.menuTab=t}let a;this.tabsContainer=document.createElement("div"),this.tabsContainer.classList.add("search-super-tabs-container","tabs-container"),ce.IS_TOUCH_SUPPORTED&&Ns({element:this.tabsContainer,onSwipe:(e,t,s)=>{const i=this.selectTab.prevId(),n=Array.from(this.tabsMenu.children);let o;if(e>0){for(let e=i+1;e<n.length;++e)if(!n[e].classList.contains("hide")){o=e;break}}else for(let e=i-1;e>=0;--e)if(!n[e].classList.contains("hide")){o=e;break}void 0!==o&&(a=function(e){const t=e=>{(0,d.d)(e)};let s=2;const i=()=>{--s||e.removeEventListener("touchmove",t,{capture:!0})};return e.addEventListener("touchmove",t,{capture:!0,passive:!1}),e.addEventListener("touchend",i,{once:!0}),i}(this.tabsContainer),this.selectTab(o))}});for(const e of this.mediaTabs){const t=document.createElement("div");t.classList.add("search-super-container-"+e.type,"tabs-tab");const s=document.createElement("div");s.classList.add("search-super-content-"+e.type),t.append(s),this.tabsContainer.append(t),this.tabs[e.inputFilter]=s,e.contentTab=s}this.container.append(t,this.tabsContainer),this.searchGroupMedia=new x(!1,"messages",!0),this.scrollable.onScrolledBottom=()=>{this.mediaTab.contentTab&&!this.loaded[this.mediaTab.inputFilter]&&this.load(!0)},this.selectTab=(0,Y.X)(this.tabsMenu,this.tabsContainer,((e,t,s)=>{if(this.prevTabId===e&&!this.skipScroll)return void this.scrollable.scrollIntoViewNew({element:this.container,position:"start"});const i=this.mediaTabs[e];this.onChangeTab&&this.onChangeTab(i);const n=this.mediaTab;if(this.mediaTab=i,-1!==this.prevTabId&&s&&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"}),t=e),n.scroll={scrollTop:t,scrollHeight:this.scrollable.scrollHeight},void 0===i.scroll){const e=this.container.getBoundingClientRect(),s=this.container.parentElement.getBoundingClientRect(),n=e.y-s.y;t>n&&(i.scroll={scrollTop:n,scrollHeight:0})}if(i.scroll){const e=n.scroll.scrollTop-i.scroll.scrollTop;e&&(i.contentTab.style.transform=`translateY(${e}px)`)}}-1===this.prevTabId||i.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),a&&(a(),a=void 0),this.onTransitionEnd()}),void 0,s),(0,l.fc)(this.tabsContainer,(e=>{this.selection.isSelecting&&((0,d.d)(e),this.selection.toggleByElement((0,Me.Z)(e.target,"search-super-item")))}),{capture:!0,passive:!1});const o=(e,t,s,n)=>{const a=(0,Me.Z)(n.target,e);if(!a)return;const o=+a.dataset.mid;if(!o)return void this.log.warn("no messageId by click on target:",a);const r=a.dataset.peerId.toPeerId(),l=Array.from(this.tabs[s].querySelectorAll("."+t)).map((t=>{const s=(0,Me.Z)(t,e);return{element:t,mid:+s.dataset.mid,peerId:s.dataset.peerId.toPeerId()}})),d=l.findIndex((e=>e.mid===o&&e.peerId===r)),c=i.Z.getMessageByPeer(r,o);(new Vl).setSearchContext(this.copySearchContext(s)).openMedia(c,l[d].element,0,!1,l.slice(0,d),l.slice(d+1))};(0,l.fc)(this.tabs.inputMessagesFilterPhotoVideo,o.bind(null,"grid-item","grid-item","inputMessagesFilterPhotoVideo")),(0,l.fc)(this.tabs.inputMessagesFilterDocument,o.bind(null,"document-with-thumb","media-container","inputMessagesFilterDocument")),this.mediaTab=this.mediaTabs[0],(0,xs.ZP)((()=>{this.lazyLoadQueue.lock()}),(()=>{this.lazyLoadQueue.unlockAndRefresh()}))}filterMessagesByType(e,t){if("inputMessagesFilterEmpty"===t)return e;"inputMessagesFilterUrl"!==t&&(e=e.filter((e=>!!e.media)));let s=[];switch(t){case"inputMessagesFilterPhotoVideo":for(let t of e){let e=t.media.photo||t.media.document||t.media.webpage&&t.media.webpage.document;e&&("document"===e._&&"video"!==e.type||s.push(t))}break;case"inputMessagesFilterDocument":for(let t of e)t.media.document&&!["voice","audio","gif","sticker","round"].includes(t.media.document.type)&&s.push(t);break;case"inputMessagesFilterUrl":for(let t of e)s.push(t);break;case"inputMessagesFilterMusic":for(let t of e)t.media.document&&"audio"===t.media.document.type&&s.push(t);break;case"inputMessagesFilterVoice":for(let t of e)t.media.document&&"voice"===t.media.document.type&&s.push(t);break;case"inputMessagesFilterRoundVoice":for(let t of e)t.media.document&&["voice","round"].includes(t.media.document.type)&&s.push(t)}return s}processEmptyFilter({message:e,searchGroup:t}){const{dialog:s,dom:i}=pd.addDialogNew({dialog:e.peerId,container:t.list,drawStatus:!1,avatarSize:54});pd.setLastMessage(s,e,i,this.searchContext.query)}processPhotoVideoFilter({message:e,promises:t,middleware:s,elemsToAppend:n}){const a=i.Z.getMediaFromMessage(e),o=document.createElement("div");let l;o.classList.add("grid-item");const d=r.Z.choosePhotoSize(a,200,200);l="photo"!==a._?ys({doc:a,message:e,container:o,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:s,onlyPreview:!0,withoutPreloader:!0,noPlayButton:!0,size:d}).thumb:Ss({photo:a,message:e,container:o,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:s,withoutPreloader:!0,noBlur:!0,size:d}),[l.images.thumb,l.images.full].filter(Boolean).forEach((e=>{e.classList.add("grid-item-media")})),t.push(l.loadPromises.thumb),n.push({element:o,message:e})}processDocumentFilter({message:e,elemsToAppend:t,inputFilter:s}){const n=i.Z.getMediaFromMessage(e),a=this.showSender||["voice","round"].includes(n.type),o=ws({message:e,withTime:!a,fontWeight:400,voiceAsMusic:!0,showSender:a,searchContext:this.copySearchContext(s),lazyLoadQueue:this.lazyLoadQueue,autoDownloadSize:0});["audio","voice","round"].includes(n.type)&&o.classList.add("audio-48"),t.push({element:o,message:e})}processUrlFilter({message:e,promises:t,middleware:s,elemsToAppend:n}){var a;let o=null===(a=e.media)||void 0===a?void 0:a.webpage;if(!o){const t=e.totalEntities?e.totalEntities.find((e=>"messageEntityUrl"===e._||"messageEntityTextUrl"===e._)):null;let s,i,n;if(t)n=e.message.slice(t.offset,t.offset+t.length);else{const t=Q.Z.matchUrl(e.message);if(!t)return;s=t[0]}s="messageEntityTextUrl"===(null==t?void 0:t._)?t.url:s||n,i=s;const a=e.message===s;s.match(/^(ftp|http|https):\/\//)||(i="https://"+s,s=s.includes("@")?s:"https://"+s),i=new URL(i).hostname,o={_:"webPage",url:s,display_url:i,id:"",hash:0},a||(o.description=e.message,o.rDescription=Q.Z.wrapRichText((0,ze.Z)(e.message,150,180)))}let l=document.createElement("div");l.classList.add("preview","row-media"),o.photo?Ss({container:l,message:null,photo:o.photo,boxWidth:0,boxHeight:0,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue,middleware:s,size:r.Z.choosePhotoSize(o.photo,60,60,!1),loadPromises:t,noBlur:!0}):(l.classList.add("empty"),l.innerHTML=Q.Z.getAbbreviation(o.title||o.display_url||o.description||o.url,!0));let d=o.rTitle||"",c=o.rDescription||"";const h=(0,Vs.Z)(c),p=(0,Vs.Z)(Q.Z.wrapRichText(o.url||"")).firstElementChild;if(p instanceof HTMLAnchorElement)try{p.innerText=decodeURIComponent(p.href)}catch(e){}h.firstChild&&h.append("\n"),h.append(p),this.showSender&&h.append("\n",i.Z.wrapSenderToPeer(e)),d||(d=Q.Z.wrapPlainText(o.display_url.split("/",1)[0]));const u=new et({title:d,titleRight:i.Z.wrapSentTime(e),subtitle:h,havePadding:!0,clickable:!0,noRipple:!0});u.container.append(l),u.container.innerText.trim().length&&n.push({element:u.container,message:e})}performSearchResult(e,t,s=!0){return ei(this,void 0,void 0,(function*(){const i=[],n=t.contentTab,a=[],o=this.middleware.get();let r,l=t.inputFilter;yield(0,xs.e9)(),"inputMessagesFilterPhotoVideo"===l&&this.searchContext.query.trim()?(l="inputMessagesFilterEmpty",r=this.searchGroupMedia,n.append(r.container)):"inputMessagesFilterEmpty"===l&&(r=this.searchGroups.messages);const d={elemsToAppend:i,inputFilter:l,message:void 0,middleware:o,promises:a,searchGroup:r};let c;switch(l){case"inputMessagesFilterEmpty":c=this.processEmptyFilter;break;case"inputMessagesFilterPhotoVideo":c=this.processPhotoVideoFilter;break;case"inputMessagesFilterVoice":case"inputMessagesFilterRoundVoice":case"inputMessagesFilterMusic":case"inputMessagesFilterDocument":c=this.processDocumentFilter;break;case"inputMessagesFilterUrl":c=this.processUrlFilter}if(c){c=c.bind(this);for(const t of e)try{d.message=t,c(d)}catch(e){this.log.error("error rendering filter",l,d,t,e)}}if(r&&r.list.childElementCount&&r.setActive(),this.loadMutex&&a.push(this.loadMutex),!a.length||(yield Promise.all(a),o())){if(i.length){const e=s?"append":"prepend";i.forEach((t=>{const{element:s,message:i}=t,n=this.getMonthContainerByTimestamp(this.groupByMonth?i.date:0,l);s.classList.add("search-super-item"),s.dataset.mid=""+i.mid,s.dataset.peerId=""+i.peerId,n.items[e](s),this.selection.isSelecting&&this.selection.toggleElementCheckbox(s,!0)}))}this.afterPerforming("inputMessagesFilterEmpty"===l?1:e.length,n)}}))}afterPerforming(e,t){if(t){const s=t.parentElement;if(Array.from(s.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"),s.append(e)}}}loadChats(){const e=new Set,t=this.middleware.get();for(let e in this.searchGroups){const t=this.searchGroups[e];this.tabs.inputMessagesFilterEmpty.append(t.container),t.clear()}const s=this.searchContext.query;if(s){const r=(t,i,r=!1)=>{t.forEach((t=>{if(e.has(t))return;e.add(t);const l=o.Z.getPeer(t),{dom:d}=pd.addDialogNew({dialog:t,container:i.list,drawStatus:!1,avatarSize:48,autonomous:i.autonomous});if(r&&(l.participants_count||l.participants)){const e=new RegExp(`(${(0,Js.Z)(s)}|${(0,Js.Z)((0,hs.ZP)(s))})`,"gi");d.titleSpan.innerHTML=d.titleSpan.innerHTML.replace(e,"<i>$1</i>"),d.lastMessageSpan.append(n.default.getChatMembersString(t.toChatId()))}else if(t===a.default.myId)d.lastMessageSpan.append((0,k.i18n)("Presence.YourChat"));else{let e=o.Z.getPeerUsername(t);if(e)e="@"+e;else{const s=E.Z.getUser(t);s&&s.phone&&(e="+"+(0,Os.u)(s.phone).formatted)}d.lastMessageSpan.innerHTML="<i>"+e+"</i>"}})),i.toggle()},d=e=>{if(t())return e};return Promise.all([E.Z.getContactsPeerIds(s,!0).then(d).then((e=>{e&&r(e,this.searchGroups.contacts,!0)})),E.Z.searchContacts(s,20).then(d).then((e=>{if(e&&(r(e.my_results,this.searchGroups.contacts,!0),r(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 k.default.IntlElement({key:"Separator.ShowMore"});e.append(t.element),this.searchGroups.globalContacts.nameEl.append(e),(0,l.fc)(e,(()=>{const e=this.searchGroups.globalContacts.container.classList.toggle("is-short");t.key=e?"Separator.ShowMore":"Separator.ShowLess",t.update()}))}})),i.Z.getConversations(s,0,20,0).promise.then(d).then((e=>{e&&r(e.dialogs.map((e=>e.peerId)),this.searchGroups.contacts,!0)}))])}if(this.searchContext.peerId||this.searchContext.minDate)return Promise.resolve();{const e=(e=!0)=>M.default.getState().then((s=>{t()&&(this.searchGroups.recent.list.innerHTML="",s.recentSearch.slice(0,20).forEach((e=>{let{dialog:t,dom:s}=pd.addDialogNew({dialog:e,container:this.searchGroups.recent.list,drawStatus:!1,meAsSaved:!0,avatarSize:48,autonomous:!0});s.lastMessageSpan.append(e.isUser()?E.Z.getUserStatusString(e):n.default.getChatMembersString(e.toChatId()))})),s.recentSearch.length?e&&this.searchGroups.recent.setActive():this.searchGroups.recent.clear())}));return Promise.all([E.Z.getTopPeers("correspondents").then((e=>{if(!t())return;const s=e.findIndex((e=>e.id===a.default.myId));-1!==s&&(e=e.slice()).splice(s,1),e.length&&e.forEach((e=>{pd.addDialogNew({dialog:e.id,container:this.searchGroups.people.list,drawStatus:!1,onlyFirstName:!0,avatarSize:54,autonomous:!1})})),this.searchGroups.people.setActive()})),e()])}}loadMembers(e){const t=this.searchContext.peerId.toChatId(),s=this.middleware.get();let i;const a=t=>ei(this,void 0,void 0,(function*(){this.loadMutex&&(yield this.loadMutex,!s())||(this.membersList||(this.membersList=new Rs({lazyLoadQueue:this.lazyLoadQueue,rippleEnabled:!1}),(0,l.fc)(this.membersList.list,(e=>{const t=(0,ft.Z)(e.target,"LI");if(!t)return;const s=t.dataset.peerId.toPeerId();let i=Promise.resolve();v.ZP.isMobile&&(i=Yt.toggleSidebar(!1)),i.then((()=>{Ol.setInnerPeer({peerId:s})}))})),e.contentTab.append(this.membersList.list),this.afterPerforming(1,e.contentTab)),t.forEach((e=>{const t=j.Z.getParticipantPeerId(e);t.isAnyChat()||E.Z.getUser(t).pFlags.deleted||this.membersList.add(t)})))}));if(j.Z.isChannel(t)){const o=this.membersList?200:50;i=n.default.getChannelParticipants(t,void 0,o,this.nextRates[e.inputFilter]).then((t=>{if(!s())return;let i=e.contentTab.firstElementChild;return this.nextRates[e.inputFilter]=(i?i.childElementCount:0)+t.participants.length,t.participants.length<o&&(this.loaded[e.inputFilter]=!0),a(t.participants)}))}else i=Promise.resolve(n.default.getChatFull(t)).then((t=>{if(!s())return;this.loaded[e.inputFilter]=!0;const i=t.participants;return"chatParticipantsForbidden"!==i._?a(i.participants):void 0}));return this.loadPromises[e.inputFilter]=i.finally((()=>{s()&&(this.loadPromises[e.inputFilter]=null)}))}loadType(e,t,s,n){var a,o;const r=e.inputFilter;if(this.loadPromises[r])return this.loadPromises[r];if("members"===e.type)return this.loadMembers(e);const l=null!==(a=this.historyStorage[r])&&void 0!==a?a:this.historyStorage[r]=[];if(!("inputMessagesFilterEmpty"!==r||l.length||(this.loadedChats||(this.loadChats(),this.loadedChats=!0),this.searchContext.query.trim()||this.searchContext.peerId||this.searchContext.minDate)))return this.loaded[r]=!0,Promise.resolve();const d="load ["+r+"]: ";if(l.length&&this.usedFromHistory[r]<l.length&&!t){let t=[],n=Math.max(0,this.usedFromHistory[r]),a=0;do{let e=l.slice(n,n+s);n+=e.length,a+=e.length,t.push(...this.filterMessagesByType(e.map((e=>i.Z.getMessageByPeer(e.peerId,e.mid))),r))}while(a<s&&n<l.length);return this.usedFromHistory[r]=n,this.performSearchResult(t,e).finally((()=>{setTimeout((()=>{this.scrollable.checkForTriggers()}),0)}))}let c=l.length?l[l.length-1].mid:0;return this.loadPromises[r]=i.Z.getSearch(Object.assign(Object.assign({},this.searchContext),{inputFilter:{_:r},maxId:c,limit:s,nextRate:null!==(o=this.nextRates[r])&&void 0!==o?o:this.nextRates[r]=0})).then((i=>{if(l.push(...i.history.map((e=>({mid:e.mid,peerId:e.peerId})))),this.log(d+"search house of glass",r,i),n())return(i.history.length<s||void 0!==this.searchContext.folderId&&!i.next_rate||i.history.length===i.count)&&(this.loaded[r]=!0),this.nextRates[r]=i.next_rate,t?Promise.resolve():(this.usedFromHistory[r]=l.length,this.loaded[r]||(this.loadPromises[r]||Promise.resolve()).then((()=>{setTimeout((()=>{if(n()&&this.mediaTab===e){const e=this.load(!0,!0);e&&e.then((()=>{n()&&setTimeout((()=>{this.scrollable.checkForTriggers()}),0)}))}}),0)})),this.performSearchResult(this.filterMessagesByType(i.history,r),e))})).catch((e=>{this.log.error("load error:",e)})).finally((()=>{this.loadPromises[r]=null}))}load(e=!1,t=!1){return ei(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(this.hideEmptyTabs){const e=this.mediaTabs.filter((e=>"inputMessagesFilterEmpty"!==e.inputFilter)),t=e.map((e=>({_:e.inputFilter}))),a=yield i.Z.getSearchCounters(s,t);if(!n())return;if(this.loadMutex&&(yield this.loadMutex,!n()))return;let o,r=0;e.forEach((e=>{const t=a.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),t.count&&++r}));const l=this.mediaTabsMap.get("members"),d=this.canViewMembers();l.menuTab.classList.toggle("hide",!d),d&&(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),o.menuTab.classList.add("active"),this.navScrollableContainer.classList.toggle("hide",r<=1))}this.firstLoad=!1}let a=e?[this.mediaTab]:this.mediaTabs.filter((e=>e!==this.mediaTab));if(a=a.filter((e=>{const t=e.inputFilter;return!this.loaded[t]||this.historyStorage[t]&&this.usedFromHistory[t]<this.historyStorage[t].length})),s.isUser()&&a.findAndSplice((e=>"members"===e.type)),!a.length)return;const o=t?50:Math.round(3*(Ct.Z.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 s;const i=new Date(1e3*e);i.setHours(0,0,0),i.setDate(1);const n=i.getTime(),a=null!==(s=this.monthContainers[t])&&void 0!==s?s:this.monthContainers[t]={};if(!(n in a)){const e=document.createElement("div");e.className="search-super-month";const s=document.createElement("div");s.classList.add("search-super-month-name");const o={month:"long"};i.getFullYear()!==(new Date).getFullYear()&&(o.year="numeric");const r=new k.default.IntlDateElement({date:i,options:o}).element;s.append(r),e.append(s);const l=document.createElement("div");l.classList.add("search-super-month-items"),e.append(s,l);const d=(0,Xs.Z)(a,"desc");let c=0;for(;c<d.length&&!(n>d[c]);++c);a[n]={container:e,items:l},Zs(e,this.tabs[t],c)}return a[n]}canViewMembers(){return this.searchContext.peerId.isAnyChat()&&!j.Z.isBroadcast(this.searchContext.peerId.toChatId())&&j.Z.hasRights(this.searchContext.peerId.toChatId(),"view_participants")}cleanup(){this.loadPromises={},this.loaded={},this.loadedChats=!1,this.nextRates={},this.firstLoad=!0,this.lazyLoadQueue.clear(),this.mediaTabs.forEach((e=>{this.usedFromHistory[e.inputFilter]=-1})),this.selection.isSelecting&&this.selection.cancelSelection(),this.middleware.clean(),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,J.y7)(t,!0);const s=t.querySelector(".content-empty");s&&s.remove()}})),this.monthContainers={},this.searchGroupMedia.clear(),this.scrollable.scrollTop=0}copySearchContext(e){const t=(0,pe.Z)(this.searchContext);return t.inputFilter={_:e},t.nextRate=this.nextRates[e],t}setQuery({peerId:e,query:t,threadId:s,historyStorage:i,folderId:n,minDate:a,maxDate:o}){this.searchContext={peerId:e,query:t||"",inputFilter:{_:this.mediaTab.inputFilter},threadId:s,folderId:n,minDate:a,maxDate:o},this.historyStorage=null!=i?i:{},this.cleanup()}}var ii,ni=s(5185),ai=s(4847);!function(e){e[e.Everybody=2]="Everybody",e[e.Contacts=1]="Contacts",e[e.Nobody=0]="Nobody"}(ii||(ii={}));const oi=new class{constructor(){this.privacy={},a.default.addMultipleEventsListeners({updatePrivacy:e=>{const t=e.key._;this.privacy[t]=e.rules,a.default.dispatchEvent("privacy_update",e)}})}setPrivacy(e,t){return ct.Z.invokeApi("account.setPrivacy",{key:{_:e},rules:t}).then((s=>(E.Z.saveApiUsers(s.users),j.Z.saveApiChats(s.chats),ni.Z.processLocalUpdate({_:"updatePrivacy",key:{_:(0,ai.Z)(e)},rules:t.map((e=>{const t={};return Object.assign(t,e),t._=(0,ai.Z)(t._),t}))}),s.rules)))}getPrivacy(e){const t=(0,ai.Z)(e),s=this.privacy[t];return s?Promise.resolve(s):this.privacy[t]=ct.Z.invokeApi("account.getPrivacy",{key:{_:e}}).then((e=>(E.Z.saveApiUsers(e.users),j.Z.saveApiChats(e.chats),this.privacy[t]=e.rules)))}getPrivacyRulesDetails(e){const t=[];let s={users:[],chats:[]},i={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":s.chats.push(...e.chats);break;case"privacyValueAllowUsers":s.users.push(...e.users);break;case"privacyValueDisallowChatParticipants":i.chats.push(...e.chats);break;case"privacyValueDisallowUsers":i.users.push(...e.users)}})),{type:t[0],disallowPeers:i,allowPeers:s}}};re.GO.appPrivacyManager=oi;const ri=oi;class li{constructor(e){this.options=e,this.onRadioChange=e=>{e=+e,this.type=e;const t=this.options.captions[this.type],s=this.radioSection.caption;t?(0,k._i18n)(s,t):s.innerHTML="",s.classList.toggle("hide",!t),this.exceptions&&(this.exceptions.get("allow").row.container.classList.toggle("hide",this.type===ii.Everybody),this.exceptions.get("disallow").row.container.classList.toggle("hide",this.type===ii.Nobody)),this.options.onRadioChange&&this.options.onRadioChange(e)},e.captions&&e.captions.reverse(),this.radioSection=new Mn({name:e.title,caption:!0}),this.radioRows=new Map;let t=[{type:ii.Everybody,langKey:"PrivacySettingsController.Everbody"},{type:ii.Contacts,langKey:"PrivacySettingsController.MyContacts"},{type:ii.Nobody,langKey:"PrivacySettingsController.Nobody"}];e.skipTypes&&(t=t.filter((t=>!e.skipTypes.includes(t.type))));const s=(0,it.a)();t.forEach((({type:e,langKey:t})=>{const i=new et({radioField:new at({langKey:t,name:s,value:""+e})});this.radioRows.set(e,i)}));const i=tt([...this.radioRows.values()],this.onRadioChange);if(this.radioSection.content.append(i),e.appendTo&&e.appendTo.append(this.radioSection.container),!e.noExceptions){const t=En(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((s=>{s.row=new et(s),s.row.container.addEventListener("click",(()=>{n.then((()=>{const t=this.peerIds[s.key];new Bt(e.tab.slider).open({type:"privacy",skippable:!0,title:s.titleLangKey,placeholder:"PrivacyModal.Search.Placeholder",takeOut:e=>{t.length=0,t.push(...e),s.row.subtitle.innerHTML="",s.row.subtitle.append(...this.generateStr(this.splitPeersByType(e)))},selectedPeerIds:t})}))})),t.append(s.row.container)}))}const n=ri.getPrivacy(e.inputKey).then((t=>{const s=ri.getPrivacyRulesDetails(t);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",(()=>{const t=[];switch(this.type){case ii.Everybody:t.push({_:"inputPrivacyValueAllowAll"});break;case ii.Contacts:t.push({_:"inputPrivacyValueAllowContacts"});break;case ii.Nobody:t.push({_:"inputPrivacyValueDisallowAll"})}this.exceptions&&[["allow","inputPrivacyValueAllowChatParticipants","inputPrivacyValueAllowUsers"],["disallow","inputPrivacyValueDisallowChatParticipants","inputPrivacyValueDisallowUsers"]].forEach((([e,s,i],n)=>{if(this.exceptions.get(e).row.container.classList.contains("hide"))return;const a=this.peerIds[e];if(a){const e=this.splitPeersByType(a);e.chats.length&&t.push({_:s,chats:e.chats}),e.users.length&&t.push({_:i,users:e.users.map((e=>E.Z.getUserInput(e)))})}})),ri.setPrivacy(e.inputKey,t)}),{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,k.join)([e.users.length?(0,k.i18n)("Users",[e.users.length]):null,e.chats.length?(0,k.i18n)("Chats",[e.chats.length]):null].filter(Boolean),!1):[(0,k.i18n)("PrivacySettingsController.AddUsers")]}}class di extends H{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-phone-number"),this.setTitle("PrivacyPhone");const e="PrivacyPhoneInfo",t=new li({tab:this,title:"PrivacyPhoneTitle",inputKey:"inputPrivacyKeyPhoneNumber",captions:[e,e,""],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,onRadioChange:e=>{i.setRadio(ii.Everybody),i.radioSection.container.classList.toggle("hide",e!==ii.Nobody)}}),s="PrivacyPhoneInfo3",i=new li({tab:this,title:"PrivacyPhoneTitle2",inputKey:"inputPrivacyKeyAddedByPhone",captions:[s,s,""],noExceptions:!0,skipTypes:[ii.Nobody]});this.scrollable.container.insertBefore(i.radioSection.container,t.radioSection.container.nextSibling)}}var ci=s(634);class hi extends O{init(){this.container.classList.add("two-step-verification","two-step-verification-set"),this.setTitle("TwoStepVerificationPasswordSet");const e=new Mn({caption:"TwoStepVerificationPasswordSetInfo",noDelimiter:!0}),t=ds.Z.getAnimatedEmojiSticker("🥳"),s=document.createElement("div");t?Is({doc:t,div:s,loop:!0,play:!0,width:160,height:160}).then((()=>{})):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const a=(0,U.Z)("btn-primary btn-color-primary",{text:"TwoStepVerificationPasswordReturnSettings"});(0,l.fc)(a,(e=>{this.close()})),this.slider.sliceTabsUntilTab(un,this),n.append(a),i.append(n),this.scrollable.container.append(e.container)}}var pi=s(4489);function ui(e){return!ne.IS_MOBILE_SAFARI||!e}class gi extends O{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 Mn({caption:!0,noDelimiter:!0});(0,k._i18n)(e.caption,"TwoStepAuth.ConfirmEmailCodeDesc",[this.email]);const t=ds.Z.getAnimatedEmojiSticker("📬"),s=document.createElement("div");t?Is({doc:t,div:s,loop:!1,play:!0,width:160,height:160,emoji:"📬"}).then((()=>{})):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const a=this.codeInputField=new pi.Z({name:"recovery-email-code",label:"TwoStepAuth.RecoveryCode",length:this.length,onFill:e=>{c(!0),ci.Z.confirmPasswordEmail(""+e).then((e=>{d()})).catch((e=>{switch(e.type){case"CODE_INVALID":a.input.classList.add("error"),(0,T.Z)(a.label,(0,k.i18n)("TwoStepAuth.RecoveryCodeInvalid"));break;case"EMAIL_HASH_EXPIRED":a.input.classList.add("error"),(0,T.Z)(a.label,(0,k.i18n)("TwoStepAuth.RecoveryCodeExpired"));break;default:console.error("confirm error",e)}c(!1)}))}}),o=(0,U.Z)("btn-primary btn-primary-transparent primary",{text:"TwoStepAuth.EmailCodeChangeEmail"}),r=(0,U.Z)("btn-primary btn-secondary btn-primary-transparent primary",{text:"ResendCode"}),d=()=>{new hi(this.slider).open()},c=e=>{(0,mt.Z)([a.input,o,r],e)};(0,l.fc)(o,(e=>{c(!0),ci.Z.cancelPasswordEmail().then((e=>{this.slider.sliceTabsUntilTab(mi,this),this.close()}),(()=>{c(!1)}))})),(0,l.fc)(r,(e=>{c(!0);const t=(0,J.y7)(r);ci.Z.resendPasswordEmail().then((e=>{t.remove(),c(!1)}))})),n.append(a.container,o,r),i.append(n),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){ui(this.isFirst)&&this.codeInputField.input.focus()}}class mi extends O{constructor(){super(...arguments),this.isFirst=!1}init(){this.container.classList.add("two-step-verification","two-step-verification-email"),this.setTitle("RecoveryEmailTitle");const e=new Mn({caption:!0,noDelimiter:!0}),t=ds.Z.getAnimatedEmojiSticker("💌"),s=document.createElement("div");t?Is({doc:t,div:s,loop:!1,play:!0,width:160,height:160,emoji:"💌"}).then((()=>{})):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const a=this.inputField=new _.Z({name:"recovery-email",label:"RecoveryEmail",plainText:!0});a.input.addEventListener("keypress",(e=>{if("Enter"===e.key)return(0,d.d)(e),h()})),a.input.addEventListener("input",(e=>{a.input.classList.remove("error")}));const o=(0,U.Z)("btn-primary btn-color-primary",{text:"Continue"}),r=(0,U.Z)("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),c=()=>{new hi(this.slider).open()},h=()=>{const e=a.value.trim(),t=Q.Z.matchEmail(e);if(!t||t[0].length!==e.length)return void a.input.classList.add("error");p(!0);const s=(0,J.y7)(o);ci.Z.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:e}).then((e=>{c()}),(t=>{if(t.type.includes("EMAIL_UNCONFIRMED")){const s=+t.type.match(/^EMAIL_UNCONFIRMED_(\d+)/)[1],i=new gi(this.slider);i.state=this.state,i.email=e,i.length=s,i.open()}else console.log("password set error",t);p(!1),s.remove()}))};(0,l.fc)(o,h);const p=e=>{e?(o.setAttribute("disabled","true"),r.setAttribute("disabled","true")):(o.removeAttribute("disabled"),r.removeAttribute("disabled"))};(0,l.fc)(r,(e=>{new gt("popup-skip-email",{buttons:[{langKey:"Cancel",isCancel:!0},{langKey:"YourEmailSkip",callback:()=>{p(!0),(0,J.y7)(r),ci.Z.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:""}).then((()=>{c()}),(e=>{p(!1)}))},isDanger:!0}],titleLangKey:"YourEmailSkipWarning",descriptionLangKey:"YourEmailSkipWarningText"}).show()})),n.append(a.container,o,r),i.append(n),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){ui(this.isFirst)&&this.inputField.input.focus()}}var vi=s(4425),fi=s(6830),bi=s(3083);class yi extends O{init(){this.container.classList.add("two-step-verification","two-step-verification-hint"),this.setTitle("TwoStepAuth.SetupHintTitle");const e=new Mn({noDelimiter:!0}),t=ds.Z.getAnimatedEmojiSticker("💡"),s=document.createElement("div");t?Is({doc:t,div:s,loop:!1,play:!0,width:160,height:160,emoji:"💡"}).then((()=>{})):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=document.createElement("div");i.classList.add("input-wrapper");const n=this.inputField=new _.Z({name:"hint",label:"TwoStepAuth.SetupHintPlaceholder"});n.input.addEventListener("keypress",(e=>{if("Enter"===e.key)return(0,d.d)(e),n.value?c():h()}));const a=(e,t)=>{e&&(0,d.d)(e);const s=t?n.value:void 0;if(s&&this.newPassword===s)return void rt(k.default.format("PasswordAsHintError",!0));const i=new mi(this.slider);i.state=this.state,i.plainPassword=this.plainPassword,i.newPassword=this.newPassword,i.hint=s,i.open()},o=(0,U.Z)("btn-primary btn-color-primary",{text:"Continue"}),r=(0,U.Z)("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),c=e=>a(e,!0),h=e=>a(e,!1);(0,l.fc)(o,c),(0,l.fc)(r,h),i.append(n.container,o,r),e.content.append(i),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){this.inputField.input.focus()}}class wi extends O{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 Mn({noDelimiter:!0}),t=document.createElement("div");t.classList.add("input-wrapper");const s=this.passwordInputField=new fi.Z({name:"re-enter-password",label:"PleaseReEnterPassword"}),i=new bi.Z(s,157),n=(0,U.Z)("btn-primary btn-color-primary",{text:"Continue"});t.append(s.container,n),e.content.append(i.container,t),this.scrollable.container.append(e.container),s.input.addEventListener("keypress",(e=>{if(s.input.classList.contains("error")&&s.setState(_.I.Neutral),"Enter"===e.key)return o()}));const a=()=>this.newPassword===s.value||(s.setError(),!1),o=e=>{if(e&&(0,d.d)(e),!a())return;const t=new yi(this.slider);t.state=this.state,t.plainPassword=this.plainPassword,t.newPassword=this.newPassword,t.open()};return(0,l.fc)(n,o),i.load()}onOpenAfterTimeout(){this.passwordInputField.input.focus()}}class Si extends O{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 Mn({noDelimiter:!0}),s=document.createElement("div");s.classList.add("input-wrapper");const i=this.passwordInputField=new fi.Z({name:"enter-password",label:e?"PleaseEnterFirstPassword":this.state.hint?void 0:"LoginPassword",labelText:!e&&this.state.hint?Q.Z.wrapEmojiText(this.state.hint):void 0}),n=new vi.Z(i,157),a=(0,U.Z)("btn-primary btn-color-primary"),o=new k.default.IntlElement({key:"Continue"});a.append(o.element),s.append(i.container,a),t.content.append(n.container,s),this.scrollable.container.append(t.container),i.input.addEventListener("keypress",(e=>{if(i.input.classList.contains("error")&&(i.input.classList.remove("error"),o.key="Continue",o.update()),"Enter"===e.key)return c()}));const r=()=>!!i.value.length||(i.input.classList.add("error"),!1);let c;if(e)c=e=>{if(e&&(0,d.d)(e),!r())return;const t=new wi(this.slider);t.state=this.state,t.newPassword=i.value,t.plainPassword=this.plainPassword,t.open()};else{let e,t=()=>(e||(e=window.setInterval(t,1e4)),ci.Z.getState().then((e=>{this.state=e,this.state.hint?i.label.innerHTML=Q.Z.wrapEmojiText(this.state.hint):(0,T.Z)(i.label,(0,k.i18n)("LoginPassword"))})));c=s=>{if(!r())return void(0,d.d)(s);a.setAttribute("disabled","true"),o.key="PleaseWait",o.update();const l=(0,J.y7)(a),c=i.value;ci.Z.check(i.value,this.state).then((t=>{if(console.log(t),"auth.authorization"===t._){clearInterval(e),n&&n.remove();const t=new Ci(this.slider);t.state=this.state,t.plainPassword=c,t.open(),this.slider.removeTabFromHistory(this)}}),(e=>{a.removeAttribute("disabled"),i.input.classList.add("error"),e.type,o.key="TwoStepAuth.InvalidPassword",o.update(),l.remove(),i.select(),t()}))},t()}return(0,l.fc)(a,c),n.load()}onOpenAfterTimeout(){ui(this.isFirst)&&this.passwordInputField.input.focus()}}class Ci extends O{init(){this.container.classList.add("two-step-verification","two-step-verification-main"),this.setTitle("TwoStepVerificationTitle");const e=new Mn({caption:!0,noDelimiter:!0}),t=ds.Z.getAnimatedEmojiSticker("🔐"),s=document.createElement("div");t?Is({doc:t,div:s,loop:!1,play:!0,width:168,height:168,emoji:"🔐"}).then((()=>{})):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=e.generateContentElement();if(this.state.pFlags.has_password){(0,k._i18n)(e.caption,"TwoStepAuth.GenericHelp");const t=(0,U.Z)("btn-primary btn-transparent",{icon:"edit",text:"TwoStepAuth.ChangePassword"}),s=(0,U.Z)("btn-primary btn-transparent",{icon:"passwordoff",text:"TwoStepAuth.RemovePassword"}),n=(0,U.Z)("btn-primary btn-transparent",{icon:"email",text:this.state.pFlags.has_recovery?"TwoStepAuth.ChangeEmail":"TwoStepAuth.SetupEmail"});(0,l.fc)(t,(()=>{const e=new Si(this.slider);e.state=this.state,e.plainPassword=this.plainPassword,e.open()})),(0,l.fc)(s,(()=>{new gt("popup-disable-password",{buttons:[{langKey:"Disable",callback:()=>{ci.Z.updateSettings({currentPassword:this.plainPassword}).then((()=>{this.slider.sliceTabsUntilTab(un,this),this.close()}))},isDanger:!0}],titleLangKey:"TurnPasswordOffQuestionTitle",descriptionLangKey:"TurnPasswordOffQuestion"}).show()})),(0,l.fc)(n,(()=>{const e=new mi(this.slider);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,n)}else{(0,k._i18n)(e.caption,"TwoStepAuth.SetPasswordHelp");const t=document.createElement("div");t.classList.add("input-wrapper");const s=(0,U.Z)("btn-primary btn-color-primary",{text:"TwoStepVerificationSetPassword"});t.append(s),i.append(t),(0,l.fc)(s,(e=>{const t=new Si(this.slider);t.state=this.state,t.open()}))}this.scrollable.container.append(e.container)}}class Li extends H{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-last-seen"),this.setTitle("PrivacyLastSeen");const e="PrivacySettingsController.LastSeenDescription";new li({tab:this,title:"LastSeenTitle",inputKey:"inputPrivacyKeyStatusTimestamp",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable})}}class Ii extends H{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 li({tab:this,title:"PrivacyProfilePhotoTitle",inputKey:"inputPrivacyKeyProfilePhoto",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,skipTypes:[ii.Nobody]})}}class Mi extends H{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 li({tab:this,title:"PrivacyForwardsTitle",inputKey:"inputPrivacyKeyForwards",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable})}}class Ei extends H{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 li({tab:this,title:"WhoCanAddMe",inputKey:"inputPrivacyKeyChatInvite",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,skipTypes:[ii.Nobody]})}}class Pi extends H{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-calls"),this.setTitle("PrivacySettings.VoiceCalls");const e="PrivacySettingsController.PhoneCallDescription";new li({tab:this,title:"WhoCanCallMe",inputKey:"inputPrivacyKeyPhoneCall",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable});{const e="PrivacySettingsController.P2p.Desc";new li({tab:this,title:"PrivacyP2PHeader",inputKey:"inputPrivacyKeyPhoneP2P",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable})}}}class Ti extends H{init(){this.header.classList.add("with-border"),this.container.classList.add("active-sessions-container"),this.setTitle("SessionsTitle");const e=e=>{const t=new et({title:[e.app_name,e.app_version].join(" "),subtitle:[e.ip,e.country].join(" - "),clickable:!0,titleRight:e.pFlags.current?void 0:(0,ie.zM)(new Date(1e3*Math.max(e.date_active,e.date_created)))});t.container.dataset.hash=""+e.hash;const s=document.createElement("div");return s.classList.add("row-midtitle"),s.innerHTML=[e.device_model,e.system_version||e.platform].filter(Boolean).join(", "),t.subtitle.parentElement.insertBefore(s,t.subtitle),t},t=this.authorizations.slice();{const n=new Mn({name:"CurrentSession",caption:"ClearOtherSessionsHelp"}),a=t.findAndSplice((e=>e.pFlags.current)),o=e(a);if(n.content.append(o.container),t.length){const e=(0,U.Z)("btn-primary btn-transparent danger",{icon:"stop",text:"TerminateAllSessions"});(0,l.fc)(e,(t=>{new gt("revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{const t=(0,mt.Z)([e],!0);ct.Z.invokeApi("auth.resetAuthorizations").then((t=>{e.remove(),s.container.remove()}),i).finally((()=>{t()}))}}],titleLangKey:"AreYouSureSessionsTitle",descriptionLangKey:"AreYouSureSessions"}).show()})),n.content.append(e)}this.scrollable.append(n.container)}if(!t.length)return;const s=new Mn({name:"OtherSessions",caption:"SessionsListInfo"});t.forEach((t=>{s.content.append(e(t).container)})),this.scrollable.append(s.container);const i=e=>{"FRESH_RESET_AUTHORISATION_FORBIDDEN"===e.type&&rt(k.default.format("RecentSessions.Error.FreshReset",!0))};let n;const a=()=>{const e=n.dataset.hash;new gt("revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{ct.Z.invokeApi("account.resetAuthorization",{hash:e}).then((e=>{e&&n.remove()}),i)}}],titleLangKey:"AreYouSureSessionTitle",descriptionLangKey:"TerminateSessionText"}).show()},o=this.menuElement=Ce([{icon:"stop",text:"Terminate",onClick:a}]);o.id="active-sessions-contextmenu",o.classList.add("contextmenu"),document.getElementById("page-chats").append(o),(0,J.Eo)(this.scrollable.container,(e=>{n=(0,Me.Z)(e.target,"row"),n&&"0"!==n.dataset.hash&&(e instanceof MouseEvent&&e.preventDefault(),e instanceof MouseEvent&&(e.cancelBubble=!0),(0,J.oy)(e,o),(0,J.YP)(o))})),(0,l.fc)(this.scrollable.container,(e=>{n=(0,Me.Z)(e.target,"row"),n&&"0"!==n.dataset.hash&&a()}))}onCloseAfterTimeout(){return this.menuElement&&this.menuElement.remove(),super.onCloseAfterTimeout()}}class ki extends O{init(){this.header.classList.add("with-border"),this.container.classList.add("blocked-users-container"),this.setTitle("BlockedUsers");{const e=new Mn({caption:"BlockedUsersInfo"});this.scrollable.append(e.container)}const e=W({icon:"add",className:"is-visible"});this.content.append(e),(0,l.fc)(e,(e=>{new Et({peerTypes:["contacts"],placeholder:"BlockModal.Search.Placeholder",onSelect:e=>{E.Z.toggleBlock(e,!0)}})}),{listenerSetter:this.listenerSetter});const t=pd.createChatList();this.scrollable.container.classList.add("chatlist-container"),this.scrollable.append(t);const s=(e,s)=>{const{dom:i}=pd.addDialogNew({dialog:e,container:t,drawStatus:!1,rippleEnabled:!0,avatarSize:48,append:s}),n=E.Z.getUser(e);n.pFlags.bot?i.lastMessageSpan.append("@"+n.username):n.phone?i.lastMessageSpan.innerHTML=E.Z.formatUserPhone(n.phone):i.lastMessageSpan.append(n.username?"@"+n.username:E.Z.getUserStatusString(e))};for(const e of this.peerIds)s(e,!0);let i;const n=this.menuElement=Ce([{icon:"lockoff",text:"Unblock",onClick:()=>{const e=i.dataset.peerId.toPeerId();E.Z.toggleBlock(e,!1)},options:{listenerSetter:this.listenerSetter}}]);n.id="blocked-users-contextmenu",n.classList.add("contextmenu"),document.getElementById("page-chats").append(n),(0,J.Eo)(this.scrollable.container,(e=>{i=(0,ft.Z)(e.target,"LI"),i&&(e instanceof MouseEvent&&e.preventDefault(),e instanceof MouseEvent&&(e.cancelBubble=!0),(0,J.oy)(e,n),(0,J.YP)(n))}),this.listenerSetter),this.listenerSetter.add(a.default)("peer_block",(e=>{const{peerId:i,blocked:n}=e,a=t.querySelector(`[data-peer-id="${i}"]`);n?a||s(i,!1):a&&a.remove()}));let o=!1;this.scrollable.onScrolledBottom=()=>{o||(o=!0,E.Z.getBlocked(t.childElementCount,50).then((e=>{for(const t of e.peerIds)s(t,!0);(e.peerIds.length<50||t.childElementCount===e.count)&&(this.scrollable.onScrolledBottom=null),this.scrollable.checkForTriggers()})).finally((()=>{o=!1})))}}onOpenAfterTimeout(){this.scrollable.onScroll()}onCloseAfterTimeout(){return this.menuElement&&this.menuElement.remove(),super.onCloseAfterTimeout()}}var xi=s(5667);function Ai(e){return"input"+(e[0].toUpperCase()+e.slice(1))}class _i extends H{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 Mn({noDelimiter:!0,caption:"SessionsInfo"});let s;const i=new et({icon:"deleteuser",titleLangKey:"BlockedUsers",subtitleLangKey:e,clickable:()=>{const e=new ki(this.slider);e.peerIds=s,e.open()}});let n;i.freezed=!0;const o=new et({icon:"lock",titleLangKey:"TwoStepVerification",subtitleLangKey:e,clickable:e=>{let t;n.pFlags.has_password?t=new Si(this.slider):n.email_unconfirmed_pattern?(t=new gi(this.slider),t.email=n.email_unconfirmed_pattern,t.length=6,t.isFirst=!0,ci.Z.resendPasswordEmail()):t=new Ci(this.slider),t.state=n,t.open()}});o.freezed=!0;const r=this.activeSessionsRow=new et({icon:"activesessions",titleLangKey:"SessionsTitle",subtitleLangKey:e,clickable:()=>{const e=new Ti(this.slider);e.authorizations=this.authorizations,e.eventListener.addEventListener("destroy",(()=>{this.updateActiveSessions()}),{once:!0}),e.open()}});r.freezed=!0,t.content.append(i.container,o.container,r.container),this.scrollable.append(t.container);const l=e=>{e?(0,T.Z)(i.subtitle,(0,k.i18n)("PrivacySettingsController.UserCount",[e])):(0,T.Z)(i.subtitle,(0,k.i18n)("BlockedEmpty",[e]))};this.listenerSetter.add(a.default)("peer_block",(()=>{d()}));const d=()=>{E.Z.getBlocked().then((e=>{i.freezed=!1,l(e.count),s=e.peerIds}))};d(),ci.Z.getState().then((e=>{n=e,(0,T.Z)(o.subtitle,(0,k.i18n)(e.pFlags.has_password?"PrivacyAndSecurity.Item.On":"PrivacyAndSecurity.Item.Off")),o.freezed=!1})),this.updateActiveSessions()}{const t=new Mn({name:"PrivacyTitle",caption:"GroupsAndChannelsHelp"});t.content.classList.add("privacy-navigation-container");const s={},i=s.inputPrivacyKeyPhoneNumber=new et({titleLangKey:"PrivacyPhoneTitle",subtitleLangKey:e,clickable:()=>{new di(this.slider).open()}}),n=s.inputPrivacyKeyStatusTimestamp=new et({titleLangKey:"LastSeenTitle",subtitleLangKey:e,clickable:()=>{new Li(this.slider).open()}}),o=s.inputPrivacyKeyProfilePhoto=new et({titleLangKey:"PrivacyProfilePhotoTitle",subtitleLangKey:e,clickable:()=>{new Ii(this.slider).open()}}),r=s.inputPrivacyKeyPhoneCall=new et({titleLangKey:"WhoCanCallMe",subtitleLangKey:e,clickable:()=>{new Pi(this.slider).open()}}),l=s.inputPrivacyKeyForwards=new et({titleLangKey:"PrivacyForwardsTitle",subtitleLangKey:e,clickable:()=>{new Mi(this.slider).open()}}),d=s.inputPrivacyKeyChatInvite=new et({titleLangKey:"WhoCanAddMe",subtitleLangKey:e,clickable:()=>{new Ei(this.slider).open()}}),c=e=>{const t=s[e];t&&ri.getPrivacy(e).then((e=>{const s=ri.getPrivacyRulesDetails(e),i=s.type===ii.Everybody?"PrivacySettingsController.Everbody":s.type===ii.Contacts?"PrivacySettingsController.MyContacts":"PrivacySettingsController.Nobody",n=s.disallowPeers.users.length+s.disallowPeers.chats.length,a=s.allowPeers.users.length+s.allowPeers.chats.length;t.subtitle.innerHTML="";const o=(0,k.i18n)(i);t.subtitle.append(o),(n||a)&&t.subtitle.append(` (${[-n,a?"+"+a:0].filter(Boolean).join(", ")})`)}))};t.content.append(i.container,n.container,o.container,r.container,l.container,d.container),this.scrollable.append(t.container);for(const e in s)c(e);a.default.addEventListener("privacy_update",(e=>{c(Ai(e.key._))}))}const t=[];{const e=new Mn({name:"Privacy.SensitiveContent"});e.container.classList.add("hide"),t.push(ct.Z.invokeApi("account.getContentSettings").then((t=>{if(!t.pFlags.sensitive_can_change)return;const s=t.pFlags.sensitive_enabled,i=new et({checkboxField:new ut.Z({text:"PrivacyAndSecurity.SensitiveText",checked:s}),subtitleLangKey:"PrivacyAndSecurity.SensitiveDesc",noCheckboxSubtitle:!0});e.content.append(i.container),e.container.classList.remove("hide"),this.eventListener.addEventListener("destroy",(()=>{const e=i.checkboxField.checked;e!==s&&ct.Z.invokeApi("account.setContentSettings",{sensitive_enabled:e})}),{once:!0})}))),this.scrollable.append(e.container)}{const e=new Mn({name:"FilterChats"}),t=()=>{new gt("popup-delete-drafts",{buttons:[{langKey:"Delete",callback:()=>{const e=(0,mt.Z)([s],!0);xi.Z.clearAllDrafts().then((()=>{e()}))},isDanger:!0}],titleLangKey:"AreYouSureClearDraftsTitle",descriptionLangKey:"AreYouSureClearDrafts"}).show()},s=(0,U.Z)("btn-primary btn-transparent",{icon:"delete",text:"PrivacyDeleteCloudDrafts"});this.listenerSetter.add(s)("click",t),e.content.append(s),this.scrollable.append(e.container)}return Promise.all(t)}updateActiveSessions(){ct.Z.invokeApi("account.getAuthorizations").then((e=>{this.activeSessionsRow.freezed=!1,this.authorizations=e.authorizations,(0,k._i18n)(this.activeSessionsRow.subtitle,"Privacy.Devices",[this.authorizations.length])}))}}function Zi(e){const t=e.getContext("2d"),s=new Array(4).fill(0),i=t.getImageData(0,0,e.width,e.height).data;for(let e=0;e<i.length;e+=4)s[0]+=i[e],s[1]+=i[e+1],s[2]+=i[e+2],s[3]+=i[e+3];const n=i.length/4,a=new Uint8ClampedArray(4);return a[0]=s[0]/n,a[1]=s[1]/n,a[2]=s[2]/n,a[3]=s[3]/n,a}function Di(e,t,s,i=1){e/=255,t/=255,s/=255;const n=Math.max(e,t,s),a=Math.min(e,t,s);let o,r,l=(n+a)/2;if(n===a)o=r=0;else{let i=n-a;switch(r=l>.5?i/(2-n-a):i/(n+a),n){case e:o=(t-s)/i+(t<s?6:0);break;case t:o=(s-e)/i+2;break;case s:o=(e-t)/i+4}o/=6}return{h:360*o,s:100*r,l:100*l,a:i}}function Fi(e,t,s,i){let n,a,o;if(e/=360,s/=100,0==(t/=100))n=a=o=s;else{const i=function(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+(t-e)*(2/3-s)*6:e},r=s<.5?s*(1+t):s+t-s*t,l=2*s-r;n=i(l,r,e+1/3),a=i(l,r,e),o=i(l,r,e-1/3)}return[Math.round(255*n),Math.round(255*a),Math.round(255*o),Math.round(255*i)]}function Ri(e){const t=[],s="#"===e[0]?1:0;if(e.length===5+s&&(e=(s?"#":"")+"0"+e.slice(s)),e.length===3+s)for(let i=s;i<e.length;++i)t.push(parseInt(e[i]+e[i],16));else if(e.length===4+s){for(let i=s;i<e.length-1;++i)t.push(parseInt(e[i]+e[i],16));t.push(parseInt(e[e.length-1],16))}else for(let i=s;i<e.length;i+=2)t.push(parseInt(e.slice(i,i+2),16));return t}function Bi(e){return Ri(e.slice(0,7))}function Ui(e){return"#"+e.map((e=>("0"+e.toString(16)).slice(-2))).join("")}function Ni(e){let{h:t,s,l:i}=Di(e[0],e[1],e[2]);return s>0&&(s=Math.min(100,s+5+.1*(100-s))),i=Math.max(0,.65*i),`hsla(${t}, ${s}%, ${i}%, .4)`}class Oi{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 s=e.length;return s||(this._animatingToNextPosition=void 0),!!s};const e=this._tails/this._curve[this._curve.length-1];for(let t=0,s=this._curve.length;t<s;++t)this._curve[t]=this._curve[t]*e;this._incrementalCurve=this._curve.map(((e,t,s)=>{var i;return e-(null!==(i=s[t-1])&&void 0!==i?i:0)}))}hexToRgb(e){const t=Bi(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 s=[];for(let e=0;e<t.length;e+=2)s.push(t[e]);return s}getNextPositions(e,t,s){const i=this.getPositions(e);if(!s[0]&&1===s.length)return[i];const n=this.getPositions(++e%this._phases).map(((e,s)=>({x:(e.x-i[s].x)/t,y:(e.y-i[s].y)/t})));return s.map((e=>n.map(((t,s)=>({x:i[s].x+t.x*e,y:i[s].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),s=t.data;let i=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,d=Math.sin(l),c=Math.cos(l),h=Math.max(0,Math.min(1,.5+o*c-n*d)),p=Math.max(0,Math.min(1,.5+o*d+n*c));let u=0,g=0,m=0,v=0;for(let t=0;t<this._colors.length;t++){const s=h-e[t].x,i=p-e[t].y;let n=Math.max(0,.9-Math.sqrt(s*s+i*i));n*=n*n*n,u+=n,g+=n*this._colors[t].r/255,m+=n*this._colors[t].g/255,v+=n*this._colors[t].b/255}s[i++]=g/u*255,s[i++]=m/u*255,s[i++]=v/u*255,s[i++]=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")),this._canvas=e,this._ctx=this._canvas.getContext("2d"),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,s=this._tails;let i;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)>s&&void 0===i&&(i=a,r%=s),n.push(r)}[n.slice(0,i),void 0!==i?n.slice(i):[]].forEach(((e,t,i)=>{const n=e[e.length-1];if(void 0!==n&&n>s&&(e[e.length-1]=+n.toFixed(2)),this._tail=null!=n?n:0,!e.length)return;const a=this.getNextPositions(this._phase,s,e);t!==i.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,Ue.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),s=new Oi;return s.init(t),{gradientRenderer:s,canvas:t}}}class Hi{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(Hi.BASE_CLASS);const e=`\n <svg class="${Hi.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="${Hi.BASE_CLASS+"-dragger"} ${Hi.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="${Hi.BASE_CLASS+"-sliders"}">\n <svg class="${Hi.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="${Hi.BASE_CLASS+"-dragger"} ${Hi.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 _.Z({plainText:!0,label:"Appearance.Color.Hex"}),this.rgbInputField=new _.Z({plainText:!0,label:"Appearance.Color.RGB"});const t=document.createElement("div");t.className=Hi.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]+)/),s=t&&t[0].length===e.length&&[6].includes(e.length);this.hexInputField.setState(s?_.I.Neutral:_.I.Error),e="#"+e,this.hexInputField.setValueSilently(e),s&&this.setColor(e,!1,!0)}));const s=/^(?:rgb)?\(?([01]?\d\d?|2[0-4]\d|25[0-5])(?:\W+)([01]?\d\d?|2[0-4]\d|25[0-5])\W+(?:([01]?\d\d?|2[0-4]\d|25[0-5])\)?)$/;this.rgbInputField.input.addEventListener("input",(()=>{const e=this.rgbInputField.value.match(s);this.rgbInputField.setState(e?_.I.Neutral:_.I.Error),e&&this.setColor(Di(+e[1],+e[2],+e[3]),!0,!1)})),this.attachBoxListeners(),this.attachHueListeners()}attachBoxListeners(){be(this.elements.box,(()=>{this.onGrabStart(),this.boxRect=this.elements.box.getBoundingClientRect()}),(e=>{this.saturationHandler(e.x,e.y)}),(()=>{this.onGrabEnd()}))}attachHueListeners(){be(this.elements.hue,(()=>{this.onGrabStart(),this.hueRect=this.elements.hue.getBoundingClientRect()}),(e=>{this.hueHandler(e.x)}),(()=>{this.onGrabEnd()}))}setColor(e,t=!0,s=!0){if(void 0===e)e={h:0,s:100,l:50,a:1};else if("string"==typeof e)if("#"===e[0])e=function(e){const t=Ri(e);return Di(t[0],t[1],t[2],t[3])}(e);else{const t=e.match(/[.?\d]+/g);e=Di(+t[0],+t[1],+t[2],void 0===t[3]?1:+t[3])}this.boxRect=this.elements.box.getBoundingClientRect();const i=this.boxRect.width/100*e.s,n=100-e.l/(100-e.s/2)*100,a=this.boxRect.height/100*n;this.saturationHandler(this.boxRect.left+i,this.boxRect.top+a,!1),this.hueRect=this.elements.hue.getBoundingClientRect();const 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,s)}getCurrentColor(){const e=Fi(this.hue,this.saturation,this.lightness,this.alpha),t=Ui(e),s=t.slice(0,-2);return{hsl:`hsl(${this.hue}, ${this.saturation}%, ${this.lightness}%)`,rgb:`rgb(${e[0]}, ${e[1]}, ${e[2]})`,hex:s,hsla:`hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, ${this.alpha})`,rgba:`rgba(${e[0]}, ${e[1]}, ${e[2]}, ${e[3]})`,hexa:t,rgbaArray:e}}updatePicker(e=!0,t=!0){const s=this.getCurrentColor();this.elements.boxDragger.setAttributeNS(null,"fill",s.hex),e&&(this.hexInputField.setValueSilently(s.hex),this.hexInputField.setState(_.I.Neutral)),t&&(this.rgbInputField.setValueSilently(s.rgbaArray.slice(0,-1).join(", ")),this.rgbInputField.setState(_.I.Neutral)),this.onChange&&this.onChange(s)}hueHandler(e,t=!0){const s=(0,ye.Z)(e-this.hueRect.left,0,this.hueRect.width)/this.hueRect.width;this.hue=Math.round(360*s);const i=`hsla(${this.hue}, 100%, 50%, ${this.alpha})`;this.elements.hueDragger.setAttributeNS(null,"x",100*s+"%"),this.elements.hueDragger.setAttributeNS(null,"fill",i),this.elements.saturation.lastElementChild.setAttributeNS(null,"stop-color",i),t&&this.updatePicker()}saturationHandler(e,t,s=!0){const i=this.boxRect.width,n=this.boxRect.height,a=(0,ye.Z)(e-this.boxRect.left,0,i)/i*100,o=(0,ye.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,ye.Z)(a,0,100),d=100-l/2,c=100-(0,ye.Z)(o,0,100),h=(0,ye.Z)(c/100*d,0,100);this.saturation=l,this.lightness=h,s&&this.updatePicker()}}Hi.BASE_CLASS="color-picker";class zi extends O{constructor(){super(...arguments),this._applyColor=(e,t=!0)=>{if(t)this.colorPicker.setColor(e);else{const t=Ri(e),s=this.theme.background,i=Ni(t);s.id="2",s.intensity=0,s.slug="",s.color=e.toLowerCase(),s.highlightningColor=i,M.default.pushToState("settings",a.default.settings),Ol.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=a.default.getTheme();const e=new Mn({});this.colorPicker=new Hi,e.content.append(this.colorPicker.container),this.scrollable.append(e.container);const t=new Mn({}),s=this.grid=document.createElement("div");s.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 i=document.createElement("div");i.classList.add("grid-item-media"),i.style.backgroundColor=e,t.append(i),s.append(t)})),(0,l.fc)(s,(e=>{const t=(0,Me.Z)(e.target,"grid-item");if(!t||t.classList.contains("active"))return;const s=t.dataset.color;s&&this.applyColor(s)}),{listenerSetter:this.listenerSetter}),t.content.append(s),this.scrollable.append(t.container),this.applyColor=(0,ms.Z)(this._applyColor,16,!0)}setActive(){const e=this.grid.querySelector(".active"),t=this.theme.background,s=t.color?this.grid.querySelector(`.grid-item[data-color="${t.color}"]`):null;e!==s&&(e&&e.classList.remove("active"),s&&s.classList.add("active"))}onOpen(){setTimeout((()=>{const e=this.theme.background,t=(e.color||"").split(",")[0],s=!!t&&!e.slug;s&&(this.colorPicker.onChange=this.onColorChange),this.colorPicker.setColor(t||"#cccccc"),s||(this.colorPicker.onChange=this.onColorChange)}),0)}onCloseAfterTimeout(){return this.colorPicker.onChange=void 0,this.colorPicker=void 0,super.onCloseAfterTimeout()}}let Vi=0;class ji extends O{constructor(){super(...arguments),this.tempId=0,this.clicked=new Set,this.wallpapersByElement=new Map,this.elementsByKey=new Map,this.onUploadClick=()=>{(0,he.hf)("image/x-png,image/png,image/jpeg").then((e=>{const t="wallpaper-upload-"+ ++Vi,s={_:"photoSize",h:0,w:0,location:{},size:e.size,type:"full"};let i={_:"document",access_hash:"",attributes:[],dc_id:0,file_reference:[],id:t,mime_type:e.type,size:e.size,date:Date.now()/1e3,pFlags:{},thumbs:[s],file_name:e.name};i=L.Z.saveDoc(i);const n=le.Z.getCacheContext(i);n.downloaded=e.size,n.url=URL.createObjectURL(e);let a={_:"wallPaper",access_hash:"",document:i,id:t,slug:t,pFlags:{}};const o=le.Z.upload(e,e.name),r=(0,se.b)();r.addNotifyListener=o.addNotifyListener,r.cancel=o.cancel,o.then((t=>{ct.Z.invokeApi("account.uploadWallPaper",{file:t,mime_type:e.type,settings:{_:"wallPaperSettings"}}).then((e=>{const t=e.document,s=le.Z.getCacheContext(t);Object.assign(s,n),a=e,a.document=L.Z.saveDoc(a.document),this.setBackgroundDocument(a).then(r.resolve,r.reject)}),r.reject)}),r.reject);const l=this.getWallpaperKey(a);r.then((()=>{this.clicked.delete(l)}),(e=>{c.remove()}));const d=new fe.Z({isUpload:!0,cancelable:!0,tryAgainOnFail:!1}),c=this.addWallPaper(a,!1);this.clicked.add(l),d.attach(c,!1,r)}))},this.onResetClick=()=>{const e=M.STATE_INIT.settings.themes.find((e=>e.name===this.theme.name));e&&(++this.tempId,this.theme.background=(0,pe.Z)(e.background),M.default.pushToState("settings",a.default.settings),Ol.applyCurrentTheme(void 0,void 0,!0),this.blurCheckboxField.setValueSilently(this.theme.background.blur))},this.onGridClick=e=>{const t=(0,Me.Z)(e.target,"grid-item");if(!t)return;const s=this.wallpapersByElement.get(t);if("wallPaperNoFile"===s._)return void this.setBackgroundDocument(s);const i=this.getWallpaperKey(s);if(this.clicked.has(i))return;this.clicked.add(i);const n=s.document,a=new fe.Z({cancelable:!0,tryAgainOnFail:!1}),o=()=>{const e=this.setBackgroundDocument(s);le.Z.getCacheContext(n).url&&!this.theme.background.blur||a.attach(t,!0,e)};a.construct(),(0,l.fc)(t,(e=>{a.preloader.parentElement?(a.onClick(e),a.detach()):o()}),{listenerSetter:this.listenerSetter}),o()},this.saveToCache=(e,t)=>{fetch(t).then((t=>{le.Z.cacheStorage.save("backgrounds/"+e,t)}))},this.setBackgroundDocument=e=>{let t=++this.tempId;const s=()=>t===this.tempId,i=e.document,n=(0,se.b)();let o;return i?(o=L.Z.downloadDoc(i,Ol.chat.bubbles?Ol.chat.bubbles.lazyLoadQueue.queueId:0),n.addNotifyListener=o.addNotifyListener,n.cancel=o.cancel):o=Promise.resolve(),o.then((()=>{if(!s())return void n.resolve();const t=this.theme.background,o=i=>{let o;if(i&&!this.theme.background.color)o=function(e){const t=document.createElement("img");return new Promise((s=>{(0,rs.ZP)(t,e,(()=>{const e=document.createElement("canvas"),i=t.naturalWidth/t.naturalHeight;1===i?(e.width=50,e.height=e.width/i):i>1?(e.height=50,e.width=e.height/i):e.width=e.height=50,e.getContext("2d").drawImage(t,0,0,t.naturalWidth,t.naturalHeight,0,0,e.width,e.height),s(Zi(e))}))}))}(i);else{const{canvas:t}=Oi.create(this.getColorsFromWallpaper(e));o=Promise.resolve(Zi(t))}o.then((o=>{var r,l,d;if(!s())return void n.resolve();const c=Ni(Array.from(o)),h=null!==(r=e.slug)&&void 0!==r?r:"";t.id=e.id,t.intensity=null!==(d=null===(l=e.settings)||void 0===l?void 0:l.intensity)&&void 0!==d?d:0,t.color=this.getColorsFromWallpaper(e),t.slug=h,t.highlightningColor=c,M.default.pushToState("settings",a.default.settings),h&&this.saveToCache(h,i),Ol.applyCurrentTheme(h,i,!0).then(n.resolve)}))};if(!i)return void o();const r=le.Z.getCacheContext(i);t.blur?setTimeout((()=>{(0,ps.Z)(r.url,12,4).then((e=>{s()?o(e):n.resolve()}))}),200):o(r.url)})),n},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"))}}init(){this.header.classList.add("with-border"),this.container.classList.add("background-container","background-image-container"),this.setTitle("ChatBackground"),this.theme=a.default.getTheme();{const e=En(this.scrollable),s=(0,U.Z)("btn-primary btn-transparent",{icon:"cameraadd",text:"ChatBackground.UploadWallpaper"}),i=(0,U.Z)("btn-primary btn-transparent",{icon:"colorize",text:"SetColor"}),n=(0,U.Z)("btn-primary btn-transparent",{icon:"favourites",text:"Appearance.Reset"});(0,l.fc)(s,this.onUploadClick,{listenerSetter:this.listenerSetter}),(0,l.fc)(i,(()=>{new zi(this.slider).open()}),{listenerSetter:this.listenerSetter}),(0,l.fc)(n,this.onResetClick,{listenerSetter:this.listenerSetter});const o=this.blurCheckboxField=new ut.Z({text:"ChatBackground.Blur",name:"blur",checked:this.theme.background.blur,withRipple:!0});this.listenerSetter.add(o.input)("change",(()=>{this.theme.background.blur=o.input.checked,M.default.pushToState("settings",a.default.settings),setTimeout((()=>{const e=t.querySelector(".active");if(!e)return;const s=this.wallpapersByElement.get(e);s.pFlags.pattern||"wallPaperNoFile"===s._||this.setBackgroundDocument(s)}),100)})),e.append(s,i,n,o.label)}a.default.addEventListener("background_change",this.setActive),ct.Z.invokeApiHashable({method:"account.getWallPapers"}).then((e=>{e.wallpapers.forEach((e=>{this.addWallPaper(e)}))}));const e=En(this.scrollable),t=this.grid=document.createElement("div");t.classList.add("grid"),(0,l.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){var s;const i=this.getColorsFromWallpaper(e),n="wallPaper"===e._;if(n&&e.pFlags.pattern&&!i)return;const a=!!e.pFlags.dark,o=n?e.document=L.Z.saveDoc(e.document):void 0,l=document.createElement("div");l.classList.add("grid-item"),l.dataset.id=""+e.id;const d=this.getWallpaperKey(e);this.wallpapersByElement.set(l,e),this.elementsByKey.set(d,l);const c=document.createElement("div");let h,p;if(c.classList.add("grid-item-media"),n?(p=r.Z.choosePhotoSize(o,200,200),h=Ss({photo:o,message:null,container:c,withoutPreloader:!0,size:p,noFadeIn:e.pFlags.pattern}),(h.loadPromises.thumb||h.loadPromises.full).then((()=>{ls.Z.mutate((()=>{l.append(c)}))})),e.pFlags.pattern&&(c.classList.add("is-pattern"),a?(h.images.full.style.display="none",h.images.thumb&&(h.images.thumb.style.display="none")):(null===(s=e.settings)||void 0===s?void 0:s.intensity)&&(h.images.full.style.opacity=""+Math.abs(e.settings.intensity)/100))):l.append(c),e.settings&&void 0!==e.settings.background_color){const{canvas:t}=Oi.create(i);if(t.classList.add("background-colors-canvas"),a&&n){const s=le.Z.getCacheContext(o,p.type);h.loadPromises.full.then((()=>{t.style.webkitMaskImage=`url(${s.url})`,t.style.opacity=""+Math.abs(e.settings.intensity)/100,c.append(t)}))}else c.append(t)}return this.getWallpaperKeyFromTheme(this.theme)===d&&l.classList.add("active"),this.grid[t?"append":"prepend"](l),l}}const Gi="STICKERS-POPUP";class Ki extends pt.Z{constructor(e){super("popup-stickers",null,{closable:!0,overlayClosable:!0,body:!0}),this.stickerSetInput=e,this.onStickersClick=e=>{const t=(0,Me.Z)(e.target,"sticker-set-sticker");if(!t)return;const s=t.dataset.docId;Ol.chat.input.sendMessageWithDocument(s)?this.hide():console.warn("got no doc by id:",s)},this.h6=document.createElement("h6"),this.h6.append((0,k.i18n)("Loading")),this.header.append(this.h6),this.addEventListener("close",(()=>{I.Z.setOnlyOnePlayableGroup("")}));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,l.fc)(this.stickersDiv,this.onStickersClick,{listenerSetter:this.listenerSetter}),(0,J.y7)(this.stickersDiv,!0),this.stickersFooter=document.createElement("div"),this.stickersFooter.classList.add("sticker-set-footer"),t.append(this.stickersDiv);const s=(0,U.Z)("btn-primary btn-primary-transparent disable-hover",{noRipple:!0,text:"Loading"});this.stickersFooter.append(s),this.body.append(t),new P.ZP(this.body),this.body.append(this.stickersFooter),this.loadStickerSet()}loadStickerSet(){return ds.Z.getStickerSet(this.stickerSetInput).then((e=>{if(!e)return lt({langPackKey:"StickerSet.DontExist"}),void this.hide();let t;this.set=e.set,I.Z.setOnlyOnePlayableGroup(Gi),this.h6.innerHTML=Q.o.wrapEmojiText(e.set.title),this.stickersFooter.classList.toggle("add",!e.set.installed_date),e.set.installed_date?(t=(0,U.Z)("btn-primary btn-primary-transparent danger",{noRipple:!0}),t.append((0,k.i18n)("RemoveStickersCount",[(0,k.i18n)("Stickers",[e.set.count])]))):(t=(0,U.Z)("btn-primary btn-color-primary",{noRipple:!0}),t.append((0,k.i18n)("AddStickersCount",[(0,k.i18n)("Stickers",[e.set.count])]))),this.stickersFooter.textContent="",this.stickersFooter.append(t),(0,l.fc)(t,(()=>{const e=(0,mt.Z)([t],!0);ds.Z.toggleStickerSet(this.set).then((()=>{this.hide()})).catch((()=>{e()}))}));const s=new X.ZP;this.stickersDiv.classList.remove("is-loading"),this.stickersDiv.innerHTML="";for(let t of e.documents){if("documentEmpty"===t._)continue;const e=document.createElement("div");e.classList.add("sticker-set-sticker");const i=v.ZP.active.esgSticker.width;Is({doc:t,div:e,lazyLoadQueue:s,group:Gi,play:!0,loop:!0,width:i,height:i}),this.stickersDiv.append(e)}}))}}var Wi,qi=s(6761);const $i=!!(null===(Wi=null===navigator||void 0===navigator?void 0:navigator.geolocation)||void 0===Wi?void 0:Wi.getCurrentPosition)&&!1;class Qi extends O{init(){return this.header.classList.add("with-border"),this.setTitle("DoubleTapSetting"),this.container.classList.add("quick-reaction-container"),Promise.all([_t.Z.getQuickReaction(),_t.Z.getAvailableReactions()]).then((([e,t])=>{t=t.filter((e=>!e.pFlags.inactive));const s=new Mn,i=t.map((t=>{const s=new at({name:"quick-reaction",text:t.title,value:t.reaction,alignRight:!0}),i=new et({radioField:s,havePadding:!0});return s.main.classList.add("quick-reaction-title"),Es({row:i,doc:t.static_icon,size:"small"}),t===e&&s.setValueSilently(!0),i})),n=tt(i,(e=>{_t.Z.setDefaultReaction(e)}));s.content.append(n),this.scrollable.append(s.container)}))}}class Yi{constructor(e,t,s,i,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,k._i18n)(l,e);const d=this.valueContainer=document.createElement("div");d.classList.add(o+"-value"),a&&(d.innerHTML=""+s),r.append(l,d),this.range=new we({step:t,min:i,max:n},s),this.range.setListeners(),this.range.setHandlers({onScrub:e=>{this.onChange&&this.onChange(e),a&&(d.innerText=""+e)}}),this.container.append(r,this.range.container)}}class Xi extends H{init(){this.header.classList.add("with-border"),this.container.classList.add("general-settings-container"),this.setTitle("General");const e=En.bind(null,this.scrollable);{const t=e("Settings"),s=new Yi("TextSize",1,a.default.settings.messagesTextSize,12,20);s.onChange=e=>{M.default.setByKey("settings.messagesTextSize",e)};const i=(0,U.Z)("btn-primary btn-transparent",{icon:"image",text:"ChatBackground"});(0,l.fc)(i,(()=>{new ji(this.slider).open()}));const n=new ut.Z({text:"EnableAnimations",name:"animations",stateKey:"settings.animationsEnabled",withRipple:!0});t.append(s.container,i,n.label)}{const t=e("General.Keyboard"),s=document.createElement("form"),i="send-shortcut",n="settings.sendShortcut",a=new et({radioField:new at({langKey:"General.SendShortcut.Enter",name:i,value:"enter",stateKey:n}),subtitleLangKey:"General.SendShortcut.NewLine.ShiftEnter"}),o=new et({radioField:new at({name:i,value:"ctrlEnter",stateKey:n}),subtitleLangKey:"General.SendShortcut.NewLine.Enter"});(0,k._i18n)(o.radioField.main,"General.SendShortcut.CtrlEnter",[ne.IS_APPLE?"⌘":"Ctrl"]),s.append(a.container,o.container),t.append(s)}if($i){const t=e("DistanceUnitsTitle"),s=document.createElement("form"),i="distance-unit",n="settings.distanceUnit",a=new et({radioField:new at({langKey:"DistanceUnitsKilometers",name:i,value:"kilometers",stateKey:n})}),o=new et({radioField:new at({langKey:"DistanceUnitsMiles",name:i,value:"miles",stateKey:n})});s.append(a.container,o.container),t.append(s)}{const t=e("General.TimeFormat"),s=document.createElement("form"),i="time-format",n="settings.timeFormat",a=[["h12","General.TimeFormat.h12"],["h23","General.TimeFormat.h23"]],o=a.map((([e,t])=>new et({radioField:new at({langKey:t,name:i,value:e,stateKey:n})}))),r=function(e,t=!0){return function(e,t,s=!0){const i=e;let n;return s||(e=_e.Z),function s(){e(),n=qi.Z.setTimeout(s,t())}(),e=i,()=>{clearTimeout(n)}}(e,(()=>1e3*(60-(new Date).getSeconds())),t)}((()=>{const e=new Date;a.forEach((([t],s)=>{const i=e.toLocaleTimeString("en-us-u-hc-"+t,{hour:"2-digit",minute:"2-digit"});o[s].subtitle.textContent=i}))}));this.eventListener.addEventListener("destroy",r),s.append(...o.map((e=>e.container))),t.append(s)}{const t=e("Emoji"),s=new ut.Z({text:"GeneralSettings.EmojiPrediction",name:"suggest-emoji",stateKey:"settings.emoji.suggest",withRipple:!0}),i=new ut.Z({text:"GeneralSettings.BigEmoji",name:"emoji-big",stateKey:"settings.emoji.big",withRipple:!0});t.append(s.label,i.label)}{const e=new Mn({name:"Telegram.InstalledStickerPacksController",caption:"StickersBotInfo"}),t=new et({titleLangKey:"DoubleTapSetting",havePadding:!0,clickable:()=>{new Qi(this.slider).open()}}),s=()=>{Promise.resolve(_t.Z.getQuickReaction()).then((e=>{Es({row:t,doc:e.static_icon,size:"small"})}))};s(),this.listenerSetter.add(a.default)("quick_reaction",s);const i=new ut.Z({text:"Stickers.SuggestStickers",name:"suggest",stateKey:"settings.stickers.suggest",withRipple:!0}),n=new ut.Z({text:"InstalledStickers.LoopAnimated",name:"loop",stateKey:"settings.stickers.loop",withRipple:!0}),o={},r=e.generateContentElement(),l=new X.ZP,d=(e,t="append")=>{const s=new et({title:Q.Z.wrapEmojiText(e.title),subtitleLangKey:"Stickers",subtitleLangArgs:[e.count],havePadding:!0,clickable:()=>{new Ki({id:e.id,access_hash:e.access_hash}).show()}});o[e.id]=s;const i=document.createElement("div");i.classList.add("row-media"),Ms({set:e,container:i,group:"GENERAL-SETTINGS",lazyLoadQueue:l,width:48,height:48,autoplay:!0}),s.container.append(i),r[t](s.container)};ds.Z.getAllStickers().then((e=>{(0,gs.Z)(e);for(const t of e.sets)d(t)})),this.listenerSetter.add(a.default)("stickers_installed",(e=>{const t=e;o[t.id]||d(t,"prepend")})),this.listenerSetter.add(a.default)("stickers_deleted",(e=>{const t=e;o[t.id]&&(o[t.id].container.remove(),delete o[t.id])})),e.content.append(t.container,i.label,n.label),this.scrollable.append(e.container)}}onOpen(){this.init&&(this.init(),this.init=null)}}class Ji extends O{init(){return e=this,t=void 0,i=function*(){this.container.classList.add("edit-profile-container"),this.setTitle("EditAccount.Title");const e=[];{const t=En(this.scrollable,void 0,"Bio.Description"),s=document.createElement("div");s.classList.add("input-wrapper"),this.firstNameInputField=new _.Z({label:"EditProfile.FirstNameLabel",name:"first-name",maxLength:70}),this.lastNameInputField=new _.Z({label:"Login.Register.LastName.Placeholder",name:"last-name",maxLength:64}),this.bioInputField=new _.Z({label:"EditProfile.BioLabel",name:"bio",maxLength:70}),s.append(this.firstNameInputField.container,this.lastNameInputField.container,this.bioInputField.container);const i=document.createElement("div");i.classList.add("caption"),(0,k.i18n_)({element:i,key:"Bio.Description"}),e.push(this.firstNameInputField,this.lastNameInputField,this.bioInputField),this.editPeer=new Xe({peerId:a.default.myId,inputFields:e,listenerSetter:this.listenerSetter}),this.content.append(this.editPeer.nextBtn),t.append(this.editPeer.avatarEdit.container,s)}{const t=new Mn({name:"EditAccount.Username",caption:!0}),s=document.createElement("div");s.classList.add("input-wrapper"),this.usernameInputField=new ht({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"}),s.append(this.usernameInputField.container);const i=t.caption;i.append((0,k.i18n)("UsernameSettings.ChangeDescription")),i.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,k.i18n)("UsernameHelpLink",[a])),i.append(n),e.push(this.usernameInputField),t.content.append(s),this.scrollable.append(t.container)}(0,l.fc)(this.editPeer.nextBtn,(()=>{this.editPeer.nextBtn.disabled=!0;let e=[];e.push(n.default.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=>n.default.uploadProfilePhoto(e)))),this.usernameInputField.isValidToChange()&&e.push(E.Z.updateUsername(this.usernameInputField.value)),Promise.race(e).finally((()=>{this.editPeer.nextBtn.removeAttribute("disabled")}))}),{listenerSetter:this.listenerSetter});const t=E.Z.getSelf(),s=yield n.default.getProfile(t.id,!0);this.firstNameInputField.setOriginalValue(t.first_name,!0),this.lastNameInputField.setOriginalValue(t.last_name,!0),this.bioInputField.setOriginalValue(s.about,!0),this.usernameInputField.setOriginalValue(t.username,!0),this.setProfileUrl(),this.editPeer.handleChange()},new((s=void 0)||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}));var e,t,s,i}setProfileUrl(){if(this.usernameInputField.input.classList.contains("error")||!this.usernameInputField.value.length)this.profileUrlContainer.style.display="none";else{this.profileUrlContainer.style.display="";let e="https://t.me/"+this.usernameInputField.value;this.profileUrlAnchor.innerText=e,this.profileUrlAnchor.href=e}}}class en extends O{constructor(){super(...arguments),this.renderResults=e=>{return t=this,s=void 0,n=function*(){yield E.Z.getContacts(),e.forEach((e=>{const{dom:t}=pd.addDialogNew({dialog:e,container:this.selector.scrollable,drawStatus:!1,rippleEnabled:!0,avatarSize:46}),s=this.selector.selected.has(e);t.containerEl.append(this.checkbox(s));const i=[];this.dialogsByFilters.forEach(((t,s)=>{if(t.has(e)){const e=document.createElement("span");e.innerHTML=Q.Z.wrapEmojiText(s.title),i.push(e)}})),(0,k.join)(i,!1).forEach((e=>{t.lastMessageSpan.append(e)}))}))},new((i=void 0)||(i=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 s;t.done?e(t.value):(s=t.value,s instanceof i?s:new i((function(e){e(s)}))).then(o,r)}l((n=n.apply(t,s||[])).next())}));var t,s,i,n},this.onSelectChange=e=>{"included"===this.type&&(this.confirmBtn.style.display=e?"":"none")}}init(){return this.content.remove(),this.container.classList.add("included-chatlist-container"),this.confirmBtn=N("check btn-confirm blue",{noRipple:!0}),this.confirmBtn.style.display="none",this.header.append(this.confirmBtn),this.confirmBtn.addEventListener("click",(()=>{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 s of e)s.isPeerId()?t.push(s.toPeerId()):this.filter.pFlags[s]=!0;let s;s="included"===this.type?e=>t.includes(e):e=>!t.includes(e),(0,b.Z)(this.filter.pinnedPeerIds,((e,t)=>{s(e)||(this.filter.pinnedPeerIds.splice(t,1),this.filter.pinned_peers.splice(t,1))}));const i="included"===this.type?"excludePeerIds":"includePeerIds",n="included"===this.type?"exclude_peers":"include_peers";(0,b.Z)(this.filter[i],((e,s)=>{t.includes(e)&&(this.filter[i].splice(s,1),this.filter[n].splice(s,1))})),this.filter["included"===this.type?"includePeerIds":"excludePeerIds"]=t,this.filter["included"===this.type?"include_peers":"exclude_peers"]=t.map((e=>o.Z.getInputPeerById(e))),this.editFolderTab.setFilter(this.filter,!1),this.close()})),this.dialogsByFilters=new Map,i.Z.filtersStorage.getDialogFilters().then((e=>{for(const t of e)this.dialogsByFilters.set(t,new Set(i.Z.dialogsStorage.getFolderDialogs(t.id).map((e=>e.peerId))))}))}checkbox(e){const t=new ut.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 Mn({noDelimiter:!0,name:"FilterChatTypes"});let s;t.container.classList.add("folder-categories"),s="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 i=document.createDocumentFragment();for(const e in s){const t=(0,U.Z)("btn-primary btn-transparent folder-category-button",{icon:s[e].ico,text:s[e].text});t.dataset.peerId=e,t.append(this.checkbox()),i.append(t)}t.content.append(i);const n=("included"===this.type?e.includePeerIds:e.excludePeerIds).slice();this.selector=new Mt({appendTo:this.container,onChange:this.onSelectChange,peerType:["dialogs"],renderResultsFunc:this.renderResults,placeholder:"Search",sectionNameLangPackKey:"FilterChats"}),this.selector.selected=new Set(n);let a=!1;const o=this.selector.add.bind(this.selector);this.selector.add=(e,t,i)=>{if(this.selector.selected.size>=100&&a&&!s[e]){const t=this.selector.list.querySelector(`[data-peer-id="${e}"] [type="checkbox"]`);return t&&setTimeout((()=>{t.checked=!1}),0),void rt(k.default.format("excluded"===this.type?"ChatList.Filter.Exclude.LimitReached":"ChatList.Filter.Include.LimitReached",!0))}const n=o(e,s[e]?(0,k.i18n)(s[e].text):void 0,i);return s[e]&&n.querySelector("avatar-element").classList.add("tgico-"+s[e].ico),n},this.selector.scrollable.container.append(t.container,this.selector.scrollable.container.lastElementChild),this.selector.addInitial(n),a=!0;for(const i in e.pFlags)s.hasOwnProperty(i)&&e.pFlags[i]&&t.content.querySelector(`[data-peer-id="${i}"]`).click()}onCloseAfterTimeout(){return this.selector&&(this.selector.container.remove(),this.selector=null),super.onCloseAfterTimeout()}open(e,t,s){return this.originalFilter=e,this.filter=(0,pe.Z)(this.originalFilter),this.type=t,this.editFolderTab=s,super.open()}}class tn extends O{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,k.i18n)("FilterIncludeExcludeInfo")),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container"),this.confirmBtn=N("check btn-confirm hide blue");const e={icon:"delete danger",text:"FilterMenuDelete",onClick:()=>{new gt("filter-delete",{titleLangKey:"ChatList.Filter.Confirm.Remove.Header",descriptionLangKey:"ChatList.Filter.Confirm.Remove.Text",buttons:[{langKey:"Delete",callback:()=>{e.element.setAttribute("disabled","true"),i.Z.filtersStorage.updateDialogFilter(this.filter,!0).then((e=>{e&&this.close()})).finally((()=>{e.element.removeAttribute("disabled")}))},isDanger:!0}]}).show()}};this.menuBtn=Ie({},"bottom-left",[e]),this.menuBtn.classList.add("hide"),this.header.append(this.confirmBtn,this.menuBtn);const t=new Mn({}),s=document.createElement("div");s.classList.add("input-wrapper"),this.nameInputField=new _.Z({label:"FilterNameHint",maxLength:12}),s.append(this.nameInputField.container),t.content.append(s);const n=(e,t,s,i)=>{const n=new Mn({name:t,noDelimiter:!0});n.container.classList.add("folder-list",e);const a=n.generateContentElement();return a.classList.add("folder-categories"),s.forEach((e=>{const t=(0,U.Z)("folder-category-button btn btn-primary btn-transparent",{icon:e.icon,text:e.text,noRipple:!e.withRipple||void 0});e.name&&(i[e.name]=t),a.append(t)})),n};this.includePeerIds=n("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=n("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");a.querySelector(".btn").addEventListener("click",(()=>{new en(this.slider).open(this.filter,"included",this)})),o.querySelector(".btn").addEventListener("click",(()=>{new en(this.slider).open(this.filter,"excluded",this)})),this.confirmBtn.addEventListener("click",(()=>{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?i.Z.filtersStorage.updateDialogFilter(this.filter):i.Z.filtersStorage.createDialogFilter(this.filter),e.then((e=>{e&&this.close()})).catch((e=>{"DIALOG_FILTERS_TOO_MUCH"===e.type?rt("Sorry, you can't create more folders."):console.error("updateDialogFilter error:",e)})).finally((()=>{this.confirmBtn.removeAttribute("disabled")}))):rt("Please choose at least one chat for this folder.")})),this.nameInputField.input.addEventListener("input",(()=>{this.filter.title=this.nameInputField.value,this.editCheckForChange()}));const r="edit"===this.type?[i.Z.filtersStorage.reloadMissingPeerIds(this.filter.id,"pinned_peers"),i.Z.filtersStorage.reloadMissingPeerIds(this.filter.id,"include_peers"),i.Z.filtersStorage.reloadMissingPeerIds(this.filter.id,"exclude_peers")]:[];return Promise.all([this.loadAnimationPromise=ae.Z.loadAnimationAsAsset({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86},"Folders_2").then((e=>(this.animation=e,ae.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=Q.Z.wrapDraftText(e.title);for(const t in this.flags)this.flags[t].style.display=e.pFlags[t]?"":"none";["includePeerIds","excludePeerIds"].forEach((t=>{const s=this[t],i=pd.createChatList(),n=e[t].slice(),a=e=>{for(let t=0,s=Math.min(n.length,e);t<s;++t){const e=n.shift(),{dom:t}=pd.addDialogNew({dialog:e,container:i,drawStatus:!1,rippleEnabled:!1,meAsSaved:!0,avatarSize:32});t.lastMessageSpan.parentElement.remove()}n.length?o.lastElementChild.replaceWith((0,k.i18n)("FilterShowMoreChats",[n.length])):o&&o.remove()};let o;if(s.generateContentElement().append(i),n.length){const e=s.generateContentElement();o=(0,U.Z)("folder-category-button btn btn-primary btn-transparent",{icon:"down"}),o.classList.add("load-more","rp-overflow"),o.addEventListener("click",(()=>a(20))),o.append((0,k.i18n)("FilterShowMoreChats",[n.length])),e.append(o)}a(4)}))}editCheckForChange(){if("edit"===this.type){const e=!(0,ue.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,pe.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.onEditOpen():this.onCreateOpen()}))}}class sn extends O{constructor(){super(...arguments),this.filtersRendered={}}renderFolder(e,t,s){let n,a,r="",d=[];if("dialogFilterSuggested"===e._)n=e.filter,r=e.description;else{if(n=e,1===Object.keys(n.pFlags).length){const e=n.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&&d.push((0,k.i18n)(t))}if(!d.length){const e=i.Z.dialogsStorage.getFolderDialogs(n.id);let t=0,s=0,a=0;for(const i of e)o.Z.isAnyGroup(i.peerId)?a++:o.Z.isBroadcast(i.peerId)?s++:t++;t&&d.push((0,k.i18n)("Chats",[t])),s&&d.push((0,k.i18n)("Channels",[s])),a&&d.push((0,k.i18n)("Groups",[a]))}}if(s)s.subtitle.textContent="",(0,k.join)(d).forEach((e=>{s.subtitle.append(e)}));else if(s=new et({title:Q.o.wrapEmojiText(n.title),subtitle:r,clickable:!0}),d.length&&(0,k.join)(d).forEach((e=>{s.subtitle.append(e)})),"dialogFilter"===e._){const e=n.id;this.filtersRendered.hasOwnProperty(n.id)||(0,l.fc)(s.container,(()=>{new tn(this.slider).open(i.Z.filtersStorage.getFilter(e))}),{listenerSetter:this.listenerSetter}),this.filtersRendered[n.id]=s}return a=s.container,n.hasOwnProperty("orderIndex")?Zs(a,a.parentElement||t,n.orderIndex):t&&t.append(a),a}init(){return e=this,t=void 0,n=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,k.i18n_)({element:e,key:"ChatList.Filter.Header"}),this.createFolderBtn=(0,U.Z)("btn-primary btn-color-primary btn-control tgico",{text:"ChatList.Filter.NewTitle",icon:"add"}),this.foldersSection=new Mn({name:"Filters"}),this.foldersSection.container.style.display="none",this.suggestedSection=new Mn({name:"FilterRecommended"}),this.suggestedSection.container.style.display="none",this.scrollable.append(this.stickerContainer,e,this.createFolderBtn,this.foldersSection.container,this.suggestedSection.container),(0,l.fc)(this.createFolderBtn,(()=>{Object.keys(this.filtersRendered).length>=10?rt("Sorry, you can't create more folders."):new tn(this.slider).open()}),{listenerSetter:this.listenerSetter});const t=()=>{this.foldersSection.container.style.display=Object.keys(this.filtersRendered).length?"":"none"};return i.Z.filtersStorage.getDialogFilters().then((e=>{for(const t of e)this.renderFolder(t,this.foldersSection.content);t()})),this.listenerSetter.add(a.default)("filter_update",(e=>{this.filtersRendered.hasOwnProperty(e.id)?this.renderFolder(e,null,this.filtersRendered[e.id]):this.renderFolder(e,this.foldersSection.content),t(),this.getSuggestedFilters()})),this.listenerSetter.add(a.default)("filter_delete",(e=>{this.filtersRendered.hasOwnProperty(e.id)&&(this.getSuggestedFilters(),this.filtersRendered[e.id].container.remove(),delete this.filtersRendered[e.id]),t()})),this.listenerSetter.add(a.default)("filter_order",(e=>{e.forEach(((e,t)=>{const s=this.filtersRendered[e].container;Zs(s,s.parentElement,t+1)}))})),this.loadAnimationPromise=ae.Z.loadAnimationAsAsset({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86},"Folders_1").then((e=>(this.animation=e,ae.Z.waitForFirstFrame(e)))),this.getSuggestedFilters(),this.loadAnimationPromise},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}onOpenAfterTimeout(){this.loadAnimationPromise.then((()=>{this.animation.autoplay=!0,this.animation.play()}))}getSuggestedFilters(){return ct.Z.invokeApi("messages.getSuggestedDialogFilters").then((e=>{this.suggestedSection.container.style.display=e.length?"":"none",Array.from(this.suggestedSection.content.children).slice(1).forEach((e=>e.remove())),e.forEach((e=>{const t=this.renderFolder(e),s=(0,U.Z)("btn-primary btn-color-primary",{text:"Add"});t.append(s),this.suggestedSection.content.append(t),(0,l.fc)(s,(n=>{if((0,d.d)(n),Object.keys(this.filtersRendered).length>=10)return void rt("Sorry, you can't create more folders.");s.setAttribute("disabled","true");const a=e.filter;a.includePeerIds=[],a.excludePeerIds=[],a.pinnedPeerIds=[],i.Z.filtersStorage.createDialogFilter(a,!0).then((e=>{e&&t.remove()})).finally((()=>{s.removeAttribute("disabled")}))}),{listenerSetter:this.listenerSetter})}))}))}}class nn extends H{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 Mn({name:e.name}),s=new et({checkboxField:new ut.Z({text:e.typeText,checked:!0}),subtitleLangKey:"Loading"}),i=new et({checkboxField:new ut.Z({text:"MessagePreview",checked:!0}),subtitleLangKey:"Loading"});t.content.append(s.container,i.container),this.scrollable.append(t.container);const n={_:e.inputKey},o=Ft.Z.getNotifySettings(n);(o instanceof Promise?o:Promise.resolve(o)).then((t=>{const o=()=>{const e=Ft.Z.isMuted(t);return s.checkboxField.checked=!e,i.checkboxField.checked=t.show_previews,e};o(),this.eventListener.addEventListener("destroy",(()=>{const e=!s.checkboxField.checked,a=i.checkboxField.checked;if(e===Ft.Z.isMuted(t)&&a===t.show_previews)return;const o=(0,pe.Z)(t);o._="inputPeerNotifySettings",o.mute_until=e?2147483647:0,o.show_previews=a,Ft.Z.updateNotifySettings(n,o)}),{once:!0}),this.listenerSetter.add(a.default)("notify_settings",(s=>{const i=Ai(s.peer._);e.inputKey===i&&(t=s.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 Mn({name:"NotificationsOther"}),t=new et({checkboxField:new ut.Z({text:"ContactJoined",checked:!0}),subtitleLangKey:"Loading"}),s=new et({checkboxField:new ut.Z({text:"Notifications.Sound",checked:!0,stateKey:"settings.notifications.sound"}),subtitleLangKey:"Loading"});M.default.getState().then((e=>{s.checkboxField.checked=e.settings.notifications.sound})),e.content.append(t.container,s.container),this.scrollable.append(e.container),Ft.Z.getContactSignUpNotification().then((e=>{t.checkboxField.checked=e,this.eventListener.addEventListener("destroy",(()=>{const s=t.checkboxField.checked;e!==s&&Ft.Z.setContactSignUpNotification(!s)}),{once:!0})}))}}}class an extends O{init(){return e=this,t=void 0,i=function*(){this.header.classList.add("with-border"),this.container.classList.add("language-container"),this.setTitle("Telegram.LanguageViewController");const e=new Mn({}),t=new Map,s=ct.Z.invokeApiCacheable("langpack.getLanguages",{lang_pack:"macos"}).then((s=>{const i=(0,it.a)();s.forEach((e=>{const s=new et({radioField:new at({text:e.name,name:i,value:e.lang_code}),subtitle:e.native_name});t.set(e.lang_code,s)}));const n=tt([...t.values()],(e=>{k.default.getLangPack(e)}));k.default.getCacheLangPack().then((e=>{const s=t.get(e.lang_code);s?s.radioField.setValueSilently(!0):console.error("no row",s,e)})),e.content.append(n)}));return this.scrollable.append(e.container),s},new((s=void 0)||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}));var e,t,s,i}}function on(e){return new Promise(((t,s)=>{const{button:i,checkbox:n}=e;i.callback=e=>{t(e?!!e.size:void 0)};const a=(0,pt.x)([i]),o=a.find((e=>e.isCancel));o.callback=()=>{s()},e.buttons=a,e.checkboxes=n&&[n],new gt("popup-confirmation",e).show()}))}function rn(e,t){const s=new Mn({name:t}),i="settings.autoDownload."+e+".",n=new ut.Z({text:"AutodownloadContacts",name:"contacts",stateKey:i+"contacts",withRipple:!0}),a=new ut.Z({text:"AutodownloadPrivateChats",name:"private",stateKey:i+"private",withRipple:!0}),o=new ut.Z({text:"AutodownloadGroupChats",name:"groups",stateKey:i+"groups",withRipple:!0}),r=new ut.Z({text:"AutodownloadChannels",name:"channels",stateKey:i+"channels",withRipple:!0});return s.content.append(n.label,a.label,o.label,r.label),s}class ln extends H{init(){this.header.classList.add("with-border"),this.setTitle("AutoDownloadPhotos");const e=rn("photo","AutoDownloadPhotosTitle");this.scrollable.append(e.container)}}class dn extends H{init(){this.header.classList.add("with-border"),this.setTitle("AutoDownloadFiles");const e=dt((e=>{M.default.setByKey("settings.autoDownloadNew.file_size_max",e)}),200,!1,!0),t=rn("file","AutoDownloadFilesTitle"),s=524288,i=20447232,n=a.default.settings.autoDownloadNew.file_size_max,o=Math.sqrt(Math.sqrt((n-s)/i)),r=new k.default.IntlElement({key:"AutodownloadSizeLimitUpTo",args:[Be(n)]}),l=new Yi("AutoDownloadMaxFileSize",.01,o,0,1,!1);l.onChange=t=>{const n=Math.pow(t,4)*i+s|0;r.compareAndUpdate({args:[Be(n)]}),e(n)},l.valueContainer.append(r.element),t.content.append(l.container),this.scrollable.append(t.container)}}class cn extends H{init(){this.header.classList.add("with-border"),this.setTitle("AutoDownloadVideos");const e=rn("video","AutoDownloadVideosTitle");this.scrollable.append(e.container)}}const hn={contacts:"AutoDownloadContacts",private:"AutoDownloadPm",groups:"AutoDownloadGroups",channels:"AutoDownloadChannels"};class pn extends H{init(){return e=this,t=void 0,i=function*(){this.header.classList.add("with-border"),this.setTitle("DataSettings");{const e=new Mn({name:"AutomaticMediaDownload",caption:"AutoDownloadAudioInfo"}),t=yield M.default.getState(),s=new ut.Z({text:"AutoDownloadMedia",name:"auto",checked:!t.settings.autoDownloadNew.pFlags.disabled,withRipple:!0}),i=()=>{(0,mt.Z)([h],(0,ue.Z)(t.settings.autoDownload,M.STATE_INIT.settings.autoDownload)&&(0,ue.Z)(t.settings.autoDownloadNew,M.STATE_INIT.settings.autoDownloadNew))},n=()=>{this.setAutoDownloadSubtitle(r,t.settings.autoDownload.photo),this.setAutoDownloadSubtitle(d,t.settings.autoDownload.video),this.setAutoDownloadSubtitle(c,t.settings.autoDownload.file,t.settings.autoDownloadNew.file_size_max)},o=e=>{const t=new e(this.slider,!0);t.open(),this.listenerSetter.add(t.eventListener)("destroy",(()=>{n(),i()}),{once:!0})},r=new et({titleLangKey:"AutoDownloadPhotos",subtitle:"",clickable:()=>{o(ln)}}),d=new et({titleLangKey:"AutoDownloadVideos",subtitle:"",clickable:()=>{o(cn)}}),c=new et({titleLangKey:"AutoDownloadFiles",subtitle:"",clickable:()=>{o(dn)}}),h=(0,U.Z)("btn-primary btn-transparent primary",{icon:"delete",text:"ResetAutomaticMediaDownload"});(0,l.fc)(h,(()=>{on({titleLangKey:"ResetAutomaticMediaDownloadAlertTitle",descriptionLangKey:"ResetAutomaticMediaDownloadAlert",button:{langKey:"Reset"}}).then((()=>{a.default.settings.autoDownloadNew=(0,pe.Z)(M.STATE_INIT.settings.autoDownloadNew),a.default.settings.autoDownload=(0,pe.Z)(M.STATE_INIT.settings.autoDownload),M.default.pushToState("settings",a.default.settings),a.default.dispatchEvent("settings_updated",{key:"settings",value:a.default.settings}),n(),s.checked=!t.settings.autoDownloadNew.pFlags.disabled}))}));const p=()=>{const e=!s.checked,t=a.default.settings;e?t.autoDownloadNew.pFlags.disabled=!0:delete t.autoDownloadNew.pFlags.disabled,[r,d,c].forEach((t=>{t.container.classList.toggle("is-disabled",e)})),M.default.pushToState("settings",t),a.default.dispatchEvent("settings_updated",{key:"settings",value:t}),i()};s.input.addEventListener("change",p),p(),n(),e.content.append(s.label,r.container,d.container,c.container,h),this.scrollable.append(e.container)}{const e=new Mn({name:"AutoplayMedia"}),t=new ut.Z({text:"AutoplayGIF",name:"gifs",stateKey:"settings.autoPlay.gifs",withRipple:!0}),s=new ut.Z({text:"AutoplayVideo",name:"videos",stateKey:"settings.autoPlay.videos",withRipple:!0});e.content.append(t.label,s.label),this.scrollable.append(e.container)}},new((s=void 0)||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}));var e,t,s,i}setAutoDownloadSubtitle(e,t,s){let i,n=[];const a=Object.keys(t),o=a.map((e=>t[e]?hn[e]:void 0)).filter(Boolean);if(o.length&&0!==s){const e=o.length===a.length;if(void 0!==s?(i=e?"AutoDownloadUpToOnAllChats":"AutoDownloadOnUpToFor",n.push(Be(s))):i=e?"AutoDownloadOnAllChats":"AutoDownloadOnFor",!e){const e=document.createElement("span");e.append(...(0,k.join)(o.map((e=>(0,k.i18n)(e))),!0,!1)),n.push(e)}}else i="AutoDownloadOff";(0,T.Z)(e.subtitle,(0,k.i18n)(i,n))}}class un extends O{constructor(){super(...arguments),this.buttons={}}init(){this.container.classList.add("settings-container"),this.setTitle("Settings");const e=Ie({},"bottom-left",[{icon:"logout",text:"EditAccount.Logout",onClick:()=>{new gt("logout",{titleLangKey:"LogOut",descriptionLangKey:"LogOut.Description",buttons:[{langKey:"LogOut",callback:()=>{ct.Z.logOut()},isDanger:!0}]}).show()}}]);this.buttons.edit=N("edit"),this.header.append(this.buttons.edit,e),this.profile=new Wt(this.scrollable,this.listenerSetter,!1),this.profile.init(),this.profile.setPeer(a.default.myId),this.profile.fillProfileElements();const t=(0,U.Z)("btn-circle btn-corner z-depth-1 profile-change-avatar",{icon:"cameraadd"});t.addEventListener("click",(()=>{const e=document.createElement("canvas");(new G.Z).open(e,(e=>{e().then((e=>n.default.uploadProfilePhoto(e)))}))})),this.profile.element.lastElementChild.firstElementChild.append(t);const s=()=>{var e;const s=E.Z.getSelf();t.classList.toggle("hide","userProfilePhoto"!==(null===(e=s.photo)||void 0===e?void 0:e._))};s(),this.listenerSetter.add(a.default)("avatar_update",(e=>{a.default.myId===e&&s()}));const i=document.createElement("div");i.classList.add("profile-buttons");const o=[["unmute","AccountSettings.Notifications",nn],["data","DataSettings",pn],["lock","AccountSettings.PrivacyAndSecurity",_i],["settings","Telegram.GeneralSettingsViewController",Xi],["folder","AccountSettings.Filters",sn]].map((([e,t,s])=>new et({titleLangKey:t,icon:e,clickable:()=>{new s(this.slider,!0).open()}})));o.push(this.devicesRow=new et({titleLangKey:"Devices",titleRightSecondary:" ",icon:"activesessions",clickable:()=>{return e=this,t=void 0,i=function*(){this.authorizations||(yield this.updateActiveSessions());const e=new Ti(this.slider);e.authorizations=this.authorizations,e.eventListener.addEventListener("destroy",(()=>{this.authorizations=void 0,this.updateActiveSessions(!0)}),{once:!0}),e.open()},new((s=void 0)||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}));var e,t,s,i}}),this.languageRow=new et({titleLangKey:"AccountSettings.Language",titleRightSecondary:(0,k.i18n)("LanguageName"),icon:"language",clickable:()=>{new an(this.slider).open()}})),i.append(...o.map((e=>e.container)));const r=new Mn;r.content.append(i),this.scrollable.append(this.profile.element,r.container),this.buttons.edit.addEventListener("click",(()=>{new Ji(this.slider).open()})),ae.Z.loadLottieWorkers(),this.updateActiveSessions()}getAuthorizations(e){if(this.getAuthorizationsPromise&&!e)return this.getAuthorizationsPromise;const t=this.getAuthorizationsPromise=ct.Z.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}))}}class gn extends O{constructor(){super(...arguments),this.uploadAvatar=null}init(){this.container.classList.add("new-channel-container"),this.setTitle("NewChannel"),this.avatarEdit=new K((e=>{this.uploadAvatar=e}));const e=new Mn({caption:"Channel.DescriptionHolderDescrpiton"}),t=document.createElement("div");t.classList.add("input-wrapper"),this.channelNameInputField=new _.Z({label:"EnterChannelName",maxLength:128}),this.channelDescriptionInputField=new _.Z({label:"DescriptionOptionalPlaceholder",maxLength:255}),t.append(this.channelNameInputField.container,this.channelDescriptionInputField.container);const s=()=>{this.nextBtn.classList.toggle("is-visible",!!this.channelNameInputField.value.length&&!this.channelNameInputField.input.classList.contains("error")&&!this.channelDescriptionInputField.input.classList.contains("error"))};this.channelNameInputField.input.addEventListener("input",s),this.channelDescriptionInputField.input.addEventListener("input",s),this.nextBtn=W({icon:"arrow_next"}),this.nextBtn.addEventListener("click",(()=>{const e=this.channelNameInputField.value,t=this.channelDescriptionInputField.value;this.nextBtn.disabled=!0,j.Z.createChannel({title:e,about:t,broadcast:!0}).then((e=>{this.uploadAvatar&&this.uploadAvatar().then((t=>{j.Z.editPhoto(e,t)})),xn.removeTabFromHistory(this),new Bt(this.slider).open({type:"channel",skippable:!0,title:"GroupAddMembers",placeholder:"SendMessageTo",takeOut:t=>j.Z.inviteToChannel(e,t)})}))})),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 mn=s(709);class vn extends pt.Z{constructor(){super("popup-create-contact popup-send-photo popup-new-media",null,{closable:!0,withConfirm:"Add"}),(0,k._i18n)(this.title,"AddContactTitle"),(0,l.fc)(this.btnConfirm,(()=>{const e=E.Z.importContact(s.value,i.value,n.value);e.then((()=>{this.hide()}),(e=>{"NO_USER"===e.type&&(lt({langPackKey:"Contacts.PhoneNumber.NotRegistred"}),d.disabled=!1)})),d.lockWithPromise(e)}),{listenerSetter:this.listenerSetter});const e=[],t=document.createElement("div");t.classList.add("name-fields");const s=new _.Z({label:"FirstName",name:"create-contact-name",maxLength:70,required:!0}),i=new _.Z({label:"LastName",name:"create-contact-lastname",maxLength:70}),n=new mn.Z({required:!0});e.push(s,i,n);const a=()=>{const e=s.value+" "+i.value;d.avatarElem.setAttribute("peer-title",e),d.avatarElem.update()};this.listenerSetter.add(s.input)("input",a),this.listenerSetter.add(i.input)("input",a),n.validate=()=>!!n.value.match(/\d/);const o=E.Z.getSelf(),r=(0,Os.u)(o.phone);r.code&&(n.value="+"+r.code.country_code);const d=new Xe({inputFields:e,listenerSetter:this.listenerSetter,doNotEditAvatar:!0,nextBtn:this.btnConfirm,avatarSize:100});t.append(s.container,i.container,d.avatarElem),this.container.append(t,n.container),this.show()}}class fn extends O{init(){this.container.id="contacts-container";const e=W({icon:"add",className:"is-visible"});this.content.append(e),(0,l.fc)(e,(()=>{new vn}),{listenerSetter:this.listenerSetter}),this.inputSearch=new Z("Search",(e=>{this.openContacts(e)})),this.listenerSetter.add(a.default)("contacts_update",(e=>{const t=E.Z.isContact(e),s=e.toPeerId();t?this.sortedUserList.add(s):this.sortedUserList.delete(s)})),this.title.replaceWith(this.inputSearch.container),this.middleware=(0,As.k)()}createList(){const e=new Rs,t=e.list;return t.id="contacts",t.classList.add("contacts-container"),pd.setListClickListener(t,(()=>{this.close()}),void 0,!0),e}onClose(){this.middleware.clean()}onOpenAfterTimeout(){!ne.IS_MOBILE&&ui(!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="",E.Z.getContactsPeerIds(e,void 0,"online").then((e=>{if(!t())return;const s=this.sortedUserList=this.createList();let i=()=>{const t=Ct.Z.height/72*1.25|0;e.splice(0,t).forEach((e=>{s.add(e)})),e.length||(i=void 0,this.scrollable.onScrolledBottom=null)};i(),this.scrollable.onScrolledBottom=()=>{i?i():this.scrollable.onScrolledBottom=null},(0,T.Z)(this.scrollable.container,s.list)}))}open(){return this.openContacts(),super.open()}}class bn extends O{init(){if(this.container.id="chats-archived-container",this.setTitle("ArchivedChats"),!pd.sortedLists[bn.filterId]){const e=pd.createChatList();pd.generateScrollable(e,bn.filterId).container.append(e),pd.setListClickListener(e,null,!0)}const e=pd.scrollables[bn.filterId];this.scrollable.container.replaceWith(e.container),this.scrollable=e}onOpen(){this.init&&(this.init(),this.init=null),this.wasFilterId=pd.filterId,pd.setFilterId(bn.filterId),pd.onTabChange()}onOpenAfterTimeout(){pd.sortedLists[this.wasFilterId].clear()}onClose(){pd.setFilterId(this.wasFilterId),pd.onTabChange()}onCloseAfterTimeout(){return pd.sortedLists[bn.filterId].clear(),super.onCloseAfterTimeout()}}bn.filterId=1;class yn extends O{constructor(){super(...arguments),this.isLocationWatched=!1}init(){this.container.classList.add("people-nearby-container"),this.setTitle("PeopleNearby"),this.errorCategory=document.createElement("div"),this.errorCategory.classList.add("text","hide","nearby-error"),this.retryBtn=W({icon:"check"});const e=ds.Z.getAnimatedEmojiSticker("🧭"),t=document.createElement("div");t.classList.add("sticker-container"),e?Is({doc:e,div:t,loop:!1,play:!0,width:86,height:86,emoji:"🧭",needUpscale:!0}).then((()=>{})):t.classList.add("media-sticker-wrapper");const s=document.createElement("div");s.classList.add("caption"),(0,k._i18n)(s,"PeopleNearbyInfo2"),this.locatedPeers=new Map;const i=()=>{const e=new Rs({avatarSize:42,createChatListOptions:{dialogSize:48,new:!0},autonomous:!1,onUpdate:e=>{const t=this.locatedPeers.get(e.id),s=[this.parseDistance(t.distance)];e.id.isUser()||s.push(n.default.getChatMembersString(e.id.toChatId())),e.dom.lastMessageSpan.textContent="",e.dom.lastMessageSpan.append(...(0,k.join)(s,!1))},getIndex:e=>2147483647-this.locatedPeers.get(e.id).distance});return pd.setListClickListener(e.list,void 0,void 0,!1),e},a=this.peopleSection=new Tn({name:"PeopleNearbyHeader",sortedList:i()}),o=this.chatsSection=new Tn({name:"ChatsNearbyHeader",sortedList:i()}),r=a.makeButton({text:"MakeMyselfVisible",icon:"location"}),d=a.makeButton({text:"StopShowingMe",icon:"location"}),c=o.makeButton({text:"NearbyCreateGroup",icon:"newgroup"});(0,l.fc)(r,(()=>{on({titleLangKey:"MakeMyselfVisibleTitle",descriptionLangKey:"MakeMyselfVisibleInfo",button:{langKey:"OK"}}).then((()=>{this.startWatching()}))}),{listenerSetter:this.listenerSetter}),(0,l.fc)(d,(()=>{this.stopWatching()}),{listenerSetter:this.listenerSetter}),(0,l.fc)(c,(()=>{new q(this.slider).open([],!0)}),{listenerSetter:this.listenerSetter}),r.classList.add("primary"),d.classList.add("danger"),c.classList.add("primary"),this.content.append(this.retryBtn),this.scrollable.append(t,s,a.container,o.container,this.errorCategory)}parseDistance(e){return"miles"===a.default.settings.distanceUnit?e>1609.34?(0,k.i18n)("MilesAway",[Math.round(e/1609)]):(0,k.i18n)("FootsAway",[Math.round(3.281*e)]):e>=1e3?(0,k.i18n)("KMetersAway2",[e/1e3]):(0,k.i18n)("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),E.Z.getLocated(e.coords.latitude,e.coords.longitude,e.coords.accuracy).then((e=>{const t=e.updates[0].peers,s=t.sort(((e,t)=>e.distance-t.distance)),i=t.filter((e=>"peerChannel"==e.peer._)).length,n=t.filter((e=>"peerChannel"!=e.peer._)).length;null==s||s.forEach((e=>{const t=o.Z.getPeerId(e.peer),s=t.isUser()?this.peopleSection:this.chatsSection;this.locatedPeers.set(t,e),s.sortedList.add(t)})),this.errorCategory.classList.toggle("hide",!(!n&&!i)),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,rt("Your position is now being shared. Do not close the page or it will be suspended."),E.Z.getLocated(this.latestLocationSaved.latitude,this.latestLocationSaved.longitude,this.latestLocationSaved.accuracy,!0,2147483647),navigator.geolocation.watchPosition((e=>{const t=e.coords.longitude!==this.latestLocationSaved.longitude,s=e.coords.latitude!==this.latestLocationSaved.latitude,i=this.calculateDistance(e.coords.latitude,e.coords.longitude,this.latestLocationSaved.latitude,this.latestLocationSaved.longitude)>100;(s||t)&&i&&(E.Z.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,rt("The sharing of your position has been stopped. You will no longer be visible to other users."),E.Z.getLocated(0,0,0,!1,0))}calculateDistance(e,t,s,i){const n=.017453292519943295;return 12742*Math.asin(Math.sqrt(.5-Math.cos((s-e)*n)+Math.cos(e*n)*Math.cos(s*n)*(1-Math.cos((i-t)*n)/2)))}}var wn=s(4159),Sn=s(7487);function Cn(e,t=2){if(0===e)return"0";const s=t<0?0:t,i=Math.floor(Math.log(e)/Math.log(1e3));return parseFloat((e/Math.pow(1e3,i)).toFixed(s))+["","K","M","B","T"][i]}const Ln="is-left-column-shown",In="sidebar-left-section";class Mn{constructor(e={}){const t=this.container=document.createElement("div");t.classList.add(In+"-container");const s=this.innerContainer=document.createElement("div");if(s.classList.add(In),e.noShadow&&s.classList.add("no-shadow"),e.fakeGradientDelimiter)s.append(Pn()),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 i=this.content=this.generateContentElement();if(e.name){const t=this.title=document.createElement("div");t.classList.add("sidebar-left-h2",In+"-name"),(0,k.i18n_)({element:t,key:e.name,args:e.nameArgs}),i.append(t)}if(t.append(s),e.caption){const s=this.caption=this.generateContentElement();s.classList.add(In+"-caption"),t.append(s),!0!==e.caption&&(0,k.i18n_)({element:s,key:e.caption})}}generateContentElement(){const e=document.createElement("div");return e.classList.add(In+"-content"),this.innerContainer.append(e),e}}const En=(e,t,s)=>{const i=new Mn({name:t,caption:s});return e.append(i.container),i.content},Pn=()=>{const e=document.createElement("div");return e.classList.add("gradient-delimiter"),e};class Tn extends Mn{constructor(e){super(e),this.sortedList=e.sortedList,this.content.append(this.sortedList.list)}makeButton(e){const t=(0,U.Z)("folder-category-button btn btn-primary btn-transparent",e);return this.title?this.content.insertBefore(t,this.title.nextSibling):this.content.prepend(t),t}}const kn=new class extends V{constructor(){super({sidebarEl:document.getElementById("column-left"),navigationType:"left"}),this.searchGroups={},this.inputSearch=new Z("Search");const e=this.sidebarEl.querySelector(".item-main .sidebar-header");e.append(this.inputSearch.container);const t=()=>{new fn(this).open()};this.backBtn=this.sidebarEl.querySelector(".sidebar-back-button");const s={icon:"archive",text:"ArchivedChats",onClick:()=>{new bn(this).open()},verify:()=>!!i.Z.dialogsStorage.getFolderDialogs(1,!1).length||!i.Z.dialogsStorage.isDialogsLoaded(1)},n=new ut.Z({toggle:!0,checked:"night"===a.default.getTheme().name});n.input.addEventListener("change",(()=>{a.default.settings.theme=n.input.checked?"night":"day",M.default.pushToState("settings",a.default.settings),a.default.dispatchEvent("theme_change")})),a.default.addEventListener("theme_change",(()=>{n.setValueSilently("night"===a.default.getTheme().name)}));const o=[{icon:"saved",text:"SavedMessages",onClick:()=>{setTimeout((()=>{Ol.setPeer({peerId:Ol.myId})}),0)}},s,{icon:"user",text:"Contacts",onClick:t},$i?{icon:"group",text:"PeopleNearby",onClick:()=>{new yn(this).open()}}:void 0,{icon:"settings",text:"Settings",onClick:()=>{new un(this).open()}},{icon:"darkmode",text:"DarkMode",onClick:()=>{},checkboxField:n},{icon:"animations",text:"Animations",onClick:()=>{},checkboxField:new ut.Z({toggle:!0,checked:!0,stateKey:"settings.animationsEnabled"})},{icon:"help",text:"TelegramFeatures",onClick:()=>{Ol.openUsername({userName:"TelegramTips"})}},{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([Sn.Z.set({kz_version:"Z"}),Sn.Z.delete("tgme_sync")]).then((()=>{location.href="https://web.telegram.org/z/"}))},verify:()=>wn.Z.isMainDomain},{icon:"char w",text:"ChatList.Menu.SwitchTo.Webogram",onClick:()=>{Sn.Z.delete("tgme_sync").then((()=>{location.href="https://web.telegram.org/?legacy=1"}))},verify:()=>wn.Z.isMainDomain}].filter(Boolean);this.toolsBtn=Ie({},"bottom-right",o,(e=>{o.forEach((e=>{e.verify&&e.element.classList.toggle("hide",!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 r=this.toolsBtn.querySelector(".btn-menu"),d=document.createElement("a");d.href="https://github.com/morethanwords/tweb/blob/master/CHANGELOG.md",d.target="_blank",d.rel="noopener noreferrer",d.classList.add("btn-menu-footer"),d.addEventListener(l.pf,(e=>{e.stopPropagation(),(0,J.UR)()}));const c=document.createElement("span");c.classList.add("btn-menu-footer-text"),c.innerHTML="Telegram Web"+wn.Z.suffix+" "+wn.Z.versionFull,d.append(c),r.classList.add("has-footer"),r.append(d),this.newBtnMenu=Ie({},"top-left",[{icon:"newchannel",text:"NewChannel",onClick:()=>{new gn(this).open()}},{icon:"newgroup",text:"NewGroup",onClick:()=>{new Bt(this).open({type:"chat",skippable:!1,takeOut:e=>{new q(this).open(e)},title:"GroupAddMembers",placeholder:"SendMessageTo"})}},{icon:"newprivate",text:"NewPrivateChat",onClick:t}]),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",e.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,ee.ripple)(this.updateBtn),this.updateBtn.append((0,k.i18n)("Update")),(0,l.fc)(this.updateBtn,(()=>{location.reload()})),e.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",s.element.append(this.archivedCount),a.default.addEventListener("folder_unread",(e=>{if(1===e.id){const t=e.unreadDialogsCount;this.archivedCount.innerText=""+Cn(t,1),this.archivedCount.classList.toggle("hide",!t)}})),E.Z.getTopPeers("correspondents"),M.default.getState().then((e=>{const t=e.recentSearch||[];for(let e=0,s=t.length;e<s;++e)M.default.requestPeer(t[e],"recentSearch");const s=setInterval((()=>{fetch("version",{cache:"no-cache"}).then((e=>200===e.status&&e.ok&&e.text()||Promise.reject())).then((e=>{e!==wn.Z.versionFull&&(this.hasUpdate=!0,clearInterval(s),this.newBtnMenu.classList.contains("is-hidden")||this.updateBtn.classList.remove("is-hidden"))})).catch(_e.Z)}),18e5)}))}initSearch(){const e=this.sidebarEl.querySelector("#search-container"),t=new P.ZP(e),s=()=>{this.backBtn.click()};this.searchGroups={contacts:new x("SearchAllChatsShort","contacts",void 0,void 0,void 0,void 0,s),globalContacts:new x("GlobalSearch","contacts",void 0,void 0,void 0,void 0,s),messages:new x("SearchMessages","messages"),people:new x(!1,"contacts",!0,"search-group-people",!0,!1,s),recent:new x("Recent","contacts",!0,"search-group-recent",!0,!0,s)};const n=this.searchSuper=new si({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});e.prepend(n.nav.parentElement.parentElement),t.container.append(n.container),n.setQuery({peerId:"".toPeerId(),folderId:0}),n.selectTab(0),n.load(!0);let a=[],o="".toPeerId(),r=0,l=0;const d=()=>{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")},c=document.createElement("div");c.classList.add("search-helper"),c.addEventListener("click",(e=>{const t=(0,Me.Z)(e.target,"selector-user");if(!t)return;const s=t.dataset.key;if(0===s.indexOf("date_")){const[e,t,i]=s.split("_");r=+t,l=+i}else o=s.toPeerId();t.addEventListener("click",(()=>{p(t)})),this.inputSearch.container.append(t),this.inputSearch.onChange(this.inputSearch.value=""),a.push(t),d()})),n.nav.parentElement.append(c);const h=(e,t)=>{const s=document.createElement("div");s.classList.add("selector-user");const i=document.createElement("avatar-element");return i.classList.add("selector-user-avatar","tgico"),i.setAttribute("dialog","1"),i.classList.add("avatar-30"),s.dataset.key=""+e,e.isPeerId()?(void 0===t&&(t=new St.Z({peerId:e.toPeerId()}).element),i.setAttribute("peer",""+e)):i.classList.add("tgico-calendarfilter"),t&&("string"==typeof t?s.innerHTML=t:((0,T.Z)(s,t),s.append(t))),s.insertAdjacentElement("afterbegin",i),s},p=e=>{0===e.dataset.key.indexOf("date_")?r=l=0:o="".toPeerId(),e.remove(),(0,z.Z)(a,e),setTimeout((()=>{d(),this.inputSearch.onChange(this.inputSearch.value)}),0)};this.inputSearch.onClear=()=>{a.forEach((e=>{p(e)}))},this.inputSearch.onChange=e=>{if(n.cleanupHTML(),n.setQuery({peerId:o,folderId:o?void 0:0,query:e,minDate:r,maxDate:l}),n.load(!0),c.innerHTML="",n.nav.classList.remove("hide"),!o&&e.trim()){const t=n.middleware.get();Promise.all([i.Z.getConversations(e).promise.then((({dialogs:e})=>e.map((e=>e.peerId)))),E.Z.getContactsPeerIds(e,!0)]).then((e=>{t()&&(new Set(e[0].concat(e[1])).forEach((e=>{c.append(h(e))})),n.nav.classList.toggle("hide",!!c.innerHTML))}))}if(!r&&e.trim()){const t=[];(0,ie.fl)(e,t),t.forEach((e=>{c.append(h("date_"+e.minDate+"_"+e.maxDate,e.title))})),n.nav.classList.toggle("hide",!!c.innerHTML)}},n.tabs.inputMessagesFilterEmpty.addEventListener("mousedown",(e=>{const t=(0,ft.Z)(e.target,"LI");if(!t)return;const s=(0,Me.Z)(t,"search-group");if(!s||s.classList.contains("search-group-recent")||s.classList.contains("search-group-people"))return;const i=t.getAttribute("data-peer-id").toPeerId();M.default.getState().then((e=>{const t=e.recentSearch||[];if(t[0]!==i){(0,z.Z)(t,i),t.unshift(i),t.length>20&&(t.length=20),M.default.pushToState("recentSearch",t);for(const e of t)M.default.requestPeer(e,"recentSearch")}}))}),{capture:!0});let u=document.createElement("div");u.classList.add("search-group-scrollable"),u.append(this.searchGroups.people.list),this.searchGroups.people.container.append(u),new P.v7(u);let g,m=!0;const v=(0,D.v)(e.parentElement,"zoom-fade",150,(e=>{g&&clearTimeout(g),0!==e||m||(n.selectTab(0,!1),this.inputSearch.onClearClick(),g=window.setTimeout((()=>{g=0,this.newBtnMenu.classList.remove("is-hidden"),this.hasUpdate&&this.updateBtn.classList.remove("is-hidden")}),150)),m=!1}));v(0);const f="is-visible",b=()=>{this.toolsBtn.classList.remove(f),this.backBtn.classList.add(f),this.newBtnMenu.classList.add("is-hidden"),this.updateBtn.classList.add("is-hidden"),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!0),ne.IS_MOBILE_SAFARI||F.Z.findItemByType("global-search")||F.Z.pushItem({onPop:()=>{s()},type:"global-search"}),v(1)};this.inputSearch.input.addEventListener("focus",b),b(),this.backBtn.addEventListener("click",(e=>{this.toolsBtn.classList.add(f),this.backBtn.classList.remove(f),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!1),F.Z.removeByType("global-search"),v(0)}));const y=N("close");this.searchGroups.recent.nameEl.append(y),y.addEventListener("click",(()=>{on({descriptionLangKey:"Search.Confirm.ClearHistory",button:{langKey:"ClearButton",isDanger:!0}}).then((()=>{M.default.getState().then((e=>{this.searchGroups.recent.clear();const t=e.recentSearch||[];for(const e of t)M.default.releaseSinglePeer(e,"recentSearch");t.length=0,M.default.pushToState("recentSearch",t)}))}))}))}};re.GO.appSidebarLeft=kn;const xn=kn;class An{constructor(e){this.chat=e,this.bubbles=[],this.detailsMap=new Map,this.groups=[],this.newGroupDiff=121}removeBubble(e){const t=this.detailsMap.get(e);t&&(t.group.length&&(t.group.findAndSplice((t=>t.bubble===e)),t.group.length?this.updateGroup(t.group):(0,z.Z)(this.groups,t.group)),this.detailsMap.delete(e))}changeBubbleMid(e,t){const s=this.detailsMap.get(e);s&&(s.mid=t)}addBubble(e,t,s){const i=t.date,n=t.mid;let o,r=t.viaBotId||t.fromId;r===a.default.myId&&t.peerId===a.default.myId&&t.fwdFromId===r&&(r=r.toPeerId(!0)),this.removeBubble(e);const l={bubble:e,mid:n,timestamp:i};if(this.bubbles.length){let e,t=-1;for(let e=0;e<this.bubbles.length;++e){const s=this.bubbles[e],a=Math.abs(s.timestamp-i);if(s.fromId===r&&a<=this.newGroupDiff){if(t=e,"scheduled"===this.chat.type)break}else t=-1;if("scheduled"!==this.chat.type&&n>s.mid)break}if(-1!==t&&(e=this.bubbles[t]),e){o=e.group;let t=0,s=0;for(;t<o.length;++t){const e=o[t].timestamp,a=o[t].mid;if(i<e)break;if(i===e&&(s=a),s&&n<s)break}o.splice(t,0,l)}else this.groups.push(o=[l])}else this.groups.push(o=[l]);const d={timestamp:i,fromId:r,mid:t.mid,group:o};let c=0;for(;c<this.bubbles.length&&!(this.bubbles[c].mid<n);++c);this.bubbles.splice(c,0,{timestamp:i,fromId:r,mid:t.mid,group:o}),this.updateGroup(o),this.detailsMap.set(e,d)}updateGroup(e){if(!e.length)return;const t=e[0].bubble;if(1===e.length)return void t.classList.add("is-group-first","is-group-last");t.classList.remove("is-group-last"),t.classList.add("is-group-first");const s=e.length-1;for(let t=1;t<s;++t)e[t].bubble.classList.remove("is-group-last","is-group-first");const i=e[e.length-1].bubble;i.classList.remove("is-group-first"),i.classList.add("is-group-last")}updateGroupByMessageId(e){const t=this.bubbles.find((t=>t.mid===e));t&&this.updateGroup(t.group)}cleanup(){this.bubbles=[],this.groups=[],this.detailsMap.clear()}}class _n extends pt.Z{constructor(e,t,s={}){if(super("popup-date-picker",s.noButtons?[]:[{langKey:"JumpToDate",callback:()=>{this.onPick&&this.onPick(this.selectedDate.getTime()/1e3|0)}},{langKey:"Cancel",isCancel:!0}],Object.assign({body:!0,overlayClosable:!0},s)),this.onPick=t,this.options=s,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 s=+t.dataset.timestamp;this.selectedDate=new Date(s),this.setTitle(),this.setTimeTitle()},this.minDate=s.minDate||new Date("2013-08-01T00:00:00"),e<this.minDate&&e.setFullYear(this.minDate.getFullYear(),this.minDate.getMonth(),this.minDate.getDate()),this.controlsDiv=document.createElement("div"),this.controlsDiv.classList.add("date-picker-controls"),this.prevBtn=document.createElement("button"),this.prevBtn.classList.add("btn-icon","tgico-down","date-picker-prev"),(0,l.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,l.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,l.fc)(this.monthsContainer,this.onDateClick,{listenerSetter:this.listenerSetter}),this.body.append(this.controlsDiv,this.monthsContainer),s.withTime){this.timeDiv=document.createElement("div"),this.timeDiv.classList.add("date-picker-time");const t=document.createElement("div");t.classList.add("date-picker-time-delimiter"),t.append(":");const s=(e,t,s,i)=>{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&&i&&i(+o[1]),o="0"+o[0]),t.setValueSilently(o),s(o.length)}))};this.hoursInputField=new _.Z({plainText:!0}),this.minutesInputField=new _.Z({plainText:!0}),s(23,this.hoursInputField,(e=>{2===e&&this.minutesInputField.input.focus(),this.setTimeTitle()}),(e=>{this.minutesInputField.value=(e+this.minutesInputField.value).slice(0,2)})),s(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,l.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 i=document.createElement("div");i.classList.add("popup-centerer"),i.append(this.container),this.element.append(i),e.setHours(0,0,0,0),this.selectedDate=e,this.maxDate=s.maxDate||new Date,this.maxDate.setHours(0,0,0,0),this.selectedMonth=new Date(this.selectedDate),this.selectedMonth.setDate(1),this.maxMonth=new Date(this.maxDate),this.maxMonth.setDate(1),this.minMonth=new Date(this.minDate),this.minMonth.setHours(0,0,0,0),this.minMonth.setDate(1),this.selectedMonth.getTime()===this.minMonth.getTime()&&this.prevBtn.setAttribute("disabled","true"),this.selectedMonth.getTime()===this.maxMonth.getTime()&&this.nextBtn.setAttribute("disabled","true"),s.noTitle&&(this.setTitle=()=>{}),this.setTimeTitle(),this.setTitle(),this.setMonth()}setTimeTitle(){if(this.btnConfirm&&this.selectedDate){let e,t=[];const s=new Date;s.setHours(0,0,0,0);const i={minute:"2-digit",hour:"2-digit"},n=new Date(this.selectedDate.getTime());if(n.setHours(+this.hoursInputField.value,+this.minutesInputField.value),this.selectedDate.getTime()===s.getTime())e="Schedule.SendToday";else{e="Schedule.SendDate";const i={month:"short",day:"numeric"};n.getFullYear()!==s.getFullYear()&&(i.year="numeric"),t.push(new k.default.IntlDateElement({date:n,options:i}).element)}t.push(new k.default.IntlDateElement({date:n,options:i}).element),this.btnConfirm.firstChild.replaceWith((0,k.i18n)(e,t))}}setTitle(){this.title.textContent="",this.title.append(new k.default.IntlDateElement({date:this.selectedDate,options:{day:"numeric",month:"long",weekday:"short"}}).element)}renderElement(e,t=""){const s=document.createElement("button");return s.classList.add("btn-icon","date-picker-month-date"),e&&s.setAttribute("disabled","true"),t&&s.append(t),s}setMonth(){const e=new Date(this.selectedMonth),t={year:"numeric",month:this.timeDiv&&v.ZP.isMobile?"short":"long"};this.monthTitle.textContent="",this.monthTitle.append(new k.default.IntlDateElement({date:e,options:t}).element),this.month&&this.month.remove(),this.month=document.createElement("div"),this.month.classList.add("date-picker-month");const s=new Date,i=s.getDay();1!==i&&s.setHours(-24*(i-1));for(let e=0;e<7;++e){const e=this.renderElement(!0,new k.default.IntlDateElement({date:s,options:{weekday:"narrow"}}).element);e.classList.remove("date-picker-month-date"),e.classList.add("date-picker-month-day"),this.month.append(e),s.setDate(s.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(),s=this.renderElement(e>this.maxDate||e<this.minDate,""+t);s.dataset.timestamp=""+e.getTime(),e.getTime()===this.selectedDate.getTime()&&(this.selectedEl=s,s.classList.add("active")),this.month.append(s),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)}}const Zn="stacked-avatars";class Dn{constructor(e){this.lazyLoadQueue=e.lazyLoadQueue,this.avatarSize=e.avatarSize,this.container=document.createElement("div"),this.container.classList.add(Zn),this.container.style.setProperty("--avatar-size",e.avatarSize+"px")}render(e,t){const s=this.container.children;(e=e.slice().reverse()).length>3&&(e=e.slice(-3)),e.forEach(((e,i)=>{let n=s[i];n||(n=document.createElement("div"),n.classList.add("stacked-avatars-avatar-container"));let a=n.firstElementChild;a||(a=new Yl,a.setAttribute("dialog","0"),a.classList.add("avatar-"+this.avatarSize,"stacked-avatars-avatar"),a.lazyLoadQueue=this.lazyLoadQueue,a.loadPromises=t),a.setAttribute("peer",""+e),a.parentNode||n.append(a),n.parentNode||this.container.append(n)})),Array.from(s).slice(e.length).forEach((e=>e.remove()))}}class Fn extends HTMLElement{constructor(){super(),this.classList.add("reaction")}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 s=this.reactionCount;if(!e&&!t){const e=_t.Z.getReaction(s.reaction);(0,Nt.Z)(e,(e=>{var t;e.center_icon||this.stickerContainer.classList.add("is-static"),e.pFlags.inactive&&this.classList.add("is-inactive");const s="inline"===this.type?14:22,i=this.wrapStickerPromise=Is({div:this.stickerContainer,doc:null!==(t=e.center_icon)&&void 0!==t?t:e.static_icon,width:s,height:s,static:!0}).finally((()=>{this.wrapStickerPromise===i&&(this.wrapStickerPromise=void 0)}))}))}}renderCounter(){var e;const t=this.reactionCount,s="inline"===this.type?2:4;if(t.count>=s||"block"===this.type&&!this.canRenderAvatars){this.counter||(this.counter=document.createElement("inline"===this.type?"i":"span"),this.counter.classList.add("reaction-counter"));const e=Cn(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 Dn({avatarSize:24}),this.append(this.stackedAvatars.container)),this.stackedAvatars.render(e.map((e=>o.Z.getPeerId(e.peer_id))))))}setIsChosen(e=!!this.reactionCount.pFlags.chosen){"inline"!==this.type&&(this.classList.contains("is-chosen")&&!this.classList.contains("backwards"))!==e&&(0,Jt.Z)(this,"is-chosen",e,this.isConnected?300:0)}fireAroundAnimation(){(0,Nt.Z)(_t.Z.getReaction(this.reactionCount.reaction),(e=>{const t="inline"===this.type?28:40,s=document.createElement("div");s.classList.add("reaction-sticker-activate"),Promise.all([Is({div:s,doc:e.center_icon,width:t,height:t,withThumb:!1,needUpscale:!0,play:!1,skipRatio:1,group:"none",needFadeIn:!1}),Ls({doc:e.around_animation,size:80,target:this.stickerContainer,side:"center",skipRatio:1,play:!1}).stickerPromise]).then((([e,t])=>{const i=()=>{(0,De.T2)((()=>{e.remove(),s.remove(),this.stickerContainer.classList.remove("has-animation")}))};e.addEventListener("enterFrame",(t=>{t===e.maxFrame&&(this.wrapStickerPromise?this.wrapStickerPromise.then((()=>{setTimeout(i,1e3)})):i())})),e.addEventListener("firstFrame",(()=>{this.stickerContainer.append(s),this.stickerContainer.classList.add("has-animation"),e.play(),t.play()}),{once:!0})}))}))}}customElements.define("reaction-element",Fn);const Rn=new Map;class Bn extends HTMLElement{constructor(){super(),this.classList.add("reactions"),this.sorted=[]}connectedCallback(){let e=Rn.get(this.key);e||Rn.set(this.key,e=new Set),e.add(this),this.onConnectCallback&&this.isConnected&&(this.onConnectCallback(),this.onConnectCallback=void 0)}disconnectedCallback(){const e=Rn.get(this.key);e.delete(this),e.size||Rn.delete(this.key)}getReactionCount(e){return this.sorted[this.sorted.indexOf(e)].reactionCount}getMessage(){return this.message}init(e,t,s){void 0!==this.key&&this.disconnectedCallback(),this.message=e,this.key=this.message.peerId+"_"+this.message.mid,this.isPlaceholder=s,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,s=!(!t||!t.results.length);if(this.classList.toggle("has-no-reactions",!s),!s&&!this.sorted.length)return;const i=_t.Z.getAvailableReactions(),n=s?i instanceof Promise?t.results:t.results.filter((e=>_t.Z.isReactionActive(e.reaction))):[];(0,b.Z)(this.sorted,((e,t,s)=>{const i=e.reactionCount.reaction;n.some((e=>e.reaction===i))||(s.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,s)=>{const i=this.sorted.findIndex((t=>t.reactionCount.reaction===e.reaction));let n=-1!==i&&this.sorted[i];n||(n=new Fn,n.init(this.type)),Zs(n,this,s);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===a.default.peerId&&e.forEach((e=>{const t=this.sorted.find((t=>t.reactionCount.reaction===e.reaction));t&&t.fireAroundAnimation()}))}}customElements.define("reactions-element",Bn);a.default.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 Un extends HTMLElement{constructor(){super(),this.updated=!1}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 Dn({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=>o.Z.getPeerId(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 k.default.IntlElement);const s=this.text;if(e?e.replies?s.compareAndUpdate({key:"Comments",args:[e.replies]}):s.compareAndUpdate({key:"LeaveAComment"}):s.compareAndUpdate({key:"ViewInChat"}),e){let 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 i=this.children[1];if(!i){i=document.createElement("span"),i.classList.add("replies-footer-text");const e=document.createElement("span");e.classList.add("tgico-next");const t=document.createElement("div");(0,ee.ripple)(t),this.append(i,e,t)}(0,T.Z)(i,s.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)?Cn(e.replies,0):""}</span>`;!e||this.updated||this.message.pFlags.is_outgoing||(i.Z.subscribeRepliesThread(this.message.peerId,this.message.mid),i.Z.updateMessage(this.message.peerId,this.message.mid,"replies_updated"),this.updated=!0),this.loadPromises&&(this.loadPromises=void 0)}}customElements.define("replies-element",Un);const Nn=()=>{const e=document.createElement("i");return e.classList.add("edited"),(0,k._i18n)(e,"EditedMessage"),e},On=()=>(0,k.i18n)("SponsoredMessage");var Hn;!function(e){e.setTime=e=>{var t;const{chatType:s,message:n}=e,a=new Date(1e3*n.date),o=[];let r,l,d,c;const h=!!n.pFlags.sponsored,p=!("action"in n)&&!h;let u,g=h?void 0:(0,ie.mr)(a);if(p){if(n.views){const e=n.post_author||(null===(t=n.fwd_from)||void 0===t?void 0:t.post_author),s=document.createElement("span");s.classList.add("post-views"),s.innerHTML=Cn(n.views,1);const i=document.createElement("i");if(i.classList.add("tgico-channelviews","time-icon"),o.push(s,i),e){const t=document.createElement("span");t.innerHTML=Q.Z.wrapEmojiText(e)+",&nbsp;",o.push(t)}}if(n.edit_date&&"scheduled"!==s&&!n.pFlags.edit_hide&&o.unshift(r=Nn()),"pinned"!==s&&n.pFlags.pinned){const e=document.createElement("i");e.classList.add("tgico-pinnedchat","time-icon"),o.unshift(e)}"peerUser"===n.peer_id._&&(u=!0,c=i.Z.getGroupsFirstMessage(n),d=new Bn,d.init(c,"inline",!0),d.render(),o.unshift(d))}else h&&o.push(l=On());g&&o.push(g);let m=h?void 0:(0,ie.xE)(a);p&&(m+=(n.edit_date&&!n.pFlags.edit_hide?`\nEdited: ${(0,ie.xE)(new Date(1e3*n.edit_date))}`:"")+(n.fwd_from?`\nOriginal: ${(0,ie.xE)(new Date(1e3*n.fwd_from.date))}`:""));const v=document.createElement("span");v.classList.add("time","tgico"),v.append(...o);const f=document.createElement("div");f.classList.add("inner","tgico"),m&&(f.title=m);let b=o;if(r&&(b[b.indexOf(r)]=Nn()),l&&(b[b.indexOf(l)]=On()),d){const e=b[b.indexOf(d)]=new Bn;e.init(c,"inline"),e.render()}return b=b.map((e=>e instanceof HTMLElement&&!e.classList.contains("i18n")&&!e.classList.contains("reactions")?e.cloneNode(!0):e)),g&&(b[b.length-1]=(0,ie.mr)(a)),f.append(...b),v.append(f),v},e.renderReplies=({bubble:e,bubbleContainer:t,message:s,messageDiv:i,loadPromises:n,lazyLoadQueue:a})=>{const o=!e.classList.contains("sticker")&&!e.classList.contains("emoji-big")&&!e.classList.contains("round"),r=new Un;return r.message=s,r.type=o?"footer":"beside",r.loadPromises=n,r.lazyLoadQueue=a,r.init(),t.prepend(r),o},e.setReply=({chat:e,bubble:t,bubbleContainer:s,message:i})=>{const n=!s;n&&(s=t.querySelector(".bubble-content"));const a=n?s.querySelector(".reply"):null;if(!i.reply_to_mid)return a&&a.remove(),void t.classList.remove("is-reply");const o=i.reply_to.reply_to_peer_id?e.appPeersManager.getPeerId(i.reply_to.reply_to_peer_id):e.peerId;let r,l=e.appMessagesManager.getMessageByPeer(o,i.reply_to_mid);"messageEmpty"===l._?(e.appMessagesManager.wrapSingleMessage(o,i.reply_to_mid),e.bubbles.needUpdate.push({replyToPeerId:o,replyMid:i.reply_to_mid,mid:i.mid}),r=(0,k.i18n)("Loading")):r=new St.Z({peerId:l.fromId||l.fwdFromId,dialog:!1,onlyFirstName:!1,plainText:!1}).element;const d=Ps(r,void 0,l);a?a.replaceWith(d):s.append(d),t.classList.add("is-reply")}}(Hn||(Hn={}));var zn=s(5393);function Vn(e,t,s){const i=e.getBoundingClientRect(),n="center"===s?Math.ceil(i.left+(i.right-i.left)/2+1):Math.ceil(i.left+1),a="bottom"===t?Math.floor(i.top+i.height-1):Math.ceil(i.top+1);return document.elementFromPoint(n,a)}function jn(e){e.style.display="none",e.offsetLeft,e.style.display=""}re.GO.getElementByPoint=Vn;class Gn{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,s=t.target.parentElement,i=t.rootBounds;e.bottom<i.top&&this.handler(!0,s),e.bottom>=i.top&&e.bottom<i.bottom&&this.handler(!1,s)}}),{threshold:0,root:this.container})}observeElements(){this.elementsObserver=new IntersectionObserver((e=>{let t=e.filter((e=>e.boundingClientRect.top<0)).sort(((e,t)=>e.boundingClientRect.top-t.boundingClientRect.top))[0];if(!t)return;let s=t.isIntersecting?t.target:t.target.nextElementSibling;this.handler(!0,s)}),{root:this.container})}addSentinel(e,t){const s=document.createElement("div");return s.classList.add("sticky_sentinel",t),e.appendChild(s)}observeStickyHeaderChanges(e){const t=this.addSentinel(e,"sticky_sentinel--top");this.headersObserver.observe(t),this.elementsObserver.observe(e)}disconnect(){this.headersObserver.disconnect(),this.elementsObserver.disconnect()}unobserve(e,t){this.elementsObserver.unobserve(e),this.headersObserver.unobserve(t)}}var Kn=s(5418),Wn=s(5880),qn=s(946),$n=s(7381),Qn=s(7922);const Yn={keywords:{},version:0,langCode:wn.Z.langPackCode};class Xn{constructor(){this.keywordLangPacks={},this.indexedLangPacks={},this.getKeywordsPromises={}}getEmojiKeywords(e=wn.Z.langPackCode){const t=this.getKeywordsPromises[e];if(t)return t;const s="emojiKeywords_"+e;return this.getKeywordsPromises[e]=Qn.Z.get(s).then((t=>((0,Wn.Z)(t)||(t={}),(0,qn.Z)(Yn,t),t.langCode=e,this.keywordLangPacks[e]=t,ct.Z.invokeApi("messages.getEmojiKeywordsDifference",{lang_code:t.langCode,from_version:t.version}).then((e=>{t.version=e.version;const i=t.keywords,n=e.keywords;for(let e=0,t=n.length;e<t;++e){const{keyword:t,emoticons:s}=n[e];i[t]=s}return Qn.Z.set({[s]:t}),t}),(()=>t)))))}getBothEmojiKeywords(){const e=[this.getEmojiKeywords()];return k.default.lastRequestedLangCode!==wn.Z.langPackCode&&e.push(this.getEmojiKeywords(k.default.lastRequestedLangCode)),this.recent||e.push(this.getRecentEmojis()),Promise.all(e)}indexEmojis(){this.index||(this.index=new $n.Z(void 0,2));for(const e in this.keywordLangPacks){if(this.indexedLangPacks[e])continue;const t=this.keywordLangPacks[e].keywords;for(const e in t){const s=t[e];this.index.indexObject(s,e)}this.indexedLangPacks[e]=!0}}searchEmojis(e){let t;if(this.indexEmojis(),(e=e.toLowerCase().replace(/_/g," ")).trim()){const s=this.index.search(e);t=Array.from(s).reduce(((e,t)=>e.concat(t)),[])}else t=this.recent.concat(Xn.POPULAR_EMOJI).slice(0,36);return t=Array.from(new Set(t)),t}getRecentEmojis(){return this.getRecentEmojisPromise?this.getRecentEmojisPromise:this.getRecentEmojisPromise=M.default.getState().then((e=>this.recent=Array.isArray(e.recentEmoji)?e.recentEmoji:[]))}pushRecentEmoji(e){e=Q.Z.fixEmoji(e),this.getRecentEmojis().then((t=>{(0,z.Z)(t,e),t.unshift(e),t.length>36&&(t.length=36),M.default.pushToState("recentEmoji",t),a.default.dispatchEvent("emoji_recent",e)}))}}Xn.POPULAR_EMOJI=["😂","😘","❤️","😍","😊","😁","👍","☺️","😔","😄","😭","💋","😒","😳","😜","🙈","😉","😃","😢","😝","😱","😡","😏","😞","😅","😚","🙊","😌","😀","😋","😆","👌","😐","😕"];const Jn=new Xn;re.GO&&(re.GO.appEmojiManager=Jn);const ea=Jn;var ta=s(6718),sa=s(9976);const ia=new Set;function na(e,t,s=!1,i=!1){const n=document.createElement("span");let o;if(n.classList.add("super-emoji"),i&&!sa.Z?o=Q.o.wrapSingleEmoji(e):(e=Q.o.fixEmoji(e),o=Q.o.wrapEmojiText(e)),n.innerHTML=o,n.children.length>1){const e=n.firstElementChild;n.innerHTML="",n.append(e)}if(n.firstElementChild&&!sa.Z){const e=n.firstElementChild,t=e.src;if(!ia.has(t)){e.setAttribute("loading","lazy");const s=document.createElement("span");s.classList.add("emoji-placeholder"),a.default.settings.animationsEnabled&&(e.style.opacity="0",s.style.opacity="1"),e.addEventListener("load",(()=>{(0,De.T2)((()=>{a.default.settings.animationsEnabled&&(e.style.opacity="",s.style.opacity=""),n.classList.remove("empty"),ia.add(t)}))}),{once:!0}),n.append(s)}}s?t.prepend(n):t.appendChild(n)}function aa(e){return(0,Me.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 oa{constructor(){this.closeScrollTop=0,this.onContentClick=e=>{(0,d.d)(e);const t=aa(e.target);t&&(Ol.chat.input.onEmojiSelected(t,!1),ce.IS_TOUCH_SUPPORTED&&(0,Gs.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={},s=new Map([["Emoji.Recent",[]]]);for(const t in ta.ZP.Emoji){const i=""+ta.ZP.Emoji[t],n=e[+i[0]-1];if(!n)continue;let a=s.get(n);a||(a=[],s.set(n,a)),a[+i.slice(1)||0]=t}s.delete(e.pop()),s.forEach(((e,s)=>{const i=document.createElement("div");i.classList.add("emoji-category");const n=document.createElement("div");n.classList.add("category-title"),n.append((0,k.i18n)(s));const a=document.createElement("div");a.classList.add("super-emojis"),i.append(n,a),e.forEach((e=>{na((0,te.zu)(e),a,!1)})),t[s]=i}));const i=this.menu=this.content.previousElementSibling,n=this.scroll=new P.ZP(this.content,"EMOJI"),o=(0,J.y7)(this.content,!0);Promise.all([(0,Kn.w)(200),ea.getRecentEmojis().then((e=>{const t=!!e.length,s=t?0:1;this.menu.children[0].classList.toggle("hide",!t),this.menu.children[s].classList.add("active");const a=wa.menuOnClick(i,n,void 0,s);return this.stickyIntersector=a.stickyIntersector,this.setMenuActive=a.setActive,e}))]).then((([s,i])=>{o.remove(),this.recentItemsDiv=t["Emoji.Recent"].querySelector(".super-emojis");for(const e of i)na(e,this.recentItemsDiv);this.recentItemsDiv.parentElement.classList.toggle("hide",!this.recentItemsDiv.childElementCount),e.unshift("Emoji.Recent"),e.map((e=>{const s=t[e];return s||console.error("no div by category:",e),n.container.append(s),this.stickyIntersector.observeStickyHeaderChanges(s),s}))})),this.content.addEventListener("click",this.onContentClick),this.init=null,a.default.addEventListener("emoji_recent",(e=>{const t=Array.from(this.recentItemsDiv.children);for(let s=0,i=t.length;s<i;++s){const i=t[s];if(e===Q.o.fixEmoji(aa(i))){if(0===s)return;i.remove()}}na(e,this.recentItemsDiv,!0),this.recentItemsDiv.parentElement.classList.remove("hide"),this.menu.children[0].classList.remove("hide"),this.closeScrollTop||this.setMenuActive(0)})),Ca.addEventListener("close",(()=>{this.closeScrollTop=this.scroll.scrollTop}))}onClose(){}}var ra=s(9897);const la=100;class da{constructor(e,t,s,i=!0){this.element=e,this.group=t,this.scrollable=s,this.scrollPromise=Promise.resolve(),this.timeout=0,this.onScroll=()=>{this.timeout?clearTimeout(this.timeout):this.scrollPromise=(0,se.b)(),this.timeout=window.setTimeout((()=>{this.timeout=0,this.scrollPromise.resolve()}),150)},this.processInvisibleDiv=e=>this.scrollPromise.then((()=>{return t=this,s=void 0,n=function*(){if(this.lazyLoadQueue.intersector.isVisible(e))return;const t=e.querySelector("video"),s=e.querySelector("img");s&&(s&&s.classList.remove("hide"),yield(0,De.d1)()),!this.lazyLoadQueue.intersector.isVisible(e)&&t&&(t.remove(),t.src="",t.load(),I.Z.getAnimations(t).forEach((e=>{I.Z.checkAnimation(e,!0,!0)})))},new((i=void 0)||(i=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 s;t.done?e(t.value):(s=t.value,s instanceof i?s:new i((function(e){e(s)}))).then(o,r)}l((n=n.apply(t,s||[])).next())}));var t,s,i,n})),this.lazyLoadQueue=new X.br(void 0,((e,t)=>{t?this.processVisibleDiv(e):this.processInvisibleDiv(e)})),i&&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,s=L.Z.getDoc(t);return this.scrollPromise.then((()=>{const t=ys({doc:s,container:e,lazyLoadQueue:null,group:this.group,noInfo:!0}).loadPromise;return t.finally((()=>{const t=e.querySelector("video");e.style.opacity="";const s=e.querySelector("img");s&&s.classList.add("hide"),t&&!t.parentElement&&setTimeout((()=>{t.src="",t.load(),I.Z.getAnimations(t).forEach((e=>{I.Z.checkAnimation(e,!0,!0)}))}),0),this.lazyLoadQueue.intersector.isVisible(e)||this.processInvisibleDiv(e)})),t}))}})}add(e,t=this.element){var s;let i=e.w,n=e.h;n<la&&(i*=la/n,n=la);const a=Math.min(300,400,i),o=(0,ra.Z)(i,n,a,la),r=document.createElement("div");r.classList.add("gif","fade-in-transition"),r.style.width=o.width+"px",r.style.opacity="0",r.dataset.docId=""+e.id,t.append(r),this.lazyLoadQueue.observe(r);const l=L.Z.getThumb(e,!1);let d;l&&(d=new Image,d.classList.add("media-poster"),l.cacheContext.url||l.promise.then((()=>{d.src=l.cacheContext.url})));const c=()=>{d&&(r.append(d),r.style.opacity="")};(null===(s=null==l?void 0:l.cacheContext)||void 0===s?void 0:s.url)?(0,rs.ZP)(d,l.cacheContext.url,c):c()}}class ca{init(){this.content=document.getElementById("content-gifs");const e=this.content.firstElementChild;e.addEventListener("click",wa.onMediaClick);const t=new P.ZP(this.content,"GIFS"),s=new da(e,ya,t),i=(0,J.y7)(this.content,!0);ct.Z.invokeApi("messages.getSavedGifs",{hash:"0"}).then((e=>{"messages.savedGifs"===e._&&e.gifs.forEach(((t,i)=>{e.gifs[i]=t=L.Z.saveDoc(t),s.add(t)})),i.remove()})),Ca.addLazyLoadQueueRepeat(s.lazyLoadQueue,s.processInvisibleDiv),this.init=null}onClose(){}}class ha{constructor(e,t){this.regularLazyLoadQueue=e,this.group=t,this.animatedDivs=new Set,this.checkAnimationContainer=(e,t)=>{I.Z.getAnimations(e).forEach((e=>{t?I.Z.checkAnimation(e,!1):I.Z.checkAnimation(e,!0,!0)}))},this.processVisibleDiv=e=>{const t=e.dataset.docId,s=L.Z.getDoc(t),i=v.ZP.active.esgSticker.width,n=Is({doc:s,div:e,width:i,height:i,lazyLoadQueue:null,group:this.group,onlyThumb:!1,play:!0,loop:!0});return n.then((()=>{this.checkAnimationContainer(e,this.lazyLoadQueue.intersector.isVisible(e))})),n},this.processInvisibleDiv=e=>{const t=e.dataset.docId,s=L.Z.getDoc(t);this.checkAnimationContainer(e,!1),e.innerHTML="",this.renderSticker(s,e)},this.lazyLoadQueue=new X.dJ(void 0,((e,t)=>{t||this.processInvisibleDiv(e)}))}clear(){this.lazyLoadQueue.clear()}renderSticker(e,t,s){return t||((t=document.createElement("div")).classList.add("grid-item","super-sticker"),e.animated&&this.observeAnimatedDiv(t)),Is({doc:e,div:t,lazyLoadQueue:this.regularLazyLoadQueue,group:this.group,onlyThumb:e.animated,loadPromises:s}),t}observeAnimatedDiv(e){this.animatedDivs.add(e),this.lazyLoadQueue.observe({div:e,load:this.processVisibleDiv})}}class pa{constructor(){this.stickerSets={},this.recentStickers=[],this.mounted=!1,this.queueCategoryPush=[]}categoryPush(e,t="",s,i){const n=document.createElement("div");n.classList.add("category-items","super-stickers");const a=document.createElement("div");return a.classList.add("category-title"),t&&(a.innerHTML=t),e.append(a,n),this.stickyIntersector.observeStickyHeaderChanges(e),this.queueCategoryPush.push({element:e,prepend:i}),s.then((e=>{e.forEach((e=>{n.append(this.superStickerRenderer.renderSticker(e))})),this.queueCategoryPush.length&&(this.queueCategoryPush.forEach((({element:e,prepend:t})=>{t?this.recentDiv.parentElement?(this.stickersDiv.prepend(e),this.stickersDiv.prepend(this.recentDiv)):this.stickersDiv.prepend(e):this.stickersDiv.append(e)})),this.queueCategoryPush.length=0)})),{titleDiv:a}}renderStickerSet(e,t=!1){return s=this,i=void 0,a=function*(){const s=document.createElement("div");s.classList.add("sticker-category"),s.dataset.id=""+e.id,s.dataset.access_hash=""+e.access_hash;const i=document.createElement("button");i.classList.add("btn-icon","menu-horizontal-div-item"),this.stickerSets[e.id]={stickers:s,tab:i},t?this.menu.insertBefore(i,this.menu.firstElementChild.nextSibling):this.menu.append(i);const n=ds.Z.getStickerSet(e);this.categoryPush(s,Q.o.wrapEmojiText(e.title),n.then((e=>e.documents)),t),yield n,Ms({set:e,container:i,group:ya,lazyLoadQueue:wa.lazyLoadQueue,width:32,height:32,autoplay:!1})},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 s;t.done?e(t.value):(s=t.value,s instanceof n?s:new n((function(e){e(s)}))).then(o,r)}l((a=a.apply(s,i||[])).next())}));var s,i,n,a}init(){this.content=document.getElementById("content-stickers"),this.recentDiv=document.createElement("div"),this.recentDiv.classList.add("sticker-category","stickers-recent");let e=this.content.previousElementSibling;this.menu=e.firstElementChild;let t=new P.v7(e);this.stickersDiv=document.createElement("div"),this.stickersDiv.classList.add("stickers-categories"),this.content.append(this.stickersDiv),a.default.addEventListener("stickers_installed",(e=>{const t=e;!this.stickerSets[t.id]&&this.mounted&&this.renderStickerSet(t,!0)})),a.default.addEventListener("stickers_deleted",(e=>{const t=e;if(this.stickerSets[t.id]&&this.mounted){const e=this.stickerSets[t.id];e.stickers.remove(),e.tab.remove(),delete this.stickerSets[t.id]}})),this.stickersDiv.addEventListener("click",(e=>{const t=e.target;if((0,Me.Z)(t,"category-title")){const e=(0,wt.Z)(t,"data-id");new Ki({id:e.dataset.id,access_hash:e.dataset.access_hash}).show()}else wa.onMediaClick(e)}));const s=(e=!1)=>{a.default.dispatchEvent("choosing_sticker",!e)};this.scroll=new P.ZP(this.content,"STICKERS"),this.scroll.setVirtualContainer(this.stickersDiv),this.scroll.onAdditionalScroll=()=>{s()},Ca.addEventListener("closed",(()=>{s(!0)})),Ca.addEventListener("opened",(()=>{s()})),this.stickyIntersector=wa.menuOnClick(this.menu,this.scroll,t).stickyIntersector;const i=(0,J.y7)(this.content,!0);Promise.all([ds.Z.getRecentStickers().then((e=>{this.recentStickers=e.stickers.slice(0,20),this.stickerSets.recent={stickers:this.recentDiv,tab:this.menu.firstElementChild},i.remove();const{titleDiv:t}=this.categoryPush(this.recentDiv,"",Promise.resolve(this.recentStickers),!0);t.append((0,k.i18n)("Stickers.Recent"))})),ds.Z.getAllStickers().then((e=>{i.remove();for(let t of e.sets)this.renderStickerSet(t)}))]).finally((()=>{this.mounted=!0,s()})),this.superStickerRenderer=new ha(wa.lazyLoadQueue,ya),Ca.addLazyLoadQueueRepeat(this.superStickerRenderer.lazyLoadQueue,this.superStickerRenderer.processInvisibleDiv),this.init=null}pushRecentSticker(e){var t;if(ds.Z.pushRecentSticker(e),!(null===(t=this.recentDiv)||void 0===t?void 0:t.parentElement))return;let s=this.recentDiv.querySelector(`[data-doc-id="${e.id}"]`);s||(s=this.superStickerRenderer.renderSticker(e));const i=this.recentDiv.querySelector(".category-items");i.prepend(s),i.childElementCount>20&&Array.from(i.children).slice(20).forEach((e=>e.remove()))}onClose(){}}const ua=new class{constructor(){this.inlineResults={},this.setHash={}}getGeoInput(e){return"geoPoint"===e._?{_:"inputGeoPoint",lat:e.lat,long:e.long,accuracy_radius:e.accuracy_radius}:{_:"inputGeoPointEmpty"}}getInlineResults(e,t,s="",i="",n){return ct.Z.invokeApi("messages.getInlineBotResults",{bot:E.Z.getUserInput(t),peer:o.Z.getInputPeerById(e),query:s,geo_point:n?this.getGeoInput(n):void 0,offset:i},{stopTime:-1,noErrorBox:!0}).then((e=>{const t=e.query_id;return e.results.forEach((e=>{"botInlineMediaResult"===e._&&(e.document&&(e.document=L.Z.saveDoc(e.document)),e.photo&&(e.photo=r.Z.savePhoto(e.photo))),this.inlineResults[this.generateQId(t,e.id)]=e})),e}))}generateQId(e,t){return e+"_"+t}pushPopularBot(e){E.Z.getTopPeers("bots_inline").then((t=>{const s=e.toPeerId(),i=t.findIndex((e=>e.id===s));let n;n=-1!==i?t[i]:{id:s,rating:0},++n.rating,(0,Ds.Z)(t,n,"rating"),M.default.setKeyValueToStorage("topPeersCache")}))}switchToPM(e,t,s){return this.setHash[t]={peerId:e,time:Date.now()},a.default.dispatchEvent("history_focus",{peerId:t.toPeerId()}),i.Z.startBot(t,void 0,s)}checkSwitchReturn(e){return t=this,s=void 0,n=function*(){const t=E.Z.getUser(e);if(!t||!t.pFlags.bot||!t.bot_inline_placeholder)return;const s=this.setHash[e];return s&&(delete this.setHash[e],Date.now()-s.time<36e5)?s.peerId:void 0},new((i=void 0)||(i=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 s;t.done?e(t.value):(s=t.value,s instanceof i?s:new i((function(e){e(s)}))).then(o,r)}l((n=n.apply(t,s||[])).next())}));var t,s,i,n}switchInlineQuery(e,t,s,i){a.default.dispatchEvent("history_focus",{peerId:e,threadId:t}),xi.Z.setDraft(e,t,"@"+E.Z.getUser(s).username+" "+i)}callbackButtonClick(e,t,s){return ct.Z.invokeApi("messages.getBotCallbackAnswer",{peer:o.Z.getInputPeerById(e),msg_id:f.Z.getServerMessageId(t),data:s.data},{stopTime:-1,noErrorBox:!0}).then((e=>{"string"==typeof e.message&&e.message.length&&rt(Q.o.wrapRichText(e.message,{noLinks:!0,noLinebreaks:!0}))}))}sendInlineResult(e,t,s,n={}){var a;const o=this.inlineResults[s];if(!o)return;this.pushPopularBot(t);const l=s.split("_"),d=l.shift(),c=l.join("_");if(n.viaBotId=t,n.queryId=d,n.resultId=c,o.send_message.reply_markup&&(n.replyMarkup=o.send_message.reply_markup),"botInlineMessageText"===o.send_message._)n.entities=o.send_message.entities,i.Z.sendText(e,o.send_message.message,n);else{let t,s="";const l=o.send_message;switch(l._){case"botInlineMessageMediaAuto":if(s=l.message,"botInlineMediaResult"===o._){const{document:e,photo:s}=o;t=e?L.Z.getMediaInput(e):r.Z.getMediaInput(s)}break;case"botInlineMessageMediaGeo":t={_:"inputMediaGeoPoint",geo_point:this.getGeoInput(l.geo)},n.geoPoint=l.geo;break;case"botInlineMessageMediaVenue":t={_:"inputMediaVenue",geo_point:this.getGeoInput(l.geo),title:l.title,address:l.address,provider:l.provider,venue_id:l.venue_id,venue_type:l.venue_type},n.geoPoint=l.geo;break;case"botInlineMessageMediaContact":t={_:"inputMediaContact",phone_number:l.phone_number,first_name:l.first_name,last_name:l.last_name,vcard:l.vcard}}t||(t={_:"messageMediaPending",type:o.type,file_name:o.title||(null===(a=o.content)||void 0===a?void 0:a.url)||o.url,size:0,progress:{percent:30,total:0}}),i.Z.sendOther(e,t,n)}}};re.GO&&(re.GO.appInlineBotsManager=ua);const ga=ua;const ma="GIFS-SEARCH";class va extends O{constructor(){super(...arguments),this.nextOffset="",this.loadedAll=!1,this.onGifsClick=e=>{const t=(0,Me.Z)(e.target,"gif");if(!t)return;const s=t.dataset.docId;Ol.chat.input.sendMessageWithDocument(s)?v.ZP.isMobile&&Yt.onCloseBtnClick():console.warn("got no doc by id:",s)}}init(){this.container.id="search-gifs-container",this.inputSearch=new Z("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,l.fc)(this.gifsDiv,this.onGifsClick,{listenerSetter:this.listenerSetter}),this.scrollable.append(this.gifsDiv),this.masonry=new da(this.gifsDiv,ma,this.scrollable)}onClose(){this.scrollable.onScrolledBottom=()=>{}}onCloseAfterTimeout(){return this.reset(),this.gifsDiv.innerHTML="",I.Z.checkAnimations(void 0,ma),this.inputSearch.remove(),super.onCloseAfterTimeout()}reset(){this.searchPromise=null,this.nextOffset="",this.loadedAll=!1,this.masonry.clear()}open(){const e=super.open();return Yt.toggleSidebar(!0).then((()=>{this.search("",!0),this.scrollable.onScrolledBottom=()=>{this.search(this.inputSearch.value,!1)}})),e}search(e,t=!0){return s=this,i=void 0,a=function*(){if(!this.searchPromise&&!this.loadedAll){this.gifBotPeerId||(this.gifBotPeerId=(yield E.Z.resolveUsername("gif")).id.toPeerId(!1));try{this.searchPromise=ga.getInlineResults(Re.NM,this.gifBotPeerId,e,this.nextOffset);const{results:s,next_offset:i}=yield this.searchPromise;if(this.inputSearch.value!==e)return;this.searchPromise=null,this.nextOffset=i,t&&(this.gifsDiv.innerHTML=""),s.length?s.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 s;t.done?e(t.value):(s=t.value,s instanceof n?s:new n((function(e){e(s)}))).then(o,r)}l((a=a.apply(s,i||[])).next())}));var s,i,n,a}}class fa extends O{init(){this.container.id="stickers-container",this.container.classList.add("chatlist-container"),this.lazyLoadQueue=new X.ZP,this.inputSearch=new Z("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),(0,l.fc)(this.setsDiv,(e=>{const t=(0,Me.Z)(e.target,"sticker-set-sticker");if(t){const e=t.dataset.docId;return void Ol.chat.input.sendMessageWithDocument(e)}const s=(0,Me.Z)(e.target,"sticker-set");if(!s)return;const i=s.dataset.stickerSet,n=s.dataset.access_hash,a=(0,Me.Z)(e.target,"sticker-set-button");a?(e.preventDefault(),e.cancelBubble=!0,a.setAttribute("disabled","true"),ds.Z.getStickerSet({id:i,access_hash:n}).then((e=>{ds.Z.toggleStickerSet(e.set).then((t=>{t&&(a.textContent="",a.append((0,k.i18n)(e.set.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),a.classList.toggle("gray",!!e.set.installed_date))})).finally((()=>{a.removeAttribute("disabled")}))}))):ds.Z.getStickerSet({id:i,access_hash:n}).then((e=>{new Ki(e.set).show()}))}),{listenerSetter:this.listenerSetter})}onCloseAfterTimeout(){return this.setsDiv.innerHTML="",I.Z.checkAnimations(void 0,"STICKERS-SEARCH"),super.onCloseAfterTimeout()}renderSet(e){const t=document.createElement("div");t.classList.add("sticker-set");const s=document.createElement("div");s.classList.add("sticker-set-header");const i=document.createElement("div");i.classList.add("sticker-set-details"),i.innerHTML=`\n <div class="sticker-set-name">${Q.o.wrapEmojiText(e.title)}</div>\n `;const n=document.createElement("div");n.classList.add("sticker-set-count"),n.append((0,k.i18n)("Stickers",[e.count])),i.append(n);const a=document.createElement("button");a.classList.add("btn-primary","btn-color-primary","sticker-set-button"),a.append((0,k.i18n)(e.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),e.installed_date&&a.classList.add("gray"),s.append(i,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)}ds.Z.getStickerSet(e).then((e=>{for(let t=0;t<r;++t){const s=o.children[t],i=e.documents[t];"documentEmpty"!==i._&&Is({doc:i,div:s,lazyLoadQueue:this.lazyLoadQueue,group:"STICKERS-SEARCH",play:!0,loop:!0,width:68,height:68})}})),t.dataset.stickerSet=""+e.id,t.dataset.access_hash=""+e.access_hash,t.dataset.title=e.title,t.append(s,o),this.setsDiv.append(t)}open(){const e=super.open();return Yt.toggleSidebar(!0).then((()=>{this.renderFeatured()})),e}renderFeatured(){return ds.Z.getFeaturedStickers().then((e=>{this.inputSearch.value||(e=this.filterRendered("",e)).forEach((e=>{this.renderSet(e.set)}))}))}filterRendered(e,t){t=t.slice();const s=Array.from(this.setsDiv.children);return(0,b.Z)(s,(s=>{const i=s.dataset.stickerSet,n=t.findIndex((e=>e.set.id===i));-1!==n?t.splice(n,1):e&&s.dataset.title.toLowerCase().includes(e.toLowerCase())||s.remove()})),I.Z.checkAnimations(void 0,"STICKERS-SEARCH"),t}search(e){return e?ds.Z.searchStickerSets(e,!1).then((t=>{this.inputSearch.value===e&&(t=this.filterRendered(e,t)).forEach((e=>{this.renderSet(e.set)}))})):this.renderFeatured()}}class ba extends R.Z{constructor(e){super(!1),this.forceClose=!1,this.inited=!1,this.onMouseOut=e=>{if(clearTimeout(this.displayTimeout),!this.isActive())return;const t=e.toElement;t&&(0,Ws.Z)(t,this.element)||(this.displayTimeout=window.setTimeout((()=>{this.toggle(!1)}),200))},this.toggle=e=>{return t=this,s=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")}),ce.IS_TOUCH_SUPPORTED?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")}),ce.IS_TOUCH_SUPPORTED?0:200)},new((i=void 0)||(i=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 s;t.done?e(t.value):(s=t.value,s instanceof i?s:new i((function(e){e(s)}))).then(o,r)}l((n=n.apply(t,s||[])).next())}));var t,s,i,n},(0,w.Z)(this,e)}attachButtonListener(e,t){let s=!0;ce.IS_TOUCH_SUPPORTED?(0,l.fc)(e,(()=>{s?(s=!1,this.toggle(!0)):this.toggle()}),{listenerSetter:t}):t.add(e)("mouseover",(i=>{s&&(t.add(e)("mouseout",this.onMouseOut),s=!1),clearTimeout(this.displayTimeout),this.displayTimeout=window.setTimeout((()=>{this.toggle(!0)}),200)}))}init(){ce.IS_TOUCH_SUPPORTED||(this.element.onmouseout=this.onMouseOut,this.element.onmouseover=e=>{this.forceClose||clearTimeout(this.displayTimeout)})}isActive(){return this.element.classList.contains("active")}}const ya="emoticons-dropdown";class wa extends ba{constructor(){super({element:document.getElementById("emoji-dropdown")}),this.tabId=-1,this.onSelectTabClick=e=>{this.tabId!==e&&(I.Z.checkAnimations(!0,ya),this.tabId=e,this.searchButton.classList.toggle("hide",0===this.tabId),this.deleteBtn.classList.toggle("hide",0!==this.tabId))},this.checkRights=()=>{const{peerId:e,threadId:t}=Ol.chat,s=this.tabsEl.children,n=Array.from(s),a=i.Z.canSendToPeer(e,t,"send_stickers");n[2].toggleAttribute("disabled",!a);const o=i.Z.canSendToPeer(e,t,"send_gifs");n[3].toggleAttribute("disabled",!o);const r=this.tabsEl.querySelector(".active");!r||1===(0,_s.Z)(r)||a&&o||this.selectTab(0,!1)},this.addEventListener("open",(()=>{return e=this,t=void 0,i=function*(){ce.IS_TOUCH_SUPPORTED&&(0,Gs.Z)()&&(yield(0,Kn.w)(100)),this.element.parentElement!==Ol.chat.input.chatInput&&Ol.chat.input.chatInput.append(this.element),this.savedRange=this.getGoodRange(),wa.lazyLoadQueue.lock(),I.Z.lockIntersectionGroup(ya)},new((s=void 0)||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}));var e,t,s,i})),this.addEventListener("opened",(()=>{I.Z.unlockIntersectionGroup(ya),wa.lazyLoadQueue.unlock(),wa.lazyLoadQueue.refresh(),this.container.classList.remove("disable-hover")})),this.addEventListener("close",(()=>{wa.lazyLoadQueue.lock(),I.Z.lockIntersectionGroup(ya),I.Z.checkAnimations(!0,ya)})),this.addEventListener("closed",(()=>{I.Z.unlockIntersectionGroup(ya),wa.lazyLoadQueue.unlock(),wa.lazyLoadQueue.refresh(),this.container.classList.remove("disable-hover"),this.savedRange=void 0}))}init(){this.emojiTab=new oa,this.stickersTab=new pa,this.gifsTab=new ca,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,Y.X)(this.tabsEl,this.container,this.onSelectTabClick,(()=>{const e=this.tabs[this.tabId];e.init&&e.init(),e.onCloseAfterTimeout&&e.onCloseAfterTimeout(),I.Z.checkAnimations(!1,ya)})),this.searchButton=this.element.querySelector(".emoji-tabs-search"),this.searchButton.addEventListener("click",(()=>{1===this.tabId?Yt.isTabExists(fa)||new fa(Yt).open():Yt.isTabExists(va)||new va(Yt).open()})),this.deleteBtn=this.element.querySelector(".emoji-tabs-delete"),this.deleteBtn.addEventListener("click",(e=>{var t;const s=Ol.chat.input.messageInput;(null===(t=s.lastChild)||void 0===t?void 0:t.tagName)?s.lastElementChild.remove():s.lastChild&&(s.lastChild.textContent.length?s.lastChild.textContent=s.lastChild.textContent.slice(0,-1):s.lastChild.remove());const i=new Event("input",{bubbles:!0,cancelable:!0});Ol.chat.input.messageInput.dispatchEvent(i),(0,d.d)(e)}));const e=ne.IS_APPLE_MOBILE,t=e?1:0;return e&&this.tabsEl.children[1].classList.add("hide"),this.tabsEl.children[t+1].click(),this.tabs[t].init&&this.tabs[t].init(),a.default.addEventListener("peer_changed",this.checkRights),this.checkRights(),super.init()}addLazyLoadQueueRepeat(e,t){this.addEventListener("close",(()=>{e.lock()})),this.addEventListener("closed",(()=>{const s=e.intersector.getVisible();for(const e of s)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===Ol.chat.input.messageInput)return e.getRangeAt(0)}}wa.lazyLoadQueue=new X.ZP,wa.menuOnClick=(e,t,s,i=0)=>{let n=-1;const a=t=>t!==i&&(e.children[i].classList.remove("active"),e.children[t].classList.add("active"),i=t,!0),o=new Gn(t.container,((i,o)=>{if(Math.abs(n-t.container.scrollTop)<=1)return;n=-1;const r=(0,_s.Z)(o);!i&&r||(a(r),s&&(r<e.childElementCount-4?s.container.scrollLeft=47*(r-3):s.container.scrollLeft=47*r))}));return e.addEventListener("click",(e=>{let s=e.target;if(s=(0,Me.Z)(s,"menu-horizontal-div-item"),!s)return;const i=(0,_s.Z)(s);if(!a(i))return;const o=(t.splitUp||t.container).children[i].offsetTop+1;t.container.scrollTop=n=o})),{stickyIntersector:o,setActive:a}},wa.onMediaClick=(e,t=!1)=>{let s=e.target;if(s=(0,ft.Z)(s,"DIV"),!s)return!1;const i=s.dataset.docId;return!!i&&(Ol.chat.input.sendMessageWithDocument(i,void 0,t)?(Sa.container&&(Sa.forceClose=!0,Sa.container.classList.add("disable-hover"),Sa.toggle(!1)),!0):(console.warn("got no doc by id:",i),!1))};const Sa=new wa;re.GO.emoticonsDropdown=Sa;const Ca=Sa,La=2147483646;var Ia=s(8939);const Ma=!("undefined"==typeof RTCPeerConnection||ne.IS_FIREFOX),Ea=Ma;function Pa(e,t,s,i=e.getBoundingClientRect()){const n=t.getBoundingClientRect();let{top:a,right:o,bottom:r,left:l}=n;if(s){const e=t.querySelector(".sticky");e&&(a=e.getBoundingClientRect().bottom)}if(i.top>=r||i.bottom<=a||i.right<=l||i.left>=o)return null;const d={top:!1,right:!1,bottom:!1,left:!1,vertical:0,horizontal:0},c="visualViewport"in window?window.visualViewport:window,h=c.width||c.innerWidth,p=c.height||c.innerHeight;return{rect:{top:i.top<a&&0!==a?(d.top=!0,++d.vertical,a):i.top,right:i.right>o&&o!==h?(d.right=!0,++d.horizontal,o):i.right,bottom:i.bottom>r&&r!==p?(d.bottom=!0,++d.vertical,r):i.bottom,left:i.left<l&&0!==l?(d.left=!0,++d.horizontal,l):i.left},overflow:d}}window.getVisibleRect=Pa;var Ta,ka=s(2575);class xa extends pt.Z{constructor(e,t){super("popup-join-chat-invite",(0,pt.x)([{langKey:t.pFlags.request_needed?"RequestJoin.Button":t.pFlags.broadcast?"JoinByPeekChannelTitle":"JoinByPeekGroupTitle",callback:()=>{ct.Z.invokeApi("messages.importChatInvite",{hash:e}).then((e=>{ni.Z.processUpdateMessage(e);const t=e.chats[0].id.toPeerId(!0);a.default.dispatchEvent("history_focus",{peerId:t})}),(e=>{"INVITE_REQUEST_SENT"===e.type&&lt({langPackKey:"RequestToJoinSent"})}))}}]),{closable:!0,overlayClosable:!0,body:!0}),this.header.remove();const s=new Yl;s.setAttribute("dialog","0"),s.classList.add("avatar-100"),"photo"===t.photo._?(t.photo=r.Z.savePhoto(t.photo),Ss({container:s,message:null,photo:t.photo,boxHeight:100,boxWidth:100,withoutPreloader:!0}),s.style.width=s.style.height=""):c.Z.putPhoto(s,Re.NM,!1,t.title);const i=document.createElement("div");i.classList.add("chat-title"),i.innerHTML=Q.Z.wrapEmojiText(t.title);const n=t.pFlags.broadcast,o=(0,k.i18n)(n?"Subscribers":"Members",[(0,ka.Z)(t.participants_count)]);if(o.classList.add("chat-participants-count"),this.body.append(s,i,o),t.pFlags.request_needed){const e=document.createElement("div");(0,k._i18n)(e,n?"RequestToJoinChannelDescription":"RequestToJoinGroupDescription"),e.classList.add("chat-participants-count","request-caption"),this.body.append(e)}}}!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"}(Ta||(Ta={}));class Aa{constructor(e,t){this.scrollable=e,this.reverse=t}get container(){return this.scrollable.container}save(){const{scrollTop:e,scrollHeight:t}=this.container;this.previousScrollHeight=t,this.previousScrollHeightMinusTop=this.reverse?t-e:e}restore(e){const{container:t,previousScrollHeightMinusTop:s,scrollable:i}=this;if(void 0!==s){const n=t.scrollHeight;if(n===this.previousScrollHeight)return;const a=this.reverse?n-s:s;t.scrollTop=a,i.lastScrollPosition=a,ne.IS_SAFARI&&e&&jn(t)}}}var _a=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const Za=new Set(["messageActionHistoryClear","messageActionChatCreate"]),Da=new Set;Ea&&Da.add("messageActionPhoneCall");const Fa=void 0;let Ra=Fa,Ba=0;class Ua{constructor(e,t,s,i,n,o,r,c,h,p,u,g){if(this.chat=e,this.appMessagesManager=t,this.appStickersManager=s,this.appUsersManager=i,this.appInlineBotsManager=n,this.appPhotosManager=o,this.appPeersManager=r,this.appProfileManager=c,this.appDraftsManager=h,this.appMessagesIdsManager=p,this.appChatsManager=u,this.appReactionsManager=g,this.unreadOut=new Set,this.needUpdate=[],this.bubbles={},this.skippedMids=new Set,this.dateMessages={},this.scrolledDown=!0,this.isScrollingTimeout=0,this.unreaded=new Map,this.unreadedSeen=new Set,this.preloader=null,this.loadedTopTimes=0,this.loadedBottomTimes=0,this.messagesQueuePromise=null,this.messagesQueue=[],this.messagesQueueOnRender=null,this.messagesQueueOnRenderAdditional=null,this.firstUnreadBubble=null,this.middleware=(0,As.k)(),this.replyFollowHistory=[],this.isHeavyAnimationInProgress=!1,this.isFirstLoad=!0,this.passEntities={},this.viewsMids=new Set,this.isTopPaddingSet=!1,this.onBubblesMouseMove=e=>{const t=(0,Me.Z)(e.target,"bubble-content");if(t&&!this.chat.selection.isSelecting){const e=(0,Me.Z)(t,"bubble");if(!this.chat.selection.canSelectBubble(e))return void this.unhoverPrevious();let{hoverBubble:s,hoverReaction:i}=this;if(e===s)return;if(this.unhoverPrevious(),s=this.hoverBubble=e,i=this.hoverReaction,i)i.dataset.loaded&&this.setHoverVisible(i,!0);else{i=this.hoverReaction=document.createElement("div"),i.classList.add("bubble-hover-reaction");const s=document.createElement("div");s.classList.add("bubble-hover-reaction-sticker"),i.append(s),t.append(i);let n=this.chat.getMessage(+e.dataset.mid);n=this.appMessagesManager.getGroupsFirstMessage(n);const a=this.getMiddleware((()=>this.hoverReaction===i));Promise.all([this.appReactionsManager.getAvailableReactionsByMessage(n),(0,Kn.w)(400)]).then((([e])=>{const t=e[0];t?Is({div:s,doc:t.select_animation,width:18,height:18,needUpscale:!0,middleware:a,group:Bl,withThumb:!1,needFadeIn:!1}).then((e=>{(0,gs.Z)(e),a()&&(e.addEventListener("firstFrame",(()=>{a()&&(i.dataset.loaded="1",this.setHoverVisible(i,!0))}),{once:!0}),(0,l.fc)(i,(e=>{(0,d.d)(e),this.appReactionsManager.sendReaction(n,t.reaction),this.unhoverPrevious()}),{listenerSetter:this.listenerSetter}))})):i.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=>{var t;let s=e.target,i=null;try{i=(0,Me.Z)(s,"bubble")}catch(e){}if(!i)return;if(i.classList.contains("is-date")&&(0,Me.Z)(s,"bubble-content")){if(i.classList.contains("is-sticky")&&!this.chatInner.classList.contains("is-scrolling"))return;for(const e in this.dateMessages)if(this.dateMessages[e].div===i){new _n(new Date(+e),this.onDatePick).show();break}return}if(!ce.IS_TOUCH_SUPPORTED&&(0,Me.Z)(s,"time"))return void this.chat.selection.toggleByElement(i);if(this.chat.selection.isSelecting&&e.isTrusted){if(i.classList.contains("service")&&void 0===i.dataset.mid)return;return(0,d.d)(e),ce.IS_TOUCH_SUPPORTED&&this.chat.selection.selectedText?void(this.chat.selection.selectedText=void 0):void this.chat.selection.toggleByElement((0,Me.Z)(s,"grouped-item")||i)}const n=(0,Me.Z)(s,"contact");if(n)return void this.chat.appImManager.setInnerPeer({peerId:n.dataset.peerId.toPeerId()});const a=(0,Me.Z)(s,"bubble-call");if(a)return void this.chat.appImManager.callUser(this.peerId.toUserId(),a.dataset.type);const o=(0,Me.Z)(s,"spoiler");if(o){const t=(0,Me.Z)(o,"message"),s="is-spoiler-visible",i=t.classList.contains(s);i||(0,d.d)(e);const n=200,a=5e3,r=i?0:2;r&&t.classList.add("will-change");const l=t.dataset.spoilerTimeout;return null!==l&&(clearTimeout(+l),delete t.dataset.spoilerTimeout),void(0,Jt.Z)(t,s,!0,n,(()=>{t.dataset.spoilerTimeout=""+window.setTimeout((()=>{(0,Jt.Z)(t,s,!1,n,(()=>{t.classList.remove("will-change"),delete t.dataset.spoilerTimeout}))}),a)}),r)}const r=(0,ft.Z)(s,"REACTION-ELEMENT");if(r){if((0,d.d)(e),r.classList.contains("is-inactive"))return;const t=r.parentElement,s=t.getReactionCount(r),i=t.getMessage();return void this.appReactionsManager.sendReaction(i,s.reaction)}if((0,Me.Z)(s,"replies")){const e=+i.dataset.mid;if(this.peerId===Re.hj){const t=this.chat.getMessage(e),s=this.appPeersManager.getPeerId(t.reply_to.reply_to_peer_id),i=t.reply_to.reply_to_top_id,n=t.fwd_from.saved_from_msg_id;this.chat.appImManager.openThread(s,n,i)}else{const t=this.appMessagesManager.filterMessages(this.chat.getMessage(e),(e=>!!e.replies))[0],s=t.replies;s&&this.appMessagesManager.getDiscussionMessage(this.peerId,t.mid).then((e=>{this.chat.appImManager.setInnerPeer({peerId:s.channel_id.toPeerId(!0),type:"discussion",threadId:e.mid})}))}return}const c=(0,Me.Z)(s,"is-via");if(c){const t=c.querySelector(".peer-title");if(s===t||(0,Ws.Z)(s,t)){const s=t.innerText+" ";return this.appDraftsManager.setDraft(this.peerId,this.chat.threadId,s),void(0,d.d)(e)}}const h=(0,Me.Z)(s,"peer-title")||(0,ft.Z)(s,"AVATAR-ELEMENT")||(0,wt.Z)(s,"data-saved-from");if(h&&h!==i){s=h||s;const e=s.dataset.peerId||s.getAttribute("peer"),t=s.dataset.savedFrom;if("string"==typeof e||t)if(t){const[e,s]=t.split("_");this.chat.appImManager.setInnerPeer({peerId:e.toPeerId(),lastMsgId:+s})}else{const t=e.toPeerId();t!==Re.NM?this.chat.appImManager.setInnerPeer({peerId:t}):rt(k.default.format("HidAccount",!0))}return}if(i.classList.contains("sticker")&&s.parentElement.classList.contains("attachment")){const e=+i.dataset.mid,s=null===(t=this.chat.getMessage(e).media)||void 0===t?void 0:t.document;return void((null==s?void 0:s.stickerSetInput)&&new Ki(s.stickerSetInput).show())}const p=(0,Me.Z)(s,"document-with-thumb");if("IMG"===s.tagName&&!s.classList.contains("emoji")&&!s.classList.contains("document-thumb")||s.classList.contains("album-item")||"VIDEO"===s.tagName&&!i.classList.contains("round")||p&&!p.querySelector(".preloader-container")){const t=(0,Me.Z)(s,"album-item")||(0,Me.Z)(s,"document-container"),n=+(t||i).dataset.mid,a=this.chat.getMessage(n);if(!a)return void this.log.warn("no message by messageId:",n);const o=(t||i).querySelector(".preloader-container");if(o)return(0,l.tH)(o),void(0,d.d)(e);const r="webpage",c=i.classList.contains(r),h=p?e=>Vl.isMediaCompatibleForDocumentViewer(e):e=>"photo"===e._||["video","gif"].includes(e.type),u=[],g=c?[n]:Object.keys(this.bubbles).map((e=>+e)).filter((e=>{const t=this.chat.getMessage(e),s=this.appMessagesManager.getMediaFromMessage(t);return s&&h(s)})).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 s=Array.from(this.bubbles[e].querySelectorAll(t)),i=new Set;if(p)s.forEach((e=>{u.push({element:e.querySelector(".document-ico"),mid:+e.dataset.mid,peerId:this.peerId})}));else{const t=!!this.bubbles[e].querySelector(".media-container-aspecter");s.forEach((s=>{if(t&&!(0,Me.Z)(s,"media-container-aspecter"))return;let n=(0,Me.Z)(s,"album-item");const a=n||s.parentElement;i.has(a)||(i.add(a),u.push({element:s,mid:n?+n.dataset.mid:e,peerId:this.peerId}))}))}})),u.sort(((e,t)=>e.mid-t.mid));let m=u.findIndex((e=>e.mid===n));return re.ZP&&this.log("open mediaViewer single with ids:",g,m,u),u[m]?((new Vl).setSearchContext({threadId:this.chat.threadId,peerId:this.peerId,inputFilter:{_:p?"inputMessagesFilterDocument":"inputMessagesFilterPhotoVideo"},useSearch:"scheduled"!==this.chat.type&&!c,isScheduled:"scheduled"===this.chat.type}).openMedia(a,u[m].element,0,!0,u.slice(0,m),u.slice(m+1)),void(0,d.d)(e)):void this.log("no target for media viewer!",s)}if(-1===["IMG","DIV","SPAN"].indexOf(s.tagName)&&(s=(0,ft.Z)(s,"DIV")),-1!==["DIV","SPAN"].indexOf(s.tagName)){if(s.classList.contains("goto-original")){const e=i.dataset.savedFrom,[t,s]=e.split("_");return void this.chat.appImManager.setInnerPeer({peerId:t.toPeerId(),lastMsgId:+s})}if(s.classList.contains("forward")){const e=+i.dataset.mid,t=this.appMessagesManager.getMessageByPeer(this.peerId,e);return void new Hs({[this.peerId]:this.appMessagesManager.getMidsByMessage(t)})}let t=!1;try{t=!!(0,Me.Z)(e.target,"reply")}catch(e){}if(t&&i.classList.contains("is-reply")){const e=+i.dataset.mid;this.replyFollowHistory.push(e);const t=this.chat.getMessage(e),s=t.reply_to.reply_to_peer_id?this.appPeersManager.getPeerId(t.reply_to.reply_to_peer_id):this.peerId,n=t.reply_to.reply_to_msg_id;this.chat.appImManager.setInnerPeer({peerId:s,lastMsgId:n,type:this.chat.type,threadId:this.chat.threadId})}}},this.onScroll=()=>{if(this.isHeavyAnimationInProgress&&this.scrolledDown)return;const e=this.scrollable.getDistanceToEnd();!ce.IS_TOUCH_SUPPORTED&&0!==this.scrollable.lastScrollDirection&&e>0&&(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)),e<300&&(this.scrollable.loadedAll.bottom||this.chat.setPeerPromise||!this.peerId)?(this.bubblesContainer.classList.add("scrolled-down"),this.scrolledDown=!0):this.bubblesContainer.classList.contains("scrolled-down")&&(this.bubblesContainer.classList.remove("scrolled-down"),this.scrolledDown=!1),this.chat.topbar.pinnedMessage&&this.chat.topbar.pinnedMessage.setCorrectIndex(this.scrollable.lastScrollDirection),this.setStickyDateManually()},this.onDatePick=e=>{const t=this.peerId;this.appMessagesManager.requestHistory(t,0,2,-1,e,this.chat.threadId).then((e=>{var s;(null===(s=null==e?void 0:e.messages)||void 0===s?void 0:s.length)?this.peerId===t&&this.chat.setMessageId(e.messages[0].mid):this.log.error("no history!")}))},this.listenerSetter=new B.Z,this.bubblesContainer=document.createElement("div"),this.bubblesContainer.classList.add("bubbles","scrolled-down"),this.chatInner=document.createElement("div"),this.chatInner.classList.add("bubbles-inner"),this.setScroll(),this.bubblesContainer.append(this.scrollable.container),this.log=this.chat.log,this.bubbleGroups=new An(this.chat),this.preloader=new fe.Z({cancelable:!1}),this.lazyLoadQueue=new X.ZP,this.lazyLoadQueue.queueId=++Ba,this.listenerSetter.add(a.default)("history_update",(({storage:e,peerId:t,mid:s})=>{if(this.chat.getMessagesStorage()===e){const e=this.bubbles[s];if(!e)return;const t=this.chat.getMessage(s);if(+e.dataset.timestamp>=t.date+Ye.Z.serverTimeOffset-1)return void this.bubbleGroups.changeBubbleMid(e,s);this.setBubblePosition(e,t,!1),this.scrollingToBubble&&this.scrollToEnd()}})),this.listenerSetter.add(a.default)("dialog_flush",(({peerId:e})=>{this.peerId===e&&this.deleteMessagesByIds(Object.keys(this.bubbles).map((e=>+e)))})),this.listenerSetter.add(a.default)("message_sent",(e=>{var t,s,i,n,o,r,l,d;const{storage:c,tempId:h,tempMessage:p,mid:u}=e;if(this.chat.getMessagesStorage()!==c)return;const g=this.getMountedBubble(h,p)||this.getMountedBubble(u);if(g){const e=this.chat.getMessage(u),a=g.bubble,c=Array.from(a.querySelectorAll("reactions-element"));if(c.length&&c.forEach((t=>{t.changeMessage(e)})),e.replies){const t=a.querySelector("replies-element");t&&(t.message=e,t.init())}if(null===(t=e.media)||void 0===t?void 0:t.document){const t=a.querySelector(`.document-container[data-mid="${h}"] .document`);if(t){const a=(0,Me.Z)(t,"document-container");!(null===(n=null===(i=null===(s=p.media)||void 0===s?void 0:s.document)||void 0===i?void 0:i.thumbs)||void 0===n?void 0:n.length)&&(null===(o=e.media.document.thumbs)||void 0===o?void 0:o.length)&&t.replaceWith(ws({message:e})),a&&(a.dataset.mid=""+u)}}if(e.grouped_id){const e=a.querySelector(`.grouped-item[data-mid="${h}"]`)||a;e&&(e.dataset.mid=""+u)}if(null===(r=e.media)||void 0===r?void 0:r.poll){const t=a.querySelector("poll-element");if(t){const s=e.media.poll;t.message=e,t.setAttribute("poll-id",s.id),t.setAttribute("message-id",""+u)}}if(null===(l=e.media)||void 0===l?void 0:l.document){const t=a.querySelector(`audio-element[data-mid="${h}"], .document[data-doc-id="${h}"], .media-round[data-mid="${h}"]`);t&&(t instanceof He||t.classList.contains("media-round")?(t.dataset.mid=""+e.mid,delete t.dataset.isOutgoing,t.message=e,t.onLoad(!0)):t.dataset.docId=e.media.document.id)}(null===(d=e.media)||void 0===d?void 0:d.webpage)&&!a.querySelector(".web")&&(0,xs.e9)().then((()=>{this.safeRenderMessage(e,!0,!1,a,!1),this.scrollToBubbleIfLast(a)}))}else this.log.warn("message_sent there is no bubble",e);const m=this.bubbles;if(m[h]){const e=m[h];m[u]=e,delete m[h],(0,De.T2)((()=>{e.classList.contains("is-outgoing")&&(e.classList.remove("is-sending","is-outgoing"),e.classList.add(this.peerId===a.default.myId&&"scheduled"!==this.chat.type?"is-read":"is-sent"))})),e.dataset.mid=""+u}this.unreadOut.has(h)&&(this.unreadOut.delete(h),this.unreadOut.add(u)),"scheduled"===this.chat.type&&(Date.now()/1e3|0)>=p.date-10&&this.deleteMessagesByIds([u])})),this.listenerSetter.add(a.default)("message_edit",(({storage:e,peerId:t,mid:s})=>{if(e!==this.chat.getMessagesStorage())return;const i=this.chat.getMessage(s),n=i.grouped_id?this.getGroupedBubble(i.grouped_id):this.getMountedBubble(s);if(!n)return;const a="scheduled"===this.chat.type;this.saveOnUpdateScroll(),this.safeRenderMessage(n.message,!0,!1,n.bubble,a),a&&(this.messagesQueuePromise||Promise.resolve()).then((()=>{this.deleteEmptyDateGroups()}))})),"scheduled"!==this.chat.type&&(this.listenerSetter.add(a.default)("missed_reactions_element",(({message:e,changedResults:t})=>{if(this.peerId!==e.peerId||!e.reactions||!e.reactions.results.length)return;const s=this.getBubbleByMessage(e);s&&(e.grouped_id&&(e=this.getGroupedBubble(e.grouped_id).message),this.appendReactionsElementToBubble(s,e,t))})),this.listenerSetter.add(a.default)("message_reactions",(({message:e,changedResults:t})=>{if(this.peerId!==e.peerId)return;if(!this.getBubbleByMessage(e))return;this.saveOnUpdateScroll();const s=e.peerId+"_"+e.mid,i=Rn.get(s);if(i)for(const s of i)s.update(e,t);else a.default.dispatchEvent("missed_reactions_element",{message:e,changedResults:t})}))),this.listenerSetter.add(a.default)("album_edit",(({peerId:e,groupId:t,deletedMids:s})=>{if(e!==this.peerId)return;const i=this.appMessagesManager.getMidsByAlbum(t).concat(s).find((e=>this.bubbles[e]));if(!i)return;const n=(0,Xs.Z)(this.appMessagesManager.groupedMessagesStorage[t],"asc").pop();this.safeRenderMessage(this.chat.getMessage(n),!0,!1,this.bubbles[i],!1)})),this.listenerSetter.add(a.default)("messages_downloaded",(({peerId:e,mids:t})=>{const s=this.getMiddleware();(0,xs.e9)().then((()=>{s()&&t.forEach((t=>{(0,b.Z)(this.needUpdate,((s,i)=>{if(s.replyMid===t&&s.replyToPeerId===e){const{mid:e,replyMid:t}=this.needUpdate.splice(i,1)[0],n=this.bubbles[e];if(!n)return;const a=this.chat.getMessage(e);this.appMessagesManager.getMessageByPeer(s.replyToPeerId,t).deleted&&delete a.reply_to_mid,Hn.setReply({chat:this.chat,bubble:n,message:a})}}))}))}))})),ce.IS_TOUCH_SUPPORTED){const e="is-gesturing-reply",t=64,s=.75*t;let i,n,a=!1;Us({element:this.bubblesContainer,verifyTouchTarget:t=>!(this.chat.selection.isSelecting||!this.chat.canSend()||(i=(0,Me.Z)(t.target,"bubble"),i&&((0,Jt.Z)(i,e,!0,250),i.offsetLeft,n?(n.classList.remove("is-visible"),n.style.opacity=""):(n=document.createElement("span"),n.classList.add("tgico-reply_filled","bubble-gesture-reply-icon")),i.append(n)),!i)),onSwipe:(e,o)=>{a=e>=s,a&&!n.classList.contains("is-visible")&&n.classList.add("is-visible"),n.style.opacity=""+Math.min(1,e/s);const r=-Math.max(0,Math.min(t,e));i.style.transform=`translateX(${r}px)`,(0,J.s3)()},onReset:()=>{const t=i;(0,Jt.Z)(t,e,!1,250,(()=>{n.parentElement===t&&(n.classList.remove("is-visible"),n.remove())})),(0,De.T2)((()=>{if(t.style.transform="",a){const{mid:e}=t.dataset;this.chat.input.initMessageReply(+e),a=!1}}))},listenerOptions:{capture:!0}})}let m;(0,l.fc)(this.bubblesContainer,this.onBubblesClick,{listenerSetter:this.listenerSetter}),re.ZP&&this.listenerSetter.add(this.bubblesContainer)("dblclick",(e=>{const t=(0,Me.Z)(e.target,"grouped-item")||(0,Me.Z)(e.target,"bubble");if(t){const e=+t.dataset.mid;this.log("debug message:",this.chat.getMessage(e)),this.highlightBubble(t)}})),ne.IS_MOBILE||"pinned"===this.chat.type||this.listenerSetter.add(this.bubblesContainer)("dblclick",(e=>{if(this.chat.selection.isSelecting||!this.chat.canSend())return;const t=e.target,s=t.classList.contains("bubble")?t:t.classList.contains("document-selection")?t.parentElement:null;if(s&&!s.classList.contains("bubble-first")){const e=+s.dataset.mid;if(this.chat.getMessage(e).pFlags.is_outgoing)return;this.chat.input.initMessageReply(e)}})),(0,xs.ZP)((()=>{this.isHeavyAnimationInProgress=!0,this.lazyLoadQueue.lock(),m=this.getMiddleware()}),(()=>{this.isHeavyAnimationInProgress=!1,m&&m()&&(this.lazyLoadQueue.unlock(),this.lazyLoadQueue.refresh()),m=null}),this.listenerSetter)}constructPeerHelpers(){if(this.listenerSetter.add(a.default)("history_append",(({storage:e,mid:t})=>{if(e===this.chat.getMessagesStorage()&&(this.scrollable.loadedAll.bottom?this.renderNewMessagesByIds([t],!0):this.chat.setMessageId(),a.default.settings.animationsEnabled)){const e=this.chat.gradientRenderer;e&&e.toNextPosition()}})),this.listenerSetter.add(a.default)("history_multiappend",(e=>{if(!(this.peerId in e))return;const t=Array.from(e[this.peerId]).slice().sort(((e,t)=>t-e));this.renderNewMessagesByIds(t)})),this.listenerSetter.add(a.default)("history_delete",(({peerId:e,msgs:t})=>{e===this.peerId&&this.deleteMessagesByIds(Array.from(t))})),this.listenerSetter.add(a.default)("dialog_unread",(({peerId:e})=>{e===this.peerId&&(this.chat.input.setUnreadCount(),this.updateUnreadByDialog())})),this.listenerSetter.add(a.default)("dialogs_multiupdate",(e=>{e[this.peerId]&&this.chat.input.setUnreadCount()})),this.listenerSetter.add(a.default)("dialog_notify_settings",(e=>{this.peerId===e.peerId&&this.chat.input.setUnreadCount()})),this.listenerSetter.add(a.default)("chat_update",(e=>{this.peerId===e.toPeerId(!0)&&this.chatInner.classList.contains("has-rights")!==this.chat.canSend()&&(this.finishPeerChange(),this.chat.input.finishPeerChange())})),this.listenerSetter.add(a.default)("settings_updated",(e=>{if("settings.emoji.big"===e.key){const e=this.scrollable.isScrolledDown;e||this.setMessagesQueuePromise(),(0,Xs.Z)(this.bubbles,"desc").forEach((e=>{const t=this.bubbles[e];if(t.classList.contains("can-have-big-emoji")){const s=this.chat.getMessage(e);this.safeRenderMessage(s,void 0,!1,t)}})),e?this.scrollable.scrollTop=99999:this.performHistoryResult([],!0,!1,void 0)}})),this.listenerSetter.add(a.default)("message_views",(({peerId:e,views:t,mid:s})=>{this.peerId===e&&(0,De.T2)((()=>{const e=this.bubbles[s];if(!e)return;const i=Array.from(e.querySelectorAll(".post-views"));if(i.length){const e=Cn(t,1);let s=!1;i.forEach((t=>{(s||t.innerHTML!==e)&&(this.saveOnUpdateScroll(),s=!0,t.innerHTML=e)}))}}))})),this.unreadedObserver=new IntersectionObserver((e=>{e.forEach((e=>{if(e.isIntersecting){const t=e.target,s=this.unreaded.get(t);this.onUnreadedInViewport(t,s)}}))})),this.viewsObserver=new IntersectionObserver((e=>{e.forEach((e=>{if(e.isIntersecting){const t=+e.target.dataset.mid;if(this.viewsObserver.unobserve(e.target),t)this.viewsMids.add(t),this.sendViewCountersDebounced();else{const{sponsoredMessage:e}=this;e&&e.random_id&&(delete e.random_id,this.chat.apiManager.invokeApiSingle("channels.viewSponsoredMessage",{channel:this.appChatsManager.getChannelInput(this.peerId.toChatId()),random_id:e.random_id}))}}}))})),this.sendViewCountersDebounced=dt((()=>{const e=[...this.viewsMids];this.viewsMids.clear(),this.appMessagesManager.incrementMessageViews(this.peerId,e)}),1e3,!1,!0),"ResizeObserver"in window){let e=this.scrollable.container.offsetHeight,t=!1,s=!1,i=0,n=0,a=0;const o=()=>{const o=this.scrollable.container.offsetHeight,r=this.scrollable.isScrolledDown;o===e||s&&r||(n+=e-o),n&&(this.scrollable.scrollTop+=Math.round(n)),e=o,i=0,a=0,n=0,t=!1,s=!1},r=e=>{a&&window.cancelAnimationFrame(a),a=window.requestAnimationFrame(e?o:()=>{a=window.requestAnimationFrame(o)})},l=a=>{if(s)return void r(!1);const o=a[0].contentRect.height;if(!e)return void(e=o);const l=e-o;let d=l+n;const c=d%1;if(d-=c,!t&&(t=!0,l<0&&this.scrollable.isScrolledDown))return n=-l,s=!0,void r(!1);if(i+=d,d){const e=this.scrollable.scrollTop+d;this.scrollable.scrollTop=e}r(!1),n=c,e=o};new ResizeObserver(l).observe(this.bubblesContainer)}}saveOnUpdateScroll(){this.onUpdateScrollSaver||(this.onUpdateScrollSaver=new Aa(this.scrollable,!0),setTimeout((()=>{this.onUpdateScrollSaver.restore(),this.onUpdateScrollSaver=void 0}),0),this.onUpdateScrollSaver.save())}setReactionsHoverListeners(){this.listenerSetter.add(a.default)("context_menu_toggle",this.unhoverPrevious),this.listenerSetter.add(a.default)("overlay_toggle",this.unhoverPrevious),this.listenerSetter.add(this.chat.selection)("toggle",this.unhoverPrevious),this.listenerSetter.add(this.bubblesContainer)("mousemove",this.onBubblesMouseMove)}setHoverVisible(e,t){(0,Jt.Z)(e,"is-visible",t,200,t?void 0:()=>{e.remove()},2)}setStickyDateManually(){const e=Object.keys(this.dateMessages).map((e=>+e)).sort(((e,t)=>t-e));let t;const{scrollTop:s}=this.scrollable.container;if(s>0)for(const s of e){const e=this.dateMessages[s],i=Pa(e.container,this.scrollable.container);if(i&&i.overflow.top)t=e.div;else if(t)break}if(t!==this.previousStickyDate){if(t){const e=!this.previousStickyDate;e&&t.classList.add("no-transition"),t.classList.add("is-sticky"),e&&(t.offsetLeft,t.classList.remove("no-transition"))}this.previousStickyDate&&this.previousStickyDate!==t&&this.previousStickyDate.classList.remove("is-sticky"),this.previousStickyDate=t}}getRenderedLength(){return Object.keys(this.bubbles).length-this.skippedMids.size}onUnreadedInViewport(e,t){this.unreadedSeen.add(t),this.unreadedObserver.unobserve(e),this.unreaded.delete(e),this.readUnreaded()}readUnreaded(){if(this.readPromise)return;const e=this.getMiddleware();this.readPromise=a.default.idle.focusPromise.then((()=>{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(this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId).maxId||0,t))}this.unreaded.forEach(((e,s)=>{e<=t&&this.onUnreadedInViewport(s,e)}));const s=[];for(const e of this.unreadedSeen){const t=this.chat.getMessage(e);this.appMessagesManager.isMentionUnread(t)&&s.push(e)}return this.appMessagesManager.readMessages(this.peerId,s),this.unreadedSeen.clear(),re.ZP&&this.log("will readHistory by maxId:",t),this.appMessagesManager.readHistory(this.peerId,t,this.chat.threadId).catch((e=>{this.log.error("readHistory err:",e),this.appMessagesManager.readHistory(this.peerId,t,this.chat.threadId)})).finally((()=>{e()&&(this.readPromise=void 0,this.unreadedSeen.size&&this.readUnreaded())}))}))}constructPinnedHelpers(){this.listenerSetter.add(a.default)("peer_pinned_messages",(e=>{const{peerId:t,mids:s,pinned:i}=e;t===this.peerId&&s&&(i||this.deleteMessagesByIds(s))}))}constructScheduledHelpers(){const e=()=>{this.chat.topbar.setTitle(this.appMessagesManager.getScheduledMessagesStorage(this.peerId).size)};this.listenerSetter.add(a.default)("scheduled_new",(({peerId:t,mid:s})=>{t===this.peerId&&(this.renderNewMessagesByIds([s]),e())})),this.listenerSetter.add(a.default)("scheduled_delete",(({peerId:t,mids:s})=>{t===this.peerId&&(this.deleteMessagesByIds(s),e())}))}onGoDownClick(){if(this.replyFollowHistory.length){(0,b.Z)(this.replyFollowHistory,((e,t)=>{const s=this.bubbles[e];let i=!0;if(s){const e=s.getBoundingClientRect();i=Ct.Z.height/2>e.top}else this.chat.getMessage(e).deleted||(i=!1);i&&this.replyFollowHistory.splice(t,1)})),this.replyFollowHistory.sort(((e,t)=>t-e));const e=this.replyFollowHistory.pop();this.chat.setMessageId(e)}else this.chat.setMessageId()}getBubbleByPoint(e){let t=Vn(this.scrollable.container,e,"center");return t&&(t=(0,Me.Z)(t,"bubble")),t}getGroupedBubble(e){const t=this.appMessagesManager.groupedMessagesStorage[e];for(const[e]of t)if(this.bubbles[e]){const s=Math.max(...t.keys());return{bubble:this.bubbles[e],mid:+e,message:this.chat.getMessage(s)}}}getBubbleByMessage(e){if(!e.grouped_id)return this.bubbles[e.mid];const t=this.getGroupedBubble(e.grouped_id);return null==t?void 0:t.bubble}getBubbleGroupedItems(e){return Array.from(e.querySelectorAll(".grouped-item"))}getMountedBubble(e,t=this.chat.getMessage(e)){if(t.grouped_id&&this.appMessagesManager.getMidsByAlbum(t.grouped_id).length>1){const s=this.getGroupedBubble(t.grouped_id);if(s)return s.bubble=s.bubble.querySelector(`.document-container[data-mid="${e}"]`)||s.bubble,s}const s=this.bubbles[e];if(s)return{bubble:s,mid:e,message:t}}findNextMountedBubbleByMsgId(e){return this.bubbles[(0,Xs.Z)(this.bubbles).find((t=>{var s;return!(t<e||!(null===(s=this.bubbles[t])||void 0===s?void 0:s.parentElement))}))]}loadMoreHistory(e,t=!1){if(!this.peerId||this.chat.setPeerPromise||this.isHeavyAnimationInProgress||e&&(this.getHistoryTopPromise||this.scrollable.loadedAll.top)||!e&&(this.getHistoryBottomPromise||this.scrollable.loadedAll.bottom))return;const s=Object.keys(this.bubbles).map((e=>+e)).sort(((e,t)=>e-t));if(s.length)if(e)re.ZP&&this.log("Will load more (up) history by id:",s[0],"maxId:",s[s.length-1],t),this.getHistory(s[0],!0,void 0,void 0,t);else{const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId);if(-1!==s.indexOf(e.maxId))return void this.setLoaded("bottom",!0);re.ZP&&this.log("Will load more (down) history by id:",s[s.length-1],t),this.getHistory(s[s.length-1],!1,!0,void 0,t)}}setScroll(){this.scrollable=new P.ZP(null,"IM",300),this.setLoaded("top",!1),this.setLoaded("bottom",!1),this.scrollable.container.append(this.chatInner),this.scrollable.onAdditionalScroll=this.onScroll,this.scrollable.onScrolledTop=()=>this.loadMoreHistory(!0),this.scrollable.onScrolledBottom=()=>this.loadMoreHistory(!1),ce.IS_TOUCH_SUPPORTED&&(this.scrollable.container.addEventListener("touchmove",(()=>{this.isScrollingTimeout?clearTimeout(this.isScrollingTimeout):this.chatInner.classList.contains("is-scrolling")||this.chatInner.classList.add("is-scrolling")}),{passive:!0}),this.scrollable.container.addEventListener("touchend",(()=>{this.chatInner.classList.contains("is-scrolling")&&(this.isScrollingTimeout&&clearTimeout(this.isScrollingTimeout),this.isScrollingTimeout=window.setTimeout((()=>{this.chatInner.classList.remove("is-scrolling"),this.isScrollingTimeout=0}),1350))}),{passive:!0}))}updateUnreadByDialog(){const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId),t=this.peerId===a.default.myId?e.readMaxId:e.readOutboxMaxId;for(const e of this.unreadOut)if(e>0&&e<=t){const t=this.bubbles[e];if(t){if(t.classList.contains("is-outgoing"))continue;t.classList.remove("is-sent","is-sending","is-outgoing"),t.classList.add("is-read")}this.unreadOut.delete(e)}}deleteMessagesByIds(e,t=!0){let s=!1;e.forEach((e=>{if(!(e in this.bubbles))return;s=!0;const t=this.bubbles[e];delete this.bubbles[e],this.skippedMids.delete(e),this.firstUnreadBubble===t&&(this.firstUnreadBubble=null),this.bubbleGroups.removeBubble(t),this.unreadedObserver&&(this.unreadedObserver.unobserve(t),this.unreaded.delete(t)),this.viewsObserver&&(this.viewsObserver.unobserve(t),this.viewsMids.delete(e)),t.remove(),this.emptyPlaceholderMid===e&&(this.emptyPlaceholderMid=void 0)})),s&&(t&&this.chat.selection.isSelecting&&this.chat.selection.deleteSelectedMids(this.peerId,e),I.Z.checkAnimations(!1,Bl),this.deleteEmptyDateGroups(),this.onScroll())}renderNewMessagesByIds(e,t){if(!this.scrollable.loadedAll.bottom){const t=this.chat.setPeerPromise;if(t){const s=this.getMiddleware();t.then((()=>{s()&&this.renderNewMessagesByIds(e)}))}return}this.chat.threadId&&(e=e.filter((e=>{const t=this.chat.getMessage(e).reply_to;return t&&(t.reply_to_top_id||t.reply_to_msg_id)===this.chat.threadId}))),e=e.filter((e=>!this.bubbles[e])),t||(t=this.scrolledDown&&(!this.scrollingToBubble||this.scrollingToBubble===this.getLastBubble()||this.scrollingToBubble===this.chatInner));const s=this.getMiddleware();let i,n=!1;if(!this.isTopPaddingSet){const{clientHeight:e,scrollHeight:t}=this.scrollable.container;n=e===t,n&&(i=this.chatInner,i.style.paddingTop=e+"px",this.scrollable.scrollTop=t,this.isTopPaddingSet=!0)}const a=this.performHistoryResult(e,!1,!0);t&&a.then((()=>{if(!s())return;let t;"scheduled"===this.chat.type&&(t=this.bubbles[Math.max(...e)]);const a=t?this.scrollToBubbleEnd(t):this.scrollToEnd();n&&a.then((()=>{s()&&n&&(i.style.paddingTop="",this.isTopPaddingSet=!1)}))}))}getLastBubble(){const e=this.getLastDateGroup();if(e)return e.lastElementChild}scrollToBubble(e,t,s,i){const n=(0,Me.Z)(e,"bubble");let a;n&&"end"!==t&&(0,_s.Z)(n)===(this.stickyIntersector?2:1)&&(a=n.parentElement);const o=this.chat.input.messageInput&&this.chat.input.messageInput.classList.contains("is-changing-height")||this.chat.container.classList.contains("is-toggling-helper");return this.scrollable.scrollIntoViewNew({element:e,position:t,margin:4,forceDirection:s,forceDuration:i,axis:"y",getNormalSize:o?({rect:e})=>{let t=Ct.Z.height;return t-=this.bubblesContainer.offsetTop,t-=v.ZP.isMobile||Ct.Z.height<570?58:78,t}:void 0,fallbackToElementStartWhenCentering:a})}scrollToEnd(){return this.scrollToBubbleEnd(this.chatInner)}scrollToBubbleEnd(e){return _a(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}}))}getLastDateGroup(){let e,t=0;for(const s in this.dateMessages){const i=this.dateMessages[s];i.firstTimestamp>t&&(e=i.container,t=i.firstTimestamp)}return e}scrollToBubbleIfLast(e){return _a(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)}getDateContainerByMessage(e,t){const s=new Date(1e3*e.date);s.setHours(0,0,0);const i=s.getTime();if(!this.dateMessages[i]){let t;const n=new Date;n.setHours(0,0,0,0);const a="scheduled"===this.chat.type;if(n.getTime()===s.getTime())t=(0,k.i18n)(a?"Chat.Date.ScheduledForToday":"Date.Today");else if(a&&e.date===La)t=(0,k.i18n)("MessageScheduledUntilOnline");else{const e={day:"numeric",month:"long"};s.getFullYear()!==n.getFullYear()&&(e.year="numeric"),t=new k.default.IntlDateElement({date:s,options:e}).element,a&&(t=(0,k.i18n)("Chat.Date.ScheduledFor",[t]))}const o=document.createElement("div");o.className="bubble service is-date";const r=document.createElement("div");r.classList.add("bubble-content");const l=document.createElement("div");l.classList.add("service-msg"),l.append(t),r.append(l),o.append(r);const d=document.createElement("section");d.className="bubbles-date-group",d.append(o),this.dateMessages[i]={div:o,container:d,firstTimestamp:s.getTime()};const c=(0,Xs.Z)(this.dateMessages,"asc");let h,p=0,u=c.length;for(;p<c.length;++p){const e=c[p];if(h=this.dateMessages[e].container,i<e)break}p===u&&h&&(h=h.nextElementSibling),h?this.chatInner.insertBefore(d,h):this.chatInner.append(d),this.stickyIntersector&&this.stickyIntersector.observeStickyHeaderChanges(d)}return this.dateMessages[i]}destroy(){this.scrollable.onScrolledTop=this.scrollable.onScrolledBottom=this.scrollable.onAdditionalScroll=null,this.listenerSetter.removeAll(),this.lazyLoadQueue.clear(),this.unreadedObserver&&this.unreadedObserver.disconnect(),this.viewsObserver&&this.viewsObserver.disconnect(),this.stickyIntersector&&this.stickyIntersector.disconnect(),delete this.lazyLoadQueue,this.unreadedObserver&&delete this.unreadedObserver,this.viewsObserver&&delete this.viewsObserver,this.stickyIntersector&&delete this.stickyIntersector}cleanup(e=!1){this.bubbles={},this.setLoaded("top",!1),this.setLoaded("bottom",!1),(0,Ue.Kx)(this.scrollable.container),(0,xs.gp)(),void 0!==Ra&&(Ra=Fa),this.skippedMids.clear(),this.dateMessages={},this.bubbleGroups.cleanup(),this.unreadOut.clear(),this.needUpdate.length=0,this.lazyLoadQueue.clear(),e&&(this.scrollable.container.textContent=""),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.unreadedObserver&&(this.unreadedObserver.disconnect(),this.unreaded.clear(),this.unreadedSeen.clear(),this.readPromise=void 0),this.viewsObserver&&(this.viewsObserver.disconnect(),this.viewsMids.clear()),this.loadedTopTimes=this.loadedBottomTimes=0,this.middleware.clean(),this.onAnimateLadder=void 0,this.resolveLadderAnimation=void 0,this.emptyPlaceholderMid=void 0,this.sponsoredMessage=void 0,this.previousStickyDate=void 0,this.scrollingToBubble=void 0,this.isTopPaddingSet=!1,this.isScrollingTimeout&&(clearTimeout(this.isScrollingTimeout),this.isScrollingTimeout=0)}setPeer(e,t,s){var i;if(!e)return this.cleanup(!0),this.peerId=e,null;const n=this.peerId===e,a=this.chat.type;("scheduled"===a||this.chat.isRestricted)&&(t=0);const o=this.historyStorage=this.appMessagesManager.getHistoryStorage(e,this.chat.threadId);let r="pinned"===a?this.appMessagesManager.pinnedMessages[e].maxId:null!==(i=this.historyStorage.maxId)&&void 0!==i?i:0;const l=void 0!==t;let d,c,h,p=0;if(!l)if(n||(c=this.chat.appImManager.getChatSavedPosition(this.chat)),c);else if(r){p=this.appMessagesManager.getReadMaxIdIfUnread(e,this.chat.threadId);const s=this.appMessagesManager.getDialogOnly(e);if(!p||n||s&&1===s.unread_count)t=r;else{const e=o.history.findSliceOffset(p);e&&e.slice.isEnd(zn.D.Bottom)&&(h=e.slice[e.offset-25]||e.slice[0]||p),d=!l,t=p}}const u=t!==r,{scrollable:g}=this;if(n){const e=this.getMountedBubble(t);if(e)return l?(this.scrollToBubble(e.bubble,"center"),this.highlightBubble(e.bubble),this.chat.dispatchEvent("setPeer",t,!1)):r&&!u&&(g.scrollTop=g.scrollHeight,this.chat.dispatchEvent("setPeer",t,!0)),void 0!==s&&this.chat.input.setStartParam(s),null}else this.peerId&&(this.lazyLoadQueue.queueId=++Ba,this.chat.apiManager.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)),this.peerId=e,this.replyFollowHistory.length=0,this.passEntities={messageEntityBotCommand:this.appPeersManager.isAnyGroup(e)||this.appUsersManager.isBot(e)};re.ZP&&this.log("setPeer peerId:",e,this.historyStorage,t,r);const m=null!=h?h:u||"scheduled"===a||this.chat.isRestricted?0:r;let v=0;if(n){let e=this.getBubbleByPoint("bottom");e&&(v=+e.dataset.mid),v<=0&&(v=Math.max(...Object.keys(this.bubbles).map((e=>+e))))}else this.isFirstLoad=!0;const f=this.chatInner;this.cleanup();const b=this.chatInner=document.createElement("div");let y;n?(b.className=f.className,b.classList.remove("disable-hover","is-scrolling")):b.classList.add("bubbles-inner"),this.lazyLoadQueue.lock(),y=c?{promise:(0,xs.e9)().then((()=>this.performHistoryResult(c.mids,!0,!1,void 0))),cached:!0}:this.getHistory(t,!0,u,m);const{promise:w,cached:S}=y;S||n||(g.container.textContent="",this.chat.finishPeerChange(l,u,t,s),this.preloader.attach(this.bubblesContainer)),I.Z.lockGroup(Bl);const C=w.then((()=>{if(S?n||this.chat.finishPeerChange(l,u,t,s):this.preloader.detach(),this.resolveLadderAnimation&&(this.resolveLadderAnimation(),this.resolveLadderAnimation=void 0),g.lastScrollDirection=0,g.lastScrollPosition=0,(0,T.Z)(g.container,b),I.Z.unlockGroup(Bl),I.Z.checkAnimations(!1,Bl),this.lazyLoadQueue.unlock(),c)g.scrollTop=g.lastScrollPosition=c.top;else if(r&&u||l){const e=v>0&&(v<t||t<0);!e&&n?g.scrollTop=g.lastScrollPosition=99999:e&&(g.scrollTop=g.lastScrollPosition=0);const s=this.getMountedBubble(t);let i=d&&this.firstUnreadBubble||(null==s?void 0:s.bubble);(null==i?void 0:i.parentElement)||(i=this.findNextMountedBubbleByMsgId(t)),i&&(this.scrollToBubble(i,d?"start":"center",n?void 0:yt.f.Static),d||this.highlightBubble(i))}else g.scrollTop=g.lastScrollPosition=99999;this.onScroll();const i=this.getMiddleware(),o=Promise.all([C,(0,xs.e9)()]);if(o.then((()=>{g.checkForTriggers()})),this.chat.dispatchEvent("setPeer",t,!u),this.appPeersManager.isChannel(e)){const e=this.getMiddleware(),t=()=>{if(!e())return;const s=[];for(const e in this.bubbles){let t=this.chat.getMessage(+e);"message"===t._&&(t=this.appMessagesManager.getGroupsFirstMessage(t),s.push(t.mid))}(s.length?this.appReactionsManager.getMessagesReactions(this.peerId,s):Promise.resolve()).then((()=>{setTimeout(t,1e4)}))};Promise.all([o,(0,xs.e9)(),(0,Kn.w)(500)]).then((()=>{t()}))}const h=this.appMessagesManager.isFetchIntervalNeeded(e);if(c||h?o.then((()=>{if(i()&&(g.checkForTriggers(),h)){const t=()=>{this.fetchNewPromise=new Promise((s=>{i()&&this.appMessagesManager.isFetchIntervalNeeded(e)?this.appMessagesManager.getNewHistory(e,this.chat.threadId).then((e=>{if(!i()||!e)return void s();const n=e.history.slice.isEnd(zn.D.Bottom);g.loadedAll.bottom&&g.loadedAll.bottom!==n&&(this.setLoaded("bottom",n),this.onScroll()),setTimeout(t,3e4),s()})):s()})).finally((()=>{this.fetchNewPromise=void 0}))};n?setTimeout(t,3e4):t()}})):t&&!this.bubbles[r]&&t!==r||this.setLoaded("bottom",!0),this.log("scrolledAllDown:",g.loadedAll.bottom),g.loadedAll.bottom&&r&&!this.unreaded.size&&this.onScrolledAllDown(),"chat"===a){const t=this.appMessagesManager.getDialogOnly(e);(null==t?void 0:t.pFlags.unread_mark)&&this.appMessagesManager.markDialogUnread(e,!0)}})).catch((e=>{throw this.log.error("getHistory promise error:",e),this.preloader.detach(),e}));return{cached:S,promise:C}}onScrolledAllDown(){if("chat"===this.chat.type||"discussion"===this.chat.type){const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId);this.appMessagesManager.readHistory(this.peerId,e.maxId,this.chat.threadId,!0)}}finishPeerChange(){const e=this.appPeersManager.isChannel(this.peerId),t=this.chat.canSend();this.chatInner.classList.toggle("has-rights",t),this.bubblesContainer.classList.toggle("is-chat-input-hidden",!t),this.chatInner.classList.toggle("is-chat",this.chat.isAnyGroup()),this.chatInner.classList.toggle("is-channel",e)}renderMessagesQueue(e,t,s,i){return this.messagesQueue.push({message:e,bubble:t,reverse:s,promises:i}),this.setMessagesQueuePromise()}setMessagesQueuePromise(){return this.messagesQueuePromise||!this.messagesQueue.length?Promise.resolve():this.messagesQueuePromise=new Promise(((e,t)=>{setTimeout((()=>{const s=this.messagesQueue.slice();this.messagesQueue.length=0;const i=s.reduce(((e,{promises:t})=>(e.push(...t),e)),[]);this.log("promises to call",i,s,this.isHeavyAnimationInProgress);const n=this.getMiddleware();Promise.all(i).then((()=>{if(!n())throw"setMessagesQueuePromise: peer changed!";this.messagesQueueOnRender&&this.messagesQueueOnRender(),this.messagesQueueOnRenderAdditional&&this.messagesQueueOnRenderAdditional(),s.forEach((({message:e,bubble:t,reverse:s})=>{this.setBubblePosition(t,e,s)})),e(),this.messagesQueuePromise=null,this.messagesQueue.length&&this.setMessagesQueuePromise(),this.setUnreadDelimiter()})).catch(t)}),0)}))}setBubblePosition(e,t,s){if(t.pFlags.local)return void this.chatInner[t.pFlags.sponsored?"append":"prepend"](e);const i=this.getDateContainerByMessage(t,s);if("scheduled"===this.chat.type||"pinned"===this.chat.type){const s=this.stickyIntersector?2:1;let n=Array.from(i.container.children).slice(s),a=0,o=0;for(;a<n.length;++a){const e=n[a],s=+e.dataset.timestamp;if(t.date<s)break;if(t.date===s&&(o=+e.dataset.mid),o&&t.mid<o)break}let r=s+a;Zs(e,i.container,r)}else s?i.container.insertBefore(e,i.container.children[this.stickyIntersector?1:0].nextSibling):i.container.append(e);"message"===t._||t.action&&Da.has(t.action._)?this.bubbleGroups.addBubble(e,t,s):e.classList.add("is-group-first","is-group-last")}getMiddleware(e){return this.middleware.get(e)}renderMessage(e,t=!1,s=!1,i=null,n=!0){var o,r;if(!i&&this.bubbles[e.mid])return;const c="message"===e._,h=c&&e.grouped_id,p="pinned"!==this.chat.type;if(e.deleted)return;if(h&&p){const t=this.appMessagesManager.groupedMessagesStorage[h],s=Math.max(...t.keys());if(e.mid<s)return}const u=this.peerId,g=e.fromId===a.default.myId||e.pFlags.out&&this.appPeersManager.isMegagroup(u),f=document.createElement("div");let b,y;if(f.classList.add("message"),i){const t=["is-highlighted","is-group-first","is-group-last"],s=i.className.split(" "),n=["bubble"].concat(t.filter((e=>s.includes(e))));i.className=n.join(" "),y=i.lastElementChild,y.classList.contains("bubble-content-wrapper")||(y=i.querySelector(".bubble-content-wrapper")),b=y.firstElementChild,b.innerHTML="",b.style.cssText="",y.innerHTML="",y.appendChild(b);const a=y.style.transitionDelay;y.style.cssText="",y.style.transitionDelay=a,i===this.firstUnreadBubble&&i.classList.add("is-first-unread");const o=+i.dataset.mid;+e.mid===o||(delete this.bubbles[o],this.skippedMids.delete(o))}else y=document.createElement("div"),y.classList.add("bubble-content-wrapper"),b=document.createElement("div"),b.classList.add("bubble-content"),(i=document.createElement("div")).classList.add("bubble"),y.appendChild(b),i.appendChild(y),g||e.pFlags.out||!this.unreadedObserver||(e.pFlags.unread||this.appMessagesManager.isMentionUnread(e)||void 0!==this.historyStorage.readMaxId&&this.historyStorage.readMaxId<e.mid)&&(this.unreadedObserver.observe(i),this.unreaded.set(i,e.mid));this.bubbles[+e.mid]=i,i.dataset.mid=""+e.mid,i.dataset.peerId=""+e.peerId,i.dataset.timestamp=""+e.date;const w=[];if(!("messageService"!==e._||e.action&&Da.has(e.action._))){const s=e.action;if(s){const t=s._;if(Za.has(t)||k.langPack.hasOwnProperty(t)&&!k.langPack[t])return this.skippedMids.add(+e.mid),i}i.className="bubble service",b.innerHTML="";const a=document.createElement("div");return a.classList.add("service-msg"),s&&("messageActionChannelMigrateFrom"===s._?a.append((0,k.i18n)("ChatMigration.From",[new St.Z({peerId:s.chat_id.toPeerId(!0)}).element])):"messageActionChatMigrateTo"===s._?a.append((0,k.i18n)("ChatMigration.To",[new St.Z({peerId:s.channel_id.toPeerId(!0)}).element])):a.append(this.appMessagesManager.wrapMessageActionTextNew(e))),b.append(a),n&&(this.renderMessagesQueue(e,i,t,w),e.pFlags.is_single&&i.classList.add("is-group-last")),i}let S,C,L=c&&e.media;if(c)if((null==L?void 0:L.document)&&!["video","gif"].includes(L.document.type));else if(h&&p){const e=this.appMessagesManager.getAlbumText(h);S=e.message,C=e.totalEntities}else"sticker"!==(null===(o=null==L?void 0:L.document)||void 0===o?void 0:o.type)&&(S=e.message,C=e.totalEntities);else"messageActionPhoneCall"===e.action._&&(L={_:"messageMediaCall",action:e.action});let I=Q.Z.wrapRichText(S,{entities:C,passEntities:this.passEntities}),M=!0,E=!1,P=!0;if(C&&!L){let e=C.filter((e=>"messageEntityEmoji"===e._)),t=S.length;if(e.reduce(((e,t)=>e+t.length),0)===t&&e.length<=3&&C.length===e.length){if(a.default.settings.emoji.big){let t=this.appStickersManager.getAnimatedEmojiSticker(S);if(1===e.length&&!L&&t)L={_:"messageMediaDocument",document:t};else{let t=document.createElement("div");t.classList.add("attachment"),t.innerHTML=I,i.classList.add("emoji-"+e.length+"x"),b.append(t)}i.classList.add("is-message-empty","emoji-big"),E=!0,M=!1,P=!1}i.classList.add("can-have-big-emoji")}}P&&m(f,I);const T=Hn.setTime({chatType:this.chat.type,message:e});if(f.append(T),b.prepend(f),c&&e.views){if(i.classList.add("channel-post"),!(null===(r=e.fwd_from)||void 0===r?void 0:r.saved_from_msg_id)&&"pinned"!==this.chat.type){const e=document.createElement("div");e.classList.add("bubble-beside-button","forward","tgico-forward_filled"),b.prepend(e),i.classList.add("with-beside-button")}!e.pFlags.is_outgoing&&this.viewsObserver&&this.viewsObserver.observe(i)}const x=c&&e.reply_markup;if(x&&"replyInlineMarkup"===x._&&x.rows&&x.rows.length){const t=x.rows,s=document.createElement("div");s.classList.add("reply-markup"),t.forEach((t=>{const i=t.buttons;if(!i||!i.length)return;const n=document.createElement("div");n.classList.add("reply-markup-row"),i.forEach((t=>{const s=Q.Z.wrapRichText(t.text,{noLinks:!0,noLinebreaks:!0});let i;switch(t._){case"keyboardButtonUrl":{const e=Q.Z.wrapRichText(" ",{entities:[{_:"messageEntityTextUrl",length:1,offset:0,url:t.url}]});i=(0,Vs.Z)(e).firstElementChild,i.classList.add("is-link","tgico");break}case"keyboardButtonSwitchInline":i=document.createElement("button"),i.classList.add("is-switch-inline","tgico"),(0,l.fc)(i,(s=>{(0,d.d)(s);const i=e.viaBotId||e.fromId;let n;n=t.pFlags.same_peer?Promise.resolve(this.peerId):this.appInlineBotsManager.checkSwitchReturn(i).then((e=>e||new Promise(((e,t)=>{const s=new Hs({[this.peerId]:[]},(t=>{e(t)}),!0);s.addEventListener("close",(()=>{t()}))})))),n.then((e=>{const s=this.peerId===e?this.chat.threadId:void 0;this.appInlineBotsManager.switchInlineQuery(e,s,i,t.query)}))}));break;default:i=document.createElement("button")}i.classList.add("reply-markup-button","rp"),i.insertAdjacentHTML("beforeend",s),(0,ee.ripple)(i),n.append(i)})),s.append(n)})),(0,l.fc)(s,(s=>{let i=s.target;if(i.classList.contains("reply-markup-button")||(i=(0,Me.Z)(i,"reply-markup-button")),!i||i.classList.contains("is-link")||i.classList.contains("is-switch-inline"))return;(0,d.d)(s);const n=(0,_s.Z)(i),a=t[(0,_s.Z)(i.parentElement)];if(!a.buttons||!a.buttons[n])return void this.log.warn("no such button",a,n,e);const o=a.buttons[n];this.appInlineBotsManager.callbackButtonClick(this.peerId,e.mid,o)})),M=!1,i.classList.add("with-reply-markup"),y.append(s)}const A=e.pFlags.is_outgoing;if(g){(e.pFlags.unread||A)&&this.unreadOut.add(e.mid);let t="";t=A?"is-sending":e.pFlags.unread||e.pFlags.is_scheduled?"is-sent":"is-read",i.classList.add(t)}A&&i.classList.add("is-outgoing");const _=c&&this.appMessagesManager.getMessageWithReplies(e),Z=!!_&&e.mid>0;Z&&i.classList.add("with-replies");const D=c&&e.fwd_from,F=c&&e.fwdFromId,R=g&&(!D||this.peerId!==a.default.myId);let B=b;const U=!(e.viaBotId||e.fromId!==a.default.myId&&e.pFlags.out);if(L){let t=document.createElement("div");t.classList.add("attachment"),S||i.classList.add("is-message-empty");let s=!1;switch(L._){case"messageMediaPhoto":{const s=L.photo;S||(M=!1),U&&i.classList.add("hide-name"),i.classList.add("photo");const n=this.appMessagesManager.groupedMessagesStorage[h];if(h&&1!==n.size&&p){i.classList.add("is-album","is-grouped"),ks({groupId:h,attachmentDiv:t,middleware:this.getMiddleware(),isOut:g,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:w,autoDownload:this.chat.autoDownload});break}const a=!ne.IS_ANDROID&&M&&!Z&&!1;a&&i.classList.add("with-media-tail"),Ss({photo:s,message:e,container:t,withTail:a,isOut:R,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:w,autoDownloadSize:this.chat.autoDownload.photo});break}case"messageMediaWebPage":{s=!0;let t=L.webpage;if("webPage"!==t._)break;i.classList.add("webpage");let n=document.createElement("div");n.classList.add("web");let a,o,r=document.createElement("div");r.classList.add("quote");const l=t.photo;(l||t.document)&&(a=document.createElement("div"),a.classList.add("preview-resizer"),o=document.createElement("div"),o.classList.add("preview"),a.append(o));const d=t.document;if(d)if("gif"===d.type||"video"===d.type||"round"===d.type){const t="round"===d.type?v.ZP.active.round:v.ZP.active.webpage;"round"===d.type?(i.classList.add("round"),o.classList.add("is-round")):i.classList.add("video"),ys({doc:d,container:o,message:e,boxWidth:t.width,boxHeight:t.height,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),isOut:R,group:Bl,loadPromises:w,autoDownload:this.chat.autoDownload})}else{const t=ws({message:e,autoDownloadSize:this.chat.autoDownload.file,lazyLoadQueue:this.lazyLoadQueue,loadPromises:w});o.append(t),o.classList.add("preview-with-document")}let c,h=document.createElement("div");if(h.classList.add("quote-text"),a&&h.append(a),t.site_name){const e=Q.Z.wrapRichText(t.url),s=(0,Vs.Z)(e).firstElementChild;s.classList.add("webpage-name");const i=document.createElement("strong");m(i,Q.Z.wrapEmojiText(t.site_name)),s.textContent="",s.append(i),h.append(s),c=s}if(t.rTitle){let e=document.createElement("div");e.classList.add("title");const s=document.createElement("strong");m(s,t.rTitle),e.append(s),h.append(e),c=e}if(t.rDescription){let e=document.createElement("div");e.classList.add("text"),m(e,t.rDescription),h.append(e),c=e}if(r.append(h),l&&!d){i.classList.add("photo");const t=l.sizes[l.sizes.length-1];let s=!1;t.w===t.h&&c?(i.classList.add("is-square-photo"),s=!0,this.appPhotosManager.setAttachmentSize(l,o,48,48,!1)):t.h>t.w&&i.classList.add("is-vertical-photo"),Ss({photo:l,message:e,container:o,boxWidth:s?0:v.ZP.active.webpage.width,boxHeight:s?0:v.ZP.active.webpage.height,isOut:R,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:w,withoutPreloader:s,autoDownloadSize:this.chat.autoDownload.photo})}n.append(r),f.insertBefore(n,T);break}case"messageMediaDocument":{const n=L.document;if(n.sticker){i.classList.add("sticker"),M=!1,E=!0,n.animated&&i.classList.add("sticker-animated");const e=v.ZP.active,s=i.classList.contains("emoji-big")?e.emojiSticker:n.animated?e.animatedSticker:e.staticSticker;this.appPhotosManager.setAttachmentSize(n,t,s.width,s.height),b.style.minWidth=t.style.width,b.style.minHeight=t.style.height,Is({doc:n,div:t,middleware:this.getMiddleware(),lazyLoadQueue:this.lazyLoadQueue,group:Bl,play:!0,loop:!0,emoji:i.classList.contains("emoji-big")?S:void 0,withThumb:!0,loadPromises:w})}else if("video"===n.type||"gif"===n.type||"round"===n.type){const s="round"===n.type;s&&(E=!0),!s&&S||(M=!1),U&&i.classList.add("hide-name"),i.classList.add(s?"round":"video");const a=this.appMessagesManager.groupedMessagesStorage[h];if(h&&1!==a.size&&p)i.classList.add("is-album","is-grouped"),ks({groupId:h,attachmentDiv:t,middleware:this.getMiddleware(),isOut:g,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:w,autoDownload:this.chat.autoDownload});else{const a=!ne.IS_ANDROID&&!ne.IS_APPLE&&!s&&M&&!Z&&!1;a&&i.classList.add("with-media-tail"),ys({doc:n,container:t,message:e,boxWidth:v.ZP.active.regular.width,boxHeight:v.ZP.active.regular.height,withTail:a,isOut:R,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),group:Bl,loadPromises:w,autoDownload:this.chat.autoDownload,searchContext:s?{peerId:this.peerId,inputFilter:{_:"inputMessagesFilterRoundVoice"},threadId:this.chat.threadId,useSearch:!e.pFlags.is_scheduled,isScheduled:e.pFlags.is_scheduled}:void 0})}}else{const t=function({albumMustBeRenderedFull:e,message:t,bubble:s,messageDiv:i,chat:n,loadPromises:a,autoDownloadSize:o,lazyLoadQueue:r,searchContext:l,useSearch:d}){let c;const h=e?n.getMidsByMid(t.mid):[t.mid];return h.forEach(((e,t)=>{const s=n.getMessage(e),d=ws({message:s,loadPromises:a,autoDownloadSize:o,lazyLoadQueue:r,searchContext:l}),p=document.createElement("div");p.classList.add("document-container"),p.dataset.mid=""+e,p.dataset.peerId=""+s.peerId;const u=document.createElement("div");if(u.classList.add("document-wrapper"),s.message){const e=document.createElement("div");e.classList.add("document-message");const t=Q.Z.wrapRichText(s.message,{entities:s.totalEntities});e.innerHTML=t,u.append(e)}if(h.length>1){const e=document.createElement("div");e.classList.add("document-selection"),p.append(e),p.classList.add("grouped-item"),0===t&&(c=u)}u.append(d),p.append(u),i.append(p)})),h.length>1&&s.classList.add("is-multiple-documents","is-grouped"),c}({albumMustBeRenderedFull:p,message:e,bubble:i,messageDiv:f,chat:this.chat,loadPromises:w,autoDownloadSize:this.chat.autoDownload.file,lazyLoadQueue:this.lazyLoadQueue,searchContext:"voice"===n.type||"audio"===n.type?{peerId:this.peerId,inputFilter:{_:"voice"===n.type?"inputMessagesFilterRoundVoice":"inputMessagesFilterMusic"},threadId:this.chat.threadId,useSearch:!e.pFlags.is_scheduled,isScheduled:e.pFlags.is_scheduled}:void 0});t&&(B=t);const a=f.lastElementChild.querySelector(".document-message, .document-size, .audio");a&&a.append(T),i.classList.remove("is-message-empty"),f.classList.add((["photo","pdf"].includes(n.type)?"document":n.type||"document")+"-message"),s=!0}break}case"messageMediaCall":{const e=L.action,t=document.createElement("div");t.classList.add("bubble-call",e.pFlags.video?"tgico-videocamera":"tgico-phone");const n=e.pFlags.video?"video":"voice";t.dataset.type=n;const a=document.createElement("div");a.classList.add("bubble-call-title"),(0,k._i18n)(a,R?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((0,Ia.Z)(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,k._i18n)(o,t)}o.classList.add("tgico","arrow-"+(void 0!==e.duration?"green":"red")),t.append(a,o),s=!0,i.classList.remove("is-message-empty"),f.classList.add("call-message"),f.append(t);break}case"messageMediaContact":{const e=L,t=document.createElement("div");t.classList.add("contact"),t.dataset.peerId=""+e.user_id,s=!0;const n=[];e.first_name&&n.push(Q.Z.wrapEmojiText(e.first_name)),e.last_name&&n.push(Q.Z.wrapEmojiText(e.last_name)),t.innerHTML=`\n <div class="contact-details">\n <div class="contact-name">${n.join(" ")}</div>\n <div class="contact-number">${e.phone_number?"+"+(0,Os.u)(e.phone_number).formatted:"Unknown phone number"}</div>\n </div>`;const a=new Yl;a.lazyLoadQueue=this.lazyLoadQueue,a.setAttribute("peer",""+e.user_id.toPeerId()),a.classList.add("contact-avatar","avatar-54"),t.prepend(a),i.classList.remove("is-message-empty"),f.classList.add("contact-message"),f.append(t);break}case"messageMediaPoll":{i.classList.remove("is-message-empty");const t=function(e){const t=new os;return t.message=e,t.setAttribute("peer-id",""+e.peerId),t.setAttribute("poll-id",e.media.poll.id),t.setAttribute("message-id",""+e.mid),t.render(),t}(e);f.prepend(t),f.classList.add("poll-message");break}default:i.classList.remove("is-message-empty"),f.append((0,k.i18n)(k.UNSUPPORTED_LANG_PACK_KEY),T),this.log.warn("unrecognized media type:",L._,e)}s||b.append(t)}E&&i.classList.add("just-media"),this.chat.selection.isSelecting&&this.chat.selection.toggleElementCheckbox(i,!0);let N="";const O=e.fromId!==a.default.myId&&this.appPeersManager.isAnyGroup(u)||e.viaBotId||e.pFlags.sponsored;if(O||D||e.reply_to_mid){let t,s;const n=e.from_id&&"peerChannel"===e.from_id._&&e.fromId===F;let o,r=D&&!D.from_id;if(e.viaBotId&&(s=document.createElement("span"),s.innerText="@"+this.appUsersManager.getUser(e.viaBotId).username,s.classList.add("peer-title"),i.classList.add("must-have-name")),r?(t=document.createElement("span"),t.innerHTML=Q.Z.wrapEmojiText(D.from_name),t.classList.add("peer-title"),i.classList.add("hidden-profile")):t=new St.Z({peerId:F||e.fromId}).element,e.reply_to_mid&&e.reply_to_mid!==this.chat.threadId&&c&&Hn.setReply({chat:this.chat,bubble:i,bubbleContainer:b,message:e}),F||D)if(this.peerId===a.default.myId||n||i.classList.add("forwarded"),e.savedFrom&&(N=e.savedFrom,t.dataset.savedFrom=N),o=document.createElement("div"),t.dataset.peerId=""+F,this.peerId!==a.default.myId&&this.peerId!==Re.hj&&!n||E){const e=[t];E&&e.unshift(document.createElement("br")),o.append((0,k.i18n)("ForwardedFrom",[e]))}else o.style.color=this.appPeersManager.getPeerColorById(F,!1),o.append(t);else e.viaBotId||(!E&&O?(o=document.createElement("div"),o.append(t),g||(o.style.color=this.appPeersManager.getPeerColorById(e.fromId,!1)),o.dataset.peerId=""+e.fromId):i.classList.add("hide-name"));if(e.viaBotId){o?o.append(" "):o=document.createElement("div");const e=document.createElement("span");e.append((0,k.i18n)("ViaBot")," ",s),e.classList.add("is-via"),o.append(e)}if(o&&(o.classList.add("name"),B.append(o)),this.chat.isAnyGroup()&&!R){let t=new Yl;t.lazyLoadQueue=this.lazyLoadQueue,t.classList.add("user-avatar","avatar-40"),t.loadPromises=w,!F&&D&&D.from_name&&t.setAttribute("peer-title",D.from_name),t.setAttribute("peer",""+((D&&(this.peerId===a.default.myId||this.peerId===Re.hj)||n?F:e.fromId)||Re.NM)),y.append(t)}}else i.classList.add("hide-name");if("pinned"===this.chat.type&&(N=`${this.chat.peerId}_${e.mid}`),_&&_.mid===this.chat.threadId&&i.classList.add("is-thread-starter","is-group-last"),N&&("pinned"===this.chat.type||D.saved_from_msg_id)&&this.peerId!==Re.hj){const e=document.createElement("div");e.classList.add("bubble-beside-button","goto-original","tgico-arrow_next"),b.append(e),i.dataset.savedFrom=N,i.classList.add("with-beside-button")}return i.classList.add(R?"is-out":"is-in"),n&&this.renderMessagesQueue(e,i,t,w),Z&&Hn.renderReplies({bubble:i,bubbleContainer:b,message:_,messageDiv:f,loadPromises:w,lazyLoadQueue:this.lazyLoadQueue})&&(M=!0),c&&this.appendReactionsElementToBubble(i,e),M&&(i.classList.add("can-have-tail"),b.append(Na())),i}appendReactionsElementToBubble(e,t,s){if(this.peerId.isUser())return;const i=this.appMessagesManager.getGroupsFirstMessage(t);if(!i.reactions||!i.reactions.results.length)return;const n=new Bn;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 i=e.querySelector(".document-message"),a=i&&i.querySelector(".time");a||(a=Hn.setTime({chatType:this.chat.type,message:t})),n.append(a),i||(i=document.createElement("div"),i.classList.add("document-message"),e.querySelector(".document-wrapper").prepend(i)),i.append(n)}else{const t=Array.from(e.querySelectorAll(".time")).pop();n.append(t),s.append(n)}}}safeRenderMessage(e,t,s,i,n){try{return this.renderMessage(e,t,s,i,n)}catch(e){this.log.error("renderMessage error:",e)}}performHistoryResult(e,t,s,i){return _a(this,void 0,void 0,(function*(){let s;e=e.slice(),i&&e.unshift(i),this.messagesQueueOnRender=()=>{s=new Aa(this.scrollable,t),s.save()},this.needReflowScroll&&(jn(this.scrollable.container),this.needReflowScroll=!1);const n=e=>{const s="number"==typeof e?this.chat.getMessage(e):e;s.pFlags.local?this.processLocalMessageRender(s):this.safeRenderMessage(s,t,!0)},a=e.length;if(t)for(let t=0;t<a;++t)n(e[t]);else for(let t=a-1;t>=0;--t)n(e[t]);if("scheduled"!==this.chat.type){const t=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId),s=t.history.first,i=t.history.last;!s.isEnd(zn.D.Bottom)||s.length&&!e.includes(s[0])||this.setLoaded("bottom",!0,!1),!i.isEnd(zn.D.Top)||i.length&&!e.includes(i[i.length-1])||this.setLoaded("top",!0,!1)}else this.setLoaded("top",!0),this.setLoaded("bottom",!0);return yield this.messagesQueuePromise,this.scrollable.loadedAll.top&&this.messagesQueueOnRenderAdditional&&(this.messagesQueueOnRenderAdditional(),this.messagesQueueOnRenderAdditional&&this.messagesQueueOnRenderAdditional()),s&&s.restore(!(1===e.length&&!t)),!0}))}requestHistory(e,t,s){return"chat"===this.chat.type||"discussion"===this.chat.type?this.appMessagesManager.getHistory(this.peerId,e,t,s,this.chat.threadId):"pinned"===this.chat.type?this.appMessagesManager.getSearch({peerId:this.peerId,inputFilter:{_:"inputMessagesFilterPinned"},maxId:e,limit:t,backLimit:s}).then((e=>({history:e.history.map((e=>e.mid))}))):"scheduled"===this.chat.type?this.appMessagesManager.getScheduledMessages(this.peerId).then((e=>({history:e.slice().reverse()}))):void 0}animateAsLadder(e,t,s,i,n){return _a(this,void 0,void 0,(function*(){if(this.chat.setPeerPromise&&!this.resolveLadderAnimation)return void(this.resolveLadderAnimation=this.animateAsLadder.bind(this,e,t,s,i,n));if(!Object.keys(this.bubbles).length)return;let a,o=(0,Xs.Z)(this.bubbles,"desc");s&&t.length&&(o=o.filter((e=>!t.includes(e)))),a=i?n||Math.max(...o):e||Math.max(...o);const r=o.slice(o.findIndex((e=>a>e))),l=s?[]:[a],d=s?[]:o.slice(0,o.findIndex((e=>a>=e))).reverse();re.ZP&&this.log("getHistory: targeting mid:",a,n,e,r.map((e=>this.appMessagesIdsManager.getServerMessageId(e))),d.map((e=>this.appMessagesIdsManager.getServerMessageId(e))));const c=[];this.chatInner.classList.add("zoom-fading");const h=s?10:40,p=s?0:1,u=(e,t=0)=>{const s=(0,se.b)();let i=0;return e.forEach(((n,a)=>{if(!this.bubbles[n]||this.skippedMids.has(n))return void this.log.warn("animateAsLadder: no bubble by mid:",n);const o=this.bubbles[n].lastElementChild;if(i=(a+t||.1)*h,o.classList.add("zoom-fade"),o.style.transitionDelay=i+"ms",a===e.length-1){const e=t=>{t.target===o&&(s.resolve(),o.removeEventListener("transitionend",e))};o.addEventListener("transitionend",e)}c.push(o)})),e.length||s.resolve(),{lastMsDelay:i,animationPromise:s}},g=u(r,p),m=u(l),v=u(d,p),f=[g.animationPromise,m.animationPromise,v.animationPromise],b=[g.lastMsDelay,m.lastMsDelay,v.lastMsDelay];let y;return this.onAnimateLadder&&(yield this.onAnimateLadder()),(0,De.T2)((()=>{this.setStickyDateManually(),c.forEach((e=>{e.classList.remove("zoom-fade")}))})),(r.length||l.length||d.length)&&(y=Promise.all(f),(0,xs.YW)(y,Math.max(...b)+200).then((()=>{(0,De.T2)((()=>{c.forEach((e=>{e.style.transitionDelay=""})),this.chatInner.classList.remove("zoom-fading")})),ne.IS_SAFARI||(this.needReflowScroll=!0)}))),y}))}renderEmptyPlaceholder(e,t,s,i){const n="empty-bubble-placeholder";let a,o;if(t.classList.add(n,n+"-"+e),"group"===e?a=(0,k.i18n)("GroupEmptyTitle1"):"saved"===e?a=(0,k.i18n)("ChatYourSelfTitle"):"noMessages"===e||"greeting"===e?a=(0,k.i18n)("NoMessages"):"noScheduledMessages"===e?a=(0,k.i18n)("NoScheduledMessages"):"restricted"===e&&(a=document.createElement("span"),a.innerText=this.appPeersManager.getRestrictionReasonText(this.peerId)),a.classList.add("center",n+"-title"),i.push(a),"group"===e)i.push((0,k.i18n)("GroupEmptyTitle2")),o=[(0,k.i18n)("GroupDescription1"),(0,k.i18n)("GroupDescription2"),(0,k.i18n)("GroupDescription3"),(0,k.i18n)("GroupDescription4")];else if("saved"===e)o=[(0,k.i18n)("ChatYourSelfDescription1"),(0,k.i18n)("ChatYourSelfDescription2"),(0,k.i18n)("ChatYourSelfDescription3"),(0,k.i18n)("ChatYourSelfDescription4")];else if("greeting"===e){const e=(0,k.i18n)("NoMessagesGreetingsDescription");e.classList.add("center",n+"-subtitle"),this.messagesQueue.findAndSplice((e=>e.bubble===t));const a=document.createElement("div");a.classList.add(n+"-sticker");const o=this.getMiddleware(),r=this.appStickersManager.getGreetingSticker().then((e=>{if(!o())return;const t=[];return Is({doc:e,div:a,middleware:o,lazyLoadQueue:this.lazyLoadQueue,group:Bl,play:!0,loop:!0,withThumb:!0,loadPromises:t}),(0,l.fc)(a,(e=>{(0,d.d)(e),wa.onMediaClick({target:e.target})})),Promise.all(t)}));this.renderMessagesQueue(s,t,!1,[r]),i.push(e,a)}o&&(i.push(...o.map((e=>{const t=document.createElement("span");return t.classList.add(n+"-list-item"),t.append(e),t}))),"group"===e?o.forEach((e=>{const t=document.createElement("span");t.classList.add("tgico-check"),e.prepend(t)})):"saved"===e&&o.forEach((e=>{const t=document.createElement("span");t.classList.add(n+"-list-bullet"),t.innerText="•",e.prepend(t)}))),i.length>1&&t.classList.add("has-description"),i.forEach((e=>e.classList.add(n+"-line")))}processLocalMessageRender(e){const t=!!e.pFlags.sponsored,s=this.safeRenderMessage(e,void 0,void 0,void 0,t);s.classList.add("is-group-last","is-group-first"),t||(s.classList.add("bubble-first"),s.classList.remove("can-have-tail","is-in"));const i=[],n=this.appPeersManager.isBot(this.peerId);if(this.chat.isRestricted)this.renderEmptyPlaceholder("restricted",s,e,i);else{if(t){let t,i,n,o;s.classList.add("avoid-selection");const r=this.sponsoredMessage=e.sponsoredMessage,d=this.appPeersManager.getPeerId(r.from_id);r.channel_post?(t="OpenChannelPost",i=this.appMessagesIdsManager.generateMessageId(r.channel_post)):r.start_param||this.appUsersManager.isBot(d.toUserId())?(t="Chat.Message.ViewBot",n=r.start_param):t=this.appPeersManager.isAnyGroup(d)?"Chat.Message.ViewGroup":"Chat.Message.ViewChannel",o=r.chat_invite?()=>{new xa(r.chat_invite_hash,r.chat_invite).show()}:r.chat_invite_hash?()=>{const e={_:Ta.JOIN_CHAT,invite:r.chat_invite_hash};this.chat.appImManager.processInternalLink(e)}:()=>{a.default.dispatchEvent("history_focus",{peerId:d,mid:i,startParam:n})};const c=(0,U.Z)("btn-primary btn-primary-transparent bubble-view-button",{text:t});return this.viewsObserver.observe(c),o&&(0,l.fc)(c,o),void s.querySelector(".bubble-content").prepend(c)}if(n&&"message"===e._){const e=document.createElement("b");e.append((0,k.i18n)("BotInfoTitle")),i.push(e,"\n\n")}else this.appPeersManager.isAnyGroup(this.peerId)&&this.appPeersManager.getPeer(this.peerId).pFlags.creator?this.renderEmptyPlaceholder("group",s,e,i):"scheduled"===this.chat.type?this.renderEmptyPlaceholder("noScheduledMessages",s,e,i):a.default.myId===this.peerId?this.renderEmptyPlaceholder("saved",s,e,i):this.appPeersManager.isUser(this.peerId)&&!n&&this.chat.canSend()&&"chat"===this.chat.type?this.renderEmptyPlaceholder("greeting",s,e,i):this.renderEmptyPlaceholder("noMessages",s,e,i)}i.length&&s.querySelector(".message, .service-msg").prepend(...i);const o=t?"append":"prepend";this.messagesQueueOnRenderAdditional?this.onAnimateLadder=()=>{if(this.chatInner[o](s),this.onAnimateLadder=void 0,!this.messagesQueuePromise)return(0,De.AD)()}:this.chatInner[o](s),this.emptyPlaceholderMid=e.mid}generateLocalMessageId(e=0){let t=("scheduled"===this.chat.type?-1:0)+e;const s=-Math.abs(t);return{id:s,mid:-Math.abs(this.appMessagesIdsManager.generateMessageId(s))}}generateLocalFirstMessage(e,t,s=0){const{id:i,mid:n}=this.generateLocalMessageId(s),a={_:e?"messageService":"message",date:0,id:i,mid:n,peer_id:this.appPeersManager.getOutputPeer(this.peerId),pFlags:{local:!0}};return e||(a.message=""),(0,gs.Z)(a),t&&t(a),this.appMessagesManager.saveMessages([a],{storage:new Map}),a.mid=n,a}setLoaded(e,t,s=!0){if(this.scrollable.loadedAll[e]!==t){if(this.scrollable.loadedAll[e]=t,"bottom"===e&&this.appPeersManager.isBroadcast(this.peerId)&&!this.chat.isRestricted){const{mid:e}=this.generateLocalMessageId(1);if(t){const t=this.getMiddleware((()=>this.scrollable.loadedAll.bottom&&!this.bubbles[e]&&this.getSponsoredMessagePromise===s)),s=this.getSponsoredMessagePromise=this.chat.apiManager.invokeApiCacheable("channels.getSponsoredMessages",{channel:this.appChatsManager.getChannelInput(this.peerId.toChatId())},{cacheSeconds:300}).then((e=>{if(!t())return;this.appUsersManager.saveApiUsers(e.users),this.appChatsManager.saveApiChats(e.chats);const s=e.messages.shift();if(!s)return;e.messages.push(s);const i=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([this.getHistoryTopPromise,this.messagesQueuePromise]).then((()=>{t()&&this.performHistoryResult([i],!1,!0)}))})).finally((()=>{this.getSponsoredMessagePromise=void 0}))}else this.deleteMessagesByIds([e]),this.getSponsoredMessagePromise=void 0}if("top"===e&&t&&this.appPeersManager.isBot(this.peerId)&&!this.chat.isRestricted){this.log("inject bot description");const e=this.getMiddleware();return Promise.resolve(this.appProfileManager.getProfile(this.peerId.toUserId())).then((t=>{var s;if(!e())return;if(!(null===(s=t.bot_info)||void 0===s?void 0:s.description))return void this.checkIfEmptyPlaceholderNeeded();const i=this.generateLocalFirstMessage(!1,(e=>{e.message=t.bot_info.description}));this.processLocalMessageRender(i)}))}this.checkIfEmptyPlaceholderNeeded()}}checkIfEmptyPlaceholderNeeded(){if(this.scrollable.loadedAll.top&&this.scrollable.loadedAll.bottom&&void 0===this.emptyPlaceholderMid&&(this.chat.isRestricted||!this.appMessagesManager.getHistoryStorage(this.peerId).count||Object.keys(this.bubbles).length&&!this.getRenderedLength()||"scheduled"===this.chat.type&&!Object.keys(this.bubbles).length)){this.log("inject empty peer placeholder");const e=this.generateLocalFirstMessage(!0);return this.processLocalMessageRender(e),!0}return!1}getHistory(e=0,t=!1,s=!1,i=0,n=!1){const o=this.peerId,r=this.appPeersManager.isBroadcast(o),l=Math.min(30,Ct.Z.height/48|0),d=r?20:Object.keys(this.bubbles).length>0?Math.max(35,l):l;let c=d;if(void 0!==Ra){if(!Ra)return{cached:!1,promise:Promise.resolve(!0)};Object.keys(this.bubbles).length>0&&--Ra}let h,p=0;if(s&&(p=c,t||(c=0)),i&&!s)if("pinned"===this.chat.type)h=[i];else{const t=this.appMessagesManager.getHistoryStorage(o,this.chat.threadId).history.slice;if(t.length<c&&!t.isEnd(zn.D.Both)){h=t.slice();for(let e=h.length-1;e>=0&&this.chat.getMessage(h[e]).grouped_id;--e)h.splice(e,1);e=h[h.length-1]||e}}let u,g=this.requestHistory(e,c,p);const m=(null==h?void 0:h.length)&&g instanceof Promise,v=this.isFirstLoad&&p&&g instanceof Promise||m;m&&(u=g,g={history:h}),this.isFirstLoad=!1;const f=e=>_a(this,void 0,void 0,(function*(){if("offsetIdOffset"in e&&e.history.isEnd(zn.D.Top)){if("discussion"===this.chat.type){const t=this.appMessagesManager.threadsServiceMessagesIdsStorage[this.peerId+"_"+this.chat.threadId];t&&e.history.push(t),e.history.push(...this.chat.getMidsByMid(this.chat.threadId).reverse())}yield this.setLoaded("top",!0)}})),b=e=>(0,xs.e9)().then((()=>f(e))).then((()=>this.performHistoryResult(e.history||[],t,s,!m&&i))),y=e=>{const s=e.then((e=>(t?this.getHistoryTopPromise!==s:this.getHistoryBottomPromise!==s)?(this.log.warn("getHistory: peer changed"),Promise.reject()):n?(this.scrollable.onScroll(),!0):b(e)),(e=>{throw this.log.error("getHistory error:",e),e}));return s};let w,S;if(g instanceof Promise)S=!1,w=y(g);else{if(n)return null;S=!0,w=b(g)}const C=m?y(u):w;if(v&&a.default.settings.animationsEnabled){let s=m?2:1;this.messagesQueueOnRenderAdditional=()=>{this.log("ship went past rocks of magnets"),--s||(this.messagesQueueOnRenderAdditional=void 0,this.animateAsLadder(i,h,m,p,e).then((()=>{setTimeout((()=>{this.loadMoreHistory(t,!0)}),0)})))}}else this.messagesQueueOnRenderAdditional=void 0;return t?this.getHistoryTopPromise=C:this.getHistoryBottomPromise=C,C.then((()=>{t?this.getHistoryTopPromise=void 0:this.getHistoryBottomPromise=void 0})),n?null:(!v&&w.then((()=>{let e;t?(this.loadedTopTimes++,this.loadedBottomTimes=Math.max(0,--this.loadedBottomTimes)):(this.loadedBottomTimes++,this.loadedTopTimes=Math.max(0,--this.loadedTopTimes)),(t&&this.loadedTopTimes>2||!t&&this.loadedBottomTimes>2)&&(e=(0,Xs.Z)(this.bubbles));const s=2*d;e&&e.length>s&&(t?(e=e.slice(s),this.setLoaded("bottom",!1)):(e=e.slice(0,e.length-s),this.setLoaded("top",!1)),this.deleteMessagesByIds(e,!1))})),w.then((()=>{"chat"===this.chat.type&&setTimeout((()=>{t?this.loadMoreHistory(!0,!0):this.loadMoreHistory(!1,!0)}),0)})),{cached:S,promise:w})}setUnreadDelimiter(){if("chat"!==this.chat.type&&"discussion"!==this.chat.type)return;if(this.attachedUnreadBubble)return;const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId);let t=this.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])){let s=this.bubbles[t];this.firstUnreadBubble&&this.firstUnreadBubble!==s&&(this.firstUnreadBubble.classList.remove("is-first-unread"),this.firstUnreadBubble=null),t!==e.maxId&&s.classList.add("is-first-unread"),this.firstUnreadBubble=s,this.attachedUnreadBubble=!0}}deleteEmptyDateGroups(){const e=+!!this.stickyIntersector+1;let t=!1;for(const s in this.dateMessages){const i=this.dateMessages[s];i.container.childElementCount===e&&(i.container.remove(),this.stickyIntersector&&this.stickyIntersector.unobserve(i.container,i.div),delete this.dateMessages[s],t=!0)}t&&(this.checkIfEmptyPlaceholderNeeded(),this.setStickyDateManually())}}function Na(){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 Oa{constructor(e,t,s,n){var r;let l,d,c,h=[],p=[];const u=o.Z.canPinMessage(e),g=(a,o,r)=>{setTimeout((()=>{let a;a=s&&!t?u?i.Z.unpinAllMessages(e):i.Z.hidePinnedMessages(e):i.Z.updatePinnedMessage(e,t,s,r,o),n&&a.then(n)}),300)};if(s){let s="UnpinMessage";t?(l="UnpinMessageAlertTitle",d="Chat.Confirm.Unpin"):u?(l="Popup.Unpin.AllTitle",d="Chat.UnpinAllMessagesConfirmation",c=[""+((null===(r=i.Z.pinnedMessages[e])||void 0===r?void 0:r.count)||1)]):(l="Popup.Unpin.HideTitle",d="Popup.Unpin.HideDescription",s="Popup.Unpin.Hide"),h.push({langKey:s,isDanger:!0,callback:g})}else{l="PinMessageAlertTitle";const t="PinMessage";e.isAnyChat()?(h.push({langKey:t,callback:e=>g(0,!1,!e.size)}),j.Z.isBroadcast(e.toChatId())?d="PinMessageAlertChannel":(d="PinMessageAlert",p.push({text:"PinNotify",checked:!0}))):(d="PinMessageAlertChat",e===a.default.myId?h.push({langKey:t,callback:g}):(h.push({langKey:t,callback:e=>g(0,!e.size)}),p.push({text:"PinAlsoFor",textArgs:[new St.Z({peerId:e}).element],checked:!0})))}(0,pt.x)(h),new gt("popup-delete-chat",{peerId:e,titleLangKey:l,descriptionLangKey:d,descriptionLangArgs:c,buttons:h,checkboxes:p}).show()}}function Ha(e=window.getSelection()){if(!e||!e.rangeCount)return!0;const t=e.getRangeAt(0);return!t.toString()||!t.START_TO_END}class za extends gt{constructor(e,t,s,n){super("popup-report-messages-confirm",{noTitle:!0,descriptionLangKey:"ReportInfo",buttons:[{langKey:"ReportChat",callback:()=>{o.isValid()&&(n&&n(),i.Z.reportMessages(e,t,s,o.value).then((e=>{e&&lt({langPackKey:"ReportSentInfo"})})))}}],body:!0});const a=document.createElement("div");Is({doc:ds.Z.getAnimatedEmojiSticker(za.STICKER_EMOJI),div:a,emoji:za.STICKER_EMOJI,width:100,height:100,loop:!1,play:!0}).finally((()=>{this.show()})),this.header.append(a);const o=new _.Z({label:"ReportHint",maxLength:512,placeholder:"ReportChatDescription"});o.input.addEventListener("input",(()=>{this.buttons[0].element.toggleAttribute("disabled",!o.isValid())})),this.body.append(o.container)}}za.STICKER_EMOJI="👮‍♀️";class Va extends gt{constructor(e,t,s){super("popup-report-messages",{titleLangKey:"ChatTitle.ReportMessages",buttons:[],body:!0}),t=t.slice();const i=[["ReportChatSpam","inputReportReasonSpam"],["ReportChatViolence","inputReportReasonViolence"],["ReportChatChild","inputReportReasonChildAbuse"],["ReportChatPornography","inputReportReasonPornography"],["ReportChatOther","inputReportReasonOther"]];i.forEach((e=>{const t=(0,U.Z)("btn-primary btn-transparent",{text:e[0]});this.body.append(t)}));const n=ds.Z.preloadAnimatedEmojiSticker(za.STICKER_EMOJI);(0,l.fc)(this.body,(a=>{const o=(0,Me.Z)(a.target,"btn-primary"),r=i[(0,_s.Z)(o)][1];n.then((()=>{this.hide(),new za(e,t,r,s)}))}),{listenerSetter:this.listenerSetter}),this.body.style.margin="0 -1rem",this.buttonsEl.style.marginTop=".5rem",this.show()}}class ja extends gt{constructor(){super("popup-sponsored",{titleLangKey:"Chat.Message.Sponsored.What",descriptionLangKey:"Chat.Message.Ad.Text",descriptionLangArgs:[(0,k.i18n)("Chat.Message.Sponsored.Link")],buttons:[{langKey:"OK",isCancel:!0},{langKey:"Chat.Message.Ad.ReadMore",callback:()=>{window.open(k.default.format("Chat.Message.Sponsored.Link",!0))},isCancel:!0}]});const e=new P.ZP(void 0);e.onAdditionalScroll=()=>{e.container.classList.toggle("scrolled-top",!e.scrollTop),e.container.classList.toggle("scrolled-bottom",e.isScrolledDown)},this.description.replaceWith(e.container),e.container.append(this.description),e.container.classList.add("scrolled-top"),this.show()}}var Ga=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Ka extends pt.Z{constructor(e,t){super("popup-reacted-list",null,{closable:!0,overlayClosable:!0,body:!0}),this.appMessagesManager=e,this.message=t,this.init()}init(){return Ga(this,void 0,void 0,(function*(){const e=this.appMessagesManager.getGroupsFirstMessage(this.message),t=this.appMessagesManager.canViewMessageReadParticipants(e),s=new Bn,i=Object.assign(Object.assign({},e),{mid:0,id:0,reactions:Object.assign(Object.assign({_:"messageReactions",results:[]},e.reactions),{pFlags:{},recent_reactions:[]})});i.reactions.results=i.reactions.results.map((e=>Object.assign(Object.assign({},e),{pFlags:{}}))),s.init(i,"block"),s.render(),s.classList.add("no-stripe"),s.classList.remove("has-no-reactions"),s.append(this.btnClose),this.header.append(s);const n=document.createElement("div");n.classList.add("tabs-container"),n.dataset.animation="tabs";const a=new Map;let o=!1;if(i.reactions.results.length){const e=this.createFakeReaction("reactions",i.reactions.results.reduce(((e,t)=>e+t.count),0));s.prepend(e),i.reactions.results.unshift(e.reactionCount),o=!0}let r=!1;if(t)try{const t=yield this.appMessagesManager.getMessageReadParticipants(e.peerId,e.mid);if(!t.length)throw"";const n=this.createFakeReaction("checks",t.length);s.prepend(n),i.reactions.results.unshift(n.reactionCount),r=!0}catch(e){}i.reactions.results.forEach((t=>{const s=new P.ZP(void 0);s.container.classList.add("tabs-tab");const i=new Mn({noShadow:!0,noDelimiter:!0}),o=pd.createChatList({dialogSize:72});pd.setListClickListener(o,(()=>{this.hide()}),void 0,!1,!0),i.content.append(o),s.container.append(i.container);const r="checks"!==t.reaction,l="checks"===t.reaction;let d;["checks","reactions"].includes(t.reaction)&&(t.reaction=void 0);const c=new bt({scrollable:s,getPromise:()=>Ga(this,void 0,void 0,(function*(){const s=yield this.appMessagesManager.getMessageReactionsListAndReadParticipants(e,void 0,t.reaction,d,r,l);return d=s.nextOffset,s.combined.forEach((({peerId:e,reaction:t})=>{const{dom:s}=pd.addDialogNew({dialog:e,autonomous:!0,container:o,avatarSize:54,rippleEnabled:!1,meAsSaved:!1,drawStatus:!1});if(t){const e=document.createElement("div");e.classList.add("reacted-list-reaction-icon"),Is({doc:_t.Z.getReactionCached(t).static_icon,div:e,width:24,height:24}),s.listEl.append(e)}(0,T.Z)(s.lastMessageSpan,E.Z.getUserStatusString(e.toUserId()))})),!d}))});a.set(s.container,c),n.append(s.container)})),this.body.append(n);const l=(0,Y.X)(s,n,((e,t)=>{if(e===s.childElementCount-1)return!1;const i=s.children[e],n=l.prevId();-1!==n&&s.children[n].setIsChosen(!1),i.setIsChosen(!0),a.get(t).load()}));l(0,!1),this.show()}))}createFakeReaction(e,t){const s=new Fn;s.init("block"),s.reactionCount={_:"reactionCount",count:t,reaction:e},s.setCanRenderAvatars(!1),s.renderCounter();const i=document.createElement("div");return i.classList.add("reaction-counter","reaction-sticker-icon","tgico-"+e),s.prepend(i),s}}const Wa="btn-menu-reactions-reaction",qa=!ne.IS_SAFARI;class $a{constructor(e,t,s){this.appReactionsManager=e,this.type=t,this.onScroll=()=>{this.reactionsMap.forEach(((e,t)=>{this.onScrollProcessItem(t,e)}))},this.onMouseMove=e=>{var t;const s=(0,Me.Z)(e.target,Wa);if(!s)return;const i=this.reactionsMap.get(s);if(!i)return;if(!(null===(t=i.appear)||void 0===t?void 0:t.paused))return;const n=i.select;n&&n.paused&&(n.autoplay=!0,n.restart())};const i=this.widthContainer=document.createElement("div");i.classList.add("btn-menu-reactions-container"),i.classList.add("btn-menu-reactions-container-"+t);const n=this.container=document.createElement("div");n.classList.add("btn-menu-reactions");const a=this.scrollable="vertical"===t?new P.ZP(void 0):new P.v7(void 0);n.append(a.container),a.onAdditionalScroll=this.onScroll,a.setListeners(),a.container.classList.add("no-scrollbar"),["big"].forEach((e=>{const t=document.createElement("div");t.classList.add("btn-menu-reactions-bubble","btn-menu-reactions-bubble-"+e),n.append(t)})),this.reactionsMap=new Map,this.animationGroup="CHAT-MENU-REACTIONS-"+Date.now(),I.Z.setOverrideIdleGroup(this.animationGroup,!0),ce.IS_TOUCH_SUPPORTED||n.addEventListener("mousemove",this.onMouseMove),(0,l.fc)(n,(e=>{const t=(0,Me.Z)(e.target,Wa);if(!t)return;const s=this.reactionsMap.get(t);s&&this.appReactionsManager.sendReaction(this.message,s.reaction)})),i.append(n),this.middleware=null!=s?s:(0,As.k)()}init(e){this.message=e;const t=this.middleware.get(),s=this.appReactionsManager.getAvailableReactionsByMessage(e);(0,Nt.Z)(s,(e=>{if(!t()||!e.length)return;e.forEach((e=>{this.renderReaction(e)}));const i=()=>{this.container.classList.add("is-visible")};s instanceof Promise?(0,De.T2)(i):i()}))}cleanup(){this.middleware.clean(),this.scrollable.removeListeners(),this.reactionsMap.clear(),I.Z.setOverrideIdleGroup(this.animationGroup,!1),I.Z.checkAnimations(!0,this.animationGroup,!0)}renderReaction(e){const t=document.createElement("div");t.classList.add(Wa);const s=document.createElement("div");s.classList.add(Wa+"-scale");const i=document.createElement("div");let n;i.classList.add(Wa+"-appear"),a.default.settings.animationsEnabled&&(n=document.createElement("div"),n.classList.add(Wa+"-select","hide"));const o={selectWrapper:n,appearWrapper:i,reaction:e.reaction};this.reactionsMap.set(t,o);const r=this.middleware.get(),l=28*(ce.IS_TOUCH_SUPPORTED?1:1.25),d={width:l,height:l,skipRatio:1,needFadeIn:!1,withThumb:!1,group:this.animationGroup,middleware:r};if(a.default.settings.animationsEnabled){let t=!0;Is(Object.assign({doc:e.appear_animation,div:i,play:!0},d)).then((e=>{(0,gs.Z)(e),o.appear=e,e.addEventListener("enterFrame",(a=>{e.maxFrame===a&&s.then((e=>{(0,gs.Z)(e),i.classList.add("hide"),n.classList.remove("hide"),t&&(o.select=e,t=!1)}),_e.Z)}))}),_e.Z);const s=Is(Object.assign({doc:e.select_animation,div:n},d)).then((e=>((0,gs.Z)(e),ae.Z.waitForFirstFrame(e)))).catch(_e.Z)}else delete d.needFadeIn,delete d.withThumb,Is(Object.assign({doc:e.static_icon,div:i},d));s.append(i),n&&s.append(n),t.append(s),this.scrollable.append(t)}onScrollProcessItem(e,t){const s=e.firstElementChild,i=Pa(e,this.scrollable.container);let n;if(i)if(i.overflow.left||i.overflow.right){const e=Math.abs(i.rect.left-i.rect.right);n="scale("+Math.min(Math.pow(e,2)/Math.pow(36,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=""}qa&&(s.style.transform=n)}}class Qa{constructor(e,t,s,i,n,a,o,r){this.attachTo=e,this.chat=t,this.appMessagesManager=s,this.appPeersManager=i,this.appPollsManager=n,this.appDocsManager=a,this.appMessagesIdsManager=o,this.appReactionsManager=r,this.onContextMenu=e=>{let t,s;try{s=(0,Me.Z)(e.target,"bubble-content-wrapper"),t=s?s.parentElement:(0,Me.Z)(e.target,"bubble")}catch(e){}if(!t||t.classList.contains("bubble-first"))return;let i=this.element;if((e instanceof MouseEvent||e.hasOwnProperty("preventDefault"))&&e.preventDefault(),i&&i.classList.contains("active"))return!1;(e instanceof MouseEvent||e.hasOwnProperty("cancelBubble"))&&(e.cancelBubble=!0);let n=+t.dataset.mid;if(!n)return;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=!Ha(),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&&!s){if(a)return;const e=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=!!s;const o=(0,Me.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=this.chat.getMessage(this.mid),this.noForwards=!a&&!this.appMessagesManager.canForward(this.message),this.viewerPeerId=void 0,this.canOpenReactedList=void 0;const r=this.init();i=r.element;const{cleanup:l,destroy:d,menuPadding:c}=r,h=t.classList.contains("is-in")?"left":"right";(0,J.oy)(e.touches?e.touches[0]:e,i,h,c),(0,J.YP)(i,(()=>{this.mid=0,this.peerId=void 0,this.target=null,this.viewerPeerId=void 0,this.canOpenReactedList=void 0,l(),setTimeout((()=>{d()}),300)}))},this.onSendScheduledClick=()=>{this.chat.selection.isSelecting?(0,l.tH)(this.chat.selection.selectionSendNowBtn):new js(this.peerId,this.chat.getMidsByMid(this.mid))},this.onReplyClick=()=>{this.chat.input.initMessageReply(this.mid)},this.onEditClick=()=>{this.chat.input.initMessageEditing(this.mid)},this.onCopyClick=()=>{Ha()?st((this.chat.selection.isSelecting?[...this.chat.selection.selectedMids.get(this.peerId)].sort(((e,t)=>e-t)):[this.mid]).reduce(((e,t)=>{const s=this.chat.getMessage(t);return e+((null==s?void 0:s.message)?s.message+"\n":"")}),"").trim()):document.execCommand("copy")},this.onCopyAnchorLinkClick=()=>{st(this.target.href)},this.onCopyLinkClick=()=>{let e;"discussion"===this.chat.type&&(e=this.appMessagesManager.getMessageByPeer(this.peerId,this.chat.threadId));const t=this.appPeersManager.getPeerUsername(e?e.fromId:this.peerId),s=this.appMessagesIdsManager.getServerMessageId(this.mid);let i,n="https://t.me/";t?(n+=t+"/"+(e?this.appMessagesIdsManager.getServerMessageId(e.fwd_from.channel_post):s),e&&(n+="?comment="+s),i="LinkCopied"):(n+="c/"+this.peerId.toChatId()+"/"+s,e&&(n+="?thread="+this.appMessagesIdsManager.getServerMessageId(e.mid)),i="LinkCopiedPrivateInfo"),rt(k.default.format(i,!0)),st(n)},this.onPinClick=()=>{new Oa(this.peerId,this.mid)},this.onUnpinClick=()=>{new Oa(this.peerId,this.mid,!0)},this.onRetractVote=()=>{this.appPollsManager.sendVote(this.message,[])},this.onStopPoll=()=>{this.appPollsManager.stopPoll(this.message)},this.onForwardClick=()=>{if(this.chat.selection.isSelecting)(0,l.tH)(this.chat.selection.selectionForwardBtn);else{const e=this.isTargetAGroupedItem?[this.mid]:this.chat.getMidsByMid(this.mid);new Hs({[this.peerId]:e})}},this.onSelectClick=()=>{this.chat.selection.toggleByElement((0,Me.Z)(this.target,"grouped-item")||(0,Me.Z)(this.target,"bubble"))},this.onClearSelectionClick=()=>{this.chat.selection.cancelSelection()},this.onDeleteClick=()=>{this.chat.selection.isSelecting?(0,l.tH)(this.chat.selection.selectionDeleteBtn):new zs(this.peerId,this.isTargetAGroupedItem?[this.mid]:this.chat.getMidsByMid(this.mid),this.chat.type)},this.listenerSetter=new B.Z,this.middleware=(0,As.k)(),ce.IS_TOUCH_SUPPORTED?(0,l.fc)(e,(e=>{if(t.selection.isSelecting)return;const s=e.target.className;s&&s.includes&&(t.log("touchend",e),["bubble","bubble-content-wrapper","bubble-content","message","time","inner"].find((e=>s.match(new RegExp(e+"($|\\s)"))))&&((0,d.d)(e),this.onContextMenu(e)))}),{listenerSetter:this.chat.bubbles.listenerSetter}):(0,J.Eo)(e,this.onContextMenu,this.chat.bubbles.listenerSetter)}cleanup(){this.listenerSetter.removeAll(),this.reactionsMenu&&this.reactionsMenu.cleanup(),this.middleware.clean()}destroy(){this.cleanup()}filterButtons(e){return this.isSponsored?e.filter((e=>e.isSponsored)):e.filter((e=>{let t;return this.chat.selection.isSelecting&&!e.withSelection?t=!1:(this.isOverBubble||ce.IS_TOUCH_SUPPORTED,t=e.verify()),t}))}setButtons(){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,gs.Z)(this.message),this.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:()=>this.chat.canSend()&&!this.message.pFlags.is_outgoing&&!!this.chat.input.messageInput&&"scheduled"!==this.chat.type},{icon:"edit",text:"Edit",onClick:this.onEditClick,verify:()=>this.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:()=>{if(!this.isSelected||this.noForwards)return!1;for(const[e,t]of this.chat.selection.selectedMids)for(const s of t)if(this.appMessagesManager.getMessageByPeer(e,s).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:()=>{st(this.target.innerHTML)},verify:()=>this.isUsernameTarget,withSelection:!0},{icon:"copy",text:"Text.Context.Copy.Hashtag",onClick:()=>{st(this.target.innerHTML)},verify:()=>this.target.classList.contains("anchor-hashtag"),withSelection:!0},{icon:"link",text:"MessageContext.CopyMessageLink1",onClick:this.onCopyLinkClick,verify:()=>this.appPeersManager.isChannel(this.peerId)&&!this.message.pFlags.is_outgoing},{icon:"pin",text:"Message.Context.Pin",onClick:this.onPinClick,verify:()=>!this.message.pFlags.is_outgoing&&"messageService"!==this.message._&&!this.message.pFlags.pinned&&this.appPeersManager.canPinMessage(this.peerId)&&"scheduled"!==this.chat.type},{icon:"unpin",text:"Message.Context.Unpin",onClick:this.onUnpinClick,verify:()=>this.message.pFlags.pinned&&this.appPeersManager.canPinMessage(this.peerId)},{icon:"download",text:"MediaViewer.Context.Download",onClick:()=>{this.appDocsManager.saveDocFile(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 s=!!ce.IS_TOUCH_SUPPORTED;const i=!t.type||!["gif","video","sticker"].includes(t.type);return i&&(s=s||!!(0,Me.Z)(this.target,"document")||!!(0,Me.Z)(this.target,"audio")),i&&s}},{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:()=>{var e;const t=null===(e=this.message.media)||void 0===e?void 0:e.poll;return this.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.pFlags.out||"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 Va(this.peerId,[this.mid])},verify:()=>!this.message.pFlags.out&&"message"===this.message._&&!this.message.pFlags.is_outgoing&&this.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 Ka(this.appMessagesManager,this.message)}},verify:()=>{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)||this.appMessagesManager.canViewMessageReadParticipants(this.message))},notDirect:()=>!0},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>this.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 ja},verify:()=>!1,isSponsored:!0}]}init(){this.cleanup(),this.setButtons();const e=this.filterButtons(this.buttons),t=this.element=Ce(e,this.listenerSetter);t.id="bubble-contextmenu",t.classList.add("contextmenu");const s=e.find((e=>!e.icon));if(s){const e=this.message.reactions,t=null==e?void 0:e.recent_reactions,i=!!(null==t?void 0:t.length),n=this.appMessagesManager.canViewMessageReadParticipants(this.message)?this.appPeersManager.getPeer(this.peerId).participants_count:void 0,a=e?e.results.reduce(((e,t)=>e+t.count),0):void 0;s.element.classList.add("tgico-"+(i?"reactions":"checks"));const o=new k.default.IntlElement({key:i?void 0===n?"Chat.Context.ReactedFast":"Chat.Context.Reacted":"NobodyViewed",args:i?void 0===n?[a]:[n,n]:void 0,element:s.textElement});let r;r=i?void 0===n?(0,k.i18n)("Chat.Context.ReactedFast",[a]):(0,k.i18n)(t.length===n?"Chat.Context.ReactedFast":"Chat.Context.Reacted",[t.length,n]):(0,k.i18n)("Loading"),r.classList.add("btn-menu-item-text-fake"),s.element.append(r);const l=3,d=.875;o.element.style.visibility="hidden",o.element.style.paddingRight=i?d*Math.min(l,t.length)+"rem":"1rem";const c=this.middleware.get();this.appMessagesManager.getMessageReactionsListAndReadParticipants(this.message).then((e=>{if(!c())return;r&&r.remove();const a=e.combined,h=void 0===n?e.reactionsCount:i?a.filter((e=>e.reaction)).length:a.length;let p;if(1===a.length)p=new St.Z({peerId:a[0].peerId,onlyFirstName:!0,dialog:!1}).element,(!i||e.readParticipants.length<=1)&&(this.viewerPeerId=a[0].peerId);else if(i){const e=h===a.length||void 0===n;p=(0,k.i18n)(e?"Chat.Context.ReactedFast":"Chat.Context.Reacted",e?[h]:[h,a.length])}else a.length?p=(0,k.i18n)("MessageSeen",[a.length]):o.element.style.visibility="";if(p&&(p.style.paddingRight=d*Math.min(l,h)+"rem",p.classList.add("btn-menu-item-text-fake"),s.element.append(p)),a.length){const e=new Dn({avatarSize:24});e.render(t?t.map((e=>this.appPeersManager.getPeerId(e.peer_id))):a.map((e=>e.peerId))),s.element.append(e.container),this.canOpenReactedList=!0}}))}let i,n;if("message"===this.message._&&!this.chat.selection.isSelecting&&!this.message.pFlags.is_outgoing&&!this.message.pFlags.is_scheduled){const e=ne.IS_APPLE||ce.IS_TOUCH_SUPPORTED?"horizontal":"vertical";n=this.reactionsMenu=new $a(this.appReactionsManager,e,this.middleware),n.init(this.appMessagesManager.getGroupsFirstMessage(this.message)),t.prepend(n.widthContainer);const s=50;i="vertical"===e?{top:24,left:s}:{top:s,right:36,left:24}}return this.chat.container.append(t),{element:t,cleanup:()=>{this.cleanup(),n&&n.cleanup()},destroy:()=>{t.remove()},menuPadding:i}}}var Ya=s(4329),Xa=s.n(Ya),Ja=s(9043);class eo{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=Ce(this.sendMenuButtons,e.listenerSetter),this.sendMenu.classList.add("menu-send",e.openSide),(0,J.Eo)(e.onContextElement,(t=>{e.onOpen&&!e.onOpen()||(this.sendMenuButtons.forEach((e=>{e.element.classList.toggle("hide",!e.verify())})),(0,d.d)(t),(0,J.YP)(this.sendMenu))}),e.listenerSetter)}setPeerId(e){this.type=e===a.default.myId?"reminder":"schedule"}}var to=s(3735),so=s(1293);class io extends pt.Z{constructor(e){if(super("popup-create-poll popup-new-media",null,{closable:!0,withConfirm:"Create",body:!0}),this.chat=e,this.tempId=0,this.onSubmitClick=()=>{this.send()},this.onInput=e=>{const t=e.target,s=(0,ft.Z)(t,"LABEL"),i=(0,so.Z)(t);i||(t.parentElement.classList.add("is-filled"),s.classList.remove("hidden-widget"),s.firstElementChild.removeAttribute("disabled")),!s.nextElementSibling&&!i&&this.questions.childElementCount<10&&this.appendMoreField(),this.handleChange()},this.onDeleteClick=e=>{const t=e.target,s=(0,ft.Z)(t,"LABEL"),i=(0,_s.Z)(s);this.correctAnswers&&this.correctAnswers[0][0]===i&&(this.correctAnswers=void 0),s.remove(),this.optionInputFields.splice(i,1),this.optionInputFields.forEach(((e,t)=>{e.options.labelOptions.length=0,e.options.labelOptions.push(t+1),k.default.weakMap.get(e.label.firstElementChild).update()})),this.handleChange()},(0,k._i18n)(this.title,"NewPoll"),this.questionInputField=new _.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 eo({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 t=document.createElement("hr"),s=document.createElement("div");s.classList.add("caption"),(0,k._i18n)(s,"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 n=document.createElement("div");n.classList.add("caption"),(0,k._i18n)(n,"Settings"),this.chat.appPeersManager.isBroadcast(this.chat.peerId)||(this.anonymousCheckboxField=new ut.Z({text:"NewPoll.Anonymous",name:"anonymous"}),this.anonymousCheckboxField.input.checked=!0,i.append(this.anonymousCheckboxField.label)),this.multipleCheckboxField=new ut.Z({text:"NewPoll.MultipleChoice",name:"multiple"}),this.quizCheckboxField=new ut.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,k._i18n)(o,"AccDescrQuizExplanation");const r=document.createElement("hr"),d=document.createElement("div");d.classList.add("poll-create-questions"),this.quizSolutionField=new _.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,k._i18n)(c,"AddAnExplanationInfo"),d.append(this.quizSolutionField.container,c),a.push(r,o,d),a.forEach((e=>e.classList.add("hide"))),this.body.parentElement.insertBefore(t,this.body),this.body.append(s,this.questions,document.createElement("hr"),n,i,...a),(0,l.fc)(this.btnConfirm,this.onSubmitClick,{listenerSetter:this.listenerSetter}),this.scrollable=new P.ZP(this.body),this.appendMoreField(),this.onEscape=()=>!this.getFilledAnswers().length,this.handleChange()}getFilledAnswers(){return Array.from(this.questions.children).map(((e,t)=>{const s=e.querySelector(".input-field-input");return s instanceof HTMLInputElement?s.value:(0,to.Z)(s,!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 s=this.getFilledAnswers();if(s.length<2)return!1;if(s.find((e=>e.length>100)))return!1;const{value:i}=(0,to.Z)(this.quizSolutionField.input,!1);return!(i.length>200)}handleChange(){const e=this.validate();this.btnConfirm.toggleAttribute("disabled",!e)}send(e=!1){const t=this.questionInputField.value,s=this.getFilledAnswers(),{value:i,entities:n}=(0,to.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:s.map(((e,t)=>({_:"pollAnswer",text:e,option:new Uint8Array([t])}))),id:void 0},r=this.chat.appPollsManager.getInputMediaPoll(o,this.correctAnswers,i,n);this.chat.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,s=new _.Z({placeholder:"NewPoll.OptionsAddOption",label:"NewPoll.OptionLabel",labelOptions:[t],name:"question-"+e,maxLength:100});this.listenerSetter.add(s.input)("input",this.onInput);const i=new at({text:"",name:"question"});i.main.append(s.container),(0,l.fc)(s.input,d.d,{listenerSetter:this.listenerSetter}),i.label.classList.add("hidden-widget"),i.input.disabled=!0,this.quizCheckboxField.input.checked||i.label.classList.remove("radio-field"),this.listenerSetter.add(i.input)("change",(()=>{if(i.input.checked){const e=(0,_s.Z)(i.label);this.correctAnswers=[new Uint8Array([e])],this.handleChange()}}));const n=document.createElement("span");n.classList.add("btn-icon","tgico-close"),s.container.append(n),(0,l.fc)(n,this.onDeleteClick,{listenerSetter:this.listenerSetter,once:!0}),this.questions.append(i.label),this.scrollable.scrollIntoViewNew({element:this.questions.lastElementChild,position:"center"}),this.optionInputFields.push(s)}}var no=s(2398);function ao(e){const t=e.src;return fetch(t).then((e=>e.arrayBuffer())).then((e=>{const t=new Uint8Array(e);let s=0;for(let e=0,i=t.length;e<i;++e)if(33==t[e]&&249==t[e+1]&&4==t[e+2]&&0==t[e+7]){const i=t[e+5]<<8|255&t[e+4];s+=i<2?10:i}return s/1e3}))}let oo;function ro(){return oo}class lo extends pt.Z{constructor(e,t,s){if(super("popup-send-photo popup-new-media",null,{closable:!0,withConfirm:"Modal.Send",confirmShortcutIsSendShortcut:!0,body:!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,no.Z)(this.input)}},this.attachFile=e=>{const t=this.willAttach,s=this.shouldCompress(e.type),i={};i.file=e;const n=document.createElement("div");n.classList.add("popup-item"),i.itemDiv=n;const a=s?this.attachMedia(e,i,n):this.attachDocument(e,i,n);return t.sendFileDetails.push(i),a},this.willAttach={type:s,sendFileDetails:[],group:!1},(0,l.fc)(this.btnConfirm,(()=>this.send()),{listenerSetter:this.listenerSetter}),"scheduled"!==this.chat.type){const e=new eo({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 P.ZP(null);i.container.append(this.mediaContainer),this.inputField=new _.Z({placeholder:"PreviewSender.CaptionPlaceholder",label:"Caption",name:"photo-caption",maxLength:a.default.config.caption_length_max}),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=[],oo=void 0})),oo=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 ut.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=>g.has(e.type)));t&&!this.mediaCheckboxField?(this.mediaCheckboxField=new ut.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>a.default.config.caption_length_max)return void rt(k.default.format("Error.PreviewSender.CaptionTooLong",!0));this.hide();const s=this.willAttach;s.isMedia="media"===s.type||void 0;const{sendFileDetails:i,isMedia:n}=s,{peerId:o,input:r}=this.chat;i.forEach((e=>{e.itemDiv=void 0}));const{length:l}=i,d=this.chat.getMessageSendingParams();this.iterate((e=>{t&&e.length!==l&&(this.chat.appMessagesManager.sendText(o,t,Object.assign(Object.assign({},d),{clearDraft:!0})),t=void 0);const i=Object.assign(Object.assign({},s),{sendFileDetails:e});this.chat.appMessagesManager.sendAlbum(o,i.sendFileDetails.map((e=>e.file)),Object.assign(Object.assign(Object.assign({},d),{caption:t,isMedia:n,clearDraft:!0}),i)),t=void 0})),r.replyToMsgId=this.chat.threadId,r.onMessageSent()}attachMedia(e,t,s){let i;if(s.classList.add("popup-item-media"),e.type.startsWith("video/")){const n=document.createElement("video"),a=document.createElement("source");a.src=t.objectURL=URL.createObjectURL(e),n.autoplay=!0,n.controls=!1,n.muted=!0,n.setAttribute("playsinline","true"),n.addEventListener("timeupdate",(()=>{n.pause()}),{once:!0}),i=(0,he.xD)(n).then((()=>{t.width=n.videoWidth,t.height=n.videoHeight,t.duration=Math.floor(n.duration);const e=n.webkitAudioDecodedByteCount;return void 0!==e&&(t.noSound=!e),s.append(n),(0,he.il)(n).then((e=>{t.thumb=Object.assign({url:URL.createObjectURL(e.blob)},e)}))})),n.append(a)}else{const n=new Image;i=new Promise((i=>{n.onload=()=>{t.width=n.naturalWidth,t.height=n.naturalHeight,s.append(n),"image/gif"===e.type?(t.noSound=!0,Promise.all([ao(n).then((e=>{t.duration=Math.ceil(e)})),(0,he.zr)(n).then((e=>{t.thumb=Object.assign({url:URL.createObjectURL(e.blob)},e)}))]).then((()=>{i()}))):i()}})),n.src=t.objectURL=URL.createObjectURL(e)}return i}attachDocument(e,t,s){s.classList.add("popup-item-document");const i=e.type.startsWith("image/"),n=e.type.startsWith("audio/");(i||n)&&(t.objectURL=URL.createObjectURL(e));const a={_:"document",file:e,file_name:e.name||"",fileName:e.name?Q.Z.wrapEmojiText(e.name):"",size:e.size,type:i?"photo":"doc"},o=le.Z.getCacheContext(a);o.url=t.objectURL,o.downloaded=e.size;const r=ws({message:{_:"message",pFlags:{is_outgoing:!0},mid:0,peerId:0,media:{_:"messageMediaDocument",document:a}}});return new Promise((e=>{const n=()=>{s.append(r),e()};if(i){const e=new Image;e.src=t.objectURL,e.onload=()=>{t.width=e.naturalWidth,t.height=e.naturalHeight,n()},e.onerror=n}else n()}))}shouldCompress(e){return"media"===this.willAttach.type&&g.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:s}=this;let i;const n=[];if("document"===e.type)i="PreviewSender.SendFile",n.push(s.length);else{let e=0,t=0,a=0;s.forEach((s=>{s.type.startsWith("image/")?++e:s.type.startsWith("video/")?++t:++a})),[e,t,a].filter((e=>e>0)).length>1?(i="PreviewSender.SendFile",n.push(s.length)):e?(i="PreviewSender.SendPhoto",n.push(e)):t&&(i="PreviewSender.SendVideo",n.push(t))}(0,T.Z)(t,(0,k.i18n)(i,n))}appendMediaToContainer(e,t){if(this.shouldCompress(t.file.type)){const s=(0,ra.Z)(t.width,t.height,380,320);e.style.width=s.width+"px",e.style.height=s.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 s=t.length;for(let i=0;i<s;){const n=t[i].file.type;let a=0;for(;a<10&&i<s;++i,++a){const e=t[i].file.type;if(this.shouldCompress(n)!==this.shouldCompress(e))break}e(t.slice(i-a,i))}}attachFiles(){const{files:e,willAttach:t,mediaContainer:s}=this;t.sendFileDetails.length=0,this.appendGroupCheckboxField(),this.appendMediaCheckboxField(),Promise.all(e.map(this.attachFile)).then((()=>{s.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))),Ts({container:t,items:e.map((e=>({w:e.width,h:e.height}))),maxWidth:380,minWidth:100,spacing:4}),s.append(t)}else e.forEach((e=>{this.appendMediaToContainer(e.itemDiv,e)}))})))})).then((()=>{this.onRender()}))}}const co="keydown",ho="active",po=["ArrowUp","ArrowDown"],uo=["ArrowLeft","ArrowRight"];class go extends R.Z{constructor(e){super(!1),this.hidden=!0,this.onVisible=()=>{this.detach&&this.detach();const e=this.list,{attach:t,detach:s,resetTarget:i}=function({list:e,type:t,onSelect:s,once:i,waitForKey:n}){let a=(null==n?void 0:n.length)?new Set(n):void 0;const o=new Set("xy"===t?po.concat(uo):"x"===t?uo:po);let r;const c=()=>r||e.querySelector(".active")||e.firstElementChild,h=(e,s)=>{if(r===e)return;let i=!1;r&&(i=!0,r.classList.remove(ho)),r=e,r&&(r.classList.add(ho),i&&m&&s&&(0,yt.Z)({container:m,element:r,position:"center",forceDuration:100,axis:"x"===t?"x":"y"}))},p=(t,s)=>{let i;return i=s?t.nextElementSibling||e.firstElementChild:t.previousElementSibling||e.lastElementChild,i};let u;u="xy"===t?(t,s)=>"ArrowUp"===s||"ArrowDown"===s?((t,s)=>{const i=s?"nextElementSibling":"previousElementSibling",n=s?"firstElementChild":"lastElementChild",a=t.getBoundingClientRect();let o=t[i]||e[n];for(;o!==t;){const t=o.getBoundingClientRect();if(t.x===a.x&&t.y!==a.y)break;o=o[i]||e[n]}return o})(t,"ArrowDown"===s):p(t,"ArrowRight"===s):(e,t)=>p(e,"ArrowRight"===t||"ArrowDown"===t);let g=s=>{const i=s.key;if(o.has(i)){if((0,d.d)(s),e.childElementCount>1){let e=c();e=u(e,i),h(e,!0)}}else("Enter"===i||"xy"!==t&&"Tab"===i)&&((0,d.d)(s),b(c()))};const m=(0,Me.Z)(e,"scrollable");e.classList.add("navigable-list");const v=t=>{const s=(0,Ws.Z)(t.target,e);s&&h(s,!1)},f=t=>{(0,d.d)(t);const s=(0,Ws.Z)(t.target,e);s&&(h(s,!1),b(c()))},b=e=>{const t=s(e);(void 0!==t?!t:i)&&S()};let y=!1;const w=()=>{y||(y=!0,document.addEventListener(co,g,{capture:!0,passive:!1}),e.addEventListener("mousemove",v,{passive:!0}),(0,l.fc)(e,f))},S=()=>{y&&(y=!1,document.removeEventListener(co,g,{capture:!0}),e.removeEventListener("mousemove",v),(0,l.EN)(e,f))},C=()=>{a||h(e.firstElementChild,!1)};if(a){const e=g;g=t=>{a.has(t.key)&&((0,d.d)(t),document.removeEventListener(co,g,{capture:!0}),g=e,document.addEventListener(co,g,{capture:!0,passive:!1}),a=void 0,C())}}else C();return w(),{attach:w,detach:S,resetTarget:C}}({list:e,type:this.listType,onSelect:this.onSelect,once:!0,waitForKey:this.waitForKey});this.attach=t,this.detach=s,this.resetTarget=i,ne.IS_MOBILE||this.navigationItem||(this.navigationItem={type:"autocomplete-helper",onPop:()=>{this.navigationItem=void 0,this.toggle(!0)},noBlurOnPop:!0},F.Z.pushItem(this.navigationItem)),this.addEventListener("hidden",(()=>{this.resetTarget=void 0,this.attach=void 0,this.detach=void 0,e.innerHTML="",s(),this.navigationItem&&(F.Z.removeItem(this.navigationItem),this.navigationItem=void 0)}),{once:!0})},(0,w.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,s){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&&(F.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 i=this.controller||e?0:2;e&&this.dispatchEvent("hiding"),(0,Jt.Z)(this.container,"is-visible",!e,a.default.settings.animationsEnabled&&!s?300:0,(()=>{this.hidden&&this.dispatchEvent("hidden")}),i)}}class mo extends go{constructor(e,t){super({appendTo:e,controller:t,listType:"xy",onSelect:e=>!wa.onMediaClick({target:e},!0),waitForKey:["ArrowUp","ArrowDown"]}),this.container.classList.add("stickers-helper"),this.addEventListener("visible",(()=>{setTimeout((()=>{this.scrollable.container.scrollTop=0}),0),a.default.dispatchEvent("choosing_sticker",!0)})),this.addEventListener("hidden",(()=>{this.onChangeScreen&&(v.ZP.removeEventListener("changeScreen",this.onChangeScreen),this.onChangeScreen=void 0),a.default.dispatchEvent("choosing_sticker",!1)}))}checkEmoticon(e){const t=this.controller.getMiddleware();this.lazyLoadQueue&&this.lazyLoadQueue.clear(),ds.Z.preloadAnimatedEmojiSticker(e),ds.Z.getStickersByEmoticon(e).then((e=>{if(!t())return;this.init&&(this.init(),this.init=null);const s=this.list.cloneNode();let i;this.lazyLoadQueue.clear(),i=e.length?new Promise((t=>{const i=[];e.forEach((e=>{s.append(this.superStickerRenderer.renderSticker(e,void 0,i))})),Promise.all(i).finally(t)})):Promise.resolve(),i.then((()=>{this.list.replaceWith(s),this.list=s,this.onChangeScreen||(this.onChangeScreen=()=>{const e=this.list.childElementCount*v.ZP.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=e+"px"},v.ZP.addEventListener("changeScreen",this.onChangeScreen)),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 P.ZP(this.container),this.lazyLoadQueue=new X.ZP,this.superStickerRenderer=new ha(this.lazyLoadQueue,Bl)}}const vo=()=>{const e=new Date;return e.setHours(0,0,0,0),e},fo=()=>{const e=new Date;return e.setFullYear(e.getFullYear()+1),e.setDate(e.getDate()-1),e};class bo extends _n{constructor(e,t,s){var i;if(super((i=e).getTime()>fo().getTime()?new Date:i,t,{noButtons:!0,noTitle:!0,closable:!0,withConfirm:!0,minDate:vo(),maxDate:fo(),withTime:!0,showOverflowMonths:!0,confirmShortcutIsSendShortcut:!0}),this.element.classList.add("popup-schedule"),this.header.append(this.controlsDiv),this.title.replaceWith(this.monthTitle),this.body.append(this.btnConfirm),s){const e=(0,U.Z)("btn-primary btn-secondary btn-primary-transparent primary",{text:"Schedule.SendWhenOnline"});this.body.append(e),(0,l.fc)(e,(()=>{t(La),this.hide()}))}}}var yo=s(6299),wo=s(9041);function So(e,t=!0){const s=[],i=[],n=window.getSelection();let a,o;if(n&&n.rangeCount){const t=n.getRangeAt(0),s=t.startOffset;if(t.startContainer&&t.startContainer==t.endContainer&&s==t.endOffset){const i=s-1,n=e.childNodes;if(t.startContainer===e&&n[i]){a=n[i],o=0;for(let e=0;e<t.endOffset;++e){const t=n[e],s=t.nodeValue||t.alt;s&&(o+=s.length)}}else a=t.startContainer,o=s}}const r=t?[]:void 0;(0,wo.Z)(e,s,i,a,o,r),i.length&&s.push(i.join(""));let l=s.join("\n");const d=l.indexOf("");return-1!=d&&(l=l.substr(0,d)+l.substr(d+1)),l=l.replace(/\u00A0/g," "),r&&Q.Z.combineSameEntities(r),{value:l,entities:r,caretPos:d}}class Co extends go{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"x",onSelect:e=>{s.onEmojiSelected(aa(e),!0)}}),this.appEmojiManager=i,this.container.classList.add("emoji-helper")}init(){this.list=document.createElement("div"),this.list.classList.add("emoji-helper-emojis","super-emojis"),this.container.append(this.list),this.scrollable=new P.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=>{na(e,this.list,!1,!0)}))),this.waitForKey=t?["ArrowUp","ArrowDown"]:void 0,this.toggle(!e.length)}checkQuery(e,t){const s=this.controller.getMiddleware();this.appEmojiManager.getBothEmojiKeywords().then((()=>{if(!s())return;const i=e.replace(/^:/,""),n=this.appEmojiManager.searchEmojis(i);this.render(n,":"!==t)}))}}class Lo extends go{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"y",onSelect:i}),this.className=s,this.container.classList.add(Lo.BASE_CLASS,s)}init(){this.list=document.createElement("div"),this.list.classList.add(Lo.BASE_CLASS+"-list",this.className+"-list"),this.container.append(this.list),this.scrollable=new P.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=Lo.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=Lo.BASE_CLASS_LIST_ELEMENT;e.className+="-list-element";const s=document.createElement("div");s.classList.add(t,e.className),s.dataset.peerId=""+e.peerId;const i=new Yl;i.classList.add("avatar-30",t+"-avatar",e.className+"-avatar"),i.setAttribute("dialog","0"),i.setAttribute("peer",""+e.peerId);const n=document.createElement("div");if(n.classList.add(t+"-name",e.className+"-name"),e.name?n.innerHTML=Q.Z.wrapEmojiText(e.name):n.append(new St.Z({peerId:e.peerId,dialog:!1,onlyFirstName:!1,plainText:!1}).element),s.append(i,n),e.description){const i=document.createElement("div");i.classList.add(t+"-description",e.className+"-description"),i.innerHTML=Q.Z.wrapEmojiText(e.description),s.append(i)}return s}}function Io(e,t){const s=[].concat(e.bot_info);let i;void 0!==t&&(i=new $n.Z({ignoreCase:!0}));const n=new Map;let a;if(s.forEach((e=>{e.commands.forEach(((t,s)=>{const a="/"+t.command;n.set(t.command,{peerId:e.user_id.toPeerId(!1),command:t.command,name:a,description:t.description,index:s}),i&&i.indexObject(t.command,a)}))})),i){const e=i.search(t);a=Array.from(e).map((e=>n.get(e)))}else a=[...n.values()];return a=a.sort(((e,t)=>n.get(e.command).index-n.get(t.command).index)),a}Lo.BASE_CLASS="autocomplete-peer-helper",Lo.BASE_CLASS_LIST_ELEMENT=Lo.BASE_CLASS+"-list-element";class Mo extends Lo{constructor(e,t,s,i,n){super(e,t,"commands-helper",(e=>{const t=e.querySelector(`.${Lo.BASE_CLASS_LIST_ELEMENT}-name`).innerHTML;return s.getReadyToSend((()=>{s.messageInput.innerHTML=t,s.sendMessage(!0)}))})),this.appProfileManager=i,this.appUsersManager=n}checkQuery(e,t){if(!this.appUsersManager.isBot(t))return!1;const s=this.controller.getMiddleware();return Promise.resolve(this.appProfileManager.getProfileByPeerId(t)).then((t=>{if(!s())return;const i=Io(t,e);this.render(i)})),!0}}class Eo{constructor(){this.helpers=new Set,this.middleware=(0,As.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()}}class Po extends Lo{constructor(e,t,s,i,n){super(e,t,"mentions-helper",(e=>{const t=n.getUser(e.dataset.peerId.toUserId());let i,a="";t.username?a="@"+t.username:(a=t.first_name||t.last_name,i={_:"messageEntityMentionName",length:a.length,offset:0,user_id:t.id}),a+=" ",s.insertAtCaret(a,i)})),this.appProfileManager=i,this.appUsersManager=n}checkQuery(e,t,s){const i=e.trim();if(e.length!==i.length)return!1;const n=this.controller.getMiddleware();return this.appProfileManager.getMentions(t&&t.toChatId(),i,s).then((e=>{if(!n())return;const t=i.slice(1).toLowerCase();this.render(e.map((e=>{const s=this.appUsersManager.getUser(e);if(!s.username||s.username.toLowerCase()!==t)return{peerId:e,description:s.username?"@"+s.username:void 0}})).filter(Boolean))})),!0}}var To=s(5494);class ko extends ba{constructor(e){super({element:document.createElement("div")}),this.onBodyTouchStart=e=>{const t=e.touches[0].target;(0,Ws.Z)(t,this.element)||t===this.btnHover||((0,d.d)(e),this.toggle(!1))},(0,w.Z)(this,e),this.element.classList.add(ko.BASE_CLASS),this.element.style.display="none",this.attachButtonListener(this.btnHover,this.listenerSetter),this.listenerSetter.add(a.default)("history_reply_markup",(({peerId:e})=>{this.peerId===e&&(this.checkAvailability()&&this.isActive()&&this.render(),(0,xs.e9)().then((()=>{this.checkForceReply()})))}))}init(){return this.appendTo.append(this.element),this.listenerSetter.add(this)("open",(()=>{this.render(),ce.IS_TOUCH_SUPPORTED&&(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}))})),this.listenerSetter.add(this.element)("click",(e=>{const t=(0,Me.Z)(e.target,"btn");if(!t)return;const s=t.dataset.type,{peerId:i}=this;"keyboardButtonRequestPhone"===s?on({titleLangKey:"ShareYouPhoneNumberTitle",button:{langKey:"OK"},descriptionLangKey:"AreYouSureShareMyContactInfoBot"}).then((()=>{this.appMessagesManager.sendContact(i,a.default.myId)})):this.appMessagesManager.sendText(i,t.dataset.text),this.toggle(!1)})),super.init()}checkForceReply(){const e=this.getReplyMarkup();"replyKeyboardForceReply"!==e._||e.pFlags.hidden||e.pFlags.used||(e.pFlags.used=!0,this.chatInput.initMessageReply(e.mid))}getReplyMarkup(){var e;return null!==(e=this.appMessagesManager.getHistoryStorage(this.peerId).replyMarkup)&&void 0!==e?e:{_:"replyKeyboardHide"}}render(e=this.getReplyMarkup()){this.element.innerHTML="";for(const t of e.rows){const e=document.createElement("div");e.classList.add(ko.BASE_CLASS+"-row");for(const s of t.buttons){const t=document.createElement("button");t.classList.add(ko.BASE_CLASS+"-button","btn"),t.innerHTML=Q.Z.wrapEmojiText(s.text),t.dataset.text=s.text,t.dataset.type=s._,e.append(t)}this.element.append(e)}}checkAvailability(e=this.getReplyMarkup()){var t;const s="replyKeyboardHide"===e._||!(null===(t=e.rows)||void 0===t?void 0:t.length);return this.btnHover.classList.toggle("hide",s),s&&this.toggle(!1),!s}setPeer(e){this.peerId=e,this.checkAvailability(),this.checkForceReply()}}ko.BASE_CLASS="reply-keyboard";var xo=s(8678);const Ao="INLINE-HELPER";class _o extends go{constructor(e,t,s,i,n){super({appendTo:e,controller:t,listType:"xy",waitForKey:["ArrowUp","ArrowDown"],onSelect:e=>{if(!e)return!1;const{peerId:t,botId:s,queryId:i}=this.list.dataset;return this.chat.input.getReadyToSend((()=>{const n=this.appInlineBotsManager.generateQId(i,e.dataset.resultId);this.appInlineBotsManager.sendInlineResult(t.toPeerId(),s,n,Object.assign(Object.assign({},this.chat.getMessageSendingParams()),{clearDraft:!0})),this.chat.input.onMessageSent(!0,!0)}))}}),this.chat=s,this.appUsersManager=i,this.appInlineBotsManager=n,this._checkQuery=(e,t,s)=>{return i=this,n=void 0,o=function*(){const i=this.controller.getMiddleware(),n=yield this.appUsersManager.resolveUsername(t);if(!i())throw"PEER_CHANGED";if("user"!==n._)throw"NOT_A_BOT";const a=this.appInlineBotsManager.getInlineResults(e,n.id,s).then((t=>{if(!i())throw"PEER_CHANGED";this.init&&(this.init(),this.init=null);const s=this.list.cloneNode();s.dataset.peerId=""+e,s.dataset.botId=""+n.id,s.dataset.queryId=""+t.query_id;const a=new da(null,Ao,this.scrollable,!1);this.lazyLoadQueue.clear(),this.superStickerRenderer.clear();const o=[],r=!!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=r?void 0:document.createElement("div");if(n&&(n.classList.add("inline-helper-result-preview"),t.append(n)),s.append(t),r)t.classList.add("grid-item");else{n.classList.add("empty"),n.innerHTML=Q.Z.wrapEmojiText([...e.title.trim()][0]);const i=document.createElement("div");i.classList.add("inline-helper-result-title"),i.innerHTML=Q.Z.wrapEmojiText(e.title);const a=document.createElement("div");a.classList.add("inline-helper-result-description"),a.innerHTML=Q.Z.wrapRichText(e.description,{noCommands:!0,noLinks:!0}),t.append(i,a);const o=document.createElement("div");o.classList.add("inline-helper-separator"),s.append(o)}if("botInlineResult"===e._){if(e.thumb&&0===e.thumb.mime_type.indexOf("image/")){let s;n?(s=document.createElement("div"),n.append(s)):s=t,s.classList.add("media-container"),r&&s.classList.add("no-border-radius"),this.lazyLoadQueue.push({div:t,load:()=>le.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,xo.Z)(e).then((e=>{Cs(s,t,e,!0)}))}))})}}else{const s=e.document||e.photo;if(["sticker","gif"].includes(null==s?void 0:s.type)&&r)(0,gs.Z)(s),"gif"===s.type?a.add(s,t):"sticker"===s.type&&(t.classList.add("super-sticker"),this.superStickerRenderer.renderSticker(s,t,o),2===s.sticker&&this.superStickerRenderer.observeAnimatedDiv(t));else if(s){const e=r?48:void 0;r&&t.classList.add("no-border-radius"),Ss({photo:s,container:r?t:n,boxWidth:e,boxHeight:e,middleware:i,lazyLoadQueue:this.lazyLoadQueue,loadPromises:o})}}}return Promise.all(o).then((()=>{if(!i())return void a.clear();s.classList.toggle("is-gallery",r),s.classList.toggle("super-stickers",r),this.container.classList.toggle("is-gallery",r);const o=this.list.parentElement;if(o.textContent="",t.switch_pm){const s=(0,U.Z)("btn-primary btn-secondary btn-primary-transparent primary");s.insertAdjacentHTML("beforeend",Q.Z.wrapEmojiText(t.switch_pm.text)),(0,l.fc)(s,(s=>{this.appInlineBotsManager.switchToPM(e,n.id,t.switch_pm.start_param)})),o.append(s)}o.append(this.list=s),this.gifsMasonry&&this.gifsMasonry.detach(),this.gifsMasonry=a,a.attach(),this.onChangeScreen||(this.onChangeScreen=()=>{if(this.list.classList.contains("is-gallery")){const e=this.list.childElementCount*v.ZP.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=e+"px"}else this.list.style.width=""},v.ZP.addEventListener("changeScreen",this.onChangeScreen)),this.onChangeScreen(),this.toggle(!t.results.length&&!t.switch_pm),this.scrollable.scrollTop=0}))}));return{user:n,renderPromise:a}},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},this.container.classList.add("inline-helper"),this.addEventListener("visible",(()=>{setTimeout((()=>{this.scrollable.container.scrollTop=0}),0)})),this.checkQuery=dt(this._checkQuery,200,!0,!0),this.addEventListener("hidden",(()=>{this.onChangeScreen&&(v.ZP.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 P.ZP(this.container),this.lazyLoadQueue=new X.ZP,this.superStickerRenderer=new ha(this.lazyLoadQueue,Ao)}}var Zo=s(8090);class Do extends Lo{constructor(e,t,s){super(e,void 0,"bot-commands",(e=>{const s=e.querySelector(`.${Lo.BASE_CLASS_LIST_ELEMENT}-name`).innerHTML;return t.getReadyToSend((()=>{t.messageInput.innerHTML=s,t.sendMessage(!0),this.toggle(!0)}))})),this.chatInput=t,this.appProfileManager=s}setUserId(e,t){var s;if(this.userId!==e||!(null===(s=this.list)||void 0===s?void 0:s.childElementCount))return this.userId=e,(0,Nt.Z)(this.appProfileManager.getProfile(e),(e=>{if(!t())return;const s=Io(e),i=50*s.length+8+24;this.container.style.setProperty("--height",i+"px"),this.render(s)}));this.toggle(!1)}}const Fo="Posting media content isn't allowed in this group.";class Ro{constructor(e,t,s,i,n,o,r,c,h,p,u,g,m,v,f){this.chat=e,this.appMessagesManager=t,this.appMessagesIdsManager=s,this.appDocsManager=i,this.appChatsManager=n,this.appPeersManager=o,this.appWebPagesManager=r,this.appImManager=c,this.appDraftsManager=h,this.serverTimeManager=p,this.appNotificationsManager=u,this.appEmojiManager=g,this.appUsersManager=m,this.appInlineBotsManager=v,this.appProfileManager=f,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,d.d)(e),this.recordCanceled=!0,this.recorder.stop(),Ja.Z.setKeepAlive(!1)},this.onEmoticonsOpen=()=>{const e=ce.IS_TOUCH_SUPPORTED?"flip-icon":"active";this.btnToggleEmoticons.classList.toggle(e,!0)},this.onEmoticonsClose=()=>{const e=ce.IS_TOUCH_SUPPORTED?"flip-icon":"active";this.btnToggleEmoticons.classList.toggle(e,!1)},this.scheduleSending=(e=this.sendMessage.bind(this,!0),t=new Date)=>{const{peerId:s}=this.chat,i=this.chat.bubbles.getMiddleware(),n=a.default.myId!==s&&s.isUser()&&this.appUsersManager.isUserOnlineVisible(s);new bo(t,(t=>{i()&&(t<=10+(Date.now()/1e3|0)&&(t=void 0),this.scheduleDate=t,e(),"scheduled"!==this.chat.type&&t&&setTimeout((()=>{i()&&this.appImManager.openScheduled(s)}),0))}),n).show()},this.prepareDocumentExecute=()=>(this.executedHistory.push(this.messageInput.innerHTML),()=>this.canUndoFromHTML=this.messageInput.innerHTML),this.undoRedo=(e,t,s)=>{(0,d.d)(e);let i=this.messageInput.innerHTML;if(i&&i!==s){this.lockRedo=!0;let e=0;do{document.execCommand(t,!1,null);const s=this.messageInput.innerHTML;if(i===s){if(++e>2)break}else e=0;i=s}while(i!==s);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 s=e.code,i=t[s];if(document.getSelection().toString().trim().length&&i&&("KeyK"===s?this.appImManager.markupTooltip.showLinkEditor():this.applyMarkdown(i),(0,d.d)(e)),"KeyZ"===s){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:s,entities:i,caretPos:n}=So(this.messageInputField.input),a=Q.Z.parseMarkdown(s,i,!0),o=Q.Z.mergeEntities(i,Q.Z.parseEntities(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=s.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=ct.Z.invokeApiHashable({method:"messages.getWebPage",processResult:e=>this.appWebPagesManager.saveWebPage(e),params:{url:t}}).then((s=>{this.getWebPagePromise===e&&(this.getWebPagePromise=void 0),this.lastUrl===t&&("webPage"===s._?(this.setTopInfo("webpage",(()=>{}),s.site_name||s.title||"Webpage",s.description||s.url||""),delete this.noWebPage,this.willSendWebPage=s):this.willSendWebPage&&this.onHelperCancel())}))}break}else this.lastUrl&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null,this.helperType?this.helperFunc():this.clearHelper());if(s.trim()){const e=Date.now();e-this.lastTimeType>=6e3&&(this.lastTimeType=e,this.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageTypingAction"})),this.botCommands&&this.botCommands.toggle(!0)}else this.lastTimeType&&this.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageCancelAction"}),this.appImManager.markupTooltip&&this.appImManager.markupTooltip.hide();this.botCommands&&this.updateBotCommandsToggle(),this.editMsgId||this.saveDraftDebounced(),this.checkAutocomplete(s,n,o),this.updateSendBtn()},this.onEmojiSelected=(e,t)=>{this.insertAtCaret(e,Q.Z.getEmojiEntityFromEmoji(e),t)},this.onBtnSendClick=e=>{if((0,d.d)(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()&&!this.chat.canSend("send_media"))return void rt(Fo);this.chatInput.classList.add("is-locked"),(0,Gs.Z)(),this.recorder.start().then((()=>{this.releaseMediaPlayback=ve.setSingleMedia(),this.recordCanceled=!1,this.setRecording(!0),Ja.Z.setKeepAlive(!0);const e=()=>{new gt("popup-cancel-record",{titleLangKey:"DiscardVoiceMessageTitle",descriptionLangKey:"DiscardVoiceMessageDescription",buttons:[{langKey:"DiscardVoiceMessageAction",callback:()=>{(0,l.tH)(this.btnCancelRecord)}},{langKey:"Continue",isCancel:!0}]}).show()};this.recordingOverlayListener=this.listenerSetter.add(document.body)("mousedown",(t=>{(0,Me.Z)(t.target,"chat-input")||(0,Me.Z)(t.target,"popup-cancel-record")||((0,d.d)(t),e())}),{capture:!0,passive:!1}),F.Z.pushItem(this.recordingNavigationItem={type:"voice",onPop:()=>(setTimeout((()=>{e()}),0),!1)}),this.recordStartTime=Date.now();const t=this.recorder.sourceNode,s=t.context.createAnalyser();t.connect(s),s.fftSize=32;const i=new Uint8Array(s.frequencyBinCount),n=255*i.length;let a=()=>{if(!this.recording)return;s.getByteFrequencyData(i);let e=0;i.forEach((t=>{e+=t}));let t=Math.min(1,e/n+.36);this.recordRippleEl.style.transform=`scale(${t})`;let o=Date.now()-this.recordStartTime,r=o%1e3,l=(""+o/1e3).toHHMMSS()+","+("00"+Math.round(r/10)).slice(-2);this.recordTimeEl.innerText=l,(0,De.T2)(a)};a()})).catch((e=>{switch(e.name){case"NotAllowedError":rt("Please allow access to your microphone");break;case"NotReadableError":rt(e.message);break;default:console.error("Recorder start error:",e,e.name,e.message),rt(e.message)}this.setRecording(!1),this.chatInput.classList.remove("is-locked")}))}},this.onHelperCancel=(e,t)=>{if(e&&(0,d.d)(e),this.willSendWebPage){const e=this.lastUrl;let t=!1;if(this.helperType&&(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=Q.Z.parseMarkdown(this.messageInputField.value,[]);if(e.message!==t)return void new gt("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,d.d)(e),(0,Me.Z)(e.target,"reply"))if("forward"===this.helperType){const{forwardElements:e}=this;e&&ce.IS_TOUCH_SUPPORTED&&!e.container.classList.contains("active")&&(0,J.YP)(e.container)}else"reply"===this.helperType?this.chat.setMessageId(this.replyToMsgId):"edit"===this.helperType&&this.chat.setMessageId(this.editMsgId)},this.listenerSetter=new B.Z}construct(){this.chatInput=document.createElement("div"),this.chatInput.classList.add("chat-input"),this.chatInput.style.display="none",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=Na();this.rowsWrapper.append(e);const t=this.fakeRowsWrapper=document.createElement("div");t.classList.add("fake-wrapper","fake-rows-wrapper");const s=this.fakeSelectionWrapper=document.createElement("div");s.classList.add("fake-wrapper","fake-selection-wrapper"),this.inputContainer.append(this.rowsWrapperWrapper,t,s),this.chatInput.append(this.inputContainer),this.goDownBtn=W({icon:"arrow_down",className:"bubbles-corner-button bubbles-go-down hide"}),this.inputContainer.append(this.goDownBtn),(0,l.fc)(this.goDownBtn,(e=>{(0,d.d)(e),this.chat.bubbles.onGoDownClick()}),{listenerSetter:this.listenerSetter});const i=this.controlContainer=document.createElement("div");i.classList.add("chat-input-control","chat-input-wrapper"),this.inputContainer.append(i)}constructPeerHelpers(){this.replyElements.container=document.createElement("div"),this.replyElements.container.classList.add("reply-wrapper"),this.replyElements.iconBtn=N(""),this.replyElements.cancelBtn=N("close reply-cancel",{noRipple:!0}),this.replyElements.container.append(this.replyElements.iconBtn,this.replyElements.cancelBtn);const e=()=>(i=!0,this.canToggleHideAuthor()),t=()=>{i=!1},s=this.forwardElements={};let i=!1;const n=[s.showSender={text:"Chat.Alert.Forward.Action.Show1",onClick:e,checkboxField:new ut.Z({checked:!0})},s.hideSender={text:"Chat.Alert.Forward.Action.Hide1",onClick:e,checkboxField:new ut.Z({checked:!1})},s.showCaption={text:"Chat.Alert.Forward.Action.ShowCaption",onClick:t,checkboxField:new ut.Z({checked:!0})},s.hideCaption={text:"Chat.Alert.Forward.Action.HideCaption",onClick:t,checkboxField:new ut.Z({checked:!1})},s.changePeer={text:"Chat.Alert.Forward.Action.Another",onClick:()=>{this.changeForwardRecipient()},icon:"replace"}],o=s.container=Ce(n,this.listenerSetter),r=Array.from(o.children);[{elements:r.slice(0,2),onChange:(e,t)=>{const n=!!+e;i&&(this.forwardWasDroppingAuthor=!n);const a=this.replyElements.container.querySelector(".reply-title");if(a){const e=a.firstElementChild,t=k.default.weakMap.get(e),i=s.showSender.checkboxField.checked?"Chat.Accessory.Forward":"Chat.Accessory.Hidden";t.key=i,t.update()}}},{elements:r.slice(2,4),onChange:e=>{const t=!!+e;let i;i=t&&void 0!==this.forwardWasDroppingAuthor?this.forwardWasDroppingAuthor?s.hideSender:s.showSender:t?s.showSender:s.hideSender,i.checkboxField.checked=!0}}].forEach((e=>{const t=Je(e.elements.map((e=>({container:e,input:e.querySelector("input")}))),e.onChange),s=document.createElement("hr");t.append(s),o.append(t)})),o.append(s.changePeer.element),ce.IS_TOUCH_SUPPORTED||(this.forwardHover=new ba({element:o})),s.modifyArgs=n.slice(0,-1),this.replyElements.container.append(o),s.modifyArgs.forEach(((e,t)=>{const{input:s}=e.checkboxField;s.type="radio",s.name=t<2?"author":"caption",s.value=""+ +!(t%2)})),this.newMessageWrapper=document.createElement("div"),this.newMessageWrapper.classList.add("new-message-wrapper"),this.sendAsContainer=document.createElement("div"),this.sendAsContainer.classList.add("new-message-send-as-container"),this.sendAsCloseBtn=document.createElement("div"),this.sendAsCloseBtn.classList.add("new-message-send-as-close","new-message-send-as-avatar","tgico-close");const c=[{text:"SendMessageAsTitle",onClick:void 0}];let h;const p=e=>{e&&(h=this.sendAsAvatar);const t=this.sendAsAvatar!==h,s=!e&&t?2:0;(0,Jt.Z)(this.sendAsCloseBtn,"is-visible",e,300,void 0,s),t||(0,Jt.Z)(h,"is-visible",!e,300,void 0,s)};if(Ie({noRipple:!0,listenerSetter:this.listenerSetter,container:this.sendAsContainer},"top-right",c,(()=>{p(!0)}),(()=>{p(!1)})),c[0].element.classList.add("btn-menu-item-header"),this.sendAsBtnMenu=this.sendAsContainer.firstElementChild,this.sendAsBtnMenu.classList.add("scrollable","scrollable-y"),this.sendAsContainer.append(this.sendAsCloseBtn),this.btnToggleEmoticons=N("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=W({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,l.fc)(this.goMentionBtn,(e=>{(0,d.d)(e),this.appMessagesManager.goToNextMention(this.chat.peerId)}),{listenerSetter:this.listenerSetter}),this.btnScheduled=N("scheduled btn-scheduled float hide",{noRipple:!0}),(0,l.fc)(this.btnScheduled,(e=>{this.appImManager.openScheduled(this.chat.peerId)}),{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.default)("scheduled_new",(({peerId:e})=>{this.chat.peerId===e&&this.btnScheduled.classList.remove("hide")})),this.listenerSetter.add(a.default)("scheduled_delete",(({peerId:e})=>{this.chat.peerId===e&&this.appMessagesManager.getScheduledMessages(this.chat.peerId).then((e=>{this.btnScheduled.classList.toggle("hide",!e.length)}))})),this.btnToggleReplyMarkup=N("botcom toggle-reply-markup float hide",{noRipple:!0}),this.replyKeyboard=new ko({appendTo:this.rowsWrapper,listenerSetter:this.listenerSetter,appMessagesManager:this.appMessagesManager,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 Do(this.rowsWrapper,this,this.appProfileManager),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,l.fc)(this.botCommandsToggle,(e=>{(0,d.d)(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=[...g].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:()=>{new io(this.chat).show()},verify:e=>e.isAnyChat()&&this.chat.canSend("send_polls")}],this.attachMenu=Ie({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.sendAsContainer,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 Eo,this.stickersHelper=new mo(this.rowsWrapper,this.autocompleteHelperController),this.emojiHelper=new Co(this.rowsWrapper,this.autocompleteHelperController,this,this.appEmojiManager),this.commandsHelper=new Mo(this.rowsWrapper,this.autocompleteHelperController,this,this.chat.appProfileManager,this.chat.appUsersManager),this.mentionsHelper=new Po(this.rowsWrapper,this.autocompleteHelperController,this,this.chat.appProfileManager,this.chat.appUsersManager),this.inlineHelper=new _o(this.rowsWrapper,this.autocompleteHelperController,this.chat,this.appUsersManager,this.appInlineBotsManager),this.rowsWrapper.append(this.newMessageWrapper),this.btnCancelRecord=N("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=N("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"></span>\n '),this.btnSendContainer.append(this.recordRippleEl,this.btnSend),"scheduled"!==this.chat.type&&(this.sendMenu=new eo({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),Ca.attachButtonListener(this.btnToggleEmoticons,this.listenerSetter),this.listenerSetter.add(Ca)("open",this.onEmoticonsOpen),this.listenerSetter.add(Ca)("close",this.onEmoticonsClose),this.attachMessageInputField(),this.listenerSetter.add(a.default)("settings_updated",(()=>{(this.stickersHelper||this.emojiHelper)&&(this.previousQuery="",this.checkAutocomplete()),this.messageInputField&&this.messageInputField.onFakeInput()})),this.listenerSetter.add(a.default)("draft_updated",(({peerId:e,threadId:t,draft:s,force:i})=>{this.chat.threadId===t&&this.chat.peerId===e&&this.setDraft(s,!0,i)})),this.listenerSetter.add(a.default)("peer_changing",(e=>{this.chat===e&&this.saveDraft()})),this.listenerSetter.add(a.default)("chat_changing",(({from:e,to:t})=>{this.chat===e?this.autocompleteHelperController.toggleListNavigation(!1):this.chat===t&&this.autocompleteHelperController.toggleListNavigation(!0)})),this.sendAsContainer&&this.listenerSetter.add(a.default)("peer_full_update",(e=>{e.isChannel()&&this.chat.peerId===e&&this.updateSendAs()})),"scheduled"===this.chat.type?this.listenerSetter.add(a.default)("scheduled_delete",(({peerId:e,mids:t})=>{this.chat.peerId===e&&t.includes(this.editMsgId)&&this.onMessageSent()})):(this.listenerSetter.add(a.default)("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(a.default)("dialogs_multiupdate",(e=>{e[this.chat.peerId]&&(this.startParam===Re.gZ?this.setStartParam():this.center(!0))})));try{this.recorder=new(Xa())({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=>{let t=e.target.files;t.length&&(new lo(this.chat,Array.from(t).slice(),this.willAttachType),this.fileInput.value="")}),!1),(0,l.fc)(this.btnSend,this.onBtnSendClick,{listenerSetter:this.listenerSetter,touchMouseDown:!0}),this.recorder&&((0,l.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&&(F.Z.removeItem(this.recordingNavigationItem),this.recordingNavigationItem=void 0),this.recordCanceled)return;const{peerId:t,threadId:s}=this.chat,i=this.replyToMsgId,n=(Date.now()-this.recordStartTime)/1e3|0,a=new Blob([e],{type:"audio/ogg"});Ja.Z.decode(e,!0).then((e=>{Ja.Z.setKeepAlive(!1),this.appMessagesManager.sendFile(t,a,{isVoiceMessage:!0,isMedia:!0,duration:n,waveform:e.waveform,objectURL:e.url,replyToMsgId:i,threadId:s,clearDraft:!0}),this.onMessageSent(!1,!0)}))}),(0,l.fc)(this.replyElements.cancelBtn,this.onHelperCancel,{listenerSetter:this.listenerSetter}),(0,l.fc)(this.replyElements.container,this.onHelperClick,{listenerSetter:this.listenerSetter}),this.saveDraftDebounced=dt((()=>this.saveDraft()),2500,!1,!0),this.botStartBtn=(0,U.Z)("btn-primary btn-transparent text-bold chat-input-control-button"),this.botStartBtn.append((0,k.i18n)("BotStart")),(0,l.fc)(this.botStartBtn,(()=>{const{startParam:e}=this;if(void 0===e)return;const t=this.toggleBotStartBtnDisability=(0,mt.Z)([this.botStartBtn],!0),s=this.chat.peerId,i=this.chat.bubbles.getMiddleware((()=>this.chat.peerId===s&&this.startParam===e&&this.toggleBotStartBtnDisability===t));this.appMessagesManager.startBot(s.toUserId(),void 0,e).then((()=>{i()&&(t(),this.toggleBotStartBtnDisability=void 0,this.setStartParam())}))}),{listenerSetter:this.listenerSetter}),this.controlContainer.append(this.botStartBtn)}constructPinnedHelpers(){this.pinnedControlBtn=(0,U.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 Oa(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=!1){const t=this.getNeededFakeContainer();if(!t&&!this.inputContainer.classList.contains("is-centering"))return;if(t===this.fakeWrapperTo)return;const s=t||this.fakeWrapperTo,i=!!t,n=this.fakeWrapperTo;let a,o="",r="";const l=s.getBoundingClientRect(),d=this.fakeRowsWrapper.getBoundingClientRect(),c=d.width,h=l.width;if(c!==h){const e=h/c,t=(c-h)/2;if(a=l.left-d.left-t,i&&(o=`translateX(${a}px) scaleX(${e})`,e<1)){const t=12;r=t+t*(1-e)+"px"}}this.fakeWrapperTo=t;const p=e?200:0;return(0,Jt.Z)(this.inputContainer,"is-centering",i,p),(0,Jt.Z)(this.rowsWrapperWrapper,"is-centering-to-control",!!(i&&t&&t.classList.contains("chat-input-control")),p),this.rowsWrapper.style.transform=o,this.rowsWrapper.style.borderRadius=r,{transform:o,borderRadius:r,needTranslateX:n&&(t&&t.classList.contains("chat-input-control")&&n===this.fakeSelectionWrapper||n.classList.contains("chat-input-control"))?-.5*a:a,widthFrom:c,widthTo:h}}setStartParam(e){this.startParam!==e&&(this.startParam=e,this.center(!0))}getNeededFakeContainer(){return this.chat.selection.isSelecting?this.fakeSelectionWrapper:void 0!==this.startParam||!this.chat.canSend()||"pinned"===this.chat.type||this.chat.isStartButtonNeeded()?this.controlContainer:void 0}getReadyToSend(e){return"scheduled"===this.chat.type?(this.scheduleSending(e),!0):(e(),!1)}setUnreadCount(){if(!this.goDownUnreadBadge)return;const e=this.appMessagesManager.getDialogOnly(this.chat.peerId),t=null==e?void 0:e.unread_count;if(this.goDownUnreadBadge.innerText=""+(t||""),this.goDownUnreadBadge.classList.toggle("badge-gray",this.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,to.Z)(this.messageInputField.input);let s;(e.length||this.replyToMsgId)&&(s={_:"draftMessage",date:(0,ie.bz)(!0)+this.serverTimeManager.serverTimeOffset,message:e,entities:t.length?t:void 0,pFlags:{no_webpage:this.noWebPage},reply_to_msg_id:this.replyToMsgId}),this.appDraftsManager.syncDraft(this.chat.peerId,this.chat.threadId,s)}destroy(){this.listenerSetter.removeAll()}cleanup(e=!0){this.chat.peerId||(this.chatInput.style.display="none",this.goDownBtn.classList.add("hide")),Ks(),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,s=!1){return!(!s&&!(0,so.Z)(this.messageInput)||"scheduled"===this.chat.type||(e||(e=this.appDraftsManager.getDraft(this.chat.peerId,this.chat.threadId))?this.messageInputField.value===e.rMessage&&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(e.rMessage,t,t),0):(s&&(this.chat.container.classList.contains("is-helper-active")&&this.t(),this.messageInputField.inputFake.textContent="",this.messageInputField.onFakeInput(!1),(this.chat.bubbles.messagesQueuePromise||Promise.resolve()).then((()=>{(0,De.T2)((()=>{this.onMessageSent()}))}))),1)))}finishPeerChange(e){const t=this.chat.peerId,{forwardElements:s,btnScheduled:i,replyKeyboard:n,sendMenu:a,goDownBtn:o,chatInput:r,sendAsContainer:l,botCommandsToggle:d}=this;r.style.display="";const c=this.appPeersManager.isBroadcast(t);if(o.classList.toggle("is-broadcast",c),o.classList.remove("hide"),this.goDownUnreadBadge&&this.setUnreadCount(),"pinned"===this.chat.type&&r.classList.toggle("can-pin",this.appPeersManager.canPinMessage(t)),s&&(this.forwardWasDroppingAuthor=!1,s.showCaption.checkboxField.setValueSilently(!0),s.showSender.checkboxField.setValueSilently(!0)),i){i.classList.add("hide");const e=this.chat.bubbles.getMiddleware();this.appMessagesManager.getScheduledMessages(t).then((t=>{e()&&i.classList.toggle("hide",!t.length)}))}if(this.newMessageWrapper&&this.updateOffset(null,!1,!0),d&&(this.hasBotCommands=void 0,this.botCommands.toggle(!0,void 0,!0),this.updateBotCommandsToggle(!0),d.remove(),this.appPeersManager.isBot(t))){const e=t.toUserId(),s=this.chat.bubbles.getMiddleware(),i=this.appProfileManager.getProfile(e);(0,Nt.Z)(i,(e=>{s()&&this.updateBotCommands(e,!(i instanceof Promise))}))}l&&(this.sendAsAvatar&&(this.sendAsAvatar.remove(),this.sendAsAvatar=void 0),l.remove(),this.sendAsPeerId=void 0,this.updatingSendAsPromise=void 0,this.updateSendAs(!0)),n&&n.setPeer(t),a&&a.setPeerId(t),this.messageInput?this.updateMessageInput():this.pinnedControlBtn&&this.pinnedControlBtn.append((0,k.i18n)(this.appPeersManager.canPinMessage(this.chat.peerId)?"Chat.Input.UnpinAll":"Chat.Pinned.DontShow")),this.startParam=e,this.center(!1)}updateOffset(e,t,s,i){e?this.newMessageWrapper.dataset.offset=e:delete this.newMessageWrapper.dataset.offset,(0,Jt.Z)(this.newMessageWrapper,"has-offset",t,s?0:300,void 0,i)}updateBotCommands(e,t){this.hasBotCommands=e.bot_info&&e.bot_info.commands.length,this.updateBotCommandsToggle(t)}updateBotCommandsToggle(e){const{botCommandsToggle:t,hasBotCommands:s}=this,i=s&&this.isInputEmpty();s||t.remove();const n=i,a=t.parentElement?0:2;t.parentElement||this.newMessageWrapper.prepend(t),this.updateOffset("commands",n,e,a)}updateSendAsButtons(e){const t=e.map(((e,t)=>{const s=document.createElement("div"),i=document.createElement("div");return i.classList.add("btn-menu-item-subtitle"),e.isUser()?i.append((0,k.i18n)("Chat.SendAs.PersonalAccount")):e===this.chat.peerId?i.append((0,k.i18n)("VoiceChat.DiscussionGroup")):i.append(this.appProfileManager.getChatMembersString(e.toChatId())),s.append(new St.Z({peerId:e}).element,i),{onClick:t?()=>{const t=this.chat.peerId;if(t.isChannel()){const s=this.appProfileManager.getCachedFullChat(t.toChatId());if(s){s.default_send_as=this.appPeersManager.getOutputPeer(e),this.sendAsPeerId=e,this.updateSendAsAvatar(e),this.updateMessageInputPlaceholder();const t=this.chat.bubbles.getMiddleware(),i=()=>{if(this.sendAsPeerId!==e||!t())return;const s=this.sendAsPeerIds.slice();(0,z.Z)(s,e),s.unshift(e),this.updateSendAsButtons(s)};a.default.settings.animationsEnabled?setTimeout(i,250):i()}}ct.Z.invokeApi("messages.saveDefaultSendAs",{peer:this.appPeersManager.getInputPeerById(t),send_as:this.appPeersManager.getInputPeerById(e)})}:void 0,textElement:s}})),s=Ce(t);t.forEach(((t,s)=>{const i=e[s],n=new Yl;n.classList.add("avatar-32","btn-menu-item-icon"),n.setAttribute("peer",""+i),s||n.classList.add("active"),t.element.prepend(n)})),Array.from(this.sendAsBtnMenu.children).slice(1).forEach((e=>e.remove())),this.sendAsBtnMenu.append(...Array.from(s.children))}updateSendAsAvatar(e,t){const s=this.sendAsAvatar;if(s&&+s.getAttribute("peer")===e)return;s||(t=!0);let i=t?0:2;const n=t?0:300,a=this.sendAsAvatar=new Yl;a.setAttribute("dialog","0"),a.setAttribute("peer",""+e),a.classList.add("new-message-send-as-avatar","avatar-30"),(0,Jt.Z)(a,"is-visible",!0,n,void 0,i),s&&(0,Jt.Z)(s,"is-visible",!1,n,(()=>{s.remove()}),i),this.sendAsContainer.append(a)}getDefaultSendAs(){return(0,Nt.Z)(this.appProfileManager.getChannelFull(this.chat.peerId.toChatId()),(e=>e.default_send_as?this.appPeersManager.getPeerId(e.default_send_as):void 0))}updateSendAs(e){const t=this.chat.peerId;if(!t.isChannel()||this.updatingSendAsPromise)return;const s=this.chat.bubbles.getMiddleware((()=>!this.updatingSendAsPromise||this.updatingSendAsPromise===r)),{sendAsContainer:i}=this,n=t.toChatId(),a=this.getDefaultSendAs();a instanceof Promise&&(e=void 0);const o=(0,Nt.Z)(a,(t=>{if(!s()||void 0===t)return;this.sendAsPeerId=t,this.updateSendAsAvatar(t,e),this.updateMessageInputPlaceholder(),this.appChatsManager.getSendAs(n).then((e=>{if(!s())return;const i=e.map((e=>this.appPeersManager.getPeerId(e)));this.sendAsPeerIds=i.slice(),(0,z.Z)(i,t),i.unshift(t),this.updateSendAsButtons(i)}));let a=0;i.parentElement||(this.newMessageWrapper.prepend(i),a=2),this.updateOffset("as",!0,e,a),this.updatingSendAsPromise=void 0})),r=this.updatingSendAsPromise=Promise.resolve(o);return r}updateMessageInputPlaceholder(){const e=k.default.weakMap.get(this.messageInput);if(e){const{peerId:t,threadId:s}=this.chat;let i;i=s?"Comment":this.appPeersManager.isBroadcast(t)?"ChannelBroadcast":void 0!==this.sendAsPeerId&&this.sendAsPeerId!==a.default.myId||this.appMessagesManager.isAnonymousSending(t)?"SendAnonymously":"Message",e.compareAndUpdate({key:i})}}updateMessageInput(){const{chatInput:e,attachMenu:t,messageInput:s}=this,{peerId:i,threadId:n}=this.chat,a=this.chat.canSend();e.classList.contains("is-hidden")!==!a&&(e.classList.add("no-transition"),e.classList.toggle("is-hidden",!a),e.offsetLeft,e.classList.remove("no-transition")),this.updateMessageInputPlaceholder();const o=this.attachMenuButtons.filter((e=>{const t=e.verify(i,n);return e.element.classList.toggle("hide",!t),t}));a?(s.setAttribute("contenteditable","true"),this.setDraft(void 0,!1),s.innerHTML||this.messageInputField.onFakeInput()):s.removeAttribute("contenteditable"),t.toggleAttribute("disabled",!o.length),t.classList.toggle("btn-disabled",!o.length),this.updateSendBtn()}attachMessageInputField(){const e=this.messageInputField;this.messageInputField=new _.Z({placeholder:"Message",name:"message",animate:!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(),Zo.T&&(0,Zo.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,yo.Z)(e))(0,d.d)(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,no.Z)(this.messageInput)})),ce.IS_TOUCH_SUPPORTED&&(0,l.fc)(this.messageInput,(e=>{this.appImManager.selectTab(1),Ca.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.appMessagesManager.readAllHistory(this.chat.peerId,this.chat.threadId)}))}applyMarkdown(e,t){const s={bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",monospace:()=>document.execCommand("fontName",!1,"monospace"),link:t?()=>document.execCommand("createLink",!1,t):()=>document.execCommand("unlink",!1,null),spoiler:()=>document.execCommand("fontName",!1,"spoiler")};if(!s[e])return!1;const i=s[e],n=this.prepareDocumentExecute(),a=[];if(a.push(document.execCommand("styleWithCSS",!1,"true")),"monospace"===e||"spoiler"===e){let t=!1;const s=window.getSelection();if(!s.isCollapsed){const i=s.getRangeAt(0),n=wo.o[e],a=i.commonAncestorContainer;(a.parentNode.matches(n.match)||a instanceof HTMLElement&&a.matches(n.match))&&(t=!0)}t?a.push(document.execCommand("fontName",!1,"Roboto")):a.push("function"==typeof i?i():document.execCommand(i,!1,null))}else a.push("function"==typeof i?i():document.execCommand(i,!1,null));return a.push(document.execCommand("styleWithCSS",!1,"false")),n(),this.appImManager.markupTooltip&&this.appImManager.markupTooltip.setActiveMarkupButton(),!0}insertAtCaret(e,t,s=!0){const{value:i,caretPos:n,entities:a}=So(this.messageInput),o=n>=0?n:i.length,r=i.substr(0,o),l=i.substr(o),d=s?r.match(Ro.AUTO_COMPLETE_REG_EXP):null,c=d?d.index+(d[0].length-d[2].length):r.length,h=r.slice(0,c)+e+l,p=Q.Z.parseEntities(i);Q.Z.mergeEntities(a,p);const u=t?Math.max(t.length,e.length):e.length,g=[];t&&(g.push(t),t.offset=c);const m=d?u-d[2].length:u;a.forEach((e=>{e.offset>=c&&(e.offset+=m)})),Q.Z.mergeEntities(a,g);{const e={_:"messageEntityCaret",offset:c+u,length:0};let t=0;for(let s=a.length;t<s&&!(a[t].offset>e.offset);++t);a.splice(t,0,e)}const v=Q.Z.wrapDraftText(h,{entities:a});this.messageInputField.setValueSilently(v,!0);const f=this.messageInput.querySelector(".composer-sel");f&&(function(e){const t=e;if(1===(e=e.previousSibling).nodeType){const s=document.createTextNode("");e.parentNode.insertBefore(s,t.nextSibling&&t.nextSibling.nodeType!==e.nodeType?t.nextSibling:t),e=s}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 s=window.getSelection();s.removeAllRanges(),s.addRange(t)}}(f),f.remove()),this.onMessageInput()}checkAutocomplete(e,t,s){if(void 0===e){const i=So(this.messageInputField.input,!0);e=i.value,t=i.caretPos,s=i.entities}if(-1===t&&(t=e.length),void 0===s){const t=Q.Z.parseMarkdown(e,s,!0);s=Q.Z.mergeEntities(s,Q.Z.parseEntities(t))}if(e=e.slice(0,t),this.previousQuery===e)return;this.previousQuery=e;const i=e.match(Ro.AUTO_COMPLETE_REG_EXP);let n;if(i){const t=s[0];let o=i[2];const r=o[0];if(this.stickersHelper&&a.default.settings.stickers.suggest&&this.chat.canSend("send_stickers")&&"messageEntityEmoji"===(null==t?void 0:t._)&&t.length===e.length&&!t.offset)n=this.stickersHelper,this.stickersHelper.checkEmoticon(e);else if("@"===r){const e=this.chat.threadId?this.appMessagesIdsManager.getServerMessageId(this.chat.threadId):void 0;this.mentionsHelper.checkQuery(o,this.chat.peerId.isUser()?Re.NM:this.chat.peerId,e)&&(n=this.mentionsHelper)}else i[1]||"/"!==r?a.default.settings.emoji.suggest&&(o=o.replace(/^\s*/,""),e.match(/^\s*:(.+):\s*$/)||e.match(/:[;!@#$%^&*()-=|]/)||!o||(n=this.emojiHelper,this.emojiHelper.checkQuery(o,r))):this.commandsHelper.checkQuery(o,this.chat.peerId)&&(n=this.commandsHelper)}n=this.checkInlineAutocomplete(e,n),this.autocompleteHelperController.hideOtherHelpers(n)}checkInlineAutocomplete(e,t){let s=!1;if(!t){const i=e.match(/^@([a-zA-Z\\d_]{3,32})\s/);if(i){const n=i[1],a=e.slice(i[0].length);s=i[0].length===e.length,t=this.inlineHelper,this.btnPreloader?(0,Jt.Z)(this.btnPreloader,"show",!0,400):(this.btnPreloader=N("none btn-preloader float show disable-hover",{noRipple:!0}),(0,J.y7)(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})=>{s&&e.bot_inline_placeholder&&(this.messageInput.dataset.inlinePlaceholder=e.bot_inline_placeholder),t.then((()=>{(0,Jt.Z)(this.btnPreloader,"show",!1,400)}))})).catch(_e.Z)}}return s||delete this.messageInput.dataset.inlinePlaceholder,t!==this.inlineHelper&&this.btnPreloader&&(0,Jt.Z)(this.btnPreloader,"show",!1,400),t}setRecording(e){this.recording!==e&&((0,Jt.Z)(this.chatInput,"is-recording",e,200),this.recording=e,this.updateSendBtn())}changeForwardRecipient(){if(this.helperWaitingForward)return;this.helperWaitingForward=!0;const e=this.helperFunc;this.clearHelper(),this.updateSendBtn();let t=!1;new Hs((0,pe.Z)(this.forwarding),(()=>{t=!0})).addEventListener("close",(()=>{this.helperWaitingForward=!1,t||e()}))}clearInput(e=!0,t=!0,s=""){if(document.activeElement===this.messageInput&&ne.IS_MOBILE_SAFARI){const e=document.createElement("input");document.body.append(e),(0,To.Z)(e),this.messageInputField.setValueSilently(s),(0,To.Z)(this.messageInput),e.remove()}else this.messageInputField.setValueSilently(s);ce.IS_TOUCH_SUPPORTED||(this.canRedoFromHTML="",this.undoHistory.length=0,this.executedHistory.length=0,this.canUndoFromHTML="");let i=!1;e&&(i=this.setDraft(void 0,!1)),!i&&t&&this.onMessageInput()}isInputEmpty(){return(0,so.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.appMessagesManager.readAllHistory(this.chat.peerId,this.chat.threadId,!0),this.scheduleDate=void 0,this.sendSilent=void 0;const s=this.messageInputField.value;Q.Z.parseEntities(s).filter((e=>"messageEntityEmoji"===e._)).forEach((e=>{const t=(0,te.zu)(e.unicode);this.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:s}=this;if("scheduled"===s.type&&!e&&!t)return void this.scheduleSending();const{peerId:i}=s,{noWebPage:n}=this,a=this.chat.getMessageSendingParams(),{value:o,entities:r}=(0,to.Z)(this.messageInputField.input);if(t){const e=this.editMessage;if(!o.trim()&&!e.media)return void new zs(i,[t],s.type);this.appMessagesManager.editMessage(e,o,{entities:r,noWebPage:n}),this.onMessageSent()}else o.trim()&&(this.appMessagesManager.sendText(i,o,Object.assign(Object.assign({entities:r},a),{noWebPage:n,webPage:this.getWebPagePromise?void 0:this.willSendWebPage,clearDraft:!0})),this.onMessageSent(!1,!1));if(this.forwarding){const e=(0,pe.Z)(this.forwarding);setTimeout((()=>{for(const t in e)this.appMessagesManager.forwardMessages(i,t.toPeerId(),e[t],Object.assign(Object.assign({},a),{dropAuthor:this.forwardElements&&this.forwardElements.hideSender.checkboxField.checked,dropCaptions:this.isDroppingCaptions()}));o||this.onMessageSent()}),0)}}sendMessageWithDocument(e,t=!1,s=!1){var i;const n="sticker"===(e=this.appDocsManager.getDoc(e)).type?"send_stickers":"gif"===e.type?"send_gifs":"send_media";return this.chat.peerId.isAnyChat()&&!this.chat.canSend(n)?(rt(Fo),!1):"scheduled"!==this.chat.type||t?!!e&&(this.appMessagesManager.sendFile(this.chat.peerId,e,Object.assign(Object.assign({},this.chat.getMessageSendingParams()),{isMedia:!0,clearDraft:s||void 0})),this.onMessageSent(s,!0),"sticker"===e.type&&(null===(i=Ca.stickersTab)||void 0===i||i.pushRecentSticker(e)),!0):(this.scheduleSending((()=>this.sendMessageWithDocument(e,!0,s))),!1)}canToggleHideAuthor(){const{forwardElements:e}=this;if(!e)return!1;const t=e.hideCaption.checkboxField;return!t.checked||(0,ft.Z)(t.label,"FORM").classList.contains("hide")}isDroppingCaptions(){return!this.canToggleHideAuthor()}initMessageEditing(e){const t=this.chat.getMessage(e);let s=Q.Z.wrapDraftText(t.message,{entities:t.totalEntities});const i=()=>{const n=this.appMessagesManager.wrapMessageForReply(t,void 0,[t.mid]);this.setTopInfo("edit",i,(0,k.i18n)("AccDescrEditing"),n,s,t),this.editMsgId=e,this.editMessage=t,s=void 0};i()}initMessagesForward(e){const t=()=>{const s=Object.keys(e).map((e=>e.toPeerId())),i=new Set;let n=0,o=0;s.forEach((t=>{const s=e[t];s.forEach((e=>{var s;const n=this.appMessagesManager.getMessageByPeer(t,e);!(null===(s=n.fwd_from)||void 0===s?void 0:s.from_name)||n.fromId||n.fwdFromId?i.add("P"+n.fromId):i.add("N"+n.fwd_from.from_name),n.media&&n.message&&++o})),n+=s.length}));const r=i.size>2,l=[...i].map((e=>{const t=e[0];if(e=e.slice(1),"P"===t){const t=e.toPeerId();return t===a.default.myId?(0,k.i18n)("Chat.Accessory.Forward.You"):new St.Z({peerId:t,dialog:!1,onlyFirstName:r}).element}return r?e.split(" ")[0]:e})),{forwardElements:d}=this;(0,ft.Z)(d.showCaption.checkboxField.label,"FORM").classList.toggle("hide",!o);const c=d.hideCaption.checkboxField.checked;o&&c?d.hideSender.checkboxField.setValueSilently(!0):void 0!==this.forwardWasDroppingAuthor&&(this.forwardWasDroppingAuthor?d.hideSender:d.showSender).checkboxField.setValueSilently(!0);const h=d.showSender.checkboxField.checked?"Chat.Accessory.Forward":"Chat.Accessory.Hidden",p=(0,k.i18n)(h,[n]),u=document.createDocumentFragment();let g,m;if(l.length<3?u.append(...(0,k.join)(l,!1)):u.append(l[0],(0,k.i18n)("AndOther",[l.length-1])),1===s.length){const t=s[0],i=e[t];if(g=this.appMessagesManager.getMessageByPeer(t,i[0]),m=!!g.grouped_id,m){const e=this.appMessagesManager.getMidsByMessage(g);(e.length!==n||e.find((e=>!i.includes(e))))&&(m=!1)}}const v=document.createDocumentFragment();if(m||1===n){const t=e[s[0]],i=this.appMessagesManager.wrapMessageForReply(g,void 0,t);v.append(u,": ",i)}else v.append((0,k.i18n)("Chat.Accessory.Forward.From"),": ",u);let f=this.setTopInfo("forward",t,p,v);d.modifyArgs.forEach(((e,t)=>{const i=e.textElement,n=k.default.weakMap.get(i);n.args=[t<2?s.length:o],n.update()})),this.forwardHover&&this.forwardHover.attachButtonListener(f,this.listenerSetter),this.forwarding=e};t()}initMessageReply(e){if(this.replyToMsgId===e)return;let t=this.chat.getMessage(e);const s=()=>{let i;"messageEmpty"===t._?(i=(0,k.i18n)("Loading"),this.chat.appMessagesManager.wrapSingleMessage(this.chat.peerId,e).then((i=>{this.replyToMsgId===e&&(t=i,"messageEmpty"===t._?this.clearHelper("reply"):s())}))):i=new St.Z({peerId:t.fromId,dialog:!1}).element,this.setTopInfo("reply",s,i,t&&t.message,void 0,t),this.replyToMsgId=e};s()}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")&&(F.Z.removeByType("input-helper"),this.chat.container.classList.remove("is-helper-active"),this.t())}t(){const e="is-toggling-helper";(0,Jt.Z)(this.chat.container,e,!0,150,(()=>{this.chat.container.classList.remove(e)}))}setInputValue(e,t=!0,s=!0){e||(e=""),t?this.clearInput(!1,!1,e):this.messageInputField.setValueSilently(e),(0,De.T2)((()=>{s&&(0,no.Z)(this.messageInput),this.onMessageInput(),this.messageInput.scrollTop=this.messageInput.scrollHeight}))}setTopInfo(e,t,s="",i="",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=N(("webpage"===e?"link":e)+" active reply-icon",{noRipple:!0}));const d=Ps(s,i,a);return l?r.replaceWith(d):o.insertBefore(d,o.lastElementChild),"webpage"===e&&(d.style.cursor="default"),this.chat.container.classList.contains("is-helper-active")||(this.chat.container.classList.add("is-helper-active"),this.t()),ne.IS_MOBILE||F.Z.pushItem({type:"input-helper",onPop:()=>{this.onHelperCancel()}}),void 0!==n&&this.setInputValue(n),setTimeout((()=>{this.updateSendBtn()}),0),d}}Ro.AUTO_COMPLETE_REG_EXP=/(\s|^)((?:(?:@|^\/)\S*)|(?::|^[^:@\/])(?!.*[:@\/]).*)$/;const Bo="pinned-container";class Uo{constructor(e){this.floating=!1,(0,w.Z)(this,e);const{divAndCaption:t,className:s}=this;t.container.classList.add(Bo,"hide"),t.title.classList.add(Bo+"-title"),t.subtitle.classList.add(Bo+"-subtitle"),t.content.classList.add(Bo+"-content"),this.btnClose=document.createElement("button"),this.btnClose.classList.add(Bo+"-close",`pinned-${s}-close`,"btn-icon","tgico-close"),this.wrapper=document.createElement("div"),this.wrapper.classList.add(Bo+"-wrapper"),(0,ee.ripple)(this.wrapper),this.wrapperUtils=document.createElement("div"),this.wrapperUtils.classList.add(Bo+"-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,l.fc)(e,(e=>{(0,d.d)(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 s=(this.floating||v.ZP.isMobile)&&!e;this.divAndCaption.container.classList.toggle("is-floating",s),this.divAndCaption.container.classList.toggle("hide",e),this.topbar.container.classList.toggle("is-pinned-floating",s),this.topbar.container.classList.toggle(`is-pinned-${this.className}-shown`,!e),this.topbar.setFloating(),this.topbar.setUtilsWidth()}fill(e,t,s){this.divAndCaption.container.dataset.peerId=""+s.peerId,this.divAndCaption.container.dataset.mid=""+s.mid,this.divAndCaption.fill(e,t,s),this.topbar.setUtilsWidth()}}class No extends Uo{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"audio",divAndCaption:new Ve("pinned-audio",((e,t)=>{(0,T.Z)(this.divAndCaption.title,e),(0,T.Z)(this.divAndCaption.subtitle,t)})),onClose:()=>{ve.stop()},floating:!0}),this.topbar=e,this.chat=t,this.appMessagesManager=s,this.onPlaybackRateChange=e=>{this.fasterEl.classList.toggle("active",e>1)},this.onPause=()=>{this.toggleEl.classList.remove("flip-icon")},this.onStop=()=>{this.toggle(!0)},this.onMediaPlay=({doc:e,message:t,media:s})=>{let i,n;"voice"===e.type||"round"===e.type?(i=new St.Z({peerId:t.fromId}).element,n=(0,ie.OD)(t.date),this.fasterEl.classList.remove("hide")):(i=e.audioTitle||e.fileName,n=e.audioPerformer||(0,k.i18n)("AudioUnknownArtist"),this.fasterEl.classList.add("hide")),this.progressLine.setMedia(s),this.fill(i,n,t),this.toggleEl.classList.toggle("flip-icon",!s.paused),this.toggle(!1)},this.divAndCaption.border.remove();const i=N("fast_rewind active",{noRipple:!0}),n=N("fast_forward active",{noRipple:!0}),o=(e,t)=>{(0,l.fc)(e,(e=>{(0,d.d)(e),t()}),{listenerSetter:this.topbar.listenerSetter})};o(i,(()=>{ve.previous()})),o(n,(()=>{ve.next()})),this.toggleEl=N("",{noRipple:!0}),this.toggleEl.classList.add("active","pinned-audio-ico","tgico"),o(this.toggleEl,(()=>{ve.toggle()})),this.wrapper.prepend(this.wrapper.firstElementChild,i,this.toggleEl,n),this.volumeSelector=new ke(this.listenerSetter,!0);const r=document.createElement("div");r.classList.add("progress-line-container"),r.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(r);const h=this.fasterEl=N("playback_2x",{noRipple:!0});o(h,(()=>{ve.playbackRate=h.classList.contains("active")?1:1.75})),this.wrapperUtils.prepend(this.volumeSelector.btn,h);const p=document.createElement("div");p.classList.add("pinned-audio-progress-wrapper"),this.progressLine=new Te(void 0,void 0,!0,!0),this.progressLine.container.classList.add("pinned-audio-progress"),p.append(this.progressLine.container),this.wrapper.insertBefore(p,this.wrapperUtils),this.topbar.listenerSetter.add(a.default)("media_play",this.onMediaPlay),this.topbar.listenerSetter.add(a.default)("media_pause",this.onPause),this.topbar.listenerSetter.add(a.default)("media_stop",this.onStop),this.topbar.listenerSetter.add(a.default)("media_playback_params",(({playbackRate:e})=>{this.onPlaybackRateChange(e)}));const u=ve.getPlayingDetails();u&&(this.onMediaPlay(u),this.onPlaybackRateChange(ve.playbackRate))}destroy(){this.progressLine&&this.progressLine.removeListeners()}}var Oo;!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"}(Oo||(Oo={}));const Ho="pinned-message-border";class zo{constructor(){this.drawRect=(e,t,s,i,n)=>`M${e},${t+n}a${n},${n},0,0,1,${s},0v${i-2*n}a${n},${n},0,0,1,${-s},0Z`,this.getClipPath=(e,t,s)=>{let i="";if(2===s)i=this.drawRect(0,0,2,t,1)+this.drawRect(0,t+2,2,t,1);else for(let e=0;e<s;++e)i+=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",i),this.clipPath},this.getBarHeight=(e,t)=>{let s;return e<=1?s=Oo.ONE:2===e?s=Oo.TWO:3===e?s=Oo.THREE:4===e?s=Oo.FOUR:e>3&&(s=Oo.MORE),s},this.getMarkHeight=(e,t)=>{let s;return e<=1?s=Oo.ONE:2===e?s=Oo.TWO:3===e?s=Oo.THREE:4===e?s=Oo.FOUR:e>3&&(s=Oo.MORE),s},this.getMarkTranslateY=(e,t,s)=>1===s?0:2===s?e?t+1:0:3===s?e?1===e?t+1:2*t+2+1:0:(t+1)*e,this.getTrackTranslateY=(e,t,s,i)=>t<=4||e<=1?0:e>=t-2?i-Oo.ONE-s:(e-2)*s+1*e,this.getTrackHeight=(e,t)=>e<=3?Oo.ONE:t*e+1*(e-1)}render(e,t){if(this.border||(this.border=document.createElement("div"),this.border.classList.add(Ho),this.wrapper=document.createElement("div"),this.border.append(this.wrapper)),1===e)return this.count!==e&&(this.wrapper.className=Ho+"-wrapper-1",this.border.classList.remove(Ho+"-mask"),this.wrapper.innerHTML=this.wrapper.style.cssText=""),this.border;const s=this.getBarHeight(e,t),i=this.getMarkHeight(e,t),n=this.getTrackHeight(e,s),a=`clipPath_${e}`,o=this.getClipPath(a,s,e),r=this.getMarkTranslateY(t,s,e),l=this.getTrackTranslateY(t,e,s,n);return this.border.classList.toggle(Ho+"-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=Ho+"-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(Ho+"-mark")),this.svg.parentElement||this.wrapper.append(this.svg,this.mark),this.mark.style.cssText=`height: ${i}px; transform: translateY(${r}px);`,this.count=e,this.index=t,this.border}}var Vo=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class jo{constructor(){this.rows={},this.container=document.createElement("div"),this.container.className=jo.BASE_CLASS}getRow(e,t=!1){if(this.rows[e])return this.rows[e].element;const s=document.createElement("div"),i=!Object.keys(this.rows).length&&!t;return s.className=jo.BASE_CLASS+"-row"+(i?"":" is-hiding hide"),this.rows[e]={element:s,new:!0},this.container.append(s),s}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)}),jo.DURATION)}setNewRow(e,t=!1){const s=this.rows[e];s.new&&(t?(s.element.classList.remove("hide"),s.element.offsetLeft):s.element.classList.remove("is-hiding","hide"),delete s.new),this.clearRows(e)}animate(e,t,s=e>t,i=!1){if(e===t)return this.setNewRow(e);const n=this.rows[e],a=this.rows[t];if(!a&&!i)return this.setNewRow(e);const o=["from-top","from-bottom"];s||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)}}jo.DURATION=200,jo.BASE_CLASS="animated-super";class Go{constructor(e=!1){this.reverse=e,this.decimals=[],this.previousNumber=0,this.container=document.createElement("div"),this.container.className=Go.BASE_CLASS}getDecimal(e){if(this.decimals[e])return this.decimals[e];const t=document.createElement("div");t.className=Go.BASE_CLASS+"-decimal";const s=document.createElement("div");s.className=Go.BASE_CLASS+"-decimal-placeholder";const i=new jo;return i.container.className=Go.BASE_CLASS+"-decimal-wrapper",t.append(s,i.container),this.container.append(t),this.decimals[e]={container:t,placeholder:s,animatedSuper:i}}clear(e){this.clearTimeout&&clearTimeout(this.clearTimeout);const t=(""+e).length;t>=this.decimals.length||(this.clearTimeout=window.setTimeout((()=>{this.decimals.splice(t,this.decimals.length-t).forEach((e=>{e.container.remove()}))}),jo.DURATION))}hideLeft(e){const t=(""+e).length;this.decimals.slice(t).forEach((t=>{const s=+t.placeholder.innerText||0;t.animatedSuper.getRow(Go.EMPTY_INDEX,!0),t.animatedSuper.animate(Go.EMPTY_INDEX,s,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(((s,i)=>{var n;const a=this.getDecimal(i),o=a.animatedSuper.getRow(s,!0),r=null!==(n=t[i])&&void 0!==n?n:Go.EMPTY_INDEX;o.innerText=a.placeholder.innerText=""+s,a.animatedSuper.animate(s,r,this.reverse?e<this.previousNumber:e>this.previousNumber,!0)})),this.hideLeft(e),this.previousNumber=e}}Go.EMPTY_INDEX=-1,Go.BASE_CLASS="animated-counter";class Ko{constructor(e,t,s,i){this.topbar=e,this.chat=t,this.appMessagesManager=s,this.appPeersManager=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.isStatic=!1,this.debug=!1,this.listenerSetter=new B.Z;const n=new Ke("pinned-message");this.pinnedMessageContainer=new Uo({topbar:e,chat:t,listenerSetter:this.listenerSetter,className:"message",divAndCaption:n,onClose:()=>Vo(this,void 0,void 0,(function*(){return i.canPinMessage(this.topbar.peerId)?new Oa(this.topbar.peerId,this.pinnedMid,!0):new Oa(this.topbar.peerId,0,!0),!1}))}),this.pinnedMessageBorder=new zo,n.border.replaceWith(this.pinnedMessageBorder.render(1,0)),this.animatedSubtitle=new jo,n.subtitle.append(this.animatedSubtitle.container),this.animatedMedia=new jo,this.animatedMedia.container.classList.add("pinned-message-media-container"),n.content.prepend(this.animatedMedia.container),this.animatedCounter=new Go(!0),n.title.append((0,k.i18n)("PinnedMessage")," ",this.animatedCounter.container);const o=this.pinnedMessageContainer.btnClose.cloneNode(!0);this.pinnedMessageContainer.attachOnCloseEvent(o),n.container.prepend(o),this.btnOpen=N("pinlist pinned-container-close pinned-message-pinlist",{noRipple:!0}),this.pinnedMessageContainer.wrapperUtils.prepend(this.btnOpen),(0,l.fc)(this.btnOpen,(e=>{(0,d.d)(e),this.topbar.openPinned(!0)}),{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.default)("peer_pinned_messages",(({peerId:e})=>{e===this.topbar.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(a.default)("peer_pinned_hidden",(({peerId:e})=>{e===this.topbar.peerId&&this.pinnedMessageContainer.toggle(this.hidden=!0)})),this.setPinnedMessage=dt((()=>this._setPinnedMessage()),100,!0,!0),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;let t=this.chat.bubbles.getBubbleByPoint("bottom");if(!t)return;const s=t.dataset.mid;t&&void 0!==s&&this.testMid(+s,e)}testMid(e,t){if(this.isStatic)return;if(this.hidden)return;let s=this.mids.findIndex((t=>t<=e));if(-1===s||this.isNeededMore(s)){if(!(this.loadedTop&&e<this.mids[this.mids.length-1]))return void(this.getCurrentIndexPromise||(this.getCurrentIndexPromise=this.getCurrentIndex(e,void 0!==t)));s=this.mids.length-1+this.offsetIndex}else s+=this.offsetIndex;if(this.pinnedIndex!==s){if(this.waitForScrollBottom&&void 0!==t&&(0===this.pinnedIndex||this.pinnedIndex>s))return;this.pinnedIndex=s,this.pinnedMid=this.mids.find((t=>t<=e))||this.mids[this.mids.length-1],this.setPinnedMessage()}}isNeededMore(e){return this.count>Ko.LOAD_COUNT&&(!this.loadedBottom&&e<=Ko.LOAD_OFFSET||!this.loadedTop&&this.count-1-e<=Ko.LOAD_OFFSET)}getCurrentIndex(e,t=!0){return Vo(this,void 0,void 0,(function*(){if(!this.loading){this.loading=!0;try{let s=!1;const i=[this.appMessagesManager.getSearch({peerId:this.topbar.peerId,inputFilter:{_:"inputMessagesFilterPinned"},maxId:e,limit:Ko.LOAD_COUNT,backLimit:Ko.LOAD_COUNT}).then((e=>(s=!0,e)))];if(!this.pinnedMaxMid){const e=this.appMessagesManager.getPinnedMessage(this.topbar.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()))}));i.push(e)}const n=(yield Promise.all(i))[0];let a=n.history.findIndex((t=>t.mid<=e));-1===a&&(a=n.history.length),this.offsetIndex=n.offset_id_offset?n.offset_id_offset-a:0,this.mids=n.history.map((e=>e.mid)).slice(),this.count=n.count,this.count||this.pinnedMessageContainer.toggle(!0),this.loadedTop=this.offsetIndex+this.mids.length===this.count,this.loadedBottom=!this.offsetIndex,this.debug&&this.chat.log("[PM]: getCurrentIndex result:",e,n,a,this.offsetIndex,this.loadedTop,this.loadedBottom)}catch(e){this.chat.log.error("[PM]: 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 B.Z,function(e,t,s,i){if(ce.IS_TOUCH_SUPPORTED){let t;const n={passive:!0};i.add(e)("touchstart",(s=>{s.touches.length>1?o():(t=s.touches[0].clientY,i.add(e)("touchmove",a,n),i.add(e)("touchend",o,n))}),n);const a=e=>{const i=e.touches[0].clientY,n=i<t;!n||s(),t=i},o=()=>{i.removeManual(e,"touchmove",a,n),i.removeManual(e,"touchend",o,n)}}else i.add(e)("wheel",(e=>{const t=e.deltaY>0;!t||s()}),{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 Vo(this,void 0,void 0,(function*(){this.locked=!0,this.debug&&this.chat.log("[PM]: handleFollowingPinnedMessage");try{this.setScrollDownListener();const e=this.chat.setPeerPromise;e instanceof Promise&&(yield e),yield(0,xs.e9)(),this.getCurrentIndexPromise&&(yield this.getCurrentIndexPromise),this.debug&&this.chat.log("[PM]: handleFollowingPinnedMessage: unlock"),this.locked=!1}catch(e){this.chat.log.error("[PM]: handleFollowingPinnedMessage error:",e),this.locked=!1,this.waitForScrollBottom=!1,this.setCorrectIndex(0)}}))}followPinnedMessage(e){return Vo(this,void 0,void 0,(function*(){const t=this.chat.getMessage(e);t&&!t.deleted&&(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 Vo(this,void 0,void 0,(function*(){const e=this.count;if(e){const t=this.pinnedIndex,s=this.chat.getMessage(this.pinnedMid),i=0===t;this.animatedCounter.container.classList.toggle("is-last",i),i||this.animatedCounter.setCount(e-t),this.pinnedMessageContainer.toggle(!1);const n=t>this.wasPinnedIndex;this.debug&&this.chat.log("[PM]: 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=Ge({title:void 0,titleEl:null,subtitle:s.message,subtitleEl:a,message:s,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=""+s.mid}else this.pinnedMessageContainer.toggle(!0),this.wasPinnedIndex=0;this.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-many",this.count>1)}))}}Ko.LOAD_COUNT=50,Ko.LOAD_OFFSET=5;const Wo=Ma;var qo=s(7298);class $o extends gt{constructor(e){super("popup-mute",{peerId:e,titleLangKey:"Notifications",buttons:[{langKey:"ChatList.Context.Mute",callback:()=>{i.Z.mutePeer(e,-1===s?Re.rU:(0,qo.Z)(!0)+s)}}],body:!0});const t=[{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"}].map((e=>new et({radioField:new at({langKey:e.langKey,name:"mute-time",value:""+e.time})})));let s;const n=tt(t,(e=>{s=+e}));t[t.length-1].radioField.checked=!0;const a=new Mn({noShadow:!0,noDelimiter:!0});a.content.append(n),this.body.append(a.container),this.show()}}class Qo{constructor(e,t,s,i,n,a,o,r,l){this.chat=e,this.appSidebarRight=t,this.appMessagesManager=s,this.appPeersManager=i,this.appChatsManager=n,this.appNotificationsManager=a,this.appProfileManager=o,this.appUsersManager=r,this.appGroupCallsManager=l,this.verifyButtons=e=>{const t=!!e||!(!this.btnMore||!this.btnMore.classList.contains("menu-open"));e&&(0,d.d)(e);const s=e=>{e.forEach((e=>{e.element.classList.toggle("hide",!e.verify())}))};t&&(s(this.menuButtons),this.menuButtons[this.menuButtons.length-1].element.lastChild.replaceWith((0,k.i18n)(this.appPeersManager.getDeleteButtonText(this.peerId)))),s(this.buttonsToVerify)},this.verifyVideoChatButton=e=>{var t;if(!Wo||this.peerId.isUser())return!1;const s=this.appGroupCallsManager.groupCall,i=this.peerId.toChatId();return(null==s?void 0:s.chatId)!==i&&((!e||!(this.peerId.isBroadcast()&&"group"===e||this.peerId.isAnyGroup()&&"broadcast"===e))&&((null===(t=this.appChatsManager.getChatTyped(i).pFlags)||void 0===t?void 0:t.call_active)||this.appChatsManager.hasRights(i,"manage_call")))},this.verifyCallButton=e=>{if(!Ea||!this.peerId.isUser())return!1;const t=this.peerId.toUserId(),s=this.appProfileManager.getCachedFullUser(t);return!!s&&!!("voice"===e?s.pFlags.phone_calls_available:s.pFlags.video_calls_available)},this.onJoinGroupCallClick=()=>{this.chat.appImManager.joinGroupCall(this.peerId)},this.onMuteClick=()=>{new $o(this.peerId)},this.onResize=()=>{this.setUtilsWidth(!0),this.setFloating()},this.onChangeScreen=(e,t)=>{this.container.classList.toggle("is-pinned-floating",v.ZP.isMobile),this.pinnedMessage&&this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-floating",t===v._G.mobile),this.onResize()},this.setUtilsWidth=(e=!1)=>{this.setUtilsRAF&&window.cancelAnimationFrame(this.setUtilsRAF),ne.IS_SAFARI&&e&&this.chatUtils.classList.add("hide"),this.setUtilsRAF=window.requestAnimationFrame((()=>{ne.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 s=t.divAndCaption.container.classList.contains("is-floating");return this.container.classList.toggle(`is-pinned-${t.className}-floating`,s),e+ +s}),0);this.container.dataset.floating=""+e},this.setPeerStatus=(e=!1)=>{if(!this.subtitle)return;const t=this.peerId;this.chat.appImManager.setPeerStatus(this.peerId,this.subtitle,e,!1,(()=>t===this.peerId))},this.listenerSetter=new B.Z,this.menuButtons=[],this.buttonsToVerify=[]}construct(){this.container=document.createElement("div"),this.container.classList.add("sidebar-header","topbar"),this.container.dataset.floating="0",this.btnBack=N("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 s=document.createElement("div");s.classList.add("top"),this.title=document.createElement("div"),this.title.classList.add("user-title"),s.append(this.title);const i=document.createElement("div");i.classList.add("bottom"),this.subtitle&&i.append(this.subtitle),t.append(s,i),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 No(this,this.chat,this.appMessagesManager),this.menuButtons.length&&(this.btnMore=Ie({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(v.ZP)("changeScreen",this.onChangeScreen),(0,l.fc)(this.container,(e=>{const t=(0,Me.Z)(e.target,"pinned-container");if((0,Gs.Z)(),t){if((0,d.d)(e),(0,Me.Z)(e.target,"progress-line"))return;const s=+t.dataset.mid;if(t.classList.contains("pinned-message"))this.pinnedMessage.followPinnedMessage(s);else{const e=t.dataset.peerId.toPeerId(),i=ve.getSearchContext();this.chat.appImManager.setInnerPeer({peerId:e,lastMsgId:s,type:i.isScheduled?"scheduled":i.threadId?"discussion":void 0,threadId:i.threadId})}}else v.ZP.activeScreen===v._G.medium&&document.body.classList.contains(Ln)?n():(0,ft.Z)(e.target,"AVATAR-ELEMENT")?this.appSidebarRight.toggleSidebar(!document.body.classList.contains($t)):this.appSidebarRight.toggleSidebar(!0)}),{listenerSetter:this.listenerSetter});const n=e=>{if(e&&(0,d.d)(e),v.ZP.activeScreen===v._G.medium&&document.body.classList.contains(Ln))this.chat.appImManager.setPeer({peerId:this.peerId});else{const e=0===this.chat.appImManager.chats.indexOf(this.chat);F.Z.back(e?"im":"chat")}};(0,l.fc)(this.btnBack,n,{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:()=>v.ZP.isMobile},{icon:"mute",text:"ChatList.Context.Mute",onClick:this.onMuteClick,verify:()=>"chat"===this.chat.type&&a.default.myId!==this.peerId&&!this.appNotificationsManager.isPeerLocalMuted(this.peerId,!1)},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:()=>{this.appMessagesManager.togglePeerMute(this.peerId)},verify:()=>"chat"===this.chat.type&&a.default.myId!==this.peerId&&this.appNotificationsManager.isPeerLocalMuted(this.peerId,!1)},{icon:"comments",text:"ViewDiscussion",onClick:()=>{const e=this.chat.bubbles.getMiddleware();Promise.resolve(this.appProfileManager.getChannelFull(this.peerId.toChatId())).then((t=>{e()&&t.linked_chat_id&&this.chat.appImManager.setInnerPeer({peerId:t.linked_chat_id.toPeerId(!0)})}))},verify:()=>{const e=this.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),M.default.getState().then((t=>{if(t.chatContextMenuHintWasShown)return;const s=e.toggleByElement.bind(e);e.toggleByElement=t=>{M.default.pushToState("chatContextMenuHintWasShown",!0),rt((0,k.i18n)("Chat.Menu.Hint")),e.toggleByElement=s,e.toggleByElement(t)}}))},verify:()=>!this.chat.selection.isSelecting&&!!Object.keys(this.chat.bubbles.bubbles).length},{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(Rt)){const e=new Rt(this.appSidebarRight);e.peerId=this.peerId,e.open(),this.appSidebarRight.toggleSidebar(!0)}},verify:()=>this.peerId.isUser()&&!this.appPeersManager.isContact(this.peerId)},{icon:"forward",text:"ShareContact",onClick:()=>{const e=this.peerId;new Et({peerTypes:["dialogs","contacts"],onSelect:t=>new Promise(((s,i)=>{new gt("",{titleLangKey:"SendMessageTitle",descriptionLangKey:"SendContactToGroupText",descriptionLangArgs:[new St.Z({peerId:t,dialog:!0}).element],buttons:[{langKey:"Send",callback:()=>{s(),this.appMessagesManager.sendContact(t,e),this.chat.appImManager.setInnerPeer({peerId:t})}},{langKey:"Cancel",callback:()=>{i()},isCancel:!0}],peerId:t,overlayClosable:!0}).show()})),placeholder:"ShareModal.Search.Placeholder",chatRightsAction:"send_messages",selfPresence:"ChatYourSelf"})},verify:()=>a.default.myId!==this.peerId&&this.peerId.isUser()&&this.appPeersManager.isContact(this.peerId)&&!!this.appUsersManager.getUser(this.peerId.toUserId()).phone},{icon:"lock",text:"BlockUser",onClick:()=>{new gt("",{peerId:this.peerId,titleLangKey:"BlockUser",descriptionLangKey:"AreYouSureBlockContact2",descriptionLangArgs:[new St.Z({peerId:this.peerId}).element],buttons:[{langKey:"BlockUser",isDanger:!0,callback:()=>{this.appUsersManager.toggleBlock(this.peerId,!0).then((e=>{e&&lt({langPackKey:"UserBlocked"})}))}}]}).show()},verify:()=>{var e;if(!this.peerId.isUser())return!1;const t=this.appProfileManager.getCachedFullUser(this.peerId.toUserId());return this.peerId!==a.default.myId&&t&&!(null===(e=t.pFlags)||void 0===e?void 0:e.blocked)}},{icon:"lockoff",text:"Unblock",onClick:()=>{this.appUsersManager.toggleBlock(this.peerId,!1).then((e=>{e&&lt({langPackKey:"UserUnblocked"})}))},verify:()=>{var e;const t=this.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 At(this.peerId)},verify:()=>"chat"===this.chat.type&&!!this.appMessagesManager.getDialogOnly(this.peerId)}],this.btnSearch=N("search"),this.attachClickEvent(this.btnSearch,(e=>{this.chat.initSearch()}),!0)}attachClickEvent(e,t,s){(0,l.fc)(e,(e=>{(0,d.d)(e),!s&&(0,Gs.Z)(),t(e)}),{listenerSetter:this.listenerSetter})}onCallClick(e){this.chat.appImManager.callUser(this.peerId.toUserId(),e)}constructPeerHelpers(){return this.avatarElement=new Yl,this.avatarElement.setAttribute("dialog","1"),this.avatarElement.classList.add("avatar-42","person-avatar"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("info"),this.pinnedMessage=new Ko(this,this.chat,this.appMessagesManager,this.appPeersManager),this.btnJoin=(0,U.Z)("btn-primary btn-color-primary chat-join hide"),this.btnCall=N("phone"),this.btnGroupCall=N("videochat"),this.btnPinned=N("pinlist"),this.btnMute=N("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,(()=>{const e=this.chat.bubbles.getMiddleware();this.btnJoin.setAttribute("disabled","true");const t=this.peerId.toChatId();let s;s=this.appChatsManager.isChannel(t)?this.appChatsManager.joinChannel(t):this.appChatsManager.addChatUser(t,a.default.myId),s.finally((()=>{e()&&this.btnJoin.removeAttribute("disabled")}))})),this.listenerSetter.add(a.default)("chat_update",(e=>{var t;if(this.peerId===e.toPeerId(!0)){const s=this.appChatsManager.getChat(e);this.btnJoin.classList.toggle("hide",!(null===(t=null==s?void 0:s.pFlags)||void 0===t?void 0:t.left)),this.setUtilsWidth(),this.verifyButtons()}})),this.listenerSetter.add(a.default)("dialog_notify_settings",(e=>{e.peerId===this.peerId&&this.setMutedState()})),this.listenerSetter.add(a.default)("peer_typings",(({peerId:e})=>{this.peerId===e&&this.setPeerStatus()})),this.listenerSetter.add(a.default)("user_update",(e=>{this.peerId===e.toPeerId()&&this.setPeerStatus()})),this.listenerSetter.add(a.default)("peer_full_update",(e=>{this.peerId===e&&this.verifyButtons()})),this.pinnedMessage&&this.chat.addEventListener("setPeer",((e,t)=>{const s=this.chat.bubbles.getMiddleware();M.default.getState().then((i=>{s()&&(this.pinnedMessage.hidden=!!i.hiddenPinnedMessages[this.chat.peerId],t?(this.pinnedMessage.unsetScrollDownListener(),this.pinnedMessage.testMid(e,0)):this.pinnedMessage.locked||(this.pinnedMessage.handleFollowingPinnedMessage(),this.pinnedMessage.testMid(e)))}))})),this.setPeerStatusInterval=window.setInterval(this.setPeerStatus,6e4),this}constructPinnedHelpers(){this.listenerSetter.add(a.default)("peer_pinned_messages",(({peerId:e,mids:t})=>{e===this.peerId&&t&&this.setTitle()}))}constructDiscussionHelpers(){this.pinnedMessage=new Ko(this,this.chat,this.appMessagesManager,this.appPeersManager)}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}setPeer(e){this.wasPeerId=this.peerId,this.peerId=e,this.container.style.display=e?"":"none"}finishPeerChange(e,t,s){var i,n;const a=this.peerId;this.avatarElement&&(this.avatarElement.setAttribute("peer",""+a),this.avatarElement.update());const o=this.appPeersManager.isBroadcast(a);if(this.btnMute&&this.btnMute.classList.toggle("hide",!o),this.btnJoin)if(this.appPeersManager.isAnyChat(a)){const e=a.toChatId();(0,T.Z)(this.btnJoin,(0,k.i18n)(this.appChatsManager.isBroadcast(e)?"Chat.Subscribe":"ChannelJoin")),this.btnJoin.classList.toggle("hide",!(null===(n=null===(i=this.appChatsManager.getChat(e))||void 0===i?void 0:i.pFlags)||void 0===n?void 0:n.left))}else this.btnJoin.classList.add("hide");this.setUtilsWidth(),this.verifyButtons();const r=this.chat.bubbles.getMiddleware();if(this.pinnedMessage)if("chat"===this.chat.type){if(void 0!==this.wasPeerId){const e=new Ko(this,this.chat,this.appMessagesManager,this.appPeersManager);this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.replaceWith(e.pinnedMessageContainer.divAndCaption.container),this.pinnedMessage.destroy(),this.pinnedMessage=e}M.default.getState().then((t=>{r()&&(this.pinnedMessage.hidden=!!t.hiddenPinnedMessages[a],e||this.pinnedMessage.setCorrectIndex(0))}))}else"discussion"===this.chat.type&&(this.pinnedMessage.pinnedMid=this.chat.threadId,this.pinnedMessage.count=1,this.pinnedMessage.pinnedIndex=0,this.pinnedMessage._setPinnedMessage());(0,De.T2)((()=>{this.setTitle(),this.setPeerStatus(!0),this.setMutedState()}))}setTitle(e){var t;let s;if("pinned"===this.chat.type?(s=void 0===e?(0,k.i18n)("Loading"):(0,k.i18n)("PinnedMessagesCount",[e]),void 0===e&&this.appMessagesManager.getSearchCounters(this.peerId,[{_:"inputMessagesFilterPinned"}],!1).then((e=>{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)}}))):"scheduled"===this.chat.type?(s=this.peerId===a.default.myId?(0,k.i18n)("Reminders"):(0,k.i18n)("ScheduledMessages"),void 0===e&&this.appMessagesManager.getScheduledMessages(this.peerId).then((e=>{this.setTitle(e.length)}))):"discussion"===this.chat.type?(s=void 0===e?(0,k.i18n)("Loading"):(0,k.i18n)("Chat.Title.Comments",[e]),void 0===e&&Promise.all([this.appMessagesManager.getHistory(this.peerId,0,1,0,this.chat.threadId),Promise.resolve()]).then((()=>{const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId).count;null===e?setTimeout((()=>{this.setTitle()}),30):this.setTitle(e)}))):"chat"===this.chat.type&&(s=new St.Z({peerId:this.peerId,dialog:!0}).element),(0,T.Z)(this.title,s),"chat"===this.chat.type){const e=this.appPeersManager.getPeer(this.peerId);(null===(t=null==e?void 0:e.pFlags)||void 0===t?void 0:t.verified)&&this.title.append(Ot())}}setMutedState(){if(!this.btnMute)return;const e=this.peerId;let t=this.appNotificationsManager.isPeerLocalMuted(e,!1);this.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 Yo extends O{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 Z("Search"),this.title.replaceWith(this.inputSearch.container),this.btnPickDate=N("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 A(e,this.inputSearch,{messages:new x("Chat.Search.PrivateSearch","messages")})}open(e,t,s,i){const n=super.open();return this.peerId?this.appSearch.beginSearch(this.peerId,this.threadId,i):(this.query=i,this.peerId=e,this.threadId=t,this.onDatePick=s,this.btnPickDate.classList.toggle("hide",!this.onDatePick),this.onDatePick&&(0,l.fc)(this.btnPickDate,(()=>{new _n(new Date,this.onDatePick).show()})),i&&this.appSearch.searchInput.inputField.setValueSilently(i),Yt.toggleSidebar(!0)),n}}class Xo{constructor(e,t,s){this.topbar=e,this.chat=t,this.foundCount=0,this.selectedIndex=0,this.onDateClick=e=>{(0,d.d)(e),new _n(new Date,this.chat.bubbles.onDatePick).show()},this.onResultsClick=e=>{const t=(0,ft.Z)(e.target,"LI");t&&this.selectResult(t)},this.onFooterClick=e=>{this.foundCount&&(this.chat.bubbles.bubblesContainer.classList.toggle("search-results-active"),this.results.classList.toggle("active"))},this.onUpClick=e=>{(0,d.d)(e),this.selectResult(this.searchGroup.list.children[this.selectedIndex+1])},this.onDownClick=e=>{(0,d.d)(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,ee.ripple)(this.backBtn);const i=this.listenerSetter=new B.Z,n=(e,t)=>{(0,l.fc)(e,t,{listenerSetter:i})};n(this.backBtn,(()=>{this.destroy()})),this.inputSearch=new Z("Search"),this.results=document.createElement("div"),this.results.classList.add("chat-search-results","chatlist-container"),this.searchGroup=new x(!1,"messages",void 0,"",!1),n(this.searchGroup.list,this.onResultsClick),this.appSearch=new A(this.results,this.inputSearch,{messages:this.searchGroup},(e=>{this.foundCount=e,this.foundCount?this.selectResult(this.searchGroup.list.children[0]):((0,T.Z)(this.foundCountEl,this.inputSearch.value?(0,k.i18n)("NoResult"):""),this.results.classList.remove("active"),this.chat.bubbles.bubblesContainer.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.bubblesContainer.append(this.results),this.footer=document.createElement("div"),this.footer.classList.add("chat-search-footer"),n(this.footer,this.onFooterClick),(0,ee.ripple)(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"),n(this.dateBtn,this.onDateClick),n(this.upBtn,this.onUpClick),n(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(),s&&this.setQuery(s),ne.IS_MOBILE_SAFARI||(this.navigationItem={type:"mobile-search",onPop:()=>{this.destroy()}},F.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.bubblesContainer.classList.remove("search-results-active"),this.chat.search=void 0,F.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(),s=+e.dataset.mid||void 0,i=(0,_s.Z)(e);i===this.foundCount-1?this.upBtn.setAttribute("disabled","true"):this.upBtn.removeAttribute("disabled"),i?this.downBtn.removeAttribute("disabled"):this.downBtn.setAttribute("disabled","true"),this.results.classList.remove("active"),this.chat.bubbles.bubblesContainer.classList.remove("search-results-active");const n=this.chat.setPeer(t,s);this.setPeerPromise=(n instanceof Promise?n:Promise.resolve(n)).then((()=>{this.selectedIndex=i,(0,T.Z)(this.foundCountEl,(0,k.i18n)("Of",[i+1,this.foundCount]));const e=this.searchGroup.list.childElementCount;this.selectedIndex>=e-6&&this.appSearch.searchMore()})).finally((()=>{this.setPeerPromise=null}))}}class Jo{constructor(){this.canvases=new Set}static getInstance(e){let t=this.INSTANCES.find((t=>(0,ue.Z)(t.options,e)));return t||(t=new Jo,t.init(e),this.INSTANCES.push(t)),t}init(e){this.options=e}renderToCanvas(e){return this.createCanvasPattern(e).then((()=>this.fillCanvas(e)))}createCanvasPattern(e){return this.createCanvasPatternPromise?this.createCanvasPatternPromise:this.createCanvasPatternPromise=new Promise((t=>{const s=document.createElement("img");s.crossOrigin="anonymous",(0,rs.cj)(s,this.options.url,!1).then((()=>{let i;if(ne.IS_SAFARI){const e=i=document.createElement("canvas");e.width=s.naturalWidth,e.height=s.naturalHeight,e.getContext("2d").drawImage(s,0,0,e.width,e.height)}else i=s;this.pattern=e.getContext("2d").createPattern(i,"repeat-x"),t()}))}))}exportCanvasPatternToImage(e){return this.exportCanvasPatternToImagePromise?this.exportCanvasPatternToImagePromise:this.exportCanvasPatternToImagePromise=new Promise((t=>{e.toBlob((e=>{const s=this.objectUrl=URL.createObjectURL(e);t(s)}),"image/png")}))}cleanup(e){this.canvases.delete(e),this.canvases.size||((0,z.Z)(Jo.INSTANCES,this),this.objectUrl&&URL.revokeObjectURL(this.objectUrl))}fillCanvas(e){const t=e.getContext("2d");t.fillStyle=this.pattern,t.fillRect(0,0,e.width,e.height)}setCanvasDimensions(e){e.width=this.options.width*window.devicePixelRatio,e.height=this.options.height*window.devicePixelRatio*1.5}createCanvas(){const e=document.createElement("canvas");return this.canvases.add(e),this.setCanvasDimensions(e),e}}Jo.INSTANCES=[];class er extends R.Z{constructor(e,t,s,i,n,a,o,r,l,d,c,h,p,u,g,m,v,f,b,y,w){super(),this.appImManager=e,this.appChatsManager=t,this.appDocsManager=s,this.appInlineBotsManager=i,this.appMessagesManager=n,this.appPeersManager=a,this.appPhotosManager=o,this.appProfileManager=r,this.appStickersManager=l,this.appUsersManager=d,this.appWebPagesManager=c,this.appPollsManager=h,this.apiManager=p,this.appDraftsManager=u,this.serverTimeManager=g,this.storage=m,this.appNotificationsManager=v,this.appEmojiManager=f,this.appMessagesIdsManager=b,this.appGroupCallsManager=y,this.appReactionsManager=w,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,$.kg)("CHAT",$.v9.Log|$.v9.Warn|$.v9.Debug|$.v9.Error),this.peerId=Re.NM,this.container.append(this.backgroundEl),this.appImManager.chatsContainer.append(this.container),this.backgroundTempId=0}setBackground(e,t){const s=a.default.getTheme();let i;if(s.background.color&&!s.background.slug&&!s.background.intensity&&"grabbing"===document.documentElement.style.cursor&&this.gradientRenderer&&!this.patternRenderer)return this.gradientCanvas.dataset.colors=s.background.color,this.gradientRenderer.init(this.gradientCanvas),Promise.resolve();const n=++this.backgroundTempId,o=this.gradientRenderer,r=this.patternRenderer,l=(this.gradientCanvas,this.patternCanvas);this.gradientRenderer=this.patternRenderer=this.gradientCanvas=this.patternCanvas=void 0;const d=s.background.intensity&&s.background.intensity/100,c=!!d&&d<0;let h,p,u,g=null==i?void 0:i.firstElementChild;if(!i)if(i=document.createElement("div"),i.classList.add("chat-background-item"),e)if(d){i.classList.add("is-pattern");const t=this.appImManager.chatsContainer.getBoundingClientRect();h=this.patternRenderer=Jo.getInstance({url:e,width:t.width,height:t.height}),g=this.patternCanvas=h.createCanvas(),g.classList.add("chat-background-item-canvas","chat-background-item-pattern-canvas")}else s.background.slug&&i.classList.add("is-image");else s.background.color&&i.classList.add("is-color");const m=s.background.color;if(m){const{canvas:e,gradientRenderer:t}=Oi.create(m);u=this.gradientRenderer=t,p=this.gradientCanvas=e,p.classList.add("chat-background-item-canvas","chat-background-item-color-canvas"),a.default.settings.animationsEnabled&&u.scrollAnimate(!0)}h&&(c?p:g).style.setProperty("--opacity-max",""+Math.abs(d));const v=new Promise((s=>{const a=()=>{if(this.backgroundTempId!==n)return h&&h.cleanup(g),void(u&&u.cleanup());const e=this.backgroundEl.lastElementChild;if(e===i)return void s();const a=[p,c?void 0:g].filter(Boolean);a.length&&i.append(...a),this.backgroundEl.append(i),(0,Jt.Z)(i,"is-visible",!0,t?0:200,e?()=>{r&&r.cleanup(l),o&&o.cleanup(),e.remove()}:null,2),s()};h?h.renderToCanvas(g).then((()=>{let e;e=c?h.exportCanvasPatternToImage(g).then((e=>{this.backgroundTempId===n&&(p.style.webkitMaskImage=`url(${e})`)})):Promise.resolve(),e.then(a)})):e?(0,rs.ZP)(i,e,a):a()}));return this.setBackgroundPromise=Promise.race([(0,Kn.w)(500),v])}setType(e){this.type=e,"scheduled"===this.type&&(this.getMessagesStorage=()=>this.appMessagesManager.getScheduledMessagesStorage(this.peerId))}init(){this.topbar=new Qo(this,Yt,this.appMessagesManager,this.appPeersManager,this.appChatsManager,this.appNotificationsManager,this.appProfileManager,this.appUsersManager,this.appGroupCallsManager),this.bubbles=new Ua(this,this.appMessagesManager,this.appStickersManager,this.appUsersManager,this.appInlineBotsManager,this.appPhotosManager,this.appPeersManager,this.appProfileManager,this.appDraftsManager,this.appMessagesIdsManager,this.appChatsManager,this.appReactionsManager),this.input=new Ro(this,this.appMessagesManager,this.appMessagesIdsManager,this.appDocsManager,this.appChatsManager,this.appPeersManager,this.appWebPagesManager,this.appImManager,this.appDraftsManager,this.serverTimeManager,this.appNotificationsManager,this.appEmojiManager,this.appUsersManager,this.appInlineBotsManager,this.appProfileManager),this.selection=new Ys(this,this.bubbles,this.input,this.appMessagesManager),this.contextMenu=new Qa(this.bubbles.bubblesContainer,this,this.appMessagesManager,this.appPeersManager,this.appPollsManager,this.appDocsManager,this.appMessagesIdsManager,this.appReactionsManager),"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||ce.IS_TOUCH_SUPPORTED||this.bubbles.setReactionsHoverListeners(),this.container.classList.add("type-"+this.type),this.container.append(this.topbar.container,this.bubbles.bubblesContainer,this.input.chatInput),this.bubbles.listenerSetter.add(a.default)("dialog_migrate",(({migrateFrom:e,migrateTo:t})=>{this.peerId===e&&this.setPeer(t)})),this.bubbles.listenerSetter.add(a.default)("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.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.selection.cleanup()}setPeer(e,t,s){e?this.inited||(this.init&&(this.init(),this.init=null),this.inited=!0):this.inited=void 0;const i=this.peerId===e;if(i){if(this.setPeerPromise)return}else a.default.dispatchEvent("peer_changing",this),this.peerId=e||Re.NM;if(!e)return Yt.toggleSidebar(!1),this.cleanup(!0),this.topbar.setPeer(e),this.bubbles.setPeer(e),void a.default.dispatchEvent("peer_changed",e);if(!i){const t=Yt.getTab(Yo);t&&t.close(),this.noForwards=this.appPeersManager.noForwards(e),this.isRestricted=this.appPeersManager.isRestricted(e),this.container.classList.toggle("no-forwards",this.noForwards),Yt.sharedMediaTab.setPeer(e,this.threadId),this.input.clearHelper(),this.selection.cleanup(),this.setAutoDownloadMedia()}this.peerChanged=i,void 0===s&&this.isStartButtonNeeded()&&(s=Re.gZ);const n=this.bubbles.setPeer(e,t,s);if(!n)return;const{promise:o}=n,r=this.setPeerPromise=o.finally((()=>{this.setPeerPromise===r&&(this.setPeerPromise=null)}));return i||(Yt.sharedMediaTab.setLoadMutex(this.setPeerPromise),Yt.sharedMediaTab.loadSidebarMedia(!0)),n}setAutoDownloadMedia(){this.autoDownload=function(e){let t,s=0,i=0,n=0;const o=a.default.settings;return!o.autoDownloadNew.pFlags.disabled&&e&&(t=e.isUser()?e.isContact()?"contacts":"private":e.isBroadcast()?"channels":"groups",o.autoDownload.photo[t]&&(s=o.autoDownloadNew.photo_size_max),o.autoDownload.video[t]&&(i=o.autoDownloadNew.video_size_max),o.autoDownload.file[t]&&(n=o.autoDownloadNew.file_size_max)),{photo:s,video:i,file:n}}(this.peerId)}setMessageId(e){return this.setPeer(this.peerId,e)}finishPeerChange(e,t,s,i){if(this.peerChanged)return;let n=this.peerId;this.peerChanged=!0,this.cleanup(!1),this.topbar.setPeer(n),this.topbar.finishPeerChange(e,t,s),this.bubbles.finishPeerChange(),this.input.finishPeerChange(i),Yt.sharedMediaTab.fillProfileElements(),this.log.setPrefix("CHAT-"+n+"-"+this.type),a.default.dispatchEvent("peer_changed",n),this.wasAlreadyUsed=!0}getMessagesStorage(){return this.appMessagesManager.getMessagesStorage(this.peerId)}getMessage(e){return this.appMessagesManager.getMessageFromStorage(this.getMessagesStorage(),e)}getMidsByMid(e){return this.appMessagesManager.getMidsByMessage(this.getMessage(e))}isAnyGroup(){return this.peerId===a.default.myId||this.peerId===Re.hj||this.appPeersManager.isAnyGroup(this.peerId)}initSearch(e){if(this.peerId)if(v.ZP.isMobile)this.search?this.search.setQuery(e):this.search=new Xo(this.topbar,this,e);else{let t=Yt.getTab(Yo);t||(t=new Yo(Yt)),t.open(this.peerId,this.threadId,this.bubbles.onDatePick,e)}}canSend(e){return this.appMessagesManager.canSendToPeer(this.peerId,this.threadId,e)}isStartButtonNeeded(){return this.appPeersManager.isBot(this.peerId)&&!this.appMessagesManager.getDialogOnly(this.peerId)&&!this.appMessagesManager.getHistoryStorage(this.peerId).history.length}getMessageSendingParams(){return{threadId:this.threadId,replyToMsgId:this.input.replyToMsgId,scheduleDate:this.input.scheduleDate,sendSilent:this.input.sendSilent,sendAsPeerId:this.input.sendAsPeerId}}}var tr=s(646);class sr{constructor(e){this.appImManager=e,this.buttons={},this.addedListener=!1,this.waitingForMouseUp=!1,this.mouseUpCounter=0,this.onMouseUpSingle=e=>{if(this.waitingForMouseUp=!1,ce.IS_TOUCH_SUPPORTED){if(e&&(0,d.d)(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 s=N(t,{noRipple:!0});e.append(this.buttons[t]=s),"link"!==t?s.addEventListener("mousedown",(e=>{(0,d.d)(e),this.appImManager.chat.input.applyMarkdown(t),this.cancelClosening()})):(0,l.fc)(s,(e=>{(0,d.d)(e),this.showLinkEditor(),this.cancelClosening()}))})),this.linkBackButton=N("left",{noRipple:!0}),this.linkInput=document.createElement("input"),(0,k._i18n)(this.linkInput,"MarkupTooltip.LinkPlaceholder",void 0,"placeholder"),this.linkInput.classList.add("input-clear"),this.linkInput.addEventListener("keydown",(e=>{const t=!this.linkInput.value.length||!!Q.Z.matchUrl(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,d.d)(e),this.container.classList.remove("is-link"),this.resetSelection(),this.setTooltipPosition(),this.cancelClosening()})),this.linkApplyButton=N("check markup-tooltip-link-apply",{noRipple:!0}),this.linkApplyButton.addEventListener("mousedown",(e=>{this.applyLink(e)}));const s=document.createElement("div");s.classList.add("markup-tooltip-link-apply-container");const i=document.createElement("span"),n=document.createElement("span"),a=document.createElement("span");i.classList.add("markup-tooltip-delimiter"),n.classList.add("markup-tooltip-delimiter"),a.classList.add("markup-tooltip-delimiter"),e.insertBefore(i,this.buttons.link),s.append(a,this.linkApplyButton),t.append(this.linkBackButton,n,this.linkInput,s),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,d.d)(e),this.resetSelection();let t=this.linkInput.value;t&&!Q.Z.matchUrlProtocol(t)&&(t="https://"+t),this.appImManager.chat.input.applyMarkdown("link",t),setTimeout((()=>{this.hide()}),0)}isLinkValid(){return!this.linkInput.value.length||!!Q.Z.matchUrl(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,F.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 s=0;s<t.rangeCount;++s){const i=t.getRangeAt(s);let{startContainer:n,endContainer:a}=i;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)))],s=new Set;return t.forEach((e=>{for(const t in wo.o){const i=wo.o[t];e.closest(i.match+", [contenteditable]")!==this.appImManager.chat.input.messageInput&&s.add(this.buttons[t])}})),[...s]}setActiveMarkupButton(){const e=this.getActiveMarkupButton();for(const t in this.buttons){const s=this.buttons[t];s.classList.toggle("active",e.includes(s))}}setTooltipPosition(e=!1){const t=document.getSelection().getRangeAt(0),s=document.body.getBoundingClientRect(),i=t.getBoundingClientRect(),n=this.appImManager.chat.input.rowsWrapper.getBoundingClientRect();this.container.style.maxWidth=n.width+"px";const a=Pa(void 0,this.appImManager.chat.input.messageInput,!1,i).rect.top+-1*s.top,o=(this.container.classList.contains("is-link")?this.wrapper.lastElementChild:this.wrapper.firstElementChild).getBoundingClientRect(),r=a-o.height-8,l=n.left,d=n.left+n.width-Math.min(n.width,o.width);let c;if(e){const e=this.container.getBoundingClientRect();c=(0,ye.Z)(e.left,l,d)}else{const e=i.left+(i.width-o.width)/2;c=(0,ye.Z)(e,l,d)}this.container.style.transform=`translate3d(${c}px, ${r}px, 0)`}show(){if(this.init&&(this.init(),this.init=null),Ha())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"),ne.IS_MOBILE||F.Z.pushItem({type:"markup",onPop:()=>{this.hide()}})}setMouseUpEvent(){this.waitingForMouseUp||(this.waitingForMouseUp=!0,document.addEventListener("mouseup",this.onMouseUpSingle,{once:!0}))}cancelClosening(){ce.IS_TOUCH_SUPPORTED&&!ne.IS_APPLE&&(document.removeEventListener("mouseup",this.onMouseUpSingle),document.addEventListener("mouseup",(e=>{(0,d.d)(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 s=document.getSelection();if(Ha(s))this.hide();else if(ce.IS_TOUCH_SUPPORTED)if(ne.IS_APPLE)this.show(),this.setTooltipPosition();else{if(2===this.mouseUpCounter)return void(this.mouseUpCounter=0);this.savedRange=s.getRangeAt(0),this.setMouseUpEvent()}else this.container&&this.container.classList.contains("is-visible")?this.setTooltipPosition():t.matches(":active")?this.setMouseUpEvent():this.show()})))}}function ir(e,t,s,i,n,a,o){return[e,",",t," ",s," ",i,",",n," ",a,",",o].join("")}function nr(e,t,s,i,n,a,o,r){const l=[];return l.push("M"+(e+s/2)+","+t),l.push("H"+(e+s-a)),a>0&&l.push("A"+ir(a,a,0,0,1,e+s,t+a)),l.push("V"+(t+i-o)),o>0&&l.push("A"+ir(o,o,0,0,1,e+s-o,t+i)),l.push("H"+(e+r)),r>0&&l.push("A"+ir(r,r,0,0,1,e+0,t+i-r)),l.push("V"+(t+n)),n>0&&l.push("A"+ir(n,n,0,0,1,e+n,t+0)),l.push("Z"),l.join(" ")}re.GO.generatePathData=nr;class ar{constructor(e,t){let s;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&&(s=document.createElement("div"),s.classList.add("drop-icon","tgico-"+t.icon));const i=document.createElement("div");let n;i.classList.add("drop-header"),i.append((0,k.i18n)(t.header,t.headerArgs)),t.subtitle&&(n=document.createElement("div"),n.classList.add("drop-subtitle"),n.append((0,k.i18n)(t.subtitle))),this.svg.append(this.path),this.outlineWrapper.append(this.svg),this.container.append(...[this.outlineWrapper,s,i,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,s=nr(5,5,e.width-t,e.height-t,t,t,t,t);this.path.setAttributeNS(null,"d",s)}}function or(e){e.forEach((e=>e.classList.add("no-transition"))),(0,De.d1)().then((()=>{e.forEach((e=>e.classList.remove("no-transition")))}))}var rr=s(490),lr=s(5228),dr=s(2459),cr=s(2207);class hr{constructor(e){this.maxRadius=10,this.minRadius=0,this.N=e,this.radius=new Array(e+1),this.radiusNext=new Array(e+1),this.progress=new Array(e+1),this.speed=new Array(e+1);for(let t=0;t<=e;t++)this.generateBlob(this.radius,t),this.generateBlob(this.radiusNext,t),this.progress[t]=0}generateBlob(e,t){const{maxRadius:s,minRadius:i,speed:n}=this,a=s-i;e[t]=i+Math.random()*a,n[t]=.017+.003*Math.random()}generateNextBlob(){const{radius:e,radiusNext:t,progress:s,N:i}=this;for(let n=0;n<i;n++)this.generateBlob(e,n),this.generateBlob(t,n),s[n]=0}update(e,t){const{N:s,progress:i,speed:n,radius:a,radiusNext:o}=this;for(let r=0;r<=s;r++)i[r]+=.8*n[r]+e*n[r]*8.2*t,i[r]>=1&&(i[r]=0,a[r]=o[r],this.generateBlob(o,r))}draw(e,t,s,i,n,a,o,r){if(n.getContext){const l=n.getContext("2d");l.beginPath(),l.moveTo(s,i),l.lineTo(e,i);const{radius:d,radiusNext:c,N:h}=this;for(let n=0;n<=h;n++)if(0===n){const s=this.progress[n],i=(t-(d[n]*(1-s)+c[n]*s))*r+o*(1-r);l.lineTo(e,i)}else{const a=this.progress[n-1],p=d[n-1]*(1-a)+c[n-1]*a,u=this.progress[n],g=(s-e)/h*(n-1),m=(s-e)/h*n,v=g+(m-g)/2,f=(t-p)*r+o*(1-r),b=(t-(d[n]*(1-u)+c[n]*u))*r+o*(1-r);l.bezierCurveTo(v,f,v,b,m,b),n===h&&l.lineTo(s,i)}a(l),l.fill(),l.closePath()}}}class pr{constructor(e){this.stateId=e,this.createGradient(e)}createGradient(e){this.shader=(t,s,i,n,a)=>{t.fillStyle=pr.getGradientFromType(t,e,s,i,n,a)}}static getGradientFromType(e,t,s,i,n,a){const o=e.createLinearGradient(s,i,n,a);return t===cr.Z.MUTED_BY_ADMIN?(o.addColorStop(0,"#F05459"),o.addColorStop(.4,"#766EE9"),o.addColorStop(1,"#57A4FE")):t===cr.Z.UNMUTED?(o.addColorStop(0,"#52CE5D"),o.addColorStop(1,"#00B1C0")):t===cr.Z.MUTED?(o.addColorStop(0,"#0976E3"),o.addColorStop(1,"#2BCEFF")):t===cr.Z.CONNECTING&&(o.addColorStop(0,"#8599aa"),o.addColorStop(1,"#8599aa")),o}update(e,t,s,i){}}class ur{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:s,lbd2:i,scale:n,left:a,top:o,right:r,bottom:l,currentState:d,previousState:c,focused:h,resizing:p,canvas:u}=this;if(!h&&!p&&this.progressToState>=1)return;let g=Date.now()-this.lastUpdateTime;g>20&&(g=17),this.animateToAmplitude!==this.amplitude&&(this.amplitude+=this.animateAmplitudeDiff*g,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*g,this.animateAmplitudeDiff2>0?this.amplitude2>this.animateToAmplitude&&(this.amplitude2=this.animateToAmplitude):this.amplitude2<this.animateToAmplitude&&(this.amplitude2=this.animateToAmplitude)),c&&(this.progressToState+=g/250,this.progressToState>1&&(this.progressToState=1,this.previousState=null));const{amplitude:m,amplitude2:v,progressToState:f}=this,b=6*v*n,y=6*v*n;u.getContext("2d").clearRect(0,0,u.width,u.height),t.minRadius=0,t.maxRadius=(2+2*m)*n,s.minRadius=0,s.maxRadius=(3+9*m)*n,i.minRadius=0,i.maxRadius=(3+9*m)*n,t.update(m,.3),s.update(m,.7),i.update(m,.7);for(let e=0;e<2;e++){if(0===e&&!c)continue;let n=1,h=null;0===e?(n=1-f,h=c):(n=c?f:1,d.update(l-o,r-a,g,m),h=d);const p=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)};s.draw(a,o-b,r,l,u,p,o,1),i.draw(a,o-y,r,l,u,p,o,1),t.draw(a,o,r,l,u,v,o,1)}e||(this.raf=requestAnimationFrame((()=>this.draw())))},this.setCurrentState=(e,t)=>{const{currentState:s,states:i}=this;(null==s?void 0:s.stateId)!==e&&(this.previousState=t?s:null,this.currentState=i.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([[cr.Z.UNMUTED,new pr(cr.Z.UNMUTED)],[cr.Z.MUTED,new pr(cr.Z.MUTED)],[cr.Z.MUTED_BY_ADMIN,new pr(cr.Z.MUTED_BY_ADMIN)],[cr.Z.CONNECTING,new pr(cr.Z.CONNECTING)]]),this.previousState=null,this.currentState=this.states.get(cr.Z.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 hr(3),this.lbd1=new hr(7),this.lbd2=new hr(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 s=this.canvas=document.createElement("canvas");return s.classList.add(e+"-canvas"),t.append(s),t}}const gr=new class{constructor(){this.cache={},a.default.addEventListener("theme_change",(()=>{this.computedStyle=void 0;const e=this.cache;this.cache={};for(let 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)}};class mr{constructor(e,t){this.item=e,(0,w.Z)(this,t)}play(e){return this.item.playPart(this,e)}}class vr{constructor(e,t){this.icon=e,this.autoplay=!1,(0,w.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:s,canvas:i,width:n,height:a}=this.icon;return t=ae.Z.loadAnimationAsAsset({container:s,canvas:i,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=>ae.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 mr(this,e)}getPart(e){return e instanceof mr?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 fr{constructor(e){(0,w.Z)(this,e),this.container||(this.container=document.createElement("div")),this.container.classList.add("rlottie-icon");const{width:t,height:s}=this;this.container.style.width=t+"px",this.container.style.height=s+"px";const i=this.canvas=document.createElement("canvas");i.classList.add("rlottie"),i.width=t,i.height=s,this.items=new Map,this.loadPromises=new Map}get loadPromise(){return Promise.all([...this.loadPromises.values()]).then(_e.Z)}getItem(e){return e||1!==this.items.size?this.items.get(e):this.items.values().next().value}add(e){const t=new vr(this,e);return this.items.set(e.name,t),t}playPart(e,t,s){if(!e.player)return void(e.onLoadForPart=()=>{this.playPart(e,t,s)});const i=e.getPart(t);e.player.playPart({from:a.default.settings.animationsEnabled&&!this.skipAnimation?i.startFrame:i.endFrame,to:i.endFrame,callback:s})}static generateEqualParts(e,t){return new Array(e).fill(0).map(((e,s)=>{const i=s*t;return{startFrame:i,endFrame:i+t-1}}))}}class br extends fr{constructor(e){super({width:e.width,height:e.height}),(0,w.Z)(this,e)}load(e,t){if(this.loaded)return this.loadPromise;this.loaded=!0,this.partState=e,this.colorState=t;const s=this.getPart(e),i=void 0!==t&&this.getColor&&this.getColor(t),n=s.item;n.initFrame=s.endFrame,n.color=i;const a=[...this.items.values()].map((e=>e.load()));return Promise.all(a).then(_e.Z)}setState(e,t,s){this.loaded||this.load(e,t);let i=!1,n=!1;return void 0!==e?i=this.setPartState(e,t,s):void 0!==t&&(n=this.setColorState(t)),i||n}setPartState(e,t,s){const{partState:i}=this;return i===e?void 0!==t&&this.setColorState(t):(void 0!==t&&this.setColorState(t,!1),this.partState=e,this.getPart(e,i).play(s),!0)}setColorState(e,t=!0){const{colorState:s}=this;if(s===e||!this.getColor)return!1;this.colorState=e;const i=this.getItem(),n=this.getColor(e,s),a=()=>{i.player.setColor(n,t)};return i.player?a():i.onLoadForColor=a,!0}destroy(){this.items.forEach((e=>{e.loadPromise.then((()=>{e.player.remove()}))}))}}class yr extends br{constructor(){super({width:36,height:36,getPart:(e,t)=>{const s=Nr;let i;switch(e){case s.HAND:i=t===s.MUTED?"muted-to-hand":"unmuted-to-hand";break;case s.MUTED:i=t===s.HAND?"hand-to-muted":"mute";break;case s.UNMUTED:i="unmute"}return this.getItem().getPart(i)}}),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"}]})}}class wr extends br{constructor(e){super({width:32,height:32,getPart:(e,t)=>{const s=Ur;let i;switch(e){case s.HAND:i=3;break;case s.MUTED:i=t===s.HAND?0:2;break;case s.UNMUTED:i=1}return this.getItem().getPart(i)},getColor:e?(e,t)=>function(e){const t=Ur;let s,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"}return s=Bi(gr.getProperty("gc-"+i+"-text-color")),s}(e):void 0}),this.colored=e,this.container.classList.add("group-call-participant-muted-icon-container");const t=fr.generateEqualParts(4,21);this.add({name:"voice_outlined2",parts:t})}setState(e){return super.setState(function(e){const t=Ur;switch(e){case t.MUTED_BY_ADMIN:case t.MUTED_FOR_ME:return t.MUTED;default:return e}}(e),e)}}const Sr="group-call-participant-status";class Cr{constructor(e){this.withIcons=e,this.container=document.createElement("div"),this.container.classList.add(Sr+"-container")}setState(e,t){const s=Ur,i=this.withIcons.filter((e=>!!t[e])).map((e=>{const t="tgico-"+("presentation"===e?"listscreenshare":"videocamera_filled"),s=document.createElement("i");return s.classList.add(Sr+"-icon",Sr+"-icon-"+e,t),s}));let n,a;if(e===s.MUTED_FOR_ME)n=(0,k.i18n)("VoiceChat.Status.MutedForYou"),a="is-muted";else if(e===s.UNMUTED)n=(0,k.i18n)("VoiceChat.Status.Speaking"),a="is-speaking";else if(e===s.HAND)n=(0,k.i18n)("VoiceChat.Status.WantsSpeak"),a="is-waiting";else{if(t.about&&!i.length)return void m(this.container,Q.Z.wrapEmojiText(t.about));n=(0,k.i18n)("VoiceChat.Status.Listening"),a="is-listening"}const o=document.createElement("span");o.classList.add(Sr,a),o.append(...i,n),(0,T.Z)(this.container,o)}}class Lr extends Fs{constructor(e){super({getIndex:e=>e.participant.date,onDelete:e=>{e.dom.listEl.remove(),this.onElementDestroy(e)},onUpdate:e=>{const{participant:t}=e,s=Vr(t);e.mutedIcon.setState(s),e.status.setState(s,t)},onSort:(e,t)=>{Zs(e.dom.listEl,this.list,t)},onElementCreate:t=>{const{dom:s}=pd.addDialogNew({dialog:t.id,container:!1,drawStatus:!1,avatarSize:this.avatarSize,autonomous:this.autonomous,meAsSaved:!1,rippleEnabled:this.rippleEnabled,lazyLoadQueue:this.lazyLoadQueue});s.listEl.classList.add("group-call-participant");const i=e.participants.get(t.id),n=Vr(i),a=new wr(!0),o=new Cr(["presentation","video"]);return a.setState(n),o.setState(n,i),(0,T.Z)(s.lastMessageSpan,o.container),s.listEl.append(a.container),t.dom=s,t.participant=i,t.mutedIcon=a,t.status=o,t},updateElementWith:De.T2}),this.instance=e,this.avatarSize=54,this.rippleEnabled=!0,this.autonomous=!0,this.createChatListOptions={dialogSize:72},this.list=pd.createChatList(this.createChatListOptions)}destroy(){this.elements.forEach((e=>{this.onElementDestroy(e)}))}onElementDestroy(e){e.mutedIcon.destroy()}}function Ir(e){const t=document.createElement("canvas");t.classList.add("call-video-blur"),t.width=16,t.height=16;const s=t.getContext("2d");s.filter="blur(2px)";const i=()=>{s.drawImage(e,0,0,e.videoWidth,e.videoHeight,0,0,t.width,t.height)};return(0,Ue.jt)((()=>(i(),t.isConnected))),i(),t}const Mr="group-call-participant-video";class Er{constructor(e,t,s){this.appPeersManager=e,this.instance=t,this.source=s,this.container=document.createElement("div"),this.container.classList.add(Mr+"-container"),this.info=document.createElement("div"),this.info.classList.add(Mr+"-info"),this.left=document.createElement("div"),this.left.classList.add(Mr+"-info-left"),this.right=document.createElement("div"),this.right.classList.add(Mr+"-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(Mr+"-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,s){let i;e.pFlags.self?(i=(0,k.i18n)("VoiceChat.Status.You"),i.classList.add("peer-title")):(this.peerTitle=new St.Z({peerId:this.appPeersManager.getPeerId(e.peer)}),i=this.peerTitle.element),this.groupCallParticipantMutedIcon=new wr(!1),this.groupCallParticipantStatus=new Cr([t]),this.left.append(i,this.groupCallParticipantStatus.container),this.right.append(this.groupCallParticipantMutedIcon.container),s.classList.add(Mr,"call-video"),s.paused&&s.play();const n=Ir(s);n.classList.add(Mr+"-blur"),this.container.prepend(n,s),this.updateParticipant(e)}updateParticipant(e){const t=Vr(e);this.groupCallParticipantMutedIcon.setState(t),this.groupCallParticipantStatus.setState(t,e)}destroy(){this.groupCallParticipantMutedIcon.destroy()}}class Pr extends Ee{constructor(e){super(),(0,w.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:s}=this;s.add(a.default)("group_call_participant",(({groupCallId:e,participant:t})=>{this.instance.id===e&&this.updateParticipant(t)})),s.add(this.instance)("pinned",(e=>{this.participantsElements.forEach((t=>{t.forEach((t=>{this.setElementDisplay(t,e)}))}))})),(0,l.fc)(this.container,(e=>{const t=(0,Me.Z)(e.target,"group-call-participant-video-container");if(!t)return;const s=this.containers.get(t);this.instance.pinnedSource!==s.source?this.instance.pinSource(s.source):this.instance.unpinAll()}),{listenerSetter:s}),this.setInstance(this.instance),this.setup({element:t,listenerSetter:s,showOnLeaveToClassName:"group-call-buttons"})}shouldDisplayElement(e,t){return this.displayPinned?!t||e.source===t:t&&e.source!==t}setElementDisplay(e,t){const s=this.shouldDisplayElement(e,t);e.container.classList.toggle("video-hidden",!s);const i=e.source===t;e.setPinned(i)}updateParticipant(e){const t=this.appPeersManager.getPeerId(e.peer),s=["video","presentation"],i=s.some((t=>!!e[t]));let n=this.participantsElements.get(t);(i||n)&&(n||this.participantsElements.set(t,n=new Map),s.forEach((s=>{let i=n.get(s);const a=e[s];if(!!a!=!!i){if(a){const t=this.instance.getVideoElementFromParticipantByType(e,s);if(!t)return;const{video:a,source:o}=t;i=new Er(this.appPeersManager,this.instance,o),this.containers.set(i.container,i),this.setElementDisplay(i,this.instance.pinnedSource),n.set(s,i),i.setParticipant(e,s,a),this.container.prepend(i.container)}else n.delete(s),i.container.remove(),n.size||(this.participantsElements.delete(t),this.containers.delete(i.container),i.destroy());this._onLengthChange()}else i&&i.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){e.participants.forEach((e=>{this.updateParticipant(e)}))}destroy(){this.containers.forEach((e=>{e.destroy()}))}}class Tr{constructor(e){this.onOpenProfileClick=()=>{const e=pt.Z.getPopups(Kr)[0];e&&e.hide(),a.default.dispatchEvent("history_focus",{peerId:this.targetPeerId})},this.toggleParticipantMuted=e=>{this.appGroupCallsManager.editParticipant(this.instance.id,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.appChatsManager.hasRights(this.chatId,"ban_users"),onClick:()=>{on({peerId:this.targetPeerId,title:new St.Z({peerId:this.targetPeerId}).element,descriptionLangKey:this.appChatsManager.isBroadcast(this.chatId)?"VoiceChat.RemovePeer.Confirm.Channel":"VoiceChat.RemovePeer.Confirm",descriptionLangArgs:[new St.Z({peerId:this.targetPeerId}).element],button:{langKey:"VoiceChat.RemovePeer.Confirm.OK",isDanger:!0}}).then((()=>{this.appChatsManager.kickFromChat(this.chatId,this.targetPeerId)}),_e.Z)}}];const{listenerSetter:t}=e;this.appChatsManager=e.appChatsManager,this.appPeersManager=e.appPeersManager,this.appGroupCallsManager=e.appGroupCallsManager,this.instance=e.instance,this.chatId=this.instance.chatId,this.element=Ce(this.buttons,t),this.element.classList.add("group-call-participant-menu","night"),(0,J.Eo)(e.onContextElement,(e=>{const t=(0,Me.Z)(e.target,"group-call-participant");if(!t)return;this.element.parentElement!==s&&s.append(this.element);const i=this.targetPeerId=t.dataset.peerId.toPeerId();this.participant=this.instance.getParticipantByPeerId(i),this.participant.pFlags.self||(this.canManageCall=this.appChatsManager.hasRights(this.chatId,"manage_call"),this.buttons.forEach((e=>{e.element.classList.toggle("hide",!e.verify(i))})),(0,d.d)(e),(0,J.oy)(e.touches?e.touches[0]:e,this.element,"right"),(0,J.YP)(this.element))}),t),t.add(a.default)("group_call_participant",(({groupCallId:e,participant:t})=>{if(this.instance.id===e){const e=this.appPeersManager.getPeerId(t.peer);this.targetPeerId===e&&(0,J.UR)()}}));let s=document.body;(0,Pe.Ms)(document.body,(()=>{const e=(0,Pe.rB)();s=e?pt.Z.getPopups(Kr)[0].getContainer():document.body,e||(0,J.UR)()}),t)}}class kr{constructor(e){(0,w.Z)(this,e);const t="group-call-participants",s=new P.ZP(void 0);s.container.classList.add(t+"-scrollable");const i=this.container=document.createElement("div");i.classList.add(t);const n=this.sortedList=new Lr(this.instance),{instance:o,listenerSetter:r}=this;this.contextMenu=new Tr(Object.assign(Object.assign({},e),{onContextElement:n.list,listenerSetter:r,instance:o})),this.groupCallParticipantsVideo=new Pr(Object.assign(Object.assign({},e),{appendTo:s.container,displayPinned:!1})),s.append(n.list),i.append(s.container),e.appendTo.append(i),r.add(a.default)("group_call_participant",(({groupCallId:e,participant:t})=>{this.instance.id===e&&this.updateParticipant(t)})),new bt({scrollable:s,getPromise:()=>this.appGroupCallsManager.getGroupCallParticipants(this.instance.id).then((({participants:e,isEnd:t})=>(e.forEach((e=>{this.updateParticipant(e)})),t)))}),this.setInstance(o)}updateParticipant(e){const t=this.appPeersManager.getPeerId(e.peer),s=this.sortedList.has(t);e.pFlags.left?s&&this.sortedList.delete(t):s?this.sortedList.update(t):this.sortedList.add(t)}setInstance(e){e.participants.forEach((e=>{this.updateParticipant(e)}))}destroy(){this.sortedList.destroy(),this.groupCallParticipantsVideo.destroy()}}class xr{constructor(e){this.appendTo=e,this.descriptionIntl=new k.default.IntlElement({key:"VoiceChat.Status.Connecting"}),this.descriptionIntl.element.classList.add("group-call-description")}detach(){this.descriptionIntl.element.remove()}update(e){const{state:t}=e;let s,i;t===cr.Z.CONNECTING?s="VoiceChat.Status.Connecting":(s="VoiceChat.Status.Members",i=[e.groupCall.participants_count]);const{descriptionIntl:n}=this;n.compareAndUpdate({key:s,args:i}),this.descriptionIntl.element.parentElement||this.appendTo.append(this.descriptionIntl.element)}}class Ar{constructor(e){this.appendTo=e,this.peerTitle=new St.Z({peerId:0})}update(e){const{peerTitle:t,appendTo:s}=this,i=e.groupCall,n=e.chatId.toPeerId(!0);i.title?m(s,Q.Z.wrapEmojiText(i.title)):(t.peerId!==n&&(t.peerId=n,t.update()),t.element.parentElement!==s&&s.append(t.element))}}const _r=!!("getDisplayMedia"in((null===navigator||void 0===navigator?void 0:navigator.mediaDevices)||{}));function Zr(e,t,s){const i=e+"-button",n=document.createElement("div");n.classList.add(i,"call-button","rp-overflow"),s.icon&&n.classList.add("tgico-"+s.icon),s.noRipple||(0,ee.ripple)(n),s.isDanger&&n.classList.add(i+"-red"),s.isConfirm&&n.classList.add(i+"-green"),s.callback&&(0,l.fc)(n,s.callback,{listenerSetter:t});let a=n;if(s.text){const e=document.createElement("div");e.classList.add(i+"-container","call-button-container");const t="string"==typeof s.text?(0,k.i18n)(s.text):s.text;t.classList.add(i+"-text","call-button-text"),e.append(n,t),a=e}return a}const Dr="movable-element",Fr="movable-element-resize-handler";class Rr extends R.Z{constructor(e){super(!0),this.onResize=()=>{this.fixDimensions(),this.fixPosition(),this.setPosition()},(0,w.Z)(this,e),this.top=this.left=this.width=this.height=0,this.element.classList.add(Dr),this.addResizeHandlers(),this.setSwipeHandler(),v.ZP.addEventListener("resize",this.onResize)}destroyElements(){this.element.classList.remove(Dr),this.handlers&&this.handlers.forEach((e=>{e.remove()}))}destroy(){v.ZP.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(Fr,Fr+"-side-"+e),this.element.append(t),t}))}setSwipeHandler(){let e,t,s,i,n;const a=this.swipeHandler=new jt({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,i=Math.abs(a)*(e?1:-1),o=n.includes("e")?Ct.Z.width-t:s+t;this.width=Math.min(o,s+i)}if(n.includes("n")||n.includes("s")){const t=n.includes("s")&&o>0||n.includes("n")&&o<0,s=Math.abs(o)*(t?1:-1),a=n.includes("s")?Ct.Z.height-e:i+e;this.height=Math.min(a,i+s)}this.fixDimensions(),n.includes("w")&&(this.left=Math.min(t+s-this.minWidth,t+a)),n.includes("n")&&(this.top=Math.min(e+i-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 s=(0,Me.Z)(t,Fr);return s?(n=s.dataset.side,a.setCursor("")):(n=void 0,a.setCursor("grabbing")),!0},onFirstSwipe:()=>{e=this.top,t=this.left,s=this.width,i=this.height}})}setPositionToCenter(){this.top=Ct.Z.height/2-this.height/2,this.left=Ct.Z.width/2-this.width/2,this.setPosition()}fixDimensions(){this.width=(0,ye.Z)(this.width,this.minWidth,Ct.Z.width),this.height=(0,ye.Z)(this.height,this.minHeight,Ct.Z.height)}fixPosition(){this.top=(0,ye.Z)(this.top,0,Ct.Z.height-this.height),this.left=(0,ye.Z)(this.left,0,Ct.Z.width-this.width)}setPosition(){this.element.style.top=this.top+"px",this.element.style.left=this.left+"px",this.element.style.right="auto",this.element.style.bottom="auto",this.element.style.width=this.width+"px",this.element.style.height=this.height+"px",this.dispatchEvent("resize")}get width(){return this._width}get height(){return this._height}set width(e){this._width=e}set height(e){this._height=e}get state(){const{top:e,left:t,width:s,height:i}=this;return{top:e,left:t,width:s,height:i}}set state(e){const{top:t,left:s,width:i,height:n}=e;this.top=t,this.left=s,this.width=i,this.height=n,this.onResize()}}var Br,Ur,Nr,Or=function(e,t,s,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!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"===i?n.call(e,s):n?n.value=s:t.set(e,s),s};class Hr{constructor(e){Br.set(this,void 0),(0,w.Z)(this,e),this.toggleMovable(!ce.IS_TOUCH_SUPPORTED),this.listenerSetter.add(v.ZP)("changeScreen",((e,t)=>{t!==v._G.mobile&&e!==v._G.mobile||this.toggleMovable(!ce.IS_TOUCH_SUPPORTED)}))}destroy(){const e=this.movable;e&&e.destroy()}get movable(){return function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)}(this,Br,"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=Or(this,Br,new Rr(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(),Or(this,Br,void 0,"f")}}}function zr(e,t,s){return t.forEach((t=>{t.classList.toggle(e,s)})),()=>zr(e,t,!s)}function Vr(e){const t=Ur;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}Br=new WeakMap,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"}(Ur||(Ur={})),function(e){e[e.HAND=0]="HAND",e[e.MUTED=1]="MUTED",e[e.UNMUTED=2]="UNMUTED"}(Nr||(Nr={}));let jr={width:420,height:640};const Gr="group-call";class Kr extends pt.Z{constructor(e){super("popup-group-call",void 0,{body:!0,withoutOverlay:!0,closable:!0}),this.onFullScreenClick=()=>{(0,Pe.Dj)(this.container)},this.onToggleControls=e=>{this.container.classList.toggle("show-controls",e),this.buttonsContainer.classList.toggle("show-controls",e)},this.toggleDisability=zr.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=()=>{const e=e=>{this.instance.hangUp(e)};this.appChatsManager.hasRights(this.instance.chatId,"manage_call")?new gt("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)},this.onFullScreenChange=()=>{this.toggleBigLayout();const e=(0,Pe.rB)(),{btnFullScreen:t,btnExitFullScreen:s}=this,i=this.container.classList.contains("is-full-screen");this.container.classList.toggle("is-full-screen",e),t&&t.classList.toggle("hide",e),s&&s.classList.toggle("hide",!e),this.btnClose.classList.toggle("hide",e),e!==i&&(I.Z.checkAnimations(e),a.default.setThemeColor(e?"#000000":void 0))},this.toggleBigLayout=()=>{var e;const t=(0,Pe.rB)(),s=null===(e=this.movablePanel)||void 0===e?void 0:e.movable,i=(t||!!(s&&s.width>=680))&&!!this.videosCount,n=this.container.classList.contains("is-big-layout");let a;i&&!n&&(a=Array.from(this.buttonsContainer.children),a.forEach((e=>{e.style.opacity="0"})),this.buttonsContainer.offsetLeft),this.container.classList.toggle("is-big-layout",i),this.btnInvite.classList.toggle("hide",i),this.btnShowColumn.classList.toggle("hide",!i),a&&a.forEach((e=>{e.style.opacity=""}))},this.toggleRightColumn=()=>{this.container.classList.toggle("is-right-column-shown")},(0,w.Z)(this,e),this.videosCount=0,this.container.classList.add(Gr,"night");const t=this.instance=this.appGroupCallsManager.groupCall,{listenerSetter:s}=this;if(!ne.IS_APPLE_MOBILE){const e=this.btnFullScreen=N("fullscreen"),t=this.btnFullScreen2=N("fullscreen group-call-cfs"),i=this.btnExitFullScreen=N("smallscreen");(0,l.fc)(e,this.onFullScreenClick,{listenerSetter:s}),(0,l.fc)(t,this.onFullScreenClick,{listenerSetter:s}),(0,l.fc)(i,(()=>{(0,Pe.C8)()}),{listenerSetter:s}),(0,Pe.Ms)(this.container,this.onFullScreenChange,s)}this.btnInvite=N("adduser");const i=this.btnShowColumn=N("rightpanel group-call-only-big");(0,l.fc)(i,this.toggleRightColumn,{listenerSetter:s});const n=document.createElement("div");n.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"),n.append(this.title,o),this.header.classList.add("group-call-header"),this.header.append(...[this.btnExitFullScreen,n,this.btnFullScreen,i].filter(Boolean));const r=this.header.cloneNode(!1),d=n.cloneNode(!1),c=this.title.cloneNode(!1);d.append(c);const h=N("rightpanel");r.append(...[h,d,this.btnFullScreen2].filter(Boolean)),(0,l.fc)(h,this.toggleRightColumn,{listenerSetter:s}),this.body.prepend(r);const p=new P.ZP(void 0);p.container.classList.add("group-call-big-video-container"),this.container.append(p.container),this.groupCallTitle=new Ar(this.title),this.groupCallDescription=new xr(o),this.groupCallBodyHeaderDescription=new xr(c),this.constructButtons(),this.groupCallParticipantsVideo=new Pr(Object.assign({appendTo:p.container,instance:t,listenerSetter:s,displayPinned:!0,onLengthChange:e=>{this.videosCount=e,this.toggleBigLayout()}},e)),this.groupCallParticipants=new kr(Object.assign({appendTo:this.body,instance:t,listenerSetter:s},e)),this.movablePanel=new Hr({listenerSetter:s,movableOptions:{minWidth:400,minHeight:480,element:this.element,verifyTouchTarget:e=>{const t=e.target;return!((0,Me.Z)(t,"chatlist")||(0,Me.Z)(t,"group-call-button")||(0,Me.Z)(t,"btn-icon")||(0,Me.Z)(t,"group-call-participants-video-container")||(0,Pe.rB)())}},onResize:()=>this.toggleBigLayout(),previousState:jr}),s.add(t)("state",(()=>{this.updateInstance()})),s.add(a.default)("group_call_update",(e=>{var t;(null===(t=this.instance)||void 0===t?void 0:t.id)===e.id&&this.updateInstance()})),s.add(t)("pinned",(()=>{this.setHasPinned()})),s.add(this.groupCallParticipantsVideo)("toggleControls",this.onToggleControls),this.addEventListener("close",(()=>{const{movablePanel:e}=this;jr=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=Zr.bind(null,Gr,this.listenerSetter),s=this.btnVideo=t({callback:this.onVideoClick,icon:"videocamera_filled"}),i=this.btnScreen=t({callback:this.onScreenClick,icon:"sharescreen_filled"});i.classList.toggle("hide",!_r);const n=t({noRipple:!0,callback:(0,ms.Z)(this.onMuteClick,600,!0)});n.classList.add("group-call-microphone-button");const a=this.groupCallMicrophoneIcon=new yr;n.append(a.container);const o=t({icon:"settings_filled"});o.classList.add("btn-disabled"),o.classList.toggle("hide",!_r);const r=t({isDanger:!0,callback:this.onLeaveClick,icon:"close"});e.append(s,i,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===cr.Z.CLOSED)return this.container.classList.contains("is-full-screen")&&(0,Pe.C8)(),void this.hide();const{participant:e,groupCall:t}=this.instance;if(!e)return;this.setTitle(),this.setDescription(),this.setHasPinned();const s=function(e,t){const s=Nr;return t.pFlags.can_self_unmute?t.pFlags.muted?s.MUTED:s.UNMUTED:s.HAND}(0,e);this.container.dataset.micState=s===Nr.HAND?"hand":s===Nr.MUTED?"muted":"unmuted",this.groupCallMicrophoneIcon.setState(s)}setTitle(){this.groupCallTitle.update(this.instance)}setDescription(){this.groupCallDescription.update(this.instance),this.groupCallBodyHeaderDescription.update(this.instance)}}var Wr,qr=s(9078);!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"}(Wr||(Wr={}));const $r=Wr;class Qr{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 s;if(this.state=t,t===$r.CONNECTED){s=document.createElement("span"),s.classList.add("call-description-duration");const t=()=>{s.innerText=(""+e.duration).toHHMMSS(!0)};this.interval=window.setInterval(t,1e3),t()}else{let i;switch(t){case $r.PENDING:i=e.isOutgoing?"Call.StatusRinging":"Call.StatusCalling";break;case $r.REQUESTING:i="Call.StatusRequesting";break;case $r.EXCHANGING_KEYS:i="VoipExchangingKeys";break;case $r.CLOSED:i=void 0!==e.connectedAt?"Call.StatusEnded":"Call.StatusFailed";break;default:i="Call.StatusConnecting"}s=(0,k.i18n)(i),void 0!==this.interval&&(clearInterval(this.interval),this.interval=void 0)}this.container.classList.toggle("has-duration",t===$r.CONNECTED),(0,T.Z)(this.container,s),this.container.parentElement||this.appendTo.append(this.container)}}class Yr extends br{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 Xr="call",Jr={width:400,height:580};let el=Object.assign({},Jr);class tl extends pt.Z{constructor(e){super("popup-call",void 0,{withoutOverlay:!0,closable:!0}),this.onFullScreenClick=()=>{(0,Pe.Dj)(this.container)},this.onFullScreenChange=()=>{const e=(0,Pe.rB)(),{btnFullScreen:t,btnExitFullScreen:s}=this,i=this.container.classList.contains("is-full-screen");this.container.classList.toggle("is-full-screen",e),t&&t.classList.toggle("hide",e),s&&s.classList.toggle("hide",!e),this.btnClose.classList.toggle("hide",e),e!==i&&(I.Z.checkAnimations(e),a.default.setThemeColor(e?"#000000":void 0),this.resizeVideoContainers())},(0,w.Z)(this,e),this.videoContainers={};const{container:t,listenerSetter:s,instance:i}=this;t.classList.add(Xr,"night");const n=document.createElement("div");n.classList.add("call-avatar");const o=this.peerId=this.instance.interlocutorUserId.toPeerId(),r=new Yl;r.isBig=!0,r.setAttribute("peer",""+o),r.classList.add("avatar-full"),n.append(r);const d=new St.Z({peerId:o}).element;d.classList.add("call-title");const c=document.createElement("div");c.classList.add("call-subtitle"),this.description=new Qr(c);const h=this.emojisSubtitle=document.createElement("div");h.classList.add("call-emojis"),t.append(n,d,c),ne.IS_MOBILE?this.header.append(h):(this.btnFullScreen=N("fullscreen"),this.btnExitFullScreen=N("smallscreen hide"),(0,l.fc)(this.btnFullScreen,this.onFullScreenClick,{listenerSetter:s}),(0,l.fc)(this.btnExitFullScreen,(()=>(0,Pe.C8)()),{listenerSetter:s}),(0,Pe.Ms)(this.container,this.onFullScreenChange,s),this.header.prepend(this.btnExitFullScreen),this.header.append(this.btnFullScreen),t.append(h)),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 p=(0,k.i18n)("VoipUserMicrophoneIsOff",[new St.Z({peerId:o,onlyFirstName:!0,limitSymbols:18}).element]);p.classList.add("call-party-state-text");const u=new Yr(!1,!0);u.setState(!1,!1),this.partyMutedState.append(u.container,p),this.partyStates.append(this.partyMutedState),this.container.append(this.partyStates),this.makeButton=Zr.bind(null,Xr,this.listenerSetter),this.constructFirstButtons(),this.constructSecondButtons(),s.add(i)("state",(()=>{this.updateInstance()})),s.add(i)("mediaState",(()=>{this.updateInstance()})),this.movablePanel=new Hr({listenerSetter:s,movableOptions:{minWidth:400,minHeight:580,element:this.element,verifyTouchTarget:e=>{const t=e.target;return!((0,Me.Z)(t,"call-button")||(0,Me.Z)(t,"btn-icon")||(0,Pe.rB)())}},previousState:this.instance.wasTryingToJoin||this.instance.isOutgoing?el:Object.assign({},Jr)});const g=this.movablePanel.movable;g&&this.listenerSetter.add(g)("resize",(()=>{this.resizeVideoContainers()}));const m=this.controlsHover=new Ee;m.setup({element:this.container,listenerSetter:this.listenerSetter,showOnLeaveToClassName:"call-buttons"}),m.showControls(!1),this.addEventListener("close",(()=>{const{movablePanel:e}=this;el=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=zr.bind(null,"btn-disabled"),s=this.btnVideo=this.makeButton({text:"Call.Camera",icon:"videocamera_filled",callback:()=>{const e=t([s,i],!0);this.instance.toggleVideoSharing().finally(e)}}),i=this.btnScreen=this.makeButton({text:"Call.Screen",icon:"sharescreen_filled",callback:()=>{const e=t([s,i],!0);this.instance.toggleScreenSharing().finally(e)}});_r||(i.classList.add("hide"),this.container.classList.add("no-screen")),this.muteI18nElement=new k.default.IntlElement({key:"Call.Mute"});const n=this.btnMute=this.makeButton({text:this.muteI18nElement.element,callback:()=>{this.instance.toggleMuted()}}),a=this.microphoneIcon=new Yr(!0,!0);n.firstElementChild.append(a.container),e.append(s,i,n),this.container.append(e)}constructSecondButtons(){const e=this.secondButtonsRow=document.createElement("div");e.classList.add("call-buttons","is-second"),this.declineI18nElement=new k.default.IntlElement({key:"Call.Decline"});const t=this.btnDecline=this.makeButton({text:this.declineI18nElement.element,icon:"endcall_filled",callback:()=>{this.instance.hangUp("phoneCallDiscardReasonHangup")},isDanger:!0}),s=this.btnAccept=this.makeButton({text:"Call.Accept",icon:"phone_filled",callback:()=>{this.instance.acceptCall()},isConfirm:!0});e.append(t,s),this.container.append(e)}createVideoContainer(e){const t=document.createElement("div");t.classList.add("call-video-container"),e.classList.add("call-video"),e.paused&&e.play(),(0,l.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 s=Ir(e);return s.classList.add("call-video-blur"),t.append(s,e),t}updateInstance(){const{instance:e}=this,{connectionState:t}=e;if(t===$r.CLOSED)return this.container.classList.contains("is-full-screen")&&(0,Pe.C8)(),this.btnVideo.classList.add("disabled"),void this.hide();const s=!e.isOutgoing&&t===$r.PENDING;this.declineI18nElement.compareAndUpdate({key:t===$r.PENDING?"Call.Decline":"Call.End"}),this.btnAccept.classList.toggle("disable",!s),this.btnAccept.classList.toggle("hide-me",!s),this.container.classList.toggle("two-button-rows",s);const i=e.isMuted,n=()=>{this.btnMute.firstElementChild.classList.toggle("active",i)},a=this.microphoneIcon.getItem().player;this.microphoneIcon.setState(!i,!i,n),a||n(),this.muteI18nElement.compareAndUpdate({key:i?"VoipUnmute":"Call.Mute"});const 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");(0,Jt.Z)(this.partyMutedState,"is-visible",!!(null==l?void 0:l.muted),300);const d=this.videoContainers,c=Object.assign({},d);["input","output"].forEach((t=>{const s=e.getMediaState(t),i=e.getVideoElement(t),n=!!(i&&i.videoWidth&&i.videoHeight);!i||n||i.dataset.hasPromise||(i.dataset.hasPromise="1",(0,he.xD)(i).then((()=>{delete i.dataset.hasPromise,this.updateInstance()})));const a=!!i&&n&&!(!s||"active"!==s.videoState&&"active"!==s.screencastState);let o=d[t];a&&i&&!o&&(o=d[t]=this.createVideoContainer(i),this.container.append(o)),!a&&o&&(o.remove(),delete d[t])}));{const e=d.input,t=d.output;Object.keys(c).length!==Object.keys(d).length&&e&&e.classList.toggle("small",!!t),t&&!e&&t.classList.remove("small")}this.resizeVideoContainers(),this.container.classList.toggle("no-video",!Object.keys(d).length),!this.emojisSubtitle.textContent&&t<$r.EXCHANGING_KEYS&&Promise.resolve(e.getEmojisFingerprint()).then((e=>{this.emojisSubtitle.innerHTML=Q.Z.wrapEmojiText(e.join(""))})),this.setDescription()}resizeVideoContainers(){Object.values(this.videoContainers).forEach((e=>{if(e.classList.contains("small")){const t=e.querySelector("video"),s=this.movablePanel.state,i=240,n=240,a=t.videoHeight>t.videoWidth,o=a?n:i,r=1/3*((0,Pe.rB)()?65535:a?s.height:s.width),l=a?t.videoWidth/t.videoHeight:1,d=a?1:t.videoHeight/t.videoWidth;e.style.width=r*l+"px",e.style.height=r*d+"px",e.style.maxWidth=o*l+"px",e.style.maxHeight=o*d+"px"}else e.style.cssText=""}))}setDescription(){this.description.update(this.instance)}}var sl=s(3075),il=s(3773);function nl(e){const t=(0,il.Z)(e,e.media[0]),s={"@type":"InitialSetup",fingerprints:[t.fingerprint],ufrag:t.ufrag,pwd:t.pwd,audio:void 0,video:void 0,screencast:void 0},i=e=>""+e;for(const t of e.media){const n=t.mediaType;if("application"===n||!t.isSending)continue;const a=s["video"===n&&s.video?"screencast":n]={},o=(0,il.Z)(e,t);a.ssrc=i(o.source),o.sourceGroups&&(a.ssrcGroups=o.sourceGroups.map((e=>({semantics:e.semantics,ssrcs:e.sources.map(i)}))));const r=a.rtpExtensions=[];t.attributes.get("extmap").forEach((e=>{r.push({id:+e.key,uri:e.value})}));const l=new Map,d=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,s=d(t),i=e.value.split("/"),[n,a,o]=i;s.name=n,s.clockrate=+a,s.channels=o?+o:0})),t.attributes.get("rtcp-fb").forEach((e=>{const t=+e.key;d(t).feedbackTypes=e.lines.map((e=>{const t=e.split(" "),[s,i]=t;return{type:s,subtype:i||""}}))})),t.attributes.get("fmtp").forEach((e=>{const t=+e.key,s=d(t).parameters={},i=e.value.split(";");for(const e of i){const[t,i]=e.split("=");s[t]=i}})),a.payloadTypes=Array.from(l.values())}return s}var al=s(9124);class ol extends sl.Z{constructor(e){super(e)}negotiateInternal(){return e=this,t=void 0,i=function*(){const{connection:e,call:t}=this;if(!e.localDescription&&!e.remoteDescription&&!t.isOutgoing)return;let s;if(t.offerReceived){t.offerReceived=!1;const i=s=yield e.createAnswer();this.log("[sdp] local",i.type,i.sdp),yield e.setLocalDescription(i),this.log("[InitialSetup] send 2")}else{const i=s=yield e.createOffer();this.log("[sdp] local",i.sdp),yield e.setLocalDescription(i),t.offerSent=!0,this.log("[InitialSetup] send 0")}const i=nl((0,al.DV)(s.sdp));t.sendCallSignalingData(i)},new((s=void 0)||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}));var e,t,s,i}}var rl=s(8500),ll=s(1677),dl=s(49),cl=s(6752),hl=s(4903);const pl="undefined"!=typeof window&&"crypto"in window?window.crypto.subtle:self.crypto.subtle;var ul=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class gl{constructor(e,t){this.isOutgoing=e,this.p2pKey=t,this.type="Signaling",this.counter=0,this.seqMap=new Map}concatSHA256(e){return t=(0,hl.Z)(...e),pl.digest("SHA-256",function(e){return e instanceof Uint8Array?e:"string"==typeof e?(new TextEncoder).encode(e):new Uint8Array(e)}(t)).then((e=>new Uint8Array(e)));var t}encryptPrepared(e){return ul(this,void 0,void 0,(function*(){const t={counter:0,bytes:new Uint8Array(16+e.length)},s=(this.isOutgoing?0:8)+("Signaling"===this.type?128:0),i=this.p2pKey,n=yield this.concatSHA256([i.subarray(s+88,s+88+32),e]),a=t.bytes;for(let e=0;e<16;++e)a[e]=n[e+8];const o=yield this.prepareAesKeyIv(i,a,s),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,s=new ArrayBuffer(4);new DataView(s).setUint32(0,t>>>0,!1);const i=new Uint8Array([...new Uint8Array(s),...e]);return this.encryptPrepared(i)}prepareAesKeyIv(e,t,s){return ul(this,void 0,void 0,(function*(){const[i,n]=yield Promise.all([this.concatSHA256([t.subarray(0,16),e.subarray(s,s+36)]),this.concatSHA256([e.subarray(40+s,40+s+36),t.subarray(0,16)])]);return{key:new Uint8Array([...i.subarray(0,8),...n.subarray(8,24),...i.subarray(24,32)]),iv:new Uint8Array([...n.subarray(0,4),...i.subarray(8,16),...n.subarray(24,28)])}}))}aesProcessCtr(e,t,s,i=!0){return ul(this,void 0,void 0,(function*(){const t=yield pl.importKey("raw",s.key,{name:"AES-CTR"},!1,[i?"encrypt":"decrypt"]),n=yield pl[i?"encrypt":"decrypt"]({name:"AES-CTR",counter:s.iv,length:8*s.iv.length},t,e);return new Uint8Array(n)}))}constTimeIsDifferent(e,t,s){let i=!0;for(let n=0;n<s;++n)e[n]!==t[n]&&(i=!1);return!i}decryptRawPacket(e){return ul(this,void 0,void 0,(function*(){if(e.length<21||e.length>134217728)return;const{isOutgoing:t,type:s}=this,i=(t?8:0)+("Signaling"===s?128:0),n=this.p2pKey,a=e.subarray(0,16),o=e.subarray(16),r=e.length-16,l=yield this.prepareAesKeyIv(n,a,i),d=yield this.aesProcessCtr(o,r,l,!1),c=yield this.concatSHA256([n.subarray(88+i,88+i+32),d]);if(this.constTimeIsDifferent(c.subarray(8),a,16))return;const h=new DataView(d.buffer).getUint32(0);return this.seqMap.has(h)?void 0:(this.seqMap.set(h,h),d.slice(4))}))}}var ml=s(630);class vl{static generateOffer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a],r=new ml.Z;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:s,setup:i}=e;r.add(`a=fingerprint:${t} ${s}`,`a=setup:${i}`)})),s&&i&&r.add(`a=ice-ufrag:${s}`,`a=ice-pwd:${i}`),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:s,ssrc:i,ssrcGroups:n,payloadTypes:a,rtpExtensions:d}=t;switch(s){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",Sl(d)),i&&r.add(`a=msid:${l} audio${i}`),r.add("a=rtcp-mux",Cl(a),Ll(s,i,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",Sl(d)),i&&r.add(`a=msid:${l} video${i}`),r.add("a=rtcp-mux","a=rtcp-rsize",Cl(a),Ll(s,i,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:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a],r=new ml.Z;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:s,setup:i}=e;r.add(`a=fingerprint:${t} ${s}`,`a=setup:${i}`)})),s&&i&&r.add(`a=ice-ufrag:${s}`,`a=ice-pwd:${i}`),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:s,ssrc:i,ssrcGroups:n,payloadTypes:a,rtpExtensions:d}=t;switch(s){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",Sl(d)),i&&r.add(`a=msid:${l} audio${i}`),r.add("a=rtcp-mux",Cl(a),Ll(s,i,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",Sl(d)),i&&r.add(`a=msid:${l} video${i}`),r.add("a=rtcp-mux","a=rtcp-rsize",Cl(a),Ll(s,i,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 fl{static generateOffer(e){const{fingerprints:t,ufrag:s,pwd:i,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:s,setup:i}=e;r+=`\na=fingerprint:${t} ${s}\na=setup:${i}`})),s&&i&&(r+=`\na=ice-ufrag:${s}\na=ice-pwd:${i}`),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:s,ssrc:i,ssrcGroups:n,payloadTypes:a,rtpExtensions:d}=t;switch(s){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+=Sl(d),r+="\na=rtcp-mux",r+=Cl(a),r+=Ll(s,i,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+=Sl(d),r+="\na=rtcp-mux\na=rtcp-rsize",r+=Cl(a),r+=Ll(s,i,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:s,pwd:i,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:s,setup:i}=e;r+=`\na=fingerprint:${t} ${s}\na=setup:${i}`})),s&&i&&(r+=`\na=ice-ufrag:${s}\na=ice-pwd:${i}`),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:s,mid:i,ssrc:n,ssrcGroups:a,payloadTypes:d,dir:c,rtpExtensions:h}=t;switch(s){case"audio":r+=`\nm=audio 9 UDP/TLS/RTP/SAVPF ${d.map((e=>e.id)).join(" ")}\nc=IN IP4 0.0.0.0\na=mid:${e}\na=sendrecv`,r+=Sl(h),r+="\na=rtcp-mux",r+=Cl(d),r+=Ll(s,n,a,l);break;case"video":r+=`\nm=video 9 UDP/TLS/RTP/SAVPF ${d.map((e=>e.id)).join(" ")}\nc=IN IP4 0.0.0.0\na=mid:${e}\na=sendrecv`,r+=Sl(h),r+="\na=rtcp-mux\na=rtcp-rsize",r+=Cl(d),r+=Ll(s,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 bl{static generateOffer(e){const{fingerprints:t,ufrag:s,pwd:i,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:s,setup:i}=e;r+=`\na=fingerprint:${t} ${s}\na=setup:${i}`})),s&&i&&(r+=`\na=ice-ufrag:${s}\na=ice-pwd:${i}`),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:s,ssrc:i,ssrcGroups:n,payloadTypes:a,rtpExtensions:d}=t;switch(s){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+=Sl(d),i&&(r+=`\na=msid:${l} audio${i}`),r+="\na=rtcp-mux",r+=Cl(a),r+=Ll(s,i,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+=Sl(d),i&&(r+=`\na=msid:${l} video${i}`),r+="\na=rtcp-mux\na=rtcp-rsize",r+=Cl(a),r+=Ll(s,i,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:s,pwd:i,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:s,setup:i}=e;r+=`\na=fingerprint:${t} ${s}\na=setup:${i}`})),s&&i&&(r+=`\na=ice-ufrag:${s}\na=ice-pwd:${i}`),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:s,ssrc:i,ssrcGroups:n,payloadTypes:a,rtpExtensions:d}=t;switch(s){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+=Sl(d),i&&(r+=`\na=msid:${l} audio${i}`),r+="\na=rtcp-mux",r+=Cl(a),r+=Ll(s,i,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+=Sl(d),i&&(r+=`\na=msid:${l} video${i}`),r+="\na=rtcp-mux\na=rtcp-rsize",r+=Cl(a),r+=Ll(s,i,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 yl(){return navigator.userAgent.toLowerCase().indexOf("firefox")>-1}function wl(){return navigator.userAgent.toLowerCase().indexOf("safari")>-1&&-1===navigator.userAgent.toLowerCase().indexOf("chrome")}function Sl(e){let t=[];for(let s=0;s<e.length;s++){const i=e[s],{id:n,uri:a}=i;console.log("[extmap] add",n,a),t.push(`a=extmap:${n} ${a}`)}return t.join("\n")}function Cl(e){let t=[];console.log("[SDP] addPayloadTypes",e);for(let s=0;s<e.length;s++){const i=e[s],{id:n,name:a,clockrate:o,channels:r,feedbackTypes:l,parameters:d}=i;if(t.push(`a=rtpmap:${n} ${a}/${o}${r?"/"+r:""}`),l&&l.forEach((e=>{const{type:s,subtype:i}=e;t.push(`a=rtcp-fb:${n} ${[s,i].join(" ")}`)})),d){const e=[];Object.getOwnPropertyNames(d).forEach((t=>{e.push(`${t}=${d[t]}`)})),t.push(`a=fmtp:${n} ${e.join(";")}`)}}return t.join("\n")}function Ll(e,t,s,i){let n=[];return s&&s.length>0?s.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:${i} ${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:${i} ${e}${t}`,`a=ssrc:${t} mslabel:${e}${t}`,`a=ssrc:${t} label:${e}${t}`),n.join("\n")}class Il{static generateCandidate(e){if(!e)return null;const{sdpString:t,sdpMLineIndex:s,sdpMid:i,foundation:n,component:a,protocol:o,priority:r,address:l,type:d,relAddress:c,generation:h,tcpType:p,networkId:u,networkCost:g,username:m}=e;if(t)return{candidate:t,sdpMLineIndex:s,sdpMid:i};throw"no sdpString"}static generateOffer(e){return yl()?fl.generateOffer(e):wl()?bl.generateOffer(e):vl.generateOffer(e)}static generateAnswer(e){return yl()?fl.generateAnswer(e):wl()?bl.generateAnswer(e):vl.generateAnswer(e)}}var Ml=s(4081),El=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Pl extends rl.Z{constructor(e){super(),this.log=(0,$.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,w.Z)(this,e),this.createdAt=Date.now(),this.offerReceived=!1,this.offerSent=!1,this.decryptQueue=[],this.candidates=[],this.addEventListener("state",(e=>{this.log("state",$r[e]),e===$r.CLOSED&&this.cleanup()}));const t=this.streamManager=new Ml.Z(ll.iK);t.direction="sendrecv",t.types.push("screencast"),this.isOutgoing||(t.locked=!0,t.canCreateConferenceEntry=!1);let s={"@type":"MediaState",type:"input",lowBattery:!1,muted:!0,screencastState:"inactive",videoRotation:0,videoState:"inactive"};const i=this;s=new Proxy(s,{set:function(e,t,n){return e[t]=n,i.setMediaState(s),i.sendMediaState(),!0}}),this.mediaStates={input:s},this.sendMediaState=dt(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?$r.CLOSED:"connected"===e||ne.IS_SAFARI&&"completed"===e?$r.CONNECTED:$r.CONNECTING}return $r.CONNECTING}get sortIndex(){const e=this.connectionState;let t=1e13*($r.CLOSED-e+1);return t+=2147483647e3-(e===$r.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 s=this.description.findEntry((e=>e.type===t));if(!s)return;return this.elements.get(""+s.recvEntry.source)}}startScreenSharingInternal(){return El(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 El(this,void 0,void 0,(function*(){return this.isSharingVideo&&(yield this.stopVideoSharing()),this.isSharingScreen?this.stopVideoSharing():this.startScreenSharingInternal()}))}startVideoSharingInternal(){return El(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 El(this,void 0,void 0,(function*(){const e=this.getMediaState("input");e.videoState=e.screencastState="inactive";const{streamManager:t,description:s}=this,i=t.inputStream.getVideoTracks()[0];i&&((0,dl.Z)(i),t.appendToConference(s))}))}toggleVideoSharing(){return El(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===$r.CLOSING||e===$r.CLOSED}get description(){var e;return null===(e=this.connectionInstance)||void 0===e?void 0:e.description}setHangUpTimeout(e,t){this.clearHangUpTimeout(),this.hangUpTimeout=qi.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 El(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($r.EXCHANGING_KEYS);const s=this.call;this.requestInputSource(!0,!!s.pFlags.video,!1);const i=s.g_a_hash;this.appCallsManager.generateDh().then((e=>(this.dh={g_a_hash:i,b:e.a,g_b:e.g_a,g_b_hash:e.g_a_hash,p:e.p},this.apiManager.invokeApi("phone.acceptCall",{peer:this.appCallsManager.getCallInput(this.id),protocol:this.protocol,g_b:this.dh.g_b})))).then((e=>{this.appCallsManager.savePhonePhoneCall(e)}))}))}joinCall(){this.log("joinCall"),this.getEmojisFingerprint(),this.overrideConnectionState();const{isOutgoing:e,encryptionKey:t,streamManager:s}=this,i=function(e){const t=[];return e.connections.forEach((e=>{switch(e._){case"phoneConnectionWebrtc":{const{ip:s,ipv6:i,port:n,username:a,password:o}=e,r=[];e.pFlags.turn?(s&&r.push(`turn:${s}:${n}`),i&&r.push(`turn:[${i}]:${n}`)):e.pFlags.stun&&(s&&r.push(`stun:${s}:${n}`),i&&r.push(`stun:[${i}]:${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",i),!i)return;const n=this.connectionInstance=new ol({call:this,streamManager:s,log:this.log.bindPrefix("connection")}),a=n.createPeerConnection(i);a.addEventListener("iceconnectionstatechange",(()=>{const e=this.connectionState;void 0===this.connectedAt&&e===$r.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 gl(e,t),this.decryptor=new gl(!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 El(this,void 0,void 0,(function*(){const t=JSON.stringify(e),s=(new TextEncoder).encode(t),{bytes:i}=yield this.encryptor.encryptRawPacket(s);this.log("sendCallSignalingData",this.id,t),yield this.apiManager.invokeApi("phone.sendSignalingData",{peer:this.appCallsManager.getCallInput(this.id),data:i})}))}sendIceCandidate(e){this.log("sendIceCandidate",e);const{candidate:t,sdpMLineIndex:s}=e;if(0!==s)return;const i=function(e){if(!e||!e.startsWith("candidate:"))return;const t=e;e=e.substr("candidate:".length);const[s,i,n,a,o,r,...l]=e.split(" "),d={sdpString:t,foundation:s,component:i,protocol:n,priority:a,address:{ip:o,port:r}};for(let e=0;e<l.length;e+=2)switch(l[e]){case"typ":d.type=l[e+1];break;case"raddr":d.relAddress||(d.relAddress={}),d.relAddress.ip=l[e+1];break;case"rport":d.relAddress||(d.relAddress={}),d.relAddress.port=l[e+1];break;case"generation":d.generation=l[e+1];break;case"tcptype":d.tcpType=l[e+1];break;case"network-id":d.networkId=l[e+1];break;case"network-cost":d.networkCost=l[e+1];break;case"ufrag":d.username=l[e+1]}return d}(t);this.sendCallSignalingData({"@type":"Candidates",candidates:[i]})}confirmCall(){return El(this,void 0,void 0,(function*(){const{appCallsManager:e,apiManager:t,protocol:s,id:i,call:n}=this,a=this.dh;this.overrideConnectionState($r.EXCHANGING_KEYS);const{key:o,key_fingerprint:r}=yield e.computeKey(n.g_b,a.a,a.p),l=yield t.invokeApi("phone.confirmCall",{peer:e.getCallInput(i),protocol:s,g_a:a.g_a,key_fingerprint:r});this.encryptionKey=o,e.savePhonePhoneCall(l),this.joinCall()}))}getEmojisFingerprint(){return this.emojisFingerprint?this.emojisFingerprint:this.getEmojisFingerprintPromise?this.getEmojisFingerprintPromise:this.getEmojisFingerprintPromise=this.apiManager.invokeCrypto("get-emojis-fingerprint",this.encryptionKey,this.dh.g_a).then((e=>(this.getEmojisFingerprintPromise=void 0,this.emojisFingerprint=e.map((e=>(0,te.zu)(e))))))}unlockStreamManager(){this.connectionInstance.streamManager.locked=!1,this.connectionInstance.appendStreamToConference()}doTheMagic(){return El(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 s=this.description;let i=s.entries.map((e=>e.mid));const n={type:"offer",sdp:s.generateSdp({bundle:i,entries:s.entries.filter((e=>i.includes(e.mid))),isAnswer:!0})};yield e.setRemoteDescription(n),t=yield e.createAnswer(),yield e.setLocalDescription(t);const a=nl((0,al.DV)(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 El(this,void 0,void 0,(function*(){if(!this.isClosing&&(this.discardReason=e,this.log("hangUp",e),this.overrideConnectionState($r.CLOSED),this.connectionInstance&&this.connectionInstance.closeConnectionAndStream(!0),e&&!t)){let t=!1;for(const e in this.mediaStates){const s=this.mediaStates[e];t="active"===s.videoState||"active"===s.screencastState||t}yield this.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,s=t.findIndex((e=>"VP8"===e.name)),i=t[s],n=t.findIndex((e=>{var t;return+(null===(t=e.parameters)||void 0===t?void 0:t.apt)===i.id}));e.payloadTypes=[t[s],t[n]]}))}applyCallSignalingData(e){return El(this,void 0,void 0,(function*(){this.log("applyCallSignalingData",this,e);const{connection:t,description:s}=this.connectionInstance;switch(e["@type"]){case"InitialSetup":{this.log("[sdp] InitialSetup",e),this.filterNotVP8(e),this.setDataToDescription(e);const i=e=>e.map((e=>({_:"groupCallParticipantVideoSourceGroup",semantics:e.semantics,sources:e.ssrcs.map((e=>+e))})));[(0,cl.z_)("audio",+e.audio.ssrc),e.video?(0,cl.z_)("video",i(e.video.ssrcGroups)):void 0,e.screencast?(0,cl.z_)("screencast",i(e.screencast.ssrcGroups)):void 0].filter(Boolean).forEach((e=>{let t=s.getEntryBySource(e.source);if(t)return;const i=s.findFreeSendRecvEntry(e.type,!1);t=new cl.Lp(i.mid,e.type),t.setDirection("sendrecv"),i.recvEntry=t,s.setEntrySource(t,e.sourceGroups||e.source)})),this.createDataChannelEntry();const n=this.offerSent;this.offerSent=!1;let a=s.entries.map((e=>e.mid));const o={type:n?"answer":"offer",sdp:s.generateSdp({bundle:a,entries:s.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=Il.generateCandidate(t);e.sdpMLineIndex=0;const s=new RTCIceCandidate(e);this.candidates.push(s)}yield this.tryToReleaseCandidates();break;default:this.log.error("unrecognized signaling data",e)}}))}tryToReleaseCandidates(){return El(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 El(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 El(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 s of t){const t=yield e.decryptRawPacket(s);if(!t)continue;const i=(new TextDecoder).decode(t);try{const e=JSON.parse(i);this.log("[update] updateNewCallSignalingData",e),this.applyCallSignalingData(e)}catch(e){this.log.error("wrong signaling data",i),this.hangUp("phoneCallDiscardReasonDisconnect")}}}))}onUpdatePhoneCallSignalingData(e){this.decryptQueue.push(e.data),this.processDecryptQueue()}}class Tl{constructor(e,t,s,i,n){this.appGroupCallsManager=e,this.appPeersManager=t,this.appChatsManager=s,this.appAvatarsManager=i,this.appCallsManager=n,this.onState=()=>{this.updateInstance(this.instance)};const o=this.listenerSetter=new B.Z;o.add(a.default)("call_instance",(({instance:e})=>{this.instance||this.updateInstance(e)})),o.add(a.default)("call_accepting",(e=>{this.instance!==e&&this.updateInstance(e)})),o.add(a.default)("group_call_instance",(e=>{this.updateInstance(e)})),o.add(a.default)("group_call_update",(e=>{const t=this.appGroupCallsManager.groupCall;(null==t?void 0:t.id)===e.id&&this.updateInstance(t)})),o.add(a.default)("group_call_amplitude",(({amplitudes:e,type:t})=>{const{weave:s}=this;if(!e.length||!s)return;let i=0;for(let t=0;t<e.length;++t){const{type:s,value:n}=e[t];i=n>i?n:i}s.setAmplitude(i)}))}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 B.Z,this.instanceListenerSetter.add(e)("state",this.onState),e instanceof qr.Z?this.currentDescription=this.groupCallDescription:(this.currentDescription=this.callDescription,this.instanceListenerSetter.add(e)("muted",this.onState)),this.container.classList.toggle("is-call",!(e instanceof qr.Z)));const s=this.instance.isMuted;let i=e instanceof qr.Z?e.state:function(e,t){switch(e){case $r.CLOSING:case $r.CLOSED:return cr.Z.CLOSED;case $r.CONNECTED:return t?cr.Z.MUTED:cr.Z.UNMUTED;default:return cr.Z.CONNECTING}}(e.connectionState,s);const{weave:n}=this;n.componentDidMount();const a=i===cr.Z.CLOSED;(!document.body.classList.contains("is-calling")||t||a)&&(a&&n.setAmplitude(0),(0,Jt.Z)(document.body,"is-calling",!a,250,a?()=>{n.componentWillUnmount(),this.clearCurrentInstance()}:void 0)),a||(n.setCurrentState(i,!0),this.setTitle(e),this.setDescription(e),this.groupCallMicrophoneIconMini.setState(!s))}setDescription(e){return this.currentDescription.update(e)}setTitle(e){if(e instanceof qr.Z)return this.groupCallTitle.update(e);(0,T.Z)(this.center,new St.Z({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 s=document.createElement("div");s.classList.add("topbar-call-left");const i=this.groupCallMicrophoneIconMini=new Yr,n=N();n.append(i.container),s.append(n);const a=(0,ms.Z)((()=>{this.instance.toggleMuted()}),600,!0);(0,l.fc)(n,(e=>{(0,d.d)(e),a()}),{listenerSetter:e});const o=this.center=document.createElement("div");o.classList.add("topbar-call-center"),this.groupCallTitle=new Ar(o),this.groupCallDescription=new xr(s),this.callDescription=new Qr(s);const r=document.createElement("div");r.classList.add("topbar-call-right");const c=N("endcall_filled");r.append(c),(0,l.fc)(c,(e=>{(0,d.d)(e);const{instance:t}=this;t&&(t instanceof qr.Z?t.hangUp():t.hangUp("phoneCallDiscardReasonHangup"))}),{listenerSetter:e}),(0,l.fc)(t,(()=>{if(this.instance instanceof qr.Z){if(pt.Z.getPopups(Kr).length)return;new Kr({appGroupCallsManager:this.appGroupCallsManager,appPeersManager:this.appPeersManager,appChatsManager:this.appChatsManager}).show()}else if(this.instance instanceof Pl){if(pt.Z.getPopups(tl).find((e=>e.getCallInstance()===this.instance)))return;new tl({appCallsManager:this.appCallsManager,appAvatarsManager:this.appAvatarsManager,appPeersManager:this.appPeersManager,instance:this.instance}).show()}}),{listenerSetter:e}),t.append(s,o,r);const h=this.weave=new ur,p=h.render("topbar-call-weave");t.prepend(p),document.getElementById("column-center").prepend(t),h.componentDidMount()}}var kl=s(5916),xl=s(4484),Al=s(3442),_l=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const Zl=45e3,Dl=new class{constructor(){this.log=(0,$.kg)("CALLS"),this.tempId=0,this.calls=new Map,this.instances=new Map,this.sortedInstances=[],Ea&&(a.default.addMultipleEventsListeners({updatePhoneCall:e=>_l(this,void 0,void 0,(function*(){var t;const s=this.saveCall(e.phone_call);let i=this.instances.get(s.id);switch(s._){case"phoneCallDiscarded":i&&i.hangUp(null===(t=s.reason)||void 0===t?void 0:t._,!0);break;case"phoneCallAccepted":i&&i.confirmCall();break;case"phoneCallRequested":i||(i=this.createCallInstance({isOutgoing:!1,interlocutorUserId:s.admin_id}),i.overrideConnectionState($r.PENDING),i.setPhoneCall(s),i.setHangUpTimeout(Zl,"phoneCallDiscardReasonMissed"));break;case"phoneCall":{if(!i||i.encryptionKey)break;const e=i.dh.g_a=s.g_a_or_b,t=i.dh,n=yield ct.Z.invokeCrypto("sha256",e);if(!(0,xl.Z)(t.g_a_hash,n)){this.log.error("Incorrect g_a_hash",t.g_a_hash,n);break}const{key:a,key_fingerprint:o}=yield this.computeKey(e,t.b,t.p);if(s.key_fingerprint!==o){this.log.error("Incorrect key fingerprint",s.key_fingerprint,o);break}i.encryptionKey=a,i.joinCall();break}}})),updatePhoneCallSignalingData:e=>{const t=this.instances.get(e.phone_call_id);(null==t?void 0:t.id)===e.phone_call_id&&t.onUpdatePhoneCallSignalingData(e)}}),this.audioAsset=new kl.Z(["call_busy.mp3","call_connect.mp3","call_end.mp3","call_incoming.mp3","call_outgoing.mp3","voip_failed.mp3"]))}get currentCall(){return this.sortedInstances[0]}getCallByUserId(e){for(const[t,s]of this.instances)if(s.interlocutorUserId===e)return s}computeKey(e,t,s){return _l(this,void 0,void 0,(function*(){return ct.Z.invokeCrypto("compute-dh-key",e,t,s)}))}saveCall(e){const t="phoneCallDiscarded"===e._,s=this.calls.get(e.id);return s?((0,Al.Z)(s,e),t&&this.calls.delete(e.id),e=s):t||this.calls.set(e.id,e),e}getCall(e){return this.calls.get(e)}getCallInput(e){const t=this.getCall(e);return{_:"inputPhoneCall",id:t.id,access_hash:t.access_hash}}createCallInstance(e){const t=new Pl(Object.assign({appCallsManager:this,apiManager:ct.Z,apiUpdatesManager:ni.Z},e));return t.addEventListener("state",(e=>{const s=this.currentCall;e===$r.CLOSED?(this.instances.delete(t.id),(0,z.Z)(this.sortedInstances,t)):(0,Ds.Z)(this.sortedInstances,t,"sortIndex"),e===$r.EXCHANGING_KEYS&&(t.wasTryingToJoin=!0);const i=void 0!==t.connectedAt;e===$r.EXCHANGING_KEYS||e===$r.CONNECTING&&i?t.setHangUpTimeout(Zl,"phoneCallDiscardReasonDisconnect"):t.clearHangUpTimeout(),s!==t&&s||(e===$r.CLOSED?t.isOutgoing||t.wasTryingToJoin?t.wasTryingToJoin&&!i?this.audioAsset.playSound("voip_failed.mp3"):this.audioAsset.playSound("phoneCallDiscardReasonBusy"===t.discardReason?"call_busy.mp3":"call_end.mp3"):this.audioAsset.stopSound():e===$r.PENDING?this.audioAsset.playSound(t.isOutgoing?"call_outgoing.mp3":"call_incoming.mp3",!0):e===$r.EXCHANGING_KEYS?this.audioAsset.playSoundIfDifferent("call_connect.mp3"):e===$r.CONNECTING?t.duration&&this.audioAsset.playSound("voip_connecting.mp3",!0):this.audioAsset.stopSound())})),t.addEventListener("id",((e,s)=>{void 0!==s&&this.instances.delete(s);const i=!!this.currentCall;this.instances.set(e,t),void 0===s&&a.default.dispatchEvent("call_instance",{instance:t,hasCurrent:i})})),t}savePhonePhoneCall(e){return E.Z.saveApiUsers(e.users),this.saveCall(e.phone_call)}generateDh(){return ct.Z.invokeApi("messages.getDhConfig",{version:0,random_length:256}).then((e=>_l(this,void 0,void 0,(function*(){return ct.Z.invokeCrypto("generate-dh",e)}))))}startCallInternal(e,t){this.log("p2pStartCallInternal",e,t);const s=n.default.getCachedFullUser(e);if(!s)return;const{video_calls_available:i}=s.pFlags,a=this.createCallInstance({isOutgoing:!0,interlocutorUserId:e});a.requestInputSource(!0,!(!t||!i),!1),a.overrideConnectionState($r.REQUESTING),a.setPhoneCall({_:"phoneCallWaiting",access_hash:"",admin_id:Re.NM,date:(0,qo.Z)(!0),id:--this.tempId,participant_id:e,protocol:a.protocol,pFlags:{video:t||void 0}}),this.generateDh().then((s=>(a.dh=s,ct.Z.invokeApi("phone.requestCall",{user_id:E.Z.getUserInput(e),protocol:a.protocol,video:t&&i,random_id:(0,it.d)(32),g_a_hash:a.dh.g_a_hash})))).then((e=>{const t=this.savePhonePhoneCall(e);a.overrideConnectionState($r.PENDING),a.setPhoneCall(t),a.setHangUpTimeout(Zl,"phoneCallDiscardReasonHangup")}))}discardCall(e,t,s,i){return _l(this,void 0,void 0,(function*(){if(!this.getCall(e))return;const n=yield ct.Z.invokeApi("phone.discardCall",{video:i,peer:this.getCallInput(e),duration:t,reason:{_:s},connection_id:"0"});ni.Z.processUpdateMessage(n)}))}};re.GO&&(re.GO.appCallsManager=Dl);const Fl=Dl;var Rl=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const Bl="chat",Ul=ce.IS_TOUCH_SUPPORTED?"touchstart":"mousemove",Nl=new class{constructor(){this.columnEl=document.getElementById("column-center"),this.offline=!1,this.updateStatusInterval=0,this.setPeerPromise=null,this.tabId=-1,this.chats=[],this.onHashChange=()=>{const e=location.hash,t=e.split("?"),s=this.parseUriParams(e,t);if(this.log("hashchange",e,t[0],s),s.tgaddr){F.Z.replaceState();const{onclick:e}=Q.Z.wrapUrl(s.tgaddr);if(e){const t=document.createElement("a");t.href=s.tgaddr,window[e](t)}}else if("#/im"===t[0]){const e=s.p;let t=void 0!==s.post?f.Z.generateMessageId(+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",a.default.settings.messagesTextSize+"px"),document.body.classList.toggle("animation-level-0",!a.default.settings.animationsEnabled),document.body.classList.toggle("animation-level-1",!1),document.body.classList.toggle("animation-level-2",a.default.settings.animationsEnabled),this.chatsSelectTabDebounced=dt((()=>{const e=this.chat.topbar;e.pinnedMessage&&e.pinnedMessage.setCorrectIndex(0),ct.Z.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)}),a.default.settings.animationsEnabled?250:0,!1,!0),ae.Z.setLoop(a.default.settings.stickers.loop),I.Z.checkAnimations(!1);for(const e of this.chats)e.setAutoDownloadMedia();k.default.setTimeFormat(a.default.settings.timeFormat),this.toggleChatGradientAnimation(this.chat)},this.onDocumentPaste=(e,t)=>{const s=ro();if(this.canDrag()||s){if(e instanceof DragEvent){const t=e.dataTransfer.types;(t.contains?t.contains("Files"):t.indexOf("Files")>=0)&&(0,d.d)(e)}(0,he.nD)(e).then((e=>{if(e.length){if(s)return void s.addFiles(e);const i=this.chat.input;i.willAttachType=t||(g.has(e[0].type)?"media":"document"),new lo(this.chat,e,i.willAttachType)}}))}},ni.Z.attach(),Ft.Z.start(),this.log=(0,$.kg)("IM",$.v9.Log|$.v9.Warn|$.v9.Debug|$.v9.Error),this.backgroundPromises={},M.STATE_INIT.settings.themes.forEach((e=>{if(e.background.slug){const t="assets/img/"+e.background.slug+".svg";this.backgroundPromises[e.background.slug]=Promise.resolve(t)}})),this.selectTab(0),window.addEventListener("blur",(()=>{I.Z.checkAnimations(!0),this.offline=a.default.idle.isIDLE=!0,this.updateStatus(),clearInterval(this.updateStatusInterval),a.default.dispatchEvent("idle",a.default.idle.isIDLE),window.addEventListener("focus",(()=>{this.offline=a.default.idle.isIDLE=!1,this.updateStatus(),this.updateStatusInterval=window.setInterval((()=>this.updateStatus()),5e4),I.Z.checkAnimations(!1),a.default.dispatchEvent("idle",a.default.idle.isIDLE)}),{once:!0})})),window.addEventListener(Ul,(()=>{this.updateStatusInterval=window.setInterval((()=>this.updateStatus()),5e4),this.updateStatus(),this.offline=a.default.idle.isIDLE=!1,a.default.dispatchEvent("idle",a.default.idle.isIDLE)}),{once:!0,passive:!0}),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(v.ZP.activeScreen),this.columnEl.append(this.chatsContainer),this.createNewChat(),this.chatsSelectTab(this.chat.container),F.Z.onHashChange=this.onHashChange,this.setSettings(),a.default.addEventListener("settings_updated",this.setSettings),(0,xs.ZP)((()=>{I.Z.setOnlyOnePlayableGroup("lock"),I.Z.checkAnimations(!0)}),(()=>{I.Z.setOnlyOnePlayableGroup(""),I.Z.checkAnimations(!1)})),this.applyCurrentTheme(),v.ZP.addEventListener("changeScreen",((e,t)=>{document.body.classList.contains(Ln)&&document.body.classList.contains($t)&&Yt.toggleSidebar(!1),this.appendEmojiAnimationContainer(t)}));const e=dt((()=>{this.setBackground(this.lastBackgroundUrl,!1)}),200,!1,!0);v.ZP.addEventListener("resize",(()=>{e()})),a.default.addEventListener("history_focus",(e=>{let{peerId:t,threadId:s,mid:i,startParam:n}=e;s&&(s=f.Z.generateMessageId(s)),i&&(i=f.Z.generateMessageId(i)),this.setInnerPeer({peerId:t,lastMsgId:i,type:s?"discussion":void 0,threadId:s,startParam:n})})),a.default.addEventListener("peer_changing",(e=>{this.saveChatPosition(e)})),a.default.addEventListener("theme_change",(()=>{this.applyCurrentTheme()})),a.default.addEventListener("choosing_sticker",(e=>{this.setChoosingStickerTyping(!e)})),a.default.addEventListener("peer_typings",(({peerId:e,typings:t})=>{var s;const n=this.chat;if(!n||n.peerId!==e||a.default.overlaysActive||v.ZP.activeScreen===v._G.mobile&&1!==this.tabId)return;const o=t.find((e=>"sendMessageEmojiInteraction"===e.action._));if("sendMessageEmojiInteraction"===(null===(s=null==o?void 0:o.action)||void 0===s?void 0:s._)){const t=o.action,s=n.bubbles.bubbles[f.Z.generateMessageId(o.action.msg_id)];if(s&&s.classList.contains("emoji-big")&&s.classList.contains("sticker")&&Pa(s,n.bubbles.scrollable.container)){const n=s.querySelector(".media-sticker-wrapper:not(.bubble-hover-reaction-sticker):not(.reaction-sticker)");JSON.parse(t.interaction.data).a.forEach((e=>{setTimeout((()=>{(0,l.tH)(n)}),1e3*e.t)})),i.Z.setTyping(e,{_:"sendMessageEmojiInteractionSeen",emoticon:t.emoticon})}}})),a.default.addEventListener("instance_deactivated",(()=>{const e=new pt.Z("popup-instance-deactivated",void 0,{overlayClosable:!0}),t=document.createElement("div");t.classList.add("instance-deactivated-container"),e.container.replaceWith(t);const s=document.createElement("div");s.classList.add("header"),s.append((0,k.i18n)("Deactivated.Title"));const i=document.createElement("div");i.classList.add("subtitle"),i.append((0,k.i18n)("Deactivated.Subtitle")),t.append(s,i),document.body.classList.add("deactivated"),e.addEventListener("close",(()=>{document.body.classList.add("deactivated-backwards"),rr.Z.activateInstance(),setTimeout((()=>{document.body.classList.remove("deactivated","deactivated-backwards")}),333)})),e.show()})),a.default.addEventListener("chat_changing",(({to:e})=>{this.toggleChatGradientAnimation(e)})),Qn.Z.get("chatPositions").then((e=>{Qn.Z.setToCache("chatPositions",e||{})})),(Ea||Wo)&&(this.topbarCall=new Tl(dr.Z,o.Z,j.Z,c.Z,Fl)),Ea&&a.default.addEventListener("call_instance",(({instance:e})=>{const t=new tl({appCallsManager:Fl,appAvatarsManager:c.Z,appPeersManager:o.Z,instance:e});e.addEventListener("acceptCallOverride",(()=>this.discardCurrentCall(e.interlocutorUserId.toPeerId(),void 0,e).then((()=>(a.default.dispatchEvent("call_accepting",e),!0))).catch((()=>!1)))),t.addEventListener("close",(()=>{const t=Fl.currentCall;t&&t!==e&&!e.wasTryingToJoin&&e.hangUp("phoneCallDiscardReasonBusy")}),{once:!0}),t.show()})),rr.Z.activateInstance();const t=()=>{lr.default.setAuthorized(!0)};setInterval(t,ie.s2),t(),this.addAnchorListener({name:"showMaskedAlert",callback:(e,t)=>{const s=t.href,i=t.cloneNode(!0);i.className="anchor-url",i.innerText=s,i.removeAttribute("onclick"),new gt("popup-masked-url",{titleLangKey:"OpenUrlTitle",descriptionLangKey:"OpenUrlAlert2",descriptionLangArgs:[i],buttons:[{langKey:"Open",callback:()=>{i.click()}}]}).show()}}),this.addAnchorListener({name:"execBotCommand",callback:({uriParams:e})=>{const{command:t,bot:s}=e;i.Z.sendText(this.chat.peerId,"/"+t+(s?"@"+s:""))}}),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={_:Ta.STICKER_SET,set:e[1]};this.processInternalLink(t)}}),this.addAnchorListener({name:"joinchat",callback:({pathnameParams:e})=>{const t={_:Ta.JOIN_CHAT,invite:e[1]||decodeURIComponent(e[0]).slice(1)};this.processInternalLink(t)}}),Wo&&this.addAnchorListener({name:"voicechat",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(Ta.VOICE_CHAT,e);this.processInternalLink(t)}}),this.addAnchorListener({name:"im",callback:({pathnameParams:e,uriParams:t})=>Rl(this,void 0,void 0,(function*(){let s;s="c"===e[0]?{_:Ta.PRIVATE_POST,channel:e[1],post:e[2],thread:"thread"in t&&t.thread,comment:t.comment}:{_:Ta.MESSAGE,domain:e[0],post:e[1],comment:t.comment,start:"start"in t?t.start:void 0},this.processInternalLink(s)}))}),this.addAnchorListener({name:"resolve",protocol:"tg",callback:({uriParams:e})=>{let t;"telegrampassport"===e.domain||(t=this.makeLink(Ta.MESSAGE,e)),this.processInternalLink(t)}}),this.addAnchorListener({name:"privatepost",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(Ta.PRIVATE_POST,e);this.processInternalLink(t)}}),this.addAnchorListener({name:"addstickers",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(Ta.STICKER_SET,e);this.processInternalLink(t)}}),["joinchat","join"].forEach((e=>{this.addAnchorListener({name:e,protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(Ta.JOIN_CHAT,e);this.processInternalLink(t)}})})),this.onHashChange(),this.attachKeydownListener()}get myId(){return a.default.myId}get chat(){return this.chats[this.chats.length-1]}toggleChatGradientAnimation(e){this.chats.forEach((t=>{t.gradientRenderer&&t.gradientRenderer.scrollAnimate(a.default.settings.animationsEnabled&&t===e)}))}appendEmojiAnimationContainer(e){const t=e===v._G.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 s;const n=t.key;if(a.default.isOverlayActive||e.has(n))return;const o=t.target,r=this.chat;if("KeyC"!==t.code||!t.ctrlKey&&!t.metaKey||"INPUT"===o.tagName){if(!t.altKey||"ArrowUp"!==n&&"ArrowDown"!==n){if("ArrowUp"===n){if(r.input.editMsgId||!r.input.isInputEmpty())return;{const e=i.Z.getHistoryStorage(r.peerId,r.threadId).history.slice;if(e.isEnd(zn.D.Bottom)&&e.length){let s;for(const t of e){const e=r.getMessage(t);if((this.myId===r.peerId?e.fromId===this.myId:e.pFlags.out)&&i.Z.canEditMessage(r.getMessage(t),"text")){s=t;break}}s&&(r.input.initMessageEditing(s),(0,d.d)(t))}}}else if("ArrowDown"===n)return}else{const e=i.Z.dialogsStorage.getFolderDialogs(a.default.filterId,!0);let t;if(a.default.peerId){const s=e.findIndex((e=>e.peerId===a.default.peerId));-1!==s&&(t=e["ArrowUp"===n?s-1:s+1])}else"ArrowDown"===n&&(t=e[0]);t&&this.setPeer({peerId:t.peerId})}if((null===(s=null==r?void 0:r.input)||void 0===s?void 0:s.messageInput)&&t.target!==r.input.messageInput&&"INPUT"!==o.tagName&&!o.hasAttribute("contenteditable")&&!ce.IS_TOUCH_SUPPORTED&&(!v.ZP.isMobile||1===this.tabId)&&!r.selection.isSelecting&&!r.input.recording){r.input.messageInput.focus(),(0,no.Z)(r.input.messageInput);const e=new KeyboardEvent(t.type,t);r.input.messageInput.dispatchEvent(e)}}}))}makeLink(e,t){return Object.assign({_:e},t)}processInternalLink(e){return Rl(this,void 0,void 0,(function*(){switch(null==e?void 0:e._){case Ta.MESSAGE:{const t=e.post?f.Z.generateMessageId(+e.post):void 0,s=e.comment?f.Z.generateMessageId(+e.comment):void 0;this.openUsername({userName:e.domain,lastMsgId:t,commentId:s,startParam:e.start});break}case Ta.PRIVATE_POST:{const t=e.channel.toChatId(),s=t.toPeerId(!0);if(j.Z.getChat(t).deleted)try{yield j.Z.resolveChannel(t)}catch(e){throw lt({langPackKey:"LinkNotFound"}),e}const i=f.Z.generateMessageId(+e.post),n=e.thread?f.Z.generateMessageId(+e.thread):void 0;n?this.openThread(s,i,n):this.setInnerPeer({peerId:s,lastMsgId:i,threadId:n});break}case Ta.STICKER_SET:new Ki({id:e.set}).show();break;case Ta.JOIN_CHAT:ct.Z.invokeApi("messages.checkChatInvite",{hash:e.invite}).then((t=>{t.chat&&j.Z.saveApiChat(t.chat,!0),"chatInviteAlready"!==t._&&"chatInvitePeek"!==t._?new xa(e.invite,t).show():this.setInnerPeer({peerId:t.chat.id.toPeerId(!0)})}),(e=>{"INVITE_HASH_EXPIRED"===e.type&&rt((0,k.i18n)("InviteExpired"))}));break;case Ta.VOICE_CHAT:Wo&&this.joinGroupCall(e.chat_id.toPeerId(!0),e.id);break;default:this.log.warn("Not supported internal link:",e)}}))}addAnchorListener(e){window[(e.protocol?e.protocol+"_":"")+e.name]=t=>{(0,d.d)(null);const s=t.href;let i,n;e.noPathnameParams||(i=new URL(t.href).pathname.split("/").slice(1)),e.noUriParams||(n=this.parseUriParams(s));const a=e.callback({pathnameParams:i,uriParams:n},t);return void 0===a&&a}}parseUriParams(e,t=e.split("?")){const s={};return t[1]?(t[1].split("&").forEach((e=>{s[e.split("=")[0]]=decodeURIComponent(e.split("=")[1])})),s):s}openUsername(e){const{userName:t,lastMsgId:s,threadId:i,commentId:n,startParam:a}=e;return E.Z.resolveUsername(t).then((e=>{const t="user"===e._,o=e.id.toPeerId(!t);return i?this.openThread(o,s,i):n?this.openComment(o,s,n):this.setInnerPeer({peerId:o,lastMsgId:s,startParam:a})}),(e=>{"USERNAME_NOT_OCCUPIED"===e.type?lt({langPackKey:"NoUsernameFound"}):"USERNAME_INVALID"===e.type&&lt({langPackKey:"Alert.UserDoesntExists"})}))}openThread(e,t,s){return i.Z.wrapSingleMessage(e,s).then((()=>{const n=i.Z.getMessageByPeer(e,s);return"messageEmpty"===n._?t=void 0:i.Z.generateThreadServiceStartMessage(n),this.setInnerPeer({peerId:e,lastMsgId:t,threadId:s,type:"discussion"})}))}openComment(e,t,s){return i.Z.getDiscussionMessage(e,t).then((e=>this.openThread(e.peerId,s,e.mid)))}callUser(e,t){return Rl(this,void 0,void 0,(function*(){Fl.getCallByUserId(e)||((yield n.default.getProfile(e)).pFlags.phone_calls_private?on({descriptionLangKey:"Call.PrivacyErrorMessage",descriptionLangArgs:[new St.Z({peerId:e.toPeerId()}).element],button:{langKey:"OK",isCancel:!0}}):(yield this.discardCurrentCall(e.toPeerId()),Fl.startCallInternal(e,"video"===t)))}))}discardCurrentCall(e,t,s){return dr.Z.groupCall&&dr.Z.groupCall!==t?this.discardGroupCallConfirmation(e):Fl.currentCall&&Fl.currentCall!==s?this.discardCallConfirmation(e):Promise.resolve()}discardCallConfirmation(e){return Rl(this,void 0,void 0,(function*(){const t=Fl.currentCall;t&&(yield on({titleLangKey:"Call.Confirm.Discard.Call.Header",descriptionLangKey:e.isUser()?"Call.Confirm.Discard.Call.ToCall.Text":"Call.Confirm.Discard.Call.ToVoice.Text",descriptionLangArgs:[new St.Z({peerId:t.interlocutorUserId.toPeerId(!1)}).element,new St.Z({peerId:e}).element],button:{langKey:"OK"}}),t.isClosing||(yield t.hangUp("phoneCallDiscardReasonDisconnect")))}))}discardGroupCallConfirmation(e){return Rl(this,void 0,void 0,(function*(){const t=dr.Z.groupCall;t&&(yield on({titleLangKey:"Call.Confirm.Discard.Voice.Header",descriptionLangKey:e.isUser()?"Call.Confirm.Discard.Voice.ToCall.Text":"Call.Confirm.Discard.Voice.ToVoice.Text",descriptionLangArgs:[new St.Z({peerId:t.chatId.toPeerId(!0)}).element,new St.Z({peerId:e}).element],button:{langKey:"OK"}}),dr.Z.groupCall===t&&(yield t.hangUp()))}))}joinGroupCall(e,t){return Rl(this,void 0,void 0,(function*(){const s=e.toChatId(),i=j.Z.hasRights(s,"manage_call");if(t&&"groupCallDiscarded"===(yield dr.Z.getGroupCallFull(t))._){if(!i)return void lt({langPackKey:"VoiceChat.Chat.Ended"});yield on({descriptionLangKey:"VoiceChat.Chat.StartNew",button:{langKey:"VoiceChat.Chat.StartNew.OK"}})}yield this.discardCurrentCall(e),(()=>{Rl(this,void 0,void 0,(function*(){const e=yield n.default.getChatFull(s);let t;if(e.call)t=dr.Z.saveGroupCall(e.call,s);else{if(!i)return;t=yield dr.Z.createGroupCall(s)}dr.Z.joinGroupCall(s,t.id,!0,!1)}))})()}))}setCurrentBackground(e=!1){const t=a.default.getTheme();if(t.background.slug){const s=M.AppStateManager.STATE_INIT.settings.themes.find((e=>e.name===t.name));return this.getBackground(t.background.slug).then((t=>this.setBackground(t,e)),(()=>(t.background=(0,pe.Z)(s.background),this.setBackground("",!0))))}return this.setBackground("",e)}getBackground(e){return this.backgroundPromises[e]?this.backgroundPromises[e]:this.backgroundPromises[e]=le.Z.cacheStorage.getFile("backgrounds/"+e).then((e=>URL.createObjectURL(e)))}setBackground(e,t=!0){this.lastBackgroundUrl=e;const s=this.chats.map((t=>t.setBackground(e)));return s[s.length-1].then((()=>{t&&a.default.dispatchEvent("background_change")}))}saveChatPosition(e){if(!["chat","discussion"].includes(e.type)||!e.peerId)return;const t=e.bubbles,s=t.scrollable.scrollTop,i=e.peerId+(e.threadId?"_"+e.threadId:""),n=Qn.Z.getFromCache("chatPositions");if(t.scrollable.getDistanceToEnd()<=16&&t.scrollable.loadedAll.bottom||!Object.keys(t.bubbles).length)delete n[i],this.log("deleted chat position");else{const e={mids:(0,Xs.Z)(t.bubbles,"desc"),top:s};n[i]=e,this.log("saved chat position:",e)}Qn.Z.set({chatPositions:n},!0)}getChatSavedPosition(e){if(!["chat","discussion"].includes(e.type)||!e.peerId)return;const t=e.peerId+(e.threadId?"_"+e.threadId:""),s=Qn.Z.getFromCache("chatPositions");return s&&s[t]}applyHighlightningColor(){let e;const t=a.default.getTheme();t.background.highlightningColor?(e=t.background.highlightningColor,document.documentElement.style.setProperty("--message-highlightning-color",e)):document.documentElement.style.removeProperty("--message-highlightning-color"),!ce.IS_TOUCH_SUPPORTED&&e&&(a.default.themeColor=function(e){return function(e){return Ui(function(e){const t=e.slice(5,-1).split(", "),s=+t.pop(),i=t.map((e=>e.endsWith("%")?+e.slice(0,-1):+e));return Fi(i[0],i[1],i[2],s)}(e))}(e).slice(0,-2)}(e))}applyCurrentTheme(e,t,s){return this.applyHighlightningColor(),a.default.setTheme(),t&&(this.backgroundPromises[e]=Promise.resolve(t)),this.setCurrentBackground(void 0===s?!!e:s)}chatsSelectTab(e,t){if(this.prevTab!==e){if(!1===t&&this.prevTab&&or([e,this.prevTab].filter(Boolean)),this.prevTab){this.prevTab.classList.remove("active"),this.chatsSelectTabDebounced(),a.default.settings.animationsEnabled&&!1!==t&&(0,xs.YW)((0,Kn.w)(400),400);const s=(0,_s.Z)(this.prevTab);(0,_s.Z)(e)>s&&F.Z.pushItem({type:"chat",onPop:e=>{this.setPeer({},e),(0,Gs.Z)()}})}e.classList.add("active"),this.prevTab=e}}init(){document.addEventListener("paste",this.onDocumentPaste,!0),ce.IS_TOUCH_SUPPORTED||this.attachDragAndDropListeners(),this.markupTooltip=new sr(this),this.markupTooltip.handleSelection()}attachDragAndDropListeners(){const e=[],t=[];let s=!1;const i=(r,l)=>Rl(this,void 0,void 0,(function*(){if(l===s)return;const d=r.dataTransfer.types,c=d.contains?d.contains("Files"):d.indexOf("Files")>=0,h=ro();if(!c||!this.canDrag()&&!h)return void(n=0);const p=h?o:a,u=h?t:e;if(l&&!u.length){const e=yield(0,he.nD)(r,!0),t=c&&!e.length,s=e.filter((e=>g.has(e))).length;this.log("drag files",e),h?(h.appendDrops(p),(e.length||t)&&u.push(new ar(p,{header:"Preview.Dragging.AddItems",headerArgs:[e.length],onDrop:e=>{i(e,!1),Nl.log("drop",e),Nl.onDocumentPaste(e,"document")}}))):((e.length||t)&&u.push(new ar(p,{icon:"dragfiles",header:"Chat.DropTitle",subtitle:"Chat.DropAsFilesDesc",onDrop:e=>{i(e,!1),Nl.log("drop",e),Nl.onDocumentPaste(e,"document")}})),(s||t)&&u.push(new ar(p,{icon:"dragmedia",header:"Chat.DropTitle",subtitle:"Chat.DropQuickDesc",onDrop:e=>{i(e,!1),Nl.log("drop",e),Nl.onDocumentPaste(e,"media")}})),this.chat.container.append(p))}(0,Jt.Z)(p,"is-visible",l,200,(()=>{l||(u.forEach((e=>{e.destroy()})),u.length=0)})),l?u.forEach((e=>{e.setPath()})):n=0,document.body.classList.toggle("is-dragging",l),s=l}));let n=0;document.body.addEventListener("dragenter",(e=>{n++})),document.body.addEventListener("dragover",(e=>{i(e,!0),(0,d.d)(e)})),document.body.addEventListener("dragleave",(e=>{n--,0===n&&i(e,!1)}));const a=document.createElement("div");a.classList.add("drops-container");const o=a.cloneNode(!0)}canDrag(){const e=this.chat;return!(!(null==e?void 0:e.peerId)||a.default.isOverlayActive||!e.canSend("send_media"))}selectTab(e,t){!1===t&&or([xn.sidebarEl,this.columnEl,Yt.sidebarEl]),document.body.classList.toggle(Ln,0===e);const s=this.tabId;this.log("selectTab",e,s);let i=a.default.settings.animationsEnabled?(0,De.d1)():Promise.resolve();if(-1!==s&&s!==e&&a.default.settings.animationsEnabled&&!1!==t){const e=100+(v.ZP.isMobile?250:200);i=(0,Kn.w)(e),(0,xs.YW)(i,e)}return this.tabId=e,(0,Gs.Z)(),v.ZP.isMobile&&2===s&&e<2&&document.body.classList.remove($t),-1!==s&&e>s&&(e<2||!F.Z.findItemByType("im"))&&F.Z.pushItem({type:"im",onPop:e=>{this.setPeer({},e)}}),a.default.dispatchEvent("im_tab_change",e),i}updateStatus(){return this.myId?(E.Z.setUserStatus(this.myId,this.offline),ct.Z.invokeApiSingle("account.updateStatus",{offline:this.offline})):Promise.resolve()}createNewChat(){const e=new er(this,j.Z,L.Z,ga,i.Z,o.Z,r.Z,n.default,ds.Z,E.Z,tr.Z,Qe.Z,ct.Z,xi.Z,Ye.Z,Qn.Z,Ft.Z,ea,f.Z,dr.Z,_t.Z);return this.chats.length&&e.setBackground(this.lastBackgroundUrl,!0),this.chats.push(e),e}spliceChats(e,t=!0,s,i){if(e>=this.chats.length)return;const n=this.chat;this.chats.length>1&&t&&a.default.dispatchEvent("peer_changing",this.chat),i||(i=this.chats.splice(e,this.chats.length-e)),a.default.dispatchEvent("chat_changing",{from:n,to:this.chat});for(let e=0;e<i.length-1;++e)F.Z.removeByType("chat",!0);if(i.length>1&&i.slice(0,-1).forEach((e=>{e.container.remove()})),this.chatsSelectTab(this.chat.container,s),t){a.default.dispatchEvent("peer_changed",this.chat.peerId);const e=Yt.getTab(Yo);e&&e.close(),Yt.sharedMediaTab.setPeer(this.chat.peerId,this.chat.threadId)&&(Yt.sharedMediaTab.loadSidebarMedia(!0),Yt.sharedMediaTab.fillProfileElements())}i.forEach((e=>{e.beforeDestroy()})),setTimeout((()=>{i.forEach((e=>{e.destroy()}))}),350)}setPeer(e={},t){var s;this.init&&(this.init(),this.init=null),null!==(s=e.peerId)&&void 0!==s||(e.peerId=Re.NM);const{peerId:i,lastMsgId:n}=e,a=this.chat,o=this.chats.indexOf(a);if(i){if(o>0&&a.peerId&&a.peerId!==i){const t=this.chats.splice(1,this.chats.length-1);if(this.chat.peerId===i)return void this.spliceChats(0,!0,!0,t);{const s=this.setPeer(e);return this.spliceChats(0,!1,!1,t),s}}}else{if(o>0)return void this.spliceChats(o,void 0,t);if(v.ZP.activeScreen===v._G.medium)return void this.selectTab(+!this.tabId,t)}if(i===a.peerId&&v.ZP.activeScreen<=v._G.medium&&document.body.classList.contains(Ln))return this.selectTab(1,t),!1;if(i||v.ZP.activeScreen!==v._G.mobile){const s=a.setPeer(i,n,e.startParam),o=(null==s?void 0:s.cached)?s.promise:Promise.resolve();i&&Promise.all([o,a.setBackgroundPromise]).then((()=>{setTimeout((()=>{setTimeout((()=>{this.chatsSelectTab(this.chat.container)}),0),this.selectTab(1,t)}),0)}))}return i?void 0:(this.selectTab(0,t),!1)}setInnerPeer(e){var t;const{peerId:s}=e;if(s===Re.NM||!s)return;const i=null!==(t=e.type)&&void 0!==t?t:e.type="chat",n=this.chats.findIndex((e=>e.peerId===s&&e.type===i));if(-1!==n)return this.spliceChats(n+1),this.setPeer(e);const o=this.chat;let r=o;return o.inited&&(r=this.createNewChat()),i&&(r.setType(i),e.threadId&&(r.threadId=e.threadId)),a.default.dispatchEvent("chat_changing",{from:o,to:r}),this.setPeer(e)}openScheduled(e){this.setInnerPeer({peerId:e,type:"scheduled"})}getTypingElement(e){const t=document.createElement("span");let s="peer-typing";switch(t.classList.add(s),t.dataset.action=e._,e._){case"sendMessageTypingAction":s+="-text";for(let e=0;e<3;++e){const e=document.createElement("span");e.className=s+"-dot",t.append(e)}break;case"sendMessageUploadAudioAction":case"sendMessageUploadDocumentAction":case"sendMessageUploadRoundAction":case"sendMessageUploadVideoAction":case"sendMessageUploadPhotoAction":s+="-upload";break;case"sendMessageRecordAudioAction":case"sendMessageRecordRoundAction":case"sendMessageRecordVideoAction":s+="-record";break;case"sendMessageEmojiInteractionSeen":case"sendMessageChooseStickerAction":s+="-choosing-sticker";for(let e=0;e<2;++e){const e=document.createElement("div");e.className=s+"-eye",t.append(e)}}return t.classList.add(s),t}getPeerTyping(e,t){if(!E.Z.isBot(e)){const s=n.default.getPeerTypings(e);if(!s||!s.length)return;const i=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=e.isUser()?a.private:s.length>1?a.multi:a.chat;let r=i.action;if(s.length>1){const e={};s.forEach((t=>{const s=t.action._;void 0===e[s]&&(e[s]=0),++e[s]})),Object.keys(e).length>1&&(r={_:"sendMessageTypingAction"})}const l=o[r._];if(!l)return;t||(t=document.createElement("span")).classList.add("online","peer-typing-container"),t.classList.toggle("peer-typing-flex","sendMessageChooseStickerAction"===r._||"sendMessageEmojiInteractionSeen"===r._);let d,c=t.firstElementChild;if(c?c.dataset.action!==r._&&c.replaceWith(this.getTypingElement(r)):(c=this.getTypingElement(r),t.prepend(c)),e.isAnyChat()&&(d=[new St.Z({peerId:i.userId.toPeerId(!1),onlyFirstName:!0}).element,s.length-1]),"sendMessageEmojiInteractionSeen"===r._){d?d.pop():d=[];const e=(0,Ze.Z)(Q.Z.wrapEmojiText(r.emoticon));d.push(e)}const h=(0,k.i18n)(l,d);return h.classList.add("peer-typing-description"),t.childElementCount>1?t.lastElementChild.replaceWith(h):t.append(h),t}}getPeerStatus(e,t){var s;return Rl(this,void 0,void 0,(function*(){let i;if(e){if(e.isAnyChat()){let t=this.getPeerTyping(e);if(t)return t;const s=e.toChatId(),a=yield n.default.getChatFull(s);this.chat.log("chatInfo res:",a);const o=a.participants_count||a.participants&&a.participants.participants&&a.participants.participants.length||1;if(i=n.default.getChatMembersString(s),o<2)return i;const r=yield n.default.getOnlines(s);if(r>1){const e=document.createElement("span");e.append(...(0,k.join)([i,(0,k.i18n)("OnlineCount",[(0,ka.Z)(r)])],!1)),i=e}return i}{const n=E.Z.getUser(e);if(a.default.myId===e&&!t)return;if(n){if(i=E.Z.getUserStatusString(n.id),!E.Z.isBot(e)){let t=this.getPeerTyping(e);if(t||"userStatusOnline"!==(null===(s=n.status)||void 0===s?void 0:s._)||(t=document.createElement("span"),t.classList.add("online"),t.append(i)),t)return t}return i}}}}))}setPeerStatus(e,t,s,i,n,a){s&&(t.innerHTML=i?"":"");const o=t.querySelector(".peer-typing-container");o&&this.getPeerTyping(e,o)||this.getPeerStatus(e,a).then((e=>{n()&&(0,T.Z)(t,e||(i?"":""))}))}setChoosingStickerTyping(e){i.Z.setTyping(this.chat.peerId,{_:e?"sendMessageCancelAction":"sendMessageChooseStickerAction"})}};re.GO&&(re.GO.appImManager=Nl);const Ol=Nl;var Hl=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class zl extends R.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,d.d)(e),ce.IS_TOUCH_SUPPORTED)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 s=this.isZooming();let i=null;const n=["ckin__player","media-viewer-buttons","media-viewer-author","media-viewer-caption","zoom-container"];s&&n.push("media-viewer-movers"),n.find((e=>{try{if(i=(0,Me.Z)(t,e),i)return!0}catch(e){return!1}})),i&&(s||"IMG"!==t.tagName&&"image"!==t.tagName)||this.close()},this.onKeyDown=e=>{if(a.default.overlaysActive>1)return;const t=e.key;let s=!0;"ArrowRight"===t?this.buttons.next.click():"ArrowLeft"===t?this.buttons.prev.click():"-"===t||"="===t?this.ctrlKeyDown&&this.changeZoom("="===t):s=!1,(e.ctrlKey||e.metaKey)&&(this.ctrlKeyDown=!0),s&&(0,d.d)(e)},this.onKeyUp=e=>{a.default.overlaysActive>1||e.ctrlKey||e.metaKey||(this.ctrlKeyDown=!1,this.isZooming()&&this.setZoomValue())},this.onWheel=e=>{if(!(a.default.overlaysActive>1||(0,Me.Z)(e.target,"media-viewer-caption")&&!this.ctrlKeyDown)&&((0,d.d)(e),this.ctrlKeyDown)){const t=e.deltaY<0;this.changeZoom(!!t)}},this.log=(0,$.kg)("AMV"),this.preloader=new fe.Z,this.preloaderStreamable=new fe.Z({cancelable:!1,streamable:!0}),this.preloader.construct(),this.preloaderStreamable.construct(),this.lazyLoadQueue=new X.lh,this.wholeDiv=document.createElement("div"),this.wholeDiv.classList.add("media-viewer-whole"),this.overlaysDiv=document.createElement("div"),this.overlaysDiv.classList.add("overlays");const s=document.createElement("div");s.classList.add("media-viewer");const i=this.topbar=document.createElement("div");i.classList.add("media-viewer-topbar","media-viewer-appear");const n=document.createElement("div");n.classList.add("media-viewer-topbar-left"),this.buttons["mobile-close"]=N("close",{onlyMobile:!0}),this.author.container=document.createElement("div"),this.author.container.classList.add("media-viewer-author","no-select");const o=document.createElement("div");this.author.avatarEl=new Yl,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"),o.append(this.author.nameEl,this.author.date),this.author.container.append(this.author.avatarEl,o);const r=document.createElement("div");r.classList.add("media-viewer-buttons"),t.concat(["download","zoom","close"]).forEach((e=>{const t=N(e,{noRipple:!0});this.buttons[e]=t,r.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=N("zoomout",{noRipple:!0}),(0,l.fc)(this.zoomElements.btnOut,(()=>this.changeZoom(!1))),this.zoomElements.btnIn=N("zoomin",{noRipple:!0}),(0,l.fc)(this.zoomElements.btnIn,(()=>this.changeZoom(!0))),this.zoomElements.rangeSelector=new we({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),s.append(this.content.main),this.overlaysDiv.append(s),n.append(this.buttons["mobile-close"],this.author.container),i.append(n,r),this.buttons.prev=document.createElement("div"),this.buttons.prev.className="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,l.fc)(this.buttons.download,this.onDownloadClick),[this.buttons.close,this.buttons["mobile-close"],this.preloaderStreamable.preloader].forEach((e=>{(0,l.fc)(e,this.close.bind(this))})),[[-1,this.buttons.prev],[1,this.buttons.next]].forEach((([e,t])=>{t.addEventListener("click",(t=>{(0,d.d)(t),this.setMoverPromise||this.listLoader.go(e)}))})),(0,l.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)},ce.IS_TOUCH_SUPPORTED&&new jt({element:this.wholeDiv,onSwipe:(e,t)=>{if(!(0,Pe.rB)())return Math.abs(e)/Ct.Z.width>.2||e>125?(e<0?this.buttons.prev.click():this.buttons.next.click(),!0):(Math.abs(t)/Ct.Z.height>.2||t>125)&&(this.close(),!0)},verifyTouchTarget:e=>"INPUT"!==e.target.tagName&&!(0,Me.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 s=e?this.zoomElements.rangeSelector.value:1;if(this.setZoomValue(s),this.zoomElements.rangeSelector.setProgress(s),this.videoPlayer&&this.videoPlayer.lockControls(!e&&void 0),e){if(this.zoomSwipeHandler)this.zoomSwipeHandler.setListeners();else{let e,t;const s=-1;this.zoomSwipeHandler=new jt({element:this.moversContainer,onFirstSwipe:()=>{e=t=0,this.moversContainer.classList.add("no-transition")},onSwipe:(i,n)=>{[i,n]=[i*s,n*s],this.zoomSwipeX+=i-e,this.zoomSwipeY+=n-t,[e,t]=[i,n],this.setZoomValue()},onReset:()=>{this.moversContainer.classList.remove("no-transition")},cursor:"move"})}this.zoomElements.rangeSelector.setProgress(s)}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=Ie({onlyMobile:!0},"bottom-left",e);this.topbar.append(t)}close(e){var t;if(e&&(0,d.d)(e),this.setMoverAnimationPromise)return Promise.reject();F.Z.removeByType("media"),this.lazyLoadQueue.clear();const s=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=void 0,this.zoomSwipeHandler&&(this.zoomSwipeHandler.removeListeners(),this.zoomSwipeHandler=void 0),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),window.removeEventListener("wheel",this.onWheel,{capture:!0}),s.finally((()=>{this.wholeDiv.remove(),a.default.isOverlayActive=!1,I.Z.checkAnimations(!1)})),s}setMoverToTarget(e,t=!1,s=0){return Hl(this,void 0,void 0,(function*(){this.dispatchEvent("setMoverBefore");const i=this.content.mover;t||(i.innerHTML="");const n=this.isZooming()&&t?this.zoomElements.rangeSelector.value:1;this.removeCenterFromMover(i);const o=0!==s,r=a.default.settings.animationsEnabled?o?350:200:0;let l,d;e&&(e instanceof Yl||e.classList.contains("grid-item")?(l=e,d=e.getBoundingClientRect()):e instanceof SVGImageElement||e.parentElement instanceof SVGForeignObjectElement?(l=(0,Me.Z)(e,"attachment"),d=l.getBoundingClientRect()):e.classList.contains("profile-avatars-avatar")&&(l=(0,Me.Z)(e,"profile-avatars-container"),d=l.getBoundingClientRect(),t&&e.getBoundingClientRect().left!==d.left&&(e=l=d=void 0))),e||(e=this.content.media),d||(l=e.parentElement,d=e.getBoundingClientRect());let c=!1;if(e!==this.content.media&&!e.classList.contains("profile-avatars-avatar")){const s=Pa(l,(0,Me.Z)(l,"scrollable"),!0);!t||s&&2!==s.overflow.vertical&&2!==s.overflow.horizontal?!s||1!==s.overflow.vertical&&1!==s.overflow.horizontal||(c=!0):(l=(e=this.content.media).parentElement,d=e.getBoundingClientRect())}const h=this.content.media.getBoundingClientRect();let p,u,g,m="";if(o?(p=1===s?Ct.Z.width:-h.width,u=h.top):(p=d.left,u=d.top),m+=`translate3d(${p}px,${u}px,0) `,e instanceof HTMLImageElement||e instanceof HTMLVideoElement||"DIV"===e.tagName){if(i.firstElementChild&&i.firstElementChild.classList.contains("media-viewer-aspecter")){g=i.firstElementChild;const e=g.querySelector(".ckin__player");if(e){const t=e.firstElementChild;g.append(t),e.remove()}g.style.cssText||(i.classList.remove("active"),this.setFullAspect(g,h,d),i.offsetLeft,i.classList.add("active"))}else g=document.createElement("div"),g.classList.add("media-viewer-aspecter"),i.prepend(g);g.style.cssText=`width: ${d.width}px; height: ${d.height}px; transform: scale3d(${h.width/d.width}, ${h.height/d.height}, 1);`}i.style.width=h.width+"px",i.style.height=h.height+"px";const v=d.width/h.width,f=d.height/h.height;o||(m+=`scale3d(${v},${f},1) `);let b=window.getComputedStyle(l).getPropertyValue("border-radius");const y=function(e){let 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=y.map((e=>parseInt(e)/v+"px")).join(" "),o||(i.style.borderRadius=b),t&&1!==n){const e=Ct.Z.width/2-d.width/2,t=Ct.Z.height/2-d.height/2,s=d.left-e,i=d.top-t;this.moversContainer.style.transform=`matrix(${v}, 0, 0, ${f}, ${s}, ${i})`}else i.style.transform=m;let w;c&&(i.style.opacity="0");const S=e.classList.contains("is-out"),C=this.setMoverAnimationPromise=(0,se.b)(),L={onAnimationEnd:C},I=setTimeout((()=>{C.isFulfilled||C.isRejected||C.resolve()}),1e3);if(C.finally((()=>{this.dispatchEvent("setMoverAfter"),this.setMoverAnimationPromise===C&&(this.setMoverAnimationPromise=null),clearTimeout(I)})),t)return e instanceof SVGSVGElement&&(w=i.querySelector("path"),w&&this.sizeTailPath(w,h,v,r,!1,S,b)),e.classList.contains("media-viewer-media")&&i.classList.add("hiding"),this.wholeDiv.classList.add("backwards"),setTimeout((()=>{this.wholeDiv.classList.remove("active")}),0),setTimeout((()=>{i.style.borderRadius=b,i.firstElementChild&&(i.firstElementChild.style.borderRadius=b)}),r/2),setTimeout((()=>{i.innerHTML="",i.classList.remove("moving","active","hiding"),i.style.cssText="display: none;",C.resolve()}),r),i.classList.remove("opening"),L;{let t,s;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 n=Array.from(e.querySelectorAll("img")).pop();n&&(t=new Image,s=n.src,i.append(t))}else if(e instanceof HTMLImageElement)t=new Image,s=e.src;else if(e instanceof HTMLVideoElement)t=document.createElement("video"),t.src=e.src;else if(e instanceof SVGSVGElement){const t=e.dataset.clipId,s=t+"-mv",{width:n,height:a}=h,o=document.createElementNS("http://www.w3.org/2000/svg","svg");o.setAttributeNS(null,"width",""+n),o.setAttributeNS(null,"height",""+a),o.setAttributeNS(null,"viewBox",`0 0 ${n} ${a}`),o.setAttributeNS(null,"preserveAspectRatio","xMidYMid meet"),o.insertAdjacentHTML("beforeend",e.firstElementChild.outerHTML.replace(t,s)),o.insertAdjacentHTML("beforeend",e.lastElementChild.outerHTML.replace(t,s));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,s,i,o)=>`translate(${t=2!=(t=+t)?n-2/v:2/v}, ${a}) scale(${+i/v}, ${+o/f})`)),l.setAttributeNS(null,"transform",t),w=r.firstElementChild.lastElementChild;const s=b.split(" ").map((e=>parseInt(e)));e=S?nr(0,0,n-9/v,a,...s):nr(9/v,0,n-9/v,a,...s),w.setAttributeNS(null,"d",e)}const d=o.lastElementChild;d.setAttributeNS(null,"width",""+h.width),d.setAttributeNS(null,"height",""+h.height),i.prepend(o)}g&&(g.style.borderRadius=b,t&&g.append(t)),t=i.querySelector("video, img"),t instanceof HTMLImageElement&&(t.classList.add("thumbnail"),g||(t.style.width=h.width+"px",t.style.height=h.height+"px"),s&&(yield(0,rs.cj)(t,s))),i.style.display="",(0,De.T2)((()=>{i.classList.add(o?"moving":"active")}))}return i.classList.add("opening"),yield(0,De.d1)(),i.style.transform=`translate3d(${h.left}px,${h.top}px,0) scale3d(1,1,1)`,c&&(i.style.opacity=""),g&&this.setFullAspect(g,h,d),setTimeout((()=>{i.style.borderRadius="",i.firstElementChild&&(i.firstElementChild.style.borderRadius="")}),0),i.dataset.timeout=""+setTimeout((()=>{i.classList.remove("moving","opening"),g&&(i.querySelector("video"),i.classList.remove("active"),g.style.cssText="",i.offsetLeft),i.classList.add("center","no-transition"),i.classList.add("active"),delete i.dataset.timeout,C.resolve()}),r),w&&this.sizeTailPath(w,h,v,r,!0,S,b),L}))}setFullAspect(e,t,s){const i=t.width/t.height;let{width:n,height:a}=s;i>0?n=a*i:a=n*i,e.style.cssText=`width: ${n}px; height: ${a}px; transform: scale3d(${t.width/n}, ${t.height/a}, 1);`}sizeTailPath(e,t,s,i,n,a,o){const r=Date.now(),{width:l,height:d}=t;i/=2;const c=o.split(" ").map((e=>parseInt(e))),h=()=>{const t=Date.now()-r;let o=i?t/i:1;o>1&&(o=1),n&&(o=1-o);const p=c.map((e=>e*o));let u;u=a?nr(0,0,l-9/s*o,d,...p):nr(9/s*o,0,l,d,...p),e.setAttributeNS(null,"d",u),t<i&&(0,De.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 s=Ct.Z.width;this.removeCenterFromMover(e),e.classList.add("moving"),e.dataset.timeout&&clearTimeout(+e.dataset.timeout);const i=e.getBoundingClientRect(),n=e.style.transform.replace(/translate3d\((.+?),/,((e,n)=>{const a=t?-i.width:s;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,s){const i=e.tagName.toLowerCase()===s?e:e.querySelector(s);if(i&&!(0,Me.Z)(e,"document")){if((0,Me.Z)(e,"attachment")){const t=e.parentElement.parentElement.querySelector(".preloader-container");if(t){if("video"===s)return void(t.classList.contains("manual")&&t.click());t.remove()}}(0,rs.ZP)(i,t),i.classList.contains("thumbnail")&&i.parentElement.classList.contains("media-container-aspecter")&&i.classList.remove("thumbnail")}}setAuthorInfo(e,t){(0,T.Z)(this.author.date,(0,ie.OD)(t));const s=e.isPeerId();let i;s?i=new St.Z({peerId:e,dialog:!1,onlyFirstName:!1,plainText:!1}).element:(i=document.createElement("span"),i.innerHTML=Q.Z.wrapEmojiText(e),i.classList.add("peer-title")),(0,T.Z)(this.author.nameEl,i);let n=this.author.avatarEl;this.author.avatarEl=n.cloneNode(),s?this.author.avatarEl.removeAttribute("peer-title"):this.author.avatarEl.setAttribute("peer-title",""+e),this.author.avatarEl.setAttribute("peer",""+(e||Re.NM)),n.parentElement.replaceChild(this.author.avatarEl,n)}_openMedia(e,t,s,i,n,o=!1,l=[],c=[],h){return Hl(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;this.setAuthorInfo(s,t);const p="document"===e._,u=p&&e.mime_type&&(["video","gif"].includes(e.type)||0===e.mime_type.indexOf("video/"));this.isFirstOpen&&(this.isFirstOpen=!1,this.listLoader.setTargets(l,c,o),window.appMediaViewer=this),this.listLoader.next.length<10&&setTimeout((()=>{this.listLoader.load(!0)}),0),this.buttons.prev.classList.toggle("hide",!this.listLoader.previous.length),this.buttons.next.classList.toggle("hide",!this.listLoader.next.length);const g=this.content.media,m=!n||n===g;m&&(n=g),this.target={element:n};const f=++this.tempId;if(g.firstElementChild&&(g.innerHTML=""),0!==i)this.moveTheMover(this.content.mover,1===i),this.setNewMover();else{a.default.isOverlayActive=!0,window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp),ce.IS_TOUCH_SUPPORTED||window.addEventListener("wheel",this.onWheel,{passive:!1,capture:!0});const e=document.getElementById("main-columns");this.pageEl.insertBefore(this.wholeDiv,e),this.wholeDiv.offsetLeft,this.wholeDiv.classList.add("active"),I.Z.checkAnimations(!0),ne.IS_MOBILE_SAFARI||F.Z.pushItem({type:"media",onPop:e=>{if(this.setMoverAnimationPromise)return!1;this.close()}})}const b=this.content.mover,y=Ct.Z.width;let w=0;const S=Ct.Z.height;S<1e6&&!v.ZP.isMobile&&(w=120);const C=S-120-w;let M=Promise.resolve();const E=r.Z.setAttachmentSize(e,g,y,C,!v.ZP.isMobile,void 0,!!(p&&e.w&&e.h)).photoSize;if(m){const t=le.Z.getCacheContext(e,E.type);let s;if(t.downloaded)s=new Image,s.src=t.url;else{const i=r.Z.getStrippedThumbIfNeeded(e,t,!0);i&&(M=i.loadPromise,s=i.image)}s&&(s.classList.add("thumbnail"),g.append(s))}const P=!(!p||!e.supportsStreaming),T=P?this.preloaderStreamable:this.preloader;let k;if(u){const t=h&&"gif"!==e.type,s=document.createElement("video"),a=()=>this.setMoverToTarget(n,!1,i).then((({onAnimationEnd:i})=>{const a=b.firstElementChild&&b.firstElementChild.classList.contains("media-viewer-aspecter")?b.firstElementChild:b,o=b.querySelector("video");o&&o.remove(),s.setAttribute("playsinline","true"),s.addEventListener("timeupdate",(()=>{this.tempId!==f&&s.pause()})),s.addEventListener("error",(()=>{4!==s.error.code&&this.log.error("Error "+s.error.code+"; details: "+s.error.message),T&&T.detach()}),{once:!0}),this.addEventListener("setMoverAfter",(()=>{s.src="",s.load()}),{once:!0}),ne.IS_SAFARI&&(s.autoplay=!0),"gif"===e.type?(s.muted=!0,s.autoplay=!0,s.loop=!0):e.duration<60&&(s.loop=!0),a.append(s);const r=new Promise((e=>{s.addEventListener("canplay",e,{once:!0})})),l=()=>{"gif"!==e.type&&(s.dataset.ckin="default",s.dataset.overlay="1",Promise.all([r,i]).then((()=>{this.tempId===f&&((this.videoPlayer=new xe({video:s,play:!0,streamable:P,onPlaybackRackMenuToggle:e=>{this.wholeDiv.classList.toggle("hide-caption",!!e)}})).addEventListener("toggleControls",(e=>{this.wholeDiv.classList.toggle("has-video-controls",e)})),this.addEventListener("setMoverBefore",(()=>{this.wholeDiv.classList.remove("has-video-controls"),this.videoPlayer.removeListeners(),this.videoPlayer=void 0}),{once:!0}),this.isZooming()&&this.videoPlayer.lockControls(!1))})))};if(P){i.then((()=>{s.readyState<s.HAVE_FUTURE_DATA&&T.attach(b,!0)}));const e=()=>{s.addEventListener("canplay",(()=>{T.detach(),s.parentElement.classList.remove("is-buffering")}),{once:!0})};s.addEventListener("waiting",(()=>{const t=s.networkState===s.NETWORK_LOADING,i=s.readyState<s.HAVE_FUTURE_DATA;t&&i&&(e(),T.attach(b,!0),s.parentElement.classList.add("is-buffering"))})),this.wholeDiv.classList.contains("no-forwards")&&s.addEventListener("contextmenu",(e=>{(0,d.d)(e)})),e()}this.lazyLoadQueue.unshift({load:()=>{const o=le.Z.getCacheContext(e),r=P?Promise.resolve():L.Z.downloadDoc(e);return P||i.then((()=>{o.url||T.attach(b,!0,r)})),Promise.all([r,i]).then((()=>{if(this.tempId!==f)return void this.log.warn("media viewer changed video");const e=o.url;if(n instanceof SVGSVGElement?a.firstElementChild.lastElementChild.append(s):(0,rs.ZP)(s,e),t){const e=ve.setSingleMedia(s,h);this.addEventListener("setMoverBefore",(()=>{e()}),{once:!0})}this.updateMediaSource(n,e,"video"),l()})),r}})}));k=M.then(a)}else{const t=()=>this.setMoverToTarget(n,!1,i).then((({onAnimationEnd:t})=>{this.lazyLoadQueue.unshift({load:()=>{const s=le.Z.getCacheContext(e,E.type),i=p?L.Z.downloadDoc(e):r.Z.preloadPhoto(e,E);return t.then((()=>{s.url||this.preloader.attachPromise(i)})),Promise.all([t,i]).then((()=>{var e;if(this.tempId!==f)return void this.log.warn("media viewer changed photo");const t=s.url;if(n instanceof SVGSVGElement){if(this.updateMediaSource(n,t,"img"),this.updateMediaSource(b,t,"img"),v.ZP.isMobile){const e=b.querySelectorAll("img");e&&e.length&&e.forEach((e=>{e.classList.remove("thumbnail")}))}}else{const s=b.firstElementChild&&b.firstElementChild.classList.contains("media-viewer-aspecter")?b.firstElementChild:b,i="IMG"===(null===(e=s.firstElementChild)||void 0===e?void 0:e.tagName)?s.firstElementChild:null;if(!i||i.src!==t){let e=new Image;e.classList.add("thumbnail"),(0,rs.ZP)(e,t,(()=>{this.updateMediaSource(n,t,"img"),i&&(0,De.T2)((()=>{i.remove()})),s.append(e)}))}}})).catch((e=>{this.log.error(e),this.preloader.attach(b),this.preloader.setManual()})),i}})}));k=M.then(t)}return this.setMoverPromise=k.catch((()=>{this.setMoverAnimationPromise=null})).finally((()=>{this.setMoverPromise=null}))}))}}class Vl extends zl{constructor(){let e;super(new C({processItem:e=>{const t="inputMessagesFilterDocument"===this.searchContext.inputFilter._,{mid:s,peerId:n}=e,a=i.Z.getMediaFromMessage(e);if(a&&(!t||Vl.isMediaCompatibleForDocumentViewer(a)))return{element:null,mid:s,peerId:n}}}),["delete","forward"]),this.onPrevClick=e=>{this.openMedia(this.getMessageByPeer(e.peerId,e.mid),e.element,-1)},this.onNextClick=e=>{this.openMedia(this.getMessageByPeer(e.peerId,e.mid),e.element,1)},this.onDeleteClick=()=>{const e=this.target;new zs(e.peerId,[e.mid],"chat",(()=>{this.target={element:this.content.media},this.close()}))},this.onForwardClick=()=>{const e=this.target;e.mid&&new Hs({[e.peerId]:[e.mid]},(()=>this.close()))},this.onAuthorClick=e=>{const{mid:t,peerId:s}=this.target;if(t&&t!==Number.MAX_SAFE_INTEGER){const i=this.searchContext.threadId,n=this.getMessageByPeer(s,t);this.close(e).then((()=>{if(v.ZP.isMobile){const e=Yt.getTab(qt);e&&e.close()}Ol.setInnerPeer({peerId:n.peerId,lastMsgId:t,type:i?"discussion":void 0,threadId:i})}))}},this.onDownloadClick=()=>{const{peerId:e,mid:t}=this.target,s=this.getMessageByPeer(e,t);if(s.media.photo)r.Z.savePhotoFile(s.media.photo,Ol.chat.bubbles.lazyLoadQueue.queueId);else{let e=null;e=s.media.webpage?s.media.webpage.document:s.media.document,e&&L.Z.saveDocFile(e,Ol.chat.bubbles.lazyLoadQueue.queueId)}},this.listLoader.onEmptied=()=>{this.close()},this.content.caption=document.createElement("div"),this.content.caption.classList.add("media-viewer-caption");const t=()=>{e&&clearTimeout(e),e=window.setTimeout((()=>{e=void 0,this.content.caption.classList.remove("is-focused")}),800)};this.content.caption.addEventListener("touchstart",(()=>{v.ZP.isMobile&&(this.content.caption.classList.add("is-focused"),e&&(clearTimeout(e),e=void 0),document.addEventListener("touchend",t,{once:!0}))})),new P.ZP(this.content.caption).onAdditionalScroll=t,this.wholeDiv.append(this.content.caption),(0,l.fc)(this.buttons.delete,this.onDeleteClick);const s=[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(s),this.setListeners()}get searchContext(){return this.listLoader.searchContext}setListeners(){super.setListeners(),(0,l.fc)(this.buttons.forward,this.onForwardClick),(0,l.fc)(this.author.container,this.onAuthorClick);const e=t=>{if(t.target instanceof HTMLAnchorElement){const s=t.target.getAttribute("onclick");if(!s||s.includes("showMaskedAlert"))return;return(0,d.d)(t),this.close().then((()=>{(0,l.EN)(this.content.caption,e,{capture:!0}),t.target.click()})),!1}};(0,l.fc)(this.content.caption,e,{capture:!0})}getMessageByPeer(e,t){return this.searchContext.isScheduled?i.Z.getScheduledMessageByPeer(e,t):i.Z.getMessageByPeer(e,t)}setCaption(e){const t=e.message;let s="";t&&(s=Q.Z.wrapRichText(t,{entities:e.totalEntities})),m(this.content.caption.firstElementChild,s),this.content.caption.classList.toggle("hide",!t)}setSearchContext(e){return this.listLoader.setSearchContext(e),this}openMedia(e,t,s=0,n=!1,a=[],o=[]){const r=Object.create(null,{_openMedia:{get:()=>super._openMedia}});return l=this,d=void 0,h=function*(){if(this.setMoverPromise)return this.setMoverPromise;const l=e.mid,d=e.fwd_from&&!e.fromId?e.fwd_from.from_name:e.fromId,c=i.Z.getMediaFromMessage(e),h="messageService"===e._||!i.Z.canForward(e);[this.buttons.forward,this.btnMenuForward.element].forEach((e=>{e.classList.toggle("hide",h)})),this.wholeDiv.classList.toggle("no-forwards",h);const p=h;[this.buttons.download,this.btnMenuDownload.element].forEach((e=>{e.classList.toggle("hide",p)}));const u=i.Z.canDeleteMessage(e);[this.buttons.delete,this.btnMenuDelete.element].forEach((e=>{e.classList.toggle("hide",!u)})),this.setCaption(e);const g=r._openMedia.call(this,c,e.date,d,s,t,n,a,o,e);return this.target.mid=l,this.target.peerId=e.peerId,g},new((c=void 0)||(c=Promise))((function(e,t){function s(e){try{n(h.next(e))}catch(e){t(e)}}function i(e){try{n(h.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(s,i)}n((h=h.apply(l,d||[])).next())}));var l,d,c,h}static isMediaCompatibleForDocumentViewer(e){return"photo"===e._||g.has(e.mime_type)}}class jl extends S{constructor(e){super(Object.assign(Object.assign({},e),{loadMore:(e,t,s)=>{var i;if(this.peerId.isAnyChat()||!t)return Promise.resolve({count:0,items:[]});const n=(null==e?void 0:e.photoId)||(null===(i=this.current)||void 0===i?void 0:i.photoId);return r.Z.getUserPhotos(this.peerId,n,s).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}}class Gl extends zl{constructor(e){super(new jl({peerId:e}),[]),this.onPrevClick=e=>{this.openMedia(e.photoId,e.element,-1)},this.onNextClick=e=>{this.openMedia(e.photoId,e.element,1)},this.onDownloadClick=()=>{r.Z.savePhotoFile(r.Z.getPhoto(this.target.photoId),Ol.chat.bubbles.lazyLoadQueue.queueId)},this.peerId=e,this.setBtnMenuToggle([{icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick}]),this.setListeners()}openMedia(e,t,s=0,i,n){const a=Object.create(null,{_openMedia:{get:()=>super._openMedia}});return o=this,l=void 0,c=function*(){if(this.setMoverPromise)return this.setMoverPromise;const o=r.Z.getPhoto(e),l=a._openMedia.call(this,o,o.date,this.peerId,s,t,!1,i,n);return this.target.photoId=o.id,l},new((d=void 0)||(d=Promise))((function(e,t){function s(e){try{n(c.next(e))}catch(e){t(e)}}function i(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 d?n:new d((function(e){e(n)}))).then(s,i)}n((c=c.apply(o,l||[])).next())}));var o,l,d,c}}var Kl=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const Wl=e=>{c.Z.removeFromAvatarsCache(e),Array.from(document.querySelectorAll('avatar-element[peer="'+e+'"]')).forEach((e=>{e.update()}))};function ql(e,t,s,a,o,l){return Kl(this,void 0,void 0,(function*(){let d=yield n.default.getFullPhoto(t);if(!s()||!d)return;const c=()=>Array.from(e.querySelectorAll("img")).find((e=>!e.classList.contains("emoji")))?e:null;if(t.isAnyChat()){const e=!!a,n="inputMessagesFilterChatPhotos";if(!a&&(a=yield i.Z.getSearch({peerId:t,inputFilter:{_:n},maxId:0,limit:1}).then((e=>e.history[0])),!s()))return;if(a){a.action.photo.id!==d.id&&(e||(a=i.Z.generateFakeAvatarMessage(t,d)));const s=e=>e.map((e=>({element:e.element,mid:e.item.mid,peerId:e.item.peerId})));return void(new Vl).setSearchContext({peerId:t,inputFilter:{_:n}}).openMedia(a,c(),void 0,void 0,o?s(o):void 0,l?s(l):void 0)}}if(d){!(0,Wn.Z)(a)&&a&&(d=r.Z.getPhoto(a));const e=e=>e.map((e=>({element:e.element,photoId:e.item})));new Gl(t).openMedia(d.id,c(),void 0,o?e(o):void 0,l?e(l):void 0)}}))}a.default.addEventListener("avatar_update",Wl),a.default.addEventListener("peer_title_edit",(e=>{c.Z.isAvatarCached(e)||Wl(e)}));const $l=new Map,Ql=new Set;class Yl extends HTMLElement{constructor(){super(...arguments),this.addedToQueue=!1}connectedCallback(){if(this.isDialog="1"===this.getAttribute("dialog"),""===this.getAttribute("clickable")){this.setAttribute("clickable","set");let e=!1;(0,l.fc)(this,(t=>Kl(this,void 0,void 0,(function*(){if((0,d.d)(t),e)return;const s=this.peerId;e=!0,yield ql(this,this.peerId,(()=>this.peerId===s)),e=!1}))))}}disconnectedCallback(){const e=$l.get(this.peerId);e&&e.has(this)&&(e.delete(this),e.size||$l.delete(this.peerId)),this.lazyLoadQueue&&this.lazyLoadQueue.unobserve(this)}static get observedAttributes(){return["peer","dialog","peer-title"]}attributeChangedCallback(e,t,s){if("peer"===e){const e=(s||"").toPeerId()||Re.NM;if(this.peerId===e)return;this.peerId=o.Z.getPeerMigratedTo(e)||e;const i=(t||"").toPeerId()||Re.NM;if(i){const e=$l.get(i);e&&(e.delete(this),e.size||$l.delete(i))}this.update()}else"peer-title"===e?this.peerTitle=s:"dialog"===e&&(this.isDialog="1"===s)}r(e=!1){const t=c.Z.putPhoto(this,this.peerId,this.isDialog,this.peerTitle,e,this.isBig),s=t?t.loadPromise:Promise.resolve();return this.loadPromises&&(t&&t.cached&&this.loadPromises.push(s),s.finally((()=>{this.loadPromises=void 0}))),t}update(){if(this.lazyLoadQueue){if(!Ql.has(this.peerId)){if(this.addedToQueue)return;this.addedToQueue=!0;let e=$l.get(this.peerId);return e||(e=new Set,$l.set(this.peerId,e)),e.add(this),this.r(!0),void this.lazyLoadQueue.push({div:this,load:()=>(Ql.add(this.peerId),this.update())})}this.addedToQueue&&this.lazyLoadQueue.unobserve(this)}Ql.add(this.peerId);const e=this.r(),t=e?e.loadPromise:Promise.resolve();this.addedToQueue&&t.finally((()=>{this.addedToQueue=!1}));const s=$l.get(this.peerId);if(s){s.delete(this);const e=Array.from(s);$l.delete(this.peerId);for(let t=0,s=e.length;t<s;++t)e[t].update()}return t}}customElements.define("avatar-element",Yl);class Xl{constructor(){this.onArchiveClick=()=>{let e=i.Z.getDialogOnly(this.selectedId);e&&i.Z.editPeerFolders([e.peerId],+!e.folder_id)},this.onPinClick=()=>{i.Z.toggleDialogPin(this.selectedId,this.filterId).catch((e=>{"PINNED_DIALOGS_TOO_MUCH"===e.type&&(this.filterId>=1?lt({langPackKey:"PinFolderLimitReached"}):new gt("pinned-dialogs-too-much",{buttons:[{langKey:"OK",isCancel:!0},{langKey:"FiltersSetupPinAlert",callback:()=>{new sn(xn).open()}}],descriptionLangKey:"PinToTopLimitReached2",descriptionLangArgs:[(0,k.i18n)("Chats",[a.default.config.pinned_dialogs_count_max])]}).show())}))},this.onUnmuteClick=()=>{i.Z.togglePeerMute(this.selectedId,!1)},this.onMuteClick=()=>{new $o(this.selectedId)},this.onUnreadClick=()=>{const e=i.Z.getDialogOnly(this.selectedId);e&&(e.unread_count?(i.Z.readHistory(this.selectedId,e.top_message),i.Z.markDialogUnread(this.selectedId,!0)):i.Z.markDialogUnread(this.selectedId))},this.onDeleteClick=()=>{new At(this.selectedId)},this.onContextMenu=e=>{this.init&&(this.init(),this.init=null);let t=null;try{t=(0,ft.Z)(e.target,"LI")}catch(e){}if(t){if(e instanceof MouseEvent&&e.preventDefault(),this.element.classList.contains("active"))return!1;e instanceof MouseEvent&&(e.cancelBubble=!0),this.filterId=pd.filterId,this.selectedId=t.dataset.peerId.toPeerId(),this.dialog=i.Z.getDialogOnly(this.selectedId),this.buttons.forEach((e=>{const t=e.verify();e.element.classList.toggle("hide",!t)})),this.buttons[this.buttons.length-1].element.lastChild.replaceWith((0,k.i18n)(o.Z.getDeleteButtonText(this.selectedId))),t.classList.add("menu-open"),(0,J.oy)(e,this.element),(0,J.YP)(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:()=>!i.Z.isDialogUnread(this.dialog)},{icon:"readchats",text:"MarkAsRead",onClick:this.onUnreadClick,verify:()=>i.Z.isDialogUnread(this.dialog)},{icon:"pin",text:"ChatList.Context.Pin",onClick:this.onPinClick,verify:()=>{var e;return!(this.filterId>1?i.Z.filtersStorage.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:()=>{var e;return this.filterId>1?i.Z.filtersStorage.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:()=>this.selectedId!==a.default.myId&&!Ft.Z.isPeerLocalMuted(this.dialog.peerId)},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:this.onUnmuteClick,verify:()=>this.selectedId!==a.default.myId&&Ft.Z.isPeerLocalMuted(this.dialog.peerId)},{icon:"archive",text:"Archive",onClick:this.onArchiveClick,verify:()=>0===this.filterId&&this.selectedId!==a.default.myId},{icon:"unarchive",text:"Unarchive",onClick:this.onArchiveClick,verify:()=>1===this.filterId&&this.selectedId!==a.default.myId},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>!0}],this.element=Ce(this.buttons),this.element.id="dialogs-contextmenu",this.element.classList.add("contextmenu"),document.getElementById("page-chats").append(this.element)}}var Jl,ed;!function(e){e[e.Connected=0]="Connected",e[e.Connecting=1]="Connecting",e[e.Closed=2]="Closed",e[e.TimedOut=3]="TimedOut"}(Jl||(Jl={}));class td{constructor(e){this.hadConnect=!1,this.connecting=!1,this.timedOut=!1,this.updating=!1,this.setConnectionStatus=()=>{Sn.Z.get("dc").then((e=>{e||(e=wn.Z.baseDcId),this.setFirstConnectionTimeout&&(clearTimeout(this.setFirstConnectionTimeout),this.setFirstConnectionTimeout=0);const t=a.default.connectionStatus["NET-"+e],s=t&&t.status===Jl.Connected;this.connecting&&s&&ni.Z.forceGetDifference(),s&&!this.hadConnect&&(this.hadConnect=!0),this.timedOut=t&&t.status===Jl.TimedOut,this.connecting=!s,this.retryAt=t&&t.retryAt,re.ZP&&this.log("connecting",this.connecting),this.setState()}))},this.setStatusText=(e,t)=>{this.currentLangPackKey!==e&&(this.currentLangPackKey=e,(0,T.Z)(this.statusEl,(0,k.i18n)(e,t)),this.statusPreloader.attach(this.statusEl))},this.setState=()=>{const e=td.CHANGE_STATE_DELAY;if(this.connecting)if(this.timedOut){const e=this.getA("ConnectionStatus.ForceReconnect",(()=>ct.Z.forceReconnect()));this.setStatusText("ConnectionStatus.TimedOut",[e])}else if(this.hadConnect)if(void 0!==this.retryAt){const e=document.createElement("span"),t=this.retryAt,s=()=>{const s=Date.now();e.innerText=""+Math.round((t-s)/1e3),s>t&&clearInterval(i)},i=setInterval(s,1e3);s();const n=this.getA("ConnectionStatus.Reconnect",(()=>ct.Z.forceReconnectTimeout()));this.setStatusText("ConnectionStatus.ReconnectIn",[e,n])}else this.setStatusText("ConnectionStatus.Reconnecting");else this.setStatusText("ConnectionStatus.Waiting");else this.updating&&this.setStatusText("Updating");re.ZP&&this.log("setState",this.connecting||this.updating),window.requestAnimationFrame((()=>{this.setStateTimeout&&clearTimeout(this.setStateTimeout),this.setStateTimeout=window.setTimeout((()=>{(0,Jt.Z)(this.statusContainer,"is-shown",this.connecting||this.updating,200),this.setStateTimeout=0,re.ZP&&this.log("setState: isShown:",this.connecting||this.updating)}),e)}))},this.log=(0,$.kg)("CS",void 0,void 0),this.statusContainer=document.createElement("div"),this.statusContainer.classList.add("connection-status"),this.statusEl=(0,U.Z)("btn-primary bg-warning connection-status-button",{noRipple:!0}),this.statusPreloader=new fe.Z({cancelable:!1}),this.statusPreloader.constructContainer({color:"transparent",bold:!0}),this.statusContainer.append(this.statusEl),e.prepend(this.statusContainer),a.default.addEventListener("connection_status_change",(e=>{console.log(e),this.setConnectionStatus()})),a.default.addEventListener("state_synchronizing",(e=>{e||(this.updating=!0,re.ZP&&this.log("updating",this.updating),this.setState())})),a.default.addEventListener("state_synchronized",(e=>{re.ZP&&this.log("state_synchronized",e),e||(this.updating=!1,re.ZP&&this.log("updating",this.updating),this.setState())})),this.setFirstConnectionTimeout=window.setTimeout(this.setConnectionStatus,td.CHANGE_STATE_DELAY+1e3)}getA(e,t){const s=document.createElement("a");return s.classList.add("force-reconnect"),s.append((0,k.i18n)(e)),(0,l.fc)(s,(e=>{(0,d.d)(e),t()})),s}}function sd(e,t,s,i,n,a,o,r){if("number"==typeof a)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]||e[t]}e.beginPath(),e.moveTo(t+a.tl,s),e.lineTo(t+i-a.tr,s),e.quadraticCurveTo(t+i,s,t+i,s+a.tr),e.lineTo(t+i,s+n-a.br),e.quadraticCurveTo(t+i,s+n,t+i-a.br,s+n),e.lineTo(t+a.bl,s+n),e.quadraticCurveTo(t,s+n,t,s+n-a.bl),e.lineTo(t,s+a.tl),e.quadraticCurveTo(t,s,t+a.tl,s),e.closePath(),o&&e.fill(),r&&e.stroke()}td.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"}(ed||(ed={}));const id=window.devicePixelRatio,nd=20*id,ad=2.5*id,od=2*id,rd=1*id;var ld=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class dd extends Fs{constructor(e,t,s){super({getIndex:e=>i.Z.getDialogOnly(e.id)[this.indexKey],onDelete:e=>{e.dom.listEl.remove(),this.onListLengthChange&&this.onListLengthChange()},onSort:(e,t)=>{const s=e.dom.listEl.parentElement!==this.list;Zs(e.dom.listEl,this.list,t),s&&this.onListLengthChange&&this.onListLengthChange()},onElementCreate:(e,t)=>{const s=t?[]:void 0,{dom:i}=hd.addListDialog({dialog:e.id,loadPromises:s,isBatch:t});return e.dom=i,(null==s?void 0:s.length)&&(e.loadPromises=s,Promise.all(s).finally((()=>{delete e.loadPromises}))),e},updateElementWith:De.TR}),this.list=e,this.indexKey=t,this.onListLengthChange=s}clear(){this.list.innerHTML="",super.clear()}}class cd{constructor(){this.chatsContainer=document.getElementById("chatlist-container"),this.scroll=null,this.log=(0,$.kg)("DIALOGS",$.v9.Log|$.v9.Error|$.v9.Warn|$.v9.Debug),this.contextMenu=new Xl,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.loadDialogsPromise=void 0,this.sortedList=this.sortedLists[this.filterId],this.onChatsScroll()},this._onListLengthChange=()=>{if(!this.loadedDialogsAtLeastOnce)return;if(this.checkIfPlaceholderNeeded(),this.filterId>0)return;const e=this.chatList,t=e.childElementCount,s=e.parentElement.parentElement,i=e.parentElement.nextElementSibling,n=!!i.childElementCount;if(t>=10)return void(n&&this.removeContactsPlaceholder());if(n)return;s.classList.add("with-contacts");const a=new Mn({name:"Contacts",noDelimiter:!0,fakeGradientDelimiter:!0});a.container.classList.add("hide"),E.Z.getContactsPeerIds(void 0,void 0,"online").then((e=>{let t=!1;const s=()=>{t&&a.container.classList.toggle("hide",!i.list.childElementCount),this.updateContactsLength(!0)},i=new Rs({avatarSize:42,createChatListOptions:{dialogSize:48,new:!0},autonomous:!1,onListLengthChange:s});this.loadContacts=()=>{const t=Ct.Z.height/60|0;e.splice(0,t).filter(this.verifyPeerIdForContacts).forEach((e=>{i.add(e)})),e.length||(this.loadContacts=void 0)},this.loadContacts(),this.processContact=e=>{if(e.isAnyChat())return;const t=this.verifyPeerIdForContacts(e),s=i.has(e);!s&&t?i.add(e):s&&!t&&i.delete(e)};const n=i.list;n.classList.add("chatlist-new"),this.setListClickListener(n),a.content.append(n),t=!0,s()})),i.append(a.container)},this.verifyPeerIdForContacts=e=>e.isContact()&&!i.Z.getDialogOnly(e),this.onChatsRegularScroll=()=>{this.sliceTimeout&&clearTimeout(this.sliceTimeout),this.sliceTimeout=window.setTimeout((()=>{this.sliceTimeout=void 0,this.chatList.childElementCount&&!this.processContact&&(0,De.TR)((()=>{const e=performance.now(),t=this.scroll.scrollTop,s=this.chatList.firstElementChild,i=this.scroll.container.getBoundingClientRect(),n=s.getBoundingClientRect(),a=Array.from(this.scroll.splitUp.children);let o=this.scroll.splitUp.offsetTop;o&&t<o&&(o-=t);const r=i.y+o,l=i.y,d=(0,ft.Z)(document.elementFromPoint(Math.ceil(n.x),Math.ceil(r+1)),s.tagName),c=(0,ft.Z)(document.elementFromPoint(Math.ceil(n.x),Math.floor(l+i.height-1)),s.tagName);if(!d||!c)return;const h=d.getBoundingClientRect().y-r,p=[],u=a.indexOf(d),g=a.indexOf(c),m=ne.IS_SAFARI?[]:a.slice(0,Math.max(0,u-10)),v=a.slice(g+10);m.length&&(this.scroll.loadedAll.top=!1),v.length&&(this.scroll.loadedAll.bottom=!1),p.push(...m),p.push(...v),p.forEach((e=>{const t=e.dataset.peerId.toPeerId();this.deleteDialog(t)})),this.setOffsets(),this.scroll.scrollTop=d.offsetTop-h,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(),Promise.resolve()):this.loadDialogsPromise?this.loadDialogsPromise:(this.log("onChatsScroll",e),this.loadDialogs(e)),this.chatsPreloader=(0,J.y7)(null,!0),this.allUnreadCount=this.folders.menu.querySelector(".badge"),this.folders.menuScrollContainer=this.folders.menu.parentElement,this.onListLengthChange=dt(this._onListLengthChange,100,!1,!0);const e=document.createElement("div");e.classList.add("connection-status-bottom"),e.append(this.folders.container),ce.IS_TOUCH_SUPPORTED&&Ns({element:this.folders.container,onSwipe:e=>{const t=s.prevId();s(e>0?t+1:t-1)}}),this.allChatsIntlElement=new k.default.IntlElement({key:"FilterAllChatsShort"}),this.setFilterId(0),this.addFilter({id:this.filterId,title:"",titleEl:this.allChatsIntlElement.element,orderIndex:0}),this.sortedList=this.sortedLists[this.filterId],this.scroll=this.scrollables[this.filterId],a.default.addEventListener("state_cleared",(()=>{M.default.getState().then((e=>{this.loadedDialogsAtLeastOnce=!1,E.Z.clear(),j.Z.clear();const t=i.Z.filtersStorage.filters;for(const e in t)a.default.dispatchEvent("updateDialogFilter",{_:"updateDialogFilter",id:+e});i.Z.clear(),this.sortedList.clear(),this.onTabChange(),this.onStateLoaded(e)}))}));const t=new P.v7(this.folders.menuScrollContainer);e.prepend(this.folders.menuScrollContainer);const s=(0,Y.X)(this.folders.menu,this.folders.container,((e,t)=>{e=+t.dataset.filterId||0,ne.IS_MOBILE_SAFARI||(e?this.filtersNavigationItem||(this.filtersNavigationItem={type:"filters",onPop:()=>{s(0),this.filtersNavigationItem=void 0}},F.Z.unshiftItem(this.filtersNavigationItem)):this.filtersNavigationItem&&(F.Z.removeItem(this.filtersNavigationItem),this.filtersNavigationItem=void 0)),this.filterId!==e&&(this.sortedLists[e].clear(),this.setFilterId(e),this.onTabChange())}),(()=>{for(const e in this.sortedLists)+e!==this.filterId&&this.sortedLists[e].clear()}),void 0,t);this.folders.menu.firstElementChild.click(),i.Z.construct(),M.default.getState().then((e=>this.onStateLoaded(e))),v.ZP.addEventListener("resize",(()=>{this.changeFiltersAllChatsKey()})),new td(this.chatsContainer),this.chatsContainer.append(e),setTimeout((()=>{ae.Z.loadLottieWorkers()}),200)}get chatList(){return this.sortedList.list}setFilterId(e){this.filterId=e,this.indexKey=i.Z.dialogsStorage?i.Z.dialogsStorage.getDialogIndexKey(this.filterId):"index",a.default.filterId=e}setOnlineStatus(e,t){const s="is-online",i=e.classList.contains(s);!i&&t&&e.classList.add(s),(0,Jt.Z)(e,"is-visible",t,250,t?void 0:()=>{e.classList.remove(s)},t&&!i?2:0)}initListeners(){a.default.addEventListener("user_update",(e=>{var t;const s=e.toPeerId(),i=this.getDialogDom(s);if(i&&!E.Z.isBot(e)&&s!==a.default.myId){const s="userStatusOnline"===(null===(t=E.Z.getUser(e).status)||void 0===t?void 0:t._);this.setOnlineStatus(i.avatarEl,s)}})),a.default.addEventListener("chat_update",(e=>{const t=e.toPeerId(!0),s=i.Z.getDialogOnly(t);s&&this.processDialogForCallStatus(s)})),a.default.addEventListener("folder_unread",(e=>{this.setFilterUnreadCount(e.id)})),a.default.addEventListener("contacts_update",(e=>{this.processContact&&this.processContact(e.toPeerId())})),a.default.addEventListener("dialog_flush",(({peerId:e})=>{const t=i.Z.getDialogOnly(e);t&&(this.setLastMessage(t,void 0,void 0,void 0,void 0,void 0,!0),this.validateDialogForFilter(t),this.setFiltersUnreadCount())})),a.default.addEventListener("dialogs_multiupdate",(e=>{for(const t in e){const s=e[t];this.updateDialog(s),this.processContact&&this.processContact(t.toPeerId()),this.validateDialogForFilter(s)}})),a.default.addEventListener("dialog_drop",(({peerId:e})=>{this.deleteDialog(e),this.processContact&&this.processContact(e)})),a.default.addEventListener("dialog_unread",(({peerId:e})=>{const t=i.Z.getDialogOnly(e);t&&(this.setUnreadMessages(t),this.validateDialogForFilter(t))})),a.default.addEventListener("dialog_notify_settings",(e=>{this.validateDialogForFilter(e),this.setUnreadMessages(e),this.setFiltersUnreadCount()})),a.default.addEventListener("dialog_draft",(({dialog:e,drop:t,peerId:s})=>{t?this.sortedList.delete(s):this.updateDialog(e),this.processContact&&this.processContact(s)})),a.default.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"] li[data-peer-id="${e}"]`)).forEach((e=>{this.setDialogActive(e,!0)}))})),a.default.addEventListener("filter_update",(e=>{if(this.filtersRendered[e.id]){if(e.id===this.filterId){const e=i.Z.dialogsStorage.getCachedDialogs(!0);this.validateListForFilter();for(let t=0,s=e.length;t<s;++t){const s=e[t];this.updateDialog(s)}}this.filtersRendered[e.id].title.innerHTML=Q.o.wrapEmojiText(e.title)}else this.addFilter(e)})),a.default.addEventListener("filter_delete",(e=>{const t=this.filtersRendered[e.id];t&&(this.folders.menu.firstElementChild.click(),t.container.remove(),t.menu.remove(),delete this.sortedLists[e.id],delete this.scrollables[e.id],delete this.filtersRendered[e.id],this.onFiltersLengthChange())})),a.default.addEventListener("filter_order",(e=>{const t=this.folders.menu;e.forEach((e=>{const s=i.Z.filtersStorage.getFilter(e),n=this.filtersRendered[e];this.sortedLists[e].indexKey=i.Z.dialogsStorage.getDialogIndexKey(e),Zs(n.menu,t,s.orderIndex),Zs(n.container,this.folders.container,s.orderIndex)})),this.indexKey=i.Z.dialogsStorage.getDialogIndexKey(this.filterId)})),a.default.addEventListener("peer_typings",(({peerId:e,typings:t})=>{const s=i.Z.getDialogOnly(e);s&&(t.length?this.setTyping(s):this.unsetTyping(s))}))}setDialogActive(e,t){const s=e.dialogDom;e.classList.toggle("active",t),t?this.lastActiveElements.add(e):this.lastActiveElements.delete(e),(null==s?void 0:s.callIcon)&&s.callIcon.setActive(t)}onStateLoaded(e){return ld(this,void 0,void 0,(function*(){if(e.notifySettings)for(const t in e.notifySettings)(0,gs.Z)(t),Ft.Z.savePeerSettings({key:t,settings:e.notifySettings[t]});Ft.Z.getNotifyPeerTypeSettings(),this.initedListeners||(this.initListeners(),this.initedListeners=!0);const t=i.Z.filtersStorage.getDialogFilters().then((e=>{for(const t of e)this.addFilter(t)}));return e.filters&&Object.keys(e.filters).length&&(yield t,this.showFiltersPromise&&(yield this.showFiltersPromise)),M.default.storagesResults.dialogs.length&&xi.Z.addMissedDialogs(),this.onChatsScroll().then((()=>{i.Z.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"),s=this.getOffsetIndex("bottom");if(!t.index&&!s.index)return!0;const i=e[this.indexKey];return(!t.index||i<=t.index)&&(!s.index||i>=s.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.setLastMessage(e,void 0,t,void 0,void 0,void 0,!0),this.sortedList.update(e.peerId))}setFilterUnreadCount(e){var t;const s=0===e?this.allUnreadCount:null===(t=this.filtersRendered[e])||void 0===t?void 0:t.unread;if(!s)return;const n=i.Z.dialogsStorage.getFolder(e),a=0===e||!!n.dialogs.find((e=>(e.unread_count||e.pFlags.unread_mark)&&!Ft.Z.isPeerLocalMuted(e.peerId,!0)));s.classList.toggle("badge-gray",!a);const o=n.unreadDialogsCount;s.innerText=o?""+o:""}setFiltersUnreadCount(){for(const e in this.filtersRendered)this.setFilterUnreadCount(+e)}validateListForFilter(){const e=i.Z.filtersStorage.getFilter(this.filterId)||null;this.sortedList.getAll().forEach((t=>{const s=i.Z.getDialogOnly(t.id);this.testDialogForFilter(s,e)||this.deleteDialog(t.id)}))}validateDialogForFilter(e,t){this.getDialogDom(e.peerId)&&(this.testDialogForFilter(e,t)||this.deleteDialog(e.peerId))}testDialogForFilter(e,t=i.Z.filtersStorage.getFilter(this.filterId)){return!(!e||t&&!i.Z.filtersStorage.testDialogForFilter(e,t)||!t&&this.filterId!==e.folder_id)}generateScrollable(e,t){const s=new P.ZP(null,"CL",500);s.container.addEventListener("scroll",this.onChatsRegularScroll),s.container.dataset.filterId=""+t,s.onScrolledTop=this.onChatsScrollTop,s.onScrolledBottom=this.onChatsScroll,s.setVirtualContainer(e);const n=new dd(e,i.Z.dialogsStorage?i.Z.dialogsStorage.getDialogIndexKey(t):"index",this.onListLengthChange);return this.scrollables[t]=s,this.sortedLists[t]=n,s}addFilter(e){if(this.filtersRendered[e.id])return;const t=document.createElement("div");t.classList.add("menu-horizontal-div-item");const s=document.createElement("span"),i=document.createElement("span");i.classList.add("text-super"),e.titleEl?i.append(e.titleEl):i.innerHTML=Q.o.wrapEmojiText(e.title);const n=document.createElement("div");n.classList.add("badge","badge-20","badge-primary");const a=document.createElement("i");s.append(i,n,a),(0,ee.ripple)(t),t.append(s),Zs(t,this.folders.menu,e.orderIndex);const o=this.createChatList(),r=this.generateScrollable(o,e.id);r.container.classList.add("tabs-tab","chatlist-parts");const l=document.createElement("div");l.classList.add("chatlist-top");const d=document.createElement("div");d.classList.add("chatlist-bottom"),l.append(o),r.container.append(l,d);const c=r.container;Zs(r.container,this.folders.container,e.orderIndex),this.setListClickListener(o,null,!0),this.filtersRendered[e.id]={menu:t,container:c,unread:n,title:i},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,s=!this.folders.menuScrollContainer.classList.contains("hide");t!==s&&(this.folders.menuScrollContainer.classList.toggle("hide",!t),t&&!s&&this.setFiltersUnreadCount(),this.chatsContainer.classList.toggle("has-filters",t)),this.changeFiltersAllChatsKey(),this.showFiltersPromise=void 0,e()}),0)}))),this.showFiltersPromise}loadDialogs(e){if(this.loadDialogsPromise)return this.loadDialogsPromise;const t=new Promise((s=>ld(this,void 0,void 0,(function*(){const{chatList:n,filterId:a,indexKey:o}=this;let r=Ct.Z.height/72*1.25|0,l=0;const{index:d}=this.getOffsetIndex(e);if(d)if("top"===e){const e=i.Z.dialogsStorage.getFolderDialogs(a,!0),t=e.findIndex((e=>e[o]<=d)),s=Math.max(0,t-r);r=t-s,l=e[s][o]+1}else l=d;try{const s=i.Z.getConversations("",l,r,a,!0);s.cached||n.childElementCount||n.parentElement.append(this.chatsPreloader);const d=yield s.promise;if(this.loadDialogsPromise!==t)return;if("bottom"===e?d.isEnd&&(this.scroll.loadedAll[e]=!0):d.isTopEnd&&(this.scroll.loadedAll[e]=!0),this.loadedDialogsAtLeastOnce=!0,d.dialogs.length){const t="top"===e?d.dialogs.slice().reverse():d.dialogs,s=[],n=[],a=e=>{n.push(e)};t.forEach((e=>{if(!i.Z.getDialogOnly(e.peerId))return;const t=this.sortedList.add(e.peerId,!0,a,!1);t.loadPromises&&s.push(...t.loadPromises)})),yield Promise.all(s).finally(),n.forEach((e=>e()))}else this.onListLengthChange();const c=d.dialogs["top"===e?0:d.dialogs.length-1];c&&(this.offsets[e]=c[o]),this.log.debug("getDialogs "+r+" dialogs by offset:",l,d,n.childElementCount),setTimeout((()=>{this.scroll.onScroll()}),0)}catch(e){this.log.error(e)}this.chatsPreloader.parentElement&&this.chatsPreloader.remove(),s()})))).finally((()=>{this.loadDialogsPromise=void 0}));return this.loadDialogsPromise=t}generateEmptyPlaceholder(e){const t="empty-placeholder",s=document.createElement("div");s.classList.add(t,t+"-"+e.classNameType);const i=document.createElement("div");i.classList.add(t+"-header"),(0,k._i18n)(i,e.title);const n=document.createElement("div");return n.classList.add(t+"-subtitle"),e.subtitle&&(0,k._i18n)(n,e.subtitle,e.subtitleArgs),s.append(i,n),{container:s,header:i,subtitle:n}}checkIfPlaceholderNeeded(){if(1===this.filterId)return;const e=this.chatList,t=e.parentElement;let s=Array.from(t.children).find((e=>e.matches(".empty-placeholder")));const n=this.scroll.loadedAll.bottom&&!e.childElementCount;if(n&&s)return;if(!n)return void(s&&(t.classList.remove("with-placeholder"),s.remove()));let a,o;if(this.filterId){a=this.generateEmptyPlaceholder({title:"FilterNoChatsToDisplay",subtitle:"FilterNoChatsToDisplayInfo",classNameType:o="folder"}),s=a.container,s.prepend(function({emoji:e,width:t,height:s}){const i=document.createElement("div"),n=ds.Z.getAnimatedEmojiSticker(e);return n?Is({doc:n,div:i,loop:!1,play:!0,width:t,height:s,emoji:e}).then((()=>{})):i.classList.add("media-sticker-wrapper"),{container:i}}({emoji:"📂",width:128,height:128}).container);const e=(0,U.Z)("btn-primary btn-color-primary btn-control tgico",{text:"FilterHeaderEdit",icon:"settings"});(0,l.fc)(e,(()=>{new tn(xn).open(i.Z.filtersStorage.getFilter(this.filterId))})),s.append(e)}else{a=this.generateEmptyPlaceholder({title:"ChatList.Main.EmptyPlaceholder.Title",classNameType:o="dialogs"}),s=a.container;const e=document.createElement("img");e.classList.add("empty-placeholder-dialogs-icon"),this.emptyDialogsPlaceholderSubtitle=new k.default.IntlElement({element:a.subtitle}),Promise.all([this.updateContactsLength(!1),(0,rs.cj)(e,"assets/img/EmptyChats.svg"),(0,De.AD)()]).then((([e])=>{s.classList.add("visible"),t.classList.toggle("has-contacts",!!e)})),s.prepend(e)}t.append(s),t.classList.add("with-placeholder"),t.dataset.placeholderType=o}updateContactsLength(e){return this.updateContactsLengthPromise?this.updateContactsLengthPromise:this.updateContactsLengthPromise=E.Z.getContacts().then((t=>{const s=this.emptyDialogsPlaceholderSubtitle;if(s){let e,i;t.length?(e="ChatList.Main.EmptyPlaceholder.Subtitle",i=[(0,k.i18n)("Contacts.Count",[t.length])]):(e="ChatList.Main.EmptyPlaceholder.SubtitleNoContacts",i=[]),s.compareAndUpdate({key:e,args:i})}return e&&this.chatList.parentElement.classList.toggle("has-contacts",!!t.length),this.updateContactsLengthPromise=void 0,t.length}))}removeContactsPlaceholder(){const e=this.chatList,t=e.parentElement.parentElement,s=e.parentElement.nextElementSibling;t.classList.remove("with-contacts"),s.innerHTML="",this.loadContacts=void 0,this.processContact=void 0}setOffsets(){const e=this.chatList,t=this.getDialogFromElement(e.firstElementChild),s=this.getDialogFromElement(e.lastElementChild),i=this.indexKey;this.offsets.top=t[i],this.offsets.bottom=s[i]}getDialogFromElement(e){return i.Z.getDialogOnly(e.dataset.peerId.toPeerId())}setListClickListener(e,t,s=!1,n=!1,a=!1){let o;const r=(a?Ol.setInnerPeer:Ol.setPeer).bind(Ol);e.dataset.autonomous=""+ +n,e.addEventListener("mousedown",(e=>{if(0!==e.button)return;this.log("dialogs click list");const s=e.target,i=(0,ft.Z)(s,"LI");if(i){if(n){const e=o===i;o&&!e&&o.classList.remove("active"),i&&(i.classList.add("active"),o=i,this.lastActiveElements.add(i))}if(i){t&&t();const e=i.dataset.peerId.toPeerId(),s=+i.dataset.mid||void 0;r({peerId:e,lastMsgId:s})}else r()}}),{capture:!0}),re.ZP&&e.addEventListener("dblclick",(e=>{const t=(0,ft.Z)(e.target,"LI");if(t){const e=t.dataset.peerId.toPeerId();this.log("debug dialog:",i.Z.getDialogByPeerId(e))}})),s&&(0,J.Eo)(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}setLastMessage(e,t,s,n,l,d=!1,c=!1){if(!s&&!(s=this.getDialogDom(e.peerId)))return;let h;if(t||(e.draft&&"draftMessage"===e.draft._&&(h=e.draft),t=i.Z.getMessageByPeer(e.peerId,e.top_message)),"messageEmpty"===t._)return s.lastMessageSpan.innerHTML="",s.lastTimeSpan.innerHTML="",delete s.listEl.dataset.mid,void(c&&this.setUnreadMessages(e,s,d));const p=e.peerId,u=t&&i.Z.isRestricted(t);{let e;if(!t.deleted&&!h&&!u){const s=i.Z.getMediaFromMessage(t);if(s&&("photo"===s._||["video","gif"].includes(s.type))){const i=r.Z.choosePhotoSize(s,20,20);if("photoSizeEmpty"!==i._&&(e=document.createElement("div"),e.classList.add("dialog-subtitle-media"),Ss({photo:s,message:t,container:e,withoutPreloader:!0,size:i,loadPromises:l}),"video"===s.type)){const t=document.createElement("span");t.classList.add("tgico-play"),e.append(t)}}}const d=!!e&&!!(null==t?void 0:t.message);let c;if(c=n&&t.message?i.Z.wrapMessageForReply(t,void 0,void 0,!1,n,d):h?i.Z.wrapMessageForReply(h):t.deleted?document.createDocumentFragment():i.Z.wrapMessageForReply(t,void 0,void 0,!1,void 0,d),e&&c.prepend(e),(0,T.Z)(s.lastMessageSpan,c),h){const e=document.createElement("b");e.classList.add("danger"),e.append((0,k.i18n)("Draft"),": "),s.lastMessageSpan.prepend(e)}else if(p.isAnyChat()&&p!==t.fromId&&!t.action){const e=o.Z.getPeer(t.fromId);if(e&&e.id){const i=document.createElement("b");e.id===a.default.myId?i.append((0,k.i18n)("FromYou")):i.append(new St.Z({peerId:t.fromId,onlyFirstName:!0}).element),i.append(": "),s.lastMessageSpan.prepend(i)}}}if(!t.deleted||h){const e=h?Math.max(h.date,t.date||0):t.date;(0,T.Z)(s.lastTimeSpan,(0,ie.zM)(new Date(1e3*e)))}else s.lastTimeSpan.textContent="";null!==c&&(c?this.setUnreadMessages(e,s,d):s.listEl.dataset.mid=t.mid)}setUnreadMessages(e,t=this.getDialogDom(e.peerId),s=!1){var n;if(!t)return;if(!s){const s=Ft.Z.isPeerLocalMuted(e.peerId,!0);s!==t.listEl.classList.contains("is-muted")&&(0,Jt.Z)(t.listEl,"is-muted",s,200)}let o;if("draftMessage"!==(null===(n=e.draft)||void 0===n?void 0:n._)){const t=i.Z.getMessageByPeer(e.peerId,e.top_message);!t.deleted&&t.pFlags.out&&t.peerId!==a.default.myId&&(o=t)}!function(e,t,s){let i;if((null==t?void 0:t.pFlags.out)&&(i=t.pFlags.is_outgoing?"sending":t.pFlags.unread?"check":"checks"),!i)return void(e.textContent="");const n="tgico-"+i,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,o);const r=i.Z.filtersStorage.getFilter(this.filterId);let l;l=r?-1!==r.pinnedPeerIds.indexOf(e.peerId):!!e.pFlags.pinned;const d=i.Z.isDialogUnread(e),c=l||d,h=(0,cs.Z)(t.unreadBadge);c&&!h&&t.subtitleEl.append(t.unreadBadge);const p=e.unread_mentions_count&&(e.unread_mentions_count>1||e.unread_count>1),u=t.mentionsBadge&&(0,cs.Z)(t.mentionsBadge);p&&(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)));const g=s?0:200;if((0,Jt.Z)(t.unreadBadge,"is-visible",c,g,c?void 0:()=>{t.unreadBadge.remove()},h?0:2),t.mentionsBadge&&(0,Jt.Z)(t.mentionsBadge,"is-visible",p,g,p?void 0:()=>{t.mentionsBadge.remove(),delete t.mentionsBadge},u?0:2),!c)return;l?t.unreadBadge.classList.add("tgico-chatspinned","tgico"):t.unreadBadge.classList.remove("tgico-chatspinned","tgico");let m=!0,v=!1;e.unread_mentions_count&&1===e.unread_count?(t.unreadBadge.innerText="@",v=!0):d?t.unreadBadge.innerText=""+(e.unread_count||" "):(t.unreadBadge.innerText="",m=!1),t.unreadBadge.classList.toggle("unread",m),t.unreadBadge.classList.toggle("mention",v)}getDialogDom(e){const t=this.sortedList.get(e);return null==t?void 0:t.dom}getDialog(e){if("object"!=typeof e){const t=i.Z.getDialogOnly(e);if(!t){const t=e||Re.NM;return{peerId:t,peer:o.Z.getOutputPeer(t),pFlags:{}}}return t}return e}setCallStatus(e,t){let{callIcon:s,listEl:i}=e;if(!s&&t){const{canvas:t,startAnimation:n}=e.callIcon=s=function(e=!1){const t=document.createElement("canvas");t.width=t.height=nd;const s=t.getContext("2d"),i=(nd-(3*od+2*ad))/2,n=Date.now();let a=!1;const o=()=>{if(t.isConnected)a||(a=t.isConnected);else if(a)return!1;const o=(r=(Date.now()-n)%1e3,-.5*(Math.cos(Math.PI*r/1e3)-1)+0);var r;s.clearRect(0,0,nd,nd),s.fillStyle=e&&!v.ZP.isMobile?gr.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*=id,sd(s,i+e*od+e*ad,(nd-n)/2,od,n,rd,!0)}return!0};return{canvas:t,startAnimation:()=>{(0,Ue.jt)(o),o()},setActive:t=>{e=t,o()}}}(i.classList.contains("active"));t.classList.add("dialog-group-call-icon"),i.append(t),n()}s&&(0,Jt.Z)(e.callIcon.canvas,"is-visible",t,200,t?void 0:()=>{e.callIcon.canvas.remove(),e.callIcon=void 0},t?2:0)}addListDialog(e){const t=this.getDialog(e.dialog);e.autonomous=!1;const s=this.addDialogNew(e);if(s){const{peerId:i}=t;Ft.Z.isPeerLocalMuted(i,!0)&&s.dom.listEl.classList.add("is-muted"),i.isUser()||this.processDialogForCallStatus(t,s.dom),this.setLastMessage(t,void 0,s.dom,void 0,e.loadPromises,e.isBatch,!0)}return s}processDialogForCallStatus(e,t){if(!Wo)return;if(t||(t=this.getDialogDom(e.peerId)),!t)return;const s=j.Z.getChat(e.peerId.toChatId());this.setCallStatus(t,!(!s.pFlags.call_active||!s.pFlags.call_not_empty))}addDialogAndSetLastMessage(e){const{peerId:t,message:s,query:n}=e,a=hd.addDialogNew(Object.assign(Object.assign(Object.assign({},e),i.Z.getMessageSenderPeerIdOrName(s)),{dialog:this.getDialog(t)}));return this.setLastMessage(a.dialog,s,a.dom,n),s.peerId!==t&&(a.dom.listEl.dataset.peerId=""+s.peerId),a}addDialogNew(e){return this.addDialog(e.dialog,e.container,e.drawStatus,e.rippleEnabled,e.onlyFirstName,e.meAsSaved,e.append,e.avatarSize,e.autonomous,e.lazyLoadQueue,e.loadPromises,e.fromName)}addDialog(e,t,s=!0,i=!0,n=!1,r=!0,l=!0,d=54,c=!!t,h,p,u){var g,m,v;const f=this.getDialog(e),b=f.peerId,y=new Yl;y.loadPromises=p,y.lazyLoadQueue=h,y.setAttribute("dialog",r?"1":"0"),void 0!==u&&y.setAttribute("peer-title",u),y.setAttribute("peer",""+b),y.classList.add("dialog-avatar","avatar-"+d),s&&b!==a.default.myId&&b.isUser()&&"userStatusOnline"===(null===(g=E.Z.getUser(b).status)||void 0===g?void 0:g._)&&this.setOnlineStatus(y,!0);const w=document.createElement("div");w.classList.add("user-caption");const S=document.createElement("span");S.classList.add("user-title");const C=new St.Z({peerId:b,fromName:u,dialog:r,onlyFirstName:n,plainText:!1});S.append(C.element),S.classList.add("tgico");const L=o.Z.getPeer(b);(null===(m=null==L?void 0:L.pFlags)||void 0===m?void 0:m.verified)&&S.append(Ot());const I=document.createElement("span");I.classList.add("user-last-message"),I.setAttribute("dir","auto");const M=document.createElement("li");M.classList.add("chatlist-chat"),i&&(0,ee.ripple)(M),M.append(y,w),M.dataset.peerId=""+b;const P=document.createElement("span");P.classList.add("message-status","sending-status");const T=document.createElement("span");T.classList.add("message-time");const k=document.createElement("div");k.className="dialog-subtitle-badge badge badge-24";const x=document.createElement("p");x.classList.add("dialog-title");const A=document.createElement("span");A.classList.add("dialog-title-details"),A.append(P,T),x.append(S,A);const _=document.createElement("p");_.classList.add("dialog-subtitle"),_.append(I),w.append(x,_);const Z={avatarEl:y,captionDiv:w,titleSpan:C.element,titleSpanContainer:S,statusSpan:P,lastTimeSpan:T,unreadBadge:k,lastMessageSpan:I,containerEl:M,listEl:M,subtitleEl:_};return t&&t[l?"append":"prepend"](M),c||(M.dialogDom=Z,(null===(v=Ol.chat)||void 0===v?void 0:v.peerId)===b&&this.setDialogActive(M,!0)),{dom:Z,dialog:f}}setTyping(e){const t=this.getDialogDom(e.peerId);if(!t)return;const s=t.lastMessageSpan.querySelector(".peer-typing-container"),i=Ol.getPeerTyping(e.peerId,s);!s&&i&&((0,T.Z)(t.lastMessageSpan,i),t.lastMessageSpan.classList.add("user-typing"))}unsetTyping(e){const t=this.getDialogDom(e.peerId);t&&(t.lastMessageSpan.classList.remove("user-typing"),this.setLastMessage(e,null,t,void 0,void 0,void 0,null))}}const hd=new cd;re.GO.appDialogsManager=hd;const pd=hd},634:(e,t,s)=>{"use strict";s.d(t,{Z:()=>o});var i=s(410),n=s(9518);const a=new class{getState(){return n.Z.invokeApi("account.getPassword").then((e=>e))}updateSettings(e={}){return this.getState().then((t=>{let s,i;const a={password:null,new_settings:{_:"account.passwordInputSettings",hint:e.hint,email:e.email}};s=e.currentPassword?n.Z.invokeCrypto("computeSRP",e.currentPassword,t,!1):Promise.resolve({_:"inputCheckPasswordEmpty"});const o=t.new_algo,r=new Uint8Array(o.salt1.length+32);return r.randomize(),r.set(o.salt1,0),o.salt1=r,i=e.newPassword?n.Z.invokeCrypto("computeSRP",e.newPassword,t,!0):Promise.resolve(new Uint8Array),Promise.all([s,i]).then((e=>(a.password=e[0],a.new_settings.new_algo=o,a.new_settings.new_password_hash=e[1],n.Z.invokeApi("account.updatePasswordSettings",a))))}))}check(e,t,s={}){return n.Z.invokeCrypto("computeSRP",e,t,!1).then((e=>n.Z.invokeApi("auth.checkPassword",{password:e},s).then((e=>("auth.authorization"===e._&&n.Z.setUser(e.user),e)))))}confirmPasswordEmail(e){return n.Z.invokeApi("account.confirmPasswordEmail",{code:e})}resendPasswordEmail(){return n.Z.invokeApi("account.resendPasswordEmail")}cancelPasswordEmail(){return n.Z.invokeApi("account.cancelPasswordEmail")}};i.GO.passwordManager=a;const o=a},4329:function(e){"undefined"!=typeof self&&self,e.exports=function(e){var t={};function s(i){if(t[i])return t[i].exports;var n=t[i]={i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,s),n.l=!0,n.exports}return s.m=e,s.c=t,s.d=function(e,t,i){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(s.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)s.d(i,n,function(t){return e[t]}.bind(null,n));return i},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=0)}([function(e,t,s){"use strict";(function(t){var s=t.AudioContext||t.webkitAudioContext,i=function(e){if(!i.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};i.isRecordingSupported=function(){return s&&t.navigator&&t.navigator.mediaDevices&&t.navigator.mediaDevices.getUserMedia&&t.WebAssembly},i.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)},i.prototype.encodeBuffers=function(e){if("recording"===this.state){for(var t=[],s=0;s<e.numberOfChannels;s++)t[s]=e.getChannelData(s);this.encoder.postMessage({command:"encode",buffers:t})}},i.prototype.initAudioContext=function(e){return e&&e.context?(this.audioContext=e.context,this.closeAudioContext=!1):(this.audioContext=new s,this.closeAudioContext=!0),this.audioContext},i.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)},i.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))))},i.prototype.loadWorker=function(){this.encoder||(this.encoder=new t.Worker(this.config.encoderPath))},i.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,s)=>{var i=s=>{switch(s.data.message){case"ready":t();break;case"page":this.encodedSamplePosition=s.data.samplePosition,e(s.data.page);break;case"done":this.encoder.removeEventListener("message",i),this.finish()}};this.encoder.addEventListener("message",i),this.encoder.postMessage(Object.assign({command:"init",originalSampleRate:this.audioContext.sampleRate,wavSampleRate:this.audioContext.sampleRate},this.config))}))},i.prototype.pause=function(e){if("recording"===this.state){if(this.state="paused",e&&this.config.streamPages){var t=this.encoder;return new Promise(((e,s)=>{var i=s=>{"flushed"===s.data.message&&(t.removeEventListener("message",i),this.onpause(),e())};t.addEventListener("message",i),t.postMessage({command:"flush"})}))}return this.onpause(),Promise.resolve()}},i.prototype.resume=function(){"paused"===this.state&&(this.state="recording",this.onresume())},i.prototype.setRecordingGain=function(e){this.config.recordingGain=e,this.recordingGainNode&&this.audioContext&&this.recordingGainNode.gain.setTargetAtTime(e,this.audioContext.currentTime,.01)},i.prototype.setMonitorGain=function(e){this.config.monitorGain=e,this.monitorGainNode&&this.audioContext&&this.monitorGainNode.gain.setTargetAtTime(e,this.audioContext.currentTime,.01)},i.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)}))},i.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 s=i=>{"done"===i.data.message&&(e.removeEventListener("message",s),t())};e.addEventListener("message",s),e.postMessage({command:"done"}),this.config.reuseWorker||e.postMessage({command:"close"})}))}return Promise.resolve()},i.prototype.destroyWorker=function(){"inactive"===this.state&&this.encoder&&(this.encoder.postMessage({command:"close"}),delete this.encoder)},i.prototype.storePage=function(e){this.recordedPages.push(e),this.totalLength+=e.length},i.prototype.streamPage=function(e){this.ondataavailable(e)},i.prototype.finish=function(){if(!this.config.streamPages){var e=new Uint8Array(this.totalLength);this.recordedPages.reduce((function(t,s){return e.set(s,t),t+s.length}),0),this.ondataavailable(e)}this.onstop(),this.config.reuseWorker||delete this.encoder},i.prototype.ondataavailable=function(){},i.prototype.onpause=function(){},i.prototype.onresume=function(){},i.prototype.onstart=function(){},i.prototype.onstop=function(){},e.exports=i}).call(this,s(1))},function(e,t){var s;s=function(){return this}();try{s=s||new Function("return this")()}catch(e){"object"==typeof window&&(s=window)}e.exports=s}])}}]);
//# sourceMappingURL=664.22c6afb6ed739f8b3773.chunk.js.map