import{r as a,j as R,u as H}from"./vendor-react-loeotUMb.js";import{a as E,f as j}from"./sciam-CJwTDRPd.js";import{c as B,m as V,k as W,j as T,n as K,l as J,o as Y}from"./use-auth-BpnYKcp5.js";import{u as $}from"./use-user-3ZABzaWr.js";import{S as z}from"./storage-DaZGhURt.js";const A=typeof window<"u"&&window.location.search.match(/debug=entitlements/)?console.debug.bind(window.console):function(){};function X(){if(typeof window===void 0)return;const t=window?.dataLayer.find(e=>e?.content?.publishedAtDate);if(t)return t.content.publishedAtDate;if(window?.__DATA__)return window?.__DATA__?.initialData?.dataLayerContent?.content?.publishedAtDate}function Z(){if(typeof window>"u")return!1;const t=X();let e={};try{const s=E.get("idp_details");s&&(e=JSON.parse(s))}catch(s){console.error(s)}if(e?.BPID){if(!t||E.get("idp_magic")&&!e?.active_contracts)return!0;if(e.active_contracts===null)return A("[entitlements] IDP accesss denied because there are no active entitlements"),!1;if(e.active_contracts===void 0)return A("[entitlements] IDP accesss granted because the entitlements are undefined, failing open"),!0;const s=new Date(t);let n=!1;return e.active_contracts.forEach(o=>{let{to:u,from:r}=o;const c=new Date(r),i=new Date(u);s>=c&&s<=i&&(n=!0)}),A(`[entitlements] IDP access ${n?"GRANTED":"DENIED"} for this page based on its release date`,{pubDate:s,active_contracts:e.active_contracts}),n}return!1}const U=a.createContext({ready:!1,hasSub:void 0,hasDigitalAccess:void 0,hasSpecialEditionAccess:void 0,hasAdFree:void 0,hasInstitutionalAccess:void 0,features:[],featureIds:[],entitlements:[]});function Ce(){return a.useContext(U)}function we({children:t}){const e=q();return R.jsx(U.Provider,{value:e,children:t})}function q(){const{featureIds:t,isActiveSubscriber:e,activePlans:s}=$(),{ready:n}=B(),{hasInstitutionalAccess:o}=Q(),u=h=>j.filter(({id:y})=>h.includes(y)),[r,c]=a.useState(t),[i,d]=a.useState(u(t));a.useEffect(()=>{const h=o?[...new Set([...t,"digital-access","special-edition-access"])]:t,y=u(h);c(h),d(y)},[o,t]);const l=()=>[...new Set(s.map(h=>h.legacy_resource_id))],[f,S]=a.useState(l);a.useEffect(()=>S(l),[s]);let P,m=o,b=o,p;return n&&(P=e,m||=r?.includes("digital-access"),b||=r?.includes("special-edition-access"),p=r?.includes("ad-free-access")),{ready:n&&(b||typeof o<"u"),hasDigitalAccess:m,hasSpecialEditionAccess:b,hasSub:P,hasAdFree:p,hasInstitutionalAccess:o,features:i,featureIds:r,plans:s,hasUnlimitedAccess:b,hasAccess:m,entitlements:f}}function Q(){const[t,e]=a.useState(void 0);return a.useEffect(()=>{function s(){const n=Z();n&&A("[entitlements] user has access from their Institution"),e(n)}return s(),window.addEventListener("ipd-update",s),()=>window.removeEventListener("idp-update",s)},[]),{hasInstitutionalAccess:t}}const D=["US","AS","GU","MP","PR","VI","UM","MH","FM","PW"],ee=["USA","ASM","GUM","MNP","PRI","VIR","UMI","MHL","FSM","PLW"],L=["AT","BE","BG","HR","CY","CZ","DK","EE","FI","FR","DE","GB","GR","HU","IE","IT","LV","LT","LU","MT","NL","PL","PT","RO","SK","SI","ES","SE","CH"],te=["AUT","BEL","BGR","HRV","CYP","CZE","DNK","EST","FIN","FRA","DEU","GBR","GRC","HUN","IRL","ITA","LVA","LTU","LUX","MLT","NLD","POL","PRT","ROU","SVK","SVN","ESP","SWE","CHE"],k=(t="")=>{const e=ne(t);return e?{region:se(e),country:e}:{region:null,country:null}},se=t=>{if(!t)return null;const e=t?.toUpperCase();return e==="CA"?"CA":e==="ROW"?"INT":D.includes(e)?"US":L.includes(e)?"EU":"INT"},ne=t=>{const e=t?.toUpperCase();if(e.length===2)return e;if(e.length===3){if(e==="CAN")return"CA";let s=ee.indexOf(e);return s>-1?D[s]:(s=te.indexOf(e),s>-1?L[s]:"ROW")}return null},Ee=()=>a.useContext(G),x={source:null,region:null,country:null},G=a.createContext(x),Se=({children:t,initial:e={}})=>{const[s,n]=a.useState(()=>({...x,...e})),[o,u]=a.useState();a.useEffect(r,[]);function r(){const l=E.get("sa_geo");if(l)try{const f=JSON.parse(l);u(f),n({...f,source:"cache"})}catch(f){console.error("Failed to parse geo cookie:",f),u(null)}else u(null)}const c=V("/api/geo/",{authMode:"none",cache:"no-store"});a.useEffect(()=>{const l=oe();if(l)return n({source:"url",...l});if(c.data)return n({source:"fastly",...c.data,...k(c.data.country)})},[!!c.data]);const[i,d]=a.useState(!1);return a.useEffect(()=>{i||["device","fastly"].includes(s.source)||typeof o>"u"||o?.source==="fastly"||(c.refetch(),d(!0))},[s?.source,typeof o,i]),a.useEffect(()=>{if((s.country||s.region)&&s.source!=="cache"&&(["device","fastly"].includes(s.source||"")||!["device","fastly"].includes(o?.source||""))){const l=JSON.stringify({source:s.source,region:s.region,country:s.country,ts:Date.now()});E.set("sa_geo",l,{expires:1,secure:!0,sameSite:"Strict"})}},[s.country||s.region,s.source]),R.jsx(G.Provider,{value:s,children:t})};function oe(){const e=new URLSearchParams(window.location.search).get("geo")?.toUpperCase()||"";return e&&console.log("Geo override from URL:",e),e==="RESET"?(E.remove("sa_geo"),null):e?e==="INT"||e==="ROW"?{region:"INT",country:null}:e==="EU"?{region:"EU",country:null}:k(e):null}let w=null,v=null;async function re(t,e){return console.log("[chargebee] no need to preconnect"),{session:v,instance:t}}function ae(t,e,s,n=!1){return new Promise(async(o,u)=>{if((s?w===s:!!w)&&!n)return console.log("[chargebee] connectPortalSession already connected"),o({instance:t,session:v});console.log("[chargebee] connectPortalSession setting portal session",{instance:t}),t.setPortalSession(async()=>{console.log("[chargebee] connectPortalSession fetching portal session",{appSlug:e,customerId:s});let c;try{c=await ce(e,s)}catch(i){throw u(i),i}return c&&requestAnimationFrame(()=>{w=c.customer_id,v=c,console.log("[chargebee] connectPortalSession resolved",c),o({instance:t,session:c})}),console.log("[chargebee] connected portal session"),c})})}function I(t){w&&(console.log("[chargebee] disconnectPortalSession"),t.closeAll(),w=null)}const ce=async(t,e)=>{const s=await W("/auth/chargebee/portal/",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-Sciam":"node"},body:new URLSearchParams({cb_app_id:t,customer_id:e||""})});if(!s.ok)throw new Error(`[chargebee] Failed to fetch portal session: ${s.statusText}`);return await s.json()};async function Pe(t=T){t=z.getItem("sciam:chargebee")??t;try{const e=ue(t);console.log("[chargebee] [setup] instance created",e),await re(e,t),console.log("[chargebee] [setup] complete"),F(e)}catch(e){console.error("[chargebee] [setup] error",e),N(e)}}let F,N;const ie=new Promise((t,e)=>{console.log("[chargebee] waiting for ready..."),F=t,N=e}).then(()=>console.log("[chargebee] ready"));let C;function ue(t,e=!1){if(C&&!e)return C;const{siteId:s,publishableKey:n}=K[t];return window.Chargebee.init({site:s,publishableKey:n,isItemsModel:!0}),C=window.Chargebee.getInstance(),C}async function _(){return await ie,C}function le(t){const[e,s]=a.useReducer(de,{status:"closed",step:null,error:null}),n=a.useMemo(()=>({close:()=>s({type:"close"}),loaded:()=>s({type:"loaded"}),success:o=>s({type:"success",payload:o||!0}),step:o=>s({type:"step",payload:o}),error:o=>s({type:"error",payload:o})}),[]);return a.useEffect(()=>{t&&t.setCheckoutCallbacks(()=>n)},[t]),{state:e,callbacks:n}}const de=(t,e)=>{const{dispatchEvent:s}=window;switch(s(new CustomEvent("chargebee:checkout",{detail:e})),s(new CustomEvent("chargebee:checkout-"+e.type,{detail:e.payload})),e.type){case"open":return{...t,status:"loading"};case"close":return{...t,status:"closed"};case"success":return{...t,status:"closed",step:null,success:e.payload};case"error":return{...t,status:"error",error:e.payload};case"loaded":return{...t,status:"open"};case"step":return{...t,status:"open",step:e.payload};default:return t}};function pe(t,e){const[s,n]=a.useReducer(fe,{status:"closed",section:null,subscriptionUpdates:null,paymentUpdates:null}),[o,u]=a.useState(null);return a.useEffect(()=>{if(!t)return;u(window.Chargebee.getPortalSections?.()||{});const r=c=>i=>n({type:"update_subscription",payload:{[i?.subscription?.id||"unknown"]:c}});return t.setPortalCallbacks({loaded:()=>n({type:"open"}),close:()=>n({type:"close"}),visit:c=>n({type:"open",payload:{section:c}}),paymentSourceAdd:()=>n({type:"update_payment",payload:"added"}),paymentSourceUpdate:()=>n({type:"update_payment",payload:"changed"}),paymentSourceRemove:()=>n({type:"update_payment",payload:"removed"}),subscriptionChanged:r("changed"),subscriptionCustomFieldsChanged:r("changed"),subscriptionCancelled:r("cancelled"),subscriptionResumed:r("resumed"),subscriptionPaused:r("paused"),scheduledPauseRemoved:r("resumed"),scheduledCancellationRemoved:r("resumed"),subscriptionReactivated:r("resumed"),subscriptionExtended:r("resumed")}),()=>{t?.setPortalCallbacks?.({})}},[t]),{sections:o,state:s,async open(r,c,i){n({type:"loading",payload:{section:null}});try{(await e(i)).open(r,c)}catch(d){return n({type:"error"}),console.error("[chargebee] Error opening portal",d,{options:r,forwardOptions:c}),!1}return!0},async openSection(r,c){const i=r?.sectionType||null;n({type:"loading",payload:{section:i}});try{(await e()).openSection(r,c)}catch(d){return n({type:"error"}),console.error("[chargebee] Error opening portal section",d),!1}return!0}}}const fe=(t,e)=>{const{dispatchEvent:s}=window;switch(s(new CustomEvent("chargebee:portal",{detail:e})),s(new CustomEvent("chargebee:portal-"+e.type,{detail:e.payload})),e.type){case"loading":return{...t,status:"loading",...e.payload};case"open":return{...t,status:"open",...e.payload};case"close":return{...t,status:"closed"};case"error":return{...t,status:"error"};case"update_subscription":return{...t,subscriptionUpdates:{...t.subscriptionUpdates||{},...e.payload}};case"update_payment":return{...t,paymentUpdates:e.payload};default:return t}},O=a.createContext(null),Ae=({children:t})=>{const e=J(),s=typeof e?.chargebee=="string"?e.chargebee:T,{user:n}=H(),[o,u]=a.useState(null),[r,c]=a.useState(null);Y(),a.useEffect(()=>{async function p(){const g=await _();u(g)}return p(),()=>I(o)},[]);const[i,d]=a.useState(null),l=pe(o,S),f=le(o);async function S(p){console.log("[useChargebee] getting portal instance");const g=o||await _();if(!n)throw new Error("[useChargebee] Cannot create a Chargebee portal session without a user");if(!g)throw new Error("[useChargebee] Cannot create a Chargebee portal session without an SDK instance");if((p?p!==r?.customer_id:!r)&&(console.log("[useChargebee] establishing session"),ae(g,s,p).then(({session:M})=>c(M))),console.log("[useChargebee] checking portal instance",i),i)return i;console.log("[useChargebee] using cb instance to create portal",g);const y=g.createChargebeePortal();return console.log("[useChargebee] created portal",y),d(y),y}const P=async p=>(await S(p),l),m=()=>{!o||!i||(o.closeAll(),d(null))},b=()=>{!o||!r||(o.logout(),I(o),c(null))};return R.jsx(O.Provider,{value:{appSlug:s,instance:o,session:r,portal:l,checkout:f,connectPortal:P,close:m,logout:b},children:t})},ve=()=>a.useContext(O);export{we as A,Se as G,Ae as P,ve as a,Ee as b,ie as c,Pe as s,Ce as u}; //# sourceMappingURL=use-chargebee-D9JKmYlM.js.map