@digilogiclabs/saas-factory-payments 1.1.0 → 1.2.2

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.
@@ -0,0 +1,60 @@
1
+ import React from 'react';
2
+ import { e as PricingPlan } from './config-x4PgwjGU.js';
3
+ import { PaymentIntent } from '@stripe/stripe-js';
4
+
5
+ interface PricingTableProps {
6
+ plans: PricingPlan[];
7
+ customerId?: string;
8
+ customerEmail?: string;
9
+ successUrl?: string;
10
+ cancelUrl?: string;
11
+ className?: string;
12
+ onCheckoutSuccess?: (plan: PricingPlan) => void;
13
+ onCheckoutError?: (plan: PricingPlan, error: string) => void;
14
+ showFeatures?: boolean;
15
+ showTrialInfo?: boolean;
16
+ layout?: 'grid' | 'list';
17
+ maxColumns?: number;
18
+ }
19
+ declare const PricingTable: React.FC<PricingTableProps>;
20
+
21
+ interface PaymentFormProps {
22
+ clientSecret?: string;
23
+ customerId?: string;
24
+ customerEmail?: string;
25
+ amount?: number;
26
+ currency?: string;
27
+ description?: string;
28
+ metadata?: Record<string, string>;
29
+ onSuccess?: (paymentIntent: PaymentIntent) => void;
30
+ onError?: (error: string) => void;
31
+ onLoading?: (loading: boolean) => void;
32
+ className?: string;
33
+ showBillingDetails?: boolean;
34
+ elementType?: 'card' | 'payment';
35
+ }
36
+ declare const PaymentForm: React.FC<PaymentFormProps>;
37
+
38
+ type SubscriptionStatus = 'active' | 'canceled' | 'past_due' | 'unpaid' | 'incomplete';
39
+ interface Subscription {
40
+ id: string;
41
+ planId: string;
42
+ planName: string;
43
+ status: SubscriptionStatus;
44
+ currentPeriodStart: Date;
45
+ currentPeriodEnd: Date;
46
+ cancelAtPeriodEnd: boolean;
47
+ amount: number;
48
+ currency: string;
49
+ interval: 'month' | 'year';
50
+ }
51
+ type SubscriptionAction = 'upgrade' | 'downgrade' | 'pause' | 'resume';
52
+ interface SubscriptionManagerProps {
53
+ subscription: Subscription;
54
+ onSubscriptionChange: (action: SubscriptionAction) => void;
55
+ onCancel: () => void;
56
+ className?: string;
57
+ }
58
+ declare const SubscriptionManager: React.FC<SubscriptionManagerProps>;
59
+
60
+ export { PaymentForm as P, SubscriptionManager as S, PricingTable as a, type PaymentFormProps as b, type SubscriptionManagerProps as c, type Subscription as d, type SubscriptionAction as e };
@@ -0,0 +1,60 @@
1
+ import React from 'react';
2
+ import { e as PricingPlan } from './config-x4PgwjGU.mjs';
3
+ import { PaymentIntent } from '@stripe/stripe-js';
4
+
5
+ interface PricingTableProps {
6
+ plans: PricingPlan[];
7
+ customerId?: string;
8
+ customerEmail?: string;
9
+ successUrl?: string;
10
+ cancelUrl?: string;
11
+ className?: string;
12
+ onCheckoutSuccess?: (plan: PricingPlan) => void;
13
+ onCheckoutError?: (plan: PricingPlan, error: string) => void;
14
+ showFeatures?: boolean;
15
+ showTrialInfo?: boolean;
16
+ layout?: 'grid' | 'list';
17
+ maxColumns?: number;
18
+ }
19
+ declare const PricingTable: React.FC<PricingTableProps>;
20
+
21
+ interface PaymentFormProps {
22
+ clientSecret?: string;
23
+ customerId?: string;
24
+ customerEmail?: string;
25
+ amount?: number;
26
+ currency?: string;
27
+ description?: string;
28
+ metadata?: Record<string, string>;
29
+ onSuccess?: (paymentIntent: PaymentIntent) => void;
30
+ onError?: (error: string) => void;
31
+ onLoading?: (loading: boolean) => void;
32
+ className?: string;
33
+ showBillingDetails?: boolean;
34
+ elementType?: 'card' | 'payment';
35
+ }
36
+ declare const PaymentForm: React.FC<PaymentFormProps>;
37
+
38
+ type SubscriptionStatus = 'active' | 'canceled' | 'past_due' | 'unpaid' | 'incomplete';
39
+ interface Subscription {
40
+ id: string;
41
+ planId: string;
42
+ planName: string;
43
+ status: SubscriptionStatus;
44
+ currentPeriodStart: Date;
45
+ currentPeriodEnd: Date;
46
+ cancelAtPeriodEnd: boolean;
47
+ amount: number;
48
+ currency: string;
49
+ interval: 'month' | 'year';
50
+ }
51
+ type SubscriptionAction = 'upgrade' | 'downgrade' | 'pause' | 'resume';
52
+ interface SubscriptionManagerProps {
53
+ subscription: Subscription;
54
+ onSubscriptionChange: (action: SubscriptionAction) => void;
55
+ onCancel: () => void;
56
+ className?: string;
57
+ }
58
+ declare const SubscriptionManager: React.FC<SubscriptionManagerProps>;
59
+
60
+ export { PaymentForm as P, SubscriptionManager as S, PricingTable as a, type PaymentFormProps as b, type SubscriptionManagerProps as c, type Subscription as d, type SubscriptionAction as e };
@@ -39,7 +39,11 @@ interface Subscription {
39
39
  created: Date;
40
40
  updated?: Date;
41
41
  amount?: number;
42
+ currency?: string;
43
+ interval?: string;
42
44
  interval_unit?: string;
45
+ planName?: string;
46
+ planId?: string;
43
47
  }
44
48
  interface SubscriptionCreateParams {
45
49
  customerId: string;
@@ -39,7 +39,11 @@ interface Subscription {
39
39
  created: Date;
40
40
  updated?: Date;
41
41
  amount?: number;
42
+ currency?: string;
43
+ interval?: string;
42
44
  interval_unit?: string;
45
+ planName?: string;
46
+ planId?: string;
43
47
  }
44
48
  interface SubscriptionCreateParams {
45
49
  customerId: string;
package/dist/index.d.mts CHANGED
@@ -1,6 +1,8 @@
1
- import { C as Customer, S as Subscription, a as CustomerCreateParams, b as SubscriptionCreateParams, c as SubscriptionStatus, d as SubscriptionUpdateParams, P as PaymentsConfig, e as PricingPlan, f as PaymentProviderType, g as PaymentMethod } from './config-CUH_4_2_.mjs';
2
- export { k as ACTIVE_STATUSES, A as ActiveSubscriptionStatus, B as BillingAddress, u as CheckoutSessionParams, s as CustomerUpdateParams, l as INACTIVE_STATUSES, n as INCOMPLETE_STATUSES, I as InactiveSubscriptionStatus, j as IncompleteSubscriptionStatus, x as Invoice, m as PROBLEMATIC_STATUSES, v as PaymentIntentParams, i as ProblematicSubscriptionStatus, t as StripeConfig, w as StripeError, h as SubscriptionItem, W as WebhookEvent, o as isActiveSubscription, p as isInactiveSubscription, r as isIncompleteSubscription, q as isProblematicSubscription } from './config-CUH_4_2_.mjs';
1
+ import { C as Customer, S as Subscription, a as CustomerCreateParams, b as SubscriptionCreateParams, c as SubscriptionStatus, d as SubscriptionUpdateParams, P as PaymentsConfig, e as PricingPlan, f as PaymentProviderType, g as PaymentMethod } from './config-x4PgwjGU.mjs';
2
+ export { k as ACTIVE_STATUSES, A as ActiveSubscriptionStatus, B as BillingAddress, u as CheckoutSessionParams, s as CustomerUpdateParams, l as INACTIVE_STATUSES, n as INCOMPLETE_STATUSES, I as InactiveSubscriptionStatus, j as IncompleteSubscriptionStatus, x as Invoice, m as PROBLEMATIC_STATUSES, v as PaymentIntentParams, i as ProblematicSubscriptionStatus, t as StripeConfig, w as StripeError, h as SubscriptionItem, W as WebhookEvent, o as isActiveSubscription, p as isInactiveSubscription, r as isIncompleteSubscription, q as isProblematicSubscription } from './config-x4PgwjGU.mjs';
3
3
  import React from 'react';
4
+ export { a as PricingTable, P as StripePaymentForm, b as StripePaymentFormProps, S as SubscriptionManager, c as SubscriptionManagerProps } from './SubscriptionManager-DCk9BiEL.mjs';
5
+ import '@stripe/stripe-js';
4
6
 
5
7
  interface CheckoutParams {
6
8
  priceId: string;
@@ -210,6 +212,15 @@ declare const validateAmount: (amount: number, currency: string) => {
210
212
  isValid: boolean;
211
213
  error?: string;
212
214
  };
215
+ declare const validateCard: (cardDetails: {
216
+ number: string;
217
+ expMonth: number;
218
+ expYear: number;
219
+ cvc: string;
220
+ }) => {
221
+ isValid: boolean;
222
+ errors: string[];
223
+ };
213
224
 
214
225
  declare const formatCurrency: (amount: number, currency?: string, options?: {
215
226
  showSymbol?: boolean;
@@ -242,6 +253,20 @@ declare const formatPaymentMethodDisplay: (paymentMethod: {
242
253
  bankName?: string;
243
254
  };
244
255
  }) => string;
256
+ declare const calculateTax: (amount: number, taxRate: number, options?: {
257
+ inclusive?: boolean;
258
+ roundTo?: number;
259
+ }) => {
260
+ subtotal: number;
261
+ tax: number;
262
+ total: number;
263
+ };
264
+ declare const formatTaxRate: (rate: number) => string;
265
+ declare const formatAmountWithTax: (amount: number, taxRate: number, currency?: string, options?: {
266
+ inclusive?: boolean;
267
+ showBreakdown?: boolean;
268
+ locale?: string;
269
+ }) => string;
245
270
 
246
271
  /**
247
272
  * Environment validation utilities for SaaS Factory Payments
@@ -398,4 +423,4 @@ interface UsePaymentsStore {
398
423
  }
399
424
  declare const usePayments: () => UsePaymentsStore;
400
425
 
401
- export { BILLING_INTERVALS, CHECKOUT_MODE, CURRENCY_SYMBOLS, type CheckoutParams, type CheckoutSession, Customer, CustomerCreateParams, DEFAULT_CURRENCY, ERROR_MESSAGES, type EnvironmentConfig, INVOICE_STATUS, MockPaymentProvider, PAYMENT_METHODS, type PaymentError, PaymentErrorType, type PaymentEvent, PaymentMethod, type PaymentProvider, PaymentProviderFactory, PaymentProviderType, PaymentsConfig, PaymentsError, PaymentsProvider, type PaymentsProviderActions, type PaymentsProviderState, type PaymentsStore, PricingPlan, STRIPE_API_VERSION, SUBSCRIPTION_STATUS, StripePaymentProvider, Subscription, SubscriptionCreateParams, SubscriptionStatus, SubscriptionUpdateParams, WEBHOOK_EVENTS, formatBillingInterval, formatCardBrand, formatCurrency, formatDate, formatPaymentMethodDisplay, formatPricingPlan, formatRelativeTime, formatSubscriptionStatus, formatTrialPeriod, getEnvironmentConfig, isClient, isDevelopment, isProduction, isServer, truncateText, usePayments, usePaymentsContext, validateAmount, validateCurrentEnvironment, validateEmail, validateEnvironment, validatePaymentsConfig, validatePhoneNumber, validatePricingPlan, validateStripeId };
426
+ export { BILLING_INTERVALS, CHECKOUT_MODE, CURRENCY_SYMBOLS, type CheckoutParams, type CheckoutSession, Customer, CustomerCreateParams, DEFAULT_CURRENCY, ERROR_MESSAGES, type EnvironmentConfig, INVOICE_STATUS, MockPaymentProvider, PAYMENT_METHODS, type PaymentError, PaymentErrorType, type PaymentEvent, PaymentMethod, type PaymentProvider, PaymentProviderFactory, PaymentProviderType, PaymentsConfig, PaymentsError, PaymentsProvider, type PaymentsProviderActions, type PaymentsProviderState, type PaymentsStore, PricingPlan, STRIPE_API_VERSION, SUBSCRIPTION_STATUS, StripePaymentProvider, Subscription, SubscriptionCreateParams, SubscriptionStatus, SubscriptionUpdateParams, WEBHOOK_EVENTS, calculateTax, formatAmountWithTax, formatBillingInterval, formatCardBrand, formatCurrency, formatDate, formatPaymentMethodDisplay, formatPricingPlan, formatRelativeTime, formatSubscriptionStatus, formatTaxRate, formatTrialPeriod, getEnvironmentConfig, isClient, isDevelopment, isProduction, isServer, truncateText, usePayments, usePaymentsContext, validateAmount, validateCard, validateCurrentEnvironment, validateEmail, validateEnvironment, validatePaymentsConfig, validatePhoneNumber, validatePricingPlan, validateStripeId };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
- import { C as Customer, S as Subscription, a as CustomerCreateParams, b as SubscriptionCreateParams, c as SubscriptionStatus, d as SubscriptionUpdateParams, P as PaymentsConfig, e as PricingPlan, f as PaymentProviderType, g as PaymentMethod } from './config-CUH_4_2_.js';
2
- export { k as ACTIVE_STATUSES, A as ActiveSubscriptionStatus, B as BillingAddress, u as CheckoutSessionParams, s as CustomerUpdateParams, l as INACTIVE_STATUSES, n as INCOMPLETE_STATUSES, I as InactiveSubscriptionStatus, j as IncompleteSubscriptionStatus, x as Invoice, m as PROBLEMATIC_STATUSES, v as PaymentIntentParams, i as ProblematicSubscriptionStatus, t as StripeConfig, w as StripeError, h as SubscriptionItem, W as WebhookEvent, o as isActiveSubscription, p as isInactiveSubscription, r as isIncompleteSubscription, q as isProblematicSubscription } from './config-CUH_4_2_.js';
1
+ import { C as Customer, S as Subscription, a as CustomerCreateParams, b as SubscriptionCreateParams, c as SubscriptionStatus, d as SubscriptionUpdateParams, P as PaymentsConfig, e as PricingPlan, f as PaymentProviderType, g as PaymentMethod } from './config-x4PgwjGU.js';
2
+ export { k as ACTIVE_STATUSES, A as ActiveSubscriptionStatus, B as BillingAddress, u as CheckoutSessionParams, s as CustomerUpdateParams, l as INACTIVE_STATUSES, n as INCOMPLETE_STATUSES, I as InactiveSubscriptionStatus, j as IncompleteSubscriptionStatus, x as Invoice, m as PROBLEMATIC_STATUSES, v as PaymentIntentParams, i as ProblematicSubscriptionStatus, t as StripeConfig, w as StripeError, h as SubscriptionItem, W as WebhookEvent, o as isActiveSubscription, p as isInactiveSubscription, r as isIncompleteSubscription, q as isProblematicSubscription } from './config-x4PgwjGU.js';
3
3
  import React from 'react';
4
+ export { a as PricingTable, P as StripePaymentForm, b as StripePaymentFormProps, S as SubscriptionManager, c as SubscriptionManagerProps } from './SubscriptionManager-Cnw5n74K.js';
5
+ import '@stripe/stripe-js';
4
6
 
5
7
  interface CheckoutParams {
6
8
  priceId: string;
@@ -210,6 +212,15 @@ declare const validateAmount: (amount: number, currency: string) => {
210
212
  isValid: boolean;
211
213
  error?: string;
212
214
  };
215
+ declare const validateCard: (cardDetails: {
216
+ number: string;
217
+ expMonth: number;
218
+ expYear: number;
219
+ cvc: string;
220
+ }) => {
221
+ isValid: boolean;
222
+ errors: string[];
223
+ };
213
224
 
214
225
  declare const formatCurrency: (amount: number, currency?: string, options?: {
215
226
  showSymbol?: boolean;
@@ -242,6 +253,20 @@ declare const formatPaymentMethodDisplay: (paymentMethod: {
242
253
  bankName?: string;
243
254
  };
244
255
  }) => string;
256
+ declare const calculateTax: (amount: number, taxRate: number, options?: {
257
+ inclusive?: boolean;
258
+ roundTo?: number;
259
+ }) => {
260
+ subtotal: number;
261
+ tax: number;
262
+ total: number;
263
+ };
264
+ declare const formatTaxRate: (rate: number) => string;
265
+ declare const formatAmountWithTax: (amount: number, taxRate: number, currency?: string, options?: {
266
+ inclusive?: boolean;
267
+ showBreakdown?: boolean;
268
+ locale?: string;
269
+ }) => string;
245
270
 
246
271
  /**
247
272
  * Environment validation utilities for SaaS Factory Payments
@@ -398,4 +423,4 @@ interface UsePaymentsStore {
398
423
  }
399
424
  declare const usePayments: () => UsePaymentsStore;
400
425
 
401
- export { BILLING_INTERVALS, CHECKOUT_MODE, CURRENCY_SYMBOLS, type CheckoutParams, type CheckoutSession, Customer, CustomerCreateParams, DEFAULT_CURRENCY, ERROR_MESSAGES, type EnvironmentConfig, INVOICE_STATUS, MockPaymentProvider, PAYMENT_METHODS, type PaymentError, PaymentErrorType, type PaymentEvent, PaymentMethod, type PaymentProvider, PaymentProviderFactory, PaymentProviderType, PaymentsConfig, PaymentsError, PaymentsProvider, type PaymentsProviderActions, type PaymentsProviderState, type PaymentsStore, PricingPlan, STRIPE_API_VERSION, SUBSCRIPTION_STATUS, StripePaymentProvider, Subscription, SubscriptionCreateParams, SubscriptionStatus, SubscriptionUpdateParams, WEBHOOK_EVENTS, formatBillingInterval, formatCardBrand, formatCurrency, formatDate, formatPaymentMethodDisplay, formatPricingPlan, formatRelativeTime, formatSubscriptionStatus, formatTrialPeriod, getEnvironmentConfig, isClient, isDevelopment, isProduction, isServer, truncateText, usePayments, usePaymentsContext, validateAmount, validateCurrentEnvironment, validateEmail, validateEnvironment, validatePaymentsConfig, validatePhoneNumber, validatePricingPlan, validateStripeId };
426
+ export { BILLING_INTERVALS, CHECKOUT_MODE, CURRENCY_SYMBOLS, type CheckoutParams, type CheckoutSession, Customer, CustomerCreateParams, DEFAULT_CURRENCY, ERROR_MESSAGES, type EnvironmentConfig, INVOICE_STATUS, MockPaymentProvider, PAYMENT_METHODS, type PaymentError, PaymentErrorType, type PaymentEvent, PaymentMethod, type PaymentProvider, PaymentProviderFactory, PaymentProviderType, PaymentsConfig, PaymentsError, PaymentsProvider, type PaymentsProviderActions, type PaymentsProviderState, type PaymentsStore, PricingPlan, STRIPE_API_VERSION, SUBSCRIPTION_STATUS, StripePaymentProvider, Subscription, SubscriptionCreateParams, SubscriptionStatus, SubscriptionUpdateParams, WEBHOOK_EVENTS, calculateTax, formatAmountWithTax, formatBillingInterval, formatCardBrand, formatCurrency, formatDate, formatPaymentMethodDisplay, formatPricingPlan, formatRelativeTime, formatSubscriptionStatus, formatTaxRate, formatTrialPeriod, getEnvironmentConfig, isClient, isDevelopment, isProduction, isServer, truncateText, usePayments, usePaymentsContext, validateAmount, validateCard, validateCurrentEnvironment, validateEmail, validateEnvironment, validatePaymentsConfig, validatePhoneNumber, validatePricingPlan, validateStripeId };
package/dist/index.js CHANGED
@@ -1,2 +1,17 @@
1
- "use strict";var pe=Object.create;var w=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var Se=(r,e)=>{for(var t in e)w(r,t,{get:e[t],enumerable:!0})},U=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of le(e))!Ee.call(r,n)&&n!==t&&w(r,n,{get:()=>e[n],enumerable:!(i=de(e,n))||i.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?pe(Pe(r)):{},U(e||!r||!r.__esModule?w(t,"default",{value:r,enumerable:!0}):t,r)),be=r=>U(w({},"__esModule",{value:!0}),r);var Xe={};Se(Xe,{ACTIVE_STATUSES:()=>k,BILLING_INTERVALS:()=>ge,CHECKOUT_MODE:()=>Ne,CURRENCY_SYMBOLS:()=>T,DEFAULT_CURRENCY:()=>D,ERROR_MESSAGES:()=>C,INACTIVE_STATUSES:()=>L,INCOMPLETE_STATUSES:()=>F,INVOICE_STATUS:()=>Oe,MockPaymentProvider:()=>N,PAYMENT_METHODS:()=>Ie,PROBLEMATIC_STATUSES:()=>M,PaymentErrorType:()=>R,PaymentProviderFactory:()=>P,PaymentsError:()=>s,PaymentsProvider:()=>H,STRIPE_API_VERSION:()=>_e,SUBSCRIPTION_STATUS:()=>ve,StripePaymentProvider:()=>O,SubscriptionStatus:()=>A,WEBHOOK_EVENTS:()=>we,formatBillingInterval:()=>Ke,formatCardBrand:()=>V,formatCurrency:()=>x,formatDate:()=>xe,formatPaymentMethodDisplay:()=>$e,formatPricingPlan:()=>Me,formatRelativeTime:()=>Ve,formatSubscriptionStatus:()=>Fe,formatTrialPeriod:()=>Be,getEnvironmentConfig:()=>B,isActiveSubscription:()=>Ce,isClient:()=>He,isDevelopment:()=>We,isInactiveSubscription:()=>he,isIncompleteSubscription:()=>Re,isProblematicSubscription:()=>ye,isProduction:()=>ze,isServer:()=>qe,truncateText:()=>Ge,usePayments:()=>Z,usePaymentsContext:()=>X,validateAmount:()=>Le,validateCurrentEnvironment:()=>Ye,validateEmail:()=>Te,validateEnvironment:()=>K,validatePaymentsConfig:()=>Ue,validatePhoneNumber:()=>De,validatePricingPlan:()=>Ae,validateStripeId:()=>ke});module.exports=be(Xe);var A=(p=>(p.ACTIVE="active",p.CANCELED="canceled",p.PAST_DUE="past_due",p.UNPAID="unpaid",p.INCOMPLETE="incomplete",p.INCOMPLETE_EXPIRED="incomplete_expired",p.TRIALING="trialing",p.ENDED="ended",p.ALL="all",p))(A||{}),k=["active","trialing"],L=["canceled","ended"],M=["past_due","unpaid"],F=["incomplete","incomplete_expired"],Ce=r=>k.includes(r),he=r=>L.includes(r),ye=r=>M.includes(r),Re=r=>F.includes(r);var R=(S=>(S.CARD_DECLINED="CARD_DECLINED",S.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",S.CUSTOMER_NOT_FOUND="CUSTOMER_NOT_FOUND",S.SUBSCRIPTION_NOT_FOUND="SUBSCRIPTION_NOT_FOUND",S.NETWORK_ERROR="NETWORK_ERROR",S.CONFIGURATION_ERROR="CONFIGURATION_ERROR",S.WEBHOOK_ERROR="WEBHOOK_ERROR",S.VALIDATION_ERROR="VALIDATION_ERROR",S.PROVIDER_NOT_CONFIGURED="PROVIDER_NOT_CONFIGURED",S.UNKNOWN_ERROR="UNKNOWN_ERROR",S.INITIALIZATION_ERROR="INITIALIZATION_ERROR",S.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",S.NOT_FOUND="NOT_FOUND",S.INVALID_REQUEST="INVALID_REQUEST",S.API_ERROR="API_ERROR",S.PERMISSION_DENIED="PERMISSION_DENIED",S.WEBHOOK_VERIFICATION_FAILED="WEBHOOK_VERIFICATION_FAILED",S))(R||{}),s=class r extends Error{type;code;details;constructor(e,t,i,n){super(t),this.name="PaymentsError",this.type=e,this.code=i,this.details=n,Object.setPrototypeOf(this,r.prototype)}};var _e="2023-10-16",Ie={CARD:"card",BANK_ACCOUNT:"bank_account",SEPA_DEBIT:"sepa_debit",IDEAL:"ideal",SOFORT:"sofort"},ve={ACTIVE:"active",CANCELED:"canceled",PAST_DUE:"past_due",UNPAID:"unpaid",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",TRIALING:"trialing"},Oe={DRAFT:"draft",OPEN:"open",PAID:"paid",UNCOLLECTIBLE:"uncollectible",VOID:"void"},Ne={PAYMENT:"payment",SUBSCRIPTION:"subscription",SETUP:"setup"},ge={DAY:"day",WEEK:"week",MONTH:"month",YEAR:"year"},T={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NZD:"NZ$"},D="USD",we={CUSTOMER_SUBSCRIPTION_CREATED:"customer.subscription.created",CUSTOMER_SUBSCRIPTION_UPDATED:"customer.subscription.updated",CUSTOMER_SUBSCRIPTION_DELETED:"customer.subscription.deleted",INVOICE_PAYMENT_SUCCEEDED:"invoice.payment_succeeded",INVOICE_PAYMENT_FAILED:"invoice.payment_failed",CHECKOUT_SESSION_COMPLETED:"checkout.session.completed",PAYMENT_INTENT_SUCCEEDED:"payment_intent.succeeded",PAYMENT_INTENT_PAYMENT_FAILED:"payment_intent.payment_failed"},C={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=r=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r),De=r=>/^\+?[\d\s-()]{10,}$/.test(r),Ue=r=>{let e=[];return r.publishableKey||e.push("publishableKey is required"),r.provider||e.push("provider is required"),r.provider!=="stripe"&&e.push("Only stripe provider is currently supported"),r.environment||e.push("environment is required"),r.environment&&!["development","production"].includes(r.environment)&&e.push('environment must be either "development" or "production"'),r.publishableKey&&!r.publishableKey.startsWith("pk_")&&e.push('publishableKey must start with "pk_"'),r.secretKey&&!r.secretKey.startsWith("sk_")&&e.push('secretKey must start with "sk_"'),r.webhookSecret&&!r.webhookSecret.startsWith("whsec_")&&e.push('webhookSecret must start with "whsec_"'),{isValid:e.length===0,errors:e}},Ae=r=>{let e=[];return r.id||e.push("id is required"),r.name||e.push("name is required"),(typeof r.price!="number"||r.price<0)&&e.push("price must be a non-negative number"),r.currency||e.push("currency is required"),r.interval||e.push("interval is required"),["day","week","month","year"].includes(r.interval)||e.push("interval must be one of: day, week, month, year"),r.stripePriceId||e.push("stripePriceId is required"),r.stripePriceId&&!r.stripePriceId.startsWith("price_")&&e.push('stripePriceId must start with "price_"'),Array.isArray(r.features)||e.push("features must be an array"),r.intervalCount&&(typeof r.intervalCount!="number"||r.intervalCount<1)&&e.push("intervalCount must be a positive number"),r.trialPeriodDays&&(typeof r.trialPeriodDays!="number"||r.trialPeriodDays<0)&&e.push("trialPeriodDays must be a non-negative number"),{isValid:e.length===0,errors:e}},ke=(r,e)=>{let t={customer:"cus_",subscription:"sub_",price:"price_",product:"prod_",payment_intent:"pi_"};return r.startsWith(t[e])},Le=(r,e)=>{if(typeof r!="number")return{isValid:!1,error:"Amount must be a number"};if(r<0)return{isValid:!1,error:"Amount must be non-negative"};let i={USD:50,EUR:50,GBP:30,JPY:50,CAD:50,AUD:50}[e.toUpperCase()]||50;return r<i?{isValid:!1,error:`Amount must be at least ${i} ${e.toLowerCase()} cents`}:{isValid:!0}};var x=(r,e=D,t={})=>{let{showSymbol:i=!0,showCents:n=!0,locale:o="en-US"}=t,c=e.toUpperCase(),a=["JPY","KRW","VND","CLP"].includes(c),h=a?r:r/100;if(i)try{return new Intl.NumberFormat(o,{style:"currency",currency:c,minimumFractionDigits:n&&!a?2:0,maximumFractionDigits:n&&!a?2:0}).format(h)}catch{let p=T[c]||c,E=n&&!a?h.toFixed(2):Math.round(h).toString();return`${p}${E}`}return n&&!a?h.toFixed(2):Math.round(h).toString()},Me=r=>{let e=x(r.price,r.currency),t=r.intervalCount&&r.intervalCount>1?`${r.intervalCount} ${r.interval}s`:r.interval;return`${e}/${t}`},Fe=r=>({active:"Active",canceled:"Canceled",past_due:"Past Due",unpaid:"Unpaid",incomplete:"Incomplete",incomplete_expired:"Incomplete (Expired)",trialing:"Trial",ended:"Ended",all:"All"})[r]||r,xe=(r,e={})=>{let{format:t="medium",locale:i="en-US",timeZone:n}=e,o=typeof r=="string"||typeof r=="number"?new Date(r):r,c={timeZone:n};switch(t){case"short":c.dateStyle="short";break;case"medium":c.dateStyle="medium";break;case"long":c.dateStyle="long";break;case"full":c.dateStyle="full";break}try{return new Intl.DateTimeFormat(i,c).format(o)}catch{return o.toLocaleDateString()}},Ve=(r,e={})=>{let{locale:t="en-US",numeric:i="auto"}=e,n=typeof r=="string"||typeof r=="number"?new Date(r):r,c=Math.floor((new Date().getTime()-n.getTime())/1e3);try{let a=new Intl.RelativeTimeFormat(t,{numeric:i});return Math.abs(c)<60?a.format(-c,"second"):Math.abs(c)<3600?a.format(-Math.floor(c/60),"minute"):Math.abs(c)<86400?a.format(-Math.floor(c/3600),"hour"):Math.abs(c)<2592e3?a.format(-Math.floor(c/86400),"day"):Math.abs(c)<31536e3?a.format(-Math.floor(c/2592e3),"month"):a.format(-Math.floor(c/31536e3),"year")}catch{if(Math.abs(c)<60)return"just now";if(Math.abs(c)<3600){let a=Math.floor(Math.abs(c)/60);return c<0?`in ${a} minutes`:`${a} minutes ago`}else if(Math.abs(c)<86400){let a=Math.floor(Math.abs(c)/3600);return c<0?`in ${a} hours`:`${a} hours ago`}else{let a=Math.floor(Math.abs(c)/86400);return c<0?`in ${a} days`:`${a} days ago`}}},Ke=(r,e=1)=>({day:e===1?"daily":`every ${e} days`,week:e===1?"weekly":`every ${e} weeks`,month:e===1?"monthly":`every ${e} months`,year:e===1?"yearly":`every ${e} years`})[r]||r,Be=r=>r===0?"No trial":r===1?"1 day trial":r<7?`${r} days trial`:r===7?"1 week trial":r<30?`${Math.floor(r/7)} weeks trial`:r===30?"1 month trial":`${Math.floor(r/30)} months trial`,Ge=(r,e)=>r.length<=e?r:`${r.substring(0,e-3)}...`,V=r=>({visa:"Visa",mastercard:"Mastercard",amex:"American Express",discover:"Discover",jcb:"JCB",diners:"Diners Club",unionpay:"UnionPay"})[r.toLowerCase()]||r,$e=r=>r.type==="card"&&r.card?`${V(r.card.brand)} \u2022\u2022\u2022\u2022 ${r.card.last4}`:r.type==="bank_account"&&r.bankAccount?`${r.bankAccount.bankName||"Bank"} \u2022\u2022\u2022\u2022 ${r.bankAccount.last4}`:r.type;var K=r=>{let e=[],t=[];return r.stripePublishableKey?r.stripePublishableKey.startsWith("pk_")||e.push('STRIPE_PUBLISHABLE_KEY must start with "pk_"'):e.push("STRIPE_PUBLISHABLE_KEY is required"),r.environment?["development","production"].includes(r.environment)||e.push('Environment must be either "development" or "production"'):e.push("Environment must be specified (development or production)"),r.environment==="production"&&(r.stripePublishableKey?.includes("test")&&t.push("Using test keys in production environment"),r.appUrl?r.appUrl.startsWith("https://")||t.push("APP_URL should use HTTPS in production"):t.push("APP_URL should be set in production for proper redirects")),typeof window>"u"&&(r.stripeSecretKey?r.stripeSecretKey.startsWith("sk_")||e.push('STRIPE_SECRET_KEY must start with "sk_"'):t.push("STRIPE_SECRET_KEY is recommended for server-side operations"),r.stripeWebhookSecret?r.stripeWebhookSecret.startsWith("whsec_")||e.push('STRIPE_WEBHOOK_SECRET must start with "whsec_"'):t.push("STRIPE_WEBHOOK_SECRET is recommended for webhook verification")),{isValid:e.length===0,errors:e,warnings:t}},B=()=>{let r=typeof window>"u",e={stripePublishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY||process.env.EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY||"",environment:process.env.NODE_ENV||"development",appUrl:process.env.NEXT_PUBLIC_APP_URL};return r&&(e.stripeSecretKey=process.env.STRIPE_SECRET_KEY,e.stripeWebhookSecret=process.env.STRIPE_WEBHOOK_SECRET),e},Ye=()=>{let r=B(),e=K(r);if(!e.isValid&&(console.error("\u274C Environment validation failed:"),e.errors.forEach(t=>console.error(` - ${t}`)),typeof window>"u"))throw new Error(`Environment validation failed: ${e.errors.join(", ")}`);return e.warnings.length>0&&(console.warn("\u26A0\uFE0F Environment warnings:"),e.warnings.forEach(t=>console.warn(` - ${t}`))),e},We=()=>process.env.NODE_ENV==="development",ze=()=>process.env.NODE_ENV==="production",qe=()=>typeof window>"u",He=()=>typeof window<"u";var v=class{config;constructor(e){this.config=e}handleError(e,t="UNKNOWN_ERROR"){if(e instanceof s)return e;let i="An unknown error occurred",n,o;return typeof e=="object"&&e!==null&&("message"in e&&typeof e.message=="string"&&(i=e.message),"code"in e&&typeof e.code=="string"&&(n=e.code),o={...e}),new s(t,i,n,o)}};var G=fe(require("stripe")),O=class extends v{name="stripe";stripeClient;constructor(e){if(super(e),!e.stripeConfig?.publishableKey)throw new s("CONFIGURATION_ERROR","Stripe publishable key is missing in config.");if(!process.env.STRIPE_SECRET_KEY)throw new s("CONFIGURATION_ERROR","STRIPE_SECRET_KEY environment variable is not set.");this.stripeClient=new G.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 s("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(i=>({price:i.priceId,quantity:i.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 s("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 s("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(i){throw this.handleError(i,"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 i=await this.stripeClient.subscriptions.retrieve(e),n=t.items?t.items.map(c=>({id:i.items.data.find(a=>a.price?.id===c.priceId)?.id,price:c.priceId,quantity:c.quantity||1})):void 0,o=await this.stripeClient.subscriptions.update(e,{items:n,metadata:t.metadata});return this.mapStripeSubscriptionToSubscription(o)}catch(i){throw this.handleError(i,"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 N=class extends v{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 s("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(i=>i.id===e);if(!t)throw new s("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t}async updateCustomer(e,t){console.log("Mock: updateCustomer",e,t);let i=this.customers.find(n=>n.id===e);if(!i)throw new s("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t.email&&(i.email=t.email),t.name&&(i.name=t.name),t.phone&&(i.phone=t.phone),t.metadata&&(i.metadata={...i.metadata,...t.metadata}),i.updated=new Date,i}async deleteCustomer(e){console.log("Mock: deleteCustomer",e);let t=this.customers.length;if(this.customers=this.customers.filter(i=>i.id!==e),this.customers.length===t)throw new s("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`)}async listPaymentMethods(e){console.log("Mock: listPaymentMethods",e);let t=this.customers.find(i=>i.id===e);if(!t)throw new s("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t.paymentMethods||[]}async attachPaymentMethod(e,t){console.log("Mock: attachPaymentMethod",e,t);let i=this.customers.find(o=>o.id===e);if(!i)throw new s("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 i.paymentMethods.push(n),n}async detachPaymentMethod(e,t){console.log("Mock: detachPaymentMethod",e,t);let i=this.customers.find(o=>o.id===e);if(!i)throw new s("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n=i.paymentMethods.length;if(i.paymentMethods=i.paymentMethods.filter(o=>o.id!==t),i.paymentMethods.length===n)throw new s("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 s("CUSTOMER_NOT_FOUND",`Mock customer ${e.customerId} not found`);let i={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(i),t.subscriptions.push(i),i}async retrieveSubscription(e){console.log("Mock: retrieveSubscription",e);let t=this.subscriptions.find(i=>i.id===e);if(!t)throw new s("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);return t}async updateSubscription(e,t){console.log("Mock: updateSubscription",e,t);let i=this.subscriptions.find(n=>n.id===e);if(!i)throw new s("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);return t.cancelAtPeriodEnd!==void 0&&(i.cancelAtPeriodEnd=t.cancelAtPeriodEnd,i.status=t.cancelAtPeriodEnd?"canceled":"active"),t.items&&(i.items=t.items.map(n=>({id:`mock_sub_item_${Math.random().toString(36).substring(7)}`,priceId:n.priceId,quantity:n.quantity||1}))),i.updated=new Date,i}async cancelSubscription(e){console.log("Mock: cancelSubscription",e);let t=this.subscriptions.find(i=>i.id===e);if(!t)throw new s("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(i=>i.id===e);if(!t)throw new s("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 i=this.customers.find(o=>o.id===e);if(!i)throw new s("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n=i.subscriptions;return t&&t!=="all"&&(n=n.filter(o=>o.status===t)),n}};var P=class{static create(e){switch(e.provider){case"stripe":return new O(e);case"paypal":throw new s("PROVIDER_NOT_CONFIGURED","PayPal provider is not yet available in this build");case"applepay":throw new s("PROVIDER_NOT_CONFIGURED","Apple Pay provider is not yet available in this build");case"mock":return new N(e);default:throw new s("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 s("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 y=require("react");var Y=require("zustand"),W=require("zustand/middleware/immer");var $={customer:null,subscriptions:[],activeSubscription:null,loading:!1,error:null,initialized:!1,config:null,isLoading:!1,isError:!1},z=(0,Y.create)()((0,W.immer)((r,e)=>({...$,get isLoading(){return e().loading},get isError(){return!!e().error},initialize:async t=>{r(i=>{i.loading=!0,i.error=null});try{let i;t?i=t:i=P.autodetect(),await P.create(i).initialize(),r(o=>{o.initialized=!0,o.loading=!1,o.config=i})}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to initialize payments provider.";n.error=new s("CONFIGURATION_ERROR",o),n.loading=!1}),i}},createCustomer:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new s("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await P.create(e().config).createCustomer(t);return r(o=>{o.customer=n,o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to create customer.";n.error=new s("NETWORK_ERROR",o),n.loading=!1}),i}},retrieveCustomer:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new s("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await P.create(e().config).retrieveCustomer(t);return r(o=>{o.customer=n,o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to retrieve customer.";n.error=new s("NETWORK_ERROR",o),n.loading=!1}),i}},createCheckoutSession:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new s("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await P.create(e().config).createCheckoutSession(t);return r(o=>{o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to create checkout session.";n.error=new s("NETWORK_ERROR",o),n.loading=!1}),i}},retrieveCheckoutSession:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new s("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await P.create(e().config).retrieveCheckoutSession(t);return r(o=>{o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to retrieve checkout session.";n.error=new s("NETWORK_ERROR",o),n.loading=!1}),i}},createSubscription:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new s("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await P.create(e().config).createSubscription(t);return await e().refreshSubscriptions(e().customer?.id||""),r(o=>{o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to create subscription.";n.error=new s("NETWORK_ERROR",o),n.loading=!1}),i}},cancelSubscription:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new s("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");await P.create(e().config).cancelSubscription(t),await e().refreshSubscriptions(e().customer?.id||""),r(n=>{n.loading=!1})}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to cancel subscription.";n.error=new s("NETWORK_ERROR",o),n.loading=!1}),i}},reactivateSubscription:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new s("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");await P.create(e().config).reactivateSubscription(t),await e().refreshSubscriptions(e().customer?.id||""),r(n=>{n.loading=!1})}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to reactivate subscription.";n.error=new s("NETWORK_ERROR",o),n.loading=!1}),i}},updateSubscription:async(t,i)=>{r(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new s("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let o=await P.create(e().config).updateSubscription(t,i);return await e().refreshSubscriptions(e().customer?.id||""),r(c=>{c.loading=!1}),o}catch(n){throw r(o=>{let c=n instanceof Error?n.message:"Failed to update subscription.";o.error=new s("NETWORK_ERROR",c),o.loading=!1}),n}},listSubscriptions:async(t,i)=>{r(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new s("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let o=await P.create(e().config).listSubscriptions(t,i);return r(c=>{c.subscriptions=o,c.loading=!1}),o}catch(n){throw r(o=>{let c=n instanceof Error?n.message:"Failed to list subscriptions.";o.error=new s("NETWORK_ERROR",c),o.loading=!1}),n}},retrieveSubscription:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new s("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await P.create(e().config).retrieveSubscription(t);return r(o=>{o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to retrieve subscription.";n.error=new s("NETWORK_ERROR",o),n.loading=!1}),i}},refreshCustomer:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new s("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await P.create(e().config).retrieveCustomer(t);r(o=>{o.customer=n,o.loading=!1})}catch(i){r(n=>{let o=i instanceof Error?i.message:"Failed to refresh customer.";n.error=new s("NETWORK_ERROR",o),n.loading=!1})}},refreshSubscriptions:async(t,i)=>{r(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new s("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let o=await P.create(e().config).listSubscriptions(t,i),c=o.find(a=>a.status==="active"||a.status==="trialing")||null;r(a=>{a.subscriptions=o,a.activeSubscription=c,a.loading=!1})}catch(n){r(o=>{let c=n instanceof Error?n.message:"Failed to refresh subscriptions.";o.error=new s("NETWORK_ERROR",c),o.loading=!1})}},reset:()=>{r(t=>{Object.assign(t,$)})}})));var j=require("react/jsx-runtime"),q=(0,y.createContext)(void 0),H=({children:r,config:e,onPaymentSuccess:t,onPaymentError:i})=>{let n=z(),{initialize:o,initialized:c,loading:a,error:h,customer:p,subscriptions:E,activeSubscription:I}=n,g=(0,y.useRef)(t),_=(0,y.useRef)(i);(0,y.useEffect)(()=>{g.current=t},[t]),(0,y.useEffect)(()=>{_.current=i},[i]),(0,y.useEffect)(()=>{!c&&!a&&!h&&o(e).catch(b=>{console.error("PaymentsProvider initialization failed:",b),_.current&&_.current(b)})},[c,a,h,e,o]);let d={config:n.config,initialized:c,loading:a,error:h,customer:p,subscriptions:E,activeSubscription:I,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,j.jsx)(q.Provider,{value:d,children:r})},X=()=>{let r=(0,y.useContext)(q);if(r===void 0)throw new Error("usePaymentsContext must be used within a PaymentsProvider");return r};var l=require("react");var Z=()=>{let[r,e]=(0,l.useState)(null),[t,i]=(0,l.useState)(null),[n,o]=(0,l.useState)(!1),[c,a]=(0,l.useState)(!1),[h,p]=(0,l.useState)(null),[E,I]=(0,l.useState)(null),[g,_]=(0,l.useState)([]),d=(0,l.useCallback)(m=>{p(m),console.error("Payments error:",m)},[]),b=(0,l.useCallback)(async(m,u)=>{if(!t)throw new s("PROVIDER_NOT_CONFIGURED",C.PROVIDER_NOT_CONFIGURED);a(!0),p(null);try{let f=await t.listSubscriptions(m,u);_(f)}catch(f){throw d(f),f}finally{a(!1)}},[t,d]),J=(0,l.useCallback)(async m=>{a(!0),p(null);try{let u=m||P.autodetect(),f=P.create(u);e(u),i(f),o(!0)}catch(u){d(u)}finally{a(!1)}},[d]),S=(0,l.useCallback)(async m=>{if(!t)throw new s("PROVIDER_NOT_CONFIGURED",C.PROVIDER_NOT_CONFIGURED);a(!0),p(null);try{let u=await t.retrieveCustomer(m);return I(u),u}catch(u){throw d(u),u}finally{a(!1)}},[t,d]),Q=(0,l.useCallback)(async m=>{if(!t)throw new s("PROVIDER_NOT_CONFIGURED",C.PROVIDER_NOT_CONFIGURED);a(!0),p(null);try{let u=await t.createCustomer(m);return I(u),u}catch(u){throw d(u),u}finally{a(!1)}},[t,d]),ee=(0,l.useCallback)(async m=>{if(!t||!E)throw new s("PROVIDER_NOT_CONFIGURED",C.PROVIDER_NOT_CONFIGURED);a(!0),p(null);try{let u=await t.createSubscription({customerId:E.id,items:[{priceId:m.priceId,quantity:m.quantity}]});return await b(E.id),u}catch(u){throw d(u),u}finally{a(!1)}},[t,E,d,b]),te=(0,l.useCallback)(async(m,u)=>{if(!t)throw new s("PROVIDER_NOT_CONFIGURED",C.PROVIDER_NOT_CONFIGURED);a(!0),p(null);try{let f=await t.listSubscriptions(m,u);return _(f),f}catch(f){throw d(f),f}finally{a(!1)}},[t,d]),re=(0,l.useCallback)(async m=>{if(!t)throw new s("PROVIDER_NOT_CONFIGURED",C.PROVIDER_NOT_CONFIGURED);a(!0),p(null);try{let u=await t.retrieveSubscription(m);return E?.id&&await b(E.id),u}catch(u){throw d(u),u}finally{a(!1)}},[t,E,d,b]),ie=(0,l.useCallback)(async m=>{if(!t)throw new s("PROVIDER_NOT_CONFIGURED",C.PROVIDER_NOT_CONFIGURED);a(!0),p(null);try{return await t.createCheckoutSession(m)}catch(u){throw d(u),u}finally{a(!1)}},[t,d]),ne=(0,l.useCallback)(async m=>{if(!t)throw new s("PROVIDER_NOT_CONFIGURED",C.PROVIDER_NOT_CONFIGURED);a(!0),p(null);try{return await t.retrieveCheckoutSession(m)}catch(u){throw d(u),u}finally{a(!1)}},[t,d]),oe=(0,l.useCallback)(async m=>{if(!t)throw new s("PROVIDER_NOT_CONFIGURED",C.PROVIDER_NOT_CONFIGURED);a(!0),p(null);try{await t.cancelSubscription(m),E?.id&&await b(E.id)}catch(u){throw d(u),u}finally{a(!1)}},[t,E,d,b]),se=(0,l.useCallback)(async m=>{if(!t)throw new s("PROVIDER_NOT_CONFIGURED",C.PROVIDER_NOT_CONFIGURED);a(!0),p(null);try{await t.reactivateSubscription(m),E?.id&&await b(E.id)}catch(u){throw d(u),u}finally{a(!1)}},[t,E,d,b]),ae=(0,l.useCallback)(async(m,u)=>{if(!t)throw new s("PROVIDER_NOT_CONFIGURED",C.PROVIDER_NOT_CONFIGURED);a(!0),p(null);try{let f=await t.updateSubscription(m,u);return E?.id&&await b(E.id),f}catch(f){throw d(f),f}finally{a(!1)}},[t,E,d,b]),ce=(0,l.useCallback)(async m=>{if(!t)throw new s("PROVIDER_NOT_CONFIGURED",C.PROVIDER_NOT_CONFIGURED);a(!0),p(null);try{let u=await t.retrieveCustomer(m);I(u)}catch(u){throw d(u),u}finally{a(!1)}},[t,d]),ue=(0,l.useCallback)(()=>{e(null),i(null),o(!1),a(!1),p(null),I(null),_([])},[]),me=g.find(m=>m.status==="active"||m.status==="trialing")||null;return(0,l.useEffect)(()=>{},[]),{config:r,provider:t,initialized:n,loading:c,error:h,isLoading:c,isError:!!h,customer:E,subscriptions:g,activeSubscription:me,initialize:J,createCustomer:Q,retrieveCustomer:S,createCheckoutSession:ie,retrieveCheckoutSession:ne,createSubscription:ee,cancelSubscription:oe,reactivateSubscription:se,listSubscriptions:te,retrieveSubscription:re,updateSubscription:ae,refreshCustomer:ce,refreshSubscriptions:b,reset:ue}};0&&(module.exports={ACTIVE_STATUSES,BILLING_INTERVALS,CHECKOUT_MODE,CURRENCY_SYMBOLS,DEFAULT_CURRENCY,ERROR_MESSAGES,INACTIVE_STATUSES,INCOMPLETE_STATUSES,INVOICE_STATUS,MockPaymentProvider,PAYMENT_METHODS,PROBLEMATIC_STATUSES,PaymentErrorType,PaymentProviderFactory,PaymentsError,PaymentsProvider,STRIPE_API_VERSION,SUBSCRIPTION_STATUS,StripePaymentProvider,SubscriptionStatus,WEBHOOK_EVENTS,formatBillingInterval,formatCardBrand,formatCurrency,formatDate,formatPaymentMethodDisplay,formatPricingPlan,formatRelativeTime,formatSubscriptionStatus,formatTrialPeriod,getEnvironmentConfig,isActiveSubscription,isClient,isDevelopment,isInactiveSubscription,isIncompleteSubscription,isProblematicSubscription,isProduction,isServer,truncateText,usePayments,usePaymentsContext,validateAmount,validateCurrentEnvironment,validateEmail,validateEnvironment,validatePaymentsConfig,validatePhoneNumber,validatePricingPlan,validateStripeId});
1
+ "use strict";var Me=Object.create;var q=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var Ve=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty;var Ke=(r,e)=>{for(var t in e)q(r,t,{get:e[t],enumerable:!0})},se=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Le(e))!Be.call(r,n)&&n!==t&&q(r,n,{get:()=>e[n],enumerable:!(i=Fe(e,n))||i.enumerable});return r};var $e=(r,e,t)=>(t=r!=null?Me(Ve(r)):{},se(e||!r||!r.__esModule?q(t,"default",{value:r,enumerable:!0}):t,r)),Ye=r=>se(q({},"__esModule",{value:!0}),r);var ft={};Ke(ft,{ACTIVE_STATUSES:()=>ce,BILLING_INTERVALS:()=>Qe,CHECKOUT_MODE:()=>Ze,CURRENCY_SYMBOLS:()=>ee,DEFAULT_CURRENCY:()=>H,ERROR_MESSAGES:()=>y,INACTIVE_STATUSES:()=>ue,INCOMPLETE_STATUSES:()=>me,INVOICE_STATUS:()=>Je,MockPaymentProvider:()=>G,PAYMENT_METHODS:()=>Xe,PROBLEMATIC_STATUSES:()=>le,PaymentErrorType:()=>M,PaymentProviderFactory:()=>R,PaymentsError:()=>c,PaymentsProvider:()=>Ne,PricingTable:()=>ne,STRIPE_API_VERSION:()=>He,SUBSCRIPTION_STATUS:()=>je,StripePaymentForm:()=>Z,StripePaymentProvider:()=>Y,SubscriptionManager:()=>oe,SubscriptionStatus:()=>ae,WEBHOOK_EVENTS:()=>et,calculateTax:()=>ie,formatAmountWithTax:()=>Ee,formatBillingInterval:()=>ot,formatCardBrand:()=>Se,formatCurrency:()=>V,formatDate:()=>be,formatPaymentMethodDisplay:()=>at,formatPricingPlan:()=>te,formatRelativeTime:()=>nt,formatSubscriptionStatus:()=>it,formatTaxRate:()=>ye,formatTrialPeriod:()=>re,getEnvironmentConfig:()=>ge,isActiveSubscription:()=>Ge,isClient:()=>dt,isDevelopment:()=>ut,isInactiveSubscription:()=>We,isIncompleteSubscription:()=>qe,isProblematicSubscription:()=>ze,isProduction:()=>lt,isServer:()=>mt,truncateText:()=>st,usePayments:()=>Te,usePaymentsContext:()=>$,validateAmount:()=>fe,validateCard:()=>Pe,validateCurrentEnvironment:()=>ct,validateEmail:()=>X,validateEnvironment:()=>he,validatePaymentsConfig:()=>de,validatePhoneNumber:()=>tt,validatePricingPlan:()=>pe,validateStripeId:()=>j});module.exports=Ye(ft);var ae=(l=>(l.ACTIVE="active",l.CANCELED="canceled",l.PAST_DUE="past_due",l.UNPAID="unpaid",l.INCOMPLETE="incomplete",l.INCOMPLETE_EXPIRED="incomplete_expired",l.TRIALING="trialing",l.ENDED="ended",l.ALL="all",l))(ae||{}),ce=["active","trialing"],ue=["canceled","ended"],le=["past_due","unpaid"],me=["incomplete","incomplete_expired"],Ge=r=>ce.includes(r),We=r=>ue.includes(r),ze=r=>le.includes(r),qe=r=>me.includes(r);var M=(h=>(h.CARD_DECLINED="CARD_DECLINED",h.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",h.CUSTOMER_NOT_FOUND="CUSTOMER_NOT_FOUND",h.SUBSCRIPTION_NOT_FOUND="SUBSCRIPTION_NOT_FOUND",h.NETWORK_ERROR="NETWORK_ERROR",h.CONFIGURATION_ERROR="CONFIGURATION_ERROR",h.WEBHOOK_ERROR="WEBHOOK_ERROR",h.VALIDATION_ERROR="VALIDATION_ERROR",h.PROVIDER_NOT_CONFIGURED="PROVIDER_NOT_CONFIGURED",h.UNKNOWN_ERROR="UNKNOWN_ERROR",h.INITIALIZATION_ERROR="INITIALIZATION_ERROR",h.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",h.NOT_FOUND="NOT_FOUND",h.INVALID_REQUEST="INVALID_REQUEST",h.API_ERROR="API_ERROR",h.PERMISSION_DENIED="PERMISSION_DENIED",h.WEBHOOK_VERIFICATION_FAILED="WEBHOOK_VERIFICATION_FAILED",h))(M||{}),c=class r extends Error{type;code;details;constructor(e,t,i,n){super(t),this.name="PaymentsError",this.type=e,this.code=i,this.details=n,Object.setPrototypeOf(this,r.prototype)}};var He="2023-10-16",Xe={CARD:"card",BANK_ACCOUNT:"bank_account",SEPA_DEBIT:"sepa_debit",IDEAL:"ideal",SOFORT:"sofort"},je={ACTIVE:"active",CANCELED:"canceled",PAST_DUE:"past_due",UNPAID:"unpaid",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",TRIALING:"trialing"},Je={DRAFT:"draft",OPEN:"open",PAID:"paid",UNCOLLECTIBLE:"uncollectible",VOID:"void"},Ze={PAYMENT:"payment",SUBSCRIPTION:"subscription",SETUP:"setup"},Qe={DAY:"day",WEEK:"week",MONTH:"month",YEAR:"year"},ee={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NZD:"NZ$"},H="USD",et={CUSTOMER_SUBSCRIPTION_CREATED:"customer.subscription.created",CUSTOMER_SUBSCRIPTION_UPDATED:"customer.subscription.updated",CUSTOMER_SUBSCRIPTION_DELETED:"customer.subscription.deleted",INVOICE_PAYMENT_SUCCEEDED:"invoice.payment_succeeded",INVOICE_PAYMENT_FAILED:"invoice.payment_failed",CHECKOUT_SESSION_COMPLETED:"checkout.session.completed",PAYMENT_INTENT_SUCCEEDED:"payment_intent.succeeded",PAYMENT_INTENT_PAYMENT_FAILED:"payment_intent.payment_failed"},y={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 X=r=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r),tt=r=>/^\+?[\d\s-()]{10,}$/.test(r),de=r=>{let e=[];return r.publishableKey||e.push("publishableKey is required"),r.provider||e.push("provider is required"),r.provider!=="stripe"&&e.push("Only stripe provider is currently supported"),r.environment||e.push("environment is required"),r.environment&&!["development","production"].includes(r.environment)&&e.push('environment must be either "development" or "production"'),r.publishableKey&&!r.publishableKey.startsWith("pk_")&&e.push('publishableKey must start with "pk_"'),r.secretKey&&!r.secretKey.startsWith("sk_")&&e.push('secretKey must start with "sk_"'),r.webhookSecret&&!r.webhookSecret.startsWith("whsec_")&&e.push('webhookSecret must start with "whsec_"'),{isValid:e.length===0,errors:e}},pe=r=>{let e=[];return r.id||e.push("id is required"),r.name||e.push("name is required"),(typeof r.price!="number"||r.price<0)&&e.push("price must be a non-negative number"),r.currency||e.push("currency is required"),r.interval||e.push("interval is required"),["day","week","month","year"].includes(r.interval)||e.push("interval must be one of: day, week, month, year"),r.stripePriceId||e.push("stripePriceId is required"),r.stripePriceId&&!r.stripePriceId.startsWith("price_")&&e.push('stripePriceId must start with "price_"'),Array.isArray(r.features)||e.push("features must be an array"),r.intervalCount&&(typeof r.intervalCount!="number"||r.intervalCount<1)&&e.push("intervalCount must be a positive number"),r.trialPeriodDays&&(typeof r.trialPeriodDays!="number"||r.trialPeriodDays<0)&&e.push("trialPeriodDays must be a non-negative number"),{isValid:e.length===0,errors:e}},j=(r,e)=>{let t={customer:"cus_",subscription:"sub_",price:"price_",product:"prod_",payment_intent:"pi_"};return r.startsWith(t[e])},fe=(r,e)=>{if(typeof r!="number")return{isValid:!1,error:"Amount must be a number"};if(r<0)return{isValid:!1,error:"Amount must be non-negative"};let i={USD:50,EUR:50,GBP:30,JPY:50,CAD:50,AUD:50}[e.toUpperCase()]||50;return r<i?{isValid:!1,error:`Amount must be at least ${i} ${e.toLowerCase()} cents`}:{isValid:!0}},Pe=r=>{let e=[],t=r.number.replace(/\s/g,"");!t||t.length<13||t.length>19?e.push("Card number must be between 13 and 19 digits"):rt(t)||e.push("Invalid card number"),(!r.expMonth||r.expMonth<1||r.expMonth>12)&&e.push("Expiration month must be between 1 and 12");let i=new Date().getFullYear();return(!r.expYear||r.expYear<i||r.expYear>i+20)&&e.push("Invalid expiration year"),r.expMonth&&r.expYear&&new Date(r.expYear,r.expMonth-1,1)<new Date&&e.push("Card has expired"),(!r.cvc||r.cvc.length<3||r.cvc.length>4)&&e.push("CVC must be 3 or 4 digits"),{isValid:e.length===0,errors:e}},rt=r=>{let e=0,t=!1;for(let i=r.length-1;i>=0;i--){let n=parseInt(r.charAt(i),10);t&&(n*=2,n>9&&(n=n%10+1)),e+=n,t=!t}return e%10===0};var V=(r,e=H,t={})=>{let{showSymbol:i=!0,showCents:n=!0,locale:o="en-US"}=t,a=e.toUpperCase(),s=["JPY","KRW","VND","CLP"].includes(a),f=s?r:r/100;if(i)try{return new Intl.NumberFormat(o,{style:"currency",currency:a,minimumFractionDigits:n&&!s?2:0,maximumFractionDigits:n&&!s?2:0}).format(f)}catch{let l=ee[a]||a,p=n&&!s?f.toFixed(2):Math.round(f).toString();return`${l}${p}`}return n&&!s?f.toFixed(2):Math.round(f).toString()},te=r=>{let e=V(r.price,r.currency),t=r.intervalCount&&r.intervalCount>1?`${r.intervalCount} ${r.interval}s`:r.interval;return`${e}/${t}`},it=r=>({active:"Active",canceled:"Canceled",past_due:"Past Due",unpaid:"Unpaid",incomplete:"Incomplete",incomplete_expired:"Incomplete (Expired)",trialing:"Trial",ended:"Ended",all:"All"})[r]||r,be=(r,e={})=>{let{format:t="medium",locale:i="en-US",timeZone:n}=e,o=typeof r=="string"||typeof r=="number"?new Date(r):r,a={timeZone:n};switch(t){case"short":a.dateStyle="short";break;case"medium":a.dateStyle="medium";break;case"long":a.dateStyle="long";break;case"full":a.dateStyle="full";break}try{return new Intl.DateTimeFormat(i,a).format(o)}catch{return o.toLocaleDateString()}},nt=(r,e={})=>{let{locale:t="en-US",numeric:i="auto"}=e,n=typeof r=="string"||typeof r=="number"?new Date(r):r,a=Math.floor((new Date().getTime()-n.getTime())/1e3);try{let s=new Intl.RelativeTimeFormat(t,{numeric:i});return Math.abs(a)<60?s.format(-a,"second"):Math.abs(a)<3600?s.format(-Math.floor(a/60),"minute"):Math.abs(a)<86400?s.format(-Math.floor(a/3600),"hour"):Math.abs(a)<2592e3?s.format(-Math.floor(a/86400),"day"):Math.abs(a)<31536e3?s.format(-Math.floor(a/2592e3),"month"):s.format(-Math.floor(a/31536e3),"year")}catch{if(Math.abs(a)<60)return"just now";if(Math.abs(a)<3600){let s=Math.floor(Math.abs(a)/60);return a<0?`in ${s} minutes`:`${s} minutes ago`}else if(Math.abs(a)<86400){let s=Math.floor(Math.abs(a)/3600);return a<0?`in ${s} hours`:`${s} hours ago`}else{let s=Math.floor(Math.abs(a)/86400);return a<0?`in ${s} days`:`${s} days ago`}}},ot=(r,e=1)=>({day:e===1?"daily":`every ${e} days`,week:e===1?"weekly":`every ${e} weeks`,month:e===1?"monthly":`every ${e} months`,year:e===1?"yearly":`every ${e} years`})[r]||r,re=r=>r===0?"No trial":r===1?"1 day trial":r<7?`${r} days trial`:r===7?"1 week trial":r<30?`${Math.floor(r/7)} weeks trial`:r===30?"1 month trial":`${Math.floor(r/30)} months trial`,st=(r,e)=>r.length<=e?r:`${r.substring(0,e-3)}...`,Se=r=>({visa:"Visa",mastercard:"Mastercard",amex:"American Express",discover:"Discover",jcb:"JCB",diners:"Diners Club",unionpay:"UnionPay"})[r.toLowerCase()]||r,at=r=>r.type==="card"&&r.card?`${Se(r.card.brand)} \u2022\u2022\u2022\u2022 ${r.card.last4}`:r.type==="bank_account"&&r.bankAccount?`${r.bankAccount.bankName||"Bank"} \u2022\u2022\u2022\u2022 ${r.bankAccount.last4}`:r.type,ie=(r,e,t={})=>{let{inclusive:i=!1,roundTo:n=2}=t,o,a,s;i?(s=r,o=r/(1+e/100),a=r-o):(o=r,a=r*(e/100),s=r+a);let f=Math.pow(10,n);return{subtotal:Math.round(o*f)/f,tax:Math.round(a*f)/f,total:Math.round(s*f)/f}},ye=r=>`${r.toFixed(2)}%`,Ee=(r,e,t=H,i={})=>{let{inclusive:n=!1,showBreakdown:o=!1,locale:a="en-US"}=i,s=ie(r,e,{inclusive:n});if(o){let f=V(s.subtotal,t,{locale:a}),l=V(s.tax,t,{locale:a}),p=V(s.total,t,{locale:a});return`${f} + ${l} tax = ${p}`}return V(s.total,t,{locale:a})};var he=r=>{let e=[],t=[];return r.stripePublishableKey?r.stripePublishableKey.startsWith("pk_")||e.push('STRIPE_PUBLISHABLE_KEY must start with "pk_"'):e.push("STRIPE_PUBLISHABLE_KEY is required"),r.environment?["development","production"].includes(r.environment)||e.push('Environment must be either "development" or "production"'):e.push("Environment must be specified (development or production)"),r.environment==="production"&&(r.stripePublishableKey?.includes("test")&&t.push("Using test keys in production environment"),r.appUrl?r.appUrl.startsWith("https://")||t.push("APP_URL should use HTTPS in production"):t.push("APP_URL should be set in production for proper redirects")),typeof window>"u"&&(r.stripeSecretKey?r.stripeSecretKey.startsWith("sk_")||e.push('STRIPE_SECRET_KEY must start with "sk_"'):t.push("STRIPE_SECRET_KEY is recommended for server-side operations"),r.stripeWebhookSecret?r.stripeWebhookSecret.startsWith("whsec_")||e.push('STRIPE_WEBHOOK_SECRET must start with "whsec_"'):t.push("STRIPE_WEBHOOK_SECRET is recommended for webhook verification")),{isValid:e.length===0,errors:e,warnings:t}},ge=()=>{let r=typeof window>"u",e={stripePublishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY||process.env.EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY||"",environment:process.env.NODE_ENV||"development",appUrl:process.env.NEXT_PUBLIC_APP_URL};return r&&(e.stripeSecretKey=process.env.STRIPE_SECRET_KEY,e.stripeWebhookSecret=process.env.STRIPE_WEBHOOK_SECRET),e},ct=()=>{let r=ge(),e=he(r);if(!e.isValid&&(console.error("\u274C Environment validation failed:"),e.errors.forEach(t=>console.error(` - ${t}`)),typeof window>"u"))throw new Error(`Environment validation failed: ${e.errors.join(", ")}`);return e.warnings.length>0&&(console.warn("\u26A0\uFE0F Environment warnings:"),e.warnings.forEach(t=>console.warn(` - ${t}`))),e},ut=()=>process.env.NODE_ENV==="development",lt=()=>process.env.NODE_ENV==="production",mt=()=>typeof window>"u",dt=()=>typeof window<"u";var K=class{config;constructor(e){this.config=e}handleError(e,t="UNKNOWN_ERROR"){if(e instanceof c)return e;let i="An unknown error occurred",n,o;return typeof e=="object"&&e!==null&&("message"in e&&typeof e.message=="string"&&(i=e.message),"code"in e&&typeof e.code=="string"&&(n=e.code),o={...e}),new c(t,i,n,o)}};var Ce=$e(require("stripe")),Y=class extends K{name="stripe";stripeClient;constructor(e){if(super(e),!e.stripeConfig?.publishableKey)throw new c("CONFIGURATION_ERROR","Stripe publishable key is missing in config.");if(!process.env.STRIPE_SECRET_KEY)throw new c("CONFIGURATION_ERROR","STRIPE_SECRET_KEY environment variable is not set.");this.stripeClient=new Ce.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 c("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(i=>({price:i.priceId,quantity:i.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 c("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 c("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(i){throw this.handleError(i,"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 i=await this.stripeClient.subscriptions.retrieve(e),n=t.items?t.items.map(a=>({id:i.items.data.find(s=>s.price?.id===a.priceId)?.id,price:a.priceId,quantity:a.quantity||1})):void 0,o=await this.stripeClient.subscriptions.update(e,{items:n,metadata:t.metadata});return this.mapStripeSubscriptionToSubscription(o)}catch(i){throw this.handleError(i,"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 G=class extends K{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 c("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(i=>i.id===e);if(!t)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t}async updateCustomer(e,t){console.log("Mock: updateCustomer",e,t);let i=this.customers.find(n=>n.id===e);if(!i)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t.email&&(i.email=t.email),t.name&&(i.name=t.name),t.phone&&(i.phone=t.phone),t.metadata&&(i.metadata={...i.metadata,...t.metadata}),i.updated=new Date,i}async deleteCustomer(e){console.log("Mock: deleteCustomer",e);let t=this.customers.length;if(this.customers=this.customers.filter(i=>i.id!==e),this.customers.length===t)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`)}async listPaymentMethods(e){console.log("Mock: listPaymentMethods",e);let t=this.customers.find(i=>i.id===e);if(!t)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t.paymentMethods||[]}async attachPaymentMethod(e,t){console.log("Mock: attachPaymentMethod",e,t);let i=this.customers.find(o=>o.id===e);if(!i)throw new c("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 i.paymentMethods.push(n),n}async detachPaymentMethod(e,t){console.log("Mock: detachPaymentMethod",e,t);let i=this.customers.find(o=>o.id===e);if(!i)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n=i.paymentMethods.length;if(i.paymentMethods=i.paymentMethods.filter(o=>o.id!==t),i.paymentMethods.length===n)throw new c("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 c("CUSTOMER_NOT_FOUND",`Mock customer ${e.customerId} not found`);let i={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(i),t.subscriptions.push(i),i}async retrieveSubscription(e){console.log("Mock: retrieveSubscription",e);let t=this.subscriptions.find(i=>i.id===e);if(!t)throw new c("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);return t}async updateSubscription(e,t){console.log("Mock: updateSubscription",e,t);let i=this.subscriptions.find(n=>n.id===e);if(!i)throw new c("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);return t.cancelAtPeriodEnd!==void 0&&(i.cancelAtPeriodEnd=t.cancelAtPeriodEnd,i.status=t.cancelAtPeriodEnd?"canceled":"active"),t.items&&(i.items=t.items.map(n=>({id:`mock_sub_item_${Math.random().toString(36).substring(7)}`,priceId:n.priceId,quantity:n.quantity||1}))),i.updated=new Date,i}async cancelSubscription(e){console.log("Mock: cancelSubscription",e);let t=this.subscriptions.find(i=>i.id===e);if(!t)throw new c("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(i=>i.id===e);if(!t)throw new c("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 i=this.customers.find(o=>o.id===e);if(!i)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n=i.subscriptions;return t&&t!=="all"&&(n=n.filter(o=>o.status===t)),n}};var R=class{static create(e){switch(e.provider){case"stripe":return new Y(e);case"paypal":throw new c("PROVIDER_NOT_CONFIGURED","PayPal provider is not yet available in this build");case"applepay":throw new c("PROVIDER_NOT_CONFIGURED","Apple Pay provider is not yet available in this build");case"mock":return new G(e);default:throw new c("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 c("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 T=require("react");var Re=require("zustand"),_e=require("zustand/middleware/immer");var ve={customer:null,subscriptions:[],activeSubscription:null,loading:!1,error:null,initialized:!1,config:null,isLoading:!1,isError:!1},Ie=(0,Re.create)()((0,_e.immer)((r,e)=>({...ve,get isLoading(){return e().loading},get isError(){return!!e().error},initialize:async t=>{r(i=>{i.loading=!0,i.error=null});try{let i;t?i=t:i=R.autodetect(),await R.create(i).initialize(),r(o=>{o.initialized=!0,o.loading=!1,o.config=i})}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to initialize payments provider.";n.error=new c("CONFIGURATION_ERROR",o),n.loading=!1}),i}},createCustomer:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).createCustomer(t);return r(o=>{o.customer=n,o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to create customer.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},retrieveCustomer:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).retrieveCustomer(t);return r(o=>{o.customer=n,o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to retrieve customer.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},createCheckoutSession:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).createCheckoutSession(t);return r(o=>{o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to create checkout session.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},retrieveCheckoutSession:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).retrieveCheckoutSession(t);return r(o=>{o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to retrieve checkout session.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},createSubscription:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).createSubscription(t);return await e().refreshSubscriptions(e().customer?.id||""),r(o=>{o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to create subscription.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},cancelSubscription:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");await R.create(e().config).cancelSubscription(t),await e().refreshSubscriptions(e().customer?.id||""),r(n=>{n.loading=!1})}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to cancel subscription.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},reactivateSubscription:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");await R.create(e().config).reactivateSubscription(t),await e().refreshSubscriptions(e().customer?.id||""),r(n=>{n.loading=!1})}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to reactivate subscription.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},updateSubscription:async(t,i)=>{r(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let o=await R.create(e().config).updateSubscription(t,i);return await e().refreshSubscriptions(e().customer?.id||""),r(a=>{a.loading=!1}),o}catch(n){throw r(o=>{let a=n instanceof Error?n.message:"Failed to update subscription.";o.error=new c("NETWORK_ERROR",a),o.loading=!1}),n}},listSubscriptions:async(t,i)=>{r(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let o=await R.create(e().config).listSubscriptions(t,i);return r(a=>{a.subscriptions=o,a.loading=!1}),o}catch(n){throw r(o=>{let a=n instanceof Error?n.message:"Failed to list subscriptions.";o.error=new c("NETWORK_ERROR",a),o.loading=!1}),n}},retrieveSubscription:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).retrieveSubscription(t);return r(o=>{o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to retrieve subscription.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},refreshCustomer:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).retrieveCustomer(t);r(o=>{o.customer=n,o.loading=!1})}catch(i){r(n=>{let o=i instanceof Error?i.message:"Failed to refresh customer.";n.error=new c("NETWORK_ERROR",o),n.loading=!1})}},refreshSubscriptions:async(t,i)=>{r(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let o=await R.create(e().config).listSubscriptions(t,i),a=o.find(s=>s.status==="active"||s.status==="trialing")||null;r(s=>{s.subscriptions=o,s.activeSubscription=a,s.loading=!1})}catch(n){r(o=>{let a=n instanceof Error?n.message:"Failed to refresh subscriptions.";o.error=new c("NETWORK_ERROR",a),o.loading=!1})}},reset:()=>{r(t=>{Object.assign(t,ve)})}})));var Oe=require("react/jsx-runtime"),we=(0,T.createContext)(void 0),Ne=({children:r,config:e,onPaymentSuccess:t,onPaymentError:i})=>{let n=Ie(),{initialize:o,initialized:a,loading:s,error:f,customer:l,subscriptions:p,activeSubscription:w}=n,m=(0,T.useRef)(t),P=(0,T.useRef)(i);(0,T.useEffect)(()=>{m.current=t},[t]),(0,T.useEffect)(()=>{P.current=i},[i]),(0,T.useEffect)(()=>{!a&&!s&&!f&&o(e).catch(v=>{console.error("PaymentsProvider initialization failed:",v),P.current&&P.current(v)})},[a,s,f,e,o]);let d={config:n.config,initialized:a,loading:s,error:f,customer:l,subscriptions:p,activeSubscription:w,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,Oe.jsx)(we.Provider,{value:d,children:r})},$=()=>{let r=(0,T.useContext)(we);if(r===void 0)throw new Error("usePaymentsContext must be used within a PaymentsProvider");return r};var E=require("react");var Te=()=>{let[r,e]=(0,E.useState)(null),[t,i]=(0,E.useState)(null),[n,o]=(0,E.useState)(!1),[a,s]=(0,E.useState)(!1),[f,l]=(0,E.useState)(null),[p,w]=(0,E.useState)(null),[m,P]=(0,E.useState)([]),d=(0,E.useCallback)(b=>{l(b),console.error("Payments error:",b)},[]),v=(0,E.useCallback)(async(b,u)=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let N=await t.listSubscriptions(b,u);P(N)}catch(N){throw d(N),N}finally{s(!1)}},[t,d]),F=(0,E.useCallback)(async b=>{s(!0),l(null);try{let u=b||R.autodetect(),N=R.create(u);e(u),i(N),o(!0)}catch(u){d(u)}finally{s(!1)}},[d]),h=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let u=await t.retrieveCustomer(b);return w(u),u}catch(u){throw d(u),u}finally{s(!1)}},[t,d]),k=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let u=await t.createCustomer(b);return w(u),u}catch(u){throw d(u),u}finally{s(!1)}},[t,d]),W=(0,E.useCallback)(async b=>{if(!t||!p)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let u=await t.createSubscription({customerId:p.id,items:[{priceId:b.priceId,quantity:b.quantity}]});return await v(p.id),u}catch(u){throw d(u),u}finally{s(!1)}},[t,p,d,v]),O=(0,E.useCallback)(async(b,u)=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let N=await t.listSubscriptions(b,u);return P(N),N}catch(N){throw d(N),N}finally{s(!1)}},[t,d]),g=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let u=await t.retrieveSubscription(b);return p?.id&&await v(p.id),u}catch(u){throw d(u),u}finally{s(!1)}},[t,p,d,v]),A=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{return await t.createCheckoutSession(b)}catch(u){throw d(u),u}finally{s(!1)}},[t,d]),B=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{return await t.retrieveCheckoutSession(b)}catch(u){throw d(u),u}finally{s(!1)}},[t,d]),D=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{await t.cancelSubscription(b),p?.id&&await v(p.id)}catch(u){throw d(u),u}finally{s(!1)}},[t,p,d,v]),I=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{await t.reactivateSubscription(b),p?.id&&await v(p.id)}catch(u){throw d(u),u}finally{s(!1)}},[t,p,d,v]),L=(0,E.useCallback)(async(b,u)=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let N=await t.updateSubscription(b,u);return p?.id&&await v(p.id),N}catch(N){throw d(N),N}finally{s(!1)}},[t,p,d,v]),z=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let u=await t.retrieveCustomer(b);w(u)}catch(u){throw d(u),u}finally{s(!1)}},[t,d]),Q=(0,E.useCallback)(()=>{e(null),i(null),o(!1),s(!1),l(null),w(null),P([])},[]),Ae=m.find(b=>b.status==="active"||b.status==="trialing")||null;return(0,E.useEffect)(()=>{},[]),{config:r,provider:t,initialized:n,loading:a,error:f,isLoading:a,isError:!!f,customer:p,subscriptions:m,activeSubscription:Ae,initialize:F,createCustomer:k,retrieveCustomer:h,createCheckoutSession:A,retrieveCheckoutSession:B,createSubscription:W,cancelSubscription:D,reactivateSubscription:I,listSubscriptions:O,retrieveSubscription:g,updateSubscription:L,refreshCustomer:z,refreshSubscriptions:v,reset:Q}};var De=require("react"),ke=require("@stripe/react-stripe-js");var U=require("react/jsx-runtime"),Ue=({priceId:r,customerId:e,customerEmail:t,successUrl:i=typeof window<"u"?`${window.location.origin}/success`:"/success",cancelUrl:n=typeof window<"u"?`${window.location.origin}/cancel`:"/cancel",children:o,className:a="",disabled:s=!1,allowPromotionCodes:f=!0,billingAddressCollection:l="auto",metadata:p,trialPeriodDays:w,onSuccess:m,onError:P,onLoading:d})=>{let v=(0,ke.useStripe)(),{initialized:F}=$(),[h,k]=(0,De.useState)(!1);return(0,U.jsx)("button",{onClick:async()=>{if(!v){let g=y.STRIPE_NOT_LOADED;P?.(g),console.error(g);return}if(!F){let g=y.PROVIDER_NOT_CONFIGURED;P?.(g),console.error(g);return}if(!j(r,"price")){let g=y.INVALID_PRICE_ID;P?.(g),console.error(g);return}if(e&&!j(e,"customer")){let g=y.INVALID_CUSTOMER_ID;P?.(g),console.error(g);return}k(!0),d?.(!0);try{let g=await fetch("/api/payments/create-checkout-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priceId:r,customerId:e,customerEmail:t,successUrl:i,cancelUrl:n,allowPromotionCodes:f,billingAddressCollection:l,metadata:p,trialPeriodDays:w})});if(!g.ok){let D=await g.json().catch(()=>({error:"Network error"}));throw new Error(D.error||y.CHECKOUT_FAILED)}let{sessionId:A}=await g.json();if(!A)throw new Error("No session ID returned from server");let B=await v.redirectToCheckout({sessionId:A});if(B.error)throw new Error(B.error.message||y.CHECKOUT_FAILED);m?.()}catch(g){let A=g instanceof Error?g.message:y.CHECKOUT_FAILED;P?.(A),console.error("Checkout error:",g)}finally{k(!1),d?.(!1)}},disabled:!v||h||s||!F,className:`
2
+ inline-flex items-center justify-center px-4 py-2
3
+ border border-transparent text-sm font-medium rounded-md
4
+ text-white bg-blue-600 hover:bg-blue-700
5
+ focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500
6
+ disabled:opacity-50 disabled:cursor-not-allowed
7
+ transition-colors duration-200
8
+ ${a}
9
+ `,"aria-label":typeof o=="string"?o:"Checkout",children:h?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)("svg",{className:"animate-spin -ml-1 mr-3 h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[(0,U.jsx)("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),(0,U.jsx)("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Processing..."]}):o})};var C=require("react/jsx-runtime"),ne=({plans:r,customerId:e,customerEmail:t,successUrl:i,cancelUrl:n,className:o="",onCheckoutSuccess:a,onCheckoutError:s,showFeatures:f=!0,showTrialInfo:l=!0,layout:p="grid",maxColumns:w=3})=>{if(!r||r.length===0)return(0,C.jsx)("div",{className:"text-center py-8 text-gray-500",children:"No pricing plans available"});let m=Math.min(r.length,w),P=p==="grid"?`grid gap-6 ${m===1?"grid-cols-1":m===2?"grid-cols-1 md:grid-cols-2":"grid-cols-1 md:grid-cols-2 lg:grid-cols-3"}`:"space-y-6";return(0,C.jsx)("div",{className:`pricing-table ${o}`,children:(0,C.jsx)("div",{className:P,children:r.map(d=>(0,C.jsx)(pt,{plan:d,customerId:e,customerEmail:t,successUrl:i,cancelUrl:n,onCheckoutSuccess:()=>a?.(d),onCheckoutError:v=>s?.(d,v),showFeatures:f,showTrialInfo:l},d.id))})})},pt=({plan:r,customerId:e,customerEmail:t,successUrl:i,cancelUrl:n,onCheckoutSuccess:o,onCheckoutError:a,showFeatures:s=!0,showTrialInfo:f=!0})=>{let l=r.popular;return(0,C.jsxs)("div",{className:`
10
+ relative bg-white rounded-lg shadow-lg overflow-hidden
11
+ ${l?"ring-2 ring-blue-500 ring-opacity-50":"border border-gray-200"}
12
+ transition-transform duration-200 hover:scale-105
13
+ `,children:[l&&(0,C.jsx)("div",{className:"absolute top-0 left-0 right-0 bg-blue-500 text-white text-center py-2 text-sm font-medium",children:"Most Popular"}),(0,C.jsxs)("div",{className:`p-6 ${l?"pt-12":""}`,children:[(0,C.jsxs)("div",{className:"text-center mb-6",children:[(0,C.jsx)("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:r.name}),r.description&&(0,C.jsx)("p",{className:"text-gray-600 text-sm mb-4",children:r.description}),(0,C.jsx)("div",{className:"mb-4",children:(0,C.jsx)("span",{className:"text-3xl font-bold text-gray-900",children:te(r)})}),f&&r.trialPeriodDays&&r.trialPeriodDays>0&&(0,C.jsx)("div",{className:"text-sm text-green-600 font-medium",children:re(r.trialPeriodDays)})]}),s&&r.features&&r.features.length>0&&(0,C.jsx)("div",{className:"mb-6",children:(0,C.jsx)("ul",{className:"space-y-3",children:r.features.map((p,w)=>(0,C.jsxs)("li",{className:"flex items-start",children:[(0,C.jsx)("svg",{className:"flex-shrink-0 w-5 h-5 text-green-500 mt-0.5 mr-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,C.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),(0,C.jsx)("span",{className:"text-gray-700 text-sm",children:p})]},w))})}),(0,C.jsx)("div",{className:"mt-6",children:(0,C.jsx)(Ue,{priceId:r.stripePriceId,customerId:e,customerEmail:t,successUrl:i,cancelUrl:n,trialPeriodDays:r.trialPeriodDays,metadata:r.metadata,onSuccess:o,onError:a,className:`
14
+ w-full justify-center py-3 px-4 text-base font-medium
15
+ ${l?"bg-blue-600 hover:bg-blue-700 text-white":"bg-gray-100 hover:bg-gray-200 text-gray-900 border border-gray-300"}
16
+ `,children:"Get Started"})})]})]})};var J=require("react"),x=require("@stripe/react-stripe-js");var _=require("react/jsx-runtime"),Z=({clientSecret:r,customerId:e,customerEmail:t,amount:i,currency:n="usd",description:o,metadata:a,onSuccess:s,onError:f,onLoading:l,className:p="",showBillingDetails:w=!0,elementType:m="payment"})=>{let P=(0,x.useStripe)(),d=(0,x.useElements)(),{initialized:v}=$(),[F,h]=(0,J.useState)(!1),[k,W]=(0,J.useState)(t||""),[O,g]=(0,J.useState)({name:"",email:t||"",phone:"",address:{line1:"",line2:"",city:"",state:"",postal_code:"",country:"US"}}),A=async D=>{if(D.preventDefault(),!P||!d){let I=y.STRIPE_NOT_LOADED;f?.(I);return}if(!v){let I=y.PROVIDER_NOT_CONFIGURED;f?.(I);return}if(w&&k&&!X(k)){f?.("Please enter a valid email address");return}h(!0),l?.(!0);try{let I;if(m==="payment"&&r)I=await P.confirmPayment({elements:d,confirmParams:{return_url:window.location.href,receipt_email:k||O.email},redirect:"if_required"});else if(m==="card"){let L=d.getElement(x.CardElement);if(!L)throw new Error("Card element not found");if(r)I=await P.confirmCardPayment(r,{payment_method:{card:L,billing_details:w?{name:O.name||void 0,email:O.email||void 0,phone:O.phone||void 0,address:O.address.line1?O.address:void 0}:void 0}});else if(i){let z=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({amount:i,currency:n,customerId:e,description:o,metadata:a})});if(!z.ok)throw new Error("Failed to create payment intent");let{client_secret:Q}=await z.json();I=await P.confirmCardPayment(Q,{payment_method:{card:L,billing_details:w?{name:O.name||void 0,email:O.email||void 0,phone:O.phone||void 0,address:O.address.line1?O.address:void 0}:void 0}})}else throw new Error("Either clientSecret or amount is required")}if(I?.error)throw new Error(I.error.message||y.PAYMENT_FAILED);I?.paymentIntent?.status==="succeeded"&&s?.(I.paymentIntent)}catch(I){let L=I instanceof Error?I.message:y.PAYMENT_FAILED;f?.(L),console.error("Payment error:",I)}finally{h(!1),l?.(!1)}},B={style:{base:{fontSize:"16px",color:"#424770","::placeholder":{color:"#aab7c4"}},invalid:{color:"#9e2146"}}};return(0,_.jsxs)("form",{onSubmit:A,className:`payment-form ${p}`,children:[w&&(0,_.jsxs)("div",{className:"mb-6 space-y-4",children:[(0,_.jsxs)("div",{children:[(0,_.jsx)("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-1",children:"Email"}),(0,_.jsx)("input",{type:"email",id:"email",value:k,onChange:D=>{W(D.target.value),g(I=>({...I,email:D.target.value}))},className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"your@email.com",required:!0})]}),(0,_.jsxs)("div",{children:[(0,_.jsx)("label",{htmlFor:"name",className:"block text-sm font-medium text-gray-700 mb-1",children:"Full Name"}),(0,_.jsx)("input",{type:"text",id:"name",value:O.name,onChange:D=>g(I=>({...I,name:D.target.value})),className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"John Doe"})]})]}),(0,_.jsxs)("div",{className:"mb-6",children:[(0,_.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Payment Information"}),(0,_.jsx)("div",{className:"p-3 border border-gray-300 rounded-md",children:m==="payment"?(0,_.jsx)(x.PaymentElement,{}):(0,_.jsx)(x.CardElement,{options:B})})]}),(0,_.jsx)("button",{type:"submit",disabled:!P||F,className:"w-full bg-blue-600 text-white py-3 px-4 rounded-md font-medium hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200",children:F?(0,_.jsxs)(_.Fragment,{children:[(0,_.jsxs)("svg",{className:"animate-spin -ml-1 mr-3 h-4 w-4 text-white inline",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[(0,_.jsx)("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),(0,_.jsx)("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Processing..."]}):`Pay ${i?`$${(i/100).toFixed(2)}`:""}`})]})};var xe=require("react"),S=require("react/jsx-runtime"),oe=({subscription:r,onSubscriptionChange:e,onCancel:t,className:i=""})=>{let[n,o]=(0,xe.useState)(!1),a=P=>new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(P),s=(P,d)=>new Intl.NumberFormat("en-US",{style:"currency",currency:d.toUpperCase()}).format(P/100),f=P=>{switch(P){case"active":return"#10b981";case"canceled":return"#ef4444";case"past_due":return"#f59e0b";case"unpaid":return"#ef4444";case"incomplete":return"#6b7280";default:return"#6b7280"}},l=P=>{switch(P){case"active":return"Active";case"canceled":return"Canceled";case"past_due":return"Past Due";case"unpaid":return"Unpaid";case"incomplete":return"Incomplete";default:return P}},p=async P=>{o(!0);try{await e(P)}finally{o(!1)}},w=async()=>{o(!0);try{await t()}finally{o(!1)}},m={container:{width:"100%"},card:{border:"1px solid #e5e7eb",borderRadius:"12px",padding:"2rem",background:"white",boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)"},header:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"1.5rem"},info:{flex:1},planName:{fontSize:"1.5rem",fontWeight:700,color:"#1f2937",margin:"0 0 0.5rem 0"},details:{display:"flex",alignItems:"baseline",gap:"0.25rem"},amount:{fontSize:"1.25rem",fontWeight:600,color:"#3b82f6"},interval:{fontSize:"1rem",color:"#6b7280"},statusBadge:{padding:"0.5rem 1rem",borderRadius:"20px",color:"white",fontSize:"0.875rem",fontWeight:600},dates:{marginBottom:"2rem",padding:"1rem",background:"#f9fafb",borderRadius:"8px"},dateLabel:{fontSize:"0.875rem",color:"#6b7280",fontWeight:500},dateValue:{fontSize:"0.875rem",color:"#1f2937"},cancellationNotice:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:"1rem",padding:"0.75rem",background:"#fef3c7",borderRadius:"6px",fontSize:"0.875rem",color:"#92400e"},actions:{display:"flex",gap:"1rem",flexWrap:"wrap"},button:{padding:"0.75rem 1.5rem",border:"none",borderRadius:"8px",fontWeight:600,fontSize:"0.875rem",cursor:"pointer",transition:"all 0.3s ease",flex:1,minWidth:"120px"},buttonPrimary:{background:"#3b82f6",color:"white"},buttonSecondary:{background:"#f3f4f6",color:"#374151",border:"1px solid #d1d5db"},buttonDanger:{background:"#ef4444",color:"white"},buttonDisabled:{opacity:.6,cursor:"not-allowed"}};return(0,S.jsx)("div",{style:m.container,className:i,children:(0,S.jsxs)("div",{style:m.card,children:[(0,S.jsxs)("div",{style:m.header,children:[(0,S.jsxs)("div",{style:m.info,children:[(0,S.jsx)("h3",{style:m.planName,children:r.planName}),(0,S.jsxs)("div",{style:m.details,children:[(0,S.jsx)("span",{style:m.amount,children:s(r.amount,r.currency)}),(0,S.jsxs)("span",{style:m.interval,children:["/",r.interval]})]})]}),(0,S.jsx)("div",{children:(0,S.jsx)("span",{style:{...m.statusBadge,backgroundColor:f(r.status)},children:l(r.status)})})]}),(0,S.jsxs)("div",{style:m.dates,children:[(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{style:m.dateLabel,children:"Current period:"}),(0,S.jsxs)("div",{style:m.dateValue,children:[a(r.currentPeriodStart)," -"," ",a(r.currentPeriodEnd)]})]}),r.cancelAtPeriodEnd&&(0,S.jsxs)("div",{style:m.cancellationNotice,children:[(0,S.jsx)("span",{children:"\u26A0\uFE0F"}),(0,S.jsx)("span",{children:"Your subscription will be canceled at the end of the current period."})]})]}),(0,S.jsxs)("div",{style:m.actions,children:[r.status==="active"&&!r.cancelAtPeriodEnd&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)("button",{style:{...m.button,...m.buttonSecondary,...n?m.buttonDisabled:{}},onClick:()=>p("upgrade"),disabled:n,children:n?"Loading...":"Upgrade Plan"}),(0,S.jsx)("button",{style:{...m.button,...m.buttonSecondary,...n?m.buttonDisabled:{}},onClick:()=>p("downgrade"),disabled:n,children:n?"Loading...":"Downgrade Plan"}),(0,S.jsx)("button",{style:{...m.button,...m.buttonDanger,...n?m.buttonDisabled:{}},onClick:w,disabled:n,children:n?"Loading...":"Cancel Subscription"})]}),r.status==="active"&&r.cancelAtPeriodEnd&&(0,S.jsx)("button",{style:{...m.button,...m.buttonPrimary,...n?m.buttonDisabled:{}},onClick:()=>p("resume"),disabled:n,children:n?"Loading...":"Resume Subscription"}),r.status==="past_due"&&(0,S.jsx)("button",{style:{...m.button,...m.buttonPrimary,...n?m.buttonDisabled:{}},onClick:()=>p("resume"),disabled:n,children:n?"Loading...":"Update Payment Method"})]})]})})};0&&(module.exports={ACTIVE_STATUSES,BILLING_INTERVALS,CHECKOUT_MODE,CURRENCY_SYMBOLS,DEFAULT_CURRENCY,ERROR_MESSAGES,INACTIVE_STATUSES,INCOMPLETE_STATUSES,INVOICE_STATUS,MockPaymentProvider,PAYMENT_METHODS,PROBLEMATIC_STATUSES,PaymentErrorType,PaymentProviderFactory,PaymentsError,PaymentsProvider,PricingTable,STRIPE_API_VERSION,SUBSCRIPTION_STATUS,StripePaymentForm,StripePaymentProvider,SubscriptionManager,SubscriptionStatus,WEBHOOK_EVENTS,calculateTax,formatAmountWithTax,formatBillingInterval,formatCardBrand,formatCurrency,formatDate,formatPaymentMethodDisplay,formatPricingPlan,formatRelativeTime,formatSubscriptionStatus,formatTaxRate,formatTrialPeriod,getEnvironmentConfig,isActiveSubscription,isClient,isDevelopment,isInactiveSubscription,isIncompleteSubscription,isProblematicSubscription,isProduction,isServer,truncateText,usePayments,usePaymentsContext,validateAmount,validateCard,validateCurrentEnvironment,validateEmail,validateEnvironment,validatePaymentsConfig,validatePhoneNumber,validatePricingPlan,validateStripeId});
2
17
  //# sourceMappingURL=index.js.map