"use strict";var React=require("react"),core=require("@gem-sdk/core"),extractSellingPlanSettings=require("../common/extractSellingPlanSettings.js"),findMatchedGroup=require("../helpers/findMatchedGroup.js"),findDefaultValue=require("../helpers/findDefaultValue.js"),findVariantByOptions=require("../helpers/findVariantByOptions.js");const useSellingSubscription=e=>{let t=core.useProduct(),n=core.useVariants(),{selectedOptions:l}=core.useSelectedOption(),r=core.useProductStore(e=>e.selectedSellingPlan),i=core.useProductStore(e=>e.setSelectedSellingPlan),a=core.usePageStore(e=>e.sellingPlanMeta),u=core.useEditorMode(),s=React.useRef(!1),o=React.useRef(void 0);React.useEffect(()=>{if(!s.current&&u===core.RenderModeEnv.EDIT&&!a){let e=new CustomEvent("element-subscription-mount");globalThis.dispatchEvent(e),s.current=!0}},[u,a]);let c=a??e?.sellingPlans,d=React.useMemo(()=>{if(!c)return{sourceApp:void 0,group:void 0,defaultOptions:void 0};let e=a&&l?findVariantByOptions.findVariantByOptions({variants:n,selectedOptions:l}):null,r=extractSellingPlanSettings.extractSellingPlanSettings({sellingPlansSetting:c,currentVariant:e,product:t,isFromEvent:!!a});return r},[c,a,n,l,t]),f=React.useMemo(()=>l?findVariantByOptions.findVariantByOptions({variants:n,selectedOptions:l}):null,[l,n]);React.useEffect(()=>{o.current=void 0},[f?.baseID]);let{sellingPlans:p,defaultValue:g}=React.useMemo(()=>{let e=f?.sellingPlanGroups??t?.sellingPlanGroups??[];if(!e||0===e.length)return{sellingPlans:[],defaultValue:void 0};let n=findMatchedGroup.findMatchedGroup({sellingPlanGroups:e,extractedSettings:d,currentVariant:f}),l=n?.sellingPlans?.filter(e=>null!=e)??[],r=l.map(e=>({label:e.name||"",value:e.baseID})),i=findDefaultValue.findDefaultValue({validPlans:l,extractedSettings:d,currentVariant:f,plans:r});return{sellingPlans:r,defaultValue:i}},[t,f,d]);return React.useEffect(()=>{!r&&g&&o.current!==g&&(o.current=g,i(g))},[g,r,i]),{sellingPlans:p,defaultValue:g,selectedSellingPlan:r,setSelectedSellingPlan:i}};exports.useSellingSubscription=useSellingSubscription;
