/*************************************************************************
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2015 Adobe Systems Incorporated
*  All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any.  The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and are protected by all applicable intellectual property laws,
* including trade secret and or copyright laws.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/
class FABManager{constructor(){if(FABManager.instance)return FABManager.instance;FABManager.instance=this,this.shadowRoot=null,this.hasShownSettingsMenu=!1,this.actionableCoachmark=new ActionableCoachmark,this.isFABHiddenForNow=!1,this.fabCustomisationTimeout=void 0,this.registerOpenCloseListeners(),this.registerFABEnabledDisabledListeners(),this.cursorXPosition=null,this.cursorYPosition=null,this.logFABShown(),this.fabDraggedTop=window.dcLocalStorage.getItem("genAIFabTopPosition"),this.enableFabDrag=window.dcLocalStorage.getItem("enableFabDrag"),this.enableFabAutoPositioning=window.dcLocalStorage.getItem("enableFabAutoPositioning"),this.isFABActiveForDrag=!1,this.isFABDragged=!1,this.fabAutoRepositioningTop=void 0,this.fabIconIframeContent=this.fetchUIContent(chrome.runtime.getURL("resources/SidePanel/FABIcon.html")),this.sidePanelButtonContent=this.fetchUIContent(chrome.runtime.getURL("resources/SidePanel/sidePanelButton.html"))}async fetchUIContent(e){return fetch(e).then(e=>e.text()).then(e=>e).catch(t=>{chrome.runtime.sendMessage({main_op:"log-error",log:{message:`Error while fetching UI content from ${e}`,error:t}})})}async logFABShown(){await GenAIWebpageEligibilityService.shouldShowTouchpoints()&&(chrome.runtime.sendMessage({main_op:"log-event-once",eventName:"DCBrowserExt:SidePanel:FabIcon:Enabled",options:{storageKey:"loggedFabEnabled",timePeriod:864e5}}),chrome.runtime.sendMessage({main_op:"log-info",log:{message:"FAB enabled"}}))}registerOpenCloseListeners(){chrome.runtime.onMessage.addListener(async e=>{switch(e.action){case"sidepanel_opened":this.removeFAB();break;case"sidepanel_closed":await GenAIWebpageEligibilityService.shouldShowTouchpoints()&&this.renderFAB()}})}async registerFABEnabledDisabledListeners(){chrome.storage.onChanged.addListener(({enableGenAIFab:e},t)=>{"local"===t&&e&&("false"===e.newValue?this.removeFAB():this.renderFAB())})}sendAnalyticsEvent=(e,t)=>{try{chrome.runtime.sendMessage({main_op:"analytics",analytics:e})}catch(e){}};isFABRendered(){return Boolean(this.shadowRoot)||Boolean(document.getElementById("aiFabShadowRoot"))}removeFAB(){this.shadowRoot?.host?.remove(),this.shadowRoot=null,this.hasShownSettingsMenu=!1}makeFABTransparent(){const e=this.shadowRoot?.querySelector(".acrobat-button-container");e?.classList?.contains("acrobat-button-container-transparent")||e?.classList?.add("acrobat-button-container-transparent")}makeFABOpaque(){const e=this.shadowRoot?.querySelector(".acrobat-button-container");e?.classList?.contains("acrobat-button-container-transparent")&&e?.classList?.remove("acrobat-button-container-transparent")}collapseFAB(){const e=this.shadowRoot?.querySelector(".close-btn"),t=this.shadowRoot?.querySelector(".tooltip-text"),o=this.shadowRoot?.querySelector(".acrobat-button");e&&t&&o&&!this.hasShownSettingsMenu&&(e.classList.remove("showCloseButton"),t?.classList?.remove("show-tooltip"),o?.classList.remove("expand-acrobat-button"))}customiseFABOpacity(){let e,t;document.addEventListener("scroll",()=>{this.makeFABTransparent(),t&&clearTimeout(t),t=setTimeout(()=>{this.cursorXPosition>.8*window.innerWidth&&this.makeFABOpaque(),t=void 0},50)}),document.addEventListener("mousemove",async t=>{if(this.cursorXPosition=t.clientX,this.cursorXPosition>.8*window.innerWidth){if(e)return;e=setTimeout(async()=>{await GenAIWebpageEligibilityService.shouldShowTouchpoints()&&this.makeFABOpaque(),e=void 0},200)}else e&&(clearTimeout(e),e=void 0)})}customiseFABVisibility(){let e;const t=()=>{if(this.enableFabDrag&&""!==this.fabDraggedTop)return document.removeEventListener("mousemove",o),void document.removeEventListener("scroll",t);this.isFABRendered()&&this.cursorYPosition<=.6*window.innerHeight&&this.removeFAB()},o=async t=>{if(this.cursorYPosition=t.clientY,!this.isFABRendered()&&this.cursorYPosition>.6*window.innerHeight){if(e)return;e=setTimeout(async()=>{await GenAIWebpageEligibilityService.shouldShowTouchpoints()&&this.renderFAB({fadeIn:!0}),e=void 0},200)}else e&&(clearTimeout(e),e=void 0)};document.addEventListener("scroll",t),document.addEventListener("mousemove",o)}async shouldRenderFAB(){const e=chrome.runtime.sendMessage({type:"get_sidepanel_state"});return await initDcLocalStorage(),!(await e).isOpen&&(isEmbeddedPDFTouchPointRendered()?(chrome.runtime.sendMessage({main_op:"log-info",log:{message:"FAB not rendered due to embedded PDF",domain:new URL(window.location.href).hostname}}),!1):"true"===window.dcLocalStorage.getItem("enableGenAIFab"))}_computeCursorCoordinates(){const e=document.createElement("div");e.id="invisibleElem",e.style.background="transparent",e.style.height="100vh",e.style.width="100vw",e.style.position="fixed",e.style.top="0",e.style.left="0",e.style.zIndex="1000",e.setAttribute("aria-hidden","true"),document.body.appendChild(e);const t=()=>{e.parentNode&&e.parentNode.removeChild(e)};e.addEventListener("mouseenter",e=>{this.cursorXPosition=e.clientX,this.cursorYPosition=e.clientY,t()}),setTimeout(()=>{t()},100)}generateUUID(){try{let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){let o=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?o:3&o|8).toString(16)})}catch(e){return Math.random()}}rePositionFABIfOverlapping(e){try{if(void 0!==this.fabAutoRepositioningTop)return void this.setFABTop(this.fabAutoRepositioningTop);let t=0,o=null;for(;t<5;){const i=getClickableOverlappingElement(e,o);if(!i?.length)break;let s=Number.MAX_SAFE_INTEGER;if(i.forEach(e=>{const t=e.getBoundingClientRect();t.top<s&&(s=t.top)}),s===Number.MAX_SAFE_INTEGER)break;const n=e.getBoundingClientRect(),a=n.height,r=s-a,{left:c,right:d,bottom:l,width:h,height:u,x:g,y:m}=n;o={top:r,left:c,right:d,bottom:l,width:h,height:u,x:g,y:m},t++}if(this.fabAutoRepositioningTop=o?.top?o.top-36:0,this.fabAutoRepositioningTop<.5*window.innerHeight)return;this.setFABTop(this.fabAutoRepositioningTop),this.sendAnalyticsEvent([["DCBrowserExt:SidePanel:FabIcon:OverlappingRepositioned"]])}catch(e){chrome.runtime.sendMessage({main_op:"log-error",log:{message:"Error in repositioning the FAB if overlapping",error:e.toString()}})}}setFABTop(e){const t=this.shadowRoot?.querySelector(".acrobat-button-container");t&&e&&(t.style.top=`${e}px`,t.style.bottom="auto")}enableFABDragging(){let e=0;const t=this.shadowRoot?.querySelector(".acrobat-button-container"),o=this.shadowRoot?.querySelector("#icon-iframe"),i=this.shadowRoot?.querySelector(".draggable-handle"),s=o?.contentDocument,n=s?.body;if(this.setFABTop(this.fabDraggedTop),!(t&&i&&s&&n))return;t.addEventListener("mouseover",()=>{i.classList.add("draggable-handle-visible")}),t.addEventListener("mouseout",()=>{i.classList.remove("draggable-handle-visible")});const a=i=>{if(0!==i.button||i.ctrlKey)return;i.stopImmediatePropagation(),i.preventDefault(),this.isFABActiveForDrag=!0,this.isFABDragged=!1,this.hideSettingsMenu(),this.collapseFAB();const s=o.getBoundingClientRect(),a=t.getBoundingClientRect();e=i.clientY-a.top,i.target.ownerDocument!==document&&(e+=s.top,n.style.cursor="grab")},r=i=>{if(!this.isFABActiveForDrag)return;this.isFABDragged=!0;let s=i.clientY-e;i.target.ownerDocument!==document&&o&&(s+=o.getBoundingClientRect().top);const n=t.offsetHeight,a=window.innerHeight-n-20;s=Math.max(20,Math.min(a,s)),this.fabDraggedTop=s,this.setFABTop(this.fabDraggedTop)},c=()=>{this.isFABActiveForDrag&&(n?.style.removeProperty("cursor"),this.isFABActiveForDrag=!1,this.isFABDragged&&(window.dcLocalStorage.setItem("genAIFabTopPosition",this.fabDraggedTop),this.sendAnalyticsEvent([["DCBrowserExt:SidePanel:FabIcon:Dragged"]]),chrome.runtime.sendMessage({main_op:"log-info",log:{message:"FAB dragged",fabTop:`${this.fabDraggedTop}px`}})))};requestAnimationFrame(()=>{try{let e;s&&"complete"===s.readyState&&(s.addEventListener?.("mousedown",t=>{this.isFABDragged=!1,e=setTimeout(()=>{a(t),e=void 0},100)}),s.addEventListener("mousemove",r),s.addEventListener("mouseup",()=>{e&&(clearTimeout(e),e=void 0),c()}))}catch(e){chrome.runtime.sendMessage({main_op:"log-error",log:{message:"Error while attaching FAB dragging listeners to iframe document",error:e}})}}),i.addEventListener("mousedown",a),document.addEventListener("mousemove",r),document.addEventListener("mouseup",c)}async enableFABCustomisation({enableHoveredState:e=!1,hoveredStateTimeout:t=""}){const o=await chrome.runtime.sendMessage({main_op:"getFloodgateFlag",flag:"dc-sp-fab-behaviour-exp-opacity"})?()=>this.customiseFABOpacity():()=>this.customiseFABVisibility();this.fabCustomisationTimeout=setTimeout(o,e?t:250)}updateCSSAsPerOS(){const e=navigator.platform,t=document.getElementById("aiFabShadowRoot"),o=t?.shadowRoot?.querySelector(".acrobat-button-container");o&&(e.includes("Mac")?(o.style.setProperty("--fab-margin-right","28px"),o.style.setProperty("--drag-handle-right","12px")):e.includes("Win")&&(o.style.setProperty("--fab-margin-right","22px"),o.style.setProperty("--drag-handle-right","6px")))}async renderFAB(e={}){const{fadeIn:t=!1,enableHoveredState:o=!1,hoveredStateTimeout:i=7e3}=e;if(this.isFABHiddenForNow||this.actionableCoachmark.isRendered())return;if(!await this.shouldRenderFAB())return;if(this.isFABRendered())return;const s=document.createElement("div");s.id="aiFabShadowRoot",s.style.opacity="0",t&&(s.style.transition="opacity 0.4s ease-out, transform 0.4s ease-out"),this.shadowRoot=s.attachShadow({mode:"open"});const n=await this.sidePanelButtonContent;if(!n)return;const a=document.createElement("template");a.innerHTML=n;const r=a.content;this.shadowRoot?.appendChild(r.cloneNode(!0));const c=this.shadowRoot?.querySelector("#icon-iframe");if(!c)return;const d=await this.fabIconIframeContent;d&&(c.srcdoc=d,c.addEventListener("load",()=>requestAnimationFrame(()=>this.adjustFABState(o,i))),util.translateElements(".translate",this.shadowRoot),this.actionableCoachmark.isRendered()||(document.documentElement.appendChild(s),this.updateCSSAsPerOS()),t&&requestAnimationFrame(()=>requestAnimationFrame(()=>s.style.opacity="1")),this.fabCustomisationTimeout||(this.cursorXPosition&&this.cursorYPosition||this._computeCursorCoordinates(),this.enableFABCustomisation({enableHoveredState:o,hoveredStateTimeout:i})))}async adjustFABState(e,t){const o=this.shadowRoot?.querySelector(".acrobat-button"),i=this.shadowRoot?.querySelector(".close-btn"),s=this.shadowRoot?.querySelector(".tooltip-text"),n=this.shadowRoot?.querySelector(".tooltip-text span:first-child"),a=document.getElementById("aiFabShadowRoot"),r=()=>{a&&(a.style.opacity="1"),e&&((e=1e3)=>{o?.classList.add("expand-acrobat-button"),i?.classList.add("showCloseButton"),s?.classList.add("show-tooltip"),setTimeout(()=>{i?.classList.remove("showCloseButton"),s?.classList.remove("show-tooltip"),o?.classList.remove("expand-acrobat-button")},e)})(t)};if(this.enableFabDrag&&this.enableFABDragging(),this.enableFabAutoPositioning&&!this.fabDraggedTop){const e=()=>{this.rePositionFABIfOverlapping(o),r()};requestAnimationFrame(()=>requestAnimationFrame(()=>{void 0!==this.fabAutoRepositioningTop?e():setTimeout(()=>e(),500)}))}else r();await GenAIWebpageEligibilityService.shouldDisableTouchpoints()&&(o?.classList.add("disabled"),n.id="tooltipTextDisabled"),o.addEventListener("mouseover",()=>{this.isFABActiveForDrag||o.classList.contains("expand-acrobat-button")||(o.classList.add("expand-acrobat-button"),i.classList.add("showCloseButton"),s.classList.add("show-tooltip"))}),o.addEventListener("mouseenter",()=>{this.isFABActiveForDrag||i.classList.contains("showCloseButton")||i.classList.add("showCloseButton")}),o.addEventListener("mouseleave",()=>this.collapseFAB()),i.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),this.hasShownSettingsMenu?this.hideSettingsMenu():this.showSettingsMenu()}),i.addEventListener("mousedown",e=>{e.stopImmediatePropagation(),e.preventDefault()}),this.attachIconIframeEventListeners()}attachIconIframeEventListeners(){const e=this.shadowRoot?.querySelector("#icon-iframe"),t=e.contentDocument;t?t.addEventListener("click",async e=>{if(!this.isFABDragged&&(e.preventDefault(),e.stopPropagation(),this.hideSettingsMenu(),!await GenAIWebpageEligibilityService.shouldDisableTouchpoints())){this.sendAnalyticsEvent([["DCBrowserExt:SidePanel:FabIcon:Clicked"]]);const e=this.generateUUID();await initDcLocalStorage(),window.dcLocalStorage.setItem("sidePanelUUID",e),chrome.runtime.sendMessage({type:"open_side_panel",touchpoint:"FAB"}),chrome.runtime.sendMessage({main_op:"log-info",log:{message:"FAB clicked",url:window.location.href}}),setTimeout(()=>{this.sendAnalyticsEvent([["DCBrowserExt:DebugSidePanel:FabIcon:Clicked"]],{uuid:e}),chrome.runtime.sendMessage({main_op:"log-info",log:{message:"Debug FAB clicked",url:window.location.href,uuid:e}})},500)}}):chrome.runtime.sendMessage({main_op:"log-error",log:{message:"Cannot access icon iframe document to attach event listeners"}})}hideSettingsMenu(){const e=this.shadowRoot?.querySelector(".close-btn");e?.classList.remove("open");const t=this.shadowRoot?.querySelector(".fab-view-settings-dialog");if(t){const e=this.shadowRoot?.querySelector(".tooltip-text");e&&(e.style.display="block");const t=this.shadowRoot?.querySelector(".fab-view-settings-dialog");t?.classList?.remove("showDialog")}this.hasShownSettingsMenu=!1}async hideFabForDomain(e){await initDcLocalStorage();const t=window.dcLocalStorage.getItem("hideFabDomainList")||[];t.includes(e)||t.push(e),window.dcLocalStorage.setItem("hideFabDomainList",t),chrome.runtime.sendMessage({main_op:"log-info",log:{message:"FAB hidden for domain",domain:e}})}async neverDisplayFab(){await initDcLocalStorage(),window.dcLocalStorage.setItem("enableGenAIFab","false")}_updateSettingsMenuPositionFromFAB(){const e=this.shadowRoot?.querySelector(".fab-view-settings-dialog"),t=this.shadowRoot?.querySelector(".acrobat-button"),o=this.shadowRoot?.querySelector(".acrobat-button-container"),i=this.shadowRoot?.querySelector(".close-btn")?.getBoundingClientRect()?.right;if(!t)return;const s=t.offsetHeight,n=e.offsetHeight,a=o.getBoundingClientRect(),r=a.top,c=a.right-i;c&&(e.style.right=`${c}px`),r<n+10?(e.style.bottom="auto",e.style.top=`${s}px`):(e.style.bottom=`${s}px`,e.style.top="auto")}showSettingsMenu(){const e=this.shadowRoot?.querySelector(".close-btn");e?.classList.add("open"),fetch(chrome.runtime.getURL("resources/SidePanel/FABViewSettings.html")).then(e=>e.text()).then(e=>{const t=this.shadowRoot?.querySelector(".tooltip-text");t&&(t.style.display="none");const o=this.shadowRoot?.querySelector(".fab-view-settings-dialog");o.innerHTML=e,o.classList.add("showDialog"),this.hasShownSettingsMenu=!0,util.translateElements(".translate",this.shadowRoot),this._updateSettingsMenuPositionFromFAB();const i=new URL(window.location.href).hostname;["hideForNow","hideFabForDomain","neverDisplayFab","preferences"].forEach(e=>{this.shadowRoot?.getElementById(e)?.addEventListener("click",async()=>{switch(e){case"hideForNow":this.isFABHiddenForNow=!0,this.removeFAB(),this.sendAnalyticsEvent([["DCBrowserExt:SidePanel:SettingsMenu:RemoveFab"]]);break;case"hideFabForDomain":this.hideFabForDomain(i),this.isFABHiddenForNow=!0,this.removeFAB(),this.sendAnalyticsEvent([["DCBrowserExt:SidePanel:SettingsMenu:RemoveFabForDomain"]]);break;case"neverDisplayFab":this.neverDisplayFab(),this.removeFAB(),this.sendAnalyticsEvent([["DCBrowserExt:SidePanel:SettingsMenu:NeverDisplay"]]);break;case"preferences":window.dcLocalStorage.setItem("optionsPageSource","FAB_MENU").then(()=>{chrome.runtime.sendMessage({type:"open_options_page",preferenceTabId:"generative-ai",controlId:"fab-section",highlightSection:["ai-assistant-banner-header-wrapper","fab-preference-toggle"]})}),this.sendAnalyticsEvent([["DCBrowserExt:SidePanel:SettingsMenu:PreferencesClicked"]])}})})})}}