bitsnap-react 1.7.1 → 1.9.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.
Files changed (112) hide show
  1. package/README.md +130 -0
  2. package/dist/CartProvider-XWTLBIZ5.js +2 -0
  3. package/dist/CartProvider-XWTLBIZ5.js.map +1 -0
  4. package/dist/CartProvider-ZURLJNBW.mjs +2 -0
  5. package/dist/analytics.d.mts +28 -0
  6. package/dist/analytics.d.ts +28 -0
  7. package/dist/analytics.js +2 -0
  8. package/dist/analytics.js.map +1 -0
  9. package/dist/analytics.mjs +2 -0
  10. package/dist/catalog.d.mts +14 -1
  11. package/dist/catalog.d.ts +14 -1
  12. package/dist/catalog.js +1 -1
  13. package/dist/catalog.js.map +1 -1
  14. package/dist/catalog.mjs +1 -1
  15. package/dist/chunk-3IMJALBX.js +2 -0
  16. package/dist/chunk-3IMJALBX.js.map +1 -0
  17. package/dist/chunk-3UHPJ6NK.js +2 -0
  18. package/dist/chunk-3UHPJ6NK.js.map +1 -0
  19. package/dist/chunk-CO2P4FR5.js +2 -0
  20. package/dist/chunk-CO2P4FR5.js.map +1 -0
  21. package/dist/chunk-E6QVQEGZ.mjs +2 -0
  22. package/dist/chunk-E6QVQEGZ.mjs.map +1 -0
  23. package/dist/chunk-FHDFLSPW.js +2 -0
  24. package/dist/chunk-FHDFLSPW.js.map +1 -0
  25. package/dist/{chunk-6KQBDN7M.mjs → chunk-GN63ITLA.mjs} +2 -2
  26. package/dist/chunk-HKVMSMDF.mjs +2 -0
  27. package/dist/chunk-HKVMSMDF.mjs.map +1 -0
  28. package/dist/chunk-JSDGZ4NY.js +2 -0
  29. package/dist/chunk-JSDGZ4NY.js.map +1 -0
  30. package/dist/chunk-KG6RU37U.js +4 -0
  31. package/dist/chunk-KG6RU37U.js.map +1 -0
  32. package/dist/chunk-KOVKUJAW.mjs +2 -0
  33. package/dist/chunk-KOVKUJAW.mjs.map +1 -0
  34. package/dist/chunk-KOYBZORL.js +2 -0
  35. package/dist/chunk-KOYBZORL.js.map +1 -0
  36. package/dist/chunk-LJWS6ZRJ.mjs +2 -0
  37. package/dist/chunk-LJWS6ZRJ.mjs.map +1 -0
  38. package/dist/chunk-LZE2E4TE.mjs +4 -0
  39. package/dist/chunk-LZE2E4TE.mjs.map +1 -0
  40. package/dist/chunk-QZJGNLCZ.js +2 -0
  41. package/dist/chunk-QZJGNLCZ.js.map +1 -0
  42. package/dist/chunk-RA452LXZ.mjs +2 -0
  43. package/dist/chunk-RA452LXZ.mjs.map +1 -0
  44. package/dist/chunk-SLLBTQTW.mjs +2 -0
  45. package/dist/chunk-SLLBTQTW.mjs.map +1 -0
  46. package/dist/chunk-SZ256RCC.mjs +2 -0
  47. package/dist/chunk-SZ256RCC.mjs.map +1 -0
  48. package/dist/chunk-V4U2PTKN.js +2 -0
  49. package/dist/chunk-V4U2PTKN.js.map +1 -0
  50. package/dist/chunk-VM6JEJFZ.js +2 -0
  51. package/dist/chunk-VM6JEJFZ.js.map +1 -0
  52. package/dist/chunk-VXB7LA4E.js +2 -0
  53. package/dist/chunk-VXB7LA4E.js.map +1 -0
  54. package/dist/chunk-XVQKEGPO.mjs +2 -0
  55. package/dist/chunk-XVQKEGPO.mjs.map +1 -0
  56. package/dist/consent.d.mts +158 -0
  57. package/dist/consent.d.ts +158 -0
  58. package/dist/consent.js +75 -0
  59. package/dist/consent.js.map +1 -0
  60. package/dist/consent.mjs +75 -0
  61. package/dist/consent.mjs.map +1 -0
  62. package/dist/course.d.mts +1882 -0
  63. package/dist/course.d.ts +1882 -0
  64. package/dist/course.js +2 -0
  65. package/dist/course.js.map +1 -0
  66. package/dist/course.mjs +2 -0
  67. package/dist/course.mjs.map +1 -0
  68. package/dist/embed/analytics.js +1 -0
  69. package/dist/embed/consent.js +74 -0
  70. package/dist/errors.js +1 -1
  71. package/dist/errors.js.map +1 -1
  72. package/dist/index.css +1 -1
  73. package/dist/index.css.map +1 -1
  74. package/dist/index.d.mts +56 -40
  75. package/dist/index.d.ts +56 -40
  76. package/dist/index.js +1 -3
  77. package/dist/index.js.map +1 -1
  78. package/dist/index.mjs +1 -1
  79. package/dist/index.mjs.map +1 -1
  80. package/dist/instrument-C_abZLHk.d.mts +912 -0
  81. package/dist/instrument-C_abZLHk.d.ts +912 -0
  82. package/dist/internal.js +1 -1
  83. package/dist/internal.js.map +1 -1
  84. package/dist/methods-CYARZTYL.mjs +2 -0
  85. package/dist/methods-CYARZTYL.mjs.map +1 -0
  86. package/dist/methods-DAPEWVI6.js +2 -0
  87. package/dist/methods-DAPEWVI6.js.map +1 -0
  88. package/dist/models.js +1 -1
  89. package/dist/models.js.map +1 -1
  90. package/dist/returns.d.mts +14 -196
  91. package/dist/returns.d.ts +14 -196
  92. package/dist/returns.js +1 -1
  93. package/dist/returns.js.map +1 -1
  94. package/dist/returns.mjs +1 -1
  95. package/dist/texts-CIEFbJTN.d.ts +196 -0
  96. package/dist/texts-tQtAGJCT.d.mts +196 -0
  97. package/dist/types-BaqLJYuq.d.ts +53 -0
  98. package/dist/types-D_WnqwR_.d.mts +53 -0
  99. package/package.json +41 -5
  100. package/dist/CartProvider-F2VH7WFO.mjs +0 -2
  101. package/dist/chunk-3TENJTY4.mjs +0 -2
  102. package/dist/chunk-3TENJTY4.mjs.map +0 -1
  103. package/dist/chunk-4HOZFM6V.mjs +0 -2
  104. package/dist/chunk-4HOZFM6V.mjs.map +0 -1
  105. package/dist/chunk-FTYJTO6O.mjs +0 -2
  106. package/dist/chunk-FTYJTO6O.mjs.map +0 -1
  107. package/dist/chunk-RATFYRKZ.mjs +0 -4
  108. package/dist/chunk-RATFYRKZ.mjs.map +0 -1
  109. package/dist/methods-PFZSMZFU.mjs +0 -2
  110. /package/dist/{CartProvider-F2VH7WFO.mjs.map → CartProvider-ZURLJNBW.mjs.map} +0 -0
  111. /package/dist/{methods-PFZSMZFU.mjs.map → analytics.mjs.map} +0 -0
  112. /package/dist/{chunk-6KQBDN7M.mjs.map → chunk-GN63ITLA.mjs.map} +0 -0
@@ -1,2 +0,0 @@
1
- import{a as E,b as $,c as N,d as K,e as V,f as G,h as q,j as k}from"./chunk-3TENJTY4.mjs";var dt=["root","grid","card","cardLink","image","imagePlaceholder","body","name","description","price","comparePrice","badge","actions","addToCartButton","selectButton","message","pagination","paginationButton","pageIndicator","emptyState","error","retryButton","skeleton"],ut={fontFamily:"--bitsnap-products-font-family",fontSize:"--bitsnap-products-font-size",background:"--bitsnap-products-background",surface:"--bitsnap-products-surface",foreground:"--bitsnap-products-foreground",mutedForeground:"--bitsnap-products-muted-foreground",border:"--bitsnap-products-border",buttonBackground:"--bitsnap-products-button-background",buttonForeground:"--bitsnap-products-button-foreground",buttonHoverBackground:"--bitsnap-products-button-hover-background",hoverSurface:"--bitsnap-products-hover-surface",focusRing:"--bitsnap-products-focus-ring",error:"--bitsnap-products-error",badgeBackground:"--bitsnap-products-badge-background",badgeForeground:"--bitsnap-products-badge-foreground",radius:"--bitsnap-products-radius"},lt={light:{background:"#ffffff",surface:"#f9fafb",foreground:"#18181b",mutedForeground:"#71717a",border:"#e4e4e7",buttonBackground:"#18181b",buttonForeground:"#fafafa",buttonHoverBackground:"#000000",hoverSurface:"#f4f4f5",focusRing:"#71717a",error:"#dc2626",badgeBackground:"#f4f4f5",badgeForeground:"#3f3f46",radius:"8px"},dark:{background:"#18181b",surface:"#27272a",foreground:"#fafafa",mutedForeground:"#a1a1aa",border:"#3f3f46",buttonBackground:"#fafafa",buttonForeground:"#18181b",buttonHoverBackground:"#e4e4e7",hoverSurface:"#3f3f46",focusRing:"#a1a1aa",error:"#f87171",badgeBackground:"#3f3f46",badgeForeground:"#e4e4e7",radius:"8px"}},pt=[];function Z(t){let e=V(t,{defaultTheme:"light",presets:lt,variables:ut,shadcnVariables:pt});return{theme:e.theme,tokens:e.tokens,elements:e.elements,boundaryClassName:e.theme,boundaryStyle:e.boundaryStyle}}function j(t,e){return G(t.elements,e)}function Q(t,e){try{return new Intl.NumberFormat(t,{style:"currency",currency:e,currencyDisplay:"symbol"})}catch{return}}function _(t,e,r=k){let o=t/100,n=Q(r,e)??Q(k,e);return n!=null?n.format(o):`${o.toFixed(2)} ${e}`}import{useCallback as W,useEffect as ft,useMemo as Pt,useState as B}from"react";var O=class extends Error{status;constructor(e,r){super(e),this.name="ProductListError",this.status=r}};function R(t){return t==null||!Number.isFinite(t)?24:Math.min(48,Math.max(1,Math.floor(t)))}function X(t,e){return Math.max(1,Math.ceil(t/e))}function I(t){return t.replace(/\/+$/,"")}function gt(t){let e=new URLSearchParams;e.set("limit",String(t.limit)),e.set("offset",String(t.offset)),t.locale&&e.set("locale",t.locale);let r=t.search?.trim();return r&&e.set("search",r),`${I(t.host)}/api/integrations/${encodeURIComponent(t.projectID)}/public-commerce/product-list?${e.toString()}`}function mt(t){return typeof t=="object"&&t!=null&&Array.isArray(t.items)&&typeof t.totalCount=="number"}async function J(t,e){let r=await fetch(gt(t),{method:"GET",credentials:"omit",headers:{Accept:"application/json"},signal:e});if(!r.ok)throw new O(`Could not load products (${r.status})`,r.status);let o=await r.json();if(!mt(o))throw new O("Unexpected product list response");return o}function F(t){let{projectID:e,locale:r,search:o,initialData:n}=t,[s]=B(()=>N),l=t.host??s,p=R(t.pageSize),c=JSON.stringify([e,l,r??null,o?.trim()??null,p]),[d,g]=B({queryKey:c,page:1});d.queryKey!==c&&g({queryKey:c,page:1});let[T,C]=B(0),[f,S]=B(()=>({requestKey:n!=null?`${c}|1|0`:"",data:n,error:void 0})),b=f.data?.totalCount??0,L=X(b,p),A=d.queryKey===c?d.page:1,y=b>0?Math.min(A,L):A,x=`${c}|${y}|${T}`,P=f.requestKey===x;ft(()=>{if(P)return;let m=new AbortController;return J({projectID:e,host:l,locale:r,search:o,limit:p,offset:(y-1)*p},m.signal).then(u=>{m.signal.aborted||S({requestKey:x,data:u,error:void 0})},u=>{m.signal.aborted||S(ct=>({requestKey:x,data:ct.data,error:u instanceof Error?u:new Error(String(u))}))}),()=>m.abort()},[x,P]);let v=W(m=>{let u=Math.max(1,Math.floor(m));g({queryKey:c,page:b>0?Math.min(u,L):u})},[c,b,L]),D=W(()=>C(m=>m+1),[]);return Pt(()=>({products:f.data?.items??[],totalCount:b,page:y,pageCount:L,setPage:v,isLoading:!P,error:P?f.error:void 0,refetch:D}),[f,b,y,L,v,P,D])}import{createContext as yt,useCallback as M,useContext as xt,useEffect as ot,useMemo as H,useRef as rt,useState as ht}from"react";function Y(t,e){if(t.projectID!=null&&t.projectID!==e.projectID)return{ok:!1,reason:`the page cart already belongs to project "${t.projectID}"`};let r=null,o=e.host?I(e.host):"",n=I(t.host);if(o&&o!==n){if(n!==I(t.defaultHost))return{ok:!1,reason:`the page cart already uses the host "${t.host}"`};r=o}return{ok:!0,setProjectID:t.projectID==null?e.projectID:null,setHost:r}}async function tt(t,e){let[{Bitsnap:r},{getProjectID:o,setProjectID:n}]=await Promise.all([import("./methods-PFZSMZFU.mjs"),import("./CartProvider-F2VH7WFO.mjs")]),s=Y({projectID:o(),host:N,defaultHost:$},e);if(!s.ok)return bt(s.reason);if(s.setProjectID!=null&&n(s.setProjectID),s.setHost!=null&&K(s.setHost),await r.addProductToCart(t.cartItemId??t.id,1,void 0,{name:t.name,price:t.price,currency:t.currency})!=null)throw new Error("Could not add the product to the cart");e.showCart&&r.showCart()}function bt(t){throw console.warn(`bitsnap-react: ProductList did not add to the cart because ${t}. Pass onAddToCart to use another cart.`),new Error("The page cart belongs to another project or host")}var Lt={en:{addToCart:"Add to cart",addingToCart:"Adding\u2026",addedToCart:"Added to cart",addToCartError:"Could not add to the cart. Try again.",chooseOptions:"Choose",viewProduct:"View",unavailable:"Unavailable",subscription:"Subscription",priceFrom:"from {price}",originalPrice:"Original price",loading:"Loading products",empty:"There are no products to show.",error:"Could not load the products.",retry:"Try again",pagination:"Pagination",previousPage:"Previous",nextPage:"Next",pageOf:"Page {page} of {pageCount}"},pl:{addToCart:"Dodaj do koszyka",addingToCart:"Dodawanie\u2026",addedToCart:"Dodano do koszyka",addToCartError:"Nie uda\u0142o si\u0119 doda\u0107 do koszyka. Spr\xF3buj ponownie.",chooseOptions:"Wybierz",viewProduct:"Zobacz",unavailable:"Niedost\u0119pny",subscription:"Subskrypcja",priceFrom:"od {price}",originalPrice:"Cena przed obni\u017Ck\u0105",loading:"\u0141adowanie produkt\xF3w",empty:"Brak produkt\xF3w do wy\u015Bwietlenia.",error:"Nie uda\u0142o si\u0119 za\u0142adowa\u0107 produkt\xF3w.",retry:"Spr\xF3buj ponownie",pagination:"Paginacja",previousPage:"Poprzednia",nextPage:"Nast\u0119pna",pageOf:"Strona {page} z {pageCount}"}};function et(t,e){return q(Lt,t,e)}function U(t,e){return t.replace(/\{(\w+)\}/g,(r,o)=>o in e?String(e[o]):r)}import{Fragment as it,jsx as a,jsxs as h}from"react/jsx-runtime";var nt=yt(void 0);function w(){let t=xt(nt);if(t==null)throw new Error("ProductList parts must be rendered inside ProductList");return t}function i(t,e){let{appearance:r}=w(),o=j(r,t);return{"data-bitsnap-products-slot":t,className:E(e,o?.className),style:o?.style}}var z="inline-flex cursor-pointer items-center justify-center px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:cursor-not-allowed aria-disabled:opacity-50",at=`${z} w-full`,Tt=`${at} no-underline`;function Ct({product:t,onAdd:e}){let{texts:r}=w(),[o,n]=ht("idle"),s=i("addToCartButton",at),l=i("message","mt-2 text-xs");ot(()=>{if(o!=="added")return;let d=setTimeout(()=>n("idle"),2e3);return()=>clearTimeout(d)},[o]);let p=M(async()=>{n("adding");try{await e(),n("added")}catch(d){console.error("bitsnap-react: could not add to the cart",d),n("error")}},[e]),c=o==="adding"?r.addingToCart:o==="added"?r.addedToCart:r.addToCart;return h(it,{children:[a("button",{type:"button",...s,disabled:o==="adding","aria-label":`${c}: ${t.name}`,onClick:p,children:c}),o==="error"?a("p",{...l,role:"alert",children:r.addToCartError}):null]})}function St({product:t,href:e,onAdd:r,renderItem:o}){let{texts:n,locale:s}=w(),l=i("card","relative flex flex-col overflow-hidden border transition-colors"),p=i("cardLink","flex flex-1 flex-col no-underline"),c=i("image","aspect-square w-full overflow-hidden"),d=i("imagePlaceholder","aspect-square w-full"),g=i("body","flex flex-1 flex-col gap-1 p-4"),T=i("name","text-base font-medium leading-snug"),C=i("description","line-clamp-2 text-sm"),f=i("price","mt-auto pt-2 text-base font-semibold"),S=i("comparePrice","ml-2 text-sm font-normal"),b=i("badge","absolute left-3 top-3 px-2 py-0.5 text-xs font-medium"),L=i("actions","p-4 pt-0"),A=i("selectButton",Tt),y=_(t.price,t.currency,s),x=t.compareAtPrice!=null&&t.compareAtPrice>t.price?_(t.compareAtPrice,t.currency,s):null;if(o!=null)return a("li",{...l,"data-unavailable":t.available?void 0:"",children:o(t,{href:e,price:y,compareAtPrice:x,texts:n,locale:s,addToCart:r})});let P=t.image?.thumbnailUrl??t.image?.url,v=t.available?t.isRecurring?n.subscription:null:n.unavailable;return h("li",{...l,"data-unavailable":t.available?void 0:"",children:[h("a",{...p,href:e,children:[P!=null?a("div",{...c,children:a("img",{src:P,alt:"",loading:"lazy",decoding:"async",className:"h-full w-full object-cover"})}):a("div",{...d,"aria-hidden":"true"}),h("div",{...g,children:[a("h3",{...T,children:t.name}),t.shortDescription?a("p",{...C,children:t.shortDescription}):null,h("p",{...f,children:[t.priceFrom?U(n.priceFrom,{price:y}):y,x!=null?h(it,{children:[h("span",{className:"sr-only",children:[n.originalPrice,": "]}),a("del",{...S,children:x})]}):null]})]})]}),v!=null?a("span",{...b,"data-kind":t.available?"subscription":"unavailable",children:v}):null,a("div",{...L,children:t.available?t.addToCart?a(Ct,{product:t,onAdd:r}):a("a",{...A,href:e,children:t.variantCount>1?n.chooseOptions:n.viewProduct}):a("button",{type:"button",...A,disabled:!0,children:n.unavailable})})]})}var st="m-0 grid list-none grid-cols-[repeat(auto-fill,minmax(min(100%,15rem),1fr))] gap-5 p-0";function vt({count:t,label:e}){let r=i("grid",st),o=i("skeleton","aspect-[3/4] animate-pulse");return a("div",{...r,role:"status","aria-busy":"true","aria-label":e,children:Array.from({length:t},(n,s)=>a("div",{...o,"aria-hidden":"true"},s))})}function At({page:t,pageCount:e,isLoading:r,onPage:o}){let{texts:n}=w(),s=i("pagination","mt-8 flex items-center justify-center gap-4"),l=i("paginationButton",z),p=i("pageIndicator","text-sm");return h("nav",{...s,"aria-label":n.pagination,children:[a("button",{type:"button",...l,"aria-disabled":r||t<=1,onClick:()=>{!r&&t>1&&o(t-1)},children:n.previousPage}),a("span",{...p,"aria-live":"polite",children:U(n.pageOf,{page:t,pageCount:e})}),a("button",{type:"button",...l,"aria-disabled":r||t>=e,onClick:()=>{!r&&t<e&&o(t+1)},children:n.nextPage})]})}function kt({options:t,productHref:e,renderItem:r,onAddToCart:o,showCartOnAdd:n}){let{texts:s}=w(),{products:l,page:p,pageCount:c,setPage:d,isLoading:g,error:T,refetch:C}=F(t),f=rt(null),S=rt(!1),b=M(u=>{S.current=!0,d(u)},[d]);ot(()=>{g||!S.current||(S.current=!1,f.current?.focus({preventScroll:!0}),f.current?.scrollIntoView({block:"start"}))},[g]);let L=i("grid",st),A=i("emptyState","py-12 text-center text-sm"),y=i("error","flex flex-col items-center gap-3 py-12 text-center text-sm"),x=i("retryButton",z),{projectID:P,host:v}=t,D=M(u=>()=>o!=null?Promise.resolve(o(u)):tt(u,{projectID:P,host:v,showCart:n}),[o,P,v,n]),m;return g&&l.length===0?m=a(vt,{count:Math.min(R(t.pageSize),8),label:s.loading}):T!=null?m=h("div",{...y,role:"alert",children:[a("p",{children:s.error}),a("button",{type:"button",...x,onClick:C,children:s.retry})]}):l.length===0?m=a("p",{...A,children:s.empty}):m=a("ul",{...L,"aria-busy":g||void 0,className:E(L.className,g&&"opacity-60"),children:l.map(u=>a(St,{product:u,href:e(u),onAdd:D(u),renderItem:r},u.id))}),h("div",{ref:f,tabIndex:-1,className:"p-1 outline-none scroll-mt-4",children:[m,c>1&&T==null?a(At,{page:p,pageCount:c,isLoading:g,onPage:b}):null]})}var It=t=>`/p/${encodeURIComponent(t.uniqueSlug)}`;function wt({productHref:t=It,appearance:e,texts:r,renderItem:o,onAddToCart:n,showCartOnAdd:s=!0,className:l,...p}){let c=p.locale??k,d=H(()=>Z(e),[e]),g=H(()=>et(c,r),[c,r]),T=H(()=>({appearance:d,texts:g,locale:c}),[d,g,c]),C=j(d,"root");return a(nt.Provider,{value:T,children:a("div",{"data-bitsnap-products":"root","data-bitsnap-products-slot":"root",className:E("bitsnap-react",d.boundaryClassName,l,C?.className),style:{...d.boundaryStyle,...C?.style},children:a(kt,{options:p,productHref:t,renderItem:o,onAddToCart:n,showCartOnAdd:s})})})}export{dt as a,_ as b,F as c,wt as d};
2
- //# sourceMappingURL=chunk-FTYJTO6O.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/products/appearance.ts","../src/components/products/format.ts","../src/components/products/useProducts.ts","../src/components/products/fetch.ts","../src/components/products/ProductList.tsx","../src/components/products/cart-target.ts","../src/components/products/add-to-cart.ts","../src/components/products/texts.ts"],"sourcesContent":["import type { CSSProperties } from \"react\";\nimport {\n getSlotAppearance,\n resolveAppearanceCore,\n type AppearanceElements,\n type ShadcnVariableMapping,\n type SlotAppearance,\n} from \"@/src/lib/appearance-core\";\n\n/**\n * Product list appearance API.\n *\n * It mirrors `CheckoutAppearance` and `ReturnsAppearance` (theme, tokens,\n * elements) so a shop can reuse one brand object for all of them. The resolver\n * is pure: it turns the caller input into a theme name, the tokens in effect,\n * the slot overrides and the inline style for the theme boundary.\n */\n\nexport type ProductListTheme = \"light\" | \"dark\";\n\nexport type ProductListAppearanceTokens = {\n /** Font family of the list. The library never loads fonts. */\n fontFamily?: string;\n /** Base font size. */\n fontSize?: string;\n /** List background. */\n background?: string;\n /** Raised surfaces: cards, image placeholders, skeletons. */\n surface?: string;\n /** Main text color. */\n foreground?: string;\n /** Secondary text: descriptions, the struck-through price. */\n mutedForeground?: string;\n /** Borders of cards and buttons. */\n border?: string;\n /** \"Add to cart\" button background. */\n buttonBackground?: string;\n /** \"Add to cart\" button text. */\n buttonForeground?: string;\n /** \"Add to cart\" button background on hover. */\n buttonHoverBackground?: string;\n /** Hover surface of cards and secondary buttons. */\n hoverSurface?: string;\n /** Focus ring color. */\n focusRing?: string;\n /** Error and unavailable state color. */\n error?: string;\n /** Badge background (subscription, unavailable). */\n badgeBackground?: string;\n /** Badge text. */\n badgeForeground?: string;\n /** Corner radius of cards, images and buttons. */\n radius?: string;\n};\n\n/**\n * Stable slot names. They are exposed as `data-bitsnap-products-slot`\n * attributes so they can also be targeted from plain CSS.\n */\nexport const PRODUCT_LIST_SLOT_NAMES = [\n \"root\",\n \"grid\",\n \"card\",\n \"cardLink\",\n \"image\",\n \"imagePlaceholder\",\n \"body\",\n \"name\",\n \"description\",\n \"price\",\n \"comparePrice\",\n \"badge\",\n \"actions\",\n \"addToCartButton\",\n \"selectButton\",\n \"message\",\n \"pagination\",\n \"paginationButton\",\n \"pageIndicator\",\n \"emptyState\",\n \"error\",\n \"retryButton\",\n \"skeleton\",\n] as const;\n\nexport type ProductListSlotName = (typeof PRODUCT_LIST_SLOT_NAMES)[number];\n\nexport type ProductListSlotAppearance = SlotAppearance;\n\nexport type ProductListAppearanceElements =\n AppearanceElements<ProductListSlotName>;\n\nexport type ProductListAppearance = {\n /** `\"light\"` or `\"dark\"`. Omitted means `\"light\"`. */\n theme?: ProductListTheme;\n /** Partial overrides applied over the theme preset. */\n tokens?: ProductListAppearanceTokens;\n /** Per element `className`/`style` overrides. */\n elements?: ProductListAppearanceElements;\n};\n\nexport type ResolvedProductListAppearance = {\n theme: ProductListTheme;\n /** Tokens that are in effect (the theme preset plus caller overrides). */\n tokens: ProductListAppearanceTokens;\n elements: ProductListAppearanceElements;\n /** Theme marker class for the theme boundary. */\n boundaryClassName: string;\n /** Inline custom properties applied to the list root. */\n boundaryStyle: CSSProperties;\n};\n\n/** CSS custom property used for each token. */\nexport const PRODUCT_LIST_TOKEN_VARIABLES = {\n fontFamily: \"--bitsnap-products-font-family\",\n fontSize: \"--bitsnap-products-font-size\",\n background: \"--bitsnap-products-background\",\n surface: \"--bitsnap-products-surface\",\n foreground: \"--bitsnap-products-foreground\",\n mutedForeground: \"--bitsnap-products-muted-foreground\",\n border: \"--bitsnap-products-border\",\n buttonBackground: \"--bitsnap-products-button-background\",\n buttonForeground: \"--bitsnap-products-button-foreground\",\n buttonHoverBackground: \"--bitsnap-products-button-hover-background\",\n hoverSurface: \"--bitsnap-products-hover-surface\",\n focusRing: \"--bitsnap-products-focus-ring\",\n error: \"--bitsnap-products-error\",\n badgeBackground: \"--bitsnap-products-badge-background\",\n badgeForeground: \"--bitsnap-products-badge-foreground\",\n radius: \"--bitsnap-products-radius\",\n} as const;\n\nexport type ProductListTokenName = keyof typeof PRODUCT_LIST_TOKEN_VARIABLES;\n\n/**\n * Complete palettes. They carry colors and radius only, so typography is never\n * reset implicitly. `products.css` falls back to the light values, which keeps\n * the list usable even when the boundary style is missing.\n */\nexport const PRODUCT_LIST_THEME_PRESETS: Record<\n ProductListTheme,\n ProductListAppearanceTokens\n> = {\n light: {\n background: \"#ffffff\",\n surface: \"#f9fafb\",\n foreground: \"#18181b\",\n mutedForeground: \"#71717a\",\n border: \"#e4e4e7\",\n buttonBackground: \"#18181b\",\n buttonForeground: \"#fafafa\",\n buttonHoverBackground: \"#000000\",\n hoverSurface: \"#f4f4f5\",\n focusRing: \"#71717a\",\n error: \"#dc2626\",\n badgeBackground: \"#f4f4f5\",\n badgeForeground: \"#3f3f46\",\n radius: \"8px\",\n },\n dark: {\n background: \"#18181b\",\n surface: \"#27272a\",\n foreground: \"#fafafa\",\n mutedForeground: \"#a1a1aa\",\n border: \"#3f3f46\",\n buttonBackground: \"#fafafa\",\n buttonForeground: \"#18181b\",\n buttonHoverBackground: \"#e4e4e7\",\n hoverSurface: \"#3f3f46\",\n focusRing: \"#a1a1aa\",\n error: \"#f87171\",\n badgeBackground: \"#3f3f46\",\n badgeForeground: \"#e4e4e7\",\n radius: \"8px\",\n },\n};\n\n/** The list renders its own elements, so no shared primitive needs remapping. */\nconst PRODUCT_LIST_SHADCN_VARIABLES: ShadcnVariableMapping<ProductListTokenName> =\n [];\n\nexport function resolveProductListAppearance(\n appearance?: ProductListAppearance,\n): ResolvedProductListAppearance {\n const resolved = resolveAppearanceCore<\n ProductListTokenName,\n ProductListTheme,\n ProductListSlotName\n >(appearance, {\n defaultTheme: \"light\",\n presets: PRODUCT_LIST_THEME_PRESETS,\n variables: PRODUCT_LIST_TOKEN_VARIABLES,\n shadcnVariables: PRODUCT_LIST_SHADCN_VARIABLES,\n });\n\n return {\n theme: resolved.theme,\n tokens: resolved.tokens,\n elements: resolved.elements,\n boundaryClassName: resolved.theme,\n boundaryStyle: resolved.boundaryStyle,\n };\n}\n\n/** Caller overrides for a single slot, if any were provided. */\nexport function getProductListSlotAppearance(\n resolved: ResolvedProductListAppearance,\n slot: ProductListSlotName,\n): ProductListSlotAppearance | undefined {\n return getSlotAppearance(resolved.elements, slot);\n}\n","import { DEFAULT_LOCALE } from \"../checkout/locale\";\n\nfunction createFormatter(\n locale: string,\n currency: string,\n): Intl.NumberFormat | undefined {\n try {\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n currencyDisplay: \"symbol\",\n });\n } catch {\n // RangeError: invalid locale or currency code.\n return undefined;\n }\n}\n\n/**\n * Formats a price in minor units (grosze, cents) for the locale, the same way\n * the cart does (`amount / 100`). An unknown locale falls back to Polish and an\n * invalid currency code to a plain number followed by the code.\n */\nexport function formatProductPrice(\n amount: number,\n currency: string,\n locale: string = DEFAULT_LOCALE,\n): string {\n const value = amount / 100;\n const formatter =\n createFormatter(locale, currency) ??\n createFormatter(DEFAULT_LOCALE, currency);\n\n return formatter != null\n ? formatter.format(value)\n : `${value.toFixed(2)} ${currency}`;\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { HOST } from \"../checkout/constants\";\nimport {\n clampPageSize,\n fetchProductList,\n pageCountFor,\n type ProductListData,\n type PublicListProduct,\n} from \"./fetch\";\n\nexport type UseProductsOptions = {\n /** Project (shop) ID. */\n projectID: string;\n /**\n * Origin of the Bitsnap backend. Defaults to the library host\n * (`https://bitsnap.pl`, or what `setCustomHost` had set when the component\n * first rendered; later `setCustomHost` calls do not move an existing list).\n * On a custom domain pass the domain itself, or an empty string for\n * same-origin requests.\n */\n host?: string;\n locale?: string;\n /** Products per page, 1 to 48. Defaults to 24. */\n pageSize?: number;\n search?: string;\n /**\n * First page, loaded on the server. It is always used for the first request\n * of the mounted list (the first fetch is skipped and the products are\n * available on the first render), so it has to be the page the props ask\n * for: page 1 with the same `pageSize`, `locale` and `search`. Later changes\n * of the props fetch again.\n */\n initialData?: ProductListData;\n};\n\nexport type UseProductsResult = {\n /** Products of the current page. Keeps the previous page while loading. */\n products: PublicListProduct[];\n totalCount: number;\n /** Current page, starting at 1. */\n page: number;\n pageCount: number;\n setPage: (page: number) => void;\n /** `true` until the current page is available, also during server rendering. */\n isLoading: boolean;\n error: Error | undefined;\n /** Loads the current page again. */\n refetch: () => void;\n};\n\ntype Snapshot = {\n /** Request the data belongs to; empty when it is not tied to one. */\n requestKey: string;\n data: ProductListData | undefined;\n error: Error | undefined;\n};\n\n/**\n * Loads the product catalog page by page. It uses a plain `fetch` without\n * credentials, never reads global state (`setProjectID`, `setCustomHost`) other\n * than the default host, and does nothing during server rendering - pass\n * `initialData` to render products in the server HTML.\n */\nexport function useProducts(options: UseProductsOptions): UseProductsResult {\n const { projectID, locale, search, initialData } = options;\n // The library host is a mutable global; read it once so a later\n // `setCustomHost` does not change the query of a mounted list.\n const [defaultHost] = useState(() => HOST);\n const host = options.host ?? defaultHost;\n const pageSize = clampPageSize(options.pageSize);\n\n // Everything that identifies a list; a change resets the page.\n const queryKey = JSON.stringify([\n projectID,\n host,\n locale ?? null,\n search?.trim() ?? null,\n pageSize,\n ]);\n\n const [pageState, setPageState] = useState({ queryKey, page: 1 });\n if (pageState.queryKey !== queryKey) {\n // Another list: start from page 1 (adjusting state while rendering).\n setPageState({ queryKey, page: 1 });\n }\n const [reloads, setReloads] = useState(0);\n const [snapshot, setSnapshot] = useState<Snapshot>(() => ({\n requestKey: initialData != null ? `${queryKey}|1|0` : \"\",\n data: initialData,\n error: undefined,\n }));\n\n // A page past the end (the catalog shrank) falls back to the last page once\n // the total is known.\n const totalCount = snapshot.data?.totalCount ?? 0;\n const pageCount = pageCountFor(totalCount, pageSize);\n const requestedPage = pageState.queryKey === queryKey ? pageState.page : 1;\n const page = totalCount > 0 ? Math.min(requestedPage, pageCount) : requestedPage;\n\n const requestKey = `${queryKey}|${page}|${reloads}`;\n\n const isCurrent = snapshot.requestKey === requestKey;\n\n useEffect(() => {\n if (isCurrent) {\n return;\n }\n\n const controller = new AbortController();\n fetchProductList(\n {\n projectID,\n host,\n locale,\n search,\n limit: pageSize,\n offset: (page - 1) * pageSize,\n },\n controller.signal,\n ).then(\n (data) => {\n if (controller.signal.aborted) {\n return;\n }\n setSnapshot({ requestKey, data, error: undefined });\n },\n (error: unknown) => {\n if (controller.signal.aborted) {\n return;\n }\n setSnapshot((previous) => ({\n requestKey,\n data: previous.data,\n error: error instanceof Error ? error : new Error(String(error)),\n }));\n },\n );\n\n return () => controller.abort();\n // `requestKey` carries projectID, host, locale, search, pageSize, page and\n // the reload counter.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [requestKey, isCurrent]);\n\n const setPage = useCallback(\n (next: number) => {\n const target = Math.max(1, Math.floor(next));\n setPageState({\n queryKey,\n page: totalCount > 0 ? Math.min(target, pageCount) : target,\n });\n },\n [queryKey, totalCount, pageCount],\n );\n\n const refetch = useCallback(() => setReloads((value) => value + 1), []);\n\n return useMemo(\n () => ({\n products: snapshot.data?.items ?? [],\n totalCount,\n page,\n pageCount,\n setPage,\n isLoading: !isCurrent,\n error: isCurrent ? snapshot.error : undefined,\n refetch,\n }),\n [snapshot, totalCount, page, pageCount, setPage, isCurrent, refetch],\n );\n}\n","import type { BitsnapModels } from \"@/src/models\";\n\nexport type PublicListProduct = BitsnapModels.PublicListProduct;\nexport type ProductListData = BitsnapModels.ProductListResponse;\n\nexport const DEFAULT_PAGE_SIZE = 24;\nexport const MAX_PAGE_SIZE = 48;\n\nexport type ProductListQuery = {\n projectID: string;\n /** Origin of the Bitsnap backend (or of a custom domain), without a path. */\n host: string;\n locale?: string;\n search?: string;\n limit: number;\n offset: number;\n};\n\nexport class ProductListError extends Error {\n readonly status: number | undefined;\n\n constructor(message: string, status?: number) {\n super(message);\n this.name = \"ProductListError\";\n this.status = status;\n }\n}\n\n/** Page size within what the backend accepts (1 to 48, default 24). */\nexport function clampPageSize(pageSize?: number): number {\n if (pageSize == null || !Number.isFinite(pageSize)) {\n return DEFAULT_PAGE_SIZE;\n }\n return Math.min(MAX_PAGE_SIZE, Math.max(1, Math.floor(pageSize)));\n}\n\nexport function pageCountFor(totalCount: number, pageSize: number): number {\n return Math.max(1, Math.ceil(totalCount / pageSize));\n}\n\n/** Origin without trailing slashes, so equal hosts compare equal as strings. */\nexport function normalizeHost(host: string): string {\n return host.replace(/\\/+$/, \"\");\n}\n\nexport function buildProductListURL(query: ProductListQuery): string {\n const params = new URLSearchParams();\n params.set(\"limit\", String(query.limit));\n params.set(\"offset\", String(query.offset));\n if (query.locale) {\n params.set(\"locale\", query.locale);\n }\n const search = query.search?.trim();\n if (search) {\n params.set(\"search\", search);\n }\n\n const host = normalizeHost(query.host);\n return `${host}/api/integrations/${encodeURIComponent(\n query.projectID,\n )}/public-commerce/product-list?${params.toString()}`;\n}\n\nfunction isProductListData(value: unknown): value is ProductListData {\n return (\n typeof value === \"object\" &&\n value != null &&\n Array.isArray((value as ProductListData).items) &&\n typeof (value as ProductListData).totalCount === \"number\"\n );\n}\n\n/**\n * Loads one page of the catalog with a plain, credential-less `fetch`. It does\n * not touch the global project ID or host.\n */\nexport async function fetchProductList(\n query: ProductListQuery,\n signal?: AbortSignal,\n): Promise<ProductListData> {\n const response = await fetch(buildProductListURL(query), {\n method: \"GET\",\n credentials: \"omit\",\n headers: { Accept: \"application/json\" },\n signal,\n });\n\n if (!response.ok) {\n throw new ProductListError(\n `Could not load products (${response.status})`,\n response.status,\n );\n }\n\n const payload: unknown = await response.json();\n if (!isProductListData(payload)) {\n throw new ProductListError(\"Unexpected product list response\");\n }\n\n return payload;\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport { DEFAULT_LOCALE } from \"../checkout/locale\";\nimport { addProductToCart } from \"./add-to-cart\";\nimport {\n getProductListSlotAppearance,\n resolveProductListAppearance,\n type ProductListAppearance,\n type ProductListSlotName,\n type ResolvedProductListAppearance,\n} from \"./appearance\";\nimport { clampPageSize, type PublicListProduct } from \"./fetch\";\nimport { formatProductPrice } from \"./format\";\nimport {\n fillProductListText,\n resolveProductListTexts,\n type ProductListTexts,\n} from \"./texts\";\nimport { useProducts, type UseProductsOptions } from \"./useProducts\";\n\n/** What `renderItem` gets next to the product. */\nexport type ProductListItemContext = {\n /** Product page URL from `productHref`. */\n href: string;\n /** Price formatted for the locale and currency, without the \"from\" prefix. */\n price: string;\n /** Formatted regular price when the product is discounted. */\n compareAtPrice: string | null;\n texts: ProductListTexts;\n locale: string;\n /** Adds the product to the cart the way the built-in button does. */\n addToCart: () => Promise<void>;\n};\n\nexport type ProductListProps = UseProductsOptions & {\n /**\n * Product page URL. Defaults to the relative `/p/{uniqueSlug}`, which works\n * on a Bitsnap custom domain. Embedded on another site, return the full\n * URL of the product page.\n */\n productHref?: (product: PublicListProduct) => string;\n appearance?: ProductListAppearance;\n /** Text overrides, applied whatever the locale. */\n texts?: Partial<ProductListTexts>;\n /** Replaces the content of a card. The card frame stays. */\n renderItem?: (\n product: PublicListProduct,\n context: ProductListItemContext,\n ) => ReactNode;\n /**\n * Called by the \"Add to cart\" button instead of the default action\n * (`Bitsnap.addProductToCart`). A rejected promise shows the error message.\n */\n onAddToCart?: (product: PublicListProduct) => void | Promise<void>;\n /** Open the cart drawer after the default add to cart. Defaults to `true`. */\n showCartOnAdd?: boolean;\n className?: string;\n};\n\ntype ListContext = {\n appearance: ResolvedProductListAppearance;\n texts: ProductListTexts;\n locale: string;\n};\n\nconst ProductListContext = createContext<ListContext | undefined>(undefined);\n\nfunction useListContext(): ListContext {\n const value = useContext(ProductListContext);\n if (value == null) {\n throw new Error(\"ProductList parts must be rendered inside ProductList\");\n }\n return value;\n}\n\n/** Stable slot attribute, built-in classes and the caller overrides for a slot. */\nfunction useSlot(slot: ProductListSlotName, className?: string) {\n const { appearance } = useListContext();\n const override = getProductListSlotAppearance(appearance, slot);\n\n return {\n \"data-bitsnap-products-slot\": slot,\n className: cn(className, override?.className),\n style: override?.style,\n };\n}\n\nconst BUTTON_CLASS =\n \"inline-flex cursor-pointer items-center justify-center px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:cursor-not-allowed aria-disabled:opacity-50\";\nconst BLOCK_BUTTON_CLASS = `${BUTTON_CLASS} w-full`;\nconst LINK_BUTTON_CLASS = `${BLOCK_BUTTON_CLASS} no-underline`;\n\ntype AddStatus = \"idle\" | \"adding\" | \"added\" | \"error\";\n\nfunction AddToCartButton({\n product,\n onAdd,\n}: {\n product: PublicListProduct;\n onAdd: () => Promise<void>;\n}) {\n const { texts } = useListContext();\n const [status, setStatus] = useState<AddStatus>(\"idle\");\n const button = useSlot(\"addToCartButton\", BLOCK_BUTTON_CLASS);\n const message = useSlot(\"message\", \"mt-2 text-xs\");\n\n useEffect(() => {\n if (status !== \"added\") {\n return;\n }\n const timer = setTimeout(() => setStatus(\"idle\"), 2000);\n return () => clearTimeout(timer);\n }, [status]);\n\n const click = useCallback(async () => {\n setStatus(\"adding\");\n try {\n await onAdd();\n setStatus(\"added\");\n } catch (error) {\n console.error(\"bitsnap-react: could not add to the cart\", error);\n setStatus(\"error\");\n }\n }, [onAdd]);\n\n const label =\n status === \"adding\"\n ? texts.addingToCart\n : status === \"added\"\n ? texts.addedToCart\n : texts.addToCart;\n\n return (\n <>\n <button\n type=\"button\"\n {...button}\n disabled={status === \"adding\"}\n aria-label={`${label}: ${product.name}`}\n onClick={click}\n >\n {label}\n </button>\n {status === \"error\" ? (\n <p {...message} role=\"alert\">\n {texts.addToCartError}\n </p>\n ) : null}\n </>\n );\n}\n\nfunction ProductCard({\n product,\n href,\n onAdd,\n renderItem,\n}: {\n product: PublicListProduct;\n href: string;\n onAdd: () => Promise<void>;\n renderItem?: ProductListProps[\"renderItem\"];\n}) {\n const { texts, locale } = useListContext();\n const card = useSlot(\n \"card\",\n \"relative flex flex-col overflow-hidden border transition-colors\",\n );\n const cardLink = useSlot(\"cardLink\", \"flex flex-1 flex-col no-underline\");\n const imageFrame = useSlot(\"image\", \"aspect-square w-full overflow-hidden\");\n const placeholder = useSlot(\"imagePlaceholder\", \"aspect-square w-full\");\n const body = useSlot(\"body\", \"flex flex-1 flex-col gap-1 p-4\");\n const name = useSlot(\"name\", \"text-base font-medium leading-snug\");\n const description = useSlot(\"description\", \"line-clamp-2 text-sm\");\n const price = useSlot(\"price\", \"mt-auto pt-2 text-base font-semibold\");\n const comparePrice = useSlot(\"comparePrice\", \"ml-2 text-sm font-normal\");\n const badge = useSlot(\n \"badge\",\n \"absolute left-3 top-3 px-2 py-0.5 text-xs font-medium\",\n );\n const actions = useSlot(\"actions\", \"p-4 pt-0\");\n const selectButton = useSlot(\"selectButton\", LINK_BUTTON_CLASS);\n\n const formattedPrice = formatProductPrice(\n product.price,\n product.currency,\n locale,\n );\n const formattedCompare =\n product.compareAtPrice != null && product.compareAtPrice > product.price\n ? formatProductPrice(product.compareAtPrice, product.currency, locale)\n : null;\n\n if (renderItem != null) {\n return (\n <li {...card} data-unavailable={product.available ? undefined : \"\"}>\n {renderItem(product, {\n href,\n price: formattedPrice,\n compareAtPrice: formattedCompare,\n texts,\n locale,\n addToCart: onAdd,\n })}\n </li>\n );\n }\n\n const imageSource = product.image?.thumbnailUrl ?? product.image?.url;\n const badgeText = !product.available\n ? texts.unavailable\n : product.isRecurring\n ? texts.subscription\n : null;\n\n return (\n <li {...card} data-unavailable={product.available ? undefined : \"\"}>\n <a {...cardLink} href={href}>\n {imageSource != null ? (\n <div {...imageFrame}>\n <img\n src={imageSource}\n alt=\"\"\n loading=\"lazy\"\n decoding=\"async\"\n className=\"h-full w-full object-cover\"\n />\n </div>\n ) : (\n <div {...placeholder} aria-hidden=\"true\" />\n )}\n <div {...body}>\n <h3 {...name}>{product.name}</h3>\n {product.shortDescription ? (\n <p {...description}>{product.shortDescription}</p>\n ) : null}\n <p {...price}>\n {product.priceFrom\n ? fillProductListText(texts.priceFrom, { price: formattedPrice })\n : formattedPrice}\n {formattedCompare != null ? (\n <>\n <span className=\"sr-only\">{texts.originalPrice}: </span>\n <del {...comparePrice}>{formattedCompare}</del>\n </>\n ) : null}\n </p>\n </div>\n </a>\n {badgeText != null ? (\n <span\n {...badge}\n data-kind={product.available ? \"subscription\" : \"unavailable\"}\n >\n {badgeText}\n </span>\n ) : null}\n <div {...actions}>\n {!product.available ? (\n <button type=\"button\" {...selectButton} disabled>\n {texts.unavailable}\n </button>\n ) : product.addToCart ? (\n <AddToCartButton product={product} onAdd={onAdd} />\n ) : (\n <a {...selectButton} href={href}>\n {product.variantCount > 1 ? texts.chooseOptions : texts.viewProduct}\n </a>\n )}\n </div>\n </li>\n );\n}\n\nconst GRID_CLASS =\n \"m-0 grid list-none grid-cols-[repeat(auto-fill,minmax(min(100%,15rem),1fr))] gap-5 p-0\";\n\nfunction SkeletonGrid({ count, label }: { count: number; label: string }) {\n const grid = useSlot(\"grid\", GRID_CLASS);\n const skeleton = useSlot(\"skeleton\", \"aspect-[3/4] animate-pulse\");\n\n return (\n <div {...grid} role=\"status\" aria-busy=\"true\" aria-label={label}>\n {Array.from({ length: count }, (_, index) => (\n <div key={index} {...skeleton} aria-hidden=\"true\" />\n ))}\n </div>\n );\n}\n\nfunction Pagination({\n page,\n pageCount,\n isLoading,\n onPage,\n}: {\n page: number;\n pageCount: number;\n isLoading: boolean;\n onPage: (page: number) => void;\n}) {\n const { texts } = useListContext();\n const nav = useSlot(\n \"pagination\",\n \"mt-8 flex items-center justify-center gap-4\",\n );\n const button = useSlot(\"paginationButton\", BUTTON_CLASS);\n const indicator = useSlot(\"pageIndicator\", \"text-sm\");\n\n return (\n <nav {...nav} aria-label={texts.pagination}>\n <button\n type=\"button\"\n {...button}\n aria-disabled={isLoading || page <= 1}\n onClick={() => {\n if (!isLoading && page > 1) {\n onPage(page - 1);\n }\n }}\n >\n {texts.previousPage}\n </button>\n <span {...indicator} aria-live=\"polite\">\n {fillProductListText(texts.pageOf, { page, pageCount })}\n </span>\n <button\n type=\"button\"\n {...button}\n aria-disabled={isLoading || page >= pageCount}\n onClick={() => {\n if (!isLoading && page < pageCount) {\n onPage(page + 1);\n }\n }}\n >\n {texts.nextPage}\n </button>\n </nav>\n );\n}\n\nfunction ProductListContent({\n options,\n productHref,\n renderItem,\n onAddToCart,\n showCartOnAdd,\n}: {\n options: UseProductsOptions;\n productHref: (product: PublicListProduct) => string;\n renderItem?: ProductListProps[\"renderItem\"];\n onAddToCart?: ProductListProps[\"onAddToCart\"];\n showCartOnAdd: boolean;\n}) {\n const { texts } = useListContext();\n const { products, page, pageCount, setPage, isLoading, error, refetch } =\n useProducts(options);\n\n // After a page change by the user, move focus to the products (the button\n // that was pressed stays where it is, but the content above it changes) and\n // bring them into view once the page has loaded.\n const content = useRef<HTMLDivElement>(null);\n const movedPage = useRef(false);\n const changePage = useCallback(\n (next: number) => {\n movedPage.current = true;\n setPage(next);\n },\n [setPage],\n );\n useEffect(() => {\n if (isLoading || !movedPage.current) {\n return;\n }\n movedPage.current = false;\n content.current?.focus({ preventScroll: true });\n content.current?.scrollIntoView({ block: \"start\" });\n }, [isLoading]);\n\n const grid = useSlot(\"grid\", GRID_CLASS);\n const empty = useSlot(\"emptyState\", \"py-12 text-center text-sm\");\n const errorSlot = useSlot(\"error\", \"flex flex-col items-center gap-3 py-12 text-center text-sm\");\n const retry = useSlot(\"retryButton\", BUTTON_CLASS);\n\n const { projectID, host } = options;\n const addFor = useCallback(\n (product: PublicListProduct) => () =>\n onAddToCart != null\n ? Promise.resolve(onAddToCart(product))\n : addProductToCart(product, {\n projectID,\n host,\n showCart: showCartOnAdd,\n }),\n [onAddToCart, projectID, host, showCartOnAdd],\n );\n\n let body: ReactNode;\n if (isLoading && products.length === 0) {\n body = (\n <SkeletonGrid\n count={Math.min(clampPageSize(options.pageSize), 8)}\n label={texts.loading}\n />\n );\n } else if (error != null) {\n body = (\n <div {...errorSlot} role=\"alert\">\n <p>{texts.error}</p>\n <button type=\"button\" {...retry} onClick={refetch}>\n {texts.retry}\n </button>\n </div>\n );\n } else if (products.length === 0) {\n body = <p {...empty}>{texts.empty}</p>;\n } else {\n body = (\n <ul\n {...grid}\n aria-busy={isLoading || undefined}\n className={cn(grid.className, isLoading && \"opacity-60\")}\n >\n {products.map((product) => (\n <ProductCard\n key={product.id}\n product={product}\n href={productHref(product)}\n onAdd={addFor(product)}\n renderItem={renderItem}\n />\n ))}\n </ul>\n );\n }\n\n return (\n <div\n ref={content}\n tabIndex={-1}\n className=\"p-1 outline-none scroll-mt-4\"\n >\n {body}\n {pageCount > 1 && error == null ? (\n <Pagination\n page={page}\n pageCount={pageCount}\n isLoading={isLoading}\n onPage={changePage}\n />\n ) : null}\n </div>\n );\n}\n\nconst defaultProductHref = (product: PublicListProduct) =>\n `/p/${encodeURIComponent(product.uniqueSlug)}`;\n\n/**\n * Responsive grid of the shop's products with pagination, loading, empty and\n * error states. Cards link to the product page and can add to the cart.\n *\n * ```tsx\n * <ProductList projectID=\"…\" locale=\"pl-PL\" initialData={firstPage} />\n * ```\n *\n * It renders on the server: pass `initialData` (the first page, fetched on the\n * server) to have the products in the HTML; without it the server renders the\n * loading skeleton and the browser fetches the first page.\n */\nexport function ProductList({\n productHref = defaultProductHref,\n appearance,\n texts,\n renderItem,\n onAddToCart,\n showCartOnAdd = true,\n className,\n ...options\n}: ProductListProps) {\n const locale = options.locale ?? DEFAULT_LOCALE;\n const resolvedAppearance = useMemo(\n () => resolveProductListAppearance(appearance),\n [appearance],\n );\n const resolvedTexts = useMemo(\n () => resolveProductListTexts(locale, texts),\n [locale, texts],\n );\n const context = useMemo(\n () => ({ appearance: resolvedAppearance, texts: resolvedTexts, locale }),\n [resolvedAppearance, resolvedTexts, locale],\n );\n const root = getProductListSlotAppearance(resolvedAppearance, \"root\");\n\n return (\n <ProductListContext.Provider value={context}>\n <div\n data-bitsnap-products=\"root\"\n data-bitsnap-products-slot=\"root\"\n className={cn(\n \"bitsnap-react\",\n resolvedAppearance.boundaryClassName,\n className,\n root?.className,\n )}\n style={\n { ...resolvedAppearance.boundaryStyle, ...root?.style } as CSSProperties\n }\n >\n <ProductListContent\n options={options}\n productHref={productHref}\n renderItem={renderItem}\n onAddToCart={onAddToCart}\n showCartOnAdd={showCartOnAdd}\n />\n </div>\n </ProductListContext.Provider>\n );\n}\n","import { normalizeHost } from \"./fetch\";\n\nexport type CartState = {\n /** Project the page cart is set up for, `null` or `undefined` when none yet. */\n projectID: string | null | undefined;\n /** Backend origin the page cart currently talks to. */\n host: string;\n /** Backend origin used when the page did not choose another one. */\n defaultHost: string;\n};\n\nexport type CartTarget = {\n projectID: string;\n /** Omitted or empty keeps the current host. */\n host?: string;\n};\n\nexport type CartPlan =\n | { ok: true; setProjectID: string | null; setHost: string | null }\n | { ok: false; reason: string };\n\n/**\n * Decides, without changing anything, whether the page cart can serve the\n * target and what has to be filled in first. Both the project and the host are\n * checked before the caller changes either of them, so a refused click leaves\n * the page cart untouched.\n */\nexport function planCartTarget(state: CartState, target: CartTarget): CartPlan {\n if (state.projectID != null && state.projectID !== target.projectID) {\n return {\n ok: false,\n reason: `the page cart already belongs to project \"${state.projectID}\"`,\n };\n }\n\n let setHost: string | null = null;\n const targetHost = target.host ? normalizeHost(target.host) : \"\";\n const currentHost = normalizeHost(state.host);\n if (targetHost && targetHost !== currentHost) {\n if (currentHost !== normalizeHost(state.defaultHost)) {\n return {\n ok: false,\n reason: `the page cart already uses the host \"${state.host}\"`,\n };\n }\n setHost = targetHost;\n }\n\n return {\n ok: true,\n setProjectID: state.projectID == null ? target.projectID : null,\n setHost,\n };\n}\n","import { DEFAULT_HOST, HOST, setCustomHost } from \"../checkout/constants\";\nimport { planCartTarget } from \"./cart-target\";\nimport type { PublicListProduct } from \"./fetch\";\n\nexport type AddToCartTarget = {\n projectID: string;\n /** Backend origin the cart talks to. Omitted or empty keeps the current one. */\n host?: string;\n /** Open the cart drawer afterwards. */\n showCart: boolean;\n};\n\n/**\n * Default \"add to cart\" action of `ProductList`: `Bitsnap.addProductToCart`\n * with quantity 1, then the cart drawer.\n *\n * The checkout is a heavy module (RPC client, cart state, payment buttons), so\n * it is loaded on the first click and never ends up in the first paint of a\n * catalog page. The cart only knows one project and one host at a time, and\n * they are page-wide (the cart is kept in localStorage, `setProjectID` also\n * changes the panel configuration). So the list only fills them in when the\n * page has not set them yet; when the page already works for another project\n * or host, nothing is changed and the call fails (pass `onAddToCart` to the\n * list in that case).\n */\nexport async function addProductToCart(\n product: PublicListProduct,\n target: AddToCartTarget,\n): Promise<void> {\n const [{ Bitsnap }, { getProjectID, setProjectID }] = await Promise.all([\n import(\"../checkout/methods\"),\n import(\"../checkout/CartProvider\"),\n ]);\n\n const plan = planCartTarget(\n { projectID: getProjectID(), host: HOST, defaultHost: DEFAULT_HOST },\n target,\n );\n if (!plan.ok) {\n return failConflict(plan.reason);\n }\n if (plan.setProjectID != null) {\n setProjectID(plan.setProjectID);\n }\n if (plan.setHost != null) {\n setCustomHost(plan.setHost);\n }\n\n // Single-variant products are added by their variant, not the product ID.\n const error = await Bitsnap.addProductToCart(\n product.cartItemId ?? product.id,\n 1,\n undefined,\n {\n name: product.name,\n price: product.price,\n currency: product.currency,\n },\n );\n if (error != null) {\n throw new Error(\"Could not add the product to the cart\");\n }\n\n if (target.showCart) {\n Bitsnap.showCart();\n }\n}\n\nfunction failConflict(reason: string): never {\n console.warn(\n `bitsnap-react: ProductList did not add to the cart because ${reason}. ` +\n \"Pass onAddToCart to use another cart.\",\n );\n throw new Error(\"The page cart belongs to another project or host\");\n}\n","import {\n lookupText,\n resolveTexts,\n type LocaleTables,\n} from \"@/src/lib/texts\";\n\n/**\n * Every string `ProductList` renders. Pass a partial object through the\n * `texts` prop to override any of them, whatever the locale. Placeholders\n * (`{price}`, `{page}`, `{pageCount}`) are filled by the component.\n */\nexport type ProductListTexts = {\n /** \"Add to cart\" button of products that can be bought straight from the list. */\n addToCart: string;\n /** Button label while the product is being added. */\n addingToCart: string;\n /** Button label after the product was added. */\n addedToCart: string;\n /** Message shown when adding to the cart failed. */\n addToCartError: string;\n /** Link of products with variants, to pick one on the product page. */\n chooseOptions: string;\n /** Link of products that cannot be added from the list (subscriptions). */\n viewProduct: string;\n /** Label of products that are out of stock. */\n unavailable: string;\n /** Badge of subscription products. */\n subscription: string;\n /** Price of products whose variants differ in price. `{price}` is the lowest one. */\n priceFrom: string;\n /** Screen reader label of the struck-through regular price. */\n originalPrice: string;\n /** Accessible label of the loading skeleton. */\n loading: string;\n /** Shown when the shop has no products (or none matches the search). */\n empty: string;\n /** Shown when the products could not be loaded. */\n error: string;\n /** Retry button of the error state. */\n retry: string;\n /** Accessible label of the pagination. */\n pagination: string;\n previousPage: string;\n nextPage: string;\n /** Page indicator. `{page}` and `{pageCount}` are filled in. */\n pageOf: string;\n};\n\nexport type ProductListTextKey = keyof ProductListTexts;\n\nexport const PRODUCT_LIST_TEXT_TABLES: LocaleTables<ProductListTextKey> = {\n en: {\n addToCart: \"Add to cart\",\n addingToCart: \"Adding…\",\n addedToCart: \"Added to cart\",\n addToCartError: \"Could not add to the cart. Try again.\",\n chooseOptions: \"Choose\",\n viewProduct: \"View\",\n unavailable: \"Unavailable\",\n subscription: \"Subscription\",\n priceFrom: \"from {price}\",\n originalPrice: \"Original price\",\n loading: \"Loading products\",\n empty: \"There are no products to show.\",\n error: \"Could not load the products.\",\n retry: \"Try again\",\n pagination: \"Pagination\",\n previousPage: \"Previous\",\n nextPage: \"Next\",\n pageOf: \"Page {page} of {pageCount}\",\n },\n pl: {\n addToCart: \"Dodaj do koszyka\",\n addingToCart: \"Dodawanie…\",\n addedToCart: \"Dodano do koszyka\",\n addToCartError: \"Nie udało się dodać do koszyka. Spróbuj ponownie.\",\n chooseOptions: \"Wybierz\",\n viewProduct: \"Zobacz\",\n unavailable: \"Niedostępny\",\n subscription: \"Subskrypcja\",\n priceFrom: \"od {price}\",\n originalPrice: \"Cena przed obniżką\",\n loading: \"Ładowanie produktów\",\n empty: \"Brak produktów do wyświetlenia.\",\n error: \"Nie udało się załadować produktów.\",\n retry: \"Spróbuj ponownie\",\n pagination: \"Paginacja\",\n previousPage: \"Poprzednia\",\n nextPage: \"Następna\",\n pageOf: \"Strona {page} z {pageCount}\",\n },\n};\n\n/** Default texts for a locale merged with the caller overrides. */\nexport function resolveProductListTexts(\n locale: string,\n overrides?: Partial<ProductListTexts>,\n): ProductListTexts {\n return resolveTexts(PRODUCT_LIST_TEXT_TABLES, locale, overrides);\n}\n\nexport function getProductListText(\n key: ProductListTextKey,\n locale: string,\n overrides?: Partial<ProductListTexts>,\n): string {\n return lookupText(resolveProductListTexts(locale, overrides), key);\n}\n\n/** Replaces `{name}` placeholders. Unknown placeholders stay untouched. */\nexport function fillProductListText(\n text: string,\n values: Record<string, string | number>,\n): string {\n return text.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in values ? String(values[name]) : match,\n );\n}\n"],"mappings":"0FA2DO,IAAMA,GAA0B,CACrC,OACA,OACA,OACA,WACA,QACA,mBACA,OACA,OACA,cACA,QACA,eACA,QACA,UACA,kBACA,eACA,UACA,aACA,mBACA,gBACA,aACA,QACA,cACA,UACF,EA8BaC,GAA+B,CAC1C,WAAY,iCACZ,SAAU,+BACV,WAAY,gCACZ,QAAS,6BACT,WAAY,gCACZ,gBAAi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AAWC,EACX,OAAQgB,EACV,EACE,MACN,CAEJ,CAEA,IAAMU,GAAsBxE,GAC1B,MAAM,mBAAmBA,EAAQ,UAAU,CAAC,GAcvC,SAASyE,GAAY,CAC1B,YAAArB,EAAcoB,GACd,WAAAhF,EACA,MAAAU,EACA,WAAAc,EACA,YAAAqC,EACA,cAAAC,EAAgB,GAChB,UAAA/D,EACA,GAAG4D,CACL,EAAqB,CACnB,IAAMlC,EAASkC,EAAQ,QAAUuB,EAC3BC,EAAqBC,EACzB,IAAMC,EAA6BrF,CAAU,EAC7C,CAACA,CAAU,CACb,EACMsF,EAAgBF,EACpB,IAAMG,GAAwB9D,EAAQf,CAAK,EAC3C,CAACe,EAAQf,CAAK,CAChB,EACM8E,EAAUJ,EACd,KAAO,CAAE,WAAYD,EAAoB,MAAOG,EAAe,OAAA7D,CAAO,GACtE,CAAC0D,EAAoBG,EAAe7D,CAAM,CAC5C,EACMgE,EAAOvF,EAA6BiF,EAAoB,MAAM,EAEpE,OACE7F,EAACE,GAAmB,SAAnB,CAA4B,MAAOgG,EAClC,SAAAlG,EAAC,OACC,wBAAsB,OACtB,6BAA2B,OAC3B,UAAWa,EACT,gBACAgF,EAAmB,kBACnBpF,EACA0F,GAAM,SACR,EACA,MACE,CAAE,GAAGN,EAAmB,cAAe,GAAGM,GAAM,KAAM,EAGxD,SAAAnG,EAACoE,GAAA,CACC,QAASC,EACT,YAAaC,EACb,WAAYpC,EACZ,YAAaqC,EACb,cAAeC,EACjB,EACF,EACF,CAEJ","names":["PRODUCT_LIST_SLOT_NAMES","PRODUCT_LIST_TOKEN_VARIABLES","PRODUCT_LIST_THEME_PRESETS","PRODUCT_LIST_SHADCN_VARIABLES","resolveProductListAppearance","appearance","resolved","resolveAppearanceCore","getProductListSlotAppearance","slot","getSlotAppearance","createFormatter","locale","currency","formatProductPrice","amount","DEFAULT_LOCALE","value","formatter","useCallback","useEffect","useMemo","useState","ProductListError","message","status","clampPageSize","pageSize","pageCountFor","totalCount","normalizeHost","host","buildProductListURL","query","params","search","isProductListData","value","fetchProductList","signal","response","payload","useProducts","options","projectID","locale","search","initialData","defaultHost","useState","HOST","host","pageSize","clampPageSize","queryKey","pageState","setPageState","reloads","setReloads","snapshot","setSnapshot","totalCount","pageCount","pageCountFor","requestedPage","page","requestKey","isCurrent","useEffect","controller","fetchProductList","data","error","previous","setPage","useCallback","next","target","refetch","value","useMemo","createContext","useCallback","useContext","useEffect","useMemo","useRef","useState","planCartTarget","state","target","setHost","targetHost","normalizeHost","currentHost","addProductToCart","product","target","Bitsnap","getProjectID","setProjectID","plan","planCartTarget","HOST","DEFAULT_HOST","failConflict","setCustomHost","reason","PRODUCT_LIST_TEXT_TABLES","resolveProductListTexts","locale","overrides","resolveTexts","fillProductListText","text","values","match","name","Fragment","jsx","jsxs","ProductListContext","createContext","useListContext","value","useContext","useSlot","slot","className","appearance","override","getProductListSlotAppearance","cn","BUTTON_CLASS","BLOCK_BUTTON_CLASS","LINK_BUTTON_CLASS","AddToCartButton","product","onAdd","texts","status","setStatus","useState","button","message","useEffect","timer","click","useCallback","error","label","ProductCard","href","renderItem","locale","card","cardLink","imageFrame","placeholder","body","name","description","price","comparePrice","badge","actions","selectButton","formattedPrice","formatProductPrice","formattedCompare","imageSource","badgeText","fillProductListText","GRID_CLASS","SkeletonGrid","count","grid","skeleton","_","index","Pagination","page","pageCount","isLoading","onPage","nav","indicator","ProductListContent","options","productHref","onAddToCart","showCartOnAdd","products","setPage","refetch","useProducts","content","useRef","movedPage","changePage","next","empty","errorSlot","retry","projectID","host","addFor","addProductToCart","clampPageSize","defaultProductHref","ProductList","DEFAULT_LOCALE","resolvedAppearance","useMemo","resolveProductListAppearance","resolvedTexts","resolveProductListTexts","context","root"]}
@@ -1,4 +0,0 @@
1
- import{A as sn,B as ln,C as cn,K as dn,N as un,O as mn,P as pn,Q as fn,R as gn,S as yn,a as yt,b as bt,c as Pt,d as ht,e as vt,f as Qt,i as _,j as Te,k as Z,l as Xt,m as en,n as I,o as at,p as Ne,q as tn,r as Le,t as nn,y as rn,z as an}from"./chunk-4HOZFM6V.mjs";import{a as x,c as K,d as Yt,g as on,l as le}from"./chunk-3TENJTY4.mjs";import{useAutoAnimate as Br}from"@formkit/auto-animate/react";import{useEffect as Nn,useState as re}from"react";import{jsx as Ge}from"react/jsx-runtime";function ce({className:e,...t}){return Ge("div",{"data-slot":"card",className:x("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function ge({className:e,...t}){return Ge("div",{"data-slot":"card-header",className:x("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function ye({className:e,...t}){return Ge("div",{"data-slot":"card-title",className:x("leading-none font-semibold",e),...t})}function wt({className:e,...t}){return Ge("div",{"data-slot":"card-description",className:x("text-muted-foreground text-sm",e),...t})}function de({className:e,...t}){return Ge("div",{"data-slot":"card-content",className:x("px-6",e),...t})}import*as bn from"react";import{OTPInput as Sr,OTPInputContext as Rr}from"input-otp";import{MinusIcon as Ir}from"lucide-react";import{jsx as De,jsxs as Ar}from"react/jsx-runtime";function Pn({className:e,containerClassName:t,...a}){return De(Sr,{"data-slot":"input-otp",containerClassName:x("flex items-center gap-2 has-disabled:opacity-50",t),className:x("disabled:cursor-not-allowed",e),...a})}function xt({className:e,...t}){return De("div",{"data-slot":"input-otp-group",className:x("flex items-center",e),...t})}function Se({index:e,className:t,...a}){let n=bn.useContext(Rr),{char:r,hasFakeCaret:o,isActive:i}=n?.slots[e]??{};return Ar("div",{"data-slot":"input-otp-slot","data-active":i,className:x("data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",t),...a,children:[r,o&&De("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:De("div",{className:"animate-caret-blink bg-foreground h-4 w-px duration-1000"})})]})}function hn({...e}){return De("div",{"data-slot":"input-otp-separator",role:"separator",...e,children:De(Ir,{})})}import{REGEXP_ONLY_DIGITS as Gr}from"input-otp";import{jsx as kt,jsxs as Lr}from"react/jsx-runtime";function Tr(){return Lr("div",{className:"flex items-center gap-2",children:[kt("div",{className:"h-3 w-3 animate-bounce rounded-full bg-current [animation-delay:-0.3s]"}),kt("div",{className:"h-3 w-3 animate-bounce rounded-full bg-current [animation-delay:-0.15s]"}),kt("div",{className:"h-3 w-3 animate-bounce rounded-full bg-current"})]})}var J=Tr;var ue={projectID:void 0,loginURL:"/panel/login",theme:void 0,host:void 0,allowedReturnOrigins:[]},vn=[];function Ct(e){ue={...ue,...e}}function ot(){return ue}function Dr(e){ue.projectID=e}function Er(e){ue.theme=e}function Ur(e){ue.loginURL=e}function zr(e){ue.host=e}function He(e){vn=e,ue={...ue,allowedReturnOrigins:e}}function $e(){return vn}import{createContext as Or,useContext as Mr}from"react";import{jsx as Nt}from"react/jsx-runtime";var wn=Or(ot()),jr=({children:e})=>Nt(Xt,{children:Nt(wn.Provider,{value:{...ot()},children:Nt("div",{className:"bitsnap-react",children:e})})}),be=()=>Mr(wn);var _r="return_url",St="__return_url",Fr="accessToken";function Ve(e){let t=new URLSearchParams(e).get(_r);return t?xn(t):null}function We(e){typeof window>"u"||(e?window.sessionStorage.setItem(St,e):window.sessionStorage.removeItem(St))}function Ee(){if(typeof window>"u")return null;let e=window.sessionStorage.getItem(St);return e?xn(e):null}function qr(e,t){return t.some(a=>{if(e===a)return!0;let n=new URL(a).hostname,r=new URL(e).hostname;return r.endsWith(`.${n}`)||r===n})}function xn(e){try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"||!qr(t.origin,$e())?null:t.toString()}catch{return null}}function Ue(e,t){let a=new URL(e);return a.searchParams.set(Fr,t),a.toString()}var Rt=(e,t)=>`bitsnap-panel-session:${encodeURIComponent(t??"https://bitsnap.pl")}:${encodeURIComponent(e)}`,It=(e,t)=>`bitsnap-panel-email:${encodeURIComponent(t??"https://bitsnap.pl")}:${encodeURIComponent(e)}`;function Ze(e,t){return typeof window>"u"||!e?void 0:window.localStorage.getItem(Rt(e,t))??void 0}function kn(e,t,a,n){typeof window>"u"||!e||(window.localStorage.setItem(Rt(e,n),t),window.localStorage.setItem(It(e,n),a))}function Cn(e,t){return typeof window>"u"||!e?null:window.localStorage.getItem(It(e,t))}function ze(e,t){typeof window>"u"||!e||(window.localStorage.removeItem(Rt(e,t)),window.localStorage.removeItem(It(e,t)))}import{jsx as w,jsxs as L}from"react/jsx-runtime";if(typeof window<"u"){let t=[window.location.origin,"https://bitsnap.pl","https://kursy.bitsnap.pl"];$e().length===0&&He(Array.from(new Set(t)))}var Hr=({projectID:e,host:t,reveal:a,email:n,setEmail:r,loginUser:o,isLoginLoading:i,errMsg:l})=>{let{projectID:s,host:y}=be();if(typeof window<"u"&&Ze(e??s,t??y)!=null)return window.location.href=window.location.href.replaceAll("login",""),null;let[m,N]=re(!1),p=c=>/^(([^<>()\[\]\\.,;:\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,}))$/.test(c.trim())?N(!0):N(!1),g=c=>{let{value:A}=c.target;p(A),r(A)};function d(){a()}function k(c){c.preventDefault(),o()}return w("main",{className:"mx-auto flex max-w-sm flex-1 flex-col justify-center space-y-12",children:w("div",{className:x("flex min-w-sm flex-col gap-6"),children:L(ce,{children:[L(ge,{children:[w(ye,{className:"text-2xl",children:"Zaloguj si\u0119"}),w(wt,{children:"Wy\u015Blemy do Ciebie kod na maila, dzi\u0119ki kt\xF3remu si\u0119 zalogujesz."})]}),w(de,{children:L("form",{onSubmit:k,children:[L("div",{className:"flex flex-col gap-6",children:[L("div",{className:"grid gap-2",children:[w(Ne,{htmlFor:"email",children:"Email"}),w(at,{id:"email",onChange:g,type:"email",placeholder:"m@example.com",required:!0}),w("span",{className:x(!m&&n.length>0?"font-bold text-red-500":"text-neutral-700 dark:text-neutral-400","text-xs"),children:!m&&n.length>0?"Nieprawid\u0142owy adres email":"Wpisz sw\xF3j adres email"})]}),L("div",{children:[L(I,{type:"submit",disabled:i,className:"relative w-full",onClick:o,children:[i&&w("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:w(J,{})}),"Zaloguj si\u0119"]}),l.length>0&&w("p",{className:"text-xs font-medium text-red-500",children:l})]})]}),L("div",{className:"mt-4 text-center text-sm",children:["Masz ju\u017C kod?"," ",w("button",{type:"button",onClick:d,className:"underline underline-offset-4",children:"Mam ju\u017C kod"})]})]})})]})})})},$r=({projectID:e,host:t,email:a,reveal:n,setEmail:r,isLoginLoading:o,loginUserResponse:i,setLoginUserResponse:l,setResponseStatus:s,errMsg:y})=>{let{mutateAsync:m,isPending:N}=Z(_.publicApi.userPanelLoginWithCode),[p,g]=re(""),[d,k]=re(!1),[c,A]=re(!1),[v,E]=re(0),S=U=>/^\d+$/.test(U.trim())?k(!0):k(!1),M=U=>{S(U),g(U)};async function V(){if(A(!0),p.length==0){k(!1);return}let U=parseInt(p),F=await m({code:U}),pe,te,ne;if(F.result.case==="accessToken"?(k(!0),pe="ok",te=void 0,ne=F.result.value):(k(!1),pe="error",te=F.result.value,ne=void 0),pe==="error"&&(k(!1),console.warn("error:",`Kod b\u0142\u0119du: ${te}`),console.warn("Nieprawid\u0142owy kod, spr\xF3buj ponownie.")),pe==="ok"){ne&&kn(e,ne,a,t);let Ie=typeof window<"u"?Ee():null;setTimeout(()=>{if(ne&&Ie){window.location.href=Ue(Ie,ne);return}window.location.reload()},100)}}function ee(){let U=setInterval(()=>{E(F=>F>0?F-1:(clearInterval(U),0))},1e3);return()=>{clearInterval(U)}}Nn(()=>{i?.status==="ok"&&i?.retryIn>0&&(E(i.retryIn),ee())},[i]);function Re(){r(""),l(null),s("default"),n()}function tt(U){U.preventDefault(),V()}return w("main",{className:"mx-auto flex max-w-md flex-1 flex-col justify-center space-y-8",children:w("div",{className:x("flex min-w-sm flex-col gap-6"),children:L(ce,{children:[L(ge,{children:[w(ye,{className:"text-2xl",children:"Wpisz kod z maila"}),w(wt,{children:"Sprawd\u017A czy przypadkiem nie wyl\u0105dowa\u0142 w spamie."})]}),L(de,{children:[L("form",{onSubmit:tt,className:"flex flex-col gap-6",children:[w("div",{className:"grid gap-2",children:w("div",{className:"my-5 flex w-full items-center justify-center",children:L("div",{className:"flex flex-col gap-2",children:[L(Pn,{id:"verify-code",maxLength:6,pattern:Gr,onChange:U=>{M(U)},children:[L(xt,{children:[w(Se,{index:0}),w(Se,{index:1}),w(Se,{index:2})]}),w(hn,{}),L(xt,{children:[w(Se,{index:3}),w(Se,{index:4}),w(Se,{index:5})]})]}),w("span",{className:x(!d&&c?"text-red-500":"text-neutral-700 dark:text-neutral-400","text-xs"),children:!d&&c?p.length==0?"Kod nie mo\u017Ce by\u0107 pusty":"Kod musi sk\u0142ada\u0107 si\u0119 z cyfr":"Wpisz kod z maila"})]})})}),L("div",{children:[L(I,{type:"submit",disabled:o||N,className:"relative w-full",children:[(o||N)&&w("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:w(J,{})}),"Zaloguj si\u0119"]}),y.length>0&&w("p",{className:"text-xs font-medium text-red-500",children:y})]})]}),L("div",{className:"mt-4 text-center text-sm",children:["Nie masz kodu?"," ",w("button",{type:"button",onClick:Re,className:"underline underline-offset-4",children:"Wr\xF3\u0107"})]})]})]})})})},Vr=()=>{let{theme:e,allowedReturnOrigins:t,projectID:a,host:n}=be(),r={"--button-background-color":e?.colors?.brand??"#FFFFFF","--button-background-color-dark":e?.colors?.brandDark??"#000000","--button-text-color":e?.colors?.brandDark??"#000000","--button-text-color-dark":e?.colors?.brand??"#FFFFFF"},[o,i]=re("login"),[l]=Br({duration:300,easing:"ease-in-out",disrespectUserMotionPreference:!1}),s=()=>i(S=>S==="login"?"verifyCode":"login"),[y,m]=re(""),[N,p]=re("default"),[g,d]=re(null),{mutateAsync:k,isPending:c}=Z(_.publicApi.userPanelLogin),[A,v]=re("");Nn(()=>{if(typeof window>"u"||window.parent!==window)return;let S=Ve(window.location.search);S&&We(S);let M=S??Ee();if(!M)return;let V=Ze(a,n);V&&(window.location.href=Ue(M,V))},[t,a,n]);async function E(){v(""),p("default");let S=await k({email:y}),M=S.result.case==="success"?"ok":"error",V=0,ee;S.result.case==="success"&&(V=S.result.value.retryIn),M==="error"&&(ee="Nieprawid\u0142owy adres email, spr\xF3buj ponownie."),d({status:M,retryIn:V,message:ee}),M==="ok"&&o==="login"?s():M==="ok"&&o==="verifyCode"?p("success"):M==="error"&&v(ee??"Nieprawid\u0142owy adres email, spr\xF3buj ponownie.")}return w("div",{className:"bg-white text-black dark:bg-black dark:text-white",children:L("div",{className:"font-inter flex h-screen w-screen flex-col p-4",style:r,ref:l,children:[L("header",{children:[e?.logoDarkURL&&w("img",{src:e?.logoDarkURL,className:"hidden dark:inline",alt:"Company Logo",draggable:!1}),e?.logoURL&&w("img",{src:e?.logoURL,className:"dark:hidden",alt:"Company Logo",draggable:!1})]}),o==="login"&&w(Hr,{projectID:a,host:n,reveal:s,email:y,setEmail:m,loginUser:E,isLoginLoading:c,errMsg:A}),o==="verifyCode"&&w($r,{projectID:a,host:n,email:y,reveal:s,setEmail:m,loginUser:E,isLoginLoading:c,loginUserResponse:g,setLoginUserResponse:d,responseStatus:N,setResponseStatus:p,errMsg:A})]})})},Wr=()=>w(Vr,{});import{useAutoAnimate as eo}from"@formkit/auto-animate/react";import{useEffect as qt,useState as to}from"react";import{useState as Zr,useCallback as Jr,useEffect as Kr}from"react";function Sn(e){let[t,a]=Zr(()=>{if(typeof window>"u")return e;let r=new URLSearchParams(window.location.search),o={};return Object.keys(e).forEach(i=>{let l=r.get(i);if(l!==null)try{o[i]=JSON.parse(l)}catch{o[i]=l}}),{...e,...o}}),n=Jr(r=>{a(o=>{let i={...o,...r};if(typeof window<"u"){let l=new URLSearchParams;Object.keys(i).forEach(y=>{let m=i[y];m!=null&&l.set(y,JSON.stringify(m))});let s=`${window.location.pathname}?${l.toString()}`;window.history.pushState({},"",s)}return i})},[]);return Kr(()=>{let r=()=>{let o=new URLSearchParams(window.location.search),i={};Object.keys(e).forEach(l=>{let s=o.get(l);if(s!==null)try{i[l]=JSON.parse(s)}catch{i[l]=s}}),a({...e,...i})};return window.addEventListener("popstate",r),()=>window.removeEventListener("popstate",r)},[e]),[t,n]}function Rn(e,t){if(e!=null)return e;let a=t?.trim();if(!(a==null||a===""))return{tokens:tn(a)}}import*as it from"@radix-ui/react-switch";import{jsx as In}from"react/jsx-runtime";function An({className:e,...t}){return In(it.Root,{"data-slot":"switch",className:x("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:In(it.Thumb,{"data-slot":"switch-thumb",className:x("bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}import{useState as Qr}from"react";import{Fragment as Xr,jsx as Je,jsxs as At}from"react/jsx-runtime";function Yr({}){let[e,t]=Qr({disableAll:!1});return At(Xr,{children:[Je("h3",{className:"text-2xl",children:"Powiadomienia"}),Je("p",{className:"text-sm text-neutral-500",children:"Zarz\u0105dzaj swoimi powiadomieniami"}),Je("div",{className:"mt-6",children:At("div",{className:"flex items-center space-x-2",children:[Je(An,{id:"disable-all-notifications",checked:e.disableAll,onCheckedChange:a=>t(n=>({...n,disableAll:a}))}),At(Ne,{htmlFor:"disable-all-notifications",className:"flex flex-col gap-1 text-base",children:["Wszystkie powiadomienia",Je("span",{className:"text-xs font-normal text-neutral-500 md:text-sm",children:"Ten przycisk mo\u017Ce wy\u0142\u0105czy\u0107 wszystkie powiadomienia"})]})]})})]})}var Tn=Yr;import{ChevronLeftIcon as ea,ChevronRightIcon as ta,MoreHorizontalIcon as na}from"lucide-react";import{jsx as ae,jsxs as Lt}from"react/jsx-runtime";function Ln({className:e,...t}){return ae("nav",{role:"navigation","aria-label":"pagination","data-slot":"pagination",className:x("mx-auto flex w-full justify-center",e),...t})}function Dn({className:e,...t}){return ae("ul",{"data-slot":"pagination-content",className:x("flex flex-row items-center gap-1",e),...t})}function Pe({...e}){return ae("li",{"data-slot":"pagination-item",...e})}function Oe({className:e,isActive:t,size:a="icon",...n}){return ae("a",{"aria-current":t?"page":void 0,"data-slot":"pagination-link","data-active":t,className:x(en({variant:t?"outline":"ghost",size:a}),e),...n})}function En({className:e,...t}){return Lt(Oe,{"aria-label":"Go to previous page",size:"default",className:x("gap-1 px-2.5 sm:pl-2.5",e),...t,children:[ae(ea,{}),ae("span",{className:"hidden sm:block",children:"Previous"})]})}function Un({className:e,...t}){return Lt(Oe,{"aria-label":"Go to next page",size:"default",className:x("gap-1 px-2.5 sm:pr-2.5",e),...t,children:[ae("span",{className:"hidden sm:block",children:"Next"}),ae(ta,{})]})}function Tt({className:e,...t}){return Lt("span",{"aria-hidden":!0,"data-slot":"pagination-ellipsis",className:x("flex size-9 items-center justify-center",e),...t,children:[ae(na,{className:"size-4"}),ae("span",{className:"sr-only",children:"More pages"})]})}import{useState as ra}from"react";import{Fragment as ca,jsx as C,jsxs as G}from"react/jsx-runtime";var aa=e=>new Date(e*1e3).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),oa=(e,t)=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100),ia={draft:"Szkic",unpaid:"Nieop\u0142acona",paid:"Op\u0142acona",overdue:"Zaleg\u0142a",cancelled:"Anulowana",completed:"Zako\u0144czone",processing:"Przetwarzane",refunded:"Zwr\xF3cone"},sa={draft:"text-neutral-400",unpaid:"text-yellow-500",paid:"text-green-600",overdue:"text-red-500",cancelled:"text-neutral-400 line-through",completed:"text-green-600",processing:"text-blue-500",refunded:"text-purple-500"};function la({openOrderDetails:e,projectID:t,accessToken:a}){let[n,r]=ra(0),o=20,{data:i,isFetching:l}=Te(_.publicApi.getOrders,{projectId:t,accessToken:a,offset:n,limit:o}),s=i?.orders??[],y=i?.totalCount??0,m=Math.floor(n/o)+1,N=Math.ceil(y/o),p=g=>{r(g)};return G(ca,{children:[C("h3",{className:"text-2xl",children:"Historia zam\xF3wie\u0144"}),C("p",{className:"text-sm text-neutral-500 dark:text-neutral-400",children:"Twoje zam\xF3wienia"}),l?C("div",{className:"mt-6 flex w-full flex-col gap-3",children:[...Array(5)].map((g,d)=>G("div",{className:"rounded-xl bg-white p-4 shadow-sm dark:bg-neutral-800",children:[G("div",{className:"flex items-center justify-between",children:[G("div",{className:"space-y-2",children:[C(Le,{className:"h-4 w-24"}),C(Le,{className:"h-3 w-32"})]}),G("div",{className:"space-y-2 text-right",children:[C(Le,{className:"ml-auto h-4 w-16"}),C(Le,{className:"ml-auto h-3 w-12"})]})]}),C("div",{className:"mt-3",children:C(Le,{className:"h-3 w-40"})})]},d))}):s.length===0?C("div",{className:"mt-6 text-sm text-neutral-400",children:"Brak zam\xF3wie\u0144."}):G("div",{children:[C("div",{className:"mt-6 flex w-full flex-col gap-3",children:s.map(g=>G("button",{onClick:()=>e(g.id),className:"block rounded-xl bg-white p-4 text-left shadow-sm transition-colors hover:bg-neutral-50 dark:bg-neutral-800 dark:hover:bg-neutral-700",children:[G("div",{className:"flex items-center justify-between",children:[G("div",{children:[G("p",{className:"font-medium",children:["Zam\xF3wienie #",g.id]}),C("p",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:g.customerName||"Klient"})]}),G("div",{className:"text-right",children:[C("p",{className:"font-semibold",children:oa(g.totalAmount,g.currency)}),C("p",{className:`text-xs font-medium ${sa[g.status]??"text-neutral-400"}`,children:ia[g.status]??g.status})]})]}),C("div",{className:"mt-2 flex items-center justify-between text-xs text-neutral-500 dark:text-neutral-400",children:G("span",{children:["Data:"," ",g.createdAt?aa(Number(g.createdAt.seconds)):"-"]})})]},g.id))}),N>1&&!l&&C("div",{className:"mt-4 flex justify-center",children:C(Ln,{children:G(Dn,{children:[m>1&&C(Pe,{children:C(En,{onClick:()=>p(n-o)})}),m>2&&C(Pe,{children:C(Oe,{onClick:()=>p(0),children:"1"})}),m>3&&C(Pe,{children:C(Tt,{})}),[m-1,m,m+1].filter(g=>g>0&&g<=N).map(g=>C(Pe,{children:C(Oe,{onClick:()=>p((g-1)*o),isActive:m===g,children:g})},g)),m<N-2&&C(Pe,{children:C(Tt,{})}),m<N&&C(Pe,{children:C(Oe,{onClick:()=>p((N-1)*o),children:N})}),m<N&&C(Pe,{children:C(Un,{onClick:()=>p(n+o)})})]})})})]})]})}var zn=la;import{useState as On}from"react";import{Fragment as pa,jsx as Q,jsxs as he}from"react/jsx-runtime";var Mn=e=>new Date(e*1e3).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),da={active:"Aktywny",cancelled:"Anulowany",paused:"Wstrzymany"},ua={active:"text-green-600",cancelled:"text-red-500",paused:"text-yellow-500"};function ma({projectID:e}){let[t,a]=On([]),[n,r]=On(!0);return he(pa,{children:[Q("h3",{className:"text-2xl",children:"Plany"}),Q("p",{className:"text-sm text-neutral-500",children:"Twoje aktywne subskrypcje"}),n?Q("div",{className:"mt-6 text-sm text-neutral-400",children:"\u0141adowanie..."}):t.length===0?Q("div",{className:"mt-6 text-sm text-neutral-400",children:"Brak aktywnych plan\xF3w."}):Q("div",{className:"mt-6 flex flex-col gap-4",children:t.map(o=>he("div",{className:"rounded-xl bg-white p-5 shadow-sm dark:bg-neutral-800",children:[he("div",{className:"flex items-start justify-between",children:[he("div",{children:[Q("p",{className:"font-semibold",children:o.tierName}),o.configName&&Q("p",{className:"text-sm text-neutral-500",children:o.configName})]}),Q("span",{className:`text-sm font-medium ${ua[o.status]??"text-neutral-500"}`,children:da[o.status]??o.status})]}),he("div",{className:"mt-3 grid grid-cols-2 gap-2 text-sm text-neutral-600 dark:text-neutral-400",children:[he("div",{children:[Q("span",{className:"font-medium",children:"Dzie\u0144 rozliczenia:"})," ",o.billingDay]}),he("div",{children:[Q("span",{className:"font-medium",children:"Data startu:"})," ",Mn(o.startDate)]}),o.endDate&&he("div",{children:[Q("span",{className:"font-medium",children:"Data zako\u0144czenia:"})," ",Mn(o.endDate)]})]})]},o.id))})]})}var jn=ma;import{useEffect as fa,useState as Dt}from"react";import{jsx as Y,jsxs as ba}from"react/jsx-runtime";function ga(e,t,a,n){typeof window>"u"||(t&&ze(a,n),window.location.href=e)}function ya({projectID:e,host:t,loginURL:a,screen:n,params:r,setParams:o,setActiveScreen:i}){let{status:l,exchangeError:s}=ln("PanelReturns"),y=sn(),m=l==="anonymous"&&(s==null||rn(s));fa(()=>{m&&ga(a,s!=null,e,t)},[m,a,s,e,t]);let[N,p]=Dt("orders"),[g,d]=Dt({items:[],note:""}),[k,c]=Dt();if(l==="anonymous"&&!m)return ba("div",{role:"alert",className:"flex flex-col items-start gap-3",children:[Y("p",{className:"text-sm",children:y(an(s))}),Y(I,{type:"button",onClick:()=>window.location.reload(),children:y("errorRetry")})]});if(l!=="authenticated")return Y(dn,{});let A=v=>{p(v),o({state:"returns",orderId:void 0,returnId:void 0}),i("returns")};if(n==="return-details"&&r.returnId)return Y(yn,{returnId:r.returnId,onBack:()=>A("myReturns")});if(N==="myReturns")return Y(gn,{onBack:()=>A("orders"),onSelectReturn:v=>{o({state:"return-details",returnId:v,orderId:void 0}),i("return-details")}});if(N==="result"&&k!=null)return Y(fn,{returnId:k,onContinue:()=>A("orders"),onOpenMyReturns:()=>A("myReturns")});if(r.orderId){let v=r.orderId;return N==="confirmation"?Y(pn,{orderId:v,items:g.items,note:g.note,onBack:()=>p("orders"),onSubmitted:E=>{c(E),d({items:[],note:""}),p("result"),o({orderId:void 0})}}):Y(mn,{orderId:v,initialItems:g.items.length>0?g.items:void 0,initialNote:g.note,onBack:()=>{d({items:[],note:""}),o({orderId:void 0})},onContinue:E=>{d(E),p("confirmation")}})}return Y(un,{showLogout:!1,onSelectOrder:v=>{d({items:[],note:""}),p("orders"),o({orderId:v})},onOpenMyReturns:()=>A("myReturns")})}function Et({accessToken:e,appearance:t,texts:a,...n}){return Y(cn,{projectID:n.projectID,host:n.host,appearance:t,texts:a,panelAccessToken:e,children:Y(ya,{...n})})}import{useState as La}from"react";import{jsx as wa}from"react/jsx-runtime";var Pa=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g,ha=e=>[...e.matchAll(Pa)].map(a=>({url:a[0],startIndex:a.index,endIndex:a.index+a[0].length-1})),va=(e,t)=>{let a="",n=0;t.sort((r,o)=>r.startIndex-o.startIndex);for(let{startIndex:r,endIndex:o,replacementText:i}of t)a+=e.slice(n,r),a+=i,n=o+1;return a+=e.slice(n),a},_n=e=>{let t=ha(e);return wa("p",{dangerouslySetInnerHTML:{__html:va(e,t.map(a=>(a.replacementText=`<a key=${a.url} href=${a.url} style="text-decoration: underline;" target="_blank">
2
- ${a.url}
3
- </a>`,a)))}})};import{fromJsonString as Da,toJsonString as Ea}from"@bufbuild/protobuf";import{useAutoAnimate as Ia}from"@formkit/auto-animate/react";import{ChevronLeft as Aa,Download as Jn}from"lucide-react";import{useEffect as Ut,useRef as Kn,useState as ve}from"react";import $n from"hls.js";import{Pause as xa,Play as ka}from"lucide-react";import{forwardRef as Ca,useEffect as st,useImperativeHandle as Na,useRef as Ke,useState as Me}from"react";function Fn(){typeof navigator>"u"||typeof navigator.mediaSession>"u"||(navigator.mediaSession.playbackState="playing")}function qn(){typeof navigator>"u"||typeof navigator.mediaSession>"u"||(navigator.mediaSession.playbackState="paused")}function Bn(e,t){typeof navigator>"u"||typeof navigator.mediaSession>"u"||e!=null&&isNaN(e)||t!=null&&isNaN(t)||navigator.mediaSession.setPositionState({playbackRate:1,duration:e,position:t})}function Gn(e){typeof navigator>"u"||typeof navigator.mediaSession>"u"||(navigator.mediaSession.metadata=new MediaMetadata({title:e.title,artwork:e.artwork?[{type:"image/png",src:e.artwork}]:void 0}),navigator.mediaSession.setActionHandler("play",t=>{e.action(t)}),navigator.mediaSession.setActionHandler("pause",t=>{e.action(t)}),navigator.mediaSession.setActionHandler("stop",t=>{e.action(t)}),navigator.mediaSession.setActionHandler("seekbackward",t=>{e.action(t)}),navigator.mediaSession.setActionHandler("seekforward",t=>{e.action(t)}),navigator.mediaSession.setActionHandler("seekto",t=>{e.action(t)}))}function Hn(){navigator.mediaSession.metadata=null}import{jsx as oe,jsxs as lt}from"react/jsx-runtime";var Sa=Ca(({chapters:e,styles:t,updateCurrentTime:a,setCurrentTimeHandler:n,title:r,imageURL:o,uniqueProductID:i,onChapterChange:l},s)=>{let y;(q=>(q[q.Playing=0]="Playing",q[q.Paused=1]="Paused"))(y||={});let[m,N]=Me(1);st(()=>{switch(m){case 0:Fn();break;case 1:qn();break}},[m]),Na(s,()=>({selectChapter:f=>{Be(f)}}));let[p,g]=Me(void 0),[d,k]=Me(void 0),c=Ke(null),A=Ke(void 0),v=Ke(void 0),E=Ke(null),S=Ke(null),[M,V]=Me(!0),[ee,Re]=Me(!1),[tt,U]=Me(!Ra());function F(f){f<10||localStorage.setItem(`__player__${i}_${S.current?.id}`,`${f}`)}function pe(){let f=localStorage.getItem(`__player__${i}_${S.current?.id}`);if(f!=null)try{let z=parseInt(f);return isNaN(z)||z<0?void 0:z}catch{return}}function te(){let f=localStorage.getItem(`__player__${i}_last_chapter`);if(f!=null)return f}function ne(f){localStorage.setItem(`__player__${i}_last_chapter`,f)}function Ie(f){localStorage.removeItem(`__player__${i}_${f}`)}function ft(){c.current!=null&&(c.current.onloadeddata=()=>{if(c.current!=null){if(c.current.readyState<2&&U(!0),c.current.readyState>=2&&U(!1),!ee){let f=pe();f!=null&&rt(f),Re(!0)}if(M){V(!1);try{fe()}catch(f){console.log("play error",f)}}}},c.current.onplay=()=>{},c.current.onseeked=()=>{},c.current.onseeking=()=>{},c.current.onpause=()=>{},c.current.onended=()=>{gt()},Gn({title:r??"",artwork:o,action:f=>{switch(f.action){case"play":fe();break;case"pause":qe();break;case"seekbackward":nt(-15);break;case"seekforward":nt(15);break;case"seekto":f.seekTime&&rt(f.seekTime);break;case"stop":qe();break;default:break}}}),P())}function gt(){if(e==null||e.length==0)return;let f=e.findIndex(q=>q.id==S.current?.id);f==-1||(Ie(e[f].id),f+1>=e.length)||Be(e[f+1])}function P(){se(),v.current==null&&(v.current=setTimeout(()=>{se(),v.current=void 0,P()},500))}function W(){v.current!=null&&clearTimeout(v.current)}function se(){c.current!=null&&(N(c.current.paused?1:0),k(c.current.duration),g(c.current.currentTime),F(c.current.currentTime),Bn(c.current.duration,c.current.currentTime),c.current.networkState===c.current.NETWORK_LOADING&&c.current.readyState<=c.current.HAVE_FUTURE_DATA?U(!0):U(!1),a&&a(c.current.currentTime))}function fe(){c.current?.play().then().catch(),se()}function qe(){c.current?.pause(),se()}function vr(){if(m===0){qe();return}fe()}function nt(f){if(c.current==null)return;let z=c.current.currentTime+f;if(z<0){c.current.currentTime=0;return}if(z>c.current.duration){c.current.currentTime=c.current.duration;return}c.current.currentTime+=f}function rt(f){if(c.current!=null){if(g(f),f<0){c.current.currentTime=0;return}if(f>c.current.duration){c.current.currentTime=c.current.duration;return}c.current.currentTime=f}}function wr(){c.current!=null&&(c.current.onplay=null,c.current.onseeked=null,c.current.onseeking=null,c.current.onpause=null,c.current.onended=null,c.current.src="",A.current?.destroy())}function Jt(f){if(f.length==0)return;let z=te();if(z==null){Be(f[0]);return}let q=f.find(Ae=>Ae.id==z);if(q==null){Be(f[0]);return}Be(q)}function Be(f){Re(!1),V(!0),S.current=f,xr(f.publicUrl),l?.(f),ne(f.id)}function xr(f){c.current!=null&&(c.current.canPlayType("application/vnd.apple.mpegurl")?c.current.src=f:$n.isSupported()&&(A.current==null&&(A.current=new $n,A.current?.attachMedia(c.current)),A.current?.loadSource(f)))}st(()=>{c.current!=null&&(ft(),Jt(e))},[c.current]),st(()=>{Jt(e)},[e]),st(()=>(n?.(rt),()=>{g(void 0),c.current?.pause(),wr(),Hn()}),[]);let Kt=f=>{let z=Math.floor(f/3600),q=Math.floor(f/60)%60,Ae=Math.floor(f%60),Cr=z>0?z<10?`0${z}:`:`${z}:`:"",Nr=Ae<10?`0${Ae}`:`${Ae}`;return isNaN(Ae)||isNaN(q)||isNaN(z)?"":`${Cr}${q}:${Nr}`},kr=f=>{let z=parseFloat(f.value)/parseFloat(f.max)*100;E.current.style.setProperty("--seek-before-width",z+"%");let q=d*z/100;rt(q)};return lt("div",{id:"audio-player-container",className:"flex flex-col",style:t,ref:E,children:[oe("video",{ref:c,className:"hidden",poster:o,title:r}),oe("input",{type:"range",min:"0",max:d!=null?Math.floor(d).toString():100,value:p??0,onChange:f=>kr(f.target),className:"w-full"}),lt("section",{className:"flex w-full items-center justify-between text-sm font-medium",children:[oe("span",{id:"current-time",children:Kt(p)}),oe("span",{id:"duration",children:Kt(d)})]}),lt("div",{className:"mt-6 flex items-center justify-center gap-x-12",children:[oe(I,{variant:"outline",onClick:()=>nt(-10),"aria-label":"Rewind 10 Seconds",children:"-10"}),lt(I,{variant:"outline",onClick:vr,"aria-label":"Play Or Pause",children:[m===1&&oe(ka,{className:"h-5 w-5"}),m===0&&oe(xa,{className:"h-5 w-5"})]}),oe(I,{variant:"outline",onClick:()=>nt(10),"aria-label":"Fast Forward 10 Seconds",children:"+10"})]}),tt&&oe("div",{className:"mt-2 flex w-full justify-center",children:oe(J,{})})]})});function Ra(){return navigator.userAgent.toLowerCase().indexOf("safari/")>-1}var Vn=Sa;import*as ct from"react";import{jsx as Wn}from"react/jsx-runtime";function Zn(){let[e,t]=ct.useState(13);return ct.useEffect(()=>{let a=setTimeout(()=>t(66),500);return()=>clearTimeout(a)},[]),Wn("div",{className:"w-[60%] h-2 bg-gray-200 rounded-full overflow-hidden",children:Wn("div",{className:"h-full bg-blue-600 transition-all duration-300",style:{width:`${e}%`}})})}import{Fragment as dt,jsx as h,jsxs as D}from"react/jsx-runtime";function me(e,...t){console.warn(e,...t)}function zt(e){console.error(e)}var Ta=({accessToken:e,product:t,styles:a,reveal:n})=>{let r=t.productType,o=Kn(null),[i]=Ia(),[l,s]=ve(null),{mutateAsync:y,isPending:m}=Z(_.publicApi.userPanelGetFileDetails),N=Kn(void 0),[p,g]=ve(null),[d,k]=ve(null),[c,A]=ve(!1),[v,E]=ve(!1),[S,M]=ve(null),{mutateAsync:V,isPending:ee}=Z(_.publicApi.userPanelGetAudiobookDetails),{mutateAsync:Re,isPending:tt}=Z(_.publicApi.userPanelGetAudiobookDetailsDownloadURLs),{mutateAsync:U}=Z(_.publicApi.userPanelGetCourseDetails),[F,pe]=ve(null),[te,ne]=ve(null);async function Ie(){try{let P=await y({accessId:t.accessId,accessToken:e});if(P.result.case==="success"){s(P.result.value.files);return}else me("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),me("Kod b\u0142\u0119du: ",P.result.value)}catch(P){me("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),zt("B\u0142\u0105d podczas pobierania danych:"+P)}}async function ft(){try{let P=await V({accessId:t.accessId,accessToken:e});if(P.result.case==="audiobook"){g(P.result.value);return}else me("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),me("Kod b\u0142\u0119du: ",P.result.value)}catch(P){me("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),zt("B\u0142\u0105d podczas pobierania danych:"+P)}}async function gt(){try{let P=await Re({accessId:t.accessId,accessToken:e,isBrowser:!0});if(P.result.case==="success"){k(P.result.value.audiobookDownloadDetails),A(P.result.value.isAvailableToDownloadInMobileApp===!0);return}else me("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),me("Kod b\u0142\u0119du: ",P.result.value)}catch(P){me("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),zt("B\u0142\u0105d podczas pobierania danych:"+P)}}return Ut(()=>{r===1&&(ft().then().catch(),gt().then().catch())},[]),Ut(()=>{if(r!==4)return;async function P(){E(!0),M(null);try{let W=await U({accessId:t.accessId,accessToken:e});W.result.case==="redirectUrl"?window.location.href=W.result.value:M("Wyst\u0105pi\u0142 b\u0142\u0105d, prosz\u0119 skontaktowa\u0107 si\u0119 z pomoc\u0105 techniczn\u0105.")}catch{M("Wyst\u0105pi\u0142 b\u0142\u0105d, prosz\u0119 skontaktowa\u0107 si\u0119 z pomoc\u0105 techniczn\u0105.")}finally{E(!1)}}P()},[]),Ut(()=>{if(p!=null&&d!=null){let P=p.chapters;if(!P)return;let W=P.map(se=>{let fe=d?.find(qe=>qe.chapterId===se.id);if(fe!=null)return{...se,publicUrl:fe.publicUrl,downloadableUrl:fe.downloadableUrl,duration:fe.duration}}).filter(se=>se!=null);W!=null&&W.length>0&&ne(W)}},[p,d]),D("div",{children:[h("div",{className:"mb-3 space-y-4 rounded bg-white p-4 dark:bg-black",children:D(I,{onClick:()=>n(),variant:"ghost",className:"w-fit",children:[h(Aa,{className:"h-6 w-6"}),h("span",{className:"font-inter text-sm font-medium",children:"Wr\xF3\u0107"})]})}),D("main",{className:"grid grid-cols-1 justify-center gap-6 sm:justify-start lg:grid-cols-2",children:[D("div",{className:"flex w-full max-w-xl flex-col gap-6",children:[r===2&&D("div",{ref:i,className:"flex flex-col space-y-4 rounded bg-white p-6 drop-shadow-xl dark:border dark:border-neutral-700 dark:bg-neutral-800 dark:drop-shadow-none",children:[D("div",{className:"flex items-center justify-between gap-x-4",children:[h("h4",{className:"text-xl font-semibold",children:"Twoje pliki"}),(l==null||l.length==0)&&h(I,{onClick:Ie,"aria-label":"Download Product",className:"text-sm font-medium transition-opacity duration-300 ease-in-out hover:opacity-80 active:opacity-80",style:a,children:m?h(J,{}):"Wy\u015Bwietl"})]}),m&&D("div",{className:"flex flex-col items-start gap-2",children:[h(Zn,{}),h("p",{className:"font-bold transition hover:text-blue-600",children:"Trwa przygotowanie plik\xF3w..."})]}),l!=null&&l.length>0&&h("div",{className:"flex flex-col items-start justify-start gap-2",children:l.map((P,W)=>D("a",{target:"_blank",className:"flex w-fit items-center gap-2 rounded-md bg-neutral-800 px-3 py-2 text-neutral-200 dark:bg-neutral-200 dark:text-neutral-800",href:P,download:!0,children:[`Plik numer ${W+1}`,h(Jn,{width:14,height:14})]},W))})]}),r===4&&D("div",{className:"flex flex-col items-center justify-center rounded-xl bg-white p-6 drop-shadow-xl dark:bg-neutral-900 dark:drop-shadow-none",children:[v&&D("div",{className:"flex flex-col items-center gap-3",children:[h(J,{}),h("p",{className:"text-lg font-semibold",children:"Trwa przekierowanie do kursu..."})]}),S&&h("p",{className:"text-center text-sm font-medium text-red-600 dark:text-red-400",children:S})]}),r===1&&h(dt,{children:D("div",{className:"flex flex-col space-y-6 rounded-xl bg-white p-3 drop-shadow-xl dark:bg-neutral-900 dark:drop-shadow-none",children:[h("h4",{className:"text-xl font-semibold",children:F?.name??"Odtwarzacz"}),F?.description&&h("p",{className:"text-sm",children:F?.description}),h(dt,{children:ee?D("div",{className:"flex gap-2",children:[h(J,{}),h("p",{className:"text-xl font-semibold",children:"Trwa pobierania audiobooka..."})]}):h(dt,{children:te!=null?h(dt,{children:h(Vn,{ref:o,chapters:te,title:p?.name??t.productName??void 0,imageURL:p?.coverImage??t.productImageUrl??void 0,styles:a,setCurrentTimeHandler:P=>{N.current=P},uniqueProductID:t.productId,onChapterChange:P=>{pe(P)}})}):h("p",{className:"mt-2",children:"Wybierz rozdzia\u0142, kt\xF3ry ci\u0119 interesuje."})})}),D("div",{className:"rounded-xl bg-neutral-100 p-3 dark:bg-neutral-800",children:[h("p",{className:"mt-3 mb-3 text-xs",children:c?"Mo\u017Cesz s\u0142ucha\u0107 tego audiobooka w aplikacji r\xF3wnie\u017C bez dost\u0119pu do internetu.":"Mo\u017Cesz s\u0142ucha\u0107 tego audiobooka w aplikacji."}),D("div",{className:"flex gap-3",children:[h("a",{href:"https://apps.apple.com/us/app/bitsnap/id6741902807",children:h("img",{width:"100",src:"https://bitsnap.pl/appstore.svg",alt:"Pobierz aplikacje z AppStore"})}),h("a",{href:"https://docs.bitsnap.pl/guides/audiobook",children:h("img",{width:"100",src:"https://bitsnap.pl/playstore.svg",alt:"Pobierz aplikacj\u0119 z GooglePlay"})})]})]})]})}),h("div",{className:"flex items-center justify-center rounded-xl bg-white p-3 drop-shadow-xl dark:bg-neutral-900 dark:drop-shadow-none",children:r===1&&h("div",{className:"max-h-96 w-full overflow-y-auto",children:ee?D("div",{className:"jusitfy-center flex flex-col items-center gap-2",children:[h(J,{}),h("p",{children:"\u0141adowanie rozdzia\u0142\xF3w..."})]}):D("div",{children:[h("h2",{className:"mb-3 text-xl font-semibold",children:"Rozdzia\u0142y"}),te==null?h("p",{children:"Brak rozdzia\u0142\xF3w do wy\u015Bwietlenia."}):h("ul",{className:"flex w-full flex-col gap-2",children:te.map((P,W)=>D("li",{className:"flex items-center justify-between",children:[D("button",{className:x("w-full rounded-lg p-2 text-left transition hover:bg-neutral-200 active:bg-neutral-200 dark:hover:bg-neutral-700 dark:active:bg-neutral-700",F?.id==P.id?"bg-neutral-200 dark:bg-neutral-700":"bg-neutral-100 dark:bg-neutral-800 dark:text-neutral-300"),onClick:()=>{o.current.selectChapter(P)},children:[D("div",{className:"flex items-center justify-between",children:[h("p",{className:"text-sm font-medium",children:P.name}),P.duration&&D("span",{className:"text-xs text-neutral-500",children:[Math.floor(P.duration/60),":",String(Math.floor(P.duration%60)).padStart(2,"0")]})]}),P.description&&h("p",{className:"mt-3 text-xs",children:P.description})]}),p&&p.isDownloadable&&P.downloadableUrl&&h("a",{href:P.downloadableUrl,children:h(Jn,{width:14,height:14})})]},W))})]})})})]}),D("div",{className:"w-full max-w-3xl space-y-6 rounded-xl bg-white p-6 drop-shadow-xl dark:bg-neutral-900 dark:drop-shadow-none",children:[h("h2",{className:"text-3xl font-semibold",children:t.productName}),h("p",{className:"text-sm font-normal text-neutral-600 dark:text-neutral-300",children:t.productDescription}),h("img",{src:t.productImageUrl,alt:"Product Photo",width:384,height:384,className:"max-h-sm max-w-sm",draggable:!1})]})]})]})},Qn=Ta;import{Fragment as Oa,jsx as B,jsxs as Qe}from"react/jsx-runtime";var Ua=({accessToken:e,projectID:t,loginURL:a,styles:n,activeScreen:r,params:o,setParams:i})=>{let{data:l,isLoading:s}=Te(_.publicApi.userPanelGetProducts,{accessToken:e});if(s)return Qe("div",{className:"flex items-center gap-2 bg-white p-2 dark:bg-black",children:[B("p",{className:"text-dark font-inter font-medium dark:text-white",children:"\u0141adowanie..."}),B(J,{})]});if(l&&l.result.case==="failure")return console.warn("error:",`Kod b\u0142\u0119du: ${l.result.value}`),ze(t),window.location.href=a,null;let y=l&&l.result.case==="success"?l.result.value.products:[];return B(za,{accessToken:e,products:y,styles:n,loginURL:a,activeScreen:r,params:o,setParams:i})},Yn=Ua,za=({accessToken:e,products:t,styles:a,loginURL:n,activeScreen:r,params:o,setParams:i})=>{if(t.length===0)return window.location.href=n,null;let[l,s]=La(o.product?Da(vt,o.product):void 0),y=p=>{p==null?(s(void 0),i({product:void 0,state:"products"})):i({product:Ea(vt,p),state:"products"})};function m(p){switch(p){case 1:return"Audio";case 2:return"Plik";case 3:return"Bilet";case 4:return"Kurs";default:return}}function N(p){s(p),y(p)}return r==="products"&&l!=null?B(Qn,{accessToken:e,product:l,styles:a,reveal:y}):Qe(Oa,{children:[B("h3",{className:"text-2xl",children:"Hej \u{1F44B}"}),B("p",{className:"text-sm text-neutral-500",children:"Poni\u017Cej znajdziesz swoje produkty"}),B("div",{className:"mt-6 flex flex-wrap items-center justify-center gap-9 sm:justify-start",children:t?.map((p,g)=>Qe("section",{onClick:()=>N(p),className:"w-full max-w-xs cursor-pointer rounded drop-shadow-xl dark:border dark:border-slate-600 dark:drop-shadow-none",children:[Qe("section",{className:"flex flex-col items-center space-y-2 rounded bg-slate-100 p-4 dark:bg-neutral-900",children:[p.productType&&B("div",{className:"w-fit self-end rounded bg-red-900 px-4 py-1",children:B("span",{className:"text-sm font-medium text-white dark:text-slate-100",children:m(p.productType)})}),B("div",{className:"jusitfy-center flex max-h-40 items-center",children:B("img",{src:p.productImageUrl,alt:`Product ${g} Photo`,draggable:!1,className:"aspect-auto max-h-40"})})]}),Qe("div",{className:"space-y-4 rounded bg-white p-4 dark:bg-black",children:[B("h2",{className:"text-xl font-semibold",children:p.productName}),B("p",{title:p.productDescription,className:"line-clamp-3 text-sm font-normal text-neutral-600 dark:text-neutral-300",children:_n(p.productDescription)}),B(I,{onClick:d=>{d.stopPropagation(),N(p)},className:"w-full text-sm font-medium transition-opacity duration-300 ease-in-out hover:opacity-80 active:opacity-80",style:a,children:"Zobacz"})]})]},g))})]})};import{useAutoAnimate as ja}from"@formkit/auto-animate/react";import{LogOut as _a,Undo2 as er}from"lucide-react";import{useState as Fa}from"react";var Ma={pl:{returnsNavLabel:"Zwroty"},en:{returnsNavLabel:"Returns"}};function Ot(e=le()){return on(Ma,e)}import{Fragment as nr,jsx as R,jsxs as ie}from"react/jsx-runtime";function qa({activeScreen:e,setActiveScreen:t,setParams:a,styles:n,theme:r,logout:o}){return ie("header",{className:"md:border-r-neutral-150 md:bg-beige-50 fixed right-0 bottom-0 left-0 z-10 flex h-12 w-full items-center bg-neutral-800 md:static md:z-0 md:min-h-screen md:w-auto md:border-r dark:md:border-r-neutral-900",children:[R(Ba,{activeScreen:e,setActiveScreen:t,setParams:a}),R(Ga,{activeScreen:e,setActiveScreen:t,setParams:a,theme:r,logout:o})]})}var tr=qa;function Ba({activeScreen:e,setActiveScreen:t,setParams:a}){let{returnsNavLabel:n}=Ot();return ie("nav",{className:"flex w-full items-center justify-evenly gap-4 md:hidden",children:[R(ut,{panelScreen:"products",label:"Produkty",imageURL:"/icons/bitsnap-24x24.svg",activeScreen:e,setActiveScreen:t,setParams:a}),R(ut,{panelScreen:"orders",label:"Faktury",imageURL:"/icons/category-24x24.svg",activeScreen:e,setActiveScreen:t,setParams:a}),R(ut,{panelScreen:"returns",label:n,icon:R(er,{className:"h-5 w-5 text-white","aria-hidden":!0}),activeScreen:e,setActiveScreen:t,setParams:a}),R(ut,{panelScreen:"profile",label:"Profil",imageURL:"/icons/profile-24x24.svg",activeScreen:e,setActiveScreen:t,setParams:a})]})}function ut({panelScreen:e,label:t,imageURL:a,icon:n,activeScreen:r,setActiveScreen:o,setParams:i}){return ie(I,{onClick:()=>{o(e),i({product:void 0,state:e})},"aria-label":t,variant:null,className:x("flex flex-col gap-0",r===e?"opacity-100":"opacity-50"),children:[n??R("img",{src:a,alt:t,className:"scale-75"}),R("span",{className:"text-xs font-normal text-white",children:t})]})}function mt({panelScreen:e,label:t,imageURL:a,darkImageURL:n,icon:r,activeScreen:o,setActiveScreen:i,setParams:l,isExpanded:s}){return ie(I,{onClick:()=>{i(e),l({product:void 0,state:e})},variant:o===e?"secondary":"ghost",className:"justify-start",children:[r!=null?R("span",{className:x("inline-flex h-5 w-5 items-center justify-center",s?"mr-4":"mr-2"),children:r}):ie(nr,{children:[R("img",{src:a,alt:t,className:x("aspect-auto h-5 w-5 dark:hidden",s?"mr-4":"mr-2")}),R("img",{src:n,alt:t,className:x("hidden aspect-auto h-5 w-5 dark:inline",s?"mr-4":"mr-2")})]}),s&&R("span",{className:"md:text-medium hidden md:inline",children:t})]})}function Ga({activeScreen:e,setActiveScreen:t,setParams:a,theme:n,logout:r}){let[o]=ja(),[i,l]=Fa(!0),{returnsNavLabel:s}=Ot();return ie("div",{ref:o,className:x("hidden px-4 pt-4 pb-12 md:flex md:h-full md:flex-col dark:bg-neutral-900",i?"md:w-52":"md:w-16"),children:[R("div",{className:"flex items-center justify-between",children:R(Ha,{theme:n,isExpanded:i})}),R(Xn,{className:"my-6"}),ie("div",{className:"flex flex-1 flex-col gap-2",children:[R(mt,{panelScreen:"products",label:"Produkty",imageURL:"/icons/bitsnap-dark-24x24.svg",darkImageURL:"/icons/bitsnap-24x24.svg",activeScreen:e,setActiveScreen:t,setParams:a,isExpanded:i}),R(mt,{panelScreen:"orders",label:"Zam\xF3wienia",imageURL:"/icons/category-dark-24x24.svg",darkImageURL:"/icons/category-24x24.svg",activeScreen:e,setActiveScreen:t,setParams:a,isExpanded:i}),R(mt,{panelScreen:"returns",label:s,icon:R(er,{className:"h-5 w-5","aria-hidden":!0}),activeScreen:e,setActiveScreen:t,setParams:a,isExpanded:i}),R(mt,{panelScreen:"profile",label:"Profil",imageURL:"/icons/profile-dark-24x24.svg",darkImageURL:"/icons/profile-24x24.svg",activeScreen:e,setActiveScreen:t,setParams:a,isExpanded:i})]}),R(Xn,{className:"mb-6"}),ie(I,{onClick:r,children:[R(_a,{className:"mr-2",width:16,height:16}),i&&R("p",{className:"md:text-medium hidden md:inline md:text-center",children:"Wyloguj si\u0119"})]})]})}function Xn({className:e}){return ie("div",{className:x("relative h-px w-full bg-neutral-300",e),children:[R("div",{className:"absolute -top-px left-0 h-1 w-1 rounded-full bg-neutral-500"}),R("div",{className:"absolute -top-px right-0 h-1 w-1 rounded-full bg-neutral-500"})]})}function Ha({theme:e,isExpanded:t}){return ie(nr,{children:[e==null&&R("p",{className:"text-xl tracking-wider md:inline dark:text-neutral-200",children:"bitsnap."}),(e?.logoDarkURL||e?.logoURL)&&R("img",{src:e.logoDarkURL??e.logoURL,alt:"Company Logo",className:"hidden h-6 w-6 dark:inline",draggable:!1}),e?.logoURL&&R("img",{src:e.logoURL,alt:"Company Logo",className:"h-6 w-6 dark:hidden",draggable:!1})]})}import{LogOut as $a}from"lucide-react";import{Fragment as Wa,jsx as je,jsxs as Mt}from"react/jsx-runtime";function Va({email:e,logout:t}){return Mt(Wa,{children:[je("h3",{className:"text-2xl",children:"Profil"}),Mt("div",{className:"mt-6 flex-1 md:flex-none",children:[je("span",{className:"text-sm text-neutral-500",children:"Email"}),je("p",{className:"mt-2 text-base",children:e||"Brak danych"})]}),je("div",{className:"flex w-full flex-col items-center space-y-2",children:Mt(I,{onClick:t,className:"max-w-64 md:hidden",children:[je($a,{className:"mr-2",width:16,height:16}),je("p",{className:"text-medium inline text-center",children:"Wyloguj si\u0119"})]})})]})}var rr=Va;import{AlertCircle as lr,CheckCircle2 as ar,ChevronLeft as Za,Loader2 as _t,Lock as or,Package as Ja,Truck as cr}from"lucide-react";import{useState as jt}from"react";import{Fragment as dr,jsx as u,jsxs as b}from"react/jsx-runtime";function Ka({status:e}){let t={created:{color:"bg-neutral-100 text-neutral-700",icon:null},paid:{color:"bg-green-100 text-green-700",icon:ar},completed:{color:"bg-blue-100 text-blue-700",icon:ar},canceled:{color:"bg-red-100 text-red-700",icon:lr},sent:{color:"bg-purple-100 text-purple-700",icon:cr},processing:{color:"bg-yellow-100 text-yellow-700",icon:_t}},a=t[e]||t.created,n=a.icon,r={created:"Utworzone",paid:"Op\u0142acone",completed:"Zako\u0144czone",canceled:"Anulowane",sent:"Wys\u0142ane",processing:"Przetwarzane"};return b("span",{className:`inline-flex items-center gap-1 rounded-full px-3 py-1 text-sm font-medium ${a.color}`,children:[n&&u(n,{className:"h-4 w-4"}),r[e]||e]})}function Qa({orderID:e,email:t}){let[a,n]=jt(""),r=Z(_.publicApi.addPublicOrderComment);return b("form",{onSubmit:async i=>{if(i.preventDefault(),!!a.trim())try{await r.mutateAsync({projectId:"",orderId:e,message:a.trim(),accessToken:t}),n("")}catch(l){console.error("Failed to add comment:",l)}},className:"mt-4 space-y-2",children:[u(Ne,{htmlFor:"comment",children:"Dodaj komentarz"}),u(nn,{id:"comment",value:a,onChange:i=>n(i.target.value),placeholder:"Wpisz komentarz...",rows:3,disabled:r.isPending}),u(I,{type:"submit",disabled:!a.trim()||r.isPending,children:r.isPending?b(dr,{children:[u(_t,{className:"mr-2 h-4 w-4 animate-spin"}),"Wysy\u0142anie..."]}):"Dodaj komentarz"})]})}function ir(e){return e?new Date(Number(e.seconds)*1e3).toLocaleDateString("pl-PL",{year:"numeric",month:"long",day:"numeric"}):"N/A"}function sr(e,t){return new Intl.NumberFormat("pl-PL",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function Ya({orderID:e,initialEmail:t,onBack:a,accessToken:n}){let{theme:r,projectID:o}=be(),[i,l]=jt(t||""),[s,y]=jt(!1),{data:m,isLoading:N,error:p,refetch:g}=Te(_.publicApi.getPublicOrderDetails,{projectId:o??"",orderId:e,email:i||void 0,accessToken:n},{enabled:!!e}),d=m?.result.case==="order"?m.result.value:null,k=d?.isVerified??!1,c=()=>{g(),y(!1)},A={"--button-background-color":r?.colors?.brand??"#000000","--button-background-color-dark":r?.colors?.brandDark??"#ffffff","--button-text-color":r?.colors?.brandDark??"#000000","--button-text-color-dark":r?.colors?.brand??"#000000"};return N?u("div",{className:"flex min-h-screen items-center justify-center",children:b("div",{className:"text-center",children:[u(_t,{className:"mx-auto h-8 w-8 animate-spin text-neutral-400"}),u("p",{className:"mt-2 text-neutral-600 dark:text-neutral-400",children:"\u0141adowanie zam\xF3wienia..."})]})}):p||!d?u("div",{className:"flex min-h-screen items-center justify-center",children:u(ce,{className:"w-full max-w-md",children:u(de,{className:"pt-6",children:b("div",{className:"text-center",children:[u(lr,{className:"mx-auto h-12 w-12 text-red-500"}),u("h2",{className:"mt-4 text-xl font-semibold",children:"Zam\xF3wienie nie znalezione"}),u("p",{className:"mt-2 text-neutral-600 dark:text-neutral-400",children:"Nie znaleziono zam\xF3wienia o podanym numerze."})]})})})}):u("div",{className:"w-full bg-white py-8 dark:bg-black",style:A,children:b("div",{className:"w-full px-4",children:[a&&b(I,{onClick:a,variant:"ghost",className:"mb-4 w-fit",children:[u(Za,{className:"h-4 w-4"}),"Wr\xF3\u0107 do historii zam\xF3wie\u0144"]}),b("div",{className:"mb-6 flex items-center gap-4",children:[r?.logoURL&&b(dr,{children:[u("img",{src:r.logoURL,alt:"Project logo",className:`h-12 w-auto ${r.logoDarkURL?"dark:hidden":""}`}),r.logoDarkURL&&u("img",{src:r.logoDarkURL,alt:"Project logo",className:"hidden h-12 w-auto dark:block"})]}),b("div",{children:[u("h1",{className:"text-3xl font-bold",children:"Zam\xF3wienie"}),b("p",{className:"text-neutral-600 dark:text-neutral-400",children:["Numer zam\xF3wienia: #",d.orderId]})]})]}),b(ce,{className:"mb-6",children:[u(ge,{children:b(ye,{className:"flex items-center",children:[u(Ja,{className:"mr-2 h-5 w-5"}),"Status zam\xF3wienia"]})}),b(de,{className:"space-y-6",children:[b("div",{children:[b("div",{className:"flex items-center gap-2",children:[u(Ka,{status:d.status}),d.processingStatus&&b("span",{className:"text-sm text-neutral-600",children:["\xB7 ",d.processingStatus]})]}),b("p",{className:"mt-2 text-sm text-neutral-600",children:["Zam\xF3wienie z\u0142o\u017Cone ",ir(d.createdAt)]})]}),b("div",{className:"border-t pt-4",children:[u("h3",{className:"mb-3 font-semibold",children:"Dane klienta"}),b("div",{className:"space-y-2",children:[b("div",{children:[u("span",{className:"font-medium",children:"Imi\u0119 i nazwisko:"})," ",u("span",{className:k?"":"text-neutral-500",children:d.customerName})]}),b("div",{children:[u("span",{className:"font-medium",children:"Email:"})," ",u("span",{className:k?"":"text-neutral-500",children:d.customerEmail})]}),d.customerPhone&&b("div",{children:[u("span",{className:"font-medium",children:"Telefon:"})," ",u("span",{className:k?"":"text-neutral-500",children:d.customerPhone})]})]})]}),!k&&u("div",{className:"border-t pt-4",children:b(I,{onClick:()=>y(!0),variant:"outline",className:"w-full",children:[u(or,{className:"mr-2 h-4 w-4"}),"Zweryfikuj sw\xF3j email"]})})]})]}),b(ce,{className:"mb-6",children:[u(ge,{children:u(ye,{children:"Produkty"})}),b(de,{className:"space-y-6",children:[u("div",{className:"space-y-4",children:d.items.map((v,E)=>b("div",{className:"flex items-center gap-4",children:[v.imageUrl&&u("img",{src:v.imageUrl,alt:v.name,className:"h-16 w-16 rounded object-cover"}),b("div",{className:"flex-1",children:[u("p",{className:"font-medium",children:v.name}),b("p",{className:"text-sm text-neutral-600",children:["Ilo\u015B\u0107: ",v.quantity]})]}),u("div",{className:"text-right",children:u("p",{className:"font-medium",children:sr(Number(v.price),v.currency)})})]},E))}),(d.deliveryAddress||d.deliveryMethod)&&b("div",{className:"border-t pt-4",children:[b("h3",{className:"mb-3 flex items-center font-semibold",children:[u(cr,{className:"mr-2 h-5 w-5"}),"Informacje o dostawie"]}),b("div",{className:"space-y-2",children:[d.deliveryAddress&&b("div",{children:[u("span",{className:"font-medium",children:"Adres:"})," ",u("span",{className:k?"":"text-neutral-500",children:d.deliveryAddress})]}),d.deliveryMethod&&b("div",{children:[u("span",{className:"font-medium",children:"Metoda:"})," ",d.deliveryMethod]}),d.trackingNumber&&k&&b("div",{children:[u("span",{className:"font-medium",children:"Tracking:"})," ",d.trackingNumber]})]})]}),u("div",{className:"border-t pt-4",children:b("div",{className:"flex justify-between text-lg font-bold",children:[u("span",{children:"Suma:"}),u("span",{children:sr(Number(d.totalAmount),d.currency)})]})})]})]}),b(ce,{children:[u(ge,{children:b(ye,{children:["Komentarze ",d.commentCount>0&&`(${d.commentCount})`]})}),b(de,{children:[d.comments.length>0?u("div",{className:"space-y-4",children:d.comments.map(v=>b("div",{className:"border-b pb-4 last:border-b-0",children:[b("div",{className:"mb-1 flex items-center gap-2",children:[u("span",{className:"font-medium",children:v.authorName||"System"}),u("span",{className:"text-xs text-neutral-500",children:ir(v.createdAt)}),v.authorType==="admin"&&u("span",{className:"rounded bg-blue-100 px-2 py-0.5 text-xs text-blue-700",children:"Admin"})]}),u("p",{className:k?"":"text-neutral-500",children:v.message})]},v.id))}):u("p",{className:"text-neutral-600",children:"Brak komentarzy."}),k?u(Qa,{orderID:d.orderId,email:i}):u("div",{className:"mt-4",children:b(I,{onClick:()=>y(!0),variant:"outline",className:"w-full",children:[u(or,{className:"mr-2 h-4 w-4"}),"Zweryfikuj sw\xF3j email"]})})]})]}),s&&u("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:b(ce,{className:"w-full max-w-md",children:[u(ge,{children:u(ye,{children:"Zweryfikuj sw\xF3j email"})}),b(de,{className:"space-y-4",children:[u("p",{className:"text-sm text-neutral-700",children:"Podaj adres email u\u017Cyty przy sk\u0142adaniu zam\xF3wienia."}),b("div",{className:"space-y-2",children:[u(Ne,{htmlFor:"verify-email",children:"Adres email"}),u(at,{id:"verify-email",type:"email",placeholder:"twoj@email.com",value:i,onChange:v=>l(v.target.value)})]}),b("div",{className:"flex gap-2",children:[u(I,{variant:"outline",onClick:()=>y(!1),className:"flex-1",children:"Anuluj"}),u(I,{onClick:c,className:"flex-1",children:"Zweryfikuj"})]})]})]})})]})})}function Xa(e){return u(Ya,{...e})}var Ft=Xa;import{jsx as we,jsxs as ur}from"react/jsx-runtime";var no=({returnsAppearance:e,returnsTexts:t}={})=>{let{projectID:a,theme:n,loginURL:r,host:o}=be(),i=Ze(a,o),l=Cn(a,o),{mutateAsync:s}=Z(_.publicApi.userPanelLogout);async function y(){i&&await s({accessToken:i}),typeof window<"u"&&(ze(a,o),window.location.reload())}let[m]=eo(),N=S=>["products","notifications","profile","plans","orders","order-details","returns","return-details"].includes(S),[p,g]=Sn({product:void 0,state:"products",orderId:void 0,returnId:void 0}),[d,k]=to(N(p.state)?p.state:"products"),c=S=>{g({state:"order-details",orderId:S}),k("order-details")},A=()=>{g({state:"orders",orderId:void 0}),k("orders")},v=S=>g({orderId:void 0,returnId:void 0,...S}),E={"--button-background-color":n?.colors?.brand??"#000000","--button-background-color-dark":n?.colors?.brandDark??"#ffffff","--button-text-color":n?.colors?.brandDark??"#000000","--button-text-color-dark":n?.colors?.brand??"#000000"};return qt(()=>{if(i==null||i.length===0){window.location.href=r??"/panel/login";return}},[]),qt(()=>{if(i==null||i.length===0){window.location.href=r??"/panel/login";return}},[d]),qt(()=>{if(typeof window>"u"||window.parent!==window||!i)return;let S=Ve(window.location.search);S&&We(S);let M=S??Ee();M&&(window.location.href=Ue(M,i))},[i]),ur("div",{ref:m,className:"font-inter relative min-h-screen w-screen bg-beige-100 text-black dark:bg-black dark:text-white md:flex",children:[we(tr,{activeScreen:d,setActiveScreen:k,setParams:v,styles:E,theme:n,logout:y}),ur("main",{className:"flex h-[calc(100vh-80px)] flex-col overflow-y-auto w-full p-5 md:h-screen",children:[d==="products"&&we(Yn,{projectID:a??"",accessToken:i,loginURL:r??"/panel/login",styles:E,activeScreen:d,params:p,setParams:g}),d==="notifications"&&we(Tn,{}),d==="plans"&&we(jn,{projectID:a??""}),d==="orders"&&we(zn,{projectID:a??"",accessToken:i??"",openOrderDetails:c}),d==="order-details"&&p.orderId&&we(Ft,{orderID:p.orderId,onBack:A}),(d==="returns"||d==="return-details")&&i&&we(Et,{projectID:a??"",host:o,accessToken:i,loginURL:r??"/panel/login",appearance:Rn(e,n?.colors?.brand),texts:t,screen:d,params:p,setParams:g,setActiveScreen:k}),d==="profile"&&we(rr,{email:l,logout:y})]})]})},ro=no;import{create as Ce}from"@bufbuild/protobuf";import{QueryClient as fo,QueryClientProvider as go}from"@tanstack/react-query";import{createContext as yo,useContext as bo,useEffect as Po}from"react";import{createClient as ao}from"@connectrpc/connect";import{createConnectTransport as oo}from"@connectrpc/connect-web";var xe;(n=>{function e(r){return ao(Qt,a(r))}n.get=e;let t=new Map;function a(r){let o=t.get(r);return o==null&&(o=oo({useBinaryFormat:!0,baseUrl:r+"/api/rpc"}),t.set(r,o)),o}})(xe||={});import T from"zod";import H from"zod";function j(e,t=2){return+(Math.round(+(e+"e+"+t))+"e-"+t)}function mr(e,t){let a=typeof navigator>"u"?"pl-PL":navigator.language;return Intl.NumberFormat(a,{style:"currency",currency:t,currencyDisplay:"symbol"}).format(e/100)}var jl=H.object({event:H.enum(["purchase","addToCart","customizeProduct","viewCart","removeFromCart","initiateCheckout","lead"]),step:H.string().optional(),value:H.number().optional(),currency:H.string().optional(),content_name:H.string().optional(),items:H.array(H.object({id:H.string(),name:H.string(),price:H.number().default(0),currency:H.string().default("PLN"),quantity:H.number().default(1)})).optional()});function Bt(e){typeof window>"u"||(io(e),lo(e),co(e))}function io(e){try{typeof window.dataLayer>"u"&&(window.dataLayer=[]);let t=so(e);window.dataLayer.push(t)}catch(t){console.warn("cannot send google analytics event",t)}}function so(e){let t=e.value??e.items?.reduce((o,i)=>o+(i.price||0)*(i.quantity||1),0)??0,a=e.items?.map(o=>({item_id:o.id,item_name:o.name||o.id,price:j((o.price||0)/100,2),quantity:o.quantity||1})),n={currency:e.currency||"PLN",value:j(t/100,2)};a&&a.length>0&&(n.items=a);let r;switch(e.event){case"purchase":r="purchase",n.transaction_id=e.step||`txn_${Date.now()}`;break;case"addToCart":r="add_to_cart";break;case"viewCart":r="view_cart";break;case"removeFromCart":r="remove_from_cart";break;case"initiateCheckout":r="begin_checkout";break;case"customizeProduct":r="customize_product";break;default:r=e.event}return{event:r,ecommerce:n,...e.step&&{step:e.step},...e.content_name&&{content_name:e.content_name}}}function lo(e){if(typeof window.fbq>"u")return;let t="",a="",n={};switch(e.event){case"purchase":t="track",a="Purchase",n={category_name:e.step,...e};break;case"lead":t="track",a="Lead",n={category_name:e.step,...e};break;case"addToCart":t="track",a="Add to Cart",n={category_name:e.step,...e};break;case"customizeProduct":t="track",a="Customize Product",n={category_name:e.step,...e};break;case"viewCart":t="track",a="View Cart",n={category_name:e.step,...e};break;case"removeFromCart":t="track",a="Remove from Cart",n={category_name:e.step,...e};break;case"initiateCheckout":t="track",a="Initiate Checkout",n={category_name:e.step,...e};break;default:break}window.location.search.includes("analytics")&&console.log("Pushing FB event",t,a,n),window.fbq(t,a,n)}function co(e){try{if(typeof window.ttq>"u")return;let t=uo(e);if(!t)return;window.location.search.includes("analytics")&&console.log("Pushing TikTok event",t.eventName,t.eventPayload),window.ttq.track(t.eventName,t.eventPayload)}catch(t){console.warn("cannot send tiktok analytics event",t)}}function uo(e){let t=e.value??e.items?.reduce((o,i)=>o+(i.price||0)*(i.quantity||1),0)??0,a=e.items?.map(o=>({content_id:o.id,content_type:"product",content_name:o.name||o.id,quantity:o.quantity||1,price:j((o.price||0)/100,2)}))||[];a.length===0&&e.content_name&&a.push({content_id:e.step||"unknown",content_type:"product",content_name:e.content_name,quantity:1,price:j(t/100,2)});let n={currency:e.currency||"PLN",value:j(t/100,2)};a.length>0&&(n.contents=a);let r=null;switch(e.event){case"purchase":r="Purchase";break;case"addToCart":r="AddToCart";break;case"initiateCheckout":r="InitiateCheckout";break;case"customizeProduct":r="CustomizeProduct";break;case"viewCart":return;case"removeFromCart":return;case"lead":return;default:return null}return{eventName:r,eventPayload:n}}function pr(e){let{items:t,googlePayConfig:a,checkout:n,result:r,cartRequiresShipping:o}=e;if(r.totalAmount==null)return;let i=[];return o&&(i.push("SHIPPING_ADDRESS"),i.push("SHIPPING_OPTION")),{apiVersion:2,apiVersionMinor:0,callbackIntents:i,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["MASTERCARD","VISA"]},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:a.gateway,gatewayMerchantId:a.gatewayId}}}],emailRequired:!0,shippingAddressParameters:{phoneNumberRequired:o},shippingAddressRequired:o,shippingOptionRequired:o,shippingOptionParameters:o?{shippingOptions:r.methods.slice(0,5).map(s=>({id:s.id,label:s.name+` - ${mr(s.amount,r.currency)}`,description:s.description??""})),defaultSelectedOptionId:r.selectedDeliveryMethod}:void 0,merchantInfo:{merchantId:a.merchantId+"",merchantName:a.merchantName},transactionInfo:{totalPriceStatus:"FINAL",totalPriceLabel:"P\u0142atno\u015B\u0107 za koszyk",totalPrice:`${j(r.totalAmount/100,2)}`,currencyCode:r.currency,countryCode:r.country,checkoutOption:"COMPLETE_IMMEDIATE_PURCHASE",displayItems:mo(t,r.methods,r.selectedDeliveryMethod??(r.methods.length>0?r.methods[0].id:void 0),n.couponCode,r.couponValue)}}}function mo(e,t,a,n,r){let o=[],i=0;for(let s of e)s.details!=null&&(i+=s.details.price*s.quantity,o.push({label:s.details.name+" x "+s.quantity,price:`${j(s.details.price/100,2)}`,type:"LINE_ITEM",status:"FINAL"}));let l=t.find(s=>s.id===a);return l!=null&&o.push({label:l.name,price:`${j(l.amount/100,2)}`,type:"SHIPPING_OPTION",status:"FINAL"}),n!=null&&r!=null&&o.push({label:`Kupon ${n}`,price:`${j(r/100,2)}`,type:"DISCOUNT",status:"FINAL"}),i>0&&o.push({label:"Subtotal",price:`${j(i/100,2)}`,type:"SUBTOTAL",status:"FINAL"}),o}function Ye(e,t){return`${K}/api/integrations/${e}/public-commerce${t}`}function ke(e){return typeof e=="object"&&e!=null&&"ERR"in e}function $(e,t,a){return{ERR:!0,error:e,type:t,data:a}}function fr(e,t){return t?.find(a=>a.id===e||(a.variants?.some(n=>n.id===e)??!1))}function gr(e,t){let a=new Set(t.map(n=>n.productID));return Array.from(new Set(e.filter(n=>!a.has(n))))}import{create as po}from"zustand";var _e=po(e=>({isCartVisible:!1,numberOfProductsInCart:0,showCart:()=>e(t=>({...t,isCartVisible:!0})),hideCart:()=>e(t=>({...t,isCartVisible:!1})),setNumberOfProductsInCart:t=>e(a=>({...a,numberOfProductsInCart:t}))}));import{Fragment as Ro,jsx as Gt}from"react/jsx-runtime";var ho="__m_a",Pr=yo(void 0),$t=void 0;function fc(e){Ct({projectID:e}),$t=e,typeof window<"u"&&He([window.location.origin])}function et(){return $t??document.querySelector('script[data-id][data-name="internal-cart"]')?.getAttribute("data-id")??void 0}function vo(){return document.querySelector('script[data-id][data-name="internal-cart"]')?.getAttribute("data-custom-host")??void 0}var wo=({children:e,locale:t})=>{let a=new fo;Po(()=>{Xe()},[]);let n=et();if(n==null)return Gt(Ro,{});let r=Zt(n,t);return Gt(go,{client:a,children:Gt(Pr.Provider,{value:r,children:e})})},Fe=async(e,t)=>{let a=[];t?.items!=null&&t.items.length>0?a=t.items:a=O()?.products??[];let n=Array.from(new Set(a.map(l=>l.productID))),r=new URLSearchParams;r.set("ids",n.join(",")),r.set("locale",t?.locale??le());let o=await fetch(Ye(e,`/products?${r.toString()}`),{method:"GET"});if(o.status!=200)return[];let i=await o.json();return a.flatMap(l=>{let s=fr(l.productID,i.result);return s==null?[]:[{...l,details:So(l.productID,s)}]})},gc=()=>{let e=bo(Pr);if(e===void 0)throw new Error("useCartProvider must be used within a CartProvider");return e},yc=wo,xo=T.object({isAvailable:T.boolean(),merchantId:T.string(),merchantName:T.string(),gateway:T.string(),gatewayId:T.string()}),ko=T.object({id:T.string(),productID:T.string(),quantity:T.number(),priceVersion:T.string().optional(),metadata:T.record(T.string(),T.string().optional()).optional()}),Co=T.object({country:T.string().optional(),couponCode:T.string().optional(),selectedDeliveryMethod:T.string().optional(),postalCode:T.string().optional(),email:T.string().optional(),products:T.array(ko).optional(),googlePayConfig:xo.optional()}),Vt={country:void 0,couponCode:void 0,email:void 0,selectedDeliveryMethod:void 0,postalCode:void 0,products:[],googlePayConfig:void 0},hr="checkout";function O(){try{let e=localStorage.getItem(hr);return e==null?Vt:Co.parse(JSON.parse(e))}catch{return Vt}}async function yr(e,t){let a=await Fe(e,{items:t.map((o,i)=>({...o,id:`price-check-${i}`}))});if(ke(a))return a;let n=gr(t.map(o=>o.productID),a);if(n.length>0)return $("item-ids-not-found","notFound",n);let r=O();r.products==null&&(r.products=[]),r.products.push(...t.map(o=>({id:Math.random().toString(36).substring(7),productID:o.productID,quantity:o.quantity,priceVersion:a.find(i=>i.productID===o.productID)?.details?.pricing?.priceVersion,metadata:o.metadata}))),Bt({event:"addToCart",currency:"PLN",items:t.map(o=>({id:o.productID,name:o.name??"",price:o.price??0,quantity:o.quantity,currency:o.currency??"PLN"}))}),X(r),Xe()}function br(e){let t=O(),a={...t,products:t?.products?.filter(n=>!e.includes(n.productID)&&!e.includes(n.id))};Bt({event:"removeFromCart",items:e.map(n=>({id:n,name:"",price:0,quantity:1,currency:"PLN"}))}),X(a),Xe()}function X(e){localStorage.setItem(hr,JSON.stringify(e))}var Zt=(e,t=le())=>{let a=vo();return a!=null&&Yt(a),{async checkIfApplePayIsAvailable(){if(typeof window>"u"||typeof document>"u"||!("ApplePaySession"in window))return!1;try{return(await xe.get(K).isOneClickPaymentAvailable({projectId:e})).applePay}catch(n){return console.error("Error checking if Apple Pay is available",n),!1}},async getGooglePayConfiguration(n){if(typeof window>"u"||typeof document>"u")return{isAvailable:!1};try{let r=await No(e);if(r?.isAvailable!=!0)return{isAvailable:!1};let o=O();if(o==null)return console.log("checkout is null"),{isAvailable:!1};let i=await Fe(e,{locale:t,items:n.items.map(m=>({id:Math.random().toString(36).substring(7),quantity:m.quantity,metadata:m.metadata,productID:m.productID}))});if(ke(i))return{isAvailable:!1};let l=await xe.get(K).getPreOrderDetails({items:i.map(m=>Ce(Pt,{id:m.productID,quantity:m.quantity})),projectId:e,postCode:o.postalCode,couponCode:o.couponCode,countryCode:o.country,selectedDeliveryMethod:o.selectedDeliveryMethod});if(l.totalAmount==null)return{isAvailable:!1};let s=i.find(m=>m.details?.isDeliverable==!0)!=null,y=await pr({items:i,googlePayConfig:r,checkout:o,cartRequiresShipping:s,result:l});return y==null?{isAvailable:!1}:{isAvailable:!0,config:y}}catch(r){return console.error("Error resolving Google Pay configuration",r),{isAvailable:!1}}},async clearCart(){let n=structuredClone(Vt);n.country=O()?.country,X(n),Xe()},async getAvailableCountries(){let n=await fetch(Ye(e,"/countries"),{method:"GET"});if(n.status!=200)return[];try{return T.array(T.object({name:T.string(),code:T.string()})).parse(await n.json())}catch(r){return $(r.toString(),"internal")}},async getCountry(){let n=O()?.country;if(n==null){n="PL";let r=O();r.country=n,X(r)}return n},async getNumberOfElementsInCart(){return O()?.products?.reduce((n,r)=>n+r.quantity,0)??0},async getProducts(){return await Fe(e,{locale:t})},async removeProductFromCart(n){return br([n.id])},async setCountry(n){let r=O();r.country=n,X(r)},async setCouponCodeIfPossible(n){let r=O();r.couponCode=n,X(r)},async setPostalCode(n){let r=O();r.postalCode=n,X(r)},async setDeliveryMethod(n){let r=O();r.selectedDeliveryMethod=n,X(r)},async setEmail(n){let r=O();r.email=n,X(r)},async addProduct(n){return await yr(e,[n])},async updateQuantity(n){let r=O();r.products=r.products?.map(o=>(o.id===n.id&&(o.quantity=n.quantity),o)),X(r),Xe()},async redirectToNextStep(){let n=O();if(n.products==null||n.products.length==0)return $("cart-is-empty","badInput");let r=n.products.reduce((l,s)=>(s.metadata!=null&&Object.keys(s.metadata).forEach(y=>{let m=s.metadata?.[y];m!=null&&(l[y]=m)}),l),{}),o={items:n.products.map(l=>({id:l.productID,quantity:l.quantity,priceVersion:l.priceVersion})),askForNote:!0,countries:n.country?[n.country]:void 0,metadata:r,locale:t},i=await Ht(o);return ke(i)?(console.warn("cannot create payment URL",i.error),i):{url:i.url}},async justRedirectToPayment(n){let r={items:[{id:n.productID,quantity:1}],askForNote:!1,details:n.email||n.name?{name:n.name,email:n.email}:void 0,locale:n.locale??t};r=Wt(r),n.country==null&&(n.country="pl"),r.details==null&&(r.details={}),r.details.address==null&&(r.details.address={}),r.details.address.country=n.country,n.marketingAgreement===!0&&(r.additionalAgreements=[{id:ho,name:"",required:!0,answer:!0}]);let o=await Ht(r);return ke(o)?o:{url:o.url}},async completeApplePayPayment(n){let r=O();if(r==null)return $("Checkout not found");let o=await Fe(e,{locale:t});if(ke(o))return o;try{let i=n.shippingContact?.givenName;n.shippingContact?.familyName!=null?i+=" "+n.shippingContact?.familyName:n.billingContact?.familyName!=null&&(i+=" "+n.billingContact?.familyName);let l={},s=pt();s!=null&&(l.ref=s);let y=await xe.get(K).authorizeOneClickPayment({gateway:0,paymentData:JSON.stringify(n.token.paymentData),paymentMethod:JSON.stringify(n.token.paymentMethod),transactionIdentifier:n.token.transactionIdentifier,order:Ce(ht,{items:o.map(m=>({id:m.productID,quantity:m.quantity})),couponCode:r.couponCode,email:n.shippingContact?.emailAddress??n.billingContact?.emailAddress??r.email??void 0,phone:n.shippingContact?.phoneNumber??n.billingContact?.phoneNumber??void 0,selectedDeliveryMethod:r.selectedDeliveryMethod,postCode:r.postalCode,projectId:e}),shippingAddress:Ce(yt,{line1:n.shippingContact?.addressLines?.[0]??"",city:n.shippingContact?.locality??"",country:n.shippingContact?.countryCode??"",zipCode:n.shippingContact?.postalCode??"",name:i}),billingAddress:Ce(bt,{name:n.billingContact?.givenName??" "+(n.billingContact?.familyName??""),line1:n.billingContact?.addressLines?.[0]??"",city:n.billingContact?.locality??"",country:n.billingContact?.countryCode??"",zipCode:n.billingContact?.postalCode??""}),metadata:Object.keys(l).length>0?JSON.stringify(l):void 0});return{isSuccess:y.isSuccess,redirectURL:y.redirectUrl}}catch(i){return console.error(i),$("Failed to authorize payment")}},async completeGooglePayPayment(n){let r=O();if(r==null)return $("Checkout not found");let o=await Fe(e,{locale:t});if(ke(o))return o;try{let i=n.paymentData.shippingAddress?.name,l={},s=pt();s!=null&&(l.ref=s);let y=await xe.get(K).authorizeOneClickPayment({gateway:1,paymentData:n.paymentData.paymentMethodData.tokenizationData.token,paymentMethod:n.paymentData.paymentMethodData.type,transactionIdentifier:"",order:Ce(ht,{items:o.map(m=>({id:m.productID,quantity:m.quantity})),couponCode:r.couponCode,email:n.paymentData.email??void 0,phone:n.paymentData.shippingAddress?.phoneNumber??void 0,selectedDeliveryMethod:n.paymentData.shippingOptionData?.id??r.selectedDeliveryMethod,postCode:n.paymentData.shippingAddress?.postalCode,projectId:e}),shippingAddress:Ce(yt,{line1:n.paymentData.shippingAddress?.address1??"",city:n.paymentData.shippingAddress?.locality??"",country:n.paymentData.shippingAddress?.countryCode??"",zipCode:n.paymentData.shippingAddress?.postalCode??"",name:i}),billingAddress:Ce(bt,{name:n.paymentData.paymentMethodData.info?.billingAddress?.name,line1:n.paymentData.paymentMethodData.info?.billingAddress?.address1??"",city:n.paymentData.paymentMethodData.info?.billingAddress?.locality??"",country:n.paymentData.paymentMethodData.info?.billingAddress?.countryCode??"",zipCode:n.paymentData.paymentMethodData.info?.billingAddress?.postalCode??""}),metadata:Object.keys(l).length>0?JSON.stringify(l):void 0});return{isSuccess:y.isSuccess,redirectURL:y.redirectUrl}}catch(i){return console.error(i),$("Failed to authorize payment")}return{isSuccess:!0}},async getApplePayPaymentRequest(n){let r=O();if(r==null)return $("Checkout not found");n&&n.expectedItems!=null&&n.expectedItems.length>0&&(r.products&&br(r.products.map(s=>s.productID)),await yr(e,n.expectedItems));let o=await Fe(e,{locale:t});if(ke(o))return o;let i=await xe.get(K).getPreOrderDetails({items:o.map(s=>Ce(Pt,{id:s.productID,quantity:s.quantity})),projectId:e,postCode:r.postalCode,couponCode:r.couponCode,countryCode:r.country,selectedDeliveryMethod:r.selectedDeliveryMethod}),l=o.map(s=>({amount:`${j(s.quantity*(s.details?.price??0)/100,2)}`,label:s.details?.name+" - "+s.quantity,type:"final"}));if(i.selectedDeliveryMethod!=null){let s=i.methods.find(y=>y.id==i.selectedDeliveryMethod);s!=null&&l.push({amount:`${j(s.amount/100,2)}`,label:s.name,type:"final"})}return i.couponCode!=null&&i.couponValue!=null&&l.push({amount:`-${j(i.couponValue/100,2)}`,label:i.couponCode,type:"final"}),{countryCode:r.country??"PL",merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],supportedNetworks:["visa","masterCard"],total:{amount:`${j((i.totalAmount??0)/100,2)}`,label:"P\u0142atno\u015B\u0107 za koszyk",type:"final"},shippingMethods:i.methods.map(s=>({amount:`${j(s.amount/100,2)}`,detail:s.description??"",identifier:s.id,label:s.name,dateComponentsRange:{startDateComponents:{days:s.minDays??1,hours:0,months:0,years:0},endDateComponents:{days:s.maxDays??14,hours:0,months:0,years:0}}})),lineItems:l,currencyCode:"PLN"}}}};async function No(e){let t=O();if(t.googlePayConfig?.isAvailable!=!0){let a=await xe.get(K).isOneClickPaymentAvailable({projectId:e});a.googlePay==!0&&a.googlePayConfig!=null?t.googlePayConfig={isAvailable:!0,gateway:a.googlePayConfig.gateway,gatewayId:a.googlePayConfig.gatewayMerchantId,merchantName:a.googlePayConfig.merchantName,merchantId:a.googlePayConfig.merchantId}:t.googlePayConfig={isAvailable:!1,gateway:"",gatewayId:"",merchantName:"",merchantId:""}}return X(t),t.googlePayConfig}function So(e,t){if(e==t.id){let n=t.variants?.findIndex(r=>r.id===e);if(n!=null&&n!=-1){let r=t.variants[n];return{...t,availableQuantity:r.availableQuantity,isDeliverable:r.isDeliverable,images:r.images??t.images,name:t.name+" "+r.name,price:r.price,currency:r.currency,pricing:r.pricing}}return t}let a=t.variants?.find(n=>n.id===e);return a==null?t:{...t,id:a.id,name:t.name+" "+a.name,price:a.price,currency:a.currency,pricing:a.pricing,metadata:t.metadata,availableQuantity:a.availableQuantity,isDeliverable:a.isDeliverable,images:a.images??t.images}}function Xe(){let e=O(),t=0;if(e==null){_e.setState(a=>({...a,numberOfProductsInCart:t}));return}t=e.products?.reduce((a,n)=>a+n.quantity,0)??0,_e.setState(a=>({...a,numberOfProductsInCart:t}))}var Io;(n=>{async function e(r,o=1,i,l){let s=et();if(s==null)throw new Error("No project ID found");let m=await Zt(s).addProduct({productID:r,quantity:o,metadata:i,...l});if(m!=null)return m}n.addProductToCart=e;function t(){_e.setState({isCartVisible:!0})}n.showCart=t;function a(){_e.setState({isCartVisible:!1})}n.hideCart=a})(Io||={});async function Ht(e){let t=et();if(t==null)throw new Error("No project ID found");e=Wt(e),e.locale??=le();let a=await fetch(Ye(t,"/buy"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(a.status!=200){if(a.headers.get("Content-Type")?.includes("application/json")){try{let r=await a.json();if("itemIds"in r&&Array.isArray(r.itemIds)){let o=r.itemIds;return $("item-ids-not-found","badInput",o)}}catch{}return $("internal-error","internal")}else console.warn("result",await a.text(),a.status,a.statusText);return $("internal-error","internal")}return{url:(await a.json()).url}}async function Nc(e){let t=et();if(t==null)throw new Error("No project ID found");let a={"Content-Type":"application/json",...e.apiKey!=null?{Authorization:`Bearer ${e.apiKey}`}:{}},n=e.testMode?`/api/payment/link/auto/${t}/test`:`/api/payment/link/auto/${t}`;return delete e.apiKey,delete e.testMode,e.locale??=le(),{status:"ok",redirectURL:(await(await fetch(K+n,{method:"POST",headers:a,body:JSON.stringify(e)})).json()).url}}function pt(){if(typeof localStorage>"u")return;let e=localStorage.getItem("bitsnap-ref");if(e!=null)return e}function Wt(e){let t=pt();return t==null||(e.metadata==null&&(e.metadata={}),e.metadata.ref=t),e}export{xe as a,ce as b,ge as c,ye as d,wt as e,de as f,Pn as g,xt as h,Se as i,Ct as j,ot as k,Dr as l,Er as m,Ur as n,zr as o,He as p,$e as q,jr as r,be as s,Ve as t,We as u,Ee as v,Ue as w,Wr as x,An as y,Ft as z,ro as A,j as B,mr as C,Bt as D,ke as E,_e as F,Io as G,Ht as H,Nc as I,pt as J,Wt as K,ho as L,$t as M,fc as N,et as O,gc as P,yc as Q,Zt as R};
4
- //# sourceMappingURL=chunk-RATFYRKZ.mjs.map