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