import{useProductShopifyEditLink as e,useProduct as t,useIsSyncProduct as i,useEditorMode as n,useSelectedOption as o,useHasPreSelected as r,useInitialSwatchesOptions as a,useSwatchesOptions as l,getSelectedVariant as d,checkInStock as s}from"@gem-sdk/core";import{useRef as c,useState as m,useEffect as p,useMemo as f,useCallback as u}from"react";import{useVariantInteraction as w}from"./useVariantInteraction.js";import{useTransition as h}from"../common/common.js";import{checkDefaultVariant as g}from"../../../helpers/product.js";import{mappingVariantStyles as v}from"../utils/mappingVariantStyles.js";let L="variant",P=!1,S=(S,O)=>{let{builderProps:j,styles:y,setting:E}=S,{optionType:I,hasPreSelected:N}=E??{},{redirectProductShopifyLink:R}=e(),U=t(),V=i(),C=c(null),{dispatchInteractionChangeOptions:J,dispatchInteractionChangeOptionsInit:M}=w({element:C,uid:j?.uid}),b=n(),{selectedOptions:k,setSelectedOption:x,forceSelectedOption:G}=o(),{setHasPreSelected:q,hasPreSelected:z}=r(),[A,B]=m("");p(()=>{let e=new URL(window.location.href),t=e.searchParams.get(L);void 0===z&&q(N||!!t)},[N,z,q]),p(()=>{let e=new URL(window.location.href),t=e.searchParams.get(L);t&&B(t)},[]);let D=()=>{let e=new URL(window.location.href),t=e.searchParams.get(L);return t?O.find(e=>e?.id===t):null},F=e=>{let t=d(O,e);return s(t)};p(()=>{let e=D();if(e){let t=e?.selectedOptions.reduce((e,t)=>t.name?{...e,[t.name]:t.value}:e,{})??{},i=F(t);M(t,i),G(t,U?.id,!0)}else if(E?.hasPreSelected){let e=F(k);M(k,e)}},[]);let H=U?.options;a(H);let K=l(H),[Q,T]=m(!1),W=g(U),X=f(()=>"groupOption"===I,[I]),Y=u(e=>{let t=e.detail,i=U?.id;T(t.isManualChange||!1),V&&t&&i==t.productId&&x(t.optionId,t.optionValue,i,!0)},[V,U?.id,x]),Z=u(e=>{let t=e.detail,i=U?.id;T(t.isManualChange||!1),V&&t&&i==t.productId&&G(t.selectedOption,i,!0)},[V,U?.id,G]),$=e=>{let t=new URL(window.location.href);e?t.searchParams.set(L,e):t.searchParams.delete(L),history.replaceState(null,"",t.toString())};p(()=>(window.addEventListener("set-selected-option",Y),window.addEventListener("force-selected-option",Z),()=>{window.removeEventListener("set-selected-option",Y),window.removeEventListener("force-selected-option",Z)}),[Z,Y]),h(e=>{if(!P){P=!0;return}let t=JSON.stringify(e),i=JSON.stringify(k);if(window.interactionLoaded){let e=F(k);J(k,e)}if(e&&t!==i){let e=d(O,k);$(e?.id||"")}},[k]);let _=u(e=>{let t=v(E?.variantPresets,y),i=t?.find(t=>t.optionName===e);return i||t?.find(e=>"base"===e.optionName)},[E,y]);return{mode:b,options:K,variants:O,variantId:A,elementRef:C,variantGroup:X,isChangeVariant:Q,selectedOptions:k,isDefaultVariant:W,getVariantConfiguration:_,redirectProductShopifyLink:R}};export{S as useGpVariants};
