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