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