@digilogiclabs/saas-factory-payments 1.2.4 → 1.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/native.d.mts +2 -1
- package/dist/native.d.ts +2 -1
- package/dist/native.js +1 -1
- package/dist/native.js.map +1 -1
- package/dist/native.mjs +1 -1
- package/dist/native.mjs.map +1 -1
- package/package.json +3 -3
package/dist/native.d.mts
CHANGED
|
@@ -87,6 +87,7 @@ interface StripeProviderProps {
|
|
|
87
87
|
children: React.ReactElement | React.ReactElement[];
|
|
88
88
|
merchantIdentifier?: string;
|
|
89
89
|
urlScheme?: string;
|
|
90
|
+
publishableKey?: string;
|
|
90
91
|
setReturnUrlSchemeOnAndroid?: boolean;
|
|
91
92
|
}
|
|
92
93
|
declare const StripeProvider: React.FC<StripeProviderProps>;
|
|
@@ -242,4 +243,4 @@ declare const cancelSubscription: (subscriptionId: string) => Promise<{
|
|
|
242
243
|
error?: string;
|
|
243
244
|
}>;
|
|
244
245
|
|
|
245
|
-
export { CheckoutButton, MobilePaymentSheet, type MobilePaymentSheetProps, NativeSubscriptionView, type NativeSubscriptionViewProps, PaymentForm, PricingTable, StripeProvider, TouchIDPayment, type TouchIDPaymentProps, cancelSubscription, createCustomer, createPaymentIntent, createSubscriptionSetup, fetchCustomerSubscriptions, fetchSubscription, formatStripeError, useCheckout, useCustomer, useSubscription, validatePaymentsConfig };
|
|
246
|
+
export { CheckoutButton, PaymentForm as CheckoutForm, MobilePaymentSheet, type MobilePaymentSheetProps, NativeSubscriptionView, type NativeSubscriptionViewProps, PaymentForm, PricingTable, StripeProvider, TouchIDPayment, type TouchIDPaymentProps, cancelSubscription, createCustomer, createPaymentIntent, createSubscriptionSetup, fetchCustomerSubscriptions, fetchSubscription, formatStripeError, useCheckout, useCustomer, useCheckout as useStripe, useSubscription, validatePaymentsConfig };
|
package/dist/native.d.ts
CHANGED
|
@@ -87,6 +87,7 @@ interface StripeProviderProps {
|
|
|
87
87
|
children: React.ReactElement | React.ReactElement[];
|
|
88
88
|
merchantIdentifier?: string;
|
|
89
89
|
urlScheme?: string;
|
|
90
|
+
publishableKey?: string;
|
|
90
91
|
setReturnUrlSchemeOnAndroid?: boolean;
|
|
91
92
|
}
|
|
92
93
|
declare const StripeProvider: React.FC<StripeProviderProps>;
|
|
@@ -242,4 +243,4 @@ declare const cancelSubscription: (subscriptionId: string) => Promise<{
|
|
|
242
243
|
error?: string;
|
|
243
244
|
}>;
|
|
244
245
|
|
|
245
|
-
export { CheckoutButton, MobilePaymentSheet, type MobilePaymentSheetProps, NativeSubscriptionView, type NativeSubscriptionViewProps, PaymentForm, PricingTable, StripeProvider, TouchIDPayment, type TouchIDPaymentProps, cancelSubscription, createCustomer, createPaymentIntent, createSubscriptionSetup, fetchCustomerSubscriptions, fetchSubscription, formatStripeError, useCheckout, useCustomer, useSubscription, validatePaymentsConfig };
|
|
246
|
+
export { CheckoutButton, PaymentForm as CheckoutForm, MobilePaymentSheet, type MobilePaymentSheetProps, NativeSubscriptionView, type NativeSubscriptionViewProps, PaymentForm, PricingTable, StripeProvider, TouchIDPayment, type TouchIDPaymentProps, cancelSubscription, createCustomer, createPaymentIntent, createSubscriptionSetup, fetchCustomerSubscriptions, fetchSubscription, formatStripeError, useCheckout, useCustomer, useCheckout as useStripe, useSubscription, validatePaymentsConfig };
|
package/dist/native.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";var rt=Object.create;var fe=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,st=Object.prototype.hasOwnProperty;var at=(o,e)=>{for(var t in e)fe(o,t,{get:e[t],enumerable:!0})},Ie=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of nt(e))!st.call(o,n)&&n!==t&&fe(o,n,{get:()=>e[n],enumerable:!(r=ot(e,n))||r.enumerable});return o};var ct=(o,e,t)=>(t=o!=null?rt(it(o)):{},Ie(e||!o||!o.__esModule?fe(t,"default",{value:o,enumerable:!0}):t,o)),ut=o=>Ie(fe({},"__esModule",{value:!0}),o);var Et={};at(Et,{CheckoutButton:()=>Pe,MobilePaymentSheet:()=>We,NativeSubscriptionView:()=>Ge,PaymentForm:()=>Ke,PaymentsProvider:()=>ke,PricingTable:()=>ze,StripeProvider:()=>Je,TouchIDPayment:()=>qe,cancelSubscription:()=>Ct,createCustomer:()=>bt,createPaymentIntent:()=>yt,createSubscriptionSetup:()=>ft,fetchCustomerSubscriptions:()=>St,fetchSubscription:()=>gt,formatStripeError:()=>Pt,useCheckout:()=>et,useCustomer:()=>tt,usePayments:()=>Xe,usePaymentsContext:()=>H,useSubscription:()=>Ze,validatePaymentsConfig:()=>ht});module.exports=ut(Et);var Ue=require("react"),Q=require("react-native"),Me=require("@stripe/stripe-react-native");var Z=require("react");var ve=require("zustand"),_e=require("zustand/middleware/immer");var u=class o extends Error{type;code;details;constructor(e,t,r,n){super(t),this.name="PaymentsError",this.type=e,this.code=r,this.details=n,Object.setPrototypeOf(this,o.prototype)}};var ne=class{config;constructor(e){this.config=e}handleError(e,t="UNKNOWN_ERROR"){if(e instanceof u)return e;let r="An unknown error occurred",n,i;return typeof e=="object"&&e!==null&&("message"in e&&typeof e.message=="string"&&(r=e.message),"code"in e&&typeof e.code=="string"&&(n=e.code),i={...e}),new u(t,r,n,i)}};var Te=ct(require("stripe")),ye=class extends ne{name="stripe";stripeClient;constructor(e){if(super(e),!e.stripeConfig?.publishableKey)throw new u("CONFIGURATION_ERROR","Stripe publishable key is missing in config.");if(!process.env.STRIPE_SECRET_KEY)throw new u("CONFIGURATION_ERROR","STRIPE_SECRET_KEY environment variable is not set.");this.stripeClient=new Te.default(process.env.STRIPE_SECRET_KEY,{apiVersion:"2024-06-20"})}async initialize(){console.log("StripePaymentProvider initialized (server-side)")}async createCheckoutSession(e){try{let t=await this.stripeClient.checkout.sessions.create({payment_method_types:["card"],line_items:[{price:e.priceId,quantity:1}],mode:e.mode||"payment",success_url:e.successUrl||`${process.env.NEXT_PUBLIC_BASE_URL}/success?session_id={CHECKOUT_SESSION_ID}`,cancel_url:e.cancelUrl||`${process.env.NEXT_PUBLIC_BASE_URL}/cancel`,customer_email:e.customerEmail,allow_promotion_codes:e.allowPromotionCodes,metadata:e.metadata});if(!t.url)throw new u("UNKNOWN_ERROR","Stripe checkout session URL is missing.");return{id:t.id,url:t.url,status:t.status,amountTotal:t.amount_total||void 0,currency:t.currency||void 0,customerEmail:t.customer_details?.email||void 0,subscriptionId:t.subscription?.toString()||void 0}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async createCustomer(e){try{let t=await this.stripeClient.customers.create({email:e.email,name:e.name,metadata:e.metadata});return{id:t.id,email:t.email||e.email,name:t.name||e.name,phone:null,stripeCustomerId:t.id,subscriptions:[],paymentMethods:[],defaultPaymentMethodId:null,metadata:t.metadata,created:new Date(t.created*1e3),updated:new Date(t.created*1e3)}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async retrieveCustomer(e){try{let t=await this.stripeClient.customers.retrieve(e);return t.deleted?null:{id:t.id,email:t.email||"",name:t.name||void 0,phone:t.phone||void 0,stripeCustomerId:t.id,subscriptions:[],paymentMethods:[],defaultPaymentMethodId:t.invoice_settings?.default_payment_method?.toString()||void 0,metadata:t.metadata,created:new Date(t.created*1e3),updated:new Date(t.created*1e3)}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async createSubscription(e){try{let t=await this.stripeClient.subscriptions.create({customer:e.customerId,items:(e.items||(e.priceId?[{priceId:e.priceId,quantity:1}]:[])).map(r=>({price:r.priceId,quantity:r.quantity||1})),trial_period_days:e.trialPeriodDays,metadata:e.metadata,expand:["latest_invoice.payment_intent"]});return this.mapStripeSubscriptionToSubscription(t)}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async cancelSubscription(e){try{await this.stripeClient.subscriptions.cancel(e)}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async reactivateSubscription(e){try{let t=await this.stripeClient.subscriptions.retrieve(e);if(t.status==="canceled"&&t.cancel_at_period_end)await this.stripeClient.subscriptions.update(e,{cancel_at_period_end:!1});else throw new u("VALIDATION_ERROR","Subscription cannot be reactivated.")}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async retrieveCheckoutSession(e){try{let t=await this.stripeClient.checkout.sessions.retrieve(e);if(!t.url)throw new u("UNKNOWN_ERROR","Stripe checkout session URL is missing.");return{id:t.id,url:t.url,status:t.status,amountTotal:t.amount_total||void 0,currency:t.currency||void 0,customerEmail:t.customer_details?.email||void 0,subscriptionId:t.subscription?.toString()||void 0}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async listSubscriptions(e,t){try{return(await this.stripeClient.subscriptions.list({customer:e,status:t==="all"?void 0:t})).data.map(this.mapStripeSubscriptionToSubscription)}catch(r){throw this.handleError(r,"NETWORK_ERROR")}}async retrieveSubscription(e){try{let t=await this.stripeClient.subscriptions.retrieve(e);return this.mapStripeSubscriptionToSubscription(t)}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async updateSubscription(e,t){try{let r=await this.stripeClient.subscriptions.retrieve(e),n=t.items?t.items.map(d=>({id:r.items.data.find(c=>c.price?.id===d.priceId)?.id,price:d.priceId,quantity:d.quantity||1})):void 0,i=await this.stripeClient.subscriptions.update(e,{items:n,metadata:t.metadata});return this.mapStripeSubscriptionToSubscription(i)}catch(r){throw this.handleError(r,"NETWORK_ERROR")}}mapStripeSubscriptionToSubscription(e){return{id:e.id,customerId:e.customer.toString(),status:e.status,items:e.items.data.map(t=>({id:t.id,priceId:t.price?.id||"",quantity:t.quantity||1})),currentPeriodStart:new Date(e.current_period_start*1e3),currentPeriodEnd:new Date(e.current_period_end*1e3),cancelAtPeriodEnd:e.cancel_at_period_end,trialStart:e.trial_start?new Date(e.trial_start*1e3):void 0,trialEnd:e.trial_end?new Date(e.trial_end*1e3):void 0,metadata:e.metadata,created:new Date(e.created*1e3),updated:new Date(e.created*1e3)}}};var he=class extends ne{name="MockPaymentProvider";customers=[];subscriptions=[];nextCustomerId=1;nextSubscriptionId=1;constructor(e){super({...e,provider:"mock"}),console.log("MockPaymentProvider initialized")}async initialize(){console.log("MockPaymentProvider initialized")}async createCheckoutSession(e){return console.log("Mock: createCheckoutSession",e),{id:"mock_cs_123",clientSecret:"mock_client_secret",url:"https://mock-checkout.example.com/success",status:"open"}}async retrieveCheckoutSession(e){if(console.log("Mock: retrieveCheckoutSession",e),e==="mock_cs_123")return{id:"mock_cs_123",clientSecret:"mock_client_secret",url:"https://mock-checkout.example.com/success",status:"complete"};throw new u("CUSTOMER_NOT_FOUND",`Mock checkout session ${e} not found`)}async createCustomer(e){console.log("Mock: createCustomer",e);let t={id:`mock_cus_${this.nextCustomerId++}`,email:e.email,name:e.name||null,phone:e.phone||null,stripeCustomerId:null,subscriptions:[],defaultPaymentMethodId:null,paymentMethods:[],metadata:e.metadata||{},created:new Date,updated:new Date};return this.customers.push(t),t}async retrieveCustomer(e){console.log("Mock: retrieveCustomer",e);let t=this.customers.find(r=>r.id===e);if(!t)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t}async updateCustomer(e,t){console.log("Mock: updateCustomer",e,t);let r=this.customers.find(n=>n.id===e);if(!r)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t.email&&(r.email=t.email),t.name&&(r.name=t.name),t.phone&&(r.phone=t.phone),t.metadata&&(r.metadata={...r.metadata,...t.metadata}),r.updated=new Date,r}async deleteCustomer(e){console.log("Mock: deleteCustomer",e);let t=this.customers.length;if(this.customers=this.customers.filter(r=>r.id!==e),this.customers.length===t)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`)}async listPaymentMethods(e){console.log("Mock: listPaymentMethods",e);let t=this.customers.find(r=>r.id===e);if(!t)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t.paymentMethods||[]}async attachPaymentMethod(e,t){console.log("Mock: attachPaymentMethod",e,t);let r=this.customers.find(i=>i.id===e);if(!r)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n={id:t,type:"card",card:{brand:"visa",last4:"4242",expMonth:12,expYear:2025,country:"US"},isDefault:!1,created:new Date};return r.paymentMethods.push(n),n}async detachPaymentMethod(e,t){console.log("Mock: detachPaymentMethod",e,t);let r=this.customers.find(i=>i.id===e);if(!r)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n=r.paymentMethods.length;if(r.paymentMethods=r.paymentMethods.filter(i=>i.id!==t),r.paymentMethods.length===n)throw new u("CUSTOMER_NOT_FOUND",`Mock payment method ${t} not found for customer ${e}`)}async createSubscription(e){console.log("Mock: createSubscription",e);let t=this.customers.find(n=>n.id===e.customerId);if(!t)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e.customerId} not found`);let r={id:`mock_sub_${this.nextSubscriptionId++}`,customerId:e.customerId,status:"active",items:(e.items||(e.priceId?[{priceId:e.priceId,quantity:1}]:[])).map(n=>({id:`mock_sub_item_${Math.random().toString(36).substring(7)}`,priceId:n.priceId,quantity:n.quantity||1})),currentPeriodStart:new Date,currentPeriodEnd:new Date(Date.now()+720*60*60*1e3),cancelAtPeriodEnd:!1,created:new Date,updated:new Date};return this.subscriptions.push(r),t.subscriptions.push(r),r}async retrieveSubscription(e){console.log("Mock: retrieveSubscription",e);let t=this.subscriptions.find(r=>r.id===e);if(!t)throw new u("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);return t}async updateSubscription(e,t){console.log("Mock: updateSubscription",e,t);let r=this.subscriptions.find(n=>n.id===e);if(!r)throw new u("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);return t.cancelAtPeriodEnd!==void 0&&(r.cancelAtPeriodEnd=t.cancelAtPeriodEnd,r.status=t.cancelAtPeriodEnd?"canceled":"active"),t.items&&(r.items=t.items.map(n=>({id:`mock_sub_item_${Math.random().toString(36).substring(7)}`,priceId:n.priceId,quantity:n.quantity||1}))),r.updated=new Date,r}async cancelSubscription(e){console.log("Mock: cancelSubscription",e);let t=this.subscriptions.find(r=>r.id===e);if(!t)throw new u("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);t.status="canceled",t.cancelAtPeriodEnd=!0,t.updated=new Date}async reactivateSubscription(e){console.log("Mock: reactivateSubscription",e);let t=this.subscriptions.find(r=>r.id===e);if(!t)throw new u("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);t.status="active",t.cancelAtPeriodEnd=!1,t.updated=new Date}async listSubscriptions(e,t){console.log("Mock: listSubscriptions",e,t);let r=this.customers.find(i=>i.id===e);if(!r)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n=r.subscriptions;return t&&t!=="all"&&(n=n.filter(i=>i.status===t)),n}};var z=class{static create(e){switch(e.provider){case"stripe":return new ye(e);case"paypal":throw new u("PROVIDER_NOT_CONFIGURED","PayPal provider is not yet available in this build");case"applepay":throw new u("PROVIDER_NOT_CONFIGURED","Apple Pay provider is not yet available in this build");case"mock":return new he(e);default:throw new u("CONFIGURATION_ERROR",`Unsupported payment provider: ${e.provider}`)}}static autodetect(){if(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY&&process.env.STRIPE_SECRET_KEY)return{provider:"stripe",publishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,environment:process.env.NODE_ENV==="production"?"production":"development",stripeConfig:{publishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY}};if(process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID&&process.env.PAYPAL_CLIENT_SECRET)return{provider:"paypal",publishableKey:process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID,environment:process.env.NODE_ENV==="production"?"production":"development",paypalConfig:{clientId:process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID,clientSecret:process.env.PAYPAL_CLIENT_SECRET,environment:process.env.NODE_ENV==="production"?"production":"sandbox",currency:process.env.PAYPAL_CURRENCY||"USD"}};if(process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_ID&&typeof window<"u"&&window.ApplePaySession)return{provider:"applepay",environment:process.env.NODE_ENV==="production"?"production":"development",applePayConfig:{merchantId:process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_ID,merchantName:process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_NAME||"Your Store",countryCode:process.env.NEXT_PUBLIC_APPLE_PAY_COUNTRY_CODE||"US",currencyCode:process.env.NEXT_PUBLIC_APPLE_PAY_CURRENCY_CODE||"USD",environment:process.env.NODE_ENV==="production"?"production":"sandbox"}};if(process.env.NODE_ENV!=="production"||process.env.VERCEL_ENV==="preview")return console.warn("No payment provider detected, defaulting to MockPaymentProvider for development/preview environment."),{provider:"mock",environment:"development"};throw new u("CONFIGURATION_ERROR","Could not auto-detect payment provider. Please provide explicit configuration.")}static getAvailableProviders(){let e=[];return process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY&&e.push("stripe"),process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID&&e.push("paypal"),typeof window<"u"&&window.ApplePaySession?.canMakePayments()&&e.push("applepay"),process.env.NODE_ENV!=="production"&&e.push("mock"),e}static createMultiple(e){return e.map(t=>this.create(t))}};var Oe={customer:null,subscriptions:[],activeSubscription:null,loading:!1,error:null,initialized:!1,config:null,isLoading:!1,isError:!1},Ne=(0,ve.create)()((0,_e.immer)((o,e)=>({...Oe,get isLoading(){return e().loading},get isError(){return!!e().error},initialize:async t=>{o(r=>{r.loading=!0,r.error=null});try{let r;t?r=t:r=z.autodetect(),await z.create(r).initialize(),o(i=>{i.initialized=!0,i.loading=!1,i.config=r})}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to initialize payments provider.";n.error=new u("CONFIGURATION_ERROR",i),n.loading=!1}),r}},createCustomer:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).createCustomer(t);return o(i=>{i.customer=n,i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to create customer.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},retrieveCustomer:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).retrieveCustomer(t);return o(i=>{i.customer=n,i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to retrieve customer.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},createCheckoutSession:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).createCheckoutSession(t);return o(i=>{i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to create checkout session.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},retrieveCheckoutSession:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).retrieveCheckoutSession(t);return o(i=>{i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to retrieve checkout session.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},createSubscription:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).createSubscription(t);return await e().refreshSubscriptions(e().customer?.id||""),o(i=>{i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to create subscription.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},cancelSubscription:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");await z.create(e().config).cancelSubscription(t),await e().refreshSubscriptions(e().customer?.id||""),o(n=>{n.loading=!1})}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to cancel subscription.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},reactivateSubscription:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");await z.create(e().config).reactivateSubscription(t),await e().refreshSubscriptions(e().customer?.id||""),o(n=>{n.loading=!1})}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to reactivate subscription.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},updateSubscription:async(t,r)=>{o(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let i=await z.create(e().config).updateSubscription(t,r);return await e().refreshSubscriptions(e().customer?.id||""),o(d=>{d.loading=!1}),i}catch(n){throw o(i=>{let d=n instanceof Error?n.message:"Failed to update subscription.";i.error=new u("NETWORK_ERROR",d),i.loading=!1}),n}},listSubscriptions:async(t,r)=>{o(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let i=await z.create(e().config).listSubscriptions(t,r);return o(d=>{d.subscriptions=i,d.loading=!1}),i}catch(n){throw o(i=>{let d=n instanceof Error?n.message:"Failed to list subscriptions.";i.error=new u("NETWORK_ERROR",d),i.loading=!1}),n}},retrieveSubscription:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).retrieveSubscription(t);return o(i=>{i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to retrieve subscription.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},refreshCustomer:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).retrieveCustomer(t);o(i=>{i.customer=n,i.loading=!1})}catch(r){o(n=>{let i=r instanceof Error?r.message:"Failed to refresh customer.";n.error=new u("NETWORK_ERROR",i),n.loading=!1})}},refreshSubscriptions:async(t,r)=>{o(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let i=await z.create(e().config).listSubscriptions(t,r),d=i.find(c=>c.status==="active"||c.status==="trialing")||null;o(c=>{c.subscriptions=i,c.activeSubscription=d,c.loading=!1})}catch(n){o(i=>{let d=n instanceof Error?n.message:"Failed to refresh subscriptions.";i.error=new u("NETWORK_ERROR",d),i.loading=!1})}},reset:()=>{o(t=>{Object.assign(t,Oe)})}})));var xe=require("react/jsx-runtime"),De=(0,Z.createContext)(void 0),ke=({children:o,config:e,onPaymentSuccess:t,onPaymentError:r})=>{let n=Ne(),{initialize:i,initialized:d,loading:c,error:m,customer:b,subscriptions:P,activeSubscription:g}=n,x=(0,Z.useRef)(t),D=(0,Z.useRef)(r);(0,Z.useEffect)(()=>{x.current=t},[t]),(0,Z.useEffect)(()=>{D.current=r},[r]),(0,Z.useEffect)(()=>{!d&&!c&&!m&&i(e).catch(S=>{console.error("PaymentsProvider initialization failed:",S),D.current&&D.current(S)})},[d,c,m,e,i]);let s={config:n.config,initialized:d,loading:c,error:m,customer:b,subscriptions:P,activeSubscription:g,createCustomer:n.createCustomer,createCheckoutSession:n.createCheckoutSession,cancelSubscription:n.cancelSubscription,reactivateSubscription:n.reactivateSubscription,updateSubscription:n.updateSubscription,refreshCustomer:n.refreshCustomer,refreshSubscriptions:n.refreshSubscriptions,reset:n.reset};return(0,xe.jsx)(De.Provider,{value:s,children:o})},H=()=>{let o=(0,Z.useContext)(De);if(o===void 0)throw new Error("usePaymentsContext must be used within a PaymentsProvider");return o};var Ae={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NZD:"NZ$"},Fe="USD";var h={PROVIDER_NOT_CONFIGURED:"Payments provider is not properly configured",STRIPE_NOT_LOADED:"Stripe has not been loaded yet",INVALID_PRICE_ID:"Invalid price ID provided",INVALID_CUSTOMER_ID:"Invalid customer ID provided",CHECKOUT_FAILED:"Checkout session creation failed",PAYMENT_FAILED:"Payment processing failed",SUBSCRIPTION_NOT_FOUND:"Subscription not found",CUSTOMER_NOT_FOUND:"Customer not found"};var te=o=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o);var G=(o,e)=>{let t={customer:"cus_",subscription:"sub_",price:"price_",product:"prod_",payment_intent:"pi_"};return o.startsWith(t[e])};var le=require("react/jsx-runtime"),Pe=({priceId:o,customerId:e,customerEmail:t,children:r,style:n,textStyle:i,disabled:d=!1,metadata:c,trialPeriodDays:m,onSuccess:b,onError:P,onLoading:g})=>{let{initPaymentSheet:x,presentPaymentSheet:D}=(0,Me.useStripe)(),{initialized:s}=H(),[S,M]=(0,Ue.useState)(!1),k=R=>{P?.(R),Q.Alert.alert("Payment Error",R),console.error("Checkout error:",R)},q=async()=>{if(!s){k(h.PROVIDER_NOT_CONFIGURED);return}if(!G(o,"price")){k(h.INVALID_PRICE_ID);return}if(e&&!G(e,"customer")){k(h.INVALID_CUSTOMER_ID);return}M(!0),g?.(!0);try{let R=await fetch("/api/payments/create-subscription-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priceId:o,customerId:e,customerEmail:t,metadata:c,trialPeriodDays:m})});if(!R.ok){let l=await R.json().catch(()=>({error:"Network error"}));throw new Error(l.error||h.CHECKOUT_FAILED)}let{setupIntentClientSecret:a,customerId:p,customerEphemeralKeySecret:v}=await R.json();if(!a)throw new Error("No setup intent client secret returned from server");let{error:T}=await x({setupIntentClientSecret:a,customerId:p,customerEphemeralKeySecret:v,merchantDisplayName:"Your App Name",allowsDelayedPaymentMethods:!0});if(T)throw new Error(T.message||"Failed to initialize payment sheet");let{error:f}=await D();if(f){if(f.code!=="Canceled")throw new Error(f.message||h.PAYMENT_FAILED);return}b?.()}catch(R){let a=R instanceof Error?R.message:h.CHECKOUT_FAILED;k(a)}finally{M(!1),g?.(!1)}},O=S||d||!s;return(0,le.jsxs)(Q.TouchableOpacity,{style:[ue.button,n,O&&ue.disabled],onPress:q,disabled:O,activeOpacity:.8,children:[S?(0,le.jsx)(Q.ActivityIndicator,{color:"#ffffff",size:"small",style:ue.loader}):null,(0,le.jsx)(Q.Text,{style:[ue.buttonText,i,S&&ue.loadingText],children:S?"Processing...":r})]})},ue=Q.StyleSheet.create({button:{backgroundColor:"#007AFF",paddingHorizontal:16,paddingVertical:12,borderRadius:8,flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48},buttonText:{color:"#ffffff",fontSize:16,fontWeight:"600",textAlign:"center"},disabled:{opacity:.5},loader:{marginRight:8},loadingText:{marginLeft:8}});var F=require("react-native");var Ce=(o,e=Fe,t={})=>{let{showSymbol:r=!0,showCents:n=!0,locale:i="en-US"}=t,d=e.toUpperCase(),c=["JPY","KRW","VND","CLP"].includes(d),m=c?o:o/100;if(r)try{return new Intl.NumberFormat(i,{style:"currency",currency:d,minimumFractionDigits:n&&!c?2:0,maximumFractionDigits:n&&!c?2:0}).format(m)}catch{let b=Ae[d]||d,P=n&&!c?m.toFixed(2):Math.round(m).toString();return`${b}${P}`}return n&&!c?m.toFixed(2):Math.round(m).toString()},Ve=o=>{let e=Ce(o.price,o.currency),t=o.intervalCount&&o.intervalCount>1?`${o.intervalCount} ${o.interval}s`:o.interval;return`${e}/${t}`};var me=(o,e={})=>{let{format:t="medium",locale:r="en-US",timeZone:n}=e,i=typeof o=="string"||typeof o=="number"?new Date(o):o,d={timeZone:n};switch(t){case"short":d.dateStyle="short";break;case"medium":d.dateStyle="medium";break;case"long":d.dateStyle="long";break;case"full":d.dateStyle="full";break}try{return new Intl.DateTimeFormat(r,d).format(i)}catch{return i.toLocaleDateString()}};var Be=o=>o===0?"No trial":o===1?"1 day trial":o<7?`${o} days trial`:o===7?"1 week trial":o<30?`${Math.floor(o/7)} weeks trial`:o===30?"1 month trial":`${Math.floor(o/30)} months trial`;var V=require("react/jsx-runtime"),{width:Le}=F.Dimensions.get("window"),ze=({plans:o,customerId:e,customerEmail:t,onCheckoutSuccess:r,onCheckoutError:n,showFeatures:i=!0,showTrialInfo:d=!0,layout:c="carousel",containerStyle:m})=>{if(!o||o.length===0)return(0,V.jsx)(F.View,{style:A.emptyContainer,children:(0,V.jsx)(F.Text,{style:A.emptyText,children:"No pricing plans available"})});let b=P=>(0,V.jsx)(lt,{plan:P,customerId:e,customerEmail:t,onCheckoutSuccess:()=>r?.(P),onCheckoutError:g=>n?.(P,g),showFeatures:i,showTrialInfo:d,style:c==="carousel"?A.carouselCard:A.listCard},P.id);return c==="carousel"?(0,V.jsx)(F.View,{style:[A.container,m],children:(0,V.jsx)(F.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:A.carouselContainer,snapToInterval:Le*.8+16,decelerationRate:"fast",children:o.map(b)})}):(0,V.jsx)(F.ScrollView,{style:[A.container,m],children:(0,V.jsx)(F.View,{style:A.listContainer,children:o.map(b)})})},lt=({plan:o,customerId:e,customerEmail:t,onCheckoutSuccess:r,onCheckoutError:n,showFeatures:i=!0,showTrialInfo:d=!0,style:c})=>{let m=o.popular;return(0,V.jsxs)(F.View,{style:[A.card,m&&A.popularCard,c],children:[m&&(0,V.jsx)(F.View,{style:A.popularBadge,children:(0,V.jsx)(F.Text,{style:A.popularBadgeText,children:"Most Popular"})}),(0,V.jsxs)(F.View,{style:A.cardHeader,children:[(0,V.jsx)(F.Text,{style:A.planName,children:o.name}),o.description&&(0,V.jsx)(F.Text,{style:A.planDescription,children:o.description}),(0,V.jsx)(F.Text,{style:A.planPrice,children:Ve(o)}),d&&o.trialPeriodDays&&o.trialPeriodDays>0&&(0,V.jsx)(F.Text,{style:A.trialInfo,children:Be(o.trialPeriodDays)})]}),i&&o.features&&o.features.length>0&&(0,V.jsx)(F.View,{style:A.featuresContainer,children:o.features.map((b,P)=>(0,V.jsxs)(F.View,{style:A.featureItem,children:[(0,V.jsx)(F.Text,{style:A.featureCheckmark,children:"\u2713"}),(0,V.jsx)(F.Text,{style:A.featureText,children:b})]},P))}),(0,V.jsx)(F.View,{style:A.buttonContainer,children:(0,V.jsx)(Pe,{priceId:o.stripePriceId,customerId:e,customerEmail:t,trialPeriodDays:o.trialPeriodDays,metadata:o.metadata,onSuccess:r,onError:n,style:[A.ctaButton,m?A.popularButton:A.regularButton],textStyle:[A.ctaButtonText,m?A.popularButtonText:A.regularButtonText],children:"Get Started"})})]})},A=F.StyleSheet.create({container:{flex:1},emptyContainer:{flex:1,justifyContent:"center",alignItems:"center",padding:20},emptyText:{fontSize:16,color:"#666",textAlign:"center"},carouselContainer:{paddingHorizontal:16},listContainer:{padding:16},carouselCard:{width:Le*.8,marginRight:16},listCard:{marginBottom:16},card:{backgroundColor:"#ffffff",borderRadius:12,padding:20,shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:8,elevation:4,borderWidth:1,borderColor:"#e0e0e0"},popularCard:{borderColor:"#007AFF",borderWidth:2},popularBadge:{position:"absolute",top:-1,left:-1,right:-1,backgroundColor:"#007AFF",paddingVertical:8,borderTopLeftRadius:12,borderTopRightRadius:12,alignItems:"center"},popularBadgeText:{color:"#ffffff",fontSize:12,fontWeight:"600"},cardHeader:{alignItems:"center",marginBottom:20,marginTop:20},planName:{fontSize:20,fontWeight:"700",color:"#333",marginBottom:8,textAlign:"center"},planDescription:{fontSize:14,color:"#666",textAlign:"center",marginBottom:16,lineHeight:20},planPrice:{fontSize:28,fontWeight:"800",color:"#333",marginBottom:8,textAlign:"center"},trialInfo:{fontSize:12,color:"#22c55e",fontWeight:"600",textAlign:"center"},featuresContainer:{marginBottom:24},featureItem:{flexDirection:"row",alignItems:"flex-start",marginBottom:12},featureCheckmark:{color:"#22c55e",fontSize:16,fontWeight:"700",marginRight:12,marginTop:2},featureText:{flex:1,fontSize:14,color:"#555",lineHeight:20},buttonContainer:{marginTop:"auto"},ctaButton:{paddingVertical:16,borderRadius:8},ctaButtonText:{fontSize:16,fontWeight:"600"},popularButton:{backgroundColor:"#007AFF"},popularButtonText:{color:"#ffffff"},regularButton:{backgroundColor:"#f8f9fa",borderWidth:1,borderColor:"#e0e0e0"},regularButtonText:{color:"#333"}});var ie=require("react"),_=require("react-native"),be=require("@stripe/stripe-react-native");var B=require("react/jsx-runtime"),Ke=({clientSecret:o,customerId:e,customerEmail:t,amount:r,currency:n="usd",description:i,metadata:d,onSuccess:c,onError:m,onLoading:b,containerStyle:P,showBillingDetails:g=!0})=>{let{confirmPayment:x}=(0,be.useStripe)(),{initialized:D}=H(),[s,S]=(0,ie.useState)(!1),[M,k]=(0,ie.useState)(t||""),[q,O]=(0,ie.useState)(""),[R,a]=(0,ie.useState)(""),[p,v]=(0,ie.useState)(!1),T=l=>{m?.(l),_.Alert.alert("Payment Error",l),console.error("Payment error:",l)},f=async()=>{if(!D){T(h.PROVIDER_NOT_CONFIGURED);return}if(g&&M&&!te(M)){T("Please enter a valid email address");return}if(!p){T("Please complete your card information");return}let l=o;if(!l&&r)try{let E=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({amount:r,currency:n,customerId:e,description:i,metadata:d})});if(!E.ok)throw new Error("Failed to create payment intent");let{client_secret:W}=await E.json();l=W}catch{T("Failed to initialize payment");return}if(!l){T("Payment could not be initialized");return}S(!0),b?.(!0);try{let E=g?{email:M||void 0,name:q||void 0,phone:R||void 0}:void 0,{error:W,paymentIntent:pe}=await x(l,{paymentMethodType:"Card",paymentMethodData:{billingDetails:E}});if(W)throw new Error(W.message||h.PAYMENT_FAILED);if(pe?.status==="Succeeded")c?.(pe),_.Alert.alert("Success","Payment completed successfully!");else throw new Error("Payment was not completed")}catch(E){let W=E instanceof Error?E.message:h.PAYMENT_FAILED;T(W)}finally{S(!1),b?.(!1)}};return(0,B.jsx)(_.KeyboardAvoidingView,{behavior:_.Platform.OS==="ios"?"padding":"height",style:[K.container,P],children:(0,B.jsxs)(_.ScrollView,{showsVerticalScrollIndicator:!1,children:[g&&(0,B.jsxs)(_.View,{style:K.billingSection,children:[(0,B.jsx)(_.Text,{style:K.sectionTitle,children:"Billing Information"}),(0,B.jsxs)(_.View,{style:K.inputContainer,children:[(0,B.jsx)(_.Text,{style:K.inputLabel,children:"Email *"}),(0,B.jsx)(_.TextInput,{style:K.textInput,value:M,onChangeText:k,placeholder:"your@email.com",keyboardType:"email-address",autoCapitalize:"none",autoCorrect:!1})]}),(0,B.jsxs)(_.View,{style:K.inputContainer,children:[(0,B.jsx)(_.Text,{style:K.inputLabel,children:"Full Name"}),(0,B.jsx)(_.TextInput,{style:K.textInput,value:q,onChangeText:O,placeholder:"John Doe",autoCapitalize:"words"})]}),(0,B.jsxs)(_.View,{style:K.inputContainer,children:[(0,B.jsx)(_.Text,{style:K.inputLabel,children:"Phone"}),(0,B.jsx)(_.TextInput,{style:K.textInput,value:R,onChangeText:a,placeholder:"+1 (555) 123-4567",keyboardType:"phone-pad"})]})]}),(0,B.jsxs)(_.View,{style:K.cardSection,children:[(0,B.jsx)(_.Text,{style:K.sectionTitle,children:"Payment Information"}),(0,B.jsx)(_.View,{style:K.cardContainer,children:(0,B.jsx)(be.CardField,{postalCodeEnabled:!0,placeholders:{number:"4242 4242 4242 4242"},cardStyle:mt,style:K.cardFieldContainer,onCardChange:l=>{v(l.complete)}})})]}),(0,B.jsx)(_.TouchableOpacity,{style:[K.payButton,s&&K.payButtonDisabled],onPress:f,disabled:s||!p,activeOpacity:.8,children:s?(0,B.jsx)(_.ActivityIndicator,{color:"#ffffff",size:"small"}):(0,B.jsxs)(_.Text,{style:K.payButtonText,children:["Pay ",r?`$${(r/100).toFixed(2)}`:""]})})]})})},mt={backgroundColor:"#fafafa",textColor:"#333",fontSize:16,placeholderColor:"#999"},K=_.StyleSheet.create({container:{flex:1,padding:20,backgroundColor:"#ffffff"},billingSection:{marginBottom:24},cardSection:{marginBottom:32},sectionTitle:{fontSize:18,fontWeight:"600",color:"#333",marginBottom:16},inputContainer:{marginBottom:16},inputLabel:{fontSize:14,fontWeight:"500",color:"#555",marginBottom:8},textInput:{borderWidth:1,borderColor:"#ddd",borderRadius:8,paddingHorizontal:12,paddingVertical:12,fontSize:16,backgroundColor:"#fafafa"},cardContainer:{borderWidth:1,borderColor:"#ddd",borderRadius:8,backgroundColor:"#fafafa"},cardFieldContainer:{width:"100%",height:50},payButton:{backgroundColor:"#007AFF",paddingVertical:16,borderRadius:8,alignItems:"center",justifyContent:"center",minHeight:52},payButtonDisabled:{opacity:.5},payButtonText:{color:"#ffffff",fontSize:18,fontWeight:"600"}});var $e=require("@stripe/stripe-react-native"),se=require("react-native");var Ye=require("react/jsx-runtime"),We=({customerId:o,amount:e,currency:t="usd",paymentIntentClientSecret:r,onSuccess:n,onError:i,children:d})=>{let{presentPaymentSheet:c,initPaymentSheet:m}=(0,$e.useStripe)(),{initialized:b}=H(),P=async()=>{if(!b){i?.("Payment provider not initialized");return}try{if(r){let{error:x}=await m({merchantDisplayName:"Your App Name",paymentIntentClientSecret:r,defaultBillingDetails:{name:""},allowsDelayedPaymentMethods:!0});if(x)throw new Error(x.message)}let{error:g}=await c();if(g){if(g.code==="Canceled")return;throw new Error(g.message)}n?.({status:"succeeded"})}catch(g){let x=g instanceof Error?g.message:"Payment failed";i?.(x),se.Alert.alert("Payment Error",x)}};return(0,Ye.jsx)(se.View,{style:dt.container,children:d})},dt=se.StyleSheet.create({container:{flex:1}});var ge=require("react"),C=require("react-native");var w=require("react/jsx-runtime"),Ge=({subscription:o,onCancel:e,onReactivate:t,onUpdate:r,style:n})=>{let{activeSubscription:i,loading:d,error:c}=H(),[m,b]=(0,ge.useState)(null);(0,ge.useEffect)(()=>{b(o||i)},[o,i]);let P=()=>{m&&C.Alert.alert("Cancel Subscription","Are you sure you want to cancel your subscription? You will retain access until the end of your current billing period.",[{text:"Keep Subscription",style:"cancel"},{text:"Cancel",style:"destructive",onPress:()=>e?.(m.id)}])},g=()=>{m&&C.Alert.alert("Reactivate Subscription","Would you like to reactivate your subscription?",[{text:"No",style:"cancel"},{text:"Reactivate",onPress:()=>t?.(m.id)}])},x=M=>{switch(M){case"active":return"#10B981";case"trialing":return"#3B82F6";case"past_due":return"#F59E0B";case"canceled":return"#EF4444";default:return"#6B7280"}},D=M=>{switch(M){case"active":return"Active";case"trialing":return"Trial";case"past_due":return"Past Due";case"canceled":return"Canceled";default:return M}};if(d)return(0,w.jsx)(C.View,{style:[I.container,n],children:(0,w.jsx)(C.Text,{style:I.loadingText,children:"Loading subscription..."})});if(c)return(0,w.jsx)(C.View,{style:[I.container,n],children:(0,w.jsxs)(C.Text,{style:I.errorText,children:["Error: ",c.message]})});if(!m)return(0,w.jsx)(C.View,{style:[I.container,n],children:(0,w.jsx)(C.Text,{style:I.noSubscriptionText,children:"No active subscription"})});let s=m.status==="active"||m.status==="trialing",S=m.status==="canceled";return(0,w.jsxs)(C.ScrollView,{style:[I.container,n],children:[(0,w.jsxs)(C.View,{style:I.header,children:[(0,w.jsx)(C.Text,{style:I.title,children:"Subscription Details"}),(0,w.jsx)(C.View,{style:[I.statusBadge,{backgroundColor:x(m.status)}],children:(0,w.jsx)(C.Text,{style:I.statusText,children:D(m.status)})})]}),(0,w.jsxs)(C.View,{style:I.detailsContainer,children:[(0,w.jsxs)(C.View,{style:I.detailRow,children:[(0,w.jsx)(C.Text,{style:I.detailLabel,children:"Amount:"}),(0,w.jsx)(C.Text,{style:I.detailValue,children:Ce(m.amount||0,m.currency)})]}),(0,w.jsxs)(C.View,{style:I.detailRow,children:[(0,w.jsx)(C.Text,{style:I.detailLabel,children:"Billing Interval:"}),(0,w.jsx)(C.Text,{style:I.detailValue,children:m.interval})]}),(0,w.jsxs)(C.View,{style:I.detailRow,children:[(0,w.jsx)(C.Text,{style:I.detailLabel,children:"Current Period:"}),(0,w.jsxs)(C.Text,{style:I.detailValue,children:[me(m.currentPeriodStart)," -"," ",me(m.currentPeriodEnd)]})]}),m.trialEnd&&(0,w.jsxs)(C.View,{style:I.detailRow,children:[(0,w.jsx)(C.Text,{style:I.detailLabel,children:"Trial Ends:"}),(0,w.jsx)(C.Text,{style:I.detailValue,children:me(m.trialEnd)})]}),m.cancelAtPeriodEnd&&(0,w.jsx)(C.View,{style:I.warningContainer,children:(0,w.jsxs)(C.Text,{style:I.warningText,children:["Your subscription will cancel on"," ",me(m.currentPeriodEnd)]})})]}),(0,w.jsxs)(C.View,{style:I.actionsContainer,children:[s&&!m.cancelAtPeriodEnd&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(C.TouchableOpacity,{style:I.primaryButton,onPress:()=>r?.(m.id),children:(0,w.jsx)(C.Text,{style:I.primaryButtonText,children:"Update Plan"})}),(0,w.jsx)(C.TouchableOpacity,{style:I.dangerButton,onPress:P,children:(0,w.jsx)(C.Text,{style:I.dangerButtonText,children:"Cancel Subscription"})})]}),m.cancelAtPeriodEnd&&(0,w.jsx)(C.TouchableOpacity,{style:I.primaryButton,onPress:g,children:(0,w.jsx)(C.Text,{style:I.primaryButtonText,children:"Reactivate Subscription"})}),S&&(0,w.jsx)(C.TouchableOpacity,{style:I.primaryButton,onPress:()=>r?.(m.id),children:(0,w.jsx)(C.Text,{style:I.primaryButtonText,children:"Subscribe Again"})})]})]})},I=C.StyleSheet.create({container:{flex:1,backgroundColor:"#FFFFFF",padding:16},header:{flexDirection:"row",justifyContent:"space-between",alignItems:"center",marginBottom:24},title:{fontSize:24,fontWeight:"bold",color:"#1F2937"},statusBadge:{paddingHorizontal:12,paddingVertical:6,borderRadius:16},statusText:{color:"#FFFFFF",fontSize:12,fontWeight:"600"},detailsContainer:{backgroundColor:"#F9FAFB",borderRadius:8,padding:16,marginBottom:24},detailRow:{flexDirection:"row",justifyContent:"space-between",alignItems:"center",paddingVertical:8,borderBottomWidth:1,borderBottomColor:"#E5E7EB"},detailLabel:{fontSize:14,color:"#6B7280",fontWeight:"500"},detailValue:{fontSize:14,color:"#1F2937",fontWeight:"600"},warningContainer:{backgroundColor:"#FEF3C7",borderRadius:8,padding:12,marginTop:16},warningText:{color:"#92400E",fontSize:14,textAlign:"center"},actionsContainer:{gap:12},primaryButton:{backgroundColor:"#3B82F6",borderRadius:8,padding:16,alignItems:"center"},primaryButtonText:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},dangerButton:{backgroundColor:"#EF4444",borderRadius:8,padding:16,alignItems:"center"},dangerButtonText:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},loadingText:{textAlign:"center",color:"#6B7280",fontSize:16},errorText:{textAlign:"center",color:"#EF4444",fontSize:16},noSubscriptionText:{textAlign:"center",color:"#6B7280",fontSize:16}});var Ee=require("react"),L=require("react-native"),je=require("@stripe/stripe-react-native"),J=require("react/jsx-runtime"),we=null;try{we=require("react-native-touch-id")}catch{}var pt={title:"Authentication Required",imageColor:"#e00606",sensorDescription:"Touch sensor",sensorErrorDescription:"Failed",cancelText:"Cancel",fallbackLabel:"Show Passcode",unifiedErrors:!1,passcodeFallback:!1},qe=({amount:o,currency:e="USD",paymentMethodId:t,clientSecret:r,onSuccess:n,onError:i,onCancel:d,title:c="Authorize Payment",subtitle:m,style:b})=>{let[P,g]=(0,Ee.useState)(!1),[x,D]=(0,Ee.useState)(!1),{confirmPayment:s}=(0,je.useStripe)(),S=async()=>{try{return await we.isSupported()!==!1}catch{return!1}},M=async()=>{try{return await we.authenticate("Authenticate to complete your payment",pt),!0}catch(a){return a.name==="UserCancel"||a.name==="UserFallback"?d?.():i?.(`Authentication failed: ${a.message}`),!1}},k=async()=>{if(!r){i?.("Payment configuration is missing");return}D(!0);try{let{error:a,paymentIntent:p}=await s(r,{paymentMethodType:"Card"});if(a)throw new Error(a.message);n?.(p)}catch(a){let p=a instanceof Error?a.message:"Payment failed";i?.(p)}finally{D(!1)}},q=async()=>{g(!0);try{if(!await S()){L.Alert.alert("Biometric Authentication Not Available","Your device does not support biometric authentication. Please use an alternative payment method.",[{text:"OK",onPress:d}]);return}await M()&&await k()}catch(a){let p=a instanceof Error?a.message:"Authentication failed";i?.(p)}finally{g(!1)}},O=(a,p)=>new Intl.NumberFormat("en-US",{style:"currency",currency:p.toUpperCase()}).format(a/100),R=()=>L.Platform.OS==="ios"?"\u{1F446}":"\u{1F512}";return(0,J.jsx)(L.View,{style:[X.container,b],children:(0,J.jsxs)(L.View,{style:X.content,children:[(0,J.jsx)(L.Text,{style:X.title,children:c}),m&&(0,J.jsx)(L.Text,{style:X.subtitle,children:m}),(0,J.jsxs)(L.View,{style:X.amountContainer,children:[(0,J.jsx)(L.Text,{style:X.amountLabel,children:"Amount"}),(0,J.jsx)(L.Text,{style:X.amount,children:O(o,e)})]}),(0,J.jsxs)(L.TouchableOpacity,{style:[X.payButton,(P||x)&&X.payButtonDisabled],onPress:q,disabled:P||x,children:[(0,J.jsx)(L.Text,{style:X.biometricIcon,children:R()}),(0,J.jsx)(L.Text,{style:X.payButtonText,children:P?"Authenticating...":x?"Processing...":`Pay with ${L.Platform.OS==="ios"?"Touch ID":"Biometrics"}`})]}),(0,J.jsx)(L.Text,{style:X.securityNote,children:"Your payment information is secured with biometric authentication"})]})})},X=L.StyleSheet.create({container:{backgroundColor:"#FFFFFF",borderRadius:12,padding:20,margin:16,shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:3.84,elevation:5},content:{alignItems:"center"},title:{fontSize:20,fontWeight:"bold",color:"#1F2937",marginBottom:8,textAlign:"center"},subtitle:{fontSize:14,color:"#6B7280",marginBottom:20,textAlign:"center"},amountContainer:{backgroundColor:"#F9FAFB",borderRadius:8,padding:16,marginBottom:24,minWidth:200,alignItems:"center"},amountLabel:{fontSize:12,color:"#6B7280",marginBottom:4},amount:{fontSize:24,fontWeight:"bold",color:"#1F2937"},payButton:{backgroundColor:"#3B82F6",borderRadius:8,paddingVertical:16,paddingHorizontal:32,flexDirection:"row",alignItems:"center",marginBottom:12},payButtonDisabled:{backgroundColor:"#9CA3AF"},biometricIcon:{fontSize:20,marginRight:8},payButtonText:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},securityNote:{fontSize:12,color:"#6B7280",textAlign:"center",marginTop:8}});var He=require("@stripe/stripe-react-native");var re=require("react-native"),oe=require("react/jsx-runtime"),Je=({children:o,merchantIdentifier:e,urlScheme:t,setReturnUrlSchemeOnAndroid:r=!1})=>{let{config:n,initialized:i}=H();return i?n?.publishableKey?(0,oe.jsx)(He.StripeProvider,{publishableKey:n.publishableKey,merchantIdentifier:e,urlScheme:t,setReturnUrlSchemeOnAndroid:r,children:o}):null:n?.environment==="development"?(0,oe.jsxs)(re.View,{style:Se.errorContainer,children:[(0,oe.jsx)(re.Text,{style:Se.errorTitle,children:"Payments Provider Error"}),(0,oe.jsx)(re.Text,{style:Se.errorMessage,children:h.PROVIDER_NOT_CONFIGURED}),(0,oe.jsx)(re.Text,{style:Se.errorSubtext,children:"Please check your PaymentsProvider configuration."})]}):null},Se=re.StyleSheet.create({errorContainer:{padding:20,backgroundColor:"#fee",borderColor:"#fcc",borderWidth:1,borderRadius:4,margin:10},errorTitle:{fontWeight:"bold",fontSize:16,color:"#c53030",marginBottom:8},errorMessage:{fontSize:14,color:"#c53030",marginBottom:4},errorSubtext:{fontSize:12,color:"#a0a0a0"}});var U=require("react");var Xe=()=>{let[o,e]=(0,U.useState)(null),[t,r]=(0,U.useState)(null),[n,i]=(0,U.useState)(!1),[d,c]=(0,U.useState)(!1),[m,b]=(0,U.useState)(null),[P,g]=(0,U.useState)(null),[x,D]=(0,U.useState)([]),s=(0,U.useCallback)(N=>{b(N),console.error("Payments error:",N)},[]),S=(0,U.useCallback)(async(N,y)=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let Y=await t.listSubscriptions(N,y);D(Y)}catch(Y){throw s(Y),Y}finally{c(!1)}},[t,s]),M=(0,U.useCallback)(async N=>{c(!0),b(null);try{let y=N||z.autodetect(),Y=z.create(y);e(y),r(Y),i(!0)}catch(y){s(y)}finally{c(!1)}},[s]),k=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.retrieveCustomer(N);return g(y),y}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),q=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.createCustomer(N);return g(y),y}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),O=(0,U.useCallback)(async N=>{if(!t||!P)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.createSubscription({customerId:P.id,items:[{priceId:N.priceId,quantity:N.quantity}]});return await S(P.id),y}catch(y){throw s(y),y}finally{c(!1)}},[t,P,s,S]),R=(0,U.useCallback)(async(N,y)=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let Y=await t.listSubscriptions(N,y);return D(Y),Y}catch(Y){throw s(Y),Y}finally{c(!1)}},[t,s]),a=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.retrieveSubscription(N);return P?.id&&await S(P.id),y}catch(y){throw s(y),y}finally{c(!1)}},[t,P,s,S]),p=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{return await t.createCheckoutSession(N)}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),v=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{return await t.retrieveCheckoutSession(N)}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),T=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{await t.cancelSubscription(N),P?.id&&await S(P.id)}catch(y){throw s(y),y}finally{c(!1)}},[t,P,s,S]),f=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{await t.reactivateSubscription(N),P?.id&&await S(P.id)}catch(y){throw s(y),y}finally{c(!1)}},[t,P,s,S]),l=(0,U.useCallback)(async(N,y)=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let Y=await t.updateSubscription(N,y);return P?.id&&await S(P.id),Y}catch(Y){throw s(Y),Y}finally{c(!1)}},[t,P,s,S]),E=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.retrieveCustomer(N);g(y)}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),W=(0,U.useCallback)(()=>{e(null),r(null),i(!1),c(!1),b(null),g(null),D([])},[]),pe=x.find(N=>N.status==="active"||N.status==="trialing")||null;return(0,U.useEffect)(()=>{},[]),{config:o,provider:t,initialized:n,loading:d,error:m,isLoading:d,isError:!!m,customer:P,subscriptions:x,activeSubscription:pe,initialize:M,createCustomer:q,retrieveCustomer:k,createCheckoutSession:p,retrieveCheckoutSession:v,createSubscription:O,cancelSubscription:T,reactivateSubscription:f,listSubscriptions:R,retrieveSubscription:a,updateSubscription:l,refreshCustomer:E,refreshSubscriptions:S,reset:W}};var j=require("react"),ae=require("react-native");var Ze=(o={})=>{let{customerId:e,subscriptionId:t,autoFetch:r=!0,onError:n,showErrorAlert:i=!0}=o,[d,c]=(0,j.useState)(null),[m,b]=(0,j.useState)([]),[P,g]=(0,j.useState)(!1),[x,D]=(0,j.useState)(null),s=(0,j.useCallback)(a=>{D(a),n?.(a),i&&ae.Alert.alert("Subscription Error",a),console.error("Subscription error:",a)},[n,i]),S=(0,j.useCallback)(async a=>{if(!G(a,"subscription"))return s("Invalid subscription ID"),null;try{let p=await fetch(`/api/payments/subscription/${a}`);if(!p.ok){let T=await p.json().catch(()=>({error:"Network error"}));throw new Error(T.error||h.SUBSCRIPTION_NOT_FOUND)}return await p.json()}catch(p){let v=p instanceof Error?p.message:h.SUBSCRIPTION_NOT_FOUND;return s(v),null}},[s]),M=(0,j.useCallback)(async a=>{if(!G(a,"customer"))return s("Invalid customer ID"),[];try{let p=await fetch(`/api/payments/customer/${a}/subscriptions`);if(!p.ok){let T=await p.json().catch(()=>({error:"Network error"}));throw new Error(T.error||h.CUSTOMER_NOT_FOUND)}return(await p.json()).subscriptions||[]}catch(p){let v=p instanceof Error?p.message:h.CUSTOMER_NOT_FOUND;return s(v),[]}},[s]),k=(0,j.useCallback)(async()=>{if(!e&&!t){s("Either customerId or subscriptionId is required");return}g(!0),D(null);try{if(t){let a=await S(t);c(a)}if(e){let a=await M(e);if(b(a),!t&&a.length>0){let p=a.find(v=>v.status==="active")||a[0];c(p)}}}finally{g(!1)}},[e,t,S,M,s]),q=(0,j.useCallback)(async a=>{let p=a||t;return p?G(p,"subscription")?new Promise(v=>{ae.Alert.alert("Cancel Subscription","Are you sure you want to cancel your subscription? It will remain active until the end of your current billing period.",[{text:"Keep Subscription",style:"cancel",onPress:()=>v(!1)},{text:"Cancel Subscription",style:"destructive",onPress:async()=>{try{let T=await fetch(`/api/payments/subscription/${p}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!T.ok){let f=await T.json().catch(()=>({error:"Network error"}));throw new Error(f.error||"Failed to cancel subscription")}await k(),ae.Alert.alert("Success","Your subscription has been cancelled and will end at the end of your current billing period."),v(!0)}catch(T){let f=T instanceof Error?T.message:"Failed to cancel subscription";s(f),v(!1)}}}])}):(s("Invalid subscription ID"),!1):(s("Subscription ID is required to cancel"),!1)},[t,k,s]),O=(0,j.useCallback)(async a=>{let p=a||t;if(!p)return s("Subscription ID is required to reactivate"),!1;if(!G(p,"subscription"))return s("Invalid subscription ID"),!1;try{let v=await fetch(`/api/payments/subscription/${p}/reactivate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!v.ok){let T=await v.json().catch(()=>({error:"Network error"}));throw new Error(T.error||"Failed to reactivate subscription")}return await k(),ae.Alert.alert("Success","Your subscription has been reactivated!"),!0}catch(v){let T=v instanceof Error?v.message:"Failed to reactivate subscription";return s(T),!1}},[t,k,s]),R=(0,j.useCallback)(async(a,p)=>{if(!G(a,"subscription"))return s("Invalid subscription ID"),!1;try{let v=await fetch(`/api/payments/subscription/${a}/payment-method`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethodId:p})});if(!v.ok){let T=await v.json().catch(()=>({error:"Network error"}));throw new Error(T.error||"Failed to update payment method")}return await k(),ae.Alert.alert("Success","Payment method updated successfully!"),!0}catch(v){let T=v instanceof Error?v.message:"Failed to update payment method";return s(T),!1}},[k,s]);return(0,j.useEffect)(()=>{r&&(e||t)&&k()},[r,e,t,k]),{subscription:d,subscriptions:m,loading:P,error:x,isLoading:P,isError:!!x,refetch:k,cancel:q,reactivate:O,updatePaymentMethod:R}};var ee=require("react"),Re=require("react-native"),Qe=require("@stripe/stripe-react-native");var et=(o={})=>{let{onSuccess:e,onError:t,onLoading:r,showErrorAlert:n=!0,showSuccessAlert:i=!0}=o,{initPaymentSheet:d,presentPaymentSheet:c,confirmPayment:m}=(0,Qe.useStripe)(),{initialized:b}=H(),[P,g]=(0,ee.useState)(!1),[x,D]=(0,ee.useState)(null),s=(0,ee.useCallback)(O=>{D(O),t?.(O),n&&Re.Alert.alert("Payment Error",O),console.error("Checkout error:",O)},[t,n]),S=(0,ee.useCallback)(O=>{e?.(O),i&&Re.Alert.alert("Success","Payment completed successfully!")},[e,i]),M=(0,ee.useCallback)(async O=>{if(!b)return s(h.PROVIDER_NOT_CONFIGURED),!1;if(!G(O.priceId,"price"))return s(h.INVALID_PRICE_ID),!1;if(O.customerId&&!G(O.customerId,"customer"))return s(h.INVALID_CUSTOMER_ID),!1;if(O.customerEmail&&!te(O.customerEmail))return s("Invalid customer email"),!1;g(!0),D(null),r?.(!0);try{let R=await fetch("/api/payments/create-subscription-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!R.ok){let l=await R.json().catch(()=>({error:"Network error"}));throw new Error(l.error||"Failed to create subscription setup")}let{setupIntentClientSecret:a,customerId:p,customerEphemeralKeySecret:v}=await R.json();if(!a)throw new Error("No setup intent client secret returned from server");let{error:T}=await d({setupIntentClientSecret:a,customerId:p,customerEphemeralKeySecret:v,merchantDisplayName:"Your App Name",allowsDelayedPaymentMethods:!0});if(T)throw new Error(T.message||"Failed to initialize payment sheet");let{error:f}=await c();if(f){if(f.code==="Canceled")return!1;throw new Error(f.message||h.PAYMENT_FAILED)}return S({type:"subscription",customerId:p}),!0}catch(R){let a=R instanceof Error?R.message:"Failed to create subscription";return s(a),!1}finally{g(!1),r?.(!1)}},[b,d,c,s,S,r]),k=(0,ee.useCallback)(async O=>{if(!b)return s(h.PROVIDER_NOT_CONFIGURED),null;if(O.amount<=0)return s("Amount must be greater than 0"),null;if(O.customerId&&!G(O.customerId,"customer"))return s(h.INVALID_CUSTOMER_ID),null;g(!0),D(null),r?.(!0);try{let R=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!R.ok){let p=await R.json().catch(()=>({error:"Network error"}));throw new Error(p.error||"Failed to create payment intent")}let{client_secret:a}=await R.json();if(!a)throw new Error("No client secret returned from server");return a}catch(R){let a=R instanceof Error?R.message:"Failed to create payment intent";return s(a),null}finally{g(!1),r?.(!1)}},[b,s,r]),q=(0,ee.useCallback)(async(O,R)=>{if(!b)return s(h.PROVIDER_NOT_CONFIGURED),!1;if(R?.email&&!te(R.email))return s("Invalid email address"),!1;g(!0),D(null),r?.(!0);try{let{error:a,paymentIntent:p}=await m(O,{paymentMethodType:"Card",paymentMethodData:{billingDetails:R}});if(a)throw new Error(a.message||h.PAYMENT_FAILED);if(p?.status==="Succeeded")return S({type:"payment",paymentIntent:p}),!0;throw new Error("Payment was not completed")}catch(a){let p=a instanceof Error?a.message:h.PAYMENT_FAILED;return s(p),!1}finally{g(!1),r?.(!1)}},[b,m,s,S,r]);return{loading:P,error:x,isLoading:P,isError:!!x,createSubscription:M,createPaymentIntent:k,processPayment:q}};var $=require("react"),de=require("react-native");var tt=(o={})=>{let{customerId:e,autoFetch:t=!0,onError:r,showErrorAlert:n=!0,showSuccessAlert:i=!0}=o,[d,c]=(0,$.useState)(null),[m,b]=(0,$.useState)([]),[P,g]=(0,$.useState)(!1),[x,D]=(0,$.useState)(null),s=(0,$.useCallback)(f=>{D(f),r?.(f),n&&de.Alert.alert("Customer Error",f),console.error("Customer error:",f)},[r,n]),S=(0,$.useCallback)(f=>{i&&de.Alert.alert("Success",f)},[i]),M=(0,$.useCallback)(async f=>{if(!G(f,"customer"))return s("Invalid customer ID"),null;try{let l=await fetch(`/api/payments/customer/${f}`);if(!l.ok){let W=await l.json().catch(()=>({error:"Network error"}));throw new Error(W.error||h.CUSTOMER_NOT_FOUND)}return await l.json()}catch(l){let E=l instanceof Error?l.message:h.CUSTOMER_NOT_FOUND;return s(E),null}},[s]),k=(0,$.useCallback)(async()=>{if(!e){s("Customer ID is required");return}g(!0),D(null);try{let f=await M(e);c(f)}finally{g(!1)}},[e,M,s]),q=(0,$.useCallback)(async f=>{if(!te(f.email))return s("Invalid email address"),null;g(!0),D(null);try{let l=await fetch("/api/payments/customer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!l.ok){let W=await l.json().catch(()=>({error:"Network error"}));throw new Error(W.error||"Failed to create customer")}let E=await l.json();return c(E),S("Customer created successfully!"),E}catch(l){let E=l instanceof Error?l.message:"Failed to create customer";return s(E),null}finally{g(!1)}},[s,S]),O=(0,$.useCallback)(async f=>{if(!e)return s("Customer ID is required"),!1;if(f.email&&!te(f.email))return s("Invalid email address"),!1;g(!0),D(null);try{let l=await fetch(`/api/payments/customer/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!l.ok){let E=await l.json().catch(()=>({error:"Network error"}));throw new Error(E.error||"Failed to update customer")}return await k(),S("Customer updated successfully!"),!0}catch(l){let E=l instanceof Error?l.message:"Failed to update customer";return s(E),!1}finally{g(!1)}},[e,k,s,S]),R=(0,$.useCallback)(async()=>e?new Promise(f=>{de.Alert.alert("Delete Customer","Are you sure you want to delete this customer? This action cannot be undone.",[{text:"Cancel",style:"cancel",onPress:()=>f(!1)},{text:"Delete",style:"destructive",onPress:async()=>{g(!0),D(null);try{let l=await fetch(`/api/payments/customer/${e}`,{method:"DELETE"});if(!l.ok){let E=await l.json().catch(()=>({error:"Network error"}));throw new Error(E.error||"Failed to delete customer")}c(null),b([]),S("Customer deleted successfully!"),f(!0)}catch(l){let E=l instanceof Error?l.message:"Failed to delete customer";s(E),f(!1)}finally{g(!1)}}}])}):(s("Customer ID is required"),!1),[e,s,S]),a=(0,$.useCallback)(async()=>{if(!e)return s("Customer ID is required"),[];try{let f=await fetch(`/api/payments/customer/${e}/payment-methods`);if(!f.ok){let W=await f.json().catch(()=>({error:"Network error"}));throw new Error(W.error||"Failed to fetch payment methods")}let E=(await f.json()).paymentMethods||[];return b(E),E}catch(f){let l=f instanceof Error?f.message:"Failed to fetch payment methods";return s(l),[]}},[e,s]),p=(0,$.useCallback)(async f=>{if(!e)return s("Customer ID is required"),!1;try{let l=await fetch(`/api/payments/customer/${e}/payment-methods`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethodId:f})});if(!l.ok){let E=await l.json().catch(()=>({error:"Network error"}));throw new Error(E.error||"Failed to add payment method")}return await a(),S("Payment method added successfully!"),!0}catch(l){let E=l instanceof Error?l.message:"Failed to add payment method";return s(E),!1}},[e,a,s,S]),v=(0,$.useCallback)(async f=>e?new Promise(l=>{de.Alert.alert("Remove Payment Method","Are you sure you want to remove this payment method?",[{text:"Cancel",style:"cancel",onPress:()=>l(!1)},{text:"Remove",style:"destructive",onPress:async()=>{try{let E=await fetch(`/api/payments/customer/${e}/payment-methods/${f}`,{method:"DELETE"});if(!E.ok){let W=await E.json().catch(()=>({error:"Network error"}));throw new Error(W.error||"Failed to remove payment method")}await a(),S("Payment method removed successfully!"),l(!0)}catch(E){let W=E instanceof Error?E.message:"Failed to remove payment method";s(W),l(!1)}}}])}):(s("Customer ID is required"),!1),[e,a,s,S]),T=(0,$.useCallback)(async f=>{if(!e)return s("Customer ID is required"),!1;try{let l=await fetch(`/api/payments/customer/${e}/default-payment-method`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethodId:f})});if(!l.ok){let E=await l.json().catch(()=>({error:"Network error"}));throw new Error(E.error||"Failed to set default payment method")}return await Promise.all([k(),a()]),S("Default payment method updated successfully!"),!0}catch(l){let E=l instanceof Error?l.message:"Failed to set default payment method";return s(E),!1}},[e,k,a,s,S]);return(0,$.useEffect)(()=>{t&&e&&(k(),a())},[t,e,k,a]),{customer:d,paymentMethods:m,loading:P,error:x,isLoading:P,isError:!!x,refetch:k,createCustomer:q,updateCustomer:O,deleteCustomer:R,fetchPaymentMethods:a,addPaymentMethod:p,removePaymentMethod:v,setDefaultPaymentMethod:T}};var ft=async o=>{try{let e=await fetch("/api/payments/create-subscription-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!e.ok)return{error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to create subscription setup"};let t=await e.json();return{setupIntentClientSecret:t.setupIntentClientSecret,customerId:t.customerId,customerEphemeralKeySecret:t.customerEphemeralKeySecret}}catch(e){return{error:e instanceof Error?e.message:"Failed to create subscription setup"}}},yt=async o=>{try{let e=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return e.ok?{clientSecret:(await e.json()).client_secret}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to create payment intent"}}catch(e){return{error:e instanceof Error?e.message:"Failed to create payment intent"}}},ht=o=>{let e=[];return o.publishableKey||e.push("publishableKey is required"),o.provider||e.push("provider is required"),o.provider!=="stripe"&&e.push("Only stripe provider is currently supported"),o.environment||e.push("environment is required"),o.environment&&!["development","production"].includes(o.environment)&&e.push('environment must be either "development" or "production"'),o.publishableKey&&!o.publishableKey.startsWith("pk_")&&e.push('publishableKey must start with "pk_"'),{isValid:e.length===0,errors:e}},Pt=o=>{if(typeof o=="string")return o;if(typeof o=="object"&&o!==null){if("message"in o&&typeof o.message=="string")return o.message;if("code"in o&&typeof o.code=="string"){let e=o.code;return{Canceled:"Payment was cancelled",Failed:"Payment failed",card_declined:"Your card was declined.",expired_card:"Your card has expired.",incorrect_cvc:"Your card's security code is incorrect.",processing_error:"An error occurred while processing your card.",incorrect_number:"Your card number is incorrect."}[e]||`Payment failed: ${e}`}}return"An unexpected error occurred."},bt=async o=>{try{let e=await fetch("/api/payments/customer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return e.ok?{customer:await e.json()}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to create customer"}}catch(e){return{error:e instanceof Error?e.message:"Failed to create customer"}}},gt=async o=>{try{let e=await fetch(`/api/payments/subscription/${o}`);return e.ok?{subscription:await e.json()}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||h.SUBSCRIPTION_NOT_FOUND}}catch(e){return{error:e instanceof Error?e.message:h.SUBSCRIPTION_NOT_FOUND}}},St=async o=>{try{let e=await fetch(`/api/payments/customer/${o}/subscriptions`);return e.ok?{subscriptions:(await e.json()).subscriptions||[]}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||h.CUSTOMER_NOT_FOUND}}catch(e){return{error:e instanceof Error?e.message:h.CUSTOMER_NOT_FOUND}}},Ct=async o=>{try{let e=await fetch(`/api/payments/subscription/${o}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0}:{success:!1,error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to cancel subscription"}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to cancel subscription"}}};0&&(module.exports={CheckoutButton,MobilePaymentSheet,NativeSubscriptionView,PaymentForm,PaymentsProvider,PricingTable,StripeProvider,TouchIDPayment,cancelSubscription,createCustomer,createPaymentIntent,createSubscriptionSetup,fetchCustomerSubscriptions,fetchSubscription,formatStripeError,useCheckout,useCustomer,usePayments,usePaymentsContext,useSubscription,validatePaymentsConfig});
|
|
2
|
+
"use strict";var rt=Object.create;var fe=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,st=Object.prototype.hasOwnProperty;var at=(o,e)=>{for(var t in e)fe(o,t,{get:e[t],enumerable:!0})},Oe=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of nt(e))!st.call(o,n)&&n!==t&&fe(o,n,{get:()=>e[n],enumerable:!(r=ot(e,n))||r.enumerable});return o};var ct=(o,e,t)=>(t=o!=null?rt(it(o)):{},Oe(e||!o||!o.__esModule?fe(t,"default",{value:o,enumerable:!0}):t,o)),ut=o=>Oe(fe({},"__esModule",{value:!0}),o);var Et={};at(Et,{CheckoutButton:()=>Pe,CheckoutForm:()=>Ee,MobilePaymentSheet:()=>Ye,NativeSubscriptionView:()=>je,PaymentForm:()=>Ee,PaymentsProvider:()=>Ae,PricingTable:()=>$e,StripeProvider:()=>Xe,TouchIDPayment:()=>He,cancelSubscription:()=>Ct,createCustomer:()=>bt,createPaymentIntent:()=>yt,createSubscriptionSetup:()=>ft,fetchCustomerSubscriptions:()=>St,fetchSubscription:()=>gt,formatStripeError:()=>Pt,useCheckout:()=>Te,useCustomer:()=>tt,usePayments:()=>Ze,usePaymentsContext:()=>H,useStripe:()=>Te,useSubscription:()=>Qe,validatePaymentsConfig:()=>ht});module.exports=ut(Et);var Ve=require("react"),Q=require("react-native"),Be=require("@stripe/stripe-react-native");var Z=require("react");var Ne=require("zustand"),De=require("zustand/middleware/immer");var u=class o extends Error{type;code;details;constructor(e,t,r,n){super(t),this.name="PaymentsError",this.type=e,this.code=r,this.details=n,Object.setPrototypeOf(this,o.prototype)}};var ne=class{config;constructor(e){this.config=e}handleError(e,t="UNKNOWN_ERROR"){if(e instanceof u)return e;let r="An unknown error occurred",n,i;return typeof e=="object"&&e!==null&&("message"in e&&typeof e.message=="string"&&(r=e.message),"code"in e&&typeof e.code=="string"&&(n=e.code),i={...e}),new u(t,r,n,i)}};var ve=ct(require("stripe")),ye=class extends ne{name="stripe";stripeClient;constructor(e){if(super(e),!e.stripeConfig?.publishableKey)throw new u("CONFIGURATION_ERROR","Stripe publishable key is missing in config.");if(!process.env.STRIPE_SECRET_KEY)throw new u("CONFIGURATION_ERROR","STRIPE_SECRET_KEY environment variable is not set.");this.stripeClient=new ve.default(process.env.STRIPE_SECRET_KEY,{apiVersion:"2024-06-20"})}async initialize(){console.log("StripePaymentProvider initialized (server-side)")}async createCheckoutSession(e){try{let t=await this.stripeClient.checkout.sessions.create({payment_method_types:["card"],line_items:[{price:e.priceId,quantity:1}],mode:e.mode||"payment",success_url:e.successUrl||`${process.env.NEXT_PUBLIC_BASE_URL}/success?session_id={CHECKOUT_SESSION_ID}`,cancel_url:e.cancelUrl||`${process.env.NEXT_PUBLIC_BASE_URL}/cancel`,customer_email:e.customerEmail,allow_promotion_codes:e.allowPromotionCodes,metadata:e.metadata});if(!t.url)throw new u("UNKNOWN_ERROR","Stripe checkout session URL is missing.");return{id:t.id,url:t.url,status:t.status,amountTotal:t.amount_total||void 0,currency:t.currency||void 0,customerEmail:t.customer_details?.email||void 0,subscriptionId:t.subscription?.toString()||void 0}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async createCustomer(e){try{let t=await this.stripeClient.customers.create({email:e.email,name:e.name,metadata:e.metadata});return{id:t.id,email:t.email||e.email,name:t.name||e.name,phone:null,stripeCustomerId:t.id,subscriptions:[],paymentMethods:[],defaultPaymentMethodId:null,metadata:t.metadata,created:new Date(t.created*1e3),updated:new Date(t.created*1e3)}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async retrieveCustomer(e){try{let t=await this.stripeClient.customers.retrieve(e);return t.deleted?null:{id:t.id,email:t.email||"",name:t.name||void 0,phone:t.phone||void 0,stripeCustomerId:t.id,subscriptions:[],paymentMethods:[],defaultPaymentMethodId:t.invoice_settings?.default_payment_method?.toString()||void 0,metadata:t.metadata,created:new Date(t.created*1e3),updated:new Date(t.created*1e3)}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async createSubscription(e){try{let t=await this.stripeClient.subscriptions.create({customer:e.customerId,items:(e.items||(e.priceId?[{priceId:e.priceId,quantity:1}]:[])).map(r=>({price:r.priceId,quantity:r.quantity||1})),trial_period_days:e.trialPeriodDays,metadata:e.metadata,expand:["latest_invoice.payment_intent"]});return this.mapStripeSubscriptionToSubscription(t)}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async cancelSubscription(e){try{await this.stripeClient.subscriptions.cancel(e)}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async reactivateSubscription(e){try{let t=await this.stripeClient.subscriptions.retrieve(e);if(t.status==="canceled"&&t.cancel_at_period_end)await this.stripeClient.subscriptions.update(e,{cancel_at_period_end:!1});else throw new u("VALIDATION_ERROR","Subscription cannot be reactivated.")}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async retrieveCheckoutSession(e){try{let t=await this.stripeClient.checkout.sessions.retrieve(e);if(!t.url)throw new u("UNKNOWN_ERROR","Stripe checkout session URL is missing.");return{id:t.id,url:t.url,status:t.status,amountTotal:t.amount_total||void 0,currency:t.currency||void 0,customerEmail:t.customer_details?.email||void 0,subscriptionId:t.subscription?.toString()||void 0}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async listSubscriptions(e,t){try{return(await this.stripeClient.subscriptions.list({customer:e,status:t==="all"?void 0:t})).data.map(this.mapStripeSubscriptionToSubscription)}catch(r){throw this.handleError(r,"NETWORK_ERROR")}}async retrieveSubscription(e){try{let t=await this.stripeClient.subscriptions.retrieve(e);return this.mapStripeSubscriptionToSubscription(t)}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async updateSubscription(e,t){try{let r=await this.stripeClient.subscriptions.retrieve(e),n=t.items?t.items.map(d=>({id:r.items.data.find(c=>c.price?.id===d.priceId)?.id,price:d.priceId,quantity:d.quantity||1})):void 0,i=await this.stripeClient.subscriptions.update(e,{items:n,metadata:t.metadata});return this.mapStripeSubscriptionToSubscription(i)}catch(r){throw this.handleError(r,"NETWORK_ERROR")}}mapStripeSubscriptionToSubscription(e){return{id:e.id,customerId:e.customer.toString(),status:e.status,items:e.items.data.map(t=>({id:t.id,priceId:t.price?.id||"",quantity:t.quantity||1})),currentPeriodStart:new Date(e.current_period_start*1e3),currentPeriodEnd:new Date(e.current_period_end*1e3),cancelAtPeriodEnd:e.cancel_at_period_end,trialStart:e.trial_start?new Date(e.trial_start*1e3):void 0,trialEnd:e.trial_end?new Date(e.trial_end*1e3):void 0,metadata:e.metadata,created:new Date(e.created*1e3),updated:new Date(e.created*1e3)}}};var he=class extends ne{name="MockPaymentProvider";customers=[];subscriptions=[];nextCustomerId=1;nextSubscriptionId=1;constructor(e){super({...e,provider:"mock"}),console.log("MockPaymentProvider initialized")}async initialize(){console.log("MockPaymentProvider initialized")}async createCheckoutSession(e){return console.log("Mock: createCheckoutSession",e),{id:"mock_cs_123",clientSecret:"mock_client_secret",url:"https://mock-checkout.example.com/success",status:"open"}}async retrieveCheckoutSession(e){if(console.log("Mock: retrieveCheckoutSession",e),e==="mock_cs_123")return{id:"mock_cs_123",clientSecret:"mock_client_secret",url:"https://mock-checkout.example.com/success",status:"complete"};throw new u("CUSTOMER_NOT_FOUND",`Mock checkout session ${e} not found`)}async createCustomer(e){console.log("Mock: createCustomer",e);let t={id:`mock_cus_${this.nextCustomerId++}`,email:e.email,name:e.name||null,phone:e.phone||null,stripeCustomerId:null,subscriptions:[],defaultPaymentMethodId:null,paymentMethods:[],metadata:e.metadata||{},created:new Date,updated:new Date};return this.customers.push(t),t}async retrieveCustomer(e){console.log("Mock: retrieveCustomer",e);let t=this.customers.find(r=>r.id===e);if(!t)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t}async updateCustomer(e,t){console.log("Mock: updateCustomer",e,t);let r=this.customers.find(n=>n.id===e);if(!r)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t.email&&(r.email=t.email),t.name&&(r.name=t.name),t.phone&&(r.phone=t.phone),t.metadata&&(r.metadata={...r.metadata,...t.metadata}),r.updated=new Date,r}async deleteCustomer(e){console.log("Mock: deleteCustomer",e);let t=this.customers.length;if(this.customers=this.customers.filter(r=>r.id!==e),this.customers.length===t)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`)}async listPaymentMethods(e){console.log("Mock: listPaymentMethods",e);let t=this.customers.find(r=>r.id===e);if(!t)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t.paymentMethods||[]}async attachPaymentMethod(e,t){console.log("Mock: attachPaymentMethod",e,t);let r=this.customers.find(i=>i.id===e);if(!r)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n={id:t,type:"card",card:{brand:"visa",last4:"4242",expMonth:12,expYear:2025,country:"US"},isDefault:!1,created:new Date};return r.paymentMethods.push(n),n}async detachPaymentMethod(e,t){console.log("Mock: detachPaymentMethod",e,t);let r=this.customers.find(i=>i.id===e);if(!r)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n=r.paymentMethods.length;if(r.paymentMethods=r.paymentMethods.filter(i=>i.id!==t),r.paymentMethods.length===n)throw new u("CUSTOMER_NOT_FOUND",`Mock payment method ${t} not found for customer ${e}`)}async createSubscription(e){console.log("Mock: createSubscription",e);let t=this.customers.find(n=>n.id===e.customerId);if(!t)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e.customerId} not found`);let r={id:`mock_sub_${this.nextSubscriptionId++}`,customerId:e.customerId,status:"active",items:(e.items||(e.priceId?[{priceId:e.priceId,quantity:1}]:[])).map(n=>({id:`mock_sub_item_${Math.random().toString(36).substring(7)}`,priceId:n.priceId,quantity:n.quantity||1})),currentPeriodStart:new Date,currentPeriodEnd:new Date(Date.now()+720*60*60*1e3),cancelAtPeriodEnd:!1,created:new Date,updated:new Date};return this.subscriptions.push(r),t.subscriptions.push(r),r}async retrieveSubscription(e){console.log("Mock: retrieveSubscription",e);let t=this.subscriptions.find(r=>r.id===e);if(!t)throw new u("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);return t}async updateSubscription(e,t){console.log("Mock: updateSubscription",e,t);let r=this.subscriptions.find(n=>n.id===e);if(!r)throw new u("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);return t.cancelAtPeriodEnd!==void 0&&(r.cancelAtPeriodEnd=t.cancelAtPeriodEnd,r.status=t.cancelAtPeriodEnd?"canceled":"active"),t.items&&(r.items=t.items.map(n=>({id:`mock_sub_item_${Math.random().toString(36).substring(7)}`,priceId:n.priceId,quantity:n.quantity||1}))),r.updated=new Date,r}async cancelSubscription(e){console.log("Mock: cancelSubscription",e);let t=this.subscriptions.find(r=>r.id===e);if(!t)throw new u("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);t.status="canceled",t.cancelAtPeriodEnd=!0,t.updated=new Date}async reactivateSubscription(e){console.log("Mock: reactivateSubscription",e);let t=this.subscriptions.find(r=>r.id===e);if(!t)throw new u("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);t.status="active",t.cancelAtPeriodEnd=!1,t.updated=new Date}async listSubscriptions(e,t){console.log("Mock: listSubscriptions",e,t);let r=this.customers.find(i=>i.id===e);if(!r)throw new u("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n=r.subscriptions;return t&&t!=="all"&&(n=n.filter(i=>i.status===t)),n}};var z=class{static create(e){switch(e.provider){case"stripe":return new ye(e);case"paypal":throw new u("PROVIDER_NOT_CONFIGURED","PayPal provider is not yet available in this build");case"applepay":throw new u("PROVIDER_NOT_CONFIGURED","Apple Pay provider is not yet available in this build");case"mock":return new he(e);default:throw new u("CONFIGURATION_ERROR",`Unsupported payment provider: ${e.provider}`)}}static autodetect(){if(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY&&process.env.STRIPE_SECRET_KEY)return{provider:"stripe",publishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,environment:process.env.NODE_ENV==="production"?"production":"development",stripeConfig:{publishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY}};if(process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID&&process.env.PAYPAL_CLIENT_SECRET)return{provider:"paypal",publishableKey:process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID,environment:process.env.NODE_ENV==="production"?"production":"development",paypalConfig:{clientId:process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID,clientSecret:process.env.PAYPAL_CLIENT_SECRET,environment:process.env.NODE_ENV==="production"?"production":"sandbox",currency:process.env.PAYPAL_CURRENCY||"USD"}};if(process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_ID&&typeof window<"u"&&window.ApplePaySession)return{provider:"applepay",environment:process.env.NODE_ENV==="production"?"production":"development",applePayConfig:{merchantId:process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_ID,merchantName:process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_NAME||"Your Store",countryCode:process.env.NEXT_PUBLIC_APPLE_PAY_COUNTRY_CODE||"US",currencyCode:process.env.NEXT_PUBLIC_APPLE_PAY_CURRENCY_CODE||"USD",environment:process.env.NODE_ENV==="production"?"production":"sandbox"}};if(process.env.NODE_ENV!=="production"||process.env.VERCEL_ENV==="preview")return console.warn("No payment provider detected, defaulting to MockPaymentProvider for development/preview environment."),{provider:"mock",environment:"development"};throw new u("CONFIGURATION_ERROR","Could not auto-detect payment provider. Please provide explicit configuration.")}static getAvailableProviders(){let e=[];return process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY&&e.push("stripe"),process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID&&e.push("paypal"),typeof window<"u"&&window.ApplePaySession?.canMakePayments()&&e.push("applepay"),process.env.NODE_ENV!=="production"&&e.push("mock"),e}static createMultiple(e){return e.map(t=>this.create(t))}};var _e={customer:null,subscriptions:[],activeSubscription:null,loading:!1,error:null,initialized:!1,config:null,isLoading:!1,isError:!1},ke=(0,Ne.create)()((0,De.immer)((o,e)=>({..._e,get isLoading(){return e().loading},get isError(){return!!e().error},initialize:async t=>{o(r=>{r.loading=!0,r.error=null});try{let r;t?r=t:r=z.autodetect(),await z.create(r).initialize(),o(i=>{i.initialized=!0,i.loading=!1,i.config=r})}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to initialize payments provider.";n.error=new u("CONFIGURATION_ERROR",i),n.loading=!1}),r}},createCustomer:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).createCustomer(t);return o(i=>{i.customer=n,i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to create customer.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},retrieveCustomer:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).retrieveCustomer(t);return o(i=>{i.customer=n,i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to retrieve customer.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},createCheckoutSession:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).createCheckoutSession(t);return o(i=>{i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to create checkout session.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},retrieveCheckoutSession:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).retrieveCheckoutSession(t);return o(i=>{i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to retrieve checkout session.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},createSubscription:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).createSubscription(t);return await e().refreshSubscriptions(e().customer?.id||""),o(i=>{i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to create subscription.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},cancelSubscription:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");await z.create(e().config).cancelSubscription(t),await e().refreshSubscriptions(e().customer?.id||""),o(n=>{n.loading=!1})}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to cancel subscription.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},reactivateSubscription:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");await z.create(e().config).reactivateSubscription(t),await e().refreshSubscriptions(e().customer?.id||""),o(n=>{n.loading=!1})}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to reactivate subscription.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},updateSubscription:async(t,r)=>{o(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let i=await z.create(e().config).updateSubscription(t,r);return await e().refreshSubscriptions(e().customer?.id||""),o(d=>{d.loading=!1}),i}catch(n){throw o(i=>{let d=n instanceof Error?n.message:"Failed to update subscription.";i.error=new u("NETWORK_ERROR",d),i.loading=!1}),n}},listSubscriptions:async(t,r)=>{o(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let i=await z.create(e().config).listSubscriptions(t,r);return o(d=>{d.subscriptions=i,d.loading=!1}),i}catch(n){throw o(i=>{let d=n instanceof Error?n.message:"Failed to list subscriptions.";i.error=new u("NETWORK_ERROR",d),i.loading=!1}),n}},retrieveSubscription:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).retrieveSubscription(t);return o(i=>{i.loading=!1}),n}catch(r){throw o(n=>{let i=r instanceof Error?r.message:"Failed to retrieve subscription.";n.error=new u("NETWORK_ERROR",i),n.loading=!1}),r}},refreshCustomer:async t=>{o(r=>{r.loading=!0,r.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await z.create(e().config).retrieveCustomer(t);o(i=>{i.customer=n,i.loading=!1})}catch(r){o(n=>{let i=r instanceof Error?r.message:"Failed to refresh customer.";n.error=new u("NETWORK_ERROR",i),n.loading=!1})}},refreshSubscriptions:async(t,r)=>{o(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new u("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let i=await z.create(e().config).listSubscriptions(t,r),d=i.find(c=>c.status==="active"||c.status==="trialing")||null;o(c=>{c.subscriptions=i,c.activeSubscription=d,c.loading=!1})}catch(n){o(i=>{let d=n instanceof Error?n.message:"Failed to refresh subscriptions.";i.error=new u("NETWORK_ERROR",d),i.loading=!1})}},reset:()=>{o(t=>{Object.assign(t,_e)})}})));var Fe=require("react/jsx-runtime"),xe=(0,Z.createContext)(void 0),Ae=({children:o,config:e,onPaymentSuccess:t,onPaymentError:r})=>{let n=ke(),{initialize:i,initialized:d,loading:c,error:m,customer:b,subscriptions:P,activeSubscription:g}=n,x=(0,Z.useRef)(t),D=(0,Z.useRef)(r);(0,Z.useEffect)(()=>{x.current=t},[t]),(0,Z.useEffect)(()=>{D.current=r},[r]),(0,Z.useEffect)(()=>{!d&&!c&&!m&&i(e).catch(S=>{console.error("PaymentsProvider initialization failed:",S),D.current&&D.current(S)})},[d,c,m,e,i]);let s={config:n.config,initialized:d,loading:c,error:m,customer:b,subscriptions:P,activeSubscription:g,createCustomer:n.createCustomer,createCheckoutSession:n.createCheckoutSession,cancelSubscription:n.cancelSubscription,reactivateSubscription:n.reactivateSubscription,updateSubscription:n.updateSubscription,refreshCustomer:n.refreshCustomer,refreshSubscriptions:n.refreshSubscriptions,reset:n.reset};return(0,Fe.jsx)(xe.Provider,{value:s,children:o})},H=()=>{let o=(0,Z.useContext)(xe);if(o===void 0)throw new Error("usePaymentsContext must be used within a PaymentsProvider");return o};var Ue={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NZD:"NZ$"},Me="USD";var h={PROVIDER_NOT_CONFIGURED:"Payments provider is not properly configured",STRIPE_NOT_LOADED:"Stripe has not been loaded yet",INVALID_PRICE_ID:"Invalid price ID provided",INVALID_CUSTOMER_ID:"Invalid customer ID provided",CHECKOUT_FAILED:"Checkout session creation failed",PAYMENT_FAILED:"Payment processing failed",SUBSCRIPTION_NOT_FOUND:"Subscription not found",CUSTOMER_NOT_FOUND:"Customer not found"};var te=o=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o);var G=(o,e)=>{let t={customer:"cus_",subscription:"sub_",price:"price_",product:"prod_",payment_intent:"pi_"};return o.startsWith(t[e])};var le=require("react/jsx-runtime"),Pe=({priceId:o,customerId:e,customerEmail:t,children:r,style:n,textStyle:i,disabled:d=!1,metadata:c,trialPeriodDays:m,onSuccess:b,onError:P,onLoading:g})=>{let{initPaymentSheet:x,presentPaymentSheet:D}=(0,Be.useStripe)(),{initialized:s}=H(),[S,M]=(0,Ve.useState)(!1),k=R=>{P?.(R),Q.Alert.alert("Payment Error",R),console.error("Checkout error:",R)},q=async()=>{if(!s){k(h.PROVIDER_NOT_CONFIGURED);return}if(!G(o,"price")){k(h.INVALID_PRICE_ID);return}if(e&&!G(e,"customer")){k(h.INVALID_CUSTOMER_ID);return}M(!0),g?.(!0);try{let R=await fetch("/api/payments/create-subscription-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priceId:o,customerId:e,customerEmail:t,metadata:c,trialPeriodDays:m})});if(!R.ok){let l=await R.json().catch(()=>({error:"Network error"}));throw new Error(l.error||h.CHECKOUT_FAILED)}let{setupIntentClientSecret:a,customerId:p,customerEphemeralKeySecret:v}=await R.json();if(!a)throw new Error("No setup intent client secret returned from server");let{error:T}=await x({setupIntentClientSecret:a,customerId:p,customerEphemeralKeySecret:v,merchantDisplayName:"Your App Name",allowsDelayedPaymentMethods:!0});if(T)throw new Error(T.message||"Failed to initialize payment sheet");let{error:f}=await D();if(f){if(f.code!=="Canceled")throw new Error(f.message||h.PAYMENT_FAILED);return}b?.()}catch(R){let a=R instanceof Error?R.message:h.CHECKOUT_FAILED;k(a)}finally{M(!1),g?.(!1)}},O=S||d||!s;return(0,le.jsxs)(Q.TouchableOpacity,{style:[ue.button,n,O&&ue.disabled],onPress:q,disabled:O,activeOpacity:.8,children:[S?(0,le.jsx)(Q.ActivityIndicator,{color:"#ffffff",size:"small",style:ue.loader}):null,(0,le.jsx)(Q.Text,{style:[ue.buttonText,i,S&&ue.loadingText],children:S?"Processing...":r})]})},ue=Q.StyleSheet.create({button:{backgroundColor:"#007AFF",paddingHorizontal:16,paddingVertical:12,borderRadius:8,flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48},buttonText:{color:"#ffffff",fontSize:16,fontWeight:"600",textAlign:"center"},disabled:{opacity:.5},loader:{marginRight:8},loadingText:{marginLeft:8}});var F=require("react-native");var Ce=(o,e=Me,t={})=>{let{showSymbol:r=!0,showCents:n=!0,locale:i="en-US"}=t,d=e.toUpperCase(),c=["JPY","KRW","VND","CLP"].includes(d),m=c?o:o/100;if(r)try{return new Intl.NumberFormat(i,{style:"currency",currency:d,minimumFractionDigits:n&&!c?2:0,maximumFractionDigits:n&&!c?2:0}).format(m)}catch{let b=Ue[d]||d,P=n&&!c?m.toFixed(2):Math.round(m).toString();return`${b}${P}`}return n&&!c?m.toFixed(2):Math.round(m).toString()},Le=o=>{let e=Ce(o.price,o.currency),t=o.intervalCount&&o.intervalCount>1?`${o.intervalCount} ${o.interval}s`:o.interval;return`${e}/${t}`};var me=(o,e={})=>{let{format:t="medium",locale:r="en-US",timeZone:n}=e,i=typeof o=="string"||typeof o=="number"?new Date(o):o,d={timeZone:n};switch(t){case"short":d.dateStyle="short";break;case"medium":d.dateStyle="medium";break;case"long":d.dateStyle="long";break;case"full":d.dateStyle="full";break}try{return new Intl.DateTimeFormat(r,d).format(i)}catch{return i.toLocaleDateString()}};var ze=o=>o===0?"No trial":o===1?"1 day trial":o<7?`${o} days trial`:o===7?"1 week trial":o<30?`${Math.floor(o/7)} weeks trial`:o===30?"1 month trial":`${Math.floor(o/30)} months trial`;var V=require("react/jsx-runtime"),{width:Ke}=F.Dimensions.get("window"),$e=({plans:o,customerId:e,customerEmail:t,onCheckoutSuccess:r,onCheckoutError:n,showFeatures:i=!0,showTrialInfo:d=!0,layout:c="carousel",containerStyle:m})=>{if(!o||o.length===0)return(0,V.jsx)(F.View,{style:A.emptyContainer,children:(0,V.jsx)(F.Text,{style:A.emptyText,children:"No pricing plans available"})});let b=P=>(0,V.jsx)(lt,{plan:P,customerId:e,customerEmail:t,onCheckoutSuccess:()=>r?.(P),onCheckoutError:g=>n?.(P,g),showFeatures:i,showTrialInfo:d,style:c==="carousel"?A.carouselCard:A.listCard},P.id);return c==="carousel"?(0,V.jsx)(F.View,{style:[A.container,m],children:(0,V.jsx)(F.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:A.carouselContainer,snapToInterval:Ke*.8+16,decelerationRate:"fast",children:o.map(b)})}):(0,V.jsx)(F.ScrollView,{style:[A.container,m],children:(0,V.jsx)(F.View,{style:A.listContainer,children:o.map(b)})})},lt=({plan:o,customerId:e,customerEmail:t,onCheckoutSuccess:r,onCheckoutError:n,showFeatures:i=!0,showTrialInfo:d=!0,style:c})=>{let m=o.popular;return(0,V.jsxs)(F.View,{style:[A.card,m&&A.popularCard,c],children:[m&&(0,V.jsx)(F.View,{style:A.popularBadge,children:(0,V.jsx)(F.Text,{style:A.popularBadgeText,children:"Most Popular"})}),(0,V.jsxs)(F.View,{style:A.cardHeader,children:[(0,V.jsx)(F.Text,{style:A.planName,children:o.name}),o.description&&(0,V.jsx)(F.Text,{style:A.planDescription,children:o.description}),(0,V.jsx)(F.Text,{style:A.planPrice,children:Le(o)}),d&&o.trialPeriodDays&&o.trialPeriodDays>0&&(0,V.jsx)(F.Text,{style:A.trialInfo,children:ze(o.trialPeriodDays)})]}),i&&o.features&&o.features.length>0&&(0,V.jsx)(F.View,{style:A.featuresContainer,children:o.features.map((b,P)=>(0,V.jsxs)(F.View,{style:A.featureItem,children:[(0,V.jsx)(F.Text,{style:A.featureCheckmark,children:"\u2713"}),(0,V.jsx)(F.Text,{style:A.featureText,children:b})]},P))}),(0,V.jsx)(F.View,{style:A.buttonContainer,children:(0,V.jsx)(Pe,{priceId:o.stripePriceId,customerId:e,customerEmail:t,trialPeriodDays:o.trialPeriodDays,metadata:o.metadata,onSuccess:r,onError:n,style:[A.ctaButton,m?A.popularButton:A.regularButton],textStyle:[A.ctaButtonText,m?A.popularButtonText:A.regularButtonText],children:"Get Started"})})]})},A=F.StyleSheet.create({container:{flex:1},emptyContainer:{flex:1,justifyContent:"center",alignItems:"center",padding:20},emptyText:{fontSize:16,color:"#666",textAlign:"center"},carouselContainer:{paddingHorizontal:16},listContainer:{padding:16},carouselCard:{width:Ke*.8,marginRight:16},listCard:{marginBottom:16},card:{backgroundColor:"#ffffff",borderRadius:12,padding:20,shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:8,elevation:4,borderWidth:1,borderColor:"#e0e0e0"},popularCard:{borderColor:"#007AFF",borderWidth:2},popularBadge:{position:"absolute",top:-1,left:-1,right:-1,backgroundColor:"#007AFF",paddingVertical:8,borderTopLeftRadius:12,borderTopRightRadius:12,alignItems:"center"},popularBadgeText:{color:"#ffffff",fontSize:12,fontWeight:"600"},cardHeader:{alignItems:"center",marginBottom:20,marginTop:20},planName:{fontSize:20,fontWeight:"700",color:"#333",marginBottom:8,textAlign:"center"},planDescription:{fontSize:14,color:"#666",textAlign:"center",marginBottom:16,lineHeight:20},planPrice:{fontSize:28,fontWeight:"800",color:"#333",marginBottom:8,textAlign:"center"},trialInfo:{fontSize:12,color:"#22c55e",fontWeight:"600",textAlign:"center"},featuresContainer:{marginBottom:24},featureItem:{flexDirection:"row",alignItems:"flex-start",marginBottom:12},featureCheckmark:{color:"#22c55e",fontSize:16,fontWeight:"700",marginRight:12,marginTop:2},featureText:{flex:1,fontSize:14,color:"#555",lineHeight:20},buttonContainer:{marginTop:"auto"},ctaButton:{paddingVertical:16,borderRadius:8},ctaButtonText:{fontSize:16,fontWeight:"600"},popularButton:{backgroundColor:"#007AFF"},popularButtonText:{color:"#ffffff"},regularButton:{backgroundColor:"#f8f9fa",borderWidth:1,borderColor:"#e0e0e0"},regularButtonText:{color:"#333"}});var ie=require("react"),_=require("react-native"),be=require("@stripe/stripe-react-native");var B=require("react/jsx-runtime"),Ee=({clientSecret:o,customerId:e,customerEmail:t,amount:r,currency:n="usd",description:i,metadata:d,onSuccess:c,onError:m,onLoading:b,containerStyle:P,showBillingDetails:g=!0})=>{let{confirmPayment:x}=(0,be.useStripe)(),{initialized:D}=H(),[s,S]=(0,ie.useState)(!1),[M,k]=(0,ie.useState)(t||""),[q,O]=(0,ie.useState)(""),[R,a]=(0,ie.useState)(""),[p,v]=(0,ie.useState)(!1),T=l=>{m?.(l),_.Alert.alert("Payment Error",l),console.error("Payment error:",l)},f=async()=>{if(!D){T(h.PROVIDER_NOT_CONFIGURED);return}if(g&&M&&!te(M)){T("Please enter a valid email address");return}if(!p){T("Please complete your card information");return}let l=o;if(!l&&r)try{let E=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({amount:r,currency:n,customerId:e,description:i,metadata:d})});if(!E.ok)throw new Error("Failed to create payment intent");let{client_secret:W}=await E.json();l=W}catch{T("Failed to initialize payment");return}if(!l){T("Payment could not be initialized");return}S(!0),b?.(!0);try{let E=g?{email:M||void 0,name:q||void 0,phone:R||void 0}:void 0,{error:W,paymentIntent:pe}=await x(l,{paymentMethodType:"Card",paymentMethodData:{billingDetails:E}});if(W)throw new Error(W.message||h.PAYMENT_FAILED);if(pe?.status==="Succeeded")c?.(pe),_.Alert.alert("Success","Payment completed successfully!");else throw new Error("Payment was not completed")}catch(E){let W=E instanceof Error?E.message:h.PAYMENT_FAILED;T(W)}finally{S(!1),b?.(!1)}};return(0,B.jsx)(_.KeyboardAvoidingView,{behavior:_.Platform.OS==="ios"?"padding":"height",style:[K.container,P],children:(0,B.jsxs)(_.ScrollView,{showsVerticalScrollIndicator:!1,children:[g&&(0,B.jsxs)(_.View,{style:K.billingSection,children:[(0,B.jsx)(_.Text,{style:K.sectionTitle,children:"Billing Information"}),(0,B.jsxs)(_.View,{style:K.inputContainer,children:[(0,B.jsx)(_.Text,{style:K.inputLabel,children:"Email *"}),(0,B.jsx)(_.TextInput,{style:K.textInput,value:M,onChangeText:k,placeholder:"your@email.com",keyboardType:"email-address",autoCapitalize:"none",autoCorrect:!1})]}),(0,B.jsxs)(_.View,{style:K.inputContainer,children:[(0,B.jsx)(_.Text,{style:K.inputLabel,children:"Full Name"}),(0,B.jsx)(_.TextInput,{style:K.textInput,value:q,onChangeText:O,placeholder:"John Doe",autoCapitalize:"words"})]}),(0,B.jsxs)(_.View,{style:K.inputContainer,children:[(0,B.jsx)(_.Text,{style:K.inputLabel,children:"Phone"}),(0,B.jsx)(_.TextInput,{style:K.textInput,value:R,onChangeText:a,placeholder:"+1 (555) 123-4567",keyboardType:"phone-pad"})]})]}),(0,B.jsxs)(_.View,{style:K.cardSection,children:[(0,B.jsx)(_.Text,{style:K.sectionTitle,children:"Payment Information"}),(0,B.jsx)(_.View,{style:K.cardContainer,children:(0,B.jsx)(be.CardField,{postalCodeEnabled:!0,placeholders:{number:"4242 4242 4242 4242"},cardStyle:mt,style:K.cardFieldContainer,onCardChange:l=>{v(l.complete)}})})]}),(0,B.jsx)(_.TouchableOpacity,{style:[K.payButton,s&&K.payButtonDisabled],onPress:f,disabled:s||!p,activeOpacity:.8,children:s?(0,B.jsx)(_.ActivityIndicator,{color:"#ffffff",size:"small"}):(0,B.jsxs)(_.Text,{style:K.payButtonText,children:["Pay ",r?`$${(r/100).toFixed(2)}`:""]})})]})})},mt={backgroundColor:"#fafafa",textColor:"#333",fontSize:16,placeholderColor:"#999"},K=_.StyleSheet.create({container:{flex:1,padding:20,backgroundColor:"#ffffff"},billingSection:{marginBottom:24},cardSection:{marginBottom:32},sectionTitle:{fontSize:18,fontWeight:"600",color:"#333",marginBottom:16},inputContainer:{marginBottom:16},inputLabel:{fontSize:14,fontWeight:"500",color:"#555",marginBottom:8},textInput:{borderWidth:1,borderColor:"#ddd",borderRadius:8,paddingHorizontal:12,paddingVertical:12,fontSize:16,backgroundColor:"#fafafa"},cardContainer:{borderWidth:1,borderColor:"#ddd",borderRadius:8,backgroundColor:"#fafafa"},cardFieldContainer:{width:"100%",height:50},payButton:{backgroundColor:"#007AFF",paddingVertical:16,borderRadius:8,alignItems:"center",justifyContent:"center",minHeight:52},payButtonDisabled:{opacity:.5},payButtonText:{color:"#ffffff",fontSize:18,fontWeight:"600"}});var We=require("@stripe/stripe-react-native"),se=require("react-native");var Ge=require("react/jsx-runtime"),Ye=({customerId:o,amount:e,currency:t="usd",paymentIntentClientSecret:r,onSuccess:n,onError:i,children:d})=>{let{presentPaymentSheet:c,initPaymentSheet:m}=(0,We.useStripe)(),{initialized:b}=H(),P=async()=>{if(!b){i?.("Payment provider not initialized");return}try{if(r){let{error:x}=await m({merchantDisplayName:"Your App Name",paymentIntentClientSecret:r,defaultBillingDetails:{name:""},allowsDelayedPaymentMethods:!0});if(x)throw new Error(x.message)}let{error:g}=await c();if(g){if(g.code==="Canceled")return;throw new Error(g.message)}n?.({status:"succeeded"})}catch(g){let x=g instanceof Error?g.message:"Payment failed";i?.(x),se.Alert.alert("Payment Error",x)}};return(0,Ge.jsx)(se.View,{style:dt.container,children:d})},dt=se.StyleSheet.create({container:{flex:1}});var ge=require("react"),C=require("react-native");var w=require("react/jsx-runtime"),je=({subscription:o,onCancel:e,onReactivate:t,onUpdate:r,style:n})=>{let{activeSubscription:i,loading:d,error:c}=H(),[m,b]=(0,ge.useState)(null);(0,ge.useEffect)(()=>{b(o||i)},[o,i]);let P=()=>{m&&C.Alert.alert("Cancel Subscription","Are you sure you want to cancel your subscription? You will retain access until the end of your current billing period.",[{text:"Keep Subscription",style:"cancel"},{text:"Cancel",style:"destructive",onPress:()=>e?.(m.id)}])},g=()=>{m&&C.Alert.alert("Reactivate Subscription","Would you like to reactivate your subscription?",[{text:"No",style:"cancel"},{text:"Reactivate",onPress:()=>t?.(m.id)}])},x=M=>{switch(M){case"active":return"#10B981";case"trialing":return"#3B82F6";case"past_due":return"#F59E0B";case"canceled":return"#EF4444";default:return"#6B7280"}},D=M=>{switch(M){case"active":return"Active";case"trialing":return"Trial";case"past_due":return"Past Due";case"canceled":return"Canceled";default:return M}};if(d)return(0,w.jsx)(C.View,{style:[I.container,n],children:(0,w.jsx)(C.Text,{style:I.loadingText,children:"Loading subscription..."})});if(c)return(0,w.jsx)(C.View,{style:[I.container,n],children:(0,w.jsxs)(C.Text,{style:I.errorText,children:["Error: ",c.message]})});if(!m)return(0,w.jsx)(C.View,{style:[I.container,n],children:(0,w.jsx)(C.Text,{style:I.noSubscriptionText,children:"No active subscription"})});let s=m.status==="active"||m.status==="trialing",S=m.status==="canceled";return(0,w.jsxs)(C.ScrollView,{style:[I.container,n],children:[(0,w.jsxs)(C.View,{style:I.header,children:[(0,w.jsx)(C.Text,{style:I.title,children:"Subscription Details"}),(0,w.jsx)(C.View,{style:[I.statusBadge,{backgroundColor:x(m.status)}],children:(0,w.jsx)(C.Text,{style:I.statusText,children:D(m.status)})})]}),(0,w.jsxs)(C.View,{style:I.detailsContainer,children:[(0,w.jsxs)(C.View,{style:I.detailRow,children:[(0,w.jsx)(C.Text,{style:I.detailLabel,children:"Amount:"}),(0,w.jsx)(C.Text,{style:I.detailValue,children:Ce(m.amount||0,m.currency)})]}),(0,w.jsxs)(C.View,{style:I.detailRow,children:[(0,w.jsx)(C.Text,{style:I.detailLabel,children:"Billing Interval:"}),(0,w.jsx)(C.Text,{style:I.detailValue,children:m.interval})]}),(0,w.jsxs)(C.View,{style:I.detailRow,children:[(0,w.jsx)(C.Text,{style:I.detailLabel,children:"Current Period:"}),(0,w.jsxs)(C.Text,{style:I.detailValue,children:[me(m.currentPeriodStart)," -"," ",me(m.currentPeriodEnd)]})]}),m.trialEnd&&(0,w.jsxs)(C.View,{style:I.detailRow,children:[(0,w.jsx)(C.Text,{style:I.detailLabel,children:"Trial Ends:"}),(0,w.jsx)(C.Text,{style:I.detailValue,children:me(m.trialEnd)})]}),m.cancelAtPeriodEnd&&(0,w.jsx)(C.View,{style:I.warningContainer,children:(0,w.jsxs)(C.Text,{style:I.warningText,children:["Your subscription will cancel on"," ",me(m.currentPeriodEnd)]})})]}),(0,w.jsxs)(C.View,{style:I.actionsContainer,children:[s&&!m.cancelAtPeriodEnd&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(C.TouchableOpacity,{style:I.primaryButton,onPress:()=>r?.(m.id),children:(0,w.jsx)(C.Text,{style:I.primaryButtonText,children:"Update Plan"})}),(0,w.jsx)(C.TouchableOpacity,{style:I.dangerButton,onPress:P,children:(0,w.jsx)(C.Text,{style:I.dangerButtonText,children:"Cancel Subscription"})})]}),m.cancelAtPeriodEnd&&(0,w.jsx)(C.TouchableOpacity,{style:I.primaryButton,onPress:g,children:(0,w.jsx)(C.Text,{style:I.primaryButtonText,children:"Reactivate Subscription"})}),S&&(0,w.jsx)(C.TouchableOpacity,{style:I.primaryButton,onPress:()=>r?.(m.id),children:(0,w.jsx)(C.Text,{style:I.primaryButtonText,children:"Subscribe Again"})})]})]})},I=C.StyleSheet.create({container:{flex:1,backgroundColor:"#FFFFFF",padding:16},header:{flexDirection:"row",justifyContent:"space-between",alignItems:"center",marginBottom:24},title:{fontSize:24,fontWeight:"bold",color:"#1F2937"},statusBadge:{paddingHorizontal:12,paddingVertical:6,borderRadius:16},statusText:{color:"#FFFFFF",fontSize:12,fontWeight:"600"},detailsContainer:{backgroundColor:"#F9FAFB",borderRadius:8,padding:16,marginBottom:24},detailRow:{flexDirection:"row",justifyContent:"space-between",alignItems:"center",paddingVertical:8,borderBottomWidth:1,borderBottomColor:"#E5E7EB"},detailLabel:{fontSize:14,color:"#6B7280",fontWeight:"500"},detailValue:{fontSize:14,color:"#1F2937",fontWeight:"600"},warningContainer:{backgroundColor:"#FEF3C7",borderRadius:8,padding:12,marginTop:16},warningText:{color:"#92400E",fontSize:14,textAlign:"center"},actionsContainer:{gap:12},primaryButton:{backgroundColor:"#3B82F6",borderRadius:8,padding:16,alignItems:"center"},primaryButtonText:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},dangerButton:{backgroundColor:"#EF4444",borderRadius:8,padding:16,alignItems:"center"},dangerButtonText:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},loadingText:{textAlign:"center",color:"#6B7280",fontSize:16},errorText:{textAlign:"center",color:"#EF4444",fontSize:16},noSubscriptionText:{textAlign:"center",color:"#6B7280",fontSize:16}});var we=require("react"),L=require("react-native"),qe=require("@stripe/stripe-react-native"),J=require("react/jsx-runtime"),Re=null;try{Re=require("react-native-touch-id")}catch{}var pt={title:"Authentication Required",imageColor:"#e00606",sensorDescription:"Touch sensor",sensorErrorDescription:"Failed",cancelText:"Cancel",fallbackLabel:"Show Passcode",unifiedErrors:!1,passcodeFallback:!1},He=({amount:o,currency:e="USD",paymentMethodId:t,clientSecret:r,onSuccess:n,onError:i,onCancel:d,title:c="Authorize Payment",subtitle:m,style:b})=>{let[P,g]=(0,we.useState)(!1),[x,D]=(0,we.useState)(!1),{confirmPayment:s}=(0,qe.useStripe)(),S=async()=>{try{return await Re.isSupported()!==!1}catch{return!1}},M=async()=>{try{return await Re.authenticate("Authenticate to complete your payment",pt),!0}catch(a){return a.name==="UserCancel"||a.name==="UserFallback"?d?.():i?.(`Authentication failed: ${a.message}`),!1}},k=async()=>{if(!r){i?.("Payment configuration is missing");return}D(!0);try{let{error:a,paymentIntent:p}=await s(r,{paymentMethodType:"Card"});if(a)throw new Error(a.message);n?.(p)}catch(a){let p=a instanceof Error?a.message:"Payment failed";i?.(p)}finally{D(!1)}},q=async()=>{g(!0);try{if(!await S()){L.Alert.alert("Biometric Authentication Not Available","Your device does not support biometric authentication. Please use an alternative payment method.",[{text:"OK",onPress:d}]);return}await M()&&await k()}catch(a){let p=a instanceof Error?a.message:"Authentication failed";i?.(p)}finally{g(!1)}},O=(a,p)=>new Intl.NumberFormat("en-US",{style:"currency",currency:p.toUpperCase()}).format(a/100),R=()=>L.Platform.OS==="ios"?"\u{1F446}":"\u{1F512}";return(0,J.jsx)(L.View,{style:[X.container,b],children:(0,J.jsxs)(L.View,{style:X.content,children:[(0,J.jsx)(L.Text,{style:X.title,children:c}),m&&(0,J.jsx)(L.Text,{style:X.subtitle,children:m}),(0,J.jsxs)(L.View,{style:X.amountContainer,children:[(0,J.jsx)(L.Text,{style:X.amountLabel,children:"Amount"}),(0,J.jsx)(L.Text,{style:X.amount,children:O(o,e)})]}),(0,J.jsxs)(L.TouchableOpacity,{style:[X.payButton,(P||x)&&X.payButtonDisabled],onPress:q,disabled:P||x,children:[(0,J.jsx)(L.Text,{style:X.biometricIcon,children:R()}),(0,J.jsx)(L.Text,{style:X.payButtonText,children:P?"Authenticating...":x?"Processing...":`Pay with ${L.Platform.OS==="ios"?"Touch ID":"Biometrics"}`})]}),(0,J.jsx)(L.Text,{style:X.securityNote,children:"Your payment information is secured with biometric authentication"})]})})},X=L.StyleSheet.create({container:{backgroundColor:"#FFFFFF",borderRadius:12,padding:20,margin:16,shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:3.84,elevation:5},content:{alignItems:"center"},title:{fontSize:20,fontWeight:"bold",color:"#1F2937",marginBottom:8,textAlign:"center"},subtitle:{fontSize:14,color:"#6B7280",marginBottom:20,textAlign:"center"},amountContainer:{backgroundColor:"#F9FAFB",borderRadius:8,padding:16,marginBottom:24,minWidth:200,alignItems:"center"},amountLabel:{fontSize:12,color:"#6B7280",marginBottom:4},amount:{fontSize:24,fontWeight:"bold",color:"#1F2937"},payButton:{backgroundColor:"#3B82F6",borderRadius:8,paddingVertical:16,paddingHorizontal:32,flexDirection:"row",alignItems:"center",marginBottom:12},payButtonDisabled:{backgroundColor:"#9CA3AF"},biometricIcon:{fontSize:20,marginRight:8},payButtonText:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},securityNote:{fontSize:12,color:"#6B7280",textAlign:"center",marginTop:8}});var Je=require("@stripe/stripe-react-native");var re=require("react-native"),oe=require("react/jsx-runtime"),Xe=({children:o,merchantIdentifier:e,urlScheme:t,publishableKey:r,setReturnUrlSchemeOnAndroid:n=!1})=>{let{config:i,initialized:d}=H();if(!d)return i?.environment==="development"?(0,oe.jsxs)(re.View,{style:Se.errorContainer,children:[(0,oe.jsx)(re.Text,{style:Se.errorTitle,children:"Payments Provider Error"}),(0,oe.jsx)(re.Text,{style:Se.errorMessage,children:h.PROVIDER_NOT_CONFIGURED}),(0,oe.jsx)(re.Text,{style:Se.errorSubtext,children:"Please check your PaymentsProvider configuration."})]}):null;let c=r||i?.publishableKey;return c?(0,oe.jsx)(Je.StripeProvider,{publishableKey:c,merchantIdentifier:e,urlScheme:t,setReturnUrlSchemeOnAndroid:n,children:o}):null},Se=re.StyleSheet.create({errorContainer:{padding:20,backgroundColor:"#fee",borderColor:"#fcc",borderWidth:1,borderRadius:4,margin:10},errorTitle:{fontWeight:"bold",fontSize:16,color:"#c53030",marginBottom:8},errorMessage:{fontSize:14,color:"#c53030",marginBottom:4},errorSubtext:{fontSize:12,color:"#a0a0a0"}});var U=require("react");var Ze=()=>{let[o,e]=(0,U.useState)(null),[t,r]=(0,U.useState)(null),[n,i]=(0,U.useState)(!1),[d,c]=(0,U.useState)(!1),[m,b]=(0,U.useState)(null),[P,g]=(0,U.useState)(null),[x,D]=(0,U.useState)([]),s=(0,U.useCallback)(N=>{b(N),console.error("Payments error:",N)},[]),S=(0,U.useCallback)(async(N,y)=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let Y=await t.listSubscriptions(N,y);D(Y)}catch(Y){throw s(Y),Y}finally{c(!1)}},[t,s]),M=(0,U.useCallback)(async N=>{c(!0),b(null);try{let y=N||z.autodetect(),Y=z.create(y);e(y),r(Y),i(!0)}catch(y){s(y)}finally{c(!1)}},[s]),k=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.retrieveCustomer(N);return g(y),y}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),q=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.createCustomer(N);return g(y),y}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),O=(0,U.useCallback)(async N=>{if(!t||!P)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.createSubscription({customerId:P.id,items:[{priceId:N.priceId,quantity:N.quantity}]});return await S(P.id),y}catch(y){throw s(y),y}finally{c(!1)}},[t,P,s,S]),R=(0,U.useCallback)(async(N,y)=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let Y=await t.listSubscriptions(N,y);return D(Y),Y}catch(Y){throw s(Y),Y}finally{c(!1)}},[t,s]),a=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.retrieveSubscription(N);return P?.id&&await S(P.id),y}catch(y){throw s(y),y}finally{c(!1)}},[t,P,s,S]),p=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{return await t.createCheckoutSession(N)}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),v=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{return await t.retrieveCheckoutSession(N)}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),T=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{await t.cancelSubscription(N),P?.id&&await S(P.id)}catch(y){throw s(y),y}finally{c(!1)}},[t,P,s,S]),f=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{await t.reactivateSubscription(N),P?.id&&await S(P.id)}catch(y){throw s(y),y}finally{c(!1)}},[t,P,s,S]),l=(0,U.useCallback)(async(N,y)=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let Y=await t.updateSubscription(N,y);return P?.id&&await S(P.id),Y}catch(Y){throw s(Y),Y}finally{c(!1)}},[t,P,s,S]),E=(0,U.useCallback)(async N=>{if(!t)throw new u("PROVIDER_NOT_CONFIGURED",h.PROVIDER_NOT_CONFIGURED);c(!0),b(null);try{let y=await t.retrieveCustomer(N);g(y)}catch(y){throw s(y),y}finally{c(!1)}},[t,s]),W=(0,U.useCallback)(()=>{e(null),r(null),i(!1),c(!1),b(null),g(null),D([])},[]),pe=x.find(N=>N.status==="active"||N.status==="trialing")||null;return(0,U.useEffect)(()=>{},[]),{config:o,provider:t,initialized:n,loading:d,error:m,isLoading:d,isError:!!m,customer:P,subscriptions:x,activeSubscription:pe,initialize:M,createCustomer:q,retrieveCustomer:k,createCheckoutSession:p,retrieveCheckoutSession:v,createSubscription:O,cancelSubscription:T,reactivateSubscription:f,listSubscriptions:R,retrieveSubscription:a,updateSubscription:l,refreshCustomer:E,refreshSubscriptions:S,reset:W}};var j=require("react"),ae=require("react-native");var Qe=(o={})=>{let{customerId:e,subscriptionId:t,autoFetch:r=!0,onError:n,showErrorAlert:i=!0}=o,[d,c]=(0,j.useState)(null),[m,b]=(0,j.useState)([]),[P,g]=(0,j.useState)(!1),[x,D]=(0,j.useState)(null),s=(0,j.useCallback)(a=>{D(a),n?.(a),i&&ae.Alert.alert("Subscription Error",a),console.error("Subscription error:",a)},[n,i]),S=(0,j.useCallback)(async a=>{if(!G(a,"subscription"))return s("Invalid subscription ID"),null;try{let p=await fetch(`/api/payments/subscription/${a}`);if(!p.ok){let T=await p.json().catch(()=>({error:"Network error"}));throw new Error(T.error||h.SUBSCRIPTION_NOT_FOUND)}return await p.json()}catch(p){let v=p instanceof Error?p.message:h.SUBSCRIPTION_NOT_FOUND;return s(v),null}},[s]),M=(0,j.useCallback)(async a=>{if(!G(a,"customer"))return s("Invalid customer ID"),[];try{let p=await fetch(`/api/payments/customer/${a}/subscriptions`);if(!p.ok){let T=await p.json().catch(()=>({error:"Network error"}));throw new Error(T.error||h.CUSTOMER_NOT_FOUND)}return(await p.json()).subscriptions||[]}catch(p){let v=p instanceof Error?p.message:h.CUSTOMER_NOT_FOUND;return s(v),[]}},[s]),k=(0,j.useCallback)(async()=>{if(!e&&!t){s("Either customerId or subscriptionId is required");return}g(!0),D(null);try{if(t){let a=await S(t);c(a)}if(e){let a=await M(e);if(b(a),!t&&a.length>0){let p=a.find(v=>v.status==="active")||a[0];c(p)}}}finally{g(!1)}},[e,t,S,M,s]),q=(0,j.useCallback)(async a=>{let p=a||t;return p?G(p,"subscription")?new Promise(v=>{ae.Alert.alert("Cancel Subscription","Are you sure you want to cancel your subscription? It will remain active until the end of your current billing period.",[{text:"Keep Subscription",style:"cancel",onPress:()=>v(!1)},{text:"Cancel Subscription",style:"destructive",onPress:async()=>{try{let T=await fetch(`/api/payments/subscription/${p}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!T.ok){let f=await T.json().catch(()=>({error:"Network error"}));throw new Error(f.error||"Failed to cancel subscription")}await k(),ae.Alert.alert("Success","Your subscription has been cancelled and will end at the end of your current billing period."),v(!0)}catch(T){let f=T instanceof Error?T.message:"Failed to cancel subscription";s(f),v(!1)}}}])}):(s("Invalid subscription ID"),!1):(s("Subscription ID is required to cancel"),!1)},[t,k,s]),O=(0,j.useCallback)(async a=>{let p=a||t;if(!p)return s("Subscription ID is required to reactivate"),!1;if(!G(p,"subscription"))return s("Invalid subscription ID"),!1;try{let v=await fetch(`/api/payments/subscription/${p}/reactivate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!v.ok){let T=await v.json().catch(()=>({error:"Network error"}));throw new Error(T.error||"Failed to reactivate subscription")}return await k(),ae.Alert.alert("Success","Your subscription has been reactivated!"),!0}catch(v){let T=v instanceof Error?v.message:"Failed to reactivate subscription";return s(T),!1}},[t,k,s]),R=(0,j.useCallback)(async(a,p)=>{if(!G(a,"subscription"))return s("Invalid subscription ID"),!1;try{let v=await fetch(`/api/payments/subscription/${a}/payment-method`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethodId:p})});if(!v.ok){let T=await v.json().catch(()=>({error:"Network error"}));throw new Error(T.error||"Failed to update payment method")}return await k(),ae.Alert.alert("Success","Payment method updated successfully!"),!0}catch(v){let T=v instanceof Error?v.message:"Failed to update payment method";return s(T),!1}},[k,s]);return(0,j.useEffect)(()=>{r&&(e||t)&&k()},[r,e,t,k]),{subscription:d,subscriptions:m,loading:P,error:x,isLoading:P,isError:!!x,refetch:k,cancel:q,reactivate:O,updatePaymentMethod:R}};var ee=require("react"),Ie=require("react-native"),et=require("@stripe/stripe-react-native");var Te=(o={})=>{let{onSuccess:e,onError:t,onLoading:r,showErrorAlert:n=!0,showSuccessAlert:i=!0}=o,{initPaymentSheet:d,presentPaymentSheet:c,confirmPayment:m}=(0,et.useStripe)(),{initialized:b}=H(),[P,g]=(0,ee.useState)(!1),[x,D]=(0,ee.useState)(null),s=(0,ee.useCallback)(O=>{D(O),t?.(O),n&&Ie.Alert.alert("Payment Error",O),console.error("Checkout error:",O)},[t,n]),S=(0,ee.useCallback)(O=>{e?.(O),i&&Ie.Alert.alert("Success","Payment completed successfully!")},[e,i]),M=(0,ee.useCallback)(async O=>{if(!b)return s(h.PROVIDER_NOT_CONFIGURED),!1;if(!G(O.priceId,"price"))return s(h.INVALID_PRICE_ID),!1;if(O.customerId&&!G(O.customerId,"customer"))return s(h.INVALID_CUSTOMER_ID),!1;if(O.customerEmail&&!te(O.customerEmail))return s("Invalid customer email"),!1;g(!0),D(null),r?.(!0);try{let R=await fetch("/api/payments/create-subscription-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!R.ok){let l=await R.json().catch(()=>({error:"Network error"}));throw new Error(l.error||"Failed to create subscription setup")}let{setupIntentClientSecret:a,customerId:p,customerEphemeralKeySecret:v}=await R.json();if(!a)throw new Error("No setup intent client secret returned from server");let{error:T}=await d({setupIntentClientSecret:a,customerId:p,customerEphemeralKeySecret:v,merchantDisplayName:"Your App Name",allowsDelayedPaymentMethods:!0});if(T)throw new Error(T.message||"Failed to initialize payment sheet");let{error:f}=await c();if(f){if(f.code==="Canceled")return!1;throw new Error(f.message||h.PAYMENT_FAILED)}return S({type:"subscription",customerId:p}),!0}catch(R){let a=R instanceof Error?R.message:"Failed to create subscription";return s(a),!1}finally{g(!1),r?.(!1)}},[b,d,c,s,S,r]),k=(0,ee.useCallback)(async O=>{if(!b)return s(h.PROVIDER_NOT_CONFIGURED),null;if(O.amount<=0)return s("Amount must be greater than 0"),null;if(O.customerId&&!G(O.customerId,"customer"))return s(h.INVALID_CUSTOMER_ID),null;g(!0),D(null),r?.(!0);try{let R=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!R.ok){let p=await R.json().catch(()=>({error:"Network error"}));throw new Error(p.error||"Failed to create payment intent")}let{client_secret:a}=await R.json();if(!a)throw new Error("No client secret returned from server");return a}catch(R){let a=R instanceof Error?R.message:"Failed to create payment intent";return s(a),null}finally{g(!1),r?.(!1)}},[b,s,r]),q=(0,ee.useCallback)(async(O,R)=>{if(!b)return s(h.PROVIDER_NOT_CONFIGURED),!1;if(R?.email&&!te(R.email))return s("Invalid email address"),!1;g(!0),D(null),r?.(!0);try{let{error:a,paymentIntent:p}=await m(O,{paymentMethodType:"Card",paymentMethodData:{billingDetails:R}});if(a)throw new Error(a.message||h.PAYMENT_FAILED);if(p?.status==="Succeeded")return S({type:"payment",paymentIntent:p}),!0;throw new Error("Payment was not completed")}catch(a){let p=a instanceof Error?a.message:h.PAYMENT_FAILED;return s(p),!1}finally{g(!1),r?.(!1)}},[b,m,s,S,r]);return{loading:P,error:x,isLoading:P,isError:!!x,createSubscription:M,createPaymentIntent:k,processPayment:q}};var $=require("react"),de=require("react-native");var tt=(o={})=>{let{customerId:e,autoFetch:t=!0,onError:r,showErrorAlert:n=!0,showSuccessAlert:i=!0}=o,[d,c]=(0,$.useState)(null),[m,b]=(0,$.useState)([]),[P,g]=(0,$.useState)(!1),[x,D]=(0,$.useState)(null),s=(0,$.useCallback)(f=>{D(f),r?.(f),n&&de.Alert.alert("Customer Error",f),console.error("Customer error:",f)},[r,n]),S=(0,$.useCallback)(f=>{i&&de.Alert.alert("Success",f)},[i]),M=(0,$.useCallback)(async f=>{if(!G(f,"customer"))return s("Invalid customer ID"),null;try{let l=await fetch(`/api/payments/customer/${f}`);if(!l.ok){let W=await l.json().catch(()=>({error:"Network error"}));throw new Error(W.error||h.CUSTOMER_NOT_FOUND)}return await l.json()}catch(l){let E=l instanceof Error?l.message:h.CUSTOMER_NOT_FOUND;return s(E),null}},[s]),k=(0,$.useCallback)(async()=>{if(!e){s("Customer ID is required");return}g(!0),D(null);try{let f=await M(e);c(f)}finally{g(!1)}},[e,M,s]),q=(0,$.useCallback)(async f=>{if(!te(f.email))return s("Invalid email address"),null;g(!0),D(null);try{let l=await fetch("/api/payments/customer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!l.ok){let W=await l.json().catch(()=>({error:"Network error"}));throw new Error(W.error||"Failed to create customer")}let E=await l.json();return c(E),S("Customer created successfully!"),E}catch(l){let E=l instanceof Error?l.message:"Failed to create customer";return s(E),null}finally{g(!1)}},[s,S]),O=(0,$.useCallback)(async f=>{if(!e)return s("Customer ID is required"),!1;if(f.email&&!te(f.email))return s("Invalid email address"),!1;g(!0),D(null);try{let l=await fetch(`/api/payments/customer/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!l.ok){let E=await l.json().catch(()=>({error:"Network error"}));throw new Error(E.error||"Failed to update customer")}return await k(),S("Customer updated successfully!"),!0}catch(l){let E=l instanceof Error?l.message:"Failed to update customer";return s(E),!1}finally{g(!1)}},[e,k,s,S]),R=(0,$.useCallback)(async()=>e?new Promise(f=>{de.Alert.alert("Delete Customer","Are you sure you want to delete this customer? This action cannot be undone.",[{text:"Cancel",style:"cancel",onPress:()=>f(!1)},{text:"Delete",style:"destructive",onPress:async()=>{g(!0),D(null);try{let l=await fetch(`/api/payments/customer/${e}`,{method:"DELETE"});if(!l.ok){let E=await l.json().catch(()=>({error:"Network error"}));throw new Error(E.error||"Failed to delete customer")}c(null),b([]),S("Customer deleted successfully!"),f(!0)}catch(l){let E=l instanceof Error?l.message:"Failed to delete customer";s(E),f(!1)}finally{g(!1)}}}])}):(s("Customer ID is required"),!1),[e,s,S]),a=(0,$.useCallback)(async()=>{if(!e)return s("Customer ID is required"),[];try{let f=await fetch(`/api/payments/customer/${e}/payment-methods`);if(!f.ok){let W=await f.json().catch(()=>({error:"Network error"}));throw new Error(W.error||"Failed to fetch payment methods")}let E=(await f.json()).paymentMethods||[];return b(E),E}catch(f){let l=f instanceof Error?f.message:"Failed to fetch payment methods";return s(l),[]}},[e,s]),p=(0,$.useCallback)(async f=>{if(!e)return s("Customer ID is required"),!1;try{let l=await fetch(`/api/payments/customer/${e}/payment-methods`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethodId:f})});if(!l.ok){let E=await l.json().catch(()=>({error:"Network error"}));throw new Error(E.error||"Failed to add payment method")}return await a(),S("Payment method added successfully!"),!0}catch(l){let E=l instanceof Error?l.message:"Failed to add payment method";return s(E),!1}},[e,a,s,S]),v=(0,$.useCallback)(async f=>e?new Promise(l=>{de.Alert.alert("Remove Payment Method","Are you sure you want to remove this payment method?",[{text:"Cancel",style:"cancel",onPress:()=>l(!1)},{text:"Remove",style:"destructive",onPress:async()=>{try{let E=await fetch(`/api/payments/customer/${e}/payment-methods/${f}`,{method:"DELETE"});if(!E.ok){let W=await E.json().catch(()=>({error:"Network error"}));throw new Error(W.error||"Failed to remove payment method")}await a(),S("Payment method removed successfully!"),l(!0)}catch(E){let W=E instanceof Error?E.message:"Failed to remove payment method";s(W),l(!1)}}}])}):(s("Customer ID is required"),!1),[e,a,s,S]),T=(0,$.useCallback)(async f=>{if(!e)return s("Customer ID is required"),!1;try{let l=await fetch(`/api/payments/customer/${e}/default-payment-method`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethodId:f})});if(!l.ok){let E=await l.json().catch(()=>({error:"Network error"}));throw new Error(E.error||"Failed to set default payment method")}return await Promise.all([k(),a()]),S("Default payment method updated successfully!"),!0}catch(l){let E=l instanceof Error?l.message:"Failed to set default payment method";return s(E),!1}},[e,k,a,s,S]);return(0,$.useEffect)(()=>{t&&e&&(k(),a())},[t,e,k,a]),{customer:d,paymentMethods:m,loading:P,error:x,isLoading:P,isError:!!x,refetch:k,createCustomer:q,updateCustomer:O,deleteCustomer:R,fetchPaymentMethods:a,addPaymentMethod:p,removePaymentMethod:v,setDefaultPaymentMethod:T}};var ft=async o=>{try{let e=await fetch("/api/payments/create-subscription-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!e.ok)return{error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to create subscription setup"};let t=await e.json();return{setupIntentClientSecret:t.setupIntentClientSecret,customerId:t.customerId,customerEphemeralKeySecret:t.customerEphemeralKeySecret}}catch(e){return{error:e instanceof Error?e.message:"Failed to create subscription setup"}}},yt=async o=>{try{let e=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return e.ok?{clientSecret:(await e.json()).client_secret}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to create payment intent"}}catch(e){return{error:e instanceof Error?e.message:"Failed to create payment intent"}}},ht=o=>{let e=[];return o.publishableKey||e.push("publishableKey is required"),o.provider||e.push("provider is required"),o.provider!=="stripe"&&e.push("Only stripe provider is currently supported"),o.environment||e.push("environment is required"),o.environment&&!["development","production"].includes(o.environment)&&e.push('environment must be either "development" or "production"'),o.publishableKey&&!o.publishableKey.startsWith("pk_")&&e.push('publishableKey must start with "pk_"'),{isValid:e.length===0,errors:e}},Pt=o=>{if(typeof o=="string")return o;if(typeof o=="object"&&o!==null){if("message"in o&&typeof o.message=="string")return o.message;if("code"in o&&typeof o.code=="string"){let e=o.code;return{Canceled:"Payment was cancelled",Failed:"Payment failed",card_declined:"Your card was declined.",expired_card:"Your card has expired.",incorrect_cvc:"Your card's security code is incorrect.",processing_error:"An error occurred while processing your card.",incorrect_number:"Your card number is incorrect."}[e]||`Payment failed: ${e}`}}return"An unexpected error occurred."},bt=async o=>{try{let e=await fetch("/api/payments/customer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return e.ok?{customer:await e.json()}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to create customer"}}catch(e){return{error:e instanceof Error?e.message:"Failed to create customer"}}},gt=async o=>{try{let e=await fetch(`/api/payments/subscription/${o}`);return e.ok?{subscription:await e.json()}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||h.SUBSCRIPTION_NOT_FOUND}}catch(e){return{error:e instanceof Error?e.message:h.SUBSCRIPTION_NOT_FOUND}}},St=async o=>{try{let e=await fetch(`/api/payments/customer/${o}/subscriptions`);return e.ok?{subscriptions:(await e.json()).subscriptions||[]}:{error:(await e.json().catch(()=>({error:"Network error"}))).error||h.CUSTOMER_NOT_FOUND}}catch(e){return{error:e instanceof Error?e.message:h.CUSTOMER_NOT_FOUND}}},Ct=async o=>{try{let e=await fetch(`/api/payments/subscription/${o}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0}:{success:!1,error:(await e.json().catch(()=>({error:"Network error"}))).error||"Failed to cancel subscription"}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to cancel subscription"}}};0&&(module.exports={CheckoutButton,CheckoutForm,MobilePaymentSheet,NativeSubscriptionView,PaymentForm,PaymentsProvider,PricingTable,StripeProvider,TouchIDPayment,cancelSubscription,createCustomer,createPaymentIntent,createSubscriptionSetup,fetchCustomerSubscriptions,fetchSubscription,formatStripeError,useCheckout,useCustomer,usePayments,usePaymentsContext,useStripe,useSubscription,validatePaymentsConfig});
|
|
3
3
|
//# sourceMappingURL=native.js.map
|