bitsnap-react 1.12.0 → 1.13.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 +40 -3
- package/dist/CartProvider-F7ER3WSS.js +2 -0
- package/dist/CartProvider-F7ER3WSS.js.map +1 -0
- package/dist/CartProvider-N73XNL7S.mjs +2 -0
- package/dist/analytics.js +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/analytics.mjs +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/{chunk-ICFYSZTV.js → chunk-3A4YOO7Z.js} +2 -2
- package/dist/chunk-3A4YOO7Z.js.map +1 -0
- package/dist/{chunk-UCESDAEC.mjs → chunk-3DGHF373.mjs} +2 -2
- package/dist/chunk-5GMWRCHK.mjs +4 -0
- package/dist/chunk-5GMWRCHK.mjs.map +1 -0
- package/dist/{chunk-MLSKHOA3.js → chunk-6CUCRTIK.js} +2 -2
- package/dist/chunk-6CUCRTIK.js.map +1 -0
- package/dist/{chunk-DGUIG334.js → chunk-EWLOGFF2.js} +2 -2
- package/dist/chunk-EWLOGFF2.js.map +1 -0
- package/dist/chunk-GAVLY6RX.mjs +2 -0
- package/dist/chunk-GAVLY6RX.mjs.map +1 -0
- package/dist/{chunk-XTIY6PXH.js → chunk-IP4OOWZ6.js} +2 -2
- package/dist/chunk-IP4OOWZ6.js.map +1 -0
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/{chunk-3QG7H2AI.mjs → chunk-K2EITRNW.mjs} +2 -2
- package/dist/{chunk-5R3WR22A.mjs → chunk-KH7DFTJY.mjs} +2 -2
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/{chunk-E5DCEFI2.mjs → chunk-L6J6H73J.mjs} +2 -2
- package/dist/chunk-M4KEUK6I.js +2 -0
- package/dist/chunk-M4KEUK6I.js.map +1 -0
- package/dist/{chunk-QSIKRVZL.mjs → chunk-OC7YS3UY.mjs} +2 -2
- package/dist/chunk-TMBC2BHN.js +4 -0
- package/dist/chunk-TMBC2BHN.js.map +1 -0
- package/dist/{chunk-DF2IK2GN.js → chunk-TSJCVFOX.js} +2 -2
- package/dist/chunk-TSJCVFOX.js.map +1 -0
- package/dist/{chunk-6IACFTJR.js → chunk-UFQVOGBS.js} +2 -2
- package/dist/chunk-UFQVOGBS.js.map +1 -0
- package/dist/chunk-XIHGWNTS.js.map +1 -1
- package/dist/{chunk-FF2ICGFQ.mjs → chunk-YNGXQJPE.mjs} +2 -2
- package/dist/{chunk-FF2ICGFQ.mjs.map → chunk-YNGXQJPE.mjs.map} +1 -1
- package/dist/consent.js.map +1 -1
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/embed/analytics.js +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.mts +59 -2
- package/dist/index.d.ts +59 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/internal.js.map +1 -1
- package/dist/methods-ADH5XI4I.js +2 -0
- package/dist/methods-ADH5XI4I.js.map +1 -0
- package/dist/methods-BCR54EWX.mjs +2 -0
- package/dist/models.js.map +1 -1
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/package.json +26 -51
- package/dist/CartProvider-XNFSUOCB.js +0 -2
- package/dist/CartProvider-XNFSUOCB.js.map +0 -1
- package/dist/CartProvider-YMJ7RFO4.mjs +0 -2
- package/dist/chunk-4BW6J7FP.js +0 -4
- package/dist/chunk-4BW6J7FP.js.map +0 -1
- package/dist/chunk-6IACFTJR.js.map +0 -1
- package/dist/chunk-DF2IK2GN.js.map +0 -1
- package/dist/chunk-DGUIG334.js.map +0 -1
- package/dist/chunk-ERL4Z7M7.js +0 -2
- package/dist/chunk-ERL4Z7M7.js.map +0 -1
- package/dist/chunk-ICFYSZTV.js.map +0 -1
- package/dist/chunk-MLSKHOA3.js.map +0 -1
- package/dist/chunk-P4Q5KXKS.mjs +0 -2
- package/dist/chunk-P4Q5KXKS.mjs.map +0 -1
- package/dist/chunk-PNTO3L2C.mjs +0 -4
- package/dist/chunk-PNTO3L2C.mjs.map +0 -1
- package/dist/chunk-XTIY6PXH.js.map +0 -1
- package/dist/methods-DDGOXLP6.mjs +0 -2
- package/dist/methods-RQPDIUUN.js +0 -2
- package/dist/methods-RQPDIUUN.js.map +0 -1
- /package/dist/{CartProvider-YMJ7RFO4.mjs.map → CartProvider-N73XNL7S.mjs.map} +0 -0
- /package/dist/{chunk-UCESDAEC.mjs.map → chunk-3DGHF373.mjs.map} +0 -0
- /package/dist/{chunk-3QG7H2AI.mjs.map → chunk-K2EITRNW.mjs.map} +0 -0
- /package/dist/{chunk-5R3WR22A.mjs.map → chunk-KH7DFTJY.mjs.map} +0 -0
- /package/dist/{chunk-E5DCEFI2.mjs.map → chunk-L6J6H73J.mjs.map} +0 -0
- /package/dist/{chunk-QSIKRVZL.mjs.map → chunk-OC7YS3UY.mjs.map} +0 -0
- /package/dist/{methods-DDGOXLP6.mjs.map → methods-BCR54EWX.mjs.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/index.js","../src/components/checkout/ApplePay.tsx","../src/components/checkout/project-id.ts"],"names":["currentProjectID","getProjectID","ApplePayButton","ApplePayButtonModule","ApplePayButtonComponent","style","buttonType","colorType","items","onClick","checkIfApplePayIsAvailable","getApplePayPaymentRequest","completeApplePayPayment","setCountry","setCouponCodeIfPossible","setDeliveryMethod","setEmail","setPostalCode","clearCart","getApplePayPreview","useCartProvider","instrument","useInstrumentContext","paymentForCartText","useCheckoutText","isApplePayAvailable","useQuery","itemsKey","el"],"mappings":"AAAA,ylCAA8V,sDAAyC,sDAAwN,sDAAiE,sDAAiD,sDAAiH,sDAAwG,sDAAgF,sDAAiE,+BAA4B,+BAA4B,kHCAllC,SCGjBA,EAAAA,CAAAA,CAAuC,CACrD,GAAI,CACF,OAAOC,gCAAAA,CACT,CAAA,UAAQ,CACN,MACF,CACF,CDEA,mDAAyB,+CAmWrB,IAvVEC,EAAAA,kBACHC,wBAAAA,CACE,OAAA,SAAWA,0BAAAA,CAmDhB,SAASC,EAAAA,CAAwB,CAC/B,KAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CACF,CAAA,CAAU,CACR,GAAM,CACJ,0BAAA,CAAAC,CAAAA,CACA,yBAAA,CAAAC,CAAAA,CACA,uBAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,uBAAA,CAAAC,CAAAA,CACA,iBAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,kBAAA,CAAAC,CACF,CAAA,CAAIC,gCAAAA,CAAgB,CACdC,CAAAA,CAAaC,gCAAAA,CAAqB,CAClCC,CAAAA,CAAqBC,gCAAAA,gBAAgC,CAAA,CACrD,CAAE,IAAA,CAAMC,CAAoB,CAAA,CAAIC,kCAAAA,CACpC,QAAA,CAAU,CAAC,wBAAwB,CAAA,CACnC,OAAA,CAAShB,CACX,CAAC,CAAA,CACKiB,CAAAA,CAAWnB,CAAAA,CAAM,GAAA,CAAKoB,CAAAA,EAAO,CAAA,EAAA","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/index.js","sourcesContent":[null,"import ApplePayButtonModule from \"apple-pay-button\";\nimport { PublicApiClient } from \"src/public.api.client\";\nimport CartProvider, {\n getCheckoutSelection,\n getProjectID,\n useCartProvider,\n} from \"./CartProvider\";\nimport { HOST } from \"./constants\";\nimport { isErr } from \"./lib/err\";\nimport { currentProjectID } from \"./project-id\";\nimport { round } from \"./lib/round.number\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { sendAnalyticEvent } from \"./frontent.analytics\";\nimport { useCheckoutText } from \"./texts.context\";\nimport {\n InstrumentProvider,\n useInstrument,\n useInstrumentContext,\n type AnalyticsOption,\n} from \"@/src/analytics/instrument\";\n\n// A CommonJS package with a `default` export: bundlers unwrap it, Node's own\n// ESM loader (server rendering of the unbundled library) does not.\nconst ApplePayButton: typeof ApplePayButtonModule =\n (ApplePayButtonModule as unknown as { default?: typeof ApplePayButtonModule })\n .default ?? ApplePayButtonModule;\n\ntype AppleButtonType =\n | \"plain\"\n | \"add-money\"\n | \"book\"\n | \"buy\"\n | \"check-out\"\n | \"continue\"\n | \"contribute\"\n | \"donate\"\n | \"order\"\n | \"pay\"\n | \"reload\"\n | \"rent\"\n | \"set-up\"\n | \"subscribe\"\n | \"support\"\n | \"tip\"\n | \"top-up\";\ntype ColorType = \"black\" | \"white\" | \"white-outline\";\n\nexport type Props = {\n style?: {\n width?: string;\n height?: string;\n borderRadius?: string;\n padding?: string;\n boxSizing?: string;\n };\n buttonType?: AppleButtonType;\n colorType?: ColorType;\n items: {\n name: string;\n id: string;\n price: number;\n /** Currency of `price` (minor units); defaults to PLN. */\n currency?: string;\n quantity: number;\n isDeliverable?: boolean;\n metadata?: { [key: string]: string | undefined };\n }[];\n onClick?: () => Promise<void>;\n /**\n * Usage statistics for your Bitsnap dashboard (Apple Pay clicks and\n * results). On by default; `false` turns it off. Inside `<BitsnapCheckout>`\n * the checkout's setting applies unless this is given.\n */\n analytics?: AnalyticsOption;\n};\n\nfunction ApplePayButtonComponent({\n style,\n buttonType,\n colorType,\n items,\n onClick,\n}: Props) {\n const {\n checkIfApplePayIsAvailable,\n getApplePayPaymentRequest,\n completeApplePayPayment,\n setCountry,\n setCouponCodeIfPossible,\n setDeliveryMethod,\n setEmail,\n setPostalCode,\n clearCart,\n getApplePayPreview,\n } = useCartProvider();\n const instrument = useInstrumentContext();\n const paymentForCartText = useCheckoutText(\"paymentForCart\");\n const { data: isApplePayAvailable } = useQuery({\n queryKey: [\"is-apple-pay-available\"],\n queryFn: checkIfApplePayIsAvailable,\n });\n const itemsKey = items.map((el) => `${el.id}:${el.quantity}`).join(\",\");\n const selection = getCheckoutSelection();\n const { data: preview } = useQuery({\n queryKey: [\n \"apple-pay-preview\",\n itemsKey,\n selection.country ?? \"\",\n selection.couponCode ?? \"\",\n selection.selectedDeliveryMethod ?? \"\",\n selection.postalCode ?? \"\",\n ],\n queryFn: () =>\n getApplePayPreview({\n items: items.map((el) => ({\n productID: el.id,\n quantity: el.quantity,\n metadata: el.metadata,\n })),\n }),\n enabled: isApplePayAvailable === true,\n });\n if (isApplePayAvailable != true) {\n return null;\n }\n // The backend's answer when it is there; else the cart's own currency and\n // total, with no delivery in it (it is added once the buyer picks a method).\n const loadedPreview =\n preview != null && !isErr(preview)\n ? preview\n : {\n countryCode: selection.country || \"PL\",\n currencyCode: items[0]?.currency ?? \"PLN\",\n totalAmount: `${round(\n items.reduce((acc, item) => acc + item.price * item.quantity, 0) /\n 100,\n 2,\n )}`,\n };\n\n const expectedItems = items.map((el) => ({\n productID: el.id,\n quantity: el.quantity,\n metadata: el.metadata,\n }));\n\n async function beginSession() {\n let reported = false;\n const report = (outcome: \"success\" | \"fail\" | \"cancel\") => {\n if (reported) {\n return;\n }\n reported = true;\n instrument.track(\"apple_pay_result\", { outcome });\n };\n instrument.track(\"apple_pay_clicked\", {});\n instrument.track(\"payment_method_selected\", {\n gateway: \"apple_pay\",\n method: \"apple_pay\",\n });\n sendAnalyticEvent({\n event: \"initiateCheckout\",\n items: items.map((el) => ({\n id: el.id,\n name: el.name,\n price: el.price,\n quantity: el.quantity,\n currency: loadedPreview.currencyCode,\n })),\n });\n const requiresShipping =\n items.find((el) => el.isDeliverable === true) != null;\n // The session has to be created inside the click, so country, currency\n // and total come from the backend's answer that was loaded beforehand.\n const session = new ApplePaySession(14, {\n countryCode: loadedPreview.countryCode,\n merchantCapabilities: [\"supports3DS\"],\n supportedNetworks: [\"visa\", \"masterCard\"],\n currencyCode: loadedPreview.currencyCode,\n total: {\n amount: loadedPreview.totalAmount,\n label: paymentForCartText,\n type: \"pending\",\n },\n // Delivery is added once the buyer picks a contact and a method.\n lineItems: items.map(\n (item) =>\n ({\n amount: `${round((item.price * item.quantity) / 100, 2)}`,\n label: item.name,\n type: \"final\",\n } as ApplePayJS.ApplePayLineItem)\n ),\n ...(requiresShipping\n ? {\n shippingMethods: [],\n supportsCouponCode: true,\n requiredBillingContactFields: [\n \"name\",\n \"email\",\n \"postalAddress\",\n \"phone\",\n ],\n requiredShippingContactFields: [\n \"name\",\n \"email\",\n \"postalAddress\",\n \"phone\",\n ],\n }\n : {}),\n });\n await onClick?.();\n const apRequest = await getApplePayPaymentRequest({ expectedItems });\n if (isErr(apRequest)) {\n console.error(\"Error creating ApplePaySession:\", apRequest.error);\n report(\"fail\");\n return;\n }\n\n session.oncancel = (event) => {\n console.log(\"ApplePaySession cancelled\", event);\n report(\"cancel\");\n };\n\n session.onvalidatemerchant = async (event) => {\n try {\n const result = await PublicApiClient.get(HOST).applePayValidateMerchant(\n {\n validationUrl: event.validationURL,\n projectId: getProjectID(),\n }\n );\n console.log(\"merchantSession\", result.merchantSession);\n if (result.merchantSession.length > 0) {\n console.log(\"completing merchant session\");\n session.completeMerchantValidation(\n JSON.parse(result.merchantSession)\n );\n } else {\n session.abort();\n }\n } catch (error) {\n session.abort();\n }\n };\n\n session.onshippingmethodselected = async (event) => {\n console.log(\"shipping method selected\", event);\n instrument.track(\"delivery_method_selected\", {\n method: event.shippingMethod.identifier,\n });\n await setDeliveryMethod(event.shippingMethod.identifier);\n const apRequest = await getApplePayPaymentRequest({ expectedItems });\n console.log(\"apRequest\", apRequest);\n if (isErr(apRequest)) {\n session.abort();\n throw new Error(\"Failed to get Apple Pay payment request\");\n }\n\n session.completeShippingMethodSelection({\n newTotal: apRequest.total,\n newLineItems: apRequest.lineItems,\n newShippingMethods: apRequest.shippingMethods,\n });\n };\n session.onshippingcontactselected = async (event) => {\n try {\n if (event.shippingContact.countryCode != null) {\n await setCountry(event.shippingContact.countryCode);\n }\n if (event.shippingContact.postalCode != null) {\n await setPostalCode(event.shippingContact.postalCode);\n }\n if (event.shippingContact.phoneNumber != null) {\n await setEmail(event.shippingContact.emailAddress);\n }\n const apRequest = await getApplePayPaymentRequest({ expectedItems });\n if (isErr(apRequest)) {\n session.abort();\n throw new Error(\"Failed to get Apple Pay payment request\");\n }\n\n console.log(\"apRequest\", apRequest);\n session.completeShippingContactSelection({\n newLineItems: apRequest.lineItems,\n newTotal: apRequest.total,\n newShippingMethods: apRequest.shippingMethods,\n });\n } catch (error) {\n console.log(\"shipping contact selected error\", error);\n session.abort();\n }\n };\n\n session.oncouponcodechanged = async (event) => {\n try {\n console.log(\"coupon code changed\", event);\n const result = await setCouponCodeIfPossible(event.couponCode);\n const apRequest = await getApplePayPaymentRequest({ expectedItems });\n console.log(\"apRequest\", apRequest);\n if (isErr(apRequest)) {\n session.abort();\n throw new Error(\"Failed to get Apple Pay payment request\");\n }\n\n session.completeCouponCodeChange({\n errors: isErr(result)\n ? [new ApplePayError(\"couponCodeInvalid\")]\n : undefined,\n newTotal: apRequest.total,\n newLineItems: apRequest.lineItems,\n newShippingMethods: apRequest.shippingMethods,\n });\n } catch (error) {\n console.log(\"coupon code changed error\", error);\n session.abort();\n }\n };\n\n session.onpaymentauthorized = async (event) => {\n instrument.track(\"payment_submitted\", {\n gateway: \"apple_pay\",\n method: \"apple_pay\",\n });\n try {\n const result = await completeApplePayPayment({\n token: event.payment.token,\n billingContact: event.payment.billingContact,\n shippingContact: event.payment.shippingContact,\n });\n if (isErr(result)) {\n console.log(\"apple pay error\", result);\n report(\"fail\");\n session.completePayment({\n status: ApplePaySession.STATUS_FAILURE,\n });\n return;\n }\n\n if (result.redirectURL) {\n setTimeout(() => {\n open(result.redirectURL, \"_self\");\n }, 2000);\n }\n report(result.isSuccess ? \"success\" : \"fail\");\n session.completePayment({\n status: result.isSuccess\n ? ApplePaySession.STATUS_SUCCESS\n : ApplePaySession.STATUS_FAILURE,\n });\n\n result.isSuccess && clearCart();\n } catch (e) {\n report(\"fail\");\n session.completePayment({\n status: ApplePaySession.STATUS_FAILURE,\n });\n }\n // event.complete(ApplePaySession.STATUS_SUCCESS);\n };\n\n session.begin();\n }\n\n return (\n <ApplePayButton\n style={style}\n buttonStyle={colorType}\n type={buttonType}\n onClick={beginSession}\n />\n );\n}\n\nfunction Wrapper(props: Props) {\n const instrument = useInstrument(\n currentProjectID(),\n props.analytics,\n \"cart\",\n );\n return (\n <InstrumentProvider value={instrument}>\n <CartProvider>\n <ApplePayButtonComponent {...props} />\n </CartProvider>\n </InstrumentProvider>\n );\n}\nexport default Wrapper;\n","import { getProjectID } from \"./CartProvider\";\n\n/** The page's project ID; `undefined` (instead of a throw) during server rendering. */\nexport function currentProjectID(): string | undefined {\n try {\n return getProjectID();\n } catch {\n return undefined;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/cart-payment-method/dist/index.js","../src/components/checkout/ApplePay.tsx","../src/components/checkout/project-id.ts"],"names":["currentProjectID","getProjectID","ApplePayButton","ApplePayButtonModule","ApplePayButtonComponent","style","buttonType","colorType","items","onClick","checkIfApplePayIsAvailable","getApplePayPaymentRequest","completeApplePayPayment","setCountry","setCouponCodeIfPossible","setDeliveryMethod","setEmail","setPostalCode","clearCart","getApplePayPreview","useCartProvider","instrument","useInstrumentContext","paymentForCartText","useCheckoutText","isApplePayAvailable","useQuery","itemsKey","el"],"mappings":"AAAA,ylCAA8X,sDAAyC,sDAAwN,sDAAiE,sDAAiD,sDAAiH,sDAAwG,sDAAgF,sDAAiE,+BAA4B,+BAA4B,kHCAlnC,SCGjBA,EAAAA,CAAAA,CAAuC,CACrD,GAAI,CACF,OAAOC,gCAAAA,CACT,CAAA,UAAQ,CACN,MACF,CACF,CDEA,mDAAyB,+CAmWrB,IAvVEC,EAAAA,kBACHC,wBAAAA,CACE,OAAA,SAAWA,0BAAAA,CAmDhB,SAASC,EAAAA,CAAwB,CAC/B,KAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CACF,CAAA,CAAU,CACR,GAAM,CACJ,0BAAA,CAAAC,CAAAA,CACA,yBAAA,CAAAC,CAAAA,CACA,uBAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,uBAAA,CAAAC,CAAAA,CACA,iBAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,kBAAA,CAAAC,CACF,CAAA,CAAIC,gCAAAA,CAAgB,CACdC,CAAAA,CAAaC,gCAAAA,CAAqB,CAClCC,CAAAA,CAAqBC,gCAAAA,gBAAgC,CAAA,CACrD,CAAE,IAAA,CAAMC,CAAoB,CAAA,CAAIC,kCAAAA,CACpC,QAAA,CAAU,CAAC,wBAAwB,CAAA,CACnC,OAAA,CAAShB,CACX,CAAC,CAAA,CACKiB,CAAAA,CAAWnB,CAAAA,CAAM,GAAA,CAAKoB,CAAAA,EAAO,CAAA,EAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/cart-payment-method/dist/index.js","sourcesContent":[null,"import ApplePayButtonModule from \"apple-pay-button\";\nimport { PublicApiClient } from \"src/public.api.client\";\nimport CartProvider, {\n getCheckoutSelection,\n getProjectID,\n useCartProvider,\n} from \"./CartProvider\";\nimport { HOST } from \"./constants\";\nimport { isErr } from \"./lib/err\";\nimport { currentProjectID } from \"./project-id\";\nimport { round } from \"./lib/round.number\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { sendAnalyticEvent } from \"./frontent.analytics\";\nimport { useCheckoutText } from \"./texts.context\";\nimport {\n InstrumentProvider,\n useInstrument,\n useInstrumentContext,\n type AnalyticsOption,\n} from \"@/src/analytics/instrument\";\n\n// A CommonJS package with a `default` export: bundlers unwrap it, Node's own\n// ESM loader (server rendering of the unbundled library) does not.\nconst ApplePayButton: typeof ApplePayButtonModule =\n (ApplePayButtonModule as unknown as { default?: typeof ApplePayButtonModule })\n .default ?? ApplePayButtonModule;\n\ntype AppleButtonType =\n | \"plain\"\n | \"add-money\"\n | \"book\"\n | \"buy\"\n | \"check-out\"\n | \"continue\"\n | \"contribute\"\n | \"donate\"\n | \"order\"\n | \"pay\"\n | \"reload\"\n | \"rent\"\n | \"set-up\"\n | \"subscribe\"\n | \"support\"\n | \"tip\"\n | \"top-up\";\ntype ColorType = \"black\" | \"white\" | \"white-outline\";\n\nexport type Props = {\n style?: {\n width?: string;\n height?: string;\n borderRadius?: string;\n padding?: string;\n boxSizing?: string;\n };\n buttonType?: AppleButtonType;\n colorType?: ColorType;\n items: {\n name: string;\n id: string;\n price: number;\n /** Currency of `price` (minor units); defaults to PLN. */\n currency?: string;\n quantity: number;\n isDeliverable?: boolean;\n metadata?: { [key: string]: string | undefined };\n }[];\n onClick?: () => Promise<void>;\n /**\n * Usage statistics for your Bitsnap dashboard (Apple Pay clicks and\n * results). On by default; `false` turns it off. Inside `<BitsnapCheckout>`\n * the checkout's setting applies unless this is given.\n */\n analytics?: AnalyticsOption;\n};\n\nfunction ApplePayButtonComponent({\n style,\n buttonType,\n colorType,\n items,\n onClick,\n}: Props) {\n const {\n checkIfApplePayIsAvailable,\n getApplePayPaymentRequest,\n completeApplePayPayment,\n setCountry,\n setCouponCodeIfPossible,\n setDeliveryMethod,\n setEmail,\n setPostalCode,\n clearCart,\n getApplePayPreview,\n } = useCartProvider();\n const instrument = useInstrumentContext();\n const paymentForCartText = useCheckoutText(\"paymentForCart\");\n const { data: isApplePayAvailable } = useQuery({\n queryKey: [\"is-apple-pay-available\"],\n queryFn: checkIfApplePayIsAvailable,\n });\n const itemsKey = items.map((el) => `${el.id}:${el.quantity}`).join(\",\");\n const selection = getCheckoutSelection();\n const { data: preview } = useQuery({\n queryKey: [\n \"apple-pay-preview\",\n itemsKey,\n selection.country ?? \"\",\n selection.couponCode ?? \"\",\n selection.selectedDeliveryMethod ?? \"\",\n selection.postalCode ?? \"\",\n ],\n queryFn: () =>\n getApplePayPreview({\n items: items.map((el) => ({\n productID: el.id,\n quantity: el.quantity,\n metadata: el.metadata,\n })),\n }),\n enabled: isApplePayAvailable === true,\n });\n if (isApplePayAvailable != true) {\n return null;\n }\n // The backend's answer when it is there; else the cart's own currency and\n // total, with no delivery in it (it is added once the buyer picks a method).\n const loadedPreview =\n preview != null && !isErr(preview)\n ? preview\n : {\n countryCode: selection.country || \"PL\",\n currencyCode: items[0]?.currency ?? \"PLN\",\n totalAmount: `${round(\n items.reduce((acc, item) => acc + item.price * item.quantity, 0) /\n 100,\n 2,\n )}`,\n };\n\n const expectedItems = items.map((el) => ({\n productID: el.id,\n quantity: el.quantity,\n metadata: el.metadata,\n }));\n\n async function beginSession() {\n let reported = false;\n const report = (outcome: \"success\" | \"fail\" | \"cancel\") => {\n if (reported) {\n return;\n }\n reported = true;\n instrument.track(\"apple_pay_result\", { outcome });\n };\n instrument.track(\"apple_pay_clicked\", {});\n instrument.track(\"payment_method_selected\", {\n gateway: \"apple_pay\",\n method: \"apple_pay\",\n });\n sendAnalyticEvent({\n event: \"initiateCheckout\",\n items: items.map((el) => ({\n id: el.id,\n name: el.name,\n price: el.price,\n quantity: el.quantity,\n currency: loadedPreview.currencyCode,\n })),\n });\n const requiresShipping =\n items.find((el) => el.isDeliverable === true) != null;\n // The session has to be created inside the click, so country, currency\n // and total come from the backend's answer that was loaded beforehand.\n const session = new ApplePaySession(14, {\n countryCode: loadedPreview.countryCode,\n merchantCapabilities: [\"supports3DS\"],\n supportedNetworks: [\"visa\", \"masterCard\"],\n currencyCode: loadedPreview.currencyCode,\n total: {\n amount: loadedPreview.totalAmount,\n label: paymentForCartText,\n type: \"pending\",\n },\n // Delivery is added once the buyer picks a contact and a method.\n lineItems: items.map(\n (item) =>\n ({\n amount: `${round((item.price * item.quantity) / 100, 2)}`,\n label: item.name,\n type: \"final\",\n } as ApplePayJS.ApplePayLineItem)\n ),\n ...(requiresShipping\n ? {\n shippingMethods: [],\n supportsCouponCode: true,\n requiredBillingContactFields: [\n \"name\",\n \"email\",\n \"postalAddress\",\n \"phone\",\n ],\n requiredShippingContactFields: [\n \"name\",\n \"email\",\n \"postalAddress\",\n \"phone\",\n ],\n }\n : {}),\n });\n await onClick?.();\n const apRequest = await getApplePayPaymentRequest({ expectedItems });\n if (isErr(apRequest)) {\n console.error(\"Error creating ApplePaySession:\", apRequest.error);\n report(\"fail\");\n return;\n }\n\n session.oncancel = (event) => {\n console.log(\"ApplePaySession cancelled\", event);\n report(\"cancel\");\n };\n\n session.onvalidatemerchant = async (event) => {\n try {\n const result = await PublicApiClient.get(HOST).applePayValidateMerchant(\n {\n validationUrl: event.validationURL,\n projectId: getProjectID(),\n }\n );\n console.log(\"merchantSession\", result.merchantSession);\n if (result.merchantSession.length > 0) {\n console.log(\"completing merchant session\");\n session.completeMerchantValidation(\n JSON.parse(result.merchantSession)\n );\n } else {\n session.abort();\n }\n } catch (error) {\n session.abort();\n }\n };\n\n session.onshippingmethodselected = async (event) => {\n console.log(\"shipping method selected\", event);\n instrument.track(\"delivery_method_selected\", {\n method: event.shippingMethod.identifier,\n });\n await setDeliveryMethod(event.shippingMethod.identifier);\n const apRequest = await getApplePayPaymentRequest({ expectedItems });\n console.log(\"apRequest\", apRequest);\n if (isErr(apRequest)) {\n session.abort();\n throw new Error(\"Failed to get Apple Pay payment request\");\n }\n\n session.completeShippingMethodSelection({\n newTotal: apRequest.total,\n newLineItems: apRequest.lineItems,\n newShippingMethods: apRequest.shippingMethods,\n });\n };\n session.onshippingcontactselected = async (event) => {\n try {\n if (event.shippingContact.countryCode != null) {\n await setCountry(event.shippingContact.countryCode);\n }\n if (event.shippingContact.postalCode != null) {\n await setPostalCode(event.shippingContact.postalCode);\n }\n if (event.shippingContact.phoneNumber != null) {\n await setEmail(event.shippingContact.emailAddress);\n }\n const apRequest = await getApplePayPaymentRequest({ expectedItems });\n if (isErr(apRequest)) {\n session.abort();\n throw new Error(\"Failed to get Apple Pay payment request\");\n }\n\n console.log(\"apRequest\", apRequest);\n session.completeShippingContactSelection({\n newLineItems: apRequest.lineItems,\n newTotal: apRequest.total,\n newShippingMethods: apRequest.shippingMethods,\n });\n } catch (error) {\n console.log(\"shipping contact selected error\", error);\n session.abort();\n }\n };\n\n session.oncouponcodechanged = async (event) => {\n try {\n console.log(\"coupon code changed\", event);\n const result = await setCouponCodeIfPossible(event.couponCode);\n const apRequest = await getApplePayPaymentRequest({ expectedItems });\n console.log(\"apRequest\", apRequest);\n if (isErr(apRequest)) {\n session.abort();\n throw new Error(\"Failed to get Apple Pay payment request\");\n }\n\n session.completeCouponCodeChange({\n errors: isErr(result)\n ? [new ApplePayError(\"couponCodeInvalid\")]\n : undefined,\n newTotal: apRequest.total,\n newLineItems: apRequest.lineItems,\n newShippingMethods: apRequest.shippingMethods,\n });\n } catch (error) {\n console.log(\"coupon code changed error\", error);\n session.abort();\n }\n };\n\n session.onpaymentauthorized = async (event) => {\n instrument.track(\"payment_submitted\", {\n gateway: \"apple_pay\",\n method: \"apple_pay\",\n });\n try {\n const result = await completeApplePayPayment({\n token: event.payment.token,\n billingContact: event.payment.billingContact,\n shippingContact: event.payment.shippingContact,\n });\n if (isErr(result)) {\n console.log(\"apple pay error\", result);\n report(\"fail\");\n session.completePayment({\n status: ApplePaySession.STATUS_FAILURE,\n });\n return;\n }\n\n if (result.redirectURL) {\n setTimeout(() => {\n open(result.redirectURL, \"_self\");\n }, 2000);\n }\n report(result.isSuccess ? \"success\" : \"fail\");\n session.completePayment({\n status: result.isSuccess\n ? ApplePaySession.STATUS_SUCCESS\n : ApplePaySession.STATUS_FAILURE,\n });\n\n result.isSuccess && clearCart();\n } catch (e) {\n report(\"fail\");\n session.completePayment({\n status: ApplePaySession.STATUS_FAILURE,\n });\n }\n // event.complete(ApplePaySession.STATUS_SUCCESS);\n };\n\n session.begin();\n }\n\n return (\n <ApplePayButton\n style={style}\n buttonStyle={colorType}\n type={buttonType}\n onClick={beginSession}\n />\n );\n}\n\nfunction Wrapper(props: Props) {\n const instrument = useInstrument(\n currentProjectID(),\n props.analytics,\n \"cart\",\n );\n return (\n <InstrumentProvider value={instrument}>\n <CartProvider>\n <ApplePayButtonComponent {...props} />\n </CartProvider>\n </InstrumentProvider>\n );\n}\nexport default Wrapper;\n","import { getProjectID } from \"./CartProvider\";\n\n/** The page's project ID; `undefined` (instead of a throw) during server rendering. */\nexport function currentProjectID(): string | undefined {\n try {\n return getProjectID();\n } catch {\n return undefined;\n }\n}\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as Gn,B as jn,C as qn,D as la,E as _,F as pa,G as da,J as Ee,K as nt,L as ua,M as ba,O as qt,P as Ft,Q as Ie,a as Je,b as Ot,c as Mt,d as kt,e as ea,f as Gt,g as aa,h as ra,i as Tt,j as Cr,k as Sr,l as Pr,m as Nr,n as Tr,o as jt,p as $r,q as Xr,r as Te,s as Et,t as gt,u as V,v as Zr,w as ca,x as It,y as On,z as Mn}from"./chunk-PNTO3L2C.mjs";import{a as Yr}from"./chunk-E5DCEFI2.mjs";import{A as Qr,a as Pe,b as X,c as Er,d as Ir,e as zr,f as Ar,i as Rr,k as Dr,l as _r,m as Lr,n as Ur,o as Br,p as Or,q as Mr,r as Gr,t as jr,u as qr,v as Fr,w as Hr,x as Vr,y as Wr,z as Kr}from"./chunk-5R3WR22A.mjs";import{a as Fn,b as Hn,c as Vn,d as Wn}from"./chunk-QSIKRVZL.mjs";import{a as na,b as ia}from"./chunk-KOVKUJAW.mjs";import{a as br,b as mr,c as gr,d as hr,e as fr,f as vr,g as wr,h as yr,i as xr,j as kr}from"./chunk-3QG7H2AI.mjs";import{g as Ce,h as ur,j as ot,k as se,l as mt,o as Se,q as G,r as $t,u as oa}from"./chunk-UCESDAEC.mjs";import{d as r,f as Bt,g as dr,j as sa,l as Ne,m as Xt}from"./chunk-P4Q5KXKS.mjs";import{l as Lt,m as Ut,n as xt,q as ta}from"./chunk-FF2ICGFQ.mjs";import"./chunk-ADYVTMGH.mjs";import"./chunk-U6FLIRIV.mjs";import ma from"apple-pay-button";function Ht(){try{return nt()}catch{return}}import{useQuery as ga}from"@tanstack/react-query";import{jsx as ce}from"react/jsx-runtime";var Jr=ma.default??ma;function to({style:t,buttonType:e,colorType:a,items:o,onClick:c}){let{checkIfApplePayIsAvailable:s,getApplePayPaymentRequest:n,completeApplePayPayment:y,setCountry:u,setCouponCodeIfPossible:d,setDeliveryMethod:w,setEmail:k,setPostalCode:x,clearCart:b,getApplePayPreview:l}=qt(),i=Ut(),S=_("paymentForCart"),{data:C}=ga({queryKey:["is-apple-pay-available"],queryFn:s}),N=o.map(m=>`${m.id}:${m.quantity}`).join(","),f=ua(),{data:R}=ga({queryKey:["apple-pay-preview",N,f.country??"",f.couponCode??"",f.selectedDeliveryMethod??"",f.postalCode??""],queryFn:()=>l({items:o.map(m=>({productID:m.id,quantity:m.quantity,metadata:m.metadata}))}),enabled:C===!0});if(C!=!0)return null;let I=R!=null&&!V(R)?R:{countryCode:f.country||"PL",currencyCode:o[0]?.currency??"PLN",totalAmount:`${Te(o.reduce((m,g)=>m+g.price*g.quantity,0)/100,2)}`},T=o.map(m=>({productID:m.id,quantity:m.quantity,metadata:m.metadata}));async function P(){let m=!1,g=p=>{m||(m=!0,i.track("apple_pay_result",{outcome:p}))};i.track("apple_pay_clicked",{}),i.track("payment_method_selected",{gateway:"apple_pay",method:"apple_pay"}),gt({event:"initiateCheckout",items:o.map(p=>({id:p.id,name:p.name,price:p.price,quantity:p.quantity,currency:I.currencyCode}))});let z=o.find(p=>p.isDeliverable===!0)!=null,E=new ApplePaySession(14,{countryCode:I.countryCode,merchantCapabilities:["supports3DS"],supportedNetworks:["visa","masterCard"],currencyCode:I.currencyCode,total:{amount:I.totalAmount,label:S,type:"pending"},lineItems:o.map(p=>({amount:`${Te(p.price*p.quantity/100,2)}`,label:p.name,type:"final"})),...z?{shippingMethods:[],supportsCouponCode:!0,requiredBillingContactFields:["name","email","postalAddress","phone"],requiredShippingContactFields:["name","email","postalAddress","phone"]}:{}});await c?.();let O=await n({expectedItems:T});if(V(O)){console.error("Error creating ApplePaySession:",O.error),g("fail");return}E.oncancel=p=>{console.log("ApplePaySession cancelled",p),g("cancel")},E.onvalidatemerchant=async p=>{try{let v=await Je.get(Bt).applePayValidateMerchant({validationUrl:p.validationURL,projectId:nt()});console.log("merchantSession",v.merchantSession),v.merchantSession.length>0?(console.log("completing merchant session"),E.completeMerchantValidation(JSON.parse(v.merchantSession))):E.abort()}catch{E.abort()}},E.onshippingmethodselected=async p=>{console.log("shipping method selected",p),i.track("delivery_method_selected",{method:p.shippingMethod.identifier}),await w(p.shippingMethod.identifier);let v=await n({expectedItems:T});if(console.log("apRequest",v),V(v))throw E.abort(),new Error("Failed to get Apple Pay payment request");E.completeShippingMethodSelection({newTotal:v.total,newLineItems:v.lineItems,newShippingMethods:v.shippingMethods})},E.onshippingcontactselected=async p=>{try{p.shippingContact.countryCode!=null&&await u(p.shippingContact.countryCode),p.shippingContact.postalCode!=null&&await x(p.shippingContact.postalCode),p.shippingContact.phoneNumber!=null&&await k(p.shippingContact.emailAddress);let v=await n({expectedItems:T});if(V(v))throw E.abort(),new Error("Failed to get Apple Pay payment request");console.log("apRequest",v),E.completeShippingContactSelection({newLineItems:v.lineItems,newTotal:v.total,newShippingMethods:v.shippingMethods})}catch(v){console.log("shipping contact selected error",v),E.abort()}},E.oncouponcodechanged=async p=>{try{console.log("coupon code changed",p);let v=await d(p.couponCode),bt=await n({expectedItems:T});if(console.log("apRequest",bt),V(bt))throw E.abort(),new Error("Failed to get Apple Pay payment request");E.completeCouponCodeChange({errors:V(v)?[new ApplePayError("couponCodeInvalid")]:void 0,newTotal:bt.total,newLineItems:bt.lineItems,newShippingMethods:bt.shippingMethods})}catch(v){console.log("coupon code changed error",v),E.abort()}},E.onpaymentauthorized=async p=>{i.track("payment_submitted",{gateway:"apple_pay",method:"apple_pay"});try{let v=await y({token:p.payment.token,billingContact:p.payment.billingContact,shippingContact:p.payment.shippingContact});if(V(v)){console.log("apple pay error",v),g("fail"),E.completePayment({status:ApplePaySession.STATUS_FAILURE});return}v.redirectURL&&setTimeout(()=>{open(v.redirectURL,"_self")},2e3),g(v.isSuccess?"success":"fail"),E.completePayment({status:v.isSuccess?ApplePaySession.STATUS_SUCCESS:ApplePaySession.STATUS_FAILURE}),v.isSuccess&&b()}catch{g("fail"),E.completePayment({status:ApplePaySession.STATUS_FAILURE})}},E.begin()}return ce(Jr,{style:t,buttonStyle:a,type:e,onClick:P})}function eo(t){let e=xt(Ht(),t.analytics,"cart");return ce(Lt,{value:e,children:ce(Ft,{children:ce(to,{...t})})})}var ze=eo;import{useEffect as Jt,useId as qo,useRef as Fo}from"react";import Z from"zod";import{useAutoAnimate as Lo}from"@formkit/auto-animate/react";import*as pt from"@radix-ui/react-dialog";import{useCallback as Uo,useRef as Bo,useState as Oo}from"react";import{createPortal as Mo}from"react-dom";import{createContext as so,useContext as co,useMemo as lo}from"react";var ao=["root","overlay","panel","header","title","closeButton","productList","product","productImage","productName","productPrice","quantityControl","quantityInput","quantityButton","removeButton","summary","totalLabel","totalValue","deliveryText","summaryNote","countryLabel","countryTrigger","countryDropdown","countrySearch","countryOption","paymentButtons","checkoutButton","emptyState","error","skeleton"],ro={fontFamily:"--bitsnap-checkout-font-family",fontSize:"--bitsnap-checkout-font-size",background:"--bitsnap-checkout-background",surface:"--bitsnap-checkout-surface",foreground:"--bitsnap-checkout-foreground",mutedForeground:"--bitsnap-checkout-muted-foreground",border:"--bitsnap-checkout-border",buttonBackground:"--bitsnap-checkout-button-background",buttonForeground:"--bitsnap-checkout-button-foreground",buttonHoverBackground:"--bitsnap-checkout-button-hover-background",hoverSurface:"--bitsnap-checkout-hover-surface",focusRing:"--bitsnap-checkout-focus-ring",error:"--bitsnap-checkout-error",overlay:"--bitsnap-checkout-overlay",radius:"--bitsnap-checkout-radius"},oo={dark:{},light:{background:"#ffffff",surface:"#f9fafb",foreground:"#18181b",mutedForeground:"#71717a",border:"#e4e4e7",buttonBackground:"#18181b",buttonForeground:"#fafafa",buttonHoverBackground:"#000000",hoverSurface:"#e4e4e7",focusRing:"#71717a",error:"#dc2626",overlay:"rgb(0 0 0 / 0.35)"}},no=[{token:"background",variable:"--background"},{token:"foreground",variable:"--foreground"},{token:"surface",variable:"--card"},{token:"surface",variable:"--popover"},{token:"foreground",variable:"--popover-foreground"},{token:"mutedForeground",variable:"--muted-foreground"},{token:"border",variable:"--border"},{token:"border",variable:"--input"},{token:"focusRing",variable:"--ring"},{token:"error",variable:"--destructive"},{token:"radius",variable:"--radius"}];function io(t){return{"--popover":t.surface??"var(--color-neutral-800)","--popover-foreground":t.foreground??"var(--color-neutral-200)"}}function Ae(t){let e=na(t,{defaultTheme:"dark",presets:oo,variables:ro,shadcnVariables:no});return{theme:e.theme,isCustomized:e.isCustomized,tokens:e.tokens,elements:e.elements,boundaryClassName:e.theme,boundaryStyle:e.boundaryStyle,dropdownStyle:io(e.tokens)}}function ha(t,e){return ia(t.elements,e)}import{jsx as po}from"react/jsx-runtime";var fa=so(Ae());function va({appearance:t,children:e}){let a=lo(()=>Ae(t),[t]);return po(fa.Provider,{value:a,children:e})}function Zt(){return co(fa)}function A(t){let e=Zt();return ha(e,t)??{}}import{useAutoAnimate as Ro}from"@formkit/auto-animate/react";import J from"react";import{useEffect as fo,useState as vo}from"react";import*as L from"@radix-ui/react-select";import{CheckIcon as uo,ChevronDownIcon as wa,ChevronUpIcon as bo}from"lucide-react";import{jsx as Q,jsxs as Re}from"react/jsx-runtime";function ya({...t}){return Q(L.Root,{"data-slot":"select",...t})}function xa({...t}){return Q(L.Value,{"data-slot":"select-value",...t})}var mo="border-input dark:bg-input/30 dark:hover:bg-input/50 bg-transparent";function ka({className:t,size:e="default",theme:a="default",children:o,...c}){return Re(L.Trigger,{"data-slot":"select-trigger","data-size":e,className:r("data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive flex w-fit items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",a==="bare"?"":mo,t),...c,children:[o,Q(L.Icon,{asChild:!0,children:Q(wa,{className:"size-4 opacity-50"})})]})}function Ca({className:t,children:e,position:a="popper",align:o="center",...c}){return Q(L.Portal,{children:Re(L.Content,{"data-slot":"select-content",className:r("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",a==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:a,align:o,...c,children:[Q(go,{}),Q(L.Viewport,{className:r("p-1",a==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:e}),Q(ho,{})]})})}function Sa({className:t,children:e,...a}){return Re(L.Item,{"data-slot":"select-item",className:r("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...a,children:[Q("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:Q(L.ItemIndicator,{children:Q(uo,{className:"size-4"})})}),Q(L.ItemText,{children:e})]})}function go({className:t,...e}){return Q(L.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:r("flex cursor-default items-center justify-center py-1",t),...e,children:Q(bo,{className:"size-4"})})}function ho({className:t,...e}){return Q(L.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:r("flex cursor-default items-center justify-center py-1",t),...e,children:Q(wa,{className:"size-4"})})}import{jsx as ht,jsxs as le}from"react/jsx-runtime";function wo({id:t,open:e,disabled:a=!1,onToggle:o,onChange:c,selectedValue:s,countries:n}){let[y,u]=vo(""),{isCustomized:d,boundaryClassName:w,boundaryStyle:k,dropdownStyle:x}=Zt(),b=A("countryTrigger"),l=A("countryDropdown"),i=A("countrySearch"),S=A("countryOption"),C=_("searchCountry"),N=_("noCountriesFound");fo(()=>{s==null&&n.length>0&&c(n[0].code)},[]);let f=n.filter(I=>I.name.toLowerCase().startsWith(y.toLowerCase())),R=n.find(I=>I.code===s);return le(ya,{value:s,onValueChange:I=>{c(I),u("")},open:e,onOpenChange:I=>{I!==e&&o(),I||u("")},disabled:a,children:[ht(ka,{"data-bitsnap-checkout-slot":"countryTrigger",theme:"bare",className:r(a?"bg-neutral-100 dark:bg-neutral-800 dark:border-neutral-700":"","w-full rounded-md",b.className),style:b.style,children:ht(xa,{children:R&&le("span",{className:"truncate flex items-center",children:[ht("img",{alt:s,src:`https://purecatamphetamine.github.io/country-flag-icons/3x2/${s}.svg`,className:"inline mr-2 h-4 rounded-sm"}),R.name]})})}),le(Ca,{"data-bitsnap-checkout":d?"dropdown":void 0,"data-bitsnap-checkout-slot":d?"countryDropdown":void 0,className:r(d?"bitsnap-react":"",w,"w-full max-h-80 max-w-[350px] z-[999999]",l.className),style:{...d?{...k,...x}:void 0,...l.style},position:"popper",children:[ht("div",{"data-bitsnap-checkout-slot":"countrySearch",className:r("sticky top-0 z-10 p-1 border-b",i.className),style:i.style,children:ht("input",{type:"search",name:"search",autoComplete:"off",className:"block w-full outline-none sm:text-body-regular bg-transparent rounded-md px-2 py-1.5",placeholder:C,"aria-label":C,value:y,onChange:I=>u(I.target.value),onClick:I=>I.stopPropagation(),onKeyDown:I=>I.stopPropagation()})}),ht("div",{className:"max-h-64 overflow-y-auto",children:f.length===0?ht("div",{className:"cursor-default select-none relative py-2 pl-3 pr-9 text-sm",children:N}):f.map(I=>le(Sa,{"data-bitsnap-checkout-slot":"countryOption",value:I.code,className:r("cursor-default select-none relative py-2 pl-3 pr-9 flex items-center transition",S.className),style:S.style,children:[ht("img",{alt:I.code,src:`https://purecatamphetamine.github.io/country-flag-icons/3x2/${I.code}.svg`,className:"inline mr-2 h-4 rounded-sm"}),ht("span",{className:"font-normal truncate",children:I.name})]},`${t}-${I.code}`))})]})]})}var Pa=wo;import{useEffect as Po,useRef as Ea,useState as za}from"react";import{MinusIcon as No,PlusIcon as To}from"lucide-react";import{Slot as _i}from"@radix-ui/react-slot";import{cva as yo}from"class-variance-authority";import{jsx as ko}from"react/jsx-runtime";var xo=yo("flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",{variants:{orientation:{horizontal:"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}});function Na({className:t,orientation:e,...a}){return ko("div",{role:"group","data-slot":"button-group","data-orientation":e,className:r(xo({orientation:e}),t),...a})}import{Fragment as Co,jsx as pe,jsxs as So}from"react/jsx-runtime";function Ta({price:t,currency:e,pricing:a,quantity:o=1}){let c=_("lowestPrice30Days"),s=_("noPriceHistory"),n=a?.regularPrice??t,y=a?.effectivePrice??t,u=a?.discount?.status==="ACTIVE"&&y<n;return pe("span",{children:u?So(Co,{children:[pe("span",{className:"mr-2 text-neutral-500 line-through",children:Et(n*o,e)}),pe("span",{className:"font-semibold text-red-700",children:Et(y*o,e)}),pe("span",{className:"mt-1 block text-xs text-neutral-600",children:a?.referencePrice.historyAvailable&&a.referencePrice.amount!=null?`${c} ${Et(a.referencePrice.amount,e)}`:s})]}):Et(y*o,e)})}function de(t){return Number.isFinite(t)?Math.min(99,Math.max(1,Math.trunc(t))):1}function De(t,e){let a=parseInt(t,10);return Number.isNaN(a)?e:de(a)}import{Fragment as zo,jsx as K,jsxs as ue}from"react/jsx-runtime";var Eo=({isNotAvailable:t,quantity:e,details:a,url:o,shouldUpdate:c})=>{let s=A("product"),n=A("productImage"),y=A("productName"),u=A("productPrice"),d=A("removeButton"),w=_("remove"),k=a.image_url??a.images?.[0],[x,b]=za(),l=k!=null&&k.length>0&&k!==x,i=a.baseName??a.name;return ue("div",{"data-bitsnap-checkout-slot":"product","data-bitsnap-checkout-unavailable":t?"":void 0,className:r("flex items-center gap-3 mx-3",t?"outline outline-1 rounded-md m-1":"",s.className),style:s.style,children:[l&&K(Ia,{url:o,tabIndex:-1,"aria-hidden":"true",className:"contents",children:K("img",{"data-bitsnap-checkout-slot":"productImage",className:r("aspect-auto max-w-[30%] max-w-32 max-h-32 py-2 overflow-hidden",n.className),style:n.style,src:k,alt:"",onError:()=>b(k)})}),ue("div",{className:"flex flex-col w-full",children:[K("p",{"data-bitsnap-checkout-slot":"productName",className:r("font-medium",y.className),style:y.style,children:K(Ia,{url:o,className:"text-inherit no-underline hover:underline",children:i})}),a.variantName!=null&&a.variantName.length>0&&K("p",{className:"text-sm opacity-70",children:a.variantName}),K("p",{"data-bitsnap-checkout-slot":"productPrice",className:r("text-sm",u.className),style:u.style,suppressHydrationWarning:!0,children:K(Ta,{price:a.price,currency:a.currency,pricing:a.pricing,quantity:e})}),ue("div",{className:"flex justify-between",children:[K(Io,{className:"",quantity:e,shouldUpdate:c}),K(G,{"data-bitsnap-checkout-slot":"removeButton",type:"button",variant:"ghost",size:"sm",className:d.className,style:d.style,"aria-label":`${w}: ${a.name}`,onClick:()=>{Promise.resolve(c(0)).catch(()=>{})},children:w})]})]})]})},Aa=Eo,Ia=({url:t,children:e,...a})=>t==null?K(zo,{children:e}):K("a",{href:t,...a,children:e}),Io=({quantity:t,shouldUpdate:e,className:a})=>{let[o,c]=za(t.toString()),s=Ea(t),n=A("quantityControl"),y=A("quantityInput"),u=A("quantityButton"),d=_("quantity"),w=_("increaseQuantity"),k=_("decreaseQuantity"),x=Ea(t);x.current=t,Po(()=>{s.current=t,c(t.toString())},[t]);function b(l){c(l.toString()),l!==s.current&&(s.current=l,Promise.resolve(e(l)).catch(()=>{s.current===l&&(s.current=x.current,c(x.current.toString()))}))}return K("div",{"data-bitsnap-checkout-slot":"quantityControl",className:r("flex",a,n.className),style:n.style,children:ue(Na,{"aria-label":d,children:[K(G,{"data-bitsnap-checkout-slot":"quantityButton",type:"button",className:u.className,style:u.style,"aria-label":k,onClick:()=>b(de(s.current-1)),children:K(No,{"aria-hidden":"true"})}),K("input",{"data-bitsnap-checkout-slot":"quantityInput",className:r("w-8 bg-transparent text-center",y.className),style:y.style,value:o,"aria-label":d,inputMode:"numeric",pattern:"[0-9]*",onChange:l=>c(l.currentTarget.value),onBlur:l=>b(De(l.currentTarget.value,s.current)),onKeyDown:l=>{l.key==="Enter"&&b(De(l.currentTarget.value,s.current))},type:"text"}),K(G,{"data-bitsnap-checkout-slot":"quantityButton",type:"button",className:u.className,style:u.style,"aria-label":w,onClick:()=>b(de(s.current+1)),children:K(To,{"aria-hidden":"true"})})]})})};import{jsx as Ao}from"react/jsx-runtime";function _e({className:t,...e}){return Ao("div",{"data-slot":"skeleton",className:"bg-neutral-700 animate-pulse rounded-md "+t,...e})}import{useMutation as Yt,useQuery as be}from"@tanstack/react-query";import{Fragment as _o,jsx as U,jsxs as it}from"react/jsx-runtime";var Do=({className:t,locale:e})=>{let a=qt(),o=Ut(),c=e??Xt(),s=A("productList"),n=A("summary"),y=A("totalLabel"),u=A("totalValue"),d=A("deliveryText"),w=A("summaryNote"),k=A("countryLabel"),x=A("paymentButtons"),b=A("checkoutButton"),l=A("emptyState"),i=A("error"),S=A("skeleton"),C=_("unavailableProducts"),N=pa(),f=_("emptyCart"),R=_("total"),I=_("delivery"),T=_("chooseCountry"),P=_("nextStep"),m=_("loadFailed"),g=_("retry"),z=_("countryRequired"),E=_("extrasCalculatedNext"),O=J.useId(),p=J.useId(),{mutateAsync:v}=Yt({mutationFn:a.removeProductFromCart}),{mutateAsync:bt}=Yt({mutationFn:a.updateQuantity}),{mutateAsync:ne}=Yt({mutationFn:a.setCountry}),{mutateAsync:ye}=Yt({mutationFn:a.clearCart}),[ie,Pt]=J.useState(""),lt=It(h=>h.notice);J.useEffect(()=>()=>It.getState().setNotice(void 0),[]);let H=ie.length>0?ie:lt??"",[W,at]=J.useState([]),[qe,tr]=J.useState(!1),{mutateAsync:er,isPending:Fe}=Yt({mutationFn:a.redirectToNextStep}),{data:He}=be({queryKey:["cart-available-countries"],queryFn:a.getAvailableCountries}),{data:ar}=be({queryKey:["cart-one-click-payment"],queryFn:a.checkIfApplePayIsAvailable}),{data:xe,isLoading:Rt,isError:rr,refetch:Ve}=be({queryKey:["cart",c],queryFn:a.getProducts}),{data:Nt,refetch:We}=be({queryKey:["cart-country"],queryFn:a.getCountry}),[or]=Ro(),q=V(xe)?void 0:xe,Ke=!Rt&&(rr||V(xe)),yt=V(He)?[]:He,Kt=q?.reduce((h,M)=>M.details==null?h:h+(M.details.pricing?.effectivePrice??M.details.price)*M.quantity,0)??0,Qt=q?.[0]?.details?.currency??"PLN",nr=q?.some(h=>h.details?.isDeliverable===!0)??!1,Dt=Nt!=null&&!V(Nt)&&Nt!=""?Nt:void 0,Qe=Nt!==void 0&&Dt==null,$e=J.useRef(!1);J.useEffect(()=>{$e.current||yt==null||yt.length===0||Nt==null||Dt!=null&&yt.some(h=>h.code===Dt)||($e.current=!0,ne(yt[0].code).then(()=>We()).catch(()=>{}))},[yt,Nt,Dt]);let Xe=J.useRef(!1);J.useEffect(()=>{Xe.current||Rt||(Xe.current=!0,o.track("cart_opened",{item_count:q?.reduce((h,M)=>h+M.quantity,0)??0,value_minor:Kt,currency:Qt}))},[Rt,o,q,Kt,Qt]);let ke=J.useRef(new Map);J.useEffect(()=>{ke.current.clear()},[q]);function ir(h,M){let F=q?.find(pr=>pr.id===h);if(F?.details==null)return;let _t=M-(ke.current.get(h)??F.quantity);if(ke.current.set(h,M),_t===0)return;let lr=F.details.pricing?.effectivePrice??F.details.price,Ye=F.catalogProductID??F.productID;o.track(_t>0?"add_to_cart":"remove_from_cart",{qty:Math.abs(_t),value_minor:Math.round(lr*Math.abs(_t)),currency:F.details.currency},{product_id:Ye,variant_id:Ye!==F.productID?F.productID:null})}let Ze=J.useRef(!1);async function sr(h,M){if(M!=null){ir(h,Math.max(0,M));try{let F=M<=0?await v({id:h}):await bt({id:h,quantity:M});if(V(F))throw new Error(`cannot change the cart: ${F.error}`)}finally{await Ve().catch(()=>{})}}}async function cr(){try{if(Pt(""),at([]),It.getState().setNotice(void 0),q!=null){!Ze.current&&q.length>0&&(Ze.current=!0,o.track("checkout_started",{item_count:q.reduce((F,_t)=>F+_t.quantity,0),checkout_type:"cart",value_minor:Kt,currency:Qt}));try{gt({event:"initiateCheckout",items:q?.map(F=>({id:F.productID,name:F.details?.name??"",price:F.details?.price??0,quantity:F.quantity,currency:F.details?.currency??"PLN"}))})}catch{}}let h=ba(),M=await er();if(V(M)){M.error=="item-ids-not-found"?(Pt(C),"data"in M&&Array.isArray(M.data)&&at(M.data)):Pt(ca(M,N));return}da(M,{cartProjectId:nt(),lines:h})||await ye(),window.location.href=M.url}catch(h){console.warn("checkout failed",h),Pt(N("checkoutFailed"))}}return it("div",{className:`${t} flex flex-col`,ref:or,children:[Rt&&it("div",{className:"relative flex w-full justify-center flex-col gap-4",children:[U(_e,{"data-bitsnap-checkout-slot":"skeleton",className:r("w-full h-32",S.className),style:S.style}),U(_e,{"data-bitsnap-checkout-slot":"skeleton",className:r("w-full h-32",S.className),style:S.style})]}),Ke&&it("div",{className:"flex flex-col items-start gap-3 p-4",children:[U("p",{role:"alert","data-bitsnap-checkout-slot":"error",className:r(i.className),style:i.style,children:m}),lt!=null&<.length>0&&U("p",{role:"alert","data-bitsnap-checkout-slot":"error",className:r("text-sm",i.className),style:i.style,children:lt}),U("button",{type:"button","data-bitsnap-checkout-slot":"checkoutButton",onClick:()=>{Ve().then().catch()},className:r("px-3 py-2 rounded-md transition font-bold",b.className),style:b.style,children:g})]}),!Rt&&!Ke&&(q==null||q.length==0)&&it("div",{className:"flex flex-col gap-4 p-4",children:[U("p",{"data-bitsnap-checkout-slot":"emptyState",className:r(l.className),style:l.style,children:f}),lt!=null&<.length>0&&U("p",{role:"alert","data-bitsnap-checkout-slot":"error",className:r("text-sm",i.className),style:i.style,children:lt})]}),U("div",{"data-bitsnap-checkout-slot":"productList",className:r("max-h-[70vh] overflow-clip overflow-y-scroll",s.className),style:s.style,children:q!=null&&q.length>0&&U("ul",{className:"mt-5",children:q.map(h=>U(J.Fragment,{children:h.details!=null&&it("li",{className:"mb-3",children:[U(Aa,{isNotAvailable:W.includes(h.productID),quantity:h.quantity,details:h.details,url:h.url,shouldUpdate:M=>sr(h.id,M)}),U("hr",{className:"h-1"})]})},h.id))})}),U("div",{className:"grow"}),Kt>0&&Qt!=null&&it(_o,{children:[it("div",{"data-bitsnap-checkout-slot":"summary",className:r("mx-3 flex flex-col",n.className),style:n.style,children:[it("div",{className:"flex flex-row justify-between text-lg",children:[U("p",{"data-bitsnap-checkout-slot":"totalLabel",className:r("text-xl",y.className),style:y.style,children:R}),it("div",{className:"flex flex-col items-end",children:[U("p",{"data-bitsnap-checkout-slot":"totalValue",className:r("font-medium",u.className),style:u.style,children:Et(Kt,Qt)}),nr&&U("p",{"data-bitsnap-checkout-slot":"deliveryText",className:r("opacity-70 text-right text-base",d.className),style:d.style,children:I})]})]}),U("p",{"data-bitsnap-checkout-slot":"summaryNote",className:r("opacity-70 text-sm",w.className),style:w.style,children:E})]}),yt&&yt?.length>1&&it("div",{children:[U("h4",{"data-bitsnap-checkout-slot":"countryLabel",className:r("ml-3 text-sm",k.className),style:k.style,children:T}),U(Pa,{id:O,open:qe,onToggle:()=>{tr(!qe)},onChange:h=>{ne(h).then(()=>{We().then().catch()})},selectedValue:Dt??"",countries:yt})]}),it("div",{className:"mb-3 flex flex-col",children:[ar&&q!=null&&q.length>0&&U("div",{"data-bitsnap-checkout-slot":"paymentButtons",className:r("w-full px-2",x.className),style:x.style,children:U(ze,{colorType:"white",style:{width:"100%"},items:q?.map(h=>({name:h.details?.name??"",id:h.productID,price:h.details?.pricing?.effectivePrice??h.details?.price??0,currency:h.details?.currency,quantity:h.quantity,isDeliverable:h.details?.isDeliverable??!1,metadata:h.metadata}))})}),q!=null&&q.length>0&&U("div",{"data-bitsnap-checkout-slot":"paymentButtons",className:r("w-full px-2",x.className),style:x.style,children:U(Le,{buttonSizeMode:"fill",buttonColor:"white",style:{width:"100%"},items:q?.map(h=>({name:h.details?.name??"",id:h.productID,price:h.details?.pricing?.effectivePrice??h.details?.price??0,quantity:h.quantity,isDeliverable:h.details?.isDeliverable??!1,metadata:h.metadata}))})}),U("button",{"data-bitsnap-checkout-slot":"checkoutButton",onClick:cr,disabled:Rt||Fe||Dt==null,"aria-describedby":Qe?p:void 0,className:r("px-3 py-2 my-2 mx-2 rounded-md disabled:opacity-40 disabled:cursor-not-allowed transition font-bold",b.className),style:b.style,children:Fe?U(X,{}):P}),Qe&&U("p",{id:p,className:"text-sm text-center opacity-70",children:z}),H.length>0&&U("p",{role:"alert","data-bitsnap-checkout-slot":"error",className:r("text-sm text-center",i.className),style:i.style,children:H})]})]})]})},Ra=Do;import{jsx as tt,jsxs as me}from"react/jsx-runtime";function Go({isVisible:t,shouldHide:e,panelId:a,locale:o}){let[c]=Lo(),[s,n]=Oo(null),y=Uo(f=>{c(f),n(f)},[c]),u=Bo(null),{boundaryClassName:d,boundaryStyle:w}=Zt(),k=A("root"),x=A("overlay"),b=A("panel"),l=A("header"),i=A("title"),S=A("closeButton"),C=_("cart"),N=_("close");return tt("div",{ref:y,"data-bitsnap-checkout":"root","data-bitsnap-checkout-slot":"root",className:r("bitsnap-react",d,k.className),style:{zIndex:999999,...w,...k.style},children:s!=null&&tt(pt.Root,{open:t,onOpenChange:f=>{f||e()},children:me(pt.Portal,{container:s,children:[tt(pt.Overlay,{"data-bitsnap-checkout-slot":"overlay","aria-hidden":"true",className:r("fixed top-0 right-0 left-0 bottom-0 cursor-pointer z-10",x.className),style:x.style,onClick:e}),me(pt.Content,{id:a,"data-bitsnap-checkout-slot":"panel","aria-modal":"true","aria-describedby":void 0,onOpenAutoFocus:()=>{let f=document.activeElement;u.current=f instanceof HTMLElement?f:null},onCloseAutoFocus:f=>{f.preventDefault(),u.current?.focus(),u.current=null},className:r("fixed z-20 top-0 right-0 bottom-0 w-full md:w-[350px] xl:w-[420px] flex flex-col",b.className),style:b.style,onPointerDownOutside:f=>f.preventDefault(),children:[me("div",{"data-bitsnap-checkout-slot":"header",className:r("mx-3 mt-7 flex justify-between items-center",l.className),style:l.style,children:[tt(pt.Title,{asChild:!0,children:tt("h1",{"data-bitsnap-checkout-slot":"title",className:r("text-2xl font-medium",i.className),style:i.style,children:C})}),tt("button",{type:"button","data-bitsnap-checkout-slot":"closeButton",className:r("rounded-xl p-2 transition",S.className),style:S.style,"aria-label":N,onClick:e,children:me("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"lucide lucide-x","aria-hidden":"true",focusable:"false",children:[tt("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),tt("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),tt(Ra,{className:"grow",locale:o})]})]})})})}var jo=t=>typeof window>"u"?null:Mo(tt(va,{appearance:t.appearance,children:tt(la,{texts:t.texts,locale:t.locale,children:tt(Ft,{locale:t.locale,children:tt(Go,{...t})})})}),document.body),Da=jo;import{Fragment as _a,jsx as zt,jsxs as ge}from"react/jsx-runtime";var Ho=Z.object({id:Z.string(),isSubscription:Z.boolean().default(!1),quantity:Z.number(),metadata:Z.record(Z.string(),Z.string().optional()).optional(),url:Z.string().optional()}),Vo={position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0};function Wo({projectID:t,locale:e,children:a,onVisibleChange:o,className:c,numberOfProductsInCartOptions:s,appearance:n,texts:y,analytics:u}){let d=xt(t,u,"cart");ta(d);let{isCartVisible:w,showCart:k,hideCart:x,numberOfProductsInCart:b}=It(),l=`bitsnap-cart-${qo()}`,i=T=>sa(T,e??Xt(),y),S=Fo(i);S.current=i;function C(T){It.getState().setNotice(S.current(T)),k()}function N(T){document.querySelectorAll("iframe").forEach(m=>{m.contentWindow?.postMessage(T,"*")})}Jt(()=>{o?.(w),w&>({event:"viewCart"})},[w]),Jt(()=>{Ee(t)},[t]),Jt(()=>{Ne(e)},[e]),Jt(()=>{if(!("cart"in window)){let T=nt();if(T==null){console.warn("There is no project ID configured.");return}window.cart={buyProduct:async P=>{try{let m=Z.object({productID:Z.string(),email:Z.string().optional(),name:Z.string().optional(),country:Z.string().optional(),marketingAgreement:Z.boolean().optional(),locale:Z.string().optional()}).parse(P),g=Ie(T);try{let E=await g.getProducts();V(E)==!1&>({event:"initiateCheckout",items:E.map(O=>({id:O.productID,name:O.details?.name??"",price:O.details?.price??0,quantity:O.quantity,currency:O.details?.currency??"PLN"}))})}catch{}let z=await g.justRedirectToPayment(m);V(z)==!1?window.location.href=z.url:C("redirectFailed")}catch(m){console.warn(m)}}}}},[]);async function f(T,P){let m=nt();if(m==null){console.warn("There is no project ID configured.");return}try{let g=Ho.parse(P);if(g.isSubscription){await R(m,g);return}await Ie(m).addProduct({productID:g.id,quantity:g.quantity,metadata:g.metadata,url:g.url}),N({id:T,type:"ADD_TO_CART",success:!0}),k()}catch(g){console.warn("cannot add item to cart",g)}}async function R(T,P){console.warn("subscriptions cannot be added to the cart yet",T,P.id),C("subscriptionUnsupported")}function I(){"__cart_is_listening"in window||(window.__cart_is_listening=!0,window.addEventListener("message",T=>{if(typeof T.data.id<"u"&&typeof T.data.type<"u"){let{id:P,type:m}=T.data;switch(m){case"ADD_TO_CART".toString():f(P,T.data.payload).then().catch();break;default:break}}}))}return Jt(()=>{if(I(),typeof window<"u")try{let T=new URLSearchParams(window.location.search),P=T.get("ref")??T.get("utm-source");typeof localStorage<"u"&&P&&P.length>0&&localStorage.setItem("bitsnap-ref",P)}catch{return}},[]),ge(_a,{children:[ge("button",{type:"button",onClick:()=>w?x():k(),"aria-label":a?void 0:b>0?`${i("openCart")}. ${i("cartItemsCount")}: ${b}`:i("openCart"),"aria-expanded":w,"aria-haspopup":"dialog","aria-controls":w?l:void 0,style:{position:"relative"},className:["bitsnap-react",c??"rounded-full hover:bg-neutral-300 transition p-1"].join(" "),children:[a?zt(_a,{children:a}):ge("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"lucide lucide-shopping-cart","aria-hidden":"true",focusable:"false",children:[zt("circle",{cx:"8",cy:"21",r:"1"}),zt("circle",{cx:"19",cy:"21",r:"1"}),zt("path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"})]}),b>0&&ge("span",{style:Vo,children:[i("cartItemsCount"),": ",b]}),s?.isVisible!=!1&&b>0&&zt("div",{"aria-hidden":"true",style:{position:"absolute",bottom:-5,right:-5,background:"black",color:"white",borderRadius:"50%",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"13px",fontWeight:600,boxShadow:"0 2px 8px rgba(0, 0, 0, 0.25)",...s?.style},children:b})]}),zt(Lt,{value:d,children:zt(Da,{isVisible:w,locale:e,appearance:n,texts:y,panelId:l,shouldHide:()=>{x()}})})]})}var Ko=Wo;import Qo from"@google-pay/button-react";import{useQuery as $o,useMutation as Xo}from"@tanstack/react-query";import{Fragment as Jo,jsx as te,jsxs as tn}from"react/jsx-runtime";function Zo({items:t,style:e,buttonColor:a,buttonSizeMode:o,test:c}){let{getGooglePayConfiguration:s,completeGooglePayPayment:n,setCountry:y,setCouponCodeIfPossible:u,setDeliveryMethod:d,setEmail:w,setPostalCode:k,clearCart:x}=qt(),b=Ut(),{data:l}=$o({queryKey:["get-google-pay-configuration",t.map(C=>C.id).join(",")],queryFn:()=>s({items:t.map(C=>({...C,id:void 0,productID:C.id}))})}),{mutateAsync:i,isPending:S}=Xo({mutationFn:n});return l==null||l.isAvailable!=!0?(console.log("google pay configuration is not available",l),null):tn(Jo,{children:[te(Qo,{buttonSizeMode:o,buttonColor:a,style:e,existingPaymentMethodRequired:!0,onClick:()=>b.track("payment_method_selected",{gateway:"google_pay",method:"google_pay"}),environment:c===!0?"TEST":"PRODUCTION",onPaymentDataChanged:async C=>{gt({event:"initiateCheckout",items:t.map(f=>({id:f.id,name:f.name,price:f.price,quantity:f.quantity,currency:"PLN"}))}),console.log("payment data changed",C),C.shippingAddress?.postalCode!=null&&await k(C.shippingAddress?.postalCode),C.shippingAddress?.countryCode!=null&&await y(C.shippingAddress?.countryCode),C.shippingOptionData?.id!=null&&await d(C.shippingOptionData.id);let N=await s({items:[]});return console.log("PAYMENT DATA CHANGED CONFIG",N),N.isAvailable?{error:void 0,newShippingOptionParameters:N.config.shippingOptionParameters,newTransactionInfo:N.config.transactionInfo}:{error:void 0}},paymentRequest:l.config,onLoadPaymentData:async C=>{b.track("payment_submitted",{gateway:"google_pay",method:"google_pay"});try{let N=await i({paymentData:C});if(V(N)){console.log("apple pay error",N);return}N.isSuccess&&x(),N.redirectURL&&open(N.redirectURL,"_self")}catch(N){console.warn("error completing google pay payment",N)}}}),S?te(X,{}):null]})}function Yo(t){let e=xt(Ht(),t.analytics,"cart");return te(Lt,{value:e,children:te(Ft,{children:te(Zo,{...t})})})}var Le=Yo;import{useReducer as In,useRef as zn,useEffect as oe}from"react";import{useQuery as An}from"@tanstack/react-query";import{Settings as Rn}from"lucide-react";import{Fragment as en,jsx as Ue,jsxs as an}from"react/jsx-runtime";var D={title:null,description:null,managingDescription:"Zarz\u0105dzaj rodzajami powiadomie\u0144 i sposobem dostarczania.",formTitle:"Podaj Email aby zapisa\u0107 si\u0119\xA0do powiadomie\u0144",formEmailLabel:"Email",formPhoneLabel:"Numer telefonu",formPhoneOptional:"(opcjonalnie)",formEmailPlaceholder:"np. mail@gmail...",formPhonePlaceholder:"np. 663...",formSubmitButton:"Zapisz si\u0119",formSuccessMessage:"Zapisa\u0142e\u015B si\u0119 do powiadomie\u0144.",agreementText:an(en,{children:[Ue("span",{style:{color:"red"},children:"*"}),"Wyra\u017Cam zgod\u0119 na przetwarzanie moich danych w celach marketingowych zgodnie z"," ",Ue("a",{href:"/regulations/polityka-prywatnosci",target:"_blank",className:"cursor-alias font-bold hover:font-medium",children:"regulaminem"})," ",Ue("span",{className:"text-xs font-light",children:"(zgod\u0119 mo\u017Cna w ka\u017Cdej chwili wycofa\u0107)"})]}),qrCodeTitle:"lub zainstaluj aplikacj\u0119 mobiln\u0105",qrCodeSubtitle:"Aplikacja mobilna",qrCodeScanText:"zeskanuj kod QR",groupsNoSelectionWarning:"Je\u015Bli \u017Cadna z grup nie jest zaznaczona, nie otrzymasz \u017Cadnych powiadomie\u0144.",groupsSelectAllButton:"Zaznacz wszystkie",groupsUpdateButton:"Aktualizuj",groupsUpdateSuccess:"Zaktualizowano pomy\u015Blnie.",groupsTitle:"Zarz\u0105dzaj grupami z kt\xF3rych chcesz otrzymywa\u0107 powiadomienia",manageDataTitle:"Ustawienia powiadomie\u0144",manageDataDescription:"W jaki spos\xF3b chcesz otrzymywa\u0107 powiadomienia?",manageDataUnsubscribeButton:"Odsubskrybuj",manageDataUpdatedMessage:"Zaktualizowano",manageDataUnsubscribeDescription:"Wypisz mnie z wszystkich powiadomie\u0144 i grup.",loginEmailLabel:"Email",loginEmailPlaceholder:"Wprowad\u017A sw\xF3j email",loginSendCodeButton:"Wy\u015Blij kod weryfikacyjny",loginSendingButton:"Wysy\u0142anie...",loginCodeLabel:"Wprowad\u017A kod weryfikacyjny",loginCodeSentMessage:"Wys\u0142ali\u015Bmy kod weryfikacyjny na adres",loginChangeEmailButton:"Popraw email",loginResendCodeButton:"Wy\u015Blij kod ponownie",loginInvalidEmailError:"Wprowad\u017A prawid\u0142owy adres email",loginSlugRequiredError:"Wymagany jest identyfikator projektu",loginInvalidCodeError:"Nieprawid\u0142owy kod weryfikacyjny",loginVerificationFailedError:"Weryfikacja nie powiod\u0142a si\u0119. Sprawd\u017A sw\xF3j kod.",loginSendEmailError:"Nie uda\u0142o si\u0119 wys\u0142a\u0107 kodu weryfikacyjnego",loginVerifyCodeError:"Nie uda\u0142o si\u0119 zweryfikowa\u0107 kodu",loginResendEmailError:"Nie uda\u0142o si\u0119 ponownie wys\u0142a\u0107 kodu weryfikacyjnego",loginTitle:"Wpisz email aby zarz\u0105dza\u0107 powiadomieniami",loginDescription:"Dostaniesz kod weryfikacyjny na email.",loginIHaveCode:"Mam ju\u017C kod"};import{LogOutIcon as rn}from"lucide-react";import{Fragment as La,jsx as At,jsxs as he}from"react/jsx-runtime";function Ua({projectName:t,projectLogo:e,projectLogoDark:a,description:o,className:c,onLogout:s}){return he(La,{children:[e!=null||t!=null&&he("h2",{className:r("flex max-w-44 items-center gap-3 text-lg font-medium text-black sm:max-w-none md:text-xl lg:text-2xl xl:text-3xl dark:text-neutral-100",c?.headerTitle),children:[e!=null&&he(La,{children:[At("img",{src:e,alt:"",className:r("h-12 w-auto dark:hidden",c?.headerLogo)}),At("img",{src:a??e,alt:"",className:r("hidden h-12 w-auto dark:inline",c?.headerLogo)})]}),At("span",{children:t})]}),he("div",{className:"flex items-center gap-2",children:[o&&At("p",{className:r("mt-4 font-medium text-left",c?.headerDescription),children:o}),At("div",{className:"grow"}),s&&At(G,{variant:"ghost",size:"icon-sm",onClick:s,children:At(rn,{className:"h-5 w-5"})})]})]})}import{useAutoAnimate as ja}from"@formkit/auto-animate/react";import{CheckCircleIcon as nn,TriangleAlertIcon as sn}from"lucide-react";import*as ft from"@radix-ui/react-popover";import{jsx as fe}from"react/jsx-runtime";function Ba({...t}){return fe(ft.Root,{"data-slot":"popover",...t})}function Oa({...t}){return fe(ft.Trigger,{"data-slot":"popover-trigger",...t})}function Ma({className:t,align:e="center",sideOffset:a=4,...o}){return fe(ft.Portal,{children:fe(ft.Content,{"data-slot":"popover-content",align:e,sideOffset:a,className:r("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",t),...o})})}import{ClockIcon as on}from"lucide-react";import{jsx as vt,jsxs as Ct}from"react/jsx-runtime";function Ga({regularity:t}){let e="";switch(t){case"rarely":e="rzadko";break;case"often":e="cz\u0119sto";break;case"very_often":e="codzienne";break}return Ct(Ba,{children:[vt(Oa,{onClick:a=>{a.stopPropagation()},children:Ct("button",{type:"button",className:"flex w-[30%] cursor-help flex-col items-center justify-center text-xs md:w-[25%] xl:w-[20%]",children:[vt(on,{size:12}),vt("span",{children:e})]})}),vt(Ma,{className:"w-80",children:Ct("div",{className:"grid gap-4",children:[Ct("div",{className:"space-y-2",children:[vt("h4",{className:"leading-none font-medium",children:"Co to oznacza?"}),Ct("ul",{className:"list-inside list-disc text-sm",children:[Ct("li",{children:[vt("span",{className:"font-semibold",children:"Rzadko"})," \u2013 powiadomienia b\u0119d\u0105 wysy\u0142ane maksymalnie kilka razy w miesi\u0105cu."]}),Ct("li",{children:[vt("span",{className:"font-semibold",children:"Cz\u0119sto"})," \u2013 powiadomienia mog\u0119 by\u0107 wysy\u0142ane kilka razy w tygodniu."]}),Ct("li",{children:[vt("span",{className:"font-semibold",children:"Codzienne"})," \u2013 powiadomienia b\u0119d\u0105 wysy\u0142ane nawet codziennie."]})]})]}),vt("div",{className:"grid gap-2"})]})})]})}import{Fragment as cn,jsx as Y,jsxs as dt}from"react/jsx-runtime";function ve({groups:t=[],isManaging:e,onToggle:a,onCheckAll:o,onUpdate:c,isUpdating:s,wasChanged:n,isUserGroupsUpdated:y,className:u,texts:d}){let[w]=ja(),[k]=ja(),x=t.filter(i=>i.isOn===!1).length>0,b=t.filter(i=>i.isOn===!1).length>0;if(t.length<=1&&e!=!0)return null;let l=dt("div",{ref:w,className:r("my-5 flex flex-col gap-3",u?.groupsList),children:[t.map(i=>dt("div",{id:i.id,role:"button",className:r(i.isOn?"bg-neutral-50 hover:bg-transparent shadow-sm border-transparent dark:bg-neutral-800":"border-neutral-200 hover:bg-neutral-50 dark:hover:border-neutral-800 shadow-sm dark:border-neutral-800","active:bg-beige-300 flex w-full cursor-pointer items-center gap-3 rounded-xl border px-3 py-2 transition active:dark:bg-neutral-900",u?.groupItem),onClick:S=>{S.target instanceof HTMLButtonElement||a(i.id)},children:[Y(jt,{checked:i.isOn,className:"data-[state=checked]:bg-blue-500 dark:data-[state=unchecked]:bg-neutral-700",onCheckedChange:()=>{a(i.id)}}),dt("div",{className:"flex flex-col items-start justify-start",children:[Y("p",{className:"font-medium text-sm",children:i.name}),i.description&&Y("p",{className:"text-xs font-light",children:i.description})]}),Y("div",{className:"grow"}),i.howOften&&Y(Ga,{regularity:i.howOften})]},i.id)),dt("div",{className:"flex gap-2",children:[e===!0&&dt(cn,{children:[dt("div",{ref:k,className:"flex flex-col items-start justify-start",children:[n&&dt(G,{variant:"default",size:"sm",className:"relative",disabled:s,onClick:c,children:[d?.groupsUpdateButton??D.groupsUpdateButton,s&&Y("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:Y(X,{})})]}),y&&dt("p",{className:"mt-3 flex items-center gap-2 text-sm text-green-500",children:[Y(nn,{color:"var(--color-green-500",size:16})," ",d?.groupsUpdateSuccess??D.groupsUpdateSuccess]})]}),Y("div",{className:"grow"})]}),b&&Y("div",{className:"flex justify-start",children:Y(G,{className:"cursor-pointer dark:bg-neutral-700",onClick:o,size:"sm",variant:"secondary",type:"button",children:d?.groupsSelectAllButton??D.groupsSelectAllButton})})]}),x&&dt("div",{className:"flex text-left gap-2 text-xs text-yellow-500",children:[Y(sn,{color:"orange",size:16}),d?.groupsNoSelectionWarning??D.groupsNoSelectionWarning]})]});return e==!0?dt(Ot,{className:"mt-5 text-left",children:[Y(Mt,{children:Y(kt,{children:d?.groupsTitle??D.groupsTitle})}),Y(Gt,{children:l})]}):l}import{jsx as St,jsxs as ee}from"react/jsx-runtime";function qa({showQRCode:t=!0,isManaging:e,className:a,texts:o}){let c=typeof window<"u",s=c?!!window.matchMedia?.("(prefers-color-scheme: dark)").matches:!1;function n(y){return y?window.location.href:""}return t?ee(Ot,{className:r("bg-beige-100 rounded-xl p-4 dark:bg-neutral-700",a?.qrCodeSection),children:[St(Mt,{children:ee(kt,{className:r("mb-3 text-base font-medium lg:text-lg",a?.qrCodeTitle),children:[o?.qrCodeSubtitle??D.qrCodeSubtitle," "+(o?.qrCodeTitle??D.qrCodeTitle)]})}),ee(Gt,{className:"flex flex-col items-center gap-2",children:[ee("div",{className:"mt-1.5 mb-3 flex items-center gap-x-2",children:[St("a",{href:"https://apps.apple.com/us/app/bitsnap/id6741902807",target:"_blank",className:"max-w-28 flex-1 basis-1/2 lg:max-w-36",children:St("img",{className:"h-auto w-full",src:Bt+"/app-store-logo.png",alt:"Download on App Store"})}),St("a",{href:"https://play.google.com/store/apps/details?id=com.bitsnap.Bitsnap&pli=1",target:"_blank",className:"max-w-28 flex-1 basis-1/2 lg:max-w-36",children:St("img",{className:"h-auto w-full",src:Bt+"/google-play-logo.png",alt:"Get in on Google Play"})})]}),c&&St("div",{className:"flex items-center justify-center",children:ee("div",{className:r("flex min-w-[40%] flex-col items-center gap-2 rounded-xl bg-white p-2 dark:bg-neutral-900",a?.qrCodeContainer),children:[St("img",{className:"mt-3 w-[80%] p-1 pt-3",src:Bt+`/api/qr-gen?url=${n(c)}&bgColor=${s?"171717":"F6F4F0"}&textColor=${s?"ffffff":"000000"}&margin=0`}),St("p",{className:"text-xs md:text-sm",children:o?.qrCodeScanText??D.qrCodeScanText})]})})]})]}):null}import{useState as ae}from"react";import{isValidPhoneNumber as bn}from"react-phone-number-input";import{useAutoAnimate as ln}from"@formkit/auto-animate/react";import{Label as Fa}from"@radix-ui/react-label";import{CheckCircleIcon as pn,CircleAlertIcon as dn,TriangleAlertIcon as un}from"lucide-react";import{useState as Be}from"react";import{jsx as rt,jsxs as wt}from"react/jsx-runtime";function Ha({submit:t,isLoading:e,errMsg:a,emailLack:o,warnMsg:c,isSubmited:s,agreementLack:n,showPhoneInput:y=!1,agreementText:u,className:d,texts:w}){let[k,x]=Be(""),[b,l]=Be(""),[i,S]=Be(!1),[C]=ln();function N(f){f.preventDefault(),t(k,b,i)}return wt("form",{ref:C,onSubmit:N,className:r("flex flex-col gap-3 text-left",d?.formContainer),children:[wt("div",{className:"flex flex-col gap-1 text-left",children:[rt(Fa,{className:"text-sm",htmlFor:"bts-notifications-form-email",children:w?.formEmailLabel??D.formEmailLabel}),rt($t,{value:k,onChange:f=>{x(f.currentTarget.value)},id:"bts-notifications-form-email",className:r(o===!0?"border-red-400":""),type:"email",placeholder:w?.formEmailPlaceholder??D.formEmailPlaceholder})]}),y&&wt("div",{className:"flex flex-col gap-1 text-left",children:[wt(Fa,{className:"text-sm",htmlFor:"bts-notifications-form-phone",children:[w?.formPhoneLabel??D.formPhoneLabel," ",rt("span",{className:"text-neutral-500 dark:text-neutral-500",children:w?.formPhoneOptional??D.formPhoneOptional})]}),rt($t,{value:b,onChange:f=>{l(f.currentTarget.value)},id:"bts-notifications-form-phone",className:"",type:"tel",autoComplete:"tel",autoCorrect:"off",placeholder:w?.formPhonePlaceholder??D.formPhonePlaceholder})]}),wt("div",{className:"flex items-start gap-x-1.5",children:[rt("input",{className:"cursor-pointer",id:"bts-notifications-form-marketing-consent",type:"checkbox",checked:i,onChange:()=>{S(!i)}}),rt("label",{htmlFor:"bts-notifications-form-marketing-consent",className:r("cursor-pointer text-xs leading-4 transition-colors md:text-sm md:leading-4",n===!0?"text-yellow-700":""),children:u})]}),a.length>0&&wt("p",{className:"mb-3 flex items-center gap-1 text-sm text-red-400",children:[rt(un,{color:"#ff6467",size:16})," ",a]}),c.length>0&&wt("p",{className:"mb-3 flex items-center gap-1 text-sm text-amber-400",children:[rt(dn,{color:"var(--color-amber-400)",size:16})," ",c]}),s==!1&&rt("div",{className:"flex justify-start",children:wt(G,{variant:"default",disabled:e,className:r(e?"cursor-not-allowed text-transparent":"","relative"),children:[w?.formSubmitButton??D.formSubmitButton,e&&rt("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:rt(X,{})})]})}),s&&wt("div",{className:"flex items-center gap-3 text-sm text-green-400",children:[rt(pn,{size:16})," ",w?.formSuccessMessage??D.formSuccessMessage]})]})}import{jsx as Oe,jsxs as gn}from"react/jsx-runtime";var mn=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;function Va({groups:t,onToggle:e,onCheckAll:a,slug:o,showPhoneInput:c=!1,agreementText:s,className:n,texts:y,isUpdating:u,wasChanged:d,onSuccess:w}){let[k,x]=ae(""),[b,l]=ae(""),[i,S]=ae(!1),[C,N]=ae(!1),[f,R]=ae(!1),{mutateAsync:I,isPending:T}=mt(ot.notifications.createNotificationUser);function P(z){return z==null?!1:bn(z,"PL")}async function m(z,E,O){if(x(""),l(""),R(!1),S(!1),N(!1),!O){N(!0),x("Zgoda w tym przypadku jest wymagana.");return}if(mn.test(z)===!1){x("Email jest nieprawid\u0142owy."),R(!0);return}E.length>0&&P(E)===!1&&l("Numer telefonu mo\u017Ce by\u0107 nieprawid\u0142owy. Zapisali\u015Bmy go ale je\u015Bli jest nieprawid\u0142owy to wpisz jeszcze raz i kliknij przycisk.");try{let p=await I({slug:o,email:z,phone:E,groups:t.filter(v=>v.isOn==!0).map(v=>v.id),mobileNotificationEnabled:!0,emailNotificationEnabled:!0,smsNotificationEnabled:!0});if(p.result.case==="success"){S(!0),setTimeout(()=>{w?.(!1,p.userId,p.accessToken)},1e3);return}else{S(!0);let v=p.result.value;if(v!=null){if(v==32){w?.(!0,void 0,void 0);return}console.log(`Code error: ${Ce[v]}`),x("Wyst\u0105pi\u0142 b\u0142\u0105d: "+Ce[v]);return}return}}catch(p){x("Wyst\u0105pi\u0142 b\u0142\u0105d podczas zapisywania. Spr\xF3buj ponownie."),console.log(`Error: ${p}`)}}let g=y?.formTitle??D.formTitle;return gn("div",{className:r("bg-beige-100 rounded-xl p-4 dark:bg-neutral-700",n?.formSection),children:[g.length>0&&Oe("h3",{className:r("mb-3 text-base font-medium lg:text-lg",n?.formTitle),children:g}),Oe(ve,{groups:t,isManaging:!1,onToggle:e??(()=>{}),onCheckAll:a??(()=>{}),isUpdating:u??!1,wasChanged:d??!1,isUserGroupsUpdated:!1,className:n,texts:y}),Oe(Ha,{errMsg:k,emailLack:f,warnMsg:b,submit:m,isLoading:T,isSubmited:i,agreementLack:C,showPhoneInput:c,agreementText:s??y?.agreementText??D.agreementText,className:n,texts:y})]})}import{useEffect as yn,useState as re}from"react";import{Label as Me}from"@radix-ui/react-label";import{MessageCircleWarningIcon as xn}from"lucide-react";import{useDebouncedCallback as kn}from"use-debounce";import{TriangleAlertIcon as hn,XIcon as fn}from"lucide-react";import{createPortal as vn}from"react-dom";import{useEffect as Wa,useState as wn}from"react";import{jsx as st,jsxs as Vt}from"react/jsx-runtime";function Ka({open:t,onOpenChange:e,onConfirm:a,isDeleting:o=!1}){let[c,s]=wn(!1);if(Wa(()=>(s(!0),()=>s(!1)),[]),Wa(()=>(t?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[t]),!c||!t)return null;let n=u=>{u.target===u.currentTarget&&e(!1)},y=()=>{a()};return vn(st("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 p-4",onClick:n,children:Vt("div",{className:r("relative w-full max-w-md rounded-2xl bg-white p-6 shadow-lg","dark:bg-neutral-800","animate-in fade-in-0 zoom-in-95 duration-200"),onClick:u=>u.stopPropagation(),children:[Vt("button",{onClick:()=>e(!1),className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-white transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-neutral-950 focus:ring-offset-2 disabled:pointer-events-none dark:ring-offset-neutral-950 dark:focus:ring-neutral-300",disabled:o,children:[st(fn,{className:"h-4 w-4"}),st("span",{className:"sr-only",children:"Zamknij"})]}),Vt("div",{className:"flex flex-col gap-4",children:[Vt("div",{className:"flex items-start gap-3",children:[st("div",{className:"flex-shrink-0",children:st(hn,{className:"h-6 w-6 text-amber-500","aria-hidden":"true"})}),st("div",{className:"flex-1",children:st("h2",{className:"text-lg font-semibold text-black dark:text-neutral-100",children:"Czy na pewno chcesz si\u0119 wypisa\u0107?"})})]}),st("p",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Klikni\u0119cie tego przycisku spowoduje wypisanie z wszelkich powiadomie\u0144 i grup, kt\xF3re zapisa\u0142e\u015B."}),Vt("div",{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",children:[st(G,{type:"button",variant:"ghost",onClick:()=>e(!1),disabled:o,className:"sm:min-w-[100px]",children:"Anuluj"}),Vt(G,{type:"button",variant:"destructive",onClick:y,disabled:o,className:r(o&&"cursor-not-allowed text-transparent","relative sm:min-w-[100px]"),children:["Usu\u0144",o&&st("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:st("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"})})]})]})]})]})}),document.body)}import{useAutoAnimate as Qa}from"@formkit/auto-animate/react";import{Fragment as Cn,jsx as j,jsxs as ct}from"react/jsx-runtime";function $a({accessToken:t,slug:e,userID:a,className:o,texts:c}){let[s]=Qa(),[n]=Qa(),{mutateAsync:y,isPending:u}=mt(ot.notifications.deleteNotificationUser),{mutateAsync:d,isPending:w}=mt(ot.notifications.updateNotificationUser),{data:k,isFetching:x}=se(ot.notifications.getNotificationUserSettings,{userId:a,slug:e,accessToken:t}),[b,l]=re(!1),[i,S]=re(!1),[C,N]=re(!1),[f,R]=re(!1),[I,T]=re(!1),P=k?.result.case==="success"?k?.result?.value:void 0;function m(){T(!0)}async function g(){await y({accessToken:t,slug:e,userId:a}),T(!1)}async function z(){await d({accessToken:t,slug:e,notificationUserId:a,mobileNotificationEnabled:f,emailNotificationEnabled:b,smsNotificationEnabled:i}),N(!0),setTimeout(()=>{N(!1)},3e3)}let E=kn(p=>{z()},300);yn(()=>{let p=k?.result.case==="success"?k?.result?.value:void 0;l(p?.emailNotificationEnabled??!1),S(p?.smsNotificationEnabled??!1),R(p?.mobileNotificationEnabled??!1)},[k]);function O(p,v){p==="email"&&l(v),p==="phone"&&S(v),p==="push"&&R(v),E(!0)}return ct("div",{className:r("bg-beige-100 rounded-xl p-4 dark:bg-neutral-700",o?.manageDataSection),children:[j("div",{className:"flex justify-start",children:j("h3",{className:r("mb-3 text-base font-medium lg:text-lg",o?.manageDataTitle),children:c?.manageDataTitle??D.manageDataTitle})}),x?j(oa,{className:"h-64 w-full"}):ct(Ot,{ref:n,className:r(w&&"relative"),children:[j(Mt,{children:j(kt,{children:j("p",{className:"text-sm text-left",children:c?.manageDataDescription??D.manageDataDescription})})}),ct(Gt,{ref:s,children:[j("div",{className:r(w&&"opacity-50 pointer-events-none","flex flex-col gap-2"),children:ct("div",{className:"flex flex-col items-start gap-5 gap-x-2",children:[P?.emailNotificationAvailable&&ct("div",{className:"flex items-center gap-3",children:[j(jt,{id:"email-enabled",className:"data-[state=checked]:bg-blue-500 dark:data-[state=unchecked]:bg-neutral-600",checked:b,onCheckedChange:()=>{O("email",!b)}}),j(Me,{htmlFor:"email-enabled",className:"text-sm",children:"Email"})]}),P?.smsNotificationAvailable&&ct("div",{className:"flex items-center gap-3",children:[j(jt,{id:"sms-enabled",className:"data-[state=checked]:bg-blue-500 dark:data-[state=unchecked]:bg-neutral-600",checked:i,onCheckedChange:()=>{O("phone",!i)}}),j(Me,{htmlFor:"sms-enabled",className:"text-sm",children:"SMS"})]}),P?.mobileNotificationAvailable&&ct(Cn,{children:[ct("div",{className:"flex items-center gap-3",children:[j(jt,{id:"push-enabled",className:"data-[state=checked]:bg-blue-500 dark:data-[state=unchecked]:bg-neutral-600",checked:f,onCheckedChange:()=>{O("push",!f)}}),j(Me,{htmlFor:"push-enabled",className:"text-sm",children:"Powiadomienia na telefon"})]}),P?.hasUserInstalledApp===!1&&ct("div",{className:"flex items-center gap-3",children:[j(xn,{color:"var(--color-amber-500)",size:26}),j("p",{className:"text-xs text-amber-500",children:"Wygl\u0105da na to, \u017Ce nie masz zainstalowanej aplikacji mobilnej. Zainstaluj i wyra\u017A zgod\u0119 na otrzymywanie powiadomie\u0144 na telefon."})]})]})]})}),ct("div",{className:"mt-5 flex flex-col gap-2 text-left",children:[j("hr",{}),C&&j("p",{className:"text-xs text-green-500",children:c?.manageDataUpdatedMessage??D.manageDataUpdatedMessage}),j("div",{className:"flex items-center gap-x-2",children:ct(G,{size:"sm",variant:"link",className:r("pl-0 ml-0",u&&"cursor-not-allowed"),onClick:m,children:[c?.manageDataUnsubscribeButton??D.manageDataUnsubscribeButton,u&&j("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:j(X,{})})]})})]})]}),w&&j("div",{className:"bg-black/30 absolute inset-0 rounded-xl",children:j("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:j(X,{})})})]}),j(Ka,{open:I,onOpenChange:T,onConfirm:g,isDeleting:u})]})}import{useState as we}from"react";import{ArrowLeft as Tn}from"lucide-react";import{useAutoAnimate as Ya}from"@formkit/auto-animate/react";import*as et from"@radix-ui/react-dialog";import{XIcon as Sn}from"lucide-react";import{jsx as Wt,jsxs as Ge}from"react/jsx-runtime";function Xa({...t}){return Wt(et.Root,{"data-slot":"dialog",...t})}function Pn({...t}){return Wt(et.Portal,{"data-slot":"dialog-portal",...t})}function Nn({className:t,...e}){return Wt(et.Overlay,{"data-slot":"dialog-overlay",className:r("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...e})}function Za({className:t,children:e,showCloseButton:a=!0,...o}){return Ge(Pn,{"data-slot":"dialog-portal",children:[Wt(Nn,{}),Ge(et.Content,{"data-slot":"dialog-content",className:r("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...o,children:[e,a&&Ge(et.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[Wt(Sn,{}),Wt("span",{className:"sr-only",children:"Close"})]})]})]})}import{Fragment as En,jsx as B,jsxs as ut}from"react/jsx-runtime";function Ja({slug:t,onSuccess:e,onError:a,className:o,isOpen:c,onClose:s,texts:n}){let[y]=Ya(),[u]=Ya(),[d,w]=we(""),[k,x]=we(""),[b,l]=we(!1),[i,S]=we(null),{mutateAsync:C,isPending:N}=mt(ot.notifications.verifyUserEmail),f=async P=>{if(P.preventDefault(),S(null),!d||!d.includes("@")){S(n.loginInvalidEmailError??"");return}try{await C({email:d,slug:t}),l(!0)}catch(m){let g=m instanceof Error?m:new Error(n.loginSendEmailError);S(g.message),a?.(g)}},R=async P=>{if(x(P),S(null),P.length===6)try{let m=await C({email:void 0,code:P,slug:t});m.ok&&m.accessToken?e?.(m.userId,m.accessToken):(S(n.loginVerificationFailedError??""),a?.(new Error(n.loginVerificationFailedError)))}catch(m){let g=m instanceof Error?m:new Error(n.loginVerifyCodeError);if(g.message.includes("Invalid code")){S(n.loginInvalidCodeError??g.message),x("");return}S(g.message),a?.(g),x("")}},I=async()=>{if(x(""),S(null),!d||!t){S(n.loginSlugRequiredError??"");return}try{await C({email:d,slug:t})}catch(P){let m=P instanceof Error?P:new Error(n.loginResendEmailError);S(m.message),a?.(m)}},T=()=>{l(!1),x(""),S(null)};return B(Xa,{open:c,onOpenChange:s,children:B(Za,{className:"sm:max-w-[425px] min-h-[250px]",children:ut("div",{className:"flex flex-col min-h-[250px] h-full",children:[ut("div",{ref:u,className:"flex items-start gap-2 mb-2",children:[b&&B(G,{variant:"ghost",size:"icon-sm",onClick:()=>{l(!1)},children:B(Tn,{className:"h-5 w-5"})}),B("div",{children:B(kt,{children:b?n.loginCodeLabel??"":n.loginTitle??""})})]}),B(ea,{className:"mb-4",children:b?ut(En,{children:[n.loginCodeSentMessage??""," ",d]}):n.loginDescription??""}),B("div",{className:"flex-1 flex flex-col",children:b?ut("form",{onSubmit:P=>P.preventDefault(),className:"flex flex-col flex-1",children:[ut("div",{className:"space-y-2",children:[B(Pe,{children:n.loginCodeLabel??""}),B(aa,{maxLength:6,value:k,onChange:R,disabled:N,children:ut(ra,{children:[B(Tt,{index:0}),B(Tt,{index:1}),B(Tt,{index:2}),B(Tt,{index:3}),B(Tt,{index:4}),B(Tt,{index:5})]})}),N&&B(X,{})]}),i&&B("div",{className:"text-sm text-destructive mt-2 mb-1",role:"alert",children:i}),B("div",{className:"grow"}),ut("div",{className:"flex flex-col items-start gap-2 pt-2",children:[d.length>0&&B(G,{variant:"link",size:"sm",onClick:I,disabled:N,className:"flex-1 ml-0 pl-0",children:n.loginResendCodeButton??""}),B(G,{variant:"link",size:"sm",onClick:T,disabled:N,className:"flex-1 ml-0 pl-0",children:n.loginChangeEmailButton??""})]})]}):ut("form",{onSubmit:f,className:"flex flex-col flex-1",children:[ut("div",{className:"space-y-2",children:[B(Pe,{htmlFor:"email",children:n.loginEmailLabel??""}),B($t,{id:"email",type:"email",placeholder:n.loginEmailPlaceholder??"",value:d,onChange:P=>w(P.target.value),required:!0,disabled:N,"aria-invalid":i?"true":"false"})]}),i&&B("div",{className:"text-sm text-destructive mt-2 mb-1",role:"alert",children:i}),B("div",{className:"grow"}),ut("div",{className:"flex flex-col items-start gap-0 pt-2",children:[B(G,{type:"submit",size:"sm",disabled:N,children:N?n.loginSendingButton??"":n.loginSendCodeButton??""}),B(G,{type:"button",variant:"link",className:"ml-0 pl-0",size:"sm",onClick:()=>{l(!0)},children:n.loginIHaveCode??""})]})]})})]})})})}import{useAutoAnimate as Dn}from"@formkit/auto-animate/react";import{jsx as $,jsxs as je}from"react/jsx-runtime";function _n(t,e){switch(e.type){case"SET_IS_LOGGED_IN":return{...t,isLoggedIn:e.value};case"SET_USER_ID":return{...t,userID:e.value};case"SET_LOADING":return{...t,isLoading:e.value};case"SET_PUBLIC_GROUPS":return{...t,groupsProvided:e.value,groups:e.value!=null&&e.value.length>0?t.groups.filter(a=>e.value?.find(o=>o.id===a.id)!=null):t.groups};case"SET_GROUPS":{let a=t.isLoggedIn==!1||t.groupsProvided!=null,o=e.value.map(c=>t.isLoggedIn==!0?c:{...c,isOn:t.groupsProvided?.find(s=>s.id===c.id)?.isOn??a});return{...t,groups:o}}case"TOGGLE_GROUP":{let a=t.groups.map(o=>o.id===e.groupID?{...o,isOn:!o.isOn}:o);return{...t,wasChanged:!0,groups:a}}case"CHECK_ALL_GROUPS":{let a=t.groups.map(o=>({...o,isOn:!0}));return{...t,groups:a,wasChanged:!0}}case"SET_WAS_CHANGED":return{...t,wasChanged:e.value};case"SET_IS_USER_GROUPS_UPDATED":return{...t,isUserGroupsUpdated:e.value};case"RESET_UPDATE_STATE":return{...t,wasChanged:!1,isUserGroupsUpdated:!0};case"SHOW_SETTINGS":return{...t,showSettings:!0};case"HIDE_SETTINGS":return{...t,showSettings:!1};default:return t}}function Ln({slug:t,userID:e,productID:a,projectID:o,analytics:c,projectName:s,projectLogo:n,projectLogoDark:y,groups:u,isManaging:d=!1,texts:w,showQRCode:k=!1,showPhoneInput:x=!1,hiddenGroupIds:b=[],className:l}){let[i]=Dn(),S=xt(o??Ht(),c),C=t??nt()??(typeof window<"u"?window.location.hostname:""),{mutateAsync:N,isPending:f}=mt(ot.notifications.updateUserGroups),{data:R,refetch:I}=An({queryKey:["notifications_accessToken"],queryFn:()=>{if(typeof window<"u")return{accessToken:localStorage.getItem("notifications_accessToken")??void 0,userID:localStorage.getItem("notifications_userID")??void 0}}}),{data:T,isPending:P,refetch:m}=se(ot.notifications.getUserGroups,{slug:C,accessToken:R?.accessToken}),[g,z]=In(_n,{isLoading:P,isUserGroupsUpdated:!1,wasChanged:!1,groupsProvided:u,groups:[],showSettings:R!=null&&d==!0,isLoggedIn:R!=null,userID:void 0});oe(()=>{z({type:"SET_LOADING",value:f||P})},[f,P]),oe(()=>{z({type:"SET_IS_LOGGED_IN",value:R?.accessToken!=null}),z({type:"SET_USER_ID",value:R?.userID}),R?.accessToken!=null&&d==!0&&z({type:"SHOW_SETTINGS"})},[R,d]),oe(()=>{if(T==null)return;let H=T.groups.map(W=>{let at="rarely";switch(W.howOften){case 0:at="rarely";break;case 1:at="often";break;case 2:at="veryOften";break}return{id:W.id,name:W.name,description:W.description,howOften:at,isOn:W.isOn??void 0}});z({type:"SET_GROUPS",value:H})},[T,P,u]);let E=zn(null);oe(()=>{let H=u?.map(W=>(W.id.startsWith("group_")||(W.id=`group_${W.id}`),W));z({type:"SET_PUBLIC_GROUPS",value:H})},[u]);let O={...D,...w};async function p(){await N({accessToken:R?.accessToken,slug:C,userId:e,groupIds:g.groups.filter(H=>H.isOn===!0).map(H=>H.id)}),z({type:"RESET_UPDATE_STATE"}),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{z({type:"SET_IS_USER_GROUPS_UPDATED",value:!1})},2e3)}function v(H){z({type:"TOGGLE_GROUP",groupID:H})}function bt(){z({type:"CHECK_ALL_GROUPS"})}function ne(){z({type:"SHOW_SETTINGS"})}function ye(){z({type:"HIDE_SETTINGS"})}function ie(){localStorage.removeItem("notifications_accessToken"),localStorage.removeItem("notifications_userID"),I(),z({type:"SET_USER_ID",value:void 0}),z({type:"SET_IS_LOGGED_IN",value:!1}),z({type:"HIDE_SETTINGS"})}async function Pt(H,W){typeof window<"u"&&(localStorage.setItem("notifications_accessToken",W),H!=null&&localStorage.setItem("notifications_userID",H)),z({type:"SET_USER_ID",value:H});try{await I(),m().then().catch().finally(()=>{d==!0&&z({type:"SHOW_SETTINGS"})})}catch(at){console.log(`Error: ${at}`)}}oe(()=>()=>{E.current&&clearTimeout(E.current)},[]);let lt=d==!0&&g.userID!=null&&R?.accessToken!=null;return je("main",{className:r("bitsnap-react relative",l?.container),children:[O.title!=null&&$("h1",{className:"text-2xl font-semibold text-black md:text-3xl lg:text-4xl xl:text-5xl dark:text-neutral-100",children:O.title}),!g.showSettings&&d&&$(G,{onClick:ne,variant:"outline",size:"icon",className:"absolute bottom-6 right-6 z-50 h-12 w-12 rounded-full shadow-lg hover:shadow-xl md:bottom-8 md:right-8","aria-label":"Settings",children:$(Rn,{className:"h-5 w-5"})}),$("div",{className:r("md:pt8 relative z-0 mt-6 overflow-hidden rounded-2xl bg-white px-3 pt-6 pb-3 md:px-5 md:pb-5 dark:bg-neutral-800",l?.header),children:g.showSettings?$("div",{className:"space-y-6",children:g.isLoggedIn&&je("div",{className:r("grid grid-cols-1 gap-3 lg:gap-6",lt?"md:grid-cols-2":""),children:[je("div",{className:l?.groupsContainer,children:[$(Ua,{projectName:s,projectLogo:n,projectLogoDark:y,description:O.managingDescription,className:l,onLogout:ie}),P&&$("div",{className:"flex justify-center items-center py-8",children:$(X,{})}),$(ve,{groups:g.groups,hiddenGroupIds:b,isManaging:d,onToggle:v,onCheckAll:bt,onUpdate:p,isUpdating:f,wasChanged:g.wasChanged,isUserGroupsUpdated:g.isUserGroupsUpdated,className:l,texts:O})]}),lt&&$($a,{accessToken:R.accessToken??"",slug:C,userID:g.userID??"",className:l,texts:O}),k!=!1&&$(qa,{showQRCode:k,isManaging:!0,className:l,texts:O})]})}):$("div",{className:r("grid grid-cols-1 gap-3 lg:gap-6"),children:$(Va,{slug:C,onToggle:H=>{z({type:"TOGGLE_GROUP",groupID:H})},onCheckAll:()=>{z({type:"CHECK_ALL_GROUPS"})},onSuccess:(H,W,at)=>{S.track("availability_signup",{},{product_id:a??null}),at!=null&&Pt(W,at),H&&z({type:"SHOW_SETTINGS"})},groups:g.groups,showPhoneInput:x,agreementText:O.agreementText,className:l,texts:O,wasChanged:g.wasChanged,isUpdating:f})})}),$(Ja,{isOpen:g.showSettings&&!g.isLoggedIn,slug:C,onSuccess:Pt,texts:O,onClose:ye})]})}function Un({slug:t,userID:e,productID:a,projectID:o,analytics:c,projectName:s,projectLogo:n,projectLogoDark:y,groups:u,isManaging:d,texts:w,showQRCode:k,showPhoneInput:x,hiddenGroupIds:b,className:l}){return $(Se,{children:$(Ln,{slug:t,userID:e,productID:a,projectID:o,analytics:c,projectName:s,projectLogo:n,projectLogoDark:y,groups:u,isManaging:d,texts:w,showQRCode:k,showPhoneInput:x,hiddenGroupIds:b,className:l})})}var Bn=Un;export{ze as ApplePayButton,On as Bitsnap,Ko as BitsnapCheckout,Yr as BitsnapReturns,_r as BitsnapReturnsProvider,ao as CHECKOUT_SLOT_NAMES,ur as Environment,Le as GooglePayButton,Zr as ITEM_IDS_NOT_FOUND,Bn as NotificationsComponent,Fn as PRODUCT_LIST_SLOT_NAMES,Xr as Panel,Tr as PanelLogin,xr as PanelProvider,Wn as ProductList,$r as PublicOrderPage,Er as RETURNS_SLOT_NAMES,Ir as ReturnsAppearanceProvider,qr as ReturnsCodeStep,Vr as ReturnsConfirmation,jr as ReturnsEmailStep,Qr as ReturnsMyReturnDetail,Kr as ReturnsMyReturnsList,Hr as ReturnsOrderDetail,Fr as ReturnsOrderList,Dr as ReturnsProvider,Wr as ReturnsResult,Nr as buildAccessTokenRedirect,Gn as createCheckout,Mn as createPaymentURL,Hn as formatProductPrice,yr as getAllowedReturnOrigins,Xt as getLocale,mr as getPanelConfig,jn as getReferenceIfPossible,Cr as getReturnURLFromSearch,qn as injectReferenceToRequestIfNeeded,Sr as persistReturnURL,Pr as readPersistedReturnURL,wr as setAllowedReturnOrigins,dr as setCustomHost,vr as setHost,Ne as setLocale,fr as setLoginURL,br as setPanelConfig,gr as setPanelProjectID,Ee as setProjectID,hr as setTheme,Or as useCreateReturn,Gr as useMyReturn,Mr as useMyReturns,kr as usePanelConfig,Vn as useProducts,Ur as useReturnOrders,Lr as useReturnSession,Br as useReturnableOrder,zr as useReturnsAppearance,Ar as useReturnsSlot,Rr as useReturnsText};
|
|
1
|
+
import{A as Rt,B as ri,C as oi,D as ni,E as ii,F as si,G as ci,H as Sa,I as L,J as be,K as Na,N as Me,O as ot,P as Ta,Q as Ea,S as Ft,T as Ht,U as Oe,a as ba,b as Bt,c as Gt,d as Nt,e as ga,f as qt,g as ha,h as fa,i as zt,j as qr,k as jr,l as Fr,m as Hr,n as Wr,o as jt,p as mo,q as go,r as Le,s as At,t as ft,u as H,v as ho,w as ka,x as Ca,y as Ue,z as Pa}from"./chunk-5GMWRCHK.mjs";import{a as fo}from"./chunk-L6J6H73J.mjs";import{A as bo,a as De,b as X,c as Vr,d as Kr,e as Qr,f as $r,i as Xr,k as Zr,l as Yr,m as Jr,n as to,o as eo,p as ao,q as ro,r as oo,t as no,u as io,v as so,w as co,x as lo,y as po,z as uo}from"./chunk-KH7DFTJY.mjs";import{a as li,b as pi,c as di,d as ui}from"./chunk-OC7YS3UY.mjs";import{a as ya,b as wa}from"./chunk-KOVKUJAW.mjs";import{a as Ar,b as Rr,c as Dr,d as _r,e as Lr,f as Ur,g as Mr,h as Or,i as Br,j as Gr}from"./chunk-K2EITRNW.mjs";import{g as Ae,h as zr,j as it,k as ue,l as ht,o as Re,q as G,r as Xt,u as va}from"./chunk-3DGHF373.mjs";import{d as r,f as Ot,g as Ir,j as xa,l as _e,m as Zt}from"./chunk-GAVLY6RX.mjs";import{l as Ut,m as Mt,n as St,q as ma}from"./chunk-YNGXQJPE.mjs";import"./chunk-ADYVTMGH.mjs";import"./chunk-U6FLIRIV.mjs";import Ia from"apple-pay-button";function Wt(){try{return ot()}catch{return}}import{useQuery as za}from"@tanstack/react-query";import{jsx as me}from"react/jsx-runtime";var vo=Ia.default??Ia;function yo({style:t,buttonType:e,colorType:a,items:o,onClick:n}){let{checkIfApplePayIsAvailable:s,getApplePayPaymentRequest:i,completeApplePayPayment:x,setCountry:b,setCouponCodeIfPossible:u,setDeliveryMethod:k,setEmail:g,setPostalCode:h,clearCart:m,getApplePayPreview:l}=Ft(),c=Mt(),P=L("paymentForCart"),{data:C}=za({queryKey:["is-apple-pay-available"],queryFn:s}),S=o.map(f=>`${f.id}:${f.quantity}`).join(","),y=Ta(),{data:R}=za({queryKey:["apple-pay-preview",S,y.country??"",y.couponCode??"",y.selectedDeliveryMethod??"",y.postalCode??""],queryFn:()=>l({items:o.map(f=>({productID:f.id,quantity:f.quantity,metadata:f.metadata}))}),enabled:C===!0});if(C!=!0)return null;let I=R!=null&&!H(R)?R:{countryCode:y.country||"PL",currencyCode:o[0]?.currency??"PLN",totalAmount:`${Le(o.reduce((f,v)=>f+v.price*v.quantity,0)/100,2)}`},T=o.map(f=>({productID:f.id,quantity:f.quantity,metadata:f.metadata}));async function N(){let f=!1,v=d=>{f||(f=!0,c.track("apple_pay_result",{outcome:d}))};c.track("apple_pay_clicked",{}),c.track("payment_method_selected",{gateway:"apple_pay",method:"apple_pay"}),ft({event:"initiateCheckout",items:o.map(d=>({id:d.id,name:d.name,price:d.price,quantity:d.quantity,currency:I.currencyCode}))});let A=o.find(d=>d.isDeliverable===!0)!=null,E=new ApplePaySession(14,{countryCode:I.countryCode,merchantCapabilities:["supports3DS"],supportedNetworks:["visa","masterCard"],currencyCode:I.currencyCode,total:{amount:I.totalAmount,label:P,type:"pending"},lineItems:o.map(d=>({amount:`${Le(d.price*d.quantity/100,2)}`,label:d.name,type:"final"})),...A?{shippingMethods:[],supportsCouponCode:!0,requiredBillingContactFields:["name","email","postalAddress","phone"],requiredShippingContactFields:["name","email","postalAddress","phone"]}:{}});await n?.();let O=await i({expectedItems:T});if(H(O)){console.error("Error creating ApplePaySession:",O.error),v("fail");return}E.oncancel=d=>{console.log("ApplePaySession cancelled",d),v("cancel")},E.onvalidatemerchant=async d=>{try{let w=await ba.get(Ot).applePayValidateMerchant({validationUrl:d.validationURL,projectId:ot()});console.log("merchantSession",w.merchantSession),w.merchantSession.length>0?(console.log("completing merchant session"),E.completeMerchantValidation(JSON.parse(w.merchantSession))):E.abort()}catch{E.abort()}},E.onshippingmethodselected=async d=>{console.log("shipping method selected",d),c.track("delivery_method_selected",{method:d.shippingMethod.identifier}),await k(d.shippingMethod.identifier);let w=await i({expectedItems:T});if(console.log("apRequest",w),H(w))throw E.abort(),new Error("Failed to get Apple Pay payment request");E.completeShippingMethodSelection({newTotal:w.total,newLineItems:w.lineItems,newShippingMethods:w.shippingMethods})},E.onshippingcontactselected=async d=>{try{d.shippingContact.countryCode!=null&&await b(d.shippingContact.countryCode),d.shippingContact.postalCode!=null&&await h(d.shippingContact.postalCode),d.shippingContact.phoneNumber!=null&&await g(d.shippingContact.emailAddress);let w=await i({expectedItems:T});if(H(w))throw E.abort(),new Error("Failed to get Apple Pay payment request");console.log("apRequest",w),E.completeShippingContactSelection({newLineItems:w.lineItems,newTotal:w.total,newShippingMethods:w.shippingMethods})}catch(w){console.log("shipping contact selected error",w),E.abort()}},E.oncouponcodechanged=async d=>{try{console.log("coupon code changed",d);let w=await u(d.couponCode),gt=await i({expectedItems:T});if(console.log("apRequest",gt),H(gt))throw E.abort(),new Error("Failed to get Apple Pay payment request");E.completeCouponCodeChange({errors:H(w)?[new ApplePayError("couponCodeInvalid")]:void 0,newTotal:gt.total,newLineItems:gt.lineItems,newShippingMethods:gt.shippingMethods})}catch(w){console.log("coupon code changed error",w),E.abort()}},E.onpaymentauthorized=async d=>{c.track("payment_submitted",{gateway:"apple_pay",method:"apple_pay"});try{let w=await x({token:d.payment.token,billingContact:d.payment.billingContact,shippingContact:d.payment.shippingContact});if(H(w)){console.log("apple pay error",w),v("fail"),E.completePayment({status:ApplePaySession.STATUS_FAILURE});return}w.redirectURL&&setTimeout(()=>{open(w.redirectURL,"_self")},2e3),v(w.isSuccess?"success":"fail"),E.completePayment({status:w.isSuccess?ApplePaySession.STATUS_SUCCESS:ApplePaySession.STATUS_FAILURE}),w.isSuccess&&m()}catch{v("fail"),E.completePayment({status:ApplePaySession.STATUS_FAILURE})}},E.begin()}return me(vo,{style:t,buttonStyle:a,type:e,onClick:N})}function wo(t){let e=St(Wt(),t.analytics,"cart");return me(Ut,{value:e,children:me(Ht,{children:me(yo,{...t})})})}var Be=wo;import{useEffect as ee,useId as cn,useRef as ln}from"react";import Z from"zod";import{useAutoAnimate as tn}from"@formkit/auto-animate/react";import*as ut from"@radix-ui/react-dialog";import{useCallback as en,useRef as an,useState as rn}from"react";import{createPortal as on}from"react-dom";import{createContext as No,useContext as To,useMemo as Eo}from"react";var xo=["root","overlay","panel","header","title","closeButton","productList","product","productImage","productName","productPrice","quantityControl","quantityInput","quantityButton","removeButton","summary","totalLabel","totalValue","deliveryText","summaryNote","countryLabel","countryTrigger","countryDropdown","countrySearch","countryOption","paymentButtons","paymentMethods","paymentMethodOption","checkoutButton","emptyState","error","skeleton"],ko={fontFamily:"--bitsnap-checkout-font-family",fontSize:"--bitsnap-checkout-font-size",background:"--bitsnap-checkout-background",surface:"--bitsnap-checkout-surface",foreground:"--bitsnap-checkout-foreground",mutedForeground:"--bitsnap-checkout-muted-foreground",border:"--bitsnap-checkout-border",buttonBackground:"--bitsnap-checkout-button-background",buttonForeground:"--bitsnap-checkout-button-foreground",buttonHoverBackground:"--bitsnap-checkout-button-hover-background",hoverSurface:"--bitsnap-checkout-hover-surface",focusRing:"--bitsnap-checkout-focus-ring",error:"--bitsnap-checkout-error",overlay:"--bitsnap-checkout-overlay",radius:"--bitsnap-checkout-radius"},Co={dark:{},light:{background:"#ffffff",surface:"#f9fafb",foreground:"#18181b",mutedForeground:"#71717a",border:"#e4e4e7",buttonBackground:"#18181b",buttonForeground:"#fafafa",buttonHoverBackground:"#000000",hoverSurface:"#e4e4e7",focusRing:"#71717a",error:"#dc2626",overlay:"rgb(0 0 0 / 0.35)"}},Po=[{token:"background",variable:"--background"},{token:"foreground",variable:"--foreground"},{token:"surface",variable:"--card"},{token:"surface",variable:"--popover"},{token:"foreground",variable:"--popover-foreground"},{token:"mutedForeground",variable:"--muted-foreground"},{token:"border",variable:"--border"},{token:"border",variable:"--input"},{token:"focusRing",variable:"--ring"},{token:"error",variable:"--destructive"},{token:"radius",variable:"--radius"}];function So(t){return{"--popover":t.surface??"var(--color-neutral-800)","--popover-foreground":t.foreground??"var(--color-neutral-200)"}}function Ge(t){let e=ya(t,{defaultTheme:"dark",presets:Co,variables:ko,shadcnVariables:Po});return{theme:e.theme,isCustomized:e.isCustomized,tokens:e.tokens,elements:e.elements,boundaryClassName:e.theme,boundaryStyle:e.boundaryStyle,dropdownStyle:So(e.tokens)}}function Aa(t,e){return wa(t.elements,e)}import{jsx as Io}from"react/jsx-runtime";var Ra=No(Ge());function Da({appearance:t,children:e}){let a=Eo(()=>Ge(t),[t]);return Io(Ra.Provider,{value:a,children:e})}function Yt(){return To(Ra)}function z(t){let e=Yt();return Aa(e,t)??{}}import{useAutoAnimate as Xo}from"@formkit/auto-animate/react";import K from"react";import{useEffect as Lo,useState as Uo}from"react";import*as U from"@radix-ui/react-select";import{CheckIcon as zo,ChevronDownIcon as _a,ChevronUpIcon as Ao}from"lucide-react";import{jsx as Q,jsxs as qe}from"react/jsx-runtime";function La({...t}){return Q(U.Root,{"data-slot":"select",...t})}function Ua({...t}){return Q(U.Value,{"data-slot":"select-value",...t})}var Ro="border-input dark:bg-input/30 dark:hover:bg-input/50 bg-transparent";function Ma({className:t,size:e="default",theme:a="default",children:o,...n}){return qe(U.Trigger,{"data-slot":"select-trigger","data-size":e,className:r("data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive flex w-fit items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",a==="bare"?"":Ro,t),...n,children:[o,Q(U.Icon,{asChild:!0,children:Q(_a,{className:"size-4 opacity-50"})})]})}function Oa({className:t,children:e,position:a="popper",align:o="center",...n}){return Q(U.Portal,{children:qe(U.Content,{"data-slot":"select-content",className:r("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",a==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:a,align:o,...n,children:[Q(Do,{}),Q(U.Viewport,{className:r("p-1",a==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:e}),Q(_o,{})]})})}function Ba({className:t,children:e,...a}){return qe(U.Item,{"data-slot":"select-item",className:r("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...a,children:[Q("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:Q(U.ItemIndicator,{children:Q(zo,{className:"size-4"})})}),Q(U.ItemText,{children:e})]})}function Do({className:t,...e}){return Q(U.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:r("flex cursor-default items-center justify-center py-1",t),...e,children:Q(Ao,{className:"size-4"})})}function _o({className:t,...e}){return Q(U.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:r("flex cursor-default items-center justify-center py-1",t),...e,children:Q(_a,{className:"size-4"})})}import{jsx as vt,jsxs as ge}from"react/jsx-runtime";function Mo({id:t,open:e,disabled:a=!1,onToggle:o,onChange:n,selectedValue:s,countries:i}){let[x,b]=Uo(""),{isCustomized:u,boundaryClassName:k,boundaryStyle:g,dropdownStyle:h}=Yt(),m=z("countryTrigger"),l=z("countryDropdown"),c=z("countrySearch"),P=z("countryOption"),C=L("searchCountry"),S=L("noCountriesFound");Lo(()=>{s==null&&i.length>0&&n(i[0].code)},[]);let y=i.filter(I=>I.name.toLowerCase().startsWith(x.toLowerCase())),R=i.find(I=>I.code===s);return ge(La,{value:s,onValueChange:I=>{n(I),b("")},open:e,onOpenChange:I=>{I!==e&&o(),I||b("")},disabled:a,children:[vt(Ma,{"data-bitsnap-checkout-slot":"countryTrigger",theme:"bare",className:r(a?"bg-neutral-100 dark:bg-neutral-800 dark:border-neutral-700":"","w-full rounded-md",m.className),style:m.style,children:vt(Ua,{children:R&&ge("span",{className:"truncate flex items-center",children:[vt("img",{alt:s,src:`https://purecatamphetamine.github.io/country-flag-icons/3x2/${s}.svg`,className:"inline mr-2 h-4 rounded-sm"}),R.name]})})}),ge(Oa,{"data-bitsnap-checkout":u?"dropdown":void 0,"data-bitsnap-checkout-slot":u?"countryDropdown":void 0,className:r(u?"bitsnap-react":"",k,"w-full max-h-80 max-w-[350px] z-[999999]",l.className),style:{...u?{...g,...h}:void 0,...l.style},position:"popper",children:[vt("div",{"data-bitsnap-checkout-slot":"countrySearch",className:r("sticky top-0 z-10 p-1 border-b",c.className),style:c.style,children:vt("input",{type:"search",name:"search",autoComplete:"off",className:"block w-full outline-none sm:text-body-regular bg-transparent rounded-md px-2 py-1.5",placeholder:C,"aria-label":C,value:x,onChange:I=>b(I.target.value),onClick:I=>I.stopPropagation(),onKeyDown:I=>I.stopPropagation()})}),vt("div",{className:"max-h-64 overflow-y-auto",children:y.length===0?vt("div",{className:"cursor-default select-none relative py-2 pl-3 pr-9 text-sm",children:S}):y.map(I=>ge(Ba,{"data-bitsnap-checkout-slot":"countryOption",value:I.code,className:r("cursor-default select-none relative py-2 pl-3 pr-9 flex items-center transition",P.className),style:P.style,children:[vt("img",{alt:I.code,src:`https://purecatamphetamine.github.io/country-flag-icons/3x2/${I.code}.svg`,className:"inline mr-2 h-4 rounded-sm"}),vt("span",{className:"font-normal truncate",children:I.name})]},`${t}-${I.code}`))})]})]})}var Ga=Mo;import{useEffect as Fo,useRef as Fa,useState as Wa}from"react";import{MinusIcon as Ho,PlusIcon as Wo}from"lucide-react";import{Slot as ts}from"@radix-ui/react-slot";import{cva as Oo}from"class-variance-authority";import{jsx as Go}from"react/jsx-runtime";var Bo=Oo("flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",{variants:{orientation:{horizontal:"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}});function qa({className:t,orientation:e,...a}){return Go("div",{role:"group","data-slot":"button-group","data-orientation":e,className:r(Bo({orientation:e}),t),...a})}import{Fragment as qo,jsx as he,jsxs as jo}from"react/jsx-runtime";function ja({price:t,currency:e,pricing:a,quantity:o=1}){let n=L("lowestPrice30Days"),s=L("noPriceHistory"),i=a?.regularPrice??t,x=a?.effectivePrice??t,b=a?.discount?.status==="ACTIVE"&&x<i;return he("span",{children:b?jo(qo,{children:[he("span",{className:"mr-2 text-neutral-500 line-through",children:At(i*o,e)}),he("span",{className:"font-semibold text-red-700",children:At(x*o,e)}),he("span",{className:"mt-1 block text-xs text-neutral-600",children:a?.referencePrice.historyAvailable&&a.referencePrice.amount!=null?`${n} ${At(a.referencePrice.amount,e)}`:s})]}):At(x*o,e)})}function fe(t){return Number.isFinite(t)?Math.min(99,Math.max(1,Math.trunc(t))):1}function je(t,e){let a=parseInt(t,10);return Number.isNaN(a)?e:fe(a)}import{Fragment as Qo,jsx as V,jsxs as ve}from"react/jsx-runtime";var Vo=({isNotAvailable:t,quantity:e,details:a,url:o,shouldUpdate:n})=>{let s=z("product"),i=z("productImage"),x=z("productName"),b=z("productPrice"),u=z("removeButton"),k=L("remove"),g=a.image_url??a.images?.[0],[h,m]=Wa(),l=g!=null&&g.length>0&&g!==h,c=a.baseName??a.name;return ve("div",{"data-bitsnap-checkout-slot":"product","data-bitsnap-checkout-unavailable":t?"":void 0,className:r("flex items-center gap-3 mx-3",t?"outline outline-1 rounded-md m-1":"",s.className),style:s.style,children:[l&&V(Ha,{url:o,tabIndex:-1,"aria-hidden":"true",className:"contents",children:V("img",{"data-bitsnap-checkout-slot":"productImage",className:r("aspect-auto max-w-[30%] max-w-32 max-h-32 py-2 overflow-hidden",i.className),style:i.style,src:g,alt:"",onError:()=>m(g)})}),ve("div",{className:"flex flex-col w-full",children:[V("p",{"data-bitsnap-checkout-slot":"productName",className:r("font-medium",x.className),style:x.style,children:V(Ha,{url:o,className:"text-inherit no-underline hover:underline",children:c})}),a.variantName!=null&&a.variantName.length>0&&V("p",{className:"text-sm opacity-70",children:a.variantName}),V("p",{"data-bitsnap-checkout-slot":"productPrice",className:r("text-sm",b.className),style:b.style,suppressHydrationWarning:!0,children:V(ja,{price:a.price,currency:a.currency,pricing:a.pricing,quantity:e})}),ve("div",{className:"flex justify-between",children:[V(Ko,{className:"",quantity:e,shouldUpdate:n}),V(G,{"data-bitsnap-checkout-slot":"removeButton",type:"button",variant:"ghost",size:"sm",className:u.className,style:u.style,"aria-label":`${k}: ${a.name}`,onClick:()=>{Promise.resolve(n(0)).catch(()=>{})},children:k})]})]})]})},Va=Vo,Ha=({url:t,children:e,...a})=>t==null?V(Qo,{children:e}):V("a",{href:t,...a,children:e}),Ko=({quantity:t,shouldUpdate:e,className:a})=>{let[o,n]=Wa(t.toString()),s=Fa(t),i=z("quantityControl"),x=z("quantityInput"),b=z("quantityButton"),u=L("quantity"),k=L("increaseQuantity"),g=L("decreaseQuantity"),h=Fa(t);h.current=t,Fo(()=>{s.current=t,n(t.toString())},[t]);function m(l){n(l.toString()),l!==s.current&&(s.current=l,Promise.resolve(e(l)).catch(()=>{s.current===l&&(s.current=h.current,n(h.current.toString()))}))}return V("div",{"data-bitsnap-checkout-slot":"quantityControl",className:r("flex",a,i.className),style:i.style,children:ve(qa,{"aria-label":u,children:[V(G,{"data-bitsnap-checkout-slot":"quantityButton",type:"button",className:b.className,style:b.style,"aria-label":g,onClick:()=>m(fe(s.current-1)),children:V(Ho,{"aria-hidden":"true"})}),V("input",{"data-bitsnap-checkout-slot":"quantityInput",className:r("w-8 bg-transparent text-center",x.className),style:x.style,value:o,"aria-label":u,inputMode:"numeric",pattern:"[0-9]*",onChange:l=>n(l.currentTarget.value),onBlur:l=>m(je(l.currentTarget.value,s.current)),onKeyDown:l=>{l.key==="Enter"&&m(je(l.currentTarget.value,s.current))},type:"text"}),V(G,{"data-bitsnap-checkout-slot":"quantityButton",type:"button",className:b.className,style:b.style,"aria-label":k,onClick:()=>m(fe(s.current+1)),children:V(Wo,{"aria-hidden":"true"})})]})})};import{jsx as $o}from"react/jsx-runtime";function Fe({className:t,...e}){return $o("div",{"data-slot":"skeleton",className:"bg-neutral-700 animate-pulse rounded-md "+t,...e})}import{useMutation as Jt,useQuery as te,useQueryClient as Zo}from"@tanstack/react-query";import Ka from"react";import{jsx as ye,jsxs as we}from"react/jsx-runtime";function Qa({choice:t,selected:e,onChange:a,disabled:o}){let n=be(),s=z("paymentMethods"),i=z("paymentMethodOption"),x=Ka.useId(),b=Ka.useId(),u=t.manualAccountTypes.length===0||t.manualAccountTypes.includes("blik"),k={online:{title:n("paymentMethodOnline"),description:n("paymentMethodOnlineDescription")},manual:{title:n(Pa(t.manualAccountTypes)),description:n("paymentMethodManualDescription"),note:u?n("paymentMethodManualBlikNote"):void 0},cod:{title:n("paymentMethodCod"),description:n("paymentMethodCodDescription")}};return we("fieldset",{"data-bitsnap-checkout-slot":"paymentMethods","aria-labelledby":b,className:r("mx-2 mt-4 mb-2 flex min-w-0 flex-col gap-2 border-0 p-0",s.className),style:s.style,disabled:o,children:[ye("legend",{id:b,className:"mb-1 px-1 text-sm font-medium",children:n("paymentMethodLegend")}),t.methods.map(g=>{let h=k[g],m=g===e,l=`${x}-${g}-description`;return we("label",{"data-bitsnap-checkout-slot":"paymentMethodOption","data-payment-method":g,"data-selected":m?"":void 0,className:r("flex cursor-pointer items-start gap-3 rounded-md border px-3 py-2.5 transition-colors",i.className),style:i.style,children:[ye("input",{type:"radio",name:x,value:g,checked:m,onChange:()=>a(g),"aria-describedby":l,className:"mt-0.5 size-4 shrink-0 cursor-pointer"}),we("span",{className:"flex min-w-0 flex-col gap-0.5",children:[ye("span",{className:"text-sm font-semibold leading-snug",children:h.title}),we("span",{id:l,"data-bitsnap-checkout-payment-method-description":"",className:"text-xs leading-snug",children:[h.description,m&&h.note!=null&&ye("span",{className:"mt-1 block font-medium",children:h.note})]})]})]},g)})]})}import{Fragment as Jo,jsx as D,jsxs as st}from"react/jsx-runtime";var Yo=({className:t,locale:e})=>{let a=Ft(),o=Mt(),n=e??Zt(),s=z("productList"),i=z("summary"),x=z("totalLabel"),b=z("totalValue"),u=z("deliveryText"),k=z("summaryNote"),g=z("countryLabel"),h=z("paymentButtons"),m=z("checkoutButton"),l=z("emptyState"),c=z("error"),P=z("skeleton"),C=L("unavailableProducts"),S=be(),y=L("emptyCart"),R=L("total"),I=L("delivery"),T=L("chooseCountry"),N=L("nextStep"),f=L("loadFailed"),v=L("retry"),A=L("countryRequired"),E=L("extrasCalculatedNext"),O=K.useId(),d=K.useId(),{mutateAsync:w}=Jt({mutationFn:a.removeProductFromCart}),{mutateAsync:gt}=Jt({mutationFn:a.updateQuantity}),{mutateAsync:se}=Jt({mutationFn:a.setCountry}),{mutateAsync:Te}=Jt({mutationFn:a.clearCart}),[ce,kt]=K.useState(""),pt=Rt(p=>p.notice);K.useEffect(()=>()=>Rt.getState().setNotice(void 0),[]);let F=ce.length>0?ce:pt??"",[W,rt]=K.useState([]),[Ze,fr]=K.useState(!1),{mutateAsync:vr,isPending:Ee}=Jt({mutationFn:a.redirectToNextStep}),{data:Ye}=te({queryKey:["cart-available-countries"],queryFn:a.getAvailableCountries}),{data:yr}=te({queryKey:["cart-one-click-payment"],queryFn:a.checkIfApplePayIsAvailable}),{data:Ie,isLoading:Lt,isError:wr,refetch:Je}=te({queryKey:["cart",n],queryFn:a.getProducts}),{data:It,refetch:ta}=te({queryKey:["cart-country"],queryFn:a.getCountry}),[xr]=Xo(),B=H(Ie)?void 0:Ie,Ct=It!=null&&!H(It)&&It!=""?It:void 0,ea=Zo(),le=B==null||B.length===0||Ct==null?void 0:B.map(p=>`${p.productID}:${p.quantity}`).sort().join(","),aa={queryKey:["cart-payment-methods",ot(),n,Ct,le],queryFn:async()=>a.getPaymentMethodChoice().catch(()=>null),staleTime:6e4,retry:!1},{data:ra,isPlaceholderData:kr}=te({...aa,enabled:le!=null,placeholderData:p=>p===void 0?void 0:Ca(p)}),pe=le!=null?ra??null:null,[oa,Cr]=K.useState(void 0),[na,ia]=K.useState(!1),sa=K.useRef(null),ca=!Lt&&(wr||H(Ie)),Pt=H(Ye)?[]:Ye,Qt=B?.reduce((p,j)=>j.details==null?p:p+(j.details.pricing?.effectivePrice??j.details.price)*j.quantity,0)??0,$t=B?.[0]?.details?.currency??"PLN",Pr=B?.some(p=>p.details?.isDeliverable===!0)??!1,la=It!==void 0&&Ct==null,pa=K.useRef(!1);K.useEffect(()=>{pa.current||Pt==null||Pt.length===0||It==null||Ct!=null&&Pt.some(p=>p.code===Ct)||(pa.current=!0,se(Pt[0].code).then(()=>ta()).catch(()=>{}))},[Pt,It,Ct]);let da=K.useRef(!1);K.useEffect(()=>{da.current||Lt||(da.current=!0,o.track("cart_opened",{item_count:B?.reduce((p,j)=>p+j.quantity,0)??0,value_minor:Qt,currency:$t}))},[Lt,o,B,Qt,$t]);let ze=K.useRef(new Map);K.useEffect(()=>{ze.current.clear()},[B]);function Sr(p,j){let J=B?.find(Er=>Er.id===p);if(J?.details==null)return;let tt=j-(ze.current.get(p)??J.quantity);if(ze.current.set(p,j),tt===0)return;let dt=J.details.pricing?.effectivePrice??J.details.price,de=J.catalogProductID??J.productID;o.track(tt>0?"add_to_cart":"remove_from_cart",{qty:Math.abs(tt),value_minor:Math.round(dt*Math.abs(tt)),currency:J.details.currency},{product_id:de,variant_id:de!==J.productID?J.productID:null})}let ua=K.useRef(!1);async function Nr(p,j){if(j!=null){Sr(p,Math.max(0,j));try{let J=j<=0?await w({id:p}):await gt({id:p,quantity:j});if(H(J))throw new Error(`cannot change the cart: ${J.error}`)}finally{await Je().catch(()=>{})}}}async function Tr(){try{kt(""),rt([]),Rt.getState().setNotice(void 0);let p=pe,j=p!=null?Ue(p,oa):void 0;if(le!=null&&(ra===void 0||kr)){ia(!0);try{p=await ea.fetchQuery(aa).catch(()=>null)}finally{ia(!1)}if(p==null)j=void 0;else if(j==null||!p.methods.includes(j)){window.setTimeout(()=>{sa.current?.querySelector("input:checked")?.focus()},0);return}}if(B!=null){!ua.current&&B.length>0&&(ua.current=!0,o.track("checkout_started",{item_count:B.reduce((dt,de)=>dt+de.quantity,0),checkout_type:"cart",value_minor:Qt,currency:$t}));try{ft({event:"initiateCheckout",items:B?.map(dt=>({id:dt.productID,name:dt.details?.name??"",price:dt.details?.price??0,quantity:dt.quantity,currency:dt.details?.currency??"PLN"}))})}catch{}}let J=Ea(),tt=await vr(j!=null?{paymentMethod:j}:void 0);if(H(tt)){ea.invalidateQueries({queryKey:["cart-payment-methods"]}),tt.error=="item-ids-not-found"?(kt(C),"data"in tt&&Array.isArray(tt.data)&&rt(tt.data)):j==="cod"&&tt.error=="gateway-not-configured"?kt(S("paymentMethodCodUnavailable")):kt(ka(tt,S));return}Na(tt,{cartProjectId:ot(),lines:J})||await Te(),window.location.href=tt.url}catch(p){console.warn("checkout failed",p),kt(S("checkoutFailed"))}}return st("div",{className:`${t} flex flex-col`,ref:xr,children:[Lt&&st("div",{className:"relative flex w-full justify-center flex-col gap-4",children:[D(Fe,{"data-bitsnap-checkout-slot":"skeleton",className:r("w-full h-32",P.className),style:P.style}),D(Fe,{"data-bitsnap-checkout-slot":"skeleton",className:r("w-full h-32",P.className),style:P.style})]}),ca&&st("div",{className:"flex flex-col items-start gap-3 p-4",children:[D("p",{role:"alert","data-bitsnap-checkout-slot":"error",className:r(c.className),style:c.style,children:f}),pt!=null&&pt.length>0&&D("p",{role:"alert","data-bitsnap-checkout-slot":"error",className:r("text-sm",c.className),style:c.style,children:pt}),D("button",{type:"button","data-bitsnap-checkout-slot":"checkoutButton",onClick:()=>{Je().then().catch()},className:r("px-3 py-2 rounded-md transition font-bold",m.className),style:m.style,children:v})]}),!Lt&&!ca&&(B==null||B.length==0)&&st("div",{className:"flex flex-col gap-4 p-4",children:[D("p",{"data-bitsnap-checkout-slot":"emptyState",className:r(l.className),style:l.style,children:y}),pt!=null&&pt.length>0&&D("p",{role:"alert","data-bitsnap-checkout-slot":"error",className:r("text-sm",c.className),style:c.style,children:pt})]}),D("div",{"data-bitsnap-checkout-slot":"productList",className:r("max-h-[70vh] overflow-clip overflow-y-scroll",s.className),style:s.style,children:B!=null&&B.length>0&&D("ul",{className:"mt-5",children:B.map(p=>D(K.Fragment,{children:p.details!=null&&st("li",{className:"mb-3",children:[D(Va,{isNotAvailable:W.includes(p.productID),quantity:p.quantity,details:p.details,url:p.url,shouldUpdate:j=>Nr(p.id,j)}),D("hr",{className:"h-1"})]})},p.id))})}),D("div",{className:"grow"}),Qt>0&&$t!=null&&st(Jo,{children:[st("div",{"data-bitsnap-checkout-slot":"summary",className:r("mx-3 flex flex-col",i.className),style:i.style,children:[st("div",{className:"flex flex-row justify-between text-lg",children:[D("p",{"data-bitsnap-checkout-slot":"totalLabel",className:r("text-xl",x.className),style:x.style,children:R}),st("div",{className:"flex flex-col items-end",children:[D("p",{"data-bitsnap-checkout-slot":"totalValue",className:r("font-medium",b.className),style:b.style,children:At(Qt,$t)}),Pr&&D("p",{"data-bitsnap-checkout-slot":"deliveryText",className:r("opacity-70 text-right text-base",u.className),style:u.style,children:I})]})]}),D("p",{"data-bitsnap-checkout-slot":"summaryNote",className:r("opacity-70 text-sm",k.className),style:k.style,children:E})]}),Pt&&Pt?.length>1&&st("div",{children:[D("h4",{"data-bitsnap-checkout-slot":"countryLabel",className:r("ml-3 text-sm",g.className),style:g.style,children:T}),D(Ga,{id:O,open:Ze,onToggle:()=>{fr(!Ze)},onChange:p=>{se(p).then(()=>{ta().then().catch()})},selectedValue:Ct??"",countries:Pt})]}),st("div",{className:"mb-3 flex flex-col",children:[yr&&B!=null&&B.length>0&&D("div",{"data-bitsnap-checkout-slot":"paymentButtons",className:r("w-full px-2",h.className),style:h.style,children:D(Be,{colorType:"white",style:{width:"100%"},items:B?.map(p=>({name:p.details?.name??"",id:p.productID,price:p.details?.pricing?.effectivePrice??p.details?.price??0,currency:p.details?.currency,quantity:p.quantity,isDeliverable:p.details?.isDeliverable??!1,metadata:p.metadata}))})}),B!=null&&B.length>0&&D("div",{"data-bitsnap-checkout-slot":"paymentButtons",className:r("w-full px-2",h.className),style:h.style,children:D(He,{buttonSizeMode:"fill",buttonColor:"white",style:{width:"100%"},items:B?.map(p=>({name:p.details?.name??"",id:p.productID,price:p.details?.pricing?.effectivePrice??p.details?.price??0,quantity:p.quantity,isDeliverable:p.details?.isDeliverable??!1,metadata:p.metadata}))})}),pe!=null&&D("div",{ref:sa,className:"contents",children:D(Qa,{choice:pe,selected:Ue(pe,oa),onChange:Cr,disabled:Ee})}),D("button",{"data-bitsnap-checkout-slot":"checkoutButton",onClick:Tr,disabled:Lt||Ee||na||Ct==null,"aria-describedby":la?d:void 0,className:r("px-3 py-2 my-2 mx-2 rounded-md disabled:opacity-40 disabled:cursor-not-allowed transition font-bold",m.className),style:m.style,children:Ee||na?D(X,{}):N}),la&&D("p",{id:d,className:"text-sm text-center opacity-70",children:A}),F.length>0&&D("p",{role:"alert","data-bitsnap-checkout-slot":"error",className:r("text-sm text-center",c.className),style:c.style,children:F})]})]})]})},$a=Yo;import{jsx as et,jsxs as xe}from"react/jsx-runtime";function nn({isVisible:t,shouldHide:e,panelId:a,locale:o}){let[n]=tn(),[s,i]=rn(null),x=en(y=>{n(y),i(y)},[n]),b=an(null),{boundaryClassName:u,boundaryStyle:k}=Yt(),g=z("root"),h=z("overlay"),m=z("panel"),l=z("header"),c=z("title"),P=z("closeButton"),C=L("cart"),S=L("close");return et("div",{ref:x,"data-bitsnap-checkout":"root","data-bitsnap-checkout-slot":"root",className:r("bitsnap-react",u,g.className),style:{zIndex:999999,...k,...g.style},children:s!=null&&et(ut.Root,{open:t,onOpenChange:y=>{y||e()},children:xe(ut.Portal,{container:s,children:[et(ut.Overlay,{"data-bitsnap-checkout-slot":"overlay","aria-hidden":"true",className:r("fixed top-0 right-0 left-0 bottom-0 cursor-pointer z-10",h.className),style:h.style,onClick:e}),xe(ut.Content,{id:a,"data-bitsnap-checkout-slot":"panel","aria-modal":"true","aria-describedby":void 0,onOpenAutoFocus:()=>{let y=document.activeElement;b.current=y instanceof HTMLElement?y:null},onCloseAutoFocus:y=>{y.preventDefault(),b.current?.focus(),b.current=null},className:r("fixed z-20 top-0 right-0 bottom-0 w-full md:w-[350px] xl:w-[420px] flex flex-col overflow-y-auto",m.className),style:m.style,onPointerDownOutside:y=>y.preventDefault(),children:[xe("div",{"data-bitsnap-checkout-slot":"header",className:r("mx-3 mt-7 flex justify-between items-center",l.className),style:l.style,children:[et(ut.Title,{asChild:!0,children:et("h1",{"data-bitsnap-checkout-slot":"title",className:r("text-2xl font-medium",c.className),style:c.style,children:C})}),et("button",{type:"button","data-bitsnap-checkout-slot":"closeButton",className:r("rounded-xl p-2 transition",P.className),style:P.style,"aria-label":S,onClick:e,children:xe("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"lucide lucide-x","aria-hidden":"true",focusable:"false",children:[et("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),et("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),et($a,{className:"grow",locale:o})]})]})})})}var sn=t=>typeof window>"u"?null:on(et(Da,{appearance:t.appearance,children:et(Sa,{texts:t.texts,locale:t.locale,children:et(Ht,{locale:t.locale,children:et(nn,{...t})})})}),document.body),Xa=sn;import{Fragment as Za,jsx as Dt,jsxs as ke}from"react/jsx-runtime";var pn=Z.object({id:Z.string(),isSubscription:Z.boolean().default(!1),quantity:Z.number(),metadata:Z.record(Z.string(),Z.string().optional()).optional(),url:Z.string().optional()}),dn={position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0};function un({projectID:t,locale:e,children:a,onVisibleChange:o,className:n,numberOfProductsInCartOptions:s,appearance:i,texts:x,analytics:b}){let u=St(t,b,"cart");ma(u);let{isCartVisible:k,showCart:g,hideCart:h,numberOfProductsInCart:m}=Rt(),l=`bitsnap-cart-${cn()}`,c=T=>xa(T,e??Zt(),x),P=ln(c);P.current=c;function C(T){Rt.getState().setNotice(P.current(T)),g()}function S(T){document.querySelectorAll("iframe").forEach(f=>{f.contentWindow?.postMessage(T,"*")})}ee(()=>{o?.(k),k&&ft({event:"viewCart"})},[k]),ee(()=>{Me(t)},[t]),ee(()=>{_e(e)},[e]),ee(()=>{if(!("cart"in window)){let T=ot();if(T==null){console.warn("There is no project ID configured.");return}window.cart={buyProduct:async N=>{try{let f=Z.object({productID:Z.string(),email:Z.string().optional(),name:Z.string().optional(),country:Z.string().optional(),marketingAgreement:Z.boolean().optional(),locale:Z.string().optional()}).parse(N),v=Oe(T);try{let E=await v.getProducts();H(E)==!1&&ft({event:"initiateCheckout",items:E.map(O=>({id:O.productID,name:O.details?.name??"",price:O.details?.price??0,quantity:O.quantity,currency:O.details?.currency??"PLN"}))})}catch{}let A=await v.justRedirectToPayment(f);H(A)==!1?window.location.href=A.url:C("redirectFailed")}catch(f){console.warn(f)}}}}},[]);async function y(T,N){let f=ot();if(f==null){console.warn("There is no project ID configured.");return}try{let v=pn.parse(N);if(v.isSubscription){await R(f,v);return}await Oe(f).addProduct({productID:v.id,quantity:v.quantity,metadata:v.metadata,url:v.url}),S({id:T,type:"ADD_TO_CART",success:!0}),g()}catch(v){console.warn("cannot add item to cart",v)}}async function R(T,N){console.warn("subscriptions cannot be added to the cart yet",T,N.id),C("subscriptionUnsupported")}function I(){"__cart_is_listening"in window||(window.__cart_is_listening=!0,window.addEventListener("message",T=>{if(typeof T.data.id<"u"&&typeof T.data.type<"u"){let{id:N,type:f}=T.data;switch(f){case"ADD_TO_CART".toString():y(N,T.data.payload).then().catch();break;default:break}}}))}return ee(()=>{if(I(),typeof window<"u")try{let T=new URLSearchParams(window.location.search),N=T.get("ref")??T.get("utm-source");typeof localStorage<"u"&&N&&N.length>0&&localStorage.setItem("bitsnap-ref",N)}catch{return}},[]),ke(Za,{children:[ke("button",{type:"button",onClick:()=>k?h():g(),"aria-label":a?void 0:m>0?`${c("openCart")}. ${c("cartItemsCount")}: ${m}`:c("openCart"),"aria-expanded":k,"aria-haspopup":"dialog","aria-controls":k?l:void 0,style:{position:"relative"},className:["bitsnap-react",n??"rounded-full hover:bg-neutral-300 transition p-1"].join(" "),children:[a?Dt(Za,{children:a}):ke("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"lucide lucide-shopping-cart","aria-hidden":"true",focusable:"false",children:[Dt("circle",{cx:"8",cy:"21",r:"1"}),Dt("circle",{cx:"19",cy:"21",r:"1"}),Dt("path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"})]}),m>0&&ke("span",{style:dn,children:[c("cartItemsCount"),": ",m]}),s?.isVisible!=!1&&m>0&&Dt("div",{"aria-hidden":"true",style:{position:"absolute",bottom:-5,right:-5,background:"black",color:"white",borderRadius:"50%",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"13px",fontWeight:600,boxShadow:"0 2px 8px rgba(0, 0, 0, 0.25)",...s?.style},children:m})]}),Dt(Ut,{value:u,children:Dt(Xa,{isVisible:k,locale:e,appearance:i,texts:x,panelId:l,shouldHide:()=>{h()}})})]})}var bn=un;import mn from"@google-pay/button-react";import{useQuery as gn,useMutation as hn}from"@tanstack/react-query";import{Fragment as yn,jsx as ae,jsxs as wn}from"react/jsx-runtime";function fn({items:t,style:e,buttonColor:a,buttonSizeMode:o,test:n}){let{getGooglePayConfiguration:s,completeGooglePayPayment:i,setCountry:x,setCouponCodeIfPossible:b,setDeliveryMethod:u,setEmail:k,setPostalCode:g,clearCart:h}=Ft(),m=Mt(),{data:l}=gn({queryKey:["get-google-pay-configuration",t.map(C=>C.id).join(",")],queryFn:()=>s({items:t.map(C=>({...C,id:void 0,productID:C.id}))})}),{mutateAsync:c,isPending:P}=hn({mutationFn:i});return l==null||l.isAvailable!=!0?(console.log("google pay configuration is not available",l),null):wn(yn,{children:[ae(mn,{buttonSizeMode:o,buttonColor:a,style:e,existingPaymentMethodRequired:!0,onClick:()=>m.track("payment_method_selected",{gateway:"google_pay",method:"google_pay"}),environment:n===!0?"TEST":"PRODUCTION",onPaymentDataChanged:async C=>{ft({event:"initiateCheckout",items:t.map(y=>({id:y.id,name:y.name,price:y.price,quantity:y.quantity,currency:"PLN"}))}),console.log("payment data changed",C),C.shippingAddress?.postalCode!=null&&await g(C.shippingAddress?.postalCode),C.shippingAddress?.countryCode!=null&&await x(C.shippingAddress?.countryCode),C.shippingOptionData?.id!=null&&await u(C.shippingOptionData.id);let S=await s({items:[]});return console.log("PAYMENT DATA CHANGED CONFIG",S),S.isAvailable?{error:void 0,newShippingOptionParameters:S.config.shippingOptionParameters,newTransactionInfo:S.config.transactionInfo}:{error:void 0}},paymentRequest:l.config,onLoadPaymentData:async C=>{m.track("payment_submitted",{gateway:"google_pay",method:"google_pay"});try{let S=await c({paymentData:C});if(H(S)){console.log("apple pay error",S);return}S.isSuccess&&h(),S.redirectURL&&open(S.redirectURL,"_self")}catch(S){console.warn("error completing google pay payment",S)}}}),P?ae(X,{}):null]})}function vn(t){let e=St(Wt(),t.analytics,"cart");return ae(Ut,{value:e,children:ae(Ht,{children:ae(fn,{...t})})})}var He=vn;import{useReducer as Qn,useRef as $n,useEffect as ie}from"react";import{useQuery as Xn}from"@tanstack/react-query";import{Settings as Zn}from"lucide-react";import{Fragment as xn,jsx as We,jsxs as kn}from"react/jsx-runtime";var _={title:null,description:null,managingDescription:"Zarz\u0105dzaj rodzajami powiadomie\u0144 i sposobem dostarczania.",formTitle:"Podaj Email aby zapisa\u0107 si\u0119\xA0do powiadomie\u0144",formEmailLabel:"Email",formPhoneLabel:"Numer telefonu",formPhoneOptional:"(opcjonalnie)",formEmailPlaceholder:"np. mail@gmail...",formPhonePlaceholder:"np. 663...",formSubmitButton:"Zapisz si\u0119",formSuccessMessage:"Zapisa\u0142e\u015B si\u0119 do powiadomie\u0144.",agreementText:kn(xn,{children:[We("span",{style:{color:"red"},children:"*"}),"Wyra\u017Cam zgod\u0119 na przetwarzanie moich danych w celach marketingowych zgodnie z"," ",We("a",{href:"/regulations/polityka-prywatnosci",target:"_blank",className:"cursor-alias font-bold hover:font-medium",children:"regulaminem"})," ",We("span",{className:"text-xs font-light",children:"(zgod\u0119 mo\u017Cna w ka\u017Cdej chwili wycofa\u0107)"})]}),qrCodeTitle:"lub zainstaluj aplikacj\u0119 mobiln\u0105",qrCodeSubtitle:"Aplikacja mobilna",qrCodeScanText:"zeskanuj kod QR",groupsNoSelectionWarning:"Je\u015Bli \u017Cadna z grup nie jest zaznaczona, nie otrzymasz \u017Cadnych powiadomie\u0144.",groupsSelectAllButton:"Zaznacz wszystkie",groupsUpdateButton:"Aktualizuj",groupsUpdateSuccess:"Zaktualizowano pomy\u015Blnie.",groupsTitle:"Zarz\u0105dzaj grupami z kt\xF3rych chcesz otrzymywa\u0107 powiadomienia",manageDataTitle:"Ustawienia powiadomie\u0144",manageDataDescription:"W jaki spos\xF3b chcesz otrzymywa\u0107 powiadomienia?",manageDataUnsubscribeButton:"Odsubskrybuj",manageDataUpdatedMessage:"Zaktualizowano",manageDataUnsubscribeDescription:"Wypisz mnie z wszystkich powiadomie\u0144 i grup.",loginEmailLabel:"Email",loginEmailPlaceholder:"Wprowad\u017A sw\xF3j email",loginSendCodeButton:"Wy\u015Blij kod weryfikacyjny",loginSendingButton:"Wysy\u0142anie...",loginCodeLabel:"Wprowad\u017A kod weryfikacyjny",loginCodeSentMessage:"Wys\u0142ali\u015Bmy kod weryfikacyjny na adres",loginChangeEmailButton:"Popraw email",loginResendCodeButton:"Wy\u015Blij kod ponownie",loginInvalidEmailError:"Wprowad\u017A prawid\u0142owy adres email",loginSlugRequiredError:"Wymagany jest identyfikator projektu",loginInvalidCodeError:"Nieprawid\u0142owy kod weryfikacyjny",loginVerificationFailedError:"Weryfikacja nie powiod\u0142a si\u0119. Sprawd\u017A sw\xF3j kod.",loginSendEmailError:"Nie uda\u0142o si\u0119 wys\u0142a\u0107 kodu weryfikacyjnego",loginVerifyCodeError:"Nie uda\u0142o si\u0119 zweryfikowa\u0107 kodu",loginResendEmailError:"Nie uda\u0142o si\u0119 ponownie wys\u0142a\u0107 kodu weryfikacyjnego",loginTitle:"Wpisz email aby zarz\u0105dza\u0107 powiadomieniami",loginDescription:"Dostaniesz kod weryfikacyjny na email.",loginIHaveCode:"Mam ju\u017C kod"};import{LogOutIcon as Cn}from"lucide-react";import{Fragment as Ya,jsx as _t,jsxs as Ce}from"react/jsx-runtime";function Ja({projectName:t,projectLogo:e,projectLogoDark:a,description:o,className:n,onLogout:s}){return Ce(Ya,{children:[e!=null||t!=null&&Ce("h2",{className:r("flex max-w-44 items-center gap-3 text-lg font-medium text-black sm:max-w-none md:text-xl lg:text-2xl xl:text-3xl dark:text-neutral-100",n?.headerTitle),children:[e!=null&&Ce(Ya,{children:[_t("img",{src:e,alt:"",className:r("h-12 w-auto dark:hidden",n?.headerLogo)}),_t("img",{src:a??e,alt:"",className:r("hidden h-12 w-auto dark:inline",n?.headerLogo)})]}),_t("span",{children:t})]}),Ce("div",{className:"flex items-center gap-2",children:[o&&_t("p",{className:r("mt-4 font-medium text-left",n?.headerDescription),children:o}),_t("div",{className:"grow"}),s&&_t(G,{variant:"ghost",size:"icon-sm",onClick:s,children:_t(Cn,{className:"h-5 w-5"})})]})]})}import{useAutoAnimate as or}from"@formkit/auto-animate/react";import{CheckCircleIcon as Sn,TriangleAlertIcon as Nn}from"lucide-react";import*as yt from"@radix-ui/react-popover";import{jsx as Pe}from"react/jsx-runtime";function tr({...t}){return Pe(yt.Root,{"data-slot":"popover",...t})}function er({...t}){return Pe(yt.Trigger,{"data-slot":"popover-trigger",...t})}function ar({className:t,align:e="center",sideOffset:a=4,...o}){return Pe(yt.Portal,{children:Pe(yt.Content,{"data-slot":"popover-content",align:e,sideOffset:a,className:r("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",t),...o})})}import{ClockIcon as Pn}from"lucide-react";import{jsx as wt,jsxs as Tt}from"react/jsx-runtime";function rr({regularity:t}){let e="";switch(t){case"rarely":e="rzadko";break;case"often":e="cz\u0119sto";break;case"very_often":e="codzienne";break}return Tt(tr,{children:[wt(er,{onClick:a=>{a.stopPropagation()},children:Tt("button",{type:"button",className:"flex w-[30%] cursor-help flex-col items-center justify-center text-xs md:w-[25%] xl:w-[20%]",children:[wt(Pn,{size:12}),wt("span",{children:e})]})}),wt(ar,{className:"w-80",children:Tt("div",{className:"grid gap-4",children:[Tt("div",{className:"space-y-2",children:[wt("h4",{className:"leading-none font-medium",children:"Co to oznacza?"}),Tt("ul",{className:"list-inside list-disc text-sm",children:[Tt("li",{children:[wt("span",{className:"font-semibold",children:"Rzadko"})," \u2013 powiadomienia b\u0119d\u0105 wysy\u0142ane maksymalnie kilka razy w miesi\u0105cu."]}),Tt("li",{children:[wt("span",{className:"font-semibold",children:"Cz\u0119sto"})," \u2013 powiadomienia mog\u0119 by\u0107 wysy\u0142ane kilka razy w tygodniu."]}),Tt("li",{children:[wt("span",{className:"font-semibold",children:"Codzienne"})," \u2013 powiadomienia b\u0119d\u0105 wysy\u0142ane nawet codziennie."]})]})]}),wt("div",{className:"grid gap-2"})]})})]})}import{Fragment as Tn,jsx as Y,jsxs as bt}from"react/jsx-runtime";function Se({groups:t=[],isManaging:e,onToggle:a,onCheckAll:o,onUpdate:n,isUpdating:s,wasChanged:i,isUserGroupsUpdated:x,className:b,texts:u}){let[k]=or(),[g]=or(),h=t.filter(c=>c.isOn===!1).length>0,m=t.filter(c=>c.isOn===!1).length>0;if(t.length<=1&&e!=!0)return null;let l=bt("div",{ref:k,className:r("my-5 flex flex-col gap-3",b?.groupsList),children:[t.map(c=>bt("div",{id:c.id,role:"button",className:r(c.isOn?"bg-neutral-50 hover:bg-transparent shadow-sm border-transparent dark:bg-neutral-800":"border-neutral-200 hover:bg-neutral-50 dark:hover:border-neutral-800 shadow-sm dark:border-neutral-800","active:bg-beige-300 flex w-full cursor-pointer items-center gap-3 rounded-xl border px-3 py-2 transition active:dark:bg-neutral-900",b?.groupItem),onClick:P=>{P.target instanceof HTMLButtonElement||a(c.id)},children:[Y(jt,{checked:c.isOn,className:"data-[state=checked]:bg-blue-500 dark:data-[state=unchecked]:bg-neutral-700",onCheckedChange:()=>{a(c.id)}}),bt("div",{className:"flex flex-col items-start justify-start",children:[Y("p",{className:"font-medium text-sm",children:c.name}),c.description&&Y("p",{className:"text-xs font-light",children:c.description})]}),Y("div",{className:"grow"}),c.howOften&&Y(rr,{regularity:c.howOften})]},c.id)),bt("div",{className:"flex gap-2",children:[e===!0&&bt(Tn,{children:[bt("div",{ref:g,className:"flex flex-col items-start justify-start",children:[i&&bt(G,{variant:"default",size:"sm",className:"relative",disabled:s,onClick:n,children:[u?.groupsUpdateButton??_.groupsUpdateButton,s&&Y("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:Y(X,{})})]}),x&&bt("p",{className:"mt-3 flex items-center gap-2 text-sm text-green-500",children:[Y(Sn,{color:"var(--color-green-500",size:16})," ",u?.groupsUpdateSuccess??_.groupsUpdateSuccess]})]}),Y("div",{className:"grow"})]}),m&&Y("div",{className:"flex justify-start",children:Y(G,{className:"cursor-pointer dark:bg-neutral-700",onClick:o,size:"sm",variant:"secondary",type:"button",children:u?.groupsSelectAllButton??_.groupsSelectAllButton})})]}),h&&bt("div",{className:"flex text-left gap-2 text-xs text-yellow-500",children:[Y(Nn,{color:"orange",size:16}),u?.groupsNoSelectionWarning??_.groupsNoSelectionWarning]})]});return e==!0?bt(Bt,{className:"mt-5 text-left",children:[Y(Gt,{children:Y(Nt,{children:u?.groupsTitle??_.groupsTitle})}),Y(qt,{children:l})]}):l}import{jsx as Et,jsxs as re}from"react/jsx-runtime";function nr({showQRCode:t=!0,isManaging:e,className:a,texts:o}){let n=typeof window<"u",s=n?!!window.matchMedia?.("(prefers-color-scheme: dark)").matches:!1;function i(x){return x?window.location.href:""}return t?re(Bt,{className:r("bg-beige-100 rounded-xl p-4 dark:bg-neutral-700",a?.qrCodeSection),children:[Et(Gt,{children:re(Nt,{className:r("mb-3 text-base font-medium lg:text-lg",a?.qrCodeTitle),children:[o?.qrCodeSubtitle??_.qrCodeSubtitle," "+(o?.qrCodeTitle??_.qrCodeTitle)]})}),re(qt,{className:"flex flex-col items-center gap-2",children:[re("div",{className:"mt-1.5 mb-3 flex items-center gap-x-2",children:[Et("a",{href:"https://apps.apple.com/us/app/bitsnap/id6741902807",target:"_blank",className:"max-w-28 flex-1 basis-1/2 lg:max-w-36",children:Et("img",{className:"h-auto w-full",src:Ot+"/app-store-logo.png",alt:"Download on App Store"})}),Et("a",{href:"https://play.google.com/store/apps/details?id=com.bitsnap.Bitsnap&pli=1",target:"_blank",className:"max-w-28 flex-1 basis-1/2 lg:max-w-36",children:Et("img",{className:"h-auto w-full",src:Ot+"/google-play-logo.png",alt:"Get in on Google Play"})})]}),n&&Et("div",{className:"flex items-center justify-center",children:re("div",{className:r("flex min-w-[40%] flex-col items-center gap-2 rounded-xl bg-white p-2 dark:bg-neutral-900",a?.qrCodeContainer),children:[Et("img",{className:"mt-3 w-[80%] p-1 pt-3",src:Ot+`/api/qr-gen?url=${i(n)}&bgColor=${s?"171717":"F6F4F0"}&textColor=${s?"ffffff":"000000"}&margin=0`}),Et("p",{className:"text-xs md:text-sm",children:o?.qrCodeScanText??_.qrCodeScanText})]})})]})]}):null}import{useState as oe}from"react";import{isValidPhoneNumber as Rn}from"react-phone-number-input";import{useAutoAnimate as En}from"@formkit/auto-animate/react";import{Label as ir}from"@radix-ui/react-label";import{CheckCircleIcon as In,CircleAlertIcon as zn,TriangleAlertIcon as An}from"lucide-react";import{useState as Ve}from"react";import{jsx as nt,jsxs as xt}from"react/jsx-runtime";function sr({submit:t,isLoading:e,errMsg:a,emailLack:o,warnMsg:n,isSubmited:s,agreementLack:i,showPhoneInput:x=!1,agreementText:b,className:u,texts:k}){let[g,h]=Ve(""),[m,l]=Ve(""),[c,P]=Ve(!1),[C]=En();function S(y){y.preventDefault(),t(g,m,c)}return xt("form",{ref:C,onSubmit:S,className:r("flex flex-col gap-3 text-left",u?.formContainer),children:[xt("div",{className:"flex flex-col gap-1 text-left",children:[nt(ir,{className:"text-sm",htmlFor:"bts-notifications-form-email",children:k?.formEmailLabel??_.formEmailLabel}),nt(Xt,{value:g,onChange:y=>{h(y.currentTarget.value)},id:"bts-notifications-form-email",className:r(o===!0?"border-red-400":""),type:"email",placeholder:k?.formEmailPlaceholder??_.formEmailPlaceholder})]}),x&&xt("div",{className:"flex flex-col gap-1 text-left",children:[xt(ir,{className:"text-sm",htmlFor:"bts-notifications-form-phone",children:[k?.formPhoneLabel??_.formPhoneLabel," ",nt("span",{className:"text-neutral-500 dark:text-neutral-500",children:k?.formPhoneOptional??_.formPhoneOptional})]}),nt(Xt,{value:m,onChange:y=>{l(y.currentTarget.value)},id:"bts-notifications-form-phone",className:"",type:"tel",autoComplete:"tel",autoCorrect:"off",placeholder:k?.formPhonePlaceholder??_.formPhonePlaceholder})]}),xt("div",{className:"flex items-start gap-x-1.5",children:[nt("input",{className:"cursor-pointer",id:"bts-notifications-form-marketing-consent",type:"checkbox",checked:c,onChange:()=>{P(!c)}}),nt("label",{htmlFor:"bts-notifications-form-marketing-consent",className:r("cursor-pointer text-xs leading-4 transition-colors md:text-sm md:leading-4",i===!0?"text-yellow-700":""),children:b})]}),a.length>0&&xt("p",{className:"mb-3 flex items-center gap-1 text-sm text-red-400",children:[nt(An,{color:"#ff6467",size:16})," ",a]}),n.length>0&&xt("p",{className:"mb-3 flex items-center gap-1 text-sm text-amber-400",children:[nt(zn,{color:"var(--color-amber-400)",size:16})," ",n]}),s==!1&&nt("div",{className:"flex justify-start",children:xt(G,{variant:"default",disabled:e,className:r(e?"cursor-not-allowed text-transparent":"","relative"),children:[k?.formSubmitButton??_.formSubmitButton,e&&nt("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:nt(X,{})})]})}),s&&xt("div",{className:"flex items-center gap-3 text-sm text-green-400",children:[nt(In,{size:16})," ",k?.formSuccessMessage??_.formSuccessMessage]})]})}import{jsx as Ke,jsxs as _n}from"react/jsx-runtime";var Dn=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;function cr({groups:t,onToggle:e,onCheckAll:a,slug:o,showPhoneInput:n=!1,agreementText:s,className:i,texts:x,isUpdating:b,wasChanged:u,onSuccess:k}){let[g,h]=oe(""),[m,l]=oe(""),[c,P]=oe(!1),[C,S]=oe(!1),[y,R]=oe(!1),{mutateAsync:I,isPending:T}=ht(it.notifications.createNotificationUser);function N(A){return A==null?!1:Rn(A,"PL")}async function f(A,E,O){if(h(""),l(""),R(!1),P(!1),S(!1),!O){S(!0),h("Zgoda w tym przypadku jest wymagana.");return}if(Dn.test(A)===!1){h("Email jest nieprawid\u0142owy."),R(!0);return}E.length>0&&N(E)===!1&&l("Numer telefonu mo\u017Ce by\u0107 nieprawid\u0142owy. Zapisali\u015Bmy go ale je\u015Bli jest nieprawid\u0142owy to wpisz jeszcze raz i kliknij przycisk.");try{let d=await I({slug:o,email:A,phone:E,groups:t.filter(w=>w.isOn==!0).map(w=>w.id),mobileNotificationEnabled:!0,emailNotificationEnabled:!0,smsNotificationEnabled:!0});if(d.result.case==="success"){P(!0),setTimeout(()=>{k?.(!1,d.userId,d.accessToken)},1e3);return}else{P(!0);let w=d.result.value;if(w!=null){if(w==32){k?.(!0,void 0,void 0);return}console.log(`Code error: ${Ae[w]}`),h("Wyst\u0105pi\u0142 b\u0142\u0105d: "+Ae[w]);return}return}}catch(d){h("Wyst\u0105pi\u0142 b\u0142\u0105d podczas zapisywania. Spr\xF3buj ponownie."),console.log(`Error: ${d}`)}}let v=x?.formTitle??_.formTitle;return _n("div",{className:r("bg-beige-100 rounded-xl p-4 dark:bg-neutral-700",i?.formSection),children:[v.length>0&&Ke("h3",{className:r("mb-3 text-base font-medium lg:text-lg",i?.formTitle),children:v}),Ke(Se,{groups:t,isManaging:!1,onToggle:e??(()=>{}),onCheckAll:a??(()=>{}),isUpdating:b??!1,wasChanged:u??!1,isUserGroupsUpdated:!1,className:i,texts:x}),Ke(sr,{errMsg:g,emailLack:y,warnMsg:m,submit:f,isLoading:T,isSubmited:c,agreementLack:C,showPhoneInput:n,agreementText:s??x?.agreementText??_.agreementText,className:i,texts:x})]})}import{useEffect as Bn,useState as ne}from"react";import{Label as Qe}from"@radix-ui/react-label";import{MessageCircleWarningIcon as Gn}from"lucide-react";import{useDebouncedCallback as qn}from"use-debounce";import{TriangleAlertIcon as Ln,XIcon as Un}from"lucide-react";import{createPortal as Mn}from"react-dom";import{useEffect as lr,useState as On}from"react";import{jsx as ct,jsxs as Vt}from"react/jsx-runtime";function pr({open:t,onOpenChange:e,onConfirm:a,isDeleting:o=!1}){let[n,s]=On(!1);if(lr(()=>(s(!0),()=>s(!1)),[]),lr(()=>(t?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[t]),!n||!t)return null;let i=b=>{b.target===b.currentTarget&&e(!1)},x=()=>{a()};return Mn(ct("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 p-4",onClick:i,children:Vt("div",{className:r("relative w-full max-w-md rounded-2xl bg-white p-6 shadow-lg","dark:bg-neutral-800","animate-in fade-in-0 zoom-in-95 duration-200"),onClick:b=>b.stopPropagation(),children:[Vt("button",{onClick:()=>e(!1),className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-white transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-neutral-950 focus:ring-offset-2 disabled:pointer-events-none dark:ring-offset-neutral-950 dark:focus:ring-neutral-300",disabled:o,children:[ct(Un,{className:"h-4 w-4"}),ct("span",{className:"sr-only",children:"Zamknij"})]}),Vt("div",{className:"flex flex-col gap-4",children:[Vt("div",{className:"flex items-start gap-3",children:[ct("div",{className:"flex-shrink-0",children:ct(Ln,{className:"h-6 w-6 text-amber-500","aria-hidden":"true"})}),ct("div",{className:"flex-1",children:ct("h2",{className:"text-lg font-semibold text-black dark:text-neutral-100",children:"Czy na pewno chcesz si\u0119 wypisa\u0107?"})})]}),ct("p",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:"Klikni\u0119cie tego przycisku spowoduje wypisanie z wszelkich powiadomie\u0144 i grup, kt\xF3re zapisa\u0142e\u015B."}),Vt("div",{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",children:[ct(G,{type:"button",variant:"ghost",onClick:()=>e(!1),disabled:o,className:"sm:min-w-[100px]",children:"Anuluj"}),Vt(G,{type:"button",variant:"destructive",onClick:x,disabled:o,className:r(o&&"cursor-not-allowed text-transparent","relative sm:min-w-[100px]"),children:["Usu\u0144",o&&ct("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:ct("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"})})]})]})]})]})}),document.body)}import{useAutoAnimate as dr}from"@formkit/auto-animate/react";import{Fragment as jn,jsx as q,jsxs as lt}from"react/jsx-runtime";function ur({accessToken:t,slug:e,userID:a,className:o,texts:n}){let[s]=dr(),[i]=dr(),{mutateAsync:x,isPending:b}=ht(it.notifications.deleteNotificationUser),{mutateAsync:u,isPending:k}=ht(it.notifications.updateNotificationUser),{data:g,isFetching:h}=ue(it.notifications.getNotificationUserSettings,{userId:a,slug:e,accessToken:t}),[m,l]=ne(!1),[c,P]=ne(!1),[C,S]=ne(!1),[y,R]=ne(!1),[I,T]=ne(!1),N=g?.result.case==="success"?g?.result?.value:void 0;function f(){T(!0)}async function v(){await x({accessToken:t,slug:e,userId:a}),T(!1)}async function A(){await u({accessToken:t,slug:e,notificationUserId:a,mobileNotificationEnabled:y,emailNotificationEnabled:m,smsNotificationEnabled:c}),S(!0),setTimeout(()=>{S(!1)},3e3)}let E=qn(d=>{A()},300);Bn(()=>{let d=g?.result.case==="success"?g?.result?.value:void 0;l(d?.emailNotificationEnabled??!1),P(d?.smsNotificationEnabled??!1),R(d?.mobileNotificationEnabled??!1)},[g]);function O(d,w){d==="email"&&l(w),d==="phone"&&P(w),d==="push"&&R(w),E(!0)}return lt("div",{className:r("bg-beige-100 rounded-xl p-4 dark:bg-neutral-700",o?.manageDataSection),children:[q("div",{className:"flex justify-start",children:q("h3",{className:r("mb-3 text-base font-medium lg:text-lg",o?.manageDataTitle),children:n?.manageDataTitle??_.manageDataTitle})}),h?q(va,{className:"h-64 w-full"}):lt(Bt,{ref:i,className:r(k&&"relative"),children:[q(Gt,{children:q(Nt,{children:q("p",{className:"text-sm text-left",children:n?.manageDataDescription??_.manageDataDescription})})}),lt(qt,{ref:s,children:[q("div",{className:r(k&&"opacity-50 pointer-events-none","flex flex-col gap-2"),children:lt("div",{className:"flex flex-col items-start gap-5 gap-x-2",children:[N?.emailNotificationAvailable&<("div",{className:"flex items-center gap-3",children:[q(jt,{id:"email-enabled",className:"data-[state=checked]:bg-blue-500 dark:data-[state=unchecked]:bg-neutral-600",checked:m,onCheckedChange:()=>{O("email",!m)}}),q(Qe,{htmlFor:"email-enabled",className:"text-sm",children:"Email"})]}),N?.smsNotificationAvailable&<("div",{className:"flex items-center gap-3",children:[q(jt,{id:"sms-enabled",className:"data-[state=checked]:bg-blue-500 dark:data-[state=unchecked]:bg-neutral-600",checked:c,onCheckedChange:()=>{O("phone",!c)}}),q(Qe,{htmlFor:"sms-enabled",className:"text-sm",children:"SMS"})]}),N?.mobileNotificationAvailable&<(jn,{children:[lt("div",{className:"flex items-center gap-3",children:[q(jt,{id:"push-enabled",className:"data-[state=checked]:bg-blue-500 dark:data-[state=unchecked]:bg-neutral-600",checked:y,onCheckedChange:()=>{O("push",!y)}}),q(Qe,{htmlFor:"push-enabled",className:"text-sm",children:"Powiadomienia na telefon"})]}),N?.hasUserInstalledApp===!1&<("div",{className:"flex items-center gap-3",children:[q(Gn,{color:"var(--color-amber-500)",size:26}),q("p",{className:"text-xs text-amber-500",children:"Wygl\u0105da na to, \u017Ce nie masz zainstalowanej aplikacji mobilnej. Zainstaluj i wyra\u017A zgod\u0119 na otrzymywanie powiadomie\u0144 na telefon."})]})]})]})}),lt("div",{className:"mt-5 flex flex-col gap-2 text-left",children:[q("hr",{}),C&&q("p",{className:"text-xs text-green-500",children:n?.manageDataUpdatedMessage??_.manageDataUpdatedMessage}),q("div",{className:"flex items-center gap-x-2",children:lt(G,{size:"sm",variant:"link",className:r("pl-0 ml-0",b&&"cursor-not-allowed"),onClick:f,children:[n?.manageDataUnsubscribeButton??_.manageDataUnsubscribeButton,b&&q("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:q(X,{})})]})})]})]}),k&&q("div",{className:"bg-black/30 absolute inset-0 rounded-xl",children:q("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:q(X,{})})})]}),q(pr,{open:I,onOpenChange:T,onConfirm:v,isDeleting:b})]})}import{useState as Ne}from"react";import{ArrowLeft as Vn}from"lucide-react";import{useAutoAnimate as gr}from"@formkit/auto-animate/react";import*as at from"@radix-ui/react-dialog";import{XIcon as Fn}from"lucide-react";import{jsx as Kt,jsxs as $e}from"react/jsx-runtime";function br({...t}){return Kt(at.Root,{"data-slot":"dialog",...t})}function Hn({...t}){return Kt(at.Portal,{"data-slot":"dialog-portal",...t})}function Wn({className:t,...e}){return Kt(at.Overlay,{"data-slot":"dialog-overlay",className:r("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...e})}function mr({className:t,children:e,showCloseButton:a=!0,...o}){return $e(Hn,{"data-slot":"dialog-portal",children:[Kt(Wn,{}),$e(at.Content,{"data-slot":"dialog-content",className:r("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...o,children:[e,a&&$e(at.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[Kt(Fn,{}),Kt("span",{className:"sr-only",children:"Close"})]})]})]})}import{Fragment as Kn,jsx as M,jsxs as mt}from"react/jsx-runtime";function hr({slug:t,onSuccess:e,onError:a,className:o,isOpen:n,onClose:s,texts:i}){let[x]=gr(),[b]=gr(),[u,k]=Ne(""),[g,h]=Ne(""),[m,l]=Ne(!1),[c,P]=Ne(null),{mutateAsync:C,isPending:S}=ht(it.notifications.verifyUserEmail),y=async N=>{if(N.preventDefault(),P(null),!u||!u.includes("@")){P(i.loginInvalidEmailError??"");return}try{await C({email:u,slug:t}),l(!0)}catch(f){let v=f instanceof Error?f:new Error(i.loginSendEmailError);P(v.message),a?.(v)}},R=async N=>{if(h(N),P(null),N.length===6)try{let f=await C({email:void 0,code:N,slug:t});f.ok&&f.accessToken?e?.(f.userId,f.accessToken):(P(i.loginVerificationFailedError??""),a?.(new Error(i.loginVerificationFailedError)))}catch(f){let v=f instanceof Error?f:new Error(i.loginVerifyCodeError);if(v.message.includes("Invalid code")){P(i.loginInvalidCodeError??v.message),h("");return}P(v.message),a?.(v),h("")}},I=async()=>{if(h(""),P(null),!u||!t){P(i.loginSlugRequiredError??"");return}try{await C({email:u,slug:t})}catch(N){let f=N instanceof Error?N:new Error(i.loginResendEmailError);P(f.message),a?.(f)}},T=()=>{l(!1),h(""),P(null)};return M(br,{open:n,onOpenChange:s,children:M(mr,{className:"sm:max-w-[425px] min-h-[250px]",children:mt("div",{className:"flex flex-col min-h-[250px] h-full",children:[mt("div",{ref:b,className:"flex items-start gap-2 mb-2",children:[m&&M(G,{variant:"ghost",size:"icon-sm",onClick:()=>{l(!1)},children:M(Vn,{className:"h-5 w-5"})}),M("div",{children:M(Nt,{children:m?i.loginCodeLabel??"":i.loginTitle??""})})]}),M(ga,{className:"mb-4",children:m?mt(Kn,{children:[i.loginCodeSentMessage??""," ",u]}):i.loginDescription??""}),M("div",{className:"flex-1 flex flex-col",children:m?mt("form",{onSubmit:N=>N.preventDefault(),className:"flex flex-col flex-1",children:[mt("div",{className:"space-y-2",children:[M(De,{children:i.loginCodeLabel??""}),M(ha,{maxLength:6,value:g,onChange:R,disabled:S,children:mt(fa,{children:[M(zt,{index:0}),M(zt,{index:1}),M(zt,{index:2}),M(zt,{index:3}),M(zt,{index:4}),M(zt,{index:5})]})}),S&&M(X,{})]}),c&&M("div",{className:"text-sm text-destructive mt-2 mb-1",role:"alert",children:c}),M("div",{className:"grow"}),mt("div",{className:"flex flex-col items-start gap-2 pt-2",children:[u.length>0&&M(G,{variant:"link",size:"sm",onClick:I,disabled:S,className:"flex-1 ml-0 pl-0",children:i.loginResendCodeButton??""}),M(G,{variant:"link",size:"sm",onClick:T,disabled:S,className:"flex-1 ml-0 pl-0",children:i.loginChangeEmailButton??""})]})]}):mt("form",{onSubmit:y,className:"flex flex-col flex-1",children:[mt("div",{className:"space-y-2",children:[M(De,{htmlFor:"email",children:i.loginEmailLabel??""}),M(Xt,{id:"email",type:"email",placeholder:i.loginEmailPlaceholder??"",value:u,onChange:N=>k(N.target.value),required:!0,disabled:S,"aria-invalid":c?"true":"false"})]}),c&&M("div",{className:"text-sm text-destructive mt-2 mb-1",role:"alert",children:c}),M("div",{className:"grow"}),mt("div",{className:"flex flex-col items-start gap-0 pt-2",children:[M(G,{type:"submit",size:"sm",disabled:S,children:S?i.loginSendingButton??"":i.loginSendCodeButton??""}),M(G,{type:"button",variant:"link",className:"ml-0 pl-0",size:"sm",onClick:()=>{l(!0)},children:i.loginIHaveCode??""})]})]})})]})})})}import{useAutoAnimate as Yn}from"@formkit/auto-animate/react";import{jsx as $,jsxs as Xe}from"react/jsx-runtime";function Jn(t,e){switch(e.type){case"SET_IS_LOGGED_IN":return{...t,isLoggedIn:e.value};case"SET_USER_ID":return{...t,userID:e.value};case"SET_LOADING":return{...t,isLoading:e.value};case"SET_PUBLIC_GROUPS":return{...t,groupsProvided:e.value,groups:e.value!=null&&e.value.length>0?t.groups.filter(a=>e.value?.find(o=>o.id===a.id)!=null):t.groups};case"SET_GROUPS":{let a=t.isLoggedIn==!1||t.groupsProvided!=null,o=e.value.map(n=>t.isLoggedIn==!0?n:{...n,isOn:t.groupsProvided?.find(s=>s.id===n.id)?.isOn??a});return{...t,groups:o}}case"TOGGLE_GROUP":{let a=t.groups.map(o=>o.id===e.groupID?{...o,isOn:!o.isOn}:o);return{...t,wasChanged:!0,groups:a}}case"CHECK_ALL_GROUPS":{let a=t.groups.map(o=>({...o,isOn:!0}));return{...t,groups:a,wasChanged:!0}}case"SET_WAS_CHANGED":return{...t,wasChanged:e.value};case"SET_IS_USER_GROUPS_UPDATED":return{...t,isUserGroupsUpdated:e.value};case"RESET_UPDATE_STATE":return{...t,wasChanged:!1,isUserGroupsUpdated:!0};case"SHOW_SETTINGS":return{...t,showSettings:!0};case"HIDE_SETTINGS":return{...t,showSettings:!1};default:return t}}function ti({slug:t,userID:e,productID:a,projectID:o,analytics:n,projectName:s,projectLogo:i,projectLogoDark:x,groups:b,isManaging:u=!1,texts:k,showQRCode:g=!1,showPhoneInput:h=!1,hiddenGroupIds:m=[],className:l}){let[c]=Yn(),P=St(o??Wt(),n),C=t??ot()??(typeof window<"u"?window.location.hostname:""),{mutateAsync:S,isPending:y}=ht(it.notifications.updateUserGroups),{data:R,refetch:I}=Xn({queryKey:["notifications_accessToken"],queryFn:()=>{if(typeof window<"u")return{accessToken:localStorage.getItem("notifications_accessToken")??void 0,userID:localStorage.getItem("notifications_userID")??void 0}}}),{data:T,isPending:N,refetch:f}=ue(it.notifications.getUserGroups,{slug:C,accessToken:R?.accessToken}),[v,A]=Qn(Jn,{isLoading:N,isUserGroupsUpdated:!1,wasChanged:!1,groupsProvided:b,groups:[],showSettings:R!=null&&u==!0,isLoggedIn:R!=null,userID:void 0});ie(()=>{A({type:"SET_LOADING",value:y||N})},[y,N]),ie(()=>{A({type:"SET_IS_LOGGED_IN",value:R?.accessToken!=null}),A({type:"SET_USER_ID",value:R?.userID}),R?.accessToken!=null&&u==!0&&A({type:"SHOW_SETTINGS"})},[R,u]),ie(()=>{if(T==null)return;let F=T.groups.map(W=>{let rt="rarely";switch(W.howOften){case 0:rt="rarely";break;case 1:rt="often";break;case 2:rt="veryOften";break}return{id:W.id,name:W.name,description:W.description,howOften:rt,isOn:W.isOn??void 0}});A({type:"SET_GROUPS",value:F})},[T,N,b]);let E=$n(null);ie(()=>{let F=b?.map(W=>(W.id.startsWith("group_")||(W.id=`group_${W.id}`),W));A({type:"SET_PUBLIC_GROUPS",value:F})},[b]);let O={..._,...k};async function d(){await S({accessToken:R?.accessToken,slug:C,userId:e,groupIds:v.groups.filter(F=>F.isOn===!0).map(F=>F.id)}),A({type:"RESET_UPDATE_STATE"}),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{A({type:"SET_IS_USER_GROUPS_UPDATED",value:!1})},2e3)}function w(F){A({type:"TOGGLE_GROUP",groupID:F})}function gt(){A({type:"CHECK_ALL_GROUPS"})}function se(){A({type:"SHOW_SETTINGS"})}function Te(){A({type:"HIDE_SETTINGS"})}function ce(){localStorage.removeItem("notifications_accessToken"),localStorage.removeItem("notifications_userID"),I(),A({type:"SET_USER_ID",value:void 0}),A({type:"SET_IS_LOGGED_IN",value:!1}),A({type:"HIDE_SETTINGS"})}async function kt(F,W){typeof window<"u"&&(localStorage.setItem("notifications_accessToken",W),F!=null&&localStorage.setItem("notifications_userID",F)),A({type:"SET_USER_ID",value:F});try{await I(),f().then().catch().finally(()=>{u==!0&&A({type:"SHOW_SETTINGS"})})}catch(rt){console.log(`Error: ${rt}`)}}ie(()=>()=>{E.current&&clearTimeout(E.current)},[]);let pt=u==!0&&v.userID!=null&&R?.accessToken!=null;return Xe("main",{className:r("bitsnap-react relative",l?.container),children:[O.title!=null&&$("h1",{className:"text-2xl font-semibold text-black md:text-3xl lg:text-4xl xl:text-5xl dark:text-neutral-100",children:O.title}),!v.showSettings&&u&&$(G,{onClick:se,variant:"outline",size:"icon",className:"absolute bottom-6 right-6 z-50 h-12 w-12 rounded-full shadow-lg hover:shadow-xl md:bottom-8 md:right-8","aria-label":"Settings",children:$(Zn,{className:"h-5 w-5"})}),$("div",{className:r("md:pt8 relative z-0 mt-6 overflow-hidden rounded-2xl bg-white px-3 pt-6 pb-3 md:px-5 md:pb-5 dark:bg-neutral-800",l?.header),children:v.showSettings?$("div",{className:"space-y-6",children:v.isLoggedIn&&Xe("div",{className:r("grid grid-cols-1 gap-3 lg:gap-6",pt?"md:grid-cols-2":""),children:[Xe("div",{className:l?.groupsContainer,children:[$(Ja,{projectName:s,projectLogo:i,projectLogoDark:x,description:O.managingDescription,className:l,onLogout:ce}),N&&$("div",{className:"flex justify-center items-center py-8",children:$(X,{})}),$(Se,{groups:v.groups,hiddenGroupIds:m,isManaging:u,onToggle:w,onCheckAll:gt,onUpdate:d,isUpdating:y,wasChanged:v.wasChanged,isUserGroupsUpdated:v.isUserGroupsUpdated,className:l,texts:O})]}),pt&&$(ur,{accessToken:R.accessToken??"",slug:C,userID:v.userID??"",className:l,texts:O}),g!=!1&&$(nr,{showQRCode:g,isManaging:!0,className:l,texts:O})]})}):$("div",{className:r("grid grid-cols-1 gap-3 lg:gap-6"),children:$(cr,{slug:C,onToggle:F=>{A({type:"TOGGLE_GROUP",groupID:F})},onCheckAll:()=>{A({type:"CHECK_ALL_GROUPS"})},onSuccess:(F,W,rt)=>{P.track("availability_signup",{},{product_id:a??null}),rt!=null&&kt(W,rt),F&&A({type:"SHOW_SETTINGS"})},groups:v.groups,showPhoneInput:h,agreementText:O.agreementText,className:l,texts:O,wasChanged:v.wasChanged,isUpdating:y})})}),$(hr,{isOpen:v.showSettings&&!v.isLoggedIn,slug:C,onSuccess:kt,texts:O,onClose:Te})]})}function ei({slug:t,userID:e,productID:a,projectID:o,analytics:n,projectName:s,projectLogo:i,projectLogoDark:x,groups:b,isManaging:u,texts:k,showQRCode:g,showPhoneInput:h,hiddenGroupIds:m,className:l}){return $(Re,{children:$(ti,{slug:t,userID:e,productID:a,projectID:o,analytics:n,projectName:s,projectLogo:i,projectLogoDark:x,groups:b,isManaging:u,texts:k,showQRCode:g,showPhoneInput:h,hiddenGroupIds:m,className:l})})}var ai=ei;export{Be as ApplePayButton,ri as Bitsnap,bn as BitsnapCheckout,fo as BitsnapReturns,Yr as BitsnapReturnsProvider,xo as CHECKOUT_SLOT_NAMES,zr as Environment,He as GooglePayButton,ho as ITEM_IDS_NOT_FOUND,ai as NotificationsComponent,li as PRODUCT_LIST_SLOT_NAMES,go as Panel,Wr as PanelLogin,Br as PanelProvider,ui as ProductList,mo as PublicOrderPage,Vr as RETURNS_SLOT_NAMES,Kr as ReturnsAppearanceProvider,io as ReturnsCodeStep,lo as ReturnsConfirmation,no as ReturnsEmailStep,bo as ReturnsMyReturnDetail,uo as ReturnsMyReturnsList,co as ReturnsOrderDetail,so as ReturnsOrderList,Zr as ReturnsProvider,po as ReturnsResult,Hr as buildAccessTokenRedirect,ii as createCheckout,ni as createPaymentURL,pi as formatProductPrice,Or as getAllowedReturnOrigins,Zt as getLocale,Rr as getPanelConfig,oi as getPaymentMethodChoice,si as getReferenceIfPossible,qr as getReturnURLFromSearch,ci as injectReferenceToRequestIfNeeded,jr as persistReturnURL,Fr as readPersistedReturnURL,Mr as setAllowedReturnOrigins,Ir as setCustomHost,Ur as setHost,_e as setLocale,Lr as setLoginURL,Ar as setPanelConfig,Dr as setPanelProjectID,Me as setProjectID,_r as setTheme,ao as useCreateReturn,oo as useMyReturn,ro as useMyReturns,Gr as usePanelConfig,di as useProducts,to as useReturnOrders,Jr as useReturnSession,eo as useReturnableOrder,Qr as useReturnsAppearance,$r as useReturnsSlot,Xr as useReturnsText};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|