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