tweb/public/14.11183df10f220f2bd1db.chunk.js
morethanwords 9f65dd79ec 1.0.0
2021-12-11 21:22:24 +04:00

2 lines
666 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.webpackJsonp=this.webpackJsonp||[]).push([[14],{101:function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var i=s(51);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.a.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.a.waitForFirstFrame(e)))}remove(){this.animation&&this.animation.remove()}}},112:function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var i=s(51);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.a.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.a.waitForFirstFrame(e))),i.a.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.a.waitForFirstFrame(e)))])}remove(){this.animation&&this.animation.remove(),this.idleAnimation&&this.idleAnimation.remove()}}},113:function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var i=s(38);class n extends i.b{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})}}},148:function(e,t,s){"use strict";s.r(t),s.d(t,"AppDialogsManager",(function(){return Pr}));var i=s(40),n=s(71),a=s(15),o=s(44),r=s(53),l=s(30),c=s(5),d=s(117),h=s(147),p=s(151);const u=[...h.a].concat([...p.a]);var m=new Set(u);function g(e,t){e.setAttribute("dir","auto"),e.innerHTML=t}var b=s(37),v=s(102),f=s(41);function y(e){Object(f.d)(e.history,(t,s,i)=>{t.action.photo||(i.splice(s,1),void 0!==e.count&&--e.count)})}var w=s(32);class S{constructor(e){this.previous=[],this.next=[],this.reverse=!1,this.loadCount=50,this.loadWhenLeft=20,this.loadedAllUp=!1,this.loadedAllDown=!1,Object(w.g)(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=>{if(e&&this.loadPromiseDown!==s||!e&&this.loadPromiseUp!==s)return;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):f.d.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 L 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=v.a.incrementMessageId(o,1)),i.a.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)};Object(f.d)(this.previous,i),Object(f.d)(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.a.getScheduledMessagesStorage(this.searchContext.peerId):i.a.getMessagesStorage(this.searchContext.peerId);return i.a.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 E=s(66),C=s(68),I=s(62),M=s(17),P=s(39),T=s(47),k=s(36),x=s(16);class O{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=kr.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(Object(x.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&&kr.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 T.b(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.a.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=>{const s=this.peerId?t.fromId:t.peerId,{dialog:i,dom:n}=kr.addDialogNew({dialog:s,container:this.scrollable,drawStatus:!1,avatarSize:54,meAsSaved:!1});t.peerId!==s&&(n.listEl.dataset.peerId=""+t.peerId),kr.setLastMessage(i,t,n,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&&Object(k.a)(n.nameEl,Object(x.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(38);class F{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 _.b({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(124),j=s(50),B=s(54),R=s(87),U=s(34);var H=(e,t={})=>Object(U.a)("btn-icon",Object.assign({icon:e||void 0},t)),N=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 z{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=H("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 T.b(this.content,void 0,void 0,!0),this.container.append(this.header,this.content),this.slider.addTab(this),this.listenerSetter=new R.a}close(){return this.slider.closeTab(this)}open(...e){return N(this,void 0,void 0,(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)}return this.slider.selectTab(this)}))}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(Object(x.i18n)(e))}}class V extends z{constructor(e){super(e),this.eventListener=new B.a}onCloseAfterTimeout(){return this.eventListener.dispatchEvent("destroy"),this.eventListener.cleanup(),super.onCloseAfterTimeout()}}class G{constructor(e){this.historyTabIds=[],this.canHideFirst=!1,this.onCloseBtnClick=()=>{j.a.findItemByType(this.navigationType)?j.a.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 z?n.container:n:this.canHideFirst?-1:0,t),!0},Object(w.g)(this,e),this.tabs||(this.tabs=new Map),this.tabsContainer=this.sidebarEl.querySelector(".sidebar-slider"),this._selectTab=Object(D.a)(this.tabsContainer,"navigation",250),this.canHideFirst||this._selectTab(0),Array.from(this.sidebarEl.querySelectorAll(".sidebar-close-button")).forEach(e=>{Object(l.b)(e,this.onCloseBtnClick)})}selectTab(e){if(this.historyTabIds[this.historyTabIds.length-1]===e)return!1;const t=e instanceof z?e:this.tabs.get(e);return t&&(t.onOpen&&t.onOpen(),t.onOpenAfterTimeout&&setTimeout(()=>{t.onOpenAfterTimeout()},250)),j.a.pushItem({type:this.navigationType,onPop:e=>(this.closeTab(void 0,e,!0),!0)}),this.historyTabIds.push(e),this._selectTab(e instanceof z?e.container:e),!0}removeTabFromHistory(e){Object(f.e)(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||j.a.removeByType(this.navigationType,!0);const i=e instanceof z?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 K=s(48),W=s(138);class q{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),this.container.addEventListener("click",()=>{(new W.a).open(this.canvas,e)})}clear(){this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height)}}var Q=(e={})=>Object(U.a)("btn-circle btn-corner z-depth-1"+(e.className?" "+e.className:""),e);class $ extends z{constructor(){super(...arguments),this.searchGroup=new O(!0,"contacts",!0,"new-group-members disable-hover",!1),this.uploadAvatar=null}init(){this.container.classList.add("new-group-container"),this.setTitle("NewGroup"),this.avatarEdit=new q(e=>{this.uploadAvatar=e});const e=document.createElement("div");e.classList.add("input-wrapper"),this.groupNameInputField=new _.b({label:"CreateGroup.NameHolder",maxLength:128}),e.append(this.groupNameInputField.container),this.groupNameInputField.input.addEventListener("input",()=>{const e=this.groupNameInputField.value;this.nextBtn.classList.toggle("is-visible",!!e.length&&!this.groupNameInputField.input.classList.contains("error"))}),this.nextBtn=Q({icon:"arrow_next"}),this.nextBtn.addEventListener("click",()=>{const e=this.groupNameInputField.value;this.nextBtn.disabled=!0,K.a.createChat(e,this.peerIds.map(e=>e.toUserId())).then(e=>{this.uploadAvatar&&this.uploadAvatar().then(t=>{K.a.editPhoto(e,t)}),mn.removeTabFromHistory(this),mn.selectTab(0)})});const t=document.createElement("div");t.classList.add("chatlist-container"),t.append(this.searchGroup.container),this.content.append(this.nextBtn),this.scrollable.append(this.avatarEdit.container,e,t)}onCloseAfterTimeout(){this.searchGroup.clear(),this.avatarEdit.clear(),this.uploadAvatar=null,this.groupNameInputField.value="",this.nextBtn.disabled=!1}open(e){const t=super.open();return t.then(()=>{this.peerIds=e,this.peerIds.forEach(e=>{let{dom:t}=kr.addDialogNew({dialog:e,container:this.searchGroup.list,drawStatus:!1,rippleEnabled:!1,avatarSize:48});t.lastMessageSpan.append(P.a.getUserStatusString(e))}),this.searchGroup.nameEl.textContent="",this.searchGroup.nameEl.append(Object(x.i18n)("Members",[this.peerIds.length])),this.searchGroup.setActive()}),t}}var Y=s(78),X=s(43),J=s(31),Z=s(123),ee=s(75),te=s(35),se=s(18),ie=s(93),ne=s(88),ae=s(46),oe=s(56),re=s(0),le=s(51),ce=s(149),de=s(29),he=s(73),pe=s(52),ue=s(1),me=s(104),ge=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 be=(()=>{try{return re.IS_SAFARI&&+navigator.userAgent.match(/ Version\/(\d+)/)[1]<14}catch(e){return!1}})();const ve=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.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=E.a.getDoc(t.docId);"audio"===s.type&&s.supportsStreaming&&be&&this.handleSafariStreamable(e);const i=he.a.getCacheContext(s);e.src=i.url;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:n,mid:o}=s,r=this.getMessageByMedia(t);if(this.playingMedia!==t){this.stop();const e=e=>e.mid===o&&e.peerId===n;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:n,mid:o})}this.setMedia(t,r)}setTimeout(()=>{a.default.dispatchEvent("media_play",{doc:i.a.getMediaFromMessage(r),message:r,media:t})},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,Object(pe.a)(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,!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),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 c=l.get(o);if(c)return c;const d=i.a.getMediaFromMessage(e);l.set(o,c=document.createElement("round"===d.type||"video"===d.type?"video":"audio")),"round"===d.type&&c.setAttribute("playsinline","true");const h={peerId:n,mid:o,docId:d.id,clean:s,isScheduled:e.pFlags.is_scheduled};this.mediaDetails.set(c,h),c.volume=1,this.container.append(c),c.addEventListener("play",this.onPlay),c.addEventListener("pause",this.onPause),c.addEventListener("ended",this.onEnded),"audio"!==d.type&&(null==e?void 0:e.pFlags.media_unread)&&e.fromId!==a.default.myId&&c.addEventListener("timeupdate",()=>{i.a.readMessages(n,[o])},{once:!0});const p=Object(ae.a)();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=he.a.getCacheContext(d);if(d.supportsStreaming||e.url)this.onMediaDocumentLoad(c);else{let e=this.waitingDocumentsForLoad[d.id];e||(e=this.waitingDocumentsForLoad[d.id]=new Set),e.add(c),E.a.downloadDoc(d)}}),c}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;return ge(this,void 0,void 0,(function*(){yield Object(me.e)(t,void 0,!1);const n=i.a.getMediaFromMessage(e),a=[],l="voice"===n.type||"round"===n.type;let c="",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=he.a.getCacheContext(n,s.type);if(i.url)a.push({src:i.url,sizes:`${s.w}x${s.h}`,type:"image/jpeg"});else{r.a.preloadPhoto(n,s).then(()=>{this.playingMedia===t&&i.url&&this.setNewMediadata(e)})}}}else if(l){const s=e.fromId||e.peerId,i=o.a.getPeerPhoto(s);if(i){const n=d.a.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)})}c=o.a.getPeerTitle(s,!0,!1),h=x.default.format("voice"===n.type?"AttachAudio":"AttachRound",!0)}if(!l){const e=n.attributes.find(e=>"documentAttributeAudio"===e._);c=e&&e.title||n.file_name,h=e&&e.performer}a.length||(re.IS_APPLE?ue.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:c,artist:h,artwork:a});navigator.mediaSession.metadata=p}))}getMessageByMedia(e){const t=this.mediaDetails.get(e),{peerId:s,mid:n}=t;return t.isScheduled?i.a.getScheduledMessageByPeer(s,n):i.a.getMessageByPeer(s,n)}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!Object(w.b)(this.searchContext,e)&&(this.searchContext=Object(w.a)(e),!0)}getSearchContext(){return this.searchContext}setTargets(e,t,s){this.listLoader?this.listLoader.reset():this.listLoader=new L({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)}setMedia(e,t){this.playingMedia=e,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}};de.a.appMediaPlaybackController=ve;var fe=ve,ye=s(103);function we(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",c,{passive:!1,once:!0}),i&&i({x:t.touches[0].clientX,y:t.touches[0].clientY,isTouch:!0,event:t})},c=e=>{t({x:e.touches[0].clientX,y:e.touches[0].clientY,isTouch:!0,event:e}),r(e),document.addEventListener("touchmove",r,{passive:!1}),document.addEventListener("touchend",l,{passive:!1,once:!0})};return e.addEventListener("touchstart",c,{passive:!1,once:!0}),()=>{e.removeEventListener("mousedown",o),document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",a),e.removeEventListener("touchstart",c),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",l)}}class Se{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)},Object(w.g)(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=we(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=Object(I.a)(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=Object(I.a)(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=Object(I.a)(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 Le=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"+(t?" tgico-"+t:""),Object(se.ripple)(o);let r=e.textElement;r||(r=e.textElement=s?Object(x.i18n)(s):document.createElement("span"),e.regularText&&(r.innerHTML=e.regularText)),r.classList.add("btn-menu-item-text"),o.append(r);const d=!!n||!!e.keepOpen;return Object(l.b)(o,e=>{Object(c.a)(e);!1!==i(e)&&(d||Object(te.c)(),n&&!a&&(n.checked="radio"===n.input.type||!n.checked))},e.options),n&&o.append(n.label),e.element=o};var Ee=(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(Le);return s.append(...i),s};const Ce=(e,t,s)=>{((null==s?void 0:s.listenerSetter)?s.listenerSetter.add(e):e.addEventListener.bind(e))(l.a,s=>{if(!e.classList.contains("btn-menu-toggle"))return!1;const i=e.querySelector(".btn-menu");Object(c.a)(s),e.classList.contains("menu-open")?Object(te.c)():(t&&t(s),Object(te.d)(i))})};var Ie=(e={},t,s,i)=>{e.asDiv=!0;const n=H("more btn-menu-toggle",e),a=Ee(s,e.listenerSetter);return a.classList.add(t),Ce(n,i,e),n.append(a),n},Me=s(6);class Pe extends B.a{constructor(){super(!1),this.hideControls=()=>{clearTimeout(this.showControlsTimeout),this.showControlsTimeout=0;const e=this.element.classList.contains("show-controls");if(!1!==this.controlsLocked){if(this.canHideControls&&!this.canHideControls()||!e||this.controlsLocked)return}else if(!e)return;this.dispatchEvent("toggleControls",!1),this.element.classList.remove("show-controls")},this.showControls=(e=!0)=>{this.showControlsTimeout?(clearTimeout(this.showControlsTimeout),this.showControlsTimeout=0):this.element.classList.contains("show-controls")||!1===this.controlsLocked||(this.dispatchEvent("toggleControls",!0),this.element.classList.add("show-controls")),e&&!this.controlsLocked&&(this.showControlsTimeout=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.showControlsTimeout=0}setup(e){Object(w.g)(this,e);const{listenerSetter:t,element:s}=this;ue.IS_TOUCH_SUPPORTED?t.add(s)("click",()=>{this.toggleControls()}):(t.add(s)("mousemove",()=>{this.showControls()}),t.add(s)("mouseenter",()=>{this.showControls(!1)}),t.add(s)("mouseleave",e=>{e.relatedTarget&&this.showOnLeaveToClassName&&Object(Me.a)(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 Te=s(108);class ke extends Se{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(fe.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(fe.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.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 xe extends Se{constructor(e,t=!1){super({step:.01,min:0,max:1,vertical:t},1),this.listenerSetter=e,this.vertical=t,this.onMuteClick=e=>{e&&Object(c.a)(e),fe.muted=!fe.muted},this.setVolume=()=>{const{volume:e,muted:t}=fe;let s;s=!e||t?"M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z":e>.5?"M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z":e>0&&e<.25?"M7 9v6h4l5 5V4l-5 5H7z":"M18.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 9v6h4l5 5V4L9 9H5z";try{this.volumeSvg.innerHTML=`<path d="${s}"></path>`}catch(e){}this.mousedown||this.setProgress(t?0:e)},this.setListeners(),this.setHandlers({onScrub:e=>{const t=Math.max(Math.min(e,1),0);fe.muted=!1,fe.volume=t}}),this.btn=document.createElement("div"),this.btn.classList.add("player-volume"),this.btn.innerHTML='\n <svg class="player-volume__icon" focusable="false" viewBox="0 0 24 24" aria-hidden="true"></svg>\n ',this.btn.classList.add("btn-icon"),this.volumeSvg=this.btn.firstElementChild,this.btn.append(this.container),Object(l.b)(this.volumeSvg,this.onMuteClick,{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.default)("media_playback_params",this.setVolume),this.setVolume()}}class Oe extends Pe{constructor(e,t=!1,s=!1,i){if(super(),this.video=e,this.wrapper=document.createElement("div"),this.wrapper.classList.add("ckin__player"),this.listenerSetter=new R.a,this.setup({element:this.wrapper,listenerSetter:this.listenerSetter,canHideControls:()=>!this.video.paused,showOnLeaveToClassName:"media-viewer-caption"}),e.parentNode.insertBefore(this.wrapper,e),this.wrapper.appendChild(e),this.skin="default",this.stylePlayer(i),"default"===this.skin){const t=this.wrapper.querySelector(".default__controls.ckin__controls");this.progress=new ke(e,s),t.prepend(this.progress.container)}if(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){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 xe(n),d=t.querySelector(".left-controls");l.btn.classList.remove("btn-icon"),d.insertBefore(l.btn,o.parentElement),Array.from(e).forEach(e=>{n.add(e)("click",()=>{this.togglePlay()})}),ue.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;return"KeyF"===i?this.toggleFullScreen():"KeyM"===i?fe.muted=!fe.muted:"Space"===i?this.togglePlay():e.altKey&&"Equal"===i?fe.playbackRate+=.25:e.altKey&&"Minus"===i?fe.playbackRate-=.25:!t.classList.contains("ckin__fullscreen")||"ArrowLeft"!==s&&"ArrowRight"!==s?n=!1:"ArrowLeft"===s?fe.seekBackward({action:"seekbackward"}):fe.seekForward({action:"seekforward"}),n?(Object(c.a)(e),!1):void 0})),n.add(s)("dblclick",()=>{ue.IS_TOUCH_SUPPORTED||this.toggleFullScreen()}),n.add(i)("click",()=>{this.toggleFullScreen()}),Object(Te.a)(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")},{once:!0}),n.add(s)("pause",()=>{this.showControls(!1)})}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():Object(me.e)(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 settings tgico-settings hide" 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=[.25,.5,1,1.25,1.5,2].map(e=>({regularText:1===e?"Normal":""+e,onClick:()=>{this.video.playbackRate=e}})),t=Ee(e),s=this.wrapper.querySelector(".settings");t.classList.add("top-left"),Ce(s),s.append(t)}toggleFullScreen(){const e=this.wrapper;if(re.IS_APPLE_MOBILE){const e=this.video;return e.webkitEnterFullscreen(),void e.enterFullscreen()}Object(Te.d)()?Object(Te.b)():Object(Te.e)(e)}onFullScreen(e){const t=Object(Te.d)();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()}}var Ae=s(115),_e=s(81),Fe=s(96),De=s(42);function je(e){return function(e,t){let s,i=!1;return(...n)=>{s=n,i||(i=!0,e(()=>{i=!1,t(...s)}))}}(De.b,e)}var Be=s(45);function Re(e){e.classList.add("is-voice");const t=e.message,s=i.a.getMediaFromMessage(t);t.pFlags.out&&e.classList.add("is-out");const n=b.b.isMobile?16:23,a=b.b.isMobile?152:190,o=b.b.isMobile?190:256,r=s.duration,d=Object(I.a)(r/60*o,a,o),h=document.createElementNS("http://www.w3.org/2000/svg","svg");h.classList.add("audio-waveform"),h.setAttributeNS(null,"width",""+d),h.setAttributeNS(null,"height",""+n),h.setAttributeNS(null,"viewBox",`0 0 ${d} ${n}`);const p=document.createElement("div");p.classList.add("audio-time"),e.append(h,p);let u=s.attributes.find(e=>"documentAttributeAudio"===e._).waveform||new Uint8Array([]);u=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}(u.slice(0,63));const m=Math.max(...u),g=u.length?u.length:100,v=Math.min(d/4|0,g);let f=0;const y=n-4;let w="";for(let e=0,t=0,s=0;e<g;++e){const i=u[e]||0;if(s+v>=g){s=s+v-g,s<(v+1)/2&&f<i&&(f=i);const e=Math.max((f*y+(m+1)/2)/(m+1),4);w+=`\n <rect x="${t}" y="${n-e}" width="2" height="${e}" rx="1" ry="1"></rect>\n `,t+=4,f=s<(v+1)/2?0:i}else f<i&&(f=i),s+=v}h.insertAdjacentHTML("beforeend",w);const S=Array.from(h.children);let L=e.querySelector(".audio-waveform");return()=>{let t=e.audio;const s=()=>{const e=t.currentTime===t.duration?0:Math.ceil(t.currentTime/t.duration*v);S.forEach((t,s)=>t.classList.toggle("active",s<e))};(!t.paused||t.currentTime>0&&t.currentTime!==t.duration)&&s();const i=je(s);return e.addAudioListener("timeupdate",i),e.addAudioListener("ended",i),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/d*t.duration;t.currentTime=i}L.addEventListener("mouseleave",i=>{e&&(t.play(),e=!1),s=!1}),L.addEventListener("mousemove",t=>{s=!0,e&&i(t)}),L.addEventListener("mousedown",s=>{s.preventDefault(),0===s.button&&(t.paused||t.pause(),i(s),e=!0)}),L.addEventListener("mouseup",i=>{s&&e&&(t.play(),e=!1)}),Object(l.b)(L,e=>{Object(c.a)(e),t.paused||i(e)})},_e.a),()=>{L.remove(),L=null,t=null}}}function Ue(e=!0){const t=new ye.a({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 He=e=>{let t,s;const i=!e.classList.contains("search-super-item"),n=Object(Me.a)(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(", "),c=Array.from(n.querySelectorAll(l)),d=c.indexOf(e),h=c.map(e=>({peerId:e.dataset.peerId.toPeerId(),mid:+e.dataset.mid}));t=h.slice(0,d),s=h.slice(d+1)}return[t,s]};class Ne extends HTMLElement{constructor(){super(...arguments),this.withTime=!1,this.voiceAsMusic=!1,this.showSender=!1,this.listenerSetter=new R.a}render(){var e,t;this.classList.add("audio"),this.dataset.mid=""+this.message.mid,this.dataset.peerId=""+this.message.peerId;const s=i.a.getMediaFromMessage(this.message),n="voice"===s.type,a=!this.voiceAsMusic&&n,o=this.message.pFlags.is_outgoing,r=o&&this.preloader,d=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?Re(this):function(e){const t=e.withTime,s=e.message,n=i.a.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(Object(Fe.a)(n.audioPerformer)),t?a.push(Object(oe.d)(s.date)):a.length||a.push(Object(I.b)(n.size)),e.showSender&&a.push(i.a.wrapSenderToPeer(s)),o.append(...Object(x.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.a;l.dataset.fontWeight=e.dataset.fontWeight,a?l.append(i.a.wrapSenderToPeer(s)):l.innerHTML=n.audioTitle||n.fileName,r.append(l),e.showSender&&r.append(i.a.wrapSentTime(s));const c=e.querySelector(".audio-subtitle");return c.append(o),()=>{let t=!1,s=new ke(e.audio,n.supportsStreaming);e.addAudioListener("ended",()=>{e.classList.remove("audio-show-progress"),c.lastChild.replaceWith(o),t=!1});const i=()=>{t||(e.classList.add("audio-show-progress"),t=!0,s&&c.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),m=this.querySelector(".audio-time");m.innerHTML=d;const g=this.onLoad=e=>{this.onLoad=void 0;const t=this.audio=fe.addMedia(this.message,e),s=this.readyPromise=Object(ae.a)();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?" / "+d:""),n=()=>{m.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&&Object(c.a)(e),s){const e=!!this.searchContext;if(fe.setSearchContext(this.searchContext||{peerId:Be.b,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1})){const[t,s]=e?He(this):[];fe.setTargets({peerId:this.message.peerId,mid:this.message.mid},t,s)}t.play().catch(()=>{})}else t.pause()};return Object(l.b)(h,e=>o(e),{listenerSetter:this.listenerSetter}),this.addAudioListener("ended",()=>{h.classList.remove("playing"),m.innerText=d}),this.addAudioListener("timeupdate",()=>{!t.currentTime&&t.paused||fe.isSafariBuffering(t)||(m.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=Ls({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;g("audio"!==s.type&&!this.noAutoDownload);const i=t=>{if(this.audio.src)return;fe.resolveWaitingForLoadMedia(this.message.peerId,this.message.mid,this.message.pFlags.is_scheduled);const i=()=>{t&&(fe.willBePlayed(this.audio),re.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=Ue(!1),s=Object(ae.a)();s.notifyAll({done:75,total:100}),s.catch(()=>{this.audio.pause(),fe.willBePlayed(void 0)}),s.cancel=()=>{s.cancel=_e.a;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=Ue(),t||(this.readyPromise=Object(ae.a)());const n=()=>{i();const n=E.a.downloadDoc(s);return t||n.then(()=>{this.readyPromise.resolve()}),e.attach(p,!1,n),{download:n}};e.setDownloadFunction(n),n()}this.append(p),this.classList.add("downloading"),this.readyPromise.then(()=>{this.classList.remove("downloading"),p.classList.add("downloaded"),setTimeout(()=>{p.remove()},200),fe.willBePlayedMedia===this.audio&&(this.audio.play(),fe.willBePlayed(void 0))})};(null===(t=this.audio)||void 0===t?void 0:t.src)||("audio"===s.type||this.noAutoDownload?Object(l.b)(h,()=>{i(!0)},{once:!0,capture:!0,passive:!1,listenerSetter:this.listenerSetter}):i(!1))}}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",Ne);class ze{constructor(e,t){this.className=e,this.fill=t,this.container=document.createElement("div"),this.container.className=e,this.border=document.createElement("div"),this.border.classList.add(e+"-border"),this.content=document.createElement("div"),this.content.classList.add(e+"-content"),this.title=document.createElement("div"),this.title.classList.add(e+"-title"),this.title.setAttribute("dir","auto"),this.subtitle=document.createElement("div"),this.subtitle.classList.add(e+"-subtitle"),this.subtitle.setAttribute("dir","auto"),this.content.append(this.title,this.subtitle),this.container.append(this.border,this.content)}}function Ve(e){var t,s;let{title:n,titleEl:a,subtitle:o,subtitleEl:l,mediaEl:c,message:d,loadPromises:h}=e;void 0!==n&&("string"==typeof n&&(n=Object(Y.f)(n,140),n=J.a.wrapEmojiText(n)),Object(k.a)(a,n)),h||(h=[]);let p=d&&d.media,u=!1,m=!1;const g=c?Array.from(c.children).slice():[];let b;if(p&&c){if(l.textContent="",l.append(i.a.wrapMessageForReply(d,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)){b=er.chat.bubbles.getMiddleware();const e=er.chat.bubbles.lazyLoadQueue;if("sticker"===(null===(s=p.document)||void 0===s?void 0:s.type))u=!0,Cs({doc:p.document,div:c,lazyLoadQueue:e,group:Xo,width:32,height:32,middleware:b,loadPromises:h});else{const t=p.photo||p.document;m="round"===t.type;try{Ls({photo:t,container:c,boxWidth:32,boxHeight:32,size:r.a.choosePhotoSize(t,32,32),middleware:b,lazyLoadQueue:e,noBlur:!0,withoutPreloader:!0,loadPromises:h}),u=!0}catch(e){}}}}else d?(l.textContent="",l.append(i.a.wrapMessageForReply(d,d.message&&Object(Y.f)(d.message,140)))):("string"==typeof o&&(o=Object(Y.f)(o,140),o=J.a.wrapEmojiText(o)),Object(k.a)(l,o||""));return Promise.all(h).then(()=>{b&&!b()||(g.forEach(e=>e.remove()),c&&c.classList.toggle("is-round",m))}),u}class Ge extends ze{constructor(e){super(e,(e,t="",s)=>{this.mediaEl||(this.mediaEl=document.createElement("div"),this.mediaEl.classList.add(this.className+"-media"));const i=Ve({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}}const Ke=0,We=1,qe=2,Qe=4,$e=8;class Ye{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=Ye.countRatios(e),this.proportions=Ye.countProportions(this.ratios),this.averageRatio=Object(f.a)(this.ratios,1)/this.count,this.maxSizeRatio=t/this.maxHeight}layout(){return this.count?this.count>=5||this.ratios.find(e=>e>2)?new Xe(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:$e|We|qe},{geometry:{x:0,y:t+this.spacing,width:e,height:t},sides:$e|Qe|qe}]}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:We|$e|Qe},{geometry:{x:e+this.spacing,y:0,width:e,height:t},sides:We|qe|Qe}]}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:We|$e|Qe},{geometry:{x:s+this.spacing,y:0,width:t,height:i},sides:We|qe|Qe}]}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:We|$e|Qe},{geometry:{x:n+this.spacing,y:0,width:i,height:s},sides:We|qe},{geometry:{x:n+this.spacing,y:s+this.spacing,width:i,height:t},sides:Qe|qe}]}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:$e|We|qe},{geometry:{x:0,y:t+this.spacing,width:s,height:i},sides:Qe|$e},{geometry:{x:s+this.spacing,y:t+this.spacing,width:n,height:i},sides:Qe|qe}]}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:$e|We|qe},{geometry:{x:0,y:t+this.spacing,width:i,height:o},sides:Qe|$e},{geometry:{x:i+this.spacing,y:t+this.spacing,width:a,height:o},sides:Qe},{geometry:{x:i+this.spacing+a+this.spacing,y:t+this.spacing,width:n,height:o},sides:qe|Qe}]}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:We|$e|Qe},{geometry:{x:t+this.spacing,y:0,width:o,height:i},sides:We|qe},{geometry:{x:t+this.spacing,y:i+this.spacing,width:o,height:n},sides:qe},{geometry:{x:t+this.spacing,y:i+n+2*this.spacing,width:o,height:a},sides:Qe|qe}]}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 Xe{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=Xe.cropRatios(e,t),this.count=e.length}static cropRatios(e,t){return e.map(e=>t>1.1?Object(I.a)(e,1,2.75):Object(I.a)(e,.6667,1))}layout(){let e=new Array(this.count),t=[];const s=(e,t)=>{const s=this.ratios.slice(e,e+t),i=Object(f.a)(s,0);return(this.maxWidth-(t-1)*this.spacing)/i},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=Object(f.a)(t,0)+this.spacing*(i-1),r=Math.min(...t),l=(Math.max(...t),r<this.minWidth?1.5:1),c=(()=>{for(let e=1;e!==i;++e)if(s[e-1]>s[e])return 1.5;return 1})(),d=Math.abs(o-this.maxHeight)*l*c;(!n||d<a)&&(n=e,a=d)}const o=n.lineCounts,r=n.heights,l=o.length;let c=0,d=0;for(let t=0;t!==l;++t){const s=o[t],i=r[t],n=Math.round(i);let a=0;for(let o=0;o!==s;++o){const r=Ke|(0===t?We:Ke)|(t===l-1?Qe:Ke)|(0===o?$e:Ke)|(o===s-1?qe:Ke),h=this.ratios[c],p=o===s-1?this.maxWidth-a:Math.round(h*i);e[c]={geometry:{x:a,y:d,width:p,height:n},sides:r},a+=p+this.spacing,++c}d+=n+this.spacing}return e}}var Je=s(129),Ze=s(70);class et{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())},Object(w.g)(this,e),this.nextBtn?this.nextBtn.classList.contains("btn-corner")||(this.handleChange=()=>{this.nextBtn.toggleAttribute("disabled",!this.isChanged()||this.disabled)}):this.nextBtn=Q({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 q(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 tt(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 st{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?g(this.subtitle,e.subtitle):this.subtitle.append(e.subtitle):e.subtitleLangKey&&this.subtitle.append(Object(x.i18n)(e.subtitleLangKey,e.subtitleLangArgs)),this.container.append(this.subtitle);let t=!!e.havePadding;if(e.radioField||e.checkboxField){if(t=!0,e.radioField&&(this.radioField=e.radioField,this.container.append(this.radioField.label)),e.checkboxField){this.checkboxField=e.checkboxField;const t=e.checkboxField.label.classList.contains("checkbox-field-toggle");t?(this.container.classList.add("row-with-toggle"),e.titleRight=this.checkboxField.label):this.container.append(this.checkboxField.label),e.noCheckboxSubtitle||t||this.checkboxField.input.addEventListener("change",()=>{Object(k.a)(this.subtitle,Object(x.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;if(e.titleRight?(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?this.title.innerHTML=e.title:this.title.append(Object(x.i18n)(e.titleLangKey)),t.append(this.title),e.titleRight){const s=document.createElement("div");s.classList.add("row-title","row-title-right"),"string"==typeof e.titleRight?s.innerHTML=e.titleRight:s.append(e.titleRight),t.append(s)}}e.icon&&(t=!0,this.title.classList.add("tgico","tgico-"+e.icon),this.container.classList.add("row-with-icon")),t&&this.container.classList.add("row-with-padding"),e.navigationTab&&(e.clickable=()=>e.navigationTab.open()),(e.clickable||e.radioField||e.checkboxField)&&("function"==typeof e.clickable&&this.container.addEventListener("click",t=>{this.freezed||e.clickable(t)}),this.container.classList.add("row-clickable","hover-effect"),e.noRipple||Object(se.ripple)(this.container,void 0,void 0,!0))}}const it=(e,t)=>tt(e.map(e=>({container:e.container,input:e.radioField.input})),t);function nt(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 at=s(65);class ot{constructor(e){const t=this.label=document.createElement("label");t.classList.add("radio-field");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=Object(w.d)(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&&Object(x._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 rt=document.createElement("div");function lt(e){Object(k.a)(rt,e),document.body.append(rt),rt.dataset.timeout&&clearTimeout(+rt.dataset.timeout),rt.dataset.timeout=""+setTimeout(()=>{rt.remove(),delete rt.dataset.timeout},3e3)}function ct(e){lt(Object(x.i18n)(e.langPackKey))}function dt(e,t,s=!0,i=!0){let n,a,o,r,l=!1;return(...c)=>(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(...c)),l=!1),n=setTimeout(()=>{!i||s&&!l||o(e(...c)),n=a=o=r=void 0,l=!1},t),a.catch(()=>{}),a)}rt.classList.add("toast");var ht=s(33);class pt extends _.b{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(_.a.Neutral,this.options.label),void(this.options.onChange&&this.options.onChange());J.b.isUsernameValid(e)?this.setState(_.a.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=ht.a.invokeApi("channels.checkUsername",{channel:K.a.getChannelInput(this.options.peerId.toChatId()),username:e}):this.checkUsernamePromise=ht.a.invokeApi("account.checkUsername",{username:e}),this.checkUsernamePromise.then(t=>{this.getValue()===e&&(t?this.setState(_.a.Valid,this.options.availableText):this.setError(this.options.takenText))},t=>{if(this.getValue()===e)switch(t.type){case"USERNAME_INVALID":this.setError(this.options.invalidText)}}).then(()=>{this.checkUsernamePromise=void 0,this.options.onChange&&this.options.onChange();const t=this.getValue();t!==e&&this.isValidToChange()&&J.b.isUsernameValid(t)&&this.checkUsername(t)}))}}var ut=s(59),mt=s(55);class gt extends ut.b{constructor(e,t={}){if(super("popup-peer"+(e?" "+e:""),t.buttons&&Object(ut.a)(t.buttons),Object.assign({overlayClosable:!0},t)),this.className=e,t.peerId){let e=new ur;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(Object(x.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=document.createElement("p");e.classList.add("popup-description"),t.descriptionLangKey?e.append(Object(x.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 mt.a(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 bt=s(58);class vt extends V{init(){this.container.classList.add("edit-peer-container","group-type-container");const e=K.a.isBroadcast(this.chatId);this.setTitle(e?"ChannelType":"GroupType");const t=new dn({name:e?"ChannelType":"GroupType"}),s=Object(at.b)(),i=new st({radioField:new ot({langKey:e?"ChannelPrivate":"MegaPrivate",name:s,value:"private"}),subtitleLangKey:e?"ChannelPrivateInfo":"MegaPrivateInfo"}),a=new st({radioField:new ot({langKey:e?"ChannelPublic":"MegaPublic",name:s,value:"public"}),subtitleLangKey:e?"ChannelPublicInfo":"MegaPublicInfo"}),o=it([i,a],e=>{const t=[c,p];"public"===e&&t.reverse(),t[0].container.classList.remove("hide"),t[1].container.classList.add("hide"),m()}),r=K.a.getChat(this.chatId);t.content.append(o);const c=new dn({}),d=new st({title:this.chatFull.exported_invite.link,subtitleLangKey:e?"ChannelPrivateLinkHelp":"MegaPrivateLinkHelp",clickable:()=>{nt(this.chatFull.exported_invite.link),lt(x.default.format("LinkCopied",!0))}}),h=Object(U.a)("btn-primary btn-transparent danger",{icon:"delete",text:"RevokeLink"});Object(l.b)(h,()=>{new gt("revoke-link",{buttons:[{langKey:"RevokeButton",callback:()=>{const e=Object(bt.a)([h],!0);n.default.getChatInviteLink(this.chatId,!0).then(t=>{e(),d.title.innerHTML=t})}}],titleLangKey:"RevokeLink",descriptionLangKey:"RevokeAlert"}).show()},{listenerSetter:this.listenerSetter}),c.content.append(d.container,h);const p=new dn({caption:e?"Channel.UsernameAboutChannel":"Channel.UsernameAboutGroup",noDelimiter:!0}),u=document.createElement("div");u.classList.add("input-wrapper");const m=()=>{const e=i.radioField.checked&&"t.me/"!==b||g.isValidToChange()&&g.input.classList.contains("valid");v.classList.toggle("is-visible",e)},g=new pt({label:"SetUrlPlaceholder",name:"group-public-link",plainText:!0,listenerSetter:this.listenerSetter,availableText:"Link.Available",invalidText:"Link.Invalid",takenText:"Link.Taken",onChange:m,peerId:this.chatId.toPeerId(!0),head:"t.me/"}),b="t.me/"+(r.username||"");u.append(g.container),p.content.append(u);const v=Q({icon:"check",className:"is-visible"});this.content.append(v),Object(l.b)(v,()=>{Object(te.g)(v);const e=a.radioField.checked?g.getValue():"";K.a.migrateChat(this.chatId).then(t=>K.a.updateUsername(t,e)).then(()=>{this.close()})},{listenerSetter:this.listenerSetter}),("t.me/"!==b?a:i).radioField.checked=!0,g.setOriginalValue(b),this.scrollable.append(t.container,c.container,p.container)}}var ft=s(63);class yt{constructor(e){this.loading=!1,this.loaded=!1,Object(w.g)(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 wt=s(89),St=s(85),Lt=s(49),Et=s(92),Ct=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 It{constructor(e){this.container=document.createElement("div"),this.list=kr.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=kr.createChatList(),this.promise=null,this.loadedWhat={},this.query=e,this.renderedPeerIds.clear(),this.needSwitchList=!0,this.getMoreResults()}},this.checkForTriggers=()=>{this.scrollable.checkForTriggers()},Object(w.g)(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=>{if(e.isPeerId()){if(!o.a.getPeer(e).deleted)return this.filterPeerTypeBy.find(t=>o.a[t](e))}return!0})),t(e)),this.input=document.createElement("input"),this.input.classList.add("selector-search-input"),this.placeholder?Object(x._i18n)(this.input,this.placeholder,void 0,"placeholder"):Object(x._i18n)(this.input,"SendMessageTo",void 0,"placeholder"),this.input.type="text",this.multiSelect){let e=document.createElement("div");e.classList.add("selector-search-container"),this.selectedContainer=document.createElement("div"),this.selectedContainer.classList.add("selector-search"),this.selectedContainer.append(this.input),e.append(this.selectedContainer),this.selectedScrollable=new T.b(e);let t=document.createElement("hr");this.selectedContainer.addEventListener("click",e=>{if(this.freezed)return;let t=e.target;if(t=Object(Me.a)(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())}),this.container.append(e,t)}this.chatsContainer.classList.add("chatlist-container"),this.chatsContainer.append(this.list),this.scrollable=new T.b(this.chatsContainer),this.scrollable.setVirtualContainer(this.list),this.chatsContainer.addEventListener("click",e=>{const t=Object(St.a)(e.target,"data-peer-id");if(Object(c.a)(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 s=dt(this.onInput,200,!1,!0);this.input.addEventListener("input",s),this.scrollable.onScrolledBottom=()=>{this.getMoreResults()},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&&!P.a.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 Ct(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(this.loadedWhat.dialogs&&this.loadedWhat.archived)return;const e=Et.a.height/72*1.25|0,t=this.getTempId("dialogs"),s=i.a.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||P.a.canSendToUser(e))||K.a.hasRights(e.toChatId(),this.chatRightsAction)}getMoreContacts(){return Ct(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?P.a.getContactsPeerIds(this.query):[],this.query?P.a.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=Object(f.b)(i.concat(t))}else this.cachedContacts=i.slice();Object(f.e)(this.cachedContacts,a.default.myId),this.promise=null}const t=Et.a.height/72*1.25|0,s=this.cachedContacts.splice(0,t);this.renderResultsFunc(s),this.cachedContacts.length||(this.loadedWhat.contacts=!0)}))}getMoreChannelParticipants(){return Ct(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=>K.a.getParticipantPeerId(e));Object(f.e)(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=>P.a.isNonContactUser(e))),e.forEach(e=>{const{dom:t}=kr.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 mt.a;s&&(i.input.checked=!0),t.containerEl.prepend(i.label)}let s;s=e.isAnyChat()?n.default.getChatMembersString(e.toChatId()):e===a.default.myId?Object(x.i18n)(this.selfPresence):P.a.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 Lt.a({peerId:e.toPeerId(),dialog:!0}).element),n.setAttribute("peer",""+e)),t&&("string"==typeof t?i.innerHTML=t:(Object(k.a)(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(this.input,"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(this.input,"center",void 0,void 0,wt.a.Static)})}}var Mt=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 Pt extends ut.b{constructor(e){super("popup-forward",null,{closable:!0,overlayClosable:!0,body:!0}),this.selector=new It({appendTo:this.body,onChange:()=>Mt(this,void 0,void 0,(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()})),peerType:e.peerTypes,onFirstRender:()=>{this.show(),this.selector.checkForTriggers(),ue.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 Tt extends V{init(){let e;this.container.classList.add("edit-peer-container","user-permissions-container"),this.setTitle("UserRestrictions");{const t=new dn({name:"UserRestrictionsCanDo"}),s=document.createElement("div");s.classList.add("chatlist-container"),t.content.insertBefore(s,t.title);const i=kr.createChatList({new:!0});s.append(i);const{dom:n}=kr.addDialogNew({dialog:this.userId.toPeerId(!1),container:i,drawStatus:!1,rippleEnabled:!0,avatarSize:48});n.lastMessageSpan.append(P.a.getUserStatusString(this.userId));const a=new xt({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._&&Object(w.b)(this.participant.banned_rights.pFlags,e.pFlags)||K.a.editBanned(this.chatId,this.participant,e)},this.eventListener.addEventListener("destroy",e,{once:!0}),this.scrollable.append(t.container)}{const t=new dn({});if("channelParticipantBanned"===this.participant._){const s=Object(U.a)("btn-primary btn-transparent danger",{icon:"delete",text:"GroupPermission.Delete"});Object(l.b)(s,()=>{const t=Object(bt.a)([s],!0);K.a.clearChannelParticipantBannedRights(this.chatId,this.participant).then(()=>{this.eventListener.removeEventListener("destroy",e),this.close()},()=>{t()})},{listenerSetter:this.listenerSetter}),t.content.append(s)}const s=Object(U.a)("btn-primary btn-transparent danger",{icon:"deleteuser",text:"UserRestrictionsBlock"});Object(l.b)(s,()=>{Object(bt.a)([s],!0);K.a.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 kt=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 xt{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=K.a.getChat(e.chatId).default_banned_rights,s=e.participant?K.a.combineParticipantBannedRights(e.chatId,e.participant.banned_rights):t;for(const i of this.v){const n=i.flags[0];i.checkboxField=new mt.a({text:i.text,checked:K.a.hasRights(e.chatId,n,s),restriction:!0,withRipple:!0}),e.participant&&t.pFlags[n]&&(i.checkboxField.input.disabled=!0,Object(l.b)(i.checkboxField.label,e=>{lt(x.default.format("UserRestrictionsDisabled",!0))},{listenerSetter:e.listenerSetter})),this.toggleWith[n]&&e.listenerSetter.add(i.checkboxField.input)("change",()=>{if(!i.checkboxField.checked){this.v.filter(e=>this.toggleWith[n].includes(e.flags[0])).forEach(e=>{e.checkboxField.checked=!1})}}),e.appendTo.append(i.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 Ot extends V{init(){return kt(this,void 0,void 0,(function*(){let e;this.container.classList.add("edit-peer-container","group-permissions-container"),this.setTitle("ChannelPermissions");{const t=new dn({name:"ChannelPermissionsHeader"});e=new xt({chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:t.content}),this.eventListener.addEventListener("destroy",()=>{K.a.editChatDefaultBannedRights(this.chatId,e.takeOut())},{once:!0}),this.scrollable.append(t.container)}{const t=new dn({name:"PrivacyExceptions"}),s=new st({titleLangKey:"ChannelAddException",subtitleLangKey:"Loading",icon:"adduser",clickable:()=>{new Pt({peerTypes:["channelParticipants"],onSelect:e=>{setTimeout(()=>{i(e)},0)},placeholder:"ExceptionModal.Search.Placeholder",peerId:-this.chatId})}}),i=e=>kt(this,void 0,void 0,(function*(){let t;try{t=yield n.default.getChannelParticipant(this.chatId,e)}catch(e){return void lt("User is no longer participant")}const s=new Tt(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 c=kr.createChatList({new:!0});r.append(c),Object(l.b)(c,e=>{const t=Object(ft.a)(e.target,"LI");if(!t)return;const s=t.dataset.peerId.toPeerId();i(s)},{listenerSetter:this.listenerSetter});const d=(t,s)=>{const i=s.banned_rights,n=K.a.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(...Object(x.join)(a.map(e=>Object(x.i18n)(e)),!1))),o.classList.toggle("hide",!a.length)},h=(e,t)=>{const{dom:s}=kr.addDialogNew({dialog:o.a.getPeerId(e.peer),container:c,drawStatus:!1,rippleEnabled:!0,avatarSize:48,append:t});d(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=c.querySelector(`[data-peer-id="${e.user_id}"]`);n?(a?d(a,e.new_participant):h(e.new_participant,!1),"channelParticipantBanned"!==(null===(s=e.prev_participant)||void 0===s?void 0:s._)&&++m):(a&&a.remove(),"channelParticipantBanned"===(null===(i=e.prev_participant)||void 0===i?void 0:i._)&&--m),p()});const p=()=>{Object(k.a)(s.subtitle,Object(x.i18n)(m?"Permissions.ExceptionsCount":"Permissions.NoExceptions",[m]))};let u,m=0;const g=()=>(u=new yt({scrollable:this.scrollable,getPromise:()=>n.default.getChannelParticipants(this.chatId,{_:"channelParticipantsBanned",q:""},50,c.childElementCount).then(e=>{for(const t of e.participants)h(t,!0);return m=e.count,p(),e.participants.length<50||e.count===c.childElementCount})}),u.load());this.scrollable.append(t.container),K.a.isChannel(this.chatId)?yield g():(p(),this.listenerSetter.add(a.default)("dialog_migrate",({migrateFrom:e,migrateTo:t})=>{this.chatId===e&&(this.chatId=t,g())}))}}))}onOpenAfterTimeout(){this.scrollable.onScroll()}}class At{constructor(e,t=o.a.getDialogType(e),s){const n=new Lt.a({peerId:e}).element,a=(t,n=p&&!!t.size)=>{let a=K.a.leave(e.toChatId());n&&(a=a.finally(()=>i.a.flushHistory(e))),s&&s(a)},r=t=>{let n;if(e.isUser())n=i.a.flushHistory(e,!1,p?!!t.size:void 0);else{if(!t.size)return a(t);n=K.a.delete(e.toChatId())}s&&s(n)};let l,c,d,h,p;switch(t){case"channel":K.a.hasRights(e.toChatId(),"delete_chat")?(K.a.deleteChannel,l="ChannelDeleteMenu",c="AreYouSureDeleteAndExitChannel",h=[{langKey:"ChannelDeleteMenu",isDanger:!0,callback:r}],p=[{text:"DeleteChannelForAll"}]):(l="LeaveChannelMenu",c="ChannelLeaveAlertWithName",d=[n],h=[{langKey:"LeaveChannel",isDanger:!0,callback:a}]);break;case"chat":l="DeleteChatUser",c="AreYouSureDeleteThisChatWithUser",d=[n],h=[{langKey:"DeleteChatUser",isDanger:!0,callback:r}],p=[{text:"DeleteMessagesOptionAlso",textArgs:[new Lt.a({peerId:e}).element]}];break;case"saved":l="DeleteChatUser",c="AreYouSureDeleteThisChatSavedMessages",h=[{langKey:"DeleteChatUser",isDanger:!0,callback:r}];break;case"megagroup":case"group":K.a.hasRights(e.toChatId(),"delete_chat")?(l="DeleteMegaMenu",c="AreYouSureDeleteAndExit",h=[{langKey:"DeleteMegaMenu",isDanger:!0,callback:r}],p=[{text:"DeleteChat.DeleteGroupForAll"}]):(l="LeaveMegaMenu",c="AreYouSureDeleteAndExitName",d=[n],h=[{langKey:"DeleteChatUser",isDanger:!0,callback:e=>a(e,!0)}])}new gt("popup-delete-chat",{peerId:e,titleLangKey:l,descriptionLangKey:c,descriptionLangArgs:d,buttons:h,checkboxes:p}).show()}}var _t=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 Ft extends z{_init(){return _t(this,void 0,void 0,(function*(){this.listenerSetter.removeAll(),this.scrollable.container.innerHTML="",this.container.classList.add("edit-peer-container","edit-group-container"),this.setTitle("Edit");const e=yield n.default.getChatFull(this.chatId,!0),t=K.a.getChat(this.chatId),s=K.a.isBroadcast(this.chatId),i=K.a.isChannel(this.chatId),o=[],r=e=>{o.push(e)};this.listenerSetter.add(a.default)("chat_update",e=>{this.chatId===e&&o.forEach(e=>e())});const c=this.chatId.toPeerId(!0);{const i=new dn({noDelimiter:!0}),n=[],o=document.createElement("div");if(o.classList.add("input-wrapper"),this.chatNameInputField=new _.b({label:s?"EnterChannelName":"CreateGroup.NameHolder",name:"chat-name",maxLength:255,required:!0}),this.descriptionInputField=new _.b({label:"DescriptionPlaceholder",name:"chat-description",maxLength:255}),this.chatNameInputField.setOriginalValue(t.title),this.descriptionInputField.setOriginalValue(e.about),o.append(this.chatNameInputField.container,this.descriptionInputField.container),n.push(this.chatNameInputField,this.descriptionInputField),this.editPeer=new et({peerId:c,inputFields:n,listenerSetter:this.listenerSetter}),this.content.append(this.editPeer.nextBtn),i.content.append(this.editPeer.avatarEdit.container,o),K.a.hasRights(this.chatId,"change_type")){const n=new st({titleLangKey:s?"ChannelType":"GroupType",clickable:()=>{const t=new vt(this.slider);t.chatId=this.chatId,t.chatFull=e,t.open(),this.listenerSetter.add(t.eventListener)("destroy",a)},icon:"lock"}),a=()=>{let e;n.subtitle.textContent="",e=s?t.username?"TypePublic":"TypePrivate":t.username?"TypePublicGroup":"TypePrivateGroup",n.subtitle.append(Object(x.i18n)(e))};a(),i.content.append(n.container)}if(K.a.hasRights(this.chatId,"change_permissions")&&!s){const e=["send_messages","send_media","send_stickers","send_polls","embed_links","invite_users","pin_messages","change_info"],s=new st({titleLangKey:"ChannelPermissions",clickable:()=>{const e=new Ot(this.slider);e.chatId=this.chatId,e.open()},icon:"permissions"}),n=()=>{s.subtitle.innerHTML=e.reduce((e,s)=>e+ +K.a.hasRights(this.chatId,s,t.default_banned_rights),0)+"/"+e.length};n(),i.content.append(s.container),this.listenerSetter.add(a.default)("chat_update",e=>{this.chatId===e&&n()})}if(this.scrollable.append(i.container),Object(l.b)(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0;let e=[];const t=this.chatId;this.chatNameInputField.isValidToChange()&&e.push(K.a.editTitle(t,this.chatNameInputField.value)),this.descriptionInputField.isValidToChange()&&e.push(K.a.editAbout(t,this.descriptionInputField.value)),this.editPeer.uploadAvatar&&e.push(this.editPeer.uploadAvatar().then(e=>K.a.editPhoto(t,e))),Promise.race(e).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()})},{listenerSetter:this.listenerSetter}),s&&K.a.hasRights(this.chatId,"change_info")){const e=new mt.a({text:"PeerInfo.SignMessages",checked:!!t.pFlags.signatures,withRipple:!0});this.listenerSetter.add(e.input)("change",()=>{const t=e.toggleDisability(!0);K.a.toggleSignatures(this.chatId,e.checked).then(()=>{t()})}),r(()=>{e.setValueSilently(!!t.pFlags.signatures)}),i.content.append(e.label)}}if(!s){const t=new dn({});if(!s&&K.a.hasRights(this.chatId,"change_permissions")){const s=new mt.a({text:"ChatHistory",withRipple:!0});this.listenerSetter.add(s.input)("change",()=>{const e=s.toggleDisability(!0);K.a.togglePreHistoryHidden(this.chatId,!s.checked).then(()=>{e()})});const n=()=>{s.setValueSilently(i&&!e.pFlags.hidden_prehistory)};n(),r(n),t.content.append(s.label)}this.scrollable.append(t.container)}if(K.a.hasRights(this.chatId,"delete_chat")){const e=new dn({}),t=Object(U.a)("btn-primary btn-transparent danger",{icon:"delete",text:s?"PeerInfo.DeleteChannel":"DeleteAndExitButton"});Object(l.b)(t,()=>{new At(c,void 0,e=>{const s=Object(bt.a)([t],!0);e.then(()=>{this.close()},()=>{s()})})},{listenerSetter:this.listenerSetter}),e.content.append(t),this.scrollable.append(e.container)}i||this.listenerSetter.add(a.default)("dialog_migrate",({migrateFrom:e,migrateTo:t})=>{c===e&&(this.chatId=t.toChatId(),this._init())})}))}init(){return this._init()}}var Dt=s(97);class jt extends z{init(){this.container.classList.add("edit-peer-container","edit-contact-container");const e=!P.a.isContact(this.peerId.toUserId());this.setTitle(e?"AddContactTitle":"Edit");{const t=new dn({noDelimiter:!0}),s=[],n=document.createElement("div");if(n.classList.add("input-wrapper"),this.nameInputField=new _.b({label:"FirstName",name:"contact-name",maxLength:70,required:!0}),this.lastNameInputField=new _.b({label:"LastName",name:"contact-lastname",maxLength:70}),this.peerId){const t=P.a.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 et({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 mt.a({text:"Notifications"});r.input.addEventListener("change",e=>{e.isTrusted&&i.a.mutePeer(this.peerId)}),this.listenerSetter.add(a.default)("notify_settings",e=>{if("notifyPeer"!==e.peer._)return;const t=o.a.getPeerId(e.peer.peer);if(this.peerId===t){const t=!Dt.a.isMuted(e.notify_settings);t!==r.checked&&(r.checked=t)}});const l=document.createElement("div");l.classList.add("profile-name"),l.append(new Lt.a({peerId:this.peerId}).element);const c=document.createElement("div");if(c.classList.add("profile-subtitle"),c.append(Object(x.i18n)("EditContact.OriginalName")),t.content.append(s,l,c,n),e){const e=P.a.getUser(this.peerId),s=new st({icon:"phone",titleLangKey:e.phone?void 0:"MobileHidden",title:e.phone?P.a.formatUserPhone(e.phone):void 0,subtitleLangKey:e.phone?"Phone":"MobileHiddenExceptionInfo",subtitleLangArgs:e.phone?void 0:[new Lt.a({peerId:this.peerId}).element]});t.content.append(s.container)}else{const e=new st({checkboxField:r}),s=!Dt.a.isPeerLocalMuted(this.peerId,!1);r.checked=s,t.content.append(e.container)}}else t.content.append(n);this.scrollable.append(t.container),Object(l.b)(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0,P.a.addContact(this.peerId,this.nameInputField.value,this.lastNameInputField.value,P.a.getUser(this.peerId).phone).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()})},{listenerSetter:this.listenerSetter})}if(!e){const e=new dn({}),t=Object(U.a)("btn-primary btn-transparent danger",{icon:"delete",text:"PeerInfo.DeleteContact"});Object(l.b)(t,()=>{new gt("popup-delete-contact",{peerId:this.peerId,titleLangKey:"DeleteContact",descriptionLangKey:"AreYouSureDeleteContact",buttons:Object(ut.a)([{langKey:"Delete",callback:()=>{const e=Object(bt.a)([t],!0);P.a.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 z{init(){this.nextBtn=Q({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=Object(te.g)(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 It({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}}var Rt=!re.IS_FIREFOX&&!1;function Ut(){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,Nt=window;let zt=!1;a.default.addEventListener("context_menu_toggle",e=>{zt=e});class Vt{constructor(e){this.cursor="grabbing",this.cancelEvent=!0,this.listenerOptions=!1,this.hadMove=!1,this.xDown=null,this.yDown=null,this.reset=e=>{ue.IS_TOUCH_SUPPORTED?Nt.removeEventListener("touchmove",this.handleMove,{capture:!0}):(Nt.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,ue.IS_TOUCH_SUPPORTED?Nt.addEventListener("touchmove",this.handleMove,{passive:!1,capture:!0}):Nt.addEventListener("mousemove",this.handleMove,!1)},this.handleMove=e=>{if(null===this.xDown||null===this.yDown||zt)return void this.reset();this.cancelEvent&&Object(c.a)(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,ue.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()},Object(w.g)(this,e),this.setCursorTo=this.element,this.setListeners()}setListeners(){ue.IS_TOUCH_SUPPORTED?(this.element.addEventListener("touchstart",this.handleStart,this.listenerOptions),Nt.addEventListener("touchend",this.reset)):(this.element.addEventListener("mousedown",this.handleStart,this.listenerOptions),Nt.addEventListener("mouseup",this.reset))}removeListeners(){ue.IS_TOUCH_SUPPORTED?(this.element.removeEventListener("touchstart",this.handleStart,this.listenerOptions),Nt.removeEventListener("touchend",this.reset)):(this.element.removeEventListener("mousedown",this.handleStart,this.listenerOptions),Nt.removeEventListener("mouseup",this.reset))}setCursor(e){this.cursor=e,!ue.IS_TOUCH_SUPPORTED&&this.hadMove&&this.setCursorTo.style.setProperty("cursor",this.cursor,"important")}}var Gt=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.scrollable=e,this.loadCallbacks=new Map,this.processItem=e=>{const t=document.createElement("div");let s;t.classList.add(Kt.BASE_CLASS+"-avatar","media-container"),e&&(s="object"!=typeof e?r.a.getPhoto(e):e.action.photo);const i=new Image;i.classList.add("avatar-photo"),i.draggable=!1;const n=()=>{if(s){const e=Ls({container:t,photo:s,size:r.a.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.a.getPeerPhoto(this.peerId);d.a.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(Kt.BASE_CLASS+"-container"),this.avatars=document.createElement("div"),this.avatars.classList.add(Kt.BASE_CLASS+"-avatars"),this.gradient=document.createElement("div"),this.gradient.classList.add(Kt.BASE_CLASS+"-gradient"),this.info=document.createElement("div"),this.info.classList.add(Kt.BASE_CLASS+"-info"),this.tabs=document.createElement("div"),this.tabs.classList.add(Kt.BASE_CLASS+"-tabs"),this.arrowPrevious=document.createElement("div"),this.arrowPrevious.classList.add(Kt.BASE_CLASS+"-arrow","tgico-avatarprevious"),this.arrowNext=document.createElement("div"),this.arrowNext.classList.add(Kt.BASE_CLASS+"-arrow",Kt.BASE_CLASS+"-arrow-next","tgico-avatarnext"),this.container.append(this.avatars,this.gradient,this.info,this.tabs,this.arrowPrevious,this.arrowNext);const t=()=>0===this.scrollable.scrollTop||(this.scrollable.scrollIntoViewNew(this.scrollable.container.firstElementChild,"start"),!1);let s=!1,i=!1;Object(l.b)(this.container,e=>Gt(this,void 0,void 0,(function*(){if(i)return void Object(c.a)(e);if(s)return void(s=!1);if(!t())return;const n=this.container.getBoundingClientRect(),a=e.pageX,o=a-n.left;if(!this.listLoader.previous.length&&!this.listLoader.next.length||o>n.width*(1/3)&&o<n.width-n.width*(1/3)){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),n=t.slice(this.listLoader.previous.length+1),a=this.avatars.children[this.listLoader.previous.length];i=!0,dr(a,e,()=>e===this.peerId,this.listLoader.current,s,n),i=!1}else{const e=a>n.right-n.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),Object(De.b)(()=>{this.avatars.classList.remove("no-transition")})}})));const n=()=>{s=!0,document.body.addEventListener(ue.IS_TOUCH_SUPPORTED?"touchend":"click",e=>{s=!1},{once:!0})};let a=0,h=0,p=0,u=0;new Vt({element:this.avatars,onSwipe:(e,t)=>{p=e;let s=h+e*-Kt.SCALE;return s>0?s=0:s<u&&(s=u),this.avatars.style.transform=Kt.TRANSLATE_TEMPLATE.replace("{x}",s+"px"),!1},verifyTouchTarget:e=>t()?!this.container.classList.contains("is-single")&&!i:(n(),Object(c.a)(e),!1),onFirstSwipe:()=>{const e=this.avatars.getBoundingClientRect();a=e.width,u=-a*(this.tabs.childElementCount-1),h=e.left-this.container.getBoundingClientRect().left,this.avatars.style.transform=Kt.TRANSLATE_TEMPLATE.replace("{x}",h+"px"),this.container.classList.add("is-swiping"),this.avatars.classList.add("no-transition"),this.avatars.offsetLeft},onReset:()=>{const e=Math.ceil(Math.abs(p)/(a/Kt.SCALE))*(p>=0?1:-1);n(),this.avatars.classList.remove("no-transition"),Object(De.b)(()=>{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.a.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.a.getUserPhotos(e,i,o).then(e=>({count:e.count,items:e.photos}))}{const t=[];return s.current||t.push(n.default.getChatFull(e.toChatId())),t.push(i.a.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.a.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*Kt.SCALE*s;this.avatars.style.transform=Kt.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(Kt.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))})}}Kt.BASE_CLASS="profile-avatars",Kt.SCALE=Rt?2:1,Kt.TRANSLATE_TEMPLATE=Rt?`translate3d({x}, 0, -1px) scale(${Kt.SCALE})`:"translate({x}, 0)";let Wt=(e,t)=>{t.title.innerHTML=e,t.container.style.display=""};class qt{constructor(e){this.scrollable=e,this.setPeerStatus=(e=!1)=>{if(!this.peerId)return;const t=this.peerId;er.setPeerStatus(this.peerId,this.subtitle,e,!0,()=>t===this.peerId)},Rt||this.scrollable.container.classList.add("no-parallax")}init(){this.init=null,this.element=document.createElement("div"),this.element.classList.add("profile-content"),this.section=new dn({noDelimiter:!0}),this.avatar=new ur,this.avatar.classList.add("profile-avatar","avatar-120"),this.avatar.setAttribute("dialog","1"),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 st({title:" ",subtitleLangKey:"UserBio",icon:"info",clickable:e=>{"A"!==e.target.tagName&&n.default.getProfileByPeerId(this.peerId).then(e=>{nt(e.about),lt(x.default.format("BioCopied",!0))})}}),this.bio.title.classList.add("pre-wrap"),this.username=new st({title:" ",subtitleLangKey:"Username",icon:"username",clickable:()=>{nt("@"+o.a.getPeer(this.peerId).username),lt(x.default.format("UsernameCopied",!0))}}),this.phone=new st({title:" ",subtitleLangKey:"Phone",icon:"phone",clickable:()=>{nt("+"+P.a.getUser(this.peerId).phone),lt(x.default.format("PhoneCopied",!0))}}),this.notifications=new st({checkboxField:new mt.a({toggle:!0}),titleLangKey:"Notifications",icon:"unmute"}),this.section.content.append(this.phone.container,this.username.container,this.bio.container,this.notifications.container),this.element.append(this.section.container,pn()),this.notifications.checkboxField.input.addEventListener("change",e=>{e.isTrusted&&i.a.mutePeer(this.peerId)}),a.default.addEventListener("dialog_notify_settings",e=>{if(this.peerId===e.peerId){const e=Dt.a.isPeerLocalMuted(this.peerId,!1);this.notifications.checkboxField.checked=!e}}),a.default.addEventListener("peer_typings",({peerId:e})=>{this.peerId===e&&this.setPeerStatus()}),a.default.addEventListener("peer_bio_edit",e=>{e===this.peerId&&this.setBio(!0)}),a.default.addEventListener("user_update",e=>{this.peerId===e&&this.setPeerStatus()}),a.default.addEventListener("contacts_update",e=>{if(this.peerId===e){const t=P.a.getUser(e);t.pFlags.self||(t.phone?Wt(P.a.formatUserPhone(t.phone),this.phone):this.phone.container.style.display="none")}}),this.setPeerStatusInterval=window.setInterval(this.setPeerStatus,6e4)}cleanupHTML(){this.bio.container.style.display="none",this.phone.container.style.display="none",this.username.container.style.display="none",this.notifications.container.style.display="",this.notifications.checkboxField.checked=!0,this.setBioTimeout&&(window.clearTimeout(this.setBioTimeout),this.setBioTimeout=0)}setAvatar(){if(this.peerId!==a.default.myId){if(o.a.getPeerPhoto(this.peerId)){const e=this.avatars;return this.avatars=new Kt(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(Rt&&this.scrollable.container.classList.add("parallax"))}}Rt&&this.scrollable.container.classList.remove("parallax"),this.avatars&&(this.avatars.container.remove(),this.avatars=void 0),this.avatar.setAttribute("peer",""+this.peerId),this.section.content.prepend(this.avatar,this.name,this.subtitle)}fillProfileElements(){var e;if(!this.cleaned)return;this.cleaned=!1;const t=this.peerId;if(this.cleanupHTML(),this.setAvatar(),t!==a.default.myId){o.a.getPeerUsername(t)&&Wt(o.a.getPeerUsername(t),this.username);const e=Dt.a.isPeerLocalMuted(t,!1);this.notifications.checkboxField.checked=!e}else Object(De.b)(()=>{this.notifications.container.style.display="none"});if(t.isUser()){let e=P.a.getUser(t);e.phone&&t!==a.default.myId&&Wt(P.a.formatUserPhone(e.phone),this.phone)}this.setBio(),Object(k.a)(this.name,new Lt.a({peerId:t,dialog:!0}).element);const s=o.a.getPeer(t);(null===(e=null==s?void 0:s.pFlags)||void 0===e?void 0:e.verified)&&this.name.append(Ut()),this.setPeerStatus(!0)}setBio(e){this.setBioTimeout&&(window.clearTimeout(this.setBioTimeout),this.setBioTimeout=0);const t=this.peerId,s=this.threadId;if(!t)return;let i;i=t.isUser()?n.default.getProfile(t,e).then(e=>this.peerId===t&&this.threadId===s&&(e.rAbout&&t!==a.default.myId&&Wt(e.rAbout,this.bio),!0)):n.default.getChatFull(t.toChatId(),e).then(e=>this.peerId===t&&this.threadId===s&&(e.about&&Wt(J.b.wrapRichText(e.about),this.bio),!0)),i.then(e=>{e&&(this.setBioTimeout=window.setTimeout(()=>this.setBio(!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 z{constructor(e){super(e,!1),this.threadId=0,this.historiesStorage={}}init(){this.container.classList.add("shared-media-container","profile-container");const e=Object(U.a)("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(Object(x.i18n)("Profile")),this.editBtn=H("edit"),i.append(this.title,this.editBtn);const n=document.createElement("div");n.classList.add("transition-item");const o=this.title.cloneNode();o.append(Object(x.i18n)("PeerInfo.SharedMedia")),n.append(o),s.append(i,n),this.header.append(s),this.profile=new qt(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=Object(D.a)(s,"slide-fade",400,null,!1);r(0),Object(l.b)(this.closeBtn,e=>{this.closeBtn.firstElementChild.classList.contains("state-back")?(this.scrollable.scrollIntoViewNew(this.scrollable.container.firstElementChild,"start"),r(0),t.classList.remove("state-back")):this.scrollable.isHeavyAnimationInProgress||this.slider.onCloseBtnClick()}),Object(l.b)(this.editBtn,e=>{let t;t=this.peerId.isAnyChat()?new Ft(this.slider):new jt(this.slider),t&&(t instanceof Ft?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 ei({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(()=>{c.classList.toggle("is-hidden","members"!==e.type)},t)}}),this.profile.element.append(this.searchSuper.container);const c=Q({icon:"addmember_filled"});this.content.append(c),c.addEventListener("click",()=>{const e=this.peerId,t=this.peerId.toChatId(),s=K.a.isChannel(t),i=(t,i)=>{let n,a,o,r,l;if(t.length>1)n="AddMembersAlertTitle",a=[Object(x.i18n)("Members",[t.length])],o="AddMembersAlertCountText",r=t.map(e=>{const t=document.createElement("b");return t.append(new Lt.a({peerId:e}).element),t}),s||(l=[{text:"AddMembersForwardMessages",checked:!0}]);else{n="AddOneMemberAlertTitle",o="AddMembersAlertNamesText";const e=document.createElement("b");e.append(new Lt.a({peerId:t[0]}).element),r=[e],s||(l=[{text:"AddOneMemberForwardMessages",textArgs:[new Lt.a({peerId:t[0]}).element],checked:!0}])}r.push(new Lt.a({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&&ct({langPackKey:"InviteToGroupError"})};if(s){const e=new Bt(this.slider);e.open({type:"channel",skippable:!1,takeOut:s=>(i(s,()=>{const i=K.a.inviteToChannel(t,s);i.catch(n),e.attachToPromise(i)}),!1),title:"GroupAddMembers",placeholder:"SendMessageTo"})}else new Pt({peerTypes:["contacts"],placeholder:"Search",onSelect:e=>{setTimeout(()=>{i([e],s=>{K.a.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.a.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()&&K.a.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&&P.a.isContact(this.peerId.toUserId()):K.a.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=new class extends G{constructor(){super({sidebarEl:document.getElementById("column-right"),canHideFirst:!0,navigationType:"right"}),this.isColumnProportionSet=!1,b.b.addEventListener("changeScreen",(e,t)=>{t===b.a.medium&&e!==b.a.mobile&&this.toggleSidebar(!1)}),b.b.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("is-right-column-shown");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=er.selectTab(s?1:2,t);return document.body.classList.toggle("is-right-column-shown",e),n}};de.a.appSidebarRight=$t;var Yt=$t;class Xt extends z{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=Je.a.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);es(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 c=document.createElement("div");c.innerHTML=J.a.wrapEmojiText(r.text);const d=document.createElement("div");d.innerText=Math.round(n[i])+"%",l.append(c,d);const h=kr.createChatList();h.classList.add("poll-results-voters"),kr.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,m=!1,g=t.voters-4;const b=()=>{m||(m=!0,Je.a.getVotes(e,r.option,p,u).then(e=>{e.votes.forEach(e=>{const{dom:t}=kr.addDialogNew({dialog:e.user_id.toPeerId(!1),container:h,drawStatus:!1,rippleEnabled:!1,meAsSaved:!1,avatarSize:32});t.lastMessageSpan.parentElement.remove()}),p&&(g-=e.votes.length,v.lastElementChild.replaceWith(Object(x.i18n)("PollResults.LoadMore",[Math.min(20,g)]))),p=e.next_offset,u=20,g&&e.votes.length||v.remove()}).finally(()=>{m=!1}))};if(b(),g<=0)return;const v=document.createElement("div");v.classList.add("poll-results-more","show-more","rp-overflow"),v.addEventListener("click",b),Object(se.ripple)(v);const f=document.createElement("div");f.classList.add("tgico-down"),v.append(f,Object(x.i18n)("PollResults.LoadMore",[Math.min(20,g)])),a.append(v)}),this.resultsDiv.append(i,a),Yt.toggleSidebar(!0).then(()=>{}),t}}var Jt=s(57);let Zt=0;const es=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",()=>{ss&&ts(ss,is,ns)}),b.b.addEventListener("resize",()=>{as.setMaxLength(),as.resizePolls()}),b.b.addEventListener("changeScreen",()=>{as.setMaxLength()});const ts=(e,t,s)=>{e.classList.remove("active"),clearTimeout(s),setTimeout(()=>{t(),e.remove(),ss===e&&is===t&&ns===s&&(ss=is=null,ns=0)},200)};let ss,is,ns;class as 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=Et.a.width<=360?Et.a.width-120:b.b.active.poll.width;this.MAX_LENGTH=e+9+this.MAX_OFFSET+-13.7}static resizePolls(){if(!this.MAX_LENGTH)return;Array.from(document.querySelectorAll("poll-element.is-voted")).forEach(e=>{e.svgLines.forEach((t,s)=>{e.setLineProgress(s,1)})})}render(){Zt||(Zt=document.getElementById("poll-line").getTotalLength(),as.setMaxLength());const e=this.message.media.poll.id,{poll:t,results:s}=Je.a.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">${J.a.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(Object(x.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-Ze.a.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(()=>{Je.a.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(Object(x.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=>{Object(c.a)(e),Yt.isTabExists(Xt)||new Xt(Yt).open(this.message)}),Object(se.ripple)(this.viewResults),this.isMultiple&&(this.sendVoteBtn=document.createElement("div"),this.sendVoteBtn.classList.add("poll-footer-button","poll-send-vote"),this.sendVoteBtn.append(Object(x.i18n)("Chat.Poll.SubmitVote")),Object(se.ripple)(this.sendVoteBtn),t.chosenIndexes.length||this.votersCountDiv.classList.add("hide"),Object(l.b)(this.sendVoteBtn,e=>{Object(c.a)(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),Object(l.b)(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),Object(l.b)(t,s=>{Object(c.a)(s),t.classList.add("active"),((e,t,s)=>{ss&&ts(ss,is,ns);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=J.a.wrapRichText(e,{entities:t}),er.chat.bubbles.bubblesContainer.append(i),i.offsetLeft,i.classList.add("active"),ss=i,is=s,ns=window.setTimeout(()=>{ts(i,s,ns)},ue.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=Object(Me.a)(e.target,"poll-answer");if(!t)return;Object(c.a)(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=Je.a.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"),Object(k.a)(this.typeDiv,Object(x.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?Object(l.b)(this,this.clickHandler):Object(l.c)(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&&Object(Jt.a)(this,"",!this.isRetracted,340),Object(De.b)(()=>{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)=>{t+=`<avatar-element class="avatar-16 poll-avatar" dialog="0" peer="${e}" ${0===s?"":`style="transform: translateX(-${3*s}px);"`}></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?Object(De.b)(e):e()}let n;e=e.slice(),es(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",Object(k.a)(this.votersCountDiv,Object(x.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]*as.MAX_LENGTH+", 485.9",s.style.strokeDashoffset=""+t*as.MAX_OFFSET)}}as.MAX_OFFSET=-46.5,as.MAX_LENGTH=0,customElements.define("poll-element",as);var os=s(111),rs=s(98),ls=s(60),cs=s(99),ds=s(120),hs=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 ps=new class{constructor(){this.storage=new cs.a(ds.a,"stickerSets"),this.getStickerSetPromises={},this.getStickersByEmoticonsPromises={},this.getAnimatedEmojiStickerSet(),a.default.addMultipleEventsListeners({updateNewStickerSet:e=>{this.saveStickerSet(e.stickerset,e.stickerset.set.id),a.default.dispatchEvent("stickers_installed",e.stickerset.set)}}),this.getGreetingStickersTimeout=window.setTimeout(()=>{this.getGreetingStickersTimeout=void 0,this.getGreetingSticker(!0)},5e3)}getGreetingSticker(e=!1){return this.getGreetingStickersTimeout&&(clearTimeout(this.getGreetingStickersTimeout),this.getGreetingStickersTimeout=void 0),this.getGreetingStickersPromise||(this.getGreetingStickersPromise=this.getStickersByEmoticon("👋⭐️",!1).then(e=>{if(!e.length)throw"NO_STICKERS";this.greetingStickers=e.slice(),this.greetingStickers.sort((e,t)=>Math.random()-Math.random())})),this.getGreetingStickersPromise.then(()=>{let t;return e||(t=this.greetingStickers.shift(),this.greetingStickers.push(t)),E.a.downloadDoc(this.greetingStickers[0]),t})}saveStickers(e){Object(f.d)(e,(t,s)=>{(t=E.a.saveDoc(t))?e[s]=t:e.splice(s,1)})}getStickerSet(e,t={}){return hs(this,void 0,void 0,(function*(){const s=e.id;return this.getStickerSetPromises[s]?this.getStickerSetPromises[s]:this.getStickerSetPromises[s]=new Promise(i=>hs(this,void 0,void 0,(function*(){var n;if(!t.overwrite){const e=yield this.storage.get(s);if(e&&(null===(n=e.documents)||void 0===n?void 0:n.length)&&(Date.now()-e.refreshTime<36e5||t.useCache))return this.saveStickers(e.documents),i(e),void delete this.getStickerSetPromises[s]}try{const n=yield ht.a.invokeApi("messages.getStickerSet",{stickerset:this.getStickerSetInput(e)}),a=t.saveById?s:n.set.id;this.saveStickerSet(n,a),i(n)}catch(e){i(null)}delete this.getStickerSetPromises[s]})))}))}getAnimatedEmojiStickerSet(){return this.getStickerSet({id:"emoji"},{saveById:!0})}getRecentStickers(){return hs(this,void 0,void 0,(function*(){const e=yield ht.a.invokeApiHashable("messages.getRecentStickers");return this.saveStickers(e.stickers),e}))}getAnimatedEmojiSticker(e){const t=this.storage.getFromCache("emoji");if(!t||!t.documents)return;e=e.replace(/\ufe0f/g,"").replace(/🏻|🏼|🏽|🏾|🏿/g,"");const s=t.packs.find(t=>t.emoticon===e);return s?E.a.getDoc(s.documents[0]):void 0}preloadAnimatedEmojiSticker(e,t,s){return this.getAnimatedEmojiStickerSet().then(()=>{const i=this.getAnimatedEmojiSticker(e);if(i)return E.a.downloadDoc(i).then(ne.c).then(n=>hs(this,void 0,void 0,(function*(){const a=b.b.active.emojiSticker,o=Object(ie.d)(e),r=yield le.a.loadAnimationWorker({container:void 0,animationData:n,width:null!=t?t:a.width,height:null!=s?s:a.height,name:"doc"+i.id,autoplay:!1,loop:!1},"none",o);r.addEventListener("firstFrame",()=>{E.a.saveLottiePreview(i,r.canvas,o),r.remove()},{once:!0})})))})}saveStickerSet(e,t){const s={_:"messages.stickerSet",set:e.set,packs:e.packs,documents:e.documents};let i=this.storage.getFromCache(t);i?Object.assign(i,s):i=this.storage.setToCache(t,s),this.saveStickers(e.documents);const n=i.set.installed_date||"emoji"===t;i.refreshTime=Date.now(),this.storage.set({[t]:i},!n)}getStickerSetThumbDownloadOptions(e){var t;const s=e.thumbs.find(e=>"photoSize"===e._),i=e.thumb_dc_id,n=null===(t=e.pFlags)||void 0===t?void 0:t.animated;return{dcId:i,location:{_:"inputStickerSetThumb",stickerset:this.getStickerSetInput(e),thumb_version:e.thumb_version},size:s.size,mimeType:n?"application/x-tgsticker":"image/webp"}}getStickerSetInput(e){return"emoji"===e.id?{_:"inputStickerSetAnimatedEmoji"}:e.access_hash?{_:"inputStickerSetID",id:e.id,access_hash:e.access_hash}:{_:"inputStickerSetShortName",short_name:""+e.id}}getFeaturedStickers(){return hs(this,void 0,void 0,(function*(){const e=yield ht.a.invokeApiHashable("messages.getFeaturedStickers");return e.sets.forEach(e=>{this.saveStickerSet({set:e.set,documents:[],packs:[]},e.set.id)}),e.sets}))}toggleStickerSet(e){return hs(this,void 0,void 0,(function*(){if(e.installed_date){if(yield ht.a.invokeApi("messages.uninstallStickerSet",{stickerset:this.getStickerSetInput(e)}))return delete e.installed_date,a.default.dispatchEvent("stickers_deleted",e),this.storage.delete(e.id,!0),!0}else{if(yield ht.a.invokeApi("messages.installStickerSet",{stickerset:this.getStickerSetInput(e),archived:!1}))return e.installed_date=Date.now()/1e3|0,a.default.dispatchEvent("stickers_installed",e),!0}return!1}))}searchStickerSets(e,t=!0){return hs(this,void 0,void 0,(function*(){const s=t?1:0,i=yield ht.a.invokeApiHashable("messages.searchStickerSets",{flags:s,exclude_featured:t||void 0,q:e});i.sets.forEach(e=>{this.saveStickerSet({set:e.set,documents:[],packs:[]},e.set.id)});const n=[],a=this.storage.getCache();for(let t in a){const{set:s}=a[t];s.title.toLowerCase().includes(e.toLowerCase())&&!i.sets.find(e=>e.set.id===s.id)&&n.push({_:"stickerSetCovered",set:s,cover:null})}return i.sets.concat(n)}))}getAllStickers(){return ht.a.invokeApiHashable("messages.getAllStickers")}preloadStickerSets(){return this.getAllStickers().then(e=>Promise.all(e.sets.map(e=>this.getStickerSet(e,{useCache:!0}))))}getStickersByEmoticon(e,t=!0){return e=J.b.fixEmoji(e),this.getStickersByEmoticonsPromises[e]?this.getStickersByEmoticonsPromises[e]:this.getStickersByEmoticonsPromises[e]=Promise.all([ht.a.invokeApiHashable("messages.getStickers",{emoticon:e}),t?this.preloadStickerSets():[],t?this.getRecentStickers():void 0]).then(([t,s,i])=>{const n=t.stickers.map(e=>E.a.saveDoc(e)),a=[],o=[],r=t=>{for(const s of t){if(J.b.fixEmoji(s.emoticon).includes(e))for(const e of s.documents){const t=E.a.getDoc(e);(t.animated?a:o).push(t)}}};if(i){r(i.packs);const e=i.stickers;[a,o].forEach(t=>{t.sort((t,s)=>e.indexOf(t)-e.indexOf(s))})}for(const e of s)r(e.packs);return[...new Set(a.concat(o,n))]})}pushRecentSticker(e){const t=J.b.fixEmoji(e.stickerEmojiRaw);for(const s in this.getStickersByEmoticonsPromises){this.getStickersByEmoticonsPromises[s].then(i=>{const n=i.findAndSplice(t=>t.id===e.id);n?i.unshift(n):s.includes(t)&&i.unshift(e)})}}};de.a.appStickersManager=ps;var us=ps,ms=s(61),gs=s(127),bs=s(130),vs=s(121),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 ys=0;function ws({doc:e,container:t,message:s,boxWidth:i,boxHeight:n,withTail:o,isOut:r,middleware:d,lazyLoadQueue:h,noInfo:p,group:u,onlyPreview:m,withoutPreloader:g,loadPromises:v,noPlayButton:f,noAutoDownload:y,size:w,searchContext:S}){var L,I;const M=!(i&&n),P=("video"!==e.type||e.size<=52428800&&!M)&&("gif"===e.type?a.default.settings.autoPlay.gifs:a.default.settings.autoPlay.videos);let T,k;if(!p){T=document.createElement("span"),T.classList.add("video-time"),t.append(T);let s=!1;"gif"!==e.type?(T.innerText=(e.duration+"").toHHMMSS(!1),f||"round"===e.type||(P&&!y?T.classList.add("tgico","can-autoplay"):s=!0)):(T.innerText="GIF",P||f||(s=!0,y=void 0)),s&&(k=document.createElement("span"),k.classList.add("video-play","tgico-largeplay","btn-circle","position-center"),t.append(k))}let x,O={};if("image/gif"===e.mime_type){const a=Ls({photo:e,message:s,container:t,boxWidth:i,boxHeight:n,withTail:o,isOut:r,lazyLoadQueue:h,middleware:d,withoutPreloader:g,loadPromises:v,noAutoDownload:y,size:w});return O.thumb=a,O.loadPromise=a.loadPromises.full,O}const A=document.createElement("video");if(A.classList.add("media-video"),A.setAttribute("playsinline","true"),A.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=b.b.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 d=i.firstElementChild.firstElementChild;ys||(ys=2*Math.PI*r),d.style.strokeDasharray=ys+" "+ys,d.style.strokeDashoffset=""+ys,T.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,T),i.append(A),t.append(i);const p=h.getContext("2d"),u=()=>{const e=i.message,t=fe.addMedia(e,!y),s=()=>{(er.chat.setPeerPromise||Promise.resolve()).finally(()=>{Object(ms.a)(t)||(t.removeEventListener("play",r),t.removeEventListener("timeupdate",o),t.removeEventListener("pause",u),t.removeEventListener("ended",m))})},n=()=>{p.drawImage(t,0,0);const e=ys-t.currentTime/t.duration*ys;return d.style.strokeDashoffset=""+e,!t.paused},a=()=>{t.duration&&(Object(ms.a)(t)?(t.paused&&n(),T.innerText=(t.duration-t.currentTime+"").toHHMMSS(!1)):s())},o=je(a),r=()=>{A.classList.add("hide"),i.classList.remove("is-paused"),Object(os.b)(n,h),x&&x.preloader&&x.preloader.classList.contains("manual")&&x.onClick()},u=()=>{Object(ms.a)(t)?i.classList.add("is-paused"):s()},m=()=>{A.classList.remove("hide"),i.classList.add("is-paused"),A.currentTime=0,T.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",m),Object(l.b)(h,s=>{if(Object(c.a)(s),x&&!x.detached&&x.onClick(),t.paused){const s=!!S;if(fe.setSearchContext(S||{peerId:Be.b,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1})){const[t,n]=s?He(i):[];fe.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(),A.classList.add("hide")):u():r()};s.pFlags.is_outgoing?(i.onLoad=u,i.dataset.isOutgoing="1"):u()}else A.autoplay=!0;let _;if(s){if(_=Ls({photo:e,message:s,container:t,boxWidth:i,boxHeight:n,withTail:o,isOut:r,lazyLoadQueue:h,middleware:d,withoutPreloader:!0,loadPromises:v,noAutoDownload:y,size:w}),O.thumb=_,!P&&"gif"!==e.type||m)return O.loadPromise=_.loadPromises.full,O;if(o){const e=(_.images.thumb||_.images.full).parentElement;A.width=+e.getAttributeNS(null,"width"),A.height=+e.getAttributeNS(null,"height"),e.append(A)}}else{const t=E.a.getThumb(e,!1);t&&t.promise.then(()=>{A.poster=t.cacheContext.url})}!A.parentElement&&t&&((null==_?void 0:_.aspecter)||t).append(A);const F=he.a.getCacheContext(e),D=!!(null===(L=null==s?void 0:s.media)||void 0===L?void 0:L.preloader);D?(x=s.media.preloader,x.attach(t,!1),y=void 0):F.downloaded||e.supportsStreaming?e.supportsStreaming&&(x=new ye.a({cancelable:!1,attachMethod:"prepend"})):x=new ye.a({attachMethod:"prepend"});const j=Object(ae.a)();A.addEventListener("error",e=>{4!==A.error.code&&console.error("Error "+A.error.code+"; details: "+A.error.message),x&&!D&&x.detach(),j.isFulfilled||j.resolve()},{once:!0}),Object(me.e)(A).then(()=>{u&&C.a.addAnimation(A,u),x&&!D&&x.detach(),j.resolve()}),"video"===e.type&&A.addEventListener("timeupdate",()=>{T.innerText=(A.duration-A.currentTime+"").toHHMMSS(!1)}),A.muted=!0,A.loop=!0,A.autoplay=!0;let B=y&&(null===(I=null==_?void 0:_.preloader)||void 0===I?void 0:I.loadFunc);const R=()=>{x&&y&&!g&&(x.construct(),x.setManual());let i=Promise.resolve();if(x&&!D)if(F.downloaded||e.supportsStreaming)e.supportsStreaming&&(y?i=Promise.reject():F.downloaded||(x.attach(t,!1,null),A.addEventListener(re.IS_SAFARI?"timeupdate":"canplay",()=>{x.detach()},{once:!0})));else{const s=i=E.a.downloadDoc(e,null==h?void 0:h.queueId,y);x.attach(t,!1,s)}return!y&&B&&(B(),B=null),y=void 0,i.then(()=>{!d||d()?("round"===e.type&&fe.resolveWaitingForLoadMedia(s.peerId,s.mid,s.pFlags.is_scheduled),Object(rs.a)(A,F.url)):j.resolve()},()=>{}),{download:i,render:j}};return x&&!D&&x.setDownloadFunction(R),"gif"!==e.type||P?O.loadPromise=h?(h.push({div:t,load:()=>R().render}),Promise.resolve()):R().render:Object(l.b)(t,e=>{Object(c.a)(e),k.remove(),R()},{capture:!0,once:!0}),O}function Ss({message:e,withTime:t,fontWeight:s,voiceAsMusic:n,showSender:o,searchContext:c,loadPromises:d,noAutoDownload:h,lazyLoadQueue:p}){var u,g;s||(s=500);const b=e.media.document||e.media.webpage.document,v=e.pFlags.is_outgoing&&(null===(u=e.media)||void 0===u?void 0:u.preloader);if("audio"===b.type||"voice"===b.type||"round"===b.type){const i=new Ne;return i.withTime=t,i.message=e,i.noAutoDownload=h,i.lazyLoadQueue=p,i.loadPromises=d,n&&(i.voiceAsMusic=n),c&&(i.searchContext=c),o&&(i.showSender=o),v&&(i.preloader=e.media.preloader),i.dataset.fontWeight=""+s,i.render(),i}let f=b.file_name?b.file_name.split("."):"",y="";y=f.length>1&&Array.isArray(f)?Object(gs.a)(f.pop().split(" ",1)[0].toLowerCase()):"file";let w=document.createElement("div");w.classList.add("document","ext-"+y),w.dataset.docId=""+b.id;const S=document.createElement("div");S.classList.add("document-ico");const L=he.a.getCacheContext(b);if((null===(g=b.thumbs)||void 0===g?void 0:g.length)||e.pFlags.is_outgoing&&L.url&&"photo"===b.type){w.classList.add("document-with-thumb");let t=[];if(e.pFlags.is_outgoing)S.innerHTML=`<img src="${L.url}">`,t.push(S.firstElementChild);else{const e=Ls({photo:b,message:null,container:S,boxWidth:54,boxHeight:54,loadPromises:d,withoutPreloader:!0,lazyLoadQueue:p,size:r.a.choosePhotoSize(b,54,54,!0)});S.style.width=S.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 S.innerText=y;let C=b.fileName||"Unknown.file";document.createElement("div").classList.add("document-description");const M=[Object(I.b)(b.size)];t&&M.push(Object(oe.d)(e.date)),o&&M.push(i.a.wrapSenderToPeer(e)),w.innerHTML=`\n ${L.downloaded&&!v?"":'<div class="document-download"></div>'}\n <div class="document-name"></div>\n <div class="document-size"></div>\n `;const P=w.querySelector(".document-name"),T=new Ae.a;T.dataset.fontWeight=""+s,T.innerHTML=C,P.append(T),o&&P.append(i.a.wrapSentTime(e));if(w.querySelector(".document-size").append(...Object(x.joinElementsWith)(M," · ")),w.prepend(S),!v&&e.pFlags.is_outgoing)return w;let k,O=null;const A=()=>{if(k){k.classList.add("downloaded");const e=k;setTimeout(()=>{e.remove()},200),k=null}O&&(O=null)},_=e=>{var t;const s=!e||e.isTrusted,i=E.a.getDoc(w.dataset.docId);let n;const o=er.chat.bubbles?er.chat.bubbles.lazyLoadQueue.queueId:void 0;return s?"pdf"===i.type?(n=E.a.downloadDoc(i,o),n.then(()=>{setTimeout(()=>{const e=he.a.getCacheContext(i).url;window.open(e)},a.default.settings.animationsEnabled?250:0)})):n=m.has(i.mime_type)&&(null===(t=i.thumbs)||void 0===t?void 0:t.length)?E.a.downloadDoc(i,o):E.a.saveDocFile(i,o):n=E.a.downloadDoc(i,o),k&&(n.then(A),O.attach(k,!0,n)),{download:n}};return E.a.downloading.has(b.id)?(k=w.querySelector(".document-download"),O=new ye.a,O.attach(k,!1,E.a.downloading.get(b.id))):L.downloaded&&!v||(k=w.querySelector(".document-download"),O=e.media.preloader,O?(O.attach(k),e.media.promise.then(A)):(O=new ye.a,O.construct(),O.setManual(),O.attach(k),O.setDownloadFunction(_))),Object(l.b)(w,e=>{O?O.onClick(e):_(e)}),w}function Ls({photo:e,message:t,container:s,boxWidth:i,boxHeight:n,withTail:o,isOut:l,lazyLoadQueue:c,middleware:d,size:h,withoutPreloader:p,loadPromises:u,noAutoDownload:m,noBlur:g,noThumb:v,noFadeIn:f,blurAfter:y}){var w;if(!e.sizes&&!e.thumbs)return i&&n&&!h&&"document"===e._&&r.a.setAttachmentSize(e,s,i,n,void 0,t),{loadPromises:{thumb:Promise.resolve(),full:Promise.resolve()},images:{thumb:null,full:null},preloader:null,aspecter:null};h||(void 0===i&&(i=b.b.active.regular.width),void 0===n&&(n=b.b.active.regular.height)),s.classList.add("media-container");let S,L,C,I=s,M=!0,P=Promise.resolve();const T="document"===e._&&"image/gif"===e.mime_type&&!h;if(L=new Image,i&&n&&!h){const a=r.a.setAttachmentSize(e,s,i,n,void 0,t,void 0,T?{_:"photoSize",w:e.w,h:e.h,size:e.size,type:"full"}:void 0);if(h=a.photoSize,M=a.isFit,C=he.a.getCacheContext(e,h.type),!M){I=document.createElement("div"),I.classList.add("media-container-aspecter"),I.style.width=a.size.width+"px",I.style.height=a.size.height+"px";const i=r.a.getStrippedThumbIfNeeded(e,C,!g,!0);if(i){P=i.loadPromise;const e=i.image;e.classList.add("media-photo"),s.append(e)}else{Ls({container:s,message:t,photo:e,boxWidth:0,boxHeight:0,size:h,lazyLoadQueue:c,isOut:l,loadPromises:u,middleware:d,withoutPreloader:p,withTail:o,noAutoDownload:m,noBlur:g,noThumb:!0,blurAfter:!0}).images.full.classList.add("media-photo","thumbnail")}s.classList.add("media-container-fitted"),s.append(I)}}else h||(h=r.a.choosePhotoSize(e,i,n,!0)),C=he.a.getCacheContext(e,null==h?void 0:h.type);if(!v){const t=r.a.getStrippedThumbIfNeeded(e,C,!g);t&&(P=Promise.all([P,t.loadPromise]),S=t.image,S.classList.add("media-photo"),I.append(S))}L.classList.add("media-photo");const k=(S||!C.downloaded)&&a.default.settings.animationsEnabled&&!f;let x;(null===(w=null==t?void 0:t.media)||void 0===w?void 0:w.preloader)&&!p?(x=t.media.preloader,x.attach(s),m=void 0):C.downloaded||(x=new ye.a({attachMethod:"prepend"}));const O=e=>Es(s,L,e,k,I,S),A=()=>d&&!d()?Promise.resolve():y?Object(bs.a)(C.url,12).then(e=>O(e)):O(C.url);let _;const F=h.w>=150&&h.h>=150||m,D=()=>{m&&!p&&x&&(x.construct(),x.setManual());const t=T&&!h?E.a.downloadDoc(e,null==c?void 0:c.queueId):r.a.preloadPhoto(e,h,null==c?void 0:c.queueId,m);x&&!C.downloaded&&!p&&F&&x.attach(s,!1,t),m=void 0;const i=t.then(A);return i.catch(()=>{}),{download:t,render:i}};return x&&x.setDownloadFunction(D),C.downloaded?P=_=D().render:c?c.push({div:s,load:()=>D().download}):_=D().render,u&&P&&u.push(P),{loadPromises:{thumb:P,full:_||Promise.resolve()},images:{thumb:S,full:L},preloader:x,aspecter:I}}function Es(e,t,s,i,n=e,a){return i&&t.classList.add("fade-in"),new Promise(o=>{Object(rs.a)(t,s,()=>{ls.a.mutateElement(e,()=>{n.append(t),Object(De.b)(()=>{o()}),i&&t.addEventListener("animationend",()=>{ls.a.mutate(()=>{t.classList.remove("fade-in"),a&&a.remove()})},{once:!0})})})})}function Cs({doc:e,div:t,middleware:s,lazyLoadQueue:i,group:n,play:o,onlyThumb:d,emoji:h,width:p,height:u,withThumb:m,loop:g,loadPromises:b,needFadeIn:v}){var f;const y=e.sticker;if(p||(p=h?void 0:200),u||(u=h?void 0:200),2===y&&le.a.loadLottieWorkers(),!y)throw console.error("wrong doc for wrapSticker!",e),new Error("wrong doc for wrapSticker!");t.dataset.docId=""+e.id,t.classList.add("media-sticker-wrapper");const w=he.a.getCacheContext(e),S=h?Object(ie.d)(h):-1,L=w.downloaded&&!v;let C=Object(ae.a)(),I=!1;if(((null===(f=e.thumbs)||void 0===f?void 0:f.length)||e.stickerCachedThumbs)&&!t.firstElementChild&&(!L||2===y||d)){let n,a=e.stickerCachedThumbs&&e.stickerCachedThumbs[S]||e.thumbs[0];const o=()=>{t.childElementCount||(n.classList.add("media-sticker","thumbnail"),ls.a.mutateElement(t,()=>{t.append(n),C.resolve()}))};if("url"in a)n=new Image,Object(rs.a)(n,a.url,o),I=!0;else if("bytes"in a){if("photoPathSize"===a._)if(a.bytes.length){const s=r.a.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._&&S<=0&&(n=new Image,vs.a||e.pFlags.stickerThumbConverted||w.url?(Object(rs.a)(n,r.a.getPreviewURLFromThumb(e,a,!0),o),I=!0):ce.a.convert(""+e.id,a.bytes).then(i=>{a.bytes=i,e.pFlags.stickerThumbConverted=!0,s&&!s()||t.childElementCount||Object(rs.a)(n,r.a.getPreviewURLFromThumb(e,a,!0),o)}).catch(()=>{}))}else if(2===y&&(m||d)&&S<=0){n=new Image;const r=()=>{if(t.childElementCount||s&&!s())return;const i=()=>{t.childElementCount||s&&!s()||Object(rs.a)(n,w.url,o)};return w.url?(i(),Promise.resolve()):E.a.getThumbURL(e,a).promise.then(i)};if(i&&d)return i.push({div:t,load:r}),Promise.resolve();r(),a.url&&(I=!0)}}if(b&&I&&b.push(C),d)return Promise.resolve();const M=()=>fs(this,void 0,void 0,(function*(){if(!s||s())if(2===y)yield E.a.downloadDoc(e,null==i?void 0:i.queueId).then(ne.c).then(i=>fs(this,void 0,void 0,(function*(){if(s&&!s())return;let r=yield le.a.loadAnimationWorker({container:t,loop:g&&!h,autoplay:o,animationData:i,width:p,height:u,name:"doc"+e.id},n,S);r.addEventListener("firstFrame",()=>{const s=t.firstElementChild;v=(v||!s||"svg"===s.tagName)&&a.default.settings.animationsEnabled;const i=()=>{s&&s!==r.canvas&&s.remove()};v?ls.a.mutate(()=>{r.canvas.classList.add("fade-in"),s&&s.classList.add("fade-out"),r.canvas.addEventListener("animationend",()=>{ls.a.mutate(()=>{r.canvas.classList.remove("fade-in"),i()})},{once:!0})}):s&&ls.a.mutate(i),E.a.saveLottiePreview(e,r.canvas,S)},{once:!0}),h&&Object(l.b)(t,e=>{Object(c.a)(e);let s=le.a.getAnimation(t);s.paused&&(s.autoplay=!0,s.restart())})})));else if(1===y){const n=new Image,o=t.firstElementChild!==n&&t.firstElementChild;return v=(v||!L||o)&&a.default.settings.animationsEnabled,n.classList.add("media-sticker"),v&&n.classList.add("fade-in"),new Promise((a,r)=>{const l=()=>{if(s&&!s())return a();Object(rs.a)(n,w.url,()=>{ls.a.mutateElement(t,()=>{t.append(n),o&&o.classList.add("fade-out"),a(),v&&n.addEventListener("animationend",()=>{n.classList.remove("fade-in"),o&&o.remove()},{once:!0})})})};w.url?l():E.a.downloadDoc(e,null==i?void 0:i.queueId).then(l,a)})}})),P=!i||L&&2!==y?M():(i.push({div:t,load:M}),Promise.resolve());return L&&1===y&&(C=P,b&&b.push(C)),P}function Is({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=us.getStickerSetThumbDownloadOptions(e),r=he.a.download(t);if(e.pFlags.animated)return r.then(ne.c).then(t=>{le.a.loadAnimationWorker({container:s,loop:!0,autoplay:n,animationData:t,width:a,height:o,needUpscale:!0,name:"setThumb"+e.id},i)});{const e=new Image;return e.classList.add("media-sticker"),r.then(t=>{Object(rs.a)(e,URL.createObjectURL(t),()=>{s.append(e)})})}}});const l=us.getStickerSet(e),c=yield l;"documentEmpty"!==c.documents[0]._&&Cs({doc:c.documents[0],div:s,group:i,lazyLoadQueue:t})}))}function Ms(e,t,s){const i=new Ge("reply");return i.fill(e,t,s),i.container}function Ps(e){const t=new Ye(e.items,e.maxWidth,e.minWidth,e.spacing,e.maxHeight).layout(),s=t.find(e=>e.sides&qe),i=s.geometry.width+s.geometry.x,n=t.find(e=>e.sides&Qe),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+"%",s&$e&&s&We&&(l.style.borderTopLeftRadius="inherit"),s&$e&&s&Qe&&(l.style.borderBottomLeftRadius="inherit"),s&qe&&s&We&&(l.style.borderTopRightRadius="inherit"),s&qe&&s&Qe&&(l.style.borderBottomRightRadius="inherit"),e.forMedia){const e=document.createElement("div");e.classList.add("album-item-media"),l.append(e)}})}function Ts({groupId:e,attachmentDiv:t,middleware:s,uploading:n,lazyLoadQueue:a,isOut:o,chat:l,loadPromises:c,noAutoDownload:d}){const h=[],p=i.a.getMidsByAlbum(e);for(const e of p){const t=l.getMessage(e),s=t.media.photo||t.media.document,i="photo"===s._?r.a.choosePhotoSize(s,480,480):{w:s.w,h:s.h};h.push({size:i,media:s,message:t})}Ps({container:t,items:h.map(e=>({w:e.size.w,h:e.size.h})),maxWidth:b.b.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._?Ls({photo:r,message:l,container:p,boxWidth:0,boxHeight:0,isOut:o,lazyLoadQueue:a,middleware:s,size:n,loadPromises:c,noAutoDownload:d}):ws({doc:l.media.document,container:p,message:l,boxWidth:0,boxHeight:0,withTail:!1,isOut:o,lazyLoadQueue:a,middleware:s,loadPromises:c,noAutoDownload:d})})}b.b.addEventListener("changeScreen",(e,t)=>{if(t===b.a.mobile||e===b.a.mobile){const e=Array.from(document.querySelectorAll(".media-round .progress-ring")),t=b.b.active.round.width,s=t/2,i=s-7;ys=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=ys+" "+ys,n.style.strokeDashoffset=""+ys})}}),a.default.addEventListener("download_start",e=>{Array.from(document.querySelectorAll(`.document[data-doc-id="${e}"]`)).forEach(e=>{e.querySelector(".preloader-container.manual")&&Object(l.d)(e)})});var ks=s(83),xs=s(110),Os=s(84);function As(e,t,s,i){return void 0===i&&(i=e.parentElement===t?Object(Os.a)(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)}class _s{constructor(e){this.updateElementWith=e=>e(),this.updateListWith=e=>e(!0),this.middleware=Object(xs.a)(),Object(w.g)(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=Object(f.f)(this.sorted,s,"index");if(!t&&this.onSort){const e=this.middleware.get();(i||this.updateElementWith)(()=>{e()&&this.onSort(s,n)})}}}var 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())}))};class Ds extends _s{constructor(e={}){let t;super({getIndex:e=>P.a.getUserStatusForSort(e.id),onDelete:e=>{e.dom.listEl.remove(),this.onListLengthChange&&this.onListLengthChange()},onUpdate:e=>{const t=P.a.getUserStatusString(e.id);Object(k.a)(e.dom.lastMessageSpan,t)},onSort:(e,t)=>{const s=e.dom.listEl.parentElement!==this.list;As(e.dom.listEl,this.list,t),s&&this.onListLengthChange&&this.onListLengthChange()},onElementCreate:e=>{const{dom:t}=kr.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.b,updateListWith:e=>Fs(this,void 0,void 0,(function*(){return Object(ms.a)(this.list)?(yield Object(ks.c)(),Object(ms.a)(this.list)?void e(!0):e(!1)):e(!1)}))}),this.avatarSize=48,this.rippleEnabled=!0,this.autonomous=!0,Object(w.g)(this,e),this.list=kr.createChatList(this.createChatListOptions);const s=()=>{t=window.setTimeout(()=>{this.updateList(e=>{e&&s()})},Ds.SORT_INTERVAL)};s()}}Ds.SORT_INTERVAL=3e4;var js=s(72);function Bs(e){let t=!1;return new Vt(Object.assign(Object.assign({},e),{verifyTouchTarget:t=>!Object(Me.a)(t.target,"progress-line")&&!Object(js.a)(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))Object(c.a)(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 Rs(e){return Bs(Object.assign(Object.assign({},e),{onSwipe:(t,s,i)=>{if(Math.abs(t)>50)return e.onSwipe(t,s,i),Object(te.b)(),!0}}))}var Us=s(107),Hs=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 Ns extends Pt{constructor(e,t,s=!1){super({peerTypes:["dialogs","contacts"],onSelect:s?t:s=>Hs(this,void 0,void 0,(function*(){if(t){const e=t(s);e instanceof Promise&&(yield e)}er.setInnerPeer(s),er.chat.input.initMessagesForward(e)})),placeholder:"ShareModal.Search.ForwardPlaceholder",chatRightsAction:"send_messages",selfPresence:"ChatYourSelf"})}}class zs{constructor(e,t,s,n){const r=new Lt.a({peerId:e}).element;t=t.slice();const l=(a,o)=>{n&&n(),"scheduled"===s?i.a.deleteScheduledMessages(e,t):i.a.deleteMessages(e,t,!!a.size||o)};let c,d,h,p,u,m=[];if(1===t.length?c="DeleteSingleMessagesTitle":(c="DeleteMessagesTitle",d=[Object(x.i18n)("messages",[t.length])]),h=o.a.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())m.push({text:"DeleteMessagesOptionAlso",textArgs:[r]});else{const s=K.a.getChat(e.toChatId()),n=K.a.hasRights(e.toChatId(),"delete_messages");if("chat"===s._){const s=n?t.slice():t.filter(t=>i.a.getMessageByPeer(e,t).fromId===a.default.myId);s.length&&(s.length===t.length?m.push({text:"DeleteForAll"}):(m.push({text:"DeleteMessagesOption"}),h="DeleteMessagesTextGroup",p=[Object(x.i18n)("messages",[s.length])]))}else u[0].callback=e=>l(e,!0)}Object(ut.a)(u);new gt("popup-delete-chat",{peerId:e,titleLangKey:c,titleLangArgs:d,descriptionLangKey:h,descriptionLangArgs:p,buttons:u,checkboxes:m}).show()}}var Vs=s(136);class Gs{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.a.sendScheduledMessages(e,t)}});new gt("popup-delete-chat",{peerId:e,title:n,description:a,buttons:o}).show()}}var Ks=s(7);function Ws(){window.getSelection?window.getSelection().empty?window.getSelection().empty():window.getSelection().removeAllRanges&&window.getSelection().removeAllRanges():document.selection&&document.selection.empty()}var qs=s(106);const Qs=e=>[...e.values()].reduce((e,t)=>e+t.size,0);class $s{constructor(e){if(this.selectedMids=new Map,this.isSelecting=!1,this.cancelSelection=()=>{this.onCancelSelection&&this.onCancelSelection(),this.selectedMids.clear(),this.toggleSelection(),Ws()},Object(w.g)(this,e),this.navigationType="multiselect-"+Object(at.b)(),ue.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 Object(te.a)(this.listenElement,e=>{if(this.isSelecting||this.verifyTouchLongPress&&!this.verifyTouchLongPress())return;document.body.classList.add("no-select"),this.listenElement.addEventListener("touchend",e=>{Object(c.a)(e),document.body.classList.remove("no-select")},{once:!0,capture:!0}),Ws();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=Object(Me.a)(e,this.lookupBetweenParentClassName);if(!a)return[];const o=Array.from(a.querySelectorAll(this.lookupBetweenElementsQuery));let r=o.indexOf(e),l=o.indexOf(t);n||([l,r]=[r,l]);return o.slice(r+1,l)};this.listenerSetter.add(this.listenElement)("mousedown",e=>{const s=Object(Me.a)(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();Object(ms.a)(a)||(a=e);let c=i.get(l);if(c||i.set(l,c=new Set),!c.has(r)){const d=this.isMidSelected(l,r);if(void 0===n&&(n=!d),c.add(r),n&&!d||!n&&d){const n=Qs(i);if(this.toggleByElement&&s){n<2&&Object(qs.a)(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 d=e=>{r||(Ws(),r=!0);const t=this.getElementFromTarget(e.target);if(t)return this.verifyMouseMoveTarget&&!this.verifyMouseMoveTarget(e,t,n)?(this.listenerSetter.removeManual(this.listenElement,"mousemove",d),void this.listenerSetter.removeManual(document,"mouseup",h,p)):void o(t)},h=e=>{i.size&&Object(l.b)(window,c.a,{capture:!0,once:!0,passive:!1}),this.listenerSetter.removeManual(this.listenElement,"mousemove",d),Ws()},p={once:!0};this.listenerSetter.add(this.listenElement)("mousemove",d),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 mt.a({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||t.action&&(s=!0),!i){this.appMessagesManager.canDeleteMessage(t)||(i=!0)}if(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;ue.IS_TOUCH_SUPPORTED||(this.listenElement.classList.toggle("no-select",this.isSelecting),s&&Ws()),Object(Ks.a)();const n=!!i||t;return this.onToggleSelection&&this.onToggleSelection(n),re.IS_MOBILE_SAFARI||(n?j.a.pushItem({type:this.navigationType,onPop:()=>{this.cancelSelection()}}):j.a.removeByType(this.navigationType)),t&&this.updateContainer(t),!0}cleanup(){this.selectedMids.clear(),this.toggleSelection(!1)}updateElementSelection(e,t){this.toggleElementCheckbox(e,!0);this.getCheckboxInputFromElement(e).checked=t,this.toggleSelection(),this.updateContainer(),Object(Jt.a)(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 lt(x.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 Ys extends $s{constructor(e,t){super({appMessagesManager:t,listenElement:e.container,listenerSetter:new R.a,verifyTarget:(e,t)=>!!t&&this.isSelecting,getElementFromTarget:e=>Object(Me.a)(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();Object(k.a)(this.selectionCountEl,Object(x.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=>{if(Object(Jt.a)(this.searchSuper.navScrollableContainer,"is-selecting",e,200,()=>{this.isSelecting||(this.selectionContainer.remove(),this.selectionContainer=this.selectionForwardBtn=this.selectionDeleteBtn=null,this.selectedText=void 0)}),Object(Jt.a)(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=H(`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=H(`message ${e}-goto`);const s={listenerSetter:this.listenerSetter};Object(l.b)(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=H(`forward ${e}-forward`),Object(l.b)(this.selectionForwardBtn,()=>{const e={};for(const[t,s]of this.selectedMids)e[t]=Array.from(s).sort((e,t)=>e-t);new Ns(e,()=>{this.cancelSelection()})},s),this.isPrivate&&(this.selectionDeleteBtn=H(`delete danger ${e}-delete`),Object(l.b)(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);if(s&&e){Array.from(this.searchSuper.tabsContainer.querySelectorAll(".search-super-item")).forEach(e=>{this.toggleElementCheckbox(e,this.isSelecting)})}return s}}class Xs extends $s{constructor(e,t,s,i){super({appMessagesManager:i,listenElement:t.bubblesContainer,listenerSetter:t.listenerSetter,getElementFromTarget:e=>Object(Me.a)(e,"grouped-item")||Object(Me.a)(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);if(e){this.chat.getMidsByMid(t).forEach(t=>e.delete(t))}}return void this.bubbles.getBubbleGroupedItems(e).forEach(this.toggleByElement)}if(!this.toggleMid(this.bubbles.peerId,t))return;if(e.classList.contains("grouped-item")){const s=Object(Me.a)(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=>{let t="",s="";if(e){const e=this.input.rowsWrapper.parentElement,i=e.querySelector(".fake-selection-wrapper"),n=e.querySelector(".fake-rows-wrapper"),a=i.getBoundingClientRect(),o=n.getBoundingClientRect(),r=o.width,l=a.width;if(r!==l){const e=l/r,i=(r-l)/2;if(t=`translateX(${a.left-o.left-i}px) scaleX(${e})`,e<1){const t=12;s=t+t*(1-e)+"px"}}}if(Object(Jt.a)(this.input.rowsWrapper,"is-centering",e,200),this.input.rowsWrapper.style.transform=t,this.input.rowsWrapper.style.borderRadius=s,Object(Jt.a)(this.listenElement,"is-selecting",e,200,()=>{this.isSelecting||(this.selectionInputWrapper.remove(),this.selectionInputWrapper=this.selectionContainer=this.selectionSendNowBtn=this.selectionForwardBtn=this.selectionDeleteBtn=null,this.selectedText=void 0),Object(De.b)(()=>{this.bubbles.onScroll()})}),this.isSelecting&&!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=H("close",{noRipple:!0});Object(l.b)(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=Object(U.a)("btn-primary btn-transparent btn-short text-bold selection-container-send",{icon:"send2"}),this.selectionSendNowBtn.append(Object(x.i18n)("MessageScheduleSend")),Object(l.b)(this.selectionSendNowBtn,()=>{new Gs(this.bubbles.peerId,[...this.selectedMids.get(this.bubbles.peerId)],()=>{this.cancelSelection()})},e)):(this.selectionForwardBtn=Object(U.a)("btn-primary btn-transparent text-bold selection-container-forward",{icon:"forward"}),this.selectionForwardBtn.append(Object(x.i18n)("Forward")),Object(l.b)(this.selectionForwardBtn,()=>{const e={};for(const[t,s]of this.selectedMids)e[t]=Array.from(s).sort((e,t)=>e-t);new Ns(e,()=>{this.cancelSelection()})},e)),this.selectionDeleteBtn=Object(U.a)("btn-primary btn-transparent danger text-bold selection-container-delete",{icon:"delete"}),this.selectionDeleteBtn.append(Object(x.i18n)("Delete")),Object(l.b)(this.selectionDeleteBtn,()=>{new zs(this.bubbles.peerId,[...this.selectedMids.get(this.bubbles.peerId)],this.chat.type,()=>{this.cancelSelection()})},e),this.selectionContainer.append(...[t,this.selectionCountEl,this.selectionSendNowBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean)),this.selectionInputWrapper.style.opacity="0",this.selectionInputWrapper.append(this.selectionContainer),this.input.rowsWrapper.parentElement.append(this.selectionInputWrapper),this.selectionInputWrapper.offsetLeft,this.selectionInputWrapper.style.opacity=""}},this.onUpdateContainer=(e,t,s)=>{Object(k.a)(this.selectionCountEl,Object(x.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);if(s){e.classList.contains("is-grouped")&&this.bubbles.getBubbleGroupedItems(e).forEach(e=>this.toggleElementCheckbox(e,t))}return 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-sending")&&!e.classList.contains("bubble-first")}}var Js=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 Zs{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?Object(l.d)(this.searchSuper.selection.selectionForwardBtn):new Ns({[this.peerId]:[this.mid]})},this.onSelectClick=()=>{this.searchSuper.selection.toggleByElement(this.target)},this.onClearSelectionClick=()=>{this.searchSuper.selection.cancelSelection()},this.onDeleteClick=()=>{this.searchSuper.selection.isSelecting?Object(l.d)(this.searchSuper.selection.selectionDeleteBtn):new zs(this.peerId,[this.mid],"chat")};const s=e=>{let s;this.init&&(this.init(),this.init=null);try{s=Object(Me.a)(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"),Object(te.e)(e,this.element),Object(te.d)(this.element,()=>{s.classList.remove("menu-open")})}};ue.IS_TOUCH_SUPPORTED||Object(te.a)(e,s)}init(){this.buttons=[{icon:"forward",text:"Forward",onClick:this.onForwardClick},{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.a.canDeleteMessage(i.a.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=Ee(this.buttons),this.element.classList.add("search-contextmenu","contextmenu"),document.getElementById("page-chats").append(this.element)}}class ei{constructor(e){this.tabs={},this.prevTabId=-1,this.lazyLoadQueue=new ee.d,this.middleware=Object(xs.a)(),this.historyStorage={},this.usedFromHistory={},this.urlsToRevoke=[],this.loadMutex=Promise.resolve(),this.nextRates={},this.loadPromises={},this.loaded={},this.loadedChats=!1,this.firstLoad=!0,this.log=Object(X.b)("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")},Object(w.g)(this,e),this.container=document.createElement("div"),this.container.classList.add("search-super"),this.searchContextMenu=new Zs(this.container,this),this.selection=new Ys(this,i.a);const t=this.navScrollableContainer=document.createElement("div");t.classList.add("search-super-tabs-scrollable","menu-horizontal-scrollable","sticky");const s=this.navScrollable=new T.a(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(Object(x.i18n)(e.name)),s.append(i),t.append(s),Object(se.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"),ue.IS_TOUCH_SUPPORTED&&Rs({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=>{Object(c.a)(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 O(!1,"messages",!0),this.scrollable.onScrolledBottom=()=>{this.mediaTab.contentTab&&this.mediaTab.contentTab.childElementCount&&this.load(!0)},this.selectTab=Object(Z.a)(this.tabsMenu,this.tabsContainer,(e,t,s)=>{if(this.prevTabId===e&&!this.skipScroll)return void this.scrollable.scrollIntoViewNew(this.container,"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(this.container,"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),Object(l.b)(this.tabsContainer,e=>{this.selection.isSelecting&&(Object(c.a)(e),this.selection.toggleByElement(Object(Me.a)(e.target,"search-super-item")))},{capture:!0,passive:!1});const o=(e,t,s,n)=>{const a=Object(Me.a)(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=Object(Me.a)(t,e);return{element:t,mid:+s.dataset.mid,peerId:s.dataset.peerId.toPeerId()}}),c=l.findIndex(e=>e.mid===o&&e.peerId===r),d=i.a.getMessageByPeer(r,o);(new nr).setSearchContext(this.copySearchContext(s)).openMedia(d,l[c].element,0,!1,l.slice(0,c),l.slice(c+1))};Object(l.b)(this.tabs.inputMessagesFilterPhotoVideo,o.bind(null,"grid-item","grid-item","inputMessagesFilterPhotoVideo")),Object(l.b)(this.tabs.inputMessagesFilterDocument,o.bind(null,"document-with-thumb","media-container","inputMessagesFilterDocument")),this.mediaTab=this.mediaTabs[0],Object(ks.a)(()=>{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}performSearchResult(e,t,s=!0){var n;return Js(this,void 0,void 0,(function*(){const a=[],o=t.contentTab,l=[],c=this.middleware.get();let d,h=t.inputFilter;switch(yield Object(ks.c)(),"inputMessagesFilterPhotoVideo"===h&&this.searchContext.query.trim()?(h="inputMessagesFilterEmpty",d=this.searchGroupMedia,o.append(d.container)):"inputMessagesFilterEmpty"===h&&(d=this.searchGroups.messages),h){case"inputMessagesFilterEmpty":for(const t of e){const{dialog:e,dom:s}=kr.addDialogNew({dialog:t.peerId,container:d.list,drawStatus:!1,avatarSize:54});kr.setLastMessage(e,t,s,this.searchContext.query)}d.list.childElementCount&&d.setActive();break;case"inputMessagesFilterPhotoVideo":for(const t of e){const e=t.media.photo||t.media.document||t.media.webpage&&t.media.webpage.document,s=document.createElement("div");let i;s.classList.add("grid-item");const n=r.a.choosePhotoSize(e,200,200);i="photo"!==e._?ws({doc:e,message:t,container:s,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:c,onlyPreview:!0,withoutPreloader:!0,noPlayButton:!0,size:n}).thumb:Ls({photo:e,message:t,container:s,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:c,withoutPreloader:!0,noBlur:!0,size:n}),[i.images.thumb,i.images.full].filter(Boolean).forEach(e=>{e.classList.add("grid-item-media")}),l.push(i.loadPromises.thumb),a.push({element:s,message:t})}break;case"inputMessagesFilterVoice":case"inputMessagesFilterRoundVoice":case"inputMessagesFilterMusic":case"inputMessagesFilterDocument":for(const t of e){const e=this.showSender||["voice","round"].includes(t.media.document.type),s=Ss({message:t,withTime:!e,fontWeight:400,voiceAsMusic:!0,showSender:e,searchContext:this.copySearchContext(h),lazyLoadQueue:this.lazyLoadQueue,noAutoDownload:!0});["audio","voice","round"].includes(t.media.document.type)&&s.classList.add("audio-48"),a.push({element:s,message:t})}break;case"inputMessagesFilterUrl":for(let t of e){let e;if((null===(n=t.media)||void 0===n?void 0:n.webpage)&&"webPageEmpty"!==t.media.webpage._)e=t.media.webpage;else{const s=t.totalEntities?t.totalEntities.find(e=>"messageEntityUrl"===e._||"messageEntityTextUrl"===e._):null;let i,n,a;if(s)a=t.message.slice(s.offset,s.offset+s.length);else{const e=J.b.matchUrl(t.message);if(!e)continue;i=e[0]}i="messageEntityTextUrl"===(null==s?void 0:s._)?s.url:i||a,n=i;const o=t.message===i;i.match(/^(ftp|http|https):\/\//)||(n="https://"+i,i=i.includes("@")?i:"https://"+i),n=new URL(n).hostname,e={url:i,display_url:n},o||(e.description=t.message,e.rDescription=J.b.wrapRichText(Object(Y.f)(t.message,150,180)))}document.createElement("div");let s=document.createElement("div");if(s.classList.add("preview","row-media"),e.photo){Ls({container:s,message:null,photo:e.photo,boxWidth:0,boxHeight:0,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue,middleware:c,size:r.a.choosePhotoSize(e.photo,60,60,!1),loadPromises:l,noBlur:!0})}else s.classList.add("empty"),s.innerHTML=J.b.getAbbreviation(e.title||e.display_url||e.description||e.url,!0);let o=e.rTitle||"",d=e.rDescription||"";const h=Object(Vs.a)(d),p=Object(Vs.a)(J.b.wrapRichText(e.url||"")).firstElementChild;p instanceof HTMLAnchorElement&&(p.innerText=decodeURIComponent(p.href)),h.firstChild&&h.append("\n"),h.append(p),this.showSender&&h.append("\n",i.a.wrapSenderToPeer(t)),o||(o=J.b.wrapPlainText(e.display_url.split("/",1)[0]));const u=new st({title:o,titleRight:i.a.wrapSentTime(t),subtitle:h,havePadding:!0,clickable:!0,noRipple:!0});u.container.append(s),u.container.innerText.trim().length&&a.push({element:u.container,message:t})}}if(this.loadMutex&&l.push(this.loadMutex),!l.length||(yield Promise.all(l),c())){if(a.length){const e=s?"append":"prepend";a.forEach(t=>{const{element:s,message:i}=t,n=this.getMonthContainerByTimestamp(this.groupByMonth?i.date:0,h);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"===h?1:e.length,o)}}))}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.a.getPeer(t),{dom:c}=kr.addDialogNew({dialog:t,container:i.list,drawStatus:!1,avatarSize:48,autonomous:i.autonomous});if(r&&(l.participants_count||l.participants)){const e=new RegExp(`(${Object(Y.e)(s)}|${Object(Y.e)(Object(gs.b)(s))})`,"gi");c.titleSpan.innerHTML=c.titleSpan.innerHTML.replace(e,"<i>$1</i>"),c.lastMessageSpan.append(n.default.getChatMembersString(t.toChatId()))}else if(t===a.default.myId)c.lastMessageSpan.append(Object(x.i18n)("Presence.YourChat"));else{let e=o.a.getPeerUsername(t);if(e)e="@"+e;else{const s=P.a.getUser(t);s&&s.phone&&(e="+"+Object(Us.a)(s.phone).formatted)}c.lastMessageSpan.innerHTML="<i>"+e+"</i>"}}),i.toggle()},l=e=>{if(t())return e};return Promise.all([P.a.getContactsPeerIds(s,!0).then(l).then(e=>{e&&r(e,this.searchGroups.contacts,!0)}),P.a.searchContacts(s,20).then(l).then(e=>{if(e&&(r(e.my_results,this.searchGroups.contacts,!0),r(e.results,this.searchGroups.globalContacts),this.searchGroups.globalContacts.nameEl.lastElementChild&&this.searchGroups.globalContacts.nameEl.lastElementChild.remove(),this.searchGroups.globalContacts.container.classList.add("is-short"),this.searchGroups.globalContacts.list.childElementCount>3)){const e=document.createElement("div");e.classList.add("search-group__show-more"),e.innerText="Show more",this.searchGroups.globalContacts.nameEl.append(e),e.addEventListener("click",()=>{const t=this.searchGroups.globalContacts.container.classList.toggle("is-short");e.innerText=t?"Show more":"Show less"})}}),i.a.getConversations(s,0,20,0).promise.then(l).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}=kr.addDialogNew({dialog:e,container:this.searchGroups.recent.list,drawStatus:!1,meAsSaved:!0,avatarSize:48,autonomous:!0});s.lastMessageSpan.append(e.isUser()?P.a.getUserStatusString(e):n.default.getChatMembersString(e.toChatId()))}),s.recentSearch.length?e&&this.searchGroups.recent.setActive():this.searchGroups.recent.clear())});return Promise.all([P.a.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=>{kr.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=>Js(this,void 0,void 0,(function*(){this.loadMutex&&(yield this.loadMutex,!s())||(this.membersList||(this.membersList=new Ds({lazyLoadQueue:this.lazyLoadQueue,rippleEnabled:!1}),this.membersList.list.addEventListener("click",e=>{const t=Object(ft.a)(e.target,"LI");if(!t)return;const s=t.dataset.peerId.toPeerId();let i=Promise.resolve();b.b.isMobile&&(i=Yt.toggleSidebar(!1)),i.then(()=>{er.setInnerPeer(s)})}),e.contentTab.append(this.membersList.list),this.afterPerforming(1,e.contentTab)),t.forEach(e=>{const t=K.a.getParticipantPeerId(e);if(t.isAnyChat())return;P.a.getUser(t).pFlags.deleted||this.membersList.add(t)}))}));if(K.a.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=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 c="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.a.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 d=l.length?l[l.length-1].mid:0;return this.loadPromises[r]=i.a.getSearch(Object.assign(Object.assign({},this.searchContext),{inputFilter:{_:r},maxId:d,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(c+"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 Js(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.a.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"),c=this.canViewMembers();l.menuTab.classList.toggle("hide",!c),c&&(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*(Et.a.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 x.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 c=Object(w.e)(a,"desc");let d=0;for(;d<c.length;++d){if(n>c[d])break}a[n]={container:e,items:l},As(e,this.tabs[t],d)}return a[n]}canViewMembers(){return this.searchContext.peerId.isAnyChat()&&!K.a.isBroadcast(this.searchContext.peerId.toChatId())&&K.a.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")||Object(te.f)(t,!0);const s=t.querySelector(".content-empty");s&&s.remove()}}),this.monthContainers={},this.searchGroupMedia.clear(),this.scrollable.scrollTop=0}copySearchContext(e){const t=Object(w.a)(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 ti,si=s(74);!function(e){e[e.Everybody=2]="Everybody",e[e.Contacts=1]="Contacts",e[e.Nobody=0]="Nobody"}(ti||(ti={}));const ii=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 ht.a.invokeApi("account.setPrivacy",{key:{_:e},rules:t}).then(s=>(P.a.saveApiUsers(s.users),K.a.saveApiChats(s.chats),si.a.processLocalUpdate({_:"updatePrivacy",key:{_:Object(Y.b)(e)},rules:t.map(e=>{const t={};return Object.assign(t,e),t._=Object(Y.b)(t._),t})}),s.rules))}getPrivacy(e){const t=Object(Y.b)(e),s=this.privacy[t];return s?Promise.resolve(s):this.privacy[t]=ht.a.invokeApi("account.getPrivacy",{key:{_:e}}).then(e=>(P.a.saveApiUsers(e.users),K.a.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}}};de.a.appPrivacyManager=ii;var ni=ii;class ai{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?Object(x._i18n)(s,t):s.innerHTML="",s.classList.toggle("hide",!t),this.exceptions&&(this.exceptions.get("allow").row.container.classList.toggle("hide",this.type===ti.Everybody),this.exceptions.get("disallow").row.container.classList.toggle("hide",this.type===ti.Nobody)),this.options.onRadioChange&&this.options.onRadioChange(e)},e.captions&&e.captions.reverse(),this.radioSection=new dn({name:e.title,caption:!0}),this.radioRows=new Map;let t=[{type:ti.Everybody,langKey:"PrivacySettingsController.Everbody"},{type:ti.Contacts,langKey:"PrivacySettingsController.MyContacts"},{type:ti.Nobody,langKey:"PrivacySettingsController.Nobody"}];e.skipTypes&&(t=t.filter(t=>!e.skipTypes.includes(t.type)));const s=Object(at.b)();t.forEach(({type:e,langKey:t})=>{const i=new st({radioField:new ot({langKey:t,name:s,value:""+e})});this.radioRows.set(e,i)});const i=it([...this.radioRows.values()],this.onRadioChange);if(this.radioSection.content.append(i),e.appendTo&&e.appendTo.append(this.radioSection.container),!e.noExceptions){const t=hn(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 st(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=ni.getPrivacy(e.inputKey).then(t=>{const s=ni.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 ti.Everybody:t.push({_:"inputPrivacyValueAllowAll"});break;case ti.Contacts:t.push({_:"inputPrivacyValueAllowContacts"});break;case ti.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=>P.a.getUserInput(e))})}}),ni.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?Object(x.join)([e.users.length?Object(x.i18n)("Users",[e.users.length]):null,e.chats.length?Object(x.i18n)("Chats",[e.chats.length]):null].filter(Boolean),!1):[Object(x.i18n)("PrivacySettingsController.AddUsers")]}}class oi extends V{init(){this.container.classList.add("privacy-tab","privacy-phone-number"),this.setTitle("PrivacyPhone");const e=new ai({tab:this,title:"PrivacyPhoneTitle",inputKey:"inputPrivacyKeyPhoneNumber",captions:["PrivacyPhoneInfo","PrivacyPhoneInfo",""],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,onRadioChange:e=>{t.setRadio(ti.Everybody),t.radioSection.container.classList.toggle("hide",e!==ti.Nobody)}}),t=new ai({tab:this,title:"PrivacyPhoneTitle2",inputKey:"inputPrivacyKeyAddedByPhone",captions:["PrivacyPhoneInfo3","PrivacyPhoneInfo3",""],noExceptions:!0,skipTypes:[ti.Nobody]});this.scrollable.container.insertBefore(t.radioSection.container,e.radioSection.container.nextSibling)}}var ri=s(79);class li extends z{init(){this.container.classList.add("two-step-verification","two-step-verification-set"),this.setTitle("TwoStepVerificationPasswordSet");const e=new dn({caption:"TwoStepVerificationPasswordSetInfo",noDelimiter:!0}),t=us.getAnimatedEmojiSticker("🥳"),s=document.createElement("div");t?Cs({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=Object(U.a)("btn-primary btn-color-primary",{text:"TwoStepVerificationPasswordReturnSettings"});Object(l.b)(a,e=>{this.close()}),this.slider.sliceTabsUntilTab(tn,this),n.append(a),i.append(n),this.scrollable.container.append(e.container)}}var ci=s(113);function di(e){return!re.IS_MOBILE_SAFARI||!e}class hi extends z{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 dn({caption:!0,noDelimiter:!0});Object(x._i18n)(e.caption,"TwoStepAuth.ConfirmEmailCodeDesc",[this.email]);const t=us.getAnimatedEmojiSticker("📬"),s=document.createElement("div");t?Cs({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 ci.a({name:"recovery-email-code",label:"TwoStepAuth.RecoveryCode",length:this.length,onFill:e=>{d(!0),ri.a.confirmPasswordEmail(""+e).then(e=>{c()}).catch(e=>{switch(e.type){case"CODE_INVALID":a.input.classList.add("error"),Object(k.a)(a.label,Object(x.i18n)("TwoStepAuth.RecoveryCodeInvalid"));break;case"EMAIL_HASH_EXPIRED":a.input.classList.add("error"),Object(k.a)(a.label,Object(x.i18n)("TwoStepAuth.RecoveryCodeExpired"));break;default:console.error("confirm error",e)}d(!1)})}}),o=Object(U.a)("btn-primary btn-primary-transparent primary",{text:"TwoStepAuth.EmailCodeChangeEmail"}),r=Object(U.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"ResendCode"}),c=()=>{new li(this.slider).open()},d=e=>{Object(bt.a)([a.input,o,r],e)};Object(l.b)(o,e=>{d(!0),ri.a.cancelPasswordEmail().then(e=>{this.slider.sliceTabsUntilTab(pi,this),this.close()},()=>{d(!1)})}),Object(l.b)(r,e=>{d(!0);const t=Object(te.f)(r);ri.a.resendPasswordEmail().then(e=>{t.remove(),d(!1)})}),n.append(a.container,o,r),i.append(n),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){di(this.isFirst)&&this.codeInputField.input.focus()}}class pi extends z{constructor(){super(...arguments),this.isFirst=!1}init(){this.container.classList.add("two-step-verification","two-step-verification-email"),this.setTitle("RecoveryEmailTitle");const e=new dn({caption:!0,noDelimiter:!0}),t=us.getAnimatedEmojiSticker("💌"),s=document.createElement("div");t?Cs({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 _.b({name:"recovery-email",label:"RecoveryEmail",plainText:!0});a.input.addEventListener("keypress",e=>{if("Enter"===e.key)return Object(c.a)(e),h()}),a.input.addEventListener("input",e=>{a.input.classList.remove("error")});const o=Object(U.a)("btn-primary btn-color-primary",{text:"Continue"}),r=Object(U.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),d=()=>{new li(this.slider).open()},h=()=>{const e=a.value.trim(),t=J.b.matchEmail(e);if(!t||t[0].length!==e.length)return void a.input.classList.add("error");p(!0);const s=Object(te.f)(o);ri.a.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:e}).then(e=>{d()},t=>{if(t.type.includes("EMAIL_UNCONFIRMED")){const s=+t.type.match(/^EMAIL_UNCONFIRMED_(\d+)/)[1],i=new hi(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()})};Object(l.b)(o,h);const p=e=>{e?(o.setAttribute("disabled","true"),r.setAttribute("disabled","true")):(o.removeAttribute("disabled"),r.removeAttribute("disabled"))};Object(l.b)(r,e=>{new gt("popup-skip-email",{buttons:[{langKey:"Cancel",isCancel:!0},{langKey:"YourEmailSkip",callback:()=>{p(!0),Object(te.f)(r),ri.a.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:""}).then(()=>{d()},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(){di(this.isFirst)&&this.inputField.input.focus()}}var ui=s(101),mi=s(95),gi=s(112);class bi extends z{init(){this.container.classList.add("two-step-verification","two-step-verification-hint"),this.setTitle("TwoStepAuth.SetupHintTitle");const e=new dn({noDelimiter:!0}),t=us.getAnimatedEmojiSticker("💡"),s=document.createElement("div");t?Cs({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 _.b({name:"hint",label:"TwoStepAuth.SetupHintPlaceholder"});n.input.addEventListener("keypress",e=>{if("Enter"===e.key)return Object(c.a)(e),n.value?d():h()});const a=(e,t)=>{e&&Object(c.a)(e);const s=t?n.value:void 0;if(s&&this.newPassword===s)return void lt(x.default.format("PasswordAsHintError",!0));const i=new pi(this.slider);i.state=this.state,i.plainPassword=this.plainPassword,i.newPassword=this.newPassword,i.hint=s,i.open()},o=Object(U.a)("btn-primary btn-color-primary",{text:"Continue"}),r=Object(U.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),d=e=>a(e,!0),h=e=>a(e,!1);Object(l.b)(o,d),Object(l.b)(r,h),i.append(n.container,o,r),e.content.append(i),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){this.inputField.input.focus()}}class vi extends z{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 dn({noDelimiter:!0}),t=document.createElement("div");t.classList.add("input-wrapper");const s=this.passwordInputField=new mi.a({name:"re-enter-password",label:"PleaseReEnterPassword"}),i=new gi.a(s,157),n=Object(U.a)("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(_.a.Neutral),"Enter"===e.key)return o()});const a=()=>this.newPassword===s.value||(s.setError(),!1),o=e=>{if(e&&Object(c.a)(e),!a())return;const t=new bi(this.slider);t.state=this.state,t.plainPassword=this.plainPassword,t.newPassword=this.newPassword,t.open()};return Object(l.b)(n,o),i.load()}onOpenAfterTimeout(){this.passwordInputField.input.focus()}}class fi extends z{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 dn({noDelimiter:!0}),s=document.createElement("div");s.classList.add("input-wrapper");const i=this.passwordInputField=new mi.a({name:"enter-password",label:e?"PleaseEnterFirstPassword":this.state.hint?void 0:"LoginPassword",labelText:!e&&this.state.hint?J.b.wrapEmojiText(this.state.hint):void 0}),n=new ui.a(i,157),a=Object(U.a)("btn-primary btn-color-primary"),o=new x.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 d()});const r=()=>!!i.value.length||(i.input.classList.add("error"),!1);let d;if(e)d=e=>{if(e&&Object(c.a)(e),!r())return;const t=new vi(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)),ri.a.getState().then(e=>{this.state=e,this.state.hint?i.label.innerHTML=J.b.wrapEmojiText(this.state.hint):Object(k.a)(i.label,Object(x.i18n)("LoginPassword"))}));d=s=>{if(!r())return void Object(c.a)(s);a.setAttribute("disabled","true"),o.key="PleaseWait",o.update();const l=Object(te.f)(a),d=i.value;ri.a.check(i.value,this.state).then(t=>{if(console.log(t),"auth.authorization"===t._){clearInterval(e),n&&n.remove();const t=new yi(this.slider);t.state=this.state,t.plainPassword=d,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 Object(l.b)(a,d),n.load()}onOpenAfterTimeout(){di(this.isFirst)&&this.passwordInputField.input.focus()}}class yi extends z{init(){this.container.classList.add("two-step-verification","two-step-verification-main"),this.setTitle("TwoStepVerificationTitle");const e=new dn({caption:!0,noDelimiter:!0}),t=us.getAnimatedEmojiSticker("🔐"),s=document.createElement("div");t?Cs({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){Object(x._i18n)(e.caption,"TwoStepAuth.GenericHelp");const t=Object(U.a)("btn-primary btn-transparent",{icon:"edit",text:"TwoStepAuth.ChangePassword"}),s=Object(U.a)("btn-primary btn-transparent",{icon:"passwordoff",text:"TwoStepAuth.RemovePassword"}),n=Object(U.a)("btn-primary btn-transparent",{icon:"email",text:this.state.pFlags.has_recovery?"TwoStepAuth.ChangeEmail":"TwoStepAuth.SetupEmail"});Object(l.b)(t,()=>{const e=new fi(this.slider);e.state=this.state,e.plainPassword=this.plainPassword,e.open()}),Object(l.b)(s,()=>{new gt("popup-disable-password",{buttons:[{langKey:"Disable",callback:()=>{ri.a.updateSettings({currentPassword:this.plainPassword}).then(()=>{this.slider.sliceTabsUntilTab(tn,this),this.close()})},isDanger:!0}],titleLangKey:"TurnPasswordOffQuestionTitle",descriptionLangKey:"TurnPasswordOffQuestion"}).show()}),Object(l.b)(n,()=>{const e=new pi(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{Object(x._i18n)(e.caption,"TwoStepAuth.SetPasswordHelp");const t=document.createElement("div");t.classList.add("input-wrapper");const s=Object(U.a)("btn-primary btn-color-primary",{text:"TwoStepVerificationSetPassword"});t.append(s),i.append(t),Object(l.b)(s,e=>{const t=new fi(this.slider);t.state=this.state,t.open()})}this.scrollable.container.append(e.container)}}class wi extends V{init(){this.container.classList.add("privacy-tab","privacy-last-seen"),this.setTitle("PrivacyLastSeen");const e="PrivacySettingsController.LastSeenDescription";new ai({tab:this,title:"LastSeenTitle",inputKey:"inputPrivacyKeyStatusTimestamp",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable})}}class Si extends V{init(){this.container.classList.add("privacy-tab","privacy-profile-photo"),this.setTitle("PrivacyProfilePhoto");const e="PrivacySettingsController.ProfilePhoto.CustomHelp";new ai({tab:this,title:"PrivacyProfilePhotoTitle",inputKey:"inputPrivacyKeyProfilePhoto",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,skipTypes:[ti.Nobody]})}}class Li extends V{init(){this.container.classList.add("privacy-tab","privacy-forward-messages"),this.setTitle("PrivacySettings.Forwards");const e="PrivacySettingsController.Forwards.CustomHelp";new ai({tab:this,title:"PrivacyForwardsTitle",inputKey:"inputPrivacyKeyForwards",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable})}}class Ei extends V{init(){this.container.classList.add("privacy-tab","privacy-add-to-groups"),this.setTitle("PrivacySettings.Groups");const e="PrivacySettingsController.GroupDescription";new ai({tab:this,title:"WhoCanAddMe",inputKey:"inputPrivacyKeyChatInvite",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,skipTypes:[ti.Nobody]})}}class Ci extends V{init(){this.container.classList.add("privacy-tab","privacy-calls"),this.setTitle("PrivacySettings.VoiceCalls");const e="PrivacySettingsController.PhoneCallDescription";new ai({tab:this,title:"WhoCanCallMe",inputKey:"inputPrivacyKeyPhoneCall",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable});{const e="PrivacySettingsController.P2p.Desc";new ai({tab:this,title:"PrivacyP2PHeader",inputKey:"inputPrivacyKeyPhoneP2P",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable})}}}class Ii extends z{init(){this.container.classList.add("active-sessions-container"),this.setTitle("SessionsTitle");const e=e=>{const t=new st({title:[e.app_name,e.app_version].join(" "),subtitle:[e.ip,e.country].join(" - "),clickable:!0,titleRight:e.pFlags.current?void 0:Object(oe.c)(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 dn({name:"CurrentSession"}),a=t.findAndSplice(e=>e.pFlags.current),o=e(a);if(n.content.append(o.container),t.length){const e=Object(U.a)("btn-primary btn-transparent danger",{icon:"stop",text:"TerminateAllSessions"});Object(l.b)(e,t=>{new gt("revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{const t=Object(bt.a)([e],!0);ht.a.invokeApi("auth.resetAuthorizations").then(t=>{e.remove(),s.container.remove(),this.privacyTab.updateActiveSessions()},i).finally(()=>{t()})}}],titleLangKey:"AreYouSureSessionsTitle",descriptionLangKey:"AreYouSureSessions"}).show()}),n.content.append(e)}this.scrollable.append(n.container)}if(!t.length)return;const s=new dn({name:"OtherSessions"});t.forEach(t=>{s.content.append(e(t).container)}),this.scrollable.append(s.container);const i=e=>{"FRESH_RESET_AUTHORISATION_FORBIDDEN"===e.type&&lt(x.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:()=>{ht.a.invokeApi("account.resetAuthorization",{hash:e}).then(e=>{e&&(n.remove(),this.privacyTab.updateActiveSessions())},i)}}],titleLangKey:"AreYouSureSessionTitle",descriptionLangKey:"TerminateSessionText"}).show()},o=this.menuElement=Ee([{icon:"stop",text:"Terminate",onClick:a}]);o.id="active-sessions-contextmenu",o.classList.add("contextmenu"),document.getElementById("page-chats").append(o),Object(te.a)(this.scrollable.container,e=>{n=Object(Me.a)(e.target,"row"),n&&"0"!==n.dataset.hash&&(e instanceof MouseEvent&&e.preventDefault(),e instanceof MouseEvent&&(e.cancelBubble=!0),Object(te.e)(e,o),Object(te.d)(o))}),Object(l.b)(this.scrollable.container,e=>{n=Object(Me.a)(e.target,"row"),n&&"0"!==n.dataset.hash&&a()})}onCloseAfterTimeout(){return this.menuElement&&this.menuElement.remove(),super.onCloseAfterTimeout()}}class Mi extends z{init(){this.container.classList.add("blocked-users-container"),this.setTitle("BlockedUsers");{const e=new dn({caption:"BlockedUsersInfo"});this.scrollable.append(e.container)}const e=Q({icon:"add",className:"is-visible"});this.content.append(e),Object(l.b)(e,e=>{new Pt({peerTypes:["contacts"],placeholder:"BlockModal.Search.Placeholder",onSelect:e=>{P.a.toggleBlock(e,!0)}})},{listenerSetter:this.listenerSetter});const t=kr.createChatList();this.scrollable.container.classList.add("chatlist-container"),this.scrollable.append(t);const s=(e,s)=>{const{dom:i}=kr.addDialogNew({dialog:e,container:t,drawStatus:!1,rippleEnabled:!0,avatarSize:48,append:s}),n=P.a.getUser(e);n.pFlags.bot?i.lastMessageSpan.append("@"+n.username):n.phone?i.lastMessageSpan.innerHTML=P.a.formatUserPhone(n.phone):i.lastMessageSpan.append(n.username?"@"+n.username:P.a.getUserStatusString(e))};for(const e of this.peerIds)s(e,!0);let i;const n=this.menuElement=Ee([{icon:"lockoff",text:"Unblock",onClick:()=>{const e=i.dataset.peerId.toPeerId();P.a.toggleBlock(e,!1)},options:{listenerSetter:this.listenerSetter}}]);n.id="blocked-users-contextmenu",n.classList.add("contextmenu"),document.getElementById("page-chats").append(n),Object(te.a)(this.scrollable.container,e=>{i=Object(ft.a)(e.target,"LI"),i&&(e instanceof MouseEvent&&e.preventDefault(),e instanceof MouseEvent&&(e.cancelBubble=!0),Object(te.e)(e,n),Object(te.d)(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,P.a.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 Pi=s(116);class Ti extends V{init(){this.container.classList.add("dont-u-dare-block-me"),this.setTitle("PrivacySettings");{const e=new dn({noDelimiter:!0});let t;const s=new st({icon:"deleteuser",titleLangKey:"BlockedUsers",subtitleLangKey:"Loading",clickable:()=>{const e=new Mi(this.slider);e.peerIds=t,e.open()}});let i;s.freezed=!0;const n=new st({icon:"lock",titleLangKey:"TwoStepVerification",subtitleLangKey:"Loading",clickable:e=>{let t;i.pFlags.has_password?t=new fi(this.slider):i.email_unconfirmed_pattern?(t=new hi(this.slider),t.email=i.email_unconfirmed_pattern,t.length=6,t.isFirst=!0,ri.a.resendPasswordEmail()):t=new yi(this.slider),t.state=i,t.open()}});n.freezed=!0;const o=this.activeSessionsRow=new st({icon:"activesessions",titleLangKey:"SessionsTitle",subtitleLangKey:"Loading",clickable:()=>{const e=new Ii(this.slider);e.privacyTab=this,e.authorizations=this.authorizations,e.open()}});o.freezed=!0,e.content.append(s.container,n.container,o.container),this.scrollable.append(e.container);const r=e=>{e?Object(k.a)(s.subtitle,Object(x.i18n)("PrivacySettingsController.UserCount",[e])):Object(k.a)(s.subtitle,Object(x.i18n)("BlockedEmpty",[e]))};this.listenerSetter.add(a.default)("peer_block",()=>{l()});const l=()=>{P.a.getBlocked().then(e=>{s.freezed=!1,r(e.count),t=e.peerIds})};l(),ri.a.getState().then(e=>{i=e,Object(k.a)(n.subtitle,Object(x.i18n)(e.pFlags.has_password?"PrivacyAndSecurity.Item.On":"PrivacyAndSecurity.Item.Off")),n.freezed=!1}),this.updateActiveSessions()}{const e=new dn({name:"PrivacyTitle"});e.content.classList.add("privacy-navigation-container");const t={},s=t.inputPrivacyKeyPhoneNumber=new st({titleLangKey:"PrivacyPhoneTitle",subtitleLangKey:"Loading",clickable:()=>{new oi(this.slider).open()}}),i=t.inputPrivacyKeyStatusTimestamp=new st({titleLangKey:"LastSeenTitle",subtitleLangKey:"Loading",clickable:()=>{new wi(this.slider).open()}}),n=t.inputPrivacyKeyProfilePhoto=new st({titleLangKey:"PrivacyProfilePhotoTitle",subtitleLangKey:"Loading",clickable:()=>{new Si(this.slider).open()}}),o=t.inputPrivacyKeyPhoneCall=new st({titleLangKey:"WhoCanCallMe",subtitleLangKey:"Loading",clickable:()=>{new Ci(this.slider).open()}}),r=t.inputPrivacyKeyForwards=new st({titleLangKey:"PrivacyForwardsTitle",subtitleLangKey:"Loading",clickable:()=>{new Li(this.slider).open()}}),l=t.inputPrivacyKeyChatInvite=new st({titleLangKey:"WhoCanAddMe",subtitleLangKey:"Loading",clickable:()=>{new Ei(this.slider).open()}}),c=e=>{const s=t[e];s&&ni.getPrivacy(e).then(e=>{const t=ni.getPrivacyRulesDetails(e),i=t.type===ti.Everybody?"PrivacySettingsController.Everbody":t.type===ti.Contacts?"PrivacySettingsController.MyContacts":"PrivacySettingsController.Nobody",n=t.disallowPeers.users.length+t.disallowPeers.chats.length,a=t.allowPeers.users.length+t.allowPeers.chats.length;s.subtitle.innerHTML="";const o=Object(x.i18n)(i);s.subtitle.append(o),(n||a)&&s.subtitle.append(` (${[-n,a?"+"+a:0].filter(Boolean).join(", ")})`)})};e.content.append(s.container,i.container,n.container,o.container,r.container,l.container),this.scrollable.append(e.container);for(const e in t)c(e);a.default.addEventListener("privacy_update",e=>{c(Object(Y.c)(e.key._))})}const e=[];{const t=new dn({name:"Privacy.SensitiveContent"});t.container.classList.add("hide"),e.push(ht.a.invokeApi("account.getContentSettings").then(e=>{if(!e.pFlags.sensitive_can_change)return;const s=e.pFlags.sensitive_enabled,i=new st({checkboxField:new mt.a({text:"PrivacyAndSecurity.SensitiveText",checked:s}),subtitleLangKey:"PrivacyAndSecurity.SensitiveDesc",noCheckboxSubtitle:!0});t.content.append(i.container),t.container.classList.remove("hide"),this.eventListener.addEventListener("destroy",()=>{const e=i.checkboxField.checked;e!==s&&ht.a.invokeApi("account.setContentSettings",{sensitive_enabled:e})},{once:!0})})),this.scrollable.append(t.container)}{const e=new dn({name:"FilterChats"}),t=()=>{new gt("popup-delete-drafts",{buttons:[{langKey:"Delete",callback:()=>{const e=Object(bt.a)([s],!0);Pi.a.clearAllDrafts().then(()=>{e()})},isDanger:!0}],titleLangKey:"AreYouSureClearDraftsTitle",descriptionLangKey:"AreYouSureClearDrafts"}).show()},s=Object(U.a)("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(e)}updateActiveSessions(){ht.a.invokeApi("account.getAuthorizations").then(e=>{this.activeSessionsRow.freezed=!1,this.authorizations=e.authorizations,Object(x._i18n)(this.activeSessionsRow.subtitle,"Privacy.Devices",[this.authorizations.length])})}}function ki(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 xi(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 Oi(e){const t=[];if(4===e.length)for(let s=1;s<e.length;++s)t.push(parseInt(e[s]+e[s],16));else if(5===e.length){for(let s=1;s<e.length-1;++s)t.push(parseInt(e[s]+e[s],16));t.push(parseInt(e[e.length-1],16))}else for(let s=1;s<e.length;s+=2)t.push(parseInt(e.slice(s,s+2),16));return t}function Ai(e){return"#"+e.map(e=>("0"+e.toString(16)).slice(-2)).join("")}function _i(e){return Ai(function(e){const t=e.slice(5,-1).split(", "),s=+t.pop(),i=t.map(e=>e.endsWith("%")?+e.slice(0,-1):+e);return xi(i[0],i[1],i[2],s)}(e))}function Fi(e){let{h:t,s:s,l:i}=ki(e[0],e[1],e[2]);s>0&&(s=Math.min(100,s+5+.1*(100-s))),i=Math.max(0,.65*i);return`hsla(${t}, ${s}%, ${i}%, .4)`}var Di=s(105);class ji{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(ji.BASE_CLASS);const e=`\n <svg class="${ji.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="${ji.BASE_CLASS+"-dragger"} ${ji.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="${ji.BASE_CLASS+"-sliders"}">\n <svg class="${ji.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="${ji.BASE_CLASS+"-dragger"} ${ji.BASE_CLASS+"-color-slider-dragger"}" x="0" y="13">\n <circle r="11" fill="inherit" stroke="#fff" stroke-width="2"></circle>\n </svg>\n </svg>\n </div>\n `;this.container.innerHTML=e,this.elements.box=this.container.firstElementChild,this.elements.boxDragger=this.elements.box.lastElementChild,this.elements.saturation=this.elements.box.firstElementChild.firstElementChild,this.elements.sliders=this.elements.box.nextElementSibling,this.elements.hue=this.elements.sliders.firstElementChild,this.elements.hueDragger=this.elements.hue.lastElementChild,this.hexInputField=new _.b({plainText:!0,label:"Appearance.Color.Hex"}),this.rgbInputField=new _.b({plainText:!0,label:"Appearance.Color.RGB"});const t=document.createElement("div");t.className=ji.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?_.a.Neutral:_.a.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?_.a.Neutral:_.a.Error),e&&this.setColor(ki(+e[1],+e[2],+e[3]),!0,!1)}),this.attachBoxListeners(),this.attachHueListeners()}attachBoxListeners(){we(this.elements.box,()=>{this.onGrabStart(),this.boxRect=this.elements.box.getBoundingClientRect()},e=>{this.saturationHandler(e.x,e.y)},()=>{this.onGrabEnd()})}attachHueListeners(){we(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=Oi(e);return ki(t[0],t[1],t[2],t[3])}(e);else{const t=e.match(/[.?\d]+/g);e=ki(+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=xi(this.hue,this.saturation,this.lightness,this.alpha),t=Ai(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(_.a.Neutral)),t&&(this.rgbInputField.setValueSilently(s.rgbaArray.slice(0,-1).join(", ")),this.rgbInputField.setState(_.a.Neutral)),this.onChange&&this.onChange(s)}hueHandler(e,t=!0){const s=Object(I.a)(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=Object(I.a)(e-this.boxRect.left,0,i)/i*100,o=Object(I.a)(t-this.boxRect.top,0,n)/n*100,r=this.elements.boxDragger;r.setAttributeNS(null,"x",a+"%"),r.setAttributeNS(null,"y",o+"%");const l=Object(I.a)(a,0,100),c=100-l/2,d=100-Object(I.a)(o,0,100),h=Object(I.a)(d/100*c,0,100);this.saturation=l,this.lightness=h,s&&this.updatePicker()}}ji.BASE_CLASS="color-picker";class Bi extends z{constructor(){super(...arguments),this._applyColor=(e,t=!0)=>{if(t)this.colorPicker.setColor(e);else{const t=Oi(e),s=this.theme.background,i=Fi(t);s.color=e.toLowerCase(),s.type="color",s.highlightningColor=i,M.default.pushToState("settings",a.default.settings),er.applyCurrentTheme(void 0,void 0,!0),this.setActive()}},this.onColorChange=e=>{this.applyColor(e.hex,!1)}}init(){this.container.classList.add("background-container","background-color-container"),this.setTitle("SetColor"),this.theme=a.default.getTheme();const e=new dn({});this.colorPicker=new ji,e.content.append(this.colorPicker.container),this.scrollable.append(e.container);const t=this.grid=document.createElement("div");t.classList.add("grid");["#E6EBEE","#B2CEE1","#008DD0","#C6E7CB","#C4E1A6","#60B16E","#CCD0AF","#A6A997","#7A7072","#FDD7AF","#FDB76E","#DD8851"].forEach(e=>{const s=document.createElement("div");s.classList.add("grid-item"),s.dataset.color=e.toLowerCase();const i=document.createElement("div");i.classList.add("grid-item-media"),i.style.backgroundColor=e,s.append(i),t.append(s)}),Object(l.b)(t,e=>{const t=Object(Me.a)(e.target,"grid-item");if(!t||t.classList.contains("active"))return;const s=t.dataset.color;s&&this.applyColor(s)},{listenerSetter:this.listenerSetter}),this.scrollable.append(t),this.applyColor=Object(Di.a)(this._applyColor,16,!0)}setActive(){const e=this.grid.querySelector(".active"),t=this.theme.background,s="color"===t.type?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;"color"===e.type&&(this.colorPicker.onChange=this.onColorChange),this.colorPicker.setColor(e.color||"#cccccc"),"color"!==e.type&&(this.colorPicker.onChange=this.onColorChange)},0)}onCloseAfterTimeout(){return this.colorPicker.onChange=void 0,this.colorPicker=void 0,super.onCloseAfterTimeout()}}let Ri=0;class Ui extends z{constructor(){super(...arguments),this.tempId=0,this.clicked=new Set,this.onUploadClick=()=>{Object(me.f)("image/x-png,image/png,image/jpeg").then(e=>{const t="wallpaper-upload-"+ ++Ri,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=E.a.saveDoc(i);const n=he.a.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=he.a.upload(e,e.name),r=Object(ae.a)();r.addNotifyListener=o.addNotifyListener,r.cancel=o.cancel,o.then(t=>{ht.a.invokeApi("account.uploadWallPaper",{file:t,mime_type:e.type,settings:{_:"wallPaperSettings"}}).then(e=>{const t=e.document,s=he.a.getCacheContext(t);Object.assign(s,n),a=e,a.document=E.a.saveDoc(a.document),c.dataset.docId=""+a.document.id,c.dataset.slug=a.slug,this.setBackgroundDocument(a.slug,a.document).then(r.resolve,r.reject)},r.reject)},r.reject),r.then(()=>{this.clicked.delete(a.document.id)},e=>{c.remove()});const l=new ye.a({isUpload:!0,cancelable:!0,tryAgainOnFail:!1}),c=this.addWallPaper(a,!1);this.clicked.add(a.document.id),l.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=Object(w.a)(e.background),M.default.pushToState("settings",a.default.settings),er.applyCurrentTheme(void 0,void 0,!0),this.blurCheckboxField.setValueSilently(this.theme.background.blur))},this.onGridClick=e=>{const t=Object(Me.a)(e.target,"grid-item");if(!t)return;const{docId:s,slug:i}=t.dataset;if(this.clicked.has(s))return;this.clicked.add(s);const n=new ye.a({cancelable:!0,tryAgainOnFail:!1}),a=E.a.getDoc(s),o=()=>{const e=this.setBackgroundDocument(i,a);he.a.getCacheContext(a).url&&!this.theme.background.blur||n.attach(t,!0,e)};n.construct(),Object(l.b)(t,e=>{n.preloader.parentElement?(n.onClick(e),n.detach()):o()},{listenerSetter:this.listenerSetter}),o()},this.saveToCache=(e,t)=>{fetch(t).then(t=>{he.a.cacheStorage.save("backgrounds/"+e,t)})},this.setBackgroundDocument=(e,t)=>{let s=++this.tempId;const i=()=>s===this.tempId,n=E.a.downloadDoc(t,er.chat.bubbles?er.chat.bubbles.lazyLoadQueue.queueId:0),o=Object(ae.a)();return o.addNotifyListener=n.addNotifyListener,o.cancel=n.cancel,n.then(()=>{if(!i())return void o.resolve();const s=this.theme.background,n=t=>{(e=>{const t=document.createElement("img");return new Promise(s=>{Object(rs.a)(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;const n=e.getContext("2d");n.drawImage(t,0,0,t.naturalWidth,t.naturalHeight,0,0,e.width,e.height);const a=new Array(4).fill(0),o=n.getImageData(0,0,e.width,e.height).data;for(let e=0;e<o.length;e+=4)a[0]+=o[e],a[1]+=o[e+1],a[2]+=o[e+2],a[3]+=o[e+3];const r=o.length/4,l=new Uint8ClampedArray(4);l[0]=a[0]/r,l[1]=a[1]/r,l[2]=a[2]/r,l[3]=a[3]/r,s(l)})})})(t).then(n=>{if(!i())return void o.resolve();const r=Fi(Array.from(n));s.slug=e,s.type="image",s.highlightningColor=r,M.default.pushToState("settings",a.default.settings),this.saveToCache(e,t),er.applyCurrentTheme(e,t).then(o.resolve)})},r=he.a.getCacheContext(t);s.blur?setTimeout(()=>{Object(bs.a)(r.url,12,4).then(e=>{i()?n(e):o.resolve()})},200):n(r.url)}),o},this.setActive=()=>{const e=this.grid.querySelector(".active"),t=this.theme.background,s="image"===t.type?this.grid.querySelector(`.grid-item[data-slug="${t.slug}"]`):null;e!==s&&(e&&e.classList.remove("active"),s&&s.classList.add("active"))}}init(){this.container.classList.add("background-container","background-image-container"),this.setTitle("ChatBackground"),this.theme=a.default.getTheme();{const t=hn(this.scrollable),s=Object(U.a)("btn-primary btn-transparent",{icon:"cameraadd",text:"ChatBackground.UploadWallpaper"}),i=Object(U.a)("btn-primary btn-transparent",{icon:"colorize",text:"SetColor"}),n=Object(U.a)("btn-primary btn-transparent",{icon:"favourites",text:"Appearance.Reset"});Object(l.b)(s,this.onUploadClick,{listenerSetter:this.listenerSetter}),Object(l.b)(i,()=>{new Bi(this.slider).open()},{listenerSetter:this.listenerSetter}),Object(l.b)(n,this.onResetClick,{listenerSetter:this.listenerSetter});const o=this.blurCheckboxField=new mt.a({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);const t=e.querySelector(".active");t&&setTimeout(()=>{this.setBackgroundDocument(t.dataset.slug,E.a.getDoc(t.dataset.docId))},100)}),t.append(s,i,n,o.label)}a.default.addEventListener("background_change",this.setActive),ht.a.invokeApiHashable("account.getWallPapers").then(e=>{e.wallpapers.forEach(e=>{this.addWallPaper(e)})});const e=this.grid=document.createElement("div");e.classList.add("grid"),Object(l.b)(e,this.onGridClick,{listenerSetter:this.listenerSetter}),this.scrollable.append(e)}addWallPaper(e,t=!0){if(e.pFlags.pattern||!e.document||0===e.document.mime_type.indexOf("application/"))return;e.document=E.a.saveDoc(e.document);const s=document.createElement("div");s.classList.add("grid-item");const i=document.createElement("div");i.classList.add("grid-item-media");const n=Ls({photo:e.document,message:null,container:i,withoutPreloader:!0,size:r.a.choosePhotoSize(e.document,200,200)});return s.dataset.docId=""+e.document.id,s.dataset.slug=e.slug,"image"===this.theme.background.type&&this.theme.background.slug===e.slug&&s.classList.add("active"),(n.loadPromises.thumb||n.loadPromises.full).then(()=>{ls.a.mutate(()=>{s.append(i)})}),this.grid[t?"append":"prepend"](s),s}}var Hi=s(109);class Ni extends ut.b{constructor(e){super("popup-stickers",null,{closable:!0,overlayClosable:!0,body:!0}),this.stickerSetInput=e,this.onStickersClick=e=>{const t=Object(Me.a)(e.target,"sticker-set-sticker");if(!t)return;const s=t.dataset.docId;er.chat.input.sendMessageWithDocument(s)?this.hide():console.warn("got no doc by id:",s)},this.h6=document.createElement("h6"),this.h6.append(Object(x.i18n)("Loading")),this.header.append(this.h6),this.addEventListener("close",()=>{C.a.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"),Object(l.b)(this.stickersDiv,this.onStickersClick,{listenerSetter:this.listenerSetter}),Object(te.f)(this.stickersDiv,!0),this.stickersFooter=document.createElement("div"),this.stickersFooter.classList.add("sticker-set-footer"),t.append(this.stickersDiv);const s=Object(U.a)("btn-primary btn-primary-transparent disable-hover",{noRipple:!0,text:"Loading"});this.stickersFooter.append(s),this.body.append(t);new T.b(this.body);this.body.append(this.stickersFooter),this.loadStickerSet()}loadStickerSet(){return us.getStickerSet(this.stickerSetInput).then(e=>{let t;this.set=e.set,C.a.setOnlyOnePlayableGroup("STICKERS-POPUP"),this.h6.innerHTML=J.a.wrapEmojiText(e.set.title),this.stickersFooter.classList.toggle("add",!e.set.installed_date),e.set.installed_date?(t=Object(U.a)("btn-primary btn-primary-transparent danger",{noRipple:!0}),t.append(Object(x.i18n)("RemoveStickersCount",[Object(x.i18n)("Stickers",[e.set.count])]))):(t=Object(U.a)("btn-primary btn-color-primary",{noRipple:!0}),t.append(Object(x.i18n)("AddStickersCount",[Object(x.i18n)("Stickers",[e.set.count])]))),this.stickersFooter.textContent="",this.stickersFooter.append(t),Object(l.b)(t,()=>{const e=Object(bt.a)([t],!0);us.toggleStickerSet(this.set).then(()=>{this.hide()}).catch(()=>{e()})});const s=new ee.d;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=b.b.active.esgSticker.width;Cs({doc:t,div:e,lazyLoadQueue:s,group:"STICKERS-POPUP",play:!0,loop:!0,width:i,height:i}),this.stickersDiv.append(e)}})}}var zi=s(2);class Vi{constructor(e,t,s,i,n){const a="range-setting-selector";this.container=document.createElement("div"),this.container.classList.add(a);const o=document.createElement("div");o.classList.add(a+"-details");const r=document.createElement("div");r.classList.add(a+"-name"),Object(x._i18n)(r,e);const l=document.createElement("div");l.classList.add(a+"-value"),l.innerHTML=""+s,o.append(r,l),this.range=new Se({step:t,min:i,max:n},s),this.range.setListeners(),this.range.setHandlers({onScrub:e=>{this.onChange&&this.onChange(e),l.innerText=""+e}}),this.container.append(o,this.range.container)}}class Gi extends V{init(){this.container.classList.add("general-settings-container"),this.setTitle("General");const e=hn.bind(null,this.scrollable);{const t=e("Settings"),s=new Vi("TextSize",1,a.default.settings.messagesTextSize,12,20);s.onChange=e=>{M.default.setByKey("settings.messagesTextSize",e)};const i=Object(U.a)("btn-primary btn-transparent",{icon:"image",text:"ChatBackground"});Object(l.b)(i,()=>{new Ui(this.slider).open()});const n=new mt.a({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 st({radioField:new ot({langKey:"General.SendShortcut.Enter",name:i,value:"enter",stateKey:n}),subtitleLangKey:"General.SendShortcut.NewLine.ShiftEnter"}),o=new st({radioField:new ot({name:i,value:"ctrlEnter",stateKey:n}),subtitleLangKey:"General.SendShortcut.NewLine.Enter"});Object(x._i18n)(o.radioField.main,"General.SendShortcut.CtrlEnter",[re.IS_APPLE?"⌘":"Ctrl"]),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 st({radioField:new ot({langKey:t,name:i,value:e,stateKey:n})})),r=function(e,t=!0){const s=e;let i;return t||(e=_e.a),function t(){e(),i=zi.a.setTimeout(t,1e3*(60-(new Date).getSeconds()))}(),e=s,()=>{clearTimeout(i)}}(()=>{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("AutoDownloadMedia"),s=new mt.a({text:"AutodownloadContacts",name:"contacts",stateKey:"settings.autoDownload.contacts",withRipple:!0}),i=new mt.a({text:"AutodownloadPrivateChats",name:"private",stateKey:"settings.autoDownload.private",withRipple:!0}),n=new mt.a({text:"AutodownloadGroupChats",name:"groups",stateKey:"settings.autoDownload.groups",withRipple:!0}),a=new mt.a({text:"AutodownloadChannels",name:"channels",stateKey:"settings.autoDownload.channels",withRipple:!0});t.append(s.label,i.label,n.label,a.label)}{const t=e("General.AutoplayMedia"),s=new mt.a({text:"AutoplayGIF",name:"gifs",stateKey:"settings.autoPlay.gifs",withRipple:!0}),i=new mt.a({text:"AutoplayVideo",name:"videos",stateKey:"settings.autoPlay.videos",withRipple:!0});t.append(s.label,i.label)}{const t=e("Emoji"),s=new mt.a({text:"GeneralSettings.EmojiPrediction",name:"suggest-emoji",stateKey:"settings.emoji.suggest",withRipple:!0}),i=new mt.a({text:"GeneralSettings.BigEmoji",name:"emoji-big",stateKey:"settings.emoji.big",withRipple:!0});t.append(s.label,i.label)}{const t=e("Telegram.InstalledStickerPacksController"),s=new mt.a({text:"Stickers.SuggestStickers",name:"suggest",stateKey:"settings.stickers.suggest",withRipple:!0}),i=new mt.a({text:"InstalledStickers.LoopAnimated",name:"loop",stateKey:"settings.stickers.loop",withRipple:!0}),n={},o=new ee.d,r=(e,s="append")=>{const i=new st({title:J.b.wrapEmojiText(e.title),subtitleLangKey:"Stickers",subtitleLangArgs:[e.count],havePadding:!0,clickable:()=>{new Ni({id:e.id,access_hash:e.access_hash}).show()}});n[e.id]=i;const a=document.createElement("div");a.classList.add("row-media"),Is({set:e,container:a,group:"GENERAL-SETTINGS",lazyLoadQueue:o,width:48,height:48,autoplay:!0}),i.container.append(a),t[s](i.container)};us.getAllStickers().then(e=>{Object(Hi.a)(e);for(const t of e.sets)r(t)}),this.listenerSetter.add(a.default)("stickers_installed",e=>{const t=e;n[t.id]||r(t,"prepend")}),this.listenerSetter.add(a.default)("stickers_deleted",e=>{const t=e;n[t.id]&&(n[t.id].container.remove(),delete n[t.id])}),t.append(s.label,i.label)}}onOpen(){this.init&&(this.init(),this.init=null)}}var Ki=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 Wi extends z{init(){return Ki(this,void 0,void 0,(function*(){this.container.classList.add("edit-profile-container"),this.setTitle("EditAccount.Title");const e=[];{const t=document.createElement("div");t.classList.add("input-wrapper"),this.firstNameInputField=new _.b({label:"EditProfile.FirstNameLabel",name:"first-name",maxLength:70}),this.lastNameInputField=new _.b({label:"Login.Register.LastName.Placeholder",name:"last-name",maxLength:64}),this.bioInputField=new _.b({label:"EditProfile.BioLabel",name:"bio",maxLength:70}),t.append(this.firstNameInputField.container,this.lastNameInputField.container,this.bioInputField.container);const s=document.createElement("div");s.classList.add("caption"),Object(x.i18n_)({element:s,key:"Bio.Description"}),e.push(this.firstNameInputField,this.lastNameInputField,this.bioInputField),this.scrollable.append(t,s)}this.scrollable.append(document.createElement("hr")),this.editPeer=new et({peerId:a.default.myId,inputFields:e,listenerSetter:this.listenerSetter}),this.content.append(this.editPeer.nextBtn),this.scrollable.prepend(this.editPeer.avatarEdit.container);{const t=document.createElement("div");t.classList.add("sidebar-left-h2"),Object(x.i18n_)({element:t,key:"EditAccount.Username"});const s=document.createElement("div");s.classList.add("input-wrapper"),this.usernameInputField=new pt({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=document.createElement("div");i.classList.add("caption"),i.append(Object(x.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(Object(x.i18n)("UsernameHelpLink",[a])),i.append(n),e.push(this.usernameInputField),this.scrollable.append(t,s,i)}Object(l.b)(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(P.a.updateUsername(this.usernameInputField.value)),Promise.race(e).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter});const t=P.a.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()}))}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}}}var qi=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 Qi extends z{constructor(){super(...arguments),this.renderResults=e=>qi(this,void 0,void 0,(function*(){yield P.a.getContacts(),e.forEach(e=>{const{dom:t}=kr.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=J.b.wrapEmojiText(s.title),i.push(e)}});Object(x.join)(i,!1).forEach(e=>{t.lastMessageSpan.append(e)})})})),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=H("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),Object(f.d)(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";Object(f.d)(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.a.getInputPeerById(e)),this.editFolderTab.setFilter(this.filter,!1),this.close()}),this.dialogsByFilters=new Map,i.a.filtersStorage.getDialogFilters().then(e=>{for(const t of e)this.dialogsByFilters.set(t,new Set(i.a.dialogsStorage.getFolderDialogs(t.id).map(e=>e.peerId)))})}checkbox(e){const t=new mt.a({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=document.createDocumentFragment(),s=new dn({noDelimiter:!0,name:"FilterChatTypes"});let i;s.container.classList.add("folder-categories"),i="excluded"===this.type?{exclude_muted:{ico:"mute",text:"ChatList.Filter.MutedChats"},exclude_archived:{ico:"archive",text:"ChatList.Filter.Archive"},exclude_read:{ico:"readchats",text:"ChatList.Filter.ReadChats"}}:{contacts:{ico:"newprivate",text:"ChatList.Filter.Contacts"},non_contacts:{ico:"noncontacts",text:"ChatList.Filter.NonContacts"},groups:{ico:"group",text:"ChatList.Filter.Groups"},broadcasts:{ico:"newchannel",text:"ChatList.Filter.Channels"},bots:{ico:"bots",text:"ChatList.Filter.Bots"}};const n=document.createDocumentFragment();for(const e in i){const t=Object(U.a)("btn-primary btn-transparent folder-category-button",{icon:i[e].ico,text:i[e].text});t.dataset.peerId=e,t.append(this.checkbox()),n.append(t)}s.content.append(n);const a=new dn({name:"FilterChats"});t.append(s.container,a.container);const o=("included"===this.type?e.includePeerIds:e.excludePeerIds).slice();this.selector=new It({appendTo:this.container,onChange:this.onSelectChange,peerType:["dialogs"],renderResultsFunc:this.renderResults,placeholder:"Search"}),this.selector.selected=new Set(o);let r=!1;const l=this.selector.add.bind(this.selector);this.selector.add=(e,t,s)=>{if(this.selector.selected.size>=100&&r&&!i[e]){const t=this.selector.list.querySelector(`[data-peer-id="${e}"] [type="checkbox"]`);t&&setTimeout(()=>{t.checked=!1},0);return void lt(x.default.format("excluded"===this.type?"ChatList.Filter.Exclude.LimitReached":"ChatList.Filter.Include.LimitReached",!0))}const n=l(e,i[e]?Object(x.i18n)(i[e].text):void 0,s);return i[e]&&n.querySelector("avatar-element").classList.add("tgico-"+i[e].ico),n};const c=this.selector.list.parentElement;a.content.append(this.selector.list),c.append(t),this.selector.addInitial(o),r=!0;for(const t in e.pFlags)i.hasOwnProperty(t)&&e.pFlags[t]&&s.content.querySelector(`[data-peer-id="${t}"]`).click()}onCloseAfterTimeout(){return this.selector&&(this.selector.container.remove(),this.selector=null),super.onCloseAfterTimeout()}open(e,t,s){return this.originalFilter=e,this.filter=Object(w.a)(this.originalFilter),this.type=t,this.editFolderTab=s,super.open()}}class $i extends z{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(Object(x.i18n)("FilterIncludeExcludeInfo")),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container"),this.confirmBtn=H("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.a.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=document.createElement("div");t.classList.add("input-wrapper"),this.nameInputField=new _.b({label:"FilterNameInputLabel",maxLength:12}),t.append(this.nameInputField.container);const s=(e,t,s,i)=>{const n=new dn({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=Object(U.a)("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=s("folder-list-included","FilterInclude",[{icon:"add primary",text:"ChatList.Filter.Include.AddChat",withRipple:!0},{text:"ChatList.Filter.Contacts",icon:"newprivate",name:"contacts"},{text:"ChatList.Filter.NonContacts",icon:"noncontacts",name:"non_contacts"},{text:"ChatList.Filter.Groups",icon:"group",name:"groups"},{text:"ChatList.Filter.Channels",icon:"channel",name:"broadcasts"},{text:"ChatList.Filter.Bots",icon:"bots",name:"bots"}],this.flags),this.excludePeerIds=s("folder-list-excluded","FilterExclude",[{icon:"minus primary",text:"ChatList.Filter.Exclude.AddChat",withRipple:!0},{text:"ChatList.Filter.MutedChats",icon:"mute",name:"exclude_muted"},{text:"ChatList.Filter.Archive",icon:"archive",name:"exclude_archived"},{text:"ChatList.Filter.ReadChats",icon:"readchats",name:"exclude_read"}],this.flags),this.scrollable.append(this.stickerContainer,this.caption,t,this.includePeerIds.container,this.excludePeerIds.container);const n=this.includePeerIds.container.querySelector(".folder-categories"),a=this.excludePeerIds.container.querySelector(".folder-categories");return n.querySelector(".btn").addEventListener("click",()=>{new Qi(this.slider).open(this.filter,"included",this)}),a.querySelector(".btn").addEventListener("click",()=>{new Qi(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(n.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.a.filtersStorage.updateDialogFilter(this.filter):i.a.filtersStorage.createDialogFilter(this.filter),e.then(e=>{e&&this.close()}).catch(e=>{"DIALOG_FILTERS_TOO_MUCH"===e.type?lt("Sorry, you can't create more folders."):console.error("updateDialogFilter error:",e)}).finally(()=>{this.confirmBtn.removeAttribute("disabled")})):lt("Please choose at least one chat for this folder.")}),this.nameInputField.input.addEventListener("input",()=>{this.filter.title=this.nameInputField.value,this.editCheckForChange()}),this.loadAnimationPromise=le.a.loadAnimationAsAsset({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86},"Folders_2").then(e=>(this.animation=e,le.a.waitForFirstFrame(e)))}onOpenAfterTimeout(){this.loadAnimationPromise.then(()=>{this.animation.autoplay=!0,this.animation.play()})}onCreateOpen(){this.caption.style.display="",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.caption.style.display="none",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=J.b.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=kr.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}=kr.addDialogNew({dialog:e,container:i,drawStatus:!1,rippleEnabled:!1,meAsSaved:!0,avatarSize:32});t.lastMessageSpan.parentElement.remove()}n.length?o.lastElementChild.replaceWith(Object(x.i18n)("FilterShowMoreChats",[n.length])):o&&o.remove()};let o;if(s.generateContentElement().append(i),n.length){const e=s.generateContentElement();o=Object(U.a)("folder-category-button btn btn-primary btn-transparent",{icon:"down"}),o.classList.add("load-more","rp-overflow"),o.addEventListener("click",()=>a(20)),o.append(Object(x.i18n)("FilterShowMoreChats",[n.length])),e.append(o)}a(4)})}editCheckForChange(){if("edit"===this.type){const e=!Object(w.b)(this.originalFilter,this.filter);this.confirmBtn.classList.toggle("hide",!e),this.menuBtn.classList.toggle("hide",e)}}setFilter(e,t){Array.from(this.container.querySelectorAll("ul, .load-more")).forEach(e=>e.remove()),t?(this.originalFilter=e,this.filter=Object(w.a)(e)):(this.filter=e,this.onEditOpen(),this.editCheckForChange())}open(e){const t=super.open();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.onCreateOpen()):(this.setFilter(e,!0),this.type="edit",this.onEditOpen()),t}}var Yi=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 Xi extends z{constructor(){super(...arguments),this.filtersRendered={}}renderFolder(e,t,s){let n,a,r="",c=[];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&&c.push(Object(x.i18n)(t))}if(!c.length){const e=i.a.dialogsStorage.getFolderDialogs(n.id);let t=0,s=0,a=0;for(const i of e)o.a.isAnyGroup(i.peerId)?a++:o.a.isBroadcast(i.peerId)?s++:t++;t&&c.push(Object(x.i18n)("Chats",[t])),s&&c.push(Object(x.i18n)("Channels",[s])),a&&c.push(Object(x.i18n)("Groups",[a]))}}if(s)s.subtitle.textContent="",Object(x.join)(c).forEach(e=>{s.subtitle.append(e)});else if(s=new st({title:J.a.wrapEmojiText(n.title),subtitle:r,clickable:!0}),c.length&&Object(x.join)(c).forEach(e=>{s.subtitle.append(e)}),"dialogFilter"===e._){const e=n.id;this.filtersRendered.hasOwnProperty(n.id)||Object(l.b)(s.container,()=>{new $i(this.slider).open(i.a.filtersStorage.getFilter(e))},{listenerSetter:this.listenerSetter}),this.filtersRendered[n.id]=s}return a=s.container,n.hasOwnProperty("orderIndex")?As(a,a.parentElement||t,n.orderIndex):t&&t.append(a),a}init(){return Yi(this,void 0,void 0,(function*(){this.container.classList.add("chat-folders-container"),this.setTitle("ChatList.Filter.List.Title"),this.scrollable.container.classList.add("chat-folders"),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container");const e=document.createElement("div");e.classList.add("caption"),Object(x.i18n_)({element:e,key:"ChatList.Filter.Header"}),this.createFolderBtn=Object(U.a)("btn-primary btn-color-primary btn-control tgico",{text:"ChatList.Filter.NewTitle",icon:"add"}),this.foldersSection=new dn({name:"Filters"}),this.foldersSection.container.style.display="none",this.suggestedSection=new dn({name:"FilterRecommended"}),this.suggestedSection.container.style.display="none",this.scrollable.append(this.stickerContainer,e,this.createFolderBtn,this.foldersSection.container,this.suggestedSection.container),Object(l.b)(this.createFolderBtn,()=>{Object.keys(this.filtersRendered).length>=10?lt("Sorry, you can't create more folders."):new $i(this.slider).open()},{listenerSetter:this.listenerSetter});const t=()=>{this.foldersSection.container.style.display=Object.keys(this.filtersRendered).length?"":"none"};return i.a.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;As(s,s.parentElement,t+1)})}),this.loadAnimationPromise=le.a.loadAnimationAsAsset({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86},"Folders_1").then(e=>(this.animation=e,le.a.waitForFirstFrame(e))),this.getSuggestedFilters(),this.loadAnimationPromise}))}onOpenAfterTimeout(){this.loadAnimationPromise.then(()=>{this.animation.autoplay=!0,this.animation.play()})}getSuggestedFilters(){return ht.a.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=Object(U.a)("btn-primary btn-color-primary",{text:"Add"});t.append(s),this.suggestedSection.content.append(t),Object(l.b)(s,n=>{if(Object(c.a)(n),Object.keys(this.filtersRendered).length>=10)return void lt("Sorry, you can't create more folders.");s.setAttribute("disabled","true");const a=e.filter;a.includePeerIds=[],a.excludePeerIds=[],a.pinnedPeerIds=[],i.a.filtersStorage.createDialogFilter(a,!0).then(e=>{e&&t.remove()}).finally(()=>{s.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter})})})}}class Ji extends V{init(){this.container.classList.add("notifications-container"),this.setTitle("Telegram.NotificationSettingsViewController");const e=e=>{const t=new dn({name:e.name}),s=new st({checkboxField:new mt.a({text:e.typeText,checked:!0}),subtitleLangKey:"Loading"}),i=new st({checkboxField:new mt.a({text:"Notifications.MessagePreview",checked:!0}),subtitleLangKey:"Loading"});t.content.append(s.container,i.container),this.scrollable.append(t.container);const n={_:e.inputKey},o=Dt.a.getNotifySettings(n);(o instanceof Promise?o:Promise.resolve(o)).then(t=>{const o=()=>{const e=Dt.a.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===Dt.a.isMuted(t)&&a===t.show_previews)return;const o=Object(w.a)(t);o._="inputPeerNotifySettings",o.mute_until=e?2147483647:0,o.show_previews=a,Dt.a.updateNotifySettings(n,o)},{once:!0}),this.listenerSetter.add(a.default)("notify_settings",s=>{const i=Object(Y.c)(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 dn({name:"NotificationsOther"}),t=new st({checkboxField:new mt.a({text:"ContactJoined",checked:!0}),subtitleLangKey:"Loading"}),s=new st({checkboxField:new mt.a({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),Dt.a.getContactSignUpNotification().then(e=>{t.checkboxField.checked=e,this.eventListener.addEventListener("destroy",()=>{const s=t.checkboxField.checked;e!==s&&Dt.a.setContactSignUpNotification(!s)},{once:!0})})}}}var Zi=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 en extends z{init(){return Zi(this,void 0,void 0,(function*(){this.container.classList.add("language-container"),this.setTitle("Telegram.LanguageViewController");const e=new dn({}),t=new Map,s=ht.a.invokeApiCacheable("langpack.getLanguages",{lang_pack:"macos"}).then(s=>{const i=Object(at.b)();s.forEach(e=>{const s=new st({radioField:new ot({text:e.name,name:i,value:e.lang_code}),subtitle:e.native_name});t.set(e.lang_code,s)});const n=it([...t.values()],e=>{x.default.getLangPack(e)});x.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}))}}class tn extends z{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:()=>{ht.a.logOut()},isDanger:!0}]}).show()}}]);this.header.append(e),this.avatarElem=new ur,this.avatarElem.setAttribute("clickable",""),this.avatarElem.classList.add("profile-avatar","avatar-120"),this.nameDiv=document.createElement("div"),this.nameDiv.classList.add("profile-name"),this.phoneDiv=document.createElement("div"),this.phoneDiv.classList.add("profile-subtitle");const t=document.createElement("div");t.classList.add("profile-buttons");const s="profile-button btn-primary btn-transparent";t.append(this.buttons.edit=Object(U.a)(s,{icon:"edit",text:"EditAccount.Title"})),t.append(this.buttons.folders=Object(U.a)(s,{icon:"folder",text:"AccountSettings.Filters"})),t.append(this.buttons.general=Object(U.a)(s,{icon:"settings",text:"Telegram.GeneralSettingsViewController"})),t.append(this.buttons.notifications=Object(U.a)(s,{icon:"unmute",text:"AccountSettings.Notifications"})),t.append(this.buttons.privacy=Object(U.a)(s,{icon:"lock",text:"AccountSettings.PrivacyAndSecurity"})),t.append(this.buttons.language=Object(U.a)(s,{icon:"language",text:"AccountSettings.Language"})),this.scrollable.append(this.avatarElem,this.nameDiv,this.phoneDiv,t),this.scrollable.container.classList.add("profile-content-wrapper"),this.buttons.edit.addEventListener("click",()=>{new Wi(this.slider).open()}),this.buttons.folders.addEventListener("click",()=>{new Xi(this.slider).open()}),this.buttons.general.addEventListener("click",()=>{new Gi(this.slider).open()}),this.buttons.notifications.addEventListener("click",()=>{new Ji(this.slider).open()}),this.buttons.privacy.addEventListener("click",()=>{new Ti(this.slider).open()}),this.buttons.language.addEventListener("click",()=>{new en(this.slider).open()}),le.a.loadLottieWorkers(),this.fillElements()}fillElements(){const e=P.a.getSelf(),t=e.id.toPeerId(!1);this.avatarElem.setAttribute("peer",""+t),this.nameDiv.append(new Lt.a({peerId:t}).element),this.phoneDiv.innerHTML=e.phone?P.a.formatUserPhone(e.phone):""}}class sn extends z{constructor(){super(...arguments),this.uploadAvatar=null}init(){this.container.classList.add("new-channel-container"),this.setTitle("NewChannel"),this.avatarEdit=new q(e=>{this.uploadAvatar=e});const e=document.createElement("div");e.classList.add("input-wrapper"),this.channelNameInputField=new _.b({label:"EnterChannelName",maxLength:128}),this.channelDescriptionInputField=new _.b({label:"DescriptionOptionalPlaceholder",maxLength:255}),e.append(this.channelNameInputField.container,this.channelDescriptionInputField.container);const t=()=>{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",t),this.channelDescriptionInputField.input.addEventListener("input",t);const s=document.createElement("div");s.classList.add("caption"),Object(x._i18n)(s,"Channel.DescriptionHolderDescrpiton"),this.nextBtn=Q({icon:"arrow_next"}),this.nextBtn.addEventListener("click",()=>{const e=this.channelNameInputField.value,t=this.channelDescriptionInputField.value;this.nextBtn.disabled=!0,K.a.createChannel(e,t).then(e=>{this.uploadAvatar&&this.uploadAvatar().then(t=>{K.a.editPhoto(e,t)}),mn.removeTabFromHistory(this),new Bt(this.slider).open({type:"channel",skippable:!0,title:"GroupAddMembers",placeholder:"SendMessageTo",takeOut:t=>K.a.inviteToChannel(e,t)})})}),this.content.append(this.nextBtn),this.scrollable.append(this.avatarEdit.container,e,s)}onCloseAfterTimeout(){return this.avatarEdit.clear(),this.uploadAvatar=null,this.channelNameInputField.value="",this.channelDescriptionInputField.value="",this.nextBtn.disabled=!1,super.onCloseAfterTimeout()}}var nn=s(125);class an extends ut.b{constructor(){super("popup-create-contact popup-send-photo popup-new-media",null,{closable:!0,withConfirm:"Add"}),Object(x._i18n)(this.title,"AddContactTitle"),Object(l.b)(this.btnConfirm,()=>{const e=P.a.importContact(s.value,i.value,n.value);e.then(()=>{this.hide()},e=>{"NO_USER"===e.type&&(ct({langPackKey:"Contacts.PhoneNumber.NotRegistred"}),c.disabled=!1)}),c.lockWithPromise(e)},{listenerSetter:this.listenerSetter});const e=[],t=document.createElement("div");t.classList.add("name-fields");const s=new _.b({label:"FirstName",name:"create-contact-name",maxLength:70,required:!0}),i=new _.b({label:"LastName",name:"create-contact-lastname",maxLength:70}),n=new nn.a({required:!0});e.push(s,i,n);const a=()=>{const e=s.value+" "+i.value;c.avatarElem.setAttribute("peer-title",e),c.avatarElem.update()};this.listenerSetter.add(s.input)("input",a),this.listenerSetter.add(i.input)("input",a);const o=P.a.getSelf(),r=Object(Us.a)(o.phone);r&&(n.validate=()=>!!n.value.match(/\d/),n.value="+"+r.code.country_code);const c=new et({inputFields:e,listenerSetter:this.listenerSetter,doNotEditAvatar:!0,nextBtn:this.btnConfirm,avatarSize:100});t.append(s.container,i.container,c.avatarElem),this.container.append(t,n.container),this.show()}}class on extends z{init(){this.container.id="contacts-container";const e=Q({icon:"add",className:"is-visible"});this.content.append(e),Object(l.b)(e,()=>{new an},{listenerSetter:this.listenerSetter}),this.inputSearch=new F("Search",e=>{this.openContacts(e)}),this.listenerSetter.add(a.default)("contacts_update",e=>{const t=P.a.isContact(e),s=e.toPeerId();t?this.sortedUserList.add(s):this.sortedUserList.delete(s)}),this.title.replaceWith(this.inputSearch.container),this.middleware=Object(xs.a)()}createList(){const e=new Ds,t=e.list;return t.id="contacts",t.classList.add("contacts-container"),kr.setListClickListener(t,()=>{this.close()},void 0,!0),e}onClose(){this.middleware.clean()}onOpenAfterTimeout(){!re.IS_MOBILE&&di(!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="",P.a.getContactsPeerIds(e,void 0,"online").then(e=>{if(!t())return;const s=this.sortedUserList=this.createList();let i=()=>{const t=Et.a.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},Object(k.a)(this.scrollable.container,s.list)})}open(){return this.openContacts(),super.open()}}class rn extends z{init(){if(this.container.id="chats-archived-container",this.setTitle("ArchivedChats"),!kr.sortedLists[rn.filterId]){const e=kr.createChatList();kr.generateScrollable(e,rn.filterId).container.append(e),kr.setListClickListener(e,null,!0)}const e=kr.scrollables[rn.filterId];this.scrollable.container.replaceWith(e.container),this.scrollable=e}onOpen(){this.init&&(this.init(),this.init=null),this.wasFilterId=kr.filterId,kr.setFilterId(rn.filterId),kr.onTabChange()}onOpenAfterTimeout(){kr.sortedLists[this.wasFilterId].clear()}onClose(){kr.setFilterId(this.wasFilterId),kr.onTabChange()}onCloseAfterTimeout(){return kr.sortedLists[rn.filterId].clear(),super.onCloseAfterTimeout()}}rn.filterId=1;var ln=s(8),cn=s(67);class dn{constructor(e){if(this.container=document.createElement("div"),this.container.classList.add("sidebar-left-section"),e.fakeGradientDelimiter)this.container.append(pn()),this.container.classList.add("with-fake-delimiter");else if(e.noDelimiter)this.container.classList.add("no-delimiter");else{const e=document.createElement("hr");this.container.append(e)}this.content=this.generateContentElement(),e.name&&(this.title=document.createElement("div"),this.title.classList.add("sidebar-left-h2","sidebar-left-section-name"),Object(x.i18n_)({element:this.title,key:e.name}),this.content.append(this.title)),e.caption&&(this.caption=this.generateContentElement(),this.caption.classList.add("sidebar-left-section-caption"),!0!==e.caption&&Object(x.i18n_)({element:this.caption,key:e.caption}))}generateContentElement(){const e=document.createElement("div");return e.classList.add("sidebar-left-section-content"),this.container.append(e),e}}const hn=(e,t,s)=>{const i=new dn({name:t,caption:s});return e.append(i.container),i.content},pn=()=>{const e=document.createElement("div");return e.classList.add("gradient-delimiter"),e},un=new class extends G{constructor(){super({sidebarEl:document.getElementById("column-left"),navigationType:"left"}),this.searchGroups={},this.inputSearch=new F("Search");const e=this.sidebarEl.querySelector(".item-main .sidebar-header");e.append(this.inputSearch.container);const t=()=>{new on(this).open()};this.backBtn=this.sidebarEl.querySelector(".sidebar-back-button");const s={icon:"archive",text:"ArchivedChats",onClick:()=>{new rn(this).open()},verify:()=>!!i.a.dialogsStorage.getFolderDialogs(1,!1).length||!i.a.dialogsStorage.isDialogsLoaded(1)},n=new mt.a({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(()=>{er.setPeer(er.myId)},0)}},s,{icon:"user",text:"Contacts",onClick:t},{icon:"settings",text:"Settings",onClick:()=>{new tn(this).open()}},{icon:"darkmode",text:"DarkMode",onClick:()=>{},checkboxField:n},{icon:"animations",text:"Animations",onClick:()=>{},checkboxField:new mt.a({toggle:!0,checked:!0,stateKey:"settings.animationsEnabled"})},{icon:"help",text:"TelegramFeatures",onClick:()=>{er.openUsername("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([cn.a.set({kz_version:"Z"}),cn.a.delete("tgme_sync")]).then(()=>{location.href="https://web.telegram.org/z/"})},verify:()=>ln.a.isMainDomain},{icon:"char w",text:"ChatList.Menu.SwitchTo.Webogram",onClick:()=>{cn.a.delete("tgme_sync").then(()=>{location.href="https://web.telegram.org/?legacy=1"})},verify:()=>ln.a.isMainDomain}];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"),c=document.createElement("a");c.href="https://github.com/morethanwords/tweb/blob/master/CHANGELOG.md",c.target="_blank",c.rel="noopener noreferrer",c.classList.add("btn-menu-footer"),c.addEventListener(l.a,e=>{e.stopPropagation(),Object(te.c)()});const d=document.createElement("span");d.classList.add("btn-menu-footer-text"),d.innerHTML="Telegram Web"+ln.a.suffix+" alpha "+ln.a.versionFull,c.append(d),r.classList.add("has-footer"),r.append(c),this.newBtnMenu=Ie({},"top-left",[{icon:"newchannel",text:"NewChannel",onClick:()=>{new sn(this).open()}},{icon:"newgroup",text:"NewGroup",onClick:()=>{new Bt(this).open({type:"chat",skippable:!1,takeOut:e=>{new $(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.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=""+Object(I.c)(t,1),this.archivedCount.classList.toggle("hide",!t)}}),P.a.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")})}initSearch(){const e=this.sidebarEl.querySelector("#search-container"),t=new T.b(e),s=()=>{this.backBtn.click()};this.searchGroups={contacts:new O("Search.Chats","contacts",void 0,void 0,void 0,void 0,s),globalContacts:new O("Search.Global","contacts",void 0,void 0,void 0,void 0,s),messages:new O("Search.Messages","messages"),people:new O(!1,"contacts",!0,"search-group-people",!0,!1,s),recent:new O("Recent","contacts",!0,"search-group-recent",!0,!0,s)};const n=this.searchSuper=new ei({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 c=()=>{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")},d=document.createElement("div");d.classList.add("search-helper"),d.addEventListener("click",e=>{const t=Object(Me.a)(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),c()}),n.nav.parentElement.append(d);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 Lt.a({peerId:e.toPeerId()}).element),i.setAttribute("peer",""+e)):i.classList.add("tgico-calendarfilter"),t&&("string"==typeof t?s.innerHTML=t:(Object(k.a)(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(),Object(f.e)(a,e),setTimeout(()=>{c(),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),d.innerHTML="",n.nav.classList.remove("hide"),!o&&e.trim()){const t=n.middleware.get();Promise.all([i.a.getConversations(e).promise.then(({dialogs:e})=>e.map(e=>e.peerId)),P.a.getContactsPeerIds(e,!0)]).then(e=>{if(!t())return;new Set(e[0].concat(e[1])).forEach(e=>{d.append(h(e))}),n.nav.classList.toggle("hide",!!d.innerHTML)})}if(!r&&e.trim()){const t=[];Object(oe.b)(e,t),t.forEach(e=>{d.append(h("date_"+e.minDate+"_"+e.maxDate,e.title))}),n.nav.classList.toggle("hide",!!d.innerHTML)}},n.tabs.inputMessagesFilterEmpty.addEventListener("mousedown",e=>{const t=Object(ft.a)(e.target,"LI");if(!t)return;const s=Object(Me.a)(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){Object(f.e)(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 T.a(u);let m,g=!0;const b=Object(D.a)(e.parentElement,"zoom-fade",150,e=>{m&&clearTimeout(m),0!==e||g||(n.selectTab(0,!1),this.inputSearch.onClearClick(),m=window.setTimeout(()=>{m=0,this.newBtnMenu.classList.remove("is-hidden")},150)),g=!1});b(0);const v=()=>{this.toolsBtn.classList.remove("is-visible"),this.backBtn.classList.add("is-visible"),this.newBtnMenu.classList.add("is-hidden"),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!0),re.IS_MOBILE_SAFARI||j.a.findItemByType("global-search")||j.a.pushItem({onPop:()=>{s()},type:"global-search"}),b(1)};this.inputSearch.input.addEventListener("focus",v),v(),this.backBtn.addEventListener("click",e=>{this.toolsBtn.classList.add("is-visible"),this.backBtn.classList.remove("is-visible"),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!1),j.a.removeByType("global-search"),b(0)});const y=document.createElement("button");y.classList.add("btn-icon","tgico-close"),this.searchGroups.recent.nameEl.append(y),y.addEventListener("click",()=>{this.searchGroups.recent.clear(),M.default.pushToState("recentSearch",[])})}};de.a.appSidebarLeft=un;var mn=un;class gn{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):Object(f.e)(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 c={timestamp:i,fromId:r,mid:t.mid,group:o};let d=0;for(;d<this.bubbles.length&&!(this.bubbles[d].mid<n);++d);this.bubbles.splice(d,0,{timestamp:i,fromId:r,mid:t.mid,group:o}),this.updateGroup(o),this.detailsMap.set(e,c)}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 bn extends ut.b{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"),Object(l.b)(this.prevBtn,this.onPrevClick,{listenerSetter:this.listenerSetter}),this.nextBtn=document.createElement("button"),this.nextBtn.classList.add("btn-icon","tgico-down","date-picker-next"),Object(l.b)(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"),Object(l.b)(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 _.b({plainText:!0}),this.minutesInputField=new _.b({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),Object(l.b)(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 x.default.IntlDateElement({date:n,options:i}).element)}t.push(new x.default.IntlDateElement({date:n,options:i}).element),this.btnConfirm.firstChild.replaceWith(Object(x.i18n)(e,t))}}setTitle(){this.title.textContent="",this.title.append(new x.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&&b.b.isMobile?"short":"long"};this.monthTitle.textContent="",this.monthTitle.append(new x.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 x.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)}}class vn{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)}}a.default.addEventListener("replies_updated",e=>{const t=e;Array.from(document.querySelectorAll(`replies-element[data-post-key="${t.peerId}_${t.mid}"]`)).forEach(e=>{e.message=t,e.render()})});class fn 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,s;if(this.firstElementChild&&(t=this.firstElementChild),(null==e?void 0:e.recent_repliers)?(t&&!t.classList.contains("replies-footer-avatars")&&(this.innerHTML="",t=null),t||(t=document.createElement("div"),t.classList.add("replies-footer-avatars")),e.recent_repliers.slice().reverse().forEach((e,s)=>{let i=t.children[s];i||(i=new ur,i.setAttribute("dialog","0"),i.classList.add("avatar-30"),i.lazyLoadQueue=this.lazyLoadQueue,this.loadPromises&&(i.loadPromises=this.loadPromises)),i.setAttribute("peer",""+o.a.getPeerId(e)),i.parentNode||t.append(i)}),Array.from(t.children).slice(e.recent_repliers.length).forEach(e=>e.remove())):(t&&!t.classList.contains("tgico-comments")&&(t.remove(),t=null),t||(t=document.createElement("span"),t.classList.add("tgico-comments"))),t.parentElement||this.append(t),s=e?e.replies?Object(x.i18n)("Comments",[e.replies]):Object(x.i18n)("LeaveAComment"):Object(x.i18n)("ViewInChat"),e){const t=i.a.getHistoryStorage(e.channel_id.toPeerId(!0));let s=!1;e.replies&&(s=void 0!==e.read_max_id&&void 0!==e.max_id?e.read_max_id<e.max_id:!t.readMaxId||t.readMaxId<(e.max_id||0)),this.classList.toggle("is-unread",s)}let n=this.children[1];if(!n){n=document.createElement("span"),n.classList.add("replies-footer-text");const e=document.createElement("span");e.classList.add("tgico-next");const t=document.createElement("div");Object(se.ripple)(t),this.append(n,e,t)}Object(k.a)(n,s)}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)?Object(I.c)(e.replies,0):""}</span>`;!e||this.updated||this.message.pFlags.is_outgoing||(i.a.subscribeRepliesThread(this.message.peerId,this.message.mid),i.a.updateMessage(this.message.peerId,this.message.mid,"replies_updated"),this.updated=!0),this.loadPromises&&(this.loadPromises=void 0)}}customElements.define("replies-element",fn);const yn=()=>{const e=document.createElement("i");return e.classList.add("edited"),Object(x._i18n)(e,"EditedMessage"),e};var wn,Sn;(Sn=wn||(wn={})).setTime=(e,t,s,i,n)=>{var a;const o=new Date(1e3*t.date),r=[];let l,c=Object(oe.e)(o);if(t.views){const e=t.post_author||(null===(a=t.fwd_from)||void 0===a?void 0:a.post_author);s.classList.add("channel-post");const i=document.createElement("span");i.classList.add("post-views"),i.innerHTML=Object(I.c)(t.views,1);const n=document.createElement("i");if(n.classList.add("tgico-channelviews","time-icon"),r.push(i,n),e){const t=document.createElement("span");t.innerHTML=J.b.wrapEmojiText(e)+",&nbsp;",r.push(t)}}if(t.edit_date&&"scheduled"!==e.type&&!t.pFlags.edit_hide&&(s.classList.add("is-edited"),r.unshift(l=yn())),"pinned"!==e.type&&t.pFlags.pinned){s.classList.add("is-pinned");const e=document.createElement("i");e.classList.add("tgico-pinnedchat","time-icon"),r.unshift(e)}r.push(c);const d=Object(oe.f)(o)+(t.edit_date?"\nEdited: "+Object(oe.f)(new Date(1e3*t.edit_date)):"")+(t.fwd_from?"\nOriginal: "+Object(oe.f)(new Date(1e3*t.fwd_from.date)):""),h=document.createElement("span");h.classList.add("time","tgico"),h.title=d,h.append(...r);const p=document.createElement("div");p.classList.add("inner","tgico"),p.title=d;let u=r;return l&&(u[u.indexOf(l)]=yn()),u=u.map(e=>e instanceof HTMLElement&&!e.classList.contains("i18n")?e.cloneNode(!0):e),u[u.length-1]=Object(oe.e)(o),p.append(...u),h.append(p),n.append(h),h},Sn.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 fn;return r.message=s,r.type=o?"footer":"beside",r.loadPromises=n,r.lazyLoadQueue=a,r.init(),t.prepend(r),o},Sn.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=Object(x.i18n)("Loading")):r=new Lt.a({peerId:l.fromId||l.fwdFromId,dialog:!1,onlyFirstName:!1,plainText:!1}).element;const c=Ms(r,void 0,l);a?a.replaceWith(c):s.append(c),t.classList.add("is-reply")};var Ln=s(128);function En(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 Cn(e){e.style.display="none",e.offsetLeft,e.style.display=""}de.a.getElementByPoint=En;var In=s(82),Mn=s(150),Pn=s(114),Tn=s(80);const kn={keywords:{},version:0,langCode:ln.a.langPackCode};class xn{constructor(){this.keywordLangPacks={},this.indexedLangPacks={},this.getKeywordsPromises={}}getEmojiKeywords(e=ln.a.langPackCode){const t=this.getKeywordsPromises[e];if(t)return t;const s="emojiKeywords_"+e;return this.getKeywordsPromises[e]=Tn.a.get(s).then(t=>(Object(Mn.a)(t)||(t={}),Object(w.k)(kn,t),t.langCode=e,this.keywordLangPacks[e]=t,ht.a.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 Tn.a.set({[s]:t}),t},()=>t)))}getBothEmojiKeywords(){const e=[this.getEmojiKeywords()];return x.default.lastRequestedLangCode!==ln.a.langPackCode&&e.push(this.getEmojiKeywords(x.default.lastRequestedLangCode)),this.recent||e.push(this.getRecentEmojis()),Promise.all(e)}indexEmojis(){this.index||(this.index=new Pn.a(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=J.b.fixEmoji(e),this.getRecentEmojis().then(t=>{Object(f.e)(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 On=new xn;de.a&&(de.a.appEmojiManager=On);var An=On,_n=s(133),Fn=s(10);const Dn=new Set;function jn(e,t,s=!1,i=!1){const n=document.createElement("span");let o;if(n.classList.add("super-emoji"),i&&!Fn.a?o=J.a.wrapSingleEmoji(e):(e=J.a.fixEmoji(e),o=J.a.wrapEmojiText(e)),n.innerHTML=o,n.children.length>1){const e=n.firstElementChild;n.innerHTML="",n.append(e)}if(n.firstElementChild&&!Fn.a){const e=n.firstElementChild,t=e.src;if(!Dn.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",()=>{Object(De.b)(()=>{a.default.settings.animationsEnabled&&(e.style.opacity="",s.style.opacity=""),n.classList.remove("empty"),Dn.add(t)})},{once:!0}),n.append(s)}}s?t.prepend(n):t.appendChild(n)}function Bn(e){return Object(Me.a)(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 Rn{constructor(){this.closeScrollTop=0,this.onContentClick=e=>{Object(c.a)(e);const t=Bn(e.target);t&&(er.chat.input.onEmojiSelected(t,!1),ue.IS_TOUCH_SUPPORTED&&Object(Ks.a)())}}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 _n.a.Emoji){const i=""+_n.a.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(Object(x.i18n)(s));const a=document.createElement("div");a.classList.add("super-emojis"),i.append(n,a),e.forEach(e=>{jn(Object(ie.a)(e),a,!1)}),t[s]=i});const i=this.menu=this.content.previousElementSibling,n=this.scroll=new T.b(this.content,"EMOJI"),o=Object(te.f)(this.content,!0);Promise.all([Object(In.a)(200),An.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=sa.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)jn(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===J.a.fixEmoji(Bn(i))){if(0===s)return;i.remove()}}jn(e,this.recentItemsDiv,!0),this.recentItemsDiv.parentElement.classList.remove("hide"),this.menu.children[0].classList.remove("hide"),this.closeScrollTop||this.setMenuActive(0)}),na.addEventListener("close",()=>{this.closeScrollTop=this.scroll.scrollTop})}onClose(){}}var Un=s(122),Hn=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 Nn{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=Object(ae.a)(),this.timeout=window.setTimeout(()=>{this.timeout=0,this.scrollPromise.resolve()},150)},this.processInvisibleDiv=e=>this.scrollPromise.then(()=>Hn(this,void 0,void 0,(function*(){if(this.lazyLoadQueue.intersector.isVisible(e))return;const t=e.querySelector("video"),s=e.querySelector("img");if(s&&(s&&s.classList.remove("hide"),yield Object(De.a)()),!this.lazyLoadQueue.intersector.isVisible(e)&&t){t.remove(),t.src="",t.load();C.a.getAnimations(t).forEach(e=>{C.a.checkAnimation(e,!0,!0)})}}))),this.lazyLoadQueue=new ee.c(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){if(e.querySelector("video"))return;this.lazyLoadQueue.push({div:e,load:()=>{const t=e.dataset.docId,s=E.a.getDoc(t);return this.scrollPromise.then(()=>{const t=ws({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();C.a.getAnimations(t).forEach(e=>{C.a.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<100&&(i*=100/n,n=100);const a=Math.min(300,400,i),o=Object(Un.a)(i,n,a,100),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=E.a.getThumb(e,!1);let c;!!l&&(c=new Image,c.classList.add("media-poster"),l.cacheContext.url||l.promise.then(()=>{c.src=l.cacheContext.url}));const d=()=>{c&&(r.append(c),r.style.opacity="")};(null===(s=null==l?void 0:l.cacheContext)||void 0===s?void 0:s.url)?Object(rs.a)(c,l.cacheContext.url,d):d()}}class zn{init(){this.content=document.getElementById("content-gifs");const e=this.content.firstElementChild;e.addEventListener("click",sa.onMediaClick);const t=new T.b(this.content,"GIFS"),s=new Nn(e,ta,t),i=Object(te.f)(this.content,!0);ht.a.invokeApi("messages.getSavedGifs",{hash:"0"}).then(e=>{"messages.savedGifs"===e._&&e.gifs.forEach((t,i)=>{e.gifs[i]=t=E.a.saveDoc(t),s.add(t)}),i.remove()}),na.addLazyLoadQueueRepeat(s.lazyLoadQueue,s.processInvisibleDiv),this.init=null}onClose(){}}var Vn=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 Gn{constructor(e,t){this.regularLazyLoadQueue=e,this.group=t,this.animatedDivs=new Set,this.checkAnimationContainer=(e,t)=>{C.a.getAnimations(e).forEach(e=>{t?C.a.checkAnimation(e,!1):C.a.checkAnimation(e,!0,!0)})},this.processVisibleDiv=e=>{const t=e.dataset.docId,s=E.a.getDoc(t),i=b.b.active.esgSticker.width,n=Cs({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=E.a.getDoc(t);this.checkAnimationContainer(e,!1),e.innerHTML="",this.renderSticker(s,e)},this.lazyLoadQueue=new ee.b(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"),2===e.sticker&&this.observeAnimatedDiv(t)),Cs({doc:e,div:t,lazyLoadQueue:this.regularLazyLoadQueue,group:this.group,onlyThumb:2===e.sticker,loadPromises:s}),t}observeAnimatedDiv(e){this.animatedDivs.add(e),this.lazyLoadQueue.observe({div:e,load:this.processVisibleDiv})}}class Kn{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 Vn(this,void 0,void 0,(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=us.getStickerSet(e);this.categoryPush(s,J.a.wrapEmojiText(e.title),n.then(e=>e.documents),t);yield n;Is({set:e,container:i,group:ta,lazyLoadQueue:sa.lazyLoadQueue,width:32,height:32,autoplay:!1})}))}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 T.a(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(Object(Me.a)(t,"category-title")){const e=Object(St.a)(t,"data-id");new Ni({id:e.dataset.id,access_hash:e.dataset.access_hash}).show()}else sa.onMediaClick(e)});const s=(e=!1)=>{a.default.dispatchEvent("choosing_sticker",!e)};this.scroll=new T.b(this.content,"STICKERS"),this.scroll.setVirtualContainer(this.stickersDiv),this.scroll.onAdditionalScroll=()=>{s()},na.addEventListener("closed",()=>{s(!0)}),na.addEventListener("opened",()=>{s()}),this.stickyIntersector=sa.menuOnClick(this.menu,this.scroll,t).stickyIntersector;const i=Object(te.f)(this.content,!0);Promise.all([us.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(Object(x.i18n)("Stickers.Recent"))}),us.getAllStickers().then(e=>{i.remove();for(let t of e.sets)this.renderStickerSet(t)})]).finally(()=>{this.mounted=!0,s()}),this.superStickerRenderer=new Gn(sa.lazyLoadQueue,ta),na.addLazyLoadQueueRepeat(this.superStickerRenderer.lazyLoadQueue,this.superStickerRenderer.processInvisibleDiv),this.init=null}pushRecentSticker(e){var t;if(us.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(){}}var Wn=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 qn=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 ht.a.invokeApi("messages.getInlineBotResults",{bot:P.a.getUserInput(t),peer:o.a.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=E.a.saveDoc(e.document)),e.photo&&(e.photo=r.a.savePhoto(e.photo))),this.inlineResults[this.generateQId(t,e.id)]=e}),e})}generateQId(e,t){return e+"_"+t}pushPopularBot(e){P.a.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,Object(f.f)(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.a.startBot(t,void 0,s)}checkSwitchReturn(e){return Wn(this,void 0,void 0,(function*(){const t=P.a.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}))}switchInlineQuery(e,t,s,i){a.default.dispatchEvent("history_focus",{peerId:e,threadId:t}),Pi.a.setDraft(e,t,"@"+P.a.getUser(s).username+" "+i)}callbackButtonClick(e,t,s){return ht.a.invokeApi("messages.getBotCallbackAnswer",{peer:o.a.getInputPeerById(e),msg_id:v.a.getServerMessageId(t),data:s.data},{stopTime:-1,noErrorBox:!0}).then(e=>{"string"==typeof e.message&&e.message.length&&lt(J.a.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("_"),c=l.shift(),d=l.join("_");if(n.viaBotId=t,n.queryId=c,n.resultId=d,o.send_message.reply_markup&&(n.replyMarkup=o.send_message.reply_markup),"botInlineMessageText"===o.send_message._)n.entities=o.send_message.entities,i.a.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?E.a.getMediaInput(e):r.a.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.a.sendOther(e,t,n)}}};de.a&&(de.a.appInlineBotsManager=qn);var Qn=qn,$n=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 Yn extends z{constructor(){super(...arguments),this.nextOffset="",this.loadedAll=!1,this.onGifsClick=e=>{const t=Object(Me.a)(e.target,"gif");if(!t)return;const s=t.dataset.docId;er.chat.input.sendMessageWithDocument(s)?b.b.isMobile&&Yt.onCloseBtnClick():console.warn("got no doc by id:",s)}}init(){this.container.id="search-gifs-container",this.inputSearch=new F("SearchGifsTitle",e=>{this.reset(),this.search(e)}),this.title.replaceWith(this.inputSearch.container),this.gifsDiv=document.createElement("div"),this.gifsDiv.classList.add("gifs-masonry"),Object(l.b)(this.gifsDiv,this.onGifsClick,{listenerSetter:this.listenerSetter}),this.scrollable.append(this.gifsDiv),this.masonry=new Nn(this.gifsDiv,"GIFS-SEARCH",this.scrollable)}onClose(){this.scrollable.onScrolledBottom=()=>{}}onCloseAfterTimeout(){return this.reset(),this.gifsDiv.innerHTML="",C.a.checkAnimations(void 0,"GIFS-SEARCH"),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 $n(this,void 0,void 0,(function*(){if(!this.searchPromise&&!this.loadedAll){this.gifBotPeerId||(this.gifBotPeerId=(yield P.a.resolveUsername("gif")).id.toPeerId(!1));try{this.searchPromise=Qn.getInlineResults(Be.b,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}}}))}}class Xn extends z{init(){this.container.id="stickers-container",this.container.classList.add("chatlist-container"),this.lazyLoadQueue=new ee.d,this.inputSearch=new F("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),Object(l.b)(this.setsDiv,e=>{const t=Object(Me.a)(e.target,"sticker-set-sticker");if(t){const e=t.dataset.docId;return void er.chat.input.sendMessageWithDocument(e)}const s=Object(Me.a)(e.target,"sticker-set");if(!s)return;const i=s.dataset.stickerSet,n=s.dataset.access_hash,a=Object(Me.a)(e.target,"sticker-set-button");a?(e.preventDefault(),e.cancelBubble=!0,a.setAttribute("disabled","true"),us.getStickerSet({id:i,access_hash:n}).then(e=>{us.toggleStickerSet(e.set).then(t=>{t&&(a.textContent="",a.append(Object(x.i18n)(e.set.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),a.classList.toggle("gray",!!e.set.installed_date))}).finally(()=>{a.removeAttribute("disabled")})})):us.getStickerSet({id:i,access_hash:n}).then(e=>{new Ni(e.set).show()})},{listenerSetter:this.listenerSetter})}onCloseAfterTimeout(){return this.setsDiv.innerHTML="",C.a.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">${J.a.wrapEmojiText(e.title)}</div>\n `;const n=document.createElement("div");n.classList.add("sticker-set-count"),n.append(Object(x.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(Object(x.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)}us.getStickerSet(e).then(e=>{for(let t=0;t<r;++t){const s=o.children[t],i=e.documents[t];"documentEmpty"!==i._&&Cs({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 us.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 Object(f.d)(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()}),C.a.checkAnimations(void 0,"STICKERS-SEARCH"),t}search(e){return e?us.searchStickerSets(e,!1).then(t=>{this.inputSearch.value===e&&(t=this.filterRendered(e,t)).forEach(e=>{this.renderSet(e.set)})}):this.renderFeatured()}}var Jn=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 Zn extends B.a{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&&Object(qs.a)(t,this.element)||(this.displayTimeout=window.setTimeout(()=>{this.toggle(!1)},200))},this.toggle=e=>Jn(this,void 0,void 0,(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.dispatchEvent("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")},ue.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")},ue.IS_TOUCH_SUPPORTED?0:200)})),Object(w.g)(this,e)}attachButtonListener(e,t){let s=!0;ue.IS_TOUCH_SUPPORTED?Object(l.b)(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(){ue.IS_TOUCH_SUPPORTED||(this.element.onmouseout=this.onMouseOut,this.element.onmouseover=e=>{this.forceClose||clearTimeout(this.displayTimeout)})}isActive(){return this.element.classList.contains("active")}}var ea=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 ta="emoticons-dropdown";class sa extends Zn{constructor(){super({element:document.getElementById("emoji-dropdown")}),this.tabId=-1,this.onSelectTabClick=e=>{this.tabId!==e&&(C.a.checkAnimations(!0,ta),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}=er.chat,s=this.tabsEl.children,n=Array.from(s),a=i.a.canSendToPeer(e,t,"send_stickers");n[2].toggleAttribute("disabled",!a);const o=i.a.canSendToPeer(e,t,"send_gifs");n[3].toggleAttribute("disabled",!o);const r=this.tabsEl.querySelector(".active");!r||1===Object(Os.a)(r)||a&&o||this.selectTab(0,!1)},this.addEventListener("open",()=>ea(this,void 0,void 0,(function*(){ue.IS_TOUCH_SUPPORTED&&Object(Ks.a)()&&(yield Object(In.a)(100)),this.element.parentElement!==er.chat.input.chatInput&&er.chat.input.chatInput.append(this.element),this.savedRange=this.getGoodRange(),sa.lazyLoadQueue.lock(),C.a.lockIntersectionGroup(ta)}))),this.addEventListener("opened",()=>{C.a.unlockIntersectionGroup(ta),sa.lazyLoadQueue.unlock(),sa.lazyLoadQueue.refresh(),this.container.classList.remove("disable-hover")}),this.addEventListener("close",()=>{sa.lazyLoadQueue.lock(),C.a.lockIntersectionGroup(ta),C.a.checkAnimations(!0,ta)}),this.addEventListener("closed",()=>{C.a.unlockIntersectionGroup(ta),sa.lazyLoadQueue.unlock(),sa.lazyLoadQueue.refresh(),this.container.classList.remove("disable-hover"),this.savedRange=void 0})}init(){this.emojiTab=new Rn,this.stickersTab=new Kn,this.gifsTab=new zn,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=Object(Z.a)(this.tabsEl,this.container,this.onSelectTabClick,()=>{const e=this.tabs[this.tabId];e.init&&e.init(),e.onCloseAfterTimeout&&e.onCloseAfterTimeout(),C.a.checkAnimations(!1,ta)}),this.searchButton=this.element.querySelector(".emoji-tabs-search"),this.searchButton.addEventListener("click",()=>{1===this.tabId?Yt.isTabExists(Xn)||new Xn(Yt).open():Yt.isTabExists(Yn)||new Yn(Yt).open()}),this.deleteBtn=this.element.querySelector(".emoji-tabs-delete"),this.deleteBtn.addEventListener("click",e=>{var t;const s=er.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});er.chat.input.messageInput.dispatchEvent(i),Object(c.a)(e)});const e=re.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===er.chat.input.messageInput)return e.getRangeAt(0)}}sa.lazyLoadQueue=new ee.d,sa.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 vn(t.container,(i,o)=>{if(Math.abs(n-t.container.scrollTop)<=1)return;n=-1;const r=Object(Os.a)(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=Object(Me.a)(s,"menu-horizontal-div-item"),!s)return;const i=Object(Os.a)(s);if(!a(i))return;const o=(t.splitUp||t.container).children[i].offsetTop+1;t.container.scrollTop=n=o}),{stickyIntersector:o,setActive:a}},sa.onMediaClick=(e,t=!1)=>{let s=e.target;if(s=Object(ft.a)(s,"DIV"),!s)return!1;const i=s.dataset.docId;return!!i&&(er.chat.input.sendMessageWithDocument(i,void 0,t)?(ia.container&&(ia.forceClose=!0,ia.container.classList.add("disable-hover"),ia.toggle(!1)),!0):(console.warn("got no doc by id:",i),!1))};const ia=new sa;de.a.emoticonsDropdown=ia;var na=ia;var aa=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 oa=new Set(["messageActionHistoryClear","messageActionChatCreate"]);let ra=void 0,la=0;class ca{constructor(e,t,s,i,n,o,r,l,d,h){if(this.chat=e,this.appMessagesManager=t,this.appStickersManager=s,this.appUsersManager=i,this.appInlineBotsManager=n,this.appPhotosManager=o,this.appPeersManager=r,this.appProfileManager=l,this.appDraftsManager=d,this.appMessagesIdsManager=h,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=Object(xs.a)(),this.replyFollowHistory=[],this.isHeavyAnimationInProgress=!1,this.isFirstLoad=!0,this.passEntities={},this.viewsMids=new Set,this.isTopPaddingSet=!1,this.onBubblesClick=e=>{var t;let s=e.target,i=null;try{i=Object(Me.a)(s,"bubble")}catch(e){}if(!i)return;if(i.classList.contains("is-date")&&Object(Me.a)(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 bn(new Date(+e),this.onDatePick).show();break}}return}if(!ue.IS_TOUCH_SUPPORTED&&Object(Me.a)(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 Object(c.a)(e),ue.IS_TOUCH_SUPPORTED&&this.chat.selection.selectedText?void(this.chat.selection.selectedText=void 0):void this.chat.selection.toggleByElement(Object(Me.a)(s,"grouped-item")||i)}const n=Object(Me.a)(s,"contact");if(n)return void this.chat.appImManager.setInnerPeer(n.dataset.peerId.toPeerId());if(Object(Me.a)(s,"replies")){const e=+i.dataset.mid;if(this.peerId===Be.c){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(s.channel_id.toPeerId(!0),void 0,"discussion",e.mid)})}return}const a=Object(Me.a)(s,"is-via");if(a){const t=a.querySelector(".peer-title");if(s===t||Object(qs.a)(s,t)){const s=t.innerText+" ";return this.appDraftsManager.setDraft(this.peerId,this.chat.threadId,s),void Object(c.a)(e)}}const o=Object(Me.a)(s,"peer-title")||Object(ft.a)(s,"AVATAR-ELEMENT")||Object(St.a)(s,"data-saved-from");if(o&&o!==i){s=o||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(e.toPeerId(),+s)}else{const t=e.toPeerId();t!==Be.b?this.chat.appImManager.setInnerPeer(t):lt(x.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 Ni(s.stickerSetInput).show())}const r=Object(Me.a)(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")||r&&!r.querySelector(".preloader-container")){const t=+(Object(Me.a)(s,"album-item")||Object(Me.a)(s,"document-container")||i).dataset.mid,n=this.chat.getMessage(t);if(!n)return void this.log.warn("no message by messageId:",t);const a="webpage",o=i.classList.contains(a),l=r?e=>nr.isMediaCompatibleForDocumentViewer(e):e=>"photo"===e._||["video","gif"].includes(e.type),d=[],h=o?[t]:Object.keys(this.bubbles).map(e=>+e).filter(e=>{const t=this.chat.getMessage(e),s=this.appMessagesManager.getMediaFromMessage(t);return s&&l(s)}).sort((e,t)=>e-t);h.forEach(e=>{let t;if(r)t=".document-container";else{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(r)s.forEach(e=>{d.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&&!Object(Me.a)(s,"media-container-aspecter"))return;let n=Object(Me.a)(s,"album-item");const a=n||s.parentElement;i.has(a)||(i.add(a),d.push({element:s,mid:n?+n.dataset.mid:e,peerId:this.peerId}))})}}),d.sort((e,t)=>e.mid-t.mid);let p=d.findIndex(e=>e.mid===t);return de.b&&this.log("open mediaViewer single with ids:",h,p,d),d[p]?((new nr).setSearchContext({threadId:this.chat.threadId,peerId:this.peerId,inputFilter:{_:r?"inputMessagesFilterDocument":"inputMessagesFilterPhotoVideo"},useSearch:"scheduled"!==this.chat.type&&!o,isScheduled:"scheduled"===this.chat.type}).openMedia(n,d[p].element,0,!0,d.slice(0,p),d.slice(p+1)),void Object(c.a)(e)):void this.log("no target for media viewer!",s)}if(-1===["IMG","DIV","SPAN"].indexOf(s.tagName)&&(s=Object(ft.a)(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(t.toPeerId(),+s)}if(s.classList.contains("forward")){const e=+i.dataset.mid,t=this.appMessagesManager.getMessageByPeer(this.peerId,e);return void new Ns({[this.peerId]:this.appMessagesManager.getMidsByMessage(t)})}let t=!1;try{t=!!Object(Me.a)(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(s,n,this.chat.type,this.chat.threadId)}}},this.onScroll=()=>{this.isHeavyAnimationInProgress&&this.scrolledDown||(ue.IS_TOUCH_SUPPORTED||(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)),this.scrollable.getDistanceToEnd()<300&&this.scrollable.loadedAll.bottom?(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.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 R.a,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 gn(this.chat),this.preloader=new ye.a({cancelable:!1}),this.lazyLoadQueue=new ee.d,this.lazyLoadQueue.queueId=++la,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+Ze.a.serverTimeOffset-1)return void this.bubbleGroups.changeBubbleMid(e,s);this.setBubblePosition(e,t,!1),this.scrollingToBubble&&this.scrollToBubbleEnd()}}),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,c;const{storage:d,tempId:h,tempMessage:p,mid:u}=e;if(this.chat.getMessagesStorage()!==d)return;const m=this.getMountedBubble(h,p)||this.getMountedBubble(u);if(m){const e=this.chat.getMessage(u),a=m.bubble;if(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=Object(Me.a)(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(Ss({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 Ne||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===(c=e.media)||void 0===c?void 0:c.webpage)&&!a.querySelector(".web")&&Object(ks.c)().then(()=>{this.safeRenderMessage(e,!0,!1,a,!1),this.scrollToBubbleIfLast(a)})}else this.log.warn("message_sent there is no bubble",e);const g=this.bubbles;if(g[h]){const e=g[h];g[u]=e,delete g[h],Object(De.b)(()=>{e.classList.contains("is-sending")&&(e.classList.remove("is-sending"),e.classList.add(this.peerId===a.default.myId&&"scheduled"!==this.chat.type?"is-read":"is-sent"))}),e.dataset.mid=""+u}if(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,o=this.scrolledDown;this.safeRenderMessage(n.message,!0,!1,n.bubble,a),o&&this.scrollToBubbleIfLast(n.bubble),a&&(this.messagesQueuePromise||Promise.resolve()).then(()=>{this.deleteEmptyDateGroups()})}),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=Object(w.e)(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();Object(ks.c)().then(()=>{s()&&t.forEach(t=>{Object(f.d)(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,wn.setReply({chat:this.chat,bubble:n,message:a})}})})})}),this.listenerSetter.add(this.bubblesContainer)("click",this.onBubblesClick),ue.IS_TOUCH_SUPPORTED){const e="is-gesturing-reply",t=64,s=.75*t;let i,n,a=!1;Bs({element:this.bubblesContainer,verifyTouchTarget:t=>!(this.chat.selection.isSelecting||!this.appMessagesManager.canSendToPeer(this.peerId,this.chat.threadId))&&(i=Object(Me.a)(t.target,"bubble"),i&&(Object(Jt.a)(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)`,Object(te.b)()},onReset:()=>{const t=i;Object(Jt.a)(t,e,!1,250,()=>{n.parentElement===t&&(n.classList.remove("is-visible"),n.remove())}),Object(De.b)(()=>{if(t.style.transform="",a){const{mid:e}=t.dataset;this.chat.input.initMessageReply(+e),a=!1}})},listenerOptions:{capture:!0}})}let p;de.b&&this.listenerSetter.add(this.bubblesContainer)("dblclick",e=>{const t=Object(Me.a)(e.target,"grouped-item")||Object(Me.a)(e.target,"bubble");if(t){const e=+t.dataset.mid;this.log("debug message:",this.chat.getMessage(e)),this.highlightBubble(t)}}),re.IS_MOBILE||"pinned"===this.chat.type||this.listenerSetter.add(this.bubblesContainer)("dblclick",e=>{if(this.chat.selection.isSelecting||!this.appMessagesManager.canSendToPeer(this.peerId,this.chat.threadId))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)}}),this.stickyIntersector=new vn(this.scrollable.container,(e,t)=>{for(const s in this.dateMessages){const i=this.dateMessages[s];if(i.container===t){i.div.classList.toggle("is-sticky",e);break}}}),Object(ks.a)(()=>{this.isHeavyAnimationInProgress=!0,this.lazyLoadQueue.lock(),p=this.getMiddleware()},()=>{this.isHeavyAnimationInProgress=!1,p&&p()&&(this.lazyLoadQueue.unlock(),this.lazyLoadQueue.refresh()),p=null},this.listenerSetter)}constructPeerHelpers(){if(this.listenerSetter.add(a.default)("history_append",({storage:e,mid:t})=>{e===this.chat.getMessagesStorage()&&(this.scrollable.loadedAll.bottom?this.renderNewMessagesByIds([t],!0):this.chat.setMessageId())}),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=>{if(this.peerId===e.toPeerId(!0)){this.chatInner.classList.contains("has-rights")!==this.appMessagesManager.canSendToPeer(this.peerId,this.chat.threadId)&&(this.finishPeerChange(),this.chat.input.updateMessageInput())}}),this.listenerSetter.add(a.default)("settings_updated",e=>{if("settings.emoji.big"===e.key){const e=this.scrollable.isScrolledDown;e||this.setMessagesQueuePromise();Object(w.e)(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&&Object(De.b)(()=>{const e=this.bubbles[s];if(!e)return;const i=Array.from(e.querySelectorAll(".post-views"));if(i.length){const e=Object(I.c)(t,1);let s=!1;i.forEach(t=>{(s||t.innerHTML!==e)&&(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=>{e.isIntersecting&&(this.viewsMids.add(+e.target.dataset.mid),this.viewsObserver.unobserve(e.target),this.sendViewCountersDebounced())})}),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)})};new ResizeObserver(a=>{if(s)return void r(!1);const o=a[0].contentRect.height;if(!e)return void(e=o);const l=e-o;let c=l+n;const d=c%1;if(c-=d,!t&&(t=!0,l<0&&this.scrollable.isScrolledDown))return n=-l,s=!0,void r(!1);if(i+=c,c){const e=this.scrollable.scrollTop+c;this.scrollable.scrollTop=e}r(!1),n=d,e=o}).observe(this.bubblesContainer)}}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(),de.b&&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){Object(f.d)(this.replyFollowHistory,(e,t)=>{const s=this.bubbles[e];let i=!0;if(s){const e=s.getBoundingClientRect();i=Et.a.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=En(this.scrollable.container,e,"center");return t&&(t=Object(Me.a)(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)}}return null}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[Object(w.e)(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)de.b&&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);de.b&&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 T.b(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),ue.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-sending"))continue;t.classList.remove("is-sent","is-sending"),t.classList.add("is-read")}this.unreadOut.delete(e)}}deleteMessagesByIds(e,t=!0){e.forEach(e=>{if(!(e in this.bubbles))return;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)}),t&&this.chat.selection.isSelecting&&this.chat.selection.deleteSelectedMids(this.peerId,e),C.a.checkAnimations(!1,Xo),this.deleteEmptyDateGroups()}renderNewMessagesByIds(e,t){if(!this.scrollable.loadedAll.bottom)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()));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=this.scrollToBubbleEnd(t)||Promise.resolve();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=Object(Me.a)(e,"bubble");if("center"===t&&Object(Os.a)(n)===(this.stickyIntersector?2:1)){const s=n.parentElement;0===Object(Os.a)(s)&&(e=s,t="start")}const a=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(e,t,4,void 0,s,i,"y",a?({rect:e})=>{let t=Et.a.height;return t-=this.bubblesContainer.offsetTop,t-=b.b.isMobile||Et.a.height<570?58:78,t}:void 0)}scrollToBubbleEnd(e=this.getLastBubble()){if(e){this.scrollingToBubble=e;const t=this.getMiddleware();return this.scrollToBubble(e,"end",void 0,void 0).then(()=>{t()&&(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){e.parentElement.lastElementChild===e&&this.getLastDateGroup().parentElement.lastElementChild===e.parentElement&&this.scrollToBubbleEnd(e)}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=Object(x.i18n)(a?"Chat.Date.ScheduledForToday":"Date.Today");else if(a&&2147483646===e.date)t=Object(x.i18n)("MessageScheduledUntilOnline");else{const e={day:"numeric",month:"long"};s.getFullYear()!==n.getFullYear()&&(e.year="numeric"),t=new x.default.IntlDateElement({date:s,options:e}).element,a&&(t=Object(x.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 c=document.createElement("div");c.className="bubbles-date-group",c.append(o),this.dateMessages[i]={div:o,container:c,firstTimestamp:s.getTime()};const d=Object(w.e)(this.dateMessages,"asc");let h,p=0,u=d.length;for(;p<d.length;++p){const e=d[p];if(h=this.dateMessages[e].container,i<e)break}p===u&&h&&(h=h.nextElementSibling),h?this.chatInner.insertBefore(c,h):this.chatInner.append(c),this.stickyIntersector&&this.stickyIntersector.observeStickyHeaderChanges(c)}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.setLoaded("top",!1),this.setLoaded("bottom",!1),Object(os.c)(this.scrollable.container),Object(ks.d)(),void 0!==ra&&(ra=void 0),this.bubbles={},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.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.scrollingToBubble=void 0,this.isTopPaddingSet=!1}setPeer(e,t){var s;if(!e)return this.cleanup(!0),this.peerId=e,null;const i=this.peerId===e,n=this.chat.type;"scheduled"===n&&(t=0),this.historyStorage=this.appMessagesManager.getHistoryStorage(e,this.chat.threadId);let a="pinned"===n?this.appMessagesManager.pinnedMessages[e].maxId:null!==(s=this.historyStorage.maxId)&&void 0!==s?s:0;const o=void 0!==t;let r,l=0;o||(i||(r=this.chat.appImManager.getChatSavedPosition(this.chat)),r||a&&(l=this.appMessagesManager.getReadMaxIdIfUnread(e,this.chat.threadId),t=l&&!i?l:a));const c=t!==a,{scrollable:d}=this;if(i){const e=this.getMountedBubble(t);if(e)return o?(this.scrollToBubble(e.bubble,"center"),this.highlightBubble(e.bubble),this.chat.dispatchEvent("setPeer",t,!1)):a&&!c&&(d.scrollTop=d.scrollHeight,this.chat.dispatchEvent("setPeer",t,!0)),null}else this.peerId&&(this.lazyLoadQueue.queueId=++la,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)};de.b&&this.log("setPeer peerId:",e,this.historyStorage,t,a);const h=c||"scheduled"===n?0:a;let p=0;if(i){let e=this.getBubbleByPoint("bottom");e&&(p=+e.dataset.mid),p<=0&&(p=Math.max(...Object.keys(this.bubbles).map(e=>+e)))}else this.isFirstLoad=!0;const u=this.chatInner;this.cleanup();const m=this.chatInner=document.createElement("div");let g;i?(m.className=u.className,m.classList.remove("disable-hover","is-scrolling")):m.classList.add("bubbles-inner"),this.lazyLoadQueue.lock(),g=r?{promise:Object(ks.c)().then(()=>this.performHistoryResult(r.mids,!0,!1,void 0)),cached:!0}:this.getHistory(t,!0,c,h);const{promise:b,cached:v}=g;v||i||(d.container.textContent="",this.chat.finishPeerChange(o,c,t),this.preloader.attach(this.bubblesContainer)),C.a.lockGroup(Xo);const f=b.then(()=>{if(v?i||this.chat.finishPeerChange(o,c,t):this.preloader.detach(),this.resolveLadderAnimation&&(this.resolveLadderAnimation(),this.resolveLadderAnimation=void 0),d.lastScrollDirection=0,d.lastScrollTop=0,Object(k.a)(d.container,m),C.a.unlockGroup(Xo),C.a.checkAnimations(!1,Xo),this.lazyLoadQueue.unlock(),r)d.scrollTop=r.top;else if(a&&c||o){const e=p>0&&(p<t||t<0),s=l===t&&!o;!e&&i?d.scrollTop=99999:e&&(d.scrollTop=0);const n=this.getMountedBubble(t);let a=s&&this.firstUnreadBubble||(null==n?void 0:n.bubble);(null==a?void 0:a.parentElement)||(a=this.findNextMountedBubbleByMsgId(t)),a&&(this.scrollToBubble(a,s?"start":"center",i?void 0:wt.a.Static),s||this.highlightBubble(a))}else d.scrollTop=99999;this.onScroll();const s=this.getMiddleware(),h=Promise.all([f,Object(ks.c)()]);h.then(()=>{d.checkForTriggers()}),this.chat.dispatchEvent("setPeer",t,!c);const u=this.appMessagesManager.isFetchIntervalNeeded(e);if(r||u?h.then(()=>{if(s()&&(d.checkForTriggers(),u)){const t=()=>{this.fetchNewPromise=new Promise(i=>{s()&&this.appMessagesManager.isFetchIntervalNeeded(e)?this.appMessagesManager.getNewHistory(e,this.chat.threadId).then(e=>{if(!s()||!e)return void i();const n=e.history.slice.isEnd(Ln.a.Bottom);d.loadedAll.bottom&&d.loadedAll.bottom!==n&&(this.setLoaded("bottom",n),this.onScroll()),setTimeout(t,3e4),i()}):i()}).finally(()=>{this.fetchNewPromise=void 0})};i?setTimeout(t,3e4):t()}}):t&&!this.bubbles[a]&&t!==a||this.setLoaded("bottom",!0),this.log("scrolledAllDown:",d.loadedAll.bottom),d.loadedAll.bottom&&a&&!this.unreaded.size&&this.onScrolledAllDown(),"chat"===n){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:v,promise:f}}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.peerId,t=this.appPeersManager.isChannel(e),s=this.appMessagesManager.canSendToPeer(e,this.chat.threadId);this.chatInner.classList.toggle("has-rights",s),this.bubblesContainer.classList.toggle("is-chat-input-hidden",!s),this.chatInner.classList.toggle("is-chat",this.chat.isAnyGroup()),this.chatInner.classList.toggle("is-channel",t)}renderMessagesQueue(e,t,s,i){this.messagesQueue.push({message:e,bubble:t,reverse:s,promises:i}),this.setMessagesQueuePromise()}setMessagesQueuePromise(){!this.messagesQueuePromise&&this.messagesQueue.length&&(this.messagesQueuePromise=new Promise((e,t)=>{setTimeout(()=>{const s=this.messagesQueue.slice();this.messagesQueue.length=0;const i=s.reduce((e,{promises:t})=>e.concat(t),[]);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.id<0)return void this.chatInner.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;As(e,i.container,r)}else s?i.container.insertBefore(e,i.container.children[this.stickyIntersector?1:0].nextSibling):i.container.append(e);"message"===t._?this.bubbleGroups.addBubble(e,t,s):e.classList.add("is-group-first","is-group-last")}getMiddleware(){return this.middleware.get()}renderMessage(e,t=!1,s=!1,i=null,n=!0){var o,r;if(!i&&this.bubbles[e.mid])return;const d="pinned"!==this.chat.type;if(e.deleted)return;if(e.grouped_id&&d){const t=this.appMessagesManager.groupedMessagesStorage[e.grouped_id],s=Math.max(...t.keys());if(e.mid<s)return}const h=this.peerId,p=e.fromId===a.default.myId||e.pFlags.out&&this.appPeersManager.isMegagroup(this.peerId),u=document.createElement("div");let m,v;if(u.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(" "),v=i.lastElementChild,v.classList.contains("bubble-content-wrapper")||(v=i.querySelector(".bubble-content-wrapper")),m=v.firstElementChild,m.innerHTML="",m.style.cssText="",v.innerHTML="",v.appendChild(m);const a=v.style.transitionDelay;v.style.cssText="",v.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 if(v=document.createElement("div"),v.classList.add("bubble-content-wrapper"),m=document.createElement("div"),m.classList.add("bubble-content"),(i=document.createElement("div")).classList.add("bubble"),v.appendChild(m),i.appendChild(v),!p&&!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 f=[];if("messageService"===e._){Object(Hi.a)(e);const s=e.action;if(s){const t=s._;if(oa.has(t)||x.langPack.hasOwnProperty(t)&&!x.langPack[t])return this.skippedMids.add(+e.mid),i}i.className="bubble service",m.innerHTML="";const a=document.createElement("div");return a.classList.add("service-msg"),s&&("messageActionChannelMigrateFrom"===s._?a.append(Object(x.i18n)("ChatMigration.From",[new Lt.a({peerId:s.chat_id.toPeerId(!0)}).element])):"messageActionChatMigrateTo"===s._?a.append(Object(x.i18n)("ChatMigration.To",[new Lt.a({peerId:s.channel_id.toPeerId(!0)}).element])):a.append(this.appMessagesManager.wrapMessageActionTextNew(e))),m.append(a),n&&(this.renderMessagesQueue(e,i,t,f),e.pFlags.is_single&&i.classList.add("is-group-last")),i}let y,w,S=e.media;if((null==S?void 0:S.document)&&!["video","gif"].includes(S.document.type));else if(e.grouped_id&&d){const t=this.appMessagesManager.getAlbumText(e.grouped_id);y=t.message,w=t.totalEntities}else"sticker"!==(null===(o=null==S?void 0:S.document)||void 0===o?void 0:o.type)&&(y=e.message,w=e.totalEntities);let L=J.b.wrapRichText(y,{entities:w,passEntities:this.passEntities}),E=!0,C=!1,I=!0;if(w&&!S){let e=w.filter(e=>"messageEntityEmoji"===e._),t=y.length;if(e.reduce((e,t)=>e+t.length,0)===t&&e.length<=3){if(a.default.settings.emoji.big){let t=this.appStickersManager.getAnimatedEmojiSticker(y);if(1===e.length&&!S&&t)S={_:"messageMediaDocument",document:t};else{let t=document.createElement("div");t.classList.add("attachment"),t.innerHTML=L,i.classList.add("emoji-"+e.length+"x"),m.append(t)}i.classList.add("is-message-empty","emoji-big"),C=!0,E=!1,I=!1}i.classList.add("can-have-big-emoji")}}I&&g(u,L);const M=wn.setTime(this.chat,e,i,m,u);if(m.prepend(u),e.views&&!(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"),m.prepend(e),i.classList.add("with-beside-button")}if(e.views&&!e.pFlags.is_outgoing&&this.viewsObserver&&this.viewsObserver.observe(i),e.reply_markup&&"replyInlineMarkup"===e.reply_markup._&&e.reply_markup.rows&&e.reply_markup.rows.length){const t=e.reply_markup.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=J.b.wrapRichText(t.text,{noLinks:!0,noLinebreaks:!0});let i;switch(t._){case"keyboardButtonUrl":{const e=J.b.wrapRichText(" ",{entities:[{_:"messageEntityTextUrl",length:1,offset:0,url:t.url}]});i=Object(Vs.a)(e).firstElementChild,i.classList.add("is-link","tgico");break}case"keyboardButtonSwitchInline":i=document.createElement("button"),i.classList.add("is-switch-inline","tgico"),Object(l.b)(i,s=>{Object(c.a)(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)=>{new Ns({[this.peerId]:[]},t=>{e(t)},!0).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),Object(se.ripple)(i),n.append(i)}),s.append(n)}),Object(l.b)(s,s=>{let i=s.target;if(i.classList.contains("reply-markup-button")||(i=Object(Me.a)(i,"reply-markup-button")),!i||i.classList.contains("is-link")||i.classList.contains("is-switch-inline"))return;Object(c.a)(s);const n=Object(Os.a)(i),a=t[Object(Os.a)(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)}),E=!1,i.classList.add("with-reply-markup"),v.append(s)}const P=e.pFlags.is_outgoing;if(p){(e.pFlags.unread||P)&&this.unreadOut.add(e.mid);let t="";t=P?"is-sending":e.pFlags.unread||e.pFlags.is_scheduled?"is-sent":"is-read",i.classList.add(t)}const T=this.appMessagesManager.getMessageWithReplies(e),k=!!T&&e.mid>0;k&&i.classList.add("with-replies");const O=p&&(!e.fwd_from||this.peerId!==a.default.myId);let A=m;if(S){let t=document.createElement("div");t.classList.add("attachment"),y||i.classList.add("is-message-empty");let s=!1;switch(S._){case"messageMediaPhoto":{const s=S.photo;y||(E=!1),e.viaBotId||i.classList.add("hide-name"),i.classList.add("photo");const n=this.appMessagesManager.groupedMessagesStorage[e.grouped_id];if(e.grouped_id&&1!==n.size&&d){i.classList.add("is-album","is-grouped"),Ts({groupId:e.grouped_id,attachmentDiv:t,middleware:this.getMiddleware(),isOut:p,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:f,noAutoDownload:this.chat.noAutoDownloadMedia});break}const a=!re.IS_ANDROID&&E&&!k&&!1;a&&i.classList.add("with-media-tail"),Ls({photo:s,message:e,container:t,withTail:a,isOut:O,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:f,noAutoDownload:this.chat.noAutoDownloadMedia});break}case"messageMediaWebPage":{s=!0;let t=S.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 c=t.document;if(c)if("gif"===c.type||"video"===c.type||"round"===c.type){const t="round"===c.type?b.b.active.round:b.b.active.webpage;"round"===c.type?(i.classList.add("round"),o.classList.add("is-round")):i.classList.add("video"),ws({doc:c,container:o,message:e,boxWidth:t.width,boxHeight:t.height,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),isOut:O,group:Xo,loadPromises:f,noAutoDownload:this.chat.noAutoDownloadMedia})}else{const t=Ss({message:e,noAutoDownload:this.chat.noAutoDownloadMedia,lazyLoadQueue:this.lazyLoadQueue,loadPromises:f});o.append(t),o.classList.add("preview-with-document")}let d,h=document.createElement("div");if(h.classList.add("quote-text"),a&&h.append(a),t.site_name){const e=J.b.wrapRichText(t.url),s=Object(Vs.a)(e).firstElementChild;s.classList.add("webpage-name"),g(s,J.b.wrapEmojiText(t.site_name)),h.append(s),d=s}if(t.rTitle){let e=document.createElement("div");e.classList.add("title"),g(e,t.rTitle),h.append(e),d=e}if(t.rDescription){let e=document.createElement("div");e.classList.add("text"),g(e,t.rDescription),h.append(e),d=e}if(r.append(h),l&&!c){i.classList.add("photo");const t=l.sizes[l.sizes.length-1];let s=!1;t.w===t.h&&d?(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"),Ls({photo:l,message:e,container:o,boxWidth:s?0:b.b.active.webpage.width,boxHeight:s?0:b.b.active.webpage.height,isOut:O,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:f,withoutPreloader:s,noAutoDownload:this.chat.noAutoDownloadMedia})}n.append(r),u.insertBefore(n,M);break}case"messageMediaDocument":{const n=S.document;if(n.sticker){i.classList.add("sticker"),E=!1,C=!0,n.animated&&i.classList.add("sticker-animated");const e=b.b.active,s=i.classList.contains("emoji-big")?e.emojiSticker:n.animated?e.animatedSticker:e.staticSticker;this.appPhotosManager.setAttachmentSize(n,t,s.width,s.height),m.style.height=t.style.height,m.style.width=t.style.width,Cs({doc:n,div:t,middleware:this.getMiddleware(),lazyLoadQueue:this.lazyLoadQueue,group:Xo,play:!0,loop:!0,emoji:i.classList.contains("emoji-big")?y:void 0,withThumb:!0,loadPromises:f})}else if("video"===n.type||"gif"===n.type||"round"===n.type){const s="round"===n.type;s&&(C=!0),!s&&y||(E=!1),e.viaBotId||i.classList.add("hide-name"),i.classList.add(s?"round":"video");const a=this.appMessagesManager.groupedMessagesStorage[e.grouped_id];if(e.grouped_id&&1!==a.size&&d)i.classList.add("is-album","is-grouped"),Ts({groupId:e.grouped_id,attachmentDiv:t,middleware:this.getMiddleware(),isOut:p,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:f,noAutoDownload:this.chat.noAutoDownloadMedia});else{const a=!re.IS_ANDROID&&!re.IS_APPLE&&!s&&E&&!k&&!1;a&&i.classList.add("with-media-tail"),ws({doc:n,container:t,message:e,boxWidth:b.b.active.regular.width,boxHeight:b.b.active.regular.height,withTail:a,isOut:O,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),group:Xo,loadPromises:f,noAutoDownload:this.chat.noAutoDownloadMedia,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,noAutoDownload:o,lazyLoadQueue:r,searchContext:l,useSearch:c}){let d;const h=e?n.getMidsByMid(t.mid):[t.mid];return h.forEach((e,t)=>{const s=n.getMessage(e),c=Ss({message:s,loadPromises:a,noAutoDownload: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=J.b.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&&(d=u)}u.append(c),p.append(u),i.append(p)}),h.length>1&&s.classList.add("is-multiple-documents","is-grouped"),d}({albumMustBeRenderedFull:d,message:e,bubble:i,messageDiv:u,chat:this.chat,loadPromises:f,noAutoDownload:this.chat.noAutoDownloadMedia,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&&(A=t);const a=u.lastElementChild.querySelector(".document-message, .document-size, .audio");a&&a.append(M.cloneNode(!0)),i.classList.remove("is-message-empty"),u.classList.add((["photo","pdf"].includes(n.type)?"document":n.type||"document")+"-message"),s=!0}break}case"messageMediaContact":{const t=document.createElement("div");t.classList.add("contact"),t.dataset.peerId=""+S.user_id,u.classList.add("contact-message"),s=!0;const n=[];e.media.first_name&&n.push(J.b.wrapEmojiText(e.media.first_name)),e.media.last_name&&n.push(J.b.wrapEmojiText(e.media.last_name)),t.innerHTML=`\n <div class="contact-details">\n <div class="contact-name">${n.join(" ")}</div>\n <div class="contact-number">${e.media.phone_number?"+"+Object(Us.a)(e.media.phone_number).formatted:"Unknown phone number"}</div>\n </div>`;const a=new ur;a.lazyLoadQueue=this.lazyLoadQueue,a.setAttribute("peer",""+e.media.user_id),a.classList.add("contact-avatar","avatar-54"),t.prepend(a),i.classList.remove("is-message-empty"),u.classList.add("contact-message"),u.append(t);break}case"messageMediaPoll":{i.classList.remove("is-message-empty");const t=function(e){const t=new as;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);u.prepend(t),u.classList.add("poll-message");break}default:i.classList.remove("is-message-empty"),u.innerHTML='<i class="media-not-supported">This message is currently not supported on Telegram Web. Try <a href="https://desktop.telegram.org/" target="_blank">desktop.telegram.org</a></i>',u.append(M),this.log.warn("unrecognized media type:",e.media._,e)}s||m.append(t)}C&&i.classList.add("just-media"),this.chat.selection.isSelecting&&this.chat.selection.toggleElementCheckbox(i,!0);let _="";const F=e.fromId!==a.default.myId&&this.appPeersManager.isAnyChat(h)&&!this.appPeersManager.isBroadcast(h)||e.viaBotId;if(F||e.fwd_from||e.reply_to_mid){let t,s;const n=e.from_id&&"peerChannel"===e.from_id._&&e.fromId===e.fwdFromId;let o,r=e.fwd_from&&!e.fwd_from.from_id&&!e.fwd_from.channel_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=J.b.wrapEmojiText(e.fwd_from.from_name),t.classList.add("peer-title"),i.classList.add("hidden-profile")):t=new Lt.a({peerId:e.fwdFromId||e.fromId}).element,e.reply_to_mid&&e.reply_to_mid!==this.chat.threadId&&wn.setReply({chat:this.chat,bubble:i,bubbleContainer:m,message:e}),e.fwdFromId||e.fwd_from)if(this.peerId===a.default.myId||n||i.classList.add("forwarded"),e.savedFrom&&(_=e.savedFrom,t.dataset.savedFrom=_),o=document.createElement("div"),t.dataset.peerId=e.fwdFromId,this.peerId!==a.default.myId&&this.peerId!==Be.c&&!n||C){const e=[t];C&&e.unshift(document.createElement("br")),o.append(Object(x.i18n)("ForwardedFrom",[e]))}else o.style.color=this.appPeersManager.getPeerColorById(e.fwdFromId,!1),o.append(t);else e.viaBotId||(!C&&F?(o=document.createElement("div"),o.append(t),p||(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(Object(x.i18n)("ViaBot")," ",s),e.classList.add("is-via"),o.append(e)}o&&(o.classList.add("name"),A.append(o));if(this.chat.isAnyGroup()&&!O){let t=new ur;t.lazyLoadQueue=this.lazyLoadQueue,t.classList.add("user-avatar","avatar-40"),t.loadPromises=f,!e.fwdFromId&&e.fwd_from&&e.fwd_from.from_name&&t.setAttribute("peer-title",e.fwd_from.from_name),t.setAttribute("peer",""+((e.fwd_from&&(this.peerId===a.default.myId||this.peerId===Be.c)||n?e.fwdFromId:e.fromId)||Be.b)),v.append(t)}}else i.classList.add("hide-name");"pinned"===this.chat.type&&(_=`${this.chat.peerId}_${e.mid}`);if(T&&T.mid===this.chat.threadId&&i.classList.add("is-thread-starter","is-group-last"),_&&("pinned"===this.chat.type||e.fwd_from.saved_from_msg_id)&&this.peerId!==Be.c){const e=document.createElement("div");e.classList.add("bubble-beside-button","goto-original","tgico-arrow_next"),m.append(e),i.dataset.savedFrom=_,i.classList.add("with-beside-button")}if(i.classList.add(O?"is-out":"is-in"),n&&this.renderMessagesQueue(e,i,t,f),k){wn.renderReplies({bubble:i,bubbleContainer:m,message:T,messageDiv:u,loadPromises:f,lazyLoadQueue:this.lazyLoadQueue})&&(E=!0)}return E&&(i.classList.add("can-have-tail"),m.append(da())),i}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 aa(this,void 0,void 0,(function*(){let s;e=e.slice(),i&&e.unshift(i),this.messagesQueueOnRender=()=>{const{scrollTop:e,scrollHeight:i}=this.scrollable;s=t?i-e:e,this.messagesQueueOnRender=void 0},this.needReflowScroll&&(Cn(this.scrollable.container),this.needReflowScroll=!1);const n=e=>{const s=this.chat.getMessage(e);s.id>0?this.safeRenderMessage(s,t,!0):this.processLocalMessageRender(s)},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(Ln.a.Bottom)||s.length&&!e.includes(s[0])||this.setLoaded("bottom",!0,!1),!i.isEnd(Ln.a.Top)||i.length&&!e.includes(i[i.length-1])||this.setLoaded("top",!0,!1)}else this.setLoaded("top",!0),this.setLoaded("bottom",!0);if(yield this.messagesQueuePromise,this.scrollable.loadedAll.top&&this.messagesQueueOnRenderAdditional&&(this.messagesQueueOnRenderAdditional(),this.messagesQueueOnRenderAdditional&&this.messagesQueueOnRenderAdditional()),void 0!==s){const e=t?this.scrollable.scrollHeight-s:s;this.scrollable.scrollTop=e,re.IS_SAFARI&&Cn(this.scrollable.container)}return!0}))}requestHistory(e,t,s){if("chat"===this.chat.type||"discussion"===this.chat.type)return this.appMessagesManager.getHistory(this.peerId,e,t,s,this.chat.threadId);if("pinned"===this.chat.type){return this.appMessagesManager.getSearch({peerId:this.peerId,inputFilter:{_:"inputMessagesFilterPinned"},maxId:e,limit:t,backLimit:s}).then(e=>({history:e.history.map(e=>e.mid)}))}return"scheduled"===this.chat.type?this.appMessagesManager.getScheduledMessages(this.peerId).then(e=>({history:e.slice().reverse()})):void 0}animateAsLadder(e,t,s,i,n){return aa(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=Object(w.e)(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],c=s?[]:o.slice(0,o.findIndex(e=>a>=e)).reverse();de.b&&this.log("getHistory: targeting mid:",a,n,e,r.map(e=>this.appMessagesIdsManager.getServerMessageId(e)),c.map(e=>this.appMessagesIdsManager.getServerMessageId(e)));const d=[];this.chatInner.classList.add("zoom-fading");const h=s?10:40,p=s?0:1,u=(e,t=0)=>{const s=Object(ae.a)();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)}d.push(o)}),e.length||s.resolve(),{lastMsDelay:i,animationPromise:s}},m=u(r,p),g=u(l),b=u(c,p),v=[m.animationPromise,g.animationPromise,b.animationPromise],f=[m.lastMsDelay,g.lastMsDelay,b.lastMsDelay];let y;return this.onAnimateLadder&&(yield this.onAnimateLadder()),Object(De.b)(()=>{d.forEach(e=>{e.classList.remove("zoom-fade")})}),(r.length||l.length||c.length)&&(y=Promise.all(v),Object(ks.b)(y,Math.max(...f)+200).then(()=>{Object(De.b)(()=>{d.forEach(e=>{e.style.transitionDelay=""}),this.chatInner.classList.remove("zoom-fading")}),re.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=Object(x.i18n)("GroupEmptyTitle1"):"saved"===e?a=Object(x.i18n)("ChatYourSelfTitle"):"noMessages"===e||"greeting"===e?a=Object(x.i18n)("NoMessages"):"noScheduledMessages"===e&&(a=Object(x.i18n)("NoScheduledMessages")),a.classList.add("center",n+"-title"),i.push(a),"group"===e)i.push(Object(x.i18n)("GroupEmptyTitle2")),o=[Object(x.i18n)("GroupDescription1"),Object(x.i18n)("GroupDescription2"),Object(x.i18n)("GroupDescription3"),Object(x.i18n)("GroupDescription4")];else if("saved"===e)o=[Object(x.i18n)("ChatYourSelfDescription1"),Object(x.i18n)("ChatYourSelfDescription2"),Object(x.i18n)("ChatYourSelfDescription3"),Object(x.i18n)("ChatYourSelfDescription4")];else if("greeting"===e){const e=Object(x.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 Cs({doc:e,div:a,middleware:o,lazyLoadQueue:this.lazyLoadQueue,group:Xo,play:!0,loop:!0,withThumb:!0,loadPromises:t}),Object(l.b)(a,e=>{Object(c.a)(e),sa.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=this.safeRenderMessage(e,void 0,void 0,void 0,!1);t.classList.add("bubble-first","is-group-last","is-group-first"),t.classList.remove("can-have-tail","is-in");const s=t.querySelector(".message, .service-msg"),i=[],n=this.appPeersManager.isBot(this.peerId);if(n&&"message"===e._){const e=document.createElement("b");e.append(Object(x.i18n)("BotInfoTitle")),i.push(e,"\n\n")}else this.appPeersManager.isAnyGroup(this.peerId)&&this.appPeersManager.getPeer(this.peerId).pFlags.creator?this.renderEmptyPlaceholder("group",t,e,i):"scheduled"===this.chat.type?this.renderEmptyPlaceholder("noScheduledMessages",t,e,i):a.default.myId===this.peerId?this.renderEmptyPlaceholder("saved",t,e,i):this.appPeersManager.isUser(this.peerId)&&!n&&this.appMessagesManager.canSendToPeer(this.peerId)&&"chat"===this.chat.type?this.renderEmptyPlaceholder("greeting",t,e,i):this.renderEmptyPlaceholder("noMessages",t,e,i);s.prepend(...i),this.messagesQueueOnRenderAdditional?this.onAnimateLadder=()=>{if(this.chatInner.prepend(t),this.onAnimateLadder=void 0,!this.messagesQueuePromise)return Object(De.d)()}:this.chatInner.prepend(t),this.emptyPlaceholderMid=e.mid}generateLocalFirstMessage(e,t){const s=this.appMessagesIdsManager.generateMessageId("scheduled"===this.chat.type?-1:0),i={_:e?"messageService":"message",date:0,id:-(+this.peerId+s),peer_id:this.appPeersManager.getOutputPeer(this.peerId),pFlags:{}};return e||(i.message=""),Object(Hi.a)(i),t&&t(i),this.appMessagesManager.saveMessages([i]),i}setLoaded(e,t,s=!0){if(this.scrollable.loadedAll[e]!==t){if(this.scrollable.loadedAll[e]=t,"top"===e&&t&&this.appPeersManager.isBot(this.peerId)){this.log("inject bot description");const e=this.getMiddleware();return 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.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=Math.min(30,Et.a.height/38|0),l=Object.keys(this.bubbles).length>0?Math.max(40,r):r;let c=l;if(void 0!==ra){if(!ra)return{cached:!1,promise:Promise.resolve(!0)};Object.keys(this.bubbles).length>0&&--ra}let d,h=0;if(s&&(h=c,t||(c=0)),i&&!s)if("pinned"===this.chat.type)d=[i];else{const t=this.appMessagesManager.getHistoryStorage(o,this.chat.threadId).history.slice;if(t.length<c&&!t.isEnd(Ln.a.Both)){d=t.slice();for(let e=d.length-1;e>=0;--e){if(!this.chat.getMessage(d[e]).grouped_id)break;d.splice(e,1)}e=d[d.length-1]||e}}let p,u=this.requestHistory(e,c,h);const m=(null==d?void 0:d.length)&&u instanceof Promise,g=this.isFirstLoad&&h&&u instanceof Promise||m;m&&(p=u,u={history:d}),this.isFirstLoad=!1;const b=e=>aa(this,void 0,void 0,(function*(){if("offsetIdOffset"in e&&e.history.isEnd(Ln.a.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)}})),v=e=>Object(ks.c)().then(()=>b(e)).then(()=>this.performHistoryResult(e.history||[],t,s,!m&&i)),f=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):v(e),e=>{throw this.log.error("getHistory error:",e),e});return s};let y,S;if(u instanceof Promise)S=!1,y=f(u);else{if(n)return null;S=!0,y=v(u)}const L=m?f(p):y;if(g&&a.default.settings.animationsEnabled){let s=m?2:1;this.messagesQueueOnRenderAdditional=()=>{if(this.log("ship went past rocks of magnets"),--s)return;this.messagesQueueOnRenderAdditional=void 0;(this.animateAsLadder(i,d,m,h,e)||Promise.resolve()).then(()=>{setTimeout(()=>{this.loadMoreHistory(t,!0)},0)})}}else this.messagesQueueOnRenderAdditional=void 0;return t?this.getHistoryTopPromise=L:this.getHistoryBottomPromise=L,L.then(()=>{t?this.getHistoryTopPromise=void 0:this.getHistoryBottomPromise=void 0}),n?null:(!g&&y.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=Object(w.e)(this.bubbles));const s=2*l;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))}),y.then(()=>{"chat"===this.chat.type&&setTimeout(()=>{t?this.loadMoreHistory(!0,!0):this.loadMoreHistory(!1,!0)},0)}),{cached:S,promise:y})}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;for(const t in this.dateMessages){const s=this.dateMessages[t];s.container.childElementCount===e&&(s.container.remove(),this.stickyIntersector&&this.stickyIntersector.unobserve(s.container,s.div),delete this.dateMessages[t])}this.checkIfEmptyPlaceholderNeeded()}}function da(){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 ha{constructor(e,t,s,n){var r;let l,c,d,h=[],p=[];const u=o.a.canPinMessage(e),m=(a,o,r)=>{setTimeout(()=>{let a;a=s&&!t?u?i.a.unpinAllMessages(e):i.a.hidePinnedMessages(e):i.a.updatePinnedMessage(e,t,s,r,o),n&&a.then(n)},300)};if(s){let s="UnpinMessage";t?(l="UnpinMessageAlertTitle",c="Chat.Confirm.Unpin"):u?(l="Popup.Unpin.AllTitle",c="Chat.UnpinAllMessagesConfirmation",d=[""+((null===(r=i.a.pinnedMessages[e])||void 0===r?void 0:r.count)||1)]):(l="Popup.Unpin.HideTitle",c="Popup.Unpin.HideDescription",s="Popup.Unpin.Hide"),h.push({langKey:s,isDanger:!0,callback:m})}else{l="PinMessageAlertTitle";const t="PinMessage";e.isAnyChat()?(h.push({langKey:t,callback:e=>m(0,!1,!e.size)}),K.a.isBroadcast(e.toChatId())?c="PinMessageAlertChannel":(c="PinMessageAlert",p.push({text:"PinNotify",checked:!0}))):(c="PinMessageAlertChat",e===a.default.myId?h.push({langKey:t,callback:m}):(h.push({langKey:t,callback:e=>m(0,!e.size)}),p.push({text:"PinAlsoFor",textArgs:[new Lt.a({peerId:e}).element],checked:!0})))}Object(ut.a)(h);new gt("popup-delete-chat",{peerId:e,titleLangKey:l,descriptionLangKey:c,descriptionLangArgs:d,buttons:h,checkboxes:p}).show()}}function pa(e=window.getSelection()){if(!e||!e.rangeCount)return!0;const t=e.getRangeAt(0);return!t.toString()||!t.START_TO_END}class ua 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.a.reportMessages(e,t,s,o.value).then(e=>{e&&ct({langPackKey:"ReportSentInfo"})}))}}],body:!0});const a=document.createElement("div");Cs({doc:us.getAnimatedEmojiSticker(ua.STICKER_EMOJI),div:a,emoji:ua.STICKER_EMOJI,width:100,height:100,loop:!1,play:!0}).finally(()=>{this.show()}),this.header.append(a);const o=new _.b({label:"ReportHint",maxLength:512,placeholder:"ReportChatDescription"});o.input.addEventListener("input",()=>{this.buttons[0].element.toggleAttribute("disabled",!o.isValid())}),this.body.append(o.container)}}ua.STICKER_EMOJI="👮‍♀️";class ma 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=Object(U.a)("btn-primary btn-transparent",{text:e[0]});this.body.append(t)});const n=us.preloadAnimatedEmojiSticker(ua.STICKER_EMOJI);Object(l.b)(this.body,a=>{const o=Object(Me.a)(a.target,"btn-primary"),r=i[Object(Os.a)(o)][1];n.then(()=>{this.hide(),new ua(e,t,r,s)})},{listenerSetter:this.listenerSetter}),this.body.style.margin="0 -1rem",this.buttonsEl.style.marginTop=".5rem",this.show()}}class ga{constructor(e,t,s,i,n,a,o){this.attachTo=e,this.chat=t,this.appMessagesManager=s,this.appPeersManager=i,this.appPollsManager=n,this.appDocsManager=a,this.appMessagesIdsManager=o,this.onSendScheduledClick=()=>{this.chat.selection.isSelecting?Object(l.d)(this.chat.selection.selectionSendNowBtn):new Gs(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=()=>{if(pa()){nt((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())}else document.execCommand("copy")},this.onCopyAnchorLinkClick=()=>{nt(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"),lt(x.default.format(i,!0)),nt(n)},this.onPinClick=()=>{new ha(this.peerId,this.mid)},this.onUnpinClick=()=>{new ha(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)Object(l.d)(this.chat.selection.selectionForwardBtn);else{const e=this.isTargetAGroupedItem?[this.mid]:this.chat.getMidsByMid(this.mid);new Ns({[this.peerId]:e})}},this.onSelectClick=()=>{this.chat.selection.toggleByElement(Object(Me.a)(this.target,"grouped-item")||Object(Me.a)(this.target,"bubble"))},this.onClearSelectionClick=()=>{this.chat.selection.cancelSelection()},this.onDeleteClick=()=>{this.chat.selection.isSelecting?Object(l.d)(this.chat.selection.selectionDeleteBtn):new zs(this.peerId,this.isTargetAGroupedItem?[this.mid]:this.chat.getMidsByMid(this.mid),this.chat.type)};const r=e=>{let s,i;this.init&&(this.init(),this.init=null);try{i=Object(Me.a)(e.target,"bubble-content-wrapper"),s=i?i.parentElement:Object(Me.a)(e.target,"bubble")}catch(e){}if(!s||s.classList.contains("bubble-first"))return;if((e instanceof MouseEvent||e.hasOwnProperty("preventDefault"))&&e.preventDefault(),this.element.classList.contains("active"))return!1;(e instanceof MouseEvent||e.hasOwnProperty("cancelBubble"))&&(e.cancelBubble=!0);let n=+s.dataset.mid;if(!n)return;if(this.isSelectable=this.chat.selection.canSelectBubble(s),this.peerId=this.chat.peerId,this.target=e.target,this.isTextSelected=!pa(),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"),t.selection.isSelecting&&!i){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)}}const a=Object(Me.a)(this.target,"grouped-item");this.isTargetAGroupedItem=!!a,this.mid=a?+a.dataset.mid:n,this.isSelected=this.chat.selection.isMidSelected(this.peerId,this.mid),this.message=this.chat.getMessage(this.mid),this.buttons.forEach(e=>{let s;t.selection.isSelecting&&!e.withSelection?s=!1:(i||ue.IS_TOUCH_SUPPORTED,s=e.verify()),e.element.classList.toggle("hide",!s)});const o=s.classList.contains("is-in")?"left":"right";Object(te.e)(e.touches?e.touches[0]:e,this.element,o),Object(te.d)(this.element,()=>{this.mid=0,this.peerId=void 0,this.target=null})};ue.IS_TOUCH_SUPPORTED?Object(l.b)(e,e=>{if(t.selection.isSelecting)return;const s=e.target.className;if(!s||!s.includes)return;t.log("touchend",e);["bubble","bubble-content-wrapper","bubble-content","message","time","inner"].find(e=>s.match(new RegExp(e+"($|\\s)")))&&(Object(c.a)(e),r(e))},{listenerSetter:this.chat.bubbles.listenerSetter}):Object(te.a)(e,r,this.chat.bubbles.listenerSetter)}init(){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(()=>{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.appMessagesManager.canSendToPeer(this.peerId,this.chat.threadId)&&!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.message.message||this.isTextSelected||this.isAnchorTarget&&this.message.message===this.target.innerText)},{icon:"copy",text:"Chat.CopySelectedText",onClick:this.onCopyClick,verify:()=>!!this.message.message&&this.isTextSelected},{icon:"copy",text:"Message.Context.Selection.Copy",onClick:this.onCopyClick,verify:()=>{if(!this.isSelected)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:()=>{nt(this.target.innerHTML)},verify:()=>this.isUsernameTarget,withSelection:!0},{icon:"copy",text:"Text.Context.Copy.Hashtag",onClick:()=>{nt(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=!!ue.IS_TOUCH_SUPPORTED;const i=!t.type||!["gif","video","sticker"].includes(t.type);return i&&(s=s||!!Object(Me.a)(this.target,"document")||!!Object(Me.a)(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:()=>"scheduled"!==this.chat.type&&!this.message.pFlags.is_outgoing&&"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 ma(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},{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}],this.element=Ee(this.buttons,this.chat.bubbles.listenerSetter),this.element.id="bubble-contextmenu",this.element.classList.add("contextmenu"),this.chat.container.append(this.element)}}var ba=s(154),va=s.n(ba),fa=s(145);class ya{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=Ee(this.sendMenuButtons,e.listenerSetter),this.sendMenu.classList.add("menu-send",e.openSide),Object(te.a)(e.onContextElement,t=>{e.onOpen&&!e.onOpen()||(this.sendMenuButtons.forEach(e=>{e.element.classList.toggle("hide",!e.verify())}),Object(c.a)(t),Object(te.d)(this.sendMenu))},e.listenerSetter)}setPeerId(e){this.type=e===a.default.myId?"reminder":"schedule"}}var wa=s(69),Sa=s(90);class La extends ut.b{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=Object(ft.a)(t,"LABEL"),i=Object(Sa.a)(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=Object(ft.a)(t,"LABEL"),i=Object(Os.a)(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);x.default.weakMap.get(e.label.firstElementChild).update()}),this.handleChange()},Object(x._i18n)(this.title,"NewPoll"),this.questionInputField=new _.b({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 ya({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"),Object(x._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"),Object(x._i18n)(n,"Settings"),this.chat.appPeersManager.isBroadcast(this.chat.peerId)||(this.anonymousCheckboxField=new mt.a({text:"NewPoll.Anonymous",name:"anonymous"}),this.anonymousCheckboxField.input.checked=!0,i.append(this.anonymousCheckboxField.label)),this.multipleCheckboxField=new mt.a({text:"NewPoll.MultipleChoice",name:"multiple"}),this.quizCheckboxField=new mt.a({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"),Object(x._i18n)(o,"AccDescrQuizExplanation");const r=document.createElement("hr"),c=document.createElement("div");c.classList.add("poll-create-questions"),this.quizSolutionField=new _.b({placeholder:"NewPoll.Explanation.Placeholder",label:"NewPoll.Explanation.Placeholder",name:"solution",maxLength:200}),this.listenerSetter.add(this.questionInputField.input)("input",()=>{this.handleChange()});const d=document.createElement("div");d.classList.add("subtitle"),Object(x._i18n)(d,"AddAnExplanationInfo"),c.append(this.quizSolutionField.container,d),a.push(r,o,c),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),Object(l.b)(this.btnConfirm,this.onSubmitClick,{listenerSetter:this.listenerSetter}),this.scrollable=new T.b(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:Object(wa.a)(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}=Object(wa.a)(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}=Object(wa.a)(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,{threadId:this.chat.threadId,replyToMsgId:this.chat.input.replyToMsgId,scheduleDate:this.chat.input.scheduleDate,silent:this.chat.input.sendSilent}),"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 _.b({placeholder:"NewPoll.OptionsAddOption",label:"NewPoll.OptionLabel",labelOptions:[t],name:"question-"+e,maxLength:100});this.listenerSetter.add(s.input)("input",this.onInput);const i=new ot({text:"",name:"question"});i.main.append(s.container),Object(l.b)(s.input,c.a,{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=Object(Os.a)(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),Object(l.b)(n,this.onDeleteClick,{listenerSetter:this.listenerSetter,once:!0}),this.questions.append(i.label),this.scrollable.scrollIntoViewNew(this.questions.lastElementChild,"center"),this.optionInputFields.push(s)}}var Ea=s(100);function Ca(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 Ia;function Ma(){return Ia}class Pa extends ut.b{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(),Object(Ea.a)(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},Object(l.b)(this.btnConfirm,()=>this.send(),{listenerSetter:this.listenerSetter}),"scheduled"!==this.chat.type){const e=new ya({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 T.b(null);i.container.append(this.mediaContainer),this.inputField=new _.b({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=[],Ia=void 0}),Ia=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 mt.a({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=>m.has(e.type));t&&!this.mediaCheckboxField?(this.mediaCheckboxField=new mt.a({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 lt(x.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,{sendSilent:l,scheduleDate:c}=r;i.forEach(e=>{e.itemDiv=void 0});const{length:d}=i,h=r.replyToMsgId;this.iterate(e=>{t&&e.length!==d&&(this.chat.appMessagesManager.sendText(o,t,{replyToMsgId:h,threadId:this.chat.threadId,silent:l,scheduleDate:c,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({caption:t,replyToMsgId:h,threadId:this.chat.threadId,isMedia:n,silent:l,scheduleDate:c,clearDraft:!0},i)),t=void 0}),r.replyToMsgId=this.chat.threadId,r.onMessageSent()}attachMedia(e,t,s){s.classList.add("popup-item-media");let i;if(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=Object(me.e)(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),Object(me.c)(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([Ca(n).then(e=>{t.duration=Math.ceil(e)}),Object(me.b)(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?J.b.wrapEmojiText(e.name):"",size:e.size,type:i?"photo":"doc"},o=he.a.getCacheContext(a);o.url=t.objectURL,o.downloaded=e.size;const r=Ss({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&&m.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))}Object(k.a)(t,Object(x.i18n)(i,n))}appendMediaToContainer(e,t){if(this.shouldCompress(t.file.type)){const s=Object(Un.a)(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)),Ps({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 Ta=["ArrowUp","ArrowDown"],ka=["ArrowLeft","ArrowRight"];function xa({list:e,type:t,onSelect:s,once:i,waitForKey:n}){const a=new Set("xy"===t?Ta.concat(ka):"x"===t?ka:Ta);let o;const r=()=>o||e.querySelector(".active")||e.firstElementChild,d=(e,s)=>{if(o===e)return;let i=!1;o&&(i=!0,o.classList.remove("active")),o=e,o&&(o.classList.add("active"),i&&m&&s&&Object(wt.b)(m,o,"center",void 0,void 0,void 0,100,"x"===t?"x":"y"))},h=(t,s)=>{let i;return i=s?t.nextElementSibling||e.firstElementChild:t.previousElementSibling||e.lastElementChild,i};let p;p="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):h(t,"ArrowRight"===s):(e,t)=>h(e,"ArrowRight"===t||"ArrowDown"===t);let u=s=>{const i=s.key;if(a.has(i)){if(Object(c.a)(s),e.childElementCount>1){let e=r();e=p(e,i),d(e,!0)}}else("Enter"===i||"xy"!==t&&"Tab"===i)&&(Object(c.a)(s),v(r()))};const m=Object(Me.a)(e,"scrollable");e.classList.add("navigable-list");const g=t=>{const s=Object(qs.a)(t.target,e);s&&d(s,!1)},b=t=>{Object(c.a)(t);const s=Object(qs.a)(t.target,e);s&&(d(s,!1),v(r()))},v=e=>{const t=s(e);(void 0!==t?!t:i)&&f()},f=()=>{document.removeEventListener("keydown",u,{capture:!0}),e.removeEventListener("mousemove",g),Object(l.c)(e,b)},y=()=>{n||d(e.firstElementChild,!1)};if(n){const e=u;u=t=>{t.key===n&&(Object(c.a)(t),document.removeEventListener("keydown",u,{capture:!0}),u=e,document.addEventListener("keydown",u,{capture:!0,passive:!1}),n=void 0,y())}}else y();return document.addEventListener("keydown",u,{capture:!0,passive:!1}),e.addEventListener("mousemove",g,{passive:!0}),Object(l.b)(e,b),{detach:f,resetTarget:y}}class Oa extends B.a{constructor(e){super(!1),this.hidden=!0,this.onVisible=()=>{this.detach&&this.detach();const e=this.list,{detach:t,resetTarget:s}=xa({list:e,type:this.listType,onSelect:this.onSelect,once:!0,waitForKey:this.waitForKey});this.detach=t,this.resetTarget=s,re.IS_MOBILE||this.navigationItem||(this.navigationItem={type:"autocomplete-helper",onPop:()=>{this.navigationItem=void 0,this.toggle(!0)},noBlurOnPop:!0},j.a.pushItem(this.navigationItem)),this.addEventListener("hidden",()=>{this.resetTarget=void 0,this.detach=void 0,e.innerHTML="",t(),this.navigationItem&&(j.a.removeItem(this.navigationItem),this.navigationItem=void 0)},{once:!0})},Object(w.g)(this,e),this.container=document.createElement("div"),this.container.classList.add("autocomplete-helper","z-depth-1"),e.appendTo.append(this.container),this.attachNavigation(),this.controller.addHelper(this)}attachNavigation(){this.addEventListener("visible",this.onVisible)}toggle(e,t=!1){this.init||(void 0===e&&(e=this.container.classList.contains("is-visible")&&!this.container.classList.contains("backwards")),this.hidden!==e?(this.hidden=e,e?(this.navigationItem&&(j.a.removeItem(this.navigationItem),this.navigationItem=void 0),t||this.controller.hideOtherHelpers(),this.detach&&this.detach()):(this.controller.hideOtherHelpers(this),this.dispatchEvent("visible")),Object(Jt.a)(this.container,"is-visible",!e,a.default.settings.animationsEnabled?200:0,()=>{this.hidden&&this.dispatchEvent("hidden")})):e||this.dispatchEvent("visible"))}}class Aa extends Oa{constructor(e,t){super({appendTo:e,controller:t,listType:"xy",onSelect:e=>!sa.onMediaClick({target:e},!0),waitForKey:"ArrowUp"}),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&&(b.b.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(),us.preloadAnimatedEmojiSticker(e),us.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*b.b.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=e+"px"},b.b.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 T.b(this.container),this.lazyLoadQueue=new ee.d,this.superStickerRenderer=new Gn(this.lazyLoadQueue,Xo)}}const _a=()=>{const e=new Date;return e.setHours(0,0,0,0),e},Fa=()=>{const e=new Date;return e.setFullYear(e.getFullYear()+1),e.setDate(e.getDate()-1),e};class Da extends bn{constructor(e,t,s){var i;if(super((i=e).getTime()>Fa().getTime()?new Date:i,t,{noButtons:!0,noTitle:!0,closable:!0,withConfirm:!0,minDate:_a(),maxDate:Fa(),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=Object(U.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"Schedule.SendWhenOnline"});this.body.append(e),Object(l.b)(e,()=>{t(2147483646),this.hide()})}}}var ja=s(142),Ba=s(86);function Ra(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;Object(Ba.a)(e,s,i,a,o,r),i.length&&s.push(i.join(""));let l=s.join("\n");const c=l.indexOf("");return-1!=c&&(l=l.substr(0,c)+l.substr(c+1)),l=l.replace(/\u00A0/g," "),r&&J.b.combineSameEntities(r),{value:l,entities:r,caretPos:c}}class Ua extends Oa{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"x",onSelect:e=>{s.onEmojiSelected(Bn(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 T.a(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=>{jn(e,this.list,!1,!0)})),this.waitForKey=t?"ArrowUp":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 Ha extends Oa{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"y",onSelect:i}),this.className=s,this.container.classList.add(Ha.BASE_CLASS,s)}init(){this.list=document.createElement("div"),this.list.classList.add(Ha.BASE_CLASS+"-list"),this.container.append(this.list),this.scrollable=new T.b(this.container),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.container.scrollTop=0},0)})}render(e){if(this.init){if(!e.length)return;this.init(),this.init=null}e.length&&(this.list.innerHTML="",e.forEach(e=>{const t=Ha.listElement({className:this.className,peerId:e.peerId,name:e.name,description:e.description});this.list.append(t)})),this.toggle(!e.length)}static listElement(e){const t=Ha.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 ur;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=J.b.wrapEmojiText(e.name):n.append(new Lt.a({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=J.b.wrapEmojiText(e.description),s.append(i)}return s}}Ha.BASE_CLASS="autocomplete-peer-helper",Ha.BASE_CLASS_LIST_ELEMENT=Ha.BASE_CLASS+"-list-element";class Na extends Ha{constructor(e,t,s,i,n){super(e,t,"commands-helper",e=>{const t=e.querySelector(`.${Ha.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 this.appProfileManager.getProfileByPeerId(t).then(t=>{if(!s())return;const i=[].concat(t.bot_info),n=new Pn.a({ignoreCase:!0}),a=new Map;i.forEach(e=>{e.commands.forEach(t=>{const s="/"+t.command;a.set(t.command,{peerId:e.user_id.toPeerId(!1),name:s,description:t.description}),n.indexObject(t.command,s)})});const o=n.search(e),r=Array.from(o).map(e=>a.get(e));this.render(r)}),!0}}class za{constructor(){this.helpers=new Set,this.middleware=Object(xs.a)()}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 Va extends Ha{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 Ga=s(4);class Ka extends Zn{constructor(e){super({element:document.createElement("div")}),this.onBodyTouchStart=e=>{const t=e.touches[0].target;Object(qs.a)(t,this.element)||t===this.btnHover||(Object(c.a)(e),this.toggle(!1))},Object(w.g)(this,e),this.element.classList.add(Ka.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(),Object(ks.c)().then(()=>{this.checkForceReply()}))})}init(){return this.appendTo.append(this.element),this.listenerSetter.add(this)("open",()=>{this.render(),ue.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=Object(Me.a)(e.target,"btn");t&&(this.appMessagesManager.sendText(this.peerId,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(Ka.BASE_CLASS+"-row");for(const s of t.buttons){const t=document.createElement("button");t.classList.add(Ka.BASE_CLASS+"-button","btn"),t.innerHTML=J.b.wrapEmojiText(s.text),t.dataset.text=s.text,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()}}Ka.BASE_CLASS="reply-keyboard";var Wa=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 qa extends Oa{constructor(e,t,s,i,n){super({appendTo:e,controller:t,listType:"xy",onSelect:e=>{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,{clearDraft:!0,scheduleDate:this.chat.input.scheduleDate,silent:this.chat.input.sendSilent,replyToMsgId:this.chat.input.replyToMsgId}),this.chat.input.onMessageSent(!0,!0)})}}),this.chat=s,this.appUsersManager=i,this.appInlineBotsManager=n,this._checkQuery=(e,t,s)=>Wa(this,void 0,void 0,(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=>{var s;if(!i())throw"PEER_CHANGED";this.init&&(this.init(),this.init=null);const a=this.list.cloneNode();a.dataset.peerId=""+e,a.dataset.botId=""+n.id,a.dataset.queryId=""+t.query_id;const o=new Nn(null,"INLINE-HELPER",this.scrollable,!1);this.lazyLoadQueue.clear(),this.superStickerRenderer.clear();const r=[],c=!!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=c?void 0:document.createElement("div");if(n&&(n.classList.add("inline-helper-result-preview"),t.append(n)),a.append(t),c)t.classList.add("grid-item");else{n.classList.add("empty"),n.innerHTML=J.b.wrapEmojiText([...e.title.trim()][0]);const s=document.createElement("div");s.classList.add("inline-helper-result-title"),s.innerHTML=J.b.wrapEmojiText(e.title);const i=document.createElement("div");i.classList.add("inline-helper-result-description"),i.innerHTML=J.b.wrapRichText(e.description,{noCommands:!0,noLinks:!0}),t.append(s,i);const o=document.createElement("div");o.classList.add("inline-helper-separator"),a.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"),c&&s.classList.add("no-border-radius"),this.lazyLoadQueue.push({div:t,load:()=>he.a.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"),Object(ne.b)(e).then(e=>{Es(s,t,e,!0)})})})}}else{const a=e.document||e.photo;if(["sticker","gif"].includes(null===(s=a)||void 0===s?void 0:s.type)&&c)Object(Hi.a)(a),"gif"===a.type?o.add(a,t):"sticker"===a.type&&(t.classList.add("super-sticker"),this.superStickerRenderer.renderSticker(a,t,r),2===a.sticker&&this.superStickerRenderer.observeAnimatedDiv(t));else if(a){const e=c?48:void 0;c&&t.classList.add("no-border-radius"),Ls({photo:a,container:c?t:n,boxWidth:e,boxHeight:e,middleware:i,lazyLoadQueue:this.lazyLoadQueue,loadPromises:r})}}}return Promise.all(r).then(()=>{if(!i())return void o.clear();a.classList.toggle("is-gallery",c),a.classList.toggle("super-stickers",c),this.container.classList.toggle("is-gallery",c);const s=this.list.parentElement;if(s.textContent="",t.switch_pm){const i=Object(U.a)("btn-primary btn-secondary btn-primary-transparent primary");i.insertAdjacentHTML("beforeend",J.b.wrapEmojiText(t.switch_pm.text)),Object(l.b)(i,s=>{this.appInlineBotsManager.switchToPM(e,n.id,t.switch_pm.start_param)}),s.append(i)}s.append(this.list=a),this.gifsMasonry&&this.gifsMasonry.detach(),this.gifsMasonry=o,o.attach(),this.onChangeScreen||(this.onChangeScreen=()=>{if(this.list.classList.contains("is-gallery")){const e=this.list.childElementCount*b.b.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=e+"px"}else this.list.style.width=""},b.b.addEventListener("changeScreen",this.onChangeScreen)),this.onChangeScreen(),this.toggle(!t.results.length&&!t.switch_pm),this.scrollable.scrollTop=0})});return{user:n,renderPromise:a}})),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&&(b.b.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 T.b(this.container),this.lazyLoadQueue=new ee.d,this.superStickerRenderer=new Gn(this.lazyLoadQueue,"INLINE-HELPER")}}var Qa=s(3);class $a{constructor(e,t,s,i,n,o,r,d,h,p,u,m,g,b){this.chat=e,this.appMessagesManager=t,this.appMessagesIdsManager=s,this.appDocsManager=i,this.appChatsManager=n,this.appPeersManager=o,this.appWebPagesManager=r,this.appImManager=d,this.appDraftsManager=h,this.serverTimeManager=p,this.appNotificationsManager=u,this.appEmojiManager=m,this.appUsersManager=g,this.appInlineBotsManager=b,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&&Object(c.a)(e),this.recordCanceled=!0,this.recorder.stop(),fa.a.setKeepAlive(!1)},this.onEmoticonsOpen=()=>{const e=ue.IS_TOUCH_SUPPORTED?"flip-icon":"active";this.btnToggleEmoticons.classList.toggle(e,!0)},this.onEmoticonsClose=()=>{const e=ue.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 Da(t,t=>{if(!i())return;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)=>{Object(c.a)(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"};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),Object(c.a)(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}=Ra(this.messageInputField.input),a=J.b.parseMarkdown(s,i,!0),o=J.b.mergeEntities(i,J.b.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)&&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=ht.a.invokeApiHashable("messages.getWebPage",{url:t}).then(s=>{s=this.appWebPagesManager.saveWebPage(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"}))}else this.lastTimeType&&this.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageCancelAction"}),this.appImManager.markupTooltip&&this.appImManager.markupTooltip.hide();this.editMsgId||this.saveDraftDebounced(),this.checkAutocomplete(s,n,o),this.updateSendBtn()},this.onEmojiSelected=(e,t)=>{this.insertAtCaret(e,J.b.getEmojiEntityFromEmoji(e),t)},this.onBtnSendClick=e=>{if(Object(c.a)(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.appMessagesManager.canSendToPeer(this.chat.peerId,this.chat.threadId,"send_media"))return void lt("Posting media content isn't allowed in this group.");this.chatInput.classList.add("is-locked"),Object(Ks.a)(),this.recorder.start().then(()=>{this.releaseMediaPlayback=fe.setSingleMedia(),this.recordCanceled=!1,this.chatInput.classList.add("is-recording"),this.recording=!0,this.updateSendBtn(),fa.a.setKeepAlive(!0);const e=()=>{new gt("popup-cancel-record",{titleLangKey:"DiscardVoiceMessageTitle",descriptionLangKey:"DiscardVoiceMessageDescription",buttons:[{langKey:"DiscardVoiceMessageAction",callback:()=>{Object(l.d)(this.btnCancelRecord)}},{langKey:"Continue",isCancel:!0}]}).show()};this.recordingOverlayListener=this.listenerSetter.add(document.body)("mousedown",t=>{Object(Me.a)(t.target,"chat-input")||Object(Me.a)(t.target,"popup-cancel-record")||(Object(c.a)(t),e())},{capture:!0,passive:!1}),j.a.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,Object(De.b)(a)};a()}).catch(e=>{switch(e.name){case"NotAllowedError":lt("Please allow access to your microphone");break;case"NotReadableError":lt(e.message);break;default:console.error("Recorder start error:",e,e.name,e.message),lt(e.message)}this.chatInput.classList.remove("is-recording","is-locked")})}},this.onHelperCancel=(e,t)=>{if(e&&Object(c.a)(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=J.b.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(Object(c.a)(e),Object(Me.a)(e.target,"reply"))if("forward"===this.helperType){const{forwardElements:e}=this;e&&ue.IS_TOUCH_SUPPORTED&&!e.container.classList.contains("active")&&Object(te.d)(e.container)}else"reply"===this.helperType?this.chat.setMessageId(this.replyToMsgId):"edit"===this.helperType&&this.chat.setMessageId(this.editMsgId)},this.listenerSetter=new R.a}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.rowsWrapper=document.createElement("div"),this.rowsWrapper.classList.add("rows-wrapper","chat-input-wrapper");const e=da();this.rowsWrapper.append(e);const t=this.fakeRowsWrapper=document.createElement("div");t.classList.add("fake-wrapper","fake-rows-wrapper");const s=document.createElement("div");s.classList.add("fake-wrapper","fake-selection-wrapper"),this.inputContainer.append(this.rowsWrapper,t,s),this.chatInput.append(this.inputContainer),this.goDownBtn=Q({icon:"arrow_down",className:"bubbles-corner-button bubbles-go-down hide"}),this.inputContainer.append(this.goDownBtn),Object(l.b)(this.goDownBtn,e=>{Object(c.a)(e),this.chat.bubbles.onGoDownClick()},{listenerSetter:this.listenerSetter})}constructPeerHelpers(){this.replyElements.container=document.createElement("div"),this.replyElements.container.classList.add("reply-wrapper"),this.replyElements.iconBtn=H(""),this.replyElements.cancelBtn=H("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 mt.a({checked:!0})},s.hideSender={text:"Chat.Alert.Forward.Action.Hide1",onClick:e,checkboxField:new mt.a({checked:!1})},s.showCaption={text:"Chat.Alert.Forward.Action.ShowCaption",onClick:t,checkboxField:new mt.a({checked:!0})},s.hideCaption={text:"Chat.Alert.Forward.Action.HideCaption",onClick:t,checkboxField:new mt.a({checked:!1})},s.changePeer={text:"Chat.Alert.Forward.Action.Another",onClick:()=>{this.changeForwardRecipient()},icon:"replace"}],o=s.container=Ee(n,this.listenerSetter),r=Array.from(o.children);if([{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=x.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=tt(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),!ue.IS_TOUCH_SUPPORTED){this.forwardHover=new Zn({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.btnToggleEmoticons=H("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=Q({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),Object(l.b)(this.goMentionBtn,e=>{Object(c.a)(e),this.appMessagesManager.goToNextMention(this.chat.peerId)},{listenerSetter:this.listenerSetter}),this.btnScheduled=H("scheduled btn-scheduled float hide",{noRipple:!0}),Object(l.b)(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=H("botcom toggle-reply-markup float hide",{noRipple:!0}),this.replyKeyboard=new Ka({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.attachMenuButtons=[{icon:"image",text:"Chat.Input.Attach.PhotoOrVideo",onClick:()=>{this.fileInput.value="";const e=[...m].join(", ");this.fileInput.setAttribute("accept",e),this.willAttachType="media",this.fileInput.click()},verify:(e,t)=>this.appMessagesManager.canSendToPeer(e,t,"send_media")},{icon:"document",text:"Chat.Input.Attach.Document",onClick:()=>{this.fileInput.value="",this.fileInput.removeAttribute("accept"),this.willAttachType="document",this.fileInput.click()},verify:(e,t)=>this.appMessagesManager.canSendToPeer(e,t,"send_media")},{icon:"poll",text:"Poll",onClick:()=>{new La(this.chat).show()},verify:(e,t)=>e.isAnyChat()&&this.appMessagesManager.canSendToPeer(e,t,"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.btnToggleEmoticons,this.inputMessageContainer,this.btnScheduled,this.btnToggleReplyMarkup,this.attachMenu,this.recordTimeEl,this.fileInput].filter(Boolean)),this.rowsWrapper.append(this.replyElements.container),this.autocompleteHelperController=new za,this.stickersHelper=new Aa(this.rowsWrapper,this.autocompleteHelperController),this.emojiHelper=new Ua(this.rowsWrapper,this.autocompleteHelperController,this,this.appEmojiManager),this.commandsHelper=new Na(this.rowsWrapper,this.autocompleteHelperController,this,this.chat.appProfileManager,this.chat.appUsersManager),this.mentionsHelper=new Va(this.rowsWrapper,this.autocompleteHelperController,this,this.chat.appProfileManager,this.chat.appUsersManager),this.inlineHelper=new qa(this.rowsWrapper,this.autocompleteHelperController,this.chat,this.appUsersManager,this.appInlineBotsManager),this.rowsWrapper.append(this.newMessageWrapper),this.btnCancelRecord=H("delete danger 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=H("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 ya({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),na.attachButtonListener(this.btnToggleEmoticons,this.listenerSetter),this.listenerSetter.add(na)("open",this.onEmoticonsOpen),this.listenerSetter.add(na)("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()}),"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"))});try{this.recorder=new va.a({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 Pa(this.chat,Array.from(t).slice(),this.willAttachType),this.fileInput.value="")},!1),Object(l.b)(this.btnSend,this.onBtnSendClick,{listenerSetter:this.listenerSetter,touchMouseDown:!0}),this.recorder&&(Object(l.b)(this.btnCancelRecord,this.onCancelRecordClick,{listenerSetter:this.listenerSetter}),this.recorder.onstop=()=>{this.recording=!1,this.chatInput.classList.remove("is-recording","is-locked"),this.updateSendBtn(),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&&(j.a.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"});fa.a.decode(e,!0).then(e=>{fa.a.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)})}),Object(l.b)(this.replyElements.cancelBtn,this.onHelperCancel,{listenerSetter:this.listenerSetter}),Object(l.b)(this.replyElements.container,this.onHelperClick,{listenerSetter:this.listenerSetter}),this.saveDraftDebounced=dt(()=>this.saveDraft(),2500,!1,!0)}constructPinnedHelpers(){const e=document.createElement("div");e.classList.add("pinned-container"),this.pinnedControlBtn=Object(U.a)("btn-primary btn-transparent text-bold pinned-container-button",{icon:"unpin"}),e.append(this.pinnedControlBtn);const t=e.cloneNode(!0);this.fakePinnedControlBtn=t.firstChild,this.fakeRowsWrapper.append(t),this.listenerSetter.add(this.pinnedControlBtn)("click",()=>{const e=this.chat.peerId;new ha(e,0,!0,()=>{this.chat.appImManager.setPeer(Be.b);const e=this.chat.appImManager.chat;e.topbar.pinnedMessage&&e.topbar.pinnedMessage.pinnedMessageContainer.toggle(!0)})}),this.rowsWrapper.append(e),this.chatInput.classList.add("type-pinned"),this.rowsWrapper.classList.add("is-centered")}getReadyToSend(e){return"scheduled"===this.chat.type?(this.scheduleSending(e),!0):(e(),!1)}setUnreadCount(){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);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}=Object(wa.a)(this.messageInputField.input);let s;(e.length||this.replyToMsgId)&&(s={_:"draftMessage",date:Object(oe.g)(!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")),Ws(),this.lastTimeType=0,this.messageInput&&(this.clearInput(),e&&this.clearHelper())}setDraft(e,t=!0,s=!1){return!(!s&&!Object(Sa.a)(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(()=>{Object(De.b)(()=>{this.onMessageSent()})})),!1))}finishPeerChange(){const e=this.chat.peerId,{forwardElements:t,btnScheduled:s,replyKeyboard:i,sendMenu:n,goDownBtn:a,chatInput:o}=this;o.style.display="";const r=this.appPeersManager.isBroadcast(e);if(a.classList.toggle("is-broadcast",r),a.classList.remove("hide"),this.goDownUnreadBadge&&this.setUnreadCount(),"pinned"===this.chat.type&&o.classList.toggle("can-pin",this.appPeersManager.canPinMessage(e)),t&&(this.forwardWasDroppingAuthor=!1,t.showCaption.checkboxField.setValueSilently(!0),t.showSender.checkboxField.setValueSilently(!0)),s){s.classList.add("hide");const t=this.chat.bubbles.getMiddleware();this.appMessagesManager.getScheduledMessages(e).then(e=>{t()&&s.classList.toggle("hide",!e.length)})}i&&i.setPeer(e),n&&n.setPeerId(e),this.messageInput?this.updateMessageInput():this.pinnedControlBtn&&(this.appPeersManager.canPinMessage(this.chat.peerId)?(this.pinnedControlBtn.append(Object(x.i18n)("Chat.Input.UnpinAll")),this.fakePinnedControlBtn.append(Object(x.i18n)("Chat.Input.UnpinAll"))):(this.pinnedControlBtn.append(Object(x.i18n)("Chat.Pinned.DontShow")),this.fakePinnedControlBtn.append(Object(x.i18n)("Chat.Pinned.DontShow"))))}updateMessageInput(){const{chatInput:e,attachMenu:t,messageInput:s}=this,{peerId:i,threadId:n}=this.chat,a=this.appMessagesManager.canSendToPeer(i,n);e.classList.add("no-transition"),e.classList.toggle("is-hidden",!a),e.offsetLeft,e.classList.remove("no-transition");const o=x.default.weakMap.get(s);if(o){let e;e=n?"Comment":this.appPeersManager.isBroadcast(i)?"ChannelBroadcast":this.appMessagesManager.isAnonymousSending(i)?"SendAnonymously":"Message",o.key!==e&&(o.key=e,o.update())}const r=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",!r.length),t.classList.toggle("btn-disabled",!r.length),this.updateSendBtn()}attachMessageInputField(){const e=this.messageInputField;this.messageInputField=new _.b({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(),Qa.a&&Object(Qa.b)(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(Object(ja.a)(e))Object(c.a)(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 Object(Ea.a)(this.messageInput)}),ue.IS_TOUCH_SUPPORTED&&Object(l.b)(this.messageInput,e=>{this.appImManager.selectTab(1),na.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)};if(!s[e])return!1;const i=s[e],n=this.prepareDocumentExecute(),a=[];if(a.push(document.execCommand("styleWithCSS",!1,"true")),"monospace"===e){let t=!1;const s=window.getSelection();if(!s.isCollapsed){const i=s.getRangeAt(0),n=Ba.b[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}=Ra(this.messageInput),o=n>=0?n:i.length,r=i.substr(0,o),l=i.substr(o),c=s?r.match($a.AUTO_COMPLETE_REG_EXP):null,d=c?c.index+(c[0].length-c[2].length):r.length,h=r.slice(0,d)+e+l,p=J.b.parseEntities(i);J.b.mergeEntities(a,p);const u=t?Math.max(t.length,e.length):e.length,m=[];t&&(m.push(t),t.offset=d);const g=c?u-c[2].length:u;a.forEach(e=>{e.offset>=d&&(e.offset+=g)}),J.b.mergeEntities(a,m);{const e={_:"messageEntityCaret",offset:d+u,length:0};let t=0;for(let s=a.length;t<s;++t){if(a[t].offset>e.offset)break}a.splice(t,0,e)}const b=J.b.wrapDraftText(h,{entities:a});this.messageInputField.setValueSilently(b,!0);const v=this.messageInput.querySelector(".composer-sel");v&&(!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)}}(v),v.remove()),this.onMessageInput()}checkAutocomplete(e,t,s){if(void 0===e){const i=Ra(this.messageInputField.input,!0);e=i.value,t=i.caretPos,s=i.entities}if(-1===t&&(t=e.length),void 0===s){const t=J.b.parseMarkdown(e,s,!0);s=J.b.mergeEntities(s,J.b.parseEntities(t))}if(e=e.substr(0,t),this.previousQuery===e)return;this.previousQuery=e;const i=e.match($a.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.appMessagesManager.canSendToPeer(this.chat.peerId,this.chat.threadId,"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()?Be.b: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?Object(Jt.a)(this.btnPreloader,"show",!0,400):(this.btnPreloader=H("none btn-preloader float show disable-hover",{noRipple:!0}),Object(te.f)(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(()=>{Object(Jt.a)(this.btnPreloader,"show",!1,400)})}).catch(_e.a)}}return s||delete this.messageInput.dataset.inlinePlaceholder,t!==this.inlineHelper&&this.btnPreloader&&Object(Jt.a)(this.btnPreloader,"show",!1,400),t}changeForwardRecipient(){if(this.helperWaitingForward)return;this.helperWaitingForward=!0;const e=this.helperFunc;this.clearHelper(),this.updateSendBtn();let t=!1;new Ns(Object(w.a)(this.forwarding),()=>{t=!0}).addEventListener("close",()=>{this.helperWaitingForward=!1,t||e()})}clearInput(e=!0,t=!0,s=""){if(document.activeElement===this.messageInput&&re.IS_MOBILE_SAFARI){const e=document.createElement("input");document.body.append(e),Object(Ga.a)(e),this.messageInputField.setValueSilently(s),Object(Ga.a)(this.messageInput),e.remove()}else this.messageInputField.setValueSilently(s);ue.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 Object(Sa.a)(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;J.b.parseEntities(s).filter(e=>"messageEntityEmoji"===e._).forEach(e=>{const t=Object(ie.a)(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{threadId:i,peerId:n}=s,{replyToMsgId:a,noWebPage:o,sendSilent:r,scheduleDate:l}=this,{value:c,entities:d}=Object(wa.a)(this.messageInputField.input);if(t){const e=this.editMessage;if(!c.trim()&&!e.media)return void new zs(n,[t],s.type);this.appMessagesManager.editMessage(e,c,{entities:d,noWebPage:o}),this.onMessageSent()}else c.trim()&&(this.appMessagesManager.sendText(n,c,{entities:d,replyToMsgId:a,threadId:i,noWebPage:o,webPage:this.getWebPagePromise?void 0:this.willSendWebPage,scheduleDate:l,silent:r,clearDraft:!0}),this.onMessageSent(!1,!1));if(this.forwarding){const e=Object(w.a)(this.forwarding);setTimeout(()=>{for(const t in e)this.appMessagesManager.forwardMessages(n,t.toPeerId(),e[t],{silent:r,scheduleDate:l,dropAuthor:this.forwardElements&&this.forwardElements.hideSender.checkboxField.checked,dropCaptions:this.isDroppingCaptions()});c||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.appMessagesManager.canSendToPeer(this.chat.peerId,this.chat.threadId,n)?(lt("Posting media content isn't allowed in this group."),!1):"scheduled"!==this.chat.type||t?!!e&&(this.appMessagesManager.sendFile(this.chat.peerId,e,{isMedia:!0,replyToMsgId:this.replyToMsgId,threadId:this.chat.threadId,silent:this.sendSilent,scheduleDate:this.scheduleDate,clearDraft:s||void 0}),this.onMessageSent(s,!0),"sticker"===e.type&&(null===(i=na.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||Object(ft.a)(t.label,"FORM").classList.contains("hide")}isDroppingCaptions(){return!this.canToggleHideAuthor()}initMessageEditing(e){const t=this.chat.getMessage(e);let s=J.b.wrapDraftText(t.message,{entities:t.totalEntities});const i=()=>{const n=this.appMessagesManager.wrapMessageForReply(t,void 0,[t.mid]);this.setTopInfo("edit",i,Object(x.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?Object(x.i18n)("Chat.Accessory.Forward.You"):new Lt.a({peerId:t,dialog:!1,onlyFirstName:r}).element}return r?e.split(" ")[0]:e}),{forwardElements:c}=this;Object(ft.a)(c.showCaption.checkboxField.label,"FORM").classList.toggle("hide",!o);const d=c.hideCaption.checkboxField.checked;o&&d?c.hideSender.checkboxField.setValueSilently(!0):void 0!==this.forwardWasDroppingAuthor&&(this.forwardWasDroppingAuthor?c.hideSender:c.showSender).checkboxField.setValueSilently(!0);const h=c.showSender.checkboxField.checked?"Chat.Accessory.Forward":"Chat.Accessory.Hidden",p=Object(x.i18n)(h,[n]),u=document.createDocumentFragment();let m,g;if(l.length<3?u.append(...Object(x.join)(l,!1)):u.append(l[0],Object(x.i18n)("AndOther",[l.length-1])),1===s.length){const t=s[0],i=e[t];if(m=this.appMessagesManager.getMessageByPeer(t,i[0]),g=!!m.grouped_id,g){const e=this.appMessagesManager.getMidsByMessage(m);(e.length!==n||e.find(e=>!i.includes(e)))&&(g=!1)}}const b=document.createDocumentFragment();if(g||1===n){const t=e[s[0]],i=this.appMessagesManager.wrapMessageForReply(m,void 0,t);b.append(u,": ",i)}else b.append(Object(x.i18n)("Chat.Accessory.Forward.From"),": ",u);let v=this.setTopInfo("forward",t,p,b);c.modifyArgs.forEach((e,t)=>{const i=e.textElement,n=x.default.weakMap.get(i);n.args=[t<2?s.length:o],n.update()}),this.forwardHover&&this.forwardHover.attachButtonListener(v,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=Object(x.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 Lt.a({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")&&(j.a.removeByType("input-helper"),this.chat.container.classList.remove("is-helper-active"),this.t())}t(){Object(Jt.a)(this.chat.container,"is-toggling-helper",!0,150,()=>{this.chat.container.classList.remove("is-toggling-helper")})}setInputValue(e,t=!0,s=!0){e||(e=""),t?this.clearInput(!1,!1,e):this.messageInputField.setValueSilently(e),Object(De.b)(()=>{s&&Object(Ea.a)(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=H(("webpage"===e?"link":e)+" active reply-icon",{noRipple:!0}));const c=Ms(s,i,a);return l?r.replaceWith(c):o.insertBefore(c,o.lastElementChild),this.chat.container.classList.contains("is-helper-active")||(this.chat.container.classList.add("is-helper-active"),this.t()),re.IS_MOBILE||j.a.pushItem({type:"input-helper",onPop:()=>{this.onHelperCancel()}}),void 0!==n&&this.setInputValue(n),setTimeout(()=>{this.updateSendBtn()},0),c}}$a.AUTO_COMPLETE_REG_EXP=/(\s|^)((?:(?:@|^\/)\S*)|(?::|^[^:@\/])(?!.*[:@\/]).*)$/;class Ya{constructor(e){this.floating=!1,Object(w.g)(this,e);const{divAndCaption:t,className:s}=this;t.container.classList.add("pinned-container","hide"),t.title.classList.add("pinned-container-title"),t.subtitle.classList.add("pinned-container-subtitle"),t.content.classList.add("pinned-container-content"),this.btnClose=document.createElement("button"),this.btnClose.classList.add("pinned-container-close",`pinned-${s}-close`,"btn-icon","tgico-close"),this.wrapper=document.createElement("div"),this.wrapper.classList.add("pinned-container-wrapper"),Object(se.ripple)(this.wrapper),this.wrapperUtils=document.createElement("div"),this.wrapperUtils.classList.add("pinned-container-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){Object(l.b)(e,e=>{Object(c.a)(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||b.b.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 Xa extends Ya{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"audio",divAndCaption:new ze("pinned-audio",(e,t)=>{Object(k.a)(this.divAndCaption.title,e),Object(k.a)(this.divAndCaption.subtitle,t)}),onClose:()=>{fe.stop()},floating:!0}),this.topbar=e,this.chat=t,this.appMessagesManager=s,this.divAndCaption.border.remove();const i=H("pprevious active",{noRipple:!0}),n=H("nnext active",{noRipple:!0});i.innerHTML='<svg class="missing-icon" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet"><g><path class="missing-icon-path" d="M6 6h2v12H6zm3.5 6l8.5 6V6z"></path></g></svg>',n.innerHTML='<svg class="missing-icon" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet"><g><path class="missing-icon-path" d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"></path></g></svg>';const o=(e,t)=>{Object(l.b)(e,e=>{Object(c.a)(e),t()},{listenerSetter:this.topbar.listenerSetter})};o(i,()=>{fe.previous()}),o(n,()=>{fe.next()}),this.toggleEl=H("",{noRipple:!0}),this.toggleEl.classList.add("active","pinned-audio-ico","tgico"),o(this.toggleEl,()=>{fe.toggle()}),this.wrapper.prepend(this.wrapper.firstElementChild,i,this.toggleEl,n),this.volumeSelector=new xe(this.listenerSetter,!0);const r=document.createElement("div");r.classList.add("progress-line-container"),r.append(this.volumeSelector.container);const d=document.createElement("div");d.classList.add("pinned-audio-volume-tunnel"),this.volumeSelector.btn.classList.add("pinned-audio-volume","active"),this.volumeSelector.btn.prepend(d),this.volumeSelector.btn.append(r),this.wrapperUtils.prepend(this.volumeSelector.btn);const h=document.createElement("div");h.classList.add("pinned-audio-progress-wrapper"),this.progressLine=new ke(void 0,void 0,!0,!0),this.progressLine.container.classList.add("pinned-audio-progress"),h.append(this.progressLine.container),this.wrapper.insertBefore(h,this.wrapperUtils),this.topbar.listenerSetter.add(a.default)("media_play",({doc:e,message:t,media:s})=>{let i,n;"voice"===e.type||"round"===e.type?(i=new Lt.a({peerId:t.fromId}).element,n=Object(oe.d)(t.date)):(i=e.audioTitle||e.fileName,n=e.audioPerformer||Object(x.i18n)("AudioUnknownArtist")),this.progressLine.setMedia(s),this.fill(i,n,t),this.toggleEl.classList.add("flip-icon"),this.toggle(!1)}),this.topbar.listenerSetter.add(a.default)("media_pause",()=>{this.toggleEl.classList.remove("flip-icon")}),this.topbar.listenerSetter.add(a.default)("media_stop",()=>{this.toggle(!0)})}}var Ja;!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"}(Ja||(Ja={}));class Za{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=Ja.ONE:2===e?s=Ja.TWO:3===e?s=Ja.THREE:4===e?s=Ja.FOUR:e>3&&(s=Ja.MORE),s},this.getMarkHeight=(e,t)=>{let s;return e<=1?s=Ja.ONE:2===e?s=Ja.TWO:3===e?s=Ja.THREE:4===e?s=Ja.FOUR:e>3&&(s=Ja.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-Ja.ONE-s:(e-2)*s+1*e,this.getTrackHeight=(e,t)=>e<=3?Ja.ONE:t*e+1*(e-1)}render(e,t){if(this.border||(this.border=document.createElement("div"),this.border.classList.add("pinned-message-border"),this.wrapper=document.createElement("div"),this.border.append(this.wrapper)),1===e)return this.count!==e&&(this.wrapper.className="pinned-message-border-wrapper-1",this.border.classList.remove("pinned-message-border-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("pinned-message-border-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="pinned-message-border-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("pinned-message-border-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 eo=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 to{constructor(){this.rows={},this.container=document.createElement("div"),this.container.className=to.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=to.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)},to.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)}}to.DURATION=200,to.BASE_CLASS="animated-super";class so{constructor(e=!1){this.reverse=e,this.decimals=[],this.previousNumber=0,this.container=document.createElement("div"),this.container.className=so.BASE_CLASS}getDecimal(e){if(this.decimals[e])return this.decimals[e];const t=document.createElement("div");t.className=so.BASE_CLASS+"-decimal";const s=document.createElement("div");s.className=so.BASE_CLASS+"-decimal-placeholder";const i=new to;return i.container.className=so.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()})},to.DURATION))}hideLeft(e){const t=(""+e).length;this.decimals.slice(t).forEach(t=>{const s=+t.placeholder.innerText||0;t.animatedSuper.getRow(so.EMPTY_INDEX,!0);t.animatedSuper.animate(so.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:so.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}}so.EMPTY_INDEX=-1,so.BASE_CLASS="animated-counter";class io{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 R.a;const n=new Ge("pinned-message");this.pinnedMessageContainer=new Ya({topbar:e,chat:t,listenerSetter:this.listenerSetter,className:"message",divAndCaption:n,onClose:()=>eo(this,void 0,void 0,(function*(){return i.canPinMessage(this.topbar.peerId)?new ha(this.topbar.peerId,this.pinnedMid,!0):new ha(this.topbar.peerId,0,!0),!1}))}),this.pinnedMessageBorder=new Za,n.border.replaceWith(this.pinnedMessageBorder.render(1,0)),this.animatedSubtitle=new to,n.subtitle.append(this.animatedSubtitle.container),this.animatedMedia=new to,this.animatedMedia.container.classList.add("pinned-message-media-container"),n.content.prepend(this.animatedMedia.container),this.animatedCounter=new so(!0),n.title.append(Object(x.i18n)("PinnedMessage")," ",this.animatedCounter.container);const o=this.pinnedMessageContainer.btnClose.cloneNode(!0);this.pinnedMessageContainer.attachOnCloseEvent(o),n.container.prepend(o),this.btnOpen=H("pinlist pinned-container-close pinned-message-pinlist",{noRipple:!0}),this.pinnedMessageContainer.wrapperUtils.prepend(this.btnOpen),Object(l.b)(this.btnOpen,e=>{Object(c.a)(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>io.LOAD_COUNT&&(!this.loadedBottom&&e<=io.LOAD_OFFSET||!this.loadedTop&&this.count-1-e<=io.LOAD_OFFSET)}getCurrentIndex(e,t=!0){return eo(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:io.LOAD_COUNT,backLimit:io.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 R.a,function(e,t,s,i){if(ue.IS_TOUCH_SUPPORTED){let n;const a={passive:!0};i.add(e)("touchstart",t=>{t.touches.length>1?r():(n=t.touches[0].clientY,i.add(e)("touchmove",o,a),i.add(e)("touchend",r,a))},a);const o=e=>{const i=e.touches[0].clientY,a=i<n;"bottom"===t&&a?s():"top"!==t||a||s(),n=i},r=()=>{i.removeManual(e,"touchmove",o,a),i.removeManual(e,"touchend",r,a)}}else i.add(e)("wheel",e=>{const i=e.deltaY>0;"bottom"===t&&i?s():"top"!==t||i||s()},{passive:!0})}(this.chat.bubbles.scrollable.container,"bottom",()=>{this.unsetScrollDownListener()},this.scrollDownListenerSetter))}unsetScrollDownListener(e=!0){this.waitForScrollBottom=!1,this.scrollDownListenerSetter&&(this.scrollDownListenerSetter.removeAll(),this.scrollDownListenerSetter=null),e&&this.setCorrectIndex(0)}handleFollowingPinnedMessage(){return eo(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 Object(ks.c)(),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 eo(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 eo(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=Ve({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)}))}}io.LOAD_COUNT=50,io.LOAD_OFFSET=5;var no=!("undefined"==typeof RTCPeerConnection||re.IS_FIREFOX);class ao{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&&Object(c.a)(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(Object(x.i18n)(this.appPeersManager.getDeleteButtonText(this.peerId)))),s(this.buttonsToVerify)},this.verifyVideoChatButton=e=>{var t;if(!no||this.peerId.isUser())return!1;const s=this.appGroupCallsManager.groupCall,i=this.peerId.toChatId();if((null==s?void 0:s.chatId)===i)return!1;if(e&&(this.peerId.isBroadcast()&&"group"===e||this.peerId.isAnyGroup()&&"broadcast"===e))return!1;return(null===(t=this.appChatsManager.getChatTyped(i).pFlags)||void 0===t?void 0:t.call_active)||this.appChatsManager.hasRights(i,"manage_call")},this.onJoinGroupCallClick=()=>{this.chat.appImManager.joinGroupCall(this.peerId)},this.onResize=()=>{this.setUtilsWidth(!0),this.setFloating()},this.onChangeScreen=(e,t)=>{this.container.classList.toggle("is-pinned-floating",b.b.isMobile),this.pinnedMessage&&this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-floating",t===b.a.mobile),this.onResize()},this.setUtilsWidth=(e=!1)=>{this.setUtilsRAF&&window.cancelAnimationFrame(this.setUtilsRAF),re.IS_SAFARI&&e&&this.chatUtils.classList.add("hide"),this.setUtilsRAF=window.requestAnimationFrame(()=>{re.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 R.a,this.menuButtons=[],this.buttonsToVerify=[]}construct(){this.container=document.createElement("div"),this.container.classList.add("sidebar-header","topbar"),this.container.dataset.floating="0",this.btnBack=H("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 Xa(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.btnGroupCall,this.btnMute,this.btnSearch,this.btnMore].filter(Boolean)),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(b.b)("changeScreen",this.onChangeScreen),Object(l.b)(this.container,e=>{const t=Object(Me.a)(e.target,"pinned-container");if(Object(Ks.a)(),t){if(Object(c.a)(e),Object(Me.a)(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=fe.getSearchContext();this.chat.appImManager.setInnerPeer(e,s,i.isScheduled?"scheduled":i.threadId?"discussion":void 0,i.threadId)}}else b.b.activeScreen===b.a.medium&&document.body.classList.contains("is-left-column-shown")?n():Object(ft.a)(e.target,"AVATAR-ELEMENT")?this.appSidebarRight.toggleSidebar(!document.body.classList.contains("is-right-column-shown")):this.appSidebarRight.toggleSidebar(!0)},{listenerSetter:this.listenerSetter});const n=e=>{if(e&&Object(c.a)(e),b.b.activeScreen===b.a.medium&&document.body.classList.contains("is-left-column-shown"))this.chat.appImManager.setPeer(this.peerId);else{const e=0===this.chat.appImManager.chats.indexOf(this.chat);j.a.back(e?"im":"chat")}};Object(l.b)(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:()=>b.b.isMobile},{icon:"mute",text:"ChatList.Context.Mute",onClick:()=>{this.appMessagesManager.mutePeer(this.peerId)},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.mutePeer(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();this.appProfileManager.getChannelFull(this.peerId.toChatId()).then(t=>{e()&&t.linked_chat_id&&this.chat.appImManager.setInnerPeer(t.linked_chat_id.toPeerId(!0))})},verify:()=>{var e;const t=this.appProfileManager.getCachedFullChat(this.peerId.toChatId());return"chat"===this.chat.type&&!!(null===(e=t)||void 0===e?void 0:e.linked_chat_id)}},{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),lt(Object(x.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(jt)){const e=new jt(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 Pt({peerTypes:["dialogs","contacts"],onSelect:t=>new Promise((s,i)=>{new gt("",{titleLangKey:"SendMessageTitle",descriptionLangKey:"SendContactToGroupText",descriptionLangArgs:[new Lt.a({peerId:t,dialog:!0}).element],buttons:[{langKey:"Send",callback:()=>{s(),this.appMessagesManager.sendOther(t,this.appUsersManager.getContactMediaInput(e)),this.chat.appImManager.setInnerPeer(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)},{icon:"lock",text:"BlockUser",onClick:()=>{new gt("",{peerId:this.peerId,titleLangKey:"BlockUser",descriptionLangKey:"AreYouSureBlockContact2",descriptionLangArgs:[new Lt.a({peerId:this.peerId}).element],buttons:[{langKey:"BlockUser",isDanger:!0,callback:()=>{this.appUsersManager.toggleBlock(this.peerId,!0).then(e=>{e&&ct({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&&ct({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=H("search"),this.attachClickEvent(this.btnSearch,e=>{this.chat.initSearch()},!0)}attachClickEvent(e,t,s){Object(l.b)(e,e=>{Object(c.a)(e),!s&&Object(Ks.a)(),t(e)},{listenerSetter:this.listenerSetter})}constructPeerHelpers(){return this.avatarElement=new ur,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 io(this,this.chat,this.appMessagesManager,this.appPeersManager),this.btnJoin=Object(U.a)("btn-primary btn-color-primary chat-join hide"),this.btnGroupCall=H("videochat"),this.btnPinned=H("pinlist"),this.btnMute=H("mute"),this.attachClickEvent(this.btnGroupCall,this.onJoinGroupCallClick),this.attachClickEvent(this.btnPinned,()=>{this.openPinned(!0)}),this.attachClickEvent(this.btnMute,()=>{this.appMessagesManager.mutePeer(this.peerId)}),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,s;if(this.peerId===e.toPeerId(!0)){const i=this.appChatsManager.getChat(e);this.btnJoin.classList.toggle("hide",!(null===(s=null===(t=i)||void 0===t?void 0:t.pFlags)||void 0===s?void 0:s.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 io(this,this.chat,this.appMessagesManager,this.appPeersManager)}openPinned(e){this.chat.appImManager.setInnerPeer(this.peerId,e?+this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.dataset.mid:0,"pinned")}destroy(){this.listenerSetter.removeAll(),window.clearInterval(this.setPeerStatusInterval),this.pinnedMessage&&this.pinnedMessage.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.appPeersManager.isAnyChat(a)&&this.btnJoin){const e=a.toChatId();Object(k.a)(this.btnJoin,Object(x.i18n)(this.appChatsManager.isChannel(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))}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 io(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());Object(De.b)(()=>{this.setTitle(),this.setPeerStatus(!0),this.setMutedState()})}setTitle(e){var t;let s;if("pinned"===this.chat.type?(s=void 0===e?Object(x.i18n)("Loading"):Object(x.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(Be.b);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?Object(x.i18n)("Reminders"):Object(x.i18n)("ScheduledMessages"),void 0===e&&this.appMessagesManager.getScheduledMessages(this.peerId).then(e=>{this.setTitle(e.length)})):"discussion"===this.chat.type?(s=void 0===e?Object(x.i18n)("Loading"):Object(x.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 Lt.a({peerId:this.peerId,dialog:!0}).element),Object(k.a)(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(Ut())}}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 oo extends z{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 F("Search"),this.title.replaceWith(this.inputSearch.container),this.btnPickDate=H("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 O("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&&Object(l.b)(this.btnPickDate,()=>{new bn(new Date,this.onDatePick).show()}),i&&this.appSearch.searchInput.inputField.setValueSilently(i),Yt.toggleSidebar(!0)),n}}class ro{constructor(e,t,s){this.topbar=e,this.chat=t,this.query=s,this.foundCount=0,this.selectedIndex=0,this.onDateClick=e=>{Object(c.a)(e),new bn(new Date,this.chat.bubbles.onDatePick).show()},this.selectResult=e=>{if(this.setPeerPromise)return this.setPeerPromise;const t=e.dataset.peerId.toPeerId(),s=+e.dataset.mid||void 0,i=Object(Os.a)(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,Object(k.a)(this.foundCountEl,Object(x.i18n)("Of",[i+1,this.foundCount]));const e=this.searchGroup.list.childElementCount;this.selectedIndex>=e-6&&this.appSearch.searchMore()}).finally(()=>{this.setPeerPromise=null})},this.onResultsClick=e=>{const t=Object(ft.a)(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=>{Object(c.a)(e),this.selectResult(this.searchGroup.list.children[this.selectedIndex+1])},this.onDownClick=e=>{Object(c.a)(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"),Object(se.ripple)(this.backBtn),this.backBtn.addEventListener("click",()=>{this.topbar.container.classList.remove("hide-pinned"),this.element.remove(),this.inputSearch.remove(),this.results.remove(),this.footer.remove(),this.footer.removeEventListener("click",this.onFooterClick),this.dateBtn.removeEventListener("click",this.onDateClick),this.upBtn.removeEventListener("click",this.onUpClick),this.downBtn.removeEventListener("click",this.onDownClick),this.searchGroup.list.removeEventListener("click",this.onResultsClick),this.chat.bubbles.bubblesContainer.classList.remove("search-results-active")},{once:!0}),this.inputSearch=new F("Search"),this.results=document.createElement("div"),this.results.classList.add("chat-search-results","chatlist-container"),this.searchGroup=new O(!1,"messages",void 0,"",!1),this.searchGroup.list.addEventListener("click",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]):(this.foundCountEl.replaceWith(this.inputSearch.value?Object(x.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"),this.footer.addEventListener("click",this.onFooterClick),Object(se.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"),this.dateBtn.addEventListener("click",this.onDateClick),this.upBtn.addEventListener("click",this.onUpClick),this.downBtn.addEventListener("click",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.inputSearch.inputField.value=s)}}class lo extends B.a{constructor(e,t,s,i,n,a,o,r,l,c,d,h,p,u,m,g,b,v,f,y){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=c,this.appWebPagesManager=d,this.appPollsManager=h,this.apiManager=p,this.appDraftsManager=u,this.serverTimeManager=m,this.storage=g,this.appNotificationsManager=b,this.appEmojiManager=v,this.appMessagesIdsManager=f,this.appGroupCallsManager=y,this.wasAlreadyUsed=!1,this.type="chat",this.inited=!1,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=Object(X.b)("CHAT",X.a.Log|X.a.Warn|X.a.Debug|X.a.Error),this.container.append(this.backgroundEl),this.appImManager.chatsContainer.append(this.container)}setBackground(e){const t=a.default.getTheme();let s;if("color"===t.background.type&&"grabbing"===document.documentElement.style.cursor){const e=this.backgroundEl.lastElementChild;e&&e.dataset.type===t.background.type&&(s=e)}return s||(s=document.createElement("div"),s.classList.add("chat-background-item"),s.dataset.type=t.background.type),"color"===t.background.type&&(s.style.backgroundColor=t.background.color,s.style.backgroundImage="none"),new Promise(t=>{const i=()=>{const e=this.backgroundEl.lastElementChild;e!==s?(this.backgroundEl.append(s),Object(De.b)(()=>{Object(De.b)(()=>{Object(Jt.a)(s,"is-visible",!0,200,e?()=>{e.remove()}:null)})}),t()):t()};e?Object(rs.a)(s,e,i):i()})}setType(e){this.type=e,"scheduled"===this.type&&(this.getMessagesStorage=()=>this.appMessagesManager.getScheduledMessagesStorage(this.peerId))}init(){this.topbar=new ao(this,Yt,this.appMessagesManager,this.appPeersManager,this.appChatsManager,this.appNotificationsManager,this.appProfileManager,this.appUsersManager,this.appGroupCallsManager),this.bubbles=new ca(this,this.appMessagesManager,this.appStickersManager,this.appUsersManager,this.appInlineBotsManager,this.appPhotosManager,this.appPeersManager,this.appProfileManager,this.appDraftsManager,this.appMessagesIdsManager),this.input=new $a(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.selection=new Xs(this,this.bubbles,this.input,this.appMessagesManager),this.contextMenu=new ga(this.bubbles.bubblesContainer,this,this.appMessagesManager,this.appPeersManager,this.appPollsManager,this.appDocsManager,this.appMessagesIdsManager),"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()),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(Be.b)})}beforeDestroy(){this.bubbles.cleanup()}destroy(){this.topbar.destroy(),this.bubbles.destroy(),this.input.destroy(),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){e?this.inited||(this.init&&(this.init(),this.init=null),this.inited=!0):this.inited=!1;const s=this.peerId===e;if(s){if(this.setPeerPromise)return}else a.default.dispatchEvent("peer_changing",this),this.peerId=e;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(!s){const t=Yt.getTab(oo);t&&t.close(),Yt.sharedMediaTab.setPeer(e,this.threadId),this.input.clearHelper(),this.selection.cleanup(),this.setAutoDownloadMedia()}this.peerChanged=s;const i=this.bubbles.setPeer(e,t);if(!i)return;const{promise:n}=i,o=this.setPeerPromise=n.finally(()=>{this.setPeerPromise===o&&(this.setPeerPromise=null)});return s||(Yt.sharedMediaTab.setLoadMutex(this.setPeerPromise),Yt.sharedMediaTab.loadSidebarMedia(!0)),i}setAutoDownloadMedia(){const e=this.peerId;if(!e)return;let t;t=e.isUser()?e.isContact()?"contacts":"private":e.isBroadcast()?"channels":"groups",this.noAutoDownloadMedia=!a.default.settings.autoDownload[t]}setMessageId(e){return this.setPeer(this.peerId,e)}finishPeerChange(e,t,s){if(this.peerChanged)return;let i=this.peerId;this.peerChanged=!0,this.cleanup(!1),this.topbar.setPeer(i),this.topbar.finishPeerChange(e,t,s),this.bubbles.finishPeerChange(),this.input.finishPeerChange(),Yt.sharedMediaTab.fillProfileElements(),this.log.setPrefix("CHAT-"+i+"-"+this.type),a.default.dispatchEvent("peer_changed",i),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===Be.c||this.appPeersManager.isAnyGroup(this.peerId)}initSearch(e){if(this.peerId)if(b.b.isMobile)new ro(this.topbar,this,e);else{let t=Yt.getTab(oo);t||(t=new oo(Yt)),t.open(this.peerId,this.threadId,this.bubbles.onDatePick,e)}}}var co=s(146);class ho{constructor(e){this.appImManager=e,this.buttons={},this.addedListener=!1,this.waitingForMouseUp=!1,this.mouseUpCounter=0,this.onMouseUpSingle=e=>{if(this.waitingForMouseUp=!1,ue.IS_TOUCH_SUPPORTED){if(Object(c.a)(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","link"].forEach(t=>{const s=H(t,{noRipple:!0});e.append(this.buttons[t]=s),"link"!==t?s.addEventListener("mousedown",e=>{Object(c.a)(e),this.appImManager.chat.input.applyMarkdown(t),this.cancelClosening()}):Object(l.b)(s,e=>{Object(c.a)(e),this.showLinkEditor(),this.cancelClosening()})}),this.linkBackButton=H("left",{noRipple:!0}),this.linkInput=document.createElement("input"),Object(x._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||!!J.b.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=>{Object(c.a)(e),this.container.classList.remove("is-link"),this.resetSelection(),this.setTooltipPosition(),this.cancelClosening()}),this.linkApplyButton=H("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){Object(c.a)(e),this.resetSelection();let t=this.linkInput.value;t&&!J.b.matchUrlProtocol(t)&&(t="https://"+t),this.appImManager.chat.input.applyMarkdown("link",t),setTimeout(()=>{this.hide()},0)}isLinkValid(){return!this.linkInput.value.length||!!J.b.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,j.a.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 Ba.b){const i=Ba.b[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=i.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,c=n.left+n.width-Math.min(n.width,o.width);let d;if(e){const e=this.container.getBoundingClientRect();d=Object(I.a)(e.left,l,c)}else{const e=i.left+(i.width-o.width)/2;d=Object(I.a)(e,l,c)}this.container.style.transform=`translate3d(${d}px, ${r}px, 0)`}show(){if(this.init&&(this.init(),this.init=null),pa())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"),re.IS_MOBILE||j.a.pushItem({type:"markup",onPop:()=>{this.hide()}})}setMouseUpEvent(){this.waitingForMouseUp||(this.waitingForMouseUp=!0,document.addEventListener("mouseup",this.onMouseUpSingle,{once:!0}))}cancelClosening(){ue.IS_TOUCH_SUPPORTED&&!re.IS_APPLE&&(document.removeEventListener("mouseup",this.onMouseUpSingle),document.addEventListener("mouseup",e=>{Object(c.a)(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;if(document.activeElement!==this.appImManager.chat.input.messageInput)return void this.hide();const t=document.getSelection();if(pa(t))this.hide();else if(ue.IS_TOUCH_SUPPORTED)if(re.IS_APPLE)this.show(),this.setTooltipPosition();else{if(2===this.mouseUpCounter)return void(this.mouseUpCounter=0);this.savedRange=t.getRangeAt(0),this.setMouseUpEvent()}else this.setMouseUpEvent()}))}}function po(e,t,s,i,n,a,o){return[e,",",t," ",s," ",i,",",n," ",a,",",o].join("")}function uo(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"+po(a,a,0,0,1,e+s,t+a)),l.push("V"+(t+i-o)),o>0&&l.push("A"+po(o,o,0,0,1,e+s-o,t+i)),l.push("H"+(e+r)),r>0&&l.push("A"+po(r,r,0,0,1,e+0,t+i-r)),l.push("V"+(t+n)),n>0&&l.push("A"+po(n,n,0,0,1,e+n,t+0)),l.push("Z"),l.join(" ")}de.a.generatePathData=uo;class mo{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(Object(x.i18n)(t.header,t.headerArgs)),t.subtitle&&(n=document.createElement("div"),n.classList.add("drop-subtitle"),n.append(Object(x.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=uo(5,5,e.width-10,e.height-10,10,10,10,10);this.path.setAttributeNS(null,"d",t)}}function go(e){e.forEach(e=>e.classList.add("no-transition")),Object(De.a)().then(()=>{e.forEach(e=>e.classList.remove("no-transition"))})}var bo,vo=s(140);class fo extends ut.b{constructor(e,t){super("popup-join-chat-invite",Object(ut.a)([{langKey:t.pFlags.broadcast?"JoinByPeekChannelTitle":"JoinByPeekGroupTitle",callback:()=>{ht.a.invokeApi("messages.importChatInvite",{hash:e}).then(e=>{si.a.processUpdateMessage(e);const t=e.chats[0].id.toPeerId(!0);a.default.dispatchEvent("history_focus",{peerId:t})})}}]),{closable:!0,overlayClosable:!0,body:!0}),this.header.remove();const s=new ur;s.setAttribute("dialog","0"),s.classList.add("avatar-100"),"photo"===t.photo._?(t.photo=r.a.savePhoto(t.photo),Ls({container:s,message:null,photo:t.photo,boxHeight:100,boxWidth:100,withoutPreloader:!0}),s.style.width=s.style.height=""):d.a.putPhoto(s,Be.b,!1,t.title);const i=document.createElement("div");i.classList.add("chat-title"),i.innerHTML=J.b.wrapEmojiText(t.title);const n=t.pFlags.broadcast,o=Object(x.i18n)(n?"Subscribers":"Members",[t.participants_count]);o.classList.add("chat-participants-count"),this.body.append(s,i,o)}}!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"}(bo||(bo={}));var yo=s(24),wo=s(137),So=s(118);class Lo{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:c,radiusNext:d,N:h}=this;for(let n=0;n<=h;n++)if(0===n){const s=this.progress[n],i=(t-(c[n]*(1-s)+d[n]*s))*r+o*(1-r);l.lineTo(e,i)}else{const a=this.progress[n-1],p=c[n-1]*(1-a)+d[n-1]*a,u=this.progress[n],m=(s-e)/h*(n-1),g=(s-e)/h*n,b=m+(g-m)/2,v=(t-p)*r+o*(1-r),f=(t-(c[n]*(1-u)+d[n]*u))*r+o*(1-r);l.bezierCurveTo(b,v,b,f,g,f),n===h&&l.lineTo(s,i)}a(l),l.fill(),l.closePath()}}}class Eo{constructor(e){this.stateId=e,this.createGradient(e)}createGradient(e){this.shader=(t,s,i,n,a)=>{t.fillStyle=Eo.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===So.a.MUTED_BY_ADMIN?(o.addColorStop(0,"#F05459"),o.addColorStop(.4,"#766EE9"),o.addColorStop(1,"#57A4FE")):t===So.a.UNMUTED?(o.addColorStop(0,"#52CE5D"),o.addColorStop(1,"#00B1C0")):t===So.a.MUTED?(o.addColorStop(0,"#0976E3"),o.addColorStop(1,"#2BCEFF")):t===So.a.CONNECTING&&(o.addColorStop(0,"#8599aa"),o.addColorStop(1,"#8599aa")),o}update(e,t,s,i){}}class Co{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:c,previousState:d,focused:h,resizing:p,canvas:u}=this;if(!h&&!p&&this.progressToState>=1)return;let m=Date.now()-this.lastUpdateTime;m>20&&(m=17),this.animateToAmplitude!==this.amplitude&&(this.amplitude+=this.animateAmplitudeDiff*m,this.animateAmplitudeDiff>0?this.amplitude>this.animateToAmplitude&&(this.amplitude=this.animateToAmplitude):this.amplitude<this.animateToAmplitude&&(this.amplitude=this.animateToAmplitude)),this.animateToAmplitude!==this.amplitude2&&(this.amplitude2+=this.animateAmplitudeDiff2*m,this.animateAmplitudeDiff2>0?this.amplitude2>this.animateToAmplitude&&(this.amplitude2=this.animateToAmplitude):this.amplitude2<this.animateToAmplitude&&(this.amplitude2=this.animateToAmplitude)),d&&(this.progressToState+=m/250,this.progressToState>1&&(this.progressToState=1,this.previousState=null));const{amplitude:g,amplitude2:b,progressToState:v}=this,f=6*b*n,y=6*b*n;u.getContext("2d").clearRect(0,0,u.width,u.height),t.minRadius=0,t.maxRadius=(2+2*g)*n,s.minRadius=0,s.maxRadius=(3+9*g)*n,i.minRadius=0,i.maxRadius=(3+9*g)*n,t.update(g,.3),s.update(g,.7),i.update(g,.7);for(let e=0;e<2;e++){if(0===e&&!d)continue;let n=1,h=null;0===e?(n=1-v,h=d):(n=d?v:1,c.update(l-o,r-a,m,g),h=c);const p=e=>{e.globalAlpha=.3*n,h.shader(e,a,o,r,l)},b=t=>{t.globalAlpha=0===e?1:n,h.shader(t,a,o,r,l)};s.draw(a,o-f,r,l,u,p,o,1),i.draw(a,o-y,r,l,u,p,o,1),t.draw(a,o,r,l,u,b,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([[So.a.UNMUTED,new Eo(So.a.UNMUTED)],[So.a.MUTED,new Eo(So.a.MUTED)],[So.a.MUTED_BY_ADMIN,new Eo(So.a.MUTED_BY_ADMIN)],[So.a.CONNECTING,new Eo(So.a.CONNECTING)]]),this.previousState=null,this.currentState=this.states.get(So.a.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 Lo(3),this.lbd1=new Lo(7),this.lbd2=new Lo(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(){const e=this.container=document.createElement("div");e.classList.add("topbar-call-weave");const t=this.canvas=document.createElement("canvas");return t.classList.add("topbar-call-weave-canvas"),e.append(t),e}}var Io=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 Mo{constructor(e,t){this.item=e,Object(w.g)(this,t)}play(){return this.item.playPart(this)}}class Po{constructor(e,t){this.icon=e,this.autoplay=!1,Object(w.g)(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=le.a.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=>le.a.waitForFirstFrame(e)).then(e=>{this.player=e}),this.loadPromise=t,this.icon.loadPromises.set(this.name,t),t}createPart(e){return new Mo(this,e)}getPart(e){return e instanceof Mo?e:"string"==typeof e?this.parts.find(t=>t.name===e):this.parts[e]}playPart(e){return this.icon.playPart(this,e)}}class To{constructor(e){Object(w.g)(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.a)}getItem(e){return e||1!==this.items.size?this.items.get(e):this.items.values().next().value}add(e){const t=new Po(this,e);return this.items.set(e.name,t),t}playPart(e,t){if(!e.player)return;const s=e.getPart(t);e.player.playPart({from:s.startFrame,to:s.endFrame})}playToPart(e,t,s){if(!e.player)return;const i=e.getPart(t),n=s?i.endFrame:i.startFrame;e.player.playToFrame({frame:n})}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 ko extends To{constructor(e){super({width:e.width,height:e.height}),Object(w.g)(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.a)}setState(e,t){this.loaded||this.load(e,t),void 0!==e&&this.setPartState(e),void 0!==t&&this.getColor&&this.setColorState(t)}setPartState(e){const{partState:t}=this;if(t===e)return;this.partState=e;this.getPart(e,t).play()}setColorState(e){const{colorState:t}=this;if(t===e)return;this.colorState=e;const s=this.getItem();if(s.player){const i=this.getColor(e,t);s.player.setColor(i)}}destroy(){this.items.forEach(e=>{e.loadPromise.then(()=>{e.player.remove()})})}}class xo extends ko{constructor(){super({width:36,height:36,getPart:(e,t)=>{const s=Vo;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"}]})}}function Oo(e){return new Promise((t,s)=>{const{button:i,checkbox:n}=e;i.callback=e=>{t(e?!!e.size:void 0)};const a=Object(ut.a)([]);a[0].callback=()=>{s()},a.unshift(i),e.buttons=a,e.checkboxes=n&&[n],new gt("popup-confirmation",e).show()})}class Ao extends ko{constructor(e){super({width:32,height:32,getPart:(e,t)=>{const s=zo;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=zo;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"}const n=Io.getProperty("gc-"+i+"-text-color");return s=function(e){return Oi(e.slice(0,7))}(n),s}(e):void 0}),this.colored=e;this.container.classList.add("group-call-participant-muted-icon-container");const t=To.generateEqualParts(4,21);this.add({name:"voice_outlined2",parts:t})}setState(e){return super.setState(function(e){const t=zo;switch(e){case t.MUTED_BY_ADMIN:case t.MUTED_FOR_ME:return t.MUTED;default:return e}}(e),e)}}class _o{constructor(e){this.withIcons=e,this.container=document.createElement("div"),this.container.classList.add("group-call-participant-status-container")}setState(e,t){const s=zo,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("group-call-participant-status-icon","group-call-participant-status-icon-"+e,t),s});let n,a;if(e===s.MUTED_FOR_ME)n=Object(x.i18n)("VoiceChat.Status.MutedForYou"),a="is-muted";else if(e===s.UNMUTED)n=Object(x.i18n)("VoiceChat.Status.Speaking"),a="is-speaking";else if(e===s.HAND)n=Object(x.i18n)("VoiceChat.Status.WantsSpeak"),a="is-waiting";else{if(t.about&&!i.length)return void g(this.container,J.b.wrapEmojiText(t.about));n=Object(x.i18n)("VoiceChat.Status.Listening"),a="is-listening"}const o=document.createElement("span");o.classList.add("group-call-participant-status",a),o.append(...i,n),Object(k.a)(this.container,o)}}class Fo extends _s{constructor(e){super({getIndex:e=>e.participant.date,onDelete:e=>{e.dom.listEl.remove(),this.onElementDestroy(e)},onUpdate:e=>{const{participant:t}=e,s=Ko(t);e.mutedIcon.setState(s),e.status.setState(s,t)},onSort:(e,t)=>{As(e.dom.listEl,this.list,t)},onElementCreate:t=>{const{dom:s}=kr.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=Ko(i),a=new Ao(!0),o=new _o(["presentation","video"]);return a.setState(n),o.setState(n,i),Object(k.a)(s.lastMessageSpan,o.container),s.listEl.append(a.container),t.dom=s,t.participant=i,t.mutedIcon=a,t.status=o,t},updateElementWith:De.b}),this.instance=e,this.avatarSize=54,this.rippleEnabled=!0,this.autonomous=!0,this.createChatListOptions={dialogSize:72},this.list=kr.createChatList(this.createChatListOptions)}destroy(){this.elements.forEach(e=>{this.onElementDestroy(e)})}onElementDestroy(e){e.mutedIcon.destroy()}}class Do{constructor(e,t,s){this.appPeersManager=e,this.instance=t,this.source=s,this.container=document.createElement("div"),this.container.classList.add("group-call-participant-video-container"),this.info=document.createElement("div"),this.info.classList.add("group-call-participant-video-info"),this.left=document.createElement("div"),this.left.classList.add("group-call-participant-video-info-left"),this.right=document.createElement("div"),this.right.classList.add("group-call-participant-video-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("group-call-participant-video-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=Object(x.i18n)("VoiceChat.Status.You"),i.classList.add("peer-title")):(this.peerTitle=new Lt.a({peerId:this.appPeersManager.getPeerId(e.peer)}),i=this.peerTitle.element),this.groupCallParticipantMutedIcon=new Ao(!1),this.groupCallParticipantStatus=new _o([t]),this.left.append(i,this.groupCallParticipantStatus.container),this.right.append(this.groupCallParticipantMutedIcon.container);const n="group-call-participant-video";s.classList.add(n),s.paused&&s.play();const a=document.createElement("canvas");a.classList.add(n+"-blur");if(a.width=16,a.height=16,s){const e=a.getContext("2d");e.filter="blur(2px)";const t=()=>{e.drawImage(s,0,0,s.videoWidth,s.videoHeight,0,0,a.width,a.height)};Object(os.a)(()=>(t(),a.isConnected)),t()}this.container.prepend(a,s),this.updateParticipant(e)}updateParticipant(e){const t=Ko(e);this.groupCallParticipantMutedIcon.setState(t),this.groupCallParticipantStatus.setState(t,e)}destroy(){this.groupCallParticipantMutedIcon.destroy()}}class jo extends Pe{constructor(e){super(),Object(w.g)(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(a.default)("group_call_pinned",({instance:e,source:t})=>{this.instance===e&&this.participantsElements.forEach(e=>{e.forEach(e=>{this.setElementDisplay(e,t)})})}),Object(l.b)(this.container,e=>{const t=Object(Me.a)(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 Do(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 Bo{constructor(e){this.onOpenProfileClick=()=>{const e=ut.b.getPopup(qo);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:()=>{Oo({peerId:this.targetPeerId,title:new Lt.a({peerId:this.targetPeerId}).element,descriptionLangKey:this.appChatsManager.isBroadcast(this.chatId)?"VoiceChat.RemovePeer.Confirm.Channel":"VoiceChat.RemovePeer.Confirm",descriptionLangArgs:[new Lt.a({peerId:this.targetPeerId}).element],button:{langKey:"VoiceChat.RemovePeer.Confirm.OK",isDanger:!0}}).then(()=>{this.appChatsManager.kickFromChat(this.chatId,this.targetPeerId)},_e.a)}}];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=Ee(this.buttons,t),this.element.classList.add("group-call-participant-menu","night"),Object(te.a)(e.onContextElement,e=>{const t=Object(Me.a)(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))}),Object(c.a)(e),Object(te.e)(e.touches?e.touches[0]:e,this.element,"right"),Object(te.d)(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&&Object(te.c)()}});let s=document.body;Object(Te.a)(document.body,()=>{const e=Object(Te.d)();s=e?ut.b.getPopup(qo).getContainer():document.body,e||Object(te.c)()},t)}}class Ro{constructor(e){Object(w.g)(this,e);const t=new T.b(void 0);t.container.classList.add("group-call-participants-scrollable");const s=this.container=document.createElement("div");s.classList.add("group-call-participants");const i=this.sortedList=new Fo(this.instance),{instance:n,listenerSetter:o}=this;this.contextMenu=new Bo(Object.assign(Object.assign({},e),{onContextElement:i.list,listenerSetter:o,instance:n})),this.groupCallParticipantsVideo=new jo(Object.assign(Object.assign({},e),{appendTo:t.container,displayPinned:!1})),t.append(i.list),s.append(t.container),e.appendTo.append(s),o.add(a.default)("group_call_participant",({groupCallId:e,participant:t})=>{this.instance.id===e&&this.updateParticipant(t)});new yt({scrollable:t,getPromise:()=>this.appGroupCallsManager.getGroupCallParticipants(this.instance.id).then(({participants:e,isEnd:t})=>(e.forEach(e=>{this.updateParticipant(e)}),t))});this.setInstance(n)}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 Uo{constructor(e){this.appendTo=e,this.descriptionIntl=new x.default.IntlElement({key:"VoiceChat.Status.Connecting"}),this.descriptionIntl.element.classList.add("group-call-description"),e.append(this.descriptionIntl.element)}update(e){const{state:t}=e;let s,i;t===So.a.CONNECTING?s="VoiceChat.Status.Connecting":(s="VoiceChat.Status.Members",i=[e.groupCall.participants_count]);const{descriptionIntl:n}=this;n.key===s&&Object(w.b)(n.args,i)||(n.key=s,n.args=i,n.update())}}class Ho{constructor(e){this.appendTo=e,this.peerTitle=new Lt.a({peerId:0})}update(e){const{peerTitle:t,appendTo:s}=this,i=e.groupCall,n=e.chatId.toPeerId(!0);i.title?g(s,J.b.wrapEmojiText(i.title)):t.peerId!==n&&(t.peerId=n,t.update(),s.append(t.element))}}class No extends B.a{constructor(e){super(!0),this.onResize=()=>{this.fixDimensions(),this.fixPosition(),this.setPosition()},Object(w.g)(this,e),this.top=this.left=this.width=this.height=0,this.element.classList.add("movable-element"),this.addResizeHandlers(),this.setSwipeHandler(),b.b.addEventListener("resize",this.onResize)}destroyElements(){this.element.classList.remove("movable-element"),this.handlers&&this.handlers.forEach(e=>{e.remove()})}destroy(){b.b.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("movable-element-resize-handler","movable-element-resize-handler-side-"+e),this.element.append(t),t})}setSwipeHandler(){let e,t,s,i,n;const a=this.swipeHandler=new Vt({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")?Et.a.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")?Et.a.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(Object(Me.a)(t,"chatlist")||Object(Me.a)(t,"group-call-button")||Object(Me.a)(t,"btn-icon")||Object(Me.a)(t,"group-call-participants-video-container")||Object(Te.d)())return!1;const s=Object(Me.a)(t,"movable-element-resize-handler");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=Et.a.height/2-this.height/2,this.left=Et.a.width/2-this.width/2,this.setPosition()}fixDimensions(){this.width=Object(I.a)(this.width,this.minWidth,Et.a.width),this.height=Object(I.a)(this.height,this.minHeight,Et.a.height)}fixPosition(){this.top=Object(I.a)(this.top,0,Et.a.height-this.height),this.left=Object(I.a)(this.left,0,Et.a.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 zo,Vo,Go=!!("getDisplayMedia"in((null===navigator||void 0===navigator?void 0:navigator.mediaDevices)||{}));function Ko(e){const t=zo;return e.pFlags.muted_by_you?t.MUTED_FOR_ME:void 0!==e.raise_hand_rating?t.HAND:e.pFlags.muted?e.pFlags.can_self_unmute?t.MUTED:t.MUTED_BY_ADMIN:t.UNMUTED}!function(e){e[e.UNMUTED=0]="UNMUTED",e[e.MUTED=1]="MUTED",e[e.MUTED_FOR_ME=2]="MUTED_FOR_ME",e[e.MUTED_BY_ADMIN=3]="MUTED_BY_ADMIN",e[e.HAND=4]="HAND"}(zo||(zo={})),function(e){e[e.HAND=0]="HAND",e[e.MUTED=1]="MUTED",e[e.UNMUTED=2]="UNMUTED"}(Vo||(Vo={}));let Wo={width:420,height:640};class qo extends ut.b{constructor(e){super("popup-group-call",void 0,{body:!0,withoutOverlay:!0,closable:!0}),this.onFullScreenChange=()=>{this.toggleBigLayout();const e=Object(Te.d)(),{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&&(C.a.checkAnimations(e),a.default.setThemeColor(e?"#000000":void 0))},this.toggleBigLayout=()=>{const e=(Object(Te.d)()||!!(this.movable&&this.movable.width>=680))&&!!this.videosCount,t=this.container.classList.contains("is-big-layout");let s;e&&!t&&(s=Array.from(this.buttonsContainer.children),s.forEach(e=>{e.style.opacity="0"}),this.buttonsContainer.offsetLeft),this.container.classList.toggle("is-big-layout",e),this.btnInvite.classList.toggle("hide",e),this.btnShowColumn.classList.toggle("hide",!e),s&&s.forEach(e=>{e.style.opacity=""})},this.toggleRightColumn=()=>{this.container.classList.toggle("is-right-column-shown")},Object(w.g)(this,e),this.videosCount=0,this.container.classList.add("group-call","night");const t=this.instance=this.appGroupCallsManager.groupCall,{listenerSetter:s}=this;if(!re.IS_APPLE_MOBILE){const e=this.btnFullScreen=H("fullscreen"),t=(this.btnFullScreen2=H("fullscreen group-call-cfs"),this.btnExitFullScreen=H("smallscreen"));Object(l.b)(e,()=>{Object(Te.e)(this.container)},{listenerSetter:s}),Object(l.b)(t,()=>{Object(Te.b)()},{listenerSetter:s}),Object(Te.a)(this.container,this.onFullScreenChange,s)}this.btnInvite=H("adduser");const i=this.btnShowColumn=H("rightpanel group-call-only-big");this.toggleMovable(!ue.IS_TOUCH_SUPPORTED),Object(l.b)(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),c=n.cloneNode(!1),d=this.title.cloneNode(!1);c.append(d);const h=H("rightpanel");r.append(...[h,c,this.btnFullScreen2].filter(Boolean)),Object(l.b)(h,this.toggleRightColumn,{listenerSetter:s}),this.body.prepend(r);const p=new T.b(void 0);p.container.classList.add("group-call-big-video-container"),this.container.append(p.container),this.groupCallTitle=new Ho(this.title),this.groupCallDescription=new Uo(o),this.groupCallBodyHeaderDescription=new Uo(d),this.groupCallParticipantsVideo=new jo(Object.assign({appendTo:p.container,instance:t,listenerSetter:s,displayPinned:!0,onLengthChange:e=>{this.videosCount=e,this.toggleBigLayout()}},e)),this.groupCallParticipants=new Ro(Object.assign({appendTo:this.body,instance:t,listenerSetter:s},e));{const e=this.buttonsContainer=document.createElement("div");e.classList.add("group-call-buttons"),this.listenerSetter.add(this.groupCallParticipantsVideo)("toggleControls",t=>{this.container.classList.toggle("show-controls",t),e.classList.toggle("show-controls",t)});const t=e=>{const t=document.createElement("div");return t.classList.add("group-call-button","rp-overflow"),e.noRipple||Object(se.ripple)(t),e.isDanger&&t.classList.add("group-call-button-red"),t},i=t({text:"VoiceChat.Video.Stream.Video"});i.classList.add("tgico-videocamera_filled"),Object(l.b)(i,()=>{const e=Object(bt.a)([i],!0);this.instance.toggleVideoSharing().finally(()=>{e()})},{listenerSetter:s});const n=t({text:"VoiceChat.Video.Stream.Screencast"});n.classList.add("tgico-sharescreen_filled"),n.classList.toggle("hide",!Go),Object(l.b)(n,()=>{const e=Object(bt.a)([n],!0);this.instance.toggleScreenSharing().finally(()=>{e()})},{listenerSetter:s});const a=t({noRipple:!0});a.classList.add("group-call-microphone-button");const o=this.groupCallMicrophoneIcon=new xo;a.append(o.container);const r=Object(Di.a)(()=>{const e=this.instance.participant;e.pFlags.can_self_unmute?this.instance.toggleMuted():void 0===e.raise_hand_rating&&this.instance.changeRaiseHand(!0)},600,!0);Object(l.b)(a,r,{listenerSetter:s});const c=t({text:"VoiceChat.Video.Stream.More"});c.classList.add("tgico-settings_filled","btn-disabled"),c.classList.toggle("hide",!Go);const d=t({text:"VoiceChat.Leave",isDanger:!0});d.classList.add("tgico-close"),Object(l.b)(d,()=>{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)},{listenerSetter:s}),e.append(i,n,a,c,d),this.container.append(e)}s.add(a.default)("group_call_state",e=>{this.instance===e&&this.updateInstance()}),s.add(a.default)("group_call_update",e=>{this.instance.id===e.id&&this.updateInstance()}),s.add(a.default)("group_call_pinned",({instance:e})=>{this.instance===e&&this.setHasPinned()}),s.add(b.b)("changeScreen",(e,t)=>{t!==b.a.mobile&&e!==b.a.mobile||this.toggleMovable(!ue.IS_TOUCH_SUPPORTED)}),this.addEventListener("close",()=>{const{movable:e}=this;e&&(Wo=e.state),this.groupCallParticipantsVideo.destroy(),this.groupCallParticipants.destroy(),this.groupCallMicrophoneIcon.destroy(),e&&e.destroy()}),this.toggleRightColumn(),this.onFullScreenChange(),this.updateInstance()}getContainer(){return this.container}toggleMovable(e){if(e){if(this.movable)return;const e=this.movable=new No({minWidth:400,minHeight:480,element:this.element});e.state=Wo,void 0===Wo.top&&e.setPositionToCenter(),this.listenerSetter.add(e)("resize",this.toggleBigLayout)}else{if(!this.movable)return;this.movable.destroyElements(),this.movable.destroy(),this.movable=void 0}}setHasPinned(){this.container.classList.toggle("has-pinned",!!this.instance.pinnedSource)}updateInstance(){if(this.instance.state===So.a.CLOSED)return this.container.classList.contains("is-full-screen")&&Object(Te.b)(),void this.hide();this.setTitle(),this.setDescription(),this.setHasPinned();const e=function(e,t){const s=Vo;return t.pFlags.can_self_unmute?t.pFlags.muted?s.MUTED:s.UNMUTED:s.HAND}(this.instance.groupCall,this.instance.participant);this.container.dataset.micState=e===Vo.HAND?"hand":e===Vo.MUTED?"muted":"unmuted",this.groupCallMicrophoneIcon.setState(e)}setTitle(){this.groupCallTitle.update(this.instance)}setDescription(){this.groupCallDescription.update(this.instance),this.groupCallBodyHeaderDescription.update(this.instance)}}class Qo extends ko{constructor(){super({width:36,height:36,getPart:e=>this.getItem().getPart(e?"unmute":"mute")}),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"}]})}}class $o{constructor(e,t,s){this.appGroupCallsManager=e,this.appPeersManager=t,this.appChatsManager=s;const i=this.listenerSetter=new R.a;i.add(a.default)("group_call_state",e=>{this.updateInstance(e)}),i.add(a.default)("group_call_update",e=>{const t=this.appGroupCallsManager.groupCall;(null==t?void 0:t.id)===e.id&&this.updateInstance(t)}),i.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)})}updateInstance(e){this.construct&&(this.construct(),this.construct=void 0);const{state:t,id:s}=e,{weave:i,container:n}=this;i.componentDidMount();const a=t===So.a.CLOSED;if(document.body.classList.contains("is-calling")&&!a||(a&&i.setAmplitude(0),Object(Jt.a)(document.body,"is-calling",!a,250,a?()=>{i.componentWillUnmount()}:void 0)),a)return;t===So.a.CONNECTING?i.setCurrentState(So.a.CONNECTING,!0):i.setCurrentState(t,!0),n.dataset.callId=""+s,this.setTitle(e),this.setDescription(e),this.groupCallMicrophoneIconMini.setState(t===So.a.UNMUTED);const o="state-"+t;n.classList.contains(o)}setDescription(e){return this.groupCallDescription.update(e)}setTitle(e){return this.groupCallTitle.update(e)}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 Qo,n=H();n.append(i.container),s.append(n);const a=Object(Di.a)(()=>{this.appGroupCallsManager.toggleMuted()},600,!0);Object(l.b)(n,e=>{Object(c.a)(e),a()},{listenerSetter:e});const o=this.center=document.createElement("div");o.classList.add("topbar-call-center"),this.groupCallTitle=new Ho(o),this.groupCallDescription=new Uo(s);const r=document.createElement("div");r.classList.add("topbar-call-right");const d=H("endcall_filled");r.append(d),Object(l.b)(d,e=>{Object(c.a)(e),this.appGroupCallsManager.hangUp(t.dataset.callId,!1,!1)},{listenerSetter:e}),Object(l.b)(t,()=>{ut.b.getPopup(qo)||new qo({appGroupCallsManager:this.appGroupCallsManager,appPeersManager:this.appPeersManager,appChatsManager:this.appChatsManager}).show()},{listenerSetter:e}),t.append(s,o,r);const h=this.weave=new Co,p=h.render();t.prepend(p),document.getElementById("column-center").prepend(t),h.componentDidMount()}}var Yo=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 Xo="chat",Jo=ue.IS_TOUCH_SUPPORTED?"touchstart":"mousemove";const Zo=new class{constructor(){this.columnEl=document.getElementById("column-center"),this.offline=!1,this.updateStatusInterval=0,this.setPeerPromise=null,this.tabId=-1,this.chats=[],this.backgroundPromises={},this.onHashChange=()=>{const e=location.hash,t=e.split("?"),s=this.parseUriParams(e,t);if(this.log("hashchange",e,t[0],s),s.tgaddr){j.a.replaceState();const{onclick:e}=J.b.wrapUrl(s.tgaddr);if(e){const t=document.createElement("a");t.href=s.tgaddr,window[e](t)}}else switch(t[0]){case"#/im":{const e=s.p;let t=void 0!==s.post?v.a.generateMessageId(+s.post):void 0;switch(e[0]){case"@":this.openUsername(e,t);break;default:this.setInnerPeer(t?e.toPeerId(!0):e.toPeerId(),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),ht.a.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)},a.default.settings.animationsEnabled?250:0,!1,!0),le.a.setLoop(a.default.settings.stickers.loop),C.a.checkAnimations(!1);for(const e of this.chats)e.setAutoDownloadMedia();x.default.setTimeFormat(a.default.settings.timeFormat)},this.onDocumentPaste=(e,t)=>{const s=Ma();if(this.canDrag()||s){if(e instanceof DragEvent){const t=e.dataTransfer.types;(t.contains?t.contains("Files"):t.indexOf("Files")>=0)&&Object(c.a)(e)}Object(me.d)(e).then(e=>{if(e.length){if(s)return void s.addFiles(e);const i=this.chat.input;i.willAttachType=t||(m.has(e[0].type)?"media":"document"),new Pa(this.chat,e,i.willAttachType)}})}},si.a.attach(),Dt.a.start(),this.log=Object(X.b)("IM",X.a.Log|X.a.Warn|X.a.Debug|X.a.Error),this.selectTab(0),window.addEventListener("blur",()=>{C.a.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),C.a.checkAnimations(!1),a.default.dispatchEvent("idle",a.default.idle.isIDLE)},{once:!0})}),window.addEventListener(Jo,()=>{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.columnEl.append(this.chatsContainer),this.createNewChat(),this.chatsSelectTab(this.chat.container),j.a.onHashChange=this.onHashChange,this.setSettings(),a.default.addEventListener("settings_updated",this.setSettings),Object(ks.a)(()=>{C.a.setOnlyOnePlayableGroup("lock"),C.a.checkAnimations(!0)},()=>{C.a.setOnlyOnePlayableGroup(""),C.a.checkAnimations(!1)}),this.applyCurrentTheme(),b.b.addEventListener("changeScreen",(e,t)=>{document.body.classList.contains("is-left-column-shown")&&document.body.classList.contains("is-right-column-shown")&&Yt.toggleSidebar(!1)}),a.default.addEventListener("history_focus",e=>{let{peerId:t,threadId:s,mid:i}=e;s&&(s=v.a.generateMessageId(s)),i&&(i=v.a.generateMessageId(i)),this.setInnerPeer(t,i,s?"discussion":void 0,s)}),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("instance_deactivated",()=>{const e=new ut.b("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(Object(x.i18n)("Deactivated.Title"));const i=document.createElement("div");i.classList.add("subtitle"),i.append(Object(x.i18n)("Deactivated.Subtitle")),t.append(s,i),document.body.classList.add("deactivated"),e.onClose=()=>{document.body.classList.add("deactivated-backwards"),vo.a.activateInstance(),setTimeout(()=>{document.body.classList.remove("deactivated","deactivated-backwards")},333)},e.show()}),Tn.a.get("chatPositions").then(e=>{Tn.a.setToCache("chatPositions",e||{})}),this.topbarCall=new $o(wo.a,o.a,K.a),vo.a.activateInstance();const e=()=>{yo.default.setAuthorized(!0)};setInterval(e,oe.a),e(),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.a.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={_:bo.STICKER_SET,set:e[1]};this.processInternalLink(t)}}),this.addAnchorListener({name:"joinchat",callback:({pathnameParams:e})=>{const t={_:bo.JOIN_CHAT,invite:e[1]||decodeURIComponent(e[0]).slice(1)};this.processInternalLink(t)}}),no&&this.addAnchorListener({name:"voicechat",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(bo.VOICE_CHAT,e);this.processInternalLink(t)}}),this.addAnchorListener({name:"im",callback:({pathnameParams:e,uriParams:t})=>Yo(this,void 0,void 0,(function*(){let s;s="c"===e[0]?{_:bo.PRIVATE_POST,channel:e[1],post:e[2],thread:"thread"in t?t.thread:void 0,comment:t.comment}:{_:bo.MESSAGE,domain:e[0],post:e[1],comment:t.comment},this.processInternalLink(s)}))}),this.addAnchorListener({name:"resolve",protocol:"tg",callback:({uriParams:e})=>{let t;"telegrampassport"===e.domain||(t=this.makeLink(bo.MESSAGE,e)),this.processInternalLink(t)}}),this.addAnchorListener({name:"privatepost",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(bo.PRIVATE_POST,e);this.processInternalLink(t)}}),this.addAnchorListener({name:"addstickers",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(bo.STICKER_SET,e);this.processInternalLink(t)}}),this.addAnchorListener({name:"joinchat",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(bo.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]}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.a.getHistoryStorage(r.peerId,r.threadId).history.slice;if(e.isEnd(Ln.a.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.a.canEditMessage(r.getMessage(t),"text")){s=t;break}}s&&(r.input.initMessageEditing(s),Object(c.a)(t))}}}else if("ArrowDown"===n)return}else{const e=i.a.dialogsStorage.getFolderDialogs(a.default.filterId,!0);let t;if(a.default.peerId){const s=e.findIndex(e=>e.peerId===a.default.peerId);if(-1!==s){t=e["ArrowUp"===n?s-1:s+1]}}else"ArrowDown"===n&&(t=e[0]);t&&this.setPeer(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")&&!ue.IS_TOUCH_SUPPORTED&&(!b.b.isMobile||1===this.tabId)&&!r.selection.isSelecting&&!r.input.recording){r.input.messageInput.focus(),Object(Ea.a)(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 Yo(this,void 0,void 0,(function*(){switch(null==e?void 0:e._){case bo.MESSAGE:{const t=e.post?v.a.generateMessageId(+e.post):void 0,s=e.comment?v.a.generateMessageId(+e.comment):void 0;this.openUsername(e.domain,t,void 0,s);break}case bo.PRIVATE_POST:{const t=e.channel.toChatId(),s=t.toPeerId(!0);if(K.a.getChat(t).deleted)try{yield K.a.resolveChannel(t)}catch(e){throw ct({langPackKey:"LinkNotFound"}),e}const i=v.a.generateMessageId(+e.post),n=e.thread?v.a.generateMessageId(+e.thread):void 0;n?this.openThread(s,i,n):this.setInnerPeer(s,i);break}case bo.STICKER_SET:new Ni({id:e.set}).show();break;case bo.JOIN_CHAT:ht.a.invokeApi("messages.checkChatInvite",{hash:e.invite}).then(t=>{t.chat&&K.a.saveApiChat(t.chat,!0),"chatInviteAlready"!==t._&&"chatInvitePeek"!==t._?new fo(e.invite,t).show():this.setInnerPeer(t.chat.id.toPeerId(!0))},e=>{"INVITE_HASH_EXPIRED"===e.type&&lt(Object(x.i18n)("InviteExpired"))});break;case bo.VOICE_CHAT:no&&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=>{Object(c.a)(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,t,s,i){return P.a.resolveUsername(e).then(e=>{const n="user"===e._?e.id.toPeerId():e.id.toPeerId(!0);return s?this.openThread(n,t,s):i?this.openComment(n,t,i):this.setInnerPeer(n,t)},e=>{"USERNAME_NOT_OCCUPIED"===e.type?ct({langPackKey:"NoUsernameFound"}):"USERNAME_INVALID"===e.type&&ct({langPackKey:"Alert.UserDoesntExists"})})}openThread(e,t,s){return i.a.wrapSingleMessage(e,s).then(()=>{const n=i.a.getMessageByPeer(e,s);return i.a.generateThreadServiceStartMessage(n),this.setInnerPeer(e,t,"discussion",s)})}openComment(e,t,s){return i.a.getDiscussionMessage(e,t).then(e=>this.openThread(e.peerId,s,e.mid))}joinGroupCall(e,t){return Yo(this,void 0,void 0,(function*(){const s=e.toChatId(),i=K.a.hasRights(s,"manage_call");if(t){if("groupCallDiscarded"===(yield wo.a.getGroupCallFull(t))._){if(!i)return void ct({langPackKey:"VoiceChat.Chat.Ended"});yield Oo({descriptionLangKey:"VoiceChat.Chat.StartNew",button:{langKey:"VoiceChat.Chat.StartNew.OK"}})}}const a=wo.a.groupCall;a&&(yield Oo({titleLangKey:"Call.Confirm.Discard.Voice.Header",descriptionLangKey:"Call.Confirm.Discard.Voice.ToVoice.Text",descriptionLangArgs:[new Lt.a({peerId:a.chatId.toPeerId(!0)}).element,new Lt.a({peerId:e}).element],button:{langKey:"OK"}}),wo.a.groupCall===a&&(yield a.hangUp())),(()=>{Yo(this,void 0,void 0,(function*(){const e=yield n.default.getChatFull(s);let t;if(e.call)t=wo.a.saveGroupCall(e.call,s);else{if(!i)return;t=yield wo.a.createGroupCall(s)}wo.a.joinGroupCall(s,t.id,!0,!1)}))})()}))}setCurrentBackground(e=!1){const t=a.default.getTheme();if("image"===t.background.type||"default"===t.background.type&&t.background.slug){const s=M.AppStateManager.STATE_INIT.settings.themes.find(e=>e.name===t.name);if(!(t.background.blur===s.background.blur&&t.background.slug===s.background.slug))return this.getBackground(t.background.slug).then(t=>this.setBackground(t,e),()=>(t.background=Object(w.a)(s.background),this.setBackground("",!0)))}return this.setBackground("",e)}getBackground(e){return this.backgroundPromises[e]?this.backgroundPromises[e]:this.backgroundPromises[e]=he.a.cacheStorage.getFile("backgrounds/"+e).then(e=>URL.createObjectURL(e))}setBackground(e,t=!0){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=Tn.a.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:Object(w.e)(t.bubbles,"desc"),top:s};n[i]=e,this.log("saved chat position:",e)}Tn.a.set({chatPositions:n},!0)}getChatSavedPosition(e){if(!["chat","discussion"].includes(e.type)||!e.peerId)return;const t=e.peerId+(e.threadId?"_"+e.threadId:""),s=Tn.a.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"),!ue.IS_TOUCH_SUPPORTED&&e&&(a.default.themeColor=function(e){return _i(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&&go([e,this.prevTab].filter(Boolean)),this.prevTab){this.prevTab.classList.remove("active"),this.chatsSelectTabDebounced(),a.default.settings.animationsEnabled&&!1!==t&&Object(ks.b)(Object(In.a)(400),400);const s=Object(Os.a)(this.prevTab);Object(Os.a)(e)>s&&j.a.pushItem({type:"chat",onPop:e=>{this.setPeer(Be.b,void 0,e),Object(Ks.a)()}})}e.classList.add("active"),this.prevTab=e}}init(){document.addEventListener("paste",this.onDocumentPaste,!0),ue.IS_TOUCH_SUPPORTED||this.attachDragAndDropListeners(),this.markupTooltip=new ho(this),this.markupTooltip.handleSelection()}attachDragAndDropListeners(){const e=[],t=[];let s=!1;const i=(r,l)=>Yo(this,void 0,void 0,(function*(){if(l===s)return;const c=r.dataTransfer.types,d=c.contains?c.contains("Files"):c.indexOf("Files")>=0,h=Ma();if(!d||!this.canDrag()&&!h)return void(n=0);const p=h?o:a,u=h?t:e;if(l&&!u.length){const e=yield Object(me.d)(r,!0),t=d&&!e.length,s=e.filter(e=>m.has(e)).length;this.log("drag files",e),h?(h.appendDrops(p),(e.length||t)&&u.push(new mo(p,{header:"Preview.Dragging.AddItems",headerArgs:[e.length],onDrop:e=>{i(e,!1),Zo.log("drop",e),Zo.onDocumentPaste(e,"document")}}))):((e.length||t)&&u.push(new mo(p,{icon:"dragfiles",header:"Chat.DropTitle",subtitle:"Chat.DropAsFilesDesc",onDrop:e=>{i(e,!1),Zo.log("drop",e),Zo.onDocumentPaste(e,"document")}})),(s||t)&&u.push(new mo(p,{icon:"dragmedia",header:"Chat.DropTitle",subtitle:"Chat.DropQuickDesc",onDrop:e=>{i(e,!1),Zo.log("drop",e),Zo.onDocumentPaste(e,"media")}})),this.chat.container.append(p))}Object(Jt.a)(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),Object(c.a)(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(){var e;const t=null===(e=this.chat)||void 0===e?void 0:e.peerId;return!(!t||a.default.isOverlayActive||!i.a.canSendToPeer(t,this.chat.threadId,"send_media"))}selectTab(e,t){!1===t&&go([mn.sidebarEl,this.columnEl,Yt.sidebarEl]),document.body.classList.toggle("is-left-column-shown",0===e);const s=this.tabId;this.log("selectTab",e,s);let i=a.default.settings.animationsEnabled?Object(De.a)():Promise.resolve();if(-1!==s&&s!==e&&a.default.settings.animationsEnabled&&!1!==t){const e=100+(b.b.isMobile?250:200);i=Object(In.a)(e),Object(ks.b)(i,e)}return this.tabId=e,Object(Ks.a)(),b.b.isMobile&&2===s&&e<2&&document.body.classList.remove("is-right-column-shown"),-1!==s&&e>s&&(e<2||!j.a.findItemByType("im"))&&j.a.pushItem({type:"im",onPop:e=>{this.setPeer(Be.b,void 0,e)}}),a.default.dispatchEvent("im_tab_change",e),i}updateStatus(){return this.myId?(P.a.setUserStatus(this.myId,this.offline),ht.a.invokeApiSingle("account.updateStatus",{offline:this.offline})):Promise.resolve()}createNewChat(){const e=new lo(this,K.a,E.a,Qn,i.a,o.a,r.a,n.default,us,P.a,co.a,Je.a,ht.a,Pi.a,Ze.a,Tn.a,Dt.a,An,v.a,wo.a);this.chats.length&&e.backgroundEl.append(this.chat.backgroundEl.lastElementChild.cloneNode(!0)),this.chats.push(e)}spliceChats(e,t=!0,s,i){if(!(e>=this.chats.length)){this.chats.length>1&&t&&a.default.dispatchEvent("peer_changing",this.chat),i||(i=this.chats.splice(e,this.chats.length-e));for(let e=0;e<i.length-1;++e)j.a.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(oo);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,s){this.init&&(this.init(),this.init=null);const i=this.chat,n=this.chats.indexOf(i);if(e){if(n>0&&i.peerId&&i.peerId!==e){const s=this.chats.splice(1,this.chats.length-1);if(this.chat.peerId===e)return void this.spliceChats(0,!0,!0,s);{const i=this.setPeer(e,t);return this.spliceChats(0,!1,!1,s),i}}}else{if(n>0)return void this.spliceChats(n,void 0,s);if(b.b.activeScreen===b.a.medium)return void this.selectTab(+!this.tabId,s)}if(e===i.peerId&&b.b.activeScreen<=b.a.medium&&document.body.classList.contains("is-left-column-shown"))return this.selectTab(1,s),!1;if(e||b.b.activeScreen!==b.a.mobile){const n=i.setPeer(e,t),a=(null==n?void 0:n.cached)?n.promise:Promise.resolve();e&&a.then(()=>{setTimeout(()=>{setTimeout(()=>{this.chatsSelectTab(this.chat.container)},0),this.selectTab(1,s)},0)})}return e?void 0:(this.selectTab(0,s),!1)}setInnerPeer(e,t,s="chat",i){if(e===Be.b||!e)return;const n=this.chats.findIndex(t=>t.peerId===e&&t.type===s);if(-1!==n)return this.spliceChats(n+1),this.setPeer(e,t);return this.chat.inited&&this.createNewChat(),s&&(this.chat.setType(s),i&&(this.chat.threadId=i)),this.setPeer(e,t)}openScheduled(e){this.setInnerPeer(e,void 0,"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"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(!P.a.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"},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"},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"),"sendMessageChooseStickerAction"===r._&&t.classList.add("peer-typing-flex");let c,d=t.firstElementChild;d?d.dataset.action!==r._&&d.replaceWith(this.getTypingElement(r)):(d=this.getTypingElement(r),t.prepend(d)),e.isAnyChat()&&(c=[new Lt.a({peerId:i.userId.toPeerId(!1),onlyFirstName:!0}).element,s.length-1]);const h=Object(x.i18n)(l,c);return h.classList.add("peer-typing-description"),t.childElementCount>1?t.lastElementChild.replaceWith(h):t.append(h),t}}getPeerStatus(e){var t;return Yo(this,void 0,void 0,(function*(){let s;if(e){if(e.isAnyChat()){let t=this.getPeerTyping(e);if(t)return t;const i=e.toChatId(),a=yield n.default.getChatFull(i);this.chat.log("chatInfo res:",a);const o=a.participants_count||a.participants&&a.participants.participants&&a.participants.participants.length||1;if(s=n.default.getChatMembersString(i),o<2)return s;const r=yield n.default.getOnlines(i);if(r>1){const e=document.createElement("span");e.append(...Object(x.join)([s,Object(x.i18n)("OnlineCount",[Object(I.d)(r)])],!1)),s=e}return s}{const i=P.a.getUser(e);if(a.default.myId===e)return;if(i){if(s=P.a.getUserStatusString(i.id),!P.a.isBot(e)){let n=this.getPeerTyping(e);if(n||"userStatusOnline"!==(null===(t=i.status)||void 0===t?void 0:t._)||(n=document.createElement("span"),n.classList.add("online"),n.append(s)),n)return n}return s}}}}))}setPeerStatus(e,t,s,i,n){s&&(t.innerHTML=i?"":"");const a=t.querySelector(".peer-typing-container");a&&this.getPeerTyping(e,a)||this.getPeerStatus(e).then(e=>{n()&&Object(k.a)(t,e||(i?"":""))})}setChoosingStickerTyping(e){i.a.setTyping(this.chat.peerId,{_:e?"sendMessageCancelAction":"sendMessageChooseStickerAction"})}};de.a&&(de.a.appImManager=Zo);var er=Zo;var tr=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 sr extends B.a{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(Object(c.a)(e),ue.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=Object(Me.a)(t,e),i)return!0}catch(e){return!1}}),i&&(s||"IMG"!==t.tagName&&"image"!==t.tagName)||this.buttons.close.click()},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&&Object(c.a)(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||Object(Me.a)(e.target,"media-viewer-caption")&&!this.ctrlKeyDown)&&(Object(c.a)(e),this.ctrlKeyDown)){const t=e.deltaY<0;this.changeZoom(!!t)}},this.log=Object(X.b)("AMV"),this.preloader=new ye.a,this.preloaderStreamable=new ye.a({cancelable:!1,streamable:!0}),this.preloader.construct(),this.preloaderStreamable.construct(),this.lazyLoadQueue=new ee.a,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"]=H("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 ur,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=H(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=H("zoomout",{noRipple:!0}),this.zoomElements.btnOut.addEventListener("click",()=>this.changeZoom(!1)),this.zoomElements.btnIn=H("zoomin",{noRipple:!0}),this.zoomElements.btnIn.addEventListener("click",()=>this.changeZoom(!0)),this.zoomElements.rangeSelector=new Se({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.setNewMover()}get target(){return this.listLoader.current}set target(e){this.listLoader.current=e}setListeners(){if(this.buttons.download.addEventListener("click",this.onDownloadClick),[this.buttons.close,this.buttons["mobile-close"],this.preloaderStreamable.preloader].forEach(e=>{e.addEventListener("click",this.close.bind(this))}),[[-1,this.buttons.prev],[1,this.buttons.next]].forEach(([e,t])=>{t.addEventListener("click",t=>{Object(c.a)(t),this.setMoverPromise||this.listLoader.go(e)})}),this.buttons.zoom.addEventListener("click",()=>{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)},ue.IS_TOUCH_SUPPORTED){new Vt({element:this.wholeDiv,onSwipe:(e,t)=>{if(Object(Te.d)())return;if(Math.abs(e)/Et.a.width>.2||e>125)return e<0?this.buttons.prev.click():this.buttons.next.click(),!0;return(Math.abs(t)/Et.a.height>.2||t>125)&&(this.buttons.close.click(),!0)},verifyTouchTarget:e=>"INPUT"!==e.target.tagName&&!Object(Me.a)(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 Vt({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&&Object(c.a)(e),this.setMoverAnimationPromise)return Promise.reject();j.a.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,C.a.checkAnimations(!1)}),s}setMoverToTarget(e,t=!1,s=0){return tr(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,c;e&&(e instanceof ur||e.classList.contains("grid-item")?(l=e,c=e.getBoundingClientRect()):e instanceof SVGImageElement||e.parentElement instanceof SVGForeignObjectElement?(l=Object(Me.a)(e,"attachment"),c=l.getBoundingClientRect()):e.classList.contains("profile-avatars-avatar")&&(l=Object(Me.a)(e,"profile-avatars-container"),c=l.getBoundingClientRect(),t&&e.getBoundingClientRect().left!==c.left&&(e=l=c=void 0))),e||(e=this.content.media),c||(l=e.parentElement,c=e.getBoundingClientRect());let d=!1;if(e!==this.content.media&&!e.classList.contains("profile-avatars-avatar")){const s=function(e,t){const s=e.getBoundingClientRect(),i=t.getBoundingClientRect();let{top:n,bottom:a}=i;const o=t.querySelector(".sticky");if(o){n=o.getBoundingClientRect().bottom}if(s.top>=a||s.bottom<=n||s.right<=i.left||s.left>=i.right)return null;const r={top:!1,right:!1,bottom:!1,left:!1,vertical:0,horizontal:0},l="visualViewport"in window?window.visualViewport:window,c=(l.width||l.innerWidth,l.height||l.innerHeight);return{rect:{top:s.top<n&&0!==n?(r.top=!0,++r.vertical,n):s.top,right:0,bottom:s.bottom>a&&a!==c?(r.bottom=!0,++r.vertical,a):s.bottom,left:0},overflow:r}}(l,Object(Me.a)(l,"scrollable"));!t||s&&2!==s.overflow.vertical&&2!==s.overflow.horizontal?!s||1!==s.overflow.vertical&&1!==s.overflow.horizontal||(d=!0):(l=(e=this.content.media).parentElement,c=e.getBoundingClientRect())}const h=this.content.media.getBoundingClientRect();let p,u,m,g="";if(o?(p=1===s?Et.a.width:-h.width,u=h.top):(p=c.left,u=c.top),g+=`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")){m=i.firstElementChild;const e=m.querySelector(".ckin__player");if(e){const t=e.firstElementChild;m.append(t),e.remove()}m.style.cssText||(i.classList.remove("active"),this.setFullAspect(m,h,c),i.offsetLeft,i.classList.add("active"))}else m=document.createElement("div"),m.classList.add("media-viewer-aspecter"),i.prepend(m);m.style.cssText=`width: ${c.width}px; height: ${c.height}px; transform: scale3d(${h.width/c.width}, ${h.height/c.height}, 1);`}i.style.width=h.width+"px",i.style.height=h.height+"px";const b=c.width/h.width,v=c.height/h.height;o||(g+=`scale3d(${b},${v},1) `);let f=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}(f);if(f=y.map(e=>parseInt(e)/b+"px").join(" "),o||(i.style.borderRadius=f),t&&1!==n){const e=Et.a.width/2-c.width/2,t=Et.a.height/2-c.height/2,s=c.left-e,i=c.top-t;this.moversContainer.style.transform=`matrix(${b}, 0, 0, ${v}, ${s}, ${i})`}else i.style.transform=g;let w;d&&(i.style.opacity="0");const S=e.classList.contains("is-out"),L=this.setMoverAnimationPromise=Object(ae.a)(),E={onAnimationEnd:L},C=setTimeout(()=>{L.isFulfilled||L.isRejected||L.resolve()},1e3);if(L.finally(()=>{this.dispatchEvent("setMoverAfter"),this.setMoverAnimationPromise===L&&(this.setMoverAnimationPromise=null),clearTimeout(C)}),t)return e instanceof SVGSVGElement&&(w=i.querySelector("path"),w&&this.sizeTailPath(w,h,b,r,!1,S,f)),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=f,i.firstElementChild&&(i.firstElementChild.style.borderRadius=f)},r/2),setTimeout(()=>{i.innerHTML="",i.classList.remove("moving","active","hiding"),i.style.cssText="display: none;",L.resolve()},r),i.classList.remove("opening"),E;{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/b:2/b}, ${a}) scale(${+i/b}, ${+o/v})`),l.setAttributeNS(null,"transform",t),w=r.firstElementChild.lastElementChild;const s=f.split(" ").map(e=>parseInt(e));e=S?uo(0,0,n-9/b,a,...s):uo(9/b,0,n-9/b,a,...s),w.setAttributeNS(null,"d",e)}const c=o.lastElementChild;c.setAttributeNS(null,"width",""+h.width),c.setAttributeNS(null,"height",""+h.height),i.prepend(o)}m&&(m.style.borderRadius=f,t&&m.append(t)),t=i.querySelector("video, img"),t instanceof HTMLImageElement&&(t.classList.add("thumbnail"),m||(t.style.width=h.width+"px",t.style.height=h.height+"px"),s&&(yield Object(rs.b)(t,s))),i.style.display="",Object(De.b)(()=>{i.classList.add(o?"moving":"active")})}return i.classList.add("opening"),yield Object(De.a)(),i.style.transform=`translate3d(${h.left}px,${h.top}px,0) scale3d(1,1,1)`,d&&(i.style.opacity=""),m&&this.setFullAspect(m,h,c),setTimeout(()=>{i.style.borderRadius="",i.firstElementChild&&(i.firstElementChild.style.borderRadius="")},0),i.dataset.timeout=""+setTimeout(()=>{i.classList.remove("moving","opening"),m&&(i.querySelector("video"),i.classList.remove("active"),m.style.cssText="",i.offsetLeft),i.classList.add("center","no-transition"),i.classList.add("active"),delete i.dataset.timeout,L.resolve()},r),w&&this.sizeTailPath(w,h,b,r,!0,S,f),E}))}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:c}=t;i/=2;const d=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=d.map(e=>e*o);let u;u=a?uo(0,0,l-9/s*o,c,...p):uo(9/s*o,0,l,c,...p),e.setAttributeNS(null,"d",u),t<i&&Object(De.b)(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=Et.a.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");if(e.classList.add("media-viewer-mover"),e.style.display="none",this.content.mover){this.content.mover.parentElement.append(e)}else this.moversContainer.append(e);return this.content.mover=e}updateMediaSource(e,t,s){const i=e.tagName.toLowerCase()===s?e:e.querySelector(s);if(i&&!Object(Me.a)(e,"document")){if(Object(Me.a)(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()}}Object(rs.a)(i,t),i.classList.contains("thumbnail")&&i.parentElement.classList.contains("media-container-aspecter")&&i.classList.remove("thumbnail")}}setAuthorInfo(e,t){Object(k.a)(this.author.date,Object(oe.d)(t));const s=e.isPeerId();let i;s?i=new Lt.a({peerId:e,dialog:!1,onlyFirstName:!1,plainText:!1}).element:(i=document.createElement("span"),i.innerHTML=J.b.wrapEmojiText(e),i.classList.add("peer-title")),Object(k.a)(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||Be.b)),n.parentElement.replaceChild(this.author.avatarEl,n)}_openMedia(e,t,s,i,n,o=!1,l=[],c=[],d){return tr(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;this.setAuthorInfo(s,t);const h="document"===e._,p=h&&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.buttons.prev.classList.toggle("hide",!this.listLoader.previous.length),this.buttons.next.classList.toggle("hide",!this.listLoader.next.length);const u=this.content.media,m=!n||n===u;m&&(n=u),this.target={element:n};const g=++this.tempId;u.firstElementChild&&(u.innerHTML="");if(0!==i)this.moveTheMover(this.content.mover,1===i),this.setNewMover();else{window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp),ue.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"),a.default.isOverlayActive=!0,C.a.checkAnimations(!0),re.IS_MOBILE_SAFARI||j.a.pushItem({type:"media",onPop:e=>{if(this.setMoverAnimationPromise)return!1;this.close()}})}const v=this.content.mover,f=Et.a.width;let y=0;const w=Et.a.height;w<1e6&&!b.b.isMobile&&(y=120);const S=w-120-y;let L=Promise.resolve();const I=r.a.setAttachmentSize(e,u,f,S,!b.b.isMobile,void 0,!!(h&&e.w&&e.h)).photoSize;if(m){const t=he.a.getCacheContext(e,I.type);let s;if(t.downloaded)s=new Image,s.src=t.url;else{const i=r.a.getStrippedThumbIfNeeded(e,t,!0);i&&(L=i.loadPromise,s=i.image)}s&&(s.classList.add("thumbnail"),u.append(s))}const M=!(!h||!e.supportsStreaming),P=M?this.preloaderStreamable:this.preloader;let T;if(p){const t=d&&"gif"!==e.type,s=document.createElement("video"),a=()=>this.setMoverToTarget(n,!1,i).then(({onAnimationEnd:i})=>{const a=v.firstElementChild&&v.firstElementChild.classList.contains("media-viewer-aspecter")?v.firstElementChild:v,o=v.querySelector("video");o&&o.remove(),s.setAttribute("playsinline","true"),s.addEventListener("timeupdate",()=>{this.tempId!==g&&s.pause()}),s.addEventListener("error",()=>{4!==s.error.code&&this.log.error("Error "+s.error.code+"; details: "+s.error.message),P&&P.detach()},{once:!0}),this.addEventListener("setMoverAfter",()=>{s.src="",s.load()},{once:!0}),re.IS_SAFARI&&(s.autoplay=!0),"gif"===e.type&&(s.muted=!0,s.autoplay=!0,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(()=>{if(this.tempId!==g)return;(this.videoPlayer=new Oe(s,!0,M)).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(M){i.then(()=>{s.readyState<s.HAVE_FUTURE_DATA&&P.attach(v,!0)});const e=()=>{s.addEventListener("canplay",()=>{P.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(),P.attach(v,!0),s.parentElement.classList.add("is-buffering"))}),e()}this.lazyLoadQueue.unshift({load:()=>{const o=he.a.getCacheContext(e),r=M?Promise.resolve():E.a.downloadDoc(e);return M||i.then(()=>{o.url||P.attach(v,!0,r)}),Promise.all([r,i]).then(()=>{if(this.tempId!==g)return void this.log.warn("media viewer changed video");if(t){const e=fe.setSingleMedia(s,d);this.addEventListener("setMoverBefore",()=>{e()},{once:!0})}const e=o.url;n instanceof SVGSVGElement?a.firstElementChild.lastElementChild.append(s):Object(rs.a)(s,e),this.updateMediaSource(n,e,"video"),l()}),r}})});T=L.then(a)}else{const t=()=>this.setMoverToTarget(n,!1,i).then(({onAnimationEnd:t})=>{this.lazyLoadQueue.unshift({load:()=>{const s=he.a.getCacheContext(e,I.type),i=h?E.a.downloadDoc(e):r.a.preloadPhoto(e,I);return t.then(()=>{s.url||this.preloader.attachPromise(i)}),Promise.all([t,i]).then(()=>{var e;if(this.tempId!==g)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(v,t,"img"),b.b.isMobile){const e=v.querySelectorAll("img");e&&e.length&&e.forEach(e=>{e.classList.remove("thumbnail")})}}else{const s=v.firstElementChild&&v.firstElementChild.classList.contains("media-viewer-aspecter")?v.firstElementChild:v,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"),Object(rs.a)(e,t,()=>{this.updateMediaSource(n,t,"img"),i&&Object(De.b)(()=>{i.remove()}),s.append(e)})}}}).catch(e=>{this.log.error(e),this.preloader.attach(v),this.preloader.setManual()}),i}})});T=L.then(t)}return this.setMoverPromise=T.catch(()=>{this.setMoverAnimationPromise=null}).finally(()=>{this.setMoverPromise=null})}))}}var ir=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 nr extends sr{constructor(){let e;super(new L({processItem:e=>{const t="inputMessagesFilterDocument"===this.searchContext.inputFilter._,{mid:s,peerId:n}=e,a=i.a.getMediaFromMessage(e);if(a&&(!t||nr.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 Ns({[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(b.b.isMobile){const e=Yt.getTab(Qt);e&&e.close()}er.setInnerPeer(n.peerId,t,i?"discussion":void 0,i)})}},this.onDownloadClick=()=>{const{peerId:e,mid:t}=this.target,s=this.getMessageByPeer(e,t);if(s.media.photo)r.a.savePhotoFile(s.media.photo,er.chat.bubbles.lazyLoadQueue.queueId);else{let e=null;e=s.media.webpage?s.media.webpage.document:s.media.document,e&&E.a.saveDocFile(e,er.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",()=>{b.b.isMobile&&(this.content.caption.classList.add("is-focused"),e&&(clearTimeout(e),e=void 0),document.addEventListener("touchend",t,{once:!0}))});new T.b(this.content.caption).onAdditionalScroll=t,this.wholeDiv.append(this.content.caption),Object(l.b)(this.buttons.delete,this.onDeleteClick);const s=[{icon:"forward",text:"Forward",onClick:this.onForwardClick},{icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick}];this.setBtnMenuToggle(s),this.btnMenuDelete=s[s.length-1].element,this.setListeners()}get searchContext(){return this.listLoader.searchContext}setListeners(){super.setListeners(),this.buttons.forward.addEventListener("click",this.onForwardClick),this.author.container.addEventListener("click",this.onAuthorClick);const e=t=>{if(t.target instanceof HTMLAnchorElement){const s=t.target.getAttribute("onclick");if(!s||s.includes("showMaskedAlert"))return;return Object(c.a)(t),this.close().then(()=>{this.content.caption.removeEventListener("click",e,{capture:!0}),t.target.click()}),!1}};this.content.caption.addEventListener("click",e,{capture:!0})}getMessageByPeer(e,t){return this.searchContext.isScheduled?i.a.getScheduledMessageByPeer(e,t):i.a.getMessageByPeer(e,t)}setCaption(e){const t=e.message;let s="";t&&(s=J.b.wrapRichText(t,{entities:e.totalEntities})),g(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 ir(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;const l=e.mid,c=e.fwd_from&&!e.fromId?e.fwd_from.from_name:e.fromId,d=i.a.getMediaFromMessage(e);this.buttons.forward.classList.toggle("hide","messageService"===e._);const h=i.a.canDeleteMessage(e);[this.buttons.delete,this.btnMenuDelete].forEach(e=>{e.classList.toggle("hide",!h)}),this.setCaption(e);const p=r._openMedia.call(this,d,e.date,c,s,t,n,a,o,e);return this.target.mid=l,this.target.peerId=e.peerId,p}))}static isMediaCompatibleForDocumentViewer(e){return"photo"===e._||m.has(e.mime_type)}}class ar extends S{constructor(e){super(Object.assign(Object.assign({},e),{loadMore:(e,t,s)=>{if(this.peerId.isAnyChat()||!t)return Promise.resolve({count:0,items:[]});const i=null==e?void 0:e.photoId;return r.a.getUserPhotos(this.peerId,i,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}}var or=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 rr extends sr{constructor(e){super(new ar({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.a.savePhotoFile(r.a.getPhoto(this.target.photoId),er.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 or(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;const o=r.a.getPhoto(e),l=a._openMedia.call(this,o,o.date,this.peerId,s,t,!1,i,n);return this.target.photoId=o.id,l}))}}var lr=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 cr=e=>{d.a.removeFromAvatarsCache(e),Array.from(document.querySelectorAll('avatar-element[peer="'+e+'"]')).forEach(e=>{e.update()})};function dr(e,t,s,a,o,l){return lr(this,void 0,void 0,(function*(){let c=yield n.default.getFullPhoto(t);if(!s()||!c)return;const d=()=>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.a.getSearch({peerId:t,inputFilter:{_:n},maxId:0,limit:1}).then(e=>e.history[0]),!s()))return;if(a){a.action.photo.id!==c.id&&(e||(a=i.a.generateFakeAvatarMessage(t,c)));const s=e=>e.map(e=>({element:e.element,mid:e.item.mid,peerId:e.item.peerId}));return void(new nr).setSearchContext({peerId:t,inputFilter:{_:n}}).openMedia(a,d(),void 0,void 0,o?s(o):void 0,l?s(l):void 0)}}if(c){Object(w.f)(a)||(c=r.a.getPhoto(a));const e=e=>e.map(e=>({element:e.element,photoId:e.item}));new rr(t).openMedia(c.id,d(),void 0,o?e(o):void 0,l?e(l):void 0)}}))}a.default.addEventListener("avatar_update",cr),a.default.addEventListener("peer_title_edit",e=>{d.a.isAvatarCached(e)||cr(e)});const hr=new Map,pr=new Set;class ur extends HTMLElement{constructor(){super(...arguments),this.isDialog=!1,this.addedToQueue=!1}connectedCallback(){if(this.isDialog="1"===this.getAttribute("dialog"),""===this.getAttribute("clickable")){this.setAttribute("clickable","set");let e=!1;Object(l.b)(this,t=>lr(this,void 0,void 0,(function*(){if(Object(c.a)(t),e)return;const s=this.peerId;e=!0,yield dr(this,this.peerId,()=>this.peerId===s),e=!1})))}}disconnectedCallback(){const e=hr.get(this.peerId);e&&e.has(this)&&(e.delete(this),e.size||hr.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()||Be.b;if(this.peerId===e)return;this.peerId=o.a.getPeerMigratedTo(e)||e;const i=(t||"").toPeerId()||Be.b;if(i){const e=hr.get(i);e&&(e.delete(this),e.size||hr.delete(i))}this.update()}else"peer-title"===e?this.peerTitle=s:"dialog"===e&&(this.isDialog="1"===s)}r(e=!1){const t=d.a.putPhoto(this,this.peerId,this.isDialog,this.peerTitle,e),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(!pr.has(this.peerId)){if(this.addedToQueue)return;this.addedToQueue=!0;let e=hr.get(this.peerId);return e||(e=new Set,hr.set(this.peerId,e)),e.add(this),this.r(!0),void this.lazyLoadQueue.push({div:this,load:()=>(pr.add(this.peerId),this.update())})}this.addedToQueue&&this.lazyLoadQueue.unobserve(this)}pr.add(this.peerId);const e=this.r(),t=e?e.loadPromise:Promise.resolve();this.addedToQueue&&t.finally(()=>{this.addedToQueue=!1});const s=hr.get(this.peerId);if(s){s.delete(this);const e=Array.from(s);hr.delete(this.peerId);for(let t=0,s=e.length;t<s;++t)e[t].update()}return t}}customElements.define("avatar-element",ur);class mr{constructor(){this.onArchiveClick=()=>{let e=i.a.getDialogOnly(this.selectedId);e&&i.a.editPeerFolders([e.peerId],+!e.folder_id)},this.onPinClick=()=>{i.a.toggleDialogPin(this.selectedId,this.filterId).catch(e=>{"PINNED_DIALOGS_TOO_MUCH"===e.type&&(this.filterId>=1?ct({langPackKey:"PinFolderLimitReached"}):new gt("pinned-dialogs-too-much",{buttons:[{langKey:"OK",isCancel:!0},{langKey:"FiltersSetupPinAlert",callback:()=>{new Xi(mn).open()}}],descriptionLangKey:"PinToTopLimitReached2",descriptionLangArgs:[Object(x.i18n)("Chats",[a.default.config.pinned_dialogs_count_max])]}).show())})},this.onUnmuteClick=()=>{i.a.mutePeer(this.selectedId,!1)},this.onMuteClick=()=>{i.a.mutePeer(this.selectedId,!0)},this.onUnreadClick=()=>{const e=i.a.getDialogOnly(this.selectedId);e&&(e.unread_count?(i.a.readHistory(this.selectedId,e.top_message),i.a.markDialogUnread(this.selectedId,!0)):i.a.markDialogUnread(this.selectedId))},this.onDeleteClick=()=>{new At(this.selectedId)},this.onContextMenu=e=>{this.init&&(this.init(),this.init=null);let t=null;try{t=Object(ft.a)(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=kr.filterId,this.selectedId=t.dataset.peerId.toPeerId(),this.dialog=i.a.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(Object(x.i18n)(o.a.getDeleteButtonText(this.selectedId))),t.classList.add("menu-open"),Object(te.e)(e,this.element),Object(te.d)(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.a.isDialogUnread(this.dialog)},{icon:"readchats",text:"MarkAsRead",onClick:this.onUnreadClick,verify:()=>i.a.isDialogUnread(this.dialog)},{icon:"pin",text:"ChatList.Context.Pin",onClick:this.onPinClick,verify:()=>{var e;return!(this.filterId>1?i.a.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.a.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&&!Dt.a.isPeerLocalMuted(this.dialog.peerId)},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:this.onUnmuteClick,verify:()=>this.selectedId!==a.default.myId&&Dt.a.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=Ee(this.buttons),this.element.id="dialogs-contextmenu",this.element.classList.add("contextmenu"),document.getElementById("page-chats").append(this.element)}}var gr,br;!function(e){e[e.Connected=0]="Connected",e[e.Connecting=1]="Connecting",e[e.Closed=2]="Closed",e[e.TimedOut=3]="TimedOut"}(gr||(gr={}));class vr{constructor(e){this.hadConnect=!1,this.connecting=!1,this.timedOut=!1,this.updating=!1,this.setConnectionStatus=()=>{cn.a.get("dc").then(e=>{e||(e=ln.a.baseDcId),this.setFirstConnectionTimeout&&(clearTimeout(this.setFirstConnectionTimeout),this.setFirstConnectionTimeout=0);const t=a.default.connectionStatus["NET-"+e],s=t&&t.status===gr.Connected;this.connecting&&s&&si.a.forceGetDifference(),s&&!this.hadConnect&&(this.hadConnect=!0),this.timedOut=t&&t.status===gr.TimedOut,this.connecting=!s,this.retryAt=t&&t.retryAt,de.b&&this.log("connecting",this.connecting),this.setState()})},this.setStatusText=(e,t)=>{this.currentLangPackKey!==e&&(this.currentLangPackKey=e,Object(k.a)(this.statusEl,Object(x.i18n)(e,t)),this.statusPreloader.attach(this.statusEl))},this.setState=()=>{const e=vr.CHANGE_STATE_DELAY;if(this.connecting)if(this.timedOut){const e=this.getA("ConnectionStatus.ForceReconnect",()=>ht.a.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",()=>ht.a.forceReconnectTimeout());this.setStatusText("ConnectionStatus.ReconnectIn",[e,n])}else this.setStatusText("ConnectionStatus.Reconnecting");else this.setStatusText("ConnectionStatus.Waiting");else this.updating&&this.setStatusText("Updating");de.b&&this.log("setState",this.connecting||this.updating),window.requestAnimationFrame(()=>{this.setStateTimeout&&clearTimeout(this.setStateTimeout);this.setStateTimeout=window.setTimeout(()=>{Object(Jt.a)(this.statusContainer,"is-shown",this.connecting||this.updating,200),this.setStateTimeout=0,de.b&&this.log("setState: isShown:",this.connecting||this.updating)},e)})},this.log=Object(X.b)("CS",void 0,void 0),this.statusContainer=document.createElement("div"),this.statusContainer.classList.add("connection-status"),this.statusEl=Object(U.a)("btn-primary bg-warning connection-status-button",{noRipple:!0}),this.statusPreloader=new ye.a({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,de.b&&this.log("updating",this.updating),this.setState())}),a.default.addEventListener("state_synchronized",e=>{de.b&&this.log("state_synchronized",e),e||(this.updating=!1,de.b&&this.log("updating",this.updating),this.setState())}),this.setFirstConnectionTimeout=window.setTimeout(this.setConnectionStatus,vr.CHANGE_STATE_DELAY+1e3)}getA(e,t){const s=document.createElement("a");return s.classList.add("force-reconnect"),s.append(Object(x.i18n)(e)),s.addEventListener("click",e=>{Object(c.a)(e),t()}),s}}function fr(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()}vr.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"}(br||(br={}));const yr=window.devicePixelRatio,wr=20*yr,Sr=2.5*yr,Lr=2*yr,Er=1*yr;function Cr(e=!1){const t=document.createElement("canvas");t.width=t.height=wr;const s=t.getContext("2d"),i=(wr-(3*Lr+2*Sr))/2,n=Date.now();let a=!1;const o=()=>{if(t.isConnected)a||(a=t.isConnected);else if(a)return!1;const o=Date.now(),r=(l=(o-n)%1e3,c=0,d=1e3,-1/2*(Math.cos(Math.PI*l/d)-1)+c);var l,c,d;s.clearRect(0,0,wr,wr),s.fillStyle=e&&!b.b.isMobile?Io.getProperty("primary-color"):"#fff";for(let e=0;e<3;++e){let t;t=r>=.5?e%2?2-2*r:2*(r-.5):e%2?2*r:1-2*r;let n=4+8*t;n*=yr;fr(s,i+e*Lr+e*Sr,(wr-n)/2,Lr,n,Er,!0)}return!0};return{canvas:t,startAnimation:()=>{Object(os.a)(o),o()},setActive:t=>{e=t,o()}}}var Ir=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 Mr extends _s{constructor(e,t,s){super({getIndex:e=>i.a.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;As(e.dom.listEl,this.list,t),s&&this.onListLengthChange&&this.onListLengthChange()},onElementCreate:(e,t)=>{const s=t?[]:void 0,{dom:i}=Tr.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.c}),this.list=e,this.indexKey=t,this.onListLengthChange=s}clear(){this.list.innerHTML="",super.clear()}}class Pr{constructor(){this.chatsContainer=document.getElementById("chatlist-container"),this.scroll=null,this.log=Object(X.b)("DIALOGS",X.a.Log|X.a.Error|X.a.Warn|X.a.Debug),this.contextMenu=new mr,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 dn({name:"Contacts",noDelimiter:!0,fakeGradientDelimiter:!0});a.container.classList.add("hide"),P.a.getContactsPeerIds(void 0,void 0,"online").then(e=>{let t=!1;const s=()=>{t&&a.container.classList.toggle("hide",!i.list.childElementCount)},i=new Ds({avatarSize:42,createChatListOptions:{dialogSize:48,new:!0},autonomous:!1,onListLengthChange:s});this.loadContacts=()=>{const t=Et.a.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.a.getDialogOnly(e),this.onChatsRegularScroll=()=>{this.sliceTimeout&&clearTimeout(this.sliceTimeout),this.sliceTimeout=window.setTimeout(()=>{this.sliceTimeout=void 0,this.chatList.childElementCount&&!this.processContact&&Object(De.c)(()=>{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,c=Object(ft.a)(document.elementFromPoint(Math.ceil(n.x),Math.ceil(r+1)),s.tagName),d=Object(ft.a)(document.elementFromPoint(Math.ceil(n.x),Math.floor(l+i.height-1)),s.tagName);if(!c||!d)return;const h=c.getBoundingClientRect().y-r,p=[],u=a.indexOf(c),m=a.indexOf(d),g=re.IS_SAFARI?[]:a.slice(0,Math.max(0,u-10)),b=a.slice(m+10);g.length&&(this.scroll.loadedAll.top=!1),b.length&&(this.scroll.loadedAll.bottom=!1),p.push(...g),p.push(...b),p.forEach(e=>{const t=e.dataset.peerId.toPeerId();this.deleteDialog(t)}),this.setOffsets(),this.scroll.scrollTop=c.offsetTop-h,this.log("slice time",performance.now()-e)})},200)},this.onChatsScrollTop=()=>{this.onChatsScroll("top")},this.onChatsScroll=(e="bottom")=>{if(!this.scroll.loadedAll[e])return this.loadDialogsPromise?this.loadDialogsPromise:(this.log("onChatsScroll",e),this.loadDialogs(e));this.loadContacts&&this.loadContacts()},this.chatsPreloader=Object(te.f)(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),ue.IS_TOUCH_SUPPORTED&&Rs({element:this.folders.container,onSwipe:e=>{const t=s.prevId();s(e>0?t+1:t-1)}}),this.setFilterId(0),this.addFilter({id:this.filterId,title:"",titleEl:Object(x.i18n)("ChatList.Filter.AllChats"),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,P.a.clear(),K.a.clear();const t=i.a.filtersStorage.filters;for(const e in t)a.default.dispatchEvent("updateDialogFilter",{_:"updateDialogFilter",id:+e});i.a.clear(),this.sortedList.clear(),this.onTabChange(),this.onStateLoaded(e)})});const t=new T.a(this.folders.menuScrollContainer);e.prepend(this.folders.menuScrollContainer);const s=Object(Z.a)(this.folders.menu,this.folders.container,(e,t)=>{e=+t.dataset.filterId||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.a.construct(),M.default.getState().then(e=>this.onStateLoaded(e)),new vr(this.chatsContainer),this.chatsContainer.append(e),setTimeout(()=>{le.a.loadLottieWorkers()},200)}get chatList(){return this.sortedList.list}setFilterId(e){this.filterId=e,this.indexKey=i.a.dialogsStorage?i.a.dialogsStorage.getDialogIndexKey(this.filterId):"index",a.default.filterId=e}setOnlineStatus(e,t){const s=e.classList.contains("is-online");!s&&t&&e.classList.add("is-online"),Object(Jt.a)(e,"is-visible",t,250,t?void 0:()=>{e.classList.remove("is-online")},t&&!s?2:0)}initListeners(){a.default.addEventListener("user_update",e=>{var t;const s=e.toPeerId(),i=this.getDialogDom(s);if(i&&!P.a.isBot(e)&&s!==a.default.myId){const s="userStatusOnline"===(null===(t=P.a.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.a.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.a.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.a.getDialogOnly(e);t&&(this.setUnreadMessages(t),this.validateDialogForFilter(t))}),a.default.addEventListener("dialog_notify_settings",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])return void this.addFilter(e);if(e.id===this.filterId){const e=i.a.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=J.a.wrapEmojiText(e.title)}),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],Object.keys(this.filtersRendered).length<=1&&this.folders.menuScrollContainer.classList.add("hide"))}),a.default.addEventListener("filter_order",e=>{const t=this.folders.menu;e.forEach(e=>{const s=i.a.filtersStorage.getFilter(e),n=this.filtersRendered[e];this.sortedLists[e].indexKey=i.a.dialogsStorage.getDialogIndexKey(e),As(n.menu,t,s.orderIndex),As(n.container,this.folders.container,s.orderIndex)}),this.indexKey=i.a.dialogsStorage.getDialogIndexKey(this.filterId)}),a.default.addEventListener("peer_typings",({peerId:e,typings:t})=>{const s=i.a.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 Ir(this,void 0,void 0,(function*(){Dt.a.getNotifyPeerTypeSettings(),this.initedListeners||(this.initListeners(),this.initedListeners=!0);const t=i.a.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&&Pi.a.addMissedDialogs(),this.onChatsScroll().then(()=>{i.a.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.a.dialogsStorage.getFolder(e),a=0===e||!!n.dialogs.find(e=>(e.unread_count||e.pFlags.unread_mark)&&!Dt.a.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);this.setFilterUnreadCount(0)}validateListForFilter(){const e=i.a.filtersStorage.getFilter(this.filterId)||null;this.sortedList.getAll().forEach(t=>{const s=i.a.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.a.filtersStorage.getFilter(this.filterId)){return!(!e||t&&!i.a.filtersStorage.testDialogForFilter(e,t)||!t&&this.filterId!==e.folder_id)}generateScrollable(e,t){const s=new T.b(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 Mr(e,i.a.dialogsStorage?i.a.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=J.a.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),t.append(s),Object(se.ripple)(t);As(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 c=document.createElement("div");c.classList.add("chatlist-bottom"),l.append(o),r.container.append(l,c);const d=r.container;As(r.container,this.folders.container,e.orderIndex),this.setListClickListener(o,null,!0),this.filtersRendered[e.id]={menu:t,container:d,unread:n,title:i},!this.showFiltersPromise&&Object.keys(this.filtersRendered).length>1&&(this.showFiltersPromise=new Promise(e=>{window.setTimeout(()=>{this.showFiltersPromise=void 0,Object.keys(this.filtersRendered).length>1&&(this.folders.menuScrollContainer.classList.remove("hide"),this.setFiltersUnreadCount()),e()},0)}))}loadDialogs(e){if(this.loadDialogsPromise)return this.loadDialogsPromise;const t=new Promise(s=>Ir(this,void 0,void 0,(function*(){const{chatList:n,filterId:a,indexKey:o}=this;let r=Et.a.height/72*1.25|0,l=0;const{index:c}=this.getOffsetIndex(e);if(c)if("top"===e){const e=i.a.dialogsStorage.getFolderDialogs(a,!0),t=e.findIndex(e=>e[o]<=c),s=Math.max(0,t-r);r=t-s,l=e[s][o]+1}else l=c;try{const s=i.a.getConversations("",l,r,a,!0);if(!s.cached&&!n.childElementCount){n.parentElement.append(this.chatsPreloader)}const c=yield s.promise;if(this.loadDialogsPromise!==t)return;if("bottom"===e?c.isEnd&&(this.scroll.loadedAll[e]=!0):c.isTopEnd&&(this.scroll.loadedAll[e]=!0),this.loadedDialogsAtLeastOnce=!0,c.dialogs.length){const t="top"===e?c.dialogs.slice().reverse():c.dialogs,s=[],n=[],a=e=>{n.push(e)};t.forEach(e=>{if(!i.a.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 d=c.dialogs["top"===e?0:c.dialogs.length-1];d&&(this.offsets[e]=d[o]),this.log.debug("getDialogs "+r+" dialogs by offset:",l,c,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"),Object(x._i18n)(i,e.title);const n=document.createElement("div");return n.classList.add(t+"-subtitle"),e.subtitle&&Object(x._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;if(this.filterId){a=this.generateEmptyPlaceholder({title:"FilterNoChatsToDisplay",subtitle:"FilterNoChatsToDisplayInfo",classNameType:"folder"}),s=a.container,s.prepend(function({emoji:e,width:t,height:s}){const i=document.createElement("div"),n=us.getAnimatedEmojiSticker(e);return n?Cs({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=Object(U.a)("btn-primary btn-color-primary btn-control tgico",{text:"FilterHeaderEdit",icon:"settings"});Object(l.b)(e,()=>{new $i(mn).open(i.a.filtersStorage.getFilter(this.filterId))}),s.append(e)}else{a=this.generateEmptyPlaceholder({title:"ChatList.Main.EmptyPlaceholder.Title",classNameType:"dialogs"}),s=a.container;const e=document.createElement("img");e.classList.add("empty-placeholder-dialogs-icon"),Promise.all([P.a.getContacts().then(e=>{let t,s;e.length?(t="ChatList.Main.EmptyPlaceholder.Subtitle",s=[Object(x.i18n)("Contacts.Count",[e.length])]):(t="ChatList.Main.EmptyPlaceholder.SubtitleNoContacts",s=[]);new x.default.IntlElement({key:t,args:s,element:a.subtitle})}),Object(rs.b)(e,"assets/img/EmptyChats.svg"),Object(De.d)()]).then(()=>{s.classList.add("visible")}),s.prepend(e)}t.append(s),t.classList.add("with-placeholder")}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.a.getDialogOnly(e.dataset.peerId.toPeerId())}setListClickListener(e,t,s=!1,n=!1,a=!1){let o;const r=(a?er.setInnerPeer:er.setPeer).bind(er);e.dataset.autonomous=""+ +n,e.addEventListener("mousedown",e=>{if(0!==e.button)return;this.log("dialogs click list");const s=e.target,i=Object(ft.a)(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(e,s)}else r(Be.b)}},{capture:!0}),de.b&&e.addEventListener("dblclick",e=>{const t=Object(ft.a)(e.target,"LI");if(t){const e=t.dataset.peerId.toPeerId();this.log("debug dialog:",i.a.getDialogByPeerId(e))}}),s&&Object(te.a)(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,c=!1,d=!1){if(!s&&!(s=this.getDialogDom(e.peerId)))return;let h;if(t||(e.draft&&"draftMessage"===e.draft._&&(h=e.draft),t=i.a.getMessageByPeer(e.peerId,e.top_message)),"messageEmpty"===t._)return s.lastMessageSpan.innerHTML="",s.lastTimeSpan.innerHTML="",delete s.listEl.dataset.mid,void(d&&this.setUnreadMessages(e,s,c));const p=e.peerId;{let e;if(!t.deleted&&!h){const s=i.a.getMediaFromMessage(t);if(s&&("photo"===s._||["video","gif"].includes(s.type))){const i=r.a.choosePhotoSize(s,20,20);if("photoSizeEmpty"!==i._&&(e=document.createElement("div"),e.classList.add("dialog-subtitle-media"),Ls({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 c=!!e&&!!(null==t?void 0:t.message);let d;if(d=n&&t.message?i.a.wrapMessageForReply(t,void 0,void 0,!1,n,c):h?i.a.wrapMessageForReply(h):t.deleted?document.createDocumentFragment():i.a.wrapMessageForReply(t,void 0,void 0,!1,void 0,c),e&&d.prepend(e),Object(k.a)(s.lastMessageSpan,d),h){const e=document.createElement("b");e.classList.add("danger"),e.append(Object(x.i18n)("Draft"),": "),s.lastMessageSpan.prepend(e)}else if(p.isAnyChat()&&p!==t.fromId&&!t.action){const e=o.a.getPeer(t.fromId);if(e&&e.id){const i=document.createElement("b");e.id===a.default.myId?i.append(Object(x.i18n)("FromYou")):i.append(new Lt.a({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;Object(k.a)(s.lastTimeSpan,Object(oe.c)(new Date(1e3*e)))}else s.lastTimeSpan.textContent="";null!==d&&(d?this.setUnreadMessages(e,s,c):s.listEl.dataset.mid=t.mid)}setUnreadMessages(e,t=this.getDialogDom(e.peerId),s=!1){var n;if(!t)return;if(!s){const s=Dt.a.isPeerLocalMuted(e.peerId,!0);s!==t.listEl.classList.contains("is-muted")&&Object(Jt.a)(t.listEl,"is-muted",s,200)}let o;if("draftMessage"!==(null===(n=e.draft)||void 0===n?void 0:n._)){const t=i.a.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.a.filtersStorage.getFilter(this.filterId);let l;l=r?-1!==r.pinnedPeerIds.indexOf(e.peerId):!!e.pFlags.pinned;const c=i.a.isDialogUnread(e),d=l||c,h=Object(ms.a)(t.unreadBadge);d&&!h&&t.subtitleEl.append(t.unreadBadge);const p=e.unread_mentions_count&&(e.unread_mentions_count>1||e.unread_count>1),u=t.mentionsBadge&&Object(ms.a)(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 m=s?0:200;if(Object(Jt.a)(t.unreadBadge,"is-visible",d,m,d?void 0:()=>{t.unreadBadge.remove()},h?0:2),t.mentionsBadge&&Object(Jt.a)(t.mentionsBadge,"is-visible",p,m,p?void 0:()=>{t.mentionsBadge.remove(),delete t.mentionsBadge},u?0:2),!d)return;l?t.unreadBadge.classList.add("tgico-chatspinned","tgico"):t.unreadBadge.classList.remove("tgico-chatspinned","tgico");let g=!0,b=!1;e.unread_mentions_count&&1===e.unread_count?(t.unreadBadge.innerText="@",b=!0):c?t.unreadBadge.innerText=""+(e.unread_count||" "):(t.unreadBadge.innerText="",g=!1),t.unreadBadge.classList.toggle("unread",g),t.unreadBadge.classList.toggle("mention",b)}getDialogDom(e){const t=this.sortedList.get(e);return null==t?void 0:t.dom}getDialog(e){if("object"!=typeof e&&e){const t=i.a.getDialogOnly(e);return t||{peerId:e,peer:o.a.getOutputPeer(e),pFlags:{}}}return e}setCallStatus(e,t){let{callIcon:s,listEl:i}=e;if(!s&&t){const{canvas:t,startAnimation:n}=e.callIcon=s=Cr(i.classList.contains("active"));t.classList.add("dialog-group-call-icon"),i.append(t),n()}s&&Object(Jt.a)(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;Dt.a.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(!no)return;if(t||(t=this.getDialogDom(e.peerId)),!t)return;const s=K.a.getChat(e.peerId.toChatId());this.setCallStatus(t,!(!s.pFlags.call_active||!s.pFlags.call_not_empty))}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)}addDialog(e,t,s=!0,i=!0,n=!1,r=!0,l=!0,c=54,d=!!t,h,p){var u,m,g;const b=this.getDialog(e),v=b.peerId,f=new ur;if(f.loadPromises=p,f.lazyLoadQueue=h,f.setAttribute("dialog",r?"1":"0"),f.setAttribute("peer",""+v),f.classList.add("dialog-avatar","avatar-"+c),s&&v!==a.default.myId&&v.isUser()){"userStatusOnline"===(null===(u=P.a.getUser(v).status)||void 0===u?void 0:u._)&&this.setOnlineStatus(f,!0)}const y=document.createElement("div");y.classList.add("user-caption");const w=document.createElement("span");w.classList.add("user-title");const S=new Lt.a({peerId:v,dialog:r,onlyFirstName:n,plainText:!1});w.append(S.element),w.classList.add("tgico");const L=o.a.getPeer(v);(null===(m=null==L?void 0:L.pFlags)||void 0===m?void 0:m.verified)&&w.append(Ut());const E=document.createElement("span");E.classList.add("user-last-message"),E.setAttribute("dir","auto");const C=document.createElement("li");C.classList.add("chatlist-chat"),i&&Object(se.ripple)(C),C.append(f,y),C.dataset.peerId=""+v;const I=document.createElement("span");I.classList.add("message-status","sending-status");const M=document.createElement("span");M.classList.add("message-time");const T=document.createElement("div");T.className="dialog-subtitle-badge badge badge-24";const k=document.createElement("p");k.classList.add("dialog-title");const x=document.createElement("span");x.classList.add("dialog-title-details"),x.append(I,M),k.append(w,x);const O=document.createElement("p");O.classList.add("dialog-subtitle"),O.append(E),y.append(k,O);const A={avatarEl:f,captionDiv:y,titleSpan:S.element,titleSpanContainer:w,statusSpan:I,lastTimeSpan:M,unreadBadge:T,lastMessageSpan:E,containerEl:C,listEl:C,subtitleEl:O};if(t){t[l?"append":"prepend"](C)}return d||(C.dialogDom=A,(null===(g=er.chat)||void 0===g?void 0:g.peerId)===v&&this.setDialogActive(C,!0)),{dom:A,dialog:b}}setTyping(e){const t=this.getDialogDom(e.peerId);if(!t)return;let s=t.lastMessageSpan.querySelector(".peer-typing-container");s?er.getPeerTyping(e.peerId,s):(s=er.getPeerTyping(e.peerId),Object(k.a)(t.lastMessageSpan,s),t.lastMessageSpan.classList.add("user-typing"))}unsetTyping(e){const t=this.getDialogDom(e.peerId);t&&(t.lastMessageSpan.classList.remove("user-typing"),this.setLastMessage(e,null,t,void 0,void 0,void 0,null))}}const Tr=new Pr;de.a.appDialogsManager=Tr;var kr=t.default=Tr},154:function(e,t,s){"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: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}])},18:function(e,t,s){"use strict";s.r(t),s.d(t,"ripple",(function(){return l}));var i=s(6),n=s(60),a=s(1),o=s(15);let r=0;function l(e,t=(()=>Promise.resolve()),s=null,l=!1){if(e.querySelector(".c-ripple"))return;e.classList.add("rp");let c=document.createElement("div");c.classList.add("c-ripple");let d;e.classList.contains("rp-square")&&c.classList.add("is-square"),e[l?"prepend":"append"](c);const h=(e,i)=>{const o=Date.now(),l=document.createElement("div"),h=r++,p=1e3*+window.getComputedStyle(c).getPropertyValue("--ripple-duration").replace("s","");d=()=>{let e=Date.now()-o;const t=()=>{n.a.mutate(()=>{l.remove()}),s&&s(h)};if(e<p){let s=Math.max(p-e,p/2);setTimeout(()=>l.classList.add("hiding"),Math.max(s-p/2,0)),setTimeout(t,s)}else l.classList.add("hiding"),setTimeout(t,p/2);a.IS_TOUCH_SUPPORTED||window.removeEventListener("contextmenu",d),d=null,u=!1},t&&t(h),window.requestAnimationFrame(()=>{const t=c.getBoundingClientRect();l.classList.add("c-ripple__circle");const s=e-t.left,n=i-t.top,a=Math.sqrt(Math.pow(Math.abs(n-t.height/2)+t.height/2,2)+Math.pow(Math.abs(s-t.width/2)+t.width/2,2)),o=s-a/2,r=n-a/2;l.style.width=l.style.height=a+"px",l.style.left=o+"px",l.style.top=r+"px",c.append(l)})},p=t=>t.target!==e&&(["BUTTON","A"].includes(t.target.tagName)||Object(i.a)(t.target,"c-ripple")!==c);let u=!1;if(a.IS_TOUCH_SUPPORTED){let t=()=>{d&&d()};e.addEventListener("touchstart",s=>{if(!o.default.settings.animationsEnabled)return;if(s.touches.length>1||u||p(s))return;u=!0;let{clientX:i,clientY:n}=s.touches[0];h(i,n),e.addEventListener("touchend",t,{once:!0}),window.addEventListener("touchmove",s=>{s.cancelBubble=!0,s.stopPropagation(),t(),e.removeEventListener("touchend",t)},{once:!0})},{passive:!0})}else e.addEventListener("mousedown",t=>{if(![0,2].includes(t.button))return;if(!o.default.settings.animationsEnabled)return;if("0"===e.dataset.ripple||p(t))return;if(u)return void(u=!1);let{clientX:s,clientY:i}=t;h(s,i),window.addEventListener("mouseup",d,{once:!0,passive:!0}),window.addEventListener("contextmenu",d,{once:!0,passive:!0})},{passive:!0})}},30:function(e,t,s){"use strict";s.d(t,"a",(function(){return a})),s.d(t,"b",(function(){return o})),s.d(t,"c",(function(){return r})),s.d(t,"d",(function(){return l}));var i=s(1),n=s(52);const a=i.IS_TOUCH_SUPPORTED?"mousedown":"click";function o(e,t,s={}){const i=s.listenerSetter?s.listenerSetter.add(e):e.addEventListener.bind(e);s.touchMouseDown=!0,i(a,t,s)}function r(e,t,s){e.removeEventListener(a,t,s)}function l(e){Object(n.a)(e,a)}},34:function(e,t,s){"use strict";var i=s(16),n=s(18);t.a=(e,t={})=>{const s=document.createElement(t.asDiv?"div":"button");return s.className=e+(t.icon?" tgico-"+t.icon:""),t.noRipple||(t.rippleSquare&&s.classList.add("rp-square"),Object(n.ripple)(s)),t.onlyMobile&&s.classList.add("only-handhelds"),t.disabled&&s.setAttribute("disabled","true"),t.text&&s.append(Object(i.i18n)(t.text)),s}},35:function(e,t,s){"use strict";s.d(t,"f",(function(){return h})),s.d(t,"g",(function(){return p})),s.d(t,"c",(function(){return g})),s.d(t,"d",(function(){return y})),s.d(t,"e",(function(){return w})),s.d(t,"b",(function(){return E})),s.d(t,"a",(function(){return C}));var i=s(29),n=s(5),a=s(30),o=s(37),r=s(1),l=s(0),c=s(15),d=s(50);function h(e,t=!1){const s='\n <svg xmlns="http://www.w3.org/2000/svg" class="preloader-circular" viewBox="25 25 50 50">\n <circle class="preloader-path" cx="50" cy="50" r="20" fill="none" stroke-miterlimit="10"/>\n </svg>';if(t){const t=document.createElement("div");return t.classList.add("preloader"),t.innerHTML=s,e&&e.appendChild(t),t}return e.insertAdjacentHTML("beforeend",s),e.lastElementChild}function p(e,t="check"){return e.classList.remove("tgico-"+t),e.disabled=!0,h(e),()=>{e.innerHTML="",e.classList.add("tgico-"+t),e.removeAttribute("disabled")}}i.a.putPreloader=h;let u=e=>{let t=b.getBoundingClientRect(),{clientX:s,clientY:i}=e,n=s>=t.right?s-t.right:t.left-s,a=i>=t.bottom?i-t.bottom:t.top-i;(n>=100||a>=100)&&g()};const m=e=>{g()},g=()=>{b&&(b.classList.remove("active"),b.parentElement.classList.remove("menu-open"),f&&f.remove(),b=null,c.default.dispatchEvent("context_menu_toggle",!1)),v&&(v(),v=null),r.IS_TOUCH_SUPPORTED||(window.removeEventListener("mousemove",u),window.removeEventListener("contextmenu",m)),document.removeEventListener(a.a,m),l.IS_MOBILE_SAFARI||d.a.removeByType("menu")};window.addEventListener("resize",()=>{b&&g()});let b=null,v=null,f=null;function y(e,t){g(),l.IS_MOBILE_SAFARI||d.a.pushItem({type:"menu",onPop:e=>{g()}}),b=e,b.classList.add("active"),b.parentElement.classList.add("menu-open"),f||(f=document.createElement("div"),f.classList.add("btn-menu-overlay"),f.addEventListener(a.a,e=>{Object(n.a)(e),m()})),b.parentElement.insertBefore(f,b),v=t,r.IS_TOUCH_SUPPORTED||(window.addEventListener("mousemove",u),window.addEventListener("contextmenu",m,{once:!0})),document.addEventListener(a.a,m),c.default.dispatchEvent("context_menu_toggle",!0)}function w({pageX:e,pageY:t},s,i){let{scrollWidth:n,scrollHeight:a}=s;const r=document.body.getBoundingClientRect(),l=r.width,c=r.height;i=o.b.isMobile?"right":"left";let d="top";const h={x:{left:e,right:e-n},intermediateX:"right"===i?8:l-n-8,y:{top:t,bottom:t-a},intermediateY:t<c/2?8:c-a-8},p={left:h.x.left+n+8<=l,right:h.x.right>=8},u={top:h.y.top+a+8<=c,bottom:h.y.bottom-8>=8};{let e;e=p[i]?h.x[i]:(i="center",h.intermediateX),s.style.left=e+"px"}{let e;e=u[d]?h.y[d]:(d="center",h.intermediateY),s.style.top=e+"px"}s.className=s.className.replace(/(top|center|bottom)-(left|center|right)/g,""),s.classList.add(("center"===d?d:"bottom")+"-"+("center"===i?i:"left"===i?"right":"left"))}let S=!1,L=0;function E(){L&&clearTimeout(L),L=window.setTimeout(()=>{L=0,S=!1},400),S=!0}function C(e,t,s){const i=s?s.add(e):e.addEventListener.bind(e),a=s?s.removeManual.bind(s,e):e.removeEventListener.bind(e);if(l.IS_APPLE&&r.IS_TOUCH_SUPPORTED){let s;const o={capture:!0},r=()=>{clearTimeout(s),a("touchmove",r,o),a("touchend",r,o),a("touchcancel",r,o)};i("touchstart",a=>{a.touches.length>1?r():(i("touchmove",r,o),i("touchend",r,o),i("touchcancel",r,o),s=window.setTimeout(()=>{S?r():(t(a.touches[0]),r(),b&&e.addEventListener("touchend",n.a,{once:!0}))},400))})}else i("contextmenu",r.IS_TOUCH_SUPPORTED?s=>{t(s),b&&e.addEventListener("touchend",n.a,{once:!0})}:t)}},50:function(e,t,s){"use strict";var i=s(29),n=s(0),a=s(43),o=s(7),r=s(5),l=s(41),c=s(72);const d=new class{constructor(){this.navigations=[],this.id=Date.now(),this.manual=!1,this.log=Object(a.b)("NC"),this.debug=!0,this.currentHash=window.location.hash;let e=!1;if(window.addEventListener("popstate",t=>{if(this.debug&&this.log("popstate",t,e),window.location.hash!==this.currentHash)return this.onHashChange&&this.onHashChange(),void this.replaceState();this.currentHash=window.location.hash;if(t.state!==this.id)return void this.pushState();const s=this.navigations.pop();s?(this.manual=!e,this.handleItem(s)):this.pushState()}),window.addEventListener("keydown",e=>{const t=this.navigations[this.navigations.length-1];t&&("Escape"!==e.key||t.onEscape&&!t.onEscape()||(Object(r.a)(e),this.back(t.type)))},{capture:!0,passive:!1}),n.IS_MOBILE_SAFARI){const t={passive:!0};window.addEventListener("touchstart",t=>{t.touches.length>1||(this.debug&&this.log("touchstart"),Object(c.a)(t)&&(e=!0,window.addEventListener("touchend",()=>{setTimeout(()=>{e=!1},100)},{passive:!0,once:!0})))},t)}history.scrollRestoration="manual",this.pushState()}handleItem(e){const t=e.onPop(!!this.manual&&void 0);this.debug&&this.log("popstate, navigation:",e,this.navigations),!1===t?this.pushItem(e):e.noBlurOnPop||Object(o.a)(),this.manual=!1}findItemByType(e){for(let t=this.navigations.length-1;t>=0;--t){const s=this.navigations[t];if(s.type===e)return{item:s,index:t}}}back(e){if(e){const t=this.findItemByType(e);if(t)return void this.backByItem(t.item,t.index)}history.back()}backByItem(e,t=this.navigations.indexOf(e)){this.manual=!0,this.navigations.splice(t,1),this.handleItem(e)}pushItem(e){this.navigations.push(e),this.debug&&this.log("pushstate",e,this.navigations),e.noHistory||this.pushState()}pushState(){this.manual=!1,history.pushState(this.id,"")}replaceState(){history.replaceState(this.id,"",location.origin+location.pathname)}removeItem(e){Object(l.e)(this.navigations,e)}removeByType(e,t=!1){for(let s=this.navigations.length-1;s>=0;--s){if(this.navigations[s].type===e&&(this.navigations.splice(s,1),t))break}}};i.a.appNavigationController=d,t.a=d},52:function(e,t,s){"use strict";function i(e,t){const s=new Event(t,{bubbles:!0,cancelable:!0});e.dispatchEvent(s)}s.d(t,"a",(function(){return i}))},60:function(e,t,s){"use strict";var i=s(42),n=s(46),a=s(29),o=s(61);const r=new class{constructor(){this.promises={},this.raf=i.b.bind(null),this.scheduled=!1}do(e,t){let s=this.promises[e];return s||(this.scheduleFlush(),s=this.promises[e]=Object(n.a)()),void 0!==t&&s.then(()=>t()),s}measure(e){return this.do("read",e)}mutate(e){return this.do("write",e)}mutateElement(e,t){const s=Object(o.a)(e)?this.mutate():Promise.resolve();return void 0!==t&&s.then(()=>t()),s}scheduleFlush(){this.scheduled||(this.scheduled=!0,this.raf(()=>{this.promises.read&&this.promises.read.resolve(),this.promises.write&&this.promises.write.resolve(),this.scheduled=!1,this.promises={}}))}};a.a&&(a.a.sequentialDom=r),t.a=r},72:function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var i=s(0);function n(e){return i.IS_MOBILE_SAFARI&&e instanceof TouchEvent&&e.touches[0].clientX<30}},79:function(e,t,s){"use strict";var i=s(29),n=s(33);const a=new class{getState(){return n.a.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.a.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.a.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.a.invokeApi("account.updatePasswordSettings",a)))})}check(e,t,s={}){return n.a.invokeCrypto("computeSRP",e,t,!1).then(e=>n.a.invokeApi("auth.checkPassword",{password:e},s).then(e=>("auth.authorization"===e._&&n.a.setUser(e.user),e)))}confirmPasswordEmail(e){return n.a.invokeApi("account.confirmPasswordEmail",{code:e})}resendPasswordEmail(){return n.a.invokeApi("account.resendPasswordEmail")}cancelPasswordEmail(){return n.a.invokeApi("account.cancelPasswordEmail")}};i.a.passwordManager=a,t.a=a},95:function(e,t,s){"use strict";s.d(t,"a",(function(){return a}));var i=s(5),n=s(38);class a extends n.b{constructor(e={}){super(Object.assign({plainText:!0},e)),this.passwordVisible=!1,this.onVisibilityClick=e=>{Object(i.a)(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.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)}}}}]);
//# sourceMappingURL=14.11183df10f220f2bd1db.chunk.js.map