tf-checkout-react-native 1.0.45 → 2.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +150 -3340
- package/dist/index.d.mts +3810 -0
- package/dist/index.d.ts +3810 -0
- package/dist/index.js +8348 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +8348 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +31 -57
- package/src/CardInput.tsx +49 -0
- package/src/EmbeddedCheckout.tsx +323 -0
- package/src/auth/AuthModal.tsx +221 -0
- package/src/auth/ForgotPasswordForm.tsx +98 -0
- package/src/auth/LoginForm.tsx +99 -0
- package/src/auth/PasswordInput.tsx +45 -0
- package/src/auth/RegisterForm.tsx +247 -0
- package/src/auth/ResetPasswordForm.tsx +112 -0
- package/src/auth/index.ts +7 -0
- package/src/configure.ts +26 -0
- package/src/confirmer.ts +180 -0
- package/src/index.tsx +25 -227
- package/src/instance.ts +13 -0
- package/src/sections/AddOns.tsx +335 -0
- package/src/sections/BillingInfo.tsx +770 -0
- package/src/sections/Confirmation.tsx +143 -0
- package/src/sections/IDVerification.tsx +77 -0
- package/src/sections/OrderSummary.tsx +116 -0
- package/src/sections/Payment.tsx +417 -0
- package/src/sections/Tickets.tsx +680 -0
- package/src/sections/billing/BillingAddressFields.tsx +126 -0
- package/src/sections/billing/BuyerField.tsx +78 -0
- package/src/sections/billing/TicketHoldersCard.tsx +119 -0
- package/src/sections/billing/types.ts +10 -0
- package/src/sections/index.ts +8 -0
- package/src/storage.ts +27 -0
- package/src/ui/CheckoutProvider.tsx +140 -0
- package/src/ui/CustomFields.tsx +176 -0
- package/src/ui/Field.tsx +171 -0
- package/src/ui/InstallmentPicker.tsx +158 -0
- package/src/ui/PaymentMethods.tsx +177 -0
- package/src/ui/QuantitySelect.tsx +103 -0
- package/src/ui/Select.tsx +151 -0
- package/src/ui/Timer.tsx +69 -0
- package/src/ui/TimerBanner.tsx +95 -0
- package/src/ui/index.ts +17 -0
- package/src/ui/primitives.tsx +191 -0
- package/src/ui/theme.ts +89 -0
- package/src/useCheckout.ts +35 -0
- package/lib/brand-DA2IARBI.png +0 -0
- package/lib/ic_check-FLIJQ3BY.png +0 -0
- package/lib/ic_clock-BZ4Z7PIP.png +0 -0
- package/lib/ic_copy-VWMA4B7X.png +0 -0
- package/lib/ic_dropdown-BCS3QDNJ.png +0 -0
- package/lib/ic_error-KDEZUPSN.png +0 -0
- package/lib/ic_eye-WGXVXVAN.png +0 -0
- package/lib/ic_eye_off-XTCE6XSO.png +0 -0
- package/lib/ic_more-LZWKYCDU.png +0 -0
- package/lib/ic_next-LCNIGEDM.png +0 -0
- package/lib/index.js +0 -18176
- package/lib/index.js.map +0 -1
- package/lib/index.mjs +0 -18263
- package/lib/index.mjs.map +0 -1
- package/lib/typescript/package.json +0 -1
- package/lib/typescript/src/api/ApiClient.d.ts +0 -49
- package/lib/typescript/src/api/ApiClient.d.ts.map +0 -1
- package/lib/typescript/src/api/Constants.d.ts +0 -11
- package/lib/typescript/src/api/Constants.d.ts.map +0 -1
- package/lib/typescript/src/api/ErrorHandler.d.ts +0 -12
- package/lib/typescript/src/api/ErrorHandler.d.ts.map +0 -1
- package/lib/typescript/src/api/api.types.d.ts +0 -8
- package/lib/typescript/src/api/api.types.d.ts.map +0 -1
- package/lib/typescript/src/api/types.d.ts +0 -518
- package/lib/typescript/src/api/types.d.ts.map +0 -1
- package/lib/typescript/src/apiv2/index.d.ts +0 -3
- package/lib/typescript/src/apiv2/index.d.ts.map +0 -1
- package/lib/typescript/src/common/query.types.d.ts +0 -3
- package/lib/typescript/src/common/query.types.d.ts.map +0 -1
- package/lib/typescript/src/components/bottomSheetModal/BottomSheetModal.d.ts +0 -8
- package/lib/typescript/src/components/bottomSheetModal/BottomSheetModal.d.ts.map +0 -1
- package/lib/typescript/src/components/bottomSheetModal/BottomSheetModalStyles.d.ts +0 -39
- package/lib/typescript/src/components/bottomSheetModal/BottomSheetModalStyles.d.ts.map +0 -1
- package/lib/typescript/src/components/bottomSheetModal/BottomSheetModalTypes.d.ts +0 -23
- package/lib/typescript/src/components/bottomSheetModal/BottomSheetModalTypes.d.ts.map +0 -1
- package/lib/typescript/src/components/button/Button.d.ts +0 -5
- package/lib/typescript/src/components/button/Button.d.ts.map +0 -1
- package/lib/typescript/src/components/button/styles.d.ts +0 -28
- package/lib/typescript/src/components/button/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/button/types.d.ts +0 -15
- package/lib/typescript/src/components/button/types.d.ts.map +0 -1
- package/lib/typescript/src/components/cartTimer/CartTimer.d.ts +0 -5
- package/lib/typescript/src/components/cartTimer/CartTimer.d.ts.map +0 -1
- package/lib/typescript/src/components/cartTimer/styles.d.ts +0 -47
- package/lib/typescript/src/components/cartTimer/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/cartTimer/types.d.ts +0 -19
- package/lib/typescript/src/components/cartTimer/types.d.ts.map +0 -1
- package/lib/typescript/src/components/checkbox/Checkbox.d.ts +0 -4
- package/lib/typescript/src/components/checkbox/Checkbox.d.ts.map +0 -1
- package/lib/typescript/src/components/checkbox/styles.d.ts +0 -39
- package/lib/typescript/src/components/checkbox/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/checkbox/types.d.ts +0 -22
- package/lib/typescript/src/components/checkbox/types.d.ts.map +0 -1
- package/lib/typescript/src/components/datePicker/DatePicker.d.ts +0 -4
- package/lib/typescript/src/components/datePicker/DatePicker.d.ts.map +0 -1
- package/lib/typescript/src/components/datePicker/styles.d.ts +0 -35
- package/lib/typescript/src/components/datePicker/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/datePicker/types.d.ts +0 -20
- package/lib/typescript/src/components/datePicker/types.d.ts.map +0 -1
- package/lib/typescript/src/components/dropdown/Dropdown.d.ts +0 -4
- package/lib/typescript/src/components/dropdown/Dropdown.d.ts.map +0 -1
- package/lib/typescript/src/components/dropdown/DropdownListItem.d.ts +0 -4
- package/lib/typescript/src/components/dropdown/DropdownListItem.d.ts.map +0 -1
- package/lib/typescript/src/components/dropdown/styles.d.ts +0 -85
- package/lib/typescript/src/components/dropdown/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/dropdown/types.d.ts +0 -35
- package/lib/typescript/src/components/dropdown/types.d.ts.map +0 -1
- package/lib/typescript/src/components/dropdownMaterial/DropdownMaterial.d.ts +0 -4
- package/lib/typescript/src/components/dropdownMaterial/DropdownMaterial.d.ts.map +0 -1
- package/lib/typescript/src/components/dropdownMaterial/styles.d.ts +0 -79
- package/lib/typescript/src/components/dropdownMaterial/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/dropdownMaterial/types.d.ts +0 -22
- package/lib/typescript/src/components/dropdownMaterial/types.d.ts.map +0 -1
- package/lib/typescript/src/components/enterPassword/EnterPassword.d.ts +0 -5
- package/lib/typescript/src/components/enterPassword/EnterPassword.d.ts.map +0 -1
- package/lib/typescript/src/components/enterPassword/styles.d.ts +0 -21
- package/lib/typescript/src/components/enterPassword/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/enterPassword/types.d.ts +0 -24
- package/lib/typescript/src/components/enterPassword/types.d.ts.map +0 -1
- package/lib/typescript/src/components/formField/FormField.d.ts +0 -4
- package/lib/typescript/src/components/formField/FormField.d.ts.map +0 -1
- package/lib/typescript/src/components/formField/styles.d.ts +0 -35
- package/lib/typescript/src/components/formField/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/formField/types.d.ts +0 -48
- package/lib/typescript/src/components/formField/types.d.ts.map +0 -1
- package/lib/typescript/src/components/index.d.ts +0 -21
- package/lib/typescript/src/components/index.d.ts.map +0 -1
- package/lib/typescript/src/components/input/Input.d.ts +0 -4
- package/lib/typescript/src/components/input/Input.d.ts.map +0 -1
- package/lib/typescript/src/components/input/styles.d.ts +0 -47
- package/lib/typescript/src/components/input/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/input/types.d.ts +0 -28
- package/lib/typescript/src/components/input/types.d.ts.map +0 -1
- package/lib/typescript/src/components/loading/Loading.d.ts +0 -4
- package/lib/typescript/src/components/loading/Loading.d.ts.map +0 -1
- package/lib/typescript/src/components/loading/styles.d.ts +0 -30
- package/lib/typescript/src/components/loading/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/loading/types.d.ts +0 -15
- package/lib/typescript/src/components/loading/types.d.ts.map +0 -1
- package/lib/typescript/src/components/loggedIn/LoggedIn.d.ts +0 -5
- package/lib/typescript/src/components/loggedIn/LoggedIn.d.ts.map +0 -1
- package/lib/typescript/src/components/loggedIn/styles.d.ts +0 -9
- package/lib/typescript/src/components/loggedIn/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/loggedIn/types.d.ts +0 -24
- package/lib/typescript/src/components/loggedIn/types.d.ts.map +0 -1
- package/lib/typescript/src/components/login/Login.d.ts +0 -5
- package/lib/typescript/src/components/login/Login.d.ts.map +0 -1
- package/lib/typescript/src/components/login/LoginView.d.ts +0 -5
- package/lib/typescript/src/components/login/LoginView.d.ts.map +0 -1
- package/lib/typescript/src/components/login/components/LoginForm.d.ts +0 -5
- package/lib/typescript/src/components/login/components/LoginForm.d.ts.map +0 -1
- package/lib/typescript/src/components/login/components/types.d.ts +0 -19
- package/lib/typescript/src/components/login/components/types.d.ts.map +0 -1
- package/lib/typescript/src/components/login/styles.d.ts +0 -62
- package/lib/typescript/src/components/login/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/login/types.d.ts +0 -144
- package/lib/typescript/src/components/login/types.d.ts.map +0 -1
- package/lib/typescript/src/components/phoneInput/PhoneInput.d.ts +0 -5
- package/lib/typescript/src/components/phoneInput/PhoneInput.d.ts.map +0 -1
- package/lib/typescript/src/components/phoneInput/styles.d.ts +0 -29
- package/lib/typescript/src/components/phoneInput/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/phoneInput/types.d.ts +0 -31
- package/lib/typescript/src/components/phoneInput/types.d.ts.map +0 -1
- package/lib/typescript/src/components/promoCode/PromoCode.d.ts +0 -5
- package/lib/typescript/src/components/promoCode/PromoCode.d.ts.map +0 -1
- package/lib/typescript/src/components/promoCode/styles.d.ts +0 -61
- package/lib/typescript/src/components/promoCode/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/promoCode/types.d.ts +0 -36
- package/lib/typescript/src/components/promoCode/types.d.ts.map +0 -1
- package/lib/typescript/src/components/radioButton/RadioButton.d.ts +0 -5
- package/lib/typescript/src/components/radioButton/RadioButton.d.ts.map +0 -1
- package/lib/typescript/src/components/radioButton/styles.d.ts +0 -25
- package/lib/typescript/src/components/radioButton/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/radioButton/types.d.ts +0 -16
- package/lib/typescript/src/components/radioButton/types.d.ts.map +0 -1
- package/lib/typescript/src/components/radioGroup/RadioGroup.d.ts +0 -4
- package/lib/typescript/src/components/radioGroup/RadioGroup.d.ts.map +0 -1
- package/lib/typescript/src/components/radioGroup/index.d.ts +0 -4
- package/lib/typescript/src/components/radioGroup/index.d.ts.map +0 -1
- package/lib/typescript/src/components/radioGroup/types.d.ts +0 -24
- package/lib/typescript/src/components/radioGroup/types.d.ts.map +0 -1
- package/lib/typescript/src/components/restorePassword/RestorePassword.d.ts +0 -5
- package/lib/typescript/src/components/restorePassword/RestorePassword.d.ts.map +0 -1
- package/lib/typescript/src/components/restorePassword/ResultDialog.d.ts +0 -5
- package/lib/typescript/src/components/restorePassword/ResultDialog.d.ts.map +0 -1
- package/lib/typescript/src/components/restorePassword/styles.d.ts +0 -34
- package/lib/typescript/src/components/restorePassword/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/restorePassword/types.d.ts +0 -49
- package/lib/typescript/src/components/restorePassword/types.d.ts.map +0 -1
- package/lib/typescript/src/components/separator/Separator.d.ts +0 -4
- package/lib/typescript/src/components/separator/Separator.d.ts.map +0 -1
- package/lib/typescript/src/components/separator/types.d.ts +0 -9
- package/lib/typescript/src/components/separator/types.d.ts.map +0 -1
- package/lib/typescript/src/components/stripePayment/StripePayment.d.ts +0 -5
- package/lib/typescript/src/components/stripePayment/StripePayment.d.ts.map +0 -1
- package/lib/typescript/src/components/stripePayment/styles.d.ts +0 -7
- package/lib/typescript/src/components/stripePayment/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/stripePayment/types.d.ts +0 -14
- package/lib/typescript/src/components/stripePayment/types.d.ts.map +0 -1
- package/lib/typescript/src/components/waitingList/WaitingList.d.ts +0 -6
- package/lib/typescript/src/components/waitingList/WaitingList.d.ts.map +0 -1
- package/lib/typescript/src/components/waitingList/WaitingListView.d.ts +0 -5
- package/lib/typescript/src/components/waitingList/WaitingListView.d.ts.map +0 -1
- package/lib/typescript/src/components/waitingList/styles.d.ts +0 -9
- package/lib/typescript/src/components/waitingList/styles.d.ts.map +0 -1
- package/lib/typescript/src/components/waitingList/types.d.ts +0 -59
- package/lib/typescript/src/components/waitingList/types.d.ts.map +0 -1
- package/lib/typescript/src/containers/billingInfo/Billing.d.ts +0 -6
- package/lib/typescript/src/containers/billingInfo/Billing.d.ts.map +0 -1
- package/lib/typescript/src/containers/billingInfo/styles.d.ts +0 -61
- package/lib/typescript/src/containers/billingInfo/styles.d.ts.map +0 -1
- package/lib/typescript/src/containers/billingInfo/types.d.ts +0 -160
- package/lib/typescript/src/containers/billingInfo/types.d.ts.map +0 -1
- package/lib/typescript/src/containers/checkout/Checkout.d.ts +0 -7
- package/lib/typescript/src/containers/checkout/Checkout.d.ts.map +0 -1
- package/lib/typescript/src/containers/checkout/CheckoutData.d.ts +0 -3
- package/lib/typescript/src/containers/checkout/CheckoutData.d.ts.map +0 -1
- package/lib/typescript/src/containers/checkout/components/Conditions.d.ts +0 -4
- package/lib/typescript/src/containers/checkout/components/Conditions.d.ts.map +0 -1
- package/lib/typescript/src/containers/checkout/components/OrderReview.d.ts +0 -4
- package/lib/typescript/src/containers/checkout/components/OrderReview.d.ts.map +0 -1
- package/lib/typescript/src/containers/checkout/components/styles.d.ts +0 -26
- package/lib/typescript/src/containers/checkout/components/styles.d.ts.map +0 -1
- package/lib/typescript/src/containers/checkout/styles.d.ts +0 -42
- package/lib/typescript/src/containers/checkout/styles.d.ts.map +0 -1
- package/lib/typescript/src/containers/checkout/types.d.ts +0 -126
- package/lib/typescript/src/containers/checkout/types.d.ts.map +0 -1
- package/lib/typescript/src/containers/index.d.ts +0 -9
- package/lib/typescript/src/containers/index.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrderDetails/MyOrderDetails.d.ts +0 -6
- package/lib/typescript/src/containers/myOrderDetails/MyOrderDetails.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrderDetails/MyOrderDetailsView.d.ts +0 -5
- package/lib/typescript/src/containers/myOrderDetails/MyOrderDetailsView.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrderDetails/components/Notification.d.ts +0 -15
- package/lib/typescript/src/containers/myOrderDetails/components/Notification.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrderDetails/components/OrderListItem.d.ts +0 -3
- package/lib/typescript/src/containers/myOrderDetails/components/OrderListItem.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrderDetails/components/TicketActions/TicketActions.d.ts +0 -5
- package/lib/typescript/src/containers/myOrderDetails/components/TicketActions/TicketActions.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrderDetails/components/TicketActions/TicketActionsTypes.d.ts +0 -30
- package/lib/typescript/src/containers/myOrderDetails/components/TicketActions/TicketActionsTypes.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrderDetails/components/TicketListItem/TicketListItem.d.ts +0 -8
- package/lib/typescript/src/containers/myOrderDetails/components/TicketListItem/TicketListItem.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrderDetails/components/TicketListItem/TicketListItemStyles.d.ts +0 -33
- package/lib/typescript/src/containers/myOrderDetails/components/TicketListItem/TicketListItemStyles.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrderDetails/components/TicketListItem/TicketListItemTypes.d.ts +0 -30
- package/lib/typescript/src/containers/myOrderDetails/components/TicketListItem/TicketListItemTypes.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrderDetails/components/styles.d.ts +0 -39
- package/lib/typescript/src/containers/myOrderDetails/components/styles.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrderDetails/styles.d.ts +0 -55
- package/lib/typescript/src/containers/myOrderDetails/styles.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrderDetails/types.d.ts +0 -126
- package/lib/typescript/src/containers/myOrderDetails/types.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrders/MyOrders.d.ts +0 -6
- package/lib/typescript/src/containers/myOrders/MyOrders.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrders/MyOrdersView.d.ts +0 -5
- package/lib/typescript/src/containers/myOrders/MyOrdersView.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrders/components/OrderListItem.d.ts +0 -5
- package/lib/typescript/src/containers/myOrders/components/OrderListItem.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrders/components/styles.d.ts +0 -56
- package/lib/typescript/src/containers/myOrders/components/styles.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrders/components/types.d.ts +0 -26
- package/lib/typescript/src/containers/myOrders/components/types.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrders/styles.d.ts +0 -37
- package/lib/typescript/src/containers/myOrders/styles.d.ts.map +0 -1
- package/lib/typescript/src/containers/myOrders/types.d.ts +0 -73
- package/lib/typescript/src/containers/myOrders/types.d.ts.map +0 -1
- package/lib/typescript/src/containers/purchaseConfirmation/PurchaseConfirmation.d.ts +0 -6
- package/lib/typescript/src/containers/purchaseConfirmation/PurchaseConfirmation.d.ts.map +0 -1
- package/lib/typescript/src/containers/purchaseConfirmation/PurchaseConfirmationView.d.ts +0 -5
- package/lib/typescript/src/containers/purchaseConfirmation/PurchaseConfirmationView.d.ts.map +0 -1
- package/lib/typescript/src/containers/purchaseConfirmation/styles.d.ts +0 -74
- package/lib/typescript/src/containers/purchaseConfirmation/styles.d.ts.map +0 -1
- package/lib/typescript/src/containers/purchaseConfirmation/types.d.ts +0 -66
- package/lib/typescript/src/containers/purchaseConfirmation/types.d.ts.map +0 -1
- package/lib/typescript/src/containers/resaleTickets/ResaleTickets.d.ts +0 -6
- package/lib/typescript/src/containers/resaleTickets/ResaleTickets.d.ts.map +0 -1
- package/lib/typescript/src/containers/resaleTickets/ResaleTicketsView.d.ts +0 -5
- package/lib/typescript/src/containers/resaleTickets/ResaleTicketsView.d.ts.map +0 -1
- package/lib/typescript/src/containers/resaleTickets/types.d.ts +0 -129
- package/lib/typescript/src/containers/resaleTickets/types.d.ts.map +0 -1
- package/lib/typescript/src/containers/resetPassword/ResetPassword.d.ts +0 -5
- package/lib/typescript/src/containers/resetPassword/ResetPassword.d.ts.map +0 -1
- package/lib/typescript/src/containers/resetPassword/ResetPasswordView.d.ts +0 -5
- package/lib/typescript/src/containers/resetPassword/ResetPasswordView.d.ts.map +0 -1
- package/lib/typescript/src/containers/resetPassword/styles.d.ts +0 -33
- package/lib/typescript/src/containers/resetPassword/styles.d.ts.map +0 -1
- package/lib/typescript/src/containers/resetPassword/types.d.ts +0 -48
- package/lib/typescript/src/containers/resetPassword/types.d.ts.map +0 -1
- package/lib/typescript/src/containers/tickets/Tickets.d.ts +0 -6
- package/lib/typescript/src/containers/tickets/Tickets.d.ts.map +0 -1
- package/lib/typescript/src/containers/tickets/TicketsView.d.ts +0 -4
- package/lib/typescript/src/containers/tickets/TicketsView.d.ts.map +0 -1
- package/lib/typescript/src/containers/tickets/components/TicketGroupListHeader.d.ts +0 -5
- package/lib/typescript/src/containers/tickets/components/TicketGroupListHeader.d.ts.map +0 -1
- package/lib/typescript/src/containers/tickets/components/TicketListItem.d.ts +0 -4
- package/lib/typescript/src/containers/tickets/components/TicketListItem.d.ts.map +0 -1
- package/lib/typescript/src/containers/tickets/components/styles.d.ts +0 -51
- package/lib/typescript/src/containers/tickets/components/styles.d.ts.map +0 -1
- package/lib/typescript/src/containers/tickets/components/types.d.ts +0 -40
- package/lib/typescript/src/containers/tickets/components/types.d.ts.map +0 -1
- package/lib/typescript/src/containers/tickets/styles.d.ts +0 -20
- package/lib/typescript/src/containers/tickets/styles.d.ts.map +0 -1
- package/lib/typescript/src/containers/tickets/types.d.ts +0 -114
- package/lib/typescript/src/containers/tickets/types.d.ts.map +0 -1
- package/lib/typescript/src/core/BillingCore/BillingCore.d.ts +0 -13
- package/lib/typescript/src/core/BillingCore/BillingCore.d.ts.map +0 -1
- package/lib/typescript/src/core/BillingCore/BillingCoreTypes.d.ts +0 -24
- package/lib/typescript/src/core/BillingCore/BillingCoreTypes.d.ts.map +0 -1
- package/lib/typescript/src/core/CheckoutCore/CheckoutCore.d.ts +0 -15
- package/lib/typescript/src/core/CheckoutCore/CheckoutCore.d.ts.map +0 -1
- package/lib/typescript/src/core/CheckoutCore/CheckoutCoreTypes.d.ts +0 -17
- package/lib/typescript/src/core/CheckoutCore/CheckoutCoreTypes.d.ts.map +0 -1
- package/lib/typescript/src/core/CoreProps.d.ts +0 -5
- package/lib/typescript/src/core/CoreProps.d.ts.map +0 -1
- package/lib/typescript/src/core/LoginCore/LoginCore.d.ts +0 -6
- package/lib/typescript/src/core/LoginCore/LoginCore.d.ts.map +0 -1
- package/lib/typescript/src/core/LoginCore/LoginCoreHelper.d.ts +0 -3
- package/lib/typescript/src/core/LoginCore/LoginCoreHelper.d.ts.map +0 -1
- package/lib/typescript/src/core/LoginCore/LoginCoreTypes.d.ts +0 -15
- package/lib/typescript/src/core/LoginCore/LoginCoreTypes.d.ts.map +0 -1
- package/lib/typescript/src/core/MyOrdersCore/MyOrdersCore.d.ts +0 -6
- package/lib/typescript/src/core/MyOrdersCore/MyOrdersCore.d.ts.map +0 -1
- package/lib/typescript/src/core/MyOrdersCore/MyOrdersCoreTypes.d.ts +0 -10
- package/lib/typescript/src/core/MyOrdersCore/MyOrdersCoreTypes.d.ts.map +0 -1
- package/lib/typescript/src/core/OrderDetailsCore/OrderDetailsCore.d.ts +0 -6
- package/lib/typescript/src/core/OrderDetailsCore/OrderDetailsCore.d.ts.map +0 -1
- package/lib/typescript/src/core/OrderDetailsCore/OrderDetailsCoreTypes.d.ts +0 -9
- package/lib/typescript/src/core/OrderDetailsCore/OrderDetailsCoreTypes.d.ts.map +0 -1
- package/lib/typescript/src/core/PurchaseConfirmationCore/PurchaseConfirmationCore.d.ts +0 -6
- package/lib/typescript/src/core/PurchaseConfirmationCore/PurchaseConfirmationCore.d.ts.map +0 -1
- package/lib/typescript/src/core/PurchaseConfirmationCore/PurchaseConfirmationCoreTypes.d.ts +0 -8
- package/lib/typescript/src/core/PurchaseConfirmationCore/PurchaseConfirmationCoreTypes.d.ts.map +0 -1
- package/lib/typescript/src/core/ResetPasswordCore/ResetPasswordCore.d.ts +0 -6
- package/lib/typescript/src/core/ResetPasswordCore/ResetPasswordCore.d.ts.map +0 -1
- package/lib/typescript/src/core/ResetPasswordCore/ResetPasswordCoreTypes.d.ts +0 -5
- package/lib/typescript/src/core/ResetPasswordCore/ResetPasswordCoreTypes.d.ts.map +0 -1
- package/lib/typescript/src/core/Session/SessionCoreTypes.d.ts +0 -9
- package/lib/typescript/src/core/Session/SessionCoreTypes.d.ts.map +0 -1
- package/lib/typescript/src/core/Session/SessionHandle.d.ts +0 -6
- package/lib/typescript/src/core/Session/SessionHandle.d.ts.map +0 -1
- package/lib/typescript/src/core/TicketsCore/TicketsCore.d.ts +0 -6
- package/lib/typescript/src/core/TicketsCore/TicketsCore.d.ts.map +0 -1
- package/lib/typescript/src/core/TicketsCore/TicketsCoreTypes.d.ts +0 -40
- package/lib/typescript/src/core/TicketsCore/TicketsCoreTypes.d.ts.map +0 -1
- package/lib/typescript/src/core/WaitingListCore/WaitingListCore.d.ts +0 -6
- package/lib/typescript/src/core/WaitingListCore/WaitingListCore.d.ts.map +0 -1
- package/lib/typescript/src/core/WaitingListCore/WaitingListCoreTypes.d.ts +0 -12
- package/lib/typescript/src/core/WaitingListCore/WaitingListCoreTypes.d.ts.map +0 -1
- package/lib/typescript/src/core/index.d.ts +0 -21
- package/lib/typescript/src/core/index.d.ts.map +0 -1
- package/lib/typescript/src/features/auth/api-hooks.d.ts +0 -178
- package/lib/typescript/src/features/auth/api-hooks.d.ts.map +0 -1
- package/lib/typescript/src/features/auth/types.d.ts +0 -51
- package/lib/typescript/src/features/auth/types.d.ts.map +0 -1
- package/lib/typescript/src/features/auth/utils.d.ts +0 -3
- package/lib/typescript/src/features/auth/utils.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/components/AddonsContainer.d.ts +0 -37
- package/lib/typescript/src/features/checkout-v2/components/AddonsContainer.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/components/Conditions.d.ts +0 -30
- package/lib/typescript/src/features/checkout-v2/components/Conditions.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/components/OrderReview.d.ts +0 -25
- package/lib/typescript/src/features/checkout-v2/components/OrderReview.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/components/TicketHoldersSection.d.ts +0 -14
- package/lib/typescript/src/features/checkout-v2/components/TicketHoldersSection.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/form/config.d.ts +0 -61
- package/lib/typescript/src/features/checkout-v2/form/config.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/form/index.d.ts +0 -22
- package/lib/typescript/src/features/checkout-v2/form/index.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/form/styles.d.ts +0 -4501
- package/lib/typescript/src/features/checkout-v2/form/styles.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/form/texts.d.ts +0 -4
- package/lib/typescript/src/features/checkout-v2/form/texts.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/form/types.d.ts +0 -191
- package/lib/typescript/src/features/checkout-v2/form/types.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/hooks/api-hooks.d.ts +0 -227
- package/lib/typescript/src/features/checkout-v2/hooks/api-hooks.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/hooks/use-checkout.d.ts +0 -37
- package/lib/typescript/src/features/checkout-v2/hooks/use-checkout.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/index.d.ts +0 -42
- package/lib/typescript/src/features/checkout-v2/index.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/types.d.ts +0 -433
- package/lib/typescript/src/features/checkout-v2/types.d.ts.map +0 -1
- package/lib/typescript/src/features/checkout-v2/utils.d.ts +0 -12
- package/lib/typescript/src/features/checkout-v2/utils.d.ts.map +0 -1
- package/lib/typescript/src/features/event/api-hooks.d.ts +0 -171
- package/lib/typescript/src/features/event/api-hooks.d.ts.map +0 -1
- package/lib/typescript/src/features/event/types.d.ts +0 -58
- package/lib/typescript/src/features/event/types.d.ts.map +0 -1
- package/lib/typescript/src/features/form/index.d.ts +0 -24
- package/lib/typescript/src/features/form/index.d.ts.map +0 -1
- package/lib/typescript/src/features/form/styles.d.ts +0 -35
- package/lib/typescript/src/features/form/styles.d.ts.map +0 -1
- package/lib/typescript/src/features/form/types.d.ts +0 -33
- package/lib/typescript/src/features/form/types.d.ts.map +0 -1
- package/lib/typescript/src/features/geo/api-hooks.d.ts +0 -12
- package/lib/typescript/src/features/geo/api-hooks.d.ts.map +0 -1
- package/lib/typescript/src/features/geo/types.d.ts +0 -13
- package/lib/typescript/src/features/geo/types.d.ts.map +0 -1
- package/lib/typescript/src/helpers/Config.d.ts +0 -24
- package/lib/typescript/src/helpers/Config.d.ts.map +0 -1
- package/lib/typescript/src/helpers/CountryCodes.d.ts +0 -16
- package/lib/typescript/src/helpers/CountryCodes.d.ts.map +0 -1
- package/lib/typescript/src/helpers/Debounced.d.ts +0 -2
- package/lib/typescript/src/helpers/Debounced.d.ts.map +0 -1
- package/lib/typescript/src/helpers/Domains.d.ts +0 -3
- package/lib/typescript/src/helpers/Domains.d.ts.map +0 -1
- package/lib/typescript/src/helpers/LocalStorage.d.ts +0 -27
- package/lib/typescript/src/helpers/LocalStorage.d.ts.map +0 -1
- package/lib/typescript/src/helpers/RefreshAccessToken.d.ts +0 -3
- package/lib/typescript/src/helpers/RefreshAccessToken.d.ts.map +0 -1
- package/lib/typescript/src/helpers/StringsHelper.d.ts +0 -3
- package/lib/typescript/src/helpers/StringsHelper.d.ts.map +0 -1
- package/lib/typescript/src/helpers/Validators.d.ts +0 -16
- package/lib/typescript/src/helpers/Validators.d.ts.map +0 -1
- package/lib/typescript/src/index.d.ts +0 -49
- package/lib/typescript/src/index.d.ts.map +0 -1
- package/lib/typescript/src/res/colors.d.ts +0 -16
- package/lib/typescript/src/res/colors.d.ts.map +0 -1
- package/lib/typescript/src/res/icons.d.ts +0 -13
- package/lib/typescript/src/res/icons.d.ts.map +0 -1
- package/lib/typescript/src/res/images.d.ts +0 -5
- package/lib/typescript/src/res/images.d.ts.map +0 -1
- package/lib/typescript/src/res/index.d.ts +0 -32
- package/lib/typescript/src/res/index.d.ts.map +0 -1
- package/lib/typescript/src/types/IAccountTickets.d.ts +0 -71
- package/lib/typescript/src/types/IAccountTickets.d.ts.map +0 -1
- package/lib/typescript/src/types/ICountry.d.ts +0 -2
- package/lib/typescript/src/types/ICountry.d.ts.map +0 -1
- package/lib/typescript/src/types/IError.d.ts +0 -6
- package/lib/typescript/src/types/IError.d.ts.map +0 -1
- package/lib/typescript/src/types/IEvent.d.ts +0 -87
- package/lib/typescript/src/types/IEvent.d.ts.map +0 -1
- package/lib/typescript/src/types/ITicket.d.ts +0 -71
- package/lib/typescript/src/types/ITicket.d.ts.map +0 -1
- package/lib/typescript/src/types/IUserProfile.d.ts +0 -30
- package/lib/typescript/src/types/IUserProfile.d.ts.map +0 -1
- package/lib/typescript/src/types/index.d.ts +0 -6
- package/lib/typescript/src/types/index.d.ts.map +0 -1
- package/lib/typescript/src/utils/Logger.d.ts +0 -21
- package/lib/typescript/src/utils/Logger.d.ts.map +0 -1
- package/lib/typescript/src/utils/handlers.d.ts +0 -9
- package/lib/typescript/src/utils/handlers.d.ts.map +0 -1
- package/lib/typescript/src/utils/storageAdapter.d.ts +0 -14
- package/lib/typescript/src/utils/storageAdapter.d.ts.map +0 -1
- package/lib/typescript/src/utils/styleUtils.d.ts +0 -18
- package/lib/typescript/src/utils/styleUtils.d.ts.map +0 -1
- package/src/api/ApiClient.ts +0 -1539
- package/src/api/Constants.ts +0 -10
- package/src/api/ErrorHandler.ts +0 -36
- package/src/api/api.types.ts +0 -8
- package/src/api/types.ts +0 -593
- package/src/apiv2/index.ts +0 -142
- package/src/assets/icons/ic_check.png +0 -0
- package/src/assets/icons/ic_clock.png +0 -0
- package/src/assets/icons/ic_copy.png +0 -0
- package/src/assets/icons/ic_dropdown.png +0 -0
- package/src/assets/icons/ic_error.png +0 -0
- package/src/assets/icons/ic_eye.png +0 -0
- package/src/assets/icons/ic_eye_off.png +0 -0
- package/src/assets/icons/ic_more.png +0 -0
- package/src/assets/icons/ic_next.png +0 -0
- package/src/assets/images/brand.png +0 -0
- package/src/common/query.types.ts +0 -6
- package/src/components/bottomSheetModal/BottomSheetModal.tsx +0 -95
- package/src/components/bottomSheetModal/BottomSheetModalStyles.ts +0 -43
- package/src/components/bottomSheetModal/BottomSheetModalTypes.ts +0 -26
- package/src/components/button/Button.tsx +0 -53
- package/src/components/button/styles.tsx +0 -30
- package/src/components/button/types.ts +0 -16
- package/src/components/cartTimer/CartTimer.tsx +0 -68
- package/src/components/cartTimer/styles.ts +0 -44
- package/src/components/cartTimer/types.ts +0 -22
- package/src/components/checkbox/Checkbox.tsx +0 -53
- package/src/components/checkbox/styles.ts +0 -41
- package/src/components/checkbox/types.ts +0 -23
- package/src/components/datePicker/DatePicker.tsx +0 -81
- package/src/components/datePicker/styles.ts +0 -39
- package/src/components/datePicker/types.ts +0 -21
- package/src/components/dropdown/Dropdown.tsx +0 -111
- package/src/components/dropdown/DropdownListItem.tsx +0 -36
- package/src/components/dropdown/styles.ts +0 -97
- package/src/components/dropdown/types.ts +0 -38
- package/src/components/dropdownMaterial/DropdownMaterial.tsx +0 -129
- package/src/components/dropdownMaterial/styles.ts +0 -91
- package/src/components/dropdownMaterial/types.ts +0 -24
- package/src/components/enterPassword/EnterPassword.tsx +0 -50
- package/src/components/enterPassword/styles.ts +0 -23
- package/src/components/enterPassword/types.ts +0 -27
- package/src/components/formField/FormField.tsx +0 -131
- package/src/components/formField/styles.ts +0 -37
- package/src/components/formField/types.ts +0 -60
- package/src/components/index.ts +0 -20
- package/src/components/input/Input.tsx +0 -77
- package/src/components/input/styles.ts +0 -53
- package/src/components/input/types.ts +0 -38
- package/src/components/loading/Loading.tsx +0 -30
- package/src/components/loading/styles.ts +0 -32
- package/src/components/loading/types.ts +0 -16
- package/src/components/loggedIn/LoggedIn.tsx +0 -60
- package/src/components/loggedIn/styles.ts +0 -9
- package/src/components/loggedIn/types.ts +0 -27
- package/src/components/login/Login.tsx +0 -161
- package/src/components/login/LoginView.tsx +0 -259
- package/src/components/login/components/LoginForm.tsx +0 -92
- package/src/components/login/components/types.ts +0 -22
- package/src/components/login/styles.ts +0 -63
- package/src/components/login/types.ts +0 -189
- package/src/components/phoneInput/PhoneInput.tsx +0 -72
- package/src/components/phoneInput/styles.ts +0 -31
- package/src/components/phoneInput/types.ts +0 -35
- package/src/components/promoCode/PromoCode.tsx +0 -111
- package/src/components/promoCode/styles.ts +0 -63
- package/src/components/promoCode/types.ts +0 -43
- package/src/components/radioButton/RadioButton.tsx +0 -26
- package/src/components/radioButton/styles.ts +0 -32
- package/src/components/radioButton/types.ts +0 -17
- package/src/components/radioGroup/RadioGroup.tsx +0 -86
- package/src/components/radioGroup/index.ts +0 -4
- package/src/components/radioGroup/types.ts +0 -26
- package/src/components/restorePassword/RestorePassword.tsx +0 -63
- package/src/components/restorePassword/ResultDialog.tsx +0 -26
- package/src/components/restorePassword/styles.ts +0 -38
- package/src/components/restorePassword/types.ts +0 -61
- package/src/components/separator/Separator.tsx +0 -26
- package/src/components/separator/types.ts +0 -9
- package/src/components/stripePayment/StripePayment.tsx +0 -51
- package/src/components/stripePayment/styles.ts +0 -7
- package/src/components/stripePayment/types.ts +0 -22
- package/src/components/waitingList/WaitingList.tsx +0 -147
- package/src/components/waitingList/WaitingListView.tsx +0 -94
- package/src/components/waitingList/styles.ts +0 -9
- package/src/components/waitingList/types.ts +0 -68
- package/src/containers/billingInfo/Billing.tsx +0 -1902
- package/src/containers/billingInfo/styles.ts +0 -64
- package/src/containers/billingInfo/types.ts +0 -217
- package/src/containers/checkout/Checkout.tsx +0 -519
- package/src/containers/checkout/CheckoutData.ts +0 -29
- package/src/containers/checkout/components/Conditions.tsx +0 -22
- package/src/containers/checkout/components/OrderReview.tsx +0 -31
- package/src/containers/checkout/components/styles.ts +0 -28
- package/src/containers/checkout/styles.ts +0 -44
- package/src/containers/checkout/types.ts +0 -148
- package/src/containers/index.ts +0 -8
- package/src/containers/myOrderDetails/MyOrderDetails.tsx +0 -318
- package/src/containers/myOrderDetails/MyOrderDetailsView.tsx +0 -269
- package/src/containers/myOrderDetails/components/Notification.tsx +0 -40
- package/src/containers/myOrderDetails/components/OrderListItem.tsx +0 -12
- package/src/containers/myOrderDetails/components/TicketActions/TicketActions.tsx +0 -68
- package/src/containers/myOrderDetails/components/TicketActions/TicketActionsTypes.ts +0 -41
- package/src/containers/myOrderDetails/components/TicketListItem/TicketListItem.tsx +0 -63
- package/src/containers/myOrderDetails/components/TicketListItem/TicketListItemStyles.ts +0 -33
- package/src/containers/myOrderDetails/components/TicketListItem/TicketListItemTypes.ts +0 -39
- package/src/containers/myOrderDetails/components/styles.ts +0 -42
- package/src/containers/myOrderDetails/styles.ts +0 -57
- package/src/containers/myOrderDetails/types.ts +0 -173
- package/src/containers/myOrders/MyOrders.tsx +0 -340
- package/src/containers/myOrders/MyOrdersView.tsx +0 -182
- package/src/containers/myOrders/components/OrderListItem.tsx +0 -50
- package/src/containers/myOrders/components/styles.ts +0 -55
- package/src/containers/myOrders/components/types.ts +0 -28
- package/src/containers/myOrders/styles.ts +0 -42
- package/src/containers/myOrders/types.ts +0 -84
- package/src/containers/purchaseConfirmation/PurchaseConfirmation.tsx +0 -145
- package/src/containers/purchaseConfirmation/PurchaseConfirmationView.tsx +0 -82
- package/src/containers/purchaseConfirmation/styles.ts +0 -79
- package/src/containers/purchaseConfirmation/types.ts +0 -77
- package/src/containers/resaleTickets/ResaleTickets.tsx +0 -234
- package/src/containers/resaleTickets/ResaleTicketsView.tsx +0 -314
- package/src/containers/resaleTickets/types.ts +0 -154
- package/src/containers/resetPassword/ResetPassword.tsx +0 -110
- package/src/containers/resetPassword/ResetPasswordView.tsx +0 -81
- package/src/containers/resetPassword/styles.ts +0 -35
- package/src/containers/resetPassword/types.ts +0 -56
- package/src/containers/tickets/Tickets.tsx +0 -525
- package/src/containers/tickets/TicketsView.tsx +0 -164
- package/src/containers/tickets/components/TicketGroupListHeader.tsx +0 -12
- package/src/containers/tickets/components/TicketListItem.tsx +0 -124
- package/src/containers/tickets/components/styles.ts +0 -54
- package/src/containers/tickets/components/types.ts +0 -47
- package/src/containers/tickets/styles.ts +0 -22
- package/src/containers/tickets/types.ts +0 -158
- package/src/core/BillingCore/BillingCore.tsx +0 -129
- package/src/core/BillingCore/BillingCoreTypes.ts +0 -34
- package/src/core/BillingCore/README.md +0 -22
- package/src/core/CheckoutCore/CheckoutCore.tsx +0 -113
- package/src/core/CheckoutCore/CheckoutCoreTypes.ts +0 -23
- package/src/core/CheckoutCore/README.md +0 -20
- package/src/core/CoreProps.ts +0 -5
- package/src/core/LoginCore/LoginCore.tsx +0 -140
- package/src/core/LoginCore/LoginCoreHelper.ts +0 -22
- package/src/core/LoginCore/LoginCoreTypes.ts +0 -21
- package/src/core/MIGRATION.md +0 -148
- package/src/core/MyOrdersCore/MyOrdersCore.tsx +0 -44
- package/src/core/MyOrdersCore/MyOrdersCoreTypes.ts +0 -15
- package/src/core/OrderDetailsCore/OrderDetailsCore.tsx +0 -36
- package/src/core/OrderDetailsCore/OrderDetailsCoreTypes.ts +0 -10
- package/src/core/PurchaseConfirmationCore/PurchaseConfirmationCore.tsx +0 -37
- package/src/core/PurchaseConfirmationCore/PurchaseConfirmationCoreTypes.ts +0 -10
- package/src/core/ResetPasswordCore/ResetPasswordCore.tsx +0 -21
- package/src/core/ResetPasswordCore/ResetPasswordCoreTypes.ts +0 -5
- package/src/core/Session/SessionCoreTypes.ts +0 -10
- package/src/core/Session/SessionHandle.tsx +0 -23
- package/src/core/TicketsCore/TicketsCore.tsx +0 -216
- package/src/core/TicketsCore/TicketsCoreTypes.ts +0 -52
- package/src/core/WaitingListCore/WaitingListCore.tsx +0 -35
- package/src/core/WaitingListCore/WaitingListCoreTypes.ts +0 -16
- package/src/core/index.ts +0 -20
- package/src/features/auth/api-hooks.ts +0 -61
- package/src/features/auth/types.ts +0 -54
- package/src/features/auth/utils.ts +0 -27
- package/src/features/checkout-v2/components/AddonsContainer.tsx +0 -159
- package/src/features/checkout-v2/components/Conditions.tsx +0 -144
- package/src/features/checkout-v2/components/OrderReview.tsx +0 -96
- package/src/features/checkout-v2/components/TicketHoldersSection.tsx +0 -131
- package/src/features/checkout-v2/form/config.tsx +0 -194
- package/src/features/checkout-v2/form/index.tsx +0 -830
- package/src/features/checkout-v2/form/styles.ts +0 -241
- package/src/features/checkout-v2/form/texts.ts +0 -133
- package/src/features/checkout-v2/form/types.ts +0 -231
- package/src/features/checkout-v2/hooks/api-hooks.ts +0 -332
- package/src/features/checkout-v2/hooks/use-checkout.ts +0 -927
- package/src/features/checkout-v2/index.tsx +0 -289
- package/src/features/checkout-v2/types.ts +0 -475
- package/src/features/checkout-v2/utils.ts +0 -156
- package/src/features/event/api-hooks.ts +0 -28
- package/src/features/event/types.ts +0 -69
- package/src/features/form/index.tsx +0 -185
- package/src/features/form/styles.ts +0 -37
- package/src/features/form/types.ts +0 -38
- package/src/features/geo/api-hooks.ts +0 -43
- package/src/features/geo/types.ts +0 -15
- package/src/helpers/Config.ts +0 -81
- package/src/helpers/CountryCodes.ts +0 -3382
- package/src/helpers/Debounced.ts +0 -27
- package/src/helpers/Domains.ts +0 -32
- package/src/helpers/LocalStorage.tsx +0 -152
- package/src/helpers/RefreshAccessToken.ts +0 -25
- package/src/helpers/StringsHelper.ts +0 -5
- package/src/helpers/Validators.ts +0 -108
- package/src/packages/rn-material-ui-textfield/README.md +0 -149
- package/src/packages/rn-material-ui-textfield/components/affix/index.js +0 -61
- package/src/packages/rn-material-ui-textfield/components/affix/styles.js +0 -8
- package/src/packages/rn-material-ui-textfield/components/counter/index.js +0 -36
- package/src/packages/rn-material-ui-textfield/components/counter/styles.js +0 -12
- package/src/packages/rn-material-ui-textfield/components/field/index.js +0 -700
- package/src/packages/rn-material-ui-textfield/components/field/styles.js +0 -42
- package/src/packages/rn-material-ui-textfield/components/field-filled/index.js +0 -21
- package/src/packages/rn-material-ui-textfield/components/field-filled/styles.js +0 -10
- package/src/packages/rn-material-ui-textfield/components/field-outlined/index.js +0 -59
- package/src/packages/rn-material-ui-textfield/components/helper/index.js +0 -78
- package/src/packages/rn-material-ui-textfield/components/helper/styles.js +0 -12
- package/src/packages/rn-material-ui-textfield/components/label/index.js +0 -123
- package/src/packages/rn-material-ui-textfield/components/label/styles.js +0 -16
- package/src/packages/rn-material-ui-textfield/components/line/index.js +0 -117
- package/src/packages/rn-material-ui-textfield/components/line/styles.js +0 -18
- package/src/packages/rn-material-ui-textfield/components/outline/index.js +0 -139
- package/src/packages/rn-material-ui-textfield/components/outline/styles.js +0 -83
- package/src/packages/rn-material-ui-textfield/index.d.ts +0 -53
- package/src/packages/rn-material-ui-textfield/index.js +0 -5
- package/src/packages/rn-material-ui-textfield/license.txt +0 -28
- package/src/res/colors.ts +0 -16
- package/src/res/icons.ts +0 -11
- package/src/res/images.ts +0 -3
- package/src/res/index.ts +0 -11
- package/src/types/IAccountTickets.ts +0 -75
- package/src/types/ICountry.ts +0 -2
- package/src/types/IError.ts +0 -5
- package/src/types/IEvent.ts +0 -87
- package/src/types/ITicket.ts +0 -75
- package/src/types/IUserProfile.ts +0 -30
- package/src/types/index.ts +0 -5
- package/src/utils/Logger.ts +0 -75
- package/src/utils/handlers.ts +0 -49
- package/src/utils/storageAdapter.ts +0 -44
- package/src/utils/styleUtils.ts +0 -76
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../tf-checkout-shared/src/client/storage.ts","../../tf-checkout-shared/src/client/config.ts","../../tf-checkout-shared/src/client/errors.ts","../../tf-checkout-shared/src/client/cookies.ts","../../tf-checkout-shared/src/client/session.ts","../../tf-checkout-shared/src/client/http.ts","../../tf-checkout-shared/src/constants/endpoints.ts","../../tf-checkout-shared/src/constants/gateways.ts","../../tf-checkout-shared/src/constants/redirectMethods.ts","../../tf-checkout-shared/src/logic/gateway.ts","../../tf-checkout-shared/src/logic/pricing.ts","../../tf-checkout-shared/src/logic/checkout.ts","../../tf-checkout-shared/src/logic/payment.ts","../../tf-checkout-shared/src/logic/paymentPlan.ts","../../tf-checkout-shared/src/logic/account.ts","../../tf-checkout-shared/src/logic/auth.ts","../../tf-checkout-shared/src/logic/verification.ts","../../tf-checkout-shared/src/engine/store.ts","../../tf-checkout-shared/src/engine/confirmer.ts","../../tf-checkout-shared/src/engine/sheets.ts","../../tf-checkout-shared/src/engine/errors.ts","../../tf-checkout-shared/src/api/index.ts","../../tf-checkout-shared/src/api/profile.ts","../../tf-checkout-shared/src/api/auth.ts","../../tf-checkout-shared/src/api/geo.ts","../../tf-checkout-shared/src/api/engagement.ts","../../tf-checkout-shared/src/api/orders.ts","../../tf-checkout-shared/src/api/resale.ts","../../tf-checkout-shared/src/api/confirmation.ts","../../tf-checkout-shared/src/api/preRegistration.ts","../../tf-checkout-shared/src/api/delegation.ts","../../tf-checkout-shared/src/api/seatmap.ts","../../tf-checkout-shared/src/api/events.ts","../../tf-checkout-shared/src/api/cart.ts","../../tf-checkout-shared/src/api/order.ts","../../tf-checkout-shared/src/api/payment.ts","../../tf-checkout-shared/src/engine/engine.ts","../../tf-checkout-shared/src/services.ts","../../tf-checkout-shared/src/hooks/index.ts","../../tf-checkout-shared/src/hooks/auth.ts","../../tf-checkout-shared/src/hooks/authFlow.ts","../../tf-checkout-shared/src/hooks/keys.ts","../../tf-checkout-shared/src/hooks/session.ts","../../tf-checkout-shared/src/hooks/profile.ts","../../tf-checkout-shared/src/hooks/geo.ts","../../tf-checkout-shared/src/hooks/events.ts","../../tf-checkout-shared/src/hooks/orders.ts","../../tf-checkout-shared/src/hooks/engagement.ts","../../tf-checkout-shared/src/hooks/checkout.ts","../../tf-checkout-shared/src/i18n/locales/en.ts","../../tf-checkout-shared/src/i18n/resolve.ts","../../tf-checkout-shared/src/i18n/locales/es-MX.ts","../../tf-checkout-shared/src/i18n/locales/index.ts","../src/confirmer.ts","../src/instance.ts","../src/useCheckout.ts","../src/storage.ts","../src/configure.ts","../src/CardInput.tsx","../src/ui/CheckoutProvider.tsx","../src/ui/InstallmentPicker.tsx","../src/ui/primitives.tsx","../src/ui/theme.ts","../src/ui/Field.tsx","../src/ui/Select.tsx","../src/ui/QuantitySelect.tsx","../src/ui/Timer.tsx","../src/ui/TimerBanner.tsx","../src/ui/PaymentMethods.tsx","../src/sections/Tickets.tsx","../src/sections/AddOns.tsx","../src/ui/CustomFields.tsx","../src/sections/BillingInfo.tsx","../src/sections/billing/BillingAddressFields.tsx","../src/sections/billing/BuyerField.tsx","../src/sections/billing/TicketHoldersCard.tsx","../src/sections/OrderSummary.tsx","../src/sections/Payment.tsx","../src/sections/IDVerification.tsx","../src/sections/Confirmation.tsx","../src/auth/AuthModal.tsx","../src/auth/ForgotPasswordForm.tsx","../src/auth/LoginForm.tsx","../src/auth/PasswordInput.tsx","../src/auth/RegisterForm.tsx","../src/auth/ResetPasswordForm.tsx","../src/EmbeddedCheckout.tsx"],"sourcesContent":["/**\n * The one platform seam the SDK's transport needs: somewhere to keep tokens.\n *\n * Web passes a `localStorage`-backed adapter, React Native an MMKV-backed one.\n * If a consumer configures nothing, we fall back to an in-memory map so the SDK\n * still works in tests and SSR (tokens just don't survive a reload).\n *\n * Deliberately synchronous — web `localStorage` and RN MMKV are both sync, and\n * a sync contract keeps the axios interceptors trivial. If you only have an\n * async store (AsyncStorage), wrap it with a small sync mirror.\n */\nexport interface StorageAdapter {\n getItem(key: string): string | null | undefined\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\n/** Process-lifetime fallback store. Not persisted — good enough for tests/SSR. */\nexport const createMemoryStorage = (): StorageAdapter => {\n const map = new Map<string, string>()\n return {\n getItem: (key) => (map.has(key) ? (map.get(key) as string) : null),\n setItem: (key, value) => void map.set(key, value),\n removeItem: (key) => void map.delete(key),\n }\n}\n","/**\n * One-time setup for the SDK. Call `configure()` at app start, before any\n * `ttf.*` call or hook runs. Everything downstream (transport, session, api)\n * reads this single record — there is no other global state.\n */\nimport { createMemoryStorage, StorageAdapter } from './storage'\n\nexport type TtfEnv = 'PROD' | 'STAG' | 'DEV'\n\n/** Host origins (NO /api suffix) — the one base-URL notion every layer derives\n * from. '' is valid: same-origin (e.g. behind a dev proxy). */\nexport const ENV_HOSTS: Record<TtfEnv, string> = {\n PROD: 'https://www.ticketfairy.com',\n STAG: 'https://test.ticketfairy.com',\n DEV: 'https://sandbox.ticketfairy.com',\n}\n\n/** Explicit `baseUrl` wins (even ''); otherwise the env host (default PROD).\n * A value in the old full-base form (…/api) is accepted — the /api suffix is\n * stripped here and re-appended for the transport. */\nexport const resolveHost = (env?: TtfEnv, baseUrl?: string): string => {\n if (baseUrl === undefined) return ENV_HOSTS[env ?? 'PROD']\n const trimmed = baseUrl.replace(/\\/+$/, '')\n return /\\/api$/.test(trimmed) ? trimmed.replace(/\\/api$/, '') : trimmed\n}\n\n/**\n * Extra auth material the consumer hands us — called on EVERY request; whatever\n * headers it returns are merged in last (they win over the SDK's own). Pass a\n * bearer token, a session cookie, an API key — anything. This is the flexible\n * \"bring your own auth\" seam. Return `undefined` to add nothing this request.\n */\nexport type AuthProvider = () => Record<string, string> | undefined\n\nexport interface TtfConfig {\n /** Host origin, e.g. `https://www.ticketfairy.com` — the `/api` path is\n * appended internally. `''` = same-origin. Omit to use `env`. */\n baseUrl?: string\n /** Picks the TicketFairy host when `baseUrl` is omitted. Defaults to PROD. */\n env?: TtfEnv\n /** OAuth client id issued to your brand. */\n clientId: string\n /** OAuth client secret issued to your brand. */\n clientSecret: string\n /** Value for the `X-Source-Origin` header (your domain). Optional. */\n sourceOrigin?: string\n /** Where tokens live. Defaults to an in-memory store (not persisted). */\n storage?: StorageAdapter\n /** Bring-your-own auth: return headers to attach to every request (token,\n * cookie, custom). Merged last, so it overrides the SDK's own headers. */\n auth?: AuthProvider\n /** Cookie-based session auth: forward the `X-TF-ECOMMERCE` login ticket (+\n * browser cookies where they exist) as headers, and capture the rotating\n * ones back from responses. Sign-in rides the legacy `/auth` session flow —\n * no bearer is minted, so the backend session that holds a reserved cart\n * survives a mid-checkout login. Enable when the app shares a session cookie\n * with TicketFairy (same-domain / SSO), runs anonymous cookie carts, or is a\n * native app (React Native persists the ticket via the storage adapter —\n * the RN `configureCheckout` turns this on by default). */\n cookieAuth?: boolean\n}\n\n/** Fully-resolved config — `storage`, `host`, and `apiBaseUrl` always present. */\nexport interface ResolvedTtfConfig extends TtfConfig {\n storage: StorageAdapter\n /** Host origin, no `/api` (e.g. `https://www.ticketfairy.com`). '' = same-origin. */\n host: string\n /** The transport base: `<host>/api`. */\n apiBaseUrl: string\n}\n\nlet current: ResolvedTtfConfig | null = null\n\n/** Wire the SDK. Idempotent — the last call wins. */\nexport const configure = (config: TtfConfig): void => {\n const host = resolveHost(config.env, config.baseUrl)\n current = {\n ...config,\n storage: config.storage ?? createMemoryStorage(),\n host,\n apiBaseUrl: `${host}/api`,\n }\n}\n\n/** Read the active config, or throw a pointed error if `configure()` was skipped. */\nexport const getConfig = (): ResolvedTtfConfig => {\n if (!current) {\n throw new Error(\n 'TicketFairy SDK is not configured — call configure({ baseUrl, clientId, clientSecret }) once at app start.'\n )\n }\n return current\n}\n\n/** The host origin (no `/api`) — for the few endpoints served off the root\n * (e.g. `/ajax/contact-email`) and for absolutizing icon paths. */\nexport const getOriginUrl = (): string => getConfig().host\n\n/** True once `configure()` has run. Lets callers branch without catching. */\nexport const isConfigured = (): boolean => current !== null\n","/**\n * One error shape for the whole SDK. Every api function rejects with a\n * `TtfError`, so callers (and hooks) branch on `.status` / `.code` instead of\n * digging through axios internals. `message` is always safe to show a user.\n */\nimport { AxiosError } from 'axios'\n\nexport class TtfError extends Error {\n /** HTTP status, or 0 for network/transport failures. */\n readonly status: number\n /** Backend error code when present (e.g. `INVALID_CREDENTIALS`). */\n readonly code?: string\n /** The raw payload, for callers that need more than the message. */\n readonly data?: unknown\n\n constructor(message: string, status: number, code?: string, data?: unknown) {\n super(message)\n this.name = 'TtfError'\n this.status = status\n this.code = code\n this.data = data\n }\n}\n\nconst flattenMessages = (value: unknown): string[] => {\n if (typeof value === 'string') return value.trim() ? [value.trim()] : []\n if (Array.isArray(value)) return value.flatMap(flattenMessages)\n if (value && typeof value === 'object')\n return Object.values(value).flatMap(flattenMessages)\n return []\n}\n\n/** Pull the friendliest message the backend gave us, including the legacy\n * `{ message: { email: [\"already registered\"] } }` validation shape. */\nconst messageFrom = (payload: unknown, fallback: string): string => {\n if (typeof payload === 'string' && payload.trim()) return payload\n if (payload && typeof payload === 'object') {\n const record = payload as Record<string, unknown>\n const candidate =\n record.message ??\n record.error ??\n record.error_description ??\n (Array.isArray(record.errors) ? (record.errors[0] as any)?.message : undefined)\n if (typeof candidate === 'string' && candidate.trim()) return candidate\n const messages = flattenMessages(candidate)\n if (messages.length > 0) return messages.join('\\n')\n }\n return fallback\n}\n\nconst codeFrom = (payload: unknown): string | undefined => {\n if (payload && typeof payload === 'object') {\n const code = (payload as Record<string, unknown>).code\n if (typeof code === 'string') return code\n }\n return undefined\n}\n\n/** Normalize any thrown value into a `TtfError`. Never throws itself. */\nexport const toTtfError = (\n error: unknown,\n fallback = 'Something went wrong'\n): TtfError => {\n if (error instanceof TtfError) return error\n if (error instanceof AxiosError) {\n const status = error.response?.status ?? 0\n const payload = error.response?.data\n return new TtfError(\n messageFrom(payload, error.message || fallback),\n status,\n codeFrom(payload),\n payload\n )\n }\n if (error instanceof Error) return new TtfError(error.message || fallback, 0)\n return new TtfError(fallback, 0)\n}\n","/**\n * Cookie access for the opt-in `cookieAuth` transport path (forwarding the\n * session cookies as headers). In the browser this is `document.cookie`.\n * Outside the browser (React Native) the same names are persisted through the\n * configured storage adapter instead — the backend accepts the session ticket\n * as a header, so a \"cookie\" only needs to survive relaunches, not be a real\n * browser cookie. This is what lets native ride the legacy cookie-session\n * login (same session as the reserved cart) with the ticket in MMKV.\n */\nimport { getConfig, isConfigured } from './config'\n\nconst hasDocument = (): boolean =>\n typeof document !== 'undefined' && typeof document.cookie === 'string'\n\nconst escapeName = (name: string): string =>\n name.replace(/([.$?*|{}()[\\]\\\\/+^])/g, '\\\\$1')\n\n/** Storage key for the non-browser fallback. */\nconst storageKey = (name: string): string => `tf_cookie_${name}`\n\nconst storageRead = (name: string): string | null => {\n if (!isConfigured()) return null\n return getConfig().storage.getItem(storageKey(name)) ?? null\n}\n\nconst storageWrite = (name: string, value: string): void => {\n if (!isConfigured()) return\n getConfig().storage.setItem(storageKey(name), value)\n}\n\nconst storageDelete = (name: string): void => {\n if (!isConfigured()) return\n getConfig().storage.removeItem(storageKey(name))\n}\n\n/** Read one cookie by name, or null when absent. */\nexport const readCookie = (name: string): string | null => {\n if (!hasDocument()) return storageRead(name)\n const match = document.cookie.match(new RegExp(`(?:^|; )${escapeName(name)}=([^;]*)`))\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Write a session-scoped cookie (path=/), or persist via storage off-browser. */\nexport const writeCookie = (name: string, value: string): void => {\n if (!hasDocument()) {\n storageWrite(name, value)\n return\n }\n document.cookie = `${name}=${value}; path=/`\n}\n\n/**\n * Expire a browser cookie for both host-only and domain-scoped variants.\n * White-labels can receive X-TF-ECOMMERCE from either their own host or a\n * parent domain, so deleting only one form can make logout appear to fail.\n * Off-browser there is exactly one stored variant to remove.\n */\nexport const deleteCookie = (name: string): void => {\n if (!hasDocument()) {\n storageDelete(name)\n return\n }\n\n const expired = `${encodeURIComponent(name)}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; max-age=0; path=/`\n // Host-only cookie.\n document.cookie = expired\n\n if (typeof window === 'undefined') return\n const hostname = window.location?.hostname ?? ''\n if (!hostname || hostname === 'localhost' || /^\\d+(?:\\.\\d+){3}$/.test(hostname)) {\n return\n }\n\n const parts = hostname.split('.')\n for (let index = 0; index < parts.length - 1; index += 1) {\n const domain = parts.slice(index).join('.')\n document.cookie = `${expired}; domain=${domain}`\n document.cookie = `${expired}; domain=.${domain}`\n }\n}\n\n/** The raw `document.cookie` string ('' outside the browser — the storage\n * fallback carries named cookies as individual headers, never a cookie jar). */\nexport const allCookies = (): string => (hasDocument() ? document.cookie : '')\n","/**\n * Token bookkeeping, one level above the raw storage adapter. The transport\n * reads these on every request; `auth.ts` writes them on login and clears them\n * on logout / 401. Keys match what the backend hands back so a future migration\n * off the legacy client stays drop-in.\n */\nimport { getConfig, isConfigured } from './config'\nimport { deleteCookie, readCookie } from './cookies'\n\nconst ACCESS_TOKEN = 'tf_access_token'\nconst REFRESH_TOKEN = 'tf_refresh_token'\nconst GUEST_TOKEN = 'tf_auth_guest_token'\nconst LEGACY_GUEST_TOKEN = 'auth_guest_token'\nconst CART_GUEST_TOKEN = 'tf_checkout_cart_guest_token'\n\ntype SessionListener = () => void\nconst listeners = new Set<SessionListener>()\n\nconst emitSessionChange = (): void => {\n for (const listener of listeners) listener()\n}\n\n/** Notify subscribers after a cookie-session login that writes no bearer token\n * (so `setTokens`' own notification never fires). Web sign-in rides the legacy\n * `/auth` cookie flow: the X-TF-ECOMMERCE ticket lands via the response\n * interceptor, and this lets `useAuthSession` observe the signed-in state. */\nexport const notifyCookieSession = (): void => emitSessionChange()\n\n/** React/platform bindings subscribe here instead of maintaining a second auth\n * flag. Tokens remain the single source of truth. */\nexport const subscribeSession = (listener: SessionListener): (() => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nexport const getAccessToken = (): string | null =>\n getConfig().storage.getItem(ACCESS_TOKEN) ?? null\n\nexport const getGuestToken = (): string | null =>\n getConfig().storage.getItem(GUEST_TOKEN) ??\n getConfig().storage.getItem(LEGACY_GUEST_TOKEN) ??\n null\n\nexport const setTokens = (tokens: { access?: string; refresh?: string }): void => {\n const { storage } = getConfig()\n if (tokens.access) storage.setItem(ACCESS_TOKEN, tokens.access)\n if (tokens.refresh) storage.setItem(REFRESH_TOKEN, tokens.refresh)\n if (tokens.access || tokens.refresh) emitSessionChange()\n}\n\n/** The transport captures the rotating guest token from response headers.\n * Keep the legacy key synchronized while old and new checkout clients coexist. */\nexport const setGuestToken = (token: string): void => {\n const { storage } = getConfig()\n storage.setItem(GUEST_TOKEN, token)\n storage.setItem(LEGACY_GUEST_TOKEN, token)\n}\n\n/** Pin the identity that owns the active reservation. OAuth can rotate the\n * general guest token during a mid-checkout login, but the cart must keep using\n * the token captured immediately after add-to-cart. */\nexport const pinCartGuestToken = (): void => {\n if (!isConfigured()) return\n const token = getGuestToken()\n if (token) getConfig().storage.setItem(CART_GUEST_TOKEN, token)\n}\n\nexport const getCartGuestToken = (): string | null =>\n isConfigured() ? (getConfig().storage.getItem(CART_GUEST_TOKEN) ?? null) : null\n\nexport const clearCartGuestToken = (): void => {\n if (isConfigured()) getConfig().storage.removeItem(CART_GUEST_TOKEN)\n}\n\nexport const clearSession = (): void => {\n const { storage } = getConfig()\n storage.removeItem(ACCESS_TOKEN)\n storage.removeItem(REFRESH_TOKEN)\n storage.removeItem(GUEST_TOKEN)\n storage.removeItem(LEGACY_GUEST_TOKEN)\n storage.removeItem(CART_GUEST_TOKEN)\n deleteCookie('X-TF-ECOMMERCE')\n emitSessionChange()\n}\n\n/**\n * True when a signed-in access token is present. Cookie-enabled web consumers\n * also recognize an existing legacy storefront session during migration.\n */\nexport const isAuthenticated = (): boolean =>\n Boolean(getAccessToken() || (getConfig().cookieAuth && readCookie('X-TF-ECOMMERCE')))\n","/**\n * The SDK's single HTTP transport. One axios instance, built lazily from\n * `configure()` and rebuilt only if the config reference changes.\n *\n * Matches the engine's checkout client exactly: base is `<host>/api`, the\n * JSON:API content headers, `withCredentials` for the web session cookie, and a\n * request interceptor that sends both identities during the guest → authenticated\n * transition: the bearer identifies the buyer while `Authorization-Guest`\n * preserves the cart that was reserved before login.\n *\n * Self-contained by design: imports nothing from checkout-flow / checkout-core.\n */\nimport axios, {\n AxiosInstance,\n AxiosRequestConfig,\n AxiosResponse,\n InternalAxiosRequestConfig,\n} from 'axios'\n\nimport { allCookies, readCookie, writeCookie } from './cookies'\nimport { getConfig, ResolvedTtfConfig } from './config'\nimport { toTtfError } from './errors'\nimport {\n clearSession,\n getAccessToken,\n getCartGuestToken,\n getGuestToken,\n setGuestToken,\n} from './session'\n\n/** Persist the guest session token the backend echoes on every response. Always\n * on: it is the cookieless session carrier, and bearer-auth consumers (React\n * Native) need it to keep the reserved cart across a mid-checkout login. */\nconst captureGuestToken = (res: AxiosResponse): void => {\n const guest = res.headers?.['authorization-guest']\n if (guest) setGuestToken(String(guest))\n}\n\n/** Persist the login cookie the backend hands back. Browser-only (`cookieAuth`). */\nconst captureCookieSession = (res: AxiosResponse): void => {\n const xtf = res.headers?.['x-tf-ecommerce']\n if (xtf) writeCookie('X-TF-ECOMMERCE', String(xtf))\n}\n\n/** A logged-in buyer can still own a cart created moments earlier as a guest:\n * the bearer identifies the buyer while `Authorization-Guest` preserves the\n * cart's session. Without it the backend swaps a bearer request onto a\n * synthetic empty session (init.php) and on-checkout 422s \"cart expired\". */\nexport const resolveAuthorizationHeaders = (\n accessToken: string | null,\n guestToken: string | null\n): Record<string, string> => ({\n ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),\n ...(guestToken ? { 'Authorization-Guest': guestToken } : {}),\n})\n\nlet instance: AxiosInstance | null = null\nlet builtFrom: ResolvedTtfConfig | null = null\n\nconst build = (config: ResolvedTtfConfig): AxiosInstance => {\n const http = axios.create({\n baseURL: config.apiBaseUrl,\n timeout: 30_000,\n withCredentials: true,\n headers: {\n Accept: 'application/vnd.api+json',\n 'Content-Type': 'application/vnd.api+json',\n },\n })\n\n http.interceptors.request.use((req: InternalAxiosRequestConfig) => {\n const access = getAccessToken()\n const authorization = resolveAuthorizationHeaders(\n access,\n getCartGuestToken() ?? getGuestToken()\n )\n for (const [key, value] of Object.entries(authorization)) {\n req.headers.set(key, value)\n }\n if (config.sourceOrigin) req.headers.set('X-Source-Origin', config.sourceOrigin)\n\n // Cookie-based session context, opt-in for browser white-labels.\n if (config.cookieAuth) {\n const xtf = readCookie('X-TF-ECOMMERCE')\n if (xtf) req.headers.set('X-TF-ECOMMERCE', xtf)\n const cookies = allCookies()\n if (cookies) req.headers.set('Additional-Cookies', cookies)\n }\n\n // Bring-your-own auth wins — merged last (token, cookie, or anything).\n const extra = config.auth?.()\n if (extra) {\n for (const [key, value] of Object.entries(extra)) req.headers.set(key, value)\n }\n return req\n })\n\n http.interceptors.response.use(\n (res) => {\n captureGuestToken(res)\n if (config.cookieAuth) captureCookieSession(res)\n return res\n },\n (error) => {\n if (error?.response) {\n captureGuestToken(error.response)\n if (config.cookieAuth) captureCookieSession(error.response)\n }\n if (error?.response?.status === 401) clearSession()\n return Promise.reject(error)\n }\n )\n\n return http\n}\n\n/** The active axios instance, rebuilt if `configure()` was called with a new object. */\nexport const getHttp = (): AxiosInstance => {\n const config = getConfig()\n if (!instance || builtFrom !== config) {\n instance = build(config)\n builtFrom = config\n }\n return instance\n}\n\n/** Drop the cached instance — used by tests and after `configure()` swaps. */\nexport const resetHttp = (): void => {\n instance = null\n builtFrom = null\n}\n\n// --- thin verbs: return response data, throw a normalized TtfError ----------\n\nexport const get = async <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {\n try {\n return (await getHttp().get<T>(url, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n\nexport const post = async <T>(\n url: string,\n body?: unknown,\n config?: AxiosRequestConfig\n): Promise<T> => {\n try {\n return (await getHttp().post<T>(url, body, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n\nexport const put = async <T>(\n url: string,\n body?: unknown,\n config?: AxiosRequestConfig\n): Promise<T> => {\n try {\n return (await getHttp().put<T>(url, body, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n\nexport const patch = async <T>(\n url: string,\n body?: unknown,\n config?: AxiosRequestConfig\n): Promise<T> => {\n try {\n return (await getHttp().patch<T>(url, body, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n\nexport const del = async <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {\n try {\n return (await getHttp().delete<T>(url, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n","/**\n * THE endpoint registry — every path the SDK calls, in one place, grouped by\n * domain to mirror `api/`, `dtos/`, and the `ttf` facade. No api function spells\n * a URL inline; they all read from here.\n *\n * Conventions:\n * - Paths are relative to the transport base (`<host>/api`) — see `client/http`.\n * A few legacy endpoints live off `/api` (`event/:id/time-slot-by-date`,\n * `event/:id/reservation/refresh/`); those omit the `v1/` prefix on purpose.\n * - `auth.contactEmail` is origin-rooted (NOT under `/api`) — it's joined with\n * `getOriginUrl()` at the call site.\n * - Static resources are string constants; parameterized ones are builder\n * functions that take the id/hash. Dynamic query params (pagination, filters)\n * are appended by the api function — only canonical flags that ARE the\n * endpoint (`?payment_config=1`) are baked in here.\n */\n\nimport { Id } from '../dtos/common'\n\nexport const ENDPOINTS = {\n /** OAuth login, registration, password recovery, and identity verification. */\n auth: {\n /** OAuth step 1 — exchange email+password for an authorization code. */\n authorizeRn: (clientId: Id) => `v1/oauth/authorize-rn?client_id=${clientId}`,\n /** OAuth step 2 — exchange the code for an access token. */\n accessToken: 'v1/oauth/access_token',\n /** Create an account (multipart form data). */\n registerRn: 'v1/oauth/register-rn',\n /** Cookie session — `DELETE` to sign out. */\n session: '/auth',\n /** Request a \"forgot password\" email (web). */\n restorePassword: '/auth/restore-password',\n /** Request a \"forgot password\" email (React Native variant). */\n restorePasswordRn: 'v1/oauth/restore-password-rn',\n /** Complete a password reset with the token from the email. */\n resetPassword: '/auth/reset-password',\n /** Existing-account lookup — ORIGIN-rooted + form-encoded, NOT under /api.\n * Joined with `getOriginUrl()` at the call site. */\n contactEmail: 'ajax/contact-email/',\n /** Read the signed-in user's identity-verification status (Netverify). */\n verificationInfo: 'v1/authenticate/get-verification-info',\n /** `GET` mints the hosted verification URL; `PATCH` marks it PENDING. */\n verify: 'v1/authenticate/verify',\n },\n\n /** The signed-in user's profile. */\n profile: {\n get: '/customer/profile/',\n },\n\n /** Billing-select geography. */\n geo: {\n /** All selectable countries. */\n countries: '/countries/list',\n /** States/provinces for a country (id→name map). */\n states: (countryId: Id) => `/countries/${countryId}/states/`,\n },\n\n /** Event catalog + engagement — everything keyed by an event id. */\n events: {\n /** `GET v1/event/:id` — event details (seated detection, slug, name). */\n info: (eventId: Id) => `v1/event/${eventId}`,\n /** Purchasable ticket types (+ promo/waiting-list metadata). */\n tickets: (eventId: Id) => `v1/event/${eventId}/tickets/`,\n /** Ticket types for one date of a time-slot event (legacy, off /api). */\n timeSlotByDate: (eventId: Id) => `event/${eventId}/time-slot-by-date`,\n /** Event add-ons. */\n addOns: (eventId: Id) => `v1/event/${eventId}/add-ons`,\n /** Custom-field groups (order / ticket / add-on scopes). */\n customFields: (eventId: Id) => `v1/event/${eventId}/custom_fields/`,\n /** Terms/conditions the buyer may need to accept. */\n conditions: (eventId: Id) => `v1/event/${eventId}/conditions`,\n /** Apply a promo/access code to the session. */\n promo: (eventId: Id) => `v1/event/${eventId}/promo`,\n /** Session currency preference (multi-currency events). */\n currency: (eventId: Id) => `v1/event/${eventId}/currency`,\n /** Unlock a password-protected event. */\n authenticate: (eventId: Id) => `v1/event/${eventId}/authenticate`,\n /** Tracking pixel (page view / order attribution). */\n track: (eventId: Id) => `v1/event/${eventId}/track`,\n /** Write ORDER-level custom-field values after the order exists. */\n orderDataCapture: (eventId: Id) => `v1/event/${eventId}/order-data-capture`,\n /** Write TICKET-level (per-holder) custom-field values. */\n ticketDataCapture: (eventId: Id) => `v1/event/${eventId}/ticket-data-capture`,\n /** Attribute the session to a referrer/promoter. */\n referrer: (eventId: Id) => `v1/event/${eventId}/referrer`,\n /** Join the sold-out waiting list. */\n waitingList: (eventId: Id) => `v1/event/${eventId}/add_to_waiting_list`,\n /** Submit RSVP details. */\n rsvp: (eventId: Id) => `v1/event/${eventId}/send-rsvp-info`,\n },\n\n /** Cart + pricing session. */\n cart: {\n /** Read the cart back (pins the event's payment method into the session). */\n get: 'v1/cart/',\n /** Cart + pre-order payment config (identifies the gateway pre-order). */\n withPaymentConfig: 'v1/cart?payment_config=1',\n /** Cart + display-ready server price breakdown; optional add-on query. */\n withPriceBreakdown: (addOnsQuery?: string) =>\n `v1/cart?price_breakdown=1${addOnsQuery ? `&${addOnsQuery}` : ''}`,\n /** Replace the whole cart with the current ticket selection. */\n addToCart: (eventId: Id) => `v1/event/${eventId}/add-to-cart/`,\n /** Price the cart (+ add-ons). */\n checkout: 'v1/checkout',\n /** Checkout gates for the current session (names_required, field gates). */\n checkoutConfigs: 'v1/checkout-configs',\n /** Payment-plan charge by explicit payment method (saved-card shortcut). */\n paymentPlan: (orderHash: string) => `cart/payment-plan/${orderHash}`,\n },\n\n /** Order lifecycle — create, review, finalize. */\n order: {\n /** Create the order from buyer + holders + add-ons (the on-checkout body). */\n create: 'v1/on-checkout/',\n /** Post-order review — gateway identity + Stripe/plan secrets + totals. */\n review: (orderHash: string) => `v1/order/${orderHash}/review`,\n /** Finalize a paid/pending order (emails receipt/voucher, defers webhook). */\n success: (orderHash: string) => `v1/order/${orderHash}/success/`,\n /** Complete a free (zero-total) registration. */\n completeFreeRegistration: (orderHash: string) =>\n `v1/order/${orderHash}/complete_free_registration`,\n /** Guard: does the signed-in user own this order hash. */\n verifyCustomer: (orderHash: string) => `v1/order/${orderHash}/verify-customer-order`,\n /** ID-verification round trip (`?url=1` mints the provider session URL). */\n idVerification: (orderHash: string, mintUrl?: boolean) =>\n `v1/order/${orderHash}/id-verification${mintUrl ? '?url=1' : ''}`,\n /** Confirmation-page payload for a completed order. */\n confirmation: (orderHash: string) => `v1/order/${orderHash}/payment/complete`,\n },\n\n /** Payment rails — the per-gateway wire after the order exists. */\n payment: {\n /** Xendit charges (e-wallets AND cards) — form-encoded, not JSON:API. */\n submitPayment: (orderHash: string) => `payments/submit-payment/${orderHash}`,\n /** OXXO: move the order to the pending-voucher state before the confirm. */\n prepareOxxo: (orderHash: string) => `order/${orderHash}/prepare-for-oxxo`,\n /** Per-payment-method-type fee re-price (re-fetch the review after). */\n methodType: (orderHash: string) => `v1/order/${orderHash}/payment-method-type`,\n /** MSI installment offers (between PM creation and the confirm). */\n installmentOffers: (orderHash: string) => `stripe/${orderHash}/installment-offers`,\n /** MSI confirm (server-side; follow with handleNextAction only). */\n confirmInstallments: (orderHash: string) =>\n `stripe/${orderHash}/confirm-installments`,\n /** PayPal Standard step 1 — switch the placed order's method. */\n changeMethod: 'v1/change-payment-method',\n /** PayPal Standard step 2 — the {action_url, fields} to top-level POST. */\n paypalForm: (orderHash: string) => `v1/order/${orderHash}/paypal-form`,\n /** Server-side confirm for redirect-based Stripe methods. */\n confirmRedirect: (orderHash: string) =>\n `v1/order/${orderHash}/stripe/confirm-redirect`,\n /** Schedule a payment plan against a new card's PaymentMethod. */\n paymentPlanCreate: (orderHash: string) => `v1/order/${orderHash}/payment_plan/create`,\n },\n\n /** Account — the buyer's own orders and tickets. */\n account: {\n /** Order history (server-paginated; caller appends page/limit/filter query). */\n orders: 'v1/account/orders/',\n /** One order's full detail. */\n order: (orderId: Id) => `v1/account/order/${orderId}`,\n /** The buyer's tickets/wallet (caller appends the query). */\n tickets: 'v1/account/tickets/',\n /** Twilio-backed phone validation. */\n validatePhone: (phone: string) =>\n `/v1/account/validate_phone?phone=${encodeURIComponent(phone)}`,\n },\n\n /** Ticket resale. */\n resale: {\n sell: (ticketId: Id) => `v1/ticket/${ticketId}/sell`,\n process: (ticketId: Id) => `v1/ticket/${ticketId}/process`,\n decline: (ticketId: Id) => `v1/ticket/${ticketId}/decline`,\n },\n\n /** Pre-registration (\"register interest, then share\"). */\n preRegistration: {\n /** Confirm pre-registration for an event. */\n confirm: (eventId: Id) => `v1/event/${eventId}/pre-registration/confirm`,\n /** Influencers/promoters available to share to. */\n influencers: (eventId: Id) => `v1/event/${eventId}/pre-registration/influencers`,\n /** The post-confirm share page (options + current standing). */\n confirmationPage: (hash: string) => `/v1/pre-registration/${hash}/confirmation-page`,\n /** Record a share action (a referral phase step). */\n submitAction: (hash: string) => `/v1/pre-registration/${hash}/submit-action`,\n },\n\n /** Guest ticket delegation (claim a ticket via an access link). */\n delegation: {\n /** Whether the recipient already has an account. */\n customerExists: (accessHash: string) =>\n `/v1/delegation-access/${accessHash}/customer-exists`,\n /** The claim page (event + ticket context). */\n consumerPageInfo: (accessHash: string) =>\n `v1/delegation-access/${accessHash}/consumer-page-info`,\n /** Issue (claim) the delegated ticket. */\n issueTicket: (accessHash: string) =>\n `v1/delegation-access/${accessHash}/issue-ticket`,\n },\n\n /** Seated events — the seat picker's wire. */\n seatmap: {\n /** The venue seat map. */\n data: (eventId: Id) => `v1/event/${eventId}/seat-map-data`,\n /** Live seat statuses (poll during selection). */\n statuses: (eventId: Id) => `v1/event/${eventId}/seats/status`,\n /** Reserve a seat selection. */\n reserve: (eventId: Id) => `v1/event/${eventId}/seats/reserve`,\n /** Release a held reservation. */\n deleteReserved: (eventId: Id) => `v1/event/${eventId}/seats/delete-reserved`,\n /** Extend a reservation's TTL (legacy, off /api). */\n refreshReservation: (eventId: Id) => `event/${eventId}/reservation/refresh/`,\n },\n} as const\n\n/** The `ENDPOINTS` shape, for callers that want to type against it. */\nexport type Endpoints = typeof ENDPOINTS\n","/**\n * Gateway-level constant sets: which Stripe payment-method types re-price the\n * order, and the Xendit processor rules. Pure data — the logic that reads them\n * lives in `logic/`.\n */\n\n/** Non-single-charge Stripe payment modes: every type here re-prices the order\n * before the client confirm. Card and wallet payments stay single_charge and\n * skip the call. */\nexport const FEE_MODE_PAYMENT_METHOD_TYPES: ReadonlySet<string> = new Set([\n 'afterpay_clearpay',\n 'zip',\n 'affirm',\n 'klarna',\n 'bancontact',\n 'paypal',\n 'ideal',\n 'cashapp',\n 'oxxo',\n 'crypto',\n 'mb_way',\n])\n\n/** Xendit wallet keys that need one extra buyer-typed field before charging. */\nexport const XENDIT_EWALLET_EXTRA_FIELD: Readonly<Record<string, string>> = {\n jenius_pay: 'cashtag',\n ovo: 'phoneNumber',\n}\n\n/** Xendit selector rows that are NOT one-tap e-wallet charges (cards tokenize\n * client-side, bank transfers issue virtual accounts) — filter these out when\n * offering the wallet buttons. */\nexport const XENDIT_NON_EWALLET_PROCESSORS: ReadonlySet<string> = new Set([\n 'credit_card',\n 'bank_transfer',\n 'virtual_account',\n])\n","/**\n * Redirect-based Stripe payment methods (Klarna/Afterpay/Affirm/iDEAL-class)\n * the WebView/popup round trip supports, keyed by the server's\n * payment_method_types spelling.\n */\nexport const SUPPORTED_REDIRECT_METHODS: ReadonlySet<string> = new Set([\n 'klarna',\n 'afterpay_clearpay',\n 'affirm',\n 'ideal',\n 'bancontact',\n 'eps',\n 'giropay',\n 'p24',\n 'alipay',\n 'grabpay',\n 'cashapp',\n 'paypal',\n])\n\n/** Filters a server `paymentMethodTypes` list to the redirect methods the flow\n * supports (order preserved, unknown types dropped). */\nexport const listRedirectMethods = (paymentMethodTypes?: string[] | null): string[] =>\n (paymentMethodTypes || []).filter(\n (type) => typeof type === 'string' && SUPPORTED_REDIRECT_METHODS.has(type)\n )\n","/**\n * Gateway identity — which processor an event/order pays through, read the same\n * way the hosted embed keys on it. Post-order (`detectGateway`, off the review's\n * payment_method) and pre-order (`identifyPreOrderGateway` + the Xendit/PayPal\n * config, off the cart payment block).\n */\nimport type {\n Gateway,\n PayPalTabConfig,\n PreOrderGateway,\n PreOrderPaymentConfig,\n XenditPreOrderConfig,\n XenditProcessor,\n} from '../dtos'\n\n/** Post-order gateway from the review's payment_method block. */\nexport const detectGateway = (\n paymentMethod: Record<string, unknown> | null | undefined\n): Gateway => {\n const pm = paymentMethod || {}\n if (pm.stripe_publishable_key || pm.stripe_client_secret) return 'stripe'\n const name = String(pm.name || '').toLowerCase()\n if (pm.razorpay_key_id || pm.key_id || name.indexOf('razorpay') !== -1) {\n return 'razorpay'\n }\n if (pm.xendit_publishable_key || name.indexOf('xendit') !== -1) return 'xendit'\n return 'unsupported'\n}\n\nconst paymentBlock = (\n cartAttributes: Record<string, unknown> | null | undefined\n): Record<string, unknown> | null => {\n const payment = cartAttributes && (cartAttributes.payment as Record<string, unknown>)\n return payment && typeof payment === 'object' ? payment : null\n}\n\n/** Pre-order gateway from the cart payment-config block. Null when unrecognised. */\nexport const identifyPreOrderGateway = (\n cartAttributes: Record<string, unknown> | null | undefined\n): PreOrderGateway | null => {\n const payment = paymentBlock(cartAttributes)\n const gateway = payment && payment.gateway\n if (\n gateway === 'stripe_payment_intents' ||\n gateway === 'xendit' ||\n gateway === 'razorpay'\n ) {\n return gateway\n }\n return null\n}\n\n/** Xendit pre-order config (publishable key, processors, UI). Null when the\n * event isn't Xendit or the key is missing. */\nexport const xenditPreOrderConfig = (\n cartAttributes: Record<string, unknown> | null | undefined\n): XenditPreOrderConfig | null => {\n const payment = paymentBlock(cartAttributes)\n if (!payment || payment.gateway !== 'xendit') return null\n const method = payment.payment_method as Record<string, unknown> | undefined\n const publishableKey = method && method.xendit_publishable_key\n if (typeof publishableKey !== 'string' || !publishableKey) return null\n return {\n publishableKey,\n onBehalfOf:\n typeof method?.xendit_on_behalf_of === 'string' && method.xendit_on_behalf_of\n ? method.xendit_on_behalf_of\n : null,\n processors: Array.isArray(payment.payment_processors)\n ? (payment.payment_processors as XenditProcessor[])\n : [],\n failureReasons:\n payment.failure_reasons && typeof payment.failure_reasons === 'object'\n ? (payment.failure_reasons as Record<string, string>)\n : {},\n ui:\n payment.ui && typeof payment.ui === 'object'\n ? (payment.ui as Record<string, string>)\n : {},\n }\n}\n\n/** PayPal Standard tab config off the cart payment block. Null when absent. */\nexport const paypalTabConfig = (\n cartAttributes: Record<string, unknown> | null | undefined\n): PayPalTabConfig | null => {\n const payment = paymentBlock(cartAttributes)\n const paypal = payment && (payment.paypal as PayPalTabConfig | null)\n if (!paypal || typeof paypal !== 'object') return null\n if (!paypal.payment_method_id || !paypal.payment_method_hash) return null\n return paypal\n}\n\n/** Pre-order deferred Stripe Elements config (single-page card mount). Null in\n * every fallback case (no config, non-Stripe, free cart). */\nexport const resolvePaymentConfig = (\n cartAttributes: Record<string, unknown> | null | undefined\n): PreOrderPaymentConfig | null => {\n const payment = cartAttributes && (cartAttributes.payment as PreOrderPaymentConfig)\n if (!payment || typeof payment !== 'object') return null\n if (!payment.elements_config || !payment.basic_config || !payment.basic_config.apiKey) {\n return null\n }\n return payment\n}\n","/**\n * Pricing logic — resolve the display-ready server breakdown, build the\n * display-only add-on query, and map `stripe_wallets` to the Payment Element\n * wallets option (payment-plan mode forces both wallets off — they can't\n * authorize future installments).\n */\nimport type { PriceBreakdown, StripeWallets, WalletsOption } from '../dtos'\n\n/** Query-string form of the display-only add-on map: `add_ons[<id>]=<qty>`.\n * The server caps at 50 entries / qty 100 and drops anything not in the cart. */\nexport const priceBreakdownAddOnsQuery = (\n addOns: Record<string | number, number> | null | undefined\n): string =>\n Object.entries(addOns || {})\n .filter(([id, qty]) => Number(id) > 0 && Number(qty) > 0)\n .map(([id, qty]) => `add_ons[${Number(id)}]=${Number(qty)}`)\n .join('&')\n\n/** Pull the `price_breakdown` block off cart attributes. Null when the backend\n * doesn't serve it (older backends) — callers keep their own rendering. */\nexport const resolvePriceBreakdown = (\n cartAttributes: Record<string, unknown> | null | undefined\n): PriceBreakdown | null => {\n const breakdown =\n cartAttributes && (cartAttributes.price_breakdown as PriceBreakdown | null)\n if (!breakdown || typeof breakdown !== 'object') return null\n if (typeof breakdown.total !== 'string' || !Array.isArray(breakdown.tickets)) {\n return null\n }\n return {\n ...breakdown,\n add_ons: Array.isArray(breakdown.add_ons) ? breakdown.add_ons : [],\n }\n}\n\nexport const walletsOption = (\n stripeWallets: StripeWallets | null | undefined,\n paymentPlanMode = false\n): WalletsOption => {\n if (paymentPlanMode) {\n return { applePay: 'never', googlePay: 'never' }\n }\n const w = stripeWallets || {}\n return {\n applePay: w.applePay === false || w.applePay === 'never' ? 'never' : 'auto',\n googlePay: w.googlePay === false || w.googlePay === 'never' ? 'never' : 'auto',\n }\n}\n","/**\n * Checkout logic — compose the on-checkout body (in-body per-ticket capture,\n * order data_capture, buyer fields), evaluate buyer-field gates, find missing\n * required add-ons, and detect seated events.\n *\n * `buildOnCheckoutBody` matters: on_checkout is the SAME engine the hosted\n * checkout runs, and REQUIRED custom fields are validated AT PLACEMENT — events\n * with required fields can only be placed when the capture rides this body.\n */\nimport type {\n BuyerFieldVisibility,\n CheckoutBilling,\n CheckoutBreakdown,\n CheckoutHolder,\n CustomFieldValues,\n EventAddon,\n EventCustomField,\n EventCustomFieldGroup,\n FieldGates,\n OnCheckoutAttributes,\n OnCheckoutInput,\n RequiredAddOnLike,\n TicketSelection,\n TicketType,\n} from '../dtos'\n\nconst hasKeys = (value?: Record<string, unknown>) =>\n !!value && Object.keys(value).length > 0\n\n/** True when a custom-field answer has been provided (array = at least one). */\nexport const hasValue = (value: string | string[] | undefined): boolean =>\n Array.isArray(value)\n ? value.length > 0\n : Boolean(value !== undefined && String(value).trim())\n\n/** The checkout's single email rule — UIs must not re-derive their own. */\nexport const isEmail = (value: string | undefined): boolean =>\n /^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/.test(value?.trim() ?? '')\n\n/** The checkout's single phone rule: 7–15 digits, punctuation ignored. */\nexport const isPhone = (value: string | undefined): boolean => {\n const digits = value?.replace(/\\D/g, '') ?? ''\n return digits.length >= 7 && digits.length <= 15\n}\n\nconst ageOn = (billing: CheckoutBilling, now: Date): number | null => {\n const { dobDay, dobMonth, dobYear } = billing\n if (!dobDay || !dobMonth || !dobYear) return null\n let age = now.getUTCFullYear() - dobYear\n const birthdayPassed =\n now.getUTCMonth() + 1 > dobMonth ||\n (now.getUTCMonth() + 1 === dobMonth && now.getUTCDate() >= dobDay)\n if (!birthdayPassed) age -= 1\n return age\n}\n\nconst ticketSlots = (\n breakdown: CheckoutBreakdown | undefined,\n selections: TicketSelection[]\n): { ticketTypeId?: string }[] => {\n const slots: { ticketTypeId?: string }[] = []\n if (breakdown?.tickets.length) {\n for (const line of breakdown.tickets)\n for (let i = 0; i < line.quantity; i++)\n slots.push({ ticketTypeId: line.ticketTypeId })\n return slots\n }\n for (const selection of selections)\n for (let i = 0; i < selection.quantity; i++) slots.push({})\n return slots\n}\n\n/**\n * Does a ticket-scoped custom field apply to this ticket type? A field with no\n * `ticketTypeIds` applies to every ticket. This is the single owner of the rule\n * — the UIs previously each carried their own copy.\n */\nexport const fieldAppliesToTicketType = (\n field: Pick<EventCustomField, 'ticketTypeIds'>,\n ticketTypeId?: string | number\n): boolean =>\n !ticketTypeId ||\n !field.ticketTypeIds ||\n field.ticketTypeIds.map(String).includes(String(ticketTypeId))\n\n/** The ticket-scoped fields that apply to a given ticket type. */\nexport const ticketFieldsFor = <T extends Pick<EventCustomField, 'ticketTypeIds'>>(\n fields: T[],\n ticketTypeId?: string | number\n): T[] => fields.filter((field) => fieldAppliesToTicketType(field, ticketTypeId))\n\n/**\n * Are every required field in `fields` answered? Mirrors the engine's own\n * preflight, including its rule that `image` fields are server-authoritative\n * and never block the client.\n */\nexport const customFieldsComplete = (\n fields: EventCustomField[],\n values: CustomFieldValues\n): boolean =>\n fields\n .filter((field) => field.required && field.type !== 'image')\n .every((field) => hasValue(values[field.name]))\n\nconst requiredFields = (\n groups: EventCustomFieldGroup[],\n scope: 'order' | 'ticket'\n): EventCustomField[] =>\n groups\n .filter((group) => group.scope === scope)\n .flatMap((group) => group.fields)\n // Image upload is not supported by this checkout yet. The server remains\n // authoritative for those fields, matching the engine preflight.\n .filter((field) => field.required && field.type !== 'image')\n\nexport interface CheckoutDetailsState {\n billing?: CheckoutBilling\n holders: CheckoutHolder[]\n selections: TicketSelection[]\n breakdown?: CheckoutBreakdown\n holderNamesRequired: boolean\n fieldGates: BuyerFieldVisibility\n customFields: EventCustomFieldGroup[]\n}\n\nexport interface CheckoutDetailsValidationOptions {\n /** Embedded guest checkout asks the buyer to type their email twice. */\n requireEmailConfirmation?: boolean\n /** Always collect one named holder per selected ticket. The hosted event\n * checkout normally follows the backend holder-name/custom-field gates;\n * tf-sports' embedded flow opts into this stricter policy. */\n collectTicketHolders?: boolean\n /** Storefront parity: collect email and phone for every ticket holder. */\n requireHolderContact?: boolean\n /** Injectable clock keeps minimum-age checks deterministic in tests. */\n now?: Date\n}\n\n/**\n * One source of truth for every buyer/holder field that must be completed\n * before payment. UI sections use the returned labels for gating and the\n * framework-agnostic engine calls the same function during preflight.\n */\nexport const missingCheckoutDetails = (\n state: CheckoutDetailsState,\n options: CheckoutDetailsValidationOptions = {}\n): string[] => {\n const missing: string[] = []\n const billing = state.billing\n if (!billing) return ['Billing details']\n\n if (!billing.firstName.trim()) missing.push('First name')\n if (!billing.lastName.trim()) missing.push('Last name')\n if (!isEmail(billing.email)) missing.push('Valid email address')\n if (\n options.requireEmailConfirmation &&\n billing.confirmEmail?.trim().toLowerCase() !== billing.email.trim().toLowerCase()\n ) {\n missing.push('Matching email confirmation')\n }\n\n const gates = state.fieldGates\n if (gates.nationalityRequired && !billing.nationality?.trim()) {\n missing.push('Nationality')\n }\n if (gates.genderRequired && !billing.gender?.trim()) missing.push('Gender')\n if (gates.requireInstagram && !billing.instagramHandle?.trim()) {\n missing.push('Instagram handle')\n }\n if (gates.phoneRequired && !isPhone(billing.phone)) missing.push('Valid phone number')\n if (gates.dobRequired) {\n const age = ageOn(billing, options.now ?? new Date())\n if (age === null) missing.push('Date of birth')\n else if (gates.minimumAge !== undefined && age < gates.minimumAge) {\n missing.push(`Age ${gates.minimumAge} or older`)\n }\n }\n if (gates.showAddress) {\n if (!billing.streetAddress?.trim()) missing.push('Street address')\n if (!billing.city?.trim()) missing.push('City')\n if (!billing.zip?.trim()) missing.push('ZIP / postcode')\n if (!billing.countryId) missing.push('Country')\n if (billing.stateRequired && !billing.stateId) missing.push('State / county')\n }\n\n for (const field of requiredFields(state.customFields, 'order')) {\n if (!hasValue(billing.dataCapture?.[field.name])) {\n missing.push(field.label || field.name)\n }\n }\n\n const slots = ticketSlots(state.breakdown, state.selections)\n const ticketFields = requiredFields(state.customFields, 'ticket')\n const holderNamesRequired =\n state.holderNamesRequired || options.collectTicketHolders === true\n const needsHolders = holderNamesRequired || ticketFields.length > 0\n const holderContactRequired = options.requireHolderContact && needsHolders\n if (needsHolders) {\n slots.forEach((slot, index) => {\n const holder = state.holders[index]\n const ticketNumber = index + 1\n if (holderNamesRequired) {\n if (!holder?.firstName.trim()) {\n missing.push(`Ticket ${ticketNumber} holder first name`)\n }\n if (!holder?.lastName.trim()) {\n missing.push(`Ticket ${ticketNumber} holder last name`)\n }\n }\n if (holderContactRequired) {\n if (!isEmail(holder?.email)) {\n missing.push(`Ticket ${ticketNumber} holder email`)\n }\n if (!isPhone(holder?.phone)) {\n missing.push(`Ticket ${ticketNumber} holder phone`)\n }\n }\n for (const field of ticketFields) {\n const ticketTypeId = holder?.ticketTypeId ?? slot.ticketTypeId\n if (\n field.ticketTypeIds &&\n ticketTypeId &&\n !field.ticketTypeIds.map(String).includes(String(ticketTypeId))\n ) {\n continue\n }\n if (!hasValue(holder?.ticketDataCapture?.[field.name])) {\n missing.push(`${field.label || field.name} (ticket ${ticketNumber})`)\n }\n }\n })\n }\n\n return missing\n}\n\n/** Merge the parity fields into an existing attributes `base` object. */\nexport const buildOnCheckoutBody = (\n input: OnCheckoutInput,\n base: Record<string, unknown> = {}\n): OnCheckoutAttributes & Record<string, unknown> => {\n const attributes: OnCheckoutAttributes & Record<string, unknown> = { ...base }\n\n const buyer = input.buyerFields || {}\n if (buyer.nationality !== undefined && buyer.nationality !== '') {\n attributes.nationality = buyer.nationality\n }\n if (buyer.gender) {\n attributes.gender = buyer.gender\n }\n if (buyer.instagramHandle) {\n attributes.instagram_handle = buyer.instagramHandle\n }\n\n if (hasKeys(input.dataCapture)) {\n attributes.data_capture = { ...input.dataCapture }\n }\n\n if (input.ticketHolders && input.ticketHolders.length) {\n const holders: Array<Record<string, unknown>> = []\n const ticketDataCapture: Array<Record<string, unknown>> = []\n let hasTicketCapture = false\n\n input.ticketHolders.forEach((holder) => {\n const row: Record<string, unknown> = {\n first_name: holder.firstName || '',\n last_name: holder.lastName || '',\n }\n if (holder.email !== undefined) row.email = holder.email\n if (holder.phone !== undefined) row.phone = holder.phone\n if (holder.ticketTypeId !== undefined) {\n row.ticket_type_id = holder.ticketTypeId\n }\n const capture = holder.ticketDataCapture || {}\n if (hasKeys(capture)) {\n row.ticket_data_capture = { ...capture }\n hasTicketCapture = true\n }\n holders.push(row)\n ticketDataCapture.push(hasKeys(capture) ? { ...capture } : {})\n })\n\n attributes.ticket_holders = holders\n\n if (hasTicketCapture) {\n attributes.ticket_data_capture = ticketDataCapture\n }\n }\n\n if (hasKeys(input.addOns)) {\n attributes.add_ons = { ...(input.addOns as Record<string, number>) }\n }\n\n if (hasKeys(input.addOnDataCapture)) {\n attributes.add_on_data_capture = { ...input.addOnDataCapture }\n }\n\n return attributes\n}\n\n/** Evaluate the buyer-field gates off `GET v1/checkout-configs` (next_page_info). */\nexport const evaluateFieldGates = (\n gates: FieldGates | null | undefined\n): BuyerFieldVisibility => {\n const g = gates || {}\n const showNationality = !!g.show_nationality_field\n const showGender = !!g.show_gender_field\n const minAge = g.minimum_age == null ? undefined : Number(g.minimum_age)\n return {\n showNationality,\n nationalityRequired: showNationality && !!g.nationality_field_required,\n showGender,\n genderRequired: showGender && !!g.gender_field_required,\n requireInstagram: !!g.require_instagram,\n showPhone: !g.hide_phone_field,\n phoneRequired: !!g.phone_required,\n showDob: !!g.age_required,\n dobRequired: !!g.age_required,\n minimumAge: Number.isFinite(minAge) ? minAge : undefined,\n showAddress: !g.free_ticket,\n }\n}\n\n/**\n * The required add-ons the selection is still missing. Empty means the\n * requirement is satisfied. A sold-out required add-on (stock exactly 0) is\n * exempt — it never blocks placement (the hosted rule).\n */\nexport const missingRequiredAddOns = <T extends RequiredAddOnLike>(\n addOns: T[] | null | undefined,\n selectedQuantities: Record<string | number, number> | null | undefined\n): T[] =>\n (addOns || []).filter((addOn) => {\n if (!addOn.required || addOn.active === false) return false\n if (addOn.stock === 0) return false\n return (Number(selectedQuantities?.[addOn.id]) || 0) < 1\n })\n\n/** The hosted cap when nothing else bounds an add-on (embed-checkout-app.js). */\nexport const ADD_ON_DEFAULT_MAX_QUANTITY = 10\n\n/**\n * The selectable quantity cap for ONE add-on — the minimum of every bound that\n * applies, mirroring the hosted `order_add_on` partial exactly:\n *\n * - `flagLimitToTicketQuantity` → the number of tickets in the cart\n * - `limitPerTicket` → `limitPerTicket × ticketQuantity`\n * - `maxQuantity` → itself (already min'd with available stock\n * server-side on public reads)\n * - nothing set → the hosted default of 10\n * - `isCheckbox` → a yes/no choice, so at most 1\n *\n * This is NOT cosmetic: the server hard-rejects quantities above these\n * (`add_on_max_quantity`), so an over-generous picker builds an order that\n * fails at placement. `stock` is deliberately not a candidate — on public\n * reads it is only a sold-out signal (0 or null), never a count.\n */\nexport const addOnMaxQuantity = (\n addOn: Pick<\n EventAddon,\n 'flagLimitToTicketQuantity' | 'limitPerTicket' | 'maxQuantity' | 'isCheckbox'\n >,\n ticketQuantity: number\n): number => {\n const candidates: number[] = []\n if (addOn.flagLimitToTicketQuantity) candidates.push(ticketQuantity)\n if (addOn.limitPerTicket && addOn.limitPerTicket > 0) {\n candidates.push(Math.floor(addOn.limitPerTicket) * ticketQuantity)\n }\n if (addOn.maxQuantity && addOn.maxQuantity > 0) {\n candidates.push(Math.floor(addOn.maxQuantity))\n }\n const max = candidates.length\n ? Math.max(0, Math.min(...candidates))\n : ADD_ON_DEFAULT_MAX_QUANTITY\n return addOn.isCheckbox ? Math.min(max, 1) : max\n}\n\n/**\n * The selectable quantity bounds for a ticket type's dropdown: `{ min, max,\n * step }`. Tables are the subtlety — their quantity is a GUEST count (bounded by\n * `minGuests`/`maxGuests`), not a count of tickets, so a \"full table of 8\" must\n * offer 8…maxGuests and never a smaller number; the generic `min/maxQuantity`\n * stay 1/10 on the wire and would wrongly let the buyer pick fewer. `step` is the\n * `multiplier` (the cart sells in blocks of N). Mirrors the old checkout's\n * `getTicketSelectOptions(maxCount, minCount, multiplier)` with\n * `maxCount = isTable ? maxGuests : maxQuantity`.\n */\nexport const ticketQuantityRange = (\n ticket: Pick<\n TicketType,\n 'isTable' | 'minQuantity' | 'maxQuantity' | 'minGuests' | 'maxGuests' | 'multiplier'\n >\n): { min: number; max: number; step: number } => ({\n min: ticket.isTable ? (ticket.minGuests ?? ticket.minQuantity) : ticket.minQuantity,\n max: ticket.isTable ? (ticket.maxGuests ?? ticket.maxQuantity) : ticket.maxQuantity,\n step: ticket.multiplier || 1,\n})\n\n/**\n * Reserved-seating detection. A seated event sells through a seat-map picker, so\n * a surface without one hands the buyer off to the event page. Accepts event\n * details, the cart/payment payload, or raw event attributes.\n */\nexport const isSeatedEvent = (event: object | null | undefined): boolean => {\n const e = (event || {}) as Record<string, unknown>\n return !!(e.seatMapAllowed || e.flagSeatMapAllowed || e.seat_map_allowed === 'yes')\n}\n","/**\n * Payment logic — the pure request-builders and response-interpreters each rail\n * needs: redirect confirm, OXXO voucher, PayPal Standard, saved-card plan, fee\n * re-price, MSI installments, and Xendit e-wallets. The `payment` api calls\n * these; they touch no transport.\n */\nimport { FEE_MODE_PAYMENT_METHOD_TYPES } from '../constants'\nimport type {\n ChangePaymentMethodInput,\n InstallmentOffer,\n InstallmentOffers,\n OxxoVoucher,\n PaymentMethodTypeInput,\n PaymentMethodTypeRequest,\n PayPalForm,\n RedirectConfirmResponse,\n RedirectOutcome,\n SavedPlanCard,\n XenditChargeOutcome,\n XenditEWalletChargeInput,\n} from '../dtos'\n\n// --- redirect methods ------------------------------------------------------\n\nexport const interpretRedirectConfirm = (\n response: RedirectConfirmResponse\n): RedirectOutcome => {\n if (response.requires_action && response.redirect_url) {\n return { kind: 'redirect', url: response.redirect_url }\n }\n if (response.requires_action && response.client_secret) {\n return {\n kind: 'inline_action',\n clientSecret: response.client_secret,\n nextActionType: response.next_action_type || '',\n }\n }\n if (response.requires_action) {\n return { kind: 'unresolved_action', status: response.status }\n }\n return { kind: 'settled', status: response.status }\n}\n\n// --- OXXO ------------------------------------------------------------------\n\n/** Read the voucher off a confirmed PaymentIntent's next action — tolerant of\n * both the web (oxxo_display_details) and RN (voucherURL) shapes. */\nexport const oxxoVoucherFromNextAction = (\n nextAction: Record<string, unknown> | null | undefined\n): OxxoVoucher | null => {\n if (!nextAction || typeof nextAction !== 'object') return null\n\n const details = nextAction.oxxo_display_details as Record<string, unknown> | undefined\n if (details && typeof details.hosted_voucher_url === 'string') {\n return {\n voucherUrl: details.hosted_voucher_url,\n voucherNumber: typeof details.number === 'string' ? details.number : null,\n expiresAt: typeof details.expires_after === 'number' ? details.expires_after : null,\n }\n }\n\n if (typeof nextAction.voucherURL === 'string' && nextAction.voucherURL) {\n return {\n voucherUrl: nextAction.voucherURL,\n voucherNumber:\n typeof nextAction.voucherNumber === 'string' ? nextAction.voucherNumber : null,\n expiresAt: typeof nextAction.expiration === 'number' ? nextAction.expiration : null,\n }\n }\n\n return null\n}\n\n// --- PayPal Standard + saved-card plan -------------------------------------\n\nexport const buildChangePaymentMethodAttributes = (\n input: ChangePaymentMethodInput\n): Record<string, unknown> => ({\n payment_method_id: input.paymentMethodId,\n payment_method_hash: input.paymentMethodHash,\n order_id: Number(input.orderId),\n order_hash: input.orderHash,\n redirect: false,\n})\n\nexport const resolvePayPalForm = (\n attributes: Record<string, unknown> | null | undefined\n): PayPalForm | null => {\n const actionUrl = attributes && attributes.action_url\n const fields = attributes && attributes.fields\n if (typeof actionUrl !== 'string' || !actionUrl) return null\n if (!fields || typeof fields !== 'object') return null\n return { action_url: actionUrl, fields: fields as Record<string, string> }\n}\n\n/** The saved-card shortcut off the review's payment_method — null unless the\n * plan configuration carries a reusable card. */\nexport const savedPlanCard = (\n paymentMethod: Record<string, unknown> | null | undefined\n): SavedPlanCard | null => {\n const plan = paymentMethod?.stripe_payment_plan_configuration as\n | Record<string, unknown>\n | undefined\n const savedCard = plan?.saved_card as Record<string, unknown> | undefined\n const paymentMethodId = savedCard?.stripe_payment_method_id\n if (typeof paymentMethodId !== 'string' || !paymentMethodId) return null\n return {\n last4: typeof savedCard?.last_4_digits === 'string' ? savedCard.last_4_digits : '',\n paymentMethodId,\n }\n}\n\n// --- fee re-price ----------------------------------------------------------\n\nexport const requiresFeeReprice = (type: string | null | undefined): boolean =>\n !!type && FEE_MODE_PAYMENT_METHOD_TYPES.has(type)\n\nexport const buildPaymentMethodTypeAttributes = (\n input: PaymentMethodTypeInput\n): PaymentMethodTypeRequest => ({\n payment_method_type: input.paymentMethodType,\n order_id: Number(input.orderId),\n order_hash: input.orderHash,\n stripe_intent_id: input.stripeIntentId,\n})\n\n/** A PaymentIntent client secret is `pi_<id>_secret_<nonce>` — the review\n * carries the secret, the re-price endpoint wants the id. Null for setup-intent\n * secrets (seti_…) and anything else. */\nexport const paymentIntentIdFromClientSecret = (\n clientSecret: string | null | undefined\n): string | null => {\n const match = /^(pi_[A-Za-z0-9]+)_secret_/.exec(clientSecret || '')\n return match ? match[1] : null\n}\n\n// --- MSI installments ------------------------------------------------------\n\nexport const buildInstallmentOffersFields = (input: {\n paymentIntentId: string\n paymentMethodId: string\n}): Record<string, string> => ({\n payment_intent: input.paymentIntentId,\n payment_method: input.paymentMethodId,\n})\n\nexport const resolveInstallmentOffers = (\n raw: Record<string, unknown> | null | undefined\n): InstallmentOffers => ({\n installments: Array.isArray(raw?.installments)\n ? (raw?.installments as InstallmentOffer[])\n : [],\n installmentsSupported: !!raw?.installments_supported,\n original:\n raw?.original && typeof raw.original === 'object'\n ? (raw.original as InstallmentOffers['original'])\n : {},\n})\n\nexport const buildConfirmInstallmentsFields = (input: {\n paymentIntentId: string\n offer: InstallmentOffer\n}): Record<string, string> => ({\n payment_intent: input.paymentIntentId,\n 'installments[count]': String(input.offer.count),\n 'installments[interval]': input.offer.interval,\n 'installments[type]': input.offer.type,\n})\n\nexport const confirmInstallmentsHasNextAction = (\n raw: Record<string, unknown> | null | undefined\n): boolean => !!raw?.has_next_action\n\n// --- Xendit e-wallets ------------------------------------------------------\n\n/** The flat form-field map (PHP bracket notation) the charge endpoint reads —\n * send it form-encoded, never as JSON. */\nexport const buildXenditEWalletChargeFields = (\n input: XenditEWalletChargeInput\n): Record<string, string> => {\n const fields: Record<string, string> = {\n order: String(input.orderId),\n orderHash: input.orderHash,\n 'paymentData[paymentType]': input.paymentType,\n }\n if (input.cashtag) fields['paymentData[data][cashtag]'] = input.cashtag\n if (input.phoneNumber) fields['paymentData[data][phoneNumber]'] = input.phoneNumber\n return fields\n}\n\nexport const interpretXenditChargeResponse = (\n raw: Record<string, unknown> | null | undefined\n): XenditChargeOutcome => {\n const redirectUrl = raw && raw.redirectUrl\n if (typeof redirectUrl === 'string' && redirectUrl) {\n return {\n kind: 'redirect',\n url: redirectUrl,\n notice: typeof raw?.popupMessage === 'string' ? raw.popupMessage : null,\n }\n }\n const reason =\n (typeof raw?.message === 'string' && raw.message) ||\n (typeof raw?.failure_reason === 'string' && raw.failure_reason) ||\n 'The payment could not be started. Please try again or pick a different payment method.'\n return { kind: 'failed', reason }\n}\n","/**\n * Payment-plan terms — the buyer-facing disclosure block.\n *\n * A faithful port of the hosted checkout's `renderPaymentPlanSelector`\n * (embed-checkout-app.js), which composes these paragraphs from the same\n * `payment_plan_configuration` the backend already sends us. Everything here is\n * pure string composition over the preview DTO, so web and native render the\n * identical wording and one set of tests covers both.\n *\n * This is not cosmetic copy. The admin-fee line states a real per-installment\n * charge, and the non-refundable line states what the buyer forfeits if they\n * default. A plan UI that omits them is understating the cost of the purchase.\n *\n * Wording is the hosted DEFAULT for each i18n key. Consumers that already\n * localize can map over the returned parts by `id`.\n */\nimport type { CheckoutPaymentPlanPreview } from '../dtos'\n\n/** The default word for a plan when the brand hasn't renamed it. */\nexport const DEFAULT_PLAN_TERMINOLOGY = 'Payment Plan'\n\n/** The brand's word for the plan — \"Payment Plan\", \"Layaway\", … */\nexport const planTerminology = (plan?: CheckoutPaymentPlanPreview | null): string =>\n plan?.terminology?.trim() || DEFAULT_PLAN_TERMINOLOGY\n\n/** `currency_symbol` + 2dp, matching the hosted `money()` helper exactly. */\nexport const formatPlanMoney = (\n plan: CheckoutPaymentPlanPreview | null | undefined,\n value: number | null | undefined\n): string => {\n const symbol = plan?.currencySymbol ?? ''\n const num = Number(value)\n return `${symbol}${Number.isFinite(num) ? num.toFixed(2) : String(value ?? '')}`\n}\n\n/** \"Click to pay in 3 payments with a Payment Plan\" — the opt-in label. */\nexport const planCheckboxLabel = (plan: CheckoutPaymentPlanPreview): string =>\n `Click to pay in ${plan.totalInstallments ?? 0} payments with a ${planTerminology(plan)}`\n\n/** The plan's submit CTA — \"Confirm Payment Plan\". */\nexport const planConfirmLabel = (plan?: CheckoutPaymentPlanPreview | null): string =>\n `Confirm ${planTerminology(plan)}`\n\n/** \"CN Brand TTF Payment Plan Terms\" — the terms heading. */\nexport const planTermsTitle = (plan: CheckoutPaymentPlanPreview): string =>\n `${plan.manufacturerName ?? ''} ${planTerminology(plan)} Terms`.trim()\n\n/** One paragraph of the terms block. `id` is stable for localization/testing. */\nexport interface PlanTermsParagraph {\n id: 'schedule' | 'adminFee' | 'nonRefundable' | 'custom' | 'note'\n text: string\n}\n\n/**\n * The schedule sentence — five variants, selected exactly as the hosted block\n * does: down-payment (event-anchored final / two-payment / many), the plain\n * two-payment case, then the general auto-equal / staged wording.\n */\nconst scheduleParagraph = (plan: CheckoutPaymentPlanPreview): string => {\n const terminology = planTerminology(plan)\n const installments = Math.trunc(Number(plan.totalInstallments ?? 0)) || 0\n const periodicity = plan.interval == null ? '' : String(plan.interval)\n const installmentPrice = formatPlanMoney(plan, plan.pricePerInstallment)\n const confirm = `By clicking on the \"Confirm ${terminology}\" button`\n\n if (plan.downPaymentEnabled && plan.downPaymentAmount != null) {\n const amount = formatPlanMoney(plan, plan.downPaymentAmount)\n const remaining = Math.max(installments - 1, 1)\n if (remaining === 1 && plan.isEventAnchored && plan.finalChargeDate) {\n return `${confirm}, you are starting your ${terminology} with a down payment of ${amount} today, followed by a final payment of ${installmentPrice} on ${plan.finalChargeDate}.`\n }\n if (remaining === 1) {\n return `${confirm}, you are starting your ${terminology} with a down payment of ${amount} today, followed by a final payment of ${installmentPrice} in ${periodicity} days.`\n }\n return `${confirm}, you are starting your ${terminology} with a down payment of ${amount} today, followed by ${remaining} further payments of ${installmentPrice}, drawn from your account every ${periodicity} days.`\n }\n\n if (installments === 2) {\n return `${confirm}, you are starting your ${terminology} of 2 payments of ${installmentPrice}, with the first payment taken today and the final payment in ${periodicity} days.`\n }\n\n return `${confirm}, you are starting your ${terminology} of ${installments} payments of ${installmentPrice}, which will be drawn from your account every ${periodicity} days, with the first payment taken today.`\n}\n\n/**\n * The full terms block, in render order. Empty when there is nothing to state\n * (no installment shape), so callers can render unconditionally.\n */\nexport const paymentPlanTerms = (\n plan: CheckoutPaymentPlanPreview | null | undefined\n): PlanTermsParagraph[] => {\n if (!plan || (plan.totalInstallments == null && plan.pricePerInstallment == null)) {\n return []\n }\n\n const parts: PlanTermsParagraph[] = [{ id: 'schedule', text: scheduleParagraph(plan) }]\n\n const hasAdminFee = Boolean(plan.hasAdminFee && plan.adminFee)\n if (hasAdminFee) {\n parts.push({\n id: 'adminFee',\n text: `This includes a non-refundable admin fee of ${formatPlanMoney(plan, plan.adminFee)} per payment.`,\n })\n }\n\n // The hosted flow folds the admin fee into the cancellation sentence unless\n // the event opts out — hence a clause rather than its own paragraph.\n const additionalClause =\n hasAdminFee && !plan.hideNonRefundableAdminFeeText\n ? ` and an admin fee of ${formatPlanMoney(plan, plan.adminFee)} for each installment paid,`\n : ''\n const forfeited = formatPlanMoney(plan, plan.totalNonRefundableAmount)\n const cancelled =\n 'If you do not complete your payments, your order will be cancelled. At that point,'\n const refunded = 'Any remaining amount you have paid will be refunded.'\n\n if (plan.nonRefundableType === 'fixed' && plan.totalNonRefundableAmount) {\n parts.push({\n id: 'nonRefundable',\n text: `${cancelled} a set amount of ${forfeited}${additionalClause} will not be refunded. ${refunded}`,\n })\n } else if (plan.nonRefundableType === 'percent' && plan.nonRefundableAmount) {\n parts.push({\n id: 'nonRefundable',\n text: `${cancelled} ${plan.nonRefundableAmount}% of your order total (${forfeited})${additionalClause} will not be refunded. ${refunded}`,\n })\n }\n\n if (plan.customMessage) {\n parts.push({ id: 'custom', text: String(plan.customMessage) })\n }\n\n parts.push({\n id: 'note',\n text: 'NOTE: If today’s payment fails, your plan will not activate. Your tickets will not be issued until you complete your final payment.',\n })\n\n return parts\n}\n","/**\n * Account/session logic — interpret the existing-account lookup and drive the\n * multi-currency preference sync.\n */\nimport type {\n ContactEmailResponse,\n CurrencyState,\n CurrencySync,\n CurrencySyncOptions,\n CurrencyTransport,\n ExistingAccount,\n} from '../dtos'\n\n/** Normalize the `/ajax/contact-email` response to a boolean existence flag. */\nexport const interpretContactEmail = (\n raw: Partial<ContactEmailResponse> | null | undefined\n): ExistingAccount => {\n const exists = !!raw && !raw.error && Number(raw.exists) === 1\n return {\n exists,\n verified: exists && typeof raw?.verified === 'boolean' ? raw.verified : null,\n }\n}\n\n/** True when the event offers more than one currency (render a switcher only\n * then — currency selection exists solely for multi-currency events). */\nexport const isMultiCurrency = (state: CurrencyState | null | undefined): boolean =>\n !!state && Array.isArray(state.available) && state.available.length > 1\n\n/**\n * Run a currency sync through the injected transport. A bare sync (no code)\n * geo-seeds and reports state; a code switches it (requiresCatalogRefresh — a\n * currency change is a full reprice, so refetch the catalog and reset selection).\n */\nexport const syncCurrency = async (\n transport: CurrencyTransport,\n eventId: string | number,\n code?: string,\n options?: CurrencySyncOptions\n): Promise<CurrencySync> => {\n const state = await transport(eventId, code, options)\n return {\n state,\n requiresCatalogRefresh: !!code,\n }\n}\n","/**\n * Authentication rules shared by web and React Native. This module is pure:\n * no React, browser APIs, FormData, or transport. Platform UI owns only field\n * rendering while the API layer owns the final multipart encoding.\n */\nimport type {\n AuthFieldErrors,\n AuthLoginInput,\n AuthRegistrationInput,\n AuthValidationResult,\n} from '../dtos'\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst SPECIAL_CHARACTER = /[^A-Za-z0-9]/\n\nconst result = (errors: AuthFieldErrors): AuthValidationResult => ({\n valid: Object.keys(errors).length === 0,\n errors,\n})\n\nexport const normalizeAuthEmail = (email: string): string => email.trim().toLowerCase()\n\nexport const validateLoginInput = (input: AuthLoginInput): AuthValidationResult => {\n const errors: AuthFieldErrors = {}\n const email = normalizeAuthEmail(input.email)\n if (!email) errors.email = 'Email is required.'\n else if (!EMAIL.test(email)) errors.email = 'Enter a valid email address.'\n if (!input.password) errors.password = 'Password is required.'\n return result(errors)\n}\n\nexport const validatePasswordResetEmail = (email: string): AuthValidationResult => {\n const errors: AuthFieldErrors = {}\n const normalized = normalizeAuthEmail(email)\n if (!normalized) errors.email = 'Email is required.'\n else if (!EMAIL.test(normalized)) errors.email = 'Enter a valid email address.'\n return result(errors)\n}\n\nexport const validateRegistrationInput = (\n input: AuthRegistrationInput,\n options: { requireAddress?: boolean; requireState?: boolean } = {}\n): AuthValidationResult => {\n const errors: AuthFieldErrors = {}\n const email = normalizeAuthEmail(input.email)\n\n if (!input.firstName.trim()) errors.firstName = 'First name is required.'\n if (!input.lastName.trim()) errors.lastName = 'Last name is required.'\n if (!email) errors.email = 'Email is required.'\n else if (!EMAIL.test(email)) errors.email = 'Enter a valid email address.'\n\n if (!input.password) errors.password = 'Password is required.'\n else if (input.password.length < 8)\n errors.password = 'Password must be at least 8 characters.'\n else if (!SPECIAL_CHARACTER.test(input.password))\n errors.password = 'Password must include a special character.'\n\n if (!input.passwordConfirmation) errors.passwordConfirmation = 'Confirm your password.'\n else if (input.passwordConfirmation !== input.password)\n errors.passwordConfirmation = 'Passwords do not match.'\n\n if (options.requireAddress) {\n if (!input.streetAddress?.trim()) errors.streetAddress = 'Street address is required.'\n if (!input.city?.trim()) errors.city = 'City is required.'\n if (!input.zip?.trim()) errors.zip = 'ZIP / postcode is required.'\n if (!input.countryId) errors.countryId = 'Country is required.'\n }\n if (options.requireState && !input.stateId)\n errors.stateId = 'State / region is required.'\n\n return result(errors)\n}\n\n/** Map the platform-neutral shape to the backend's registration contract. */\nexport const buildRegistrationFields = (\n input: AuthRegistrationInput\n): Record<string, string> => {\n const fields: Record<string, string> = {\n first_name: input.firstName.trim(),\n last_name: input.lastName.trim(),\n email: normalizeAuthEmail(input.email),\n password: input.password,\n password_confirmation: input.passwordConfirmation,\n }\n\n const optional: Array<[string, string | undefined]> = [\n ['phone', input.phone?.trim()],\n ['street_address', input.streetAddress?.trim()],\n ['city', input.city?.trim()],\n ['zip', input.zip?.trim()],\n ['country', input.countryId],\n ['state', input.stateId],\n ]\n for (const [key, value] of optional) {\n if (value) fields[key] = value\n }\n return { ...fields, ...input.registrationFields }\n}\n","/**\n * ID-verification poller — a NEED_ID_VERIFICATION order signals\n * `needIdVerification`; the buyer completes the provider check in a new\n * tab/window while this polls `GET v1/order/:hash/id-verification` until\n * verified. Pure state machine — fetch and clock are injected, so it runs\n * identically in React, React Native, and tests (5s ticks, capped).\n */\nimport type {\n IdVerificationCallbacks,\n IdVerificationPoller,\n IdVerificationStatus,\n} from '../dtos'\n\nexport const ID_VERIFICATION_POLL_MS = 5000\nexport const ID_VERIFICATION_MAX_TICKS = 60\nexport const ID_VERIFICATION_MAX_CONSECUTIVE_FAILURES = 3\n\nexport const createIdVerificationPoller = (\n callbacks: IdVerificationCallbacks\n): IdVerificationPoller => {\n const schedule =\n callbacks.schedule || ((fn: () => void, ms: number) => setTimeout(fn, ms))\n let ticks = 0\n let consecutiveFailures = 0\n let stopped = false\n // Injected schedulers can't be portably cancelled, so a generation token\n // invalidates ticks scheduled by a previous start()/stop() cycle.\n let generation = 0\n\n const scheduleNextOrTimeout = (\n runGeneration: number,\n status?: IdVerificationStatus\n ) => {\n ticks += 1\n if (ticks >= ID_VERIFICATION_MAX_TICKS) {\n callbacks.onPhase('timeout', status)\n return\n }\n schedule(() => tick(runGeneration), ID_VERIFICATION_POLL_MS)\n }\n\n const tick = (runGeneration: number) => {\n if (stopped || runGeneration !== generation) return\n callbacks\n .fetchStatus()\n .then((status) => {\n if (stopped || runGeneration !== generation) return\n consecutiveFailures = 0\n if (status.verified || !status.required) {\n callbacks.onPhase('verified', status)\n return\n }\n scheduleNextOrTimeout(runGeneration, status)\n })\n .catch(() => {\n if (stopped || runGeneration !== generation) return\n // Transient failures keep polling — the buyer may be mid-check — but a\n // persistently failing endpoint surfaces as an error instead of five\n // silent minutes.\n consecutiveFailures += 1\n if (consecutiveFailures >= ID_VERIFICATION_MAX_CONSECUTIVE_FAILURES) {\n callbacks.onPhase('error')\n return\n }\n scheduleNextOrTimeout(runGeneration)\n })\n }\n\n return {\n start: () => {\n stopped = false\n ticks = 0\n consecutiveFailures = 0\n generation += 1\n // Capture before onPhase — a synchronously re-entrant start() inside the\n // callback must make THIS run stale, not adopt its token.\n const runGeneration = generation\n callbacks.onPhase('polling')\n tick(runGeneration)\n },\n stop: () => {\n stopped = true\n generation += 1\n },\n }\n}\n","/**\n * The checkout store — a tiny framework-agnostic observable over the\n * `CheckoutSnapshot`. The engine writes to it; `useCheckout()` (or a plain\n * `subscribe()` in a non-React app) reads from it. No React, no globals: the\n * same store instance drives web, React Native, Node, and tests.\n *\n * State updates are immutable (a new snapshot object each change) so\n * `useSyncExternalStore` and shallow-equality consumers re-render correctly.\n *\n * `progress` is separate on purpose: it holds the retry-safety bookkeeping\n * (which order exists, whether it's been charged) that must NEVER be part of\n * the reactive snapshot — it's how retries avoid creating a second order or\n * charging twice.\n */\nimport type { CheckoutSnapshot } from '../dtos'\n\nexport type CheckoutListener = (snapshot: CheckoutSnapshot) => void\n\n/** Retry-safety bookkeeping — mutated directly by the engine, never rendered. */\nexport interface OrderProgress {\n /** The created order's hash — a retry reuses it instead of minting a second. */\n orderHash?: string\n /** True once the charge landed — a retry then only replays finalization. */\n paymentConfirmed?: boolean\n}\n\nexport interface CheckoutStore {\n /** The current snapshot (stable reference until the next change). */\n getState: () => CheckoutSnapshot\n /** Merge a partial snapshot (or a function of the current one) and notify. */\n setState: (\n patch:\n | Partial<CheckoutSnapshot>\n | ((prev: CheckoutSnapshot) => Partial<CheckoutSnapshot>)\n ) => void\n /** Subscribe to changes; returns an unsubscribe function. */\n subscribe: (listener: CheckoutListener) => () => void\n /** Reset to the initial idle snapshot (and clear progress) and notify. */\n reset: () => void\n /** Retry-safety state (order hash + charged flag). Not reactive. */\n progress: OrderProgress\n /** Drop any half-created order — the cart contents changed, so a previously\n * created order is stale and must not be reused. */\n invalidateOrderProgress: () => void\n /** Move to the terminal 'expired' state and clear progress. */\n expireCart: () => void\n}\n\n/** The empty checkout — what every store starts at and `reset()` returns to. */\nexport const initialSnapshot = (): CheckoutSnapshot => ({\n status: 'idle',\n selections: [],\n ticketTypeIds: [],\n customFields: [],\n holderNamesRequired: false,\n fieldGates: {\n showNationality: false,\n nationalityRequired: false,\n showGender: false,\n genderRequired: false,\n requireInstagram: false,\n showPhone: false,\n phoneRequired: false,\n showDob: false,\n dobRequired: false,\n showAddress: false,\n },\n addOns: {},\n holders: [],\n consent: { ttfOptIn: false, brandOptIn: false },\n})\n\nexport const createCheckoutStore = (\n initial: CheckoutSnapshot = initialSnapshot()\n): CheckoutStore => {\n let state = initial\n const listeners = new Set<CheckoutListener>()\n // .forEach (not for-of) so the SDK stays iterable under an es5 consumer target.\n const emit = () => {\n listeners.forEach((listener) => listener(state))\n }\n\n const store: CheckoutStore = {\n progress: {},\n getState: () => state,\n setState: (patch) => {\n const next = typeof patch === 'function' ? patch(state) : patch\n state = { ...state, ...next }\n emit()\n },\n subscribe: (listener) => {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n reset: () => {\n state = initialSnapshot()\n store.progress = {}\n emit()\n },\n invalidateOrderProgress: () => {\n store.progress = {}\n },\n expireCart: () => {\n store.progress = {}\n state = { ...state, status: 'expired' }\n emit()\n },\n }\n return store\n}\n","/**\n * The payment-confirmation port — the hexagonal seam that keeps the engine\n * framework- AND payment-SDK-agnostic. The orchestration is pure TS EXCEPT for\n * the calls that talk to a Stripe SDK (init, read intent status, confirm card /\n * wallet). Those live behind this interface: React Native binds it with\n * @stripe/stripe-react-native, web with stripe-js, tests with a fake.\n *\n * Status vocabulary: confirmers return Stripe PaymentIntent statuses in the RN\n * SDK's PascalCase form ('Succeeded' | 'RequiresCapture' | 'Processing' | …).\n * Adapters over SDKs with other spellings (stripe-js is lowercase) normalize.\n */\nimport type { CheckoutBilling, InstallmentOffer, PayPalForm } from '../dtos'\n\nexport interface PaymentConfirmer {\n /** Initialize the underlying SDK for the given keys. */\n init(options: {\n publishableKey: string\n /** Stripe connected-account id (already cleaned — never ''). */\n accountId?: string\n /** Apple Pay merchant id, when the platform supports it. */\n merchantIdentifier?: string\n /** App deep-link scheme (React Native) — redirect methods return through it. */\n urlScheme?: string\n }): Promise<void>\n\n /** Status of the PaymentIntent behind `clientSecret`, or undefined when it\n * can't be retrieved. Used to skip re-charging on retries. */\n getIntentStatus(clientSecret: string): Promise<string | undefined>\n\n /** Confirm a card payment. Returns the resulting intent status or throws. */\n confirmCard(clientSecret: string, billing: CheckoutBilling): Promise<string | undefined>\n\n /** Present the platform-pay sheet (Apple Pay on iOS). Returns the resulting\n * intent status or throws — a user-cancelled sheet is an error. */\n confirmApplePay(\n clientSecret: string,\n total: string,\n currencyCode: string,\n merchant: { merchantCountryCode?: string; merchantName?: string }\n ): Promise<string | undefined>\n\n /** Present the Google Pay sheet (Android). Optional — only platforms with a\n * native Google Pay SDK bind it; unbound, the engine throws UNSUPPORTED_GATEWAY. */\n confirmGooglePay?(\n clientSecret: string,\n total: string,\n currencyCode: string,\n merchant: {\n merchantCountryCode?: string\n merchantName?: string\n /** Use Google Pay's TEST environment (no real charge). */\n testEnv?: boolean\n }\n ): Promise<string | undefined>\n}\n\n/**\n * A payment is confirmed enough to finalize in any of these states: Succeeded\n * (auto-capture), RequiresCapture (manual-capture authorizes now, captures\n * later — NOT a failure), or Processing (settling asynchronously).\n */\nexport const CONFIRMED_INTENT_STATUSES: string[] = [\n 'Succeeded',\n 'RequiresCapture',\n 'Processing',\n]\n\n/**\n * A Stripe connected-account id, or undefined when there is none. The backend\n * returns '' for platform-account events; passing '' sets an empty\n * `Stripe-Account` header, which Stripe rejects — coerce empties to undefined.\n */\nexport const cleanAccountId = (id?: string | null): string | undefined =>\n id && id.trim() ? id : undefined\n\n/**\n * Optional confirmer capabilities the alternative rails need. A platform that\n * doesn't implement one simply can't run that rail — the engine throws a typed\n * UNSUPPORTED_GATEWAY error instead of failing mid-payment.\n */\nexport interface PaymentConfirmerExtras {\n /** Create a card PaymentMethod (MSI offer lookup runs between creation and\n * the confirm). Returns the PaymentMethod id. */\n createCardPaymentMethod?(billing: CheckoutBilling): Promise<string>\n /** Create a redirect-method PaymentMethod (Klarna/Afterpay/iDEAL-class).\n * Returns the id, or null when the platform can't express the type. */\n createRedirectPaymentMethod?(\n methodType: string,\n billing: CheckoutBilling\n ): Promise<string | null>\n /** Run the pending next action of a SERVER-confirmed intent (MSI). Throws on\n * failure; never confirms a second time. */\n handleNextAction?(clientSecret: string): Promise<void>\n /** Confirm an OXXO voucher intent. Returns the raw nextAction payload (engine\n * extracts the voucher) plus any error — Stripe can report an error while\n * still issuing the voucher. */\n confirmOxxo?(\n clientSecret: string,\n billing: CheckoutBilling\n ): Promise<{ error?: string; nextAction?: unknown }>\n /** Payment plan (new card): confirm the review's SetupIntent to SAVE the card\n * — NOTHING is charged; the plan schedules server-side. Returns the saved\n * PaymentMethod id, or throws. */\n confirmPaymentPlanSetup?(\n clientSecret: string,\n billing: CheckoutBilling\n ): Promise<string>\n /** Payment plan (saved-card shortcut): confirm an on-session card payment\n * against an EXISTING PaymentMethod — the 3DS step runs only when the plan\n * charge comes back requires_action. Throws on failure. */\n confirmSavedCardPayment?(clientSecret: string, paymentMethodId: string): Promise<void>\n}\n\n/** What a provider page run should load: a URL, or an inline HTML document\n * (PayPal's auto-submitting top-level form). */\nexport interface ProviderPageRequest {\n uri?: string\n html?: string\n /** Base URL for an inline document (relative return-leg resolution). */\n baseUrl?: string\n /** Navigating to a URL with this prefix ends the run as 'success'. */\n returnUrlPrefix: string\n}\n\nexport interface ProviderPageOutcome {\n event: 'success' | 'dismiss' | 'failed'\n /** The intercepted return URL (carries e.g. `redirect_status`). */\n returnUrl?: string\n /** Payload posted by data-driven sheets (Razorpay's `razorpay_payment_id`,\n * Xendit card tokenization's `token`) — the platform's plumbing delivers it. */\n data?: Record<string, unknown>\n description?: string\n}\n\n/**\n * The full port set the pay rails run on. `confirmer` is required (card/Apple\n * Pay); the rest are optional platform capabilities:\n * - providerPage: run a provider's page and resolve on the return leg (a\n * WebView sheet on RN, a redirect/popup on web).\n * - openUrl: open an external URL (OXXO voucher, ID-verification).\n * - onInstallmentOffers: offer MSI plans; resolve the chosen one, or null to\n * decline and fall through to a normal single charge.\n * - tokenizeXenditCard: tokenize a Xendit card inline (web); when absent the\n * engine runs the Xendit card document through `providerPage`.\n */\nexport interface CheckoutPorts extends PaymentConfirmerExtras {\n confirmer: PaymentConfirmer\n providerPage?: (request: ProviderPageRequest) => Promise<ProviderPageOutcome>\n openUrl?: (url: string) => void | Promise<void>\n onInstallmentOffers?: (offers: InstallmentOffer[]) => Promise<InstallmentOffer | null>\n tokenizeXenditCard?: (params: {\n publishableKey: string\n amount: string | number\n billing: CheckoutBilling\n onBehalfOf?: string | null\n }) => Promise<Record<string, unknown>>\n}\n\n/** A typed \"this platform can't run this rail\" error — consumers branch on\n * `code` to hand off to the event page. */\nexport const unsupportedGatewayError = (message?: string): Error & { code: string } => {\n const err = new Error(\n message ??\n \"This payment method isn't available in the app. Please finish buying on the event page.\"\n ) as Error & { code: string }\n err.code = 'UNSUPPORTED_GATEWAY'\n return err\n}\n\nconst escapeHtmlAttribute = (value: string) =>\n value\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n\n/**\n * PayPal Standard runs as a TOP-LEVEL form POST (PayPal refuses framing) — an\n * auto-submitting form document is all the provider page needs to load.\n */\nexport const buildAutoSubmitFormHtml = (form: PayPalForm): string => {\n const inputs = Object.entries(form.fields)\n .map(\n ([name, value]) =>\n `<input type=\"hidden\" name=\"${escapeHtmlAttribute(name)}\" value=\"${escapeHtmlAttribute(String(value ?? ''))}\" />`\n )\n .join('\\n ')\n\n return `<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n </head>\n <body>\n <form id=\"gateway-form\" method=\"POST\" action=\"${escapeHtmlAttribute(form.action_url)}\">\n ${inputs}\n </form>\n <script>\n document.getElementById('gateway-form').submit();\n </script>\n </body>\n</html>`\n}\n","/**\n * Gateway sheet documents (Razorpay web checkout, Xendit card tokenization) —\n * pure HTML string builders the `providerPage` port loads (a WebView on RN, a\n * popup on web). No runtime deps: these just build a document; the raw card\n * details never leave the page — only the resulting token/payment id is posted\n * back through the provider-page outcome.\n */\nexport interface RazorpayCheckoutHtmlOptions {\n keyId: string\n /** Charge amount in minor units (paise) — the server's pay_now × 100. */\n amountMinor: number\n description?: string\n buyerName?: string\n buyerEmail?: string\n orderHash: string\n}\n\n/**\n * Razorpay hosted checkout inside a WebView. Reports back via\n * `window.ReactNativeWebView.postMessage` with `{event:'success',\n * razorpay_payment_id}` / `{event:'dismiss'}` / `{event:'failed', description}`.\n * `notes.order_hash` ties the charge to the order server-side.\n */\nexport const buildRazorpayCheckoutHtml = (\n options: RazorpayCheckoutHtmlOptions\n): string => {\n const rzpOptions = JSON.stringify({\n key: options.keyId,\n amount: Math.round(options.amountMinor),\n name: 'Ticket Fairy',\n description: options.description || '',\n prefill: {\n name: options.buyerName || '',\n email: options.buyerEmail || '',\n },\n notes: {\n order_hash: options.orderHash,\n },\n })\n\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<script src=\"https://checkout.razorpay.com/v1/checkout.js\"></script>\n</head>\n<body style=\"margin:0;background:#ffffff\">\n<script>\n function report(payload) {\n if (window.ReactNativeWebView) {\n window.ReactNativeWebView.postMessage(JSON.stringify(payload));\n }\n }\n try {\n var options = ${rzpOptions};\n options.handler = function (response) {\n report({\n event: 'success',\n razorpay_payment_id: response && response.razorpay_payment_id,\n });\n };\n options.modal = {\n ondismiss: function () {\n report({ event: 'dismiss' });\n },\n };\n var rzp = new Razorpay(options);\n rzp.on('payment.failed', function (resp) {\n report({\n event: 'failed',\n description: resp && resp.error && resp.error.description,\n });\n });\n rzp.open();\n } catch (e) {\n report({ event: 'failed', description: e && e.message });\n }\n</script>\n</body>\n</html>`\n}\n\nexport interface XenditCheckoutHtmlOptions {\n publishableKey: string\n /** Tokenization amount — the server-returned pay-now figure verbatim. The\n * CHARGE amount stays server-side in submit-payment. */\n amount: number | string\n buyerFirstName?: string\n buyerLastName?: string\n buyerEmail?: string\n buyerPhone?: string\n onBehalfOf?: string | null\n}\n\n/**\n * Xendit card tokenization inside a WebView: card entry, `Xendit.card.createToken`\n * with 3DS (the challenge iframe re-invokes the handler when it resolves),\n * reporting `{event:'success', token}` / `{event:'failed', description}`.\n */\nexport const buildXenditCheckoutHtml = (options: XenditCheckoutHtmlOptions): string => {\n const opts = JSON.stringify({\n publishableKey: options.publishableKey,\n amount: options.amount,\n firstName: options.buyerFirstName || '',\n lastName: options.buyerLastName || '',\n email: options.buyerEmail || '',\n phone: options.buyerPhone || '',\n onBehalfOf: options.onBehalfOf || null,\n })\n\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<script src=\"https://js.xendit.co/v1/xendit.min.js\"></script>\n<style>\n body { margin: 0; background: #ffffff; font-family: -apple-system, Roboto, sans-serif; }\n .wrap { padding: 16px; }\n label { display: block; font-size: 14px; margin-bottom: 12px; color: #333; }\n input { display: block; width: 100%; box-sizing: border-box; margin-top: 4px;\n padding: 12px 10px; font-size: 16px; border: 1px solid #e0e0e0; border-radius: 8px; }\n .row { display: flex; gap: 12px; }\n .row label { flex: 1; }\n .note { font-size: 13px; color: #666; margin-bottom: 12px; display: none; }\n .err { font-size: 13px; color: #c0392b; margin-bottom: 12px; min-height: 16px; }\n button { width: 100%; padding: 14px; font-size: 16px; border: 0; border-radius: 8px;\n background: #111111; color: #ffffff; }\n button:disabled { opacity: 0.5; }\n #threeds { display: none; position: fixed; inset: 0; background: #ffffff; }\n #threeds iframe { width: 100%; height: 100%; border: 0; }\n</style>\n</head>\n<body>\n<div class=\"wrap\">\n <label>Card number\n <input id=\"num\" inputmode=\"numeric\" autocomplete=\"cc-number\">\n </label>\n <div class=\"row\">\n <label>Expiry (MM/YY)\n <input id=\"exp\" inputmode=\"numeric\" autocomplete=\"cc-exp\" placeholder=\"MM/YY\">\n </label>\n <label>Security code\n <input id=\"cvn\" type=\"password\" inputmode=\"numeric\" autocomplete=\"cc-csc\">\n </label>\n </div>\n <div class=\"note\" id=\"note\">Your bank may ask you to confirm it’s really you.</div>\n <div class=\"err\" id=\"err\"></div>\n <button id=\"pay\">Submit Payment</button>\n</div>\n<div id=\"threeds\"><iframe id=\"threedsFrame\"></iframe></div>\n<script>\n var OPTS = ${opts};\n var payBtn = document.getElementById('pay');\n var errBox = document.getElementById('err');\n var note = document.getElementById('note');\n var threeds = document.getElementById('threeds');\n var threedsFrame = document.getElementById('threedsFrame');\n var submitting = false;\n\n function report(payload) {\n if (window.ReactNativeWebView) {\n window.ReactNativeWebView.postMessage(JSON.stringify(payload));\n }\n }\n function reset(message) {\n submitting = false;\n payBtn.disabled = false;\n note.style.display = 'none';\n threeds.style.display = 'none';\n threedsFrame.src = 'about:blank';\n errBox.textContent = message || '';\n }\n\n function handler(err, token) {\n if (err) {\n reset(err.message || 'Your payment was not accepted. Please try again or use a different card.');\n return;\n }\n if (token.status === 'VERIFIED') {\n threeds.style.display = 'none';\n report({ event: 'success', token: token });\n } else if (token.status === 'IN_REVIEW' && token.payer_authentication_url) {\n note.style.display = 'block';\n threedsFrame.src = token.payer_authentication_url;\n threeds.style.display = 'block';\n } else {\n var reason = token && token.failure_reason ? ' (' + token.failure_reason + ')' : '';\n reset('Your payment was not accepted' + reason + '. Please try again or use a different card.');\n }\n }\n\n payBtn.addEventListener('click', function () {\n if (submitting) return;\n errBox.textContent = '';\n var number = (document.getElementById('num').value || '').replace(/\\\\s+/g, '');\n var expParts = (document.getElementById('exp').value || '').split('/');\n var expMonth = (expParts[0] || '').trim();\n var expYear = (expParts[1] || '').trim();\n if (expYear.length === 2) expYear = '20' + expYear;\n var cvn = (document.getElementById('cvn').value || '').trim();\n if (!number || !expMonth || !expYear || !cvn) {\n errBox.textContent = 'Please fill in your card details.';\n return;\n }\n if (!window.Xendit) {\n report({ event: 'failed', description: 'The payment service could not be loaded.' });\n return;\n }\n submitting = true;\n payBtn.disabled = true;\n try {\n window.Xendit.setPublishableKey(OPTS.publishableKey);\n var data = {\n amount: OPTS.amount,\n card_number: number,\n card_exp_month: expMonth,\n card_exp_year: expYear,\n card_cvn: cvn,\n is_multiple_use: false,\n should_authenticate: true,\n };\n // card_holder_* fields are ALL-OR-NOTHING peers in Xendit's validation —\n // send the group only when complete.\n if (OPTS.firstName && OPTS.lastName && OPTS.email && OPTS.phone) {\n data.card_holder_first_name = OPTS.firstName;\n data.card_holder_last_name = OPTS.lastName;\n data.card_holder_email = OPTS.email;\n data.card_holder_phone_number = OPTS.phone;\n }\n if (OPTS.onBehalfOf) data.on_behalf_of = OPTS.onBehalfOf;\n window.Xendit.card.createToken(data, handler);\n } catch (e) {\n reset((e && e.message) || 'Something went wrong. Please try again.');\n }\n });\n</script>\n</body>\n</html>`\n}\n","/**\n * Engine error helpers. Failures already arrive as `TtfError` (the transport\n * normalizes them), so these just read it: a friendly message, and whether the\n * failure is the backend rejecting an expired cart/checkout session.\n */\nimport { toTtfError } from '../client'\n\n/** The friendliest message for a failed call (the backend's own, else generic). */\nexport const errorMessage = (error: unknown): string => toTtfError(error).message\n\n/**\n * \"expired\" in the languages the backend's per-locale cart-expiry message can\n * use. Message-sniffing is a fallback — the 422 body carries no structured code.\n */\nconst EXPIRED_WORDS =\n /expir|caduc|scadut|abgelaufen|verlopen|udløbet|löpt ut|utløpt|vypršel|wygasł|истек|expirou|kedaluwarsa|hết hạn|期限切れ|已过期|已過期|만료/i\n\n/**\n * True when a failed request is the backend rejecting an expired cart/checkout\n * session (422 + an \"…expired\" message). Lets the flow show a \"restart\"\n * recovery instead of a raw error; ordinary 422 validation errors stay generic.\n */\nexport const isCartExpiredError = (error: unknown): boolean => {\n const e = toTtfError(error)\n if (e.status !== 422) return false\n return EXPIRED_WORDS.test(e.message)\n}\n","/**\n * The raw api surface — one function per endpoint, each \"just does the call\"\n * and returns typed data (or throws `TtfError`). The `ttf` facade in\n * `services.ts` is a thin, domain-grouped convenience over exactly these.\n * Power users can import them directly.\n */\nexport * from './auth'\nexport * from './profile'\nexport * from './geo'\nexport * from './engagement'\nexport * from './orders'\nexport * from './resale'\nexport * from './confirmation'\nexport * from './preRegistration'\nexport * from './delegation'\nexport * from './seatmap'\n// Checkout flow — catalog, cart/pricing, order, payment rails\nexport * from './events'\nexport * from './cart'\nexport * from './order'\nexport * from './payment'\n","/**\n * Profile reads. The signed-in user's record, straight off `/customer/profile/`.\n * (Login lives in `auth.ts`; this is imported there to resolve the profile after\n * the token lands.)\n */\nimport { get } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { TfEnvelope, TfProfile } from '../types'\n\n/** Fetch the signed-in user's profile. Throws `TtfError` if unauthenticated. */\nexport const getProfile = async (): Promise<TfProfile> => {\n const res = await get<TfEnvelope<TfProfile>>(ENDPOINTS.profile.get, {\n withCredentials: true,\n })\n return res.data\n}\n","/**\n * Auth — the whole surface, not just login. This is the domain shared was\n * missing most: register, password reset/restore, logout, email-exists.\n *\n * Login is the platform's two-step OAuth chain (authorize-rn → access_token);\n * on success we persist the tokens via the session module and every later call\n * rides the bearer automatically.\n */\nimport { getConfig, getOriginUrl } from '../client/config'\nimport { TtfError } from '../client/errors'\nimport { del, get, patch, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { clearSession, notifyCookieSession, setTokens } from '../client/session'\nimport type { AuthRegistrationInput } from '../dtos'\nimport { buildRegistrationFields } from '../logic/auth'\nimport { TfEnvelope, TfProfile } from '../types'\nimport { getProfile } from './profile'\n\nconst toFormData = (fields: Record<string, string | Blob>): FormData => {\n const form = new FormData()\n for (const [key, value] of Object.entries(fields)) form.append(key, value)\n return form\n}\n\n/**\n * Sign in with email + password. Runs the OAuth chain, stores the tokens, and\n * resolves to the freshly-loaded profile. Throws `TtfError` on bad credentials.\n */\nexport const login = async (email: string, password: string): Promise<TfProfile> => {\n const { clientId, clientSecret, cookieAuth } = getConfig()\n\n // Web checkouts share TicketFairy's session cookie (`cookieAuth`). Sign in the\n // way the legacy checkout did — POST /auth (backend `customerLogin`) — so the\n // server issues the X-TF-ECOMMERCE session ticket and the buyer stays on the\n // SAME session that already holds their reserved cart. The OAuth bearer chain\n // below issues no such ticket and rides a separate identity, so a guest who\n // logs in mid-checkout loses the reserved cart and the next on-checkout 422s\n // with \"cart expired\". Bearerless by design (no `setTokens`), exactly like the\n // old flow — the response interceptor captures the ticket the backend returns.\n if (cookieAuth) {\n await post(`${ENDPOINTS.auth.session}?clientId=${clientId}`, { email, password })\n const profile = await getProfile()\n notifyCookieSession()\n return profile\n }\n\n if (!clientId || !clientSecret) {\n throw new TtfError('login: clientId/clientSecret are not configured.', 0)\n }\n\n const authorize = await post<{ data?: { code?: string } }>(\n ENDPOINTS.auth.authorizeRn(clientId),\n toFormData({ email, password }),\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n const code = authorize.data?.code\n if (!code) throw new TtfError('login: authorization code not received.', 0)\n\n const token = await post<{ access_token?: string; refresh_token?: string }>(\n ENDPOINTS.auth.accessToken,\n toFormData({\n code,\n scope: 'profile',\n grant_type: 'authorization_code',\n client_id: clientId,\n client_secret: clientSecret,\n }),\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n if (!token.access_token) throw new TtfError('login: no access token received.', 0)\n\n setTokens({ access: token.access_token, refresh: token.refresh_token })\n return getProfile()\n}\n\n/**\n * Create an account. Pass the registration fields as a flat record — the\n * backend endpoint (`v1/oauth/register-rn`) takes multipart form data, so field\n * names are forwarded verbatim (`email`, `password`, `first_name`, …).\n */\nexport const register = async (\n fields: Record<string, string | Blob>\n): Promise<TfProfile> => {\n const { clientId, clientSecret } = getConfig()\n const requestFields = {\n ...fields,\n client_id: fields.client_id ?? clientId,\n client_secret: fields.client_secret ?? clientSecret,\n }\n if (!requestFields.client_id || !requestFields.client_secret) {\n throw new TtfError('register: clientId/clientSecret are not configured.', 0)\n }\n const res = await post<\n | TfEnvelope<TfProfile>\n | {\n data?: {\n attributes?: {\n access_token?: string\n refresh_token?: string\n user_profile?: Record<string, unknown>\n }\n }\n }\n >(ENDPOINTS.auth.registerRn, toFormData(requestFields), {\n headers: { 'Content-Type': 'multipart/form-data' },\n })\n const data = res.data\n const attributes =\n data && typeof data === 'object' && 'attributes' in data ? data.attributes : undefined\n if (attributes?.access_token) {\n setTokens({\n access: attributes.access_token,\n refresh: attributes.refresh_token,\n })\n try {\n return await getProfile()\n } catch {\n // Some staging responses expose a reduced profile while the full profile\n // endpoint catches up. Fall through to it instead of failing a completed\n // registration.\n }\n }\n\n const candidate = (attributes?.user_profile ?? data) as Record<string, unknown>\n const firstName = String(candidate?.firstName ?? candidate?.first_name ?? '')\n const lastName = String(candidate?.lastName ?? candidate?.last_name ?? '')\n const email = String(candidate?.email ?? '')\n return {\n id: String(candidate?.id ?? ''),\n firstName,\n lastName,\n email,\n phone: candidate?.phone ? String(candidate.phone) : undefined,\n streetAddress: candidate?.streetAddress\n ? String(candidate.streetAddress)\n : candidate?.street_address\n ? String(candidate.street_address)\n : undefined,\n zipCode: candidate?.zipCode\n ? String(candidate.zipCode)\n : candidate?.zip\n ? String(candidate.zip)\n : undefined,\n countryId: String(candidate?.countryId ?? candidate?.country_id ?? ''),\n company: null,\n stateId: candidate?.stateId\n ? String(candidate.stateId)\n : candidate?.state_id\n ? String(candidate.state_id)\n : undefined,\n city: candidate?.city ? String(candidate.city) : undefined,\n username: String(candidate?.username ?? email),\n screenName: null,\n bio: null,\n shortBio: null,\n region: null,\n image: null,\n recommendedEvents: [],\n rnRoles: [],\n hasDashboardAccess: false,\n ticketHolders: [],\n linkedCryptoWallets: [],\n }\n}\n\n/** Typed registration used by platform auth flows. */\nexport const registerAccount = (input: AuthRegistrationInput): Promise<TfProfile> =>\n register(buildRegistrationFields(input))\n\n/** Kick off the \"forgot password\" email for an address. */\nexport const restorePassword = async (email: string): Promise<void> => {\n await post(ENDPOINTS.auth.restorePassword, { email })\n}\n\n/** Complete a password reset with the token from the email. */\nexport const resetPassword = async (input: {\n token: string\n password: string\n passwordConfirmation?: string\n}): Promise<void> => {\n await post(ENDPOINTS.auth.resetPassword, {\n token: input.token,\n password: input.password,\n password_confirmation: input.passwordConfirmation ?? input.password,\n })\n}\n\n/** React Native \"forgot password\" variant (`v1/oauth/restore-password-rn`). */\nexport const restorePasswordRn = async (email: string): Promise<void> => {\n await post(ENDPOINTS.auth.restorePasswordRn, { email })\n}\n\n// --- Account identity verification (Netverify/Jumio, `v1/authenticate/*`) ----\n\n/** Mint (or read) the hosted identity-verification URL for the signed-in user. */\nexport const mintVerificationUrl = async (): Promise<unknown> =>\n get(ENDPOINTS.auth.verify)\n\n/** Read the signed-in user's current identity-verification status. */\nexport const getVerificationInfo = async (): Promise<unknown> =>\n get(ENDPOINTS.auth.verificationInfo)\n\n/** Mark identity verification as PENDING after the buyer starts the provider flow. */\nexport const updateVerificationStatus = async (): Promise<unknown> =>\n patch(ENDPOINTS.auth.verify, {\n data: { attributes: { verification: { verificationStatus: 'PENDING' } } },\n })\n\n/** Sign out: tell the backend, then drop local tokens regardless of the result. */\nexport const logout = async (): Promise<void> => {\n try {\n await del(ENDPOINTS.auth.session)\n } finally {\n clearSession()\n }\n}\n\n/**\n * Whether an email already has an account. Normalizes the legacy\n * `/ajax/contact-email` response (`exists: 0|1`) to a boolean; never throws —\n * returns `{ exists: false }` on failure so callers can treat it as advisory.\n */\nexport const checkEmailExists = async (\n email: string\n): Promise<{ exists: boolean; error?: string }> => {\n try {\n const res = await post<{ exists?: number; error?: number; message?: string }>(\n `${getOriginUrl()}/${ENDPOINTS.auth.contactEmail}`,\n toFormData({ email, is_checkout_flow: 'true' }),\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n return {\n exists: res.exists === 1,\n error: res.error === 1 ? res.message : undefined,\n }\n } catch {\n return { exists: false, error: 'Failed to check email' }\n }\n}\n","/**\n * Geo lookups for billing selects: the country list and a country's states.\n * The states endpoint answers with an id→name map; we normalize it to an array\n * so consumers get one consistent `{ id, name }` shape.\n */\nimport { get } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { TfCountry, TfState } from '../types'\n\n/** All selectable countries (billing `countryId` values). */\nexport const getCountries = async (): Promise<TfCountry[]> => {\n const res = await get<{ data: TfCountry[] }>(ENDPOINTS.geo.countries)\n return res.data ?? []\n}\n\n/** States/provinces for a country, normalized from the backend's id→name map. */\nexport const getStates = async (countryId: string | number): Promise<TfState[]> => {\n const res = await get<{ data: Record<string, string> }>(ENDPOINTS.geo.states(countryId))\n return Object.entries(res.data ?? {}).map(([id, name]) => ({ id, name }))\n}\n","/**\n * Pre-purchase engagement: referral attribution, sold-out waiting lists, RSVP\n * capture, and phone validation. None of these existed in shared before — they\n * lived only in the platform packages' own api layers.\n */\nimport { get, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport type { WaitingListEntry } from '../dtos'\n\nexport type { WaitingListEntry }\n\n/**\n * Attribute the buyer's session to a referrer/promoter (the numeric customer id\n * from a share/tracking link). The server credits it when the order completes;\n * pass `null` to clear. The endpoint always answers success, so ids can't be\n * probed.\n */\nexport const attributeReferrer = async (\n eventId: string,\n referrer: string | number | null\n): Promise<void> => {\n await post(ENDPOINTS.events.referrer(eventId), { referrer: referrer ?? '' })\n}\n\n/** Join the waiting list for a sold-out event (or one sold-out ticket type). */\nexport const joinWaitingList = async (\n eventId: string,\n entry: WaitingListEntry\n): Promise<void> => {\n await post(ENDPOINTS.events.waitingList(eventId), {\n data: { attributes: entry },\n })\n}\n\n/** Submit RSVP details for an RSVP-style event. */\nexport const sendRsvp = async (\n eventId: string,\n data: Record<string, unknown>\n): Promise<unknown> => post(ENDPOINTS.events.rsvp(eventId), data)\n\n/** Validate a phone number (Twilio-backed) before letting the buyer proceed. */\nexport const validatePhone = async (\n phone: string\n): Promise<{ valid: boolean; [key: string]: unknown }> => {\n const res = await get<{ valid?: boolean; [key: string]: unknown }>(\n ENDPOINTS.account.validatePhone(phone)\n )\n return { valid: Boolean(res?.valid), ...res }\n}\n","/**\n * Account orders — the buyer's purchase history and a single order's detail.\n * Backed by `v1/account/orders` (paginated, filterable by event/brand) and\n * `v1/account/order/:id`. New to shared; previously platform-only.\n */\nimport { get, put } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { TfEnvelope, TfListEnvelope } from '../types'\n\n/** A row in the order history. Fields the platform is known to return are typed;\n * the index signature keeps forward-compatible extras accessible. */\nexport interface TfOrderSummary {\n id?: string | number\n hash?: string\n status?: string\n total?: string | number\n currency?: string\n eventName?: string\n createdAt?: string\n [key: string]: unknown\n}\n\n/** A single order's full detail (tickets, buyer, totals). */\nexport interface TfOrderDetails extends TfOrderSummary {\n tickets?: unknown[]\n}\n\nexport interface OrdersQuery {\n page?: number\n limit?: number\n /** Restrict to one event by slug. */\n eventSlug?: string\n /** Restrict to a brand (and its subbrands). */\n brandSlug?: string\n}\n\n/** List the signed-in user's orders, newest first (server-paginated). */\nexport const getOrders = async (\n query: OrdersQuery = {}\n): Promise<TfListEnvelope<TfOrderSummary>> => {\n const { page = 1, limit = 10, eventSlug = '', brandSlug } = query\n const params = new URLSearchParams({\n page: String(page),\n limit: String(limit),\n 'filter[event]': eventSlug,\n })\n if (brandSlug) {\n params.set('filter[brand]', brandSlug)\n params.set('filter[subbrands]', 'true')\n }\n return get<TfListEnvelope<TfOrderSummary>>(\n `${ENDPOINTS.account.orders}?${params.toString()}`\n )\n}\n\n/** The authenticated account endpoint accepts the numeric order id. Public\n * order hashes belong to the confirmation endpoint and must be resolved first. */\nexport const getOrder = async (orderId: string): Promise<TfEnvelope<TfOrderDetails>> => {\n if (!/^\\d+$/.test(String(orderId))) {\n throw new TypeError(\n 'Account order details require a numeric order id; resolve public order hashes first.'\n )\n }\n return get<TfEnvelope<TfOrderDetails>>(ENDPOINTS.account.order(orderId))\n}\n\n/** The signed-in user's tickets (wallet), server-paginated + filterable. */\nexport const getMyTickets = async (\n query: OrdersQuery & { from?: string } = {}\n): Promise<TfListEnvelope<Record<string, unknown>>> => {\n const { page = 1, limit = 10, eventSlug = '', brandSlug, from } = query\n const params = new URLSearchParams({\n page: String(page),\n limit: String(limit),\n 'filter[event]': eventSlug,\n })\n if (brandSlug) {\n params.set('filter[brand]', brandSlug)\n params.set('filter[subbrands]', 'true')\n }\n if (from) params.set('from', from)\n return get<TfListEnvelope<Record<string, unknown>>>(\n `${ENDPOINTS.account.tickets}?${params.toString()}`\n )\n}\n\n/** Update the order-level data-capture answers shown on the order detail page. */\nexport const updateOrderCustomFields = async (\n eventId: string,\n orderId: string,\n values: Record<string, unknown>\n): Promise<unknown> =>\n put(`v1/event/${eventId}/order-data-capture`, {\n data: {\n attributes: {\n order_id: orderId,\n data_capture: values,\n },\n },\n })\n\n/** Update data-capture answers for one issued ticket. */\nexport const updateTicketHolderCustomFields = async (\n eventId: string,\n ticketHash: string,\n values: Record<string, unknown>\n): Promise<unknown> =>\n put(`v1/event/${eventId}/ticket-data-capture`, {\n data: {\n attributes: {\n ticket_hash: ticketHash,\n ticket_data_capture: {\n [ticketHash]: values,\n },\n },\n },\n })\n","/**\n * Ticket resale — list a ticket for resale, process a pending resale, or\n * decline one. Backed by `v1/ticket/:id/{sell,process,decline}`. New to shared;\n * previously only in the web package's `resale.ts`.\n */\nimport { del, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** Put a ticket up for resale. `payload` carries price/recipient per the event's\n * resale rules; forwarded verbatim. */\nexport const sellTicket = async (\n ticketId: string,\n payload: Record<string, unknown> = {}\n): Promise<unknown> => post(ENDPOINTS.resale.sell(ticketId), payload)\n\n/** Remove a ticket that is currently listed for resale. */\nexport const removeTicketFromResale = async (ticketId: string): Promise<unknown> =>\n del(ENDPOINTS.resale.sell(ticketId))\n\n/** Process (accept/complete) a pending resale for a ticket. */\nexport const processResale = async (\n ticketId: string,\n payload: Record<string, unknown> = {}\n): Promise<unknown> => post(ENDPOINTS.resale.process(ticketId), payload)\n\n/** Decline a pending resale for a ticket. */\nexport const declineResale = async (ticketId: string): Promise<unknown> =>\n post(ENDPOINTS.resale.decline(ticketId))\n","/**\n * Post-purchase confirmation — the \"your order is complete\" page data, keyed by\n * order hash. Backed by `v1/order/:hash/payment/complete`. New to shared.\n */\nimport { get } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** Fetch the confirmation-page payload for a completed order. */\nexport const getConfirmation = async (\n orderHash: string\n): Promise<Record<string, unknown>> =>\n get<Record<string, unknown>>(ENDPOINTS.order.confirmation(orderHash))\n","/**\n * Pre-registration — the \"register your interest, then share to climb the list\"\n * flow. Confirm interest for an event, then read the post-confirm share page and\n * submit share actions (referral phases). Backed by `pre-registration/*`\n * endpoints. New to shared.\n */\nimport { get, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** Decode the backend's lightweight pre-registration share-action token. */\nexport const decodeShareActionToken = (value: string, method?: string): string => {\n if (method === 'reverse_string') return value.split('').reverse().join('')\n if (method === 'symmetric_shuffle_string') {\n const split = Math.floor(value.length / 2)\n return value.substring(split) + value.substring(0, split)\n }\n if (method === 'shuffle_every_two_symbols_in_string') {\n let shuffled = ''\n for (let index = 0; index < value.length; index += 2) {\n shuffled += `${value[index + 1] ?? ''}${value[index] ?? ''}`\n }\n return shuffled\n }\n return value\n}\n\n/** Confirm pre-registration for an event. `attributes` carries the buyer's\n * answers; forwarded under the JSON:API `{ data: { attributes } }` envelope. */\nexport const confirmPreRegistration = async (\n eventId: string,\n attributes: Record<string, unknown>\n): Promise<unknown> =>\n post(ENDPOINTS.preRegistration.confirm(eventId), { data: { attributes } })\n\n/** Influencers/promoters available to share to for an event's pre-reg phase. */\nexport const getInfluencers = async (eventId: string): Promise<unknown> =>\n get(ENDPOINTS.preRegistration.influencers(eventId))\n\n/** The post-confirmation share page (options + the buyer's current standing). */\nexport const getConfirmationPage = async (hash: string): Promise<unknown> =>\n get(ENDPOINTS.preRegistration.confirmationPage(hash))\n\n/** Record a share action (a referral phase step) against a pre-reg hash. */\nexport const submitShareAction = async (\n hash: string,\n input: {\n eventActionId: number | string\n accessToken?: string\n shareActionToken?: string\n tokenShuffleMethod?: string\n phase?: string\n }\n): Promise<unknown> =>\n post(ENDPOINTS.preRegistration.submitAction(hash), {\n data: {\n attributes: {\n phase: input.phase ?? 'pre-registration',\n eventActionId: Number(input.eventActionId),\n accessToken:\n input.accessToken ??\n decodeShareActionToken(input.shareActionToken ?? '', input.tokenShuffleMethod),\n },\n },\n })\n","/**\n * Guest ticket delegation — the flow where someone is handed a ticket via an\n * access link and claims it without a full account. Check whether they already\n * have an account, read the claim page, and issue the ticket. Backed by\n * `v1/delegation-access/:hash/*`. New to shared.\n */\nimport { get, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** Whether the delegated recipient already has an account. */\nexport const checkCustomerExists = async (\n accessHash: string\n): Promise<Record<string, unknown>> =>\n get(ENDPOINTS.delegation.customerExists(accessHash))\n\n/** The claim page for a delegation access link (event + ticket context). */\nexport const getConsumerPageInfo = async (accessHash: string): Promise<unknown> =>\n get(ENDPOINTS.delegation.consumerPageInfo(accessHash))\n\n/** Issue (claim) the delegated ticket. `data` carries the recipient details;\n * forwarded under the JSON:API `{ data: { attributes } }` envelope. */\nexport const issueTicket = async (\n accessHash: string,\n data: Record<string, unknown>\n): Promise<unknown> =>\n post(ENDPOINTS.delegation.issueTicket(accessHash), {\n data: { attributes: data },\n })\n","/**\n * Seated events — the wire behind the seat picker. Fetch the venue map, poll\n * live seat statuses, and reserve a selection. The seats.io / tf-seat-map-view\n * widget itself is platform UI; these are just its API calls, so they belong in\n * shared. Backed by `v1/event/:id/{seat-map-data,seats/status,seats/reserve}`.\n * New to shared.\n */\nimport { del, get, patch, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** The venue seat map for an event (optionally scoped via `params`). */\nexport const getSeatMapData = async (\n eventId: string,\n params?: Record<string, unknown>\n): Promise<unknown> => {\n const url = ENDPOINTS.seatmap.data(eventId)\n console.log('[SeatMap API] getSeatMapData called', { eventId, params, url })\n try {\n const resp = await get(url, { params })\n console.log('[SeatMap API] getSeatMapData response', JSON.stringify(resp, null, 2))\n return resp\n } catch (err) {\n console.error('[SeatMap API] getSeatMapData FAILED', err)\n throw err\n }\n}\n\n/** Live availability/status for the event's seats (poll during selection). */\nexport const getSeatStatuses = async (eventId: string): Promise<unknown> =>\n get(ENDPOINTS.seatmap.statuses(eventId))\n\n/** Reserve a seat selection, e.g. `{ tierId, seatId, ttl: 10 }` — forwarded\n * under the backend's `{ data: … }` envelope. */\nexport const reserveSeats = async (\n eventId: string,\n reservation: Record<string, unknown>\n): Promise<unknown> => post(ENDPOINTS.seatmap.reserve(eventId), { data: reservation })\n\n/** Release a held reservation (DELETE with a body). */\nexport const removeReservedSeats = async (\n eventId: string,\n tierId: string,\n seatIds: string[]\n): Promise<unknown> =>\n // axios DELETE body rides `config.data`; the web sends { tierId, seatIds } bare.\n del(ENDPOINTS.seatmap.deleteReserved(eventId), {\n data: { tierId, seatIds },\n })\n\n/** Extend a seat reservation's TTL for an in-flight order. */\nexport const refreshReservation = async (\n eventId: string,\n orderId: string\n): Promise<unknown> =>\n patch(ENDPOINTS.seatmap.refreshReservation(eventId), { order_id: orderId })\n","/**\n * Catalog — the read side of an event: tickets, seating/info, terms, time-slot\n * sessions, custom fields, add-ons, promo codes, and multi-currency. Ported\n * faithfully from the engine's api layer; this layer OWNS the wire contract\n * (JSON:API `{ data: { attributes } }` envelopes, cents-vs-units, map-vs-array)\n * so nothing above it sees those details.\n */\nimport { get, post, put } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { isSeatedEvent as coreIsSeatedEvent } from '../logic'\nimport type {\n CurrencyState,\n CurrencySyncOptions,\n EventAddon,\n EventCondition,\n EventCustomField,\n EventCustomFieldGroup,\n TicketType,\n} from '../dtos'\n\nconst mapTicket = (t: any): TicketType => ({\n id: String(t.id),\n name: t.displayName ?? '',\n groupName: t.groupName ?? t.group_name ?? null,\n optionName: t.optionName ?? '',\n price: Number(t.price ?? 0),\n // `basePrice` is the with-fees amount; fall back to price when the wire omits it.\n priceWithFees: Number(t.basePrice ?? t.price ?? 0),\n priceSymbol: t.priceSymbol ?? '',\n currency: t.priceCurrency ?? '',\n feeIncluded: Boolean(t.feeIncluded),\n // `depositPercent` arrives as a string (\"50.00\") or null.\n depositPercent: t.depositPercent != null ? Number(t.depositPercent) : null,\n soldOut: Boolean(t.soldOut),\n salesStarted: Boolean(t.salesStarted),\n salesEnded: Boolean(t.salesEnded),\n minQuantity: Number(t.minQuantity ?? 1),\n maxQuantity: Number(t.maxQuantity ?? 10),\n multiplier: Number(t.multiplier ?? 1) || 1,\n isTable: Boolean(t.isTable),\n // Tables constrain the selectable quantity by guests, not the generic\n // min/max (which stay 1/10 on the wire). Undefined for non-tables.\n minGuests: t.minGuests != null ? Number(t.minGuests) : undefined,\n maxGuests: t.maxGuests != null ? Number(t.maxGuests) : undefined,\n allowDirectPurchase: Boolean(t.allowDirectPurchase),\n waitingListEnabled: Boolean(t.waitingListEnabled),\n waitingListMaxQuantity:\n t.waitingListMaxQuantity != null ? Number(t.waitingListMaxQuantity) : undefined,\n descriptionRich: t.descriptionRich ?? null,\n})\n\n/** Purchasable ticket types for an event. */\nexport const getEventTickets = async (eventId: string): Promise<TicketType[]> => {\n const body = await get<any>(ENDPOINTS.events.tickets(eventId))\n const ticketsObj = body?.data?.attributes?.tickets ?? {}\n return Object.values(ticketsObj).map(mapTicket)\n}\n\nexport interface EventSeatingInfo {\n /** The event uses reserved seating — the buyer picks on a seat map instead of\n * choosing quantities. Render seat-map ticket types read-only and route to\n * \"Select seats\". */\n isSeatedEvent: boolean\n /** The seat map is a TABLE map (its CTA reads \"Select on map\" vs \"Select\n * seats\"). Only meaningful when `isSeatedEvent`. */\n tableMapEnabled: boolean\n /** The event sells per date/time session — pick a date, then time-slot tickets.\n * (Attribute names inferred defensively; pass dates via a prop if your page\n * data already has them.) */\n isTimeSlotEvent: boolean\n /** Selectable session dates (ISO `yyyy-mm-dd`) for a time-slot event. */\n availableDates: string[]\n /** The event lets a buyer combine MORE THAN ONE ticket type in a single order.\n * When false (the default), selecting a new type replaces the previous one —\n * the ticket screen enforces one type at a time. Tables and regular tickets\n * are mutually exclusive regardless. */\n allowMultipleTicketTypePurchases: boolean\n slug: string | null\n name: string | null\n /** ISO country code used to seed billing/phone inputs like the storefront. */\n countryCode: string | null\n}\n\n/**\n * `GET v1/event/:id` — returns what the seated-event handoff needs:\n * `isSeatedEvent` (core's helper over the event attributes), plus slug/name for\n * the event-page link. `pk` is the optional preview key for unpublished events.\n */\nexport const getEventInfo = async (\n eventId: string,\n pk?: string\n): Promise<EventSeatingInfo> => {\n const body = await get<any>(ENDPOINTS.events.info(eventId), {\n params: pk ? { pk } : undefined,\n })\n const attributes = body?.data?.attributes ?? {}\n const a = attributes as Record<string, any>\n const slotSettings = a.timeslotSettings ?? a.timeslot_settings ?? {}\n const dates =\n slotSettings.availableDates ?? slotSettings.available_dates ?? a.available_dates ?? []\n const rawCountry = a.country\n const countryCode =\n (typeof rawCountry === 'string' ? rawCountry : rawCountry?.code) ??\n a.countryCode ??\n a.country_code ??\n null\n return {\n isSeatedEvent: coreIsSeatedEvent(attributes),\n tableMapEnabled: Boolean(a.tableMapEnabled ?? a.table_map_enabled),\n isTimeSlotEvent: Boolean(\n a.isTimeSlotEvent ?? a.is_time_slot_event ?? a.time_slot_event ?? a.is_timeslot\n ),\n availableDates: Array.isArray(dates) ? dates.map(String) : [],\n allowMultipleTicketTypePurchases: Boolean(\n a.allowMultipleTicketTypePurchases ?? a.allow_multiple_ticket_type_purchases\n ),\n slug: attributes.slug ?? null,\n name: attributes.name ?? null,\n countryCode: countryCode ? String(countryCode).toUpperCase() : null,\n }\n}\n\n/**\n * Event terms/conditions (client-side gate — nothing is submitted, the server\n * already knows them). LIVE contract: `attributes` is an ARRAY OF STRINGS, each\n * a MANDATORY acknowledgement; null when none. The object form\n * `{ conditions: [{id,name,content,is_required}] }` is tolerated defensively.\n */\nexport const getEventConditions = async (eventId: string): Promise<EventCondition[]> => {\n const body = await get<any>(ENDPOINTS.events.conditions(eventId))\n const attrs = body?.data?.attributes\n const items: any[] = Array.isArray(attrs)\n ? attrs\n : Array.isArray(attrs?.conditions)\n ? attrs.conditions\n : []\n return items\n .map((c, i): EventCondition => {\n if (typeof c === 'string') {\n return { id: String(i + 1), name: '', content: c, isRequired: true }\n }\n return {\n id: String(c?.id ?? i + 1),\n name: String(c?.name ?? ''),\n content: String(c?.content ?? ''),\n isRequired: c?.is_required === true,\n }\n })\n .filter((c) => c.content || c.name)\n}\n\n/**\n * Ticket types for one DATE of a time-slot (session/calendar) event. Each\n * returned `id` (matrix_record_id) is specific to the chosen date/session — how\n * the server knows the date; no date field exists in the add-to-cart body.\n * @param date \"YYYY-MM-DD\"\n * @param options.groupIds restrict to specific slot groups; omit for all.\n */\nexport const getEventTimeSlotTickets = async (\n eventId: string,\n date: string,\n options?: { groupIds?: number[] }\n): Promise<TicketType[]> => {\n const body = await get<any>(ENDPOINTS.events.timeSlotByDate(eventId), {\n params: {\n date,\n remove_past_slots: true,\n ...(options?.groupIds?.length ? { groupIds: options.groupIds } : {}),\n },\n })\n const grouped = body?.data?.attributes?.time_grouped_slot_ticket_types ?? {}\n const out: TicketType[] = []\n for (const [slotDate, hours] of Object.entries<any>(grouped ?? {})) {\n for (const hourKey of Object.keys(hours ?? {}).sort()) {\n const times = hours[hourKey] ?? {}\n for (const timeKey of Object.keys(times).sort()) {\n for (const s of Object.values<any>(times[timeKey] ?? {})) {\n if (!s?.matrix_record_id) continue\n const stock = Number(s.in_stock ?? s.real_stock ?? 0)\n out.push({\n id: String(s.matrix_record_id),\n name: s.display_name || s.option_value || 'Ticket',\n groupName: s.group_name ?? s.groupName ?? null,\n optionName: String(s.option_key ?? ''),\n price: Number(s.base_price ?? 0),\n priceWithFees: Number(s.price_with_fees ?? s.base_price ?? 0),\n priceSymbol: s.price_symbol ?? s.priceSymbol ?? '',\n currency: '',\n feeIncluded: false,\n depositPercent: s.deposit_percent != null ? Number(s.deposit_percent) : null,\n soldOut: Boolean(s.sold_out) || stock <= 0,\n salesStarted: s.sales_started != null ? Boolean(s.sales_started) : true,\n salesEnded: Boolean(s.sales_ended),\n minQuantity: Number(s.min_quantity ?? 1) || 1,\n maxQuantity: Number(s.max_quantity ?? 10) || 10,\n multiplier: Number(s.multiplier ?? 1) || 1,\n isTable: Boolean(s.is_table),\n allowDirectPurchase: true,\n descriptionRich: s.description ?? null,\n timeSlot: { date: slotDate, time: timeKey },\n })\n }\n }\n }\n }\n return out\n}\n\n/** checkbox → '1'/null; select_multi → string[]; else → string. Matches the\n * server's `!trim(value)` required check. */\nconst normalizeDefaultValue = (type: string, raw: unknown): string | string[] | null => {\n if (type === 'checkbox') {\n if (raw === true || raw === 1 || raw === '1') return '1'\n return null\n }\n if (raw == null || raw === '') return null\n if (type === 'select_multi') {\n if (Array.isArray(raw)) return raw.map(String)\n return [String(raw)]\n }\n if (Array.isArray(raw)) return String(raw[0] ?? '')\n return String(raw)\n}\n\n/** The event's custom-field groups (order / ticket / add-on scopes). [] when\n * the event has none. */\nexport const getEventCustomFields = async (\n eventId: string\n): Promise<EventCustomFieldGroup[]> => {\n const body = await get<any>(ENDPOINTS.events.customFields(eventId))\n const items: any[] = body?.data?.attributes ?? []\n if (!Array.isArray(items)) return []\n const groups: any[] = items.flatMap((item) => {\n if (!item || typeof item !== 'object') return []\n if (item.type && Array.isArray(item.fields)) return [item]\n return Object.values<any>(item)\n .map((v) => (v && typeof v === 'object' ? v.group : undefined))\n .filter((g) => g && typeof g === 'object')\n })\n return groups\n .filter((g) => g?.type === 'order' || g?.type === 'ticket' || g?.type === 'add-on')\n .map(\n (g): EventCustomFieldGroup => ({\n id: String(g.id ?? ''),\n label: g.label ?? null,\n scope: g.type,\n fields: (Array.isArray(g.fields) ? g.fields : []).map(\n (f: any): EventCustomField => ({\n id: String(f.id ?? ''),\n name: String(f.name ?? f.id ?? ''),\n label: String(f.label || f.name || ''),\n type: f.type,\n required: f.required === true,\n description: f.description ?? null,\n defaultValue: normalizeDefaultValue(f.type, f.defaultValue),\n options: (Array.isArray(f.options) ? f.options : []).map((o: any) => ({\n id: String(o.id ?? o.value ?? ''),\n name: String(o.name ?? o.value ?? ''),\n value: String(o.value ?? o.name ?? ''),\n })),\n ticketTypeIds: Array.isArray(f.settings?.ticketTypes)\n ? f.settings.ticketTypes.map(String)\n : null,\n })\n ),\n })\n )\n}\n\n/** Labels of REQUIRED order/ticket custom fields. Fails OPEN ([]) on error. */\nexport const getRequiredCustomFieldLabels = async (\n eventId: string\n): Promise<string[]> => {\n try {\n const groups = await getEventCustomFields(eventId)\n return groups\n .filter((g) => g.scope === 'order' || g.scope === 'ticket')\n .flatMap((g) => g.fields)\n .filter((f) => f.required)\n .map((f) => f.label || f.name)\n } catch {\n return []\n }\n}\n\n/** Event add-ons (active only), prices converted from wire cents to units. */\nexport const getEventAddons = async (eventId: string): Promise<EventAddon[]> => {\n const body = await get<any>(ENDPOINTS.events.addOns(eventId))\n const items: any[] = body?.data?.attributes?.add_ons ?? []\n return items\n .map((item) => {\n const a = item.attributes ?? {}\n return {\n id: String(a.id ?? item.id),\n name: a.name ?? '',\n description: a.description ?? null,\n price: Number(a.price ?? 0) / 100,\n currency: a.currency ?? '',\n feeIncluded: Boolean(a.feeIncluded),\n imageUrl: a.imageUrl ?? a.image ?? null,\n // NEVER coerce null to 0. The wire uses null for \"untracked\" (an\n // unlimited add-on) and an explicit 0 for \"sold out\"; every consumer\n // below treats `stock === 0` as the sold-out sentinel. Collapsing the\n // two made unlimited add-ons look sold out, which hid the whole\n // section (`addons.every(a => a.stock === 0)`) and silently exempted\n // required add-ons from the pre-flight gate.\n stock: a.stock == null ? null : Number(a.stock),\n maxQuantity: a.maxQuantity == null ? null : Number(a.maxQuantity),\n // The quantity-cap inputs. Dropping these let the UI offer quantities\n // the server hard-rejects (add_on_max_quantity) — see addOnMaxQuantity.\n flagLimitToTicketQuantity: Boolean(a.flagLimitToTicketQuantity),\n limitPerTicket: a.limitPerTicket == null ? null : Number(a.limitPerTicket),\n isCheckbox: Boolean(a.isCheckbox),\n level: a.level ?? null,\n groupName: a.groupName ?? null,\n required: Boolean(a.required),\n prerequisiteTicketTypeIds: Array.isArray(a.prerequisiteTicketTypeIds)\n ? a.prerequisiteTicketTypeIds.map(String)\n : null,\n active: a.active !== false,\n }\n })\n .filter((a) => a.active)\n .map(({ active: _active, ...addon }) => addon)\n}\n\n/**\n * The web checkout's add-on visibility rule: an add-on applies iff it has no\n * prerequisite ticket types, or they intersect the cart's DECRYPTED ids. With\n * no ids yet (cart not primed), returns the list unchanged. Pure — no request.\n */\nexport const filterAddonsForTickets = (\n addons: EventAddon[],\n ticketTypeIds: string[]\n): EventAddon[] => {\n if (!ticketTypeIds.length) return addons\n const selected = new Set(ticketTypeIds.map(String))\n return addons.filter((a) => {\n const prereq = a.prerequisiteTicketTypeIds\n if (!prereq || prereq.length === 0) return true\n return prereq.some((id) => selected.has(String(id)))\n })\n}\n\nexport interface TicketCatalogPromoMeta {\n isPromotionsEnabled: boolean\n isAccessCodeEnabled: boolean\n promoCodeValid?: boolean\n promoCodeMessage?: string\n}\n\n/** Tickets plus the catalog-level promo/access metadata the same response\n * carries — the read-back half of the promo-code loop. */\nexport const getEventTicketsWithMeta = async (\n eventId: string\n): Promise<{\n tickets: TicketType[]\n promo: TicketCatalogPromoMeta\n showWaitingList: boolean\n}> => {\n const body = await get<any>(ENDPOINTS.events.tickets(eventId))\n const attrs = body?.data?.attributes ?? {}\n const ticketsObj = attrs.tickets ?? {}\n return {\n tickets: Object.values(ticketsObj).map(mapTicket),\n promo: {\n isPromotionsEnabled: attrs.isPromotionsEnabled === true,\n isAccessCodeEnabled: attrs.is_access_code === true,\n promoCodeValid:\n typeof attrs.ValidPromoCode === 'boolean' ? attrs.ValidPromoCode : undefined,\n promoCodeMessage: attrs.PromoCodeValidationMessage ?? undefined,\n },\n showWaitingList: attrs.showWaitingList === true,\n }\n}\n\n/**\n * Applies a promo/access code to the session (empty string removes it). The\n * endpoint ALWAYS answers success (anti-brute-force) — read the outcome from a\n * fresh `getEventTicketsWithMeta` (`promo.promoCodeValid`).\n */\nexport const submitPromoCode = async (eventId: string, promo: string): Promise<void> => {\n await post(ENDPOINTS.events.promo(eventId), { promo: promo.trim() })\n}\n\n/**\n * Session currency preference (multi-currency events). A bare call geo-seeds and\n * reports the resolved state; passing a code switches it (every later read\n * reprices — restart ticket selection after a switch). `{ seed: true }` replays\n * a carried-over currency without overwriting the buyer's own choice.\n */\nexport const setEventCurrency = async (\n eventId: string,\n code?: string,\n options?: CurrencySyncOptions\n): Promise<CurrencyState> => {\n const body = await post<any>(ENDPOINTS.events.currency(eventId), {\n data: {\n attributes: code\n ? options?.seed\n ? { currency: code, seed: true }\n : { currency: code }\n : {},\n },\n })\n return body?.data?.attributes as CurrencyState\n}\n\n/** Unlock a password-protected event. Throws `TtfError` on the wrong password. */\nexport const authenticateEvent = async (\n eventId: string,\n password: string\n): Promise<unknown> =>\n post(ENDPOINTS.events.authenticate(eventId), {\n attributes: { data: { password } },\n })\n\n/** Fire the event's tracking pixel (page view / order attribution). */\nexport const trackEvent = async (\n eventId: string,\n options: { pageUrl?: string; page?: string; orderHash?: string }\n): Promise<unknown> =>\n get(ENDPOINTS.events.track(eventId), {\n params: {\n page_url: options.pageUrl,\n page: options.page,\n order_hash: options.orderHash,\n },\n })\n\n/** Write ORDER-level custom-field values after the order exists. */\nexport const updateOrderDataCapture = async (\n eventId: string,\n orderId: string,\n dataCapture: Record<string, unknown>\n): Promise<unknown> =>\n put(ENDPOINTS.events.orderDataCapture(eventId), {\n data: { attributes: { order_id: orderId, data_capture: dataCapture } },\n })\n\n/** Write TICKET-level (per-holder) custom-field values for one ticket hash. */\nexport const updateTicketDataCapture = async (\n eventId: string,\n ticketHash: string,\n values: Record<string, unknown>\n): Promise<unknown> =>\n put(ENDPOINTS.events.ticketDataCapture(eventId), {\n data: {\n attributes: {\n ticket_hash: ticketHash,\n ticket_data_capture: { [ticketHash]: values },\n },\n },\n })\n","/**\n * Cart + checkout session — build the server cart, read it back (pins the\n * event's payment method into the session), price it with add-ons, and read the\n * pre-order payment config. Ported faithfully from the engine's api layer.\n */\nimport { ENV_HOSTS, getOriginUrl } from '../client/config'\nimport { get, post } from '../client/http'\nimport {\n ENDPOINTS,\n listRedirectMethods,\n XENDIT_NON_EWALLET_PROCESSORS,\n} from '../constants'\nimport {\n evaluateFieldGates,\n identifyPreOrderGateway,\n interpretContactEmail,\n paypalTabConfig,\n priceBreakdownAddOnsQuery,\n resolvePriceBreakdown,\n walletsOption,\n xenditPreOrderConfig,\n} from '../logic'\nimport type {\n AddonSelection,\n BuyerFieldVisibility,\n CheckoutBreakdown,\n CheckoutPaymentPlan,\n CheckoutPaymentPlanPreview,\n CheckoutWalletAvailability,\n ExistingAccount,\n PreOrderGateway,\n PriceBreakdown,\n SeatLine,\n StripeConfig,\n StripeWallets,\n TicketSelection,\n XenditProcessor,\n} from '../dtos'\n\n/**\n * Adds ALL selected ticket types to the server cart in ONE call. The endpoint\n * REPLACES the entire cart every call, so per-type calls would keep only the\n * last. The `{ data: { attributes } }` envelope is mandatory (the backend\n * copies data.attributes into $_POST and 422s without it).\n */\nexport const addTicketsToCart = async (\n eventId: string,\n selections: TicketSelection[]\n): Promise<{ holderNamesRequired: boolean }> => {\n const first = selections[0]\n if (!first) throw new Error('addTicketsToCart: no tickets selected.')\n const body = await post<any>(ENDPOINTS.cart.addToCart(eventId), {\n data: {\n attributes: {\n alternative_view_id: null,\n product_cart_quantity: first.quantity,\n product_options: { [first.optionName]: first.id },\n product_id: Number(eventId),\n ticket_types: Object.fromEntries(\n selections.map((t) => [\n t.id,\n {\n product_options: { [t.optionName]: t.id, ticket_price: t.price },\n quantity: t.quantity,\n },\n ])\n ),\n },\n },\n })\n return { holderNamesRequired: Boolean(body?.data?.attributes?.names_required) }\n}\n\n/**\n * Adds RESERVED SEATS to the server cart — the seat-map analogue of\n * `addTicketsToCart`, a faithful port of the legacy `getAddToCartRequestData`\n * (`seatMapContainer/utils.ts`). Kept separate because a seated order's body\n * differs from a plain-ticket one in two ways `addTicketsToCart` can't express:\n *\n * - `product_cart_quantity` is the TOTAL number of reserved seats (not the\n * first line's quantity), and\n * - when ANY line carries a guest count (tables / group tickets) the\n * `ticket_types` map is keyed by INDEX with `quantity = guests` (one line per\n * seat); otherwise it's keyed by ticket-type id with quantities aggregated.\n *\n * Seat ids never appear in the body — the server binds cart lines to seats\n * through the live reservation (held by `ttf.seatmap.reserve`).\n */\nexport const addSeatsToCart = async (\n eventId: string,\n lines: SeatLine[]\n): Promise<{ holderNamesRequired: boolean }> => {\n if (!lines.length) throw new Error('addSeatsToCart: no seats selected.')\n const hasGuests = lines.some((l) => l.guests != null)\n const product_options: Record<string, string> = {}\n const ticket_types: Record<string, unknown> = {}\n lines.forEach((l, index) => {\n // Last-write-wins over the shared option key — matches legacy utils.ts.\n product_options[l.optionName] = l.ticketTypeId\n const key = hasGuests ? index : l.ticketTypeId\n const prevQty = hasGuests\n ? 0\n : ((ticket_types[l.ticketTypeId] as { quantity?: number } | undefined)?.quantity ??\n 0)\n const quantity = hasGuests ? (l.guests as number) : prevQty + 1\n ticket_types[key] = {\n quantity,\n product_options: { [l.optionName]: l.ticketTypeId, ticket_price: l.price },\n }\n })\n const body = await post<any>(ENDPOINTS.cart.addToCart(eventId), {\n data: {\n attributes: {\n alternative_view_id: null,\n product_cart_quantity: lines.length,\n product_options,\n product_id: Number(eventId),\n ticket_types,\n },\n },\n })\n return { holderNamesRequired: Boolean(body?.data?.attributes?.names_required) }\n}\n\n/**\n * Reads the cart back. MANDATORY between add-to-cart and updateCheckout: this\n * call writes the event's payment method into the PHP session, which\n * POST v1/checkout reads. Returns reservation seconds remaining plus the raw\n * pre-order gateway string (preserved verbatim so an unknown/future gateway\n * stays fail-closed at the engine's Stripe-only guard).\n */\nexport const getCart = async (): Promise<{\n expiresInSeconds: number\n preOrderGateway: string | null\n}> => {\n const body = await get<any>(ENDPOINTS.cart.get, { params: { payment_config: 1 } })\n const attrs = body?.data?.attributes\n const raw = Number(attrs?.expiresAt)\n const gateway = attrs?.payment?.gateway\n return {\n expiresInSeconds: Number.isFinite(raw) && raw > 0 ? raw : 420,\n preOrderGateway: typeof gateway === 'string' && gateway ? gateway : null,\n }\n}\n\n/**\n * Checkout gates for the CURRENT cart session (`GET v1/checkout-configs`).\n * Session-scoped: call only after the cart exists. The reliable source for the\n * collect_names gate (staging's add-to-cart returns empty attributes).\n */\nexport const getCheckoutConfigs = async (): Promise<{\n holderNamesRequired: boolean\n fieldGates: BuyerFieldVisibility\n}> => {\n const body = await get<any>(ENDPOINTS.cart.checkoutConfigs)\n const attrs = body?.data?.attributes ?? {}\n return {\n holderNamesRequired: Boolean(attrs.names_required),\n fieldGates: evaluateFieldGates(attrs),\n }\n}\n\nexport interface CheckoutPricing {\n /** DECRYPTED ticket type ids (the tickets endpoint only has encrypted ones). */\n ticketTypeIds: string[]\n breakdown?: CheckoutBreakdown\n stripe?: StripeConfig\n paymentPlan?: CheckoutPaymentPlan\n redirectPaymentMethods?: string[]\n walletAvailability?: CheckoutWalletAvailability\n /** Server deferred-mode Stripe Elements config (mode/amount/currency) — mounts\n * the wallet-capable Payment Element exactly as the old checkout did. */\n stripeElementsConfig?: Record<string, unknown>\n}\n\n/** Parses `payment_plan_configuration` into the camelCase installment preview\n * (display-only). Undefined when absent or without an installment shape. */\nconst parsePlanPreview = (\n config: Record<string, any> | null | undefined\n): CheckoutPaymentPlanPreview | undefined => {\n if (!config || typeof config !== 'object') return undefined\n const num = (v: unknown): number | undefined =>\n v == null || v === '' || Number.isNaN(Number(v)) ? undefined : Number(v)\n const bool = (v: unknown): boolean | undefined =>\n typeof v === 'boolean' ? v : undefined\n const preview: CheckoutPaymentPlanPreview = {\n interval: num(config.interval),\n totalInstallments: num(config.total_installments),\n pricePerInstallment: num(config.price_per_installment),\n total: num(config.total),\n downPaymentEnabled:\n typeof config.down_payment_enabled === 'boolean'\n ? config.down_payment_enabled\n : undefined,\n downPaymentAmount:\n config.down_payment_amount == null ? null : num(config.down_payment_amount),\n currency: typeof config.currency === 'string' ? config.currency : undefined,\n currencySymbol:\n typeof config.currency_symbol === 'string' ? config.currency_symbol : undefined,\n customMessage: config.custom_message == null ? null : String(config.custom_message),\n terminology: typeof config.terminology === 'string' ? config.terminology : undefined,\n manufacturerName:\n typeof config.manufacturer_name === 'string' ? config.manufacturer_name : undefined,\n\n // The disclosure fields. The backend has always sent these; dropping them\n // here is what made our plan terms a three-line summary while the hosted\n // checkout states the admin fee and what the buyer forfeits on default.\n isAutoEqual: bool(config.is_auto_equal),\n hasAdminFee: bool(config.has_admin_fee),\n adminFee: config.admin_fee == null ? null : (num(config.admin_fee) ?? null),\n nonRefundableType:\n config.non_refundable_type === 'fixed' || config.non_refundable_type === 'percent'\n ? config.non_refundable_type\n : null,\n nonRefundableAmount:\n config.non_refundable_amount == null\n ? null\n : (num(config.non_refundable_amount) ?? null),\n totalNonRefundableAmount:\n config.total_non_refundable_amount == null\n ? null\n : (num(config.total_non_refundable_amount) ?? null),\n hideNonRefundableAdminFeeText: bool(config.hide_non_refundable_admin_fee_text),\n isEventAnchored: bool(config.is_event_anchored),\n finalChargeDate:\n config.final_charge_date == null ? null : String(config.final_charge_date),\n\n downPaymentMode:\n config.down_payment_mode == null ? null : String(config.down_payment_mode),\n downPaymentScope:\n config.down_payment_scope == null ? null : String(config.down_payment_scope),\n downPaymentPercent:\n config.down_payment_percent == null\n ? null\n : (num(config.down_payment_percent) ?? null),\n downPaymentPerTicketAmount:\n config.down_payment_per_ticket_amount == null\n ? null\n : (num(config.down_payment_per_ticket_amount) ?? null),\n downPaymentTicketCount:\n config.down_payment_ticket_count == null\n ? null\n : (num(config.down_payment_ticket_count) ?? null),\n }\n return preview.totalInstallments != null || preview.pricePerInstallment != null\n ? preview\n : undefined\n}\n\n/**\n * Prices the cart (+ chosen add-ons); returns the decrypted ticket type ids and\n * the Stripe config. Re-run whenever the add-on selection changes.\n *\n * paymentOption MUST be 'single_charge' — any other value makes the backend\n * reprice with a method-specific fee structure and silently drop booking fees\n * (undercharge vs. the price shown on the event page).\n */\nexport const updateCheckout = async (\n eventId: string,\n addOns: AddonSelection,\n options: { isFromResale?: boolean } = {}\n): Promise<CheckoutPricing> => {\n const body = await post<any>(ENDPOINTS.cart.checkout, {\n data: {\n attributes: {\n event_id: eventId,\n add_ons: addOns,\n is_from_resale: options.isFromResale ?? false,\n payment_information: {\n paymentSolution: 'stripe',\n paymentOption: 'single_charge',\n },\n },\n },\n })\n const attrs = body?.data?.attributes\n const cb = attrs?.cart_price_breakdown\n const api = attrs?.additional_payment_information\n const basic = api?.basic_config\n const planConfig = api?.payment_plan_configuration\n const planSavedLast4 = planConfig?.saved_card?.last_4_digits\n const redirectPaymentMethods = listRedirectMethods(\n api?.elements_config?.paymentMethodTypes\n )\n const wallets = walletsOption(api?.stripe_wallets as StripeWallets | undefined)\n\n return {\n ticketTypeIds: (cb?.tickets_price_breakdown ?? []).map((i: any) =>\n String(i.ticket_type_id)\n ),\n breakdown: cb\n ? {\n total: Number(cb.total ?? 0),\n totalAddOns: Number(cb.total_add_ons ?? 0),\n currencyCode: cb.currency?.currency ?? '',\n currencySymbol: cb.currency?.symbol ?? '',\n tickets: (cb.tickets_price_breakdown ?? []).map((t: any) => ({\n name: t.ticket_type_name,\n ticketTypeId: t.ticket_type_id != null ? String(t.ticket_type_id) : '',\n quantity: Number(t.quantity ?? 0),\n unit: String(t.price_per_ticket ?? ''),\n total: Number(t.total_price ?? 0),\n })),\n }\n : undefined,\n stripe: basic?.apiKey\n ? { publishableKey: basic.apiKey, accountId: basic.accountId || null }\n : undefined,\n paymentPlan:\n api?.payment_plan_available === true\n ? {\n available: true,\n savedCardLast4:\n typeof planSavedLast4 === 'string' ? planSavedLast4 : undefined,\n configuration: parsePlanPreview(planConfig),\n }\n : undefined,\n redirectPaymentMethods,\n walletAvailability: {\n applePay: wallets.applePay === 'auto',\n googlePay: wallets.googlePay === 'auto',\n },\n // The whole deferred block (mode/amount/currency/paymentMethodTypes). The\n // Payment Element mounts against this — server-computed amounts sidestep\n // zero-decimal-currency math. Undefined when the event isn't Stripe-deferred.\n stripeElementsConfig:\n api?.elements_config && typeof api.elements_config === 'object'\n ? (api.elements_config as Record<string, unknown>)\n : undefined,\n }\n}\n\n/**\n * Server-priced order summary (display-ready, server-formatted strings — render\n * verbatim, never recompute). Null when the backend doesn't serve the block.\n */\nexport const getPriceBreakdown = async (\n addOns?: AddonSelection\n): Promise<PriceBreakdown | null> => {\n const body = await get<any>(\n ENDPOINTS.cart.withPriceBreakdown(priceBreakdownAddOnsQuery(addOns))\n )\n return resolvePriceBreakdown(body?.data?.attributes)\n}\n\n/** Raw pre-order payment-config attributes (GET v1/cart?payment_config=1) — feed\n * to core's paypalTabConfig / xenditPreOrderConfig / walletsOption. */\nexport const getPaymentConfigAttributes = async (): Promise<Record<string, unknown>> => {\n const body = await get<any>(ENDPOINTS.cart.withPaymentConfig)\n return (body?.data?.attributes ?? {}) as Record<string, unknown>\n}\n\nexport interface PreOrderPaymentMethods {\n gateway: PreOrderGateway | null\n xenditEWallets: XenditProcessor[]\n xenditCard: boolean\n paypal: boolean\n}\n\n/** Resolves a (possibly relative) processor icon path against the host origin. */\nconst absolutizeIcon = (origin: string, icon?: string): string | undefined => {\n if (!icon) return undefined\n if (/^(https?:)?\\/\\//i.test(icon) || icon.startsWith('data:')) return icon\n if (!origin) return icon\n return `${origin}/${icon.replace(/^\\//, '')}`\n}\n\n/**\n * What this event's checkout can pay with BEFORE the order exists — read from\n * the pre-order payment config exactly as the hosted selector does.\n */\nexport const getPreOrderPaymentMethods = async (): Promise<PreOrderPaymentMethods> => {\n const attrs = await getPaymentConfigAttributes()\n const xendit = xenditPreOrderConfig(attrs)\n // The backend returns each processor icon as a RELATIVE path (e.g.\n // `/resources/images/payment/xendit/dana.png`). These are TicketFairy-global\n // brand marks served PUBLICLY from the production site — that's how the old\n // checkout loaded them (its relative paths resolved against the public host).\n // Resolve them the same way, against the public origin, so an <img> loads\n // them token-free even when the API is pointed at the access-gated staging\n // host (test.ticketfairy.com/resources 302s to a CF login, and an <img>\n // can't carry the CF-Access token). Absolute icon URLs are left untouched.\n const iconOrigin = ENV_HOSTS.PROD\n return {\n gateway: identifyPreOrderGateway(attrs),\n xenditEWallets: xendit\n ? xendit.processors\n .filter((row) => !XENDIT_NON_EWALLET_PROCESSORS.has(row.key))\n .map((row) => ({ ...row, icon: absolutizeIcon(iconOrigin, row.icon) }))\n : [],\n xenditCard: Boolean(xendit),\n paypal: Boolean(paypalTabConfig(attrs)),\n }\n}\n\n/**\n * Existing-account detection (the hosted `init_email_check`): reports whether a\n * live account owns the email so returning buyers get a sign-in prompt. Never a\n * gate — debounce it, keep typing unblocked. Origin-rooted and form-encoded.\n */\nexport const checkBuyerEmail = async (email: string): Promise<ExistingAccount> => {\n const res = await post<any>(\n `${getOriginUrl()}/${ENDPOINTS.auth.contactEmail}`,\n `email=${encodeURIComponent(email)}&is_checkout_flow=1`,\n { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }\n )\n return interpretContactEmail(res)\n}\n","/**\n * Order — create the order from the buyer/holders/add-ons, read the review\n * (gateway identity + Stripe/plan secrets), finalize (free registration or\n * success), and read ID-verification status. Ported faithfully from the\n * engine's api layer; the on-checkout body is composed by core's\n * `buildOnCheckoutBody` (the contract-pinned builder checkout-v2 also uses).\n */\nimport { post, get } from '../client/http'\nimport { TtfError } from '../client/errors'\nimport { ENDPOINTS } from '../constants'\nimport {\n buildOnCheckoutBody,\n detectGateway,\n paymentIntentIdFromClientSecret,\n savedPlanCard,\n} from '../logic'\nimport type {\n AddonSelection,\n CheckoutBilling,\n CheckoutConsent,\n CheckoutHolder,\n CustomFieldValues,\n IdVerificationStatus,\n SavedPlanCard,\n} from '../dtos'\nimport type { TfProfile } from '../types'\n\nexport interface CreatedOrder {\n hash: string\n total: string\n payNow: string\n status: string\n /** Duplicate-charge guard: true when the server answered with an\n * ALREADY-COMPLETED paid order (payment landed out-of-band). Go straight to\n * confirmation — never charge again. */\n alreadyPaid: boolean\n}\n\nexport const createOrder = async (input: {\n billing: CheckoutBilling\n holders: CheckoutHolder[]\n addOns: AddonSelection\n consent: CheckoutConsent\n /** Add-on custom-field values keyed by add-on id → add_on_data_capture. */\n addOnDataCapture?: Record<string, CustomFieldValues>\n}): Promise<CreatedOrder> => {\n const { billing, holders, addOns, consent, addOnDataCapture } = input\n\n const attributes = buildOnCheckoutBody(\n {\n buyerFields: {\n nationality: billing.nationality,\n gender: billing.gender,\n instagramHandle: billing.instagramHandle,\n },\n dataCapture: billing.dataCapture,\n ticketHolders: holders.map((h) => ({\n firstName: h.firstName,\n lastName: h.lastName,\n email: h.email,\n phone: h.phone ?? '',\n ticketTypeId: h.ticketTypeId,\n ticketDataCapture: h.ticketDataCapture,\n })),\n addOns,\n ...(addOnDataCapture\n ? {\n addOnDataCapture: Object.fromEntries(\n Object.entries(addOnDataCapture).filter(\n ([id, values]) =>\n Number(addOns[id]) > 0 && values && Object.keys(values).length > 0\n )\n ),\n }\n : {}),\n },\n {\n email: billing.email,\n confirm_email: billing.email,\n first_name: billing.firstName,\n last_name: billing.lastName,\n password: '',\n phone: billing.phone ?? '',\n ttf_opt_in: consent.ttfOptIn,\n brand_opt_in: consent.brandOptIn,\n ...(billing.streetAddress ? { street_address: billing.streetAddress } : {}),\n ...(billing.city ? { city: billing.city } : {}),\n ...(billing.zip ? { zip: billing.zip } : {}),\n ...(billing.countryId ? { country: Number(billing.countryId) } : {}),\n ...(billing.stateId ? { state: Number(billing.stateId) } : {}),\n ...(billing.dobDay && billing.dobMonth && billing.dobYear\n ? {\n dob_day: billing.dobDay,\n dob_month: billing.dobMonth,\n dob_year: billing.dobYear,\n }\n : {}),\n }\n )\n\n const body = await post<any>(ENDPOINTS.order.create, { data: { attributes } })\n const a = body?.data?.attributes\n if (!a?.hash) throw new TtfError('Order was not created (no hash in response).', 0)\n return {\n hash: String(a.hash),\n total: String(a.total ?? ''),\n payNow: String(a.pay_now ?? ''),\n status: String(a.status ?? ''),\n alreadyPaid: String(a.status ?? '') === 'paid',\n }\n}\n\nexport interface OrderReview {\n total: string\n clientSecret: string | null\n publishableKey: string | null\n connectedAccount: string | null\n expiresInSeconds?: number\n paymentAlreadyProcessed: boolean\n gateway: ReturnType<typeof detectGateway>\n orderId?: string\n currency?: string\n stripeIntentId?: string\n payNow?: string\n razorpayKeyId?: string\n xenditPublishableKey?: string\n xenditOnBehalfOf?: string | null\n paymentPlanSetupSecret?: string\n paymentPlanSavedCard: SavedPlanCard | null\n}\n\nexport const getOrderReview = async (orderHash: string): Promise<OrderReview> => {\n const body = await get<any>(ENDPOINTS.order.review(orderHash))\n const a = body?.data?.attributes\n const method = a?.payment_method ?? {}\n const rawExpiry = Number(a?.expires_at)\n return {\n total: String(a?.order_details?.total ?? ''),\n paymentAlreadyProcessed: Boolean(method.payment_already_processed),\n clientSecret: method.stripe_client_secret ?? null,\n publishableKey: method.stripe_publishable_key ?? null,\n connectedAccount: method.stripe_connected_account || null,\n expiresInSeconds: Number.isFinite(rawExpiry) && rawExpiry > 0 ? rawExpiry : undefined,\n gateway: detectGateway(method),\n orderId: a?.order_details?.id != null ? String(a.order_details.id) : undefined,\n currency: a?.order_details?.currency ?? undefined,\n stripeIntentId:\n (typeof method.stripe_intent_id === 'string' && method.stripe_intent_id) ||\n paymentIntentIdFromClientSecret(method.stripe_client_secret) ||\n undefined,\n payNow:\n a?.order_details?.pay_now != null ? String(a.order_details.pay_now) : undefined,\n razorpayKeyId: method.razorpay_key_id || method.key_id || method.api_key || undefined,\n xenditPublishableKey:\n method.xendit_publishable_key ||\n method.publishable_key ||\n method.api_key ||\n undefined,\n xenditOnBehalfOf: (method.xendit_on_behalf_of as string | undefined) ?? null,\n paymentPlanSetupSecret:\n (typeof method.stripe_payment_plan_configuration?.stripe_setup_intent_secret ===\n 'string' &&\n method.stripe_payment_plan_configuration.stripe_setup_intent_secret) ||\n undefined,\n paymentPlanSavedCard: savedPlanCard(method as Record<string, unknown>),\n }\n}\n\n/**\n * Maps a signed-in user's profile into a `CheckoutBilling` to prefill the\n * billing form. Merge over your own edits:\n * `setBilling({ ...mapProfileToBilling(profile), ...edits })`.\n */\nexport const mapProfileToBilling = (profile: TfProfile): CheckoutBilling => {\n const str = (v: string | number | null | undefined): string | undefined =>\n v == null || v === '' ? undefined : String(v)\n // 0 / '0' / '-1' are \"no selection\" sentinels for country/state ids.\n const idStr = (v: string | number | null | undefined): string | undefined => {\n const s = str(v)\n return s === undefined || s === '0' || s === '-1' ? undefined : s\n }\n return {\n firstName: profile.firstName ?? '',\n lastName: profile.lastName ?? '',\n email: profile.email ?? '',\n phone: str(profile.phone),\n streetAddress: str(profile.streetAddress),\n city: str(profile.city),\n zip: str(profile.zipCode),\n countryId: idStr(profile.countryId),\n stateId: idStr(profile.stateId),\n }\n}\n\nexport const completeFreeRegistration = async (orderHash: string): Promise<void> => {\n await post(ENDPOINTS.order.completeFreeRegistration(orderHash))\n}\n\nexport const confirmOrderSuccess = async (\n orderHash: string,\n options?: {\n /** Razorpay settle token (`razorpay_payment_id`) — the server fetches +\n * captures the charge with it. */\n token?: string\n }\n): Promise<{ needIdVerification: boolean }> => {\n const body = await post<any>(\n ENDPOINTS.order.success(orderHash),\n options?.token ? { token: options.token } : undefined\n )\n return {\n needIdVerification: Boolean(\n body?.data?.attributes?.needIdVerification ?? body?.data?.needIdVerification\n ),\n }\n}\n\n/**\n * ID-verification status for a NEED_ID_VERIFICATION order. Pass `mintUrl: true`\n * on the call that OPENS the provider session (the server mints\n * `verification_url` on that call only); poll the plain form afterwards.\n */\nexport const getIdVerificationStatus = async (\n orderHash: string,\n mintUrl?: boolean\n): Promise<IdVerificationStatus> => {\n const body = await get<any>(ENDPOINTS.order.idVerification(orderHash, mintUrl))\n return (body?.data?.attributes ?? {}) as IdVerificationStatus\n}\n\n/** Whether the signed-in user owns this order (guards the confirmation page\n * against someone opening another buyer's order hash). */\nexport const verifyCustomerOrder = async (orderHash: string): Promise<unknown> =>\n get(ENDPOINTS.order.verifyCustomer(orderHash))\n","/**\n * Payment-rail transports — the per-gateway wire calls the engine dispatches to\n * after the order exists: fee re-price, redirect confirm, OXXO prepare, Xendit\n * e-wallet/card charge, MSI installments, payment plans, and PayPal Standard.\n * Ported faithfully from the engine's api layer; request/response shaping stays\n * in core's interpreters.\n */\nimport { get, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport {\n buildPaymentMethodTypeAttributes,\n interpretRedirectConfirm,\n resolvePayPalForm,\n} from '../logic'\nimport type {\n PaymentMethodTypeInput,\n PayPalForm,\n RedirectConfirmRequest,\n RedirectOutcome,\n} from '../dtos'\n\nconst postFormEncoded = (\n uri: string,\n fields: Record<string, string>\n): Promise<Record<string, unknown>> =>\n post<Record<string, unknown>>(\n uri,\n Object.entries(fields)\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join('&'),\n { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }\n ).then((data) => data ?? {})\n\nconst appendFormObject = (\n form: FormData,\n prefix: string,\n obj: Record<string, unknown>\n) => {\n Object.keys(obj).forEach((key) => {\n const value = obj[key]\n if (value === null || value === undefined) return\n if (typeof value === 'object') {\n appendFormObject(form, `${prefix}[${key}]`, value as Record<string, unknown>)\n } else {\n form.append(`${prefix}[${key}]`, String(value))\n }\n })\n}\n\n/**\n * Per-payment-method-type fee re-price (Klarna/Afterpay-class types carry their\n * own fee structures). Run BEFORE confirming a fee-mode type, then re-fetch the\n * review — charging the pre-reprice amount would undercharge.\n */\nexport const changePaymentMethodType = async (\n orderHash: string,\n input: PaymentMethodTypeInput\n): Promise<void> => {\n await post(ENDPOINTS.payment.methodType(orderHash), {\n data: { attributes: buildPaymentMethodTypeAttributes(input) },\n })\n}\n\n/** Server-side confirm for redirect-based Stripe methods — returns the provider\n * hand-off (or 'settled' when no redirect is needed). */\nexport const confirmRedirect = async (\n orderHash: string,\n request: RedirectConfirmRequest\n): Promise<RedirectOutcome> => {\n const body = await post<any>(ENDPOINTS.payment.confirmRedirect(orderHash), request)\n return interpretRedirectConfirm(body?.data?.attributes)\n}\n\n/** OXXO: move the order (and its goods) to the pending-voucher state BEFORE the\n * client confirm. Empty body; needs the registered session. */\nexport const prepareForOxxo = async (orderHash: string): Promise<void> => {\n await post(ENDPOINTS.payment.prepareOxxo(orderHash))\n}\n\n/** Xendit e-wallet charge — multipart fields from core's\n * `buildXenditEWalletChargeFields`; interpret with `interpretXenditChargeResponse`. */\nexport const submitXenditEWalletCharge = async (\n fields: Record<string, string>\n): Promise<Record<string, unknown>> => {\n const form = new FormData()\n Object.entries(fields).forEach(([key, value]) => form.append(key, value))\n const data = await post<Record<string, unknown>>(\n ENDPOINTS.payment.submitPayment(encodeURIComponent(fields.orderHash)),\n form,\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n return data ?? {}\n}\n\n/** MSI offers — between payment-method creation and the confirm; the server\n * gates to MXN carts. Fields from `buildInstallmentOffersFields`. */\nexport const getInstallmentOffers = (\n orderHash: string,\n fields: Record<string, string>\n): Promise<Record<string, unknown>> =>\n postFormEncoded(ENDPOINTS.payment.installmentOffers(orderHash), fields)\n\n/** MSI confirm: the intent confirms SERVER-SIDE — when has_next_action comes\n * back, run only handleNextAction, never a second confirmPayment. */\nexport const confirmInstallments = (\n orderHash: string,\n fields: Record<string, string>\n): Promise<Record<string, unknown>> =>\n postFormEncoded(ENDPOINTS.payment.confirmInstallments(orderHash), fields)\n\n/**\n * Payment plan (installments) with a NEW card: the card is saved via the\n * review's SetupIntent (confirmed on the confirmer, nothing charged), then this\n * schedules the plan server-side against the resulting PaymentMethod.\n */\nexport const createPaymentPlan = async (\n orderHash: string,\n stripePaymentMethodId: string\n): Promise<{ needIdVerification: boolean }> => {\n const body = await post<any>(ENDPOINTS.payment.paymentPlanCreate(orderHash), {\n stripe_payment_method_id: stripePaymentMethodId,\n })\n return {\n needIdVerification: Boolean(\n body?.data?.attributes?.needIdVerification ?? body?.data?.needIdVerification\n ),\n }\n}\n\n/**\n * Payment-plan saved-card shortcut: charge the plan directly to the reusable\n * card the review carries, skipping the SetupIntent round trip. The server may\n * answer `requires_action` with a client secret — run 3DS, then settle.\n */\nexport const chargeSavedCardPlan = async (\n orderHash: string,\n paymentMethodId: string\n): Promise<{ requiresAction: boolean; clientSecret?: string }> => {\n const data = await postFormEncoded(ENDPOINTS.cart.paymentPlan(orderHash), {\n paymentMethodId,\n })\n const inner = ((data.data as Record<string, unknown> | undefined) ?? data) || {}\n return {\n requiresAction: Boolean(inner.requires_action),\n clientSecret:\n typeof inner.client_secret === 'string' ? inner.client_secret : undefined,\n }\n}\n\n/** PayPal Standard step 1: switch the placed order's payment method (attributes\n * from core's `buildChangePaymentMethodAttributes`). */\nexport const changePaymentMethod = async (\n attributes: Record<string, unknown>\n): Promise<void> => {\n await post(ENDPOINTS.payment.changeMethod, {\n data: { attributes },\n })\n}\n\n/** PayPal Standard step 2: the `{action_url, fields}` document the provider page\n * auto-submits (PayPal refuses framing — top-level POST only). */\nexport const getPayPalForm = async (orderHash: string): Promise<PayPalForm | null> => {\n const body = await get<any>(ENDPOINTS.payment.paypalForm(orderHash))\n return resolvePayPalForm(body?.data?.attributes ?? null)\n}\n\n/**\n * Xendit CARD charge: the sheet tokenized the card (with 3DS) client-side; the\n * token is charged server-side (the amount is resolved from the order, the\n * token only proves the card). Success responses may still carry error:true;\n * that throws here.\n */\nexport const submitXenditCardCharge = async (\n orderId: string,\n orderHash: string,\n token: Record<string, unknown>\n): Promise<Record<string, unknown>> => {\n const form = new FormData()\n form.append('order', String(orderId))\n form.append('orderHash', orderHash)\n form.append('paymentData[paymentType]', 'credit_card')\n appendFormObject(form, 'paymentData[data]', token)\n\n const result = await post<Record<string, unknown>>(\n ENDPOINTS.payment.submitPayment(encodeURIComponent(orderHash)),\n form,\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n const data = result ?? {}\n if (data.error === true) {\n throw new Error(\n String(\n data.message ||\n data.failure_reason ||\n 'Your payment was not accepted. Please try again or use a different card.'\n )\n )\n }\n return data\n}\n","/**\n * The checkout sequence — framework-free and payment-SDK-free (card/wallet\n * confirmation goes through the injected PaymentConfirmer port). Encodes the\n * traps the server contract hides:\n * - add-to-cart replaces the whole cart → ONE call with every ticket type\n * - GET /cart must run before POST /checkout (primes the session)\n * - decrypted ticket_type_ids only exist in the pricing response\n * - free strictly means order total === 0\n * - retries must never create a second order or charge twice\n */\nimport {\n addSeatsToCart,\n addTicketsToCart,\n changePaymentMethod,\n changePaymentMethodType,\n chargeSavedCardPlan,\n checkBuyerEmail as checkBuyerEmailApi,\n completeFreeRegistration,\n confirmInstallments,\n confirmOrderSuccess,\n confirmRedirect,\n createOrder,\n createPaymentPlan,\n getCart,\n getCheckoutConfigs,\n getEventAddons,\n getEventConditions,\n getEventCustomFields,\n getIdVerificationStatus,\n getInstallmentOffers,\n getOrderReview,\n getPaymentConfigAttributes,\n getPayPalForm,\n getPriceBreakdown,\n prepareForOxxo,\n setEventCurrency,\n submitXenditCardCharge,\n submitXenditEWalletCharge,\n updateCheckout,\n} from '../api'\nimport { getOriginUrl } from '../client'\nimport { clearCartGuestToken, pinCartGuestToken } from '../client/session'\nimport { XENDIT_EWALLET_EXTRA_FIELD } from '../constants'\nimport type {\n AddonSelection,\n CheckoutBilling,\n CheckoutConsent,\n CheckoutHolder,\n CheckoutOptions,\n CheckoutSnapshot,\n CurrencySync,\n CurrencySyncOptions,\n CustomFieldValues,\n EventAddon,\n EventCondition,\n EventCustomFieldGroup,\n IdVerificationCallbacks,\n IdVerificationPoller,\n IdVerificationStatus,\n InstallmentOffer,\n PlaceOrderResult,\n PreOrderGateway,\n RequiredAddOnLike,\n SeatLine,\n TicketSelection,\n} from '../dtos'\nimport {\n buildChangePaymentMethodAttributes,\n buildConfirmInstallmentsFields,\n buildInstallmentOffersFields,\n buildXenditEWalletChargeFields,\n confirmInstallmentsHasNextAction,\n createIdVerificationPoller,\n evaluateFieldGates,\n interpretXenditChargeResponse,\n missingCheckoutDetails,\n missingRequiredAddOns,\n oxxoVoucherFromNextAction,\n paypalTabConfig,\n requiresFeeReprice,\n resolveInstallmentOffers,\n} from '../logic'\nimport {\n buildAutoSubmitFormHtml,\n cleanAccountId,\n CONFIRMED_INTENT_STATUSES,\n unsupportedGatewayError,\n type CheckoutPorts,\n} from './confirmer'\nimport { errorMessage, isCartExpiredError } from './errors'\nimport { buildRazorpayCheckoutHtml, buildXenditCheckoutHtml } from './sheets'\nimport { createCheckoutStore, type CheckoutStore } from './store'\n\n/** How the shopper pays. Apple/Google Pay show the native wallet sheet; card\n * confirms the card field the consumer rendered. */\nexport type PaymentMethod = 'card' | 'applePay' | 'googlePay'\n\n/** A full payment request — the alternative rails carry parameters. The plain\n * `PaymentMethod` strings remain valid ('card' ≡ `{ method: 'card' }`). */\nexport type PaymentRequest =\n | { method: 'card' }\n /** Pay with the ORDER'S OWN gateway (the prebuilt \"just pay\" button):\n * razorpay → the Razorpay sheet, xendit → the Xendit card rail,\n * stripe/unknown → the card path (incl. MSI). */\n | { method: 'auto'; description?: string }\n | { method: 'applePay' }\n | { method: 'googlePay' }\n /** Redirect-based Stripe methods (Klarna/Afterpay/Affirm/iDEAL-class). Needs\n * ports.providerPage + ports.createRedirectPaymentMethod. */\n | { method: 'redirect'; methodType: string }\n /** OXXO cash voucher (Mexico). Needs ports.confirmOxxo; result is\n * `pending: true` + `pendingVoucherUrl`. */\n | { method: 'oxxo' }\n /** Xendit e-wallet (walletKey from the pre-order processors, e.g. 'dana';\n * Jenius Pay wants extra.cashtag, OVO extra.phoneNumber). Needs providerPage. */\n | {\n method: 'xenditEWallet'\n walletKey: string\n extra?: { cashtag?: string; phoneNumber?: string }\n }\n /** PayPal Standard (top-level form; settles via IPN — may return pending). */\n | { method: 'paypal' }\n /** Razorpay web checkout (posts razorpay_payment_id → settle token on /success). */\n | { method: 'razorpay'; description?: string }\n /** Xendit CARD: the sheet tokenizes (3DS) and posts `token`; charge server-side. */\n | { method: 'xenditCard' }\n /** Payment plan (installments, Stripe): the card is SAVED via the review's\n * SetupIntent (nothing charged now), the plan schedules server-side; a\n * reusable saved card is charged directly (opt out with useSavedCard:false). */\n | { method: 'paymentPlan'; useSavedCard?: boolean }\n\nconst normalizeRequest = (method?: PaymentMethod | PaymentRequest): PaymentRequest =>\n typeof method === 'string' ? { method } : (method ?? { method: 'card' })\n\n/** The platform capabilities + wallet/redirect options the rails run on. */\nexport interface EngineContext {\n ports: CheckoutPorts\n options: CheckoutOptions\n}\n\n// ---------------------------------------------------------------------------\n// Pre-flight helpers (pure)\n// ---------------------------------------------------------------------------\n\nconst hasValue = (v: string | string[] | undefined): boolean =>\n Array.isArray(v) ? v.length > 0 : Boolean(v && String(v).trim())\n\nconst missingRequiredAddOnCaptures = (\n groups: EventCustomFieldGroup[],\n addOns: AddonSelection,\n addOnDataCapture: Record<string, CustomFieldValues> | undefined\n): string[] => {\n const missing: string[] = []\n for (const g of groups.filter((g) => g.scope === 'add-on')) {\n if (!(Number(addOns[g.id]) > 0)) continue\n const values = addOnDataCapture?.[g.id]\n for (const f of g.fields.filter((f) => f.required && f.type !== 'image')) {\n if (!hasValue(values?.[f.name])) {\n missing.push(`${f.label || f.name}${g.label ? ` (${g.label})` : ''}`)\n }\n }\n }\n return missing\n}\n\nconst unacceptedRequiredConditions = (\n conditions: EventCondition[] | undefined,\n accepted: Record<string, boolean> | undefined\n): EventCondition[] =>\n (conditions ?? []).filter((c) => c.isRequired && accepted?.[c.id] !== true)\n\nconst assertNotBusy = (store: CheckoutStore) => {\n const { status } = store.getState()\n if (status === 'priming' || status === 'repricing' || status === 'placing') {\n throw new Error('Checkout is busy — please wait.')\n }\n}\n\n/**\n * Routes a failed call to the right terminal state: an expired-cart rejection\n * becomes 'expired' (offer a restart), anything else 'error'. Exception: once\n * the card is charged, the order MUST be finalized — even an expiry rejection\n * on the finalize call stays a recoverable 'error' (a retry replays only the\n * finalize on the same hash), never the destructive restart.\n */\nconst failCheckout = (store: CheckoutStore, e: unknown): void => {\n const expired = isCartExpiredError(e) && !store.progress.paymentConfirmed\n if (expired) clearCartGuestToken()\n store.setState({ status: expired ? 'expired' : 'error', error: errorMessage(e) })\n}\n\n// ---------------------------------------------------------------------------\n// Prime + reprice\n// ---------------------------------------------------------------------------\n\n/** Builds the server cart for a ticket selection and prices it. Idempotent per\n * selection (the server replaces the cart; the store resets for the new run). */\nexport const primeWith = (\n store: CheckoutStore,\n ctx: EngineContext,\n eventId: string,\n selections: TicketSelection[]\n): Promise<void> => {\n if (!selections.length) throw new Error('Select at least one ticket.')\n return primeCore(store, ctx, eventId, selections, () =>\n addTicketsToCart(eventId, selections)\n )\n}\n\n/** One reserved seat → one store selection, so the holder math (one holder per\n * ticket) stays correct. A guest-capable table contributes `guests` holders —\n * the server counts tickets from the `ticket_types` quantities, which for a\n * guest line equal the guest count. (If a real table-map event turns out to\n * need one holder per TABLE, drop the `?? l.guests` and use `1`.) */\nconst seatLinesToSelections = (lines: SeatLine[]): TicketSelection[] =>\n lines.map((l) => ({\n id: l.ticketTypeId,\n name: 'Seat',\n optionName: l.optionName,\n price: l.price,\n currency: '',\n quantity: l.guests ?? 1,\n }))\n\n/** Builds the server cart for RESERVED SEATS and prices it — the seat-map\n * analogue of `primeWith`. Reservations were already placed on seat click\n * (`ttf.seatmap.reserve`); this turns them into cart lines + prices the order,\n * reusing the exact same session-prime / gateway-guard / pricing pipeline. */\nexport const primeSeatsWith = (\n store: CheckoutStore,\n ctx: EngineContext,\n eventId: string,\n lines: SeatLine[]\n): Promise<void> => {\n if (!lines.length) throw new Error('Select at least one seat.')\n return primeCore(store, ctx, eventId, seatLinesToSelections(lines), () =>\n addSeatsToCart(eventId, lines)\n )\n}\n\n/**\n * Attach the engine to a cart that another supported flow already created\n * (currently resale and compatibility links). Unlike `prime`, this does not\n * add or replace ticket lines.\n */\nexport const resumeCartWith = async (\n store: CheckoutStore,\n ctx: EngineContext,\n eventId: string,\n options: { isFromResale?: boolean } = {}\n): Promise<void> => {\n assertNotBusy(store)\n store.reset()\n store.setState({ status: 'priming', eventId, selections: [] })\n\n try {\n const { expiresInSeconds, preOrderGateway } = await getCart()\n pinCartGuestToken()\n const payableGateways = ['stripe_payment_intents', 'xendit']\n if (preOrderGateway && !payableGateways.includes(preOrderGateway)) {\n throw new Error(\n \"This event's payment provider isn't supported in this checkout yet.\"\n )\n }\n\n const [pricing, customFields, configGates, priceBreakdown, addons, conditions] =\n await Promise.all([\n updateCheckout(eventId, {}, options),\n getEventCustomFields(eventId).catch((): EventCustomFieldGroup[] => []),\n getCheckoutConfigs().catch(() => ({\n holderNamesRequired: false,\n fieldGates: evaluateFieldGates(null),\n })),\n getPriceBreakdown().catch(() => null),\n getEventAddons(eventId).catch((): EventAddon[] => []),\n getEventConditions(eventId).catch((): EventCondition[] => []),\n ])\n\n store.setState({\n status: 'ready',\n gateway: (preOrderGateway ?? undefined) as PreOrderGateway | undefined,\n ticketTypeIds: pricing.ticketTypeIds,\n breakdown: pricing.breakdown,\n stripe: pricing.stripe,\n paymentPlan: pricing.paymentPlan,\n customFields,\n requiredAddOns: addons\n .filter((addon) => addon.required)\n .map((addon) => ({\n id: addon.id,\n name: addon.name,\n required: true,\n stock: addon.stock,\n })),\n conditions,\n redirectPaymentMethods: pricing.redirectPaymentMethods,\n walletAvailability: pricing.walletAvailability,\n stripeElementsConfig: pricing.stripeElementsConfig,\n holderNamesRequired: configGates.holderNamesRequired,\n fieldGates: configGates.fieldGates,\n priceBreakdown,\n expiresAt: Date.now() + expiresInSeconds * 1000,\n })\n\n if (pricing.stripe) {\n await ctx.ports.confirmer\n .init({\n publishableKey: pricing.stripe.publishableKey,\n accountId: cleanAccountId(pricing.stripe.accountId),\n })\n .catch(() => undefined)\n }\n } catch (error) {\n failCheckout(store, error)\n throw error\n }\n}\n\n/** The shared prime pipeline: reset → populate the cart → session-prime +\n * gateway guard → price/custom-fields/conditions/add-ons fan-out → ready.\n * `populateCart` is the only thing that differs between tickets and seats. */\nconst primeCore = async (\n store: CheckoutStore,\n ctx: EngineContext,\n eventId: string,\n selections: TicketSelection[],\n populateCart: () => Promise<{ holderNamesRequired: boolean }>\n): Promise<void> => {\n assertNotBusy(store)\n\n // Never start a new cart on top of a CHARGED-but-unfinalized order: priming\n // resets the store, which would drop the confirmed payment and let the shopper\n // pay a second time. That order must be finalized (retry placeOrder), not replaced.\n if (store.progress.paymentConfirmed) {\n throw new Error(\n 'You already have a paid order being finalized. Please complete it before starting a new purchase.'\n )\n }\n\n store.reset()\n store.setState({ status: 'priming', eventId, selections })\n\n try {\n const { holderNamesRequired } = await populateCart()\n pinCartGuestToken()\n // Mandatory session priming — also identifies the payment gateway.\n const { expiresInSeconds, preOrderGateway } = await getCart()\n\n // Fail fast — BEFORE any order exists — on events this package can't pay.\n // Fails open when the backend doesn't identify a gateway. Xendit events are\n // payable through the e-wallet rail, so they prime.\n const PAYABLE_PRE_ORDER_GATEWAYS = ['stripe_payment_intents', 'xendit']\n if (preOrderGateway && !PAYABLE_PRE_ORDER_GATEWAYS.includes(preOrderGateway)) {\n throw new Error(\n \"This event's payment provider isn't supported in the app yet. Please complete your purchase on the event page.\"\n )\n }\n\n const [pricing, customFields, configGates, priceBreakdown, addons, conditions] =\n await Promise.all([\n updateCheckout(eventId, {}),\n getEventCustomFields(eventId).catch((): EventCustomFieldGroup[] => []),\n getCheckoutConfigs().catch(() => ({\n holderNamesRequired: false,\n fieldGates: evaluateFieldGates(null),\n })),\n getPriceBreakdown().catch(() => null),\n getEventAddons(eventId).catch((): EventAddon[] => []),\n getEventConditions(eventId).catch((): EventCondition[] => []),\n ])\n\n const requiredAddOns: RequiredAddOnLike[] = addons\n .filter((a) => a.required)\n .map((a) => ({ id: a.id, name: a.name, required: true, stock: a.stock }))\n\n store.setState({\n status: 'ready',\n // Validated payable above; the raw string narrows to the gateway union.\n gateway: (preOrderGateway ?? undefined) as PreOrderGateway | undefined,\n ticketTypeIds: pricing.ticketTypeIds,\n breakdown: pricing.breakdown,\n stripe: pricing.stripe,\n paymentPlan: pricing.paymentPlan,\n customFields,\n requiredAddOns,\n conditions,\n redirectPaymentMethods: pricing.redirectPaymentMethods,\n walletAvailability: pricing.walletAvailability,\n stripeElementsConfig: pricing.stripeElementsConfig,\n holderNamesRequired: holderNamesRequired || configGates.holderNamesRequired,\n fieldGates: configGates.fieldGates,\n priceBreakdown,\n expiresAt: Date.now() + expiresInSeconds * 1000,\n })\n\n // Initialize the payment SDK as soon as the keys exist so the consumer's\n // card field is ready without any wiring on their side.\n if (pricing.stripe) {\n await ctx.ports.confirmer\n .init({\n publishableKey: pricing.stripe.publishableKey,\n accountId: cleanAccountId(pricing.stripe.accountId),\n })\n .catch(() => undefined) // re-initialized at pay time with review keys\n }\n } catch (e) {\n failCheckout(store, e)\n throw e\n }\n}\n\n/** Stores the add-on selection and re-prices the cart with it. */\nexport const repriceWith = async (\n store: CheckoutStore,\n addOns: AddonSelection\n): Promise<void> => {\n const { eventId } = store.getState()\n if (!eventId) throw new Error('reprice: no active checkout.')\n assertNotBusy(store)\n\n // Changing add-ons invalidates any order created by a failed attempt.\n store.invalidateOrderProgress()\n\n store.setState({ status: 'repricing', addOns })\n try {\n const pricing = await updateCheckout(eventId, addOns)\n const priceBreakdown = await getPriceBreakdown(addOns).catch(() => null)\n store.setState({\n status: 'ready',\n ticketTypeIds: pricing.ticketTypeIds,\n breakdown: pricing.breakdown,\n priceBreakdown,\n paymentPlan: pricing.paymentPlan,\n redirectPaymentMethods: pricing.redirectPaymentMethods,\n walletAvailability: pricing.walletAvailability,\n stripeElementsConfig: pricing.stripeElementsConfig,\n ...(pricing.stripe ? { stripe: pricing.stripe } : {}),\n })\n } catch (e) {\n failCheckout(store, e)\n throw e\n }\n}\n\n// ---------------------------------------------------------------------------\n// Place order (create → review → rail dispatch → finalize)\n// ---------------------------------------------------------------------------\n\nexport const placeOrderWith = async (\n store: CheckoutStore,\n ctx: EngineContext,\n method: PaymentMethod | PaymentRequest = 'card'\n): Promise<PlaceOrderResult> => {\n const { ports, options } = ctx\n const { confirmer } = ports\n let request = normalizeRequest(method)\n const snap = store.getState()\n const { billing, holders, addOns, consent, selections, stripe } = snap\n\n assertNotBusy(store)\n\n const failPreflight = (message: string): Error => {\n store.setState({ status: 'error', error: message })\n return new Error(message)\n }\n\n const missingDetails = missingCheckoutDetails(snap)\n if (missingDetails.length > 0) {\n throw failPreflight(\n `Please complete the required checkout detail${missingDetails.length > 1 ? 's' : ''}: ${missingDetails\n .slice(0, 4)\n .join(', ')}${missingDetails.length > 4 ? '…' : ''}.`\n )\n }\n if (!billing) {\n // `missingCheckoutDetails` already reports this; retain the explicit guard\n // so TypeScript and non-standard callers both see billing as required.\n throw failPreflight('Billing details are incomplete.')\n }\n // Don't attempt an order the server will reject on an elapsed reservation.\n // Exception: once payment is confirmed we MUST finalize regardless of the timer.\n if (\n !store.progress.paymentConfirmed &&\n (snap.status === 'expired' ||\n (snap.expiresAt != null && Date.now() >= snap.expiresAt))\n ) {\n store.expireCart()\n throw new Error('Your cart has expired. Please choose your tickets again.')\n }\n\n // One holder entry per ticket; pad/trim to match.\n const totalTickets = selections.reduce((sum, t) => sum + t.quantity, 0) || 1\n const paddedHolders: CheckoutHolder[] = Array.from(\n { length: totalTickets },\n (_, i) => holders[i] ?? { firstName: '', lastName: '', email: '', phone: undefined }\n )\n\n const unaccepted = unacceptedRequiredConditions(\n snap.conditions,\n snap.acceptedConditions\n )\n if (unaccepted.length > 0) {\n const names = unaccepted.map((c) => c.name).filter(Boolean)\n throw failPreflight(\n `Please accept the required condition${unaccepted.length > 1 ? 's' : ''}${\n names.length ? `: ${names.join(', ')}` : ''\n }.`\n )\n }\n\n const missingCaptures = missingRequiredAddOnCaptures(\n snap.customFields,\n addOns,\n snap.addOnDataCapture\n )\n if (missingCaptures.length > 0) {\n throw failPreflight(\n `Please fill in the required field${missingCaptures.length > 1 ? 's' : ''}: ${missingCaptures\n .slice(0, 4)\n .join(', ')}${missingCaptures.length > 4 ? '…' : ''}.`\n )\n }\n\n const missingAddOns = missingRequiredAddOns(snap.requiredAddOns, addOns)\n if (missingAddOns.length > 0) {\n const names = missingAddOns.map((a) => a.name || '').filter(Boolean)\n throw failPreflight(\n `Please add the required add-on${missingAddOns.length > 1 ? 's' : ''}: ${names.join(', ')}`\n )\n }\n\n store.setState({ status: 'placing', error: undefined })\n try {\n // 1. Create the order (skip if a previous attempt already did).\n let orderHash = store.progress.orderHash\n if (!orderHash) {\n const order = await createOrder({\n billing,\n holders: paddedHolders,\n addOns,\n consent,\n addOnDataCapture: snap.addOnDataCapture,\n })\n orderHash = order.hash\n store.progress.orderHash = orderHash\n\n // Duplicate-charge guard: the server answered with the ALREADY-COMPLETED\n // paid order for this checkout — go straight to confirmation.\n if (order.alreadyPaid) {\n const result: PlaceOrderResult = {\n orderHash,\n free: false,\n needIdVerification: false,\n alreadyPaid: true,\n }\n store.progress = {}\n clearCartGuestToken()\n store.setState({ status: 'succeeded', order: result })\n return result\n }\n }\n\n // 2. Review — order lock + authoritative total + Stripe secrets.\n const review = await getOrderReview(orderHash)\n if (review.expiresInSeconds != null) {\n store.setState({ expiresAt: Date.now() + review.expiresInSeconds * 1000 })\n }\n\n // 'auto' pays with the order's own gateway.\n if (request.method === 'auto') {\n request =\n review.gateway === 'razorpay'\n ? { method: 'razorpay', description: request.description }\n : review.gateway === 'xendit'\n ? { method: 'xenditCard' }\n : { method: 'card' }\n }\n\n // 3a. Free strictly means total === 0.\n if (review.total !== '' && Number(review.total) === 0) {\n await completeFreeRegistration(orderHash)\n const result: PlaceOrderResult = {\n orderHash,\n free: true,\n needIdVerification: false,\n currency: review.currency,\n }\n store.progress = {}\n clearCartGuestToken()\n store.setState({ status: 'succeeded', order: result })\n return result\n }\n\n // Duplicate-charge guard: the server withholds the secret for intents that\n // already succeeded / are settling — skip charging, only replay finalize.\n if (review.paymentAlreadyProcessed) {\n store.progress.paymentConfirmed = true\n }\n\n const finish = (partial: PlaceOrderResult): PlaceOrderResult => {\n const result: PlaceOrderResult = { currency: review.currency, ...partial }\n store.progress = {}\n clearCartGuestToken()\n store.setState({ status: 'succeeded', order: result })\n return result\n }\n\n let confirmedPaymentIntentId: string | undefined\n\n if (!store.progress.paymentConfirmed) {\n // ---- OXXO cash voucher (own finalize: pending result) --------------\n if (request.method === 'oxxo') {\n if (!ports.confirmOxxo) throw unsupportedGatewayError()\n if (review.gateway !== 'stripe' || !review.clientSecret) {\n throw new Error('This payment method is not available for this order')\n }\n const publishableKey = review.publishableKey ?? stripe?.publishableKey\n if (!publishableKey) throw new Error('Missing Stripe publishable key.')\n await confirmer.init({\n publishableKey,\n accountId: cleanAccountId(review.connectedAccount ?? stripe?.accountId),\n merchantIdentifier: options.merchantIdentifier,\n urlScheme: options.urlScheme,\n })\n await prepareForOxxo(orderHash)\n const { error: oxxoError, nextAction } = await ports.confirmOxxo(\n review.clientSecret,\n billing\n )\n const voucher = oxxoVoucherFromNextAction(\n (nextAction as Record<string, unknown>) || null\n )\n if (oxxoError && !voucher) throw new Error(oxxoError || 'Payment failed')\n if (!voucher) {\n throw new Error(\n 'We couldn’t issue the OXXO voucher. Please try again or pay with a card.'\n )\n }\n store.progress.paymentConfirmed = true\n try {\n await Promise.resolve(ports.openUrl?.(voucher.voucherUrl))\n } catch {\n // The voucher is also emailed and carried on the result.\n }\n const { needIdVerification } = await confirmOrderSuccess(orderHash)\n return finish({\n orderHash,\n free: false,\n needIdVerification,\n pending: true,\n pendingVoucherUrl: voucher.voucherUrl,\n })\n }\n\n // ---- PayPal Standard (own finalize: IPN settles asynchronously) ----\n if (request.method === 'paypal') {\n if (!ports.providerPage) throw unsupportedGatewayError()\n const paypalConfig = paypalTabConfig(await getPaymentConfigAttributes())\n if (!paypalConfig) throw new Error('PayPal is not available for this order')\n if (!review.orderId) throw new Error('PayPal is not available for this order')\n await changePaymentMethod(\n buildChangePaymentMethodAttributes({\n paymentMethodId: paypalConfig.payment_method_id,\n paymentMethodHash: paypalConfig.payment_method_hash,\n orderId: review.orderId,\n orderHash,\n })\n )\n const paypalForm = await getPayPalForm(orderHash)\n if (!paypalForm) {\n throw new Error(\n 'We couldn’t start the PayPal payment. Please try again or pay by card.'\n )\n }\n const origin = getOriginUrl()\n const sheet = await ports.providerPage({\n html: buildAutoSubmitFormHtml(paypalForm),\n baseUrl: origin,\n returnUrlPrefix: `${origin}/store/order-complete`,\n })\n if (sheet.event === 'failed') {\n throw new Error(sheet.description || 'Payment failed')\n }\n store.progress.paymentConfirmed = true\n try {\n const { needIdVerification } = await confirmOrderSuccess(orderHash)\n return finish({ orderHash, free: false, needIdVerification })\n } catch {\n return finish({\n orderHash,\n free: false,\n needIdVerification: false,\n pending: true,\n })\n }\n }\n\n // ---- Razorpay web checkout (own finalize: settle token) ------------\n if (request.method === 'razorpay') {\n if (!ports.providerPage) throw unsupportedGatewayError()\n if (review.gateway !== 'razorpay' || !review.razorpayKeyId) {\n throw new Error('This payment method is not available for this order')\n }\n const sheet = await ports.providerPage({\n html: buildRazorpayCheckoutHtml({\n keyId: review.razorpayKeyId,\n amountMinor: Math.round(Number(review.payNow ?? review.total) * 100),\n description: request.description ?? '',\n buyerName: `${billing.firstName} ${billing.lastName}`.trim(),\n buyerEmail: billing.email,\n orderHash,\n }),\n returnUrlPrefix: `${getOriginUrl()}/store/order-complete`,\n })\n if (sheet.event === 'dismiss') throw new Error('Payment was cancelled')\n if (sheet.event === 'failed') {\n throw new Error(\n sheet.description ||\n 'Your payment was not accepted. Please try again or use a different card.'\n )\n }\n store.progress.paymentConfirmed = true\n const paymentId =\n typeof sheet.data?.razorpay_payment_id === 'string'\n ? sheet.data.razorpay_payment_id\n : undefined\n const { needIdVerification } = await confirmOrderSuccess(\n orderHash,\n paymentId ? { token: paymentId } : undefined\n )\n return finish({ orderHash, free: false, needIdVerification })\n }\n\n // ---- Payment plan (installments; own finalize — the plan IS the record)\n if (request.method === 'paymentPlan') {\n if (review.gateway !== 'stripe') {\n throw new Error('This payment method is not available for this order')\n }\n // The SetupIntent secret's presence IS the \"plan available\" signal.\n if (!review.paymentPlanSetupSecret) {\n throw new Error(\n \"The payment plan isn't available for this order right now. Turn off installments to pay in full.\"\n )\n }\n const publishableKey = review.publishableKey ?? stripe?.publishableKey\n if (!publishableKey) throw new Error('Missing Stripe publishable key.')\n await confirmer.init({\n publishableKey,\n accountId: cleanAccountId(review.connectedAccount ?? stripe?.accountId),\n merchantIdentifier: options.merchantIdentifier,\n urlScheme: options.urlScheme,\n })\n\n // Saved-card shortcut: charge the plan to the card the review carries.\n const savedCard =\n request.useSavedCard === false ? null : review.paymentPlanSavedCard\n if (savedCard) {\n const charge = await chargeSavedCardPlan(orderHash, savedCard.paymentMethodId)\n if (charge.requiresAction && charge.clientSecret) {\n if (!ports.confirmSavedCardPayment) throw unsupportedGatewayError()\n await ports.confirmSavedCardPayment(\n charge.clientSecret,\n savedCard.paymentMethodId\n )\n }\n return finish({ orderHash, free: false, needIdVerification: false })\n }\n\n // New card: SAVE it via the SetupIntent (nothing charged), then create\n // the plan against the resulting PaymentMethod.\n if (!ports.confirmPaymentPlanSetup) throw unsupportedGatewayError()\n const paymentMethodId = await ports.confirmPaymentPlanSetup(\n review.paymentPlanSetupSecret,\n billing\n )\n const { needIdVerification } = await createPaymentPlan(orderHash, paymentMethodId)\n return finish({ orderHash, free: false, needIdVerification })\n }\n\n // ---- Xendit CARD (tokenize inline or via sheet; server-side charge) -\n if (request.method === 'xenditCard') {\n if (\n review.gateway !== 'xendit' ||\n !review.xenditPublishableKey ||\n !review.orderId\n ) {\n throw new Error('This payment method is not available for this order')\n }\n let token: Record<string, unknown> | undefined\n if (ports.tokenizeXenditCard) {\n token = await ports.tokenizeXenditCard({\n publishableKey: review.xenditPublishableKey,\n amount: review.payNow ?? review.total,\n billing,\n onBehalfOf: review.xenditOnBehalfOf ?? null,\n })\n } else if (ports.providerPage) {\n const sheet = await ports.providerPage({\n html: buildXenditCheckoutHtml({\n publishableKey: review.xenditPublishableKey,\n amount: review.payNow ?? review.total,\n buyerFirstName: billing.firstName,\n buyerLastName: billing.lastName,\n buyerEmail: billing.email,\n buyerPhone: billing.phone || '',\n onBehalfOf: review.xenditOnBehalfOf ?? null,\n }),\n baseUrl: 'https://js.xendit.co',\n returnUrlPrefix: `${getOriginUrl()}/store/order-complete`,\n })\n if (sheet.event === 'dismiss') throw new Error('Payment was cancelled')\n const t = sheet.data?.token\n if (sheet.event === 'failed' || !t || typeof t !== 'object') {\n throw new Error(\n sheet.description ||\n 'Your payment was not accepted. Please try again or use a different card.'\n )\n }\n token = t as Record<string, unknown>\n } else {\n throw unsupportedGatewayError()\n }\n await submitXenditCardCharge(review.orderId, orderHash, token)\n store.progress.paymentConfirmed = true\n }\n\n // ---- Xendit e-wallet (provider page + /success reconcile) ----------\n else if (request.method === 'xenditEWallet') {\n if (!ports.providerPage) throw unsupportedGatewayError()\n const requiredExtra = XENDIT_EWALLET_EXTRA_FIELD[request.walletKey]\n if (requiredExtra === 'cashtag' && !request.extra?.cashtag) {\n throw new Error('Please enter your cashtag to pay with this wallet.')\n }\n if (requiredExtra === 'phoneNumber' && !request.extra?.phoneNumber) {\n throw new Error('Please enter your mobile number to pay with this wallet.')\n }\n if (review.gateway !== 'xendit' || !review.orderId) {\n throw new Error('This payment method is not available for this order')\n }\n const outcome = interpretXenditChargeResponse(\n await submitXenditEWalletCharge(\n buildXenditEWalletChargeFields({\n orderId: review.orderId,\n orderHash,\n paymentType: request.walletKey,\n cashtag: request.extra?.cashtag,\n phoneNumber: request.extra?.phoneNumber,\n })\n )\n )\n if (outcome.kind !== 'redirect') throw new Error(outcome.reason)\n const sheet = await ports.providerPage({\n uri: outcome.url,\n returnUrlPrefix: `${getOriginUrl()}/store/order-complete`,\n })\n if (sheet.event === 'failed') {\n throw new Error(sheet.description || 'Payment failed')\n }\n store.progress.paymentConfirmed = true\n }\n\n // ---- Redirect-based Stripe methods (Klarna/Afterpay/iDEAL-class) ---\n else if (request.method === 'redirect') {\n if (!ports.providerPage || !ports.createRedirectPaymentMethod) {\n throw unsupportedGatewayError()\n }\n if (review.gateway !== 'stripe') {\n throw new Error('This payment method is not available for this order')\n }\n // Klarna/Afterpay-class types carry their own fees: re-price BEFORE\n // confirming (the server confirms the re-priced intent).\n if (\n requiresFeeReprice(request.methodType) &&\n review.stripeIntentId &&\n review.orderId\n ) {\n await changePaymentMethodType(orderHash, {\n paymentMethodType: request.methodType,\n orderId: review.orderId,\n orderHash,\n stripeIntentId: review.stripeIntentId,\n })\n }\n const paymentMethodId = await ports.createRedirectPaymentMethod(\n request.methodType,\n billing\n )\n if (!paymentMethodId) throw unsupportedGatewayError()\n const returnUrl = options.redirectReturnUrl || `${getOriginUrl()}/`\n const outcome = await confirmRedirect(orderHash, {\n payment_method_id: paymentMethodId,\n return_url: returnUrl,\n })\n if (outcome.kind === 'redirect') {\n const sheet = await ports.providerPage({\n uri: outcome.url,\n returnUrlPrefix: returnUrl,\n })\n if (sheet.event === 'dismiss') throw new Error('Payment was cancelled')\n if (sheet.event === 'failed') {\n throw new Error(\n sheet.description ||\n 'Your payment was not completed. Please try again or use a different payment method.'\n )\n }\n const redirectStatus = /[?&]redirect_status=([^&#]+)/.exec(\n sheet.returnUrl || ''\n )?.[1]\n if (redirectStatus === 'failed') {\n throw new Error(\n 'Your payment was not completed. Please try again or use a different payment method.'\n )\n }\n } else if (outcome.kind !== 'settled') {\n throw new Error(\n \"This payment method isn't available right now. Please pay with a card instead.\"\n )\n }\n store.progress.paymentConfirmed = true\n }\n\n // ---- Card / Apple Pay / Google Pay (the Stripe confirmer path, MSI) -\n else {\n if (!review.clientSecret) {\n throw new Error(\n \"This event's payment method isn't supported in the app yet. Please complete your purchase on the event page.\"\n )\n }\n const publishableKey = review.publishableKey ?? stripe?.publishableKey\n if (!publishableKey) throw new Error('Missing Stripe publishable key.')\n await confirmer.init({\n publishableKey,\n accountId: cleanAccountId(review.connectedAccount ?? stripe?.accountId),\n merchantIdentifier: options.merchantIdentifier,\n urlScheme: options.urlScheme,\n })\n\n // If a previous attempt already authorized this intent, reuse it rather\n // than confirming — and re-charging — again.\n const existingStatus = await confirmer.getIntentStatus(review.clientSecret)\n const alreadyConfirmed = Boolean(\n existingStatus && CONFIRMED_INTENT_STATUSES.includes(existingStatus)\n )\n\n if (!alreadyConfirmed) {\n // MSI (Mexican months without interest): offer plans between PM\n // creation and the confirm. A chosen plan confirms SERVER-SIDE — only\n // handleNextAction may run afterwards, never a second confirm.\n let confirmedViaInstallments = false\n if (\n request.method === 'card' &&\n review.currency === 'MXN' &&\n ports.onInstallmentOffers &&\n ports.createCardPaymentMethod &&\n ports.handleNextAction &&\n review.stripeIntentId\n ) {\n let offers: InstallmentOffer[] = []\n try {\n const paymentMethodId = await ports.createCardPaymentMethod(billing)\n offers = resolveInstallmentOffers(\n await getInstallmentOffers(\n orderHash,\n buildInstallmentOffersFields({\n paymentIntentId: review.stripeIntentId,\n paymentMethodId,\n })\n )\n ).installments\n } catch {\n // Offers unavailable — fall through to the normal confirm.\n }\n if (offers.length > 0) {\n const chosen = await ports.onInstallmentOffers(offers)\n if (chosen) {\n const confirmResponse = await confirmInstallments(\n orderHash,\n buildConfirmInstallmentsFields({\n paymentIntentId: review.stripeIntentId,\n offer: chosen,\n })\n )\n if (confirmInstallmentsHasNextAction(confirmResponse)) {\n await ports.handleNextAction(review.clientSecret)\n }\n confirmedViaInstallments = true\n }\n }\n }\n\n if (!confirmedViaInstallments) {\n const currencyCode = snap.breakdown?.currencyCode ?? review.currency ?? ''\n let status: string | undefined\n if (request.method === 'applePay') {\n status = await confirmer.confirmApplePay(\n review.clientSecret,\n review.total,\n currencyCode,\n {\n merchantCountryCode: options.merchantCountryCode,\n merchantName: options.merchantName,\n }\n )\n } else if (request.method === 'googlePay') {\n if (!confirmer.confirmGooglePay) throw unsupportedGatewayError()\n status = await confirmer.confirmGooglePay(\n review.clientSecret,\n review.total,\n currencyCode,\n {\n merchantCountryCode: options.merchantCountryCode,\n merchantName: options.merchantName,\n testEnv: options.googlePayTestEnv,\n }\n )\n } else {\n status = await confirmer.confirmCard(review.clientSecret, billing)\n }\n if (!status || !CONFIRMED_INTENT_STATUSES.includes(status)) {\n throw new Error(`Payment not completed (status: ${status ?? 'unknown'}).`)\n }\n }\n }\n store.progress.paymentConfirmed = true\n confirmedPaymentIntentId = review.stripeIntentId\n }\n }\n\n // 4. Record the payment server-side.\n const { needIdVerification } = await confirmOrderSuccess(orderHash)\n\n return finish({\n orderHash,\n free: false,\n needIdVerification,\n ...(confirmedPaymentIntentId ? { paymentIntentId: confirmedPaymentIntentId } : {}),\n })\n } catch (e) {\n failCheckout(store, e)\n throw e\n }\n}\n\n// ---------------------------------------------------------------------------\n// Pay an order created outside the engine (retry-safe session)\n// ---------------------------------------------------------------------------\n\nexport interface OrderPaymentSession {\n /** The order to pay (from your own on-checkout call). */\n orderHash: string\n /** Buyer details for the payment legs (billing_details, wallet sheets…). */\n billing: CheckoutBilling\n /** Engine progress store — created on first payOrder call. Carry the session\n * object so a retry after a CONFIRMED charge only replays finalization. */\n store?: CheckoutStore\n}\n\n/** Pays an ALREADY-CREATED order through the engine's rails — same duplicate-\n * charge guards, same rails, same UNSUPPORTED_GATEWAY. Order creation and its\n * pre-flights are the caller's; the engine seeds a session store with the hash. */\nexport const payOrderWith = async (\n ctx: EngineContext,\n session: OrderPaymentSession,\n method: PaymentMethod | PaymentRequest = 'card'\n): Promise<PlaceOrderResult> => {\n if (!session.store) {\n session.store = createCheckoutStore()\n session.store.setState({ status: 'ready' })\n }\n session.store.setState({ billing: session.billing })\n if (!session.store.progress.orderHash) {\n session.store.progress.orderHash = session.orderHash\n }\n return placeOrderWith(session.store, ctx, method)\n}\n\n// ---------------------------------------------------------------------------\n// Currency\n// ---------------------------------------------------------------------------\n\n/** Syncs the session currency. A bare call geo-seeds; a `code` switches it —\n * after which the catalog reprices, so the engine resets the checkout (billing/\n * holders preserved) and the consumer re-runs prime with re-fetched tickets. */\nexport const syncCurrencyWith = async (\n store: CheckoutStore,\n eventId: string,\n code?: string,\n options?: CurrencySyncOptions\n): Promise<CurrencySync> => {\n const state = await setEventCurrency(eventId, code, options)\n const requiresCatalogRefresh = Boolean(code && !options?.seed)\n\n if (requiresCatalogRefresh) {\n if (store.progress.paymentConfirmed) {\n throw new Error(\n 'You already have a paid order being finalized. Please complete it before switching currency.'\n )\n }\n const { billing, holders } = store.getState()\n store.reset()\n store.setState({ billing, holders, currency: state })\n } else {\n store.setState({ currency: state })\n }\n\n return { state, requiresCatalogRefresh }\n}\n\n// ---------------------------------------------------------------------------\n// ID verification\n// ---------------------------------------------------------------------------\n\nexport interface RunIdVerificationOptions {\n /** Opens the provider verification URL. Omit to leave opening to the consumer. */\n openUrl?: (url: string) => void | Promise<void>\n /** Called once the check is confirmed required. Return true to TAKE OVER (the\n * engine stops — no open, no poll). */\n onRequired?: (info: {\n orderHash: string\n verificationUrl: string | null\n }) => boolean | void\n onPhase?: IdVerificationCallbacks['onPhase']\n schedule?: IdVerificationCallbacks['schedule']\n /** Fires `recheck` when the provider hand-off might have completed (e.g. the\n * app returns to the foreground). Return an unsubscribe. */\n registerForegroundListener?: (recheck: () => void) => () => void\n}\n\n/** Standalone poller for a NEED_ID_VERIFICATION order (mint + open the URL\n * first via `getIdVerificationStatus(hash, true)`, then start this). */\nexport const createIdVerificationPollerFor = (\n orderHash: string,\n onPhase: IdVerificationCallbacks['onPhase'],\n schedule?: IdVerificationCallbacks['schedule']\n): IdVerificationPoller =>\n createIdVerificationPoller({\n fetchStatus: () => getIdVerificationStatus(orderHash),\n onPhase,\n schedule,\n })\n\n/**\n * Runs ID verification end-to-end for a NEED_ID_VERIFICATION order: mint the\n * provider URL, open it, poll to completion. Already-verified → resolves now;\n * `onRequired` returns true → resolves undefined (consumer took over); verified\n * → resolves the status; timeout/error → REJECTS with a reassuring message (the\n * payment already settled — treat a rejection as a verification stall, never a\n * payment failure).\n */\nexport const runIdVerificationWith = (\n orderHash: string,\n options: RunIdVerificationOptions = {}\n): Promise<IdVerificationStatus | undefined> =>\n getIdVerificationStatus(orderHash, true).then((status) => {\n if (status.verified || status.required === false) return status\n\n if (\n options.onRequired?.({\n orderHash,\n verificationUrl: status.verification_url || null,\n }) === true\n ) {\n return undefined\n }\n if (status.verification_url && options.openUrl) {\n Promise.resolve(options.openUrl(status.verification_url)).catch(() => {\n // The consumer can still surface the URL via onRequired.\n })\n }\n\n return new Promise<IdVerificationStatus | undefined>((resolve, reject) => {\n let settled = false\n let unsubscribe: (() => void) | undefined\n const finish = (run: () => void) => {\n if (settled) return\n settled = true\n poller.stop()\n unsubscribe?.()\n run()\n }\n const poller = createIdVerificationPoller({\n fetchStatus: () => getIdVerificationStatus(orderHash),\n onPhase: (phase, fresh) => {\n options.onPhase?.(phase, fresh)\n if (phase === 'verified') {\n finish(() => resolve(fresh))\n } else if (phase === 'timeout' || phase === 'error') {\n finish(() =>\n reject(\n new Error(\n 'ID verification is taking longer than usual. Your payment is safe — your tickets will be emailed as soon as the check completes.'\n )\n )\n )\n }\n },\n schedule: options.schedule,\n })\n unsubscribe = options.registerForegroundListener?.(() => {\n getIdVerificationStatus(orderHash)\n .then((fresh) => {\n if (fresh.verified || fresh.required === false) finish(() => resolve(fresh))\n })\n .catch(() => {\n // Poller keeps running.\n })\n })\n poller.start()\n })\n })\n\n// ---------------------------------------------------------------------------\n// The engine facade\n// ---------------------------------------------------------------------------\n\nexport interface EngineConfig {\n /** Platform capabilities — confirmer (required) + optional rails. */\n ports: CheckoutPorts\n /** Wallet/redirect options (merchant identity, redirect URL, url scheme). */\n options?: CheckoutOptions\n /** Reuse an existing store; one is created otherwise. */\n store?: CheckoutStore\n}\n\nexport interface CheckoutEngine {\n /** The underlying store — subscribe/getState for non-React consumers. */\n store: CheckoutStore\n getSnapshot: () => CheckoutSnapshot\n subscribe: (listener: (s: CheckoutSnapshot) => void) => () => void\n /** Build + price the cart for a ticket selection. */\n prime: (eventId: string, selections: TicketSelection[]) => Promise<void>\n /** Build + price the cart for reserved SEATS (seat-map events). */\n primeSeats: (eventId: string, lines: SeatLine[]) => Promise<void>\n /** Resume an existing server-side cart without replacing its ticket lines. */\n resumeCart: (eventId: string, options?: { isFromResale?: boolean }) => Promise<void>\n /** Set the add-on selection and re-price. */\n setAddons: (addOns: AddonSelection) => Promise<void>\n setBilling: (billing: CheckoutBilling) => void\n setHolders: (holders: CheckoutHolder[]) => void\n setConsent: (consent: CheckoutConsent) => void\n setAcceptedConditions: (accepted: Record<string, boolean>) => void\n setAddonDataCapture: (capture: Record<string, CustomFieldValues>) => void\n /** Debounced existing-account check; sets `existingAccountEmail` on the snapshot. */\n checkBuyerEmail: (email: string) => Promise<void>\n /** Create the order and pay (or register free). */\n placeOrder: (method?: PaymentMethod | PaymentRequest) => Promise<PlaceOrderResult>\n /** Switch/seed the session currency. */\n syncCurrency: (\n eventId: string,\n code?: string,\n options?: CurrencySyncOptions\n ) => Promise<CurrencySync>\n /** Run ID verification for a NEED_ID_VERIFICATION order. */\n runIdVerification: (\n orderHash: string,\n options?: RunIdVerificationOptions\n ) => Promise<IdVerificationStatus | undefined>\n reset: () => void\n}\n\n/**\n * Binds the orchestration to a store + a platform's ports. In React, wrap this\n * with `useCheckout()`; in any other JS runtime, use it directly.\n */\nexport const createEngine = (config: EngineConfig): CheckoutEngine => {\n const store = config.store ?? createCheckoutStore()\n const ctx: EngineContext = { ports: config.ports, options: config.options ?? {} }\n\n return {\n store,\n getSnapshot: () => store.getState(),\n subscribe: (listener) => store.subscribe(listener),\n prime: (eventId, selections) => primeWith(store, ctx, eventId, selections),\n primeSeats: (eventId, lines) => primeSeatsWith(store, ctx, eventId, lines),\n resumeCart: (eventId, options) => resumeCartWith(store, ctx, eventId, options),\n setAddons: (addOns) => repriceWith(store, addOns),\n setBilling: (billing) => store.setState({ billing }),\n setHolders: (holders) => store.setState({ holders }),\n setConsent: (consent) => store.setState({ consent }),\n setAcceptedConditions: (acceptedConditions) => store.setState({ acceptedConditions }),\n setAddonDataCapture: (addOnDataCapture) => store.setState({ addOnDataCapture }),\n checkBuyerEmail: async (email) => {\n const { exists } = await checkBuyerEmailApi(email)\n store.setState({ existingAccountEmail: exists ? email : null })\n },\n placeOrder: (method) => placeOrderWith(store, ctx, method),\n syncCurrency: (eventId, code, options) =>\n syncCurrencyWith(store, eventId, code, options),\n runIdVerification: (orderHash, options) => runIdVerificationWith(orderHash, options),\n reset: () => {\n clearCartGuestToken()\n store.reset()\n },\n }\n}\n","/**\n * `ttf` — the facade. A domain-grouped, configured view over the raw `api/`\n * calls, so app code reads like the sentence it is:\n *\n * await ttf.auth.login(email, password)\n * const tickets = await ttf.events.tickets(eventId)\n * await ttf.cart.add(eventId, selections)\n * const review = await ttf.order.review(hash)\n * await ttf.payment.prepareOxxo(hash)\n *\n * It adds no logic of its own — every method IS the api function. One place to\n * discover the whole surface; one name to import.\n */\nimport * as auth from './api/auth'\nimport * as cart from './api/cart'\nimport * as confirmation from './api/confirmation'\nimport * as delegation from './api/delegation'\nimport * as engagement from './api/engagement'\nimport * as events from './api/events'\nimport * as geo from './api/geo'\nimport * as order from './api/order'\nimport * as orders from './api/orders'\nimport * as payment from './api/payment'\nimport * as preRegistration from './api/preRegistration'\nimport * as profile from './api/profile'\nimport * as resale from './api/resale'\nimport * as seatmap from './api/seatmap'\n\nexport const ttf = {\n auth: {\n login: auth.login,\n register: auth.register,\n registerAccount: auth.registerAccount,\n logout: auth.logout,\n restorePassword: auth.restorePassword,\n restorePasswordRn: auth.restorePasswordRn,\n resetPassword: auth.resetPassword,\n checkEmailExists: auth.checkEmailExists,\n // Account identity verification (Netverify/Jumio)\n mintVerificationUrl: auth.mintVerificationUrl,\n getVerificationInfo: auth.getVerificationInfo,\n updateVerificationStatus: auth.updateVerificationStatus,\n },\n profile: {\n get: profile.getProfile,\n },\n geo: {\n countries: geo.getCountries,\n states: geo.getStates,\n },\n\n // --- checkout flow -------------------------------------------------------\n events: {\n tickets: events.getEventTickets,\n ticketsWithMeta: events.getEventTicketsWithMeta,\n info: events.getEventInfo,\n conditions: events.getEventConditions,\n timeSlotTickets: events.getEventTimeSlotTickets,\n customFields: events.getEventCustomFields,\n requiredCustomFieldLabels: events.getRequiredCustomFieldLabels,\n addons: events.getEventAddons,\n filterAddonsForTickets: events.filterAddonsForTickets,\n submitPromoCode: events.submitPromoCode,\n setCurrency: events.setEventCurrency,\n authenticate: events.authenticateEvent,\n track: events.trackEvent,\n updateOrderDataCapture: events.updateOrderDataCapture,\n updateTicketDataCapture: events.updateTicketDataCapture,\n },\n cart: {\n add: cart.addTicketsToCart,\n addSeats: cart.addSeatsToCart,\n get: cart.getCart,\n checkoutConfigs: cart.getCheckoutConfigs,\n price: cart.updateCheckout,\n priceBreakdown: cart.getPriceBreakdown,\n paymentConfig: cart.getPaymentConfigAttributes,\n preOrderMethods: cart.getPreOrderPaymentMethods,\n checkBuyerEmail: cart.checkBuyerEmail,\n },\n order: {\n create: order.createOrder,\n review: order.getOrderReview,\n mapProfileToBilling: order.mapProfileToBilling,\n completeFreeRegistration: order.completeFreeRegistration,\n confirmSuccess: order.confirmOrderSuccess,\n idVerificationStatus: order.getIdVerificationStatus,\n verifyCustomer: order.verifyCustomerOrder,\n },\n payment: {\n changeMethodType: payment.changePaymentMethodType,\n confirmRedirect: payment.confirmRedirect,\n prepareOxxo: payment.prepareForOxxo,\n xenditEWalletCharge: payment.submitXenditEWalletCharge,\n xenditCardCharge: payment.submitXenditCardCharge,\n installmentOffers: payment.getInstallmentOffers,\n confirmInstallments: payment.confirmInstallments,\n createPaymentPlan: payment.createPaymentPlan,\n chargeSavedCardPlan: payment.chargeSavedCardPlan,\n changeMethod: payment.changePaymentMethod,\n paypalForm: payment.getPayPalForm,\n },\n\n // --- account & post-purchase --------------------------------------------\n orders: {\n list: orders.getOrders,\n get: orders.getOrder,\n myTickets: orders.getMyTickets,\n updateOrderCustomFields: orders.updateOrderCustomFields,\n updateTicketHolderCustomFields: orders.updateTicketHolderCustomFields,\n },\n engagement: {\n attributeReferrer: engagement.attributeReferrer,\n joinWaitingList: engagement.joinWaitingList,\n sendRsvp: engagement.sendRsvp,\n validatePhone: engagement.validatePhone,\n },\n resale: {\n sell: resale.sellTicket,\n remove: resale.removeTicketFromResale,\n process: resale.processResale,\n decline: resale.declineResale,\n },\n confirmation: {\n get: confirmation.getConfirmation,\n },\n preRegistration: {\n confirm: preRegistration.confirmPreRegistration,\n influencers: preRegistration.getInfluencers,\n confirmationPage: preRegistration.getConfirmationPage,\n submitShareAction: preRegistration.submitShareAction,\n },\n delegation: {\n checkCustomerExists: delegation.checkCustomerExists,\n consumerPageInfo: delegation.getConsumerPageInfo,\n issueTicket: delegation.issueTicket,\n },\n seatmap: {\n data: seatmap.getSeatMapData,\n statuses: seatmap.getSeatStatuses,\n reserve: seatmap.reserveSeats,\n removeReserved: seatmap.removeReservedSeats,\n refreshReservation: seatmap.refreshReservation,\n },\n} as const\n\nexport type Ttf = typeof ttf\n","/**\n * React hooks over the `ttf` facade — one authored copy, imported unchanged by\n * both platform packages. React and @tanstack/react-query are peer deps, so a\n * consumer supplies its own QueryClientProvider.\n */\nexport * from './auth'\nexport * from './authFlow'\nexport * from './session'\nexport * from './profile'\nexport * from './geo'\nexport * from './events'\nexport * from './orders'\nexport * from './engagement'\nexport * from './checkout'\nexport { ttfKeys } from './keys'\nexport type { QueryOpts, MutationOpts } from './types'\n","/**\n * Auth hooks — React Query mutations over the `ttf.auth` facade. Authored once\n * here; both web and RN import them unchanged. Pass `onSuccess`/`onError` (or\n * any mutation option) through the `options` argument.\n */\nimport { useMutation } from '@tanstack/react-query'\n\nimport { ttf } from '../services'\nimport { AuthRegistrationInput } from '../dtos'\nimport { TfProfile } from '../types'\nimport { MutationOpts } from './types'\n\nexport const useLogin = (\n options?: MutationOpts<TfProfile, { email: string; password: string }>\n) =>\n useMutation({\n mutationFn: ({ email, password }: { email: string; password: string }) =>\n ttf.auth.login(email, password),\n ...options,\n })\n\nexport const useRegister = (\n options?: MutationOpts<TfProfile, Record<string, string | Blob>>\n) => useMutation({ mutationFn: ttf.auth.register, ...options })\n\nexport const useRegisterAccount = (\n options?: MutationOpts<TfProfile, AuthRegistrationInput>\n) => useMutation({ mutationFn: ttf.auth.registerAccount, ...options })\n\nexport const useRestorePassword = (options?: MutationOpts<void, string>) =>\n useMutation({ mutationFn: ttf.auth.restorePassword, ...options })\n\nexport const useRestorePasswordRn = (options?: MutationOpts<void, string>) =>\n useMutation({ mutationFn: ttf.auth.restorePasswordRn, ...options })\n\nexport const useResetPassword = (\n options?: MutationOpts<\n void,\n { token: string; password: string; passwordConfirmation?: string }\n >\n) => useMutation({ mutationFn: ttf.auth.resetPassword, ...options })\n\nexport const useLogout = (options?: MutationOpts<void, void>) =>\n useMutation({ mutationFn: () => ttf.auth.logout(), ...options })\n\nexport const useCheckEmailExists = (\n options?: MutationOpts<{ exists: boolean; error?: string }, string>\n) => useMutation({ mutationFn: ttf.auth.checkEmailExists, ...options })\n","/**\n * Headless authentication flow shared by every platform UI.\n *\n * This owns validation, mutations, profile-cache/session synchronization,\n * errors, success state, and view transitions. Web renders it in a modal;\n * React Native can render the same contract as screens or a native sheet.\n */\nimport { useQueryClient } from '@tanstack/react-query'\nimport { useCallback, useState } from 'react'\n\nimport type {\n AuthFieldErrors,\n AuthFieldName,\n AuthFlowView,\n AuthLoginInput,\n AuthRegistrationInput,\n} from '../dtos'\nimport {\n normalizeAuthEmail,\n validateLoginInput,\n validatePasswordResetEmail,\n validateRegistrationInput,\n} from '../logic'\nimport type { TfProfile } from '../types'\nimport {\n useLogin,\n useLogout,\n useRegisterAccount,\n useRestorePassword,\n useRestorePasswordRn,\n} from './auth'\nimport { ttfKeys } from './keys'\nimport { useAuthSession } from './session'\n\nexport interface UseAuthFlowOptions {\n initialView?: AuthFlowView\n initialEmail?: string\n /** Match the legacy modal's full account form by default. */\n requireRegistrationAddress?: boolean\n /** Web and native use different restore-password routes on the legacy API. */\n passwordResetTransport?: 'web' | 'native'\n /** Extra backend fields for specialized registration links. */\n registrationFields?: Record<string, string>\n onAuthenticated?: (profile: TfProfile) => void\n onLoggedOut?: () => void\n}\n\nexport interface RegistrationSubmitOptions {\n /** Require state only when the selected country actually exposes states. */\n requireState?: boolean\n}\n\nconst messageFrom = (error: unknown, fallback: string): string =>\n error instanceof Error && error.message ? error.message : fallback\n\nexport const useAuthFlow = (options: UseAuthFlowOptions = {}) => {\n const queryClient = useQueryClient()\n const session = useAuthSession()\n const loginMutation = useLogin()\n const registerMutation = useRegisterAccount()\n const restoreMutation = useRestorePassword()\n const restoreNativeMutation = useRestorePasswordRn()\n const logoutMutation = useLogout()\n const [view, setViewState] = useState<AuthFlowView>(options.initialView ?? 'login')\n const [suggestedEmail, setSuggestedEmail] = useState(\n normalizeAuthEmail(options.initialEmail ?? '')\n )\n const [fieldErrors, setFieldErrors] = useState<AuthFieldErrors>({})\n const [error, setError] = useState('')\n const [successMessage, setSuccessMessage] = useState('')\n\n const clearFeedback = useCallback(() => {\n setFieldErrors({})\n setError('')\n setSuccessMessage('')\n loginMutation.reset()\n registerMutation.reset()\n restoreMutation.reset()\n restoreNativeMutation.reset()\n }, [loginMutation, registerMutation, restoreMutation, restoreNativeMutation])\n\n const clearFieldError = useCallback((field: AuthFieldName) => {\n setFieldErrors((current) => {\n if (!current[field]) return current\n const next = { ...current }\n delete next[field]\n return next\n })\n setError('')\n }, [])\n\n const setView = useCallback(\n (next: AuthFlowView, email?: string) => {\n clearFeedback()\n if (email !== undefined) setSuggestedEmail(normalizeAuthEmail(email))\n setViewState(next)\n },\n [clearFeedback]\n )\n\n const showLogin = useCallback((email?: string) => setView('login', email), [setView])\n const showRegister = useCallback(\n (email?: string) => setView('register', email),\n [setView]\n )\n const showForgotPassword = useCallback(\n (email?: string) => setView('forgot-password', email),\n [setView]\n )\n\n const authenticated = useCallback(\n (profile: TfProfile) => {\n queryClient.setQueryData(ttfKeys.profile, profile)\n setSuggestedEmail(normalizeAuthEmail(profile.email))\n clearFeedback()\n options.onAuthenticated?.(profile)\n },\n [clearFeedback, options, queryClient]\n )\n\n const submitLogin = useCallback(\n async (input: AuthLoginInput): Promise<TfProfile | null> => {\n clearFeedback()\n const validation = validateLoginInput(input)\n if (!validation.valid) {\n setFieldErrors(validation.errors)\n return null\n }\n try {\n const profile = await loginMutation.mutateAsync({\n email: normalizeAuthEmail(input.email),\n password: input.password,\n })\n authenticated(profile)\n return profile\n } catch (caught) {\n setError(messageFrom(caught, 'Unable to log in. Please try again.'))\n return null\n }\n },\n [authenticated, clearFeedback, loginMutation]\n )\n\n const submitRegistration = useCallback(\n async (\n input: AuthRegistrationInput,\n submitOptions: RegistrationSubmitOptions = {}\n ): Promise<TfProfile | null> => {\n clearFeedback()\n const validation = validateRegistrationInput(input, {\n requireAddress: options.requireRegistrationAddress ?? true,\n requireState: submitOptions.requireState,\n })\n if (!validation.valid) {\n setFieldErrors(validation.errors)\n return null\n }\n try {\n const profile = await registerMutation.mutateAsync({\n ...input,\n email: normalizeAuthEmail(input.email),\n registrationFields: options.registrationFields,\n })\n authenticated(profile)\n return profile\n } catch (caught) {\n const message = messageFrom(\n caught,\n 'Unable to create your account. Please try again.'\n )\n setError(message)\n if (/exist|already|registered/i.test(message))\n setFieldErrors({ email: 'This email already has an account.' })\n return null\n }\n },\n [\n authenticated,\n clearFeedback,\n options.registrationFields,\n options.requireRegistrationAddress,\n registerMutation,\n ]\n )\n\n const submitPasswordReset = useCallback(\n async (email: string): Promise<boolean> => {\n clearFeedback()\n const validation = validatePasswordResetEmail(email)\n if (!validation.valid) {\n setFieldErrors(validation.errors)\n return false\n }\n const normalizedEmail = normalizeAuthEmail(email)\n const mutation =\n options.passwordResetTransport === 'native'\n ? restoreNativeMutation\n : restoreMutation\n try {\n await mutation.mutateAsync(normalizedEmail)\n setSuggestedEmail(normalizedEmail)\n setSuccessMessage(\n 'If an account exists for this email, password reset instructions are on the way.'\n )\n return true\n } catch (caught) {\n setError(\n messageFrom(caught, 'Unable to send reset instructions. Please try again.')\n )\n return false\n }\n },\n [\n clearFeedback,\n options.passwordResetTransport,\n restoreMutation,\n restoreNativeMutation,\n ]\n )\n\n const logout = useCallback(async (): Promise<boolean> => {\n clearFeedback()\n try {\n await logoutMutation.mutateAsync()\n queryClient.removeQueries({ queryKey: ttfKeys.profile })\n options.onLoggedOut?.()\n return true\n } catch (caught) {\n // The API always clears local tokens in a finally block, so reflect the\n // logged-out state even if the backend session-close request failed.\n queryClient.removeQueries({ queryKey: ttfKeys.profile })\n setError(messageFrom(caught, 'You have been logged out locally.'))\n options.onLoggedOut?.()\n return true\n }\n }, [clearFeedback, logoutMutation, options, queryClient])\n\n return {\n view,\n suggestedEmail,\n fieldErrors,\n error,\n successMessage,\n isAuthenticated: session.isAuthenticated,\n isSubmitting:\n loginMutation.isPending ||\n registerMutation.isPending ||\n restoreMutation.isPending ||\n restoreNativeMutation.isPending ||\n logoutMutation.isPending,\n showLogin,\n showRegister,\n showForgotPassword,\n clearFeedback,\n clearFieldError,\n submitLogin,\n submitRegistration,\n submitPasswordReset,\n logout,\n mutations: {\n login: loginMutation,\n register: registerMutation,\n restorePassword: restoreMutation,\n restorePasswordNative: restoreNativeMutation,\n logout: logoutMutation,\n },\n }\n}\n\nexport type UseAuthFlow = ReturnType<typeof useAuthFlow>\n","/** React Query cache keys for the SDK, all namespaced under `ttf`. */\nimport { OrdersQuery } from '../api/orders'\n\nexport const ttfKeys = {\n profile: ['ttf', 'profile'] as const,\n countries: ['ttf', 'countries'] as const,\n states: (countryId: string | number) => ['ttf', 'states', countryId] as const,\n event: (eventId: string) => ['ttf', 'event', eventId] as const,\n tickets: (eventId: string) => ['ttf', 'tickets', eventId] as const,\n addons: (eventId: string) => ['ttf', 'addons', eventId] as const,\n orders: (query: OrdersQuery) => ['ttf', 'orders', query] as const,\n order: (orderId: string) => ['ttf', 'order', orderId] as const,\n}\n","/** Reactive authentication state backed by the shared token session. */\nimport { useSyncExternalStore } from 'react'\n\nimport { isAuthenticated, subscribeSession } from '../client'\n\nexport const useAuthSession = (): { isAuthenticated: boolean } => {\n const authenticated = useSyncExternalStore(\n subscribeSession,\n isAuthenticated,\n () => false\n )\n return { isAuthenticated: authenticated }\n}\n","/** Profile hook — the signed-in user's record as a React Query query. */\nimport { useQuery } from '@tanstack/react-query'\n\nimport { ttf } from '../services'\nimport { TfProfile } from '../types'\nimport { ttfKeys } from './keys'\nimport { useAuthSession } from './session'\nimport { QueryOpts } from './types'\n\nexport const useProfile = (options?: QueryOpts<TfProfile>) => {\n const session = useAuthSession()\n return useQuery({\n queryKey: ttfKeys.profile,\n queryFn: () => ttf.profile.get(),\n enabled: session.isAuthenticated,\n ...options,\n })\n}\n","/** Geo hooks — countries always, states gated on a chosen country. */\nimport { useQuery } from '@tanstack/react-query'\n\nimport { TfCountry, TfState } from '../types'\nimport { ttf } from '../services'\nimport { ttfKeys } from './keys'\nimport { QueryOpts } from './types'\n\nexport const useCountries = (options?: QueryOpts<TfCountry[]>) =>\n useQuery({\n queryKey: ttfKeys.countries,\n queryFn: () => ttf.geo.countries(),\n staleTime: Infinity,\n ...options,\n })\n\nexport const useStates = (\n countryId: string | number | undefined,\n options?: QueryOpts<TfState[]>\n) =>\n useQuery({\n queryKey: ttfKeys.states(countryId ?? ''),\n queryFn: () => ttf.geo.states(countryId as string | number),\n enabled: Boolean(countryId),\n ...options,\n })\n","/** Catalog read hooks — an event's info, purchasable tickets, and add-ons. */\nimport { useQuery } from '@tanstack/react-query'\n\nimport type { EventAddon, TicketType } from '../dtos'\nimport { ttf } from '../services'\nimport { ttfKeys } from './keys'\nimport { QueryOpts } from './types'\n\n/** Event details (seated detection, slug, name). Gated on a chosen event id. */\nexport const useEvent = (\n eventId: string | undefined,\n options?: QueryOpts<Awaited<ReturnType<typeof ttf.events.info>>>\n) =>\n useQuery({\n queryKey: ttfKeys.event(eventId ?? ''),\n queryFn: () => ttf.events.info(eventId as string),\n enabled: Boolean(eventId),\n ...options,\n })\n\n/** Purchasable ticket types for an event. Gated on a chosen event id. */\nexport const useTickets = (\n eventId: string | undefined,\n options?: QueryOpts<TicketType[]>\n) =>\n useQuery({\n queryKey: ttfKeys.tickets(eventId ?? ''),\n queryFn: () => ttf.events.tickets(eventId as string),\n enabled: Boolean(eventId),\n ...options,\n })\n\n/** Tickets PLUS the catalog-level promo/access-code metadata and waiting-list\n * flag the same response carries. Use this (over `useTickets`) when the ticket\n * screen needs promo codes, access codes, or waiting lists. `refetch()` after\n * applying a code to pick up updated prices / newly-unlocked tickets. */\nexport const useTicketsWithMeta = (\n eventId: string | undefined,\n options?: QueryOpts<Awaited<ReturnType<typeof ttf.events.ticketsWithMeta>>>\n) =>\n useQuery({\n queryKey: [...ttfKeys.tickets(eventId ?? ''), 'meta'],\n queryFn: () => ttf.events.ticketsWithMeta(eventId as string),\n enabled: Boolean(eventId),\n ...options,\n })\n\n/** Purchasable ticket types for ONE date of a time-slot / calendar event. Each\n * ticket carries its `timeSlot: { date, time }`. Gated on event id + date. */\nexport const useTimeSlotTickets = (\n eventId: string | undefined,\n date: string | undefined,\n options?: QueryOpts<TicketType[]>\n) =>\n useQuery({\n queryKey: [...ttfKeys.tickets(eventId ?? ''), 'slots', date ?? ''],\n queryFn: () => ttf.events.timeSlotTickets(eventId as string, date as string),\n enabled: Boolean(eventId && date),\n ...options,\n })\n\n/** The event's add-on catalog (upsells). Gated on a chosen event id. Filter it\n * to the primed cart with `ttf.events.filterAddonsForTickets(list, ids)`. */\nexport const useEventAddons = (\n eventId: string | undefined,\n options?: QueryOpts<EventAddon[]>\n) =>\n useQuery({\n queryKey: ttfKeys.addons(eventId ?? ''),\n queryFn: () => ttf.events.addons(eventId as string),\n enabled: Boolean(eventId),\n ...options,\n })\n","/** Order-history hooks — the buyer's list and one order's detail. */\nimport { useQuery } from '@tanstack/react-query'\n\nimport { OrdersQuery, TfOrderDetails, TfOrderSummary } from '../api/orders'\nimport { TfEnvelope, TfListEnvelope } from '../types'\nimport { ttf } from '../services'\nimport { ttfKeys } from './keys'\nimport { QueryOpts } from './types'\n\nexport const useOrders = (\n query: OrdersQuery = {},\n options?: QueryOpts<TfListEnvelope<TfOrderSummary>>\n) =>\n useQuery({\n queryKey: ttfKeys.orders(query),\n queryFn: () => ttf.orders.list(query),\n ...options,\n })\n\nexport const useOrder = (\n orderId: string | undefined,\n options?: QueryOpts<TfEnvelope<TfOrderDetails>>\n) =>\n useQuery({\n queryKey: ttfKeys.order(orderId ?? ''),\n queryFn: () => ttf.orders.get(orderId as string),\n enabled: Boolean(orderId),\n ...options,\n })\n","/** Engagement hooks — phone validation, waiting list, referral, RSVP. */\nimport { useMutation } from '@tanstack/react-query'\n\nimport { WaitingListEntry } from '../api/engagement'\nimport { ttf } from '../services'\nimport { MutationOpts } from './types'\n\nexport const useValidatePhone = (\n options?: MutationOpts<{ valid: boolean; [key: string]: unknown }, string>\n) => useMutation({ mutationFn: ttf.engagement.validatePhone, ...options })\n\nexport const useJoinWaitingList = (\n eventId: string,\n options?: MutationOpts<void, WaitingListEntry>\n) =>\n useMutation({\n mutationFn: (entry: WaitingListEntry) =>\n ttf.engagement.joinWaitingList(eventId, entry),\n ...options,\n })\n\nexport const useAttributeReferrer = (\n eventId: string,\n options?: MutationOpts<void, string | number | null>\n) =>\n useMutation({\n mutationFn: (referrer: string | number | null) =>\n ttf.engagement.attributeReferrer(eventId, referrer),\n ...options,\n })\n\nexport const useSendRsvp = (\n eventId: string,\n options?: MutationOpts<unknown, Record<string, unknown>>\n) =>\n useMutation({\n mutationFn: (data: Record<string, unknown>) => ttf.engagement.sendRsvp(eventId, data),\n ...options,\n })\n","/**\n * `useCheckout()` — the engine's React binding, with the shared DX every\n * platform wants baked in ONCE here (not re-written per platform):\n * - the snapshot is spread flat (`checkout.status`, `checkout.breakdown`, …)\n * - a reservation countdown (`secondsLeft`) and an `isBusy` flag\n * - `missingRequiredAddonNames`, `isLoggedIn`\n * - promo / referrer / waiting-list helpers over `ttf`\n * - `placeOrder(method, { autoRunIdVerification })`\n *\n * A platform lib only injects its `ports` (Stripe confirmer, provider page, …)\n * — it does NOT re-implement any of the above. Non-React apps use\n * `createEngine()` + `store.subscribe` directly.\n */\nimport { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'\n\nimport type {\n CheckoutSnapshot,\n PlaceOrderResult,\n SeatLine,\n TicketSelection,\n WaitingListEntry,\n} from '../dtos'\nimport {\n createCheckoutStore,\n createEngine,\n type CheckoutEngine,\n type CheckoutStore,\n type EngineConfig,\n type PaymentMethod,\n type PaymentRequest,\n type RunIdVerificationOptions,\n} from '../engine'\nimport { missingRequiredAddOns } from '../logic'\nimport { ttf } from '../services'\nimport { useAuthSession } from './session'\n\nexport interface PlaceOrderHookOptions {\n /** After a successful order needing ID verification, run it automatically\n * (mint + open + poll). The rejection is swallowed — payment already\n * settled — so it never surfaces as a payment failure. Uses the engine's\n * `openUrl` port to open the provider URL. */\n autoRunIdVerification?: boolean\n idVerification?: RunIdVerificationOptions\n}\n\n/**\n * A gated buyer field this event asks for BEYOND name/email — surfaced from the\n * server's checkout-configs so consumers render exactly what's needed instead of\n * guessing. Write the captured value straight to `billing[key]` (e.g.\n * `setBilling({ ...billing, instagramHandle })`); the engine forwards it in the\n * order body. `nationality` expects a country id (see `ttf.geo.countries()` /\n * `useCountries()`); `gender` expects `'M'` | `'F'`.\n */\nexport interface BuyerFieldSpec {\n key: 'nationality' | 'gender' | 'instagramHandle'\n label: string\n required: boolean\n /** How to render it: a country picker, an M/F choice, or a handle text box. */\n kind: 'nationality' | 'gender' | 'instagram'\n}\n\nexport interface UseCheckout extends CheckoutSnapshot {\n /** The whole snapshot object (the fields above are spread from it). */\n snapshot: CheckoutSnapshot\n /** True while a cart/order operation is in flight. */\n isBusy: boolean\n /** Whole-seconds countdown for the cart reservation (undefined when none).\n * Raw on purpose — format it however your UI wants. */\n secondsLeft?: number\n /** Required add-on names still missing (same rule the pre-flight enforces). */\n missingRequiredAddonNames: string[]\n /** Gated buyer fields this event needs beyond name/email (Instagram /\n * nationality / gender), each with its required flag — render these from\n * data. Empty when the event gates none. Pairs with `customFields` (the\n * order/ticket capture groups) for the full \"what must I collect\" picture. */\n buyerFields: BuyerFieldSpec[]\n /** Whether a signed-in access token is present. */\n isLoggedIn: boolean\n\n /** Build + price the cart for a ticket selection (alias for `prime`). */\n setTickets: (eventId: string, selections: TicketSelection[]) => Promise<void>\n /** Build + price the cart for reserved SEATS (alias for `primeSeats`). */\n setSeats: (eventId: string, lines: SeatLine[]) => Promise<void>\n /** Attach to an existing server-side cart (e.g. accepted resale invitation). */\n resumeCart: CheckoutEngine['resumeCart']\n setAddons: CheckoutEngine['setAddons']\n setBilling: CheckoutEngine['setBilling']\n setHolders: CheckoutEngine['setHolders']\n setConsent: CheckoutEngine['setConsent']\n setAcceptedConditions: CheckoutEngine['setAcceptedConditions']\n /** Accept/unaccept one condition block (merges into the map). */\n acceptCondition: (id: string, accepted: boolean) => void\n setAddonDataCapture: CheckoutEngine['setAddonDataCapture']\n checkBuyerEmail: CheckoutEngine['checkBuyerEmail']\n placeOrder: (\n method?: PaymentMethod | PaymentRequest,\n options?: PlaceOrderHookOptions\n ) => Promise<PlaceOrderResult>\n runIdVerification: CheckoutEngine['runIdVerification']\n syncCurrency: CheckoutEngine['syncCurrency']\n reset: CheckoutEngine['reset']\n applyPromoCode: (eventId: string, promo: string) => Promise<void>\n attributeReferrer: (eventId: string, referrer: string | number | null) => Promise<void>\n joinWaitingList: (eventId: string, entry: WaitingListEntry) => Promise<void>\n}\n\n// ONE app-wide checkout store. Every useCheckout() call — SignIn, Tickets, Pay,\n// each component mounting on its own — must read and write the SAME cart, with\n// no Context and no prop-drilling. Per-component engines all bind this single\n// store below. Without it, each component would get its own store: the step\n// that primes would flip ITS status to 'ready' while the step doing the gating\n// reads a different store still 'idle', so the pay UI silently never appears.\n// (Callers can still pass an explicit `config.store` to opt out.)\nlet sharedStore: CheckoutStore | null = null\n\nexport const useCheckout = (config: EngineConfig): UseCheckout => {\n const authSession = useAuthSession()\n // Create the engine exactly once — its store, subscribe, and actions must be\n // stable references for useSyncExternalStore and consumers' effects. The store\n // it binds is the app-wide singleton (unless the caller supplied their own),\n // so every useCheckout() across the tree shares one cart.\n const engineRef = useRef<CheckoutEngine | null>(null)\n if (engineRef.current === null) {\n if (sharedStore === null) sharedStore = createCheckoutStore()\n engineRef.current = createEngine({ ...config, store: config.store ?? sharedStore })\n }\n const engine = engineRef.current\n\n const snapshot = useSyncExternalStore(\n engine.subscribe,\n engine.getSnapshot,\n engine.getSnapshot // server snapshot === client (SSR-safe: idle checkout)\n )\n\n const isBusy =\n snapshot.status === 'priming' ||\n snapshot.status === 'repricing' ||\n snapshot.status === 'placing'\n\n // Whole-seconds countdown for the cart reservation.\n const [now, setNow] = useState(() => Date.now())\n useEffect(() => {\n if (snapshot.expiresAt == null) return\n const t = setInterval(() => setNow(Date.now()), 1000)\n return () => clearInterval(t)\n }, [snapshot.expiresAt])\n const secondsLeft =\n snapshot.expiresAt != null\n ? Math.max(0, Math.round((snapshot.expiresAt - now) / 1000))\n : undefined\n\n const missingRequiredAddonNames = missingRequiredAddOns(\n snapshot.requiredAddOns,\n snapshot.addOns\n )\n .map((a) => a.name || '')\n .filter(Boolean)\n\n // The event's gated buyer fields, surfaced render-ready from checkout-configs\n // so consumers stop guessing (this is what caused \"Instagram handle is\n // required\" to fail silently — the gate was in the data, just never shown).\n const gates = snapshot.fieldGates\n const buyerFields: BuyerFieldSpec[] = []\n if (gates.showNationality)\n buyerFields.push({\n key: 'nationality',\n label: 'Nationality',\n required: gates.nationalityRequired,\n kind: 'nationality',\n })\n if (gates.showGender)\n buyerFields.push({\n key: 'gender',\n label: 'Gender',\n required: gates.genderRequired,\n kind: 'gender',\n })\n if (gates.requireInstagram)\n buyerFields.push({\n key: 'instagramHandle',\n label: 'Instagram handle',\n required: true,\n kind: 'instagram',\n })\n\n const isLoggedIn = authSession.isAuthenticated\n\n // The engine's own openUrl port (the platform's) — used to open the provider\n // URL for the opt-in auto-run.\n const openUrl = config.ports.openUrl\n\n const placeOrder = useCallback(\n async (\n method?: PaymentMethod | PaymentRequest,\n options?: PlaceOrderHookOptions\n ): Promise<PlaceOrderResult> => {\n const result = await engine.placeOrder(method)\n if (options?.autoRunIdVerification && result.needIdVerification) {\n try {\n await engine.runIdVerification(result.orderHash, {\n openUrl,\n ...options.idVerification,\n })\n } catch {\n // Verification stall — payment is safe; tickets follow by email.\n }\n }\n return result\n },\n [engine, openUrl]\n )\n\n const setTickets = useCallback(\n (eventId: string, selections: TicketSelection[]) => engine.prime(eventId, selections),\n [engine]\n )\n const setSeats = useCallback(\n (eventId: string, lines: SeatLine[]) => engine.primeSeats(eventId, lines),\n [engine]\n )\n const acceptCondition = useCallback(\n (id: string, accepted: boolean) =>\n engine.setAcceptedConditions({\n ...(snapshot.acceptedConditions ?? {}),\n [id]: accepted,\n }),\n [engine, snapshot.acceptedConditions]\n )\n const applyPromoCode = useCallback(\n (eventId: string, promo: string) => ttf.events.submitPromoCode(eventId, promo),\n []\n )\n const attributeReferrer = useCallback(\n (eventId: string, referrer: string | number | null) =>\n ttf.engagement.attributeReferrer(eventId, referrer),\n []\n )\n const joinWaitingList = useCallback(\n (eventId: string, entry: WaitingListEntry) =>\n ttf.engagement.joinWaitingList(eventId, entry),\n []\n )\n\n return {\n ...snapshot,\n snapshot,\n isBusy,\n secondsLeft,\n missingRequiredAddonNames,\n buyerFields,\n isLoggedIn,\n setTickets,\n setSeats,\n resumeCart: engine.resumeCart,\n setAddons: engine.setAddons,\n setBilling: engine.setBilling,\n setHolders: engine.setHolders,\n setConsent: engine.setConsent,\n setAcceptedConditions: engine.setAcceptedConditions,\n acceptCondition,\n setAddonDataCapture: engine.setAddonDataCapture,\n checkBuyerEmail: engine.checkBuyerEmail,\n placeOrder,\n runIdVerification: engine.runIdVerification,\n syncCurrency: engine.syncCurrency,\n reset: engine.reset,\n applyPromoCode,\n attributeReferrer,\n joinWaitingList,\n }\n}\n","import type { Messages } from '../types'\n\n/**\n * English (UK) — the source of truth.\n *\n * Every key the SDK renders exists here, so a translator's job is to copy this\n * file and translate values; nothing else needs discovering. Other locales may\n * be partial and resolve missing keys through the chain in ../resolve.ts.\n *\n * Keys are namespaced by surface (`auth.`, `billing.`, `tickets.`, …) so a host\n * overriding one area does not have to know the whole catalogue. Values are the\n * strings the components previously hard-coded, moved verbatim — this file is a\n * relocation, not a rewrite, so behaviour is unchanged for anyone who never\n * sets a locale.\n */\nexport const en: Messages = {\n // --- Common ------------------------------------------------------------\n 'common.close': 'Close',\n 'common.dismiss': 'Dismiss',\n 'common.loading': 'Loading',\n 'common.required': 'Required',\n 'common.increase': 'Increase',\n 'common.decrease': 'Decrease',\n 'common.total': 'Total',\n 'common.date': 'Date',\n 'common.event': 'Event',\n 'common.currency': 'Currency',\n\n // --- Auth --------------------------------------------------------------\n 'auth.title': 'Authentication',\n 'auth.changePassword': 'Change Password',\n 'auth.email': 'Email *',\n 'auth.emailPlaceholder': 'Email',\n 'auth.password': 'Password *',\n 'auth.passwordPlaceholder': 'Password',\n 'auth.newPassword': 'New Password *',\n 'auth.confirmPassword': 'Confirm password *',\n 'auth.confirmPasswordPlaceholder': 'Confirm Password',\n 'auth.firstName': 'First name *',\n 'auth.firstNamePlaceholder': 'First Name',\n 'auth.lastName': 'Last name *',\n 'auth.lastNamePlaceholder': 'Last Name',\n 'auth.phone': 'Phone',\n 'auth.streetAddress': 'Street address *',\n 'auth.streetAddressPlaceholder': 'Street Address',\n 'auth.city': 'City *',\n 'auth.cityPlaceholder': 'City',\n 'auth.postcode': 'ZIP / postcode *',\n 'auth.postcodePlaceholder': 'Zip / Postal Code',\n 'auth.state': 'State / Province',\n 'auth.country': 'Country',\n 'auth.selectCountry': 'Select country',\n 'auth.loginSkipAhead': 'Login & skip ahead:',\n\n // --- Billing -----------------------------------------------------------\n 'billing.address': 'Billing address *',\n 'billing.email': 'Email Address *',\n 'billing.firstName': 'First Name *',\n 'billing.lastName': 'Last Name *',\n 'billing.phone': 'Phone *',\n 'billing.cityPlaceholder': 'City *',\n 'billing.streetPlaceholder': 'Street address *',\n 'billing.postcodePlaceholder': 'ZIP / Postcode *',\n 'billing.countryLabel': 'Country',\n 'billing.stateLabel': 'State / region',\n 'billing.socialPlaceholder': '@handle or profile URL',\n 'billing.male': 'Male',\n 'billing.female': 'Female',\n 'billing.ticketHolders': 'Ticket Holders',\n 'billing.emailPlaceholder': 'Email *',\n 'billing.confirmEmailPlaceholder': 'Confirm email *',\n 'billing.holderFirstName': 'First name *',\n 'billing.holderLastName': 'Last name *',\n 'billing.emailMismatch': 'The email addresses do not match.',\n\n // --- Tickets & seats ---------------------------------------------------\n 'tickets.yourTickets': 'Your Tickets',\n 'tickets.selectType': 'Please select a ticket type',\n 'tickets.soldOut': 'Sold out',\n 'tickets.guests': 'Guests',\n 'tickets.reserveTables': 'Reserve tables',\n 'tickets.noSessions': 'No sessions available on this date.',\n\n // --- Payment -----------------------------------------------------------\n 'payment.method': 'Payment method',\n 'payment.useThisCard': 'Use this card',\n 'payment.payInInstallments': 'Pay in installments?',\n 'payment.chooseInstallments': 'Choose installments',\n\n // --- Referral ----------------------------------------------------------\n 'referral.cheaperOrFree': 'Your tickets can be cheaper — or even FREE!',\n 'referral.inviteFriends': 'Invite friends',\n 'referral.howToInvite': 'How do you invite your friends?',\n 'referral.sendThisLink': 'Send them this link:',\n 'referral.howMuchCheaper': 'How much cheaper?',\n}\n","import { en } from './locales/en'\nimport type { LocaleCode, Messages, Translate, TranslatorOptions } from './types'\n\n/**\n * Locale bundles the SDK ships. English is the source of truth: every key\n * exists here, and every other locale is allowed to be partial.\n */\nconst CATALOGUES: Partial<Record<LocaleCode, Messages>> = { 'en-GB': en }\n\n/** Register a locale bundle. Used by ./locales/index to avoid a load cycle. */\nexport const registerCatalogue = (locale: LocaleCode, messages: Messages): void => {\n CATALOGUES[locale] = messages\n}\n\nexport const DEFAULT_LOCALE: LocaleCode = 'en-GB'\n\n/**\n * Per-locale fallback chains.\n *\n * en-US is an override-only layer (American spellings), so it MUST resolve\n * through en-GB rather than standing alone — the same structure the storefront\n * and the legacy platform use.\n */\nconst FALLBACKS: Record<LocaleCode, LocaleCode[]> = {\n 'en-GB': [],\n 'en-US': ['en-GB'],\n 'es-MX': ['en-GB'],\n fr: ['en-GB'],\n de: ['en-GB'],\n ru: ['en-GB'],\n id: ['en-GB'],\n}\n\n/** Map a raw device/browser language onto a locale we ship. */\nexport const resolveLocale = (raw?: string | null): LocaleCode => {\n if (!raw) return DEFAULT_LOCALE\n const lower = raw.toLowerCase()\n const base = lower.split('-')[0]\n\n if (base === 'en') return lower === 'en-us' ? 'en-US' : 'en-GB'\n if (base === 'es') return 'es-MX'\n if (base === 'fr' || base === 'de' || base === 'ru' || base === 'id') return base as LocaleCode\n return DEFAULT_LOCALE\n}\n\nconst INTERPOLATE = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g\n\n/**\n * Build a translator.\n *\n * Resolution order: host overrides -> requested locale -> its fallback chain\n * -> English -> the key itself. The last step means a missing string surfaces\n * as a visible key rather than an empty element, which is far easier to spot\n * in review than a silent blank.\n */\nexport const createTranslator = (options: TranslatorOptions = {}): Translate => {\n const locale = options.locale && FALLBACKS[options.locale] ? options.locale : DEFAULT_LOCALE\n const chain: Messages[] = []\n\n if (options.messages) chain.push(options.messages as Messages)\n const primary = CATALOGUES[locale]\n if (primary) chain.push(primary)\n for (const next of FALLBACKS[locale]) {\n const fallback = CATALOGUES[next]\n if (fallback) chain.push(fallback)\n }\n if (!chain.includes(en)) chain.push(en)\n\n return (key, vars) => {\n let template: string | undefined\n for (const source of chain) {\n const hit = source[key]\n if (typeof hit === 'string' && hit.length > 0) {\n template = hit\n break\n }\n }\n if (template === undefined) return key\n if (!vars) return template\n\n return template.replace(INTERPOLATE, (whole, name: string) => {\n const value = vars[name]\n return value === undefined || value === null ? whole : String(value)\n })\n }\n}\n","import type { Messages } from '../types'\n\n/**\n * Spanish (Mexico).\n *\n * Partial catalogues are legal — anything absent resolves through en-GB — but\n * this one is complete against ./en.ts so the checkout reads fully Spanish for\n * the storefronts that need it today.\n */\nexport const esMX: Messages = {\n // --- Common ------------------------------------------------------------\n 'common.close': 'Cerrar',\n 'common.dismiss': 'Descartar',\n 'common.loading': 'Cargando',\n 'common.required': 'Obligatorio',\n 'common.increase': 'Aumentar',\n 'common.decrease': 'Disminuir',\n 'common.total': 'Total',\n 'common.date': 'Fecha',\n 'common.event': 'Evento',\n 'common.currency': 'Moneda',\n\n // --- Auth --------------------------------------------------------------\n 'auth.title': 'Autenticación',\n 'auth.changePassword': 'Cambiar contraseña',\n 'auth.email': 'Correo electrónico *',\n 'auth.emailPlaceholder': 'Correo electrónico',\n 'auth.password': 'Contraseña *',\n 'auth.passwordPlaceholder': 'Contraseña',\n 'auth.newPassword': 'Nueva contraseña *',\n 'auth.confirmPassword': 'Confirma la contraseña *',\n 'auth.confirmPasswordPlaceholder': 'Confirma la contraseña',\n 'auth.firstName': 'Nombre *',\n 'auth.firstNamePlaceholder': 'Nombre',\n 'auth.lastName': 'Apellido *',\n 'auth.lastNamePlaceholder': 'Apellido',\n 'auth.phone': 'Teléfono',\n 'auth.streetAddress': 'Calle y número *',\n 'auth.streetAddressPlaceholder': 'Calle y número',\n 'auth.city': 'Ciudad *',\n 'auth.cityPlaceholder': 'Ciudad',\n 'auth.postcode': 'Código postal *',\n 'auth.postcodePlaceholder': 'Código postal',\n 'auth.state': 'Estado / Provincia',\n 'auth.country': 'País',\n 'auth.selectCountry': 'Selecciona un país',\n 'auth.loginSkipAhead': 'Inicia sesión y avanza más rápido:',\n\n // --- Billing -----------------------------------------------------------\n 'billing.address': 'Dirección de facturación *',\n 'billing.email': 'Correo electrónico *',\n 'billing.firstName': 'Nombre *',\n 'billing.lastName': 'Apellido *',\n 'billing.phone': 'Teléfono *',\n 'billing.cityPlaceholder': 'Ciudad *',\n 'billing.streetPlaceholder': 'Calle y número *',\n 'billing.postcodePlaceholder': 'Código postal *',\n 'billing.countryLabel': 'País',\n 'billing.stateLabel': 'Estado / región',\n 'billing.socialPlaceholder': '@usuario o URL del perfil',\n 'billing.male': 'Hombre',\n 'billing.female': 'Mujer',\n 'billing.ticketHolders': 'Titulares de los boletos',\n 'billing.emailPlaceholder': 'Correo electrónico *',\n 'billing.confirmEmailPlaceholder': 'Confirma tu correo *',\n 'billing.holderFirstName': 'Nombre *',\n 'billing.holderLastName': 'Apellido *',\n 'billing.emailMismatch': 'Los correos electrónicos no coinciden.',\n\n // --- Tickets & seats ---------------------------------------------------\n 'tickets.yourTickets': 'Tus boletos',\n 'tickets.selectType': 'Selecciona un tipo de boleto',\n 'tickets.soldOut': 'Agotado',\n 'tickets.guests': 'Invitados',\n 'tickets.reserveTables': 'Reservar mesas',\n 'tickets.noSessions': 'No hay funciones disponibles en esta fecha.',\n\n // --- Payment -----------------------------------------------------------\n 'payment.method': 'Método de pago',\n 'payment.useThisCard': 'Usar esta tarjeta',\n 'payment.payInInstallments': '¿Pagar a plazos?',\n 'payment.chooseInstallments': 'Elegir plazos',\n\n // --- Referral ----------------------------------------------------------\n 'referral.cheaperOrFree': 'Tus boletos pueden costar menos, ¡o incluso ser GRATIS!',\n 'referral.inviteFriends': 'Invita a tus amigos',\n 'referral.howToInvite': '¿Cómo invitas a tus amigos?',\n 'referral.sendThisLink': 'Envíales este enlace:',\n 'referral.howMuchCheaper': '¿Cuánto más barato?',\n}\n","import { registerCatalogue } from '../resolve'\nimport { en } from './en'\nimport { esMX } from './es-MX'\n\n/**\n * Registers every bundle the SDK ships.\n *\n * en-GB is registered by ../resolve directly (it is the fallback of last\n * resort and must exist before any lookup). The rest register here.\n *\n * Adding a locale: create ./<code>.ts exporting a Messages object, then\n * register it below. Partial catalogues are fine — missing keys resolve\n * through the fallback chain to English.\n */\nregisterCatalogue('es-MX', esMX)\n\nexport { en, esMX }\n","/**\n * React Native adapter of the SDK's `PaymentConfirmer` + `CheckoutPorts` — the\n * native mirror of the web `confirmer.ts`. It binds `@stripe/stripe-react-native`\n * so the engine in `tf-checkout-shared` runs the exact same\n * cart → order → charge → finalize sequence the web runs, with the same\n * retry-safety invariants and duplicate-charge guards.\n *\n * Uses the IMPERATIVE stripe-react-native functions (not the `useConfirmPayment`\n * hook) because the confirmer is a module singleton, not a component. Card data\n * flows from the mounted `<CardInput/>` (`<CardField/>`) into `confirmPayment`\n * natively — there is no element to register the way web does.\n *\n * Deferred (optional ports, left unimplemented — the engine falls back to a\n * typed \"unsupported gateway\" for them): WebView-based rails — Razorpay / PayPal\n * / Stripe redirect methods (`providerPage`, `createRedirectPaymentMethod`) and\n * Xendit tokenization (`tokenizeXenditCard`). They need `react-native-webview`,\n * which this package injects rather than depends on; wiring them is a follow-up.\n */\nimport { Linking } from 'react-native'\nimport {\n confirmPayment,\n confirmPlatformPayPayment,\n confirmSetupIntent,\n createPaymentMethod,\n handleNextAction,\n initStripe,\n PlatformPay,\n retrievePaymentIntent,\n type BillingDetails,\n} from '@stripe/stripe-react-native'\n\nimport type {\n CheckoutBilling,\n CheckoutPorts,\n PaymentConfirmer,\n} from 'tf-checkout-shared'\n\n/** `CheckoutBilling` → the native SDK's `BillingDetails`. Mirrors the web\n * `stripeBillingDetails`; the SDK collects card data from `<CardField/>`. */\nconst toBillingDetails = (billing: CheckoutBilling): BillingDetails => ({\n email: billing.email,\n name: `${billing.firstName} ${billing.lastName}`.trim(),\n phone: billing.phone || undefined,\n address: {\n line1: billing.streetAddress || undefined,\n city: billing.city || undefined,\n postalCode: billing.zip || undefined,\n // Stripe wants ISO-2; CheckoutBilling carries it when the consumer resolved\n // it (backend ids are numeric). Left undefined otherwise.\n country: billing.countryCode || undefined,\n state: billing.stateCode || undefined,\n },\n})\n\nconst failed = (message: string | undefined, fallback: string): Error =>\n new Error(message || fallback)\n\n/**\n * The confirmer every `useCheckout`/`<CardInput/>` binds to. `init()` is\n * idempotent per key so an event on a connected Stripe account re-initializes\n * only when the key/account actually changes.\n */\nexport const createRnStripeConfirmer = (): PaymentConfirmer => {\n let initKey: string | null = null\n\n return {\n init: async ({ publishableKey, accountId, merchantIdentifier, urlScheme }) => {\n const key = `${publishableKey}:${accountId ?? ''}:${merchantIdentifier ?? ''}`\n if (initKey === key) return\n await initStripe({\n publishableKey,\n ...(accountId ? { stripeAccountId: accountId } : {}),\n ...(merchantIdentifier ? { merchantIdentifier } : {}),\n ...(urlScheme ? { urlScheme } : {}),\n })\n initKey = key\n },\n\n // Native statuses are already the port's PascalCase vocabulary — no normalize.\n getIntentStatus: async (clientSecret) => {\n const { paymentIntent } = await retrievePaymentIntent(clientSecret)\n return paymentIntent?.status\n },\n\n confirmCard: async (clientSecret, billing) => {\n const { error, paymentIntent } = await confirmPayment(clientSecret, {\n paymentMethodType: 'Card',\n paymentMethodData: { billingDetails: toBillingDetails(billing) },\n })\n if (error) throw failed(error.message, 'Payment failed.')\n return paymentIntent?.status\n },\n\n confirmApplePay: async (clientSecret, total, currencyCode, merchant) => {\n const { error, paymentIntent } = await confirmPlatformPayPayment(clientSecret, {\n applePay: {\n merchantCountryCode: merchant.merchantCountryCode ?? 'US',\n currencyCode,\n cartItems: [\n {\n label: merchant.merchantName ?? 'Order',\n amount: total,\n paymentType: PlatformPay.PaymentType.Immediate,\n },\n ],\n },\n })\n if (error) throw failed(error.message, 'Apple Pay failed.')\n return paymentIntent?.status\n },\n\n confirmGooglePay: async (clientSecret, total, currencyCode, merchant) => {\n const { error, paymentIntent } = await confirmPlatformPayPayment(clientSecret, {\n googlePay: {\n testEnv: merchant.testEnv === true,\n merchantCountryCode: merchant.merchantCountryCode ?? 'US',\n currencyCode,\n merchantName: merchant.merchantName ?? 'Order',\n },\n })\n if (error) throw failed(error.message, 'Google Pay failed.')\n return paymentIntent?.status\n },\n }\n}\n\n/**\n * The native ports the alternative Stripe rails run on. OXXO / MSI / payment-plan\n * legs bind the same imperative stripe-react-native functions; `openUrl` uses\n * `Linking`. WebView rails are intentionally absent (see file header).\n */\nexport const createRnPorts = (): Omit<CheckoutPorts, 'confirmer'> => ({\n openUrl: (url: string) => {\n void Linking.openURL(url)\n },\n\n createCardPaymentMethod: async (billing) => {\n const { paymentMethod, error } = await createPaymentMethod({\n paymentMethodType: 'Card',\n paymentMethodData: { billingDetails: toBillingDetails(billing) },\n })\n if (error || !paymentMethod?.id) throw failed(error?.message, 'Payment failed')\n return paymentMethod.id\n },\n\n handleNextAction: async (clientSecret) => {\n const { error } = await handleNextAction(clientSecret)\n if (error) throw failed(error.message, 'Payment failed')\n },\n\n confirmOxxo: async (clientSecret, billing) => {\n const { error, paymentIntent } = await confirmPayment(clientSecret, {\n paymentMethodType: 'Oxxo',\n paymentMethodData: { billingDetails: toBillingDetails(billing) },\n })\n return { error: error?.message, nextAction: paymentIntent?.nextAction as unknown }\n },\n\n // Payment plan (new card): confirm the SetupIntent to SAVE the card (nothing\n // charged) and return its PaymentMethod id for the server-side plan.\n confirmPaymentPlanSetup: async (clientSecret, billing) => {\n const { setupIntent, error } = await confirmSetupIntent(clientSecret, {\n paymentMethodType: 'Card',\n paymentMethodData: { billingDetails: toBillingDetails(billing) },\n })\n const paymentMethodId = setupIntent?.paymentMethod?.id\n if (error || !paymentMethodId) throw failed(error?.message, 'Card setup failed')\n return paymentMethodId\n },\n\n // Payment plan (saved-card 3DS): confirm the pending charge against the\n // existing PaymentMethod when the plan comes back requires_action.\n confirmSavedCardPayment: async (clientSecret, paymentMethodId) => {\n const { error } = await confirmPayment(clientSecret, {\n paymentMethodType: 'Card',\n paymentMethodData: { paymentMethodId },\n })\n if (error) throw failed(error.message, 'Payment failed')\n },\n})\n","/**\n * The package-level native platform instances. Created once at module load, so\n * the hook and the UI components all bind to the SAME confirmer/ports.\n */\nimport type { PaymentConfirmer } from 'tf-checkout-shared'\n\nimport { createRnPorts, createRnStripeConfirmer } from './confirmer'\n\n/** The confirmer every `useCheckout`/`<CardInput/>` binds to. */\nexport const rnConfirmer: PaymentConfirmer = createRnStripeConfirmer()\n\n/** The native ports the alternative Stripe rails (OXXO / plan) run on. */\nexport const rnPorts = createRnPorts()\n","/**\n * Native `useCheckout` — a thin injector: the SDK's `useCheckout` with the RN\n * platform ports pre-wired (stripe-react-native confirmer + native rails). ALL\n * the DX (countdown, isBusy, promo/referrer/waiting-list, auto ID verification,\n * the flat snapshot) lives in the SDK's hook, so web and native share it — this\n * file only supplies what's platform-specific.\n *\n * configureCheckout({ env: 'PROD', clientId, clientSecret }) // once, at app start\n * const checkout = useCheckout()\n * await checkout.setTickets(eventId, selections)\n * checkout.setBilling(b)\n * await checkout.placeOrder('card') // <CardInput/> rendered\n */\nimport {\n useCheckout as useSharedCheckout,\n type CheckoutOptions,\n type CheckoutPorts,\n type UseCheckout,\n} from 'tf-checkout-shared'\n\nimport { rnConfirmer, rnPorts } from './instance'\n\nexport interface UseCheckoutOptions {\n /** Extra platform ports merged over the native defaults (e.g. an injected\n * WebView `providerPage`, or an MSI `onInstallmentOffers` picker). */\n ports?: Omit<CheckoutPorts, 'confirmer'>\n /** Wallet/redirect engine options (merchant identity, deep-link scheme). */\n options?: CheckoutOptions\n}\n\nexport const useCheckout = (opts: UseCheckoutOptions = {}): UseCheckout =>\n useSharedCheckout({\n ports: { confirmer: rnConfirmer, ...rnPorts, ...opts.ports },\n options: opts.options,\n })\n","/**\n * React Native storage adapter for the SDK's token/session store.\n *\n * The shared transport reads/writes tokens through a SYNCHRONOUS `StorageAdapter`\n * (see tf-checkout-shared `client/storage.ts`). Web hands it a `localStorage`\n * adapter; the native side needs a synchronous, persisted store so the buyer's\n * bearer session survives an app restart. `react-native-mmkv` is exactly that —\n * synchronous get/set/delete backed by native MMKV — so we wrap it here.\n *\n * Unlike web, native has no session cookie: the bearer token IS the session, so\n * `configureCheckout` defaults to this persisted adapter (never in-memory) so a\n * signed-in buyer stays signed in between launches.\n */\nimport { MMKV } from 'react-native-mmkv'\n\nimport type { StorageAdapter } from 'tf-checkout-shared'\n\n/** Build a `StorageAdapter` backed by an MMKV instance (its own `id` namespace\n * so it never collides with the host app's MMKV data). */\nexport const createMmkvStorage = (id = 'tf-checkout'): StorageAdapter => {\n const mmkv = new MMKV({ id })\n return {\n getItem: (key) => mmkv.getString(key) ?? null,\n setItem: (key, value) => mmkv.set(key, value),\n removeItem: (key) => mmkv.delete(key),\n }\n}\n","/**\n * One-time SDK setup for React Native. Wraps the shared `configure()` and\n * defaults the token store to a persisted MMKV adapter. Call once at app\n * start, before any `useCheckout`/`ttf` call:\n *\n * configureCheckout({ env: 'PROD', clientId, clientSecret })\n *\n * `cookieAuth` defaults ON: native sign-in must ride the legacy cookie-session\n * flow (`POST /auth`), NOT the OAuth bearer chain. The cart lives in the\n * backend session, and a bearer request without a guest header is moved onto a\n * synthetic empty session — so a buyer who reserves tickets and then logs in\n * mid-checkout would lose the cart (\"The cart is expired\"). On the cookie flow\n * no bearer is ever minted, the session that holds the cart stays put, and the\n * X-TF-ECOMMERCE ticket is persisted to MMKV (the shared cookie shim falls\n * back to the storage adapter off-browser) so sign-in survives a relaunch.\n * Pass `cookieAuth: false` to opt back into the bearer chain.\n */\nimport { configure, type TtfConfig } from 'tf-checkout-shared'\n\nimport { createMmkvStorage } from './storage'\n\n/** Persisted MMKV-backed token store, shared by every configure call. */\nexport const mmkvStorageAdapter = createMmkvStorage()\n\nexport const configureCheckout = (config: TtfConfig): void =>\n configure({ storage: mmkvStorageAdapter, cookieAuth: true, ...config })\n","/**\n * `<CardInput/>` — the native card field. The RN analogue of the web\n * `CardInput`, but simpler: `@stripe/stripe-react-native`'s `<CardField/>` feeds\n * card data straight into `confirmPayment` natively, so there is no element to\n * register with the confirmer — just mount this inside the payment step and\n * report completeness up so the pay button can gate on it.\n *\n * The native SDK must be initialized first; the engine does that during prime\n * (`confirmer.init` → `initStripe`), which always runs before the payment step\n * is reached.\n */\nimport React, { type FC } from 'react'\nimport { StyleSheet } from 'react-native'\nimport { CardField } from '@stripe/stripe-react-native'\n\nimport { useTheme } from './ui/CheckoutProvider'\n\nexport interface CardInputProps {\n /** Fires with the field's completeness so the payment CTA can enable/disable. */\n onComplete?: (complete: boolean) => void\n}\n\nexport const CardInput: FC<CardInputProps> = ({ onComplete }) => {\n const theme = useTheme()\n return (\n <CardField\n postalCodeEnabled={false}\n // Set explicitly and neutrally: stripe-react-native's own default number\n // placeholder is a Stripe TEST PAN, which reads to a real buyer as an\n // instruction to type it. Matches the web field's \"Card number\". Demo\n // copy belongs behind `<Payment showTestCardHint />`, not in the field.\n placeholders={{ number: 'Card number' }}\n cardStyle={{\n backgroundColor: theme.surface,\n textColor: theme.text,\n placeholderColor: theme.muted,\n borderColor: theme.border,\n borderWidth: 1,\n borderRadius: theme.radiusControl,\n }}\n style={styles.field}\n onCardChange={(details) => onComplete?.(details.complete)}\n />\n )\n}\n\nconst styles = StyleSheet.create({\n field: { height: 50, marginVertical: 4 },\n})\n","/**\n * `<CheckoutProvider>` — wrap your checkout UI once. The RN analogue of the web\n * provider. It:\n * - provides the checkout to every section via context (so `<Tickets/>`,\n * `<Payment/>`, … just read it). By default it runs `useCheckout()` (the\n * native-wired engine: stripe-react-native + shared store); pass your own\n * instance as `value` to bring your own.\n * - resolves the `theme` token set and exposes it via `useTheme()`.\n * - coordinates submit-attempt validation across separately composed sections.\n * - bundles a `QueryClientProvider` (the shared react-query hooks need one).\n *\n * Unlike web there are no CSS variables and no DOM scroll-to-invalid — sections\n * read `attempt` to reveal their own errors on a failed submit.\n */\nimport React, {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useState,\n type FC,\n type ReactNode,\n} from 'react'\n\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query'\n\nimport type { UseCheckout } from 'tf-checkout-shared'\n\nimport { useCheckout } from '../useCheckout'\nimport { useInstallmentPicker } from './InstallmentPicker'\nimport { resolveTheme, type CheckoutTheme, type ResolvedTheme } from './theme'\n\nconst CheckoutCtx = createContext<UseCheckout | null>(null)\nconst ThemeCtx = createContext<ResolvedTheme>(resolveTheme())\nconst ValidationCtx = createContext<{\n attempt: number\n requestValidation: () => void\n} | null>(null)\n\n/** One shared react-query client for the whole checkout — created lazily so it\n * survives across mounts (matching the app-wide engine store singleton). */\nlet sharedQueryClient: QueryClient | null = null\nconst getQueryClient = (): QueryClient => {\n if (!sharedQueryClient) {\n sharedQueryClient = new QueryClient({\n defaultOptions: { queries: { retry: 1, staleTime: 60_000 } },\n })\n }\n return sharedQueryClient\n}\n\nexport interface CheckoutProviderProps {\n /**\n * Bring your own checkout instance (from a top-level `useCheckout()`). Omit\n * and the provider runs `useCheckout()` itself. Either way the sections read\n * the same shared cart (the engine store is a module singleton).\n */\n value?: UseCheckout\n /** Retheme via design tokens. */\n theme?: CheckoutTheme\n /** Provide your own react-query client instead of the bundled shared one. */\n queryClient?: QueryClient\n children: ReactNode\n}\n\n/** The context boundary — given a resolved checkout instance + theme. */\nconst CheckoutRoot: FC<{\n checkout: UseCheckout\n theme?: CheckoutTheme\n children: ReactNode\n}> = ({ checkout, theme, children }) => {\n const [attempt, setAttempt] = useState(0)\n const requestValidation = useCallback(() => setAttempt((n) => n + 1), [])\n const validation = useMemo(\n () => ({ attempt, requestValidation }),\n [attempt, requestValidation]\n )\n const resolved = useMemo(() => resolveTheme(theme), [theme])\n\n return (\n <CheckoutCtx.Provider value={checkout}>\n <ThemeCtx.Provider value={resolved}>\n <ValidationCtx.Provider value={validation}>{children}</ValidationCtx.Provider>\n </ThemeCtx.Provider>\n </CheckoutCtx.Provider>\n )\n}\n\n/** Default path: the provider owns the `useCheckout()` call. */\nconst SelfProvidedCheckout: FC<Omit<CheckoutProviderProps, 'value' | 'queryClient'>> = ({\n children,\n ...rest\n}) => {\n // Bridge the engine's mid-payment MSI (installments) callback to a native modal.\n const { onInstallmentOffers, picker } = useInstallmentPicker()\n const checkout = useCheckout({ ports: { onInstallmentOffers } })\n return (\n <CheckoutRoot checkout={checkout} {...rest}>\n {children}\n {picker}\n </CheckoutRoot>\n )\n}\n\nexport const CheckoutProvider: FC<CheckoutProviderProps> = ({\n value,\n queryClient,\n ...rest\n}) => (\n // `value` present ⇒ don't call `useCheckout()` (no second binding); absent ⇒\n // the self-providing branch owns it. The choice is static per mount.\n <QueryClientProvider client={queryClient ?? getQueryClient()}>\n {value ? (\n <CheckoutRoot checkout={value} {...rest} />\n ) : (\n <SelfProvidedCheckout {...rest} />\n )}\n </QueryClientProvider>\n)\n\n/** Read the shared checkout inside any component under `<CheckoutProvider>`. */\nexport const useCheckoutContext = (): UseCheckout => {\n const ctx = useContext(CheckoutCtx)\n if (!ctx) {\n throw new Error('useCheckoutContext must be used within <CheckoutProvider>.')\n }\n return ctx\n}\n\n/** Read the resolved theme tokens. */\nexport const useTheme = (): ResolvedTheme => useContext(ThemeCtx)\n\n/** Coordinate submit-attempt validation across separately composed sections. */\nexport const useCheckoutValidation = () => {\n const ctx = useContext(ValidationCtx)\n if (!ctx) {\n throw new Error('useCheckoutValidation must be used within <CheckoutProvider>.')\n }\n return ctx\n}\n","/**\n * MSI (meses sin intereses) picker — the RN analogue of the web\n * `useInstallmentPicker`. Mexican card payments can be split into interest-free\n * installments: mid-payment the engine calls the `onInstallmentOffers` port with\n * the available plans and waits for the buyer's choice. This hook bridges that\n * callback to a native modal — returns the port + a `picker` element to render.\n *\n * Wiring: like web, the provider owns this. To turn MSI on, `SelfProvidedCheckout`\n * in `ui/CheckoutProvider.tsx` should do the same two lines the web provider does:\n *\n * const { onInstallmentOffers, picker } = useInstallmentPicker()\n * const checkout = useCheckout({ ports: { onInstallmentOffers } })\n * return <CheckoutRoot checkout={checkout}>{children}{picker}</CheckoutRoot>\n *\n * The native `useCheckout` already accepts `ports.onInstallmentOffers` (it's part\n * of `Omit<CheckoutPorts,'confirmer'>`), so no engine change is needed — only the\n * provider hook-up. Left as a provider follow-up so this slice stays scoped to\n * the payment section + this self-contained hook/modal.\n */\nimport React, { useCallback, useMemo, useState } from 'react'\nimport { Modal, Pressable, StyleSheet, Text, View } from 'react-native'\n\nimport type { InstallmentOffer } from 'tf-checkout-shared'\n\nimport { useTheme } from './CheckoutProvider'\nimport { Button } from './primitives'\nimport type { ResolvedTheme } from './theme'\n\nexport const useInstallmentPicker = () => {\n const [pending, setPending] = useState<{\n offers: InstallmentOffer[]\n resolve: (offer: InstallmentOffer | null) => void\n } | null>(null)\n\n // Stable across renders (useCheckout reads ports once) — resolves when the\n // buyer picks a plan (or declines) below.\n const onInstallmentOffers = useCallback(\n (offers: InstallmentOffer[]) =>\n new Promise<InstallmentOffer | null>((resolve) => setPending({ offers, resolve })),\n []\n )\n\n const choose = (offer: InstallmentOffer | null) => {\n pending?.resolve(offer)\n setPending(null)\n }\n\n const picker = (\n <InstallmentModal\n offers={pending?.offers ?? null}\n onChoose={choose}\n onClose={() => choose(null)}\n />\n )\n\n return { onInstallmentOffers, picker }\n}\n\nconst InstallmentModal: React.FC<{\n offers: InstallmentOffer[] | null\n onChoose: (offer: InstallmentOffer | null) => void\n onClose: () => void\n}> = ({ offers, onChoose, onClose }) => {\n const theme = useTheme()\n const s = useStyles(theme)\n return (\n <Modal\n visible={offers !== null}\n transparent\n animationType=\"fade\"\n onRequestClose={onClose}\n >\n <Pressable style={s.backdrop} onPress={onClose}>\n <Pressable style={s.box} onPress={() => {}}>\n <Text style={s.title} accessibilityRole=\"header\">\n Pay in installments?\n </Text>\n <View style={s.list}>\n {(offers ?? []).map((offer, i) => (\n <Pressable\n key={i}\n accessibilityRole=\"button\"\n style={({ pressed }) => [s.option, pressed && s.optionPressed]}\n onPress={() => onChoose(offer)}\n >\n <Text style={s.optionMain}>\n {offer.count} ×{' '}\n {offer.per_installment_formatted ?? offer.per_installment}\n </Text>\n <Text style={s.optionMeta}>\n {offer.total_formatted ? `${offer.total_formatted} total` : ''}\n {offer.diff_from_original_formatted\n ? ` · ${offer.diff_from_original_formatted}`\n : ''}\n </Text>\n </Pressable>\n ))}\n </View>\n <Button variant=\"ghost\" onPress={() => onChoose(null)}>\n Pay in full instead\n </Button>\n </Pressable>\n </Pressable>\n </Modal>\n )\n}\n\nconst useStyles = (theme: ResolvedTheme) =>\n useMemo(\n () =>\n StyleSheet.create({\n backdrop: {\n flex: 1,\n backgroundColor: 'rgba(0,0,0,0.4)',\n alignItems: 'center',\n justifyContent: 'center',\n padding: 24,\n },\n box: {\n width: '100%',\n maxWidth: 420,\n backgroundColor: theme.surface,\n borderRadius: theme.radiusCard,\n borderWidth: StyleSheet.hairlineWidth,\n borderColor: theme.border,\n padding: 16,\n gap: 12,\n },\n title: {\n color: theme.text,\n fontSize: theme.fontSize + 2,\n fontWeight: '700',\n fontFamily: theme.fontFamily,\n },\n list: { gap: 8 },\n option: {\n borderWidth: StyleSheet.hairlineWidth,\n borderColor: theme.border,\n borderRadius: theme.radiusControl,\n paddingVertical: 12,\n paddingHorizontal: 14,\n gap: 2,\n },\n optionPressed: { borderColor: theme.accent, opacity: 0.9 },\n optionMain: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n optionMeta: {\n color: theme.muted,\n fontSize: theme.fontSize - 2,\n fontFamily: theme.fontFamily,\n },\n }),\n [theme]\n )\n","/**\n * Native UI primitives — the RN analogues of the web `ui/` presentation\n * components (`Button`, `Card`, `SectionHeader`, `Loader`, …). All theme-aware\n * via `useTheme()`; no CSS, just `StyleSheet` built from the resolved tokens.\n */\nimport React, { useMemo, type FC, type ReactNode } from 'react'\nimport {\n ActivityIndicator,\n Pressable,\n StyleSheet,\n Text,\n View,\n type StyleProp,\n type TextStyle,\n type ViewStyle,\n} from 'react-native'\n\nimport { useTheme } from './CheckoutProvider'\nimport type { ResolvedTheme } from './theme'\n\n/** Small spinner. */\nexport const Loader: FC<{ size?: 'small' | 'large'; color?: string }> = ({\n size = 'small',\n color,\n}) => {\n const theme = useTheme()\n return <ActivityIndicator size={size} color={color ?? theme.accent} />\n}\n\n/** A titled surface — the RN `Card` + `SectionHeader`. */\nexport const Card: FC<{ children: ReactNode; style?: StyleProp<ViewStyle> }> = ({\n children,\n style,\n}) => {\n const theme = useTheme()\n const s = useStyles(theme)\n return <View style={[s.card, style]}>{children}</View>\n}\n\nexport const SectionHeader: FC<{ title: string; subtitle?: string }> = ({\n title,\n subtitle,\n}) => {\n const theme = useTheme()\n const s = useStyles(theme)\n return (\n <View style={s.sectionHeader}>\n <Text style={s.sectionTitle}>{title}</Text>\n {subtitle ? <Text style={s.sectionSubtitle}>{subtitle}</Text> : null}\n </View>\n )\n}\n\nexport const Divider: FC = () => {\n const theme = useTheme()\n const s = useStyles(theme)\n return <View style={s.divider} />\n}\n\n/** Body / muted / title text helpers so sections don't re-derive colors. */\nexport const BodyText: FC<{ children: ReactNode; style?: StyleProp<TextStyle> }> = ({\n children,\n style,\n}) => {\n const theme = useTheme()\n const s = useStyles(theme)\n return <Text style={[s.body, style]}>{children}</Text>\n}\n\nexport const MutedText: FC<{ children: ReactNode; style?: StyleProp<TextStyle> }> = ({\n children,\n style,\n}) => {\n const theme = useTheme()\n const s = useStyles(theme)\n return <Text style={[s.muted, style]}>{children}</Text>\n}\n\nexport const ErrorText: FC<{ children: ReactNode }> = ({ children }) => {\n const theme = useTheme()\n const s = useStyles(theme)\n return <Text style={s.errorText}>{children}</Text>\n}\n\nexport interface ButtonProps {\n onPress: () => void\n children: ReactNode\n loading?: boolean\n disabled?: boolean\n variant?: 'primary' | 'ghost'\n}\n\nexport const Button: FC<ButtonProps> = ({\n onPress,\n children,\n loading = false,\n disabled = false,\n variant = 'primary',\n}) => {\n const theme = useTheme()\n const s = useStyles(theme)\n const isDisabled = disabled || loading\n const ghost = variant === 'ghost'\n return (\n <Pressable\n accessibilityRole=\"button\"\n accessibilityState={{ disabled: isDisabled, busy: loading }}\n disabled={isDisabled}\n onPress={onPress}\n style={({ pressed }) => [\n s.button,\n ghost && s.buttonGhost,\n isDisabled && s.buttonDisabled,\n pressed && !isDisabled && s.buttonPressed,\n ]}\n >\n {loading ? (\n <ActivityIndicator\n size=\"small\"\n color={ghost ? theme.accent : theme.accentContrast}\n />\n ) : (\n <Text style={[s.buttonLabel, ghost && s.buttonLabelGhost]}>{children}</Text>\n )}\n </Pressable>\n )\n}\n\n/** Build the primitive stylesheet from the resolved theme (memoized per theme). */\nexport const useStyles = (theme: ResolvedTheme) =>\n useMemo(\n () =>\n StyleSheet.create({\n card: {\n backgroundColor: theme.surface,\n borderColor: theme.border,\n borderWidth: StyleSheet.hairlineWidth,\n borderRadius: theme.radiusCard,\n padding: 16,\n gap: 12,\n },\n sectionHeader: { gap: 2 },\n sectionTitle: {\n color: theme.text,\n fontSize: theme.fontSize + 2,\n fontWeight: '700',\n fontFamily: theme.fontFamily,\n },\n sectionSubtitle: {\n color: theme.muted,\n fontSize: theme.fontSize - 2,\n fontFamily: theme.fontFamily,\n },\n divider: { height: StyleSheet.hairlineWidth, backgroundColor: theme.border },\n body: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontFamily: theme.fontFamily,\n },\n muted: {\n color: theme.muted,\n fontSize: theme.fontSize - 1,\n fontFamily: theme.fontFamily,\n },\n errorText: { color: theme.error, fontSize: theme.fontSize - 2 },\n button: {\n backgroundColor: theme.accent,\n borderRadius: theme.radiusControl,\n paddingVertical: 14,\n paddingHorizontal: 20,\n alignItems: 'center',\n justifyContent: 'center',\n minHeight: 48,\n },\n buttonGhost: {\n backgroundColor: 'transparent',\n borderWidth: StyleSheet.hairlineWidth,\n borderColor: theme.border,\n },\n buttonDisabled: { opacity: 0.5 },\n buttonPressed: { opacity: 0.85 },\n buttonLabel: {\n color: theme.accentContrast,\n fontSize: theme.fontSize,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n buttonLabelGhost: { color: theme.text },\n }),\n [theme]\n )\n","/**\n * The native checkout theme — the RN analogue of the web `theme.ts`. Web maps\n * tokens to `--tf-checkout-*` CSS variables; RN has no CSS variables, so a theme\n * is a plain JS token object resolved (partial-over-default) at the provider and\n * read through `useTheme()`. Pass any subset to `<CheckoutProvider theme={…}>`.\n */\n\nexport interface CheckoutTheme {\n /** Force a palette. Omit to follow the base light palette. */\n colorScheme?: 'light' | 'dark'\n /** Primary color — buttons, selected states, focus. */\n accent?: string\n /** Text/icon color on top of `accent`. */\n accentContrast?: string\n /** Card background. */\n surface?: string\n /** Subtle fill (summary rows, muted pills). */\n surfaceMuted?: string\n /** Screen background behind the cards. */\n background?: string\n /** Primary text. */\n text?: string\n /** Secondary text (labels, hints, \"incl. fees\"). */\n muted?: string\n /** Borders + dividers. */\n border?: string\n /** Error text + invalid field borders. */\n error?: string\n /** Success (confirmation check). */\n success?: string\n /** Corner radius for cards. */\n radiusCard?: number\n /** Corner radius for inputs / buttons. */\n radiusControl?: number\n /** Base font size. */\n fontSize?: number\n /** Font family for the whole component tree (optional). */\n fontFamily?: string\n}\n\n/** A theme with every token resolved to a concrete value — what components read. */\nexport type ResolvedTheme = Required<\n Omit<CheckoutTheme, 'colorScheme' | 'fontFamily'>\n> & {\n colorScheme: 'light' | 'dark'\n fontFamily?: string\n}\n\nconst LIGHT: ResolvedTheme = {\n colorScheme: 'light',\n accent: '#111827',\n accentContrast: '#ffffff',\n surface: '#ffffff',\n surfaceMuted: '#f5f5fa',\n background: '#ffffff',\n text: '#111827',\n muted: '#6b7280',\n border: '#e5e7eb',\n error: '#d9534f',\n success: '#139679',\n radiusCard: 12,\n radiusControl: 10,\n fontSize: 15,\n}\n\nconst DARK: ResolvedTheme = {\n ...LIGHT,\n colorScheme: 'dark',\n accent: '#818cf8',\n accentContrast: '#111827',\n surface: '#1b1b2b',\n surfaceMuted: '#23233a',\n background: '#101018',\n text: '#f5f5fa',\n muted: '#9ca3af',\n border: '#33334d',\n}\n\n/** Merge a partial theme over the light/dark base into a concrete token set. */\nexport const resolveTheme = (theme?: CheckoutTheme): ResolvedTheme => {\n const base = theme?.colorScheme === 'dark' ? DARK : LIGHT\n if (!theme) return base\n const out: ResolvedTheme = { ...base }\n for (const key of Object.keys(theme) as (keyof CheckoutTheme)[]) {\n const value = theme[key]\n if (value !== undefined) (out as Record<string, unknown>)[key] = value\n }\n return out\n}\n","/**\n * Native form controls — the RN analogues of the web `Field` / `Input` /\n * `Checkbox`. Theme-aware; `Field` renders a label + the control + an inline\n * error, and marks itself invalid so submit-attempt validation can reveal it.\n */\nimport React, { useMemo, useState, type FC, type ReactNode } from 'react'\nimport {\n Pressable,\n StyleSheet,\n Text,\n TextInput,\n View,\n type KeyboardTypeOptions,\n} from 'react-native'\n\nimport { useTheme } from './CheckoutProvider'\nimport type { ResolvedTheme } from './theme'\n\nexport const Field: FC<{\n label?: string\n error?: string\n required?: boolean\n children: ReactNode\n}> = ({ label, error, required, children }) => {\n const theme = useTheme()\n const s = useFieldStyles(theme)\n return (\n <View style={s.field}>\n {label ? (\n <Text style={s.label}>\n {label}\n {required ? <Text style={s.required}> *</Text> : null}\n </Text>\n ) : null}\n {children}\n {error ? <Text style={s.error}>{error}</Text> : null}\n </View>\n )\n}\n\nexport interface InputProps {\n value: string\n onChangeText: (text: string) => void\n placeholder?: string\n keyboardType?: KeyboardTypeOptions\n autoCapitalize?: 'none' | 'sentences' | 'words' | 'characters'\n secureTextEntry?: boolean\n editable?: boolean\n invalid?: boolean\n onBlur?: () => void\n}\n\nexport const Input: FC<InputProps> = ({\n value,\n onChangeText,\n placeholder,\n keyboardType,\n autoCapitalize = 'sentences',\n secureTextEntry,\n editable = true,\n invalid = false,\n onBlur,\n}) => {\n const theme = useTheme()\n const s = useFieldStyles(theme)\n const [focused, setFocused] = useState(false)\n return (\n <TextInput\n style={[\n s.input,\n focused && s.inputFocused,\n invalid && s.inputInvalid,\n !editable && s.inputDisabled,\n ]}\n value={value}\n onChangeText={onChangeText}\n placeholder={placeholder}\n placeholderTextColor={theme.muted}\n keyboardType={keyboardType}\n autoCapitalize={autoCapitalize}\n autoCorrect={false}\n secureTextEntry={secureTextEntry}\n editable={editable}\n onFocus={() => setFocused(true)}\n onBlur={() => {\n setFocused(false)\n onBlur?.()\n }}\n />\n )\n}\n\nexport const Checkbox: FC<{\n checked: boolean\n onChange: (checked: boolean) => void\n label: ReactNode\n invalid?: boolean\n}> = ({ checked, onChange, label, invalid = false }) => {\n const theme = useTheme()\n const s = useFieldStyles(theme)\n return (\n <Pressable\n accessibilityRole=\"checkbox\"\n accessibilityState={{ checked }}\n onPress={() => onChange(!checked)}\n style={s.checkboxRow}\n >\n <View\n style={[\n s.checkboxBox,\n checked && s.checkboxBoxChecked,\n invalid && !checked && s.checkboxBoxInvalid,\n ]}\n >\n {checked ? <Text style={s.checkboxMark}>✓</Text> : null}\n </View>\n {typeof label === 'string' ? <Text style={s.checkboxLabel}>{label}</Text> : label}\n </Pressable>\n )\n}\n\nconst useFieldStyles = (theme: ResolvedTheme) =>\n useMemo(\n () =>\n StyleSheet.create({\n field: { gap: 6 },\n label: {\n color: theme.muted,\n fontSize: theme.fontSize - 2,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n required: { color: theme.error },\n error: { color: theme.error, fontSize: theme.fontSize - 3 },\n input: {\n borderWidth: StyleSheet.hairlineWidth,\n borderColor: theme.border,\n borderRadius: theme.radiusControl,\n paddingHorizontal: 12,\n paddingVertical: 12,\n color: theme.text,\n fontSize: theme.fontSize,\n backgroundColor: theme.surface,\n fontFamily: theme.fontFamily,\n },\n inputFocused: { borderColor: theme.accent },\n inputInvalid: { borderColor: theme.error },\n inputDisabled: { backgroundColor: theme.surfaceMuted, color: theme.muted },\n checkboxRow: { flexDirection: 'row', alignItems: 'flex-start', gap: 10 },\n checkboxBox: {\n width: 22,\n height: 22,\n borderRadius: 6,\n borderWidth: StyleSheet.hairlineWidth,\n borderColor: theme.border,\n alignItems: 'center',\n justifyContent: 'center',\n backgroundColor: theme.surface,\n },\n checkboxBoxChecked: { backgroundColor: theme.accent, borderColor: theme.accent },\n checkboxBoxInvalid: { borderColor: theme.error },\n checkboxMark: { color: theme.accentContrast, fontSize: 14, fontWeight: '700' },\n checkboxLabel: {\n flex: 1,\n color: theme.text,\n fontSize: theme.fontSize - 1,\n fontFamily: theme.fontFamily,\n },\n }),\n [theme]\n )\n","/**\n * Native `<Select/>` — the RN analogue of the web `Field` `Select`. There is no\n * DOM `<select>` on native, so this is a themed pressable that opens a modal\n * list of options. Generic over the option value so callers keep type-safety\n * (country ids, gender codes, currency codes, ISO dates, …).\n */\nimport React, { useMemo, useState } from 'react'\nimport { FlatList, Modal, Pressable, StyleSheet, Text, View } from 'react-native'\n\nimport { useTheme } from './CheckoutProvider'\nimport type { ResolvedTheme } from './theme'\n\nexport interface SelectOption<T = string> {\n label: string\n value: T\n}\n\nexport function Select<T = string>({\n value,\n onChange,\n options,\n placeholder = 'Select…',\n invalid = false,\n disabled = false,\n}: {\n value: T | null | undefined\n onChange: (value: T) => void\n options: SelectOption<T>[]\n placeholder?: string\n invalid?: boolean\n disabled?: boolean\n}) {\n const theme = useTheme()\n const s = useSelectStyles(theme)\n const [open, setOpen] = useState(false)\n\n const selected = options.find((o) => o.value === value)\n\n return (\n <>\n <Pressable\n accessibilityRole=\"button\"\n disabled={disabled}\n onPress={() => setOpen(true)}\n style={[s.control, invalid && s.controlInvalid, disabled && s.controlDisabled]}\n >\n <Text style={[s.value, !selected && s.placeholder]} numberOfLines={1}>\n {selected ? selected.label : placeholder}\n </Text>\n <Text style={s.chevron}>▾</Text>\n </Pressable>\n\n <Modal\n visible={open}\n transparent\n animationType=\"fade\"\n onRequestClose={() => setOpen(false)}\n >\n <Pressable style={s.backdrop} onPress={() => setOpen(false)}>\n <Pressable style={s.sheet} onPress={() => {}}>\n <FlatList\n data={options}\n keyExtractor={(item, i) => `${String(item.value)}:${i}`}\n keyboardShouldPersistTaps=\"handled\"\n renderItem={({ item }) => {\n const isSelected = item.value === value\n return (\n <Pressable\n style={s.option}\n onPress={() => {\n onChange(item.value)\n setOpen(false)\n }}\n >\n <Text style={[s.optionLabel, isSelected && s.optionLabelSelected]}>\n {item.label}\n </Text>\n {isSelected ? <Text style={s.optionCheck}>✓</Text> : null}\n </Pressable>\n )\n }}\n ItemSeparatorComponent={() => <View style={s.sep} />}\n />\n </Pressable>\n </Pressable>\n </Modal>\n </>\n )\n}\n\nconst useSelectStyles = (theme: ResolvedTheme) =>\n useMemo(\n () =>\n StyleSheet.create({\n control: {\n flexDirection: 'row',\n alignItems: 'center',\n justifyContent: 'space-between',\n borderWidth: StyleSheet.hairlineWidth,\n borderColor: theme.border,\n borderRadius: theme.radiusControl,\n paddingHorizontal: 12,\n paddingVertical: 12,\n backgroundColor: theme.surface,\n gap: 8,\n },\n controlInvalid: { borderColor: theme.error },\n controlDisabled: { backgroundColor: theme.surfaceMuted },\n value: {\n flex: 1,\n color: theme.text,\n fontSize: theme.fontSize,\n fontFamily: theme.fontFamily,\n },\n placeholder: { color: theme.muted },\n chevron: { color: theme.muted, fontSize: theme.fontSize },\n backdrop: {\n flex: 1,\n backgroundColor: 'rgba(0,0,0,0.4)',\n justifyContent: 'flex-end',\n },\n sheet: {\n backgroundColor: theme.surface,\n borderTopLeftRadius: theme.radiusCard,\n borderTopRightRadius: theme.radiusCard,\n maxHeight: '70%',\n paddingVertical: 8,\n },\n option: {\n flexDirection: 'row',\n alignItems: 'center',\n justifyContent: 'space-between',\n paddingHorizontal: 20,\n paddingVertical: 14,\n gap: 12,\n },\n optionLabel: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontFamily: theme.fontFamily,\n },\n optionLabelSelected: { color: theme.accent, fontWeight: '700' },\n optionCheck: { color: theme.accent, fontSize: theme.fontSize, fontWeight: '700' },\n sep: {\n height: StyleSheet.hairlineWidth,\n backgroundColor: theme.border,\n marginHorizontal: 20,\n },\n }),\n [theme]\n )\n","/**\n * `<QuantitySelect>` — a compact ± stepper for choosing a quantity. The RN\n * analogue of the web `QuantitySelect` (a 0…max dropdown); native has no DOM\n * `<select>`, so this reuses the stepper look the native ticket screen used\n * (minus / value / plus). Same API as the web control:\n * `{ value, onChange, min, max, step, disabled }`.\n */\nimport React, { useMemo, type FC } from 'react'\nimport { Pressable, StyleSheet, Text, View } from 'react-native'\n\nimport { useTheme } from './CheckoutProvider'\nimport type { ResolvedTheme } from './theme'\n\nexport interface QuantitySelectProps {\n value: number\n onChange: (value: number) => void\n /** Minimum purchasable quantity when buying (0 = none is always allowed). */\n min?: number\n max?: number\n /** Step between quantities (the old checkout's `multiplier`). */\n step?: number\n disabled?: boolean\n}\n\nexport const QuantitySelect: FC<QuantitySelectProps> = ({\n value,\n onChange,\n min = 0,\n max = 10,\n step = 1,\n disabled = false,\n}) => {\n const theme = useTheme()\n const s = useQuantityStyles(theme)\n // 0 (buy none) is always offered; the first non-zero step honors the type's\n // minimum, then steps up to the cap — mirroring the web dropdown's option grid\n // (0, lo, lo + step, …) so a min-2 type goes 0 → 2 → 3, never 0 → 1.\n const lo = Math.max(1, min)\n const cap = Math.min(max, 50)\n const atZero = value <= 0\n const atCap = value >= cap\n\n const dec = () => {\n if (disabled) return\n onChange(value <= lo ? 0 : Math.max(lo, value - step))\n }\n const inc = () => {\n if (disabled) return\n onChange(value === 0 ? Math.min(cap, lo) : Math.min(cap, value + step))\n }\n\n return (\n <View style={s.stepper}>\n <Pressable\n accessibilityRole=\"button\"\n accessibilityLabel=\"Remove one\"\n disabled={disabled || atZero}\n onPress={dec}\n style={[s.btn, (disabled || atZero) && s.btnDisabled]}\n >\n <Text style={s.glyph}>−</Text>\n </Pressable>\n <Text style={s.value}>{value}</Text>\n <Pressable\n accessibilityRole=\"button\"\n accessibilityLabel=\"Add one\"\n disabled={disabled || atCap}\n onPress={inc}\n style={[s.btn, (disabled || atCap) && s.btnDisabled]}\n >\n <Text style={s.glyph}>+</Text>\n </Pressable>\n </View>\n )\n}\n\nconst useQuantityStyles = (theme: ResolvedTheme) =>\n useMemo(\n () =>\n StyleSheet.create({\n stepper: { flexDirection: 'row', alignItems: 'center', gap: 14 },\n btn: {\n width: 36,\n height: 36,\n borderRadius: 18,\n borderWidth: StyleSheet.hairlineWidth,\n borderColor: theme.border,\n alignItems: 'center',\n justifyContent: 'center',\n },\n btnDisabled: { opacity: 0.4 },\n glyph: { color: theme.text, fontSize: 20, fontWeight: '600', lineHeight: 22 },\n value: {\n minWidth: 24,\n textAlign: 'center',\n color: theme.text,\n fontSize: theme.fontSize,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n }),\n [theme]\n )\n","/**\n * `<Timer>` — a reservation countdown label. RN analogue of the web `Timer`.\n * Pass `checkout.secondsLeft`. Renders \"h:mm:ss\" (≥ 1h) or \"m:ss\", turning\n * urgent (error color) at/under `urgentAt` seconds.\n */\nimport React, { useMemo, type FC, type ReactNode } from 'react'\nimport { StyleSheet, Text, View } from 'react-native'\n\nimport { useTheme } from './CheckoutProvider'\nimport type { ResolvedTheme } from './theme'\n\nconst clock = (s: number): string => {\n const v = Math.max(0, Math.floor(s))\n return v >= 3600\n ? `${Math.floor(v / 3600)}:${String(Math.floor((v % 3600) / 60)).padStart(\n 2,\n '0'\n )}:${String(v % 60).padStart(2, '0')}`\n : `${Math.floor(v / 60)}:${String(v % 60).padStart(2, '0')}`\n}\n\nexport interface TimerProps {\n seconds: number\n /** Below this many seconds it turns urgent (default 60). */\n urgentAt?: number\n /** Text before the clock, e.g. \"Reserved for\". */\n label?: ReactNode\n}\n\nexport const Timer: FC<TimerProps> = ({ seconds, urgentAt = 60, label }) => {\n const theme = useTheme()\n const s = useTimerStyles(theme)\n const urgent = seconds <= urgentAt\n return (\n <View style={s.row}>\n {/* A string label must be wrapped in <Text> on native; a node renders as-is. */}\n {label != null ? (\n typeof label === 'string' ? (\n <Text style={s.label}>{label}</Text>\n ) : (\n label\n )\n ) : null}\n <Text style={[s.clock, urgent && s.clockUrgent]}>{clock(seconds)}</Text>\n </View>\n )\n}\n\nconst useTimerStyles = (theme: ResolvedTheme) =>\n useMemo(\n () =>\n StyleSheet.create({\n row: { flexDirection: 'row', alignItems: 'center', gap: 6 },\n label: {\n color: theme.muted,\n fontSize: theme.fontSize - 1,\n fontFamily: theme.fontFamily,\n },\n clock: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontWeight: '700',\n fontVariant: ['tabular-nums'],\n fontFamily: theme.fontFamily,\n },\n clockUrgent: { color: theme.error },\n }),\n [theme]\n )\n","/**\n * `<TimerBanner>` — the dismissible reservation-countdown banner the old\n * checkout showed atop the add-ons / billing / payment steps. RN analogue of the\n * web `TimerBanner`: feed it `checkout.secondsLeft` and it renders the message +\n * \"mm:ss\" with an × to dismiss. Renders nothing when there's no live reservation\n * (`seconds` undefined / ≤ 0) or once dismissed.\n */\nimport React, { useMemo, useState, type FC } from 'react'\nimport { Pressable, StyleSheet, Text, View } from 'react-native'\n\nimport { useTheme } from './CheckoutProvider'\nimport type { ResolvedTheme } from './theme'\n\nconst clock = (s: number): string => {\n const m = String(Math.floor(s / 60)).padStart(2, '0')\n const ss = String(s % 60).padStart(2, '0')\n return `${m}:${ss}`\n}\n\nexport interface TimerBannerProps {\n seconds?: number\n /** Show urgent styling at/under this many seconds. Default 60. */\n urgentAt?: number\n message?: string\n}\n\nexport const TimerBanner: FC<TimerBannerProps> = ({\n seconds,\n urgentAt = 60,\n message = 'Please complete your purchase before the timer reaches zero.',\n}) => {\n const theme = useTheme()\n const s = useBannerStyles(theme)\n const [dismissed, setDismissed] = useState(false)\n if (seconds === undefined || seconds <= 0 || dismissed) return null\n const urgent = seconds <= urgentAt\n return (\n // `accessibilityLiveRegion=\"polite\"` is the RN analogue of the web\n // `role=\"status\"` — announce the countdown without stealing focus.\n <View accessibilityLiveRegion=\"polite\" style={[s.banner, urgent && s.bannerUrgent]}>\n <Text style={[s.msg, urgent && s.textUrgent]}>{message}</Text>\n <Text style={[s.clock, urgent && s.textUrgent]}>{clock(seconds)}</Text>\n <Pressable\n accessibilityRole=\"button\"\n accessibilityLabel=\"Dismiss\"\n hitSlop={8}\n onPress={() => setDismissed(true)}\n style={s.close}\n >\n <Text style={[s.closeGlyph, urgent && s.textUrgent]}>×</Text>\n </Pressable>\n </View>\n )\n}\n\nconst useBannerStyles = (theme: ResolvedTheme) =>\n useMemo(\n () =>\n StyleSheet.create({\n banner: {\n flexDirection: 'row',\n alignItems: 'center',\n gap: 10,\n paddingVertical: 10,\n paddingHorizontal: 12,\n borderRadius: theme.radiusControl,\n borderWidth: StyleSheet.hairlineWidth,\n borderColor: theme.border,\n backgroundColor: theme.surfaceMuted,\n },\n bannerUrgent: { borderColor: theme.error },\n msg: {\n flex: 1,\n color: theme.text,\n fontSize: theme.fontSize - 1,\n fontFamily: theme.fontFamily,\n },\n clock: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontWeight: '700',\n fontVariant: ['tabular-nums'],\n fontFamily: theme.fontFamily,\n },\n textUrgent: { color: theme.error },\n close: { paddingHorizontal: 2 },\n closeGlyph: {\n color: theme.muted,\n fontSize: 18,\n lineHeight: 18,\n fontWeight: '600',\n },\n }),\n [theme]\n )\n","/**\n * Native payment-method radio list — the RN analogue of the web\n * `PaymentMethods`. Presentational only: it renders the selectable rows (icon +\n * label), slots a card field under the selected card/plan row via\n * `children`/`inputSlotFor`, and renders the selected method's extra input\n * (Xendit e-wallet cashtag / phone). It does NOT own the Pay button or\n * `placeOrder` — `<Payment/>` builds the options and maps a selection back to a\n * `placeOrder` request via the option's `id`.\n */\nimport React, { useMemo, type FC, type ReactNode } from 'react'\nimport { Image, Pressable, StyleSheet, Text, View } from 'react-native'\n\nimport { useTheme } from './CheckoutProvider'\nimport { Field, Input } from './Field'\nimport type { ResolvedTheme } from './theme'\n\n// The method descriptor + row shape live in the SDK so both platforms render\n// the SAME option list. Imported for local use and re-exported for consumers\n// that already import them from here.\nimport type {\n PaymentMethodId,\n PaymentMethodOption,\n} from 'tf-checkout-shared'\n\nexport type { PaymentMethodId, PaymentMethodOption }\n\nexport interface PaymentMethodsProps {\n options: PaymentMethodOption[]\n /** Selected `option.value` (controlled). */\n selected: string\n onSelect: (value: string) => void\n /** Extra-field values keyed by `option.value`. */\n extraValues?: Record<string, { cashtag?: string; phoneNumber?: string }>\n onExtraChange?: (\n value: string,\n patch: { cashtag?: string; phoneNumber?: string }\n ) => void\n /** Reveal required extra-field errors after the buyer attempts payment. */\n showValidation?: boolean\n /** Rendered under the selected row whose value === `inputSlotFor`. */\n inputSlotFor?: string\n children?: ReactNode\n}\n\nconst EXTRA_LABEL: Record<'cashtag' | 'phoneNumber', string> = {\n cashtag: 'Jenius $cashtag',\n phoneNumber: 'OVO phone number',\n}\n\nexport const PaymentMethods: FC<PaymentMethodsProps> = ({\n options,\n selected,\n onSelect,\n extraValues = {},\n onExtraChange,\n showValidation = false,\n inputSlotFor,\n children,\n}) => {\n const theme = useTheme()\n const s = useStyles(theme)\n return (\n <View style={s.list} accessibilityRole=\"radiogroup\">\n {options.map((option) => {\n const active = option.value === selected\n const extraValue =\n option.extra === 'phoneNumber'\n ? extraValues[option.value]?.phoneNumber\n : extraValues[option.value]?.cashtag\n const extraInvalid =\n Boolean(active && option.extra && showValidation) && !extraValue?.trim()\n const showBody =\n active && (option.value === inputSlotFor || Boolean(option.extra))\n return (\n <View key={option.value} style={[s.row, active && s.rowActive]}>\n <Pressable\n accessibilityRole=\"radio\"\n accessibilityState={{ selected: active }}\n onPress={() => onSelect(option.value)}\n style={s.rowHead}\n >\n <View style={[s.radio, active && s.radioActive]}>\n {active ? <View style={s.radioDot} /> : null}\n </View>\n {option.iconUrl ? (\n <Image\n source={{ uri: option.iconUrl }}\n style={s.icon}\n resizeMode=\"contain\"\n accessibilityIgnoresInvertColors\n />\n ) : null}\n <Text style={s.rowLabel}>{option.label}</Text>\n </Pressable>\n\n {showBody ? (\n <View style={s.slot}>\n {option.value === inputSlotFor ? children : null}\n {option.extra ? (\n <Field\n label={`${EXTRA_LABEL[option.extra]} *`}\n error={extraInvalid ? 'This field is required.' : undefined}\n >\n <Input\n value={extraValue ?? ''}\n onChangeText={(text) =>\n onExtraChange?.(\n option.value,\n option.extra === 'phoneNumber'\n ? { phoneNumber: text }\n : { cashtag: text }\n )\n }\n placeholder={\n option.extra === 'phoneNumber' ? 'e.g. 081234567890' : '$cashtag'\n }\n keyboardType={\n option.extra === 'phoneNumber' ? 'phone-pad' : 'default'\n }\n autoCapitalize=\"none\"\n invalid={extraInvalid}\n />\n </Field>\n ) : null}\n </View>\n ) : null}\n </View>\n )\n })}\n </View>\n )\n}\n\nconst useStyles = (theme: ResolvedTheme) =>\n useMemo(\n () =>\n StyleSheet.create({\n list: { gap: 8 },\n row: {\n borderWidth: StyleSheet.hairlineWidth,\n borderColor: theme.border,\n borderRadius: theme.radiusControl,\n overflow: 'hidden',\n },\n rowActive: { borderColor: theme.accent },\n rowHead: {\n flexDirection: 'row',\n alignItems: 'center',\n gap: 10,\n padding: 14,\n },\n radio: {\n width: 20,\n height: 20,\n borderRadius: 10,\n borderWidth: 2,\n borderColor: theme.border,\n alignItems: 'center',\n justifyContent: 'center',\n },\n radioActive: { borderColor: theme.accent },\n radioDot: {\n width: 10,\n height: 10,\n borderRadius: 5,\n backgroundColor: theme.accent,\n },\n icon: { width: 24, height: 24 },\n rowLabel: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontFamily: theme.fontFamily,\n },\n slot: { paddingHorizontal: 14, paddingBottom: 14, gap: 10 },\n }),\n [theme]\n )\n","/**\n * `<Tickets/>` — ticket-type catalog + quantity selection. The RN analogue of\n * the web `Tickets` section, at full parity: per-type price line (struck\n * original when discounted, FREE at 0, \"(… with fees)\" sub-line, deposit %),\n * View/Hide info descriptions, sold-out / not-started / ended badges, group\n * headings + a \"Reserve tables\" divider, one-type-at-a-time selection (unless\n * `allowMultipleTicketTypePurchases`), promo / access codes, waiting-list\n * sign-up, a currency switcher, time-slot dates, and a \"Select seats\" hand-off\n * for seated events. Reads the shared engine via `useCheckoutContext()`; primes\n * the cart with `checkout.setTickets`.\n */\nimport React, { Fragment, useEffect, useMemo, useRef, useState, type FC } from 'react'\nimport { Pressable, StyleSheet, Text, View } from 'react-native'\n\nimport {\n errorMessage,\n hooks,\n ticketQuantityRange,\n type TicketSelection,\n type TicketType,\n type WaitingListEntry,\n} from 'tf-checkout-shared'\n\nimport {\n Button,\n Card,\n Divider,\n ErrorText,\n Loader,\n MutedText,\n SectionHeader,\n} from '../ui/primitives'\nimport { useCheckoutContext, useTheme } from '../ui/CheckoutProvider'\nimport { Field, Input } from '../ui/Field'\nimport { QuantitySelect } from '../ui/QuantitySelect'\nimport { Select } from '../ui/Select'\nimport type { ResolvedTheme } from '../ui/theme'\n\n// Web renders the rich description via `dangerouslySetInnerHTML`. React Native\n// has no HTML renderer, so we strip tags + decode a few common entities to show\n// the description as plain text (the adaptation for native).\nconst stripHtml = (html: string): string =>\n html\n .replace(/<\\s*br\\s*\\/?\\s*>/gi, '\\n')\n .replace(/<\\/\\s*(p|div|li|h[1-6])\\s*>/gi, '\\n')\n .replace(/<[^>]+>/g, '')\n .replace(/ /gi, ' ')\n .replace(/&/gi, '&')\n .replace(/</gi, '<')\n .replace(/>/gi, '>')\n .replace(/'|'/gi, \"'\")\n .replace(/"/gi, '\"')\n .replace(/\\n{3,}/g, '\\n\\n')\n .replace(/[ \\t]+\\n/g, '\\n')\n .trim()\n\nconst money = (sym: string, n: number): string => `${sym} ${Number(n).toFixed(2)}`\n\n/** Inline waiting-list sign-up for a sold-out type. */\nconst WaitingListForm: FC<{\n ticket: TicketType\n onJoin: (entry: WaitingListEntry) => Promise<void>\n}> = ({ ticket, onJoin }) => {\n const [form, setForm] = useState({ firstName: '', lastName: '', email: '' })\n const [state, setState] = useState<'idle' | 'busy' | 'done' | 'error'>('idle')\n const [error, setError] = useState('')\n const ok = Boolean(form.firstName.trim() && form.lastName.trim() && form.email.trim())\n\n if (state === 'done')\n return (\n <MutedText>You’re on the waiting list — we’ll email you if a spot opens.</MutedText>\n )\n\n return (\n <View style={staticStyles.wlForm}>\n <Field>\n <Input\n placeholder=\"First name\"\n value={form.firstName}\n onChangeText={(t) => setForm((f) => ({ ...f, firstName: t }))}\n />\n </Field>\n <Field>\n <Input\n placeholder=\"Last name\"\n value={form.lastName}\n onChangeText={(t) => setForm((f) => ({ ...f, lastName: t }))}\n />\n </Field>\n <Field>\n <Input\n placeholder=\"Email\"\n value={form.email}\n keyboardType=\"email-address\"\n autoCapitalize=\"none\"\n onChangeText={(t) => setForm((f) => ({ ...f, email: t }))}\n />\n </Field>\n <Button\n variant=\"ghost\"\n loading={state === 'busy'}\n disabled={!ok || state === 'busy'}\n onPress={() => {\n setState('busy')\n setError('')\n onJoin({ ...form, ticketTypeId: ticket.id })\n .then(() => setState('done'))\n .catch((e) => {\n setState('error')\n setError(errorMessage(e))\n })\n }}\n >\n Join the waiting list\n </Button>\n {error ? <ErrorText>{error}</ErrorText> : null}\n </View>\n )\n}\n\nexport interface TicketsProps {\n eventId: string\n /** Optional heading above the catalog. The legacy storefront shows none, so\n * the default is intentionally hidden. */\n title?: string | false\n /** Fired once the cart is primed (tickets added) — e.g. reveal `<AddOns/>`. */\n onContinue?: () => void\n /** CTA label. Old storefront uses \"Get tickets\". */\n buttonLabel?: string\n /** Force time-slot mode + supply the selectable session dates (ISO yyyy-mm-dd).\n * Omit to auto-detect from the event (`isTimeSlotEvent` / `availableDates`). */\n timeSlotDates?: string[]\n /** SEATED events: fired when the buyer taps \"Select seats\". Wire this to\n * reveal `<SeatMap/>`. Without it the seat CTA is hidden. */\n onSelectSeats?: () => void\n /** Apply this code once when the ticket catalog mounts. */\n initialPromoCode?: string\n /** Attribute this visit once. */\n referrer?: string | number\n /** Web also reads promo/referral values from the URL. React Native has no\n * `window.location`, so URL attribution is skipped here; the prop is accepted\n * for parity and defaults true. */\n readAttributionFromUrl?: boolean\n}\n\nexport const Tickets: FC<TicketsProps> = ({\n eventId,\n title = false,\n onContinue,\n buttonLabel = 'Get tickets',\n timeSlotDates,\n onSelectSeats,\n initialPromoCode,\n referrer,\n readAttributionFromUrl = true,\n}) => {\n const checkout = useCheckoutContext()\n const theme = useTheme()\n const s = useTicketStyles(theme)\n const ticketsQuery = hooks.useTicketsWithMeta(eventId)\n const promoMeta = ticketsQuery.data?.promo\n const showWaitingList = ticketsQuery.data?.showWaitingList ?? false\n\n const [qty, setQty] = useState<Record<string, number>>({})\n const [slotDate, setSlotDate] = useState('')\n\n // Time-slot / calendar events: pick a date, then buy from that session's slots.\n const eventInfo = hooks.useEvent(eventId).data\n const isTimeSlot = Boolean(timeSlotDates?.length || eventInfo?.isTimeSlotEvent)\n const dates = useMemo(\n () => timeSlotDates ?? eventInfo?.availableDates ?? [],\n [timeSlotDates, eventInfo?.availableDates]\n )\n useEffect(() => {\n if (isTimeSlot && !slotDate && dates.length) setSlotDate(dates[0])\n }, [isTimeSlot, slotDate, dates])\n const slotQuery = hooks.useTimeSlotTickets(eventId, isTimeSlot ? slotDate : undefined)\n\n const tickets = useMemo(\n () => (isTimeSlot ? (slotQuery.data ?? []) : (ticketsQuery.data?.tickets ?? [])),\n [isTimeSlot, slotQuery.data, ticketsQuery.data?.tickets]\n )\n const [error, setError] = useState('')\n const [code, setCode] = useState('')\n const [codeState, setCodeState] = useState<'idle' | 'busy'>('idle')\n const [promoOpen, setPromoOpen] = useState(false)\n const [wlOpen, setWlOpen] = useState<Record<string, boolean>>({})\n const [visibleDescription, setVisibleDescription] = useState<string | null>(null)\n const attributionEvent = useRef<string | null>(null)\n\n // Match hosted links: attribute referral visits and apply a carried promo once\n // per event. Explicit props win. URL reading (web-only) is intentionally\n // skipped on native — `readAttributionFromUrl` is accepted for prop parity.\n useEffect(() => {\n if (attributionEvent.current === eventId) return\n attributionEvent.current = eventId\n\n const promo = initialPromoCode?.trim() ?? ''\n const referral = referrer\n\n if (referral !== undefined && String(referral).trim()) {\n checkout.attributeReferrer(eventId, referral).catch(() => undefined)\n }\n if (promo) {\n setCode(promo)\n setPromoOpen(true)\n setCodeState('busy')\n checkout\n .applyPromoCode(eventId, promo)\n .catch(() => undefined)\n .finally(() => {\n ticketsQuery.refetch().finally(() => setCodeState('idle'))\n })\n }\n // Checkout actions and query functions are stable; this effect is scoped to\n // one attribution pass per event.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [eventId, initialPromoCode, referrer, readAttributionFromUrl])\n\n // Seed the currency state once so a multi-currency event can offer a switcher\n // on the ticket screen (before the cart is primed). No-op for single-currency.\n useEffect(() => {\n checkout.syncCurrency(eventId, undefined, { seed: true }).catch(() => undefined)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [eventId])\n\n const changeCurrency = (nextCode: string) => {\n checkout\n .syncCurrency(eventId, nextCode)\n .then((res) => {\n if (res.requiresCatalogRefresh) {\n setQty({})\n ticketsQuery.refetch()\n }\n })\n .catch(() => undefined)\n }\n\n // Remember each type's first-seen (pre-promo) price so a discount can strike it.\n const originals = useRef<Record<string, number>>({})\n useEffect(() => {\n for (const t of tickets)\n if (originals.current[t.id] == null) originals.current[t.id] = t.price\n }, [tickets])\n\n const selected = tickets.filter((t) => (qty[t.id] ?? 0) > 0)\n // The current selection's kind — drives the CTA label and the mutual-exclusion\n // rule below (a table order and a ticket order can't be combined).\n const selectionIsTable = selected.some((t) => t.isTable)\n const allowMultiple = eventInfo?.allowMultipleTicketTypePurchases === true\n\n // Ported from the old checkout's `handleTicketSelect`: unless the event opts\n // into multiple types (`allowMultipleTicketTypePurchases`), a new selection\n // REPLACES the previous one — one ticket type per order. Even when multiple are\n // allowed, switching between a table and a regular ticket clears the rest.\n const selectQty = (t: TicketType, value: number) =>\n setQty((prev) => {\n const activeIds = Object.keys(prev).filter((k) => (prev[k] ?? 0) > 0)\n const prevIsTable = activeIds.length\n ? Boolean(tickets.find((x) => x.id === activeIds[0])?.isTable)\n : t.isTable\n const switchingKind = activeIds.length > 0 && prevIsTable !== t.isTable\n\n if (!allowMultiple) return value > 0 ? { [t.id]: value } : {}\n if (switchingKind && value > 0) return { [t.id]: value }\n const next = { ...prev }\n if (value > 0) next[t.id] = value\n else delete next[t.id]\n return next\n })\n\n // Seated events: the buyer picks on a seat map, so seat-map ticket types show\n // read-only (no quantity control) and the CTA becomes \"Select seats\". A type\n // with `allowDirectPurchase` opts out and keeps its stepper.\n const isSeated = eventInfo?.isSeatedEvent ?? false\n const seatMapRow = (t: TicketType) => isSeated && !t.allowDirectPurchase\n const hasSeatMapTickets = tickets.some(seatMapRow)\n const directPurchasable = tickets.filter((t) => !seatMapRow(t))\n const seatCtaLabel = eventInfo?.tableMapEnabled ? 'Select on map' : 'Select seats'\n\n // A \"Reserve tables\" divider before the first table type — only when regular\n // tickets actually precede it (a tables-first list gets no stray divider).\n const firstTableIndex = tickets.findIndex((t) => t.isTable)\n const firstTableId =\n firstTableIndex > 0 && tickets.slice(0, firstTableIndex).some((t) => !t.isTable)\n ? tickets[firstTableIndex].id\n : undefined\n\n const prime = () => {\n setError('')\n const selections: TicketSelection[] = selected.map((t) => ({\n id: t.id,\n name: t.name,\n optionName: t.optionName,\n price: t.price,\n quantity: qty[t.id] ?? 0,\n currency: t.currency,\n }))\n checkout\n .setTickets(eventId, selections)\n .then(() => onContinue?.())\n .catch((e) => setError(errorMessage(e)))\n }\n\n const applyCode = () => {\n if (!code.trim()) return\n setCodeState('busy')\n checkout\n .applyPromoCode(eventId, code.trim())\n .catch(() => undefined)\n .finally(() => {\n ticketsQuery.refetch().finally(() => setCodeState('idle'))\n })\n }\n\n const isAccess = promoMeta?.isAccessCodeEnabled\n const showCodeInput = promoMeta?.isPromotionsEnabled || isAccess\n const listQuery = isTimeSlot ? slotQuery : ticketsQuery\n const currency = checkout.currency\n\n const renderRow = (t: TicketType) => {\n const notStarted = !t.salesStarted\n const unavailable = t.soldOut || t.salesEnded || notStarted\n const original = originals.current[t.id]\n const discounted = original != null && original > t.price\n const canWaitlist =\n t.soldOut && (t.waitingListEnabled || showWaitingList) && !t.salesEnded\n const isFree = Number(t.price) === 0\n const sym = t.priceSymbol || t.currency\n const range = ticketQuantityRange(t)\n const ticketIndex = tickets.findIndex((candidate) => candidate.id === t.id)\n const previousTicket = ticketIndex > 0 ? tickets[ticketIndex - 1] : undefined\n const startsNamedGroup =\n Boolean(t.groupName) && t.groupName !== previousTicket?.groupName\n\n const groupHeading = startsNamedGroup ? (\n <Text style={s.group}>{t.groupName}</Text>\n ) : t.id === firstTableId ? (\n <>\n <Divider />\n <Text style={s.group}>Reserve tables</Text>\n </>\n ) : null\n\n return (\n <Fragment key={t.id}>\n {groupHeading}\n <View style={s.rowWrap}>\n <View style={s.row}>\n <View style={s.info}>\n <View style={s.nameRow}>\n <Text style={s.name}>{t.name}</Text>\n {t.descriptionRich ? (\n <Pressable\n accessibilityRole=\"button\"\n onPress={() =>\n setVisibleDescription((cur) => (cur === t.id ? null : t.id))\n }\n >\n <Text style={s.infoToggle}>\n {visibleDescription === t.id ? 'Hide info' : 'View info'}\n </Text>\n </Pressable>\n ) : null}\n </View>\n <View style={s.priceRow}>\n {discounted && original != null ? (\n <Text style={s.oldPrice}>{money(sym, original)}</Text>\n ) : null}\n <Text style={[s.amount, isFree && s.amountFree]}>\n {isFree ? 'FREE' : money(sym, t.price)}\n </Text>\n {/* Native affordance kept from the RN ticket screen: tables price\n per table. */}\n {t.isTable ? <Text style={s.perTable}>· per table</Text> : null}\n {/* Fees sub-line — omitted for free / sold-out types. */}\n {!isFree && !t.soldOut ? (\n <Text style={s.fees}>({money(sym, t.priceWithFees)} with fees)</Text>\n ) : null}\n {t.depositPercent != null ? (\n <Text style={s.deposit}>{t.depositPercent.toFixed(2)}% DEPOSIT</Text>\n ) : null}\n </View>\n </View>\n {/* Seat-map types are read-only here — no quantity control; the buyer\n picks them on the map via \"Select seats\". */}\n {seatMapRow(t) ? null : unavailable ? (\n <Text style={s.soldout}>\n {t.soldOut\n ? 'Sold out'\n : notStarted\n ? 'Sales not started'\n : 'Sales Ended'}\n </Text>\n ) : (\n <View style={s.qtyWrap}>\n {/* Tables pick a number of GUESTS (bounded by minGuests/maxGuests),\n not a count of tickets — the label makes that explicit. */}\n {t.isTable ? <Text style={s.guests}>Guests</Text> : null}\n <QuantitySelect\n value={qty[t.id] ?? 0}\n min={range.min}\n max={range.max}\n step={range.step}\n onChange={(v) => selectQty(t, v)}\n />\n </View>\n )}\n </View>\n {t.descriptionRich && visibleDescription === t.id ? (\n <Text style={s.description}>{stripHtml(t.descriptionRich)}</Text>\n ) : null}\n {canWaitlist ? (\n wlOpen[t.id] ? (\n <WaitingListForm\n ticket={t}\n onJoin={(entry) => checkout.joinWaitingList(eventId, entry)}\n />\n ) : (\n <Pressable\n accessibilityRole=\"button\"\n onPress={() => setWlOpen((w) => ({ ...w, [t.id]: true }))}\n >\n <Text style={s.wlToggle}>Join the waiting list</Text>\n </Pressable>\n )\n ) : null}\n </View>\n </Fragment>\n )\n }\n\n // Time-slot layout groups the date's tickets under their time heading.\n const timeGroups: { time: string; items: TicketType[] }[] = []\n if (isTimeSlot)\n for (const t of tickets) {\n const time = t.timeSlot?.time ?? ''\n const g = timeGroups.find((x) => x.time === time)\n if (g) g.items.push(t)\n else timeGroups.push({ time, items: [t] })\n }\n\n return (\n <Card>\n {title ? <SectionHeader title={title} /> : null}\n\n {listQuery.isLoading ? (\n <View style={s.loading}>\n <Loader />\n </View>\n ) : null}\n\n {listQuery.error ? (\n <ErrorText>{(listQuery.error as Error).message}</ErrorText>\n ) : null}\n\n {isTimeSlot && dates.length > 0 ? (\n <View style={s.selectBlock}>\n <Text style={s.selectLabel}>Date</Text>\n <Select\n value={slotDate}\n onChange={(d) => {\n setSlotDate(d)\n setQty({})\n }}\n options={dates.map((d) => ({ label: d, value: d }))}\n />\n </View>\n ) : null}\n\n {currency && currency.available.length > 1 ? (\n <View style={s.selectBlock}>\n <Text style={s.selectLabel}>Currency</Text>\n <Select\n value={currency.currency}\n onChange={changeCurrency}\n options={currency.available.map((c) => ({\n label: `${c.name} (${c.code})`,\n value: c.code,\n }))}\n />\n </View>\n ) : null}\n\n {isTimeSlot && !slotQuery.isLoading && tickets.length === 0 && slotDate ? (\n <MutedText>No sessions available on this date.</MutedText>\n ) : null}\n\n {isTimeSlot\n ? timeGroups.map((g) => (\n <Fragment key={g.time}>\n {g.time ? <Text style={s.slotTime}>{g.time}</Text> : null}\n {g.items.map(renderRow)}\n </Fragment>\n ))\n : tickets.map(renderRow)}\n\n {/* Promo / access code */}\n {showCodeInput ? (\n <View style={s.promo}>\n {!isAccess && !promoOpen ? (\n <Pressable accessibilityRole=\"button\" onPress={() => setPromoOpen(true)}>\n <Text style={s.promoToggle}>Got a promo code? Tap here</Text>\n </Pressable>\n ) : (\n <>\n <Field>\n <Input\n placeholder={isAccess ? 'Access code' : 'Promo code'}\n value={code}\n autoCapitalize=\"characters\"\n onChangeText={setCode}\n />\n </Field>\n <Button\n variant=\"ghost\"\n onPress={applyCode}\n loading={codeState === 'busy'}\n disabled={codeState === 'busy' || !code.trim()}\n >\n {isAccess ? 'ENTER' : 'APPLY'}\n </Button>\n {promoMeta?.promoCodeMessage ? (\n promoMeta.promoCodeValid === false ? (\n <ErrorText>{promoMeta.promoCodeMessage}</ErrorText>\n ) : (\n <MutedText>{promoMeta.promoCodeMessage}</MutedText>\n )\n ) : null}\n </>\n )}\n </View>\n ) : null}\n\n {/* Direct-purchase CTA — hidden on a fully-seated event (nothing to buy by\n quantity; the seat map is the only path). */}\n {directPurchasable.length > 0 ? (\n <Button\n onPress={prime}\n loading={checkout.isBusy}\n disabled={checkout.isBusy || selected.length === 0}\n >\n {checkout.isBusy\n ? 'Reserving…'\n : selectionIsTable\n ? 'Reserve tables'\n : buttonLabel}\n </Button>\n ) : null}\n\n {/* Seated events: hand off to the seat map instead of quantity selection. */}\n {hasSeatMapTickets ? (\n <Button variant=\"ghost\" onPress={() => onSelectSeats?.()}>\n {seatCtaLabel}\n </Button>\n ) : null}\n\n {error || checkout.error ? <ErrorText>{error || checkout.error}</ErrorText> : null}\n </Card>\n )\n}\n\n/** Theme-independent layout bits (used by the WaitingListForm subcomponent). */\nconst staticStyles = StyleSheet.create({\n wlForm: { gap: 8 },\n})\n\nconst useTicketStyles = (theme: ResolvedTheme) =>\n useMemo(\n () =>\n StyleSheet.create({\n loading: { paddingVertical: 24, alignItems: 'center' },\n selectBlock: { gap: 6 },\n selectLabel: {\n color: theme.muted,\n fontSize: theme.fontSize - 2,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n slotTime: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontWeight: '700',\n marginTop: 4,\n fontFamily: theme.fontFamily,\n },\n group: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontWeight: '700',\n marginTop: 4,\n fontFamily: theme.fontFamily,\n },\n rowWrap: { gap: 8 },\n row: { flexDirection: 'row', alignItems: 'flex-start', gap: 12 },\n info: { flex: 1, gap: 4 },\n nameRow: { flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', gap: 8 },\n name: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n infoToggle: {\n color: theme.accent,\n fontSize: theme.fontSize - 2,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n priceRow: {\n flexDirection: 'row',\n alignItems: 'center',\n flexWrap: 'wrap',\n gap: 6,\n },\n oldPrice: {\n color: theme.muted,\n fontSize: theme.fontSize - 1,\n textDecorationLine: 'line-through',\n fontVariant: ['tabular-nums'],\n fontFamily: theme.fontFamily,\n },\n amount: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontWeight: '700',\n fontVariant: ['tabular-nums'],\n fontFamily: theme.fontFamily,\n },\n amountFree: { color: theme.success },\n perTable: {\n color: theme.muted,\n fontSize: theme.fontSize - 1,\n fontFamily: theme.fontFamily,\n },\n fees: {\n color: theme.muted,\n fontSize: theme.fontSize - 1,\n fontFamily: theme.fontFamily,\n },\n deposit: {\n color: theme.muted,\n fontSize: theme.fontSize - 2,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n soldout: {\n color: theme.muted,\n fontSize: theme.fontSize - 1,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n qtyWrap: { flexDirection: 'row', alignItems: 'center', gap: 8 },\n guests: {\n color: theme.muted,\n fontSize: theme.fontSize - 2,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n description: {\n color: theme.muted,\n fontSize: theme.fontSize - 1,\n fontFamily: theme.fontFamily,\n },\n wlToggle: {\n color: theme.accent,\n fontSize: theme.fontSize - 1,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n promo: { gap: 8 },\n promoToggle: {\n color: theme.accent,\n fontSize: theme.fontSize - 1,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n }),\n [theme]\n )\n","/**\n * `<AddOns/>` — optional upsells for the primed cart. The RN analogue of the web\n * `AddOns` section: lists the event's add-ons (filtered to the tickets in the\n * cart), lets the buyer pick quantities, and captures any per-add-on custom\n * fields. On continue it writes the selection (`setAddons`, which reprices) and\n * the captured fields (`setAddonDataCapture`).\n *\n * Renders nothing when the event has no applicable add-ons (or they're all sold\n * out), so it's safe to always place between `<Tickets/>` and `<BillingInfo/>`.\n */\nimport React, { Fragment, useEffect, useMemo, useState, type FC } from 'react'\nimport { Pressable, StyleSheet, Text, View } from 'react-native'\n\nimport {\n addOnMaxQuantity,\n errorMessage,\n hooks,\n ttf,\n type CustomFieldValues,\n type EventAddon,\n} from 'tf-checkout-shared'\n\nimport { Button, Card, ErrorText, Loader, MutedText } from '../ui/primitives'\nimport { useCheckoutContext, useTheme } from '../ui/CheckoutProvider'\n// Created by a sibling agent; imported here per the port plan. Mirrors the web\n// `CustomFieldGroupFields` API: { group, values, onChange(name, value) }.\nimport { CustomFieldGroupFields } from '../ui/CustomFields'\nimport { QuantitySelect } from '../ui/QuantitySelect'\nimport type { ResolvedTheme } from '../ui/theme'\n\n// Web renders the add-on description via `dangerouslySetInnerHTML`. React Native\n// has no HTML renderer, so we strip tags + decode a few common entities to show\n// the description as plain text (the adaptation for native).\nconst stripHtml = (html: string): string =>\n html\n .replace(/<\\s*br\\s*\\/?\\s*>/gi, '\\n')\n .replace(/<\\/\\s*(p|div|li|h[1-6])\\s*>/gi, '\\n')\n .replace(/<[^>]+>/g, '')\n .replace(/ /gi, ' ')\n .replace(/&/gi, '&')\n .replace(/</gi, '<')\n .replace(/>/gi, '>')\n .replace(/'|'/gi, \"'\")\n .replace(/"/gi, '\"')\n .replace(/\\n{3,}/g, '\\n\\n')\n .replace(/[ \\t]+\\n/g, '\\n')\n .trim()\n\nconst money = (currency: string, n: number): string =>\n `${currency} ${Number(n).toFixed(2)}`\n\nexport interface AddOnsProps {\n eventId: string\n /** Fired once add-ons are saved to the cart — e.g. reveal `<BillingInfo/>`. */\n onContinue?: () => void\n /** Fired when the buyer skips add-ons. Hidden when a required add-on exists. */\n onSkip?: () => void\n /** CTA label. Old checkout uses \"CONFIRM SELECTION\". */\n buttonLabel?: string\n /** Eyebrow above the title. Old checkout uses \"Get Your Tickets\". */\n eyebrow?: string\n /** Section heading. Old checkout uses \"UPGRADES & ADD-ONS\". */\n heading?: string\n}\n\nexport const AddOns: FC<AddOnsProps> = ({\n eventId,\n onContinue,\n onSkip,\n buttonLabel = 'CONFIRM SELECTION',\n eyebrow = 'Get Your Tickets',\n heading = 'UPGRADES & ADD-ONS',\n}) => {\n const checkout = useCheckoutContext()\n const theme = useTheme()\n const s = useAddonStyles(theme)\n // No onContinue ⇒ combined form (inside <EmbeddedCheckout/>): apply the\n // selection live (no \"confirm\" click) — the old checkout applied add-ons at\n // checkout too.\n const combined = !onContinue\n const addonsQuery = hooks.useEventAddons(eventId)\n const all = addonsQuery.data ?? []\n const addons = ttf.events.filterAddonsForTickets(all, checkout.ticketTypeIds)\n // Tickets reserved in the cart — the bound for ticket-scoped add-on caps\n // (the hosted partial's `selectedTotalQty()`).\n const ticketQuantity = (checkout.breakdown?.tickets ?? []).reduce(\n (total, line) => total + (line.quantity || 0),\n 0\n )\n\n const [qty, setQty] = useState<Record<string, number>>(checkout.addOns ?? {})\n const [capture, setCapture] = useState<Record<string, CustomFieldValues>>(\n checkout.addOnDataCapture ?? {}\n )\n const [error, setError] = useState('')\n\n // Custom-field groups keyed by add-on id (scope 'add-on', group id = add-on id).\n const fieldGroups = useMemo(() => {\n const map: Record<string, (typeof checkout.customFields)[number]> = {}\n for (const g of checkout.customFields) if (g.scope === 'add-on') map[g.id] = g\n return map\n }, [checkout.customFields])\n\n // Combined mode: debounce-apply the selection to the cart (which reprices) as\n // it changes, instead of gating behind a \"confirm\" button.\n useEffect(() => {\n if (!combined) return\n const selection = Object.fromEntries(Object.entries(qty).filter(([, n]) => n > 0))\n if (JSON.stringify(selection) === JSON.stringify(checkout.addOns ?? {})) return\n const captureForSelected = Object.fromEntries(\n Object.entries(capture).filter(([id]) => (selection[id] ?? 0) > 0)\n )\n const t = setTimeout(() => {\n checkout.setAddonDataCapture(captureForSelected)\n checkout.setAddons(selection).catch((e) => setError(errorMessage(e)))\n }, 500)\n return () => clearTimeout(t)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [combined, qty, capture])\n\n const hasRequired = (checkout.requiredAddOns ?? []).some((a) => a.required)\n const head = (\n <View style={s.head}>\n {eyebrow ? <Text style={s.eyebrow}>{eyebrow}</Text> : null}\n <Text style={s.heading}>{heading}</Text>\n {onSkip && !hasRequired ? (\n <Pressable accessibilityRole=\"button\" onPress={onSkip} style={s.skipBtn}>\n <Text style={s.skip}>Skip</Text>\n </Pressable>\n ) : null}\n </View>\n )\n\n if (addonsQuery.isLoading) {\n return (\n <Card>\n {head}\n <View style={s.sectionLoader}>\n <Loader />\n </View>\n </Card>\n )\n }\n if (addons.length === 0) return null\n // A catalog containing only unavailable rows is not a useful checkout step.\n // Required sold-out add-ons are already exempted by the engine preflight.\n if (addons.every((addon) => addon.stock === 0)) return null\n\n // The hosted cap — ticket-quantity / per-ticket / max-quantity bounds. The\n // server hard-rejects anything above it, so never offer a larger number.\n const max = (a: EventAddon) => addOnMaxQuantity(a, ticketQuantity)\n const soldOut = (a: EventAddon) => a.stock === 0\n\n // Group add-ons under their groupName heading (nulls fall under no heading).\n const groups: { heading: string | null; items: EventAddon[] }[] = []\n for (const a of addons) {\n const last = groups[groups.length - 1]\n if (last && last.heading === (a.groupName ?? null)) last.items.push(a)\n else groups.push({ heading: a.groupName ?? null, items: [a] })\n }\n\n const missing = checkout.missingRequiredAddonNames\n const save = () => {\n setError('')\n const selection = Object.fromEntries(Object.entries(qty).filter(([, n]) => n > 0))\n // Only keep captured fields for add-ons that are actually selected.\n const captureForSelected = Object.fromEntries(\n Object.entries(capture).filter(([id]) => (selection[id] ?? 0) > 0)\n )\n checkout.setAddonDataCapture(captureForSelected)\n checkout\n .setAddons(selection)\n .then(() => onContinue?.())\n .catch((e) => setError(errorMessage(e)))\n }\n\n const selectedCount = Object.values(qty).filter((n) => n > 0).length\n\n return (\n <Card>\n {head}\n <Text style={s.subtitle}>PLEASE SELECT FROM THE OPTIONAL ADD-ONS BELOW</Text>\n\n {groups.map((g, gi) => (\n <Fragment key={g.heading ?? `g${gi}`}>\n {g.heading ? <Text style={s.group}>{g.heading}</Text> : null}\n {g.items.map((a) => {\n const n = qty[a.id] ?? 0\n const group = fieldGroups[a.id]\n const desc = a.description ? stripHtml(a.description) : ''\n return (\n <View key={a.id} style={s.item}>\n <View style={s.row}>\n <View style={s.info}>\n <Text style={s.name}>\n {a.name}\n {a.required ? <Text style={s.req}> · required</Text> : null}\n </Text>\n <Text style={s.price}>\n {money(a.currency, a.price)}\n {a.feeIncluded ? (\n <Text style={s.priceNote}> incl. fees</Text>\n ) : null}\n </Text>\n {desc ? <Text style={s.desc}>{desc}</Text> : null}\n </View>\n {soldOut(a) ? (\n <Text style={s.soldOut}>Sold out</Text>\n ) : (\n <QuantitySelect\n value={n}\n min={0}\n max={max(a)}\n onChange={(v) => setQty((q) => ({ ...q, [a.id]: v }))}\n />\n )}\n </View>\n {n > 0 && group ? (\n <View style={s.fields}>\n <CustomFieldGroupFields\n group={group}\n values={capture[a.id] ?? {}}\n onChange={(name: string, val: string | string[]) =>\n setCapture((c) => ({\n ...c,\n [a.id]: { ...(c[a.id] ?? {}), [name]: val },\n }))\n }\n />\n </View>\n ) : null}\n </View>\n )\n })}\n </Fragment>\n ))}\n\n {!combined ? (\n <Button\n onPress={save}\n loading={checkout.isBusy}\n disabled={checkout.isBusy || selectedCount === 0}\n >\n {checkout.isBusy ? 'Updating…' : buttonLabel}\n </Button>\n ) : null}\n {missing.length > 0 ? (\n <MutedText>Required add-on: {missing.join(', ')}.</MutedText>\n ) : null}\n {error || checkout.error ? <ErrorText>{error || checkout.error}</ErrorText> : null}\n </Card>\n )\n}\n\nconst useAddonStyles = (theme: ResolvedTheme) =>\n useMemo(\n () =>\n StyleSheet.create({\n head: { flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', gap: 8 },\n eyebrow: {\n color: theme.muted,\n fontSize: theme.fontSize - 3,\n fontWeight: '700',\n letterSpacing: 0.5,\n textTransform: 'uppercase',\n fontFamily: theme.fontFamily,\n },\n heading: {\n flex: 1,\n color: theme.text,\n fontSize: theme.fontSize + 2,\n fontWeight: '700',\n fontFamily: theme.fontFamily,\n },\n skipBtn: { paddingHorizontal: 4, paddingVertical: 2 },\n skip: {\n color: theme.accent,\n fontSize: theme.fontSize - 1,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n subtitle: {\n color: theme.muted,\n fontSize: theme.fontSize - 3,\n fontWeight: '600',\n letterSpacing: 0.3,\n textTransform: 'uppercase',\n fontFamily: theme.fontFamily,\n },\n sectionLoader: { paddingVertical: 20, alignItems: 'center' },\n group: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontWeight: '700',\n marginTop: 4,\n fontFamily: theme.fontFamily,\n },\n item: { gap: 10 },\n row: { flexDirection: 'row', alignItems: 'flex-start', gap: 12 },\n info: { flex: 1, gap: 2 },\n name: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n req: { color: theme.muted, fontWeight: '400' },\n price: {\n color: theme.text,\n fontSize: theme.fontSize - 1,\n fontVariant: ['tabular-nums'],\n fontFamily: theme.fontFamily,\n },\n priceNote: { color: theme.muted },\n desc: {\n color: theme.muted,\n fontSize: theme.fontSize - 1,\n fontFamily: theme.fontFamily,\n },\n soldOut: {\n color: theme.muted,\n fontSize: theme.fontSize - 1,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n fields: {\n gap: 10,\n paddingTop: 4,\n paddingLeft: 12,\n borderLeftWidth: StyleSheet.hairlineWidth,\n borderLeftColor: theme.border,\n },\n }),\n [theme]\n )\n","/**\n * Data-driven custom fields — the RN analogue of the web `ui/CustomFields`. The\n * event describes what to collect (`EventCustomField[]`, order- / ticket- /\n * add-on-scoped); these render it and report values back. No per-brand form code:\n * pass the group, hold the values.\n *\n * Native adaptations vs web:\n * - `<select>` and `radio` (single choice) both render as the native `Select`\n * sheet — there is no native radio primitive.\n * - `select_multi` renders a column of native `Checkbox` rows.\n * - there is no multiline `Textarea` primitive, so `textarea` falls back to a\n * single-line `Input` (value parity preserved).\n */\nimport React, { type FC } from 'react'\nimport { View } from 'react-native'\n\nimport type {\n CustomFieldValues,\n EventCustomField,\n EventCustomFieldGroup,\n} from 'tf-checkout-shared'\nimport { ticketFieldsFor } from 'tf-checkout-shared'\n\nimport { Checkbox, Field, Input } from './Field'\nimport { ErrorText, MutedText } from './primitives'\nimport { Select, type SelectOption } from './Select'\n\ntype FieldValue = string | string[]\n\nconst asString = (v: FieldValue | undefined): string =>\n Array.isArray(v) ? (v[0] ?? '') : (v ?? '')\nconst asArray = (v: FieldValue | undefined): string[] =>\n Array.isArray(v) ? v : v ? [v] : []\n\nexport interface CustomFieldInputProps {\n field: EventCustomField\n value: FieldValue | undefined\n onChange: (value: FieldValue) => void\n error?: string\n}\n\n/** Render one custom field by its declared `type`. */\nexport const CustomFieldInput: FC<CustomFieldInputProps> = ({\n field,\n value,\n onChange,\n error,\n}) => {\n const invalid = error !== undefined && error !== null\n const desc = field.description ? <MutedText>{field.description}</MutedText> : null\n\n switch (field.type) {\n case 'textarea':\n // Native adaptation: no multiline Textarea primitive — single-line Input.\n return (\n <Field label={field.label} required={field.required} error={error}>\n {desc}\n <Input value={asString(value)} onChangeText={onChange} invalid={invalid} />\n </Field>\n )\n case 'select':\n case 'radio': {\n // Native adaptation: web renders radio inline; both single-choice types use\n // the `Select` sheet here (no native radio primitive).\n const options: SelectOption[] = field.options.map((o) => ({\n label: o.name,\n value: o.value,\n }))\n return (\n <Field label={field.label} required={field.required} error={error}>\n {desc}\n <Select\n value={asString(value) || undefined}\n onChange={onChange}\n options={options}\n placeholder=\"— select —\"\n invalid={invalid}\n />\n </Field>\n )\n }\n case 'select_multi': {\n const picked = asArray(value)\n const toggle = (v: string, on: boolean) =>\n onChange(on ? [...picked, v] : picked.filter((x) => x !== v))\n return (\n <Field label={field.label} required={field.required} error={error}>\n {desc}\n <View style={{ gap: 8 }}>\n {field.options.map((o) => (\n <Checkbox\n key={o.id}\n checked={picked.includes(o.value)}\n onChange={(on) => toggle(o.value, on)}\n label={o.name}\n />\n ))}\n </View>\n </Field>\n )\n }\n case 'checkbox':\n return (\n <View style={{ gap: 6 }}>\n <Checkbox\n checked={asString(value) === '1'}\n onChange={(on) => onChange(on ? '1' : '')}\n label={`${field.label}${field.required ? ' *' : ''}`}\n invalid={invalid}\n />\n {error !== undefined && error !== null ? <ErrorText>{error}</ErrorText> : null}\n </View>\n )\n case 'image':\n // File capture needs an upload rail the SDK doesn't own yet — surface it\n // rather than silently dropping a required field.\n return (\n <Field label={field.label} required={field.required} error={error}>\n {desc}\n <MutedText>Image upload isn’t supported in this build.</MutedText>\n </Field>\n )\n default:\n // text / phone / email\n return (\n <Field label={field.label} required={field.required} error={error}>\n {desc}\n <Input\n value={asString(value)}\n onChangeText={onChange}\n keyboardType={\n field.type === 'email'\n ? 'email-address'\n : field.type === 'phone'\n ? 'phone-pad'\n : 'default'\n }\n autoCapitalize={field.type === 'email' ? 'none' : 'sentences'}\n invalid={invalid}\n />\n </Field>\n )\n }\n}\n\nexport interface CustomFieldGroupFieldsProps {\n group: EventCustomFieldGroup\n values: CustomFieldValues\n onChange: (name: string, value: FieldValue) => void\n /** Restrict to fields scoped to this holder's ticket type (ticket groups). */\n ticketTypeId?: string\n}\n\n/** Render every field in a group, wired to a values map. */\nexport const CustomFieldGroupFields: FC<CustomFieldGroupFieldsProps> = ({\n group,\n values,\n onChange,\n ticketTypeId,\n}) => (\n <>\n {ticketFieldsFor(group.fields, ticketTypeId).map((f) => (\n <CustomFieldInput\n key={f.id}\n field={f}\n value={values[f.name]}\n onChange={(v) => onChange(f.name, v)}\n />\n ))}\n </>\n)\n\n/** True when every required field in the group has a non-empty value.\n * Re-exported from the SDK so web, native and the engine preflight all apply\n * one rule (including its \"image uploads are server-authoritative\" carve-out). */\nexport { customFieldsComplete } from 'tf-checkout-shared'\n","/**\n * `<BillingInfo/>` — the buyer + attendee details step. Collects: the buyer's\n * name/email + event-gated buyer fields (Instagram/nationality/gender), any\n * ORDER-level custom fields, PER-HOLDER name + ticket-level custom fields (when\n * the event requires holder names or has ticket-scoped fields), and marketing\n * opt-ins. Writes it all into the engine (`setBilling` with `dataCapture`,\n * `setHolders` with `ticketDataCapture`, `setConsent`) so `<Payment/>`'s\n * pre-flight passes. The RN analogue of the web `BillingInfo`, at full field\n * parity — same fields, labels, validation rules, and copy.\n *\n * Native adaptations (see inline comments): the web `PhoneInput` lib becomes an\n * `Input` with `keyboardType=\"phone-pad\"`; the web date input becomes a text\n * `Input` accepting `YYYY-MM-DD`; every `<select>` becomes the `../ui/Select`\n * sheet; the privacy-policy link opens via `Linking` instead of an `<a>`.\n */\nimport React, {\n Fragment,\n useEffect,\n useMemo,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react'\nimport { Linking, Pressable, StyleSheet, Text, View } from 'react-native'\n\nimport {\n hooks,\n mapProfileToBilling,\n missingCheckoutDetails,\n isEmail,\n ticketFieldsFor,\n type CheckoutBilling,\n type CheckoutHolder,\n type CustomFieldValues,\n type EventCustomFieldGroup,\n} from 'tf-checkout-shared'\n\nimport {\n useCheckoutContext,\n useCheckoutValidation,\n useTheme,\n} from '../ui/CheckoutProvider'\nimport { CustomFieldInput } from '../ui/CustomFields'\nimport { Checkbox, Field, Input } from '../ui/Field'\nimport { Button, Card, ErrorText, SectionHeader } from '../ui/primitives'\nimport type { ResolvedTheme } from '../ui/theme'\nimport { BillingAddressFields } from './billing/BillingAddressFields'\nimport { BuyerField } from './billing/BuyerField'\nimport { TicketHoldersCard } from './billing/TicketHoldersCard'\nimport type { BillingDraft, HolderDraft } from './billing/types'\n\nexport interface BillingInfoProps {\n /** Event context is used to default the country. */\n eventId?: string\n /** Fired once billing is saved to the engine — e.g. reveal `<Payment/>`. */\n onContinue?: () => void\n /** Section heading. Old checkout uses \"Billing Information\". */\n heading?: string\n /** CTA label. */\n buttonLabel?: string\n /** When provided and the buyer isn't signed in, shows a \"Login & skip ahead\"\n * row. The current email is passed when login follows an account match. */\n onLogin?: (email?: string) => void\n /** Hide this card only after a signed-in profile satisfies every ordinary\n * billing requirement and the event needs no extra buyer/holder answers. */\n skipWhenProfileComplete?: boolean\n /** Ask guests to repeat their email and require an exact match. */\n requireEmailConfirmation?: boolean\n /** Always collect one named holder per selected ticket. EmbeddedCheckout uses\n * this to match tf-sports; standalone sections default to backend gates. */\n collectTicketHolders?: boolean\n /** When holder details are enabled, also collect each holder's email and phone. */\n collectHolderContact?: boolean\n /** Marketing opt-in labels. Render a checkbox for each provided (unchecked). */\n ttfOptInLabel?: string\n brandOptInLabel?: string\n /** Required host privacy acknowledgement. The URL is supplied by the consumer. */\n privacyPolicy?: CheckoutPrivacyPolicy\n /** Show the legacy inline \"Required\" error after a failed payment attempt. */\n showPrivacyError?: boolean\n /** Optional numbered badge (old checkout shows none — omitted by default). The\n * native `SectionHeader` has no badge slot, so this is accepted for API parity\n * but not rendered. */\n step?: ReactNode\n}\n\nexport interface CheckoutPrivacyPolicy {\n url: string\n brandName: string\n linkLabel?: string\n}\n\nexport const BillingInfo: FC<BillingInfoProps> = ({\n eventId,\n onContinue,\n heading = 'Billing Information',\n buttonLabel = 'Continue to payment',\n onLogin,\n skipWhenProfileComplete = false,\n requireEmailConfirmation = false,\n collectTicketHolders = false,\n collectHolderContact = false,\n ttfOptInLabel = 'Keep me updated about future events from The Ticket Fairy',\n brandOptInLabel,\n privacyPolicy,\n showPrivacyError = false,\n}) => {\n const checkout = useCheckoutContext()\n const validation = useCheckoutValidation()\n const theme = useTheme()\n const s = useStyles(theme)\n const profile = hooks.useProfile({ retry: false })\n const event = hooks.useEvent(eventId)\n // No onContinue ⇒ this is one combined form (inside <EmbeddedCheckout/>): mirror the\n // fields into the engine live and drop the \"continue\" button, so the buyer\n // fills billing + pays with ONE button — the way the old checkout flowed.\n const combined = !onContinue\n\n const [billing, setBilling] = useState<BillingDraft>({\n firstName: checkout.billing?.firstName ?? '',\n lastName: checkout.billing?.lastName ?? '',\n email: checkout.billing?.email ?? '',\n confirmEmail: checkout.billing?.confirmEmail ?? '',\n phone: checkout.billing?.phone,\n streetAddress: checkout.billing?.streetAddress,\n city: checkout.billing?.city,\n zip: checkout.billing?.zip,\n countryId: checkout.billing?.countryId,\n stateId: checkout.billing?.stateId,\n countryCode: checkout.billing?.countryCode,\n stateCode: checkout.billing?.stateCode,\n nationality: checkout.billing?.nationality,\n gender: checkout.billing?.gender,\n instagramHandle: checkout.billing?.instagramHandle,\n })\n const [dataCapture, setDataCapture] = useState<CustomFieldValues>(\n checkout.billing?.dataCapture ?? {}\n )\n const [holders, setHolders] = useState<HolderDraft[]>(() =>\n checkout.holders.map((holder) => ({\n firstName: holder.firstName,\n lastName: holder.lastName,\n email: holder.email,\n phone: holder.phone ?? '',\n ticketTypeId: holder.ticketTypeId,\n ticketDataCapture: holder.ticketDataCapture ?? {},\n }))\n )\n const [consent, setConsent] = useState({ ttfOptIn: false, brandOptIn: false })\n const [dob, setDob] = useState(() => {\n const b = checkout.billing\n if (!b?.dobDay || !b.dobMonth || !b.dobYear) return ''\n return `${b.dobYear}-${String(b.dobMonth).padStart(2, '0')}-${String(\n b.dobDay\n ).padStart(2, '0')}`\n }) // ISO yyyy-mm-dd\n const restoredHolders = useRef(checkout.holders)\n const profileSeeded = useRef(false)\n const countryDefaultApplied = useRef(Boolean(checkout.billing?.countryId))\n\n // The engine setters are stable references (the shared hook holds the engine in\n // a ref). Alias them so the live-commit effect below can depend on the SETTERS\n // — never the whole `checkout` object (a fresh snapshot every render → effect\n // re-fires each render → setBilling → re-render → infinite loop).\n const {\n setBilling: commitBilling,\n setHolders: commitHolders,\n setConsent: commitConsent,\n } = checkout\n\n const gates = checkout.fieldGates\n\n // Custom-field groups by scope.\n const orderGroups = useMemo(\n () => checkout.customFields.filter((g) => g.scope === 'order'),\n [checkout.customFields]\n )\n const ticketGroups = useMemo(\n () => checkout.customFields.filter((g) => g.scope === 'ticket'),\n [checkout.customFields]\n )\n const ticketFields = useMemo(\n () => ticketGroups.flatMap((g) => g.fields),\n [ticketGroups]\n )\n const holderNamesRequired = checkout.holderNamesRequired || collectTicketHolders\n const showHolders = holderNamesRequired || ticketFields.length > 0\n\n // One holder slot per ticket, tagged with its ticket type (drives ticket-field\n // scoping + the engine's per-holder validation).\n const slots = useMemo(() => {\n const out: { ticketTypeId?: string; ticketName?: string }[] = []\n const lines = checkout.breakdown?.tickets ?? []\n for (const line of lines)\n for (let i = 0; i < line.quantity; i++)\n out.push({ ticketTypeId: line.ticketTypeId, ticketName: line.name })\n if (!out.length) {\n const total = checkout.selections.reduce((n, sel) => n + sel.quantity, 0)\n for (let i = 0; i < total; i++) out.push({})\n }\n return out\n }, [checkout.breakdown, checkout.selections])\n\n // The initial state above restores anything already on the engine. A profile\n // that arrives later may fill blanks ONCE, but must never be consulted again\n // while the buyer edits — otherwise clearing the final character restores the\n // previous engine value on the next live commit.\n useEffect(() => {\n const p = profile.data\n if (!p || profileSeeded.current) return\n profileSeeded.current = true\n const profileBilling = mapProfileToBilling(p)\n setBilling((prev) => {\n const next = {\n ...prev,\n firstName: prev.firstName || profileBilling.firstName || '',\n lastName: prev.lastName || profileBilling.lastName || '',\n email: prev.email || profileBilling.email || '',\n confirmEmail:\n prev.confirmEmail || (checkout.isLoggedIn ? profileBilling.email : '') || '',\n phone: prev.phone || profileBilling.phone,\n streetAddress: prev.streetAddress || profileBilling.streetAddress,\n city: prev.city || profileBilling.city,\n zip: prev.zip || profileBilling.zip,\n countryId: prev.countryId || profileBilling.countryId,\n stateId: prev.stateId || profileBilling.stateId,\n }\n const keys = Object.keys(next) as (keyof BillingDraft)[]\n return keys.every((k) => next[k] === prev[k]) ? prev : next\n })\n }, [profile.data, checkout.isLoggedIn])\n\n // Resize holders to the slot count, preserving typed values; tag ticket type.\n useEffect(() => {\n setHolders((prev) =>\n slots.map((slot, i) => ({\n firstName: prev[i]?.firstName ?? restoredHolders.current[i]?.firstName ?? '',\n lastName: prev[i]?.lastName ?? restoredHolders.current[i]?.lastName ?? '',\n email: prev[i]?.email ?? restoredHolders.current[i]?.email ?? '',\n phone: prev[i]?.phone ?? restoredHolders.current[i]?.phone ?? '',\n ticketDataCapture:\n prev[i]?.ticketDataCapture ??\n restoredHolders.current[i]?.ticketDataCapture ??\n {},\n ticketTypeId: slot.ticketTypeId,\n ticketName: slot.ticketName,\n }))\n )\n }, [slots])\n\n // Match the storefront: ticket 1 silently starts as the buyer. The legacy\n // checkout has no extra \"use buyer details\" control.\n useEffect(() => {\n if (!showHolders) return\n setHolders((prev) =>\n prev.map((holder, index) =>\n index === 0\n ? {\n ...holder,\n firstName: billing.firstName,\n lastName: billing.lastName,\n email: billing.email,\n phone: billing.phone ?? '',\n }\n : holder\n )\n )\n }, [showHolders, billing.firstName, billing.lastName, billing.email, billing.phone])\n\n // Debounced \"this email already has an account\" check → nudges the buyer to\n // sign in (autofill + avoid duplicate accounts). Skips signed-in buyers.\n useEffect(() => {\n const email = billing.email.trim()\n if (checkout.isLoggedIn || !isEmail(email)) return\n const t = setTimeout(\n () => checkout.checkBuyerEmail(email).catch(() => undefined),\n 600\n )\n return () => clearTimeout(t)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [billing.email, checkout.isLoggedIn])\n const emailTaken =\n !checkout.isLoggedIn && checkout.existingAccountEmail === billing.email.trim()\n\n const needsNationality = checkout.buyerFields.some((f) => f.kind === 'nationality')\n const countriesQuery = hooks.useCountries({\n enabled: needsNationality || gates.showAddress,\n })\n const countries = useMemo(() => countriesQuery.data ?? [], [countriesQuery.data])\n const statesQuery = hooks.useStates(billing.countryId, {\n enabled: Boolean(billing.countryId),\n })\n const states = useMemo(() => statesQuery.data ?? [], [statesQuery.data])\n\n // Event country → signed-in profile → US, matching the hosted checkout's\n // country preference order. Also retain the ISO code for Stripe.\n useEffect(() => {\n if (\n countryDefaultApplied.current ||\n billing.countryId ||\n countries.length === 0 ||\n profile.isLoading ||\n (eventId && event.isLoading)\n ) {\n return\n }\n const eventCode = event.data?.countryCode?.toLowerCase()\n const preferred =\n countries.find((country) => country.code?.toLowerCase() === eventCode) ??\n countries.find(\n (country) =>\n profile.data?.countryId !== null &&\n profile.data?.countryId !== undefined &&\n String(country.id) === String(profile.data.countryId)\n ) ??\n countries.find((country) => country.code?.toLowerCase() === 'us')\n if (!preferred) return\n countryDefaultApplied.current = true\n setBilling((current) => ({\n ...current,\n countryId: String(preferred.id),\n countryCode: preferred.code?.toUpperCase(),\n stateId: undefined,\n stateCode: undefined,\n }))\n }, [\n billing.countryId,\n countries,\n profile.isLoading,\n profile.data?.countryId,\n eventId,\n event.isLoading,\n event.data?.countryCode,\n ])\n\n useEffect(() => {\n if (!billing.countryId) return\n const country = countries.find(\n (candidate) => String(candidate.id) === String(billing.countryId)\n )\n const countryCode = country?.code?.toUpperCase()\n if (countryCode && countryCode !== billing.countryCode) {\n setBilling((current) => ({ ...current, countryCode }))\n }\n }, [billing.countryId, billing.countryCode, countries])\n\n useEffect(() => {\n if (!billing.stateId) return\n const state = states.find(\n (candidate) => String(candidate.id) === String(billing.stateId)\n )\n const stateCode = state?.code\n if (stateCode && stateCode !== billing.stateCode) {\n setBilling((current) => ({ ...current, stateCode }))\n }\n }, [billing.stateId, billing.stateCode, states])\n\n const setB = (k: keyof BillingDraft) => (value: string) =>\n setBilling((b) => ({ ...b, [k]: value }))\n\n const patchHolder = (i: number, patch: Partial<HolderDraft>) =>\n setHolders((hs) => hs.map((h, j) => (j === i ? { ...h, ...patch } : h)))\n\n const [dobYear, dobMonth, dobDay] = dob ? dob.split('-').map(Number) : []\n const committedBilling: CheckoutBilling = {\n ...checkout.billing,\n ...billing,\n stateRequired: gates.showAddress && Boolean(billing.countryId) && states.length > 0,\n dataCapture,\n dobDay,\n dobMonth,\n dobYear,\n }\n const committedHolders: CheckoutHolder[] = holders.map((holder) => ({\n firstName: holderNamesRequired\n ? holder.firstName\n : holder.firstName || billing.firstName,\n lastName: holderNamesRequired ? holder.lastName : holder.lastName || billing.lastName,\n email:\n showHolders && collectHolderContact ? holder.email : holder.email || billing.email,\n phone:\n showHolders && collectHolderContact ? holder.phone : holder.phone || billing.phone,\n ticketTypeId: holder.ticketTypeId,\n ticketDataCapture: holder.ticketDataCapture,\n }))\n const missingDetails = missingCheckoutDetails(\n {\n billing: committedBilling,\n holders: committedHolders,\n selections: checkout.selections,\n breakdown: checkout.breakdown,\n holderNamesRequired: checkout.holderNamesRequired,\n fieldGates: checkout.fieldGates,\n customFields: checkout.customFields,\n },\n {\n requireEmailConfirmation,\n collectTicketHolders,\n requireHolderContact: collectHolderContact,\n }\n )\n const complete = missingDetails.length === 0\n const showValidation = validation.attempt > 0\n const missingSet = new Set(missingDetails)\n const fieldError = (key: string, message = 'This field is required.') =>\n showValidation && missingSet.has(key) ? message : undefined\n const dobError = showValidation\n ? missingDetails.find(\n (detail) => detail === 'Date of birth' || detail.startsWith('Age ')\n )\n : undefined\n\n const commit = () => {\n commitBilling(committedBilling)\n commitHolders(committedHolders)\n if (ttfOptInLabel || brandOptInLabel) commitConsent(consent)\n }\n\n // Combined mode: keep the engine in sync as the form is filled, so <Payment/>\n // is always chargeable without a separate \"continue\" click. Depend on the\n // stable engine setters + the local source state — NOT the freshly-rebuilt\n // `committed*` objects (new refs each render → infinite loop).\n useEffect(() => {\n if (combined) commit()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n combined,\n commitBilling,\n commitHolders,\n commitConsent,\n billing,\n holders,\n consent,\n dob,\n dataCapture,\n ])\n\n const renderGroupFields = (\n group: EventCustomFieldGroup,\n values: CustomFieldValues,\n onChange: (name: string, v: string | string[]) => void,\n ticketTypeId?: string,\n ticketIndex?: number\n ) =>\n ticketFieldsFor(group.fields, ticketTypeId).map((f) => {\n const label = f.label || f.name\n const missingKey =\n ticketIndex === undefined ? label : `${label} (ticket ${ticketIndex + 1})`\n return (\n <CustomFieldInput\n key={f.id}\n field={f}\n value={values[f.name]}\n error={fieldError(missingKey)}\n onChange={(v) => onChange(f.name, v)}\n />\n )\n })\n\n const hasEventSpecificDetails =\n checkout.buyerFields.length > 0 ||\n checkout.customFields.some((group) => group.fields.length > 0) ||\n showHolders ||\n gates.showDob\n const skipBilling =\n skipWhenProfileComplete &&\n checkout.isLoggedIn &&\n profile.isSuccess &&\n complete &&\n !hasEventSpecificDetails\n\n // This is the safe EmbeddedCheckout interpretation of legacy\n // `skip_billing_page`: payment remains visible; only a fully satisfied,\n // ordinary billing card disappears.\n if (skipBilling) return null\n\n const privacyInvalid = (showPrivacyError || showValidation) && !consent.ttfOptIn\n\n return (\n <>\n <Card>\n <SectionHeader title={heading} />\n\n {onLogin && !checkout.isLoggedIn ? (\n <View style={s.loginRow}>\n <Text style={s.note}>Login & skip ahead:</Text>\n <Pressable onPress={() => onLogin()}>\n <Text style={s.link}>Login</Text>\n </Pressable>\n </View>\n ) : null}\n\n <View style={s.row}>\n <View style={s.col}>\n <Field error={fieldError('First name', 'First name is required.')}>\n <Input\n placeholder=\"First name *\"\n value={billing.firstName}\n onChangeText={setB('firstName')}\n autoCapitalize=\"words\"\n invalid={Boolean(fieldError('First name'))}\n />\n </Field>\n </View>\n <View style={s.col}>\n <Field error={fieldError('Last name', 'Last name is required.')}>\n <Input\n placeholder=\"Last name *\"\n value={billing.lastName}\n onChangeText={setB('lastName')}\n autoCapitalize=\"words\"\n invalid={Boolean(fieldError('Last name'))}\n />\n </Field>\n </View>\n </View>\n\n <View style={s.row}>\n <View style={s.col}>\n <Field\n error={fieldError('Valid email address', 'Enter a valid email address.')}\n >\n <Input\n placeholder=\"Email *\"\n value={billing.email}\n onChangeText={setB('email')}\n keyboardType=\"email-address\"\n autoCapitalize=\"none\"\n invalid={Boolean(fieldError('Valid email address'))}\n />\n </Field>\n </View>\n {requireEmailConfirmation && !checkout.isLoggedIn ? (\n <View style={s.col}>\n <Field\n error={fieldError(\n 'Matching email confirmation',\n 'Email addresses must match.'\n )}\n >\n <Input\n placeholder=\"Confirm email *\"\n value={billing.confirmEmail ?? ''}\n onChangeText={setB('confirmEmail')}\n keyboardType=\"email-address\"\n autoCapitalize=\"none\"\n invalid={Boolean(fieldError('Matching email confirmation'))}\n />\n </Field>\n </View>\n ) : null}\n </View>\n {!showValidation &&\n requireEmailConfirmation &&\n billing.confirmEmail &&\n billing.confirmEmail.trim().toLowerCase() !==\n billing.email.trim().toLowerCase() ? (\n <ErrorText>The email addresses do not match.</ErrorText>\n ) : null}\n {emailTaken ? (\n <Text style={s.note}>\n This email is already registered.{' '}\n {onLogin ? (\n <Text style={s.link} onPress={() => onLogin(billing.email)}>\n Log in to autofill your details\n </Text>\n ) : (\n 'Log in to autofill your details.'\n )}\n </Text>\n ) : null}\n\n {checkout.buyerFields.map((f) => (\n <BuyerField\n key={f.key}\n field={f}\n value={String(billing[f.key] ?? '')}\n onChange={(v) => setBilling((b) => ({ ...b, [f.key]: v }))}\n countries={countries}\n error={fieldError(\n f.kind === 'nationality'\n ? 'Nationality'\n : f.kind === 'gender'\n ? 'Gender'\n : 'Instagram handle'\n )}\n />\n ))}\n\n {gates.showPhone ? (\n <Field\n label=\"Phone\"\n required={gates.phoneRequired}\n error={fieldError('Valid phone number', 'Enter a valid phone number.')}\n >\n {/* Native: web PhoneInput lib → plain phone-pad Input. */}\n <Input\n placeholder=\"Phone number\"\n value={billing.phone ?? ''}\n onChangeText={(v) => setBilling((current) => ({ ...current, phone: v }))}\n keyboardType=\"phone-pad\"\n invalid={Boolean(fieldError('Valid phone number'))}\n />\n </Field>\n ) : null}\n\n {gates.showDob ? (\n <Field\n label={`Date of birth *${\n gates.minimumAge ? ` (must be ${gates.minimumAge}+)` : ''\n }`}\n error={\n dobError === 'Date of birth'\n ? 'Date of birth is required.'\n : dobError\n ? `You must be ${gates.minimumAge} or older.`\n : undefined\n }\n >\n {/* Native: web date input → text Input, ISO YYYY-MM-DD. */}\n <Input\n placeholder=\"YYYY-MM-DD\"\n value={dob}\n onChangeText={setDob}\n keyboardType=\"numbers-and-punctuation\"\n invalid={Boolean(dobError)}\n />\n </Field>\n ) : null}\n\n {gates.showAddress ? (\n <BillingAddressFields\n billing={billing}\n countries={countries}\n states={states}\n fieldError={fieldError}\n setBilling={setBilling}\n />\n ) : null}\n\n {/* Order-level custom fields */}\n {orderGroups.map((g) => (\n <Fragment key={g.id}>\n {g.label ? <Text style={s.sectionLabel}>{g.label}</Text> : null}\n {renderGroupFields(g, dataCapture, (name, v) =>\n setDataCapture((d) => ({ ...d, [name]: v }))\n )}\n </Fragment>\n ))}\n\n {/* Marketing opt-ins (optional) */}\n {brandOptInLabel ? (\n <Checkbox\n checked={consent.brandOptIn}\n onChange={(brandOptIn) => setConsent((c) => ({ ...c, brandOptIn }))}\n label={brandOptInLabel}\n />\n ) : null}\n {privacyPolicy ? (\n <View style={s.consent}>\n <Checkbox\n checked={consent.ttfOptIn}\n onChange={(ttfOptIn) => setConsent((c) => ({ ...c, ttfOptIn }))}\n invalid={privacyInvalid}\n label={\n <Text style={s.consentLabel}>\n I have read and agree to {privacyPolicy.brandName}{' '}\n <Text\n style={s.link}\n onPress={() =>\n Linking.openURL(privacyPolicy.url).catch(() => undefined)\n }\n >\n {privacyPolicy.linkLabel || 'Privacy Policy.'}\n </Text>\n {' *'}\n </Text>\n }\n />\n {privacyInvalid ? <ErrorText>Required</ErrorText> : null}\n </View>\n ) : ttfOptInLabel ? (\n <Checkbox\n checked={consent.ttfOptIn}\n onChange={(ttfOptIn) => setConsent((c) => ({ ...c, ttfOptIn }))}\n label={ttfOptInLabel}\n />\n ) : null}\n\n {!combined ? (\n <Button\n onPress={() => {\n if (!complete) {\n validation.requestValidation()\n return\n }\n commit()\n onContinue?.()\n }}\n >\n {buttonLabel}\n </Button>\n ) : null}\n </Card>\n\n {showHolders ? (\n <TicketHoldersCard\n holders={holders}\n holderNamesRequired={holderNamesRequired}\n collectHolderContact={collectHolderContact}\n fieldError={fieldError}\n patchHolder={patchHolder}\n renderCustomFields={(holder, index) =>\n ticketGroups.map((group) =>\n renderGroupFields(\n group,\n holder.ticketDataCapture,\n (name, value) =>\n patchHolder(index, {\n ticketDataCapture: {\n ...holder.ticketDataCapture,\n [name]: value,\n },\n }),\n holder.ticketTypeId,\n index\n )\n )\n }\n />\n ) : null}\n </>\n )\n}\n\nconst useStyles = (theme: ResolvedTheme) =>\n useMemo(\n () =>\n StyleSheet.create({\n loginRow: { flexDirection: 'row', alignItems: 'center', gap: 8 },\n note: {\n color: theme.muted,\n fontSize: theme.fontSize - 1,\n fontFamily: theme.fontFamily,\n },\n link: {\n color: theme.accent,\n fontSize: theme.fontSize - 1,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n sectionLabel: {\n color: theme.text,\n fontSize: theme.fontSize,\n fontWeight: '600',\n fontFamily: theme.fontFamily,\n },\n consent: { gap: 6 },\n consentLabel: {\n flex: 1,\n color: theme.text,\n fontSize: theme.fontSize - 1,\n fontFamily: theme.fontFamily,\n },\n row: { flexDirection: 'row', gap: 10 },\n col: { flex: 1 },\n }),\n [theme]\n )\n","import React, { type Dispatch, type FC, type SetStateAction } from 'react'\nimport { StyleSheet, View } from 'react-native'\n\nimport { Field, Input } from '../../ui/Field'\nimport { BodyText } from '../../ui/primitives'\nimport { Select, type SelectOption } from '../../ui/Select'\nimport type { BillingDraft, BillingFieldError, LocationOption } from './types'\n\ninterface BillingAddressFieldsProps {\n billing: BillingDraft\n countries: LocationOption[]\n states: LocationOption[]\n fieldError: BillingFieldError\n setBilling: Dispatch<SetStateAction<BillingDraft>>\n}\n\n/**\n * Address fields shared by the embedded and stepped billing experiences. The RN\n * analogue of the web `BillingAddressFields`: country/state `<select>` become the\n * native `../ui/Select`; text inputs keep the same placeholder copy.\n */\nexport const BillingAddressFields: FC<BillingAddressFieldsProps> = ({\n billing,\n countries,\n states,\n fieldError,\n setBilling,\n}) => {\n const setValue = (key: keyof BillingDraft) => (value: string) =>\n setBilling((current) => ({ ...current, [key]: value }))\n\n const countryOptions: SelectOption[] = countries.map((country) => ({\n label: country.name,\n value: String(country.id),\n }))\n const stateOptions: SelectOption[] = states.map((state) => ({\n label: state.name,\n value: String(state.id),\n }))\n\n return (\n <>\n <BodyText style={styles.sectionLabel}>Billing address *</BodyText>\n <Field error={fieldError('Street address', 'Street address is required.')}>\n <Input\n placeholder=\"Street address *\"\n value={billing.streetAddress ?? ''}\n onChangeText={setValue('streetAddress')}\n invalid={Boolean(fieldError('Street address'))}\n />\n </Field>\n <View style={styles.row}>\n <View style={styles.col}>\n <Field error={fieldError('City', 'City is required.')}>\n <Input\n placeholder=\"City *\"\n value={billing.city ?? ''}\n onChangeText={setValue('city')}\n invalid={Boolean(fieldError('City'))}\n />\n </Field>\n </View>\n <View style={styles.col}>\n <Field error={fieldError('ZIP / postcode', 'ZIP / postcode is required.')}>\n <Input\n placeholder=\"ZIP / Postcode *\"\n value={billing.zip ?? ''}\n onChangeText={setValue('zip')}\n keyboardType=\"numbers-and-punctuation\"\n invalid={Boolean(fieldError('ZIP / postcode'))}\n />\n </Field>\n </View>\n </View>\n <View style={styles.row}>\n <View style={styles.col}>\n <Field error={fieldError('Country', 'Country is required.')}>\n <Select\n value={billing.countryId ?? undefined}\n onChange={(value) => {\n const country = countries.find(\n (candidate) => String(candidate.id) === value\n )\n setBilling((current) => ({\n ...current,\n countryId: value,\n countryCode: country?.code?.toUpperCase(),\n stateId: undefined,\n stateCode: undefined,\n }))\n }}\n options={countryOptions}\n placeholder=\"— country * —\"\n invalid={Boolean(fieldError('Country'))}\n />\n </Field>\n </View>\n <View style={styles.col}>\n <Field error={fieldError('State / county', 'State / county is required.')}>\n <Select\n value={billing.stateId ?? undefined}\n onChange={(value) => {\n const state = states.find((candidate) => String(candidate.id) === value)\n setBilling((current) => ({\n ...current,\n stateId: value,\n stateCode: state?.code,\n }))\n }}\n options={stateOptions}\n placeholder={`— state / county${states.length > 0 ? ' *' : ''} —`}\n disabled={!billing.countryId || states.length === 0}\n invalid={Boolean(fieldError('State / county'))}\n />\n </Field>\n </View>\n </View>\n </>\n )\n}\n\nconst styles = StyleSheet.create({\n sectionLabel: { fontWeight: '600' },\n row: { flexDirection: 'row', gap: 10 },\n col: { flex: 1 },\n})\n","import React, { type FC } from 'react'\n\nimport type { BuyerFieldSpec } from 'tf-checkout-shared'\n\nimport { Field, Input } from '../../ui/Field'\nimport { Select, type SelectOption } from '../../ui/Select'\nimport type { LocationOption } from './types'\n\ninterface BuyerFieldProps {\n field: BuyerFieldSpec\n value: string\n countries: LocationOption[]\n error?: string\n onChange: (value: string) => void\n}\n\n/**\n * Renders one backend-configured buyer field without owning form state. The RN\n * analogue of the web `BuyerField`: the web `<select>`/`<option>` become the\n * native `../ui/Select` sheet; the Instagram field stays a text `Input`.\n */\nexport const BuyerField: FC<BuyerFieldProps> = ({\n field,\n value,\n countries,\n error,\n onChange,\n}) => {\n const invalid = error !== undefined && error !== null\n\n if (field.kind === 'gender') {\n const options: SelectOption[] = [\n { label: 'Male', value: 'M' },\n { label: 'Female', value: 'F' },\n ]\n return (\n <Field label={field.label} required={field.required} error={error}>\n <Select\n value={value || undefined}\n onChange={onChange}\n options={options}\n placeholder=\"— select —\"\n invalid={invalid}\n />\n </Field>\n )\n }\n\n if (field.kind === 'nationality') {\n const options: SelectOption[] = countries.map((country) => ({\n label: country.name,\n value: String(country.id),\n }))\n return (\n <Field label={field.label} required={field.required} error={error}>\n <Select\n value={value || undefined}\n onChange={onChange}\n options={options}\n placeholder=\"— select —\"\n invalid={invalid}\n />\n </Field>\n )\n }\n\n return (\n <Field label={field.label} required={field.required} error={error}>\n <Input\n placeholder=\"@handle or profile URL\"\n value={value}\n onChangeText={onChange}\n autoCapitalize=\"none\"\n invalid={invalid}\n />\n </Field>\n )\n}\n","import React, { type FC, type ReactNode } from 'react'\nimport { StyleSheet, View } from 'react-native'\n\nimport { Field, Input } from '../../ui/Field'\nimport { BodyText, Card, SectionHeader } from '../../ui/primitives'\nimport type { BillingFieldError, HolderDraft } from './types'\n\ninterface TicketHoldersCardProps {\n holders: HolderDraft[]\n holderNamesRequired: boolean\n collectHolderContact: boolean\n fieldError: BillingFieldError\n renderCustomFields: (holder: HolderDraft, index: number) => ReactNode\n patchHolder: (index: number, patch: Partial<HolderDraft>) => void\n}\n\n/**\n * Ticket-holder card kept separate from buyer billing for parity and reuse. The\n * RN analogue of the web `TicketHoldersCard`: the web `PhoneInput` lib becomes a\n * plain `Input` with `keyboardType=\"phone-pad\"`.\n */\nexport const TicketHoldersCard: FC<TicketHoldersCardProps> = ({\n holders,\n holderNamesRequired,\n collectHolderContact,\n fieldError,\n renderCustomFields,\n patchHolder,\n}) => (\n <Card>\n <SectionHeader title=\"Ticket Holders\" />\n {holders.map((holder, index) => {\n const firstNameKey = `Ticket ${index + 1} holder first name`\n const lastNameKey = `Ticket ${index + 1} holder last name`\n const emailKey = `Ticket ${index + 1} holder email`\n const phoneKey = `Ticket ${index + 1} holder phone`\n\n return (\n <View key={index} style={styles.holder}>\n <BodyText style={styles.holderTitle}>Ticket {index + 1}</BodyText>\n {holderNamesRequired ? (\n <View style={styles.row}>\n <View style={styles.col}>\n <Field\n label=\"First Name\"\n required\n error={fieldError(firstNameKey, 'First name is required.')}\n >\n <Input\n value={holder.firstName}\n onChangeText={(value) => patchHolder(index, { firstName: value })}\n autoCapitalize=\"words\"\n invalid={Boolean(fieldError(firstNameKey))}\n />\n </Field>\n </View>\n <View style={styles.col}>\n <Field\n label=\"Last Name\"\n required\n error={fieldError(lastNameKey, 'Last name is required.')}\n >\n <Input\n value={holder.lastName}\n onChangeText={(value) => patchHolder(index, { lastName: value })}\n autoCapitalize=\"words\"\n invalid={Boolean(fieldError(lastNameKey))}\n />\n </Field>\n </View>\n </View>\n ) : null}\n {collectHolderContact ? (\n <View style={styles.row}>\n <View style={styles.col}>\n <Field\n label=\"Email Address\"\n required\n error={fieldError(emailKey, 'Enter a valid email address.')}\n >\n <Input\n value={holder.email}\n onChangeText={(value) => patchHolder(index, { email: value })}\n keyboardType=\"email-address\"\n autoCapitalize=\"none\"\n invalid={Boolean(fieldError(emailKey))}\n />\n </Field>\n </View>\n <View style={styles.col}>\n <Field\n label=\"Phone\"\n required\n error={fieldError(phoneKey, 'Enter a valid phone number.')}\n >\n {/* Native: plain phone-pad Input in place of web's PhoneInput lib. */}\n <Input\n value={holder.phone}\n onChangeText={(value) => patchHolder(index, { phone: value })}\n keyboardType=\"phone-pad\"\n invalid={Boolean(fieldError(phoneKey))}\n />\n </Field>\n </View>\n </View>\n ) : null}\n {renderCustomFields(holder, index)}\n </View>\n )\n })}\n </Card>\n)\n\nconst styles = StyleSheet.create({\n holder: { gap: 12 },\n holderTitle: { fontWeight: '700' },\n row: { flexDirection: 'row', gap: 10 },\n col: { flex: 1 },\n})\n","/**\n * `<OrderSummary/>` — the priced cart lines + total, read off the shared\n * engine's `breakdown` (authoritative totals) and `priceBreakdown` (server\n * display-ready strings), with the event name from `useEvent`. The RN analogue\n * of the web `OrderSummary`. Presentation only; returns null until the cart has\n * tickets.\n */\nimport React, { type FC } from 'react'\nimport { StyleSheet, View } from 'react-native'\n\nimport { hooks } from 'tf-checkout-shared'\n\nimport { BodyText, Card, Divider, MutedText, SectionHeader } from '../ui/primitives'\nimport { useCheckoutContext, useTheme } from '../ui/CheckoutProvider'\n\n/** Fallback money formatter — server-priced strings (`priceBreakdown`) win when\n * present; this only formats the raw `breakdown` totals. Mirrors the web\n * `currencySymbol || \\`${currencyCode} \\`` rule. */\nconst money = (symbol: string, code: string, amount: number): string =>\n symbol ? `${symbol}${amount.toFixed(2)}` : `${code} ${amount.toFixed(2)}`\n\nexport interface OrderSummaryProps {\n /** Event whose name to show; omit to skip the event line. */\n eventId?: string\n}\n\n/** Storefront-compatible order summary shown after the checkout controls. */\nexport const OrderSummary: FC<OrderSummaryProps> = ({ eventId }) => {\n const checkout = useCheckoutContext()\n const theme = useTheme()\n const event = hooks.useEvent(eventId)\n const breakdown = checkout.breakdown\n const detailed = checkout.priceBreakdown\n\n if (!breakdown || breakdown.tickets.length === 0) return null\n\n const total =\n detailed?.total ??\n money(breakdown.currencySymbol, breakdown.currencyCode, Number(breakdown.total))\n\n return (\n <Card>\n <SectionHeader title=\"Order summary\" />\n\n {event.data?.name ? (\n <View style={styles.group}>\n <MutedText>Event</MutedText>\n <BodyText>{event.data.name}</BodyText>\n </View>\n ) : null}\n\n <View style={styles.group}>\n <MutedText>Your Tickets</MutedText>\n {breakdown.tickets.map((ticket, index) => {\n const detail = detailed?.tickets[index]\n const unit = detail?.unit_price ?? ticket.unit\n // Show the fee-inclusive line total only when it differs from the unit\n // price (matches web — a bare unit price would just repeat the line).\n const withFees =\n detail?.line_total && detail.line_total !== detail.unit_price\n ? detail.line_total\n : null\n return (\n <View key={`${ticket.ticketTypeId}-${index}`} style={styles.item}>\n <BodyText style={styles.tabular}>\n {ticket.quantity} x {ticket.name} - {unit} each\n </BodyText>\n {withFees ? (\n <MutedText style={styles.tabular}>({withFees} with fees)</MutedText>\n ) : null}\n </View>\n )\n })}\n </View>\n\n {(detailed?.add_ons.length ?? 0) > 0 ? (\n <View style={styles.group}>\n <MutedText>{detailed?.add_ons_title || 'Add-ons'}</MutedText>\n {detailed?.add_ons.map((addOn, index) => (\n <View key={`${addOn.name}-${index}`} style={styles.item}>\n <BodyText style={styles.tabular}>\n {addOn.quantity} x {addOn.name}\n {addOn.show_price ? ` - ${addOn.unit_price} each` : ''}\n </BodyText>\n </View>\n ))}\n </View>\n ) : null}\n\n <Divider />\n <View style={styles.totalRow}>\n <BodyText style={[styles.total, { fontSize: theme.fontSize + 1 }]}>\n Total\n </BodyText>\n <BodyText\n style={[styles.total, styles.tabular, { fontSize: theme.fontSize + 1 }]}\n >\n {total}\n </BodyText>\n </View>\n </Card>\n )\n}\n\nconst styles = StyleSheet.create({\n group: { gap: 4 },\n item: { gap: 2 },\n tabular: { fontVariant: ['tabular-nums'] },\n totalRow: {\n flexDirection: 'row',\n justifyContent: 'space-between',\n alignItems: 'center',\n gap: 12,\n },\n total: { fontWeight: '700' },\n})\n","/**\n * `<Payment/>` — order review + payment-method selection + T&C, then place the\n * order. The RN analogue of the web `Payment` section. Buyer details come from\n * `<BillingInfo/>` (read back off the shared checkout). The method list is built\n * from the event's gateway + `ttf.cart.preOrderMethods()` + the priced snapshot,\n * and each selection maps to the right `placeOrder` rail.\n *\n * Native adaptations vs web (all behaviour-preserving where the platform allows):\n * - No Stripe Payment Element / wallet widget: web folds Apple/Google Pay into\n * the Element and lists NO wallet rows, so neither do we. Native wallets are\n * confirmer legs (`placeOrder({method:'applePay'|'googlePay'})`) — a native\n * wallet button would slot in as an extra row triggering that request.\n * - The card slot renders the native `<CardInput/>` (Stripe `<CardField/>`) for\n * the Stripe card + payment-plan-new-card paths. Xendit card entry tokenizes\n * in a WebView sheet (deferred in `confirmer.ts`), so the Xendit card row\n * shows a note instead of a field; `placeOrder({method:'xenditCard'})` returns\n * the typed unsupported-gateway error until that WebView port is injected.\n * - Redirect rails / Razorpay / PayPal / Xendit e-wallets render their rows and\n * call `placeOrder` with the mapped request; the WebView `providerPage` port\n * that presents them is likewise a follow-up (see `confirmer.ts` header).\n * - Conditions render as plain text (HTML stripped) — no DOM to inject markup.\n */\nimport React, { useEffect, useMemo, useState, type FC } from 'react'\nimport { View } from 'react-native'\n\nimport {\n XENDIT_EWALLET_EXTRA_FIELD,\n errorMessage,\n missingCheckoutDetails,\n paymentPlanTerms,\n planConfirmLabel,\n planTermsTitle,\n ttf,\n type CheckoutPaymentPlanPreview,\n type EventCondition,\n type PaymentRequest,\n type PlaceOrderResult,\n} from 'tf-checkout-shared'\n\nimport { CardInput } from '../CardInput'\nimport { useCheckoutContext, useCheckoutValidation } from '../ui/CheckoutProvider'\nimport { Checkbox } from '../ui/Field'\nimport { PaymentMethods, type PaymentMethodOption } from '../ui/PaymentMethods'\nimport {\n BodyText,\n Button,\n Card,\n ErrorText,\n Loader,\n MutedText,\n SectionHeader,\n} from '../ui/primitives'\nimport { OrderSummary } from './OrderSummary'\n\ntype PreOrderMethods = Awaited<ReturnType<typeof ttf.cart.preOrderMethods>>\n\n/** Server spellings → display labels for Stripe redirect rails. */\nconst REDIRECT_LABELS: Record<string, string> = {\n klarna: 'Klarna',\n afterpay_clearpay: 'Afterpay / Clearpay',\n affirm: 'Affirm',\n ideal: 'iDEAL',\n bancontact: 'Bancontact',\n eps: 'EPS',\n giropay: 'giropay',\n p24: 'Przelewy24',\n alipay: 'Alipay',\n grabpay: 'GrabPay',\n cashapp: 'Cash App Pay',\n paypal: 'PayPal',\n}\nconst redirectLabel = (t: string) =>\n REDIRECT_LABELS[t] ?? t.replace(/_/g, ' ').replace(/\\b\\w/g, (c) => c.toUpperCase())\n\n/** Strip HTML from condition copy — native has no DOM to render markup into. */\nconst stripHtml = (html: string) =>\n html\n .replace(/<[^>]*>/g, '')\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/ /g, ' ')\n .replace(/'/g, \"'\")\n .replace(/"/g, '\"')\n .trim()\n\nexport interface PaymentProps {\n onComplete?: (order: PlaceOrderResult) => void\n /** Optional event context (parity with web; native `OrderSummary` reads the\n * priced cart, not the event, so it is currently unused here). */\n eventId?: string\n /** Must match the policy used by the paired `<BillingInfo/>`. */\n requireEmailConfirmation?: boolean\n /** Must match the holder policy used by the paired `<BillingInfo/>`. */\n collectTicketHolders?: boolean\n /** Must match the holder-contact policy used by the paired `<BillingInfo/>`. */\n requireHolderContact?: boolean\n /** Host-owned acknowledgements such as a brand privacy policy. */\n additionalConditions?: EventCondition[]\n /** Require the privacy checkbox managed by BillingInfo before payment. */\n requirePrivacyPolicy?: boolean\n /** Called when payment is attempted before required privacy consent. */\n onPrivacyRequired?: () => void\n /** Test card copy is useful in examples, but should never appear by default. */\n showTestCardHint?: boolean\n}\n\n/**\n * Payment-plan terms — the full hosted disclosure block (schedule, admin fee,\n * non-refundable clause, brand message, activation note). Composed in the SDK\n * so this matches web word for word; these are disclosures, not summary copy.\n */\nconst PlanTerms: FC<{ plan: CheckoutPaymentPlanPreview }> = ({ plan }) => {\n const parts = paymentPlanTerms(plan)\n if (parts.length === 0) return null\n return (\n <View style={{ gap: 4 }}>\n <BodyText style={{ fontWeight: '700' }}>{planTermsTitle(plan)}</BodyText>\n {parts.map((part) => (\n <MutedText key={part.id}>{part.text}</MutedText>\n ))}\n </View>\n )\n}\n\nexport const Payment: FC<PaymentProps> = ({\n onComplete,\n // `eventId` is accepted for prop-parity with web; the native `OrderSummary`\n // reads the priced cart (not the event), so it is intentionally unused here.\n eventId,\n requireEmailConfirmation = false,\n collectTicketHolders = false,\n requireHolderContact = false,\n additionalConditions = [],\n requirePrivacyPolicy = false,\n onPrivacyRequired,\n showTestCardHint = false,\n}) => {\n const checkout = useCheckoutContext()\n const validation = useCheckoutValidation()\n const [error, setError] = useState('')\n const [methods, setMethods] = useState<PreOrderMethods | null>(null)\n const [selected, setSelected] = useState('')\n const [extras, setExtras] = useState<\n Record<string, { cashtag?: string; phoneNumber?: string }>\n >({})\n const [useSavedCard, setUseSavedCard] = useState(true)\n\n useEffect(() => {\n let active = true\n ttf.cart\n .preOrderMethods()\n .then((m) => active && setMethods(m))\n .catch(() => active && setMethods(null))\n return () => {\n active = false\n }\n }, [])\n\n const bd = checkout.breakdown\n const isFree = bd !== undefined && Number(bd.total) === 0\n const isXendit = checkout.gateway === 'xendit'\n\n // Build the selectable method rows from gateway + probe + snapshot.\n const options = useMemo<PaymentMethodOption[]>(() => {\n if (isFree || !methods) return []\n const out: PaymentMethodOption[] = []\n if (isXendit) {\n if (methods.xenditCard)\n out.push({ id: { kind: 'xenditCard' }, value: 'xenditCard', label: 'Card' })\n for (const w of methods.xenditEWallets)\n out.push({\n id: { kind: 'xenditEWallet', walletKey: w.key },\n value: `ew:${w.key}`,\n label: w.label,\n iconUrl: w.icon,\n extra: (XENDIT_EWALLET_EXTRA_FIELD[w.key] as 'cashtag' | 'phoneNumber') ?? null,\n })\n } else if (checkout.gateway === 'razorpay') {\n out.push({ id: { kind: 'razorpay' }, value: 'razorpay', label: 'Razorpay' })\n } else {\n // Stripe (or unknown → fail open to card).\n out.push({ id: { kind: 'card' }, value: 'card', label: 'Card' })\n for (const t of checkout.redirectPaymentMethods ?? []) {\n if (t === 'paypal' && methods.paypal) continue // dedupe vs PayPal Standard\n out.push({\n id: { kind: 'redirect', methodType: t },\n value: `rd:${t}`,\n label: redirectLabel(t),\n })\n }\n if (checkout.paymentPlan?.available)\n out.push({\n id: { kind: 'paymentPlan' },\n value: 'paymentPlan',\n label: 'Payment plan',\n })\n // OXXO cash voucher — Mexico only, and never listed in redirect methods.\n if (checkout.breakdown?.currencyCode === 'MXN')\n out.push({ id: { kind: 'oxxo' }, value: 'oxxo', label: 'OXXO (pay in cash)' })\n }\n if (methods.paypal)\n out.push({ id: { kind: 'paypal' }, value: 'paypal', label: 'PayPal' })\n return out\n }, [\n isFree,\n methods,\n isXendit,\n checkout.gateway,\n checkout.redirectPaymentMethods,\n checkout.paymentPlan,\n checkout.breakdown,\n ])\n\n // Default the selection to the first row once options exist.\n useEffect(() => {\n if (options.length && !options.some((o) => o.value === selected))\n setSelected(options[0].value)\n }, [options, selected])\n\n const cardValue = isXendit ? 'xenditCard' : 'card'\n const selectedOption = options.find((o) => o.value === selected)\n const isCardSelected = selected === cardValue\n const isPlanSelected = selectedOption?.id.kind === 'paymentPlan'\n // The native Stripe card field: shown for the Stripe card path and for a\n // payment-plan NEW card (SetupIntent). Xendit card is a WebView sheet (below).\n const showStripeCardField =\n !isXendit && (isCardSelected || (isPlanSelected && !useSavedCard))\n const showXenditCardNote = isXendit && isCardSelected\n\n // When there's only ONE way to pay and it's a card, there's nothing to\n // *choose* — render the field directly, no radio wrapper (matching web).\n const onlyOption = options.length === 1 ? options[0] : undefined\n const singleCard =\n onlyOption?.id.kind === 'card' || onlyOption?.id.kind === 'xenditCard'\n\n // Gating: buyer + every configured holder/custom field complete, required\n // conditions accepted, and payment-method extras filled.\n const b = checkout.billing\n const missingDetails = missingCheckoutDetails(\n {\n billing: b,\n holders: checkout.holders,\n selections: checkout.selections,\n breakdown: checkout.breakdown,\n holderNamesRequired: checkout.holderNamesRequired,\n fieldGates: checkout.fieldGates,\n customFields: checkout.customFields,\n },\n { requireEmailConfirmation, collectTicketHolders, requireHolderContact }\n )\n const billingReady = missingDetails.length === 0\n const conditions = [...(checkout.conditions ?? []), ...additionalConditions]\n const requiredConditions = conditions.filter((c) => c.isRequired)\n const conditionsOk = requiredConditions.every(\n (c) => checkout.acceptedConditions?.[c.id]\n )\n const extra = selectedOption?.extra\n const extrasOk =\n !extra ||\n (extra === 'cashtag'\n ? Boolean(extras[selected]?.cashtag?.trim())\n : Boolean(extras[selected]?.phoneNumber?.trim()))\n const privacyOk = !requirePrivacyPolicy || checkout.consent.ttfOptIn\n // The plan CTA carries the brand's terminology (\"Confirm Layaway\"), and the\n // terms sentence quotes this same label — they must agree.\n const payLabel = isFree\n ? 'Complete Registration'\n : isPlanSelected\n ? planConfirmLabel(checkout.paymentPlan?.configuration)\n : 'Submit Payment'\n // 'placing' → order in flight; 'succeeded' → placed, host navigating away.\n // Both keep the CTA busy so it can't be re-clicked during the handoff.\n const finalizing = checkout.status === 'placing' || checkout.status === 'succeeded'\n\n const pay = () => {\n setError('')\n if (!billingReady || !conditionsOk || !extrasOk || !privacyOk) {\n if (!privacyOk) onPrivacyRequired?.()\n validation.requestValidation()\n return\n }\n // Backfill one holder per ticket if billing was set without holders.\n if (checkout.holders.length === 0 && b) {\n const n = checkout.selections.reduce((acc, s) => acc + s.quantity, 0) || 1\n checkout.setHolders(\n Array.from({ length: n }, () => ({\n firstName: b.firstName,\n lastName: b.lastName,\n email: b.email,\n }))\n )\n }\n let req: PaymentRequest = { method: 'auto' }\n const id = selectedOption?.id\n if (isFree || !id) req = { method: 'auto' }\n else if (id.kind === 'xenditEWallet')\n req = { method: 'xenditEWallet', walletKey: id.walletKey, extra: extras[selected] }\n else if (id.kind === 'redirect')\n req = { method: 'redirect', methodType: id.methodType }\n else if (id.kind === 'paymentPlan') req = { method: 'paymentPlan', useSavedCard }\n else req = { method: id.kind } as PaymentRequest\n // Called synchronously in the press handler — popup rails (e-wallet,\n // redirect, razorpay, paypal) want the user gesture on their WebView host.\n checkout\n .placeOrder(req)\n .then((order) => onComplete?.(order))\n .catch((e) => setError(errorMessage(e)))\n }\n\n const savedLast4 = checkout.paymentPlan?.savedCardLast4\n const checkoutError = checkout.error ?? ''\n\n // The card/plan field + its note + plan terms. Rendered inside the selected\n // method row when there's a choice, or directly when there's only a card.\n const testHint = isXendit\n ? 'Test card: 4000 0000 0000 0002 · any future date · any CVC'\n : 'Test card: 4242 4242 4242 4242 · any future date · any CVC'\n const paymentInput = (\n <>\n {showStripeCardField ? <CardInput /> : null}\n {showXenditCardNote ? (\n // Xendit card tokenizes in a WebView sheet (deferred — see confirmer.ts).\n <MutedText>\n Card details are entered in a secure Xendit window when you pay.\n </MutedText>\n ) : null}\n {showTestCardHint && (showStripeCardField || showXenditCardNote) ? (\n <MutedText>{testHint}</MutedText>\n ) : null}\n {isPlanSelected && checkout.paymentPlan?.configuration ? (\n <PlanTerms plan={checkout.paymentPlan.configuration} />\n ) : null}\n {/* Returning plan buyer with a reusable card on file. Ticked by default,\n and when it stays ticked the card field never mounts — the plan is\n created straight off the saved payment method, like the hosted flow. */}\n {isPlanSelected && savedLast4 ? (\n <View style={{ gap: 4 }}>\n <MutedText>\n Your payment will proceed with the card ending in **** {savedLast4}\n </MutedText>\n <Checkbox checked={useSavedCard} onChange={setUseSavedCard} label=\"Use this card\" />\n </View>\n ) : null}\n </>\n )\n\n return (\n <View style={{ gap: 12 }}>\n <Card>\n <SectionHeader title=\"Payment\" />\n\n {/* Payment method */}\n {!isFree ? (\n <>\n {!singleCard ? <MutedText>Payment method</MutedText> : null}\n {!methods ? (\n <Loader />\n ) : singleCard ? (\n paymentInput\n ) : (\n <PaymentMethods\n options={options}\n selected={selected}\n onSelect={setSelected}\n extraValues={extras}\n onExtraChange={(v, patch) =>\n setExtras((s) => ({ ...s, [v]: { ...s[v], ...patch } }))\n }\n showValidation={validation.attempt > 0}\n inputSlotFor={\n isPlanSelected ? (useSavedCard ? undefined : 'paymentPlan') : cardValue\n }\n >\n {paymentInput}\n </PaymentMethods>\n )}\n </>\n ) : null}\n\n {/* Conditions */}\n {conditions.map((c) => {\n const invalid =\n validation.attempt > 0 && c.isRequired && !checkout.acceptedConditions?.[c.id]\n return (\n <View key={c.id} style={{ gap: 4 }}>\n <Checkbox\n checked={Boolean(checkout.acceptedConditions?.[c.id])}\n invalid={invalid}\n onChange={(next) => checkout.acceptCondition(c.id, next)}\n label={`${stripHtml(c.content || c.name)}${c.isRequired ? ' *' : ''}`}\n />\n {invalid ? (\n <ErrorText>You must accept this condition to continue.</ErrorText>\n ) : null}\n </View>\n )\n })}\n </Card>\n\n <OrderSummary />\n\n <Button\n onPress={pay}\n // Stay busy through 'succeeded' too: in redirect mode the checkout\n // remains mounted while the host navigates away, so the button must not\n // flip back to a clickable state before the redirect lands.\n loading={finalizing}\n disabled={checkout.isBusy || finalizing || (!isFree && !methods)}\n >\n {finalizing ? 'Placing…' : payLabel}\n </Button>\n\n {error || checkoutError ? <ErrorText>{error || checkoutError}</ErrorText> : null}\n </View>\n )\n}\n","/**\n * `<IDVerification/>` — shown after an order that needs identity verification\n * (`order.needIdVerification`). Kicks off the engine's verify flow: mint the\n * provider URL, open it, and poll to completion, reflecting each phase. The\n * order is already paid — a stall here never means a failed payment. The RN\n * analogue of the web `IDVerification`.\n *\n * If you place your order with `placeOrder(method, { autoRunIdVerification:true })`\n * the engine runs this for you; this section is the manual, visible counterpart.\n *\n * Native adaptation vs web: the provider page opens via `Linking.openURL`\n * (React Native) rather than `window.open(url, '_blank')`.\n */\nimport React, { useState, type FC } from 'react'\nimport { Linking } from 'react-native'\n\nimport { errorMessage, type IdVerificationPhase } from 'tf-checkout-shared'\n\nimport { BodyText, Button, Card, ErrorText, SectionHeader } from '../ui/primitives'\nimport { useCheckoutContext, useTheme } from '../ui/CheckoutProvider'\n\ntype UiPhase = IdVerificationPhase | 'starting'\n\nconst MESSAGE: Record<UiPhase, string> = {\n idle: 'To complete the purchase, please verify your identity.',\n starting: 'Opening the verification page…',\n polling: 'Waiting for verification to complete in the other tab…',\n verified: 'Identity verified — your tickets are on their way.',\n timeout: 'Still not confirmed. Finish in the other tab, then check again.',\n error: 'We couldn’t reach the verification service. Try again.',\n}\n\nexport const IDVerification: FC = () => {\n const checkout = useCheckoutContext()\n const theme = useTheme()\n const order = checkout.order\n const [phase, setPhase] = useState<UiPhase>('idle')\n const [error, setError] = useState('')\n\n if (!order?.needIdVerification) return null\n\n const done = phase === 'verified'\n const running = phase === 'starting' || phase === 'polling'\n\n const run = () => {\n setError('')\n setPhase('starting')\n checkout\n .runIdVerification(order.orderHash, {\n // Native: open the provider page with Linking (web uses window.open).\n openUrl: (url) => {\n if (url) Linking.openURL(url).catch(() => undefined)\n },\n onPhase: (p) => setPhase(p),\n })\n .then((status) => setPhase(status?.verified ? 'verified' : 'polling'))\n .catch((e) => {\n setPhase('error')\n setError(errorMessage(e))\n })\n }\n\n return (\n <Card>\n <SectionHeader title=\"Account Verification\" />\n <BodyText style={done ? { color: theme.success } : undefined}>\n {MESSAGE[phase]}\n </BodyText>\n {!done ? (\n <Button onPress={run} loading={running} disabled={running}>\n {phase === 'idle' ? 'Verify' : running ? 'Verifying…' : 'Check again'}\n </Button>\n ) : null}\n {error ? <ErrorText>{error}</ErrorText> : null}\n </Card>\n )\n}\n","/**\n * `<Confirmation/>` — the order-placed receipt + a referral/share growth block,\n * read off `checkout.order`; returns null until an order exists. The RN analogue\n * of the web `Confirmation`.\n *\n * Native adaptations vs web:\n * - There is no `window.location.href`, so the share URL comes only from the\n * `shareUrl` prop (no implicit \"current page\" fallback).\n * - The web version renders three per-network links (Facebook / X / WhatsApp).\n * On native those collapse into ONE `Share.share()` call — the OS share sheet\n * already offers every installed app, so per-network buttons are redundant.\n * - Voucher / \"View my tickets\" links open via `Linking.openURL` instead of\n * anchor tags.\n */\nimport React, { useState, type FC, type ReactNode } from 'react'\nimport { Linking, Share, StyleSheet, Text, View } from 'react-native'\n\n// `@react-native-clipboard/clipboard` is a dependency of this package.\nimport Clipboard from '@react-native-clipboard/clipboard'\n\nimport { BodyText, Button, Card, MutedText, SectionHeader } from '../ui/primitives'\nimport { Input } from '../ui/Field'\nimport { useCheckoutContext, useTheme } from '../ui/CheckoutProvider'\n\nexport interface ConfirmationProps {\n /** URL friends land on (referral/event page). No implicit current-page\n * fallback on native — omit to hide the share block. */\n shareUrl?: string\n /** Message prefilled into the native share sheet. */\n shareMessage?: string\n /** Link to the buyer's tickets/order — renders a \"View my tickets\" button. */\n viewOrderUrl?: string\n /** Override the body copy (otherwise it varies on the order state). */\n message?: string\n /** Extra content (e.g. your own referral-reward ladder from the order payload). */\n children?: ReactNode\n}\n\nexport const Confirmation: FC<ConfirmationProps> = ({\n shareUrl,\n shareMessage = 'I just got my tickets — grab yours!',\n viewOrderUrl,\n message,\n children,\n}) => {\n const checkout = useCheckoutContext()\n const theme = useTheme()\n const order = checkout.order\n const [copied, setCopied] = useState(false)\n\n if (!order) return null\n const pending = order.pending\n\n // No `window.location` on native — the share URL is the prop or nothing.\n const url = shareUrl ?? ''\n\n const title = pending\n ? 'Payment pending'\n : order.free\n ? 'Registration complete'\n : 'Your Tickets are Confirmed!'\n\n const note = pending\n ? 'We’ll email your tickets as soon as the payment settles.'\n : order.alreadyPaid\n ? 'This order was already paid — nothing was charged again.'\n : order.free\n ? 'You’re registered — check your email for your confirmation.'\n : 'Your tickets are available in the My Tickets section — please bring them with you to the event.'\n\n const openUrl = (target: string) => {\n Linking.openURL(target).catch(() => undefined)\n }\n\n const copy = () => {\n if (!url) return\n Clipboard.setString(url)\n setCopied(true)\n setTimeout(() => setCopied(false), 1500)\n }\n\n const share = () => {\n if (!url) return\n // Facebook / X / WhatsApp collapse into the single native share sheet.\n Share.share({ message: `${shareMessage} ${url}`, url }).catch(() => undefined)\n }\n\n return (\n <Card>\n <View style={styles.glyphWrap}>\n <Text style={[styles.glyph, { color: pending ? theme.muted : theme.success }]}>\n {pending ? '⏳' : '✓'}\n </Text>\n </View>\n\n <SectionHeader title={title} />\n <BodyText>{message ?? note}</BodyText>\n\n {order.orderHash ? <MutedText>Reference: {order.orderHash}</MutedText> : null}\n\n {pending && order.pendingVoucherUrl ? (\n <Button\n variant=\"ghost\"\n onPress={() => openUrl(order.pendingVoucherUrl as string)}\n >\n View payment voucher\n </Button>\n ) : null}\n\n {viewOrderUrl ? (\n <Button variant=\"ghost\" onPress={() => openUrl(viewOrderUrl)}>\n View my tickets\n </Button>\n ) : null}\n\n {children}\n\n {/* Referral / share — invite friends for cheaper (or free) tickets. */}\n {!pending && url ? (\n <View style={styles.share}>\n <BodyText style={styles.shareHeading}>\n Your tickets can be cheaper — or even FREE!\n </BodyText>\n <MutedText>\n Invite friends with your link. When they buy, you get rewarded.\n </MutedText>\n <Input value={url} onChangeText={() => undefined} editable={false} />\n <Button variant=\"ghost\" onPress={copy}>\n {copied ? 'Copied!' : 'Copy link'}\n </Button>\n <Button onPress={share}>Share</Button>\n </View>\n ) : null}\n </Card>\n )\n}\n\nconst styles = StyleSheet.create({\n glyphWrap: { alignItems: 'center', paddingVertical: 4 },\n glyph: { fontSize: 44, fontWeight: '800' },\n share: { gap: 10 },\n shareHeading: { fontWeight: '700' },\n})\n","/**\n * `<AuthModal/>` — sign-in / create-account / password-reset sheet over the\n * shared headless `hooks.useAuthFlow`. The RN analogue of the web `AuthModal`:\n * same flow contract (validation, mutations, errors, view transitions,\n * suggested-email carry-over), re-skinned as a native bottom-sheet `Modal`.\n *\n * Native adaptations vs. the web modal:\n * - No DOM focus-trap, `Tab` cycling, or `body` scroll-lock — the native\n * `Modal` already traps focus and blocks background interaction. Backdrop\n * press and the hardware back button close it (unless a submit is running).\n * - The web logo is an SVG `<img>`; RN can't render an SVG URL without an\n * extra library, so the logo is an optional `<Image>` shown only when a\n * (raster) `logoUrl` is supplied — no built-in SVG default.\n *\n * Render inside `<CheckoutProvider>` so it inherits the theme + query client.\n */\nimport React, { useCallback, type FC } from 'react'\nimport { Image, Modal, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'\n\nimport { hooks, type TfProfile } from 'tf-checkout-shared'\n\nimport { MutedText } from '../ui/primitives'\nimport { useTheme } from '../ui/CheckoutProvider'\nimport { ForgotPasswordForm } from './ForgotPasswordForm'\nimport { LoginForm } from './LoginForm'\nimport { RegisterForm } from './RegisterForm'\n\nexport interface AuthModalProps {\n open: boolean\n onClose: () => void\n allowRegistration?: boolean\n allowPasswordReset?: boolean\n requireRegistrationAddress?: boolean\n /** Optional raster logo shown above the form. */\n logoUrl?: string\n onAuthenticated?: (profile: TfProfile) => void\n initialEmail?: string\n /** Optional context shown above the active form. */\n message?: string\n}\n\n/** A single Login / Sign Up tab. */\nconst Tab: FC<{ label: string; active: boolean; onPress: () => void }> = ({\n label,\n active,\n onPress,\n}) => {\n const theme = useTheme()\n return (\n <Pressable\n accessibilityRole=\"tab\"\n accessibilityState={{ selected: active }}\n onPress={onPress}\n style={[styles.tab, { borderBottomColor: active ? theme.accent : 'transparent' }]}\n >\n <Text style={[styles.tabText, { color: active ? theme.text : theme.muted }]}>\n {label}\n </Text>\n </Pressable>\n )\n}\n\nexport const AuthModal: FC<AuthModalProps> = ({\n open,\n onClose,\n allowRegistration = true,\n allowPasswordReset = true,\n requireRegistrationAddress = true,\n logoUrl,\n onAuthenticated,\n initialEmail,\n message,\n}) => {\n const theme = useTheme()\n const closeAfterAuth = useCallback(\n (profile: TfProfile) => {\n onAuthenticated?.(profile)\n onClose()\n },\n [onAuthenticated, onClose]\n )\n const auth = hooks.useAuthFlow({\n initialEmail,\n requireRegistrationAddress,\n onAuthenticated: closeAfterAuth,\n })\n\n const isPasswordReset = auth.view === 'forgot-password'\n const showTabs = allowRegistration && !isPasswordReset\n // Don't let a backdrop / back-button dismiss interrupt an in-flight submit.\n const requestClose = () => {\n if (!auth.isSubmitting) onClose()\n }\n\n return (\n <Modal visible={open} animationType=\"slide\" transparent onRequestClose={requestClose}>\n <Pressable style={styles.backdrop} onPress={requestClose}>\n {/* Inner press swallows taps so they don't bubble to the backdrop. */}\n <Pressable\n style={[styles.sheet, { backgroundColor: theme.surface }]}\n onPress={() => {}}\n >\n <View style={styles.header}>\n <Text style={[styles.title, { color: theme.text }]}>\n {isPasswordReset ? 'Password reset' : 'Ticket Fairy account'}\n </Text>\n <Pressable\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close\"\n disabled={auth.isSubmitting}\n onPress={onClose}\n hitSlop={12}\n >\n <Text style={[styles.close, { color: theme.muted }]}>✕</Text>\n </Pressable>\n </View>\n\n <ScrollView\n contentContainerStyle={styles.body}\n keyboardShouldPersistTaps=\"handled\"\n >\n {logoUrl ? (\n <Image\n accessibilityLabel=\"The Ticket Fairy\"\n source={{ uri: logoUrl }}\n style={styles.logo}\n resizeMode=\"contain\"\n />\n ) : null}\n\n {showTabs ? (\n <View style={[styles.tabs, { borderBottomColor: theme.border }]}>\n <Tab\n label=\"Login\"\n active={auth.view === 'login'}\n onPress={() => auth.showLogin(auth.suggestedEmail)}\n />\n <Tab\n label=\"Sign Up\"\n active={auth.view === 'register'}\n onPress={() => auth.showRegister(auth.suggestedEmail)}\n />\n </View>\n ) : null}\n\n {message && !isPasswordReset ? <MutedText>{message}</MutedText> : null}\n\n {auth.view === 'login' ? (\n <LoginForm\n initialEmail={auth.suggestedEmail}\n errors={auth.fieldErrors}\n error={auth.error}\n loading={auth.isSubmitting}\n allowPasswordReset={allowPasswordReset}\n onSubmit={auth.submitLogin}\n onForgotPassword={auth.showForgotPassword}\n onFieldChange={auth.clearFieldError}\n />\n ) : null}\n\n {auth.view === 'register' && allowRegistration ? (\n <RegisterForm\n initialEmail={auth.suggestedEmail}\n errors={auth.fieldErrors}\n error={auth.error}\n loading={auth.isSubmitting}\n requireAddress={requireRegistrationAddress}\n onSubmit={auth.submitRegistration}\n onFieldChange={auth.clearFieldError}\n />\n ) : null}\n\n {isPasswordReset ? (\n <ForgotPasswordForm\n initialEmail={auth.suggestedEmail}\n errors={auth.fieldErrors}\n error={auth.error}\n successMessage={auth.successMessage}\n loading={auth.isSubmitting}\n onSubmit={auth.submitPasswordReset}\n onBackToLogin={auth.showLogin}\n onFieldChange={() => auth.clearFieldError('email')}\n />\n ) : null}\n </ScrollView>\n </Pressable>\n </Pressable>\n </Modal>\n )\n}\n\nconst styles = StyleSheet.create({\n backdrop: { flex: 1, justifyContent: 'flex-end', backgroundColor: 'rgba(0,0,0,0.4)' },\n sheet: {\n borderTopLeftRadius: 20,\n borderTopRightRadius: 20,\n maxHeight: '90%',\n paddingBottom: 24,\n },\n header: {\n flexDirection: 'row',\n alignItems: 'center',\n justifyContent: 'space-between',\n padding: 20,\n },\n title: { fontSize: 18, fontWeight: '700' },\n close: { fontSize: 18 },\n body: { paddingHorizontal: 20, paddingBottom: 8, gap: 16 },\n logo: { width: '100%', height: 44, alignSelf: 'center' },\n tabs: {\n flexDirection: 'row',\n borderBottomWidth: StyleSheet.hairlineWidth,\n },\n tab: {\n flex: 1,\n alignItems: 'center',\n paddingVertical: 12,\n borderBottomWidth: 2,\n },\n tabText: { fontSize: 15, fontWeight: '600' },\n})\n","/**\n * `<ForgotPasswordForm/>` — native password-recovery presentation over the\n * shared auth-flow controller. Mirrors the web form: an email prompt that, once\n * the reset request succeeds, swaps to a success state with a \"Back to log in\"\n * action.\n */\nimport React, { useEffect, useState, type FC } from 'react'\nimport { Pressable, StyleSheet, Text, View } from 'react-native'\n\nimport type { AuthFieldErrors } from 'tf-checkout-shared'\n\nimport { Button, ErrorText, MutedText } from '../ui/primitives'\nimport { Field, Input } from '../ui/Field'\nimport { useTheme } from '../ui/CheckoutProvider'\n\nexport interface ForgotPasswordFormProps {\n initialEmail?: string\n errors?: AuthFieldErrors\n error?: string\n successMessage?: string\n loading?: boolean\n onSubmit: (email: string) => void | Promise<unknown>\n onBackToLogin: (email: string) => void\n onFieldChange?: () => void\n}\n\nexport const ForgotPasswordForm: FC<ForgotPasswordFormProps> = ({\n initialEmail = '',\n errors = {},\n error,\n successMessage,\n loading = false,\n onSubmit,\n onBackToLogin,\n onFieldChange,\n}) => {\n const theme = useTheme()\n const [email, setEmail] = useState(initialEmail)\n\n useEffect(() => {\n if (initialEmail && !email) setEmail(initialEmail)\n }, [email, initialEmail])\n\n const submit = () => void onSubmit(email)\n\n if (successMessage) {\n return (\n <View style={styles.form}>\n <Text style={[styles.success, { color: theme.success }]}>{successMessage}</Text>\n <Button onPress={() => onBackToLogin(email)}>Back to log in</Button>\n </View>\n )\n }\n\n return (\n <View style={styles.form}>\n <MutedText>\n Enter your email and we’ll send you instructions to reset your password.\n </MutedText>\n\n {error ? <ErrorText>{error}</ErrorText> : null}\n\n <Field label=\"Email\" required error={errors.email}>\n <Input\n value={email}\n onChangeText={(text) => {\n setEmail(text)\n onFieldChange?.()\n }}\n placeholder=\"Email\"\n keyboardType=\"email-address\"\n autoCapitalize=\"none\"\n invalid={Boolean(errors.email)}\n />\n </Field>\n\n <Button onPress={submit} loading={loading}>\n Send reset instructions\n </Button>\n\n <Pressable\n accessibilityRole=\"button\"\n onPress={() => onBackToLogin(email)}\n hitSlop={8}\n style={styles.link}\n >\n <Text style={[styles.linkText, { color: theme.accent }]}>Back to log in</Text>\n </Pressable>\n </View>\n )\n}\n\nconst styles = StyleSheet.create({\n form: { gap: 14 },\n success: { fontSize: 15, fontWeight: '600' },\n link: { alignItems: 'center', paddingVertical: 4 },\n linkText: { fontSize: 14, fontWeight: '600' },\n})\n","/**\n * `<LoginForm/>` — native email + password form. Pure presentation: it holds\n * only local field state and delegates every auth concern (validation,\n * mutation, errors) to its caller, exactly like the web `LoginForm`.\n */\nimport React, { useEffect, useState, type FC } from 'react'\nimport { Pressable, StyleSheet, Text, View } from 'react-native'\n\nimport type { AuthFieldErrors, AuthLoginInput } from 'tf-checkout-shared'\n\nimport { Button, ErrorText } from '../ui/primitives'\nimport { Field, Input } from '../ui/Field'\nimport { useTheme } from '../ui/CheckoutProvider'\nimport { PasswordInput } from './PasswordInput'\n\nexport interface LoginFormProps {\n initialEmail?: string\n errors?: AuthFieldErrors\n error?: string\n loading?: boolean\n allowPasswordReset?: boolean\n onSubmit: (input: AuthLoginInput) => void | Promise<unknown>\n onForgotPassword?: (email: string) => void\n onFieldChange?: (field: keyof AuthLoginInput) => void\n}\n\nexport const LoginForm: FC<LoginFormProps> = ({\n initialEmail = '',\n errors = {},\n error,\n loading = false,\n allowPasswordReset = true,\n onSubmit,\n onForgotPassword,\n onFieldChange,\n}) => {\n const theme = useTheme()\n const [email, setEmail] = useState(initialEmail)\n const [password, setPassword] = useState('')\n\n useEffect(() => {\n if (initialEmail && !email) setEmail(initialEmail)\n }, [email, initialEmail])\n\n const submit = () => void onSubmit({ email, password })\n\n return (\n <View style={styles.form}>\n {error ? <ErrorText>{error}</ErrorText> : null}\n\n <Field label=\"Email\" required error={errors.email}>\n <Input\n value={email}\n onChangeText={(text) => {\n setEmail(text)\n onFieldChange?.('email')\n }}\n placeholder=\"Email\"\n keyboardType=\"email-address\"\n autoCapitalize=\"none\"\n invalid={Boolean(errors.email)}\n />\n </Field>\n\n <Field label=\"Password\" required error={errors.password}>\n <PasswordInput\n value={password}\n onChangeText={(text) => {\n setPassword(text)\n onFieldChange?.('password')\n }}\n placeholder=\"Password\"\n invalid={Boolean(errors.password)}\n />\n </Field>\n\n <Button onPress={submit} loading={loading}>\n Login\n </Button>\n\n {allowPasswordReset && onForgotPassword ? (\n <Pressable\n accessibilityRole=\"button\"\n onPress={() => onForgotPassword(email)}\n hitSlop={8}\n style={styles.link}\n >\n <Text style={[styles.linkText, { color: theme.accent }]}>Forgot password?</Text>\n </Pressable>\n ) : null}\n </View>\n )\n}\n\nconst styles = StyleSheet.create({\n form: { gap: 14 },\n link: { alignItems: 'center', paddingVertical: 4 },\n linkText: { fontSize: 14, fontWeight: '600' },\n})\n","/**\n * `<PasswordInput/>` — the RN analogue of the web password field's reveal\n * affordance. Wraps the shared `Input` in `secureTextEntry` mode and overlays a\n * tap-to-toggle eye. Native has no SVG by default, so the icon is a plain emoji\n * `Text` toggle (👁 / 🙈) rather than the web's inline `<svg>`. `forwardRef` is\n * not needed here — nothing in the native flow reaches for the input node.\n */\nimport React, { useState, type FC } from 'react'\nimport { Pressable, StyleSheet, Text, View } from 'react-native'\n\nimport { Input, type InputProps } from '../ui/Field'\n\nexport type PasswordInputProps = Omit<InputProps, 'secureTextEntry'>\n\nexport const PasswordInput: FC<PasswordInputProps> = (props) => {\n const [visible, setVisible] = useState(false)\n return (\n <View style={styles.wrap}>\n {/* Keep `secureTextEntry` after the spread so it always reflects `visible`. */}\n <Input {...props} autoCapitalize=\"none\" secureTextEntry={!visible} />\n <Pressable\n accessibilityRole=\"button\"\n accessibilityLabel={visible ? 'Hide password' : 'Show password'}\n accessibilityState={{ selected: visible }}\n onPress={() => setVisible((current) => !current)}\n hitSlop={10}\n style={styles.toggle}\n >\n <Text style={styles.icon}>{visible ? '🙈' : '👁'}</Text>\n </Pressable>\n </View>\n )\n}\n\nconst styles = StyleSheet.create({\n wrap: { position: 'relative', justifyContent: 'center' },\n toggle: {\n position: 'absolute',\n right: 10,\n top: 0,\n bottom: 0,\n justifyContent: 'center',\n },\n icon: { fontSize: 18 },\n})\n","/**\n * `<RegisterForm/>` — native create-account form. Same field contract as the\n * web `RegisterForm` (all validation delegated to the shared controller), with\n * two native adaptations:\n * - the web `<select>`s become the native `<Select/>` bottom-sheet picker;\n * - there's no `react-international-phone` on native, so Phone is a plain\n * `phone-pad` input (the US default still seeds it with \"+1\").\n */\nimport React, { useEffect, useMemo, useState, type FC } from 'react'\nimport { StyleSheet, View } from 'react-native'\n\nimport {\n hooks,\n type AuthFieldErrors,\n type AuthFieldName,\n type AuthRegistrationInput,\n} from 'tf-checkout-shared'\n\nimport { Button, ErrorText } from '../ui/primitives'\nimport { Field, Input } from '../ui/Field'\nimport { Select, type SelectOption } from '../ui/Select'\nimport { PasswordInput } from './PasswordInput'\n\nexport interface RegisterFormProps {\n initialEmail?: string\n errors?: AuthFieldErrors\n error?: string\n loading?: boolean\n requireAddress?: boolean\n onSubmit: (\n input: AuthRegistrationInput,\n options: { requireState: boolean }\n ) => void | Promise<unknown>\n onFieldChange?: (field: AuthFieldName) => void\n}\n\nconst emptyRegistration = (email: string): AuthRegistrationInput => ({\n firstName: '',\n lastName: '',\n email,\n password: '',\n passwordConfirmation: '',\n phone: '',\n streetAddress: '',\n city: '',\n zip: '',\n countryId: '',\n stateId: '',\n})\n\nexport const RegisterForm: FC<RegisterFormProps> = ({\n initialEmail = '',\n errors = {},\n error,\n loading = false,\n requireAddress = true,\n onSubmit,\n onFieldChange,\n}) => {\n const [values, setValues] = useState<AuthRegistrationInput>(() =>\n emptyRegistration(initialEmail)\n )\n const countriesQuery = hooks.useCountries()\n const countries = useMemo(() => countriesQuery.data ?? [], [countriesQuery.data])\n const statesQuery = hooks.useStates(values.countryId, {\n enabled: requireAddress && Boolean(values.countryId),\n })\n const states = useMemo(() => statesQuery.data ?? [], [statesQuery.data])\n\n useEffect(() => {\n if (initialEmail && !values.email)\n setValues((current) => ({ ...current, email: initialEmail }))\n }, [initialEmail, values.email])\n\n // Default to the US, resolved by ISO code rather than a hard-coded id so it\n // stays backend/environment safe (same approach as the web form).\n useEffect(() => {\n if (!requireAddress || values.countryId || countries.length === 0) return\n const preferred =\n countries.find((country) => country.code?.toLowerCase() === 'us') ?? countries[0]\n setValues((current) => ({\n ...current,\n countryId: String(preferred.id),\n phone:\n current.phone || (preferred.code?.toLowerCase() === 'us' ? '+1' : current.phone),\n }))\n }, [countries, requireAddress, values.countryId])\n\n const patch = (next: Partial<AuthRegistrationInput>) =>\n setValues((current) => ({ ...current, ...next }))\n const setField = (field: AuthFieldName, value: string) => {\n setValues((current) => ({ ...current, [field]: value }))\n onFieldChange?.(field)\n }\n\n const countryOptions: SelectOption[] = useMemo(\n () =>\n countries.map((country) => ({ label: country.name, value: String(country.id) })),\n [countries]\n )\n const stateOptions: SelectOption[] = useMemo(\n () => states.map((state) => ({ label: state.name, value: String(state.id) })),\n [states]\n )\n\n const submit = () => void onSubmit(values, { requireState: states.length > 0 })\n\n return (\n <View style={styles.form}>\n {error ? <ErrorText>{error}</ErrorText> : null}\n\n <View style={styles.row}>\n <View style={styles.flex}>\n <Field label=\"First name\" required error={errors.firstName}>\n <Input\n value={values.firstName}\n onChangeText={(text) => setField('firstName', text)}\n placeholder=\"First Name\"\n autoCapitalize=\"words\"\n invalid={Boolean(errors.firstName)}\n />\n </Field>\n </View>\n <View style={styles.flex}>\n <Field label=\"Last name\" required error={errors.lastName}>\n <Input\n value={values.lastName}\n onChangeText={(text) => setField('lastName', text)}\n placeholder=\"Last Name\"\n autoCapitalize=\"words\"\n invalid={Boolean(errors.lastName)}\n />\n </Field>\n </View>\n </View>\n\n <Field label=\"Email\" required error={errors.email}>\n <Input\n value={values.email}\n onChangeText={(text) => setField('email', text)}\n placeholder=\"Email\"\n keyboardType=\"email-address\"\n autoCapitalize=\"none\"\n invalid={Boolean(errors.email)}\n />\n </Field>\n\n {requireAddress ? (\n <>\n <Field label=\"Street address\" required error={errors.streetAddress}>\n <Input\n value={values.streetAddress ?? ''}\n onChangeText={(text) => setField('streetAddress', text)}\n placeholder=\"Street Address\"\n invalid={Boolean(errors.streetAddress)}\n />\n </Field>\n\n <Field label=\"ZIP / postcode\" required error={errors.zip}>\n <Input\n value={values.zip ?? ''}\n onChangeText={(text) => setField('zip', text)}\n placeholder=\"Zip / Postal Code\"\n invalid={Boolean(errors.zip)}\n />\n </Field>\n\n <Field label=\"Country\" required error={errors.countryId}>\n <Select\n value={values.countryId ?? ''}\n options={countryOptions}\n placeholder=\"Select country\"\n invalid={Boolean(errors.countryId)}\n onChange={(next) => {\n patch({ countryId: next, stateId: '' })\n onFieldChange?.('countryId')\n onFieldChange?.('stateId')\n }}\n />\n </Field>\n\n <Field\n label=\"State / Province\"\n required={states.length > 0}\n error={errors.stateId}\n >\n <Select\n value={values.stateId ?? ''}\n options={stateOptions}\n placeholder={states.length > 0 ? 'Select state / region' : 'Not required'}\n disabled={!values.countryId || states.length === 0}\n invalid={Boolean(errors.stateId)}\n onChange={(next) => setField('stateId', next)}\n />\n </Field>\n\n <Field label=\"City\" required error={errors.city}>\n <Input\n value={values.city ?? ''}\n onChangeText={(text) => setField('city', text)}\n placeholder=\"City\"\n invalid={Boolean(errors.city)}\n />\n </Field>\n </>\n ) : null}\n\n <Field label=\"Phone\">\n <Input\n value={values.phone ?? ''}\n onChangeText={(text) => setField('phone', text)}\n placeholder=\"Phone\"\n keyboardType=\"phone-pad\"\n autoCapitalize=\"none\"\n />\n </Field>\n\n <Field label=\"Password\" required error={errors.password}>\n <PasswordInput\n value={values.password}\n onChangeText={(text) => setField('password', text)}\n placeholder=\"Password\"\n invalid={Boolean(errors.password)}\n />\n </Field>\n\n <Field label=\"Confirm password\" required error={errors.passwordConfirmation}>\n <PasswordInput\n value={values.passwordConfirmation}\n onChangeText={(text) => setField('passwordConfirmation', text)}\n placeholder=\"Confirm Password\"\n invalid={Boolean(errors.passwordConfirmation)}\n />\n </Field>\n\n <Button onPress={submit} loading={loading}>\n Create Account\n </Button>\n </View>\n )\n}\n\nconst styles = StyleSheet.create({\n form: { gap: 14 },\n row: { flexDirection: 'row', gap: 10 },\n flex: { flex: 1 },\n})\n","/**\n * `<ResetPasswordForm/>` — completes the reset started by\n * `<ForgotPasswordForm/>`, given the `token` from the reset email. Owns its own\n * client-side validation (min length, a required special character, and a\n * confirmation match) and drives `hooks.useResetPassword`, mirroring the web\n * form. On success it swaps to a confirmation with an optional \"Log in\" action.\n */\nimport React, { useMemo, useState, type FC } from 'react'\nimport { StyleSheet, Text, View } from 'react-native'\n\nimport { errorMessage, hooks } from 'tf-checkout-shared'\n\nimport { Button, ErrorText } from '../ui/primitives'\nimport { Field } from '../ui/Field'\nimport { useTheme } from '../ui/CheckoutProvider'\nimport { PasswordInput } from './PasswordInput'\n\nexport interface ResetPasswordFormProps {\n /** Token from the password-reset email. */\n token: string\n onSuccess?: () => void\n onBackToLogin?: () => void\n}\n\nexport const ResetPasswordForm: FC<ResetPasswordFormProps> = ({\n token,\n onSuccess,\n onBackToLogin,\n}) => {\n const theme = useTheme()\n const [password, setPassword] = useState('')\n const [confirmation, setConfirmation] = useState('')\n const [submitted, setSubmitted] = useState(false)\n const [success, setSuccess] = useState(false)\n\n const validation = useMemo(() => {\n if (!submitted)\n return {} as { token?: string; password?: string; confirmation?: string }\n return {\n token: token ? '' : 'This password-reset link is missing its token.',\n password:\n password.length < 8\n ? 'Password must have at least 8 characters.'\n : !/[@$!%*#?&]/.test(password)\n ? 'Password must contain at least one special character.'\n : '',\n confirmation: password !== confirmation ? 'Passwords must match.' : '',\n }\n }, [confirmation, password, submitted, token])\n\n const reset = hooks.useResetPassword({\n onSuccess: () => {\n setSuccess(true)\n onSuccess?.()\n },\n })\n\n const submit = () => {\n setSubmitted(true)\n const passwordValid = password.length >= 8 && /[@$!%*#?&]/.test(password)\n if (!token || !passwordValid || password !== confirmation) return\n reset.mutate({ token, password, passwordConfirmation: confirmation })\n }\n\n if (success) {\n return (\n <View style={styles.form}>\n <Text style={[styles.success, { color: theme.success }]}>\n Your password has been changed. You can now log in.\n </Text>\n {onBackToLogin ? <Button onPress={onBackToLogin}>Log in</Button> : null}\n </View>\n )\n }\n\n return (\n <View style={styles.form}>\n <Text style={[styles.title, { color: theme.text }]}>Change Password</Text>\n\n {validation.token ? <ErrorText>{validation.token}</ErrorText> : null}\n {reset.error ? <ErrorText>{errorMessage(reset.error)}</ErrorText> : null}\n\n <Field label=\"New Password\" required error={validation.password}>\n <PasswordInput\n value={password}\n onChangeText={setPassword}\n placeholder=\"New Password\"\n invalid={Boolean(validation.password)}\n />\n </Field>\n\n <Field label=\"Confirm Password\" required error={validation.confirmation}>\n <PasswordInput\n value={confirmation}\n onChangeText={setConfirmation}\n placeholder=\"Confirm Password\"\n invalid={Boolean(validation.confirmation)}\n />\n </Field>\n\n <Button onPress={submit} loading={reset.isPending} disabled={!token}>\n Submit\n </Button>\n </View>\n )\n}\n\nconst styles = StyleSheet.create({\n form: { gap: 14 },\n title: { fontSize: 18, fontWeight: '700' },\n success: { fontSize: 15, fontWeight: '600' },\n})\n","/**\n * `<EmbeddedCheckout eventId=\"…\" />` — the batteries-included native checkout.\n * The RN analogue of the web `EmbeddedCheckout`: it wraps `<CheckoutProvider>`\n * and follows the same storefront UX — ticket selection and the checkout body\n * are separate views, with a compact selection summary + Edit once the cart is\n * reserved. In the checkout view the sections render as one combined form\n * (add-ons → buyer details → payment), all reading the one shared engine store.\n *\n * Compose the sections yourself for a custom layout — they all read the same\n * `useCheckout()` from the provider.\n *\n * Native adaptations vs web (commented at each site): no smooth `scrollIntoView`\n * (RN `ScrollView`); no URL attribution (`readAttributionFromUrl` accepted for\n * parity); the seat-map view is a placeholder until the native seat picker\n * (WebView + seats.io) lands.\n */\nimport React, { useEffect, useRef, useState, type FC } from 'react'\nimport { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'\n\nimport type {\n CheckoutBilling,\n CheckoutConsent,\n CheckoutHolder,\n EventCondition,\n PlaceOrderResult,\n TfProfile,\n} from 'tf-checkout-shared'\n\nimport { AuthModal } from './auth/AuthModal'\nimport { AddOns } from './sections/AddOns'\nimport { BillingInfo, type CheckoutPrivacyPolicy } from './sections/BillingInfo'\nimport { Confirmation } from './sections/Confirmation'\nimport { IDVerification } from './sections/IDVerification'\nimport { Payment } from './sections/Payment'\nimport { Tickets } from './sections/Tickets'\nimport { CheckoutProvider, useCheckoutContext, useTheme } from './ui/CheckoutProvider'\nimport { Card, BodyText, MutedText, Button } from './ui/primitives'\nimport { TimerBanner } from './ui/TimerBanner'\nimport type { CheckoutTheme } from './ui/theme'\n\ntype SelectionView = 'tickets' | 'seats'\nexport type CheckoutView = SelectionView | 'checkout'\n\nexport interface EmbeddedCheckoutAuthOptions {\n allowRegistration?: boolean\n allowPasswordReset?: boolean\n requireRegistrationAddress?: boolean\n logoUrl?: string\n onAuthenticated?: (profile: TfProfile) => void\n}\n\nexport interface EmbeddedCheckoutProps {\n /** The event whose tickets to sell. */\n eventId: string\n /** Called with the placed order once payment settles. */\n onComplete?: (order: PlaceOrderResult) => void\n /**\n * `inline` (default) renders verification + receipt in place. `redirect`\n * leaves completion routing to `onComplete` and keeps the checkout mounted.\n */\n confirmationMode?: 'inline' | 'redirect'\n /** Initial screen. `seats` preserves an existing seat-map entry point. */\n initialView?: SelectionView\n /** Reports the visible flow view so hosts can coordinate their own UI. */\n onViewChange?: (view: CheckoutView) => void\n /** Require guests to repeat their email. Defaults to storefront-compatible true. */\n requireEmailConfirmation?: boolean\n /** Collect one named holder per ticket. Defaults true to match tf-sports. */\n collectTicketHolders?: boolean\n /** Collect email/phone when ticket-holder details are required. Defaults true. */\n collectHolderContact?: boolean\n /** Open the host application's login UI instead of the built-in modal. */\n onLogin?: (email?: string) => void\n /** Configure the built-in login/create-account/reset modal, or set false to\n * remove auth UI. Ignored when `onLogin` is provided. */\n auth?: false | EmbeddedCheckoutAuthOptions\n /** Legacy skip-billing equivalent for complete signed-in profiles. */\n skipBillingWhenProfileComplete?: boolean\n /** Optional marketing copy controlled by the embedding brand. */\n ttfOptInLabel?: string\n brandOptInLabel?: string\n /** Consumer-owned privacy policy link + brand name. Required when provided. */\n privacyPolicy?: CheckoutPrivacyPolicy\n /** Host-owned required/optional acknowledgements, e.g. a privacy policy. */\n additionalConditions?: EventCondition[]\n /** Apply/attribute hosted links without a custom Tickets section. */\n initialPromoCode?: string\n referrer?: string | number\n /** Accepted for web parity; native has no `window.location`, so it's a no-op. */\n readAttributionFromUrl?: boolean\n /** Opt into sandbox card copy in demos. Defaults false. */\n showTestCardHint?: boolean\n /** Recolor via design tokens. */\n theme?: CheckoutTheme\n}\n\ninterface PreservedDetails {\n billing?: CheckoutBilling\n holders: CheckoutHolder[]\n consent: CheckoutConsent\n}\n\nconst Flow: FC<Omit<EmbeddedCheckoutProps, 'theme'>> = ({\n eventId,\n onComplete,\n confirmationMode = 'inline',\n initialView = 'tickets',\n onViewChange,\n requireEmailConfirmation = true,\n collectTicketHolders = true,\n collectHolderContact = true,\n onLogin,\n auth,\n skipBillingWhenProfileComplete = false,\n ttfOptInLabel,\n brandOptInLabel,\n privacyPolicy,\n additionalConditions = [],\n initialPromoCode,\n referrer,\n readAttributionFromUrl = true,\n showTestCardHint = false,\n}) => {\n const checkout = useCheckoutContext()\n const theme = useTheme()\n const [view, setView] = useState<CheckoutView>(initialView)\n const [selectionView, setSelectionView] = useState<SelectionView>(initialView)\n const editedDetailsRef = useRef<PreservedDetails | null>(null)\n const [authRequest, setAuthRequest] = useState<{ email?: string; key: number } | null>(\n null\n )\n const [privacyAttempted, setPrivacyAttempted] = useState(false)\n\n const openBuiltInAuth = (email?: string) =>\n setAuthRequest((current) => ({ email, key: (current?.key ?? 0) + 1 }))\n const requestLogin = onLogin ?? (auth !== false ? openBuiltInAuth : undefined)\n\n // Never let state from another event/run select this component's UI view.\n const checkoutBelongsToEvent = checkout.eventId === eventId\n const checkoutAvailable = checkoutBelongsToEvent && checkout.status !== 'expired'\n const visibleView: CheckoutView =\n view === 'checkout' && !checkoutAvailable ? 'tickets' : view\n\n useEffect(() => {\n if (view === 'checkout' && !checkoutAvailable) {\n setView('tickets')\n setSelectionView('tickets')\n }\n }, [checkoutAvailable, view])\n\n useEffect(() => {\n onViewChange?.(visibleView)\n }, [onViewChange, visibleView])\n\n const enterCheckout = (from: SelectionView) => {\n const preserved = editedDetailsRef.current\n if (preserved) {\n if (preserved.billing) checkout.setBilling(preserved.billing)\n checkout.setHolders(preserved.holders)\n checkout.setConsent(preserved.consent)\n editedDetailsRef.current = null\n }\n setSelectionView(from)\n setView('checkout')\n }\n\n const editSelection = () => {\n editedDetailsRef.current = {\n billing: checkout.billing,\n holders: checkout.holders,\n consent: checkout.consent,\n }\n setView(selectionView)\n }\n\n // Match the storefront summary: show the reserved tickets' amount, not a moving\n // order total that changes while the buyer picks add-ons.\n const breakdown = checkout.breakdown\n const selectedCount =\n breakdown?.tickets.reduce((total, t) => total + t.quantity, 0) ??\n checkout.selections.reduce((total, t) => total + t.quantity, 0)\n const selectedTicketsTotal = breakdown?.tickets.reduce(\n (total, t) => total + Number(t.total),\n 0\n )\n const formattedTotal = breakdown\n ? breakdown.currencySymbol\n ? `${breakdown.currencySymbol}${Number(selectedTicketsTotal).toFixed(2)}`\n : `${breakdown.currencyCode} ${Number(selectedTicketsTotal).toFixed(2)}`\n : null\n\n // Inline mode replaces the checkout with verification + receipt. Redirect mode\n // keeps the checkout mounted (onComplete already fired) so nothing flashes.\n const succeeded = checkout.status === 'succeeded' && Boolean(checkout.order)\n if (visibleView === 'checkout' && succeeded && confirmationMode === 'inline') {\n return (\n <ScrollView contentContainerStyle={styles.content}>\n <IDVerification />\n <Confirmation />\n </ScrollView>\n )\n }\n\n return (\n <ScrollView\n contentContainerStyle={styles.content}\n keyboardShouldPersistTaps=\"handled\"\n >\n {visibleView === 'tickets' && (\n <Tickets\n eventId={eventId}\n onContinue={() => enterCheckout('tickets')}\n onSelectSeats={() => setView('seats')}\n initialPromoCode={initialPromoCode}\n referrer={referrer}\n readAttributionFromUrl={readAttributionFromUrl}\n />\n )}\n\n {visibleView === 'seats' && (\n <View style={styles.stack}>\n <Pressable onPress={() => setView('tickets')} style={styles.back}>\n <Text style={[styles.backText, { color: theme.accent }]}>\n ← Back to tickets\n </Text>\n </Pressable>\n {/* Native seat picker (WebView + seats.io) is a follow-up; the web\n `<SeatMap/>` has no RN analogue yet. */}\n <Card>\n <BodyText>Seat selection isn’t available in the app yet.</BodyText>\n <MutedText>\n Please pick general-admission tickets, or use the web checkout to choose\n seats.\n </MutedText>\n </Card>\n </View>\n )}\n\n {visibleView === 'checkout' && (\n <View style={styles.stack}>\n <TimerBanner seconds={checkout.secondsLeft} />\n <View style={[styles.selection, { borderColor: theme.border }]}>\n <Text style={[styles.selectionText, { color: theme.text }]}>\n {selectedCount} {selectedCount === 1 ? 'ticket' : 'tickets'} selected\n {formattedTotal ? ` · ${formattedTotal}` : ''}\n </Text>\n <Pressable onPress={editSelection} accessibilityRole=\"button\">\n <Text style={[styles.editText, { color: theme.accent }]}>Edit</Text>\n </Pressable>\n </View>\n\n <AddOns eventId={eventId} />\n <BillingInfo\n eventId={eventId}\n onLogin={requestLogin}\n skipWhenProfileComplete={skipBillingWhenProfileComplete}\n requireEmailConfirmation={requireEmailConfirmation}\n collectTicketHolders={collectTicketHolders}\n collectHolderContact={collectHolderContact}\n ttfOptInLabel={ttfOptInLabel}\n brandOptInLabel={brandOptInLabel}\n privacyPolicy={privacyPolicy}\n showPrivacyError={privacyAttempted}\n />\n <Payment\n onComplete={onComplete}\n eventId={eventId}\n requireEmailConfirmation={requireEmailConfirmation}\n collectTicketHolders={collectTicketHolders}\n requireHolderContact={collectHolderContact}\n additionalConditions={additionalConditions}\n requirePrivacyPolicy={Boolean(privacyPolicy)}\n onPrivacyRequired={() => setPrivacyAttempted(true)}\n showTestCardHint={showTestCardHint}\n />\n </View>\n )}\n\n {authRequest && auth !== false && !onLogin && (\n <AuthModal\n key={authRequest.key}\n open\n initialEmail={authRequest.email}\n message={\n authRequest.email\n ? 'This email already has an account. Log in to autofill your checkout details.'\n : undefined\n }\n allowRegistration={auth?.allowRegistration}\n allowPasswordReset={auth?.allowPasswordReset}\n requireRegistrationAddress={auth?.requireRegistrationAddress}\n logoUrl={auth?.logoUrl}\n onAuthenticated={auth?.onAuthenticated}\n onClose={() => setAuthRequest(null)}\n />\n )}\n </ScrollView>\n )\n}\n\nexport const EmbeddedCheckout: FC<EmbeddedCheckoutProps> = ({ theme, ...flow }) => (\n <CheckoutProvider theme={theme}>\n <Flow key={flow.eventId} {...flow} />\n </CheckoutProvider>\n)\n\nconst styles = StyleSheet.create({\n content: { padding: 16, gap: 12 },\n stack: { gap: 12 },\n back: { paddingVertical: 4 },\n backText: { fontSize: 15, fontWeight: '600' },\n selection: {\n flexDirection: 'row',\n alignItems: 'center',\n justifyContent: 'space-between',\n borderWidth: StyleSheet.hairlineWidth,\n borderRadius: 10,\n paddingVertical: 10,\n paddingHorizontal: 14,\n },\n selectionText: { fontSize: 14, flex: 1 },\n editText: { fontSize: 14, fontWeight: '600' },\n})\n"],"mappings":";AEKA,SAAS,kBAAkB;AGO3B,OAAO,WAKA;AkCZP,SAAS,mBAAmB;ACE5B,SAAS,sBAAsB;AAC/B,SAAS,aAAa,gBAAgB;AEPtC,SAAS,4BAA4B;ACArC,SAAS,gBAAgB;ACAzB,SAAS,YAAAA,iBAAgB;ACAzB,SAAS,YAAAA,iBAAgB;ACAzB,SAAS,YAAAA,iBAAgB;ACAzB,SAAS,eAAAC,oBAAmB;ACY5B,SAAS,eAAAC,cAAa,WAAW,QAAQ,YAAAC,WAAU,wBAAAC,6BAA4B;;;;;;AhDKxE,IAAM,sBAAsB,MAAsB;AACvD,QAAM,MAAM,oBAAI,IAAoB;AACpC,SA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A,EAEJ;AAEJ;AAEO,IAAM,mBAA8C,CAAC,EAAE,OAAO,GAAG,KAAK,MAC3E,gBAAAA,MAAC,oBAAiB,OAChB,0BAAAA,MAAC,QAAyB,GAAG,QAAlB,KAAK,OAAmB,GACrC;AAGF,IAAMQ,WAASI,aAAW,OAAO;AAAA,EAC/B,SAAS,EAAE,SAAS,IAAI,KAAK,GAAG;AAAA,EAChC,OAAO,EAAE,KAAK,GAAG;AAAA,EACjB,MAAM,EAAE,iBAAiB,EAAE;AAAA,EAC3B,UAAU,EAAE,UAAU,IAAI,YAAY,MAAM;AAAA,EAC5C,WAAW;AAAA,IACT,eAAe;AAAA,IACf,YAAY;AAAA,IACZ,gBAAgB;AAAA,IAChB,aAAaA,aAAW;AAAA,IACxB,cAAc;AAAA,IACd,iBAAiB;AAAA,IACjB,mBAAmB;AAAA,EACrB;AAAA,EACA,eAAe,EAAE,UAAU,IAAI,MAAM,EAAE;AAAA,EACvC,UAAU,EAAE,UAAU,IAAI,YAAY,MAAM;AAC9C,CAAC;","names":["useQuery","useMutation","useCallback","useState","useSyncExternalStore","_a","_b","listeners","patch","_c","_d","_e","result","hasValue","g","f","needIdVerification","messageFrom","current","logout","attributeReferrer","joinWaitingList","useCheckout","StyleSheet","useCallback","useMemo","useState","useCallback","useMemo","useState","Pressable","StyleSheet","Text","View","jsx","jsxs","useState","useCallback","useStyles","Pressable","Text","View","useMemo","StyleSheet","jsx","jsxs","useState","useCallback","useMemo","useCheckout","jsx","StyleSheet","useMemo","useState","Pressable","StyleSheet","Text","View","jsx","jsxs","View","Text","useState","Pressable","useMemo","StyleSheet","useMemo","useState","Modal","Pressable","StyleSheet","Text","View","jsx","jsxs","useState","Pressable","Text","Modal","View","useMemo","StyleSheet","useMemo","Pressable","StyleSheet","Text","View","jsx","jsxs","View","Pressable","Text","useMemo","StyleSheet","useMemo","StyleSheet","Text","View","jsx","jsxs","View","Text","useMemo","StyleSheet","useMemo","useState","Pressable","StyleSheet","Text","View","jsx","jsxs","clock","useState","View","Text","Pressable","useMemo","StyleSheet","useMemo","Pressable","StyleSheet","Text","View","jsx","jsxs","useStyles","View","Pressable","Text","useMemo","StyleSheet","Fragment","useEffect","useMemo","useRef","useState","Pressable","StyleSheet","Text","View","Fragment","jsx","jsxs","useState","View","useMemo","_a","useEffect","_b","_c","useRef","Text","Pressable","StyleSheet","Fragment","useEffect","useMemo","useState","Pressable","StyleSheet","Text","View","View","Fragment","jsx","jsxs","View","jsx","jsxs","stripHtml","money","useState","useMemo","useEffect","_a","View","Text","Pressable","Fragment","_b","StyleSheet","Fragment","useEffect","useMemo","useRef","useState","Linking","Pressable","StyleSheet","Text","View","StyleSheet","View","Fragment","jsx","jsxs","current","styles","View","_a","StyleSheet","jsx","StyleSheet","View","jsx","jsxs","View","styles","StyleSheet","Fragment","jsx","jsxs","useStyles","useState","_a","_b","useRef","useMemo","useEffect","_c","_d","_e","_f","_g","_h","_i","_j","_k","_l","_m","_n","_o","_p","_q","_r","_s","_t","current","patch","View","Text","Pressable","Linking","StyleSheet","StyleSheet","View","jsx","jsxs","money","View","styles","_a","StyleSheet","useEffect","useMemo","useState","View","Fragment","jsx","jsxs","stripHtml","View","useState","useEffect","useMemo","_a","_b","_c","_d","patch","useState","Linking","jsx","jsxs","useState","Linking","useState","Linking","StyleSheet","Text","View","jsx","jsxs","useState","Linking","View","styles","Text","StyleSheet","useCallback","Image","Modal","Pressable","StyleSheet","Text","View","useEffect","useState","Pressable","StyleSheet","Text","View","jsx","jsxs","useState","useEffect","View","styles","Text","Pressable","StyleSheet","useEffect","useState","Pressable","StyleSheet","Text","View","useState","Pressable","StyleSheet","Text","View","jsx","jsxs","useState","View","styles","Pressable","current","Text","StyleSheet","jsx","jsxs","useState","useEffect","View","styles","Pressable","Text","StyleSheet","useEffect","useMemo","useState","StyleSheet","View","Fragment","jsx","jsxs","useState","useMemo","_a","useEffect","current","patch","View","styles","StyleSheet","jsx","jsxs","Pressable","styles","Text","useCallback","Modal","View","Image","StyleSheet","useMemo","useState","StyleSheet","Text","View","jsx","jsxs","useState","useMemo","View","styles","Text","StyleSheet","useEffect","useRef","useState","Pressable","ScrollView","StyleSheet","Text","View","jsx","jsxs","useState","useRef","current","_a","useEffect","ScrollView","styles","View","Pressable","Text","StyleSheet"]}
|