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