import{useRef as e,useState as r,useMemo as t,useEffect as u}from"react";import n from"../../carousel-v3/hooks/useTrackPreviewPause.js";import{useTransition as i}from"./useTransition.js";import{useCurrentDevice as o,isBrowser as l}from"@gem-sdk/core";let useMarqueeScrollToItem=c=>{let{setting:m,builderProps:a,styles:s}=c,d=e(null),T=o(),{speed:f,direction:v,isPreview:g,itemWidthType:q}=m||{},{itemMaxWidth:w}=s||{},h=e(null),S=e(null),p=e(null),I=e(null),[b,k]=r(),[y,B]=r(),[E,M]=r(0),[N,O]=r(!1),[R,_]=r(!1),{isFirstPreviewClicked:C}=n(g),$=t(()=>E||(f&&C&&g&&!N?100*f:0),[f,C,g,E,N]),j=e=>{let r=d.current?.getBoundingClientRect(),t=window.innerWidth,u=d.current?.querySelector(`.gem-marquee-item-${e}`);if(!u)return;let n=u.getBoundingClientRect().left,i=u.getBoundingClientRect().width;if(n>0&&n+20<t)return;let o=n+i/2-t/2;i>t&&(o=n-(r?.left||0));let l=o/1e3;return l},J=e=>{let r=e.detail;a?.uid===r.id&&("activeItem"===r.field&&k(r.value),"hoverItem"===r.field&&B(r.value))};i((e,r)=>{if(void 0===e||!r||e==f&&r==v)return;I.current&&clearTimeout(I.current);let t=f||0;return M(100*t),I.current=setTimeout(()=>{M(0)},3e3),()=>{I.current&&clearTimeout(I.current)}},[f,v]),i(e=>{e!==$&&void 0!==e&&0===$&&L()},[$]),i(e=>{e&&JSON.stringify(e)!==JSON.stringify(w)&&(h.current&&clearTimeout(h.current),_(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{L()},1500),h.current=setTimeout(()=>{_(!1)},3e3))},[w]),u(()=>(window.addEventListener("update-marquee",J),()=>{window.removeEventListener("update-marquee",J)}),[]),u(()=>{if(void 0!==b)return P(b||"0"),()=>{p.current&&clearTimeout(p.current),h.current&&clearTimeout(h.current)}},[b]),u(()=>()=>{p.current&&clearTimeout(p.current),h.current&&clearTimeout(h.current),S.current&&clearTimeout(S.current)},[]),u(()=>{N&&O(!1)},[g]);let L=e=>{let r=d.current?.querySelector(".first-block");r?.scrollIntoView({inline:"center",block:"nearest",behavior:e?"smooth":void 0})},P=e=>{if(q?.[T]==="BASE_ON_NUMBER_OF_ITEMS")return;if(S.current&&clearTimeout(S.current),_(!0),S.current=setTimeout(()=>{_(!1)},2e3),"0"==e){L(!0);return}let r=d.current?.querySelector(`.gem-marquee-item-${e}`);r?.scrollIntoView({inline:"center",block:"nearest",behavior:"smooth"})},V=t(()=>l()?j(parseInt(b??"0")):void 0,[b]),x=e=>`gem-marquee-item gem-marquee-item-${e}`;return{rate:$,wrapperElement:d,timeToScroll:V,hoverItem:y,setHoverItem:B,setActiveItem:k,getTimeScroll:j,activeItem:b,direction:v,isPause:R,scrollTime:1e3*Math.abs(V??0),scrollToItemClass:x}};export{useMarqueeScrollToItem};
