"use strict";var core=require("@gem-sdk/core"),React=require("react"),useScrollPercentage=require("./useScrollPercentage.js"),helpers=require("../common/helpers.js");const useDialog=(e,t,a)=>{let r=core.useModalStore(e=>e.setModalActive),c=core.useModalStore(e=>e.clearModal),o=React.useRef(),u=React.useRef(!1),l=React.useRef(!1),s=React.useRef(null),[i,n]=React.useState(!1),d=useScrollPercentage.useScrollPercentage(),p=core.useModalStore(e=>e.activeId),g=p===t?.uid,R=a?g:i,m=e?.dialogId??t?.uid,{trigger:f,triggerTime:b,mobileTrigger:v,mobileTriggerTime:h,closeOnClickOutside:w,frequency:k=3,triggerPercentage:E=0,frequencyMode:S="once"}=e??{},{onListener:C,trigger:M,ref:D}=core.useInteraction(),I=React.useCallback(e=>{if(window.interactionLoaded){e();return}window.addEventListener("gp:flow-actions-loaded",()=>{e()})},[]),$=React.useMemo(()=>helpers.createDialogKey(m??t?.uid,f),[t?.uid,m,f]),q=React.useCallback(()=>{I(()=>{M({event:"gp:popup-open",selector:`[data-id="${t?.uid}"`})})},[I,M,t?.uid]),L=React.useCallback(()=>{I(()=>{M({event:"gp:popup-close",selector:`[data-id="${t?.uid}"`})})},[M,t?.uid,I]),P=React.useCallback(()=>{localStorage.setItem($.time,`${Date.now()}`),l.current=!0,n(!0),q()},[$.time]);React.useEffect(()=>{let e=e=>{e?.popupUId==`#${t?.uid}`&&P()};return core.globalEvent.subscribe("onOpenDialog",e),()=>{core.globalEvent.remove("onOpenDialog",e)}},[t?.uid,P]);let T=React.useCallback(()=>{n(!1),r(),c(),L()},[r,c]),x=React.useCallback(()=>{let e=localStorage.getItem($.time);if(e)switch(S){case"once":break;case"after-period-time":{let t=helpers.isShowModal(e,k);t&&P();break}case"every":P()}else P()},[$.time,k,P,S]),j=React.useCallback(()=>{l.current||a||"show-when-about-exit"!==f||x()},[x,a,f]);React.useEffect(()=>{let e=`[data-id="${t?.uid}"]`;C&&(C({event:"gp:toggle-popup-open",selector:e},()=>{P()}),C({event:"gp:toggle-popup-close",selector:e},()=>{T()}))},[C]),React.useEffect(()=>(document.addEventListener("mouseleave",j),()=>{document.removeEventListener("mouseleave",j)}),[j]),React.useEffect(()=>{if(!l.current&&helpers.isMobile(navigator.userAgent)&&"show-when-about-exit"===f&&"timer"===v)return o.current=setTimeout(()=>{x()},(h??0)*1e3),()=>{clearTimeout(o.current)}},[v,h,x,f]),React.useEffect(()=>{!u.current&&"show-after-scroll"===f&&d>=E&&(u.current=!0,x())},[d,E,x,f]);let y=React.useCallback(e=>{let t=e.target===s.current;w&&t&&T()},[T,w]);return React.useEffect(()=>{switch(f){case"show-on-page-load":x();break;case"show-after-time":o.current=setTimeout(()=>{x()},1e3*helpers.parseNumber(b))}return()=>{clearTimeout(o.current)}},[x,f,b]),{ref:D,isOpen:i,overlay:s,handleClickOverlay:y,closeModal:T,activeId:p,open:R,dialogId:m}};exports.useDialog=useDialog;
