bitsnap-react 1.16.0 → 1.18.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 (125) hide show
  1. package/AGENTS.md +5 -0
  2. package/README.md +87 -0
  3. package/dist/CartProvider-ECQQH3PS.css +2 -0
  4. package/dist/CartProvider-ECQQH3PS.css.map +1 -0
  5. package/dist/CartProvider-OEI526IN.js +2 -0
  6. package/dist/{CartProvider-VGZMDVFJ.js.map → CartProvider-OEI526IN.js.map} +1 -1
  7. package/dist/CartProvider-RYAA3JDA.mjs +2 -0
  8. package/dist/{PanelModelFiles-NYCOFPLY.js → PanelModelFiles-7HPXWONN.js} +2 -2
  9. package/dist/{PanelModelFiles-NYCOFPLY.js.map → PanelModelFiles-7HPXWONN.js.map} +1 -1
  10. package/dist/PanelModelFiles-JZFSF7BF.mjs +2 -0
  11. package/dist/PanelModelFiles-JZFSF7BF.mjs.map +1 -0
  12. package/dist/analytics.d.mts +2 -2
  13. package/dist/analytics.d.ts +2 -2
  14. package/dist/analytics.js +1 -1
  15. package/dist/analytics.mjs +1 -1
  16. package/dist/catalog.css +1 -1
  17. package/dist/catalog.css.map +1 -1
  18. package/dist/catalog.d.mts +3 -1
  19. package/dist/catalog.d.ts +3 -1
  20. package/dist/catalog.js +1 -1
  21. package/dist/catalog.mjs +1 -1
  22. package/dist/{chunk-GXUNRJ5S.js → chunk-4HGZZJEL.js} +2 -2
  23. package/dist/{chunk-GXUNRJ5S.js.map → chunk-4HGZZJEL.js.map} +1 -1
  24. package/dist/chunk-4OVOKGGS.mjs +2 -0
  25. package/dist/chunk-4OVOKGGS.mjs.map +1 -0
  26. package/dist/chunk-5X7TP3TQ.mjs +2 -0
  27. package/dist/{chunk-SULHGFYN.mjs.map → chunk-5X7TP3TQ.mjs.map} +1 -1
  28. package/dist/{chunk-QQQ2JSPQ.mjs → chunk-CF45RDMD.mjs} +2 -2
  29. package/dist/{chunk-QQQ2JSPQ.mjs.map → chunk-CF45RDMD.mjs.map} +1 -1
  30. package/dist/{chunk-GQJDFLSL.js → chunk-DP2NOHCI.js} +2 -2
  31. package/dist/{chunk-GQJDFLSL.js.map → chunk-DP2NOHCI.js.map} +1 -1
  32. package/dist/chunk-EVIDNS22.mjs +2 -0
  33. package/dist/chunk-EVIDNS22.mjs.map +1 -0
  34. package/dist/chunk-G4V2KWTV.js +2 -0
  35. package/dist/chunk-G4V2KWTV.js.map +1 -0
  36. package/dist/{chunk-SXKJ26OA.mjs → chunk-GEBRXFT3.mjs} +2 -2
  37. package/dist/chunk-GWF3MRUP.js +2 -0
  38. package/dist/chunk-GWF3MRUP.js.map +1 -0
  39. package/dist/chunk-JA62KNAQ.js +2 -0
  40. package/dist/chunk-JA62KNAQ.js.map +1 -0
  41. package/dist/chunk-JHJ3ZZF4.mjs +2 -0
  42. package/dist/chunk-JHJ3ZZF4.mjs.map +1 -0
  43. package/dist/{chunk-WKE6ECID.mjs → chunk-UPAOIY4R.mjs} +2 -2
  44. package/dist/chunk-V5ECGBFW.js +5 -0
  45. package/dist/chunk-V5ECGBFW.js.map +1 -0
  46. package/dist/{chunk-SRQOFCMO.js → chunk-VNV5BD4X.js} +2 -2
  47. package/dist/{chunk-SRQOFCMO.js.map → chunk-VNV5BD4X.js.map} +1 -1
  48. package/dist/chunk-WJO5GSY3.mjs +5 -0
  49. package/dist/chunk-WJO5GSY3.mjs.map +1 -0
  50. package/dist/chunk-ZATPBYOA.js +2 -0
  51. package/dist/chunk-ZATPBYOA.js.map +1 -0
  52. package/dist/chunk-ZHTMK5TA.mjs +2 -0
  53. package/dist/chunk-ZHTMK5TA.mjs.map +1 -0
  54. package/dist/course.d.mts +13 -3
  55. package/dist/course.d.ts +13 -3
  56. package/dist/course.js +1 -1
  57. package/dist/course.js.map +1 -1
  58. package/dist/course.mjs +1 -1
  59. package/dist/course.mjs.map +1 -1
  60. package/dist/embed/analytics.js +1 -1
  61. package/dist/index.css +1 -1
  62. package/dist/index.css.map +1 -1
  63. package/dist/index.d.mts +41 -12
  64. package/dist/index.d.ts +41 -12
  65. package/dist/index.js +1 -1
  66. package/dist/index.js.map +1 -1
  67. package/dist/index.mjs +1 -1
  68. package/dist/index.mjs.map +1 -1
  69. package/dist/{instrument-BE8ktMUv.d.mts → instrument-eXaC8hc2.d.mts} +1 -1
  70. package/dist/{instrument-BE8ktMUv.d.ts → instrument-eXaC8hc2.d.ts} +1 -1
  71. package/dist/methods-AULQDKVS.mjs +2 -0
  72. package/dist/methods-OJEZREBK.css +2 -0
  73. package/dist/methods-OJEZREBK.css.map +1 -0
  74. package/dist/methods-PMH5VQ25.js +2 -0
  75. package/dist/{methods-WRONKK3D.js.map → methods-PMH5VQ25.js.map} +1 -1
  76. package/dist/returns.d.mts +19 -10
  77. package/dist/returns.d.ts +19 -10
  78. package/dist/returns.js +1 -1
  79. package/dist/returns.js.map +1 -1
  80. package/dist/returns.mjs +1 -1
  81. package/dist/{texts-tQtAGJCT.d.mts → texts-LGhuQfA9.d.mts} +28 -3
  82. package/dist/{texts-CIEFbJTN.d.ts → texts-m6XQGZ6w.d.ts} +28 -3
  83. package/dist/types-ClFCVzk_.d.ts +121 -0
  84. package/dist/types-D6LsoycW.d.mts +121 -0
  85. package/dist/viewer3d.css +1 -1
  86. package/dist/viewer3d.css.map +1 -1
  87. package/dist/viewer3d.mjs +1 -1
  88. package/package.json +2 -2
  89. package/dist/CartProvider-PDEV6GCV.css +0 -2
  90. package/dist/CartProvider-PDEV6GCV.css.map +0 -1
  91. package/dist/CartProvider-VGZMDVFJ.js +0 -2
  92. package/dist/CartProvider-ZY5OLTAF.mjs +0 -2
  93. package/dist/PanelModelFiles-RV7OHUUZ.mjs +0 -2
  94. package/dist/PanelModelFiles-RV7OHUUZ.mjs.map +0 -1
  95. package/dist/chunk-5AYH23UJ.mjs +0 -4
  96. package/dist/chunk-5AYH23UJ.mjs.map +0 -1
  97. package/dist/chunk-AGYS7Z6G.mjs +0 -2
  98. package/dist/chunk-AGYS7Z6G.mjs.map +0 -1
  99. package/dist/chunk-DPKWYLN7.mjs +0 -2
  100. package/dist/chunk-DPKWYLN7.mjs.map +0 -1
  101. package/dist/chunk-I3QXJJ7U.mjs +0 -2
  102. package/dist/chunk-I3QXJJ7U.mjs.map +0 -1
  103. package/dist/chunk-LL7ASBGY.js +0 -2
  104. package/dist/chunk-LL7ASBGY.js.map +0 -1
  105. package/dist/chunk-OZHXRKMX.js +0 -2
  106. package/dist/chunk-OZHXRKMX.js.map +0 -1
  107. package/dist/chunk-QERYM7RC.js +0 -2
  108. package/dist/chunk-QERYM7RC.js.map +0 -1
  109. package/dist/chunk-QXGK337V.mjs +0 -2
  110. package/dist/chunk-QXGK337V.mjs.map +0 -1
  111. package/dist/chunk-SULHGFYN.mjs +0 -2
  112. package/dist/chunk-WPOXLITY.js +0 -2
  113. package/dist/chunk-WPOXLITY.js.map +0 -1
  114. package/dist/chunk-Y5KWVTXT.js +0 -4
  115. package/dist/chunk-Y5KWVTXT.js.map +0 -1
  116. package/dist/methods-NJEP64AG.mjs +0 -2
  117. package/dist/methods-QAZED7TJ.css +0 -2
  118. package/dist/methods-QAZED7TJ.css.map +0 -1
  119. package/dist/methods-WRONKK3D.js +0 -2
  120. package/dist/types-DP1vxo5E.d.mts +0 -53
  121. package/dist/types-u8VwmC3j.d.ts +0 -53
  122. /package/dist/{CartProvider-ZY5OLTAF.mjs.map → CartProvider-RYAA3JDA.mjs.map} +0 -0
  123. /package/dist/{chunk-SXKJ26OA.mjs.map → chunk-GEBRXFT3.mjs.map} +0 -0
  124. /package/dist/{chunk-WKE6ECID.mjs.map → chunk-UPAOIY4R.mjs.map} +0 -0
  125. /package/dist/{methods-NJEP64AG.mjs.map → methods-AULQDKVS.mjs.map} +0 -0
@@ -0,0 +1,5 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkZATPBYOAjs = require('./chunk-ZATPBYOA.js');var _chunkVNV5BD4Xjs = require('./chunk-VNV5BD4X.js');var _chunkG4V2KWTVjs = require('./chunk-G4V2KWTV.js');var _chunk4HGZZJELjs = require('./chunk-4HGZZJEL.js');var _chunkDP2NOHCIjs = require('./chunk-DP2NOHCI.js');var _chunk7RXW6XFYjs = require('./chunk-7RXW6XFY.js');var _react = require('@formkit/auto-animate/react');var _react3 = require('react');var _jsxruntime = require('react/jsx-runtime');function Ee({className:e,...t}){return _jsxruntime.jsx.call(void 0, "div",{"data-slot":"card",className:_chunk4HGZZJELjs.g.call(void 0, "bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Oe({className:e,...t}){return _jsxruntime.jsx.call(void 0, "div",{"data-slot":"card-header",className:_chunk4HGZZJELjs.g.call(void 0, "@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 Ue({className:e,...t}){return _jsxruntime.jsx.call(void 0, "div",{"data-slot":"card-title",className:_chunk4HGZZJELjs.g.call(void 0, "leading-none font-semibold",e),...t})}function Tn({className:e,...t}){return _jsxruntime.jsx.call(void 0, "div",{"data-slot":"card-description",className:_chunk4HGZZJELjs.g.call(void 0, "text-muted-foreground text-sm",e),...t})}function Te({className:e,...t}){return _jsxruntime.jsx.call(void 0, "div",{"data-slot":"card-content",className:_chunk4HGZZJELjs.g.call(void 0, "px-6",e),...t})}var _lucidereact = require('lucide-react');var ra="text-muted-foreground text-xs leading-5",na="dark:border-foreground/30 dark:focus-visible:border-foreground/70 dark:focus-visible:ring-foreground/25 dark:aria-invalid:border-destructive-foreground dark:aria-invalid:ring-destructive-foreground/30",oa=new Set(["invalidEmail","emailNotFound","deliveryUnavailable"]),lr="inline-flex min-h-11 items-center px-1 text-sm underline underline-offset-4 hover:no-underline focus-visible:ring-[3px] focus-visible:ring-ring/50 rounded-sm outline-none disabled:opacity-50 disabled:no-underline";function Ln({login:e,texts:t,allowHaveCode:n=!0,emailPlaceholder:a,emailInputId:r,codeInputId:o,className:i,buttonClassName:d,children:c}){let l=_react3.useId.call(void 0, ),b=_nullishCoalesce(r, () => (`${l}-email`)),P=_nullishCoalesce(o, () => (`${l}-code`)),w=`${l}-notice`,h=`${l}-hint`,{notice:y}=e,u=_optionalChain([y, 'optionalAccess', _2 => _2.kind])==="error",m=e.busy==="send",p=e.busy==="verify",x=e.busy==="resend",U=_chunk4HGZZJELjs.g.call(void 0, "h-11 w-full",d),le=_optionalChain([y, 'optionalAccess', _3 => _3.kind])==="success",E=_jsxruntime.jsxs.call(void 0, "div",{id:w,className:"min-h-10 text-sm leading-5",children:[_jsxruntime.jsx.call(void 0, "p",{role:"alert",className:"font-medium text-red-700 dark:text-red-400",children:u?y.text:null}),_jsxruntime.jsxs.call(void 0, "p",{role:"status",className:_chunk4HGZZJELjs.g.call(void 0, "flex items-start gap-1.5",le?"font-medium text-emerald-700 dark:text-emerald-400":"text-foreground"),children:[le&&_jsxruntime.jsx.call(void 0, _lucidereact.CircleCheck,{"aria-hidden":!0,className:"mt-0.5 size-4 shrink-0"}),_jsxruntime.jsx.call(void 0, "span",{children:y!=null&&!u?y.text:null})]})]}),de=u&&e.step==="email"&&(y.failure==null||oa.has(y.failure)),Ce=_jsxruntime.jsx.call(void 0, "p",{className:"sr-only",role:"status","aria-live":"polite",children:e.announcement}),ee=_jsxruntime.jsxs.call(void 0, "div",{className:"grid gap-2",children:[_jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.d,{htmlFor:b,children:t.emailLabel}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.r,{id:b,ref:e.emailRef,name:"email",type:"email",autoComplete:"email",inputMode:"email",autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,autoFocus:!0,required:!0,className:_chunk4HGZZJELjs.g.call(void 0, "h-11 text-base disabled:opacity-100 disabled:text-foreground/70",na),placeholder:_nullishCoalesce(a, () => (t.emailPlaceholder)),value:e.email,disabled:e.isBusy,"aria-invalid":de?!0:void 0,"aria-describedby":w,onChange:Y=>e.setEmail(Y.target.value)})]});if(e.step==="email")return _jsxruntime.jsxs.call(void 0, "form",{noValidate:!0,className:_chunk4HGZZJELjs.g.call(void 0, "flex flex-col gap-4",i),onSubmit:Y=>{Y.preventDefault(),e.sendCode()},children:[Ce,ee,E,_jsxruntime.jsxs.call(void 0, _chunkG4V2KWTVjs.q,{type:"submit",disabled:e.isBusy,"aria-busy":m,className:U,children:[m&&_jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.e,{"aria-hidden":!0}),m?t.sending:t.sendCode]}),n&&_jsxruntime.jsxs.call(void 0, "p",{className:"flex flex-wrap items-center justify-center text-center text-sm",children:[t.haveCodePrompt!==""&&_jsxruntime.jsx.call(void 0, "span",{children:t.haveCodePrompt}),_jsxruntime.jsx.call(void 0, "button",{type:"button",className:lr,disabled:e.isBusy,onClick:e.haveCode,children:t.haveCode})]})]});let[A,fe]=t.codeSentTo.split("{email}"),J=e.dead!=null,He=J?t.resendNew:e.secondsLeft>0?_chunkZATPBYOAjs.i.call(void 0, t.resendIn,{seconds:e.secondsLeft}):t.resend;return _jsxruntime.jsxs.call(void 0, "form",{noValidate:!0,className:_chunk4HGZZJELjs.g.call(void 0, "flex flex-col gap-4",i),onSubmit:Y=>{Y.preventDefault(),e.submitCode()},children:[Ce,e.needsEmail?ee:_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap items-center justify-between gap-x-2",children:[_jsxruntime.jsxs.call(void 0, "p",{className:"min-w-0 flex-[1_1_14rem] text-sm leading-5 break-words",children:[A,_jsxruntime.jsx.call(void 0, "strong",{className:"font-semibold",children:e.email}),"\u2060",fe]}),_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk4HGZZJELjs.g.call(void 0, lr,"-ml-1 shrink-0"),disabled:e.isBusy,onClick:e.changeEmail,children:t.changeEmail})]}),c,_jsxruntime.jsxs.call(void 0, "div",{className:"grid gap-2",children:[_jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.d,{htmlFor:P,children:t.codeLabel}),_jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.k,{id:P,name:"code",inputRef:e.codeRef,value:e.code,onChange:e.setCode,onComplete:Y=>void e.submitCode(Y),disabled:e.isBusy||J,invalid:u&&!e.needsEmail,"aria-describedby":`${w} ${h}`}),_jsxruntime.jsxs.call(void 0, "p",{id:h,className:ra,children:[t.validity," ",t.spamHint]})]}),E,_jsxruntime.jsxs.call(void 0, _chunkG4V2KWTVjs.q,{type:"submit",disabled:e.isBusy||J,"aria-busy":p,className:U,children:[p&&_jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.e,{"aria-hidden":!0}),p?t.verifying:t.verify]}),e.needsEmail?_jsxruntime.jsx.call(void 0, "div",{className:"flex justify-center",children:_jsxruntime.jsx.call(void 0, "button",{type:"button",className:lr,disabled:e.isBusy,onClick:e.changeEmail,children:t.noCode})}):_jsxruntime.jsxs.call(void 0, _chunkG4V2KWTVjs.q,{type:"button",variant:J?"default":"outline",disabled:e.isBusy||!J&&e.secondsLeft>0,"aria-busy":x,className:J?U:"h-11 w-full",onClick:()=>void e.resend(),children:[x&&_jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.e,{"aria-hidden":!0}),He]})]})}function dr(e){switch(e){case 1:return"emailNotFound";case 2:return"invalidEmail";case 3:return"wrongCode";case 14:return"expired";case 15:return"tooManyAttempts";case 13:return"rateLimited";case 12:return"deliveryFailed";case 11:return"deliveryUnavailable";default:return"unknown"}}var aa={pl:{title:"Zaloguj si\u0119",description:"Wy\u015Blemy do Ciebie kod na maila, dzi\u0119ki kt\xF3remu si\u0119 zalogujesz.",codeTitle:"Wpisz kod z maila",codeDescription:"Kod ma 6 cyfr."},en:{title:"Sign in",description:"We will email you a code that signs you in.",codeTitle:"Enter the code from the email",codeDescription:"The code has 6 digits."}};function Rn(e=_chunk7RXW6XFYjs.f.call(void 0, ),t){return{..._chunkZATPBYOAjs.h.call(void 0, e,t),..._chunk7RXW6XFYjs.a.call(void 0, aa,e),...ia(t,["title","description","codeTitle","codeDescription"])}}function ia(e,t){let n={};for(let a of t){let r=_optionalChain([e, 'optionalAccess', _4 => _4[a]]);r!=null&&(n[a]=r)}return n}var sa="return_url",cr="__return_url",la="accessToken";function gt(e){let t=new URLSearchParams(e).get(sa);return t?An(t):null}function yt(e){typeof window>"u"||(e?window.sessionStorage.setItem(cr,e):window.sessionStorage.removeItem(cr))}function Ye(){if(typeof window>"u")return null;let e=window.sessionStorage.getItem(cr);return e?An(e):null}function da(e,t){return t.some(n=>{if(e===n)return!0;let a=new URL(n).hostname,r=new URL(e).hostname;return r.endsWith(`.${a}`)||r===a})}function An(e){try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"||!da(t.origin,_chunkVNV5BD4Xjs.h.call(void 0, ))?null:t.toString()}catch (e2){return null}}function Ze(e,t){let n=new URL(e);return n.searchParams.set(la,t),n.toString()}if(typeof window<"u"){let t=[window.location.origin,"https://bitsnap.pl","https://kursy.bitsnap.pl"];_chunkVNV5BD4Xjs.h.call(void 0, ).length===0&&_chunkVNV5BD4Xjs.g.call(void 0, Array.from(new Set(t)))}var ua=({texts:e,projectID:t,host:n,locale:a,logo:r})=>{let o=_chunkDP2NOHCIjs.m.call(void 0, ),{mutateAsync:i}=_chunkG4V2KWTVjs.m.call(void 0, _chunkG4V2KWTVjs.k.publicApi.userPanelLogin),{mutateAsync:d}=_chunkG4V2KWTVjs.m.call(void 0, _chunkG4V2KWTVjs.k.publicApi.userPanelLoginWithCode),c=_react3.useMemo.call(void 0, ()=>({async send(h){try{let y=await i({email:h});return y.result.case==="success"?{ok:!0,retryIn:y.result.value.retryIn||void 0,challengeId:y.result.value.challengeId||void 0}:{ok:!1,kind:dr(y.result.case==="failure"?y.result.value:0)}}catch(y){return{ok:!1,kind:_chunkZATPBYOAjs.a.call(void 0, y),cause:y}}},async verify({email:h,code:y,challengeId:u}){try{let m=await d({code:parseInt(y,10),email:h,challengeId:u});return m.result.case==="accessToken"&&m.result.value?{ok:!0,value:{accessToken:m.result.value}}:{ok:!1,kind:dr(m.result.case==="failure"?m.result.value:0)}}catch(m){return{ok:!1,kind:_chunkZATPBYOAjs.a.call(void 0, m),cause:m}}}}),[i,d]),l=_chunkZATPBYOAjs.j.call(void 0, {adapter:c,texts:e,storageKey:_chunkZATPBYOAjs.f.call(void 0, "panel",t,n),onVerified:({accessToken:h},y)=>{o.track("panel_login",{}),_chunkVNV5BD4Xjs.l.call(void 0, t,h,y,n);let u=typeof window<"u"?Ye():null;setTimeout(()=>{if(u){window.location.href=Ze(u,h);return}window.location.reload()},100)}}),b=l.step==="code",P=b&&!l.needsEmail?e.codeTitle:e.title,w=b&&!l.needsEmail?e.codeDescription:e.description;return _jsxruntime.jsx.call(void 0, "main",{className:"mx-auto flex w-full max-w-sm flex-1 flex-col justify-start pt-4 sm:pt-[12vh]",children:_jsxruntime.jsxs.call(void 0, Ee,{children:[_jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.c,{projectId:t,locale:a,className:"px-4 sm:px-6",...r}),_jsxruntime.jsxs.call(void 0, Oe,{className:"px-4 sm:px-6",children:[_jsxruntime.jsx.call(void 0, Ue,{role:"heading","aria-level":1,className:"text-2xl",children:P}),_jsxruntime.jsx.call(void 0, Tn,{children:w})]}),_jsxruntime.jsx.call(void 0, Te,{className:"px-4 sm:px-6",children:_jsxruntime.jsx.call(void 0, Ln,{login:l,texts:e,emailInputId:"email",codeInputId:"verify-code"})})]})})},pa=({analytics:e,texts:t,locale:n,showLogo:a,logoUrl:r,logoDarkUrl:o})=>{let{theme:i,allowedReturnOrigins:d,projectID:c,host:l}=_chunkVNV5BD4Xjs.j.call(void 0, ),b=_chunkDP2NOHCIjs.n.call(void 0, c,e,"panel"),P=_react3.useMemo.call(void 0, ()=>Rn(_nullishCoalesce(n, () => (_chunk7RXW6XFYjs.f.call(void 0, ))),t),[n,t]),w={"--button-background-color":_nullishCoalesce(_optionalChain([i, 'optionalAccess', _5 => _5.colors, 'optionalAccess', _6 => _6.brand]), () => ("#FFFFFF")),"--button-background-color-dark":_nullishCoalesce(_optionalChain([i, 'optionalAccess', _7 => _7.colors, 'optionalAccess', _8 => _8.brandDark]), () => ("#000000")),"--button-text-color":_nullishCoalesce(_optionalChain([i, 'optionalAccess', _9 => _9.colors, 'optionalAccess', _10 => _10.brandDark]), () => ("#000000")),"--button-text-color-dark":_nullishCoalesce(_optionalChain([i, 'optionalAccess', _11 => _11.colors, 'optionalAccess', _12 => _12.brand]), () => ("#FFFFFF"))},[h]=_react.useAutoAnimate.call(void 0, {duration:300,easing:"ease-in-out",disrespectUserMotionPreference:!1});return _react3.useEffect.call(void 0, ()=>{typeof window>"u"||_chunkVNV5BD4Xjs.k.call(void 0, c,l)!=null&&(window.location.href=window.location.href.replaceAll("login",""))},[c,l]),_react3.useEffect.call(void 0, ()=>{if(typeof window>"u"||window.parent!==window)return;let y=gt(window.location.search);y&&yt(y);let u=_nullishCoalesce(y, () => (Ye()));if(!u)return;let m=_chunkVNV5BD4Xjs.k.call(void 0, c,l);m&&(window.location.href=Ze(u,m))},[d,c,l]),_jsxruntime.jsx.call(void 0, _chunkDP2NOHCIjs.l,{value:b,children:_jsxruntime.jsx.call(void 0, "div",{className:"bg-white text-black dark:bg-black dark:text-white",children:_jsxruntime.jsx.call(void 0, "div",{className:"font-inter flex min-h-screen w-full flex-col p-4",style:w,ref:h,children:_jsxruntime.jsx.call(void 0, ua,{texts:P,projectID:c,host:l,locale:n,logo:{showLogo:a,logoUrl:_nullishCoalesce(r, () => (_optionalChain([i, 'optionalAccess', _13 => _13.logoURL]))),logoDarkUrl:_nullishCoalesce(o, () => (_optionalChain([i, 'optionalAccess', _14 => _14.logoDarkURL])))}})})})})},ma= exports.k =(e={})=>_jsxruntime.jsx.call(void 0, pa,{...e});function Un(e){let[t,n]=_react3.useState.call(void 0, ()=>{if(typeof window>"u")return e;let r=new URLSearchParams(window.location.search),o={};return Object.keys(e).forEach(i=>{let d=r.get(i);if(d!==null)try{o[i]=JSON.parse(d)}catch (e3){o[i]=d}}),{...e,...o}}),a=_react3.useCallback.call(void 0, r=>{n(o=>{let i={...o,...r};if(typeof window<"u"){let d=new URLSearchParams;Object.keys(i).forEach(l=>{let b=i[l];b!=null&&d.set(l,JSON.stringify(b))});let c=`${window.location.pathname}?${d.toString()}`;window.history.pushState({},"",c)}return i})},[]);return _react3.useEffect.call(void 0, ()=>{let r=()=>{let o=new URLSearchParams(window.location.search),i={};Object.keys(e).forEach(d=>{let c=o.get(d);if(c!==null)try{i[d]=JSON.parse(c)}catch (e4){i[d]=c}}),n({...e,...i})};return window.addEventListener("popstate",r),()=>window.removeEventListener("popstate",r)},[e]),[t,a]}function _n(e,t){if(e!=null)return e;let n=_optionalChain([t, 'optionalAccess', _15 => _15.trim, 'call', _16 => _16()]);if(!(n==null||n===""))return{tokens:_chunkG4V2KWTVjs.t.call(void 0, n)}}var ha={pl:{returnsNavLabel:"Zwroty",openCourse:"Otw\xF3rz kurs",libraryNavLabel:"Biblioteka",ordersNavLabel:"Zam\xF3wienia",accountNavLabel:"Konto",navigationLabel:"Panel klienta",logout:"Wyloguj si\u0119",profileHeading:"Profil",emailLabel:"E-mail",noData:"Brak danych",languageLabel:"J\u0119zyk",polishLanguage:"Polski",englishLanguage:"English",plansHeading:"Plany",plansUnavailable:"Plany nie s\u0105 obecnie dost\u0119pne w panelu.",notificationsHeading:"Powiadomienia",notificationsUnavailable:"Ustawienia powiadomie\u0144 nie s\u0105 obecnie dost\u0119pne w panelu.",ordersHeading:"Historia zam\xF3wie\u0144",ordersDescription:"Twoje zam\xF3wienia",ordersEmpty:"Brak zam\xF3wie\u0144.",ordersError:"Nie uda\u0142o si\u0119 pobra\u0107 zam\xF3wie\u0144.",retry:"Spr\xF3buj ponownie",orderLabel:"Zam\xF3wienie",customerLabel:"Klient",dateLabel:"Data",ordersEnd:"To ju\u017C wszystkie Twoje zam\xF3wienia.",previousPage:"Poprzednia strona",nextPage:"Nast\u0119pna strona",paginationLabel:"Strony zam\xF3wie\u0144",statusDraft:"Szkic",statusUnpaid:"Nieop\u0142acone",statusPaid:"Op\u0142acone",statusOverdue:"Zaleg\u0142e",statusCancelled:"Anulowane",statusCompleted:"Zako\u0144czone",statusProcessing:"Przetwarzane",statusRefunded:"Zwr\xF3cone"},en:{returnsNavLabel:"Returns",openCourse:"Open the course",libraryNavLabel:"Library",ordersNavLabel:"Orders",accountNavLabel:"Account",navigationLabel:"Customer panel",logout:"Log out",profileHeading:"Profile",emailLabel:"Email",noData:"No data",languageLabel:"Language",polishLanguage:"Polski",englishLanguage:"English",plansHeading:"Plans",plansUnavailable:"Plans are currently unavailable in the panel.",notificationsHeading:"Notifications",notificationsUnavailable:"Notification settings are currently unavailable in the panel.",ordersHeading:"Order history",ordersDescription:"Your orders",ordersEmpty:"No orders yet.",ordersError:"Could not load your orders.",retry:"Try again",orderLabel:"Order",customerLabel:"Customer",dateLabel:"Date",ordersEnd:"You\u2019ve reached the end of your orders.",previousPage:"Previous page",nextPage:"Next page",paginationLabel:"Order pages",statusDraft:"Draft",statusUnpaid:"Unpaid",statusPaid:"Paid",statusOverdue:"Overdue",statusCancelled:"Cancelled",statusCompleted:"Completed",statusProcessing:"Processing",statusRefunded:"Refunded"}};function ue(e=_chunk7RXW6XFYjs.f.call(void 0, )){return _chunk7RXW6XFYjs.a.call(void 0, ha,e)}function ur({}){let e=ue();return _jsxruntime.jsxs.call(void 0, "section",{children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-2xl",children:e.notificationsHeading}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-6 text-sm text-neutral-600 dark:text-neutral-400",children:e.notificationsUnavailable})]})}var va=e=>new Date(e*1e3).toLocaleDateString(_chunk7RXW6XFYjs.f.call(void 0, ),{year:"numeric",month:"short",day:"numeric"}),ka=(e,t)=>new Intl.NumberFormat(_chunk7RXW6XFYjs.f.call(void 0, ),{style:"currency",currency:t.toUpperCase()}).format(e/100),xa={draft:"text-neutral-600 dark:text-neutral-400",unpaid:"text-amber-700 dark:text-amber-300",paid:"text-green-700 dark:text-green-400",overdue:"text-red-700 dark:text-red-400",cancelled:"text-neutral-600 line-through dark:text-neutral-400",completed:"text-green-700 dark:text-green-400",processing:"text-blue-700 dark:text-blue-400",refunded:"text-purple-700 dark:text-purple-400"};function wa({openOrderDetails:e,projectID:t,accessToken:n}){let a=ue(),r={draft:a.statusDraft,unpaid:a.statusUnpaid,paid:a.statusPaid,overdue:a.statusOverdue,cancelled:a.statusCancelled,completed:a.statusCompleted,processing:a.statusProcessing,refunded:a.statusRefunded},[o,i]=_react3.useState.call(void 0, 0),d=20,{data:c,isFetching:l,isError:b,refetch:P}=_chunkG4V2KWTVjs.l.call(void 0, _chunkG4V2KWTVjs.k.publicApi.getOrders,{projectId:t,accessToken:n,offset:o,limit:d}),w=_nullishCoalesce(_optionalChain([c, 'optionalAccess', _17 => _17.orders]), () => ([])),h=_nullishCoalesce(_optionalChain([c, 'optionalAccess', _18 => _18.totalCount]), () => (0)),y=Math.floor(o/d)+1,u=Math.ceil(h/d),m=p=>{i(p)};return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-2xl",children:a.ordersHeading}),_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-500 dark:text-neutral-400",children:a.ordersDescription}),l?_jsxruntime.jsx.call(void 0, "div",{className:"mt-6 flex w-full flex-col gap-3",children:[...Array(5)].map((p,x)=>_jsxruntime.jsxs.call(void 0, "div",{className:"rounded-xl bg-white p-4 shadow-sm dark:bg-neutral-800",children:[_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-center justify-between gap-3",children:[_jsxruntime.jsxs.call(void 0, "div",{className:"space-y-2",children:[_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.u,{className:"h-4 w-24"}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.u,{className:"h-3 w-32"})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"space-y-2 text-right",children:[_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.u,{className:"ml-auto h-4 w-16"}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.u,{className:"ml-auto h-3 w-12"})]})]}),_jsxruntime.jsx.call(void 0, "div",{className:"mt-3",children:_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.u,{className:"h-3 w-40"})})]},x))}):b?_jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:"mt-6 space-y-3",children:[_jsxruntime.jsx.call(void 0, "p",{children:a.ordersError}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{onClick:()=>void P(),className:"min-h-11 focus-visible:outline-2 focus-visible:outline-current",children:a.retry})]}):w.length===0?_jsxruntime.jsx.call(void 0, "div",{className:"mt-6 text-sm text-neutral-600 dark:text-neutral-400",children:a.ordersEmpty}):_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "div",{className:"mt-6 flex w-full flex-col gap-3",children:w.map(p=>_jsxruntime.jsxs.call(void 0, "button",{onClick:()=>e(p.id),className:"block min-h-11 focus-visible:outline-2 focus-visible:outline-current 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:[_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-center justify-between gap-3",children:[_jsxruntime.jsxs.call(void 0, "div",{className:"min-w-0 break-words",children:[_jsxruntime.jsxs.call(void 0, "p",{className:"font-medium",children:[a.orderLabel," #",p.id]}),_jsxruntime.jsx.call(void 0, "p",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:p.customerName||a.customerLabel})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"shrink-0 text-right",children:[_jsxruntime.jsx.call(void 0, "p",{className:"font-semibold",children:ka(p.totalAmount,p.currency)}),_jsxruntime.jsx.call(void 0, "p",{className:`text-xs font-medium ${_nullishCoalesce(xa[p.status], () => ("text-neutral-400"))}`,children:_nullishCoalesce(r[p.status], () => (p.status))})]})]}),_jsxruntime.jsx.call(void 0, "div",{className:"mt-2 flex items-center justify-between gap-3 text-xs text-neutral-500 dark:text-neutral-400",children:_jsxruntime.jsxs.call(void 0, "span",{children:[a.dateLabel,":"," ",p.createdAt?va(Number(p.createdAt.seconds)):"-"]})})]},p.id))}),y>=u&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-6 text-center text-sm text-neutral-600 dark:text-neutral-400",children:a.ordersEnd}),u>1&&_jsxruntime.jsxs.call(void 0, "nav",{"aria-label":a.paginationLabel,className:"mt-4 flex flex-wrap items-center justify-center gap-2",children:[y>1&&_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{variant:"outline",className:"min-h-11",onClick:()=>m(o-d),children:a.previousPage}),Array.from(new Set([1,y-1,y,y+1,u])).filter(p=>p>0&&p<=u).sort((p,x)=>p-x).map(p=>_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{variant:p===y?"secondary":"ghost",className:"min-h-11 min-w-11","aria-current":p===y?"page":void 0,onClick:()=>m((p-1)*d),children:p},p)),y<u&&_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{variant:"outline",className:"min-h-11",onClick:()=>m(o+d),children:a.nextPage})]})]})]})}var jn=wa;function pr({projectID:e}){let t=ue();return _jsxruntime.jsxs.call(void 0, "section",{children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-2xl",children:t.plansHeading}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-6 text-sm text-neutral-600 dark:text-neutral-400",children:t.plansUnavailable})]})}function Sa(e,t,n,a){typeof window>"u"||(t&&_chunkVNV5BD4Xjs.n.call(void 0, n,a),window.location.href=e)}function Ea({projectID:e,host:t,loginURL:n,screen:a,params:r,setParams:o,setActiveScreen:i}){let{status:d,exchangeError:c}=_chunkZATPBYOAjs.t.call(void 0, "PanelReturns"),l=_chunkZATPBYOAjs.r.call(void 0, ),b=d==="anonymous"&&(c==null||_chunkZATPBYOAjs.p.call(void 0, c));_react3.useEffect.call(void 0, ()=>{b&&Sa(n,c!=null,e,t)},[b,n,c,e,t]);let[P,w]=_react3.useState.call(void 0, "orders"),[h,y]=_react3.useState.call(void 0, {items:[],note:""}),[u,m]=_react3.useState.call(void 0, );if(d==="anonymous"&&!b)return _jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:"flex flex-col items-start gap-3",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm",children:l(_chunkZATPBYOAjs.q.call(void 0, c))}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{type:"button",onClick:()=>window.location.reload(),children:l("errorRetry")})]});if(d!=="authenticated")return _jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.C,{});let p=x=>{w(x),o({state:"returns",orderId:void 0,returnId:void 0}),i("returns")};if(a==="return-details"&&r.returnId)return _jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.K,{returnId:r.returnId,onBack:()=>p("myReturns")});if(P==="myReturns")return _jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.J,{onBack:()=>p("orders"),onSelectReturn:x=>{o({state:"return-details",returnId:x,orderId:void 0}),i("return-details")}});if(P==="result"&&u!=null)return _jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.I,{returnId:u,onContinue:()=>p("orders"),onOpenMyReturns:()=>p("myReturns")});if(r.orderId){let x=r.orderId;return P==="confirmation"?_jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.H,{orderId:x,items:h.items,note:h.note,onBack:()=>w("orders"),onSubmitted:U=>{m(U),y({items:[],note:""}),w("result"),o({orderId:void 0})}}):_jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.G,{orderId:x,initialItems:h.items.length>0?h.items:void 0,initialNote:h.note,onBack:()=>{y({items:[],note:""}),o({orderId:void 0})},onContinue:U=>{y(U),w("confirmation")}})}return _jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.F,{showLogout:!1,onSelectOrder:x=>{y({items:[],note:""}),w("orders"),o({orderId:x})},onOpenMyReturns:()=>p("myReturns")})}function fr({accessToken:e,appearance:t,texts:n,...a}){return _jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.u,{projectID:a.projectID,host:a.host,appearance:t,texts:n,panelAccessToken:e,children:_jsxruntime.jsx.call(void 0, Ea,{...a})})}var La={hello:"Hej \u{1F44B}",intro:"Poni\u017Cej znajdziesz swoje produkty",loading:"\u0141adowanie produkt\xF3w\u2026",empty:"Nie masz jeszcze produkt\xF3w w tym sklepie. Twoje zakupy pojawi\u0105 si\u0119 tutaj.",audio:"Audio",files:"Pliki",course:"Kurs",ticket:"Bilet",listen:"S\u0142uchaj",openCourse:"Otw\xF3rz kurs",downloadFiles:"Pobierz pliki",showTicket:"Poka\u017C bilet",back:"Wr\xF3\u0107",yourFiles:"Twoje pliki",download:"Pobierz",retry:"Spr\xF3buj ponownie",fileError:"Nie uda\u0142o si\u0119 wczyta\u0107 plik\xF3w.",noFiles:"Brak plik\xF3w do pobrania.",ticketInfo:"Tw\xF3j zakupiony bilet",file:"Plik"},Ra={hello:"Hi \u{1F44B}",intro:"Your products are below",loading:"Loading products\u2026",empty:"You have no products in this shop yet. Your purchases will show up here.",audio:"Audio",files:"Files",course:"Course",ticket:"Ticket",listen:"Listen",openCourse:"Open course",downloadFiles:"Download files",showTicket:"Show ticket",back:"Back",yourFiles:"Your files",download:"Download",retry:"Try again",fileError:"Your files could not be loaded.",noFiles:"No files to download.",ticketInfo:"Your purchased ticket",file:"File"};function Qe(){return _chunk7RXW6XFYjs.f.call(void 0, ).toLowerCase().startsWith("en")?Ra:La}var Aa=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g,Da=e=>[...e.matchAll(Aa)].map(n=>({url:n[0],startIndex:n.index,endIndex:n.index+n[0].length-1})),Ma=(e,t)=>{let n="",a=0;t.sort((r,o)=>r.startIndex-o.startIndex);for(let{startIndex:r,endIndex:o,replacementText:i}of t)n+=e.slice(a,r),n+=i,a=o+1;return n+=e.slice(a),n},Hn=e=>{let t=Da(e);return _jsxruntime.jsx.call(void 0, "p",{dangerouslySetInnerHTML:{__html:Ma(e,t.map(n=>(n.replacementText=`<a key=${n.url} href=${n.url} style="text-decoration: underline;" target="_blank">
2
+ ${n.url}
3
+ </a>`,n)))}})};var _protobuf = require('@bufbuild/protobuf');var _hlsjs = require('hls.js'); var _hlsjs2 = _interopRequireDefault(_hlsjs);function Ua(){return _jsxruntime.jsxs.call(void 0, "div",{className:"flex items-center gap-2",children:[_jsxruntime.jsx.call(void 0, "div",{className:"h-3 w-3 animate-bounce rounded-full bg-current [animation-delay:-0.3s]"}),_jsxruntime.jsx.call(void 0, "div",{className:"h-3 w-3 animate-bounce rounded-full bg-current [animation-delay:-0.15s]"}),_jsxruntime.jsx.call(void 0, "div",{className:"h-3 w-3 animate-bounce rounded-full bg-current"})]})}var _e=Ua;var ja=[401,403],$n="networkError",qn="mediaError";function Fa(e,t){if(e==null||e.fatal!==!0)return{action:"ignore"};let n=_optionalChain([e, 'access', _19 => _19.response, 'optionalAccess', _20 => _20.code]),a=e.type===$n?"network":e.type===qn?"media":"unknown",r=n==null?{kind:a}:{kind:a,status:n};return n!=null&&ja.includes(n)?{action:"expired",error:{kind:"network",status:n}}:e.type===$n&&!t.network?{action:"restart-load"}:e.type===qn&&!t.media?{action:"recover-media"}:{action:"fail",error:r}}function Bn(e){let t=_nullishCoalesce(e.HlsCtor, () => (_hlsjs2.default)),n=new t,a,r=!1,o=!1;return n.attachMedia(e.media),n.on(t.Events.ERROR,(i,d)=>{let c=Fa(d,{network:r,media:o});switch(c.action){case"expired":_optionalChain([e, 'access', _21 => _21.handlers, 'optionalAccess', _22 => _22.onExpiredUrl, 'optionalCall', _23 => _23()]),_optionalChain([e, 'access', _24 => _24.handlers, 'optionalAccess', _25 => _25.onError, 'optionalCall', _26 => _26(c.error)]);break;case"restart-load":r=!0,n.startLoad();break;case"recover-media":o=!0,n.recoverMediaError();break;case"fail":_optionalChain([e, 'access', _27 => _27.handlers, 'optionalAccess', _28 => _28.onError, 'optionalCall', _29 => _29(c.error)]);break;case"ignore":break}}),{load(i){a=i,r=!1,o=!1,n.loadSource(i)},retry(){a!=null&&(r=!1,o=!1,n.loadSource(a))},destroy(){n.destroy()},get src(){return a}}}function Kn(e){try{return e.canPlayType("application/vnd.apple.mpegurl")!==""}catch (e5){return!1}}function Gn(e){switch(_optionalChain([e, 'optionalAccess', _30 => _30.code])){case 2:return{kind:"network"};case 3:case 4:return{kind:"media"};default:return{kind:"unknown"}}}var Ha={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",avif:"image/avif",svg:"image/svg+xml"},yr="512x512";function Xe(){return typeof navigator<"u"&&typeof navigator.mediaSession<"u"}function $a(e){if(typeof e!="string"||e.length===0)return{src:e,sizes:yr};let t=e.split(/[?#]/)[0],n=t.includes(".")?t.slice(t.lastIndexOf(".")+1).toLowerCase():"",a=Ha[n],r={src:e,sizes:yr};return a!=null&&(r.type=a),r}function qa(e){if(e==null)return;let t=Array.isArray(e)?e:[e],n=[];for(let a of t){if(typeof a=="string"){a.length>0&&n.push($a(a));continue}a!=null&&a.src.length>0&&n.push({src:a.src,sizes:_nullishCoalesce(a.sizes, () => (yr)),...a.type!=null?{type:a.type}:{}})}return n.length>0?n:void 0}function hr(e){!Xe()||typeof MediaMetadata>"u"||(navigator.mediaSession.metadata=new MediaMetadata({title:e.title,album:e.album,artist:e.artist,artwork:qa(e.artwork)}))}function Wn(){Xe()&&(navigator.mediaSession.playbackState="playing")}function Vn(){Xe()&&(navigator.mediaSession.playbackState="paused")}function Jn(e,t,n=1){if(!Xe()||e==null||!Number.isFinite(e)||e<=0||t!=null&&isNaN(t))return;let a=Math.min(Math.max(_nullishCoalesce(t, () => (0)),0),e),r=Number.isFinite(n)&&n>0?n:1;try{navigator.mediaSession.setPositionState({playbackRate:r,duration:e,position:a})}catch (e6){}}var Yn=["play","pause","stop","seekbackward","seekforward","seekto","previoustrack","nexttrack"];function Zn(e){if(Xe()){hr({title:e.title,album:e.album,artist:e.artist,artwork:e.artwork});for(let t of Yn)try{navigator.mediaSession.setActionHandler(t,n=>{e.action(n)})}catch (e7){}}}function Qn(){if(Xe()){navigator.mediaSession.metadata=null;for(let e of Yn)try{navigator.mediaSession.setActionHandler(e,null)}catch (e8){}}}var Ga={play:"Odtw\xF3rz",pause:"Wstrzymaj",previous:"Poprzedni rozdzia\u0142",next:"Nast\u0119pny rozdzia\u0142",rewind:"Cofnij o 10 sekund",forward:"Przewi\u0144 o 10 sekund",progress:"Post\u0119p odtwarzania",of:"z",speed:"Pr\u0119dko\u015B\u0107",sleep:"Wy\u0142\u0105cznik czasowy",off:"Wy\u0142\u0105czony",end:"Koniec rozdzia\u0142u",cancel:"Anuluj wy\u0142\u0105cznik",error:"Nie uda\u0142o si\u0119 odtworzy\u0107 nagrania.",retry:"Spr\xF3buj ponownie",left:"zosta\u0142o",book:"ca\u0142a ksi\u0105\u017Cka",chapter:"rozdzia\u0142",chapters:"Rozdzia\u0142y",loading:"\u0141adowanie rozdzia\u0142\xF3w\u2026",empty:"Brak rozdzia\u0142\xF3w do wy\u015Bwietlenia.",resume:"Kontynuuj",chapterName:"Rozdzia\u0142",download:"Pobierz rozdzia\u0142",playing:"Teraz odtwarzane",played:"Ods\u0142uchane"},Wa={play:"Play",pause:"Pause",previous:"Previous chapter",next:"Next chapter",rewind:"Rewind 10 seconds",forward:"Forward 10 seconds",progress:"Playback progress",of:"of",speed:"Speed",sleep:"Sleep timer",off:"Off",end:"End of chapter",cancel:"Cancel timer",error:"The recording could not be played.",retry:"Try again",left:"left",book:"whole book",chapter:"chapter",chapters:"Chapters",loading:"Loading chapters\u2026",empty:"No chapters to display.",resume:"Continue",chapterName:"Chapter",download:"Download chapter",playing:"Now playing",played:"Played"};function At(e){let[t,n]=_react3.useState.call(void 0, "pl");return _react3.useEffect.call(void 0, ()=>{try{n(_chunk7RXW6XFYjs.f.call(void 0, ))}catch (e9){}},[]),(_nullishCoalesce(e, () => (t))).toLowerCase().startsWith("en")?Wa:Ga}function ve(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;return`${t>=3600?`${Math.floor(t/3600)}:`:""}${String(Math.floor(t/60)%60).padStart(2,"0")}:${String(t%60).padStart(2,"0")}`}var W={get(e){try{return localStorage.getItem(e)}catch (e10){return null}},set(e,t){try{localStorage.setItem(e,t)}catch (e11){}},remove(e){try{localStorage.removeItem(e)}catch (e12){}}},br="__player__speed",Dt=[.75,1,1.25,1.5,1.75,2];var ri=_react3.forwardRef.call(void 0, ({chapters:e,locale:t,styles:n,updateCurrentTime:a,setCurrentTimeHandler:r,title:o,imageURL:i,coverShownBeside:d,author:c,uniqueProductID:l,onChapterChange:b,onError:P,onExpiredUrl:w,onFinished:h},y)=>{let u=At(t),[m,p]=_react3.useState.call(void 0, 1),x=_react3.useRef.call(void 0, 1),[U,le]=_react3.useState.call(void 0, ),[E,de]=_react3.useState.call(void 0, "off"),[Ce,ee]=_react3.useState.call(void 0, 0),A=_react3.useRef.call(void 0, {mode:"off",deadline:0});function fe(){A.current={mode:"off",deadline:0},de("off"),ee(0)}function J(s){let g=Number(s)*60;A.current={mode:s,deadline:Number.isFinite(g)?Date.now()+g*1e3:0},de(s),ee(Number.isFinite(g)?g:0)}function He(s){Dt.includes(s)&&(p(s),x.current=s,W.set(br,String(s)),_.current&&(_.current.playbackRate=s),B())}_react3.useEffect.call(void 0, ()=>{let s=Number(W.get(br));Dt.includes(s)&&He(s);let g=setInterval(()=>{let{mode:k,deadline:T}=A.current;if(k==="off"||k==="chapter")return;let be=Math.max(0,Math.ceil((T-Date.now())/1e3));ee(be),be===0&&(Me.current=!1,xt(),fe())},1e3);return()=>clearInterval(g)},[]);let Y;(k=>(k[k.Playing=0]="Playing",k[k.Paused=1]="Paused"))(Y||={});let[De,lt]=_react3.useState.call(void 0, 1),[Ht,Ne]=_react3.useState.call(void 0, void 0),[C,ge]=_react3.useState.call(void 0, void 0),[$e,ce]=_react3.useState.call(void 0, !1),[vt,Fr]=_react3.useState.call(void 0, null),_=_react3.useRef.call(void 0, null),ye=_react3.useRef.call(void 0, null),kt=_react3.useRef.call(void 0, void 0),Go=_react3.useRef.call(void 0, null),te=_react3.useRef.call(void 0, null),$t=_react3.useRef.call(void 0, null),Me=_react3.useRef.call(void 0, !1),qe=_react3.useRef.call(void 0, !1),dt=_react3.useRef.call(void 0, null),qt=_react3.useRef.call(void 0, null),Bt=_react3.useRef.call(void 0, e),Hr=_react3.useRef.call(void 0, null),re=_react3.useRef.call(void 0, {onChapterChange:b,onError:P,onExpiredUrl:w,onFinished:h,updateCurrentTime:a,title:o,imageURL:i,author:c});re.current={onChapterChange:b,onError:P,onExpiredUrl:w,onFinished:h,updateCurrentTime:a,title:o,imageURL:i,author:c};function Kt(s){!qe.current||!Number.isFinite(s)||s<0||W.set(`__player__${l}_${_optionalChain([te, 'access', _31 => _31.current, 'optionalAccess', _32 => _32.id])}`,`${Math.floor(s)}`)}function Wo(){let s=W.get(`__player__${l}_${_optionalChain([te, 'access', _33 => _33.current, 'optionalAccess', _34 => _34.id])}`);if(s!=null)try{let g=parseInt(s);return isNaN(g)||g<0?void 0:g}catch (e13){return}}function Vo(){let s=W.get(`__player__${l}_last_chapter`);if(s!=null)return s}function $r(s){W.set(`__player__${l}_last_chapter`,s)}function qr(s){W.remove(`__player__${l}_${s}`)}function Gt(s){hr({title:_nullishCoalesce(_nullishCoalesce(_optionalChain([s, 'optionalAccess', _35 => _35.name]), () => (re.current.title)), () => ("")),album:re.current.title,artist:re.current.author,artwork:re.current.imageURL})}function Br(s){$t.current=s,Fr(s),ce(!1),_optionalChain([re, 'access', _36 => _36.current, 'access', _37 => _37.onError, 'optionalCall', _38 => _38(s)])}function Kr(){$t.current=null,Fr(null)}function Gr(){let s=_.current;if(s==null)return;let g=s.play();g!=null&&typeof g.catch=="function"&&g.catch(()=>{}),B()}function Wr(){Gr()}function xt(){_optionalChain([_, 'access', _39 => _39.current, 'optionalAccess', _40 => _40.pause, 'call', _41 => _41()]),B()}function Jo(){if(De===0){xt();return}Wr()}function Ie(s){let g=_.current;if(g==null||!Number.isFinite(s))return;let k=Number.isFinite(g.duration)?g.duration:0,T=k>0?Math.min(Math.max(s,0),k):Math.max(s,0);Ne(T),g.currentTime=T,B()}function wt(s){let g=_.current;if(g==null)return;let k=Number.isFinite(g.duration)?g.duration:void 0,T=Math.max(g.currentTime+s,0);k!=null&&T>k&&(T=k),Ie(T)}function Wt(s){let g=_.current;if(g!=null){if(Kr(),ce(!0),Kn(g)){Vt(),g.src=s,g.load();return}if(_hlsjs2.default.isSupported()){ye.current==null&&(ye.current=Bn({media:g,handlers:{onError:k=>{Br(k)},onExpiredUrl:()=>{_optionalChain([re, 'access', _42 => _42.current, 'access', _43 => _43.onExpiredUrl, 'optionalCall', _44 => _44()])}}})),ye.current.load(s);return}Vt(),g.src=s,g.load()}}function Vt(){_optionalChain([ye, 'access', _45 => _45.current, 'optionalAccess', _46 => _46.destroy, 'call', _47 => _47()]),ye.current=null}function Ct(s,g){let k=_optionalChain([g, 'optionalAccess', _48 => _48.play])===!0;te.current&&_.current&&!_.current.ended&&Kt(_.current.currentTime),qe.current=!1,dt.current=null,Me.current=k,te.current=s,le(s.id),Ne(0),ge(s.duration),Wt(s.publicUrl),Gt(s),_optionalChain([re, 'access', _49 => _49.current, 'access', _50 => _50.onChapterChange, 'optionalCall', _51 => _51(s)]),$r(s.id)}function Jt(s){if(s.length===0)return;let g=Vo(),k=_nullishCoalesce((g!=null?s.find(T=>T.id===g):void 0), () => (s[0]));Ct(k,{play:!1})}function Yt(){let s=Bt.current,g=te.current;if(s==null||s.length===0||g==null)return;let k=s.findIndex(be=>be.id===g.id);if(k===-1)return;let T=k+1;if(T>=s.length){Yo(g);return}Ct(s[T],{play:!0})}function Vr(){let s=Bt.current,g=te.current;if(g==null)return;let k=_.current;if(k!=null&&k.currentTime>3){Ie(0);return}let T=s==null?-1:s.findIndex(be=>be.id===g.id);if(T>0){Ct(s[T-1],{play:!0});return}Ie(0)}function Yo(s){qr(s.id),Me.current=!1,_optionalChain([_, 'access', _52 => _52.current, 'optionalAccess', _53 => _53.pause, 'call', _54 => _54()]),lt(1),_optionalChain([re, 'access', _55 => _55.current, 'access', _56 => _56.onFinished, 'optionalCall', _57 => _57()])}function Jr(){let s=te.current;if(s!=null){if(W.set(`__player__${l}_${s.id}_completed`,"true"),qr(s.id),A.current.mode==="chapter"){Me.current=!1,xt(),fe();return}Yt(),B()}}function Yr(){let s=_.current;if(s!=null){if(ce(!1),s.playbackRate=x.current,qt.current=null,!qe.current){qe.current=!0;let g=dt.current;if(dt.current=null,g!=null)Ie(g);else{let k=Wo();k!=null&&Ie(k)}}Me.current&&(Me.current=!1,Gr())}}function Zr(){let s=_optionalChain([_, 'access', _58 => _58.current, 'optionalAccess', _59 => _59.error]),g=_optionalChain([te, 'access', _60 => _60.current, 'optionalAccess', _61 => _61.publicUrl]);(_optionalChain([s, 'optionalAccess', _62 => _62.code])===2||_optionalChain([s, 'optionalAccess', _63 => _63.code])===4)&&ye.current==null&&g!=null&&qt.current!==g&&(qt.current=g,_optionalChain([re, 'access', _64 => _64.current, 'access', _65 => _65.onExpiredUrl, 'optionalCall', _66 => _66()])),Br(Gn(s))}function Qr(){let g=_nullishCoalesce(_optionalChain([te, 'access', _67 => _67.current, 'optionalAccess', _68 => _68.publicUrl]), () => (_optionalChain([ye, 'access', _69 => _69.current, 'optionalAccess', _70 => _70.src])));if(g==null)return;let T=_nullishCoalesce(_optionalChain([_, 'access', _71 => _71.current, 'optionalAccess', _72 => _72.currentTime]), () => (0));Kr(),qe.current=!1,dt.current=T>0?T:null,Ne(T),ye.current!=null?ye.current.retry():Wt(g)}function Zo(s){switch(s.action){case"play":Wr();break;case"pause":case"stop":xt();break;case"seekbackward":wt(-(_nullishCoalesce(s.seekOffset, () => (10))));break;case"seekforward":wt(_nullishCoalesce(s.seekOffset, () => (10)));break;case"seekto":s.seekTime!=null&&Ie(s.seekTime);break;case"previoustrack":Vr();break;case"nexttrack":Yt();break;default:break}}_react3.useImperativeHandle.call(void 0, y,()=>({selectChapter:s=>{Ct(s,{play:!0})},retry:Qr,getError:()=>$t.current}));function B(){let s=_.current;s!=null&&(lt(s.paused?1:0),ge(s.duration),Ne(s.currentTime),s.ended||Kt(s.currentTime),Jn(s.duration,s.currentTime,s.playbackRate),s.networkState===s.NETWORK_LOADING&&s.readyState<=s.HAVE_FUTURE_DATA?ce(!0):ce(!1),_optionalChain([re, 'access', _73 => _73.current, 'access', _74 => _74.updateCurrentTime, 'optionalCall', _75 => _75(s.currentTime)]))}_react3.useEffect.call(void 0, ()=>(Zn({title:_nullishCoalesce(o, () => ("")),album:o,artist:c,artwork:i,action:Zo}),()=>{Qn()}),[]),_react3.useEffect.call(void 0, ()=>{Gt(te.current)},[o,c,i]),_react3.useEffect.call(void 0, ()=>{let s=_.current;if(s!=null)return s.addEventListener("loadeddata",Yr),s.addEventListener("ended",Jr),s.addEventListener("error",Zr),s.addEventListener("timeupdate",B),s.addEventListener("play",B),s.addEventListener("pause",B),s.addEventListener("ratechange",B),B(),kt.current=setInterval(B,500),()=>{s.removeEventListener("loadeddata",Yr),s.removeEventListener("ended",Jr),s.removeEventListener("error",Zr),s.removeEventListener("timeupdate",B),s.removeEventListener("play",B),s.removeEventListener("pause",B),s.removeEventListener("ratechange",B),kt.current!=null&&(clearInterval(kt.current),kt.current=void 0),s.ended||Kt(s.currentTime),Ne(void 0),s.pause(),Vt(),s.removeAttribute("src"),s.load()}},[]),_react3.useEffect.call(void 0, ()=>{_optionalChain([r, 'optionalCall', _76 => _76(Ie)])},[]);let Zt=e.map(s=>`${s.id}|${_nullishCoalesce(s.publicUrl, () => (""))}`).join(`
4
+ `);_react3.useEffect.call(void 0, ()=>{Bt.current=e;let s=Hr.current;if(s===Zt)return;if(Hr.current=Zt,s==null){Jt(e);return}let g=te.current;if(g==null){Jt(e);return}let k=e.find(T=>T.id===g.id);if(!(k!=null&&k.publicUrl===g.publicUrl)){if(k!=null){let T=_.current,be=_nullishCoalesce(_optionalChain([T, 'optionalAccess', _77 => _77.currentTime]), () => (0)),Xo=T!=null&&!T.paused;te.current=k,qe.current=!1,dt.current=be>0?be:null,Me.current=Xo,Wt(k.publicUrl),Gt(k),_optionalChain([re, 'access', _78 => _78.current, 'access', _79 => _79.onChapterChange, 'optionalCall', _80 => _80(k)]),$r(k.id);return}Jt(e)}},[Zt]),_react3.useEffect.call(void 0, ()=>{switch(De){case 0:Wn();break;case 1:Vn();break}},[De]);let Be=e.findIndex(s=>s.id===U),he=Number.isFinite(C)&&C>0?C:_nullishCoalesce(_optionalChain([e, 'access', _81 => _81[Be], 'optionalAccess', _82 => _82.duration]), () => (0)),ct=Math.min(Math.max(_nullishCoalesce(Ht, () => (0)),0),he||1/0),Xr=e.length>0&&e.every(s=>Number.isFinite(s.duration)&&s.duration>0),Qo=Math.max(0,he-ct+(Xr?e.slice(Be+1).reduce((s,g)=>s+g.duration,0):0))/m,Qt=Math.ceil(Qo/60),en=`${Math.floor(Qt/60)>0?`${Math.floor(Qt/60)} h `:""}${Qt%60} min`;return _jsxruntime.jsxs.call(void 0, "div",{id:"audio-player-container",className:"bitsnap-audio-player flex min-w-0 flex-col gap-3 text-neutral-900 dark:text-neutral-100",style:{...n,"--seek-before-width":`${he>0?ct/he*100:0}%`},ref:Go,"data-player-error":_optionalChain([vt, 'optionalAccess', _83 => _83.kind]),children:[_jsxruntime.jsx.call(void 0, "video",{ref:_,className:"hidden",poster:i,title:o}),_jsxruntime.jsxs.call(void 0, "div",{className:_chunk4HGZZJELjs.g.call(void 0, "flex min-w-0 items-center gap-3",d&&"lg:hidden"),children:[i&&_jsxruntime.jsx.call(void 0, "img",{src:i,alt:"",className:"h-16 w-16 shrink-0 rounded object-contain"}),_jsxruntime.jsxs.call(void 0, "div",{className:"min-w-0 break-words",children:[_jsxruntime.jsx.call(void 0, "p",{className:"font-semibold",children:_nullishCoalesce(_optionalChain([e, 'access', _84 => _84[Be], 'optionalAccess', _85 => _85.name]), () => (o))}),c&&_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-600 dark:text-neutral-300",children:c})]})]}),vt&&_jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:"rounded-lg bg-red-50 p-3 text-red-800 dark:bg-red-950 dark:text-red-200",children:[_jsxruntime.jsx.call(void 0, "p",{children:u.error}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{variant:"outline",onClick:Qr,children:u.retry})]}),_jsxruntime.jsx.call(void 0, "input",{type:"range",min:"0",max:he||100,value:ct,disabled:!he,"aria-label":u.progress,"aria-valuetext":`${ve(ct)} ${u.of} ${ve(he)}`,onChange:s=>Ie(Number(s.target.value))}),_jsxruntime.jsxs.call(void 0, "section",{className:"flex w-full justify-between text-sm tabular-nums",children:[_jsxruntime.jsx.call(void 0, "span",{id:"current-time",children:ve(ct)}),_jsxruntime.jsx.call(void 0, "span",{id:"duration",children:ve(he)})]}),he>0&&_jsxruntime.jsxs.call(void 0, "p",{className:"text-sm text-neutral-600 dark:text-neutral-300",children:[u.left==="left"?`${en} ${u.left}`:`${u.left} ${en}`," ","\xB7 ",Xr?u.book:u.chapter," (",m,"\xD7)"]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap items-center justify-center gap-2",children:[_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{variant:"outline",onClick:Vr,disabled:Be<0,"aria-label":u.previous,children:_jsxruntime.jsx.call(void 0, _lucidereact.SkipBack,{className:"h-5 w-5"})}),_jsxruntime.jsxs.call(void 0, _chunkG4V2KWTVjs.q,{variant:"outline",onClick:()=>wt(-10),"aria-label":u.rewind,children:["\u2212",10]}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{variant:"outline",onClick:Jo,"aria-label":De===1?u.play:u.pause,children:De===1?_jsxruntime.jsx.call(void 0, _lucidereact.Play,{className:"h-5 w-5"}):_jsxruntime.jsx.call(void 0, _lucidereact.Pause,{className:"h-5 w-5"})}),_jsxruntime.jsxs.call(void 0, _chunkG4V2KWTVjs.q,{variant:"outline",onClick:()=>wt(10),"aria-label":u.forward,children:["+",10]}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{variant:"outline",onClick:Yt,disabled:Be<0||Be>=e.length-1,"aria-label":u.next,children:_jsxruntime.jsx.call(void 0, _lucidereact.SkipForward,{className:"h-5 w-5"})})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap gap-3 md:grid md:grid-cols-2",children:[_jsxruntime.jsxs.call(void 0, "label",{className:"flex flex-1 items-center gap-2 text-sm md:flex-col md:items-start md:whitespace-nowrap",children:[u.speed,_jsxruntime.jsx.call(void 0, "select",{"aria-label":u.speed,value:m,onChange:s=>He(Number(s.target.value)),children:Dt.map(s=>_jsxruntime.jsxs.call(void 0, "option",{value:s,children:[s,"\xD7"]},s))})]}),_jsxruntime.jsxs.call(void 0, "label",{className:"flex flex-1 items-center gap-2 text-sm md:flex-col md:items-start md:whitespace-nowrap",children:[u.sleep,_jsxruntime.jsxs.call(void 0, "select",{"aria-label":u.sleep,value:E,onChange:s=>J(s.target.value),children:[_jsxruntime.jsx.call(void 0, "option",{value:"off",children:u.off}),[15,30,45,60].map(s=>_jsxruntime.jsxs.call(void 0, "option",{value:s,children:[s," min"]},s)),_jsxruntime.jsx.call(void 0, "option",{value:"chapter",children:u.end})]})]})]}),E!=="off"&&_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-center justify-between gap-2 text-sm",children:[_jsxruntime.jsx.call(void 0, "span",{role:"timer",children:E==="chapter"?u.end:ve(Ce)}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{variant:"outline",onClick:fe,children:u.cancel})]}),$e&&_jsxruntime.jsx.call(void 0, "div",{role:"status",className:"flex justify-center",children:_jsxruntime.jsx.call(void 0, _e,{})})]})}),Xn=ri;function Pr({chapters:e,currentID:t,productID:n,onSelect:a,downloadable:r,onDownload:o,loading:i,locale:d}){let c=At(d),[l,b]=_react3.useState.call(void 0, null),[P,w]=_react3.useState.call(void 0, []);_react3.useEffect.call(void 0, ()=>{let u=`__player__${n}_`,m=W.get(`${u}last_chapter`),p=Number(m&&W.get(`${u}${m}`));b(m&&p>0&&Number.isFinite(p)?{id:m,time:p}:null),w((_nullishCoalesce(e, () => ([]))).filter(x=>W.get(`${u}${x.id}_completed`)==="true"||Number(W.get(`${u}${x.id}`))>0).map(x=>x.id))},[e,n,t]);let h=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _86 => _86.findIndex, 'call', _87 => _87(u=>u.id===_optionalChain([l, 'optionalAccess', _88 => _88.id]))]), () => (-1)),y=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _89 => _89.findIndex, 'call', _90 => _90(u=>u.id===t)]), () => (-1));return _jsxruntime.jsxs.call(void 0, "div",{className:"max-h-96 w-full overflow-y-auto",children:[_jsxruntime.jsx.call(void 0, "h2",{className:"mb-3 text-xl font-semibold",children:c.chapters}),i?_jsxruntime.jsx.call(void 0, "p",{role:"status",children:c.loading}):_optionalChain([e, 'optionalAccess', _91 => _91.length])?_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[l&&h>=0&&_jsxruntime.jsxs.call(void 0, "button",{type:"button",className:"mb-3 min-h-11 rounded-lg border border-neutral-300 px-3 py-2 text-left dark:border-neutral-600",onClick:()=>a(e[h]),children:[c.resume,": ",c.chapterName," ",h+1,","," ",ve(l.time)]}),_jsxruntime.jsx.call(void 0, "ul",{className:"flex w-full flex-col gap-2",children:e.map((u,m)=>{let p=u.id===t,x=m<y||P.includes(u.id);return _jsxruntime.jsxs.call(void 0, "li",{className:"flex min-w-0 items-center gap-2",children:[_jsxruntime.jsxs.call(void 0, "button",{type:"button","aria-current":p?"true":void 0,className:`min-h-11 min-w-0 flex-1 rounded-lg p-3 text-left hover:bg-neutral-200 dark:hover:bg-neutral-700 ${p?"bg-neutral-200 dark:bg-neutral-700":"bg-neutral-100 dark:bg-neutral-800"}`,onClick:()=>a(u),children:[_jsxruntime.jsxs.call(void 0, "span",{className:"flex items-center gap-2",children:[p?_jsxruntime.jsx.call(void 0, _lucidereact.Play,{className:"size-4 shrink-0","aria-label":c.playing}):x?_jsxruntime.jsx.call(void 0, _lucidereact.Check,{className:"size-4 shrink-0","aria-label":c.played}):null,_jsxruntime.jsx.call(void 0, "span",{className:"min-w-0 flex-1 break-words text-sm font-medium",children:u.name}),!!u.duration&&_jsxruntime.jsx.call(void 0, "span",{className:"shrink-0 text-xs tabular-nums text-neutral-600 dark:text-neutral-300",children:ve(u.duration)})]}),u.description&&_jsxruntime.jsx.call(void 0, "span",{className:"mt-2 block text-xs",children:u.description})]}),r&&u.downloadableUrl&&_jsxruntime.jsx.call(void 0, "a",{href:u.downloadableUrl,onClick:o,"aria-label":`${c.download} ${m+1}`,className:"inline-flex min-h-11 min-w-11 items-center justify-center rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:_jsxruntime.jsx.call(void 0, _lucidereact.Download,{className:"size-4","aria-hidden":"true"})})]},u.id)})})]}):_jsxruntime.jsx.call(void 0, "p",{children:c.empty})]})}function xe(e,...t){console.warn(e,...t)}function vr(e){console.error(e)}var ui=({accessToken:e,product:t,styles:n,reveal:a})=>{let r=Qe(),o=t.productType,i=_chunkDP2NOHCIjs.m.call(void 0, ),d=()=>i.track("panel_download",{},{product_id:t.productId.length<=64?t.productId:null}),c=_react3.useRef.call(void 0, null),[l]=_react.useAutoAnimate.call(void 0, ),[b,P]=_react3.useState.call(void 0, !1),[w,h]=_react3.useState.call(void 0, null),{mutateAsync:y,isPending:u}=_chunkG4V2KWTVjs.m.call(void 0, _chunkG4V2KWTVjs.k.publicApi.userPanelGetFileDetails),m=_react3.useRef.call(void 0, void 0),[p,x]=_react3.useState.call(void 0, null),[U,le]=_react3.useState.call(void 0, null),[E,de]=_react3.useState.call(void 0, !1),{mutateAsync:Ce,isPending:ee}=_chunkG4V2KWTVjs.m.call(void 0, _chunkG4V2KWTVjs.k.publicApi.userPanelGetAudiobookDetails),{mutateAsync:A,isPending:fe}=_chunkG4V2KWTVjs.m.call(void 0, _chunkG4V2KWTVjs.k.publicApi.userPanelGetAudiobookDetailsDownloadURLs),[J,He]=_react3.useState.call(void 0, null),[Y,De]=_react3.useState.call(void 0, null);async function lt(){P(!1);try{let C=await y({accessId:t.accessId,accessToken:e});if(C.result.case==="success"){h(C.result.value.files);return}else P(!0),xe("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),xe("Kod b\u0142\u0119du: ",C.result.value)}catch(C){P(!0),xe("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),vr("B\u0142\u0105d podczas pobierania danych:"+C)}}async function Ht(){try{let C=await Ce({accessId:t.accessId,accessToken:e});if(C.result.case==="audiobook"){x(C.result.value);return}else xe("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),xe("Kod b\u0142\u0119du: ",C.result.value)}catch(C){xe("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),vr("B\u0142\u0105d podczas pobierania danych:"+C)}}async function Ne(){try{let C=await A({accessId:t.accessId,accessToken:e,isBrowser:!0});if(C.result.case==="success"){le(C.result.value.audiobookDownloadDetails),de(C.result.value.isAvailableToDownloadInMobileApp===!0);return}else xe("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),xe("Kod b\u0142\u0119du: ",C.result.value)}catch(C){xe("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),vr("B\u0142\u0105d podczas pobierania danych:"+C)}}return _react3.useEffect.call(void 0, ()=>{o===2&&lt(),o===1&&(Ht().then().catch(),Ne().then().catch())},[]),_react3.useEffect.call(void 0, ()=>{if(p!=null&&U!=null){let C=p.chapters;if(!C)return;let ge=C.map($e=>{let ce=_optionalChain([U, 'optionalAccess', _92 => _92.find, 'call', _93 => _93(vt=>vt.chapterId===$e.id)]);if(ce!=null)return{...$e,publicUrl:ce.publicUrl,downloadableUrl:ce.downloadableUrl,duration:ce.duration}}).filter($e=>$e!=null);ge!=null&&ge.length>0&&De(ge)}},[p,U]),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "div",{className:"mb-3 space-y-4 rounded bg-white p-4 dark:bg-black",children:_jsxruntime.jsxs.call(void 0, _chunkG4V2KWTVjs.q,{onClick:()=>a(),variant:"ghost",className:"min-h-11 w-fit",children:[_jsxruntime.jsx.call(void 0, _lucidereact.ChevronLeft,{className:"h-6 w-6"}),_jsxruntime.jsx.call(void 0, "span",{className:"font-inter text-sm font-medium",children:r.back})]})}),_jsxruntime.jsxs.call(void 0, "main",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[_jsxruntime.jsxs.call(void 0, "header",{className:"flex min-w-0 flex-col gap-4 rounded-xl border border-neutral-200 bg-white p-4 dark:border-neutral-700 dark:bg-neutral-900 lg:row-span-2 lg:self-start",children:[_jsxruntime.jsx.call(void 0, "img",{src:t.productImageUrl,alt:t.productName,width:384,height:384,draggable:!1,className:"aspect-square max-h-72 w-full object-contain"}),_jsxruntime.jsx.call(void 0, "h2",{className:"text-2xl font-semibold",children:t.productName})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex min-w-0 flex-col gap-6",children:[o===2&&_jsxruntime.jsxs.call(void 0, "section",{ref:l,className:"flex flex-col gap-4 rounded-xl border border-neutral-200 bg-white p-4 dark:border-neutral-700 dark:bg-neutral-900",children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-xl font-semibold",children:r.yourFiles}),u&&_jsxruntime.jsx.call(void 0, "div",{role:"status","aria-label":r.loading,children:_jsxruntime.jsx.call(void 0, _e,{})}),b&&_jsxruntime.jsxs.call(void 0, "div",{role:"alert",children:[_jsxruntime.jsx.call(void 0, "p",{children:r.fileError}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{className:"min-h-11",onClick:lt,children:r.retry})]}),_optionalChain([w, 'optionalAccess', _94 => _94.length])===0&&_jsxruntime.jsx.call(void 0, "p",{children:r.noFiles}),w&&_jsxruntime.jsx.call(void 0, "ul",{className:"flex flex-col gap-3",children:w.map((C,ge)=>_jsxruntime.jsxs.call(void 0, "li",{className:"flex min-w-0 flex-wrap items-center justify-between gap-3",children:[_jsxruntime.jsx.call(void 0, "span",{className:"min-w-0 break-all text-sm",children:no(C)||`${r.file} ${ge+1}`}),_jsxruntime.jsxs.call(void 0, "a",{target:"_blank",rel:"noopener noreferrer",href:C,download:!0,onClick:d,className:"inline-flex min-h-11 items-center gap-2 rounded-md bg-neutral-900 px-3 py-2 text-sm text-white focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 dark:bg-neutral-100 dark:text-neutral-900","aria-label":`${r.download}: ${no(C)||`${r.file} ${ge+1}`}`,children:[r.download,_jsxruntime.jsx.call(void 0, _lucidereact.Download,{className:"size-4","aria-hidden":"true"})]})]},C))})]}),o===3&&_jsxruntime.jsxs.call(void 0, "section",{className:"rounded-xl border border-neutral-200 bg-white p-4 dark:border-neutral-700 dark:bg-neutral-900",children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-lg font-semibold",children:r.ticket}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-2 font-medium",children:t.productName}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-2 text-sm text-neutral-600 dark:text-neutral-300",children:r.ticketInfo})]}),o===1&&_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:_jsxruntime.jsxs.call(void 0, "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:[_jsxruntime.jsx.call(void 0, "h4",{className:"text-xl font-semibold",children:_nullishCoalesce(_optionalChain([J, 'optionalAccess', _95 => _95.name]), () => ("Odtwarzacz"))}),_optionalChain([J, 'optionalAccess', _96 => _96.description])&&_jsxruntime.jsx.call(void 0, "p",{className:"text-sm",children:_optionalChain([J, 'optionalAccess', _97 => _97.description])}),_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:ee?_jsxruntime.jsxs.call(void 0, "div",{className:"flex gap-2",children:[_jsxruntime.jsx.call(void 0, _e,{}),_jsxruntime.jsx.call(void 0, "p",{className:"text-xl font-semibold",children:"Trwa pobierania audiobooka..."})]}):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:Y!=null?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:_jsxruntime.jsx.call(void 0, Xn,{ref:c,coverShownBeside:!0,chapters:Y,author:typeof _optionalChain([p, 'optionalAccess', _98 => _98.author])=="string"?p.author:void 0,onExpiredUrl:()=>{Ne()},title:_nullishCoalesce(_nullishCoalesce(_optionalChain([p, 'optionalAccess', _99 => _99.name]), () => (t.productName)), () => (void 0)),imageURL:_nullishCoalesce(_nullishCoalesce(_optionalChain([p, 'optionalAccess', _100 => _100.coverImage]), () => (t.productImageUrl)), () => (void 0)),styles:n,setCurrentTimeHandler:C=>{m.current=C},uniqueProductID:t.productId,onChapterChange:C=>{He(C)}})}):_jsxruntime.jsx.call(void 0, "p",{className:"mt-2",children:"Wybierz rozdzia\u0142, kt\xF3ry ci\u0119 interesuje."})})}),_jsxruntime.jsxs.call(void 0, "div",{className:"rounded-xl bg-neutral-100 p-3 dark:bg-neutral-800",children:[_jsxruntime.jsx.call(void 0, "p",{className:"mt-3 mb-3 text-xs",children:E?"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."}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex gap-3",children:[_jsxruntime.jsx.call(void 0, "a",{href:"https://apps.apple.com/us/app/bitsnap/id6741902807",children:_jsxruntime.jsx.call(void 0, "img",{width:"100",src:"https://bitsnap.pl/appstore.svg",alt:"Pobierz aplikacje z AppStore"})}),_jsxruntime.jsx.call(void 0, "a",{href:"https://play.google.com/store/apps/details?id=com.bitsnap.Bitsnap",children:_jsxruntime.jsx.call(void 0, "img",{width:"100",src:"https://bitsnap.pl/playstore.svg",alt:"Pobierz aplikacj\u0119 z GooglePlay"})})]})]})]})}),_jsxruntime.jsx.call(void 0, "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:o===1&&_jsxruntime.jsx.call(void 0, Pr,{chapters:Y,currentID:_optionalChain([J, 'optionalAccess', _101 => _101.id]),productID:t.productId,loading:ee,downloadable:_optionalChain([p, 'optionalAccess', _102 => _102.isDownloadable])===!0,onDownload:d,onSelect:C=>_optionalChain([c, 'access', _103 => _103.current, 'optionalAccess', _104 => _104.selectChapter, 'call', _105 => _105(C)])})})]}),_jsxruntime.jsx.call(void 0, "section",{className:"rounded-xl border border-neutral-200 bg-white p-4 dark:border-neutral-700 dark:bg-neutral-900",children:_jsxruntime.jsx.call(void 0, "p",{className:"whitespace-pre-wrap text-sm text-neutral-600 dark:text-neutral-300",children:t.productDescription})})]})]})},oo=ui;function no(e){try{return decodeURIComponent(new URL(e,"https://bitsnap.pl").pathname.split("/").pop()||"")}catch (e14){return""}}var _connectquery = require('@connectrpc/connect-query');function ao(e,t){let n=_connectquery.useTransport.call(void 0, ),[a,r]=_react3.useState.call(void 0, {status:"loading"});return _react3.useEffect.call(void 0, ()=>{if(!e){r({status:"hidden"});return}let o=!1;return r({status:"loading"}),Promise.resolve().then(() => _interopRequireWildcard(require("./model-files-client-P4PORZJ6.js"))).then(({listModelFiles:i})=>i(n,e,t)).catch(()=>({status:"hidden"})).then(i=>{o||r(i)}),()=>{o=!0}},[n,e,t]),a}var wi=_react3.lazy.call(void 0, ()=>Promise.resolve().then(() => _interopRequireWildcard(require("./PanelModelFiles-7HPXWONN.js")))),Ci=({accessToken:e,projectID:t,loginURL:n,styles:a,activeScreen:r,params:o,setParams:i,openCourse:d})=>{let{host:c}=_chunkVNV5BD4Xjs.j.call(void 0, ),{data:l,isLoading:b,error:P,refetch:w}=_chunkG4V2KWTVjs.l.call(void 0, _chunkG4V2KWTVjs.k.publicApi.userPanelGetProducts,{accessToken:e}),h=ao(e,t),y=Ni({products:b?{status:"loading"}:P!=null?{status:"error"}:_optionalChain([l, 'optionalAccess', _106 => _106.result, 'access', _107 => _107.case])==="success"?{status:"ok",count:l.result.value.products.length}:_optionalChain([l, 'optionalAccess', _108 => _108.result, 'access', _109 => _109.case])==="failure"?{status:"failure",unauthorized:l.result.value===9}:{status:"error"},modelFiles:h});if(_react3.useEffect.call(void 0, ()=>{y.kind==="signed-out"&&(_chunkVNV5BD4Xjs.n.call(void 0, t,c),window.location.href=n)},[y.kind,t,c,n]),y.kind==="loading"||y.kind==="signed-out")return _jsxruntime.jsx.call(void 0, "div",{role:"status","aria-label":Qe().loading,"aria-busy":"true",className:"grid grid-cols-2 gap-4 sm:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5",children:Array.from({length:6},(x,U)=>_jsxruntime.jsx.call(void 0, "div",{"aria-hidden":"true",className:"h-72 rounded-xl bg-neutral-100 motion-safe:animate-pulse dark:bg-neutral-800"},U))});let u=l&&l.result.case==="success"?l.result.value.products:[],m=h.status==="ready"?h.models:[],p=m.length>0?_jsxruntime.jsx.call(void 0, _react3.Suspense,{fallback:null,children:_jsxruntime.jsx.call(void 0, wi,{accessToken:e,models:m,buttonStyle:a})}):null;return y.kind==="error"?_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, Si,{onRetry:()=>void w()}),p]}):y.kind==="empty"?_jsxruntime.jsx.call(void 0, Ii,{}):_jsxruntime.jsx.call(void 0, Ei,{accessToken:e,products:u,styles:a,activeScreen:r,params:o,setParams:i,openCourse:d,filesSection:p})};function Ni({products:e,modelFiles:t}){if(e.status==="failure"&&e.unauthorized)return{kind:"signed-out"};if(e.status==="loading")return{kind:"loading"};if(e.status==="ok"&&e.count>0)return{kind:"list"};if(t.status==="loading")return{kind:"loading"};if(e.status==="failure"||e.status==="error")return t.status==="unauthorized"?{kind:"signed-out"}:{kind:"error"};let n=t.status==="ready"?t.models.length:0;return e.count===0&&n===0?{kind:"empty"}:{kind:"list"}}function Ii(){let e=Qe();return _jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col items-start gap-1","data-testid":"panel-empty",children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-2xl",children:e.hello}),_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-500",children:e.empty})]})}function Si({onRetry:e}){let t=_chunk7RXW6XFYjs.f.call(void 0, ).toLowerCase().startsWith("en");return _jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col items-start gap-3",role:"alert","data-testid":"panel-error",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-600 dark:text-neutral-300",children:t?"Your products could not be loaded.":"Nie uda\u0142o si\u0119 wczyta\u0107 Twoich produkt\xF3w."}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{type:"button",onClick:e,className:"text-sm",children:t?"Try again":"Spr\xF3buj ponownie"})]})}var so=Ci,Ei=({accessToken:e,products:t,styles:n,filesSection:a,activeScreen:r,params:o,setParams:i,openCourse:d})=>{let c=Qe(),[l,b]=_react3.useState.call(void 0, ()=>io(o.product,t));_react3.useEffect.call(void 0, ()=>{b(io(o.product,t))},[o.product,t]);let P=h=>{b(h),i({product:h?h.accessId||h.productId:void 0,state:"products"})};_react3.useEffect.call(void 0, ()=>{r==="products"&&_optionalChain([l, 'optionalAccess', _110 => _110.productType])===4&&d(l.accessId)},[r,l,d]);function w(h){if(h.productType===4){d(h.accessId);return}P(h)}return r==="products"&&_optionalChain([l, 'optionalAccess', _111 => _111.productType])===4?null:r==="products"&&l!=null?_jsxruntime.jsx.call(void 0, oo,{accessToken:e,product:l,styles:n,reveal:P,onOpenCourse:d}):_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-2xl",children:c.hello}),t.length>0&&_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-500 dark:text-neutral-400",children:c.intro}),_jsxruntime.jsx.call(void 0, "div",{className:"mt-6 grid grid-cols-2 gap-4 sm:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5",children:t.map(h=>{let[y,u,m]=h.productType===1?[c.audio,c.listen,_lucidereact.Headphones]:h.productType===4?[c.course,c.openCourse,_lucidereact.BookOpen]:h.productType===3?[c.ticket,c.showTicket,_lucidereact.Ticket]:[c.files,c.downloadFiles,_lucidereact.Files];return _jsxruntime.jsxs.call(void 0, "button",{type:"button",onClick:()=>w(h),className:"flex min-h-11 min-w-0 flex-col overflow-hidden rounded-xl border border-neutral-200 bg-white text-left text-neutral-900 transition-colors hover:border-neutral-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-neutral-500 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-50 dark:hover:border-neutral-500",children:[_jsxruntime.jsxs.call(void 0, "span",{className:"flex w-full flex-col gap-3 bg-neutral-100 p-3 dark:bg-neutral-800",children:[_jsxruntime.jsxs.call(void 0, "span",{className:"flex w-fit items-center gap-1.5 rounded-md bg-white px-2 py-1 text-xs font-medium dark:bg-neutral-900",children:[_jsxruntime.jsx.call(void 0, m,{className:"size-4","aria-hidden":"true"}),y]}),_jsxruntime.jsx.call(void 0, "img",{src:h.productImageUrl,alt:h.productName,draggable:!1,className:"aspect-square w-full object-contain"})]}),_jsxruntime.jsxs.call(void 0, "span",{className:"flex flex-1 flex-col gap-3 p-3",children:[_jsxruntime.jsx.call(void 0, "span",{className:"line-clamp-2 font-semibold",children:h.productName}),_jsxruntime.jsx.call(void 0, "span",{className:"line-clamp-2 text-sm text-neutral-600 dark:text-neutral-300",children:Hn(h.productDescription)}),_jsxruntime.jsx.call(void 0, "span",{className:"mt-auto pt-2 text-sm font-medium underline underline-offset-4",children:u})]})]},h.accessId||h.productId)})}),a]})};function io(e,t){if(!e)return;let n=t.find(a=>(a.accessId||a.productId)===e||a.productId===e);if(n)return n;try{let a=_protobuf.fromJsonString.call(void 0, _chunkG4V2KWTVjs.e,e);return t.find(r=>a.accessId?r.accessId===a.accessId:r.productId===a.productId)}catch (e15){return}}var co=[{screen:"products",label:"libraryNavLabel",icon:_lucidereact.Library},{screen:"orders",label:"ordersNavLabel",icon:_lucidereact.Receipt},{screen:"returns",label:"returnsNavLabel",icon:_lucidereact.Undo2},{screen:"profile",label:"accountNavLabel",icon:_lucidereact.User}];function uo(e){return e==="course"?"products":e==="order-details"?"orders":e==="return-details"?"returns":e}function xr({activeScreen:e,setActiveScreen:t,setParams:n,theme:a,logout:r,email:o,projectID:i}){let d=ue(),{data:c}=_chunkZATPBYOAjs.b.call(void 0, _nullishCoalesce(i, () => ("")),!!i);return _jsxruntime.jsxs.call(void 0, "header",{className:"flex h-14 shrink-0 items-center border-b border-neutral-200 bg-white px-4 md:h-dvh md:w-56 md:flex-col md:items-stretch md:border-r md:border-b-0 md:py-5 dark:border-neutral-800 dark:bg-neutral-900",children:[_jsxruntime.jsxs.call(void 0, "div",{className:"flex min-w-0 items-center gap-3 md:mb-6 md:flex-col md:items-start",children:[_jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.c,{projectId:i,logoUrl:_optionalChain([a, 'optionalAccess', _112 => _112.logoURL]),logoDarkUrl:_optionalChain([a, 'optionalAccess', _113 => _113.logoDarkURL]),name:_optionalChain([c, 'optionalAccess', _114 => _114.name]),className:"shrink-0"}),_optionalChain([c, 'optionalAccess', _115 => _115.name])&&_jsxruntime.jsx.call(void 0, "span",{title:c.name,className:"truncate text-sm font-medium md:line-clamp-2 md:whitespace-normal",children:c.name})]}),_jsxruntime.jsx.call(void 0, "nav",{"aria-label":d.navigationLabel,className:"fixed inset-x-0 bottom-0 z-10 flex h-[calc(56px+env(safe-area-inset-bottom))] items-start justify-around border-t border-neutral-200 bg-white pb-[env(safe-area-inset-bottom)] md:static md:h-auto md:flex-1 md:flex-col md:justify-start md:gap-2 md:border-0 md:bg-transparent md:pb-0 dark:border-neutral-800 dark:bg-neutral-900",children:co.map(({screen:l,label:b,icon:P})=>{let w=uo(e)===l;return _jsxruntime.jsxs.call(void 0, "button",{type:"button","aria-current":w?"page":void 0,onClick:()=>{t(l),n({product:void 0,state:l})},className:_chunk4HGZZJELjs.g.call(void 0, "flex h-14 min-h-11 min-w-0 flex-1 flex-col items-center justify-center gap-1 px-1 text-[11px] focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-current md:h-11 md:w-full md:flex-none md:flex-row md:justify-start md:gap-3 md:rounded-md md:px-3 md:text-sm",w?"bg-neutral-100 font-semibold text-black dark:bg-neutral-800 dark:text-white":"text-neutral-600 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:bg-neutral-800"),children:[_jsxruntime.jsx.call(void 0, P,{className:"h-5 w-5 shrink-0","aria-hidden":"true"}),_jsxruntime.jsx.call(void 0, "span",{children:d[b]})]},l)})}),_jsxruntime.jsxs.call(void 0, "div",{className:"hidden border-t border-neutral-200 pt-4 md:block dark:border-neutral-800",children:[o&&_jsxruntime.jsx.call(void 0, "p",{title:o,className:"mb-3 truncate text-sm text-neutral-600 dark:text-neutral-400",children:o}),_jsxruntime.jsxs.call(void 0, "button",{type:"button",onClick:r,className:"flex min-h-11 w-full items-center gap-3 rounded-md px-3 text-sm text-red-700 hover:bg-red-50 focus-visible:outline-2 focus-visible:outline-current dark:text-red-400 dark:hover:bg-neutral-800",children:[_jsxruntime.jsx.call(void 0, _lucidereact.LogOut,{className:"h-4 w-4","aria-hidden":"true"}),d.logout]})]})]})}function wr({email:e,logout:t,onLocaleChange:n}){let[a,r]=_react3.useState.call(void 0, _chunk7RXW6XFYjs.f),o=ue(a);return _jsxruntime.jsxs.call(void 0, "section",{className:"w-full max-w-xl",children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-2xl",children:o.accountNavLabel}),_jsxruntime.jsx.call(void 0, "h4",{className:"mt-6 mb-2 text-sm font-medium text-neutral-600 dark:text-neutral-400",children:o.profileHeading}),_jsxruntime.jsxs.call(void 0, "div",{className:"divide-y divide-neutral-200 rounded-lg border border-neutral-200 bg-white dark:divide-neutral-800 dark:border-neutral-800 dark:bg-neutral-900",children:[_jsxruntime.jsxs.call(void 0, "div",{className:"p-4",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-600 dark:text-neutral-400",children:o.emailLabel}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-1 break-words",children:e||o.noData})]}),_jsxruntime.jsxs.call(void 0, "label",{className:"flex min-h-11 flex-wrap items-center justify-between gap-3 p-4",children:[_jsxruntime.jsx.call(void 0, "span",{children:o.languageLabel}),_jsxruntime.jsxs.call(void 0, "select",{value:a.toLowerCase().startsWith("en")?"en-US":"pl-PL",onChange:i=>{_chunk7RXW6XFYjs.e.call(void 0, i.target.value),r(i.target.value),_optionalChain([n, 'optionalCall', _116 => _116()])},className:"min-h-11 rounded-md border border-neutral-300 bg-white px-3 focus-visible:outline-2 focus-visible:outline-current dark:border-neutral-700 dark:bg-neutral-900",children:[_jsxruntime.jsx.call(void 0, "option",{value:"pl-PL",children:o.polishLanguage}),_jsxruntime.jsx.call(void 0, "option",{value:"en-US",children:o.englishLanguage})]})]})]}),_jsxruntime.jsxs.call(void 0, "button",{type:"button",onClick:t,className:"mt-6 flex min-h-11 w-full items-center gap-3 rounded-lg border border-neutral-200 bg-white px-4 py-3 text-red-700 hover:bg-red-50 focus-visible:outline-2 focus-visible:outline-current dark:border-neutral-800 dark:bg-neutral-900 dark:text-red-400 dark:hover:bg-neutral-800",children:[_jsxruntime.jsx.call(void 0, _lucidereact.LogOut,{className:"h-5 w-5","aria-hidden":"true"}),o.logout]})]})}var zi=_react3.lazy.call(void 0, ()=>Promise.resolve().then(() => _interopRequireWildcard(require("./course.js"))).then(e=>({default:e.PanelCourse})));function Cr(e){return _jsxruntime.jsx.call(void 0, _react3.Suspense,{fallback:_jsxruntime.jsx.call(void 0, "div",{className:"flex items-center gap-2 p-2",role:"status",children:_jsxruntime.jsx.call(void 0, _e,{})}),children:_jsxruntime.jsx.call(void 0, "div",{className:"[--course-mobile-bottom:calc(56px+env(safe-area-inset-bottom))] md:[--course-mobile-bottom:0px]",children:_jsxruntime.jsx.call(void 0, zi,{...e})})})}function $i({status:e}){let t={created:{color:"bg-neutral-100 text-neutral-700",icon:null},paid:{color:"bg-green-100 text-green-700",icon:_lucidereact.CheckCircle2},completed:{color:"bg-blue-100 text-blue-700",icon:_lucidereact.CheckCircle2},canceled:{color:"bg-red-100 text-red-700",icon:_lucidereact.AlertCircle},sent:{color:"bg-purple-100 text-purple-700",icon:_lucidereact.Truck},processing:{color:"bg-yellow-100 text-yellow-700",icon:_lucidereact.Loader2}},n=t[e]||t.created,a=n.icon,r={created:"Utworzone",paid:"Op\u0142acone",completed:"Zako\u0144czone",canceled:"Anulowane",sent:"Wys\u0142ane",processing:"Przetwarzane"};return _jsxruntime.jsxs.call(void 0, "span",{className:`inline-flex items-center gap-1 rounded-full px-3 py-1 text-sm font-medium ${n.color}`,children:[a&&_jsxruntime.jsx.call(void 0, a,{className:"h-4 w-4"}),r[e]||e]})}function qi({orderID:e,email:t}){let[n,a]=_react3.useState.call(void 0, ""),r=_chunkG4V2KWTVjs.m.call(void 0, _chunkG4V2KWTVjs.k.publicApi.addPublicOrderComment);return _jsxruntime.jsxs.call(void 0, "form",{onSubmit:async i=>{if(i.preventDefault(),!!n.trim())try{await r.mutateAsync({projectId:"",orderId:e,message:n.trim(),accessToken:t}),a("")}catch(d){console.error("Failed to add comment:",d)}},className:"mt-4 space-y-2",children:[_jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.d,{htmlFor:"comment",children:"Dodaj komentarz"}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.v,{id:"comment",value:n,onChange:i=>a(i.target.value),placeholder:"Wpisz komentarz...",rows:3,disabled:r.isPending}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{type:"submit",disabled:!n.trim()||r.isPending,children:r.isPending?_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, _lucidereact.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Wysy\u0142anie..."]}):"Dodaj komentarz"})]})}function fo(e){return e?new Date(Number(e.seconds)*1e3).toLocaleDateString("pl-PL",{year:"numeric",month:"long",day:"numeric"}):"N/A"}function go(e,t){return new Intl.NumberFormat("pl-PL",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function Bi({orderID:e,initialEmail:t,onBack:n,accessToken:a,analytics:r}){let{theme:o,projectID:i}=_chunkVNV5BD4Xjs.j.call(void 0, ),d=_chunkDP2NOHCIjs.n.call(void 0, i,r,"order"),[c,l]=_react3.useState.call(void 0, t||""),[b,P]=_react3.useState.call(void 0, !1),{data:w,isLoading:h,error:y,refetch:u}=_chunkG4V2KWTVjs.l.call(void 0, _chunkG4V2KWTVjs.k.publicApi.getPublicOrderDetails,{projectId:_nullishCoalesce(i, () => ("")),orderId:e,email:c||void 0,accessToken:a},{enabled:!!e}),m=_optionalChain([w, 'optionalAccess', _117 => _117.result, 'access', _118 => _118.case])==="order"?w.result.value:null,p=_nullishCoalesce(_optionalChain([m, 'optionalAccess', _119 => _119.isVerified]), () => (!1)),x=m!=null;_react3.useEffect.call(void 0, ()=>{x&&d.track("panel_order_viewed",{},{order_ref:null})},[d,x]);let U=()=>{u(),P(!1)},le={"--button-background-color":_nullishCoalesce(_optionalChain([o, 'optionalAccess', _120 => _120.colors, 'optionalAccess', _121 => _121.brand]), () => ("#000000")),"--button-background-color-dark":_nullishCoalesce(_optionalChain([o, 'optionalAccess', _122 => _122.colors, 'optionalAccess', _123 => _123.brandDark]), () => ("#ffffff")),"--button-text-color":_nullishCoalesce(_optionalChain([o, 'optionalAccess', _124 => _124.colors, 'optionalAccess', _125 => _125.brandDark]), () => ("#000000")),"--button-text-color-dark":_nullishCoalesce(_optionalChain([o, 'optionalAccess', _126 => _126.colors, 'optionalAccess', _127 => _127.brand]), () => ("#000000"))};return h?_jsxruntime.jsx.call(void 0, "div",{className:"flex min-h-screen items-center justify-center",children:_jsxruntime.jsxs.call(void 0, "div",{className:"text-center",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Loader2,{className:"mx-auto h-8 w-8 animate-spin text-neutral-400"}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-2 text-neutral-600 dark:text-neutral-400",children:"\u0141adowanie zam\xF3wienia..."})]})}):y||!m?_jsxruntime.jsx.call(void 0, "div",{className:"flex min-h-screen items-center justify-center",children:_jsxruntime.jsx.call(void 0, Ee,{className:"w-full max-w-md",children:_jsxruntime.jsx.call(void 0, Te,{className:"pt-6",children:_jsxruntime.jsxs.call(void 0, "div",{className:"text-center",children:[_jsxruntime.jsx.call(void 0, _lucidereact.AlertCircle,{className:"mx-auto h-12 w-12 text-red-500"}),_jsxruntime.jsx.call(void 0, "h2",{className:"mt-4 text-xl font-semibold",children:"Zam\xF3wienie nie znalezione"}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-2 text-neutral-600 dark:text-neutral-400",children:"Nie znaleziono zam\xF3wienia o podanym numerze."})]})})})}):_jsxruntime.jsx.call(void 0, "div",{className:"w-full bg-white py-8 dark:bg-black",style:le,children:_jsxruntime.jsxs.call(void 0, "div",{className:"w-full px-4",children:[n&&_jsxruntime.jsxs.call(void 0, _chunkG4V2KWTVjs.q,{onClick:n,variant:"ghost",className:"mb-4 w-fit",children:[_jsxruntime.jsx.call(void 0, _lucidereact.ChevronLeft,{className:"h-4 w-4"}),"Wr\xF3\u0107 do historii zam\xF3wie\u0144"]}),_jsxruntime.jsxs.call(void 0, "div",{className:"mb-6 flex items-center gap-4",children:[_optionalChain([o, 'optionalAccess', _128 => _128.logoURL])&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, "img",{src:o.logoURL,alt:"Project logo",className:`h-12 w-auto ${o.logoDarkURL?"dark:hidden":""}`}),o.logoDarkURL&&_jsxruntime.jsx.call(void 0, "img",{src:o.logoDarkURL,alt:"Project logo",className:"hidden h-12 w-auto dark:block"})]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "h1",{className:"text-3xl font-bold",children:"Zam\xF3wienie"}),_jsxruntime.jsxs.call(void 0, "p",{className:"text-neutral-600 dark:text-neutral-400",children:["Numer zam\xF3wienia: #",m.orderId]})]})]}),_jsxruntime.jsxs.call(void 0, Ee,{className:"mb-6",children:[_jsxruntime.jsx.call(void 0, Oe,{children:_jsxruntime.jsxs.call(void 0, Ue,{className:"flex items-center",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Package,{className:"mr-2 h-5 w-5"}),"Status zam\xF3wienia"]})}),_jsxruntime.jsxs.call(void 0, Te,{className:"space-y-6",children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-center gap-2",children:[_jsxruntime.jsx.call(void 0, $i,{status:m.status}),m.processingStatus&&_jsxruntime.jsxs.call(void 0, "span",{className:"text-sm text-neutral-600",children:["\xB7 ",m.processingStatus]})]}),_jsxruntime.jsxs.call(void 0, "p",{className:"mt-2 text-sm text-neutral-600",children:["Zam\xF3wienie z\u0142o\u017Cone ",fo(m.createdAt)]})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"border-t pt-4",children:[_jsxruntime.jsx.call(void 0, "h3",{className:"mb-3 font-semibold",children:"Dane klienta"}),_jsxruntime.jsxs.call(void 0, "div",{className:"space-y-2",children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "span",{className:"font-medium",children:"Imi\u0119 i nazwisko:"})," ",_jsxruntime.jsx.call(void 0, "span",{className:p?"":"text-neutral-500",children:m.customerName})]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "span",{className:"font-medium",children:"Email:"})," ",_jsxruntime.jsx.call(void 0, "span",{className:p?"":"text-neutral-500",children:m.customerEmail})]}),m.customerPhone&&_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "span",{className:"font-medium",children:"Telefon:"})," ",_jsxruntime.jsx.call(void 0, "span",{className:p?"":"text-neutral-500",children:m.customerPhone})]})]})]}),!p&&_jsxruntime.jsx.call(void 0, "div",{className:"border-t pt-4",children:_jsxruntime.jsxs.call(void 0, _chunkG4V2KWTVjs.q,{onClick:()=>P(!0),variant:"outline",className:"w-full",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Lock,{className:"mr-2 h-4 w-4"}),"Zweryfikuj sw\xF3j email"]})})]})]}),_jsxruntime.jsxs.call(void 0, Ee,{className:"mb-6",children:[_jsxruntime.jsx.call(void 0, Oe,{children:_jsxruntime.jsx.call(void 0, Ue,{children:"Produkty"})}),_jsxruntime.jsxs.call(void 0, Te,{className:"space-y-6",children:[_jsxruntime.jsx.call(void 0, "div",{className:"space-y-4",children:m.items.map((E,de)=>_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-center gap-4",children:[E.imageUrl&&_jsxruntime.jsx.call(void 0, "img",{src:E.imageUrl,alt:E.name,className:"h-16 w-16 rounded object-cover"}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex-1",children:[_jsxruntime.jsx.call(void 0, "p",{className:"font-medium",children:E.name}),_jsxruntime.jsxs.call(void 0, "p",{className:"text-sm text-neutral-600",children:["Ilo\u015B\u0107: ",E.quantity]})]}),_jsxruntime.jsx.call(void 0, "div",{className:"text-right",children:_jsxruntime.jsx.call(void 0, "p",{className:"font-medium",children:go(Number(E.price),E.currency)})})]},de))}),(m.deliveryAddress||m.deliveryMethod)&&_jsxruntime.jsxs.call(void 0, "div",{className:"border-t pt-4",children:[_jsxruntime.jsxs.call(void 0, "h3",{className:"mb-3 flex items-center font-semibold",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Truck,{className:"mr-2 h-5 w-5"}),"Informacje o dostawie"]}),_jsxruntime.jsxs.call(void 0, "div",{className:"space-y-2",children:[m.deliveryAddress&&_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "span",{className:"font-medium",children:"Adres:"})," ",_jsxruntime.jsx.call(void 0, "span",{className:p?"":"text-neutral-500",children:m.deliveryAddress})]}),m.deliveryMethod&&_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "span",{className:"font-medium",children:"Metoda:"})," ",m.deliveryMethod]}),m.trackingNumber&&p&&_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "span",{className:"font-medium",children:"Tracking:"})," ",m.trackingNumber]})]})]}),_jsxruntime.jsx.call(void 0, "div",{className:"border-t pt-4",children:_jsxruntime.jsxs.call(void 0, "div",{className:"flex justify-between text-lg font-bold",children:[_jsxruntime.jsx.call(void 0, "span",{children:"Suma:"}),_jsxruntime.jsx.call(void 0, "span",{children:go(Number(m.totalAmount),m.currency)})]})})]})]}),_jsxruntime.jsxs.call(void 0, Ee,{children:[_jsxruntime.jsx.call(void 0, Oe,{children:_jsxruntime.jsxs.call(void 0, Ue,{children:["Komentarze ",m.commentCount>0&&`(${m.commentCount})`]})}),_jsxruntime.jsxs.call(void 0, Te,{children:[m.comments.length>0?_jsxruntime.jsx.call(void 0, "div",{className:"space-y-4",children:m.comments.map(E=>_jsxruntime.jsxs.call(void 0, "div",{className:"border-b pb-4 last:border-b-0",children:[_jsxruntime.jsxs.call(void 0, "div",{className:"mb-1 flex items-center gap-2",children:[_jsxruntime.jsx.call(void 0, "span",{className:"font-medium",children:E.authorName||"System"}),_jsxruntime.jsx.call(void 0, "span",{className:"text-xs text-neutral-500",children:fo(E.createdAt)}),E.authorType==="admin"&&_jsxruntime.jsx.call(void 0, "span",{className:"rounded bg-blue-100 px-2 py-0.5 text-xs text-blue-700",children:"Admin"})]}),_jsxruntime.jsx.call(void 0, "p",{className:p?"":"text-neutral-500",children:E.message})]},E.id))}):_jsxruntime.jsx.call(void 0, "p",{className:"text-neutral-600",children:"Brak komentarzy."}),p?_jsxruntime.jsx.call(void 0, qi,{orderID:m.orderId,email:c}):_jsxruntime.jsx.call(void 0, "div",{className:"mt-4",children:_jsxruntime.jsxs.call(void 0, _chunkG4V2KWTVjs.q,{onClick:()=>P(!0),variant:"outline",className:"w-full",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Lock,{className:"mr-2 h-4 w-4"}),"Zweryfikuj sw\xF3j email"]})})]})]}),b&&_jsxruntime.jsx.call(void 0, "div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:_jsxruntime.jsxs.call(void 0, Ee,{className:"w-full max-w-md",children:[_jsxruntime.jsx.call(void 0, Oe,{children:_jsxruntime.jsx.call(void 0, Ue,{children:"Zweryfikuj sw\xF3j email"})}),_jsxruntime.jsxs.call(void 0, Te,{className:"space-y-4",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-700",children:"Podaj adres email u\u017Cyty przy sk\u0142adaniu zam\xF3wienia."}),_jsxruntime.jsxs.call(void 0, "div",{className:"space-y-2",children:[_jsxruntime.jsx.call(void 0, _chunkZATPBYOAjs.d,{htmlFor:"verify-email",children:"Adres email"}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.r,{id:"verify-email",type:"email",placeholder:"twoj@email.com",value:c,onChange:E=>l(E.target.value)})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex gap-2",children:[_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{variant:"outline",onClick:()=>P(!1),className:"flex-1",children:"Anuluj"}),_jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.q,{onClick:U,className:"flex-1",children:"Zweryfikuj"})]})]})]})})]})})}function Ki(e){return _jsxruntime.jsx.call(void 0, Bi,{...e})}var Sr=Ki;var Wi=({returnsAppearance:e,returnsTexts:t,analytics:n}={})=>{let{projectID:a,theme:r,loginURL:o,host:i}=_chunkVNV5BD4Xjs.j.call(void 0, ),[,d]=_react3.useState.call(void 0, 0),c=_chunkDP2NOHCIjs.n.call(void 0, a,n,"panel"),l=_chunkVNV5BD4Xjs.k.call(void 0, a,i),b=_chunkVNV5BD4Xjs.m.call(void 0, a,i),{mutateAsync:P}=_chunkG4V2KWTVjs.m.call(void 0, _chunkG4V2KWTVjs.k.publicApi.userPanelLogout);async function w(){l&&await P({accessToken:l}),typeof window<"u"&&(_chunkVNV5BD4Xjs.n.call(void 0, a,i),window.location.reload())}let[h]=_react.useAutoAnimate.call(void 0, ),y=A=>["products","notifications","profile","plans","orders","order-details","returns","return-details","course"].includes(A),[u,m]=Un({product:void 0,state:"products",orderId:void 0,returnId:void 0,course:void 0,item:void 0}),[p,x]=_react3.useState.call(void 0, y(u.state)?u.state:"products"),U=A=>{m({state:"order-details",orderId:A}),x("order-details")},le=()=>{m({state:"orders",orderId:void 0}),x("orders")},E=A=>m({orderId:void 0,returnId:void 0,course:void 0,item:void 0,...A}),de=A=>{m({state:"course",course:A,item:void 0,product:void 0}),x("course")},Ce=()=>{m({state:"products",course:void 0,item:void 0,product:void 0}),x("products")};_react3.useEffect.call(void 0, ()=>{y(u.state)&&(u.state==="course"||p==="course")&&x(u.state)},[u.state]);let ee={"--button-background-color":_nullishCoalesce(_optionalChain([r, 'optionalAccess', _129 => _129.colors, 'optionalAccess', _130 => _130.brand]), () => ("#000000")),"--button-background-color-dark":_nullishCoalesce(_optionalChain([r, 'optionalAccess', _131 => _131.colors, 'optionalAccess', _132 => _132.brandDark]), () => ("#ffffff")),"--button-text-color":_nullishCoalesce(_optionalChain([r, 'optionalAccess', _133 => _133.colors, 'optionalAccess', _134 => _134.brandDark]), () => ("#000000")),"--button-text-color-dark":_nullishCoalesce(_optionalChain([r, 'optionalAccess', _135 => _135.colors, 'optionalAccess', _136 => _136.brand]), () => ("#000000"))};return _react3.useEffect.call(void 0, ()=>{if(l==null||l.length===0){window.location.href=_nullishCoalesce(o, () => ("/panel/login"));return}},[]),_react3.useEffect.call(void 0, ()=>{if(l==null||l.length===0){window.location.href=_nullishCoalesce(o, () => ("/panel/login"));return}},[p]),_react3.useEffect.call(void 0, ()=>{if(typeof window>"u"||window.parent!==window||!l)return;let A=gt(window.location.search);A&&yt(A);let fe=_nullishCoalesce(A, () => (Ye()));fe&&(window.location.href=Ze(fe,l))},[l]),_jsxruntime.jsx.call(void 0, _chunkDP2NOHCIjs.l,{value:c,children:_jsxruntime.jsxs.call(void 0, "div",{ref:h,className:"font-inter relative flex h-dvh w-full flex-col bg-beige-100 text-black dark:bg-black dark:text-white md:flex-row",children:[_jsxruntime.jsx.call(void 0, xr,{activeScreen:p,setActiveScreen:x,setParams:E,styles:ee,theme:r,logout:w,email:b,projectID:a}),_jsxruntime.jsxs.call(void 0, "main",{className:"flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto w-full p-5 pb-[calc(76px+env(safe-area-inset-bottom))] md:pb-5",children:[p==="products"&&_jsxruntime.jsx.call(void 0, so,{projectID:_nullishCoalesce(a, () => ("")),accessToken:l,loginURL:_nullishCoalesce(o, () => ("/panel/login")),styles:ee,activeScreen:p,params:u,setParams:m,openCourse:de}),p==="course"&&u.course&&l&&_jsxruntime.jsx.call(void 0, Cr,{accessId:u.course,accessToken:l,theme:r,itemId:u.item,onItemChange:A=>m({item:A}),onBack:Ce}),p==="notifications"&&_jsxruntime.jsx.call(void 0, ur,{}),p==="plans"&&_jsxruntime.jsx.call(void 0, pr,{projectID:_nullishCoalesce(a, () => (""))}),p==="orders"&&_jsxruntime.jsx.call(void 0, jn,{projectID:_nullishCoalesce(a, () => ("")),accessToken:_nullishCoalesce(l, () => ("")),openOrderDetails:U}),p==="order-details"&&u.orderId&&_jsxruntime.jsx.call(void 0, Sr,{orderID:u.orderId,onBack:le}),(p==="returns"||p==="return-details")&&l&&_jsxruntime.jsx.call(void 0, fr,{projectID:_nullishCoalesce(a, () => ("")),host:i,accessToken:l,loginURL:_nullishCoalesce(o, () => ("/panel/login")),appearance:_n(e,_optionalChain([r, 'optionalAccess', _137 => _137.colors, 'optionalAccess', _138 => _138.brand])),texts:t,screen:p,params:u,setParams:m,setActiveScreen:x}),p==="profile"&&_jsxruntime.jsx.call(void 0, wr,{email:b,logout:w,onLocaleChange:()=>d(A=>A+1)})]})]})})},Vi= exports.m =Wi;var _reactquery = require('@tanstack/react-query');var _connect = require('@connectrpc/connect');var _connectweb = require('@connectrpc/connect-web');var me;(a=>{function e(r){return _connect.createClient.call(void 0, _chunkG4V2KWTVjs.f,n(r))}a.get=e;let t=new Map;function n(r){let o=t.get(r);return o==null&&(o=_connectweb.createConnectTransport.call(void 0, {useBinaryFormat:!0,baseUrl:r+"/api/rpc",interceptors:[_chunk4HGZZJELjs.b]}),t.set(r,o)),o}})(me = exports.a||={});var _zod = require('zod'); var _zod2 = _interopRequireDefault(_zod);function z(e,t=2){return+(Math.round(+(e+"e+"+t))+"e-"+t)}function ko(e,t){let n=typeof navigator>"u"?"pl-PL":navigator.language;return Intl.NumberFormat(n,{style:"currency",currency:t,currencyDisplay:"symbol"}).format(e/100)}var ju=_zod2.default.object({event:_zod2.default.enum(["purchase","addToCart","customizeProduct","viewCart","removeFromCart","initiateCheckout","lead"]),step:_zod2.default.string().optional(),value:_zod2.default.number().optional(),currency:_zod2.default.string().optional(),content_name:_zod2.default.string().optional(),items:_zod2.default.array(_zod2.default.object({id:_zod2.default.string(),name:_zod2.default.string(),price:_zod2.default.number().default(0),currency:_zod2.default.string().default("PLN"),quantity:_zod2.default.number().default(1)})).optional()});function Er(e){typeof window>"u"||(Zi(e),Xi(e),es(e))}function Zi(e){try{typeof window.dataLayer>"u"&&(window.dataLayer=[]);let t=Qi(e);window.dataLayer.push(t)}catch(t){console.warn("cannot send google analytics event",t)}}function Qi(e){let t=_nullishCoalesce(_nullishCoalesce(e.value, () => (_optionalChain([e, 'access', _139 => _139.items, 'optionalAccess', _140 => _140.reduce, 'call', _141 => _141((o,i)=>o+(i.price||0)*(i.quantity||1),0)]))), () => (0)),n=_optionalChain([e, 'access', _142 => _142.items, 'optionalAccess', _143 => _143.map, 'call', _144 => _144(o=>({item_id:o.id,item_name:o.name||o.id,price:z((o.price||0)/100,2),quantity:o.quantity||1}))]),a={currency:e.currency||"PLN",value:z(t/100,2)};n&&n.length>0&&(a.items=n);let r;switch(e.event){case"purchase":r="purchase",a.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:a,...e.step&&{step:e.step},...e.content_name&&{content_name:e.content_name}}}function Xi(e){if(typeof window.fbq>"u")return;let t="",n="",a={};switch(e.event){case"purchase":t="track",n="Purchase",a={category_name:e.step,...e};break;case"lead":t="track",n="Lead",a={category_name:e.step,...e};break;case"addToCart":t="track",n="Add to Cart",a={category_name:e.step,...e};break;case"customizeProduct":t="track",n="Customize Product",a={category_name:e.step,...e};break;case"viewCart":t="track",n="View Cart",a={category_name:e.step,...e};break;case"removeFromCart":t="track",n="Remove from Cart",a={category_name:e.step,...e};break;case"initiateCheckout":t="track",n="Initiate Checkout",a={category_name:e.step,...e};break;default:break}window.location.search.includes("analytics")&&console.log("Pushing FB event",t,n,a),window.fbq(t,n,a)}function es(e){try{if(typeof window.ttq>"u")return;let t=ts(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 ts(e){let t=_nullishCoalesce(_nullishCoalesce(e.value, () => (_optionalChain([e, 'access', _145 => _145.items, 'optionalAccess', _146 => _146.reduce, 'call', _147 => _147((o,i)=>o+(i.price||0)*(i.quantity||1),0)]))), () => (0)),n=_optionalChain([e, 'access', _148 => _148.items, 'optionalAccess', _149 => _149.map, 'call', _150 => _150(o=>({content_id:o.id,content_type:"product",content_name:o.name||o.id,quantity:o.quantity||1,price:z((o.price||0)/100,2)}))])||[];n.length===0&&e.content_name&&n.push({content_id:e.step||"unknown",content_type:"product",content_name:e.content_name,quantity:1,price:z(t/100,2)});let a={currency:e.currency||"PLN",value:z(t/100,2)};n.length>0&&(a.contents=n);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:a}}function xo(e){let{items:t,googlePayConfig:n,checkout:a,result:r,cartRequiresShipping:o}=e,i=_nullishCoalesce(e.locale, () => (_chunk7RXW6XFYjs.f.call(void 0, )));if(r.totalAmount==null)return;let d=[];return o&&(d.push("SHIPPING_ADDRESS"),d.push("SHIPPING_OPTION")),{apiVersion:2,apiVersionMinor:0,callbackIntents:d,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["MASTERCARD","VISA"]},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:n.gateway,gatewayMerchantId:n.gatewayId}}}],emailRequired:!0,shippingAddressParameters:{phoneNumberRequired:o},shippingAddressRequired:o,shippingOptionRequired:o,shippingOptionParameters:o?{shippingOptions:r.methods.slice(0,5).map(l=>({id:l.id,label:l.name+` - ${ko(l.amount,r.currency)}`,description:_nullishCoalesce(l.description, () => (""))})),defaultSelectedOptionId:r.selectedDeliveryMethod}:void 0,merchantInfo:{merchantId:n.merchantId+"",merchantName:n.merchantName},transactionInfo:{totalPriceStatus:"FINAL",totalPriceLabel:_chunk7RXW6XFYjs.c.call(void 0, "paymentForCart",i,e.texts),totalPrice:`${z(r.totalAmount/100,2)}`,currencyCode:r.currency,countryCode:r.country,checkoutOption:"COMPLETE_IMMEDIATE_PURCHASE",displayItems:rs(t,r.methods,_nullishCoalesce(r.selectedDeliveryMethod, () => ((r.methods.length>0?r.methods[0].id:void 0))),a.couponCode,r.couponValue,_chunk7RXW6XFYjs.c.call(void 0, "coupon",i,e.texts))}}}function rs(e,t,n,a,r,o="Coupon"){let i=[],d=0;for(let l of e){if(l.details==null)continue;let b=_nullishCoalesce(_optionalChain([l, 'access', _151 => _151.details, 'access', _152 => _152.pricing, 'optionalAccess', _153 => _153.effectivePrice]), () => (l.details.price));d+=b*l.quantity,i.push({label:l.details.name+" x "+l.quantity,price:`${z(b/100,2)}`,type:"LINE_ITEM",status:"FINAL"})}let c=t.find(l=>l.id===n);return c!=null&&i.push({label:c.name,price:`${z(c.amount/100,2)}`,type:"SHIPPING_OPTION",status:"FINAL"}),a!=null&&r!=null&&i.push({label:`${o} ${a}`,price:`${z(r/100,2)}`,type:"DISCOUNT",status:"FINAL"}),d>0&&i.push({label:"Subtotal",price:`${z(d/100,2)}`,type:"SUBTOTAL",status:"FINAL"}),i}function nt(e,t){return`${_chunk4HGZZJELjs.e}/api/integrations/${e}/public-commerce${t}`}function Ae(e){return typeof e=="object"&&e!=null&&"ERR"in e}function q(e,t,n){return{ERR:!0,error:e,type:t,data:n}}function wo(e,t){return _optionalChain([t, 'optionalAccess', _154 => _154.find, 'call', _155 => _155(n=>n.id===e||(_nullishCoalesce(_optionalChain([n, 'access', _156 => _156.variants, 'optionalAccess', _157 => _157.some, 'call', _158 => _158(a=>a.id===e)]), () => (!1))))])}function Co(e,t){let n=new Set(t.map(a=>a.productID));return Array.from(new Set(e.filter(a=>!n.has(a))))}function No(e,t){let n=_optionalChain([e, 'optionalAccess', _159 => _159.trim, 'call', _160 => _160()]);if(!(n==null||n.length===0))try{let a=new URL(n,t);return a.protocol!=="http:"&&a.protocol!=="https:"?void 0:a.href}catch (e16){return}}var _zustand = require('zustand');var ot=_zustand.create.call(void 0, e=>({isCartVisible:!1,notice:void 0,setNotice:t=>e(n=>({...n,notice:t})),numberOfProductsInCart:0,showCart:()=>e(t=>({...t,isCartVisible:!0})),hideCart:()=>e(t=>({...t,isCartVisible:!1})),setNumberOfProductsInCart:t=>e(n=>({...n,numberOfProductsInCart:t}))}));var Ut=_react3.createContext.call(void 0, {});function ep({texts:e,locale:t,children:n}){let a=_react3.useMemo.call(void 0, ()=>({texts:e,locale:t}),[e,t]);return _jsxruntime.jsx.call(void 0, Ut.Provider,{value:a,children:n})}function So(){return _react3.useContext.call(void 0, Ut)}function tp(e){let{texts:t,locale:n}=_react3.useContext.call(void 0, Ut);return _chunk7RXW6XFYjs.c.call(void 0, e,_nullishCoalesce(n, () => (_chunk7RXW6XFYjs.f.call(void 0, ))),t)}function rp(){let{texts:e,locale:t}=_react3.useContext.call(void 0, Ut),n=_nullishCoalesce(t, () => (_chunk7RXW6XFYjs.f.call(void 0, )));return _react3.useMemo.call(void 0, ()=>a=>_chunk7RXW6XFYjs.c.call(void 0, a,n,e),[n,e])}var Rr="bitsnap-pending-order";function Lo(e,t){let n=new Map;for(let r of t)n.set(r.id,(_nullishCoalesce(n.get(r.id), () => (0)))+r.quantity);let a=[];for(let r of e){let o=n.get(r.id);o==null?a.push(r):r.quantity>o&&a.push({...r,quantity:r.quantity-o})}return a}var is=60*1e3;function Ro(e,t=Date.now,n=is){let a;return r=>{let o=`${r.orderId}:${r.ts}`,i=t();return _optionalChain([a, 'optionalAccess', _161 => _161.key])===o&&i-a.at<n?Promise.reject(new Error("pending order was asked about recently")):(a={key:o,at:i},e(r))}}function ss(e){if(!(e==null||e.length===0))try{let t=new URL(e,"https://bitsnap.invalid").pathname,n=/\/payment\/common\/([^/]+)\/([^/]+)\/?$/.exec(t);return n==null?void 0:{projectId:decodeURIComponent(n[1]),orderId:decodeURIComponent(n[2])}}catch (e17){return}}function ls(e){if(e==null||e.length===0)return!1;try{let t=new URL(e,"https://bitsnap.invalid").pathname;return/\/payment\/manualPayment\/[^/]+\/[^/]+\/?$/.test(t)}catch (e18){return!1}}function ds(e,t=Date.now(),n={}){if(ls(e.url))return;let a=ss(e.url),r=_nullishCoalesce(Eo(e.orderId), () => (_optionalChain([a, 'optionalAccess', _162 => _162.orderId]))),o=_nullishCoalesce(Eo(e.projectId), () => (_optionalChain([a, 'optionalAccess', _163 => _163.projectId])));if(!(r==null||o==null))return{orderId:r,projectId:o,...n.cartProjectId!=null?{cartProjectId:n.cartProjectId}:{},lines:_nullishCoalesce(n.lines, () => ([])),ts:t}}function ap(e,t={}){let n=ds(e,t.now,t);return n!=null&&cs(n,t.storage)}function Eo(e){return e!=null&&e.length>0?e:void 0}function _t(){try{return typeof localStorage>"u"?void 0:localStorage}catch (e19){return}}function cs(e,t=_t()){try{return _optionalChain([t, 'optionalAccess', _164 => _164.setItem, 'call', _165 => _165(Rr,JSON.stringify(e))]),t!=null}catch (e20){return!1}}function To(e=_t()){try{let t=_optionalChain([e, 'optionalAccess', _166 => _166.getItem, 'call', _167 => _167(Rr)]);if(t==null)return;let n=JSON.parse(t);if(typeof n=="object"&&n!=null&&typeof n.orderId=="string"&&typeof n.projectId=="string"&&typeof n.ts=="number"&&n.orderId.length>0){let{orderId:a,projectId:r,cartProjectId:o,ts:i,lines:d}=n;return{orderId:a,projectId:r,...typeof o=="string"?{cartProjectId:o}:{},lines:Array.isArray(d)?d.filter(c=>typeof _optionalChain([c, 'optionalAccess', _168 => _168.id])=="string"&&typeof c.quantity=="number"):[],ts:i}}}catch (e21){}Lr(e)}function Lr(e=_t()){try{_optionalChain([e, 'optionalAccess', _169 => _169.removeItem, 'call', _170 => _170(Rr)])}catch (e22){}}function Ao(e){let t=_nullishCoalesce(_optionalChain([e, 'access', _171 => _171.details, 'optionalAccess', _172 => _172.status]), () => (us(_optionalChain([e, 'access', _173 => _173.details, 'optionalAccess', _174 => _174.$unknown]))));return t==="created"||t==="placed"||t==="paid"||t==="canceled"?t:"unknown"}function us(e){if(Array.isArray(e)){for(let t of e)if(_optionalChain([t, 'optionalAccess', _175 => _175.no])===3&&t.wireType===2&&t.data instanceof Uint8Array){let n=0,a=0;for(let r=0;a<t.data.length&&r<35;r+=7){let o=t.data[a++];if(n|=(o&127)<<r,!(o&128))break}if(a+n!==t.data.length)return;try{return new TextDecoder().decode(t.data.subarray(a))}catch (e23){return}}}}async function Do(e){let t=_nullishCoalesce(e.storage, () => (_t())),n=To(t);if(n==null)return"none";if((_nullishCoalesce(e.now, () => (Date.now)))()-n.ts>864e5)return Lr(t),"expired";if(e.projectId!=null&&n.cartProjectId!=null&&n.cartProjectId!==e.projectId)return"pending";let r;try{r=await e.fetchStatus(n)}catch (e24){return"pending"}let o=To(t);if(_optionalChain([o, 'optionalAccess', _176 => _176.orderId])!==n.orderId||o.ts!==n.ts)return"pending";if(r==="paid"||r==="placed"){try{await e.removeLines(n.lines)}catch (e25){return"pending"}return Lr(t),"paid"}return"pending"}var hs="__m_a",jo=_react3.createContext.call(void 0, void 0),Or= exports.I =void 0;function Rp(e){_chunkVNV5BD4Xjs.a.call(void 0, {projectID:e}),Or= exports.I =e,typeof window<"u"&&_chunkVNV5BD4Xjs.g.call(void 0, [window.location.origin])}function st(){return _nullishCoalesce(_nullishCoalesce(Or, () => (_optionalChain([document, 'access', _177 => _177.querySelector, 'call', _178 => _178('script[data-id][data-name="internal-cart"]'), 'optionalAccess', _179 => _179.getAttribute, 'call', _180 => _180("data-id")]))), () => (void 0))}function bs(){return _nullishCoalesce(_optionalChain([document, 'access', _181 => _181.querySelector, 'call', _182 => _182('script[data-id][data-name="internal-cart"]'), 'optionalAccess', _183 => _183.getAttribute, 'call', _184 => _184("data-custom-host")]), () => (void 0))}var Ps=({children:e,locale:t})=>{let[n]=_react3.useState.call(void 0, ()=>new _reactquery.QueryClient),a=So();_react3.useEffect.call(void 0, ()=>{it()},[]);let r=st();if(_react3.useEffect.call(void 0, ()=>{if(r==null)return;let i=()=>{xs(r).then(c=>{c==="paid"&&n.invalidateQueries({queryKey:["cart"]})})},d=()=>{document.visibilityState==="visible"&&i()};return i(),window.addEventListener("pageshow",i),document.addEventListener("visibilitychange",d),()=>{window.removeEventListener("pageshow",i),document.removeEventListener("visibilitychange",d)}},[r,n]),r==null)return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{});let o=_r(r,_nullishCoalesce(t, () => (a.locale)),a.texts);return _jsxruntime.jsx.call(void 0, _reactquery.QueryClientProvider,{client:n,children:_jsxruntime.jsx.call(void 0, jo.Provider,{value:o,children:e})})},Ar,vs=Ro(async e=>Ao(await me.get(_chunk4HGZZJELjs.e).getOrder({id:e.orderId,projectId:e.projectId})));function Ap(){let{country:e,couponCode:t,selectedDeliveryMethod:n,postalCode:a}=_nullishCoalesce(R(), () => (jt));return{country:e,couponCode:t,selectedDeliveryMethod:n,postalCode:a}}function Dp(){return(_nullishCoalesce(_optionalChain([R, 'call', _185 => _185(), 'optionalAccess', _186 => _186.products]), () => ([]))).map(e=>({id:e.id,quantity:e.quantity}))}function ks(e){let t=R();ne({...t,products:Lo(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _187 => _187.products]), () => ([])),e)}),it()}function xs(e){return Ar??=Do({projectId:e,fetchStatus:vs,removeLines:ks}).catch(t=>{console.warn("cannot check the pending order",t)}).finally(()=>{Ar=void 0}),Ar}var at=async(e,t)=>{let n=[];_optionalChain([t, 'optionalAccess', _188 => _188.items])!=null&&t.items.length>0?n=t.items:n=_nullishCoalesce(_optionalChain([R, 'call', _189 => _189(), 'optionalAccess', _190 => _190.products]), () => ([]));let a=Array.from(new Set(n.map(i=>i.productID)));if(a.length===0)return[];let r=new URLSearchParams;r.set("ids",a.join(",")),r.set("locale",_nullishCoalesce(_optionalChain([t, 'optionalAccess', _191 => _191.locale]), () => (_chunk7RXW6XFYjs.f.call(void 0, ))));let o;try{let i=await fetch(_chunk4HGZZJELjs.c.call(void 0, nt(e,`/products?${r.toString()}`)),{method:"GET"});if(i.status!=200)return q("products-load-failed","internal");o=await i.json()}catch(i){return console.warn("cannot load the products of the cart",i),q("products-load-failed","internal")}return n.flatMap(i=>{let d=wo(i.productID,o.result);return d==null?[]:[{...i,details:Es(i.productID,d),catalogProductID:d.id}]})},Mp= exports.O =()=>{let e=_react3.useContext.call(void 0, jo);if(e===void 0)throw new Error("useCartProvider must be used within a CartProvider");return e},Op= exports.P =Ps,ws=_zod2.default.object({isAvailable:_zod2.default.boolean(),merchantId:_zod2.default.string(),merchantName:_zod2.default.string(),gateway:_zod2.default.string(),gatewayId:_zod2.default.string()}),Cs=_zod2.default.object({id:_zod2.default.string(),productID:_zod2.default.string(),quantity:_zod2.default.number(),priceVersion:_zod2.default.string().optional(),metadata:_zod2.default.record(_zod2.default.string(),_zod2.default.string().optional()).optional(),url:_zod2.default.string().optional()}),Ns=_zod2.default.object({country:_zod2.default.string().optional(),couponCode:_zod2.default.string().optional(),selectedDeliveryMethod:_zod2.default.string().optional(),postalCode:_zod2.default.string().optional(),email:_zod2.default.string().optional(),products:_zod2.default.array(Cs).optional(),googlePayConfig:ws.optional()}),jt={country:void 0,couponCode:void 0,email:void 0,selectedDeliveryMethod:void 0,postalCode:void 0,products:[],googlePayConfig:void 0},Fo="checkout";function R(){try{let e=localStorage.getItem(Fo);return e==null?jt:Ns.parse(JSON.parse(e))}catch (e26){return jt}}async function Oo(e,t){let n=await at(e,{items:t.map((o,i)=>({...o,id:`price-check-${i}`}))});if(Ae(n))return n;let a=Co(t.map(o=>o.productID),n);if(a.length>0)return q("item-ids-not-found","notFound",a);let r=R();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:_optionalChain([n, 'access', _192 => _192.find, 'call', _193 => _193(i=>i.productID===o.productID), 'optionalAccess', _194 => _194.details, 'optionalAccess', _195 => _195.pricing, 'optionalAccess', _196 => _196.priceVersion]),metadata:o.metadata,url:No(o.url,typeof window<"u"?window.location.href:void 0)}))),Is(t,n),Er({event:"addToCart",currency:"PLN",items:t.map(o=>({id:o.productID,name:_nullishCoalesce(o.name, () => ("")),price:_nullishCoalesce(o.price, () => (0)),quantity:o.quantity,currency:_nullishCoalesce(o.currency, () => ("PLN"))}))}),ne(r),it()}function Is(e,t){for(let n of e)try{let a=t.find(d=>d.productID===n.productID),r=_nullishCoalesce(_nullishCoalesce(_optionalChain([a, 'optionalAccess', _197 => _197.details, 'optionalAccess', _198 => _198.pricing, 'optionalAccess', _199 => _199.effectivePrice]), () => (_optionalChain([a, 'optionalAccess', _200 => _200.details, 'optionalAccess', _201 => _201.price]))), () => (n.price)),o=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _202 => _202.details, 'optionalAccess', _203 => _203.currency]), () => (n.currency));if(r==null||o==null)continue;let i=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _204 => _204.catalogProductID]), () => (n.productID));(_nullishCoalesce(n.analytics, () => (_chunkDP2NOHCIjs.o.call(void 0, )))).track("add_to_cart",{qty:n.quantity,value_minor:Math.round(r*n.quantity),currency:o},{product_id:i,variant_id:i!==n.productID?n.productID:null})}catch (e27){}}function Uo(e){let t=R(),n={...t,products:_optionalChain([t, 'optionalAccess', _205 => _205.products, 'optionalAccess', _206 => _206.filter, 'call', _207 => _207(a=>!e.includes(a.productID)&&!e.includes(a.id))])};Er({event:"removeFromCart",items:e.map(a=>({id:a,name:"",price:0,quantity:1,currency:"PLN"}))}),ne(n),it()}function ne(e){localStorage.setItem(Fo,JSON.stringify(e))}function _o(e,t){if(e.products==null||e.products.length==0)return;let n=e.products.reduce((a,r)=>(r.metadata!=null&&Object.keys(r.metadata).forEach(o=>{let i=_optionalChain([r, 'access', _208 => _208.metadata, 'optionalAccess', _209 => _209[o]]);i!=null&&(a[o]=i)}),a),{});return{items:e.products.map(a=>({id:a.productID,quantity:a.quantity,priceVersion:a.priceVersion})),askForNote:!0,countries:e.country?[e.country]:void 0,metadata:n,locale:t}}var _r=(e,t=_chunk7RXW6XFYjs.f.call(void 0, ),n)=>{let a=bs();return a!=null&&_chunk4HGZZJELjs.f.call(void 0, a),{async checkIfApplePayIsAvailable(){if(typeof window>"u"||typeof document>"u"||!("ApplePaySession"in window))return!1;try{return(await me.get(_chunk4HGZZJELjs.e).isOneClickPaymentAvailable({projectId:e})).applePay}catch(r){return console.error("Error checking if Apple Pay is available",r),!1}},async getGooglePayConfiguration(r){if(typeof window>"u"||typeof document>"u")return{isAvailable:!1};try{let o=await Ss(e);if(_optionalChain([o, 'optionalAccess', _210 => _210.isAvailable])!=!0)return{isAvailable:!1};let i=R();if(i==null)return console.log("checkout is null"),{isAvailable:!1};let d=await at(e,{locale:t,items:r.items.map(P=>({id:Math.random().toString(36).substring(7),quantity:P.quantity,metadata:P.metadata,productID:P.productID}))});if(Ae(d))return{isAvailable:!1};let c=await me.get(_chunk4HGZZJELjs.e).getPreOrderDetails({items:d.map(P=>_protobuf.create.call(void 0, _chunkG4V2KWTVjs.c,{id:P.productID,quantity:P.quantity})),projectId:e,postCode:i.postalCode,couponCode:i.couponCode,countryCode:i.country,selectedDeliveryMethod:i.selectedDeliveryMethod});if(c.totalAmount==null)return{isAvailable:!1};let l=d.find(P=>_optionalChain([P, 'access', _211 => _211.details, 'optionalAccess', _212 => _212.isDeliverable])==!0)!=null,b=await xo({items:d,googlePayConfig:o,checkout:i,cartRequiresShipping:l,result:c,locale:t,texts:n});return b==null?{isAvailable:!1}:{isAvailable:!0,config:b}}catch(o){return console.error("Error resolving Google Pay configuration",o),{isAvailable:!1}}},async clearCart(){let r=structuredClone(jt);r.country=_optionalChain([R, 'call', _213 => _213(), 'optionalAccess', _214 => _214.country]),ne(r),it()},async getAvailableCountries(){let r=await fetch(_chunk4HGZZJELjs.c.call(void 0, nt(e,"/countries")),{method:"GET"});if(r.status!=200)return[];try{return _zod2.default.array(_zod2.default.object({name:_zod2.default.string(),code:_zod2.default.string()})).parse(await r.json())}catch(o){return q(o.toString(),"internal")}},async getCountry(){let r=_optionalChain([R, 'call', _215 => _215(), 'optionalAccess', _216 => _216.country]);if(r==null){r="PL";let o=R();o.country=r,ne(o)}return r},async getNumberOfElementsInCart(){return _nullishCoalesce(_optionalChain([R, 'call', _217 => _217(), 'optionalAccess', _218 => _218.products, 'optionalAccess', _219 => _219.reduce, 'call', _220 => _220((r,o)=>r+o.quantity,0)]), () => (0))},async getProducts(){return await at(e,{locale:t})},async removeProductFromCart(r){return Uo([r.id])},async setCountry(r){let o=R();o.country=r,ne(o)},async setCouponCodeIfPossible(r){let o=R();o.couponCode=r,ne(o)},async setPostalCode(r){let o=R();o.postalCode=r,ne(o)},async setDeliveryMethod(r){let o=R();o.selectedDeliveryMethod=r,ne(o)},async setEmail(r){let o=R();o.email=r,ne(o)},async addProduct(r){return await Oo(e,[r])},async updateQuantity(r){let o=R();o.products=_optionalChain([o, 'access', _221 => _221.products, 'optionalAccess', _222 => _222.map, 'call', _223 => _223(i=>(i.id===r.id&&(i.quantity=r.quantity),i))]),ne(o),it()},async getPaymentMethodChoice(){let r=_o(R(),t);return r==null?null:zo(r)},async redirectToNextStep(r){let o=_o(R(),t);if(o==null)return q("cart-is-empty","badInput");_optionalChain([r, 'optionalAccess', _224 => _224.paymentMethod])!=null&&(o.paymentMethod=r.paymentMethod);let i=await Mr(o);return Ae(i)?(console.warn("cannot create payment URL",i.error),i):{url:i.url,...i.orderId!=null?{orderId:i.orderId}:{},...i.projectId!=null?{projectId:i.projectId}:{}}},async justRedirectToPayment(r){let o={items:[{id:r.productID,quantity:1}],askForNote:!1,details:r.email||r.name?{name:r.name,email:r.email}:void 0,locale:_nullishCoalesce(r.locale, () => (t))};o=Ur(o),r.country==null&&(r.country="pl"),o.details==null&&(o.details={}),o.details.address==null&&(o.details.address={}),o.details.address.country=r.country,r.marketingAgreement===!0&&(o.additionalAgreements=[{id:hs,name:"",required:!0,answer:!0}]);let i=await Mr(o);return Ae(i)?i:{url:i.url}},async getApplePayPreview(r){let o=R();try{let i=await me.get(_chunk4HGZZJELjs.e).getPreOrderDetails({items:r.items.map(d=>_protobuf.create.call(void 0, _chunkG4V2KWTVjs.c,{id:d.productID,quantity:d.quantity})),projectId:e,postCode:o.postalCode,couponCode:o.couponCode,countryCode:o.country,selectedDeliveryMethod:o.selectedDeliveryMethod});return i.totalAmount==null||i.currency.length===0?q("pre-order-unavailable","internal"):{countryCode:i.country||o.country||"PL",currencyCode:i.currency,totalAmount:`${z(i.totalAmount/100,2)}`}}catch(i){return console.warn("cannot load the Apple Pay preview",i),q("pre-order-unavailable","internal")}},async completeApplePayPayment(r){let o=R();if(o==null)return q("Checkout not found");let i=await at(e,{locale:t});if(Ae(i))return i;try{let d=_optionalChain([r, 'access', _225 => _225.shippingContact, 'optionalAccess', _226 => _226.givenName]);_optionalChain([r, 'access', _227 => _227.shippingContact, 'optionalAccess', _228 => _228.familyName])!=null?d+=" "+_optionalChain([r, 'access', _229 => _229.shippingContact, 'optionalAccess', _230 => _230.familyName]):_optionalChain([r, 'access', _231 => _231.billingContact, 'optionalAccess', _232 => _232.familyName])!=null&&(d+=" "+_optionalChain([r, 'access', _233 => _233.billingContact, 'optionalAccess', _234 => _234.familyName]));let c={},l=zt();l!=null&&(c.ref=l);let b=await me.get(_chunk4HGZZJELjs.e).authorizeOneClickPayment({gateway:0,paymentData:JSON.stringify(r.token.paymentData),paymentMethod:JSON.stringify(r.token.paymentMethod),transactionIdentifier:r.token.transactionIdentifier,order:_protobuf.create.call(void 0, _chunkG4V2KWTVjs.d,{items:i.map(P=>({id:P.productID,quantity:P.quantity})),couponCode:o.couponCode,email:_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([r, 'access', _235 => _235.shippingContact, 'optionalAccess', _236 => _236.emailAddress]), () => (_optionalChain([r, 'access', _237 => _237.billingContact, 'optionalAccess', _238 => _238.emailAddress]))), () => (o.email)), () => (void 0)),phone:_nullishCoalesce(_nullishCoalesce(_optionalChain([r, 'access', _239 => _239.shippingContact, 'optionalAccess', _240 => _240.phoneNumber]), () => (_optionalChain([r, 'access', _241 => _241.billingContact, 'optionalAccess', _242 => _242.phoneNumber]))), () => (void 0)),selectedDeliveryMethod:o.selectedDeliveryMethod,postCode:o.postalCode,projectId:e}),shippingAddress:_protobuf.create.call(void 0, _chunkG4V2KWTVjs.a,{line1:_nullishCoalesce(_optionalChain([r, 'access', _243 => _243.shippingContact, 'optionalAccess', _244 => _244.addressLines, 'optionalAccess', _245 => _245[0]]), () => ("")),city:_nullishCoalesce(_optionalChain([r, 'access', _246 => _246.shippingContact, 'optionalAccess', _247 => _247.locality]), () => ("")),country:_nullishCoalesce(_optionalChain([r, 'access', _248 => _248.shippingContact, 'optionalAccess', _249 => _249.countryCode]), () => ("")),zipCode:_nullishCoalesce(_optionalChain([r, 'access', _250 => _250.shippingContact, 'optionalAccess', _251 => _251.postalCode]), () => ("")),name:d}),billingAddress:_protobuf.create.call(void 0, _chunkG4V2KWTVjs.b,{name:_nullishCoalesce(_optionalChain([r, 'access', _252 => _252.billingContact, 'optionalAccess', _253 => _253.givenName]), () => (" "+(_nullishCoalesce(_optionalChain([r, 'access', _254 => _254.billingContact, 'optionalAccess', _255 => _255.familyName]), () => (""))))),line1:_nullishCoalesce(_optionalChain([r, 'access', _256 => _256.billingContact, 'optionalAccess', _257 => _257.addressLines, 'optionalAccess', _258 => _258[0]]), () => ("")),city:_nullishCoalesce(_optionalChain([r, 'access', _259 => _259.billingContact, 'optionalAccess', _260 => _260.locality]), () => ("")),country:_nullishCoalesce(_optionalChain([r, 'access', _261 => _261.billingContact, 'optionalAccess', _262 => _262.countryCode]), () => ("")),zipCode:_nullishCoalesce(_optionalChain([r, 'access', _263 => _263.billingContact, 'optionalAccess', _264 => _264.postalCode]), () => (""))}),metadata:Object.keys(c).length>0?JSON.stringify(c):void 0});return{isSuccess:b.isSuccess,redirectURL:b.redirectUrl}}catch(d){return console.error(d),q("Failed to authorize payment")}},async completeGooglePayPayment(r){let o=R();if(o==null)return q("Checkout not found");let i=await at(e,{locale:t});if(Ae(i))return i;try{let d=_optionalChain([r, 'access', _265 => _265.paymentData, 'access', _266 => _266.shippingAddress, 'optionalAccess', _267 => _267.name]),c={},l=zt();l!=null&&(c.ref=l);let b=await me.get(_chunk4HGZZJELjs.e).authorizeOneClickPayment({gateway:1,paymentData:r.paymentData.paymentMethodData.tokenizationData.token,paymentMethod:r.paymentData.paymentMethodData.type,transactionIdentifier:"",order:_protobuf.create.call(void 0, _chunkG4V2KWTVjs.d,{items:i.map(P=>({id:P.productID,quantity:P.quantity})),couponCode:o.couponCode,email:_nullishCoalesce(r.paymentData.email, () => (void 0)),phone:_nullishCoalesce(_optionalChain([r, 'access', _268 => _268.paymentData, 'access', _269 => _269.shippingAddress, 'optionalAccess', _270 => _270.phoneNumber]), () => (void 0)),selectedDeliveryMethod:_nullishCoalesce(_optionalChain([r, 'access', _271 => _271.paymentData, 'access', _272 => _272.shippingOptionData, 'optionalAccess', _273 => _273.id]), () => (o.selectedDeliveryMethod)),postCode:_optionalChain([r, 'access', _274 => _274.paymentData, 'access', _275 => _275.shippingAddress, 'optionalAccess', _276 => _276.postalCode]),projectId:e}),shippingAddress:_protobuf.create.call(void 0, _chunkG4V2KWTVjs.a,{line1:_nullishCoalesce(_optionalChain([r, 'access', _277 => _277.paymentData, 'access', _278 => _278.shippingAddress, 'optionalAccess', _279 => _279.address1]), () => ("")),city:_nullishCoalesce(_optionalChain([r, 'access', _280 => _280.paymentData, 'access', _281 => _281.shippingAddress, 'optionalAccess', _282 => _282.locality]), () => ("")),country:_nullishCoalesce(_optionalChain([r, 'access', _283 => _283.paymentData, 'access', _284 => _284.shippingAddress, 'optionalAccess', _285 => _285.countryCode]), () => ("")),zipCode:_nullishCoalesce(_optionalChain([r, 'access', _286 => _286.paymentData, 'access', _287 => _287.shippingAddress, 'optionalAccess', _288 => _288.postalCode]), () => ("")),name:d}),billingAddress:_protobuf.create.call(void 0, _chunkG4V2KWTVjs.b,{name:_optionalChain([r, 'access', _289 => _289.paymentData, 'access', _290 => _290.paymentMethodData, 'access', _291 => _291.info, 'optionalAccess', _292 => _292.billingAddress, 'optionalAccess', _293 => _293.name]),line1:_nullishCoalesce(_optionalChain([r, 'access', _294 => _294.paymentData, 'access', _295 => _295.paymentMethodData, 'access', _296 => _296.info, 'optionalAccess', _297 => _297.billingAddress, 'optionalAccess', _298 => _298.address1]), () => ("")),city:_nullishCoalesce(_optionalChain([r, 'access', _299 => _299.paymentData, 'access', _300 => _300.paymentMethodData, 'access', _301 => _301.info, 'optionalAccess', _302 => _302.billingAddress, 'optionalAccess', _303 => _303.locality]), () => ("")),country:_nullishCoalesce(_optionalChain([r, 'access', _304 => _304.paymentData, 'access', _305 => _305.paymentMethodData, 'access', _306 => _306.info, 'optionalAccess', _307 => _307.billingAddress, 'optionalAccess', _308 => _308.countryCode]), () => ("")),zipCode:_nullishCoalesce(_optionalChain([r, 'access', _309 => _309.paymentData, 'access', _310 => _310.paymentMethodData, 'access', _311 => _311.info, 'optionalAccess', _312 => _312.billingAddress, 'optionalAccess', _313 => _313.postalCode]), () => (""))}),metadata:Object.keys(c).length>0?JSON.stringify(c):void 0});return{isSuccess:b.isSuccess,redirectURL:b.redirectUrl}}catch(d){return console.error(d),q("Failed to authorize payment")}return{isSuccess:!0}},async getApplePayPaymentRequest(r){let o=R();if(o==null)return q("Checkout not found");r&&r.expectedItems!=null&&r.expectedItems.length>0&&(o.products&&Uo(o.products.map(l=>l.productID)),await Oo(e,r.expectedItems));let i=await at(e,{locale:t});if(Ae(i))return i;let d=await me.get(_chunk4HGZZJELjs.e).getPreOrderDetails({items:i.map(l=>_protobuf.create.call(void 0, _chunkG4V2KWTVjs.c,{id:l.productID,quantity:l.quantity})),projectId:e,postCode:o.postalCode,couponCode:o.couponCode,countryCode:o.country,selectedDeliveryMethod:o.selectedDeliveryMethod}),c=i.map(l=>({amount:`${z(l.quantity*(_nullishCoalesce(_nullishCoalesce(_optionalChain([l, 'access', _314 => _314.details, 'optionalAccess', _315 => _315.pricing, 'optionalAccess', _316 => _316.effectivePrice]), () => (_optionalChain([l, 'access', _317 => _317.details, 'optionalAccess', _318 => _318.price]))), () => (0)))/100,2)}`,label:_optionalChain([l, 'access', _319 => _319.details, 'optionalAccess', _320 => _320.name])+" - "+l.quantity,type:"final"}));if(d.selectedDeliveryMethod!=null){let l=d.methods.find(b=>b.id==d.selectedDeliveryMethod);l!=null&&c.push({amount:`${z(l.amount/100,2)}`,label:l.name,type:"final"})}return d.couponCode!=null&&d.couponValue!=null&&c.push({amount:`-${z(d.couponValue/100,2)}`,label:d.couponCode,type:"final"}),{countryCode:d.country||o.country||"PL",merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],supportedNetworks:["visa","masterCard"],total:{amount:`${z((_nullishCoalesce(d.totalAmount, () => (0)))/100,2)}`,label:_chunk7RXW6XFYjs.c.call(void 0, "paymentForCart",t,n),type:"final"},shippingMethods:d.methods.map(l=>({amount:`${z(l.amount/100,2)}`,detail:_nullishCoalesce(l.description, () => ("")),identifier:l.id,label:l.name,dateComponentsRange:{startDateComponents:{days:_nullishCoalesce(l.minDays, () => (1)),hours:0,months:0,years:0},endDateComponents:{days:_nullishCoalesce(l.maxDays, () => (14)),hours:0,months:0,years:0}}})),lineItems:c,currencyCode:d.currency||_optionalChain([i, 'access', _321 => _321[0], 'optionalAccess', _322 => _322.details, 'optionalAccess', _323 => _323.currency])||"PLN"}}}};async function Ss(e){let t=R();if(_optionalChain([t, 'access', _324 => _324.googlePayConfig, 'optionalAccess', _325 => _325.isAvailable])!=!0){let n=await me.get(_chunk4HGZZJELjs.e).isOneClickPaymentAvailable({projectId:e});n.googlePay==!0&&n.googlePayConfig!=null?t.googlePayConfig={isAvailable:!0,gateway:n.googlePayConfig.gateway,gatewayId:n.googlePayConfig.gatewayMerchantId,merchantName:n.googlePayConfig.merchantName,merchantId:n.googlePayConfig.merchantId}:t.googlePayConfig={isAvailable:!1,gateway:"",gatewayId:"",merchantName:"",merchantId:""}}return ne(t),t.googlePayConfig}function Es(e,t){if(e==t.id){let a=_optionalChain([t, 'access', _326 => _326.variants, 'optionalAccess', _327 => _327.findIndex, 'call', _328 => _328(r=>r.id===e)]);if(a!=null&&a!=-1){let r=t.variants[a];return{...t,availableQuantity:r.availableQuantity,isDeliverable:r.isDeliverable,images:_nullishCoalesce(r.images, () => (t.images)),name:t.name+" "+r.name,baseName:t.name,variantName:r.name,price:r.price,currency:r.currency,pricing:r.pricing}}return t}let n=_optionalChain([t, 'access', _329 => _329.variants, 'optionalAccess', _330 => _330.find, 'call', _331 => _331(a=>a.id===e)]);return n==null?t:{...t,id:n.id,name:t.name+" "+n.name,baseName:t.name,variantName:n.name,price:n.price,currency:n.currency,pricing:n.pricing,metadata:t.metadata,availableQuantity:n.availableQuantity,isDeliverable:n.isDeliverable,images:_nullishCoalesce(n.images, () => (t.images))}}function it(){let e=R(),t=0;if(e==null){ot.setState(n=>({...n,numberOfProductsInCart:t}));return}t=_nullishCoalesce(_optionalChain([e, 'access', _332 => _332.products, 'optionalAccess', _333 => _333.reduce, 'call', _334 => _334((n,a)=>n+a.quantity,0)]), () => (0)),ot.setState(n=>({...n,numberOfProductsInCart:t}))}var Ls=200,Rs= exports.r ="item-ids-not-found",Pt="internal-error",Ho={"no-payment-gateway":"noPaymentGateway","gateway-not-configured":"gatewayNotConfigured","shipping-not-configured":"shippingNotConfigured","mixed-recurring":"mixedRecurring","currency-unsupported":"currencyUnsupported","price-changed":"priceChanged","product-not-found":"unavailableProducts","product-not-available":"unavailableProducts"},As=new Set(["internal","invalid-request"]),Ds=new Set(["product-not-available","product-not-found"]);function Ms(e){return typeof e=="string"&&Object.hasOwn(Ho,e)?Ho[e]:void 0}function Os(e){return/<\/?[a-z!?][^>]*>/i.test(e)}function Us(e){return/^[A-Za-z][A-Za-z0-9]*(?:[-_.:][A-Za-z0-9]+)*$/.test(e)&&!/^[A-Z][a-z]+$/.test(e)||/^\[object \w+\]$|^(?:undefined|null)$/.test(e)}function _s(e){return/Error:/.test(e)||/\n\s+at /.test(e)}function zr(e){let t=e.trim();if(!(t.length===0||t.length>Ls||/[\r\n]/.test(t)||Os(t)||Us(t)||_s(t)))return t}var zs=3;function Ft(e,t=0){if(typeof e=="object"&&e!=null){if(Array.isArray(e)||t>=zs)return{};let n=e,a=Ft(n.error,t+1);if(a.message==null&&n.message!=null){let r=Ft(n.message,t+1);a={...r,code:_nullishCoalesce(a.code, () => (r.code))}}return typeof n.code=="string"&&n.code.length>0&&(a.code=n.code),a}if(typeof e!="string")return{};try{let n=JSON.parse(e);return typeof n=="object"&&n!=null?Ft(n,t+1):{}}catch (e28){}return{message:zr(e)}}function js(e){let t;try{t=JSON.parse(e)}catch (e29){return{code:Pt,message:zr(e)}}if(typeof t=="string")return{code:Pt,message:zr(t)};if(typeof t!="object"||t==null)return{code:Pt};let n=t,{message:a,code:r}=Ft(n.error),o={code:typeof n.code=="string"&&n.code.length>0?n.code:_nullishCoalesce(r, () => (Pt)),message:a};return Array.isArray(n.itemIds)&&(o.itemIds=n.itemIds.filter(i=>typeof i=="string")),o}function jr(e,t){let{code:n,message:a,itemIds:r}=js(t),o=r!=null&&r.length>0;if(o&&(n===Pt||Ds.has(n)))return q(Rs,"badInput",r);let i={message:a};return o&&(i.itemIds=r),q(n,e>=500?"internal":"badInput",i)}function Fp(e,t){let n=Ms(e.error);if(n!=null)return t(n);if(e.type==="internal"||typeof e.error=="string"&&As.has(e.error))return t("checkoutFailed");let a=_optionalChain([e, 'access', _335 => _335.data, 'optionalAccess', _336 => _336.message]);return typeof a=="string"&&a.length>0?a:t("checkoutFailed")}var Fs=["online","manual","cod"],Hs=["bankTransfer","blik"];function $o(e,t){if(!Array.isArray(e))return[];let n=[];for(let a of e)t.includes(a)&&!n.includes(a)&&n.push(a);return n}function $s(e){if(typeof e!="object"||e==null)return null;let t=e.choice;if(typeof t!="object"||t==null)return null;let n=$o(t.methods,Fs);return n.length<2?null:{methods:n,manualAccountTypes:$o(t.manualAccountTypes,Hs)}}function $p(e){if(e==null)return null;let t=e.methods.filter(n=>n!=="cod");return t.length<2?null:{...e,methods:t}}function qp(e,t){return t!=null&&e.methods.includes(t)?t:e.methods[0]}function Bp(e){let t=e.includes("bankTransfer"),n=e.includes("blik");return n&&!t?"paymentMethodManualBlik":t&&!n?"paymentMethodManualTransfer":"paymentMethodManualBoth"}async function qo(e,t,n=5e3){let a=typeof AbortController>"u"?void 0:new AbortController,r=setTimeout(()=>_optionalChain([a, 'optionalAccess', _337 => _337.abort, 'call', _338 => _338()]),n);try{let o=await fetch(e,{method:"POST",headers:t.headers,body:t.body,signal:_optionalChain([a, 'optionalAccess', _339 => _339.signal])});return o.ok?$s(await o.json()):null}catch (e30){return null}finally{clearTimeout(r)}}var qs;(a=>{async function e(r,o=1,i,d){let c=st();if(c==null)throw new Error("No project ID found");let b=await _r(c).addProduct({productID:r,quantity:o,metadata:i,...d});if(b!=null)return b}a.addProductToCart=e;function t(){ot.setState({isCartVisible:!0})}a.showCart=t;function n(){ot.setState({isCartVisible:!1})}a.hideCart=n})(qs = exports.x||={});async function Bo(e){try{return await e.text()}catch (e31){return""}}function Ko(e,t){return t=Ur(t),t.locale??=_chunk7RXW6XFYjs.f.call(void 0, ),{headers:{..._chunk4HGZZJELjs.a,..._chunkDP2NOHCIjs.h.call(void 0, e),"Content-Type":"application/json"},body:JSON.stringify(t)}}async function zo(e){let t=st();return t==null?null:qo(nt(t,"/payment-methods"),Ko(t,e))}async function Mr(e){let t=st();if(t==null)throw new Error("No project ID found");let n=await fetch(nt(t,"/buy"),{method:"POST",...Ko(t,e)});if(n.status!=200){let r=jr(n.status,await Bo(n));return console.warn("cannot create payment URL",n.status,r.error),r}let a=await n.json();return{url:a.url,...a.orderId!=null?{orderId:a.orderId}:{},...a.projectId!=null?{projectId:a.projectId}:{}}}async function em(e){let t=st();if(t==null)throw new Error("No project ID found");let n={..._chunk4HGZZJELjs.a,..._chunkDP2NOHCIjs.h.call(void 0, t),"Content-Type":"application/json",...e.apiKey!=null?{Authorization:`Bearer ${e.apiKey}`}:{}},a=e.testMode?`/api/payment/link/auto/${t}/test`:`/api/payment/link/auto/${t}`;delete e.apiKey,delete e.testMode,e.locale??=_chunk7RXW6XFYjs.f.call(void 0, );let r=await fetch(_chunk4HGZZJELjs.e+a,{method:"POST",headers:n,body:JSON.stringify(e)});return r.ok?{status:"ok",redirectURL:(await r.json()).url}:{...jr(r.status,await Bo(r)),status:"error"}}function zt(){if(typeof localStorage>"u")return;let e=localStorage.getItem("bitsnap-ref");if(e!=null)return e}function Ur(e){let t=zt();return t==null||(e.metadata==null&&(e.metadata={}),e.metadata.ref=t),e}exports.a = me; exports.b = Ee; exports.c = Oe; exports.d = Ue; exports.e = Te; exports.f = Ln; exports.g = gt; exports.h = yt; exports.i = Ye; exports.j = Ze; exports.k = ma; exports.l = Sr; exports.m = Vi; exports.n = z; exports.o = ko; exports.p = Er; exports.q = Ae; exports.r = Rs; exports.s = Fp; exports.t = $p; exports.u = qp; exports.v = Bp; exports.w = ot; exports.x = qs; exports.y = zo; exports.z = Mr; exports.A = em; exports.B = zt; exports.C = Ur; exports.D = ep; exports.E = tp; exports.F = rp; exports.G = ap; exports.H = hs; exports.I = Or; exports.J = Rp; exports.K = st; exports.L = Ap; exports.M = Dp; exports.N = xs; exports.O = Mp; exports.P = Op; exports.Q = _r;
5
+ //# sourceMappingURL=chunk-V5ECGBFW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-V5ECGBFW.js","../src/panel/components/PanelLogin.tsx","../src/ui/card.tsx","../src/ui/email-code-login/EmailCodeLoginForm.tsx","../src/lib/render.text.tsx","../src/panel/audio-player/media.session.coordinator.ts","../src/panel/audio-player/AudioPlayer.tsx"],"names":["Card","className","props","jsx","cn","CardHeader","CardTitle","CardDescription","CardContent","MUTED","DARK_FIELD","EMAIL_FAILURES","LINK","EmailCodeLoginForm","login","texts","allowHaveCode","emailPlaceholder","emailInputId","codeInputId","buttonClassName","children","uid","useId","emailId"],"mappings":"AAAA,ylCAAgN,sDAAiG,sDAA+I,sDAA+E,sDAAyE,sDAAgE,oDCAznB,+BACwB,+CCKnD,SAFKA,EAAAA,CAAK,CAAE,SAAA,CAAAC,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CAClE,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,MAAA,CACV,SAAA,CAAWC,gCAAAA,mFACT,CACAH,CACF,CAAA,CACC,GAAGC,CAAAA,CACN,CAEJ,CAEA,SAASG,EAAAA,CAAW,CAAE,SAAA,CAAAJ,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CACxE,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,aAAA,CACV,SAAA,CAAWC,gCAAAA,0JACT,CACAH,CACF,CAAA,CACC,GAAGC,CAAAA,CACN,CAEJ,CAEA,SAASI,EAAAA,CAAU,CAAE,SAAA,CAAAL,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CACvE,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,YAAA,CACV,SAAA,CAAWC,gCAAAA,4BAAG,CAA8BH,CAAS,CAAA,CACpD,GAAGC,CAAAA,CACN,CAEJ,CAEA,SAASK,EAAAA,CAAgB,CAAE,SAAA,CAAAN,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CAC7E,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,kBAAA,CACV,SAAA,CAAWC,gCAAAA,+BAAG,CAAiCH,CAAS,CAAA,CACvD,GAAGC,CAAAA,CACN,CAEJ,CAeA,SAASM,EAAAA,CAAY,CAAE,SAAA,CAAAP,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CACzE,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,cAAA,CACV,SAAA,CAAWC,gCAAAA,MAAG,CAAQH,CAAS,CAAA,CAC9B,GAAGC,CAAAA,CACN,CAEJ,CCvEA,2CAA4B,IA6BtBO,EAAAA,CAAQ,yCAAA,CAERC,EAAAA,CACJ,0MAAA,CAEIC,EAAAA,CAAiB,IAAI,GAAA,CAAI,CAAC,cAAA,CAAgB,eAAA,CAAiB,qBAAqB,CAAC,CAAA,CACjFC,EAAAA,CACJ,sNAAA,CAOK,SAASC,EAAAA,CAAmB,CACjC,KAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CAAgB,CAAA,CAAA,CAChB,gBAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,SAAA,CAAAlB,CAAAA,CACA,eAAA,CAAAmB,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAA4B,CAC1B,IAAMC,CAAAA,CAAMC,2BAAAA,CAAM,CACZC,CAAAA,kBAAUN,CAAAA,SAAgB,CAAA,EAAA;ACGlB,QAAA;ACT6B,YAAA;AC2zBb","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-V5ECGBFW.js","sourcesContent":[null,"import { useAutoAnimate } from \"@formkit/auto-animate/react\";\nimport { useEffect, useMemo, type CSSProperties } from \"react\";\nimport {\n InstrumentProvider,\n useInstrument,\n useInstrumentContext,\n type AnalyticsOption,\n} from \"../../analytics/instrument\";\nimport { getLocale } from \"../../components/checkout/locale\";\nimport { rpcProvider, useMutation } from \"../../rpc-provider\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"../../ui/card\";\nimport { kindFromRpcError } from \"../../ui/email-code-login/errors\";\nimport {\n LoginBrandLogo,\n type LoginLogoOptions,\n} from \"../../ui/email-code-login/LoginBrandLogo\";\nimport { EmailCodeLoginForm } from \"../../ui/email-code-login/EmailCodeLoginForm\";\nimport { pendingLoginKey } from \"../../ui/email-code-login/pending\";\nimport {\n useEmailCodeLogin,\n type EmailCodeAdapter,\n} from \"../../ui/email-code-login/useEmailCodeLogin\";\nimport {\n getAllowedReturnOrigins,\n setAllowedReturnOrigins,\n} from \"../config\";\nimport { panelFailureKind } from \"../login-adapter\";\nimport { resolvePanelLoginTexts, type PanelLoginTexts } from \"../login-texts\";\nimport { usePanelConfig } from \"../PanelProvider\";\nimport type { PanelLoginProps } from \"../types\";\nimport {\n buildAccessTokenRedirect,\n getReturnURLFromSearch,\n persistReturnURL,\n readPersistedReturnURL,\n} from \"../return-url\";\nimport { getPanelSession, savePanelSession } from \"../session-storage\";\n\nif (typeof window !== \"undefined\") {\n const currentOrigin = window.location.origin;\n const knownSiblings = [\n currentOrigin,\n \"https://bitsnap.pl\",\n \"https://kursy.bitsnap.pl\",\n ];\n if (getAllowedReturnOrigins().length === 0) {\n setAllowedReturnOrigins(Array.from(new Set(knownSiblings)));\n }\n}\n\n\n/** Props of {@link PanelLogin}; `PanelLoginProps` of the package is a superset. */\nexport type PanelLoginComponentProps = Pick<\n PanelLoginProps,\n \"analytics\" | \"texts\" | \"locale\" | \"showLogo\" | \"logoUrl\" | \"logoDarkUrl\"\n>;\n\ntype PanelLoginResult = { accessToken: string };\n\nconst PanelLoginForm = ({\n texts,\n projectID,\n host,\n locale,\n logo,\n}: {\n texts: PanelLoginTexts;\n projectID?: string;\n host?: string;\n locale?: string;\n logo: LoginLogoOptions;\n}) => {\n const instrument = useInstrumentContext();\n const { mutateAsync: loginUserAsync } = useMutation(\n rpcProvider.publicApi.userPanelLogin,\n );\n const { mutateAsync: verifyCodeAsync } = useMutation(\n rpcProvider.publicApi.userPanelLoginWithCode,\n );\n\n const adapter = useMemo<EmailCodeAdapter<PanelLoginResult>>(\n () => ({\n async send(email) {\n try {\n const response = await loginUserAsync({ email });\n if (response.result.case === \"success\") {\n return {\n ok: true,\n retryIn: response.result.value.retryIn || undefined,\n challengeId: response.result.value.challengeId || undefined,\n };\n }\n return {\n ok: false,\n kind: panelFailureKind(\n response.result.case === \"failure\" ? response.result.value : 0,\n ),\n };\n } catch (cause) {\n return { ok: false, kind: kindFromRpcError(cause), cause };\n }\n },\n async verify({ email, code, challengeId }) {\n try {\n const response = await verifyCodeAsync({\n code: parseInt(code, 10),\n email,\n challengeId,\n });\n if (response.result.case === \"accessToken\" && response.result.value) {\n return { ok: true, value: { accessToken: response.result.value } };\n }\n return {\n ok: false,\n kind: panelFailureKind(\n response.result.case === \"failure\" ? response.result.value : 0,\n ),\n };\n } catch (cause) {\n return { ok: false, kind: kindFromRpcError(cause), cause };\n }\n },\n }),\n [loginUserAsync, verifyCodeAsync],\n );\n\n const login = useEmailCodeLogin<PanelLoginResult>({\n adapter,\n texts,\n storageKey: pendingLoginKey(\"panel\", projectID, host),\n onVerified: ({ accessToken }, email) => {\n instrument.track(\"panel_login\", {});\n savePanelSession(projectID, accessToken, email, host);\n const returnURL =\n typeof window !== \"undefined\" ? readPersistedReturnURL() : null;\n setTimeout(() => {\n if (returnURL) {\n window.location.href = buildAccessTokenRedirect(returnURL, accessToken);\n return;\n }\n window.location.reload();\n }, 100);\n },\n });\n\n const onCodeStep = login.step === \"code\";\n const title = onCodeStep && !login.needsEmail ? texts.codeTitle : texts.title;\n const description =\n onCodeStep && !login.needsEmail ? texts.codeDescription : texts.description;\n\n return (\n // Top-aligned: a vertically centred card moved when the step changed height.\n <main className=\"mx-auto flex w-full max-w-sm flex-1 flex-col justify-start pt-4 sm:pt-[12vh]\">\n <Card>\n <LoginBrandLogo\n projectId={projectID}\n locale={locale}\n className=\"px-4 sm:px-6\"\n {...logo}\n />\n <CardHeader className=\"px-4 sm:px-6\">\n <CardTitle role=\"heading\" aria-level={1} className=\"text-2xl\">\n {title}\n </CardTitle>\n <CardDescription>{description}</CardDescription>\n </CardHeader>\n <CardContent className=\"px-4 sm:px-6\">\n <EmailCodeLoginForm\n login={login}\n texts={texts}\n emailInputId=\"email\"\n codeInputId=\"verify-code\"\n />\n </CardContent>\n </Card>\n </main>\n );\n};\n\nconst PanelLoginComponentWrapper = ({\n analytics,\n texts: textOverrides,\n locale,\n showLogo,\n logoUrl,\n logoDarkUrl,\n}: PanelLoginComponentProps) => {\n const { theme, allowedReturnOrigins, projectID, host } = usePanelConfig();\n const instrument = useInstrument(projectID, analytics, \"panel\");\n const texts = useMemo(\n () => resolvePanelLoginTexts(locale ?? getLocale(), textOverrides),\n [locale, textOverrides],\n );\n\n const styles = {\n \"--button-background-color\": theme?.colors?.brand ?? \"#FFFFFF\",\n \"--button-background-color-dark\": theme?.colors?.brandDark ?? \"#000000\",\n \"--button-text-color\": theme?.colors?.brandDark ?? \"#000000\",\n \"--button-text-color-dark\": theme?.colors?.brand ?? \"#FFFFFF\",\n } as CSSProperties;\n\n const [parent] = useAutoAnimate({\n duration: 300,\n easing: \"ease-in-out\",\n disrespectUserMotionPreference: false,\n });\n\n // Already signed in: leave the login page. Declared before the return URL\n // effect below, so that one (a token redirect) wins when both apply.\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n if (getPanelSession(projectID, host) != null) {\n window.location.href = window.location.href.replaceAll(\"login\", \"\");\n }\n }, [projectID, host]);\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n if (window.parent !== window) return;\n\n const queryReturnURL = getReturnURLFromSearch(window.location.search);\n if (queryReturnURL) {\n persistReturnURL(queryReturnURL);\n }\n\n const returnURL = queryReturnURL ?? readPersistedReturnURL();\n if (!returnURL) return;\n\n const existingToken = getPanelSession(projectID, host);\n if (!existingToken) return;\n\n window.location.href = buildAccessTokenRedirect(returnURL, existingToken);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [allowedReturnOrigins, projectID, host]);\n\n return (\n <InstrumentProvider value={instrument}>\n <div className=\"bg-white text-black dark:bg-black dark:text-white\">\n <div\n className=\"font-inter flex min-h-screen w-full flex-col p-4\"\n style={styles}\n ref={parent}\n >\n <PanelLoginForm\n texts={texts}\n projectID={projectID}\n host={host}\n locale={locale}\n logo={{\n showLogo,\n logoUrl: logoUrl ?? theme?.logoURL,\n logoDarkUrl: logoDarkUrl ?? theme?.logoDarkURL,\n }}\n />\n </div>\n </div>\n </InstrumentProvider>\n );\n};\n\nexport const PanelLogin = (props: PanelLoginComponentProps = {}) => {\n return <PanelLoginComponentWrapper {...props} />;\n};\n","import * as React from \"react\"\n\nimport { cn } from \"@/src/lib/utils\"\n\nfunction Card({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card\"\n className={cn(\n \"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"@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\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\"leading-none font-semibold\", className)}\n {...props}\n />\n )\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-muted-foreground text-sm\", className)}\n {...props}\n />\n )\n}\n\nfunction CardAction({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-action\"\n className={cn(\n \"col-start-2 row-span-2 row-start-1 self-start justify-self-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"px-6\", className)}\n {...props}\n />\n )\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\"flex items-center px-6 [.border-t]:pt-6\", className)}\n {...props}\n />\n )\n}\n\nexport {\n Card,\n CardHeader,\n CardFooter,\n CardTitle,\n CardAction,\n CardDescription,\n CardContent,\n}\n","import { CircleCheck } from \"lucide-react\";\nimport { useId, type FormEvent, type ReactNode } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport { Button } from \"../button\";\nimport { Input } from \"../input\";\nimport { Label } from \"../label\";\nimport { Spinner } from \"../spinner\";\nimport { OtpCodeField } from \"./OtpCodeField\";\nimport { fillText, type EmailCodeTexts } from \"./texts\";\nimport { type EmailCodeLogin } from \"./useEmailCodeLogin\";\n\nexport type EmailCodeLoginFormProps = {\n login: EmailCodeLogin;\n texts: EmailCodeTexts;\n /** Offers \"I already have a code\" under the e-mail step. */\n allowHaveCode?: boolean;\n /** Overrides the e-mail input placeholder. */\n emailPlaceholder?: string;\n /** `id` of the e-mail input; unique per instance by default. */\n emailInputId?: string;\n /** `id` of the code input; unique per instance by default. */\n codeInputId?: string;\n className?: string;\n /** Classes of the two primary buttons (brand colors). */\n buttonClassName?: string;\n /** Shown above the fields of the code step, after the \"sent to\" line. */\n children?: ReactNode;\n};\n\nconst MUTED = \"text-muted-foreground text-xs leading-5\";\n/** Borders of the dark theme: the `input` token is nearly the card colour. */\nconst DARK_FIELD =\n \"dark:border-foreground/30 dark:focus-visible:border-foreground/70 dark:focus-visible:ring-foreground/25 dark:aria-invalid:border-destructive-foreground dark:aria-invalid:ring-destructive-foreground/30\";\n/** Failures about the address itself; a throttled or failed send is not. */\nconst EMAIL_FAILURES = new Set([\"invalidEmail\", \"emailNotFound\", \"deliveryUnavailable\"]);\nconst LINK =\n \"inline-flex min-h-11 items-center px-1 text-sm underline underline-offset-4 hover:no-underline focus-visible:ring-[3px] focus-visible:ring-ring/50 rounded-sm outline-none disabled:opacity-50 disabled:no-underline\";\n\n/**\n * The two steps of the shared e-mail-code login. Markup only: all state comes\n * from {@link useEmailCodeLogin}. The surface wraps it in its own card or\n * dialog and renders the titles.\n */\nexport function EmailCodeLoginForm({\n login,\n texts,\n allowHaveCode = true,\n emailPlaceholder,\n emailInputId,\n codeInputId,\n className,\n buttonClassName,\n children,\n}: EmailCodeLoginFormProps) {\n const uid = useId();\n const emailId = emailInputId ?? `${uid}-email`;\n const codeId = codeInputId ?? `${uid}-code`;\n const noticeId = `${uid}-notice`;\n const hintId = `${uid}-hint`;\n\n const { notice } = login;\n const isError = notice?.kind === \"error\";\n const sending = login.busy === \"send\";\n const verifying = login.busy === \"verify\";\n const resending = login.busy === \"resend\";\n const buttonBase = cn(\"h-11 w-full\", buttonClassName);\n\n // Both live regions stay mounted (empty) so that a screen reader has\n // registered them before a message is put in; only their text changes.\n // The area reserves two lines, so a longer message does not push the buttons.\n const success = notice?.kind === \"success\";\n const noticeArea = (\n <div id={noticeId} className=\"min-h-10 text-sm leading-5\">\n <p\n role=\"alert\"\n className=\"font-medium text-red-700 dark:text-red-400\"\n >\n {isError ? notice.text : null}\n </p>\n <p\n role=\"status\"\n className={cn(\n \"flex items-start gap-1.5\",\n success\n ? \"font-medium text-emerald-700 dark:text-emerald-400\"\n : \"text-foreground\",\n )}\n >\n {success && <CircleCheck aria-hidden className=\"mt-0.5 size-4 shrink-0\" />}\n <span>{notice != null && !isError ? notice.text : null}</span>\n </p>\n </div>\n );\n const emailInvalid =\n isError &&\n login.step === \"email\" &&\n (notice.failure == null || EMAIL_FAILURES.has(notice.failure));\n\n const announcer = (\n <p className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n {login.announcement}\n </p>\n );\n\n const emailField = (\n <div className=\"grid gap-2\">\n <Label htmlFor={emailId}>{texts.emailLabel}</Label>\n <Input\n id={emailId}\n ref={login.emailRef}\n name=\"email\"\n type=\"email\"\n autoComplete=\"email\"\n inputMode=\"email\"\n autoCapitalize=\"none\"\n autoCorrect=\"off\"\n spellCheck={false}\n autoFocus\n required\n className={cn(\n \"h-11 text-base disabled:opacity-100 disabled:text-foreground/70\",\n DARK_FIELD,\n )}\n placeholder={emailPlaceholder ?? texts.emailPlaceholder}\n value={login.email}\n disabled={login.isBusy}\n aria-invalid={emailInvalid ? true : undefined}\n aria-describedby={noticeId}\n onChange={(event) => login.setEmail(event.target.value)}\n />\n </div>\n );\n\n if (login.step === \"email\") {\n return (\n <form\n noValidate\n className={cn(\"flex flex-col gap-4\", className)}\n onSubmit={(event: FormEvent) => {\n event.preventDefault();\n void login.sendCode();\n }}\n >\n {announcer}\n {emailField}\n {noticeArea}\n <Button\n type=\"submit\"\n disabled={login.isBusy}\n aria-busy={sending}\n className={buttonBase}\n >\n {sending && <Spinner aria-hidden />}\n {sending ? texts.sending : texts.sendCode}\n </Button>\n {allowHaveCode && (\n <p className=\"flex flex-wrap items-center justify-center text-center text-sm\">\n {texts.haveCodePrompt !== \"\" && <span>{texts.haveCodePrompt}</span>}\n <button\n type=\"button\"\n className={LINK}\n disabled={login.isBusy}\n onClick={login.haveCode}\n >\n {texts.haveCode}\n </button>\n </p>\n )}\n </form>\n );\n }\n\n const [before, after] = texts.codeSentTo.split(\"{email}\");\n const dead = login.dead != null;\n const resendLabel = dead\n ? texts.resendNew\n : login.secondsLeft > 0\n ? fillText(texts.resendIn, { seconds: login.secondsLeft })\n : texts.resend;\n\n return (\n <form\n noValidate\n className={cn(\"flex flex-col gap-4\", className)}\n onSubmit={(event: FormEvent) => {\n event.preventDefault();\n void login.submitCode();\n }}\n >\n {announcer}\n {login.needsEmail ? (\n emailField\n ) : (\n <div className=\"flex flex-wrap items-center justify-between gap-x-2\">\n {/* The address moves to its own line before it is cut; the word\n joiner keeps the full stop with it. */}\n <p className=\"min-w-0 flex-[1_1_14rem] text-sm leading-5 break-words\">\n {before}\n <strong className=\"font-semibold\">{login.email}</strong>\n {\"\\u2060\"}\n {after}\n </p>\n <button\n type=\"button\"\n className={cn(LINK, \"-ml-1 shrink-0\")}\n disabled={login.isBusy}\n onClick={login.changeEmail}\n >\n {texts.changeEmail}\n </button>\n </div>\n )}\n {children}\n <div className=\"grid gap-2\">\n <Label htmlFor={codeId}>{texts.codeLabel}</Label>\n <OtpCodeField\n id={codeId}\n name=\"code\"\n inputRef={login.codeRef}\n value={login.code}\n onChange={login.setCode}\n onComplete={(value) => void login.submitCode(value)}\n disabled={login.isBusy || dead}\n invalid={isError && !login.needsEmail}\n aria-describedby={`${noticeId} ${hintId}`}\n />\n <p id={hintId} className={MUTED}>\n {texts.validity} {texts.spamHint}\n </p>\n </div>\n {noticeArea}\n <Button\n type=\"submit\"\n disabled={login.isBusy || dead}\n aria-busy={verifying}\n className={buttonBase}\n >\n {verifying && <Spinner aria-hidden />}\n {verifying ? texts.verifying : texts.verify}\n </Button>\n {login.needsEmail ? (\n <div className=\"flex justify-center\">\n <button\n type=\"button\"\n className={LINK}\n disabled={login.isBusy}\n onClick={login.changeEmail}\n >\n {texts.noCode}\n </button>\n </div>\n ) : (\n <Button\n type=\"button\"\n variant={dead ? \"default\" : \"outline\"}\n disabled={login.isBusy || (!dead && login.secondsLeft > 0)}\n aria-busy={resending}\n className={dead ? buttonBase : \"h-11 w-full\"}\n onClick={() => void login.resend()}\n >\n {resending && <Spinner aria-hidden />}\n {resendLabel}\n </Button>\n )}\n </form>\n );\n}\n","const URL_REGEX =\n /https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)/g;\n\ntype Replacements = {\n url: string;\n startIndex: number;\n endIndex: number;\n replacementText?: string;\n};\n\nconst findURLIndices = (text: string) => {\n const matches = [...text.matchAll(URL_REGEX)];\n return matches.map(\n (match) =>\n ({\n url: match[0],\n startIndex: match.index,\n endIndex: match.index + match[0].length - 1,\n }) as Replacements,\n );\n};\n\nconst replaceTextByIndices = (\n originalText: string,\n replacements: Replacements[],\n) => {\n let result = \"\";\n let lastIndex = 0;\n\n // Sort replacements by startIndex to handle them in order\n replacements.sort((a, b) => a.startIndex - b.startIndex);\n\n for (const { startIndex, endIndex, replacementText } of replacements) {\n // Append text before the current replacement\n result += originalText.slice(lastIndex, startIndex);\n // Append the replacement text\n result += replacementText;\n // Update lastIndex to after the replaced segment\n lastIndex = endIndex + 1;\n }\n\n // Append any remaining text after the last replacement\n result += originalText.slice(lastIndex);\n\n return result;\n};\n\nexport const renderText = (txt: string) => {\n const urlIndices = findURLIndices(txt);\n\n return (\n <p\n dangerouslySetInnerHTML={{\n __html: replaceTextByIndices(\n txt,\n urlIndices.map((el) => {\n el[\"replacementText\"] =\n `<a key=${el.url} href=${el.url} style=\"text-decoration: underline;\" target=\"_blank\">\n ${el.url}\n </a>`;\n return el;\n }),\n ),\n }}\n ></p>\n );\n};\n","/** Skip length of the player buttons and of the lock-screen skip handlers. */\nexport const SEEK_STEP_SECONDS = 10;\n\n/** Under this position \"previous track\" restarts the chapter instead of going back. */\nexport const PREVIOUS_TRACK_RESTART_SECONDS = 3;\n\nexport type MediaSessionArtwork = {\n src: string;\n sizes?: string;\n type?: string;\n};\n\nexport type MediaSessionMetadata = {\n title: string;\n album?: string;\n artist?: string;\n artwork?: string | MediaSessionArtwork | (string | MediaSessionArtwork)[];\n};\n\nconst MIME_BY_EXTENSION: Record<string, string> = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n avif: \"image/avif\",\n svg: \"image/svg+xml\",\n};\n\n/** Lock-screen artwork size we declare; the player does not decode the image. */\nconst ARTWORK_SIZES = \"512x512\";\n\nfunction mediaSessionAvailable(): boolean {\n return (\n typeof navigator != \"undefined\" &&\n typeof navigator.mediaSession != \"undefined\"\n );\n}\n\n/**\n * Turns an image URL into a media-session artwork entry. The `type` comes from\n * the file extension and is omitted when the extension is unknown, so the\n * browser does not get a wrong MIME type.\n */\nexport function mediaSessionArtworkFromUrl(url: string): MediaSessionArtwork {\n if (typeof url != \"string\" || url.length === 0) {\n return { src: url, sizes: ARTWORK_SIZES };\n }\n const withoutQuery = url.split(/[?#]/)[0];\n const extension = withoutQuery.includes(\".\")\n ? withoutQuery.slice(withoutQuery.lastIndexOf(\".\") + 1).toLowerCase()\n : \"\";\n const type = MIME_BY_EXTENSION[extension];\n const artwork: MediaSessionArtwork = { src: url, sizes: ARTWORK_SIZES };\n if (type != null) {\n artwork.type = type;\n }\n return artwork;\n}\n\nfunction normalizeArtwork(\n artwork: MediaSessionMetadata[\"artwork\"],\n): MediaSessionArtwork[] | undefined {\n if (artwork == null) {\n return undefined;\n }\n const entries = Array.isArray(artwork) ? artwork : [artwork];\n const normalized: MediaSessionArtwork[] = [];\n for (const entry of entries) {\n if (typeof entry === \"string\") {\n if (entry.length > 0) {\n normalized.push(mediaSessionArtworkFromUrl(entry));\n }\n continue;\n }\n if (entry != null && entry.src.length > 0) {\n normalized.push({\n src: entry.src,\n sizes: entry.sizes ?? ARTWORK_SIZES,\n ...(entry.type != null ? { type: entry.type } : {}),\n });\n }\n }\n return normalized.length > 0 ? normalized : undefined;\n}\n\nexport function mediaSessionSetMetadata(metadata: MediaSessionMetadata) {\n if (\n !mediaSessionAvailable() ||\n typeof MediaMetadata == \"undefined\"\n ) {\n return;\n }\n navigator.mediaSession.metadata = new MediaMetadata({\n title: metadata.title,\n album: metadata.album,\n artist: metadata.artist,\n artwork: normalizeArtwork(metadata.artwork),\n });\n}\n\nexport function mediaSessionPlay() {\n if (!mediaSessionAvailable()) return;\n navigator.mediaSession.playbackState = \"playing\";\n}\n\nexport function mediaSessionPause() {\n if (!mediaSessionAvailable()) return;\n navigator.mediaSession.playbackState = \"paused\";\n}\n\n/**\n * Reports duration, position and the real playback rate to the lock screen.\n * `setPositionState` throws on values it does not accept (no duration yet,\n * position past the end), so those calls are skipped or clamped.\n */\nexport function mediaSessionUpdateDurationAndPosition(\n duration: number | undefined,\n currentTime: number | undefined,\n playbackRate = 1,\n) {\n if (!mediaSessionAvailable()) return;\n if (duration == null || !Number.isFinite(duration) || duration <= 0) {\n return;\n }\n if (currentTime != null && isNaN(currentTime)) {\n return;\n }\n const position = Math.min(Math.max(currentTime ?? 0, 0), duration);\n const rate =\n Number.isFinite(playbackRate) && playbackRate > 0 ? playbackRate : 1;\n try {\n navigator.mediaSession.setPositionState({\n playbackRate: rate,\n duration,\n position,\n });\n } catch (e) {\n // Older browsers reject some combinations; the lock screen just keeps the\n // previous state.\n }\n}\n\nconst MEDIA_SESSION_ACTIONS: MediaSessionAction[] = [\n \"play\",\n \"pause\",\n \"stop\",\n \"seekbackward\",\n \"seekforward\",\n \"seekto\",\n \"previoustrack\",\n \"nexttrack\",\n];\n\nexport function startMediaSessionCoordinator(args: {\n title: string;\n album?: string;\n artist?: string;\n artwork?: MediaSessionMetadata[\"artwork\"];\n\n action: (details: MediaSessionActionDetails) => void;\n}) {\n if (!mediaSessionAvailable()) return;\n\n mediaSessionSetMetadata({\n title: args.title,\n album: args.album,\n artist: args.artist,\n artwork: args.artwork,\n });\n\n for (const action of MEDIA_SESSION_ACTIONS) {\n try {\n navigator.mediaSession.setActionHandler(action, (details) => {\n args.action(details);\n });\n } catch (e) {\n // The browser does not support this action (e.g. nexttrack).\n }\n }\n}\n\nexport function stopMediaSessionCoordinator() {\n if (!mediaSessionAvailable()) return;\n navigator.mediaSession.metadata = null;\n for (const action of MEDIA_SESSION_ACTIONS) {\n try {\n navigator.mediaSession.setActionHandler(action, null);\n } catch (e) {\n // Unsupported action; nothing to clear.\n }\n }\n}\n","import Hls from \"hls.js\";\nimport { Pause, Play, SkipBack, SkipForward } from \"lucide-react\";\nimport {\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n type CSSProperties,\n} from \"react\";\nimport { cn } from \"../../lib/utils\";\nimport { Button } from \"../../ui/button\";\nimport LoadingIndicator from \"../LoadingIndicator\";\nimport {\n createHlsSource,\n playerErrorFromMediaError,\n prefersNativeHls,\n type HlsSource,\n type PlayerError,\n} from \"./hls-engine\";\nimport {\n PREVIOUS_TRACK_RESTART_SECONDS,\n SEEK_STEP_SECONDS,\n mediaSessionPause,\n mediaSessionPlay,\n mediaSessionSetMetadata,\n mediaSessionUpdateDurationAndPosition,\n startMediaSessionCoordinator,\n stopMediaSessionCoordinator,\n} from \"./media.session.coordinator\";\n\nimport \"./audio-player.css\";\nimport { useAudioTexts, formatTime } from \"./texts\";\nimport { playerStorage, SPEED_KEY, SPEEDS } from \"./storage\";\n\nexport type ChapterWithPublicUrl = {\n id: string;\n multimediaId?: string;\n name: string;\n description?: string;\n publicUrl: string;\n downloadableUrl?: string;\n duration?: number;\n};\n\n/** What the player could not play; `status` is the HTTP status when known. */\nexport type AudioPlayerError = PlayerError;\n\nexport type AudioPlayerMethods = {\n selectChapter: (chapter: ChapterWithPublicUrl) => void;\n /** Loads the current chapter again after an error, keeping the position. */\n retry: () => void;\n /** The error currently shown, if any. */\n getError: () => AudioPlayerError | null;\n};\n\ntype AudioPlayerProps = {\n locale?: string;\n chapters: ChapterWithPublicUrl[];\n styles: CSSProperties;\n updateCurrentTime?: (currentTime: number) => void;\n\n title?: string;\n imageURL?: string;\n /** Hide the repeated visual heading when the desktop details show the cover beside it. */\n coverShownBeside?: boolean;\n /** Book author, used as the lock-screen artist. */\n author?: string;\n\n setCurrentTimeHandler?: (seekTo: (second: number) => void) => void;\n uniqueProductID: string;\n\n onChapterChange?: (chapter: ChapterWithPublicUrl) => void;\n /** A fatal playback error the player could not recover from. */\n onError?: (error: AudioPlayerError) => void;\n /** The signed URL returned 401/403; the owner should refetch the chapters. */\n onExpiredUrl?: () => void;\n /** The last chapter ended. */\n onFinished?: () => void;\n};\n\nconst AudioPlayer = forwardRef<AudioPlayerMethods, AudioPlayerProps>(\n (\n {\n chapters,\n locale,\n styles,\n updateCurrentTime,\n setCurrentTimeHandler,\n title,\n imageURL,\n coverShownBeside,\n author,\n uniqueProductID,\n onChapterChange,\n onError,\n onExpiredUrl,\n onFinished,\n },\n ref,\n ) => {\n const t = useAudioTexts(locale);\n const [speed, setSpeed] = useState(1);\n const speedRef = useRef(1);\n const [chapterID, setChapterID] = useState<string>();\n const [sleepMode, setSleepMode] = useState(\"off\");\n const [sleepRemaining, setSleepRemaining] = useState(0);\n const sleepRef = useRef<{ mode: string; deadline: number }>({\n mode: \"off\",\n deadline: 0,\n });\n\n function cancelSleep() {\n sleepRef.current = { mode: \"off\", deadline: 0 };\n setSleepMode(\"off\");\n setSleepRemaining(0);\n }\n function changeSleep(mode: string) {\n const seconds = Number(mode) * 60;\n sleepRef.current = {\n mode,\n deadline: Number.isFinite(seconds) ? Date.now() + seconds * 1000 : 0,\n };\n setSleepMode(mode);\n setSleepRemaining(Number.isFinite(seconds) ? seconds : 0);\n }\n function changeSpeed(rate: number) {\n if (!SPEEDS.includes(rate)) return;\n setSpeed(rate);\n speedRef.current = rate;\n playerStorage.set(SPEED_KEY, String(rate));\n if (videoRef.current) videoRef.current.playbackRate = rate;\n updatePlayerDetails();\n }\n useEffect(() => {\n const saved = Number(playerStorage.get(SPEED_KEY));\n if (SPEEDS.includes(saved)) changeSpeed(saved);\n const timer = setInterval(() => {\n const { mode, deadline } = sleepRef.current;\n if (mode === \"off\" || mode === \"chapter\") return;\n const remaining = Math.max(\n 0,\n Math.ceil((deadline - Date.now()) / 1000),\n );\n setSleepRemaining(remaining);\n if (remaining === 0) {\n playWhenReadyRef.current = false;\n pause();\n cancelSleep();\n }\n }, 1000);\n return () => clearInterval(timer);\n }, []);\n\n enum PlayState {\n Playing,\n Paused,\n }\n\n const [playState, setPlayState] = useState<PlayState>(PlayState.Paused);\n const [currentTime, setCurrentTime] = useState<number | undefined>(\n undefined,\n );\n const [duration, setDuration] = useState<number | undefined>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n const [playerError, setPlayerError] = useState<AudioPlayerError | null>(\n null,\n );\n\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const hlsRef = useRef<HlsSource | null>(null);\n const timerRef = useRef<ReturnType<typeof setInterval> | undefined>(\n undefined,\n );\n\n const audioPlayerContainerRef = useRef<HTMLDivElement>(null!);\n\n const currentChapterRef = useRef<ChapterWithPublicUrl | null>(null);\n const playerErrorRef = useRef<AudioPlayerError | null>(null);\n\n /** Set by a user action; the next `loadeddata` starts playback once. */\n const playWhenReadyRef = useRef(false);\n /** Position restored for the chapter that is loading, once. */\n const resumedRef = useRef(false);\n /** Position to restore instead of the remembered one (URL refresh, retry). */\n const pendingSeekRef = useRef<number | null>(null);\n /** Chapter URL that already asked the owner for a fresh signed URL. */\n const expiredUrlRef = useRef<string | null>(null);\n const chaptersRef = useRef(chapters);\n const chaptersSignatureRef = useRef<string | null>(null);\n\n // The owner passes new callbacks on every render; the player must keep the\n // current ones without restarting playback.\n const callbacksRef = useRef({\n onChapterChange,\n onError,\n onExpiredUrl,\n onFinished,\n updateCurrentTime,\n title,\n imageURL,\n author,\n });\n callbacksRef.current = {\n onChapterChange,\n onError,\n onExpiredUrl,\n onFinished,\n updateCurrentTime,\n title,\n imageURL,\n author,\n };\n\n function saveLastPlayedTime(timeInSeconds: number) {\n if (\n !resumedRef.current ||\n !Number.isFinite(timeInSeconds) ||\n timeInSeconds < 0\n ) {\n return;\n }\n playerStorage.set(\n `__player__${uniqueProductID}_${currentChapterRef.current?.id}`,\n `${Math.floor(timeInSeconds)}`,\n );\n }\n\n function getLastPlayedTime(): number | undefined {\n const time = playerStorage.get(\n `__player__${uniqueProductID}_${currentChapterRef.current?.id}`,\n );\n\n if (time == null) {\n return undefined;\n }\n try {\n const result = parseInt(time);\n\n if (isNaN(result) || result < 0) {\n return undefined;\n }\n\n return result;\n } catch (e) {\n return undefined;\n }\n }\n\n function getLastSelectedChapterID(): string | undefined {\n const lastSelectedChapterID = playerStorage.get(\n `__player__${uniqueProductID}_last_chapter`,\n );\n if (lastSelectedChapterID == null) {\n return undefined;\n }\n return lastSelectedChapterID;\n }\n\n function setLastSelectedChapterID(chapterID: string) {\n playerStorage.set(`__player__${uniqueProductID}_last_chapter`, chapterID);\n }\n\n function deleteMemoryChapter(chapterID: string) {\n playerStorage.remove(`__player__${uniqueProductID}_${chapterID}`);\n }\n\n function syncMediaSessionMetadata(chapter: ChapterWithPublicUrl | null) {\n mediaSessionSetMetadata({\n title: chapter?.name ?? callbacksRef.current.title ?? \"\",\n album: callbacksRef.current.title,\n artist: callbacksRef.current.author,\n artwork: callbacksRef.current.imageURL,\n });\n }\n\n function reportError(error: AudioPlayerError) {\n playerErrorRef.current = error;\n setPlayerError(error);\n setIsLoading(false);\n callbacksRef.current.onError?.(error);\n }\n\n function clearError() {\n playerErrorRef.current = null;\n setPlayerError(null);\n }\n\n function attemptPlay() {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n const result = video.play() as Promise<void> | undefined;\n if (result != null && typeof result.catch == \"function\") {\n result.catch(() => {\n // The browser blocked playback; the user presses play.\n });\n }\n updatePlayerDetails();\n }\n\n function play() {\n attemptPlay();\n }\n\n function pause() {\n videoRef.current?.pause();\n updatePlayerDetails();\n }\n\n function togglePlayState() {\n if (playState === PlayState.Playing) {\n pause();\n return;\n }\n play();\n }\n\n function seekTo(toSecond: number) {\n const video = videoRef.current;\n if (video == null || !Number.isFinite(toSecond)) {\n return;\n }\n const knownDuration = Number.isFinite(video.duration)\n ? video.duration\n : 0;\n const target =\n knownDuration > 0\n ? Math.min(Math.max(toSecond, 0), knownDuration)\n : Math.max(toSecond, 0);\n setCurrentTime(target);\n video.currentTime = target;\n updatePlayerDetails();\n }\n\n function seekBy(seconds: number) {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n const knownDuration = Number.isFinite(video.duration)\n ? video.duration\n : undefined;\n let target = Math.max(video.currentTime + seconds, 0);\n if (knownDuration != null && target > knownDuration) {\n target = knownDuration;\n }\n seekTo(target);\n }\n\n function loadSource(src: string) {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n clearError();\n setIsLoading(true);\n\n if (prefersNativeHls(video)) {\n destroyHls();\n video.src = src;\n video.load();\n return;\n }\n\n if (Hls.isSupported()) {\n if (hlsRef.current == null) {\n hlsRef.current = createHlsSource({\n media: video,\n handlers: {\n onError: (error) => {\n reportError(error);\n },\n onExpiredUrl: () => {\n callbacksRef.current.onExpiredUrl?.();\n },\n },\n });\n }\n hlsRef.current.load(src);\n return;\n }\n\n // No Media Source and no native HLS: let the browser try the URL itself.\n destroyHls();\n video.src = src;\n video.load();\n }\n\n function destroyHls() {\n hlsRef.current?.destroy();\n hlsRef.current = null;\n }\n\n function playChapter(\n chapter: ChapterWithPublicUrl,\n options?: { play?: boolean },\n ) {\n const shouldPlay = options?.play === true;\n if (\n currentChapterRef.current &&\n videoRef.current &&\n !videoRef.current.ended\n ) {\n saveLastPlayedTime(videoRef.current.currentTime);\n }\n resumedRef.current = false;\n pendingSeekRef.current = null;\n playWhenReadyRef.current = shouldPlay;\n currentChapterRef.current = chapter;\n setChapterID(chapter.id);\n setCurrentTime(0);\n setDuration(chapter.duration);\n loadSource(chapter.publicUrl);\n syncMediaSessionMetadata(chapter);\n callbacksRef.current.onChapterChange?.(chapter);\n setLastSelectedChapterID(chapter.id);\n }\n\n function loadChapters(list: ChapterWithPublicUrl[]) {\n if (list.length === 0) {\n return;\n }\n\n const chapterID = getLastSelectedChapterID();\n const chapter =\n (chapterID != null\n ? list.find((candidate) => candidate.id === chapterID)\n : undefined) ?? list[0];\n\n // Mount and content changes never start playback on their own.\n playChapter(chapter, { play: false });\n }\n\n function playNextChapter() {\n const list = chaptersRef.current;\n const current = currentChapterRef.current;\n if (list == null || list.length === 0 || current == null) {\n return;\n }\n const currentChapterIndex = list.findIndex(\n (chapter) => chapter.id === current.id,\n );\n if (currentChapterIndex === -1) {\n return;\n }\n const nextChapterIndex = currentChapterIndex + 1;\n if (nextChapterIndex >= list.length) {\n finishPlayback(current);\n return;\n }\n playChapter(list[nextChapterIndex], { play: true });\n }\n\n function playPreviousChapter() {\n const list = chaptersRef.current;\n const current = currentChapterRef.current;\n if (current == null) {\n return;\n }\n const video = videoRef.current;\n if (video != null && video.currentTime > PREVIOUS_TRACK_RESTART_SECONDS) {\n seekTo(0);\n return;\n }\n const currentChapterIndex =\n list == null\n ? -1\n : list.findIndex((chapter) => chapter.id === current.id);\n if (currentChapterIndex > 0) {\n playChapter(list[currentChapterIndex - 1], { play: true });\n return;\n }\n seekTo(0);\n }\n\n function finishPlayback(chapter: ChapterWithPublicUrl) {\n // The chapter is done: no resume point, and the element stays at the end.\n deleteMemoryChapter(chapter.id);\n playWhenReadyRef.current = false;\n videoRef.current?.pause();\n setPlayState(PlayState.Paused);\n callbacksRef.current.onFinished?.();\n }\n\n function handleEnded() {\n const current = currentChapterRef.current;\n if (current == null) {\n return;\n }\n playerStorage.set(\n `__player__${uniqueProductID}_${current.id}_completed`,\n \"true\",\n );\n deleteMemoryChapter(current.id);\n if (sleepRef.current.mode === \"chapter\") {\n playWhenReadyRef.current = false;\n pause();\n cancelSleep();\n return;\n }\n playNextChapter();\n updatePlayerDetails();\n }\n\n function handleLoadedData() {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n setIsLoading(false);\n video.playbackRate = speedRef.current;\n expiredUrlRef.current = null;\n if (!resumedRef.current) {\n resumedRef.current = true;\n const pending = pendingSeekRef.current;\n pendingSeekRef.current = null;\n if (pending != null) {\n seekTo(pending);\n } else {\n const lastPlayedTime = getLastPlayedTime();\n if (lastPlayedTime != null) {\n seekTo(lastPlayedTime);\n }\n }\n }\n if (playWhenReadyRef.current) {\n playWhenReadyRef.current = false;\n attemptPlay();\n }\n }\n\n function handleMediaElementError() {\n const mediaError = videoRef.current?.error;\n const src = currentChapterRef.current?.publicUrl;\n // Safari plays HLS itself and reports an expired signed URL as a network\n // error (2) or an unsupported source (4). Ask for a fresh URL once per\n // URL; an error that repeats after that refresh is a real error.\n const refreshable = mediaError?.code === 2 || mediaError?.code === 4;\n if (\n refreshable &&\n hlsRef.current == null &&\n src != null &&\n expiredUrlRef.current !== src\n ) {\n expiredUrlRef.current = src;\n callbacksRef.current.onExpiredUrl?.();\n }\n reportError(playerErrorFromMediaError(mediaError));\n }\n\n function retry() {\n const chapter = currentChapterRef.current;\n const src = chapter?.publicUrl ?? hlsRef.current?.src;\n if (src == null) {\n return;\n }\n const video = videoRef.current;\n const position = video?.currentTime ?? 0;\n clearError();\n resumedRef.current = false;\n pendingSeekRef.current = position > 0 ? position : null;\n setCurrentTime(position);\n if (hlsRef.current != null) {\n hlsRef.current.retry();\n } else {\n loadSource(src);\n }\n }\n\n function handleMediaSessionAction(details: MediaSessionActionDetails) {\n switch (details.action) {\n case \"play\":\n play();\n break;\n case \"pause\":\n case \"stop\":\n pause();\n break;\n case \"seekbackward\":\n seekBy(-(details.seekOffset ?? SEEK_STEP_SECONDS));\n break;\n case \"seekforward\":\n seekBy(details.seekOffset ?? SEEK_STEP_SECONDS);\n break;\n case \"seekto\":\n // A seek to 0 is valid: only a missing time is ignored.\n if (details.seekTime != null) {\n seekTo(details.seekTime);\n }\n break;\n case \"previoustrack\":\n playPreviousChapter();\n break;\n case \"nexttrack\":\n playNextChapter();\n break;\n default:\n break;\n }\n }\n\n useImperativeHandle(ref, () => {\n return {\n selectChapter: (chapter: ChapterWithPublicUrl) => {\n playChapter(chapter, { play: true });\n },\n retry,\n getError: () => playerErrorRef.current,\n };\n });\n\n function updatePlayerDetails() {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n setPlayState(video.paused ? PlayState.Paused : PlayState.Playing);\n setDuration(video.duration);\n setCurrentTime(video.currentTime);\n if (!video.ended) {\n saveLastPlayedTime(video.currentTime);\n }\n mediaSessionUpdateDurationAndPosition(\n video.duration,\n video.currentTime,\n video.playbackRate,\n );\n if (\n video.networkState === video.NETWORK_LOADING &&\n video.readyState <= video.HAVE_FUTURE_DATA\n ) {\n setIsLoading(true);\n } else {\n setIsLoading(false);\n }\n callbacksRef.current.updateCurrentTime?.(video.currentTime);\n }\n\n // Lock-screen handlers are registered once; they read refs, so they always\n // see the current chapters and callbacks.\n useEffect(() => {\n startMediaSessionCoordinator({\n title: title ?? \"\",\n album: title,\n artist: author,\n artwork: imageURL,\n action: handleMediaSessionAction,\n });\n\n return () => {\n stopMediaSessionCoordinator();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // The book title, cover or author arrive after the details request.\n useEffect(() => {\n syncMediaSessionMetadata(currentChapterRef.current);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [title, author, imageURL]);\n\n useEffect(() => {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n video.addEventListener(\"loadeddata\", handleLoadedData);\n video.addEventListener(\"ended\", handleEnded);\n video.addEventListener(\"error\", handleMediaElementError);\n video.addEventListener(\"timeupdate\", updatePlayerDetails);\n video.addEventListener(\"play\", updatePlayerDetails);\n video.addEventListener(\"pause\", updatePlayerDetails);\n video.addEventListener(\"ratechange\", updatePlayerDetails);\n\n updatePlayerDetails();\n timerRef.current = setInterval(updatePlayerDetails, 500);\n\n return () => {\n video.removeEventListener(\"loadeddata\", handleLoadedData);\n video.removeEventListener(\"ended\", handleEnded);\n video.removeEventListener(\"error\", handleMediaElementError);\n video.removeEventListener(\"timeupdate\", updatePlayerDetails);\n video.removeEventListener(\"play\", updatePlayerDetails);\n video.removeEventListener(\"pause\", updatePlayerDetails);\n video.removeEventListener(\"ratechange\", updatePlayerDetails);\n if (timerRef.current != null) {\n clearInterval(timerRef.current);\n timerRef.current = undefined;\n }\n if (!video.ended) saveLastPlayedTime(video.currentTime);\n setCurrentTime(undefined);\n video.pause();\n destroyHls();\n video.removeAttribute(\"src\");\n video.load();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (setCurrentTimeHandler != null) {\n setCurrentTimeHandler(seekTo);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Compare by chapter ids and URLs: a new array with the same content must\n // not reload the stream or restart playback.\n const chaptersSignature = chapters\n .map((chapter) => `${chapter.id}|${chapter.publicUrl ?? \"\"}`)\n .join(\"\\n\");\n\n useEffect(() => {\n chaptersRef.current = chapters;\n const previousSignature = chaptersSignatureRef.current;\n if (previousSignature === chaptersSignature) {\n return;\n }\n chaptersSignatureRef.current = chaptersSignature;\n\n if (previousSignature == null) {\n loadChapters(chapters);\n return;\n }\n\n const current = currentChapterRef.current;\n if (current == null) {\n loadChapters(chapters);\n return;\n }\n const replacement = chapters.find((chapter) => chapter.id === current.id);\n if (replacement != null && replacement.publicUrl === current.publicUrl) {\n // Same stream, different array: keep playing.\n return;\n }\n if (replacement != null) {\n // A fresh signed URL for the chapter that is playing: keep the position\n // and whether it was playing.\n const video = videoRef.current;\n const position = video?.currentTime ?? 0;\n const wasPlaying = video != null && !video.paused;\n currentChapterRef.current = replacement;\n resumedRef.current = false;\n pendingSeekRef.current = position > 0 ? position : null;\n playWhenReadyRef.current = wasPlaying;\n loadSource(replacement.publicUrl);\n syncMediaSessionMetadata(replacement);\n callbacksRef.current.onChapterChange?.(replacement);\n setLastSelectedChapterID(replacement.id);\n return;\n }\n loadChapters(chapters);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [chaptersSignature]);\n\n useEffect(() => {\n switch (playState) {\n case PlayState.Playing:\n mediaSessionPlay();\n break;\n case PlayState.Paused:\n mediaSessionPause();\n break;\n }\n }, [playState]);\n\n const currentIndex = chapters.findIndex(\n (chapter) => chapter.id === chapterID,\n );\n const knownDuration =\n Number.isFinite(duration) && duration! > 0\n ? duration!\n : (chapters[currentIndex]?.duration ?? 0);\n const position = Math.min(\n Math.max(currentTime ?? 0, 0),\n knownDuration || Infinity,\n );\n const wholeBookKnown =\n chapters.length > 0 &&\n chapters.every(\n (chapter) => Number.isFinite(chapter.duration) && chapter.duration! > 0,\n );\n const remaining =\n Math.max(\n 0,\n knownDuration -\n position +\n (wholeBookKnown\n ? chapters\n .slice(currentIndex + 1)\n .reduce((sum, chapter) => sum + chapter.duration!, 0)\n : 0),\n ) / speed;\n const minutesLeft = Math.ceil(remaining / 60);\n const leftText = `${Math.floor(minutesLeft / 60) > 0 ? `${Math.floor(minutesLeft / 60)} h ` : \"\"}${minutesLeft % 60} min`;\n\n return (\n <div\n id=\"audio-player-container\"\n className=\"bitsnap-audio-player flex min-w-0 flex-col gap-3 text-neutral-900 dark:text-neutral-100\"\n style={\n {\n ...styles,\n \"--seek-before-width\": `${knownDuration > 0 ? (position / knownDuration) * 100 : 0}%`,\n } as CSSProperties\n }\n ref={audioPlayerContainerRef}\n data-player-error={playerError?.kind}\n >\n <video\n ref={videoRef}\n className=\"hidden\"\n poster={imageURL}\n title={title}\n />\n <div className={cn(\"flex min-w-0 items-center gap-3\", coverShownBeside && \"lg:hidden\")}>\n {imageURL && (\n <img\n src={imageURL}\n alt=\"\"\n className=\"h-16 w-16 shrink-0 rounded object-contain\"\n />\n )}\n <div className=\"min-w-0 break-words\">\n <p className=\"font-semibold\">\n {chapters[currentIndex]?.name ?? title}\n </p>\n {author && (\n <p className=\"text-sm text-neutral-600 dark:text-neutral-300\">\n {author}\n </p>\n )}\n </div>\n </div>\n {playerError && (\n <div\n role=\"alert\"\n className=\"rounded-lg bg-red-50 p-3 text-red-800 dark:bg-red-950 dark:text-red-200\"\n >\n <p>{t.error}</p>\n <Button variant=\"outline\" onClick={retry}>\n {t.retry}\n </Button>\n </div>\n )}\n <input\n type=\"range\"\n min=\"0\"\n max={knownDuration || 100}\n value={position}\n disabled={!knownDuration}\n aria-label={t.progress}\n aria-valuetext={`${formatTime(position)} ${t.of} ${formatTime(knownDuration)}`}\n onChange={(event) => seekTo(Number(event.target.value))}\n />\n <section className=\"flex w-full justify-between text-sm tabular-nums\">\n <span id=\"current-time\">{formatTime(position)}</span>\n <span id=\"duration\">{formatTime(knownDuration)}</span>\n </section>\n {knownDuration > 0 && (\n <p className=\"text-sm text-neutral-600 dark:text-neutral-300\">\n {t.left === \"left\"\n ? `${leftText} ${t.left}`\n : `${t.left} ${leftText}`}{\" \"}\n · {wholeBookKnown ? t.book : t.chapter} ({speed}×)\n </p>\n )}\n <div className=\"flex flex-wrap items-center justify-center gap-2\">\n <Button\n variant=\"outline\"\n onClick={playPreviousChapter}\n disabled={currentIndex < 0}\n aria-label={t.previous}\n >\n <SkipBack className=\"h-5 w-5\" />\n </Button>\n <Button\n variant=\"outline\"\n onClick={() => seekBy(-SEEK_STEP_SECONDS)}\n aria-label={t.rewind}\n >\n −{SEEK_STEP_SECONDS}\n </Button>\n <Button\n variant=\"outline\"\n onClick={togglePlayState}\n aria-label={playState === PlayState.Paused ? t.play : t.pause}\n >\n {playState === PlayState.Paused ? (\n <Play className=\"h-5 w-5\" />\n ) : (\n <Pause className=\"h-5 w-5\" />\n )}\n </Button>\n <Button\n variant=\"outline\"\n onClick={() => seekBy(SEEK_STEP_SECONDS)}\n aria-label={t.forward}\n >\n +{SEEK_STEP_SECONDS}\n </Button>\n <Button\n variant=\"outline\"\n onClick={playNextChapter}\n disabled={currentIndex < 0 || currentIndex >= chapters.length - 1}\n aria-label={t.next}\n >\n <SkipForward className=\"h-5 w-5\" />\n </Button>\n </div>\n <div className=\"flex flex-wrap gap-3 md:grid md:grid-cols-2\">\n <label className=\"flex flex-1 items-center gap-2 text-sm md:flex-col md:items-start md:whitespace-nowrap\">\n {t.speed}\n <select\n aria-label={t.speed}\n value={speed}\n onChange={(event) => changeSpeed(Number(event.target.value))}\n >\n {SPEEDS.map((rate) => (\n <option key={rate} value={rate}>\n {rate}×\n </option>\n ))}\n </select>\n </label>\n <label className=\"flex flex-1 items-center gap-2 text-sm md:flex-col md:items-start md:whitespace-nowrap\">\n {t.sleep}\n <select\n aria-label={t.sleep}\n value={sleepMode}\n onChange={(event) => changeSleep(event.target.value)}\n >\n <option value=\"off\">{t.off}</option>\n {[15, 30, 45, 60].map((minutes) => (\n <option key={minutes} value={minutes}>\n {minutes} min\n </option>\n ))}\n <option value=\"chapter\">{t.end}</option>\n </select>\n </label>\n </div>\n {sleepMode !== \"off\" && (\n <div className=\"flex items-center justify-between gap-2 text-sm\">\n <span role=\"timer\">\n {sleepMode === \"chapter\" ? t.end : formatTime(sleepRemaining)}\n </span>\n <Button variant=\"outline\" onClick={cancelSleep}>\n {t.cancel}\n </Button>\n </div>\n )}\n {isLoading && (\n <div role=\"status\" className=\"flex justify-center\">\n <LoadingIndicator />\n </div>\n )}\n </div>\n );\n },\n);\n\nexport default AudioPlayer;\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkWPOXLITYjs = require('./chunk-WPOXLITY.js');var _chunkGQJDFLSLjs = require('./chunk-GQJDFLSL.js');var t={projectID:void 0,loginURL:"/panel/login",theme:void 0,host:void 0,allowedReturnOrigins:[]},u=[];function w(e){t={...t,...e}}function s(){return t}function P(e){t.projectID=e}function v(e){t.theme=e}function C(e){t.loginURL=e}function R(e){t.host=e}function x(e){u=e,t={...t,allowedReturnOrigins:e}}function y(){return u}var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var f=_react.createContext.call(void 0, s()),b= exports.i =({children:e,analytics:n})=>{let o=s(),i=_chunkGQJDFLSLjs.n.call(void 0, o.projectID,n,"panel");return _jsxruntime.jsx.call(void 0, _chunkWPOXLITYjs.o,{children:_jsxruntime.jsx.call(void 0, f.Provider,{value:{...o},children:_jsxruntime.jsx.call(void 0, _chunkGQJDFLSLjs.l,{value:i,children:_jsxruntime.jsx.call(void 0, "div",{className:"bitsnap-react",children:e})})})})},L= exports.j =()=>_react.useContext.call(void 0, f);var l=(e,n)=>`bitsnap-panel-session:${encodeURIComponent(_nullishCoalesce(n, () => ("https://bitsnap.pl")))}:${encodeURIComponent(e)}`,a=(e,n)=>`bitsnap-panel-email:${encodeURIComponent(_nullishCoalesce(n, () => ("https://bitsnap.pl")))}:${encodeURIComponent(e)}`;function $(e,n){return typeof window>"u"||!e?void 0:_nullishCoalesce(window.localStorage.getItem(l(e,n)), () => (void 0))}function G(e,n,o,i){typeof window>"u"||!e||(window.localStorage.setItem(l(e,i),n),window.localStorage.setItem(a(e,i),o))}function k(e,n){return typeof window>"u"||!e?null:window.localStorage.getItem(a(e,n))}function E(e,n){typeof window>"u"||!e||(window.localStorage.removeItem(l(e,n)),window.localStorage.removeItem(a(e,n)))}exports.a = w; exports.b = s; exports.c = P; exports.d = v; exports.e = C; exports.f = R; exports.g = x; exports.h = y; exports.i = b; exports.j = L; exports.k = $; exports.l = G; exports.m = k; exports.n = E;
2
- //# sourceMappingURL=chunk-SRQOFCMO.js.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkG4V2KWTVjs = require('./chunk-G4V2KWTV.js');var _chunkDP2NOHCIjs = require('./chunk-DP2NOHCI.js');var t={projectID:void 0,loginURL:"/panel/login",theme:void 0,host:void 0,allowedReturnOrigins:[]},u=[];function w(e){t={...t,...e}}function s(){return t}function P(e){t.projectID=e}function v(e){t.theme=e}function C(e){t.loginURL=e}function R(e){t.host=e}function x(e){u=e,t={...t,allowedReturnOrigins:e}}function y(){return u}var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var f=_react.createContext.call(void 0, s()),b= exports.i =({children:e,analytics:n})=>{let o=s(),i=_chunkDP2NOHCIjs.n.call(void 0, o.projectID,n,"panel");return _jsxruntime.jsx.call(void 0, _chunkG4V2KWTVjs.p,{children:_jsxruntime.jsx.call(void 0, f.Provider,{value:{...o},children:_jsxruntime.jsx.call(void 0, _chunkDP2NOHCIjs.l,{value:i,children:_jsxruntime.jsx.call(void 0, "div",{className:"bitsnap-react",children:e})})})})},L= exports.j =()=>_react.useContext.call(void 0, f);var l=(e,n)=>`bitsnap-panel-session:${encodeURIComponent(_nullishCoalesce(n, () => ("https://bitsnap.pl")))}:${encodeURIComponent(e)}`,a=(e,n)=>`bitsnap-panel-email:${encodeURIComponent(_nullishCoalesce(n, () => ("https://bitsnap.pl")))}:${encodeURIComponent(e)}`;function $(e,n){return typeof window>"u"||!e?void 0:_nullishCoalesce(window.localStorage.getItem(l(e,n)), () => (void 0))}function G(e,n,o,i){typeof window>"u"||!e||(window.localStorage.setItem(l(e,i),n),window.localStorage.setItem(a(e,i),o))}function k(e,n){return typeof window>"u"||!e?null:window.localStorage.getItem(a(e,n))}function E(e,n){typeof window>"u"||!e||(window.localStorage.removeItem(l(e,n)),window.localStorage.removeItem(a(e,n)))}exports.a = w; exports.b = s; exports.c = P; exports.d = v; exports.e = C; exports.f = R; exports.g = x; exports.h = y; exports.i = b; exports.j = L; exports.k = $; exports.l = G; exports.m = k; exports.n = E;
2
+ //# sourceMappingURL=chunk-VNV5BD4X.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-SRQOFCMO.js","../src/panel/config.ts","../src/panel/PanelProvider.tsx","../src/panel/session-storage.ts"],"names":["config","allowedReturnOrigins","setPanelConfig","newConfig","getPanelConfig","setProjectID","projectID","setTheme","theme","setLoginURL","loginURL","setHost","host","setAllowedReturnOrigins","origins","getAllowedReturnOrigins","PanelContext","createContext","PanelProvider","children","analytics","instrument","useInstrument","jsx","RpcProvider","InstrumentProvider","usePanelConfig","useContext","panelSessionKey"],"mappings":"AAAA,mOAAuC,sDAA+C,ICElFA,CAAAA,CAAsB,CACxB,SAAA,CAAW,KAAA,CAAA,CACX,QAAA,CAAU,cAAA,CACV,KAAA,CAAO,KAAA,CAAA,CACP,IAAA,CAAM,KAAA,CAAA,CACN,oBAAA,CAAsB,CAAC,CACzB,CAAA,CAEIC,CAAAA,CAAiC,CAAC,CAAA,CAU/B,SAASC,CAAAA,CAAeC,CAAAA,CAAuC,CACpEH,CAAAA,CAAS,CAAE,GAAGA,CAAAA,CAAQ,GAAGG,CAAU,CACrC,CAEO,SAASC,CAAAA,CAAAA,CAA8B,CAC5C,OAAOJ,CACT,CAEO,SAASK,CAAAA,CAAaC,CAAAA,CAAyB,CACpDN,CAAAA,CAAO,SAAA,CAAYM,CACrB,CAEO,SAASC,CAAAA,CAASC,CAAAA,CAA6B,CACpDR,CAAAA,CAAO,KAAA,CAAQQ,CACjB,CAEO,SAASC,CAAAA,CAAYC,CAAAA,CAAwB,CAClDV,CAAAA,CAAO,QAAA,CAAWU,CACpB,CAEO,SAASC,CAAAA,CAAQC,CAAAA,CAAoB,CAC1CZ,CAAAA,CAAO,IAAA,CAAOY,CAChB,CAEO,SAASC,CAAAA,CAAwBC,CAAAA,CAAyB,CAC/Db,CAAAA,CAAuBa,CAAAA,CACvBd,CAAAA,CAAS,CAAE,GAAGA,CAAAA,CAAQ,oBAAA,CAAsBc,CAAQ,CACtD,CAEO,SAASC,CAAAA,CAAAA,CAAoC,CAClD,OAAOd,CACT,CCnDA,8BAA0C,+CA2BhC,IAlBJe,CAAAA,CAAeC,kCAAAA,CAA2Bb,CAAe,CAAC,CAAA,CAEnDc,CAAAA,aASR,CAAC,CAAE,QAAA,CAAAC,CAAAA,CAAU,SAAA,CAAAC,CAAU,CAAA,CAAA,EAAM,CAChC,IAAMpB,CAAAA,CAASI,CAAAA,CAAe,CAAA,CACxBiB,CAAAA,CAAaC,gCAAAA,CAActB,CAAO,SAAA,CAAWoB,CAAAA,CAAW,OAAO,CAAA,CACrE,OACEG,6BAAAA,kBAACC,CAAA,CACC,QAAA,CAAAD,6BAAAA,CAACP,CAAa,QAAA,CAAb,CAAsB,KAAA,CAAO,CAAE,GAAGhB,CAAO,CAAA,CACxC,QAAA,CAAAuB,6BAAAA,kBAACE,CAAA,CAAmB,KAAA,CAAOJ,CAAAA,CACzB,QAAA,CAAAE,6BAAAA,KAAC,CAAA,CAAI,SAAA,CAAU,eAAA,CAAiB,QAAA,CAAAJ,CAAAA,CAAS,CAAA,CAC3C,CAAA,CACF,CAAA,CACF,CAEJ,CAAA,CAEaO,CAAAA,aAAiB,CAAA,CAAA,EAAMC,+BAAAA,CAAuB,CAAA,CClC3D,IAAMC,CAAAA,CAAkB,CAACtB,CAAAA,CAAmBM,CAAAA,CAAAA,EAC1C,CAAA,sBAAA,EAAyB,kBAAA,kBAAmBA,CAAAA,SAAQ,sBAAoB,CAAC,CAAA,CAAA,EAAI,kBAAA,CAAmBN,CAAS,CAAC,CAAA,CAAA","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-SRQOFCMO.js","sourcesContent":[null,"import type { GetThemeOutput } from \"./types\";\n\nlet config: PanelConfig = {\n projectID: undefined,\n loginURL: \"/panel/login\",\n theme: undefined,\n host: undefined,\n allowedReturnOrigins: [],\n};\n\nlet allowedReturnOrigins: string[] = [];\n\nexport interface PanelConfig {\n projectID?: string;\n loginURL?: string;\n theme?: GetThemeOutput;\n host?: string;\n allowedReturnOrigins: string[];\n}\n\nexport function setPanelConfig(newConfig: Partial<PanelConfig>): void {\n config = { ...config, ...newConfig };\n}\n\nexport function getPanelConfig(): PanelConfig {\n return config;\n}\n\nexport function setProjectID(projectID: string): void {\n config.projectID = projectID;\n}\n\nexport function setTheme(theme: GetThemeOutput): void {\n config.theme = theme;\n}\n\nexport function setLoginURL(loginURL: string): void {\n config.loginURL = loginURL;\n}\n\nexport function setHost(host: string): void {\n config.host = host;\n}\n\nexport function setAllowedReturnOrigins(origins: string[]): void {\n allowedReturnOrigins = origins;\n config = { ...config, allowedReturnOrigins: origins };\n}\n\nexport function getAllowedReturnOrigins(): string[] {\n return allowedReturnOrigins;\n}\n","import { createContext, useContext } from \"react\";\nimport {\n InstrumentProvider,\n useInstrument,\n type AnalyticsOption,\n} from \"../analytics/instrument\";\nimport { RpcProvider } from \"../rpc-provider\";\nimport { getPanelConfig, type PanelConfig } from \"./config\";\n\nconst PanelContext = createContext<PanelConfig>(getPanelConfig());\n\nexport const PanelProvider: React.FC<{\n children: React.ReactNode;\n /**\n * Usage statistics for your Bitsnap dashboard (panel logins, orders viewed,\n * downloads, course progress). On by default; `false` turns it off. An\n * object lets you forward every event: `{ onEvent }`. Nothing is stored on\n * the visitor's device.\n */\n analytics?: AnalyticsOption;\n}> = ({ children, analytics }) => {\n const config = getPanelConfig();\n const instrument = useInstrument(config.projectID, analytics, \"panel\");\n return (\n <RpcProvider>\n <PanelContext.Provider value={{ ...config }}>\n <InstrumentProvider value={instrument}>\n <div className=\"bitsnap-react\">{children}</div>\n </InstrumentProvider>\n </PanelContext.Provider>\n </RpcProvider>\n );\n};\n\nexport const usePanelConfig = () => useContext(PanelContext);\n","const panelSessionKey = (projectID: string, host?: string) =>\n `bitsnap-panel-session:${encodeURIComponent(host ?? \"https://bitsnap.pl\")}:${encodeURIComponent(projectID)}`;\n\nconst panelEmailKey = (projectID: string, host?: string) =>\n `bitsnap-panel-email:${encodeURIComponent(host ?? \"https://bitsnap.pl\")}:${encodeURIComponent(projectID)}`;\n\nexport function getPanelSession(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return undefined;\n const token = window.localStorage.getItem(panelSessionKey(projectID, host));\n return token ?? undefined;\n}\n\nexport function savePanelSession(projectID: string | undefined, token: string, email: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return;\n window.localStorage.setItem(panelSessionKey(projectID, host), token);\n window.localStorage.setItem(panelEmailKey(projectID, host), email);\n}\n\nexport function getPanelEmail(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return null;\n return window.localStorage.getItem(panelEmailKey(projectID, host));\n}\n\nexport function clearPanelSession(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return;\n window.localStorage.removeItem(panelSessionKey(projectID, host));\n window.localStorage.removeItem(panelEmailKey(projectID, host));\n}\n"]}
1
+ {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-VNV5BD4X.js","../src/panel/config.ts","../src/panel/PanelProvider.tsx","../src/panel/session-storage.ts"],"names":["config","allowedReturnOrigins","setPanelConfig","newConfig","getPanelConfig","setProjectID","projectID","setTheme","theme","setLoginURL","loginURL","setHost","host","setAllowedReturnOrigins","origins","getAllowedReturnOrigins","PanelContext","createContext","PanelProvider","children","analytics","instrument","useInstrument","jsx","RpcProvider","InstrumentProvider","usePanelConfig","useContext","panelSessionKey"],"mappings":"AAAA,mOAAkC,sDAA+C,ICE7EA,CAAAA,CAAsB,CACxB,SAAA,CAAW,KAAA,CAAA,CACX,QAAA,CAAU,cAAA,CACV,KAAA,CAAO,KAAA,CAAA,CACP,IAAA,CAAM,KAAA,CAAA,CACN,oBAAA,CAAsB,CAAC,CACzB,CAAA,CAEIC,CAAAA,CAAiC,CAAC,CAAA,CAU/B,SAASC,CAAAA,CAAeC,CAAAA,CAAuC,CACpEH,CAAAA,CAAS,CAAE,GAAGA,CAAAA,CAAQ,GAAGG,CAAU,CACrC,CAEO,SAASC,CAAAA,CAAAA,CAA8B,CAC5C,OAAOJ,CACT,CAEO,SAASK,CAAAA,CAAaC,CAAAA,CAAyB,CACpDN,CAAAA,CAAO,SAAA,CAAYM,CACrB,CAEO,SAASC,CAAAA,CAASC,CAAAA,CAA6B,CACpDR,CAAAA,CAAO,KAAA,CAAQQ,CACjB,CAEO,SAASC,CAAAA,CAAYC,CAAAA,CAAwB,CAClDV,CAAAA,CAAO,QAAA,CAAWU,CACpB,CAEO,SAASC,CAAAA,CAAQC,CAAAA,CAAoB,CAC1CZ,CAAAA,CAAO,IAAA,CAAOY,CAChB,CAEO,SAASC,CAAAA,CAAwBC,CAAAA,CAAyB,CAC/Db,CAAAA,CAAuBa,CAAAA,CACvBd,CAAAA,CAAS,CAAE,GAAGA,CAAAA,CAAQ,oBAAA,CAAsBc,CAAQ,CACtD,CAEO,SAASC,CAAAA,CAAAA,CAAoC,CAClD,OAAOd,CACT,CCnDA,8BAA0C,+CA2BhC,IAlBJe,CAAAA,CAAeC,kCAAAA,CAA2Bb,CAAe,CAAC,CAAA,CAEnDc,CAAAA,aASR,CAAC,CAAE,QAAA,CAAAC,CAAAA,CAAU,SAAA,CAAAC,CAAU,CAAA,CAAA,EAAM,CAChC,IAAMpB,CAAAA,CAASI,CAAAA,CAAe,CAAA,CACxBiB,CAAAA,CAAaC,gCAAAA,CAActB,CAAO,SAAA,CAAWoB,CAAAA,CAAW,OAAO,CAAA,CACrE,OACEG,6BAAAA,kBAACC,CAAA,CACC,QAAA,CAAAD,6BAAAA,CAACP,CAAa,QAAA,CAAb,CAAsB,KAAA,CAAO,CAAE,GAAGhB,CAAO,CAAA,CACxC,QAAA,CAAAuB,6BAAAA,kBAACE,CAAA,CAAmB,KAAA,CAAOJ,CAAAA,CACzB,QAAA,CAAAE,6BAAAA,KAAC,CAAA,CAAI,SAAA,CAAU,eAAA,CAAiB,QAAA,CAAAJ,CAAAA,CAAS,CAAA,CAC3C,CAAA,CACF,CAAA,CACF,CAEJ,CAAA,CAEaO,CAAAA,aAAiB,CAAA,CAAA,EAAMC,+BAAAA,CAAuB,CAAA,CClC3D,IAAMC,CAAAA,CAAkB,CAACtB,CAAAA,CAAmBM,CAAAA,CAAAA,EAC1C,CAAA,sBAAA,EAAyB,kBAAA,kBAAmBA,CAAAA,SAAQ,sBAAoB,CAAC,CAAA,CAAA,EAAI,kBAAA,CAAmBN,CAAS,CAAC,CAAA,CAAA","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-VNV5BD4X.js","sourcesContent":[null,"import type { GetThemeOutput } from \"./types\";\n\nlet config: PanelConfig = {\n projectID: undefined,\n loginURL: \"/panel/login\",\n theme: undefined,\n host: undefined,\n allowedReturnOrigins: [],\n};\n\nlet allowedReturnOrigins: string[] = [];\n\nexport interface PanelConfig {\n projectID?: string;\n loginURL?: string;\n theme?: GetThemeOutput;\n host?: string;\n allowedReturnOrigins: string[];\n}\n\nexport function setPanelConfig(newConfig: Partial<PanelConfig>): void {\n config = { ...config, ...newConfig };\n}\n\nexport function getPanelConfig(): PanelConfig {\n return config;\n}\n\nexport function setProjectID(projectID: string): void {\n config.projectID = projectID;\n}\n\nexport function setTheme(theme: GetThemeOutput): void {\n config.theme = theme;\n}\n\nexport function setLoginURL(loginURL: string): void {\n config.loginURL = loginURL;\n}\n\nexport function setHost(host: string): void {\n config.host = host;\n}\n\nexport function setAllowedReturnOrigins(origins: string[]): void {\n allowedReturnOrigins = origins;\n config = { ...config, allowedReturnOrigins: origins };\n}\n\nexport function getAllowedReturnOrigins(): string[] {\n return allowedReturnOrigins;\n}\n","import { createContext, useContext } from \"react\";\nimport {\n InstrumentProvider,\n useInstrument,\n type AnalyticsOption,\n} from \"../analytics/instrument\";\nimport { RpcProvider } from \"../rpc-provider\";\nimport { getPanelConfig, type PanelConfig } from \"./config\";\n\nconst PanelContext = createContext<PanelConfig>(getPanelConfig());\n\nexport const PanelProvider: React.FC<{\n children: React.ReactNode;\n /**\n * Usage statistics for your Bitsnap dashboard (panel logins, orders viewed,\n * downloads, course progress). On by default; `false` turns it off. An\n * object lets you forward every event: `{ onEvent }`. Nothing is stored on\n * the visitor's device.\n */\n analytics?: AnalyticsOption;\n}> = ({ children, analytics }) => {\n const config = getPanelConfig();\n const instrument = useInstrument(config.projectID, analytics, \"panel\");\n return (\n <RpcProvider>\n <PanelContext.Provider value={{ ...config }}>\n <InstrumentProvider value={instrument}>\n <div className=\"bitsnap-react\">{children}</div>\n </InstrumentProvider>\n </PanelContext.Provider>\n </RpcProvider>\n );\n};\n\nexport const usePanelConfig = () => useContext(PanelContext);\n","const panelSessionKey = (projectID: string, host?: string) =>\n `bitsnap-panel-session:${encodeURIComponent(host ?? \"https://bitsnap.pl\")}:${encodeURIComponent(projectID)}`;\n\nconst panelEmailKey = (projectID: string, host?: string) =>\n `bitsnap-panel-email:${encodeURIComponent(host ?? \"https://bitsnap.pl\")}:${encodeURIComponent(projectID)}`;\n\nexport function getPanelSession(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return undefined;\n const token = window.localStorage.getItem(panelSessionKey(projectID, host));\n return token ?? undefined;\n}\n\nexport function savePanelSession(projectID: string | undefined, token: string, email: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return;\n window.localStorage.setItem(panelSessionKey(projectID, host), token);\n window.localStorage.setItem(panelEmailKey(projectID, host), email);\n}\n\nexport function getPanelEmail(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return null;\n return window.localStorage.getItem(panelEmailKey(projectID, host));\n}\n\nexport function clearPanelSession(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return;\n window.localStorage.removeItem(panelSessionKey(projectID, host));\n window.localStorage.removeItem(panelEmailKey(projectID, host));\n}\n"]}