import{useRef as e,useEffect as l,useMemo as t}from"react";import{useProduct as n,useVariants as r,useSelectedOption as i,useProductStore as s,usePageStore as o,useEditorMode as a,RenderModeEnv as u}from"@gem-sdk/core";import{extractSellingPlanSettings as p}from"../common/extractSellingPlanSettings.js";import{findMatchedGroup as m}from"../helpers/findMatchedGroup.js";import{findDefaultValue as c}from"../helpers/findDefaultValue.js";import{findVariantByOptions as d}from"../helpers/findVariantByOptions.js";let f=f=>{let g=n(),v=r(),{selectedOptions:P}=i(),h=s(e=>e.selectedSellingPlan),S=s(e=>e.setSelectedSellingPlan),b=o(e=>e.sellingPlanMeta),V=a(),j=e(!1),D=e(void 0);l(()=>{if(!j.current&&V===u.EDIT&&!b){let e=new CustomEvent("element-subscription-mount");globalThis.dispatchEvent(e),j.current=!0}},[V,b]);let E=b??f?.sellingPlans,G=t(()=>{if(!E)return{sourceApp:void 0,group:void 0,defaultOptions:void 0};let e=b&&P?d({variants:v,selectedOptions:P}):null,l=p({sellingPlansSetting:E,currentVariant:e,product:g,isFromEvent:!!b});return l},[E,b,v,P,g]),I=t(()=>P?d({variants:v,selectedOptions:P}):null,[P,v]);l(()=>{D.current=void 0},[I?.baseID]);let{sellingPlans:x,defaultValue:M}=t(()=>{let e=I?.sellingPlanGroups??g?.sellingPlanGroups??[];if(!e||0===e.length)return{sellingPlans:[],defaultValue:void 0};let l=m({sellingPlanGroups:e,extractedSettings:G,currentVariant:I}),t=l?.sellingPlans?.filter(e=>null!=e)??[],n=t.map(e=>({label:e.name||"",value:e.baseID})),r=c({validPlans:t,extractedSettings:G,currentVariant:I,plans:n});return{sellingPlans:n,defaultValue:r}},[g,I,G]);return l(()=>{!h&&M&&D.current!==M&&(D.current=M,S(M))},[M,h,S]),{sellingPlans:x,defaultValue:M,selectedSellingPlan:h,setSelectedSellingPlan:S}};export{f as useSellingSubscription};
