bitsnap-react 1.20.0 → 1.21.1

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 (124) hide show
  1. package/dist/BitsnapCart-3RSI3PIM.mjs +2 -0
  2. package/dist/BitsnapCart-4DKJ7OXL.js +2 -0
  3. package/dist/BitsnapCart-4DKJ7OXL.js.map +1 -0
  4. package/dist/{CartProvider-G7FQUPXL.mjs → CartProvider-TXRCAXOT.mjs} +2 -2
  5. package/dist/CartProvider-ZAGTSCHJ.js +2 -0
  6. package/dist/CartProvider-ZAGTSCHJ.js.map +1 -0
  7. package/dist/PanelModelFiles-EKQRLF46.js.map +1 -1
  8. package/dist/analytics.js +1 -1
  9. package/dist/analytics.js.map +1 -1
  10. package/dist/analytics.mjs +1 -1
  11. package/dist/catalog.js +1 -1
  12. package/dist/catalog.js.map +1 -1
  13. package/dist/catalog.mjs +1 -1
  14. package/dist/chat.d.mts +2 -2
  15. package/dist/chat.d.ts +2 -2
  16. package/dist/chat.js +1 -1
  17. package/dist/chat.js.map +1 -1
  18. package/dist/chat.mjs +1 -1
  19. package/dist/chat.mjs.map +1 -1
  20. package/dist/{chunk-A2ZDFN3J.mjs → chunk-2HINORSP.mjs} +2 -2
  21. package/dist/{chunk-EFN4OW2C.js → chunk-3TUL63IC.js} +2 -2
  22. package/dist/chunk-3TUL63IC.js.map +1 -0
  23. package/dist/chunk-56X4DBMQ.mjs +5 -0
  24. package/dist/chunk-56X4DBMQ.mjs.map +1 -0
  25. package/dist/{chunk-4Y233NII.js → chunk-6DEKVABT.js} +2 -2
  26. package/dist/chunk-6DEKVABT.js.map +1 -0
  27. package/dist/chunk-6Q3VGPSF.js.map +1 -1
  28. package/dist/{chunk-LHQEM3CU.mjs → chunk-7WTQGXPQ.mjs} +2 -2
  29. package/dist/{chunk-IRZJIPUF.js → chunk-EK3D44XW.js} +2 -2
  30. package/dist/chunk-EK3D44XW.js.map +1 -0
  31. package/dist/{chunk-BTERIY6N.mjs → chunk-EXC5Z5VM.mjs} +2 -2
  32. package/dist/{chunk-IXQCN7MR.mjs → chunk-FG7NLLJV.mjs} +2 -2
  33. package/dist/{chunk-RJPQMDIQ.js → chunk-FPCMLZFM.js} +2 -2
  34. package/dist/chunk-FPCMLZFM.js.map +1 -0
  35. package/dist/{chunk-2G46TAUX.mjs → chunk-GLKBCVNH.mjs} +2 -2
  36. package/dist/{chunk-2G46TAUX.mjs.map → chunk-GLKBCVNH.mjs.map} +1 -1
  37. package/dist/{chunk-AQYHQY2Y.js → chunk-J4GUVJP4.js} +2 -2
  38. package/dist/chunk-J4GUVJP4.js.map +1 -0
  39. package/dist/{chunk-TW25G7XX.mjs → chunk-J6WKSO33.mjs} +2 -2
  40. package/dist/{chunk-TW25G7XX.mjs.map → chunk-J6WKSO33.mjs.map} +1 -1
  41. package/dist/{chunk-GHBRR665.js → chunk-J6YI6FJN.js} +2 -2
  42. package/dist/chunk-J6YI6FJN.js.map +1 -0
  43. package/dist/chunk-JSDGZ4NY.js.map +1 -1
  44. package/dist/{chunk-HP3I6D2R.js → chunk-K2HIALKR.js} +2 -2
  45. package/dist/chunk-K2HIALKR.js.map +1 -0
  46. package/dist/chunk-KOYBZORL.js.map +1 -1
  47. package/dist/chunk-MDAFPGPA.js.map +1 -1
  48. package/dist/{chunk-YPA6MMGJ.js → chunk-MMQTRSI5.js} +2 -2
  49. package/dist/chunk-MMQTRSI5.js.map +1 -0
  50. package/dist/chunk-NW5PFIZB.js +2 -0
  51. package/dist/chunk-NW5PFIZB.js.map +1 -0
  52. package/dist/{chunk-C736F727.js → chunk-OCJ7YWFX.js} +2 -2
  53. package/dist/chunk-OCJ7YWFX.js.map +1 -0
  54. package/dist/chunk-Q337IQNA.js.map +1 -1
  55. package/dist/{chunk-URQBHNJK.mjs → chunk-QWQPAN4F.mjs} +2 -2
  56. package/dist/{chunk-KO7ZERN5.mjs → chunk-QXCL5CE6.mjs} +2 -2
  57. package/dist/chunk-TWZQ4CBY.js +5 -0
  58. package/dist/chunk-TWZQ4CBY.js.map +1 -0
  59. package/dist/{chunk-IXX6SUMB.mjs → chunk-VU2MX5HY.mjs} +2 -2
  60. package/dist/chunk-W3RGQYPD.js.map +1 -1
  61. package/dist/{chunk-LHNTSQYO.mjs → chunk-YV3UGLQ3.mjs} +2 -2
  62. package/dist/chunk-Z3YOJ6NZ.js.map +1 -1
  63. package/dist/consent.js.map +1 -1
  64. package/dist/course.js +1 -1
  65. package/dist/course.js.map +1 -1
  66. package/dist/course.mjs +1 -1
  67. package/dist/embed/analytics.js +1 -1
  68. package/dist/errors.js.map +1 -1
  69. package/dist/index.css +1 -1
  70. package/dist/index.css.map +1 -1
  71. package/dist/index.d.mts +2 -2
  72. package/dist/index.d.ts +2 -2
  73. package/dist/index.js +1 -1
  74. package/dist/index.js.map +1 -1
  75. package/dist/index.mjs +1 -1
  76. package/dist/index.mjs.map +1 -1
  77. package/dist/internal.js.map +1 -1
  78. package/dist/methods-27HZQY5L.js +2 -0
  79. package/dist/methods-27HZQY5L.js.map +1 -0
  80. package/dist/methods-27JU6IH7.mjs +2 -0
  81. package/dist/model-files-client-P4PORZJ6.js.map +1 -1
  82. package/dist/models.js.map +1 -1
  83. package/dist/returns.js +1 -1
  84. package/dist/returns.js.map +1 -1
  85. package/dist/returns.mjs +1 -1
  86. package/dist/viewer3d.js.map +1 -1
  87. package/dist/viewer3d.mjs +1 -1
  88. package/dist/{widgets-Bsojw94g.d.ts → widgets-BL6pCMdc.d.ts} +34 -2
  89. package/dist/{widgets-u7xMJbsY.d.mts → widgets-DmHlIbp8.d.mts} +34 -2
  90. package/package.json +1 -1
  91. package/dist/BitsnapCart-V4S4EXYV.js +0 -2
  92. package/dist/BitsnapCart-V4S4EXYV.js.map +0 -1
  93. package/dist/BitsnapCart-Z6JFYNH2.mjs +0 -2
  94. package/dist/CartProvider-5NP4WACK.js +0 -2
  95. package/dist/CartProvider-5NP4WACK.js.map +0 -1
  96. package/dist/chunk-4Y233NII.js.map +0 -1
  97. package/dist/chunk-5M3OUOMU.mjs +0 -5
  98. package/dist/chunk-5M3OUOMU.mjs.map +0 -1
  99. package/dist/chunk-AQYHQY2Y.js.map +0 -1
  100. package/dist/chunk-C736F727.js.map +0 -1
  101. package/dist/chunk-EFN4OW2C.js.map +0 -1
  102. package/dist/chunk-GHBRR665.js.map +0 -1
  103. package/dist/chunk-HP3I6D2R.js.map +0 -1
  104. package/dist/chunk-IRZJIPUF.js.map +0 -1
  105. package/dist/chunk-KDL35KEI.js +0 -2
  106. package/dist/chunk-KDL35KEI.js.map +0 -1
  107. package/dist/chunk-KZWCVKLU.js +0 -5
  108. package/dist/chunk-KZWCVKLU.js.map +0 -1
  109. package/dist/chunk-RJPQMDIQ.js.map +0 -1
  110. package/dist/chunk-YPA6MMGJ.js.map +0 -1
  111. package/dist/methods-33CWGKNA.mjs +0 -2
  112. package/dist/methods-4GB652MQ.js +0 -2
  113. package/dist/methods-4GB652MQ.js.map +0 -1
  114. /package/dist/{BitsnapCart-Z6JFYNH2.mjs.map → BitsnapCart-3RSI3PIM.mjs.map} +0 -0
  115. /package/dist/{CartProvider-G7FQUPXL.mjs.map → CartProvider-TXRCAXOT.mjs.map} +0 -0
  116. /package/dist/{chunk-A2ZDFN3J.mjs.map → chunk-2HINORSP.mjs.map} +0 -0
  117. /package/dist/{chunk-LHQEM3CU.mjs.map → chunk-7WTQGXPQ.mjs.map} +0 -0
  118. /package/dist/{chunk-BTERIY6N.mjs.map → chunk-EXC5Z5VM.mjs.map} +0 -0
  119. /package/dist/{chunk-IXQCN7MR.mjs.map → chunk-FG7NLLJV.mjs.map} +0 -0
  120. /package/dist/{chunk-URQBHNJK.mjs.map → chunk-QWQPAN4F.mjs.map} +0 -0
  121. /package/dist/{chunk-KO7ZERN5.mjs.map → chunk-QXCL5CE6.mjs.map} +0 -0
  122. /package/dist/{chunk-IXX6SUMB.mjs.map → chunk-VU2MX5HY.mjs.map} +0 -0
  123. /package/dist/{chunk-LHNTSQYO.mjs.map → chunk-YV3UGLQ3.mjs.map} +0 -0
  124. /package/dist/{methods-33CWGKNA.mjs.map → methods-27JU6IH7.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 _chunkK2HIALKRjs = require('./chunk-K2HIALKR.js');var _chunkNW5PFIZBjs = require('./chunk-NW5PFIZB.js');var _chunkMMQTRSI5js = require('./chunk-MMQTRSI5.js');var _chunkZ3YOJ6NZjs = require('./chunk-Z3YOJ6NZ.js');var _chunkMDAFPGPAjs = require('./chunk-MDAFPGPA.js');var _chunk3TUL63ICjs = require('./chunk-3TUL63IC.js');var _chunk6DEKVABTjs = require('./chunk-6DEKVABT.js');var _chunkEK3D44XWjs = require('./chunk-EK3D44XW.js');var _chunkQ337IQNAjs = require('./chunk-Q337IQNA.js');var _react = require('@formkit/auto-animate/react');var _react3 = require('react');var _jsxruntime = require('react/jsx-runtime');function Re({className:e,...t}){return _jsxruntime.jsx.call(void 0, "div",{"data-slot":"card",className:_chunk6DEKVABTjs.g.call(void 0, "bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function je({className:e,...t}){return _jsxruntime.jsx.call(void 0, "div",{"data-slot":"card-header",className:_chunk6DEKVABTjs.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 Fe({className:e,...t}){return _jsxruntime.jsx.call(void 0, "div",{"data-slot":"card-title",className:_chunk6DEKVABTjs.g.call(void 0, "leading-none font-semibold",e),...t})}function jn({className:e,...t}){return _jsxruntime.jsx.call(void 0, "div",{"data-slot":"card-description",className:_chunk6DEKVABTjs.g.call(void 0, "text-muted-foreground text-sm",e),...t})}function De({className:e,...t}){return _jsxruntime.jsx.call(void 0, "div",{"data-slot":"card-content",className:_chunk6DEKVABTjs.g.call(void 0, "px-6",e),...t})}var _lucidereact = require('lucide-react');var ga="text-muted-foreground text-xs leading-5",ya="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",ha=new Set(["invalidEmail","emailNotFound","deliveryUnavailable"]),ur="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 Fn({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, ),f=_nullishCoalesce(r, () => (`${l}-email`)),P=_nullishCoalesce(o, () => (`${l}-code`)),x=`${l}-notice`,I=`${l}-hint`,{notice:g}=e,u=_optionalChain([g, 'optionalAccess', _2 => _2.kind])==="error",m=e.busy==="send",p=e.busy==="verify",b=e.busy==="resend",S=_chunk6DEKVABTjs.g.call(void 0, "h-11 w-full",d),U=_optionalChain([g, 'optionalAccess', _3 => _3.kind])==="success",N=_jsxruntime.jsxs.call(void 0, "div",{id:x,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?g.text:null}),_jsxruntime.jsxs.call(void 0, "p",{role:"status",className:_chunk6DEKVABTjs.g.call(void 0, "flex items-start gap-1.5",U?"font-medium text-emerald-700 dark:text-emerald-400":"text-foreground"),children:[U&&_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:g!=null&&!u?g.text:null})]})]}),ce=u&&e.step==="email"&&(g.failure==null||ha.has(g.failure)),Se=_jsxruntime.jsx.call(void 0, "p",{className:"sr-only",role:"status","aria-live":"polite",children:e.announcement}),oe=_jsxruntime.jsxs.call(void 0, "div",{className:"grid gap-2",children:[_jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.d,{htmlFor:f,children:t.emailLabel}),_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.l,{id:f,ref:e.emailRef,name:"email",type:"email",autoComplete:"email",inputMode:"email",autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,autoFocus:!0,required:!0,className:_chunk6DEKVABTjs.g.call(void 0, "h-11 text-base disabled:opacity-100 disabled:text-foreground/70",ya),placeholder:_nullishCoalesce(a, () => (t.emailPlaceholder)),value:e.email,disabled:e.isBusy,"aria-invalid":ce?!0:void 0,"aria-describedby":x,onChange:Z=>e.setEmail(Z.target.value)})]});if(e.step==="email")return _jsxruntime.jsxs.call(void 0, "form",{noValidate:!0,className:_chunk6DEKVABTjs.g.call(void 0, "flex flex-col gap-4",i),onSubmit:Z=>{Z.preventDefault(),e.sendCode()},children:[Se,oe,N,_jsxruntime.jsxs.call(void 0, _chunkMMQTRSI5js.k,{type:"submit",disabled:e.isBusy,"aria-busy":m,className:S,children:[m&&_jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.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:ur,disabled:e.isBusy,onClick:e.haveCode,children:t.haveCode})]})]});let[te,fe]=t.codeSentTo.split("{email}"),E=e.dead!=null,ge=E?t.resendNew:e.secondsLeft>0?_chunkK2HIALKRjs.i.call(void 0, t.resendIn,{seconds:e.secondsLeft}):t.resend;return _jsxruntime.jsxs.call(void 0, "form",{noValidate:!0,className:_chunk6DEKVABTjs.g.call(void 0, "flex flex-col gap-4",i),onSubmit:Z=>{Z.preventDefault(),e.submitCode()},children:[Se,e.needsEmail?oe:_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:[te,_jsxruntime.jsx.call(void 0, "strong",{className:"font-semibold",children:e.email}),"\u2060",fe]}),_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk6DEKVABTjs.g.call(void 0, ur,"-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, _chunkK2HIALKRjs.d,{htmlFor:P,children:t.codeLabel}),_jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.k,{id:P,name:"code",inputRef:e.codeRef,value:e.code,onChange:e.setCode,onComplete:Z=>void e.submitCode(Z),disabled:e.isBusy||E,invalid:u&&!e.needsEmail,"aria-describedby":`${x} ${I}`}),_jsxruntime.jsxs.call(void 0, "p",{id:I,className:ga,children:[t.validity," ",t.spamHint]})]}),N,_jsxruntime.jsxs.call(void 0, _chunkMMQTRSI5js.k,{type:"submit",disabled:e.isBusy||E,"aria-busy":p,className:S,children:[p&&_jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.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:ur,disabled:e.isBusy,onClick:e.changeEmail,children:t.noCode})}):_jsxruntime.jsxs.call(void 0, _chunkMMQTRSI5js.k,{type:"button",variant:E?"default":"outline",disabled:e.isBusy||!E&&e.secondsLeft>0,"aria-busy":b,className:E?S:"h-11 w-full",onClick:()=>void e.resend(),children:[b&&_jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.e,{"aria-hidden":!0}),ge]})]})}function pr(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 16:return"captchaRequired";case 17:return"captchaInvalid";case 12:return"deliveryFailed";case 11:return"deliveryUnavailable";default:return"unknown"}}var ba={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 Hn(e=_chunkQ337IQNAjs.f.call(void 0, ),t){return{..._chunkK2HIALKRjs.h.call(void 0, e,t),..._chunkQ337IQNAjs.a.call(void 0, ba,e),...Pa(t,["title","description","codeTitle","codeDescription"])}}function Pa(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 va="return_url",mr="__return_url",ka="accessToken";function gt(e){let t=new URLSearchParams(e).get(va);return t?qn(t):null}function yt(e){typeof window>"u"||(e?window.sessionStorage.setItem(mr,e):window.sessionStorage.removeItem(mr))}function Ze(){if(typeof window>"u")return null;let e=window.sessionStorage.getItem(mr);return e?qn(e):null}function xa(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 qn(e){try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"||!xa(t.origin,_chunkMDAFPGPAjs.h.call(void 0, ))?null:t.toString()}catch (e2){return null}}function Qe(e,t){let n=new URL(e);return n.searchParams.set(ka,t),n.toString()}if(typeof window<"u"){let t=[window.location.origin,"https://bitsnap.pl","https://kursy.bitsnap.pl"];_chunkMDAFPGPAjs.h.call(void 0, ).length===0&&_chunkMDAFPGPAjs.g.call(void 0, Array.from(new Set(t)))}var Na=({texts:e,projectID:t,host:n,locale:a,logo:r})=>{let[o,i]=_react3.useState.call(void 0, !1),d=_react3.useRef.call(void 0, void 0),c=_react3.useRef.call(void 0, ""),l=_react3.useMemo.call(void 0, ()=>()=>new Promise(b=>{i(!0);let S=window.setTimeout(()=>{d.current=void 0,i(!1),b(!1)},5*60*1e3);d.current=U=>{window.clearTimeout(S),d.current=void 0,i(!1),c.current=_nullishCoalesce(U, () => ("")),b(U!==null)}}),[]),f=_chunkEK3D44XWjs.m.call(void 0, ),{mutateAsync:P}=_chunkMMQTRSI5js.g.call(void 0, _chunkMMQTRSI5js.e.publicApi.userPanelLogin),{mutateAsync:x}=_chunkMMQTRSI5js.g.call(void 0, _chunkMMQTRSI5js.e.publicApi.userPanelLoginWithCode),I=_react3.useMemo.call(void 0, ()=>({async send(b){try{let S=await P({email:b,turnstileToken:c.current});return c.current="",S.result.case==="success"?{ok:!0,retryIn:S.result.value.retryIn||void 0,challengeId:S.result.value.challengeId||void 0}:{ok:!1,kind:pr(S.result.case==="failure"?S.result.value:0)}}catch(S){return{ok:!1,kind:_chunkK2HIALKRjs.a.call(void 0, S),cause:S}}},async verify({email:b,code:S,challengeId:U}){try{let N=await x({code:parseInt(S,10),email:b,challengeId:U});return N.result.case==="accessToken"&&N.result.value?{ok:!0,value:{accessToken:N.result.value}}:{ok:!1,kind:pr(N.result.case==="failure"?N.result.value:0)}}catch(N){return{ok:!1,kind:_chunkK2HIALKRjs.a.call(void 0, N),cause:N}}}}),[P,x]),g=_chunkK2HIALKRjs.j.call(void 0, {adapter:I,texts:e,beforeSend:l,storageKey:_chunkK2HIALKRjs.f.call(void 0, "panel",t,n),onVerified:({accessToken:b},S)=>{f.track("panel_login",{}),_chunkMDAFPGPAjs.j.call(void 0, t,b,S,n);let U=typeof window<"u"?Ze():null;setTimeout(()=>{if(U){window.location.href=Qe(U,b);return}window.location.reload()},100)}}),u=g.step==="code",m=u&&!g.needsEmail?e.codeTitle:e.title,p=u&&!g.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, Re,{children:[_jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.c,{projectId:t,locale:a,className:"px-4 sm:px-6",...r}),_jsxruntime.jsxs.call(void 0, je,{className:"px-4 sm:px-6",children:[_jsxruntime.jsx.call(void 0, Fe,{role:"heading","aria-level":1,className:"text-2xl",children:m}),_jsxruntime.jsx.call(void 0, jn,{children:p})]}),_jsxruntime.jsxs.call(void 0, De,{className:"px-4 sm:px-6",children:[_jsxruntime.jsx.call(void 0, Fn,{login:g,texts:e,emailInputId:"email",codeInputId:"verify-code"}),o&&_jsxruntime.jsx.call(void 0, _chunkZ3YOJ6NZjs.a,{action:"panel_login",locale:a,onToken:b=>_optionalChain([d, 'access', _5 => _5.current, 'optionalCall', _6 => _6(b)]),onFailure:()=>_optionalChain([d, 'access', _7 => _7.current, 'optionalCall', _8 => _8(null)])})]})]})})},Ia=({analytics:e,texts:t,locale:n,showLogo:a,logoUrl:r,logoDarkUrl:o})=>{let{theme:i,allowedReturnOrigins:d,projectID:c,host:l}=_chunkNW5PFIZBjs.b.call(void 0, ),f=_chunkEK3D44XWjs.n.call(void 0, c,e,"panel"),P=_react3.useMemo.call(void 0, ()=>Hn(_nullishCoalesce(n, () => (_chunkQ337IQNAjs.f.call(void 0, ))),t),[n,t]),x={"--button-background-color":_nullishCoalesce(_optionalChain([i, 'optionalAccess', _9 => _9.colors, 'optionalAccess', _10 => _10.brand]), () => ("#FFFFFF")),"--button-background-color-dark":_nullishCoalesce(_optionalChain([i, 'optionalAccess', _11 => _11.colors, 'optionalAccess', _12 => _12.brandDark]), () => ("#000000")),"--button-text-color":_nullishCoalesce(_optionalChain([i, 'optionalAccess', _13 => _13.colors, 'optionalAccess', _14 => _14.brandDark]), () => ("#000000")),"--button-text-color-dark":_nullishCoalesce(_optionalChain([i, 'optionalAccess', _15 => _15.colors, 'optionalAccess', _16 => _16.brand]), () => ("#FFFFFF"))},[I]=_react.useAutoAnimate.call(void 0, {duration:300,easing:"ease-in-out",disrespectUserMotionPreference:!1});return _react3.useEffect.call(void 0, ()=>{typeof window>"u"||_chunkMDAFPGPAjs.i.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 g=gt(window.location.search);g&&yt(g);let u=_nullishCoalesce(g, () => (Ze()));if(!u)return;let m=_chunkMDAFPGPAjs.i.call(void 0, c,l);m&&(window.location.href=Qe(u,m))},[d,c,l]),_jsxruntime.jsx.call(void 0, _chunkEK3D44XWjs.l,{value:f,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:x,ref:I,children:_jsxruntime.jsx.call(void 0, Na,{texts:P,projectID:c,host:l,locale:n,logo:{showLogo:a,logoUrl:_nullishCoalesce(r, () => (_optionalChain([i, 'optionalAccess', _17 => _17.logoURL]))),logoDarkUrl:_nullishCoalesce(o, () => (_optionalChain([i, 'optionalAccess', _18 => _18.logoDarkURL])))}})})})})},Sa= exports.k =(e={})=>_jsxruntime.jsx.call(void 0, Ia,{...e});function Kn(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 f=i[l];f!=null&&d.set(l,JSON.stringify(f))});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 Gn(e,t){if(e!=null)return e;let n=_optionalChain([t, 'optionalAccess', _19 => _19.trim, 'call', _20 => _20()]);if(!(n==null||n===""))return{tokens:_chunkMMQTRSI5js.n.call(void 0, n)}}var Aa={pl:{returnsNavLabel:"Zwroty",openCourse:"Otw\xF3rz kurs",libraryNavLabel:"Biblioteka",messagesNavLabel:"Wiadomo\u015Bci",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",messagesNavLabel:"Messages",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 pe(e=_chunkQ337IQNAjs.f.call(void 0, )){return _chunkQ337IQNAjs.a.call(void 0, Aa,e)}function yr({}){let e=pe();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 Ma=e=>new Date(e*1e3).toLocaleDateString(_chunkQ337IQNAjs.f.call(void 0, ),{year:"numeric",month:"short",day:"numeric"}),Oa=(e,t)=>new Intl.NumberFormat(_chunkQ337IQNAjs.f.call(void 0, ),{style:"currency",currency:t.toUpperCase()}).format(e/100),Ua={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 _a({openOrderDetails:e,projectID:t,accessToken:n}){let a=pe(),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:f,refetch:P}=_chunkMMQTRSI5js.f.call(void 0, _chunkMMQTRSI5js.e.publicApi.getOrders,{projectId:t,accessToken:n,offset:o,limit:d}),x=_nullishCoalesce(_optionalChain([c, 'optionalAccess', _21 => _21.orders]), () => ([])),I=_nullishCoalesce(_optionalChain([c, 'optionalAccess', _22 => _22.totalCount]), () => (0)),g=Math.floor(o/d)+1,u=Math.ceil(I/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,b)=>_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, _chunkMMQTRSI5js.o,{className:"h-4 w-24"}),_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.o,{className:"h-3 w-32"})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"space-y-2 text-right",children:[_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.o,{className:"ml-auto h-4 w-16"}),_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.o,{className:"ml-auto h-3 w-12"})]})]}),_jsxruntime.jsx.call(void 0, "div",{className:"mt-3",children:_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.o,{className:"h-3 w-40"})})]},b))}):f?_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, _chunkMMQTRSI5js.k,{onClick:()=>void P(),className:"min-h-11 focus-visible:outline-2 focus-visible:outline-current",children:a.retry})]}):x.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:x.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:Oa(p.totalAmount,p.currency)}),_jsxruntime.jsx.call(void 0, "p",{className:`text-xs font-medium ${_nullishCoalesce(Ua[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?Ma(Number(p.createdAt.seconds)):"-"]})})]},p.id))}),g>=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:[g>1&&_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.k,{variant:"outline",className:"min-h-11",onClick:()=>m(o-d),children:a.previousPage}),Array.from(new Set([1,g-1,g,g+1,u])).filter(p=>p>0&&p<=u).sort((p,b)=>p-b).map(p=>_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.k,{variant:p===g?"secondary":"ghost",className:"min-h-11 min-w-11","aria-current":p===g?"page":void 0,onClick:()=>m((p-1)*d),children:p},p)),g<u&&_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.k,{variant:"outline",className:"min-h-11",onClick:()=>m(o+d),children:a.nextPage})]})]})]})}var Wn=_a;function hr({projectID:e}){let t=pe();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 Ha(e,t,n,a){typeof window>"u"||(t&&_chunkMDAFPGPAjs.l.call(void 0, n,a),window.location.href=e)}function qa({projectID:e,host:t,loginURL:n,screen:a,params:r,setParams:o,setActiveScreen:i}){let{status:d,exchangeError:c}=_chunkK2HIALKRjs.t.call(void 0, "PanelReturns"),l=_chunkK2HIALKRjs.r.call(void 0, ),f=d==="anonymous"&&(c==null||_chunkK2HIALKRjs.p.call(void 0, c));_react3.useEffect.call(void 0, ()=>{f&&Ha(n,c!=null,e,t)},[f,n,c,e,t]);let[P,x]=_react3.useState.call(void 0, "orders"),[I,g]=_react3.useState.call(void 0, {items:[],note:""}),[u,m]=_react3.useState.call(void 0, );if(d==="anonymous"&&!f)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(_chunkK2HIALKRjs.q.call(void 0, c))}),_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.k,{type:"button",onClick:()=>window.location.reload(),children:l("errorRetry")})]});if(d!=="authenticated")return _jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.C,{});let p=b=>{x(b),o({state:"returns",orderId:void 0,returnId:void 0}),i("returns")};if(a==="return-details"&&r.returnId)return _jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.K,{returnId:r.returnId,onBack:()=>p("myReturns")});if(P==="myReturns")return _jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.J,{onBack:()=>p("orders"),onSelectReturn:b=>{o({state:"return-details",returnId:b,orderId:void 0}),i("return-details")}});if(P==="result"&&u!=null)return _jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.I,{returnId:u,onContinue:()=>p("orders"),onOpenMyReturns:()=>p("myReturns")});if(r.orderId){let b=r.orderId;return P==="confirmation"?_jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.H,{orderId:b,items:I.items,note:I.note,onBack:()=>x("orders"),onSubmitted:S=>{m(S),g({items:[],note:""}),x("result"),o({orderId:void 0})}}):_jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.G,{orderId:b,initialItems:I.items.length>0?I.items:void 0,initialNote:I.note,onBack:()=>{g({items:[],note:""}),o({orderId:void 0})},onContinue:S=>{g(S),x("confirmation")}})}return _jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.F,{showLogout:!1,onSelectOrder:b=>{g({items:[],note:""}),x("orders"),o({orderId:b})},onOpenMyReturns:()=>p("myReturns")})}function Pr({accessToken:e,appearance:t,texts:n,...a}){return _jsxruntime.jsx.call(void 0, _chunkK2HIALKRjs.u,{projectID:a.projectID,host:a.host,appearance:t,texts:n,panelAccessToken:e,children:_jsxruntime.jsx.call(void 0, qa,{...a})})}var Ba={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",chat:"Czat",community:"Spo\u0142eczno\u015B\u0107",openMessages:"Otw\xF3rz wiadomo\u015Bci",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"},Ka={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",chat:"Chat",community:"Community",openMessages:"Open messages",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 Xe(){return _chunkQ337IQNAjs.f.call(void 0, ).toLowerCase().startsWith("en")?Ka:Ba}var Ga=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g,Va=e=>[...e.matchAll(Ga)].map(n=>({url:n[0],startIndex:n.index,endIndex:n.index+n[0].length-1})),Wa=(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},Jn=e=>{let t=Va(e);return _jsxruntime.jsx.call(void 0, "p",{dangerouslySetInnerHTML:{__html:Wa(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 Ja(){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 ke=Ja;var Xa=[401,403],Zn="networkError",Qn="mediaError";function ei(e,t){if(e==null||e.fatal!==!0)return{action:"ignore"};let n=_optionalChain([e, 'access', _23 => _23.response, 'optionalAccess', _24 => _24.code]),a=e.type===Zn?"network":e.type===Qn?"media":"unknown",r=n==null?{kind:a}:{kind:a,status:n};return n!=null&&Xa.includes(n)?{action:"expired",error:{kind:"network",status:n}}:e.type===Zn&&!t.network?{action:"restart-load"}:e.type===Qn&&!t.media?{action:"recover-media"}:{action:"fail",error:r}}function Xn(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=ei(d,{network:r,media:o});switch(c.action){case"expired":_optionalChain([e, 'access', _25 => _25.handlers, 'optionalAccess', _26 => _26.onExpiredUrl, 'optionalCall', _27 => _27()]),_optionalChain([e, 'access', _28 => _28.handlers, 'optionalAccess', _29 => _29.onError, 'optionalCall', _30 => _30(c.error)]);break;case"restart-load":r=!0,n.startLoad();break;case"recover-media":o=!0,n.recoverMediaError();break;case"fail":_optionalChain([e, 'access', _31 => _31.handlers, 'optionalAccess', _32 => _32.onError, 'optionalCall', _33 => _33(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 eo(e){try{return e.canPlayType("application/vnd.apple.mpegurl")!==""}catch (e5){return!1}}function to(e){switch(_optionalChain([e, 'optionalAccess', _34 => _34.code])){case 2:return{kind:"network"};case 3:case 4:return{kind:"media"};default:return{kind:"unknown"}}}var ti={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",avif:"image/avif",svg:"image/svg+xml"},kr="512x512";function et(){return typeof navigator<"u"&&typeof navigator.mediaSession<"u"}function ri(e){if(typeof e!="string"||e.length===0)return{src:e,sizes:kr};let t=e.split(/[?#]/)[0],n=t.includes(".")?t.slice(t.lastIndexOf(".")+1).toLowerCase():"",a=ti[n],r={src:e,sizes:kr};return a!=null&&(r.type=a),r}function ni(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(ri(a));continue}a!=null&&a.src.length>0&&n.push({src:a.src,sizes:_nullishCoalesce(a.sizes, () => (kr)),...a.type!=null?{type:a.type}:{}})}return n.length>0?n:void 0}function xr(e){!et()||typeof MediaMetadata>"u"||(navigator.mediaSession.metadata=new MediaMetadata({title:e.title,album:e.album,artist:e.artist,artwork:ni(e.artwork)}))}function ro(){et()&&(navigator.mediaSession.playbackState="playing")}function no(){et()&&(navigator.mediaSession.playbackState="paused")}function oo(e,t,n=1){if(!et()||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 ao=["play","pause","stop","seekbackward","seekforward","seekto","previoustrack","nexttrack"];function io(e){if(et()){xr({title:e.title,album:e.album,artist:e.artist,artwork:e.artwork});for(let t of ao)try{navigator.mediaSession.setActionHandler(t,n=>{e.action(n)})}catch (e7){}}}function so(){if(et()){navigator.mediaSession.metadata=null;for(let e of ao)try{navigator.mediaSession.setActionHandler(e,null)}catch (e8){}}}var ii={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"},si={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 Rt(e){let[t,n]=_react3.useState.call(void 0, "pl");return _react3.useEffect.call(void 0, ()=>{try{n(_chunkQ337IQNAjs.f.call(void 0, ))}catch (e9){}},[]),(_nullishCoalesce(e, () => (t))).toLowerCase().startsWith("en")?si:ii}function xe(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 Y={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){}}},wr="__player__speed",Dt=[.75,1,1.25,1.5,1.75,2];var yi=_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:f,onError:P,onExpiredUrl:x,onFinished:I},g)=>{let u=Rt(t),[m,p]=_react3.useState.call(void 0, 1),b=_react3.useRef.call(void 0, 1),[S,U]=_react3.useState.call(void 0, ),[N,ce]=_react3.useState.call(void 0, "off"),[Se,oe]=_react3.useState.call(void 0, 0),te=_react3.useRef.call(void 0, {mode:"off",deadline:0});function fe(){te.current={mode:"off",deadline:0},ce("off"),oe(0)}function E(s){let h=Number(s)*60;te.current={mode:s,deadline:Number.isFinite(h)?Date.now()+h*1e3:0},ce(s),oe(Number.isFinite(h)?h:0)}function ge(s){Dt.includes(s)&&(p(s),b.current=s,Y.set(wr,String(s)),z.current&&(z.current.playbackRate=s),K())}_react3.useEffect.call(void 0, ()=>{let s=Number(Y.get(wr));Dt.includes(s)&&ge(s);let h=setInterval(()=>{let{mode:k,deadline:D}=te.current;if(k==="off"||k==="chapter")return;let Pe=Math.max(0,Math.ceil((D-Date.now())/1e3));oe(Pe),Pe===0&&(ze.current=!1,xt(),fe())},1e3);return()=>clearInterval(h)},[]);let Z;(k=>(k[k.Playing=0]="Playing",k[k.Paused=1]="Paused"))(Z||={});let[_e,lt]=_react3.useState.call(void 0, 1),[Bt,Ee]=_react3.useState.call(void 0, void 0),[w,ye]=_react3.useState.call(void 0, void 0),[Be,ue]=_react3.useState.call(void 0, !1),[vt,Wr]=_react3.useState.call(void 0, null),z=_react3.useRef.call(void 0, null),he=_react3.useRef.call(void 0, null),kt=_react3.useRef.call(void 0, void 0),aa=_react3.useRef.call(void 0, null),re=_react3.useRef.call(void 0, null),Kt=_react3.useRef.call(void 0, null),ze=_react3.useRef.call(void 0, !1),Ke=_react3.useRef.call(void 0, !1),dt=_react3.useRef.call(void 0, null),Gt=_react3.useRef.call(void 0, null),Vt=_react3.useRef.call(void 0, e),Yr=_react3.useRef.call(void 0, null),ne=_react3.useRef.call(void 0, {onChapterChange:f,onError:P,onExpiredUrl:x,onFinished:I,updateCurrentTime:a,title:o,imageURL:i,author:c});ne.current={onChapterChange:f,onError:P,onExpiredUrl:x,onFinished:I,updateCurrentTime:a,title:o,imageURL:i,author:c};function Wt(s){!Ke.current||!Number.isFinite(s)||s<0||Y.set(`__player__${l}_${_optionalChain([re, 'access', _35 => _35.current, 'optionalAccess', _36 => _36.id])}`,`${Math.floor(s)}`)}function ia(){let s=Y.get(`__player__${l}_${_optionalChain([re, 'access', _37 => _37.current, 'optionalAccess', _38 => _38.id])}`);if(s!=null)try{let h=parseInt(s);return isNaN(h)||h<0?void 0:h}catch (e13){return}}function sa(){let s=Y.get(`__player__${l}_last_chapter`);if(s!=null)return s}function Jr(s){Y.set(`__player__${l}_last_chapter`,s)}function Zr(s){Y.remove(`__player__${l}_${s}`)}function Yt(s){xr({title:_nullishCoalesce(_nullishCoalesce(_optionalChain([s, 'optionalAccess', _39 => _39.name]), () => (ne.current.title)), () => ("")),album:ne.current.title,artist:ne.current.author,artwork:ne.current.imageURL})}function Qr(s){Kt.current=s,Wr(s),ue(!1),_optionalChain([ne, 'access', _40 => _40.current, 'access', _41 => _41.onError, 'optionalCall', _42 => _42(s)])}function Xr(){Kt.current=null,Wr(null)}function en(){let s=z.current;if(s==null)return;let h=s.play();h!=null&&typeof h.catch=="function"&&h.catch(()=>{}),K()}function tn(){en()}function xt(){_optionalChain([z, 'access', _43 => _43.current, 'optionalAccess', _44 => _44.pause, 'call', _45 => _45()]),K()}function la(){if(_e===0){xt();return}tn()}function Le(s){let h=z.current;if(h==null||!Number.isFinite(s))return;let k=Number.isFinite(h.duration)?h.duration:0,D=k>0?Math.min(Math.max(s,0),k):Math.max(s,0);Ee(D),h.currentTime=D,K()}function wt(s){let h=z.current;if(h==null)return;let k=Number.isFinite(h.duration)?h.duration:void 0,D=Math.max(h.currentTime+s,0);k!=null&&D>k&&(D=k),Le(D)}function Jt(s){let h=z.current;if(h!=null){if(Xr(),ue(!0),eo(h)){Zt(),h.src=s,h.load();return}if(_hlsjs2.default.isSupported()){he.current==null&&(he.current=Xn({media:h,handlers:{onError:k=>{Qr(k)},onExpiredUrl:()=>{_optionalChain([ne, 'access', _46 => _46.current, 'access', _47 => _47.onExpiredUrl, 'optionalCall', _48 => _48()])}}})),he.current.load(s);return}Zt(),h.src=s,h.load()}}function Zt(){_optionalChain([he, 'access', _49 => _49.current, 'optionalAccess', _50 => _50.destroy, 'call', _51 => _51()]),he.current=null}function Ct(s,h){let k=_optionalChain([h, 'optionalAccess', _52 => _52.play])===!0;re.current&&z.current&&!z.current.ended&&Wt(z.current.currentTime),Ke.current=!1,dt.current=null,ze.current=k,re.current=s,U(s.id),Ee(0),ye(s.duration),Jt(s.publicUrl),Yt(s),_optionalChain([ne, 'access', _53 => _53.current, 'access', _54 => _54.onChapterChange, 'optionalCall', _55 => _55(s)]),Jr(s.id)}function Qt(s){if(s.length===0)return;let h=sa(),k=_nullishCoalesce((h!=null?s.find(D=>D.id===h):void 0), () => (s[0]));Ct(k,{play:!1})}function Xt(){let s=Vt.current,h=re.current;if(s==null||s.length===0||h==null)return;let k=s.findIndex(Pe=>Pe.id===h.id);if(k===-1)return;let D=k+1;if(D>=s.length){da(h);return}Ct(s[D],{play:!0})}function rn(){let s=Vt.current,h=re.current;if(h==null)return;let k=z.current;if(k!=null&&k.currentTime>3){Le(0);return}let D=s==null?-1:s.findIndex(Pe=>Pe.id===h.id);if(D>0){Ct(s[D-1],{play:!0});return}Le(0)}function da(s){Zr(s.id),ze.current=!1,_optionalChain([z, 'access', _56 => _56.current, 'optionalAccess', _57 => _57.pause, 'call', _58 => _58()]),lt(1),_optionalChain([ne, 'access', _59 => _59.current, 'access', _60 => _60.onFinished, 'optionalCall', _61 => _61()])}function nn(){let s=re.current;if(s!=null){if(Y.set(`__player__${l}_${s.id}_completed`,"true"),Zr(s.id),te.current.mode==="chapter"){ze.current=!1,xt(),fe();return}Xt(),K()}}function on(){let s=z.current;if(s!=null){if(ue(!1),s.playbackRate=b.current,Gt.current=null,!Ke.current){Ke.current=!0;let h=dt.current;if(dt.current=null,h!=null)Le(h);else{let k=ia();k!=null&&Le(k)}}ze.current&&(ze.current=!1,en())}}function an(){let s=_optionalChain([z, 'access', _62 => _62.current, 'optionalAccess', _63 => _63.error]),h=_optionalChain([re, 'access', _64 => _64.current, 'optionalAccess', _65 => _65.publicUrl]);(_optionalChain([s, 'optionalAccess', _66 => _66.code])===2||_optionalChain([s, 'optionalAccess', _67 => _67.code])===4)&&he.current==null&&h!=null&&Gt.current!==h&&(Gt.current=h,_optionalChain([ne, 'access', _68 => _68.current, 'access', _69 => _69.onExpiredUrl, 'optionalCall', _70 => _70()])),Qr(to(s))}function sn(){let h=_nullishCoalesce(_optionalChain([re, 'access', _71 => _71.current, 'optionalAccess', _72 => _72.publicUrl]), () => (_optionalChain([he, 'access', _73 => _73.current, 'optionalAccess', _74 => _74.src])));if(h==null)return;let D=_nullishCoalesce(_optionalChain([z, 'access', _75 => _75.current, 'optionalAccess', _76 => _76.currentTime]), () => (0));Xr(),Ke.current=!1,dt.current=D>0?D:null,Ee(D),he.current!=null?he.current.retry():Jt(h)}function ca(s){switch(s.action){case"play":tn();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&&Le(s.seekTime);break;case"previoustrack":rn();break;case"nexttrack":Xt();break;default:break}}_react3.useImperativeHandle.call(void 0, g,()=>({selectChapter:s=>{Ct(s,{play:!0})},retry:sn,getError:()=>Kt.current}));function K(){let s=z.current;s!=null&&(lt(s.paused?1:0),ye(s.duration),Ee(s.currentTime),s.ended||Wt(s.currentTime),oo(s.duration,s.currentTime,s.playbackRate),s.networkState===s.NETWORK_LOADING&&s.readyState<=s.HAVE_FUTURE_DATA?ue(!0):ue(!1),_optionalChain([ne, 'access', _77 => _77.current, 'access', _78 => _78.updateCurrentTime, 'optionalCall', _79 => _79(s.currentTime)]))}_react3.useEffect.call(void 0, ()=>(io({title:_nullishCoalesce(o, () => ("")),album:o,artist:c,artwork:i,action:ca}),()=>{so()}),[]),_react3.useEffect.call(void 0, ()=>{Yt(re.current)},[o,c,i]),_react3.useEffect.call(void 0, ()=>{let s=z.current;if(s!=null)return s.addEventListener("loadeddata",on),s.addEventListener("ended",nn),s.addEventListener("error",an),s.addEventListener("timeupdate",K),s.addEventListener("play",K),s.addEventListener("pause",K),s.addEventListener("ratechange",K),K(),kt.current=setInterval(K,500),()=>{s.removeEventListener("loadeddata",on),s.removeEventListener("ended",nn),s.removeEventListener("error",an),s.removeEventListener("timeupdate",K),s.removeEventListener("play",K),s.removeEventListener("pause",K),s.removeEventListener("ratechange",K),kt.current!=null&&(clearInterval(kt.current),kt.current=void 0),s.ended||Wt(s.currentTime),Ee(void 0),s.pause(),Zt(),s.removeAttribute("src"),s.load()}},[]),_react3.useEffect.call(void 0, ()=>{_optionalChain([r, 'optionalCall', _80 => _80(Le)])},[]);let er=e.map(s=>`${s.id}|${_nullishCoalesce(s.publicUrl, () => (""))}`).join(`
4
+ `);_react3.useEffect.call(void 0, ()=>{Vt.current=e;let s=Yr.current;if(s===er)return;if(Yr.current=er,s==null){Qt(e);return}let h=re.current;if(h==null){Qt(e);return}let k=e.find(D=>D.id===h.id);if(!(k!=null&&k.publicUrl===h.publicUrl)){if(k!=null){let D=z.current,Pe=_nullishCoalesce(_optionalChain([D, 'optionalAccess', _81 => _81.currentTime]), () => (0)),pa=D!=null&&!D.paused;re.current=k,Ke.current=!1,dt.current=Pe>0?Pe:null,ze.current=pa,Jt(k.publicUrl),Yt(k),_optionalChain([ne, 'access', _82 => _82.current, 'access', _83 => _83.onChapterChange, 'optionalCall', _84 => _84(k)]),Jr(k.id);return}Qt(e)}},[er]),_react3.useEffect.call(void 0, ()=>{switch(_e){case 0:ro();break;case 1:no();break}},[_e]);let Ge=e.findIndex(s=>s.id===S),be=Number.isFinite(w)&&w>0?w:_nullishCoalesce(_optionalChain([e, 'access', _85 => _85[Ge], 'optionalAccess', _86 => _86.duration]), () => (0)),ct=Math.min(Math.max(_nullishCoalesce(Bt, () => (0)),0),be||1/0),ln=e.length>0&&e.every(s=>Number.isFinite(s.duration)&&s.duration>0),ua=Math.max(0,be-ct+(ln?e.slice(Ge+1).reduce((s,h)=>s+h.duration,0):0))/m,tr=Math.ceil(ua/60),dn=`${Math.floor(tr/60)>0?`${Math.floor(tr/60)} h `:""}${tr%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":`${be>0?ct/be*100:0}%`},ref:aa,"data-player-error":_optionalChain([vt, 'optionalAccess', _87 => _87.kind]),children:[_jsxruntime.jsx.call(void 0, "video",{ref:z,className:"hidden",poster:i,title:o}),_jsxruntime.jsxs.call(void 0, "div",{className:_chunk6DEKVABTjs.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', _88 => _88[Ge], 'optionalAccess', _89 => _89.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, _chunkMMQTRSI5js.k,{variant:"outline",onClick:sn,children:u.retry})]}),_jsxruntime.jsx.call(void 0, "input",{type:"range",min:"0",max:be||100,value:ct,disabled:!be,"aria-label":u.progress,"aria-valuetext":`${xe(ct)} ${u.of} ${xe(be)}`,onChange:s=>Le(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:xe(ct)}),_jsxruntime.jsx.call(void 0, "span",{id:"duration",children:xe(be)})]}),be>0&&_jsxruntime.jsxs.call(void 0, "p",{className:"text-sm text-neutral-600 dark:text-neutral-300",children:[u.left==="left"?`${dn} ${u.left}`:`${u.left} ${dn}`," ","\xB7 ",ln?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, _chunkMMQTRSI5js.k,{variant:"outline",onClick:rn,disabled:Ge<0,"aria-label":u.previous,children:_jsxruntime.jsx.call(void 0, _lucidereact.SkipBack,{className:"h-5 w-5"})}),_jsxruntime.jsxs.call(void 0, _chunkMMQTRSI5js.k,{variant:"outline",onClick:()=>wt(-10),"aria-label":u.rewind,children:["\u2212",10]}),_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.k,{variant:"outline",onClick:la,"aria-label":_e===1?u.play:u.pause,children:_e===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, _chunkMMQTRSI5js.k,{variant:"outline",onClick:()=>wt(10),"aria-label":u.forward,children:["+",10]}),_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.k,{variant:"outline",onClick:Xt,disabled:Ge<0||Ge>=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=>ge(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:N,onChange:s=>E(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})]})]})]}),N!=="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:N==="chapter"?u.end:xe(Se)}),_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.k,{variant:"outline",onClick:fe,children:u.cancel})]}),Be&&_jsxruntime.jsx.call(void 0, "div",{role:"status",className:"flex justify-center",children:_jsxruntime.jsx.call(void 0, ke,{})})]})}),lo=yi;function Cr({chapters:e,currentID:t,productID:n,onSelect:a,downloadable:r,onDownload:o,loading:i,locale:d}){let c=Rt(d),[l,f]=_react3.useState.call(void 0, null),[P,x]=_react3.useState.call(void 0, []);_react3.useEffect.call(void 0, ()=>{let u=`__player__${n}_`,m=Y.get(`${u}last_chapter`),p=Number(m&&Y.get(`${u}${m}`));f(m&&p>0&&Number.isFinite(p)?{id:m,time:p}:null),x((_nullishCoalesce(e, () => ([]))).filter(b=>Y.get(`${u}${b.id}_completed`)==="true"||Number(Y.get(`${u}${b.id}`))>0).map(b=>b.id))},[e,n,t]);let I=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _90 => _90.findIndex, 'call', _91 => _91(u=>u.id===_optionalChain([l, 'optionalAccess', _92 => _92.id]))]), () => (-1)),g=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _93 => _93.findIndex, 'call', _94 => _94(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', _95 => _95.length])?_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[l&&I>=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[I]),children:[c.resume,": ",c.chapterName," ",I+1,","," ",xe(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,b=m<g||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}):b?_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:xe(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 Ce(e,...t){console.warn(e,...t)}function Nr(e){console.error(e)}var Ni=({accessToken:e,product:t,styles:n,reveal:a})=>{let r=Xe(),o=t.productType,i=_chunkEK3D44XWjs.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, ),[f,P]=_react3.useState.call(void 0, !1),[x,I]=_react3.useState.call(void 0, null),{mutateAsync:g,isPending:u}=_chunkMMQTRSI5js.g.call(void 0, _chunkMMQTRSI5js.e.publicApi.userPanelGetFileDetails),m=_react3.useRef.call(void 0, void 0),[p,b]=_react3.useState.call(void 0, null),[S,U]=_react3.useState.call(void 0, null),[N,ce]=_react3.useState.call(void 0, !1),{mutateAsync:Se,isPending:oe}=_chunkMMQTRSI5js.g.call(void 0, _chunkMMQTRSI5js.e.publicApi.userPanelGetAudiobookDetails),{mutateAsync:te,isPending:fe}=_chunkMMQTRSI5js.g.call(void 0, _chunkMMQTRSI5js.e.publicApi.userPanelGetAudiobookDetailsDownloadURLs),[E,ge]=_react3.useState.call(void 0, null),[Z,_e]=_react3.useState.call(void 0, null);async function lt(){P(!1);try{let w=await g({accessId:t.accessId,accessToken:e});if(w.result.case==="success"){I(w.result.value.files);return}else P(!0),Ce("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),Ce("Kod b\u0142\u0119du: ",w.result.value)}catch(w){P(!0),Ce("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),Nr("B\u0142\u0105d podczas pobierania danych:"+w)}}async function Bt(){try{let w=await Se({accessId:t.accessId,accessToken:e});if(w.result.case==="audiobook"){b(w.result.value);return}else Ce("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),Ce("Kod b\u0142\u0119du: ",w.result.value)}catch(w){Ce("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),Nr("B\u0142\u0105d podczas pobierania danych:"+w)}}async function Ee(){try{let w=await te({accessId:t.accessId,accessToken:e,isBrowser:!0});if(w.result.case==="success"){U(w.result.value.audiobookDownloadDetails),ce(w.result.value.isAvailableToDownloadInMobileApp===!0);return}else Ce("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),Ce("Kod b\u0142\u0119du: ",w.result.value)}catch(w){Ce("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),Nr("B\u0142\u0105d podczas pobierania danych:"+w)}}return _react3.useEffect.call(void 0, ()=>{o===2&&lt(),o===1&&(Bt().then().catch(),Ee().then().catch())},[]),_react3.useEffect.call(void 0, ()=>{if(p!=null&&S!=null){let w=p.chapters;if(!w)return;let ye=w.map(Be=>{let ue=_optionalChain([S, 'optionalAccess', _96 => _96.find, 'call', _97 => _97(vt=>vt.chapterId===Be.id)]);if(ue!=null)return{...Be,publicUrl:ue.publicUrl,downloadableUrl:ue.downloadableUrl,duration:ue.duration}}).filter(Be=>Be!=null);ye!=null&&ye.length>0&&_e(ye)}},[p,S]),_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, _chunkMMQTRSI5js.k,{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, ke,{})}),f&&_jsxruntime.jsxs.call(void 0, "div",{role:"alert",children:[_jsxruntime.jsx.call(void 0, "p",{children:r.fileError}),_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.k,{className:"min-h-11",onClick:lt,children:r.retry})]}),_optionalChain([x, 'optionalAccess', _98 => _98.length])===0&&_jsxruntime.jsx.call(void 0, "p",{children:r.noFiles}),x&&_jsxruntime.jsx.call(void 0, "ul",{className:"flex flex-col gap-3",children:x.map((w,ye)=>_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:mo(w)||`${r.file} ${ye+1}`}),_jsxruntime.jsxs.call(void 0, "a",{target:"_blank",rel:"noopener noreferrer",href:w,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}: ${mo(w)||`${r.file} ${ye+1}`}`,children:[r.download,_jsxruntime.jsx.call(void 0, _lucidereact.Download,{className:"size-4","aria-hidden":"true"})]})]},w))})]}),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([E, 'optionalAccess', _99 => _99.name]), () => ("Odtwarzacz"))}),_optionalChain([E, 'optionalAccess', _100 => _100.description])&&_jsxruntime.jsx.call(void 0, "p",{className:"text-sm",children:_optionalChain([E, 'optionalAccess', _101 => _101.description])}),_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:oe?_jsxruntime.jsxs.call(void 0, "div",{className:"flex gap-2",children:[_jsxruntime.jsx.call(void 0, ke,{}),_jsxruntime.jsx.call(void 0, "p",{className:"text-xl font-semibold",children:"Trwa pobierania audiobooka..."})]}):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:Z!=null?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:_jsxruntime.jsx.call(void 0, lo,{ref:c,coverShownBeside:!0,chapters:Z,author:typeof _optionalChain([p, 'optionalAccess', _102 => _102.author])=="string"?p.author:void 0,onExpiredUrl:()=>{Ee()},title:_nullishCoalesce(_nullishCoalesce(_optionalChain([p, 'optionalAccess', _103 => _103.name]), () => (t.productName)), () => (void 0)),imageURL:_nullishCoalesce(_nullishCoalesce(_optionalChain([p, 'optionalAccess', _104 => _104.coverImage]), () => (t.productImageUrl)), () => (void 0)),styles:n,setCurrentTimeHandler:w=>{m.current=w},uniqueProductID:t.productId,onChapterChange:w=>{ge(w)}})}):_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:N?"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, Cr,{chapters:Z,currentID:_optionalChain([E, 'optionalAccess', _105 => _105.id]),productID:t.productId,loading:oe,downloadable:_optionalChain([p, 'optionalAccess', _106 => _106.isDownloadable])===!0,onDownload:d,onSelect:w=>_optionalChain([c, 'access', _107 => _107.current, 'optionalAccess', _108 => _108.selectChapter, 'call', _109 => _109(w)])})})]}),_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})})]})]})},fo=Ni;function mo(e){try{return decodeURIComponent(new URL(e,"https://bitsnap.pl").pathname.split("/").pop()||"")}catch (e14){return""}}var _connectquery = require('@connectrpc/connect-query');function go(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 ji=_react3.lazy.call(void 0, ()=>Promise.resolve().then(() => _interopRequireWildcard(require("./PanelModelFiles-EKQRLF46.js")))),Fi=({accessToken:e,projectID:t,loginURL:n,styles:a,activeScreen:r,params:o,setParams:i,openCourse:d,openMessages:c})=>{let{host:l}=_chunkNW5PFIZBjs.b.call(void 0, ),{data:f,isLoading:P,error:x,refetch:I}=_chunkMMQTRSI5js.f.call(void 0, _chunkMMQTRSI5js.e.publicApi.userPanelGetProducts,{accessToken:e}),g=go(e,t),u=Hi({products:P?{status:"loading"}:x!=null?{status:"error"}:_optionalChain([f, 'optionalAccess', _110 => _110.result, 'access', _111 => _111.case])==="success"?{status:"ok",count:f.result.value.products.length}:_optionalChain([f, 'optionalAccess', _112 => _112.result, 'access', _113 => _113.case])==="failure"?{status:"failure",unauthorized:f.result.value===9}:{status:"error"},modelFiles:g});if(_react3.useEffect.call(void 0, ()=>{u.kind==="signed-out"&&(_chunkMDAFPGPAjs.l.call(void 0, t,l),window.location.href=n)},[u.kind,t,l,n]),u.kind==="loading"||u.kind==="signed-out")return _jsxruntime.jsx.call(void 0, "div",{role:"status","aria-label":Xe().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},(S,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 m=f&&f.result.case==="success"?f.result.value.products:[],p=g.status==="ready"?g.models:[],b=p.length>0?_jsxruntime.jsx.call(void 0, _react3.Suspense,{fallback:null,children:_jsxruntime.jsx.call(void 0, ji,{accessToken:e,models:p,buttonStyle:a})}):null;return u.kind==="error"?_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, $i,{onRetry:()=>void I()}),b]}):u.kind==="empty"?_jsxruntime.jsx.call(void 0, qi,{}):_jsxruntime.jsx.call(void 0, Bi,{accessToken:e,products:m,styles:a,activeScreen:r,params:o,setParams:i,openCourse:d,openMessages:c,filesSection:b})};function Hi({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 qi(){let e=Xe();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 $i({onRetry:e}){let t=_chunkQ337IQNAjs.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, _chunkMMQTRSI5js.k,{type:"button",onClick:e,className:"text-sm",children:t?"Try again":"Spr\xF3buj ponownie"})]})}var bo=Fi;function yo(e){return e.productType===5||e.productType===6}var Bi=({accessToken:e,products:t,styles:n,filesSection:a,activeScreen:r,params:o,setParams:i,openCourse:d,openMessages:c})=>{let l=Xe(),[f,P]=_react3.useState.call(void 0, ()=>ho(o.product,t));_react3.useEffect.call(void 0, ()=>{P(ho(o.product,t))},[o.product,t]);let x=g=>{P(g),i({product:g?Sr(g):void 0,state:"products"})};_react3.useEffect.call(void 0, ()=>{r==="products"&&_optionalChain([f, 'optionalAccess', _114 => _114.productType])===4?d(f.accessId):r==="products"&&f&&yo(f)&&c&&c()},[r,f,d,c]);function I(g){if(yo(g)&&c){c();return}if(g.productType===4){d(g.accessId);return}x(g)}return r==="products"&&_optionalChain([f, 'optionalAccess', _115 => _115.productType])===4?null:r==="products"&&f!=null?_jsxruntime.jsx.call(void 0, fo,{accessToken:e,product:f,styles:n,reveal:x,onOpenCourse:d}):_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-2xl",children:l.hello}),t.length>0&&_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-500 dark:text-neutral-400",children:l.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(g=>{let[u,m,p]=g.productType===1?[l.audio,l.listen,_lucidereact.Headphones]:g.productType===4?[l.course,l.openCourse,_lucidereact.BookOpen]:g.productType===5?[l.chat,l.openMessages,_lucidereact.MessageCircle]:g.productType===6?[l.community,l.openMessages,_lucidereact.Users]:g.productType===3?[l.ticket,l.showTicket,_lucidereact.Ticket]:[l.files,l.downloadFiles,_lucidereact.Files];return _jsxruntime.jsxs.call(void 0, "button",{type:"button",onClick:()=>I(g),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, p,{className:"size-4","aria-hidden":"true"}),u]}),_jsxruntime.jsx.call(void 0, "img",{src:g.productImageUrl,alt:g.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:g.productName}),_jsxruntime.jsx.call(void 0, "span",{className:"line-clamp-2 text-sm text-neutral-600 dark:text-neutral-300",children:Jn(g.productDescription)}),_jsxruntime.jsx.call(void 0, "span",{className:"mt-auto pt-2 text-sm font-medium underline underline-offset-4",children:m})]})]},Sr(g))})}),a]})};function Sr(e){return`${_nullishCoalesce(_optionalChain([_chunk3TUL63ICjs.g, 'access', _116 => _116[e.productType], 'optionalAccess', _117 => _117.toLowerCase, 'call', _118 => _118()]), () => ("product"))}-${e.accessId||e.productId}`}function ho(e,t){if(!e)return;let n=t.find(r=>Sr(r)===e);if(n)return n;let a=t.find(r=>(r.accessId||r.productId)===e||r.productId===e);if(a)return a;try{let r=_protobuf.fromJsonString.call(void 0, _chunk3TUL63ICjs.f,e);return t.find(o=>(r.accessId?o.accessId===r.accessId:o.productId===r.productId)&&(r.productType===0||o.productType===r.productType))}catch (e15){return}}var vo=[{screen:"products",label:"libraryNavLabel",icon:_lucidereact.Library},{screen:"messages",label:"messagesNavLabel",icon:_lucidereact.MessageCircle},{screen:"orders",label:"ordersNavLabel",icon:_lucidereact.Receipt},{screen:"returns",label:"returnsNavLabel",icon:_lucidereact.Undo2},{screen:"profile",label:"accountNavLabel",icon:_lucidereact.User}];function ko(e){return e==="course"?"products":e==="order-details"?"orders":e==="return-details"?"returns":e}function Er({activeScreen:e,setActiveScreen:t,setParams:n,theme:a,logout:r,email:o,projectID:i,showMessages:d=!1}){let c=pe(),{data:l}=_chunkK2HIALKRjs.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, _chunkK2HIALKRjs.c,{projectId:i,logoUrl:_optionalChain([a, 'optionalAccess', _119 => _119.logoURL]),logoDarkUrl:_optionalChain([a, 'optionalAccess', _120 => _120.logoDarkURL]),name:_optionalChain([l, 'optionalAccess', _121 => _121.name]),className:"shrink-0"}),_optionalChain([l, 'optionalAccess', _122 => _122.name])&&_jsxruntime.jsx.call(void 0, "span",{title:l.name,className:"truncate text-sm font-medium md:line-clamp-2 md:whitespace-normal",children:l.name})]}),_jsxruntime.jsx.call(void 0, "nav",{"aria-label":c.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:vo.filter(({screen:f})=>f!=="messages"||d).map(({screen:f,label:P,icon:x})=>{let I=ko(e)===f;return _jsxruntime.jsxs.call(void 0, "button",{type:"button","aria-current":I?"page":void 0,onClick:()=>{t(f),n({product:void 0,state:f})},className:_chunk6DEKVABTjs.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",I?"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, x,{className:"h-5 w-5 shrink-0","aria-hidden":"true"}),_jsxruntime.jsx.call(void 0, "span",{children:c[P]})]},f)})}),_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"}),c.logout]})]})]})}function Lr({email:e,logout:t,onLocaleChange:n}){let[a,r]=_react3.useState.call(void 0, _chunkQ337IQNAjs.f),o=pe(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=>{_chunkQ337IQNAjs.e.call(void 0, i.target.value),r(i.target.value),_optionalChain([n, 'optionalCall', _123 => _123()])},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 ts=_react3.lazy.call(void 0, ()=>Promise.resolve().then(() => _interopRequireWildcard(require("./course.js"))).then(e=>({default:e.PanelCourse})));function Tr(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, ke,{})}),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, ts,{...e})})})}var os=_react3.lazy.call(void 0, ()=>Promise.resolve().then(() => _interopRequireWildcard(require("./chat.js"))).then(e=>({default:e.PanelMessages})));function Ar(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, ke,{})}),children:_jsxruntime.jsx.call(void 0, os,{...e})})}function as(e,t){return!!t||e.some(n=>n.productType===5||n.productType===6)}function xo(e){let{data:t}=_chunkMMQTRSI5js.f.call(void 0, _chunkMMQTRSI5js.e.publicApi.userPanelGetProducts,{accessToken:_nullishCoalesce(e, () => (""))},{enabled:!!e}),n=_optionalChain([t, 'optionalAccess', _124 => _124.result, 'access', _125 => _125.case])==="success"?t.result.value:void 0,a=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _126 => _126.products]), () => ([])),r=_optionalChain([n, 'optionalAccess', _127 => _127.chatApiUrl])||void 0;return{visible:as(a,r),products:a,chatApiUrl:r}}function ds({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 cs({orderID:e,email:t}){let[n,a]=_react3.useState.call(void 0, ""),r=_chunkMMQTRSI5js.g.call(void 0, _chunkMMQTRSI5js.e.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, _chunkK2HIALKRjs.d,{htmlFor:"comment",children:"Dodaj komentarz"}),_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.p,{id:"comment",value:n,onChange:i=>a(i.target.value),placeholder:"Wpisz komentarz...",rows:3,disabled:r.isPending}),_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.k,{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 No(e){return e?new Date(Number(e.seconds)*1e3).toLocaleDateString("pl-PL",{year:"numeric",month:"long",day:"numeric"}):"N/A"}function Io(e,t){return new Intl.NumberFormat("pl-PL",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function us({orderID:e,initialEmail:t,onBack:n,accessToken:a,analytics:r}){let{theme:o,projectID:i}=_chunkNW5PFIZBjs.b.call(void 0, ),d=_chunkEK3D44XWjs.n.call(void 0, i,r,"order"),[c,l]=_react3.useState.call(void 0, t||""),[f,P]=_react3.useState.call(void 0, !1),{data:x,isLoading:I,error:g,refetch:u}=_chunkMMQTRSI5js.f.call(void 0, _chunkMMQTRSI5js.e.publicApi.getPublicOrderDetails,{projectId:_nullishCoalesce(i, () => ("")),orderId:e,email:c||void 0,accessToken:a},{enabled:!!e}),m=_optionalChain([x, 'optionalAccess', _128 => _128.result, 'access', _129 => _129.case])==="order"?x.result.value:null,p=_nullishCoalesce(_optionalChain([m, 'optionalAccess', _130 => _130.isVerified]), () => (!1)),b=m!=null;_react3.useEffect.call(void 0, ()=>{b&&d.track("panel_order_viewed",{},{order_ref:null})},[d,b]);let S=()=>{u(),P(!1)},U={"--button-background-color":_nullishCoalesce(_optionalChain([o, 'optionalAccess', _131 => _131.colors, 'optionalAccess', _132 => _132.brand]), () => ("#000000")),"--button-background-color-dark":_nullishCoalesce(_optionalChain([o, 'optionalAccess', _133 => _133.colors, 'optionalAccess', _134 => _134.brandDark]), () => ("#ffffff")),"--button-text-color":_nullishCoalesce(_optionalChain([o, 'optionalAccess', _135 => _135.colors, 'optionalAccess', _136 => _136.brandDark]), () => ("#000000")),"--button-text-color-dark":_nullishCoalesce(_optionalChain([o, 'optionalAccess', _137 => _137.colors, 'optionalAccess', _138 => _138.brand]), () => ("#000000"))};return I?_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..."})]})}):g||!m?_jsxruntime.jsx.call(void 0, "div",{className:"flex min-h-screen items-center justify-center",children:_jsxruntime.jsx.call(void 0, Re,{className:"w-full max-w-md",children:_jsxruntime.jsx.call(void 0, De,{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:U,children:_jsxruntime.jsxs.call(void 0, "div",{className:"w-full px-4",children:[n&&_jsxruntime.jsxs.call(void 0, _chunkMMQTRSI5js.k,{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', _139 => _139.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, Re,{className:"mb-6",children:[_jsxruntime.jsx.call(void 0, je,{children:_jsxruntime.jsxs.call(void 0, Fe,{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, De,{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, ds,{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 ",No(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, _chunkMMQTRSI5js.k,{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, Re,{className:"mb-6",children:[_jsxruntime.jsx.call(void 0, je,{children:_jsxruntime.jsx.call(void 0, Fe,{children:"Produkty"})}),_jsxruntime.jsxs.call(void 0, De,{className:"space-y-6",children:[_jsxruntime.jsx.call(void 0, "div",{className:"space-y-4",children:m.items.map((N,ce)=>_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-center gap-4",children:[N.imageUrl&&_jsxruntime.jsx.call(void 0, "img",{src:N.imageUrl,alt:N.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:N.name}),_jsxruntime.jsxs.call(void 0, "p",{className:"text-sm text-neutral-600",children:["Ilo\u015B\u0107: ",N.quantity]})]}),_jsxruntime.jsx.call(void 0, "div",{className:"text-right",children:_jsxruntime.jsx.call(void 0, "p",{className:"font-medium",children:Io(Number(N.price),N.currency)})})]},ce))}),(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:Io(Number(m.totalAmount),m.currency)})]})})]})]}),_jsxruntime.jsxs.call(void 0, Re,{children:[_jsxruntime.jsx.call(void 0, je,{children:_jsxruntime.jsxs.call(void 0, Fe,{children:["Komentarze ",m.commentCount>0&&`(${m.commentCount})`]})}),_jsxruntime.jsxs.call(void 0, De,{children:[m.comments.length>0?_jsxruntime.jsx.call(void 0, "div",{className:"space-y-4",children:m.comments.map(N=>_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:N.authorName||"System"}),_jsxruntime.jsx.call(void 0, "span",{className:"text-xs text-neutral-500",children:No(N.createdAt)}),N.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:N.message})]},N.id))}):_jsxruntime.jsx.call(void 0, "p",{className:"text-neutral-600",children:"Brak komentarzy."}),p?_jsxruntime.jsx.call(void 0, cs,{orderID:m.orderId,email:c}):_jsxruntime.jsx.call(void 0, "div",{className:"mt-4",children:_jsxruntime.jsxs.call(void 0, _chunkMMQTRSI5js.k,{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"]})})]})]}),f&&_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, Re,{className:"w-full max-w-md",children:[_jsxruntime.jsx.call(void 0, je,{children:_jsxruntime.jsx.call(void 0, Fe,{children:"Zweryfikuj sw\xF3j email"})}),_jsxruntime.jsxs.call(void 0, De,{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, _chunkK2HIALKRjs.d,{htmlFor:"verify-email",children:"Adres email"}),_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.l,{id:"verify-email",type:"email",placeholder:"twoj@email.com",value:c,onChange:N=>l(N.target.value)})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex gap-2",children:[_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.k,{variant:"outline",onClick:()=>P(!1),className:"flex-1",children:"Anuluj"}),_jsxruntime.jsx.call(void 0, _chunkMMQTRSI5js.k,{onClick:S,className:"flex-1",children:"Zweryfikuj"})]})]})]})})]})})}function ps(e){return _jsxruntime.jsx.call(void 0, us,{...e})}var Mr=ps;var fs=({returnsAppearance:e,returnsTexts:t,analytics:n}={})=>{let{projectID:a,theme:r,loginURL:o,host:i}=_chunkNW5PFIZBjs.b.call(void 0, ),[,d]=_react3.useState.call(void 0, 0),c=_chunkEK3D44XWjs.n.call(void 0, a,n,"panel"),l=_chunkMDAFPGPAjs.i.call(void 0, a,i),f=_chunkMDAFPGPAjs.k.call(void 0, a,i),{mutateAsync:P}=_chunkMMQTRSI5js.g.call(void 0, _chunkMMQTRSI5js.e.publicApi.userPanelLogout);async function x(){l&&await P({accessToken:l}),typeof window<"u"&&(_chunkMDAFPGPAjs.l.call(void 0, a,i),window.location.reload())}let[I]=_react.useAutoAnimate.call(void 0, ),g=E=>["products","notifications","profile","plans","orders","order-details","returns","return-details","course","messages"].includes(E),[u,m]=Kn({product:void 0,state:"products",orderId:void 0,returnId:void 0,course:void 0,item:void 0,chatProject:void 0,thread:void 0,channel:void 0}),[p,b]=_react3.useState.call(void 0, g(u.state)?u.state:"products"),S=E=>{m({state:"order-details",orderId:E}),b("order-details")},U=()=>{m({state:"orders",orderId:void 0}),b("orders")},N=E=>m({orderId:void 0,returnId:void 0,course:void 0,item:void 0,chatProject:void 0,thread:void 0,channel:void 0,...E}),ce=E=>{m({state:"course",course:E,item:void 0,product:void 0}),b("course")},Se=()=>{m({state:"products",course:void 0,item:void 0,product:void 0}),b("products")},oe=()=>{m({state:"messages",product:void 0,chatProject:void 0,thread:void 0,channel:void 0}),b("messages")},te=xo(l);_react3.useEffect.call(void 0, ()=>{g(u.state)&&(u.state==="course"||p==="course"||u.state==="messages"||p==="messages")&&b(u.state)},[u.state]);let fe={"--button-background-color":_nullishCoalesce(_optionalChain([r, 'optionalAccess', _140 => _140.colors, 'optionalAccess', _141 => _141.brand]), () => ("#000000")),"--button-background-color-dark":_nullishCoalesce(_optionalChain([r, 'optionalAccess', _142 => _142.colors, 'optionalAccess', _143 => _143.brandDark]), () => ("#ffffff")),"--button-text-color":_nullishCoalesce(_optionalChain([r, 'optionalAccess', _144 => _144.colors, 'optionalAccess', _145 => _145.brandDark]), () => ("#000000")),"--button-text-color-dark":_nullishCoalesce(_optionalChain([r, 'optionalAccess', _146 => _146.colors, 'optionalAccess', _147 => _147.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 E=gt(window.location.search);E&&yt(E);let ge=_nullishCoalesce(E, () => (Ze()));ge&&(window.location.href=Qe(ge,l))},[l]),_jsxruntime.jsx.call(void 0, _chunkEK3D44XWjs.l,{value:c,children:_jsxruntime.jsxs.call(void 0, "div",{ref:I,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, Er,{activeScreen:p,setActiveScreen:b,setParams:N,styles:fe,theme:r,logout:x,email:f,projectID:a,showMessages:te.visible||p==="messages"}),_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, bo,{projectID:_nullishCoalesce(a, () => ("")),accessToken:l,loginURL:_nullishCoalesce(o, () => ("/panel/login")),styles:fe,activeScreen:p,params:u,setParams:m,openCourse:ce,openMessages:oe}),p==="messages"&&l&&_jsxruntime.jsx.call(void 0, Ar,{accessToken:l,products:te.products,chatApiUrl:te.chatApiUrl,projectID:a,host:i,selection:{chatProject:u.chatProject,thread:u.thread,channel:u.channel},onSelect:E=>m({chatProject:E.chatProject,thread:E.thread,channel:E.channel})}),p==="course"&&u.course&&l&&_jsxruntime.jsx.call(void 0, Tr,{accessId:u.course,accessToken:l,theme:r,itemId:u.item,onItemChange:E=>m({item:E}),onBack:Se}),p==="notifications"&&_jsxruntime.jsx.call(void 0, yr,{}),p==="plans"&&_jsxruntime.jsx.call(void 0, hr,{projectID:_nullishCoalesce(a, () => (""))}),p==="orders"&&_jsxruntime.jsx.call(void 0, Wn,{projectID:_nullishCoalesce(a, () => ("")),accessToken:_nullishCoalesce(l, () => ("")),openOrderDetails:S}),p==="order-details"&&u.orderId&&_jsxruntime.jsx.call(void 0, Mr,{orderID:u.orderId,onBack:U}),(p==="returns"||p==="return-details")&&l&&_jsxruntime.jsx.call(void 0, Pr,{projectID:_nullishCoalesce(a, () => ("")),host:i,accessToken:l,loginURL:_nullishCoalesce(o, () => ("/panel/login")),appearance:Gn(e,_optionalChain([r, 'optionalAccess', _148 => _148.colors, 'optionalAccess', _149 => _149.brand])),texts:t,screen:p,params:u,setParams:m,setActiveScreen:b}),p==="profile"&&_jsxruntime.jsx.call(void 0, Lr,{email:f,logout:x,onLocaleChange:()=>d(E=>E+1)})]})]})})},gs= exports.G =fs;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, _chunk3TUL63ICjs.h,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:[_chunk6DEKVABTjs.b]}),t.set(r,o)),o}})(me = exports.a||={});var _zod = require('zod'); var _zod2 = _interopRequireDefault(_zod);function j(e,t=2){return+(Math.round(+(e+"e+"+t))+"e-"+t)}function Ro(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 gp=_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 Or(e){typeof window>"u"||(bs(e),vs(e),ks(e))}function bs(e){try{typeof window.dataLayer>"u"&&(window.dataLayer=[]);let t=Ps(e);window.dataLayer.push(t)}catch(t){console.warn("cannot send google analytics event",t)}}function Ps(e){let t=_nullishCoalesce(_nullishCoalesce(e.value, () => (_optionalChain([e, 'access', _150 => _150.items, 'optionalAccess', _151 => _151.reduce, 'call', _152 => _152((o,i)=>o+(i.price||0)*(i.quantity||1),0)]))), () => (0)),n=_optionalChain([e, 'access', _153 => _153.items, 'optionalAccess', _154 => _154.map, 'call', _155 => _155(o=>({item_id:o.id,item_name:o.name||o.id,price:j((o.price||0)/100,2),quantity:o.quantity||1}))]),a={currency:e.currency||"PLN",value:j(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 vs(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 ks(e){try{if(typeof window.ttq>"u")return;let t=xs(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 xs(e){let t=_nullishCoalesce(_nullishCoalesce(e.value, () => (_optionalChain([e, 'access', _156 => _156.items, 'optionalAccess', _157 => _157.reduce, 'call', _158 => _158((o,i)=>o+(i.price||0)*(i.quantity||1),0)]))), () => (0)),n=_optionalChain([e, 'access', _159 => _159.items, 'optionalAccess', _160 => _160.map, 'call', _161 => _161(o=>({content_id:o.id,content_type:"product",content_name:o.name||o.id,quantity:o.quantity||1,price:j((o.price||0)/100,2)}))])||[];n.length===0&&e.content_name&&n.push({content_id:e.step||"unknown",content_type:"product",content_name:e.content_name,quantity:1,price:j(t/100,2)});let a={currency:e.currency||"PLN",value:j(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 Do(e){let{items:t,googlePayConfig:n,checkout:a,result:r,cartRequiresShipping:o}=e,i=_nullishCoalesce(e.locale, () => (_chunkQ337IQNAjs.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+` - ${Ro(l.amount,r.currency)}`,description:_nullishCoalesce(l.description, () => (""))})),defaultSelectedOptionId:r.selectedDeliveryMethod}:void 0,merchantInfo:{merchantId:n.merchantId+"",merchantName:n.merchantName},transactionInfo:{totalPriceStatus:"FINAL",totalPriceLabel:_chunkQ337IQNAjs.c.call(void 0, "paymentForCart",i,e.texts),totalPrice:`${j(r.totalAmount/100,2)}`,currencyCode:r.currency,countryCode:r.country,checkoutOption:"COMPLETE_IMMEDIATE_PURCHASE",displayItems:ws(t,r.methods,_nullishCoalesce(r.selectedDeliveryMethod, () => ((r.methods.length>0?r.methods[0].id:void 0))),a.couponCode,r.couponValue,_chunkQ337IQNAjs.c.call(void 0, "coupon",i,e.texts))}}}function ws(e,t,n,a,r,o="Coupon"){let i=[],d=0;for(let l of e){if(l.details==null)continue;let f=_nullishCoalesce(_optionalChain([l, 'access', _162 => _162.details, 'access', _163 => _163.pricing, 'optionalAccess', _164 => _164.effectivePrice]), () => (l.details.price));d+=f*l.quantity,i.push({label:l.details.name+" x "+l.quantity,price:`${j(f/100,2)}`,type:"LINE_ITEM",status:"FINAL"})}let c=t.find(l=>l.id===n);return c!=null&&i.push({label:c.name,price:`${j(c.amount/100,2)}`,type:"SHIPPING_OPTION",status:"FINAL"}),a!=null&&r!=null&&i.push({label:`${o} ${a}`,price:`${j(r/100,2)}`,type:"DISCOUNT",status:"FINAL"}),d>0&&i.push({label:"Subtotal",price:`${j(d/100,2)}`,type:"SUBTOTAL",status:"FINAL"}),i}function ot(e,t){return`${_chunk6DEKVABTjs.e}/api/integrations/${e}/public-commerce${t}`}function Ue(e){return typeof e=="object"&&e!=null&&"ERR"in e}function B(e,t,n){return{ERR:!0,error:e,type:t,data:n}}function Mo(e,t){return _optionalChain([t, 'optionalAccess', _165 => _165.find, 'call', _166 => _166(n=>n.id===e||(_nullishCoalesce(_optionalChain([n, 'access', _167 => _167.variants, 'optionalAccess', _168 => _168.some, 'call', _169 => _169(a=>a.id===e)]), () => (!1))))])}function Oo(e,t){let n=new Set(t.map(a=>a.productID));return Array.from(new Set(e.filter(a=>!n.has(a))))}function Uo(e,t){let n=_optionalChain([e, 'optionalAccess', _170 => _170.trim, 'call', _171 => _171()]);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 at=_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 _t=_react3.createContext.call(void 0, {});function Tp({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, _t.Provider,{value:a,children:n})}function zo(){return _react3.useContext.call(void 0, _t)}function Ap(e){let{texts:t,locale:n}=_react3.useContext.call(void 0, _t);return _chunkQ337IQNAjs.c.call(void 0, e,_nullishCoalesce(n, () => (_chunkQ337IQNAjs.f.call(void 0, ))),t)}function Rp(){let{texts:e,locale:t}=_react3.useContext.call(void 0, _t),n=_nullishCoalesce(t, () => (_chunkQ337IQNAjs.f.call(void 0, )));return _react3.useMemo.call(void 0, ()=>a=>_chunkQ337IQNAjs.c.call(void 0, a,n,e),[n,e])}var zr="bitsnap-pending-order";function Ho(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 Ss=60*1e3;function qo(e,t=Date.now,n=Ss){let a;return r=>{let o=`${r.orderId}:${r.ts}`,i=t();return _optionalChain([a, 'optionalAccess', _172 => _172.key])===o&&i-a.at<n?Promise.reject(new Error("pending order was asked about recently")):(a={key:o,at:i},e(r))}}function Es(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 Ts(e,t=Date.now(),n={}){if(Ls(e.url))return;let a=Es(e.url),r=_nullishCoalesce(jo(e.orderId), () => (_optionalChain([a, 'optionalAccess', _173 => _173.orderId]))),o=_nullishCoalesce(jo(e.projectId), () => (_optionalChain([a, 'optionalAccess', _174 => _174.projectId])));if(!(r==null||o==null))return{orderId:r,projectId:o,...n.cartProjectId!=null?{cartProjectId:n.cartProjectId}:{},lines:_nullishCoalesce(n.lines, () => ([])),ts:t}}function Op(e,t={}){let n=Ts(e,t.now,t);return n!=null&&As(n,t.storage)}function jo(e){return e!=null&&e.length>0?e:void 0}function zt(){try{return typeof localStorage>"u"?void 0:localStorage}catch (e19){return}}function As(e,t=zt()){try{return _optionalChain([t, 'optionalAccess', _175 => _175.setItem, 'call', _176 => _176(zr,JSON.stringify(e))]),t!=null}catch (e20){return!1}}function Fo(e=zt()){try{let t=_optionalChain([e, 'optionalAccess', _177 => _177.getItem, 'call', _178 => _178(zr)]);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', _179 => _179.id])=="string"&&typeof c.quantity=="number"):[],ts:i}}}catch (e21){}_r(e)}function _r(e=zt()){try{_optionalChain([e, 'optionalAccess', _180 => _180.removeItem, 'call', _181 => _181(zr)])}catch (e22){}}function $o(e){let t=_nullishCoalesce(_optionalChain([e, 'access', _182 => _182.details, 'optionalAccess', _183 => _183.status]), () => (Rs(_optionalChain([e, 'access', _184 => _184.details, 'optionalAccess', _185 => _185.$unknown]))));return t==="created"||t==="placed"||t==="paid"||t==="canceled"?t:"unknown"}function Rs(e){if(Array.isArray(e)){for(let t of e)if(_optionalChain([t, 'optionalAccess', _186 => _186.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 Bo(e){let t=_nullishCoalesce(e.storage, () => (zt())),n=Fo(t);if(n==null)return"none";if((_nullishCoalesce(e.now, () => (Date.now)))()-n.ts>864e5)return _r(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=Fo(t);if(_optionalChain([o, 'optionalAccess', _187 => _187.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 _r(t),"paid"}return"pending"}var zs="__m_a",Zo=_react3.createContext.call(void 0, void 0),qr= exports.I =void 0;function sm(e){_chunkMDAFPGPAjs.a.call(void 0, {projectID:e}),qr= exports.I =e,typeof window<"u"&&_chunkMDAFPGPAjs.g.call(void 0, [window.location.origin])}function st(){return _nullishCoalesce(_nullishCoalesce(qr, () => (_optionalChain([document, 'access', _188 => _188.querySelector, 'call', _189 => _189('script[data-id][data-name="internal-cart"]'), 'optionalAccess', _190 => _190.getAttribute, 'call', _191 => _191("data-id")]))), () => (void 0))}function js(){return _nullishCoalesce(_optionalChain([document, 'access', _192 => _192.querySelector, 'call', _193 => _193('script[data-id][data-name="internal-cart"]'), 'optionalAccess', _194 => _194.getAttribute, 'call', _195 => _195("data-custom-host")]), () => (void 0))}var Fs=({children:e,locale:t})=>{let[n]=_react3.useState.call(void 0, ()=>new _reactquery.QueryClient),a=zo();_react3.useEffect.call(void 0, ()=>{Ie()},[]);let r=st();if(_react3.useEffect.call(void 0, ()=>{if(r==null)return;let i=()=>{$s(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=Kr(r,_nullishCoalesce(t, () => (a.locale)),a.texts);return _jsxruntime.jsx.call(void 0, _reactquery.QueryClientProvider,{client:n,children:_jsxruntime.jsx.call(void 0, Zo.Provider,{value:o,children:e})})},jr,Hs=qo(async e=>$o(await me.get(_chunk6DEKVABTjs.e).getOrder({id:e.orderId,projectId:e.projectId})));function lm(){let{country:e,couponCode:t,selectedDeliveryMethod:n,postalCode:a}=_nullishCoalesce(T(), () => (qt));return{country:e,couponCode:t,selectedDeliveryMethod:n,postalCode:a}}function dm(){return(_nullishCoalesce(_optionalChain([T, 'call', _196 => _196(), 'optionalAccess', _197 => _197.products]), () => ([]))).map(e=>({id:e.id,quantity:e.quantity}))}function qs(e){let t=T();V({...t,products:Ho(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _198 => _198.products]), () => ([])),e)}),Ie()}function $s(e){return jr??=Bo({projectId:e,fetchStatus:Hs,removeLines:qs}).catch(t=>{console.warn("cannot check the pending order",t)}).finally(()=>{jr=void 0}),jr}var it=async(e,t)=>{let n=[];_optionalChain([t, 'optionalAccess', _199 => _199.items])!=null&&t.items.length>0?n=t.items:n=_nullishCoalesce(_optionalChain([T, 'call', _200 => _200(), 'optionalAccess', _201 => _201.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', _202 => _202.locale]), () => (_chunkQ337IQNAjs.f.call(void 0, ))));let o;try{let i=await fetch(_chunk6DEKVABTjs.c.call(void 0, ot(e,`/products?${r.toString()}`)),{method:"GET"});if(i.status!=200)return B("products-load-failed","internal");o=await i.json()}catch(i){return console.warn("cannot load the products of the cart",i),B("products-load-failed","internal")}return n.flatMap(i=>{let d=Mo(i.productID,o.result);return d==null?[]:[{...i,details:Js(i.productID,d),catalogProductID:d.id}]})},cm= exports.O =()=>{let e=_react3.useContext.call(void 0, Zo);if(e===void 0)throw new Error("useCartProvider must be used within a CartProvider");return e},um= exports.P =Fs,Bs=_zod2.default.object({isAvailable:_zod2.default.boolean(),merchantId:_zod2.default.string(),merchantName:_zod2.default.string(),gateway:_zod2.default.string(),gatewayId:_zod2.default.string()}),Ks=_zod2.default.object({id:_zod2.default.string(),productID:_zod2.default.string(),quantity:_zod2.default.number(),priceVersion:_zod2.default.string().optional(),amount:_zod2.default.number().int().nonnegative().optional(),metadata:_zod2.default.record(_zod2.default.string(),_zod2.default.string().optional()).optional(),url:_zod2.default.string().optional()}),Gs=_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(Ks).optional(),googlePayConfig:Bs.optional()}),qt={country:void 0,couponCode:void 0,email:void 0,selectedDeliveryMethod:void 0,postalCode:void 0,products:[],googlePayConfig:void 0},Br="checkout";function Vs(){return typeof localStorage>"u"?[]:(_nullishCoalesce(T().products, () => ([]))).map(e=>({...e}))}function pm(){return Vs().map(e=>`${e.productID}:${e.quantity}`).sort().join(",")}function mm(e){let t=T();if(!(t.products==null||t.products.length===0))return{items:t.products.map(n=>({id:n.productID,quantity:n.quantity,...n.priceVersion!=null?{priceVersion:n.priceVersion}:{},...n.amount!=null?{amount:n.amount}:{}})),...t.country!=null?{countries:[t.country]}:{},...t.couponCode!=null?{couponCode:t.couponCode}:{},...t.selectedDeliveryMethod!=null?{deliveryMethod:t.selectedDeliveryMethod}:{},locale:e}}function fm(e){let t=T(),n=new Map;for(let a of _nullishCoalesce(t.products, () => ([]))){let r=_nullishCoalesce(n.get(a.productID), () => ([]));r.push(a),n.set(a.productID,r)}t.products=e.map(a=>{let r=_optionalChain([n, 'access', _203 => _203.get, 'call', _204 => _204(a.productId), 'optionalAccess', _205 => _205.shift, 'call', _206 => _206()]);return{id:Math.random().toString(36).substring(7),productID:a.productId,quantity:a.quantity,..._optionalChain([r, 'optionalAccess', _207 => _207.priceVersion])!=null?{priceVersion:r.priceVersion}:{},..._optionalChain([r, 'optionalAccess', _208 => _208.metadata])!=null?{metadata:r.metadata}:{},..._optionalChain([r, 'optionalAccess', _209 => _209.url])!=null?{url:r.url}:{}}}),V(t),Ie()}function gm(e){let t=new Map;for(let r of e)t.set(r.id,(_nullishCoalesce(t.get(r.id), () => (0)))+r.quantity);let n=T(),a=(_nullishCoalesce(n.products, () => ([]))).flatMap(r=>{let o=t.get(r.productID);return o==null?[r]:r.quantity<=o?[]:[{...r,quantity:r.quantity-o}]});V({...n,products:a}),Ie()}function ym(e){let t=T();t.products=_nullishCoalesce(t.products, () => ([]));for(let n of e)t.products.push({id:Math.random().toString(36).substring(7),productID:n.id,quantity:n.quantity});V(t),Ie()}function T(){try{let e=localStorage.getItem(Br);return e==null?qt:Gs.parse(JSON.parse(e))}catch (e26){return qt}}async function Go(e,t){let n=await it(e,{items:t.map((o,i)=>({...o,id:`price-check-${i}`}))});if(Ue(n))return n;let a=Oo(t.map(o=>o.productID),n);if(a.length>0)return B("item-ids-not-found","notFound",a);let r=T();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', _210 => _210.find, 'call', _211 => _211(i=>i.productID===o.productID), 'optionalAccess', _212 => _212.details, 'optionalAccess', _213 => _213.pricing, 'optionalAccess', _214 => _214.priceVersion]),amount:o.amount,metadata:o.metadata,url:Uo(o.url,typeof window<"u"?window.location.href:void 0)}))),Ws(t,n),Or({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"))}))}),V(r),Ie()}function Ws(e,t){for(let n of e)try{let a=t.find(d=>d.productID===n.productID),r=_nullishCoalesce(_nullishCoalesce(_optionalChain([a, 'optionalAccess', _215 => _215.details, 'optionalAccess', _216 => _216.pricing, 'optionalAccess', _217 => _217.effectivePrice]), () => (_optionalChain([a, 'optionalAccess', _218 => _218.details, 'optionalAccess', _219 => _219.price]))), () => (n.price)),o=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _220 => _220.details, 'optionalAccess', _221 => _221.currency]), () => (n.currency));if(r==null||o==null)continue;let i=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _222 => _222.catalogProductID]), () => (n.productID));(_nullishCoalesce(n.analytics, () => (_chunkEK3D44XWjs.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 Vo(e){let t=T(),n={...t,products:_optionalChain([t, 'optionalAccess', _223 => _223.products, 'optionalAccess', _224 => _224.filter, 'call', _225 => _225(a=>!e.includes(a.productID)&&!e.includes(a.id))])};Or({event:"removeFromCart",items:e.map(a=>({id:a,name:"",price:0,quantity:1,currency:"PLN"}))}),V(n),Ie()}function V(e){localStorage.setItem(Br,JSON.stringify(e)),Xo()}var Ft=new Set,Qo=0,jt=!1;function Wo(e){e.key===Br&&Xo()}function hm(e){return Ft.add(e),!jt&&typeof window<"u"&&(window.addEventListener("storage",Wo),jt=!0),()=>{Ft.delete(e),Ft.size===0&&jt&&(window.removeEventListener("storage",Wo),jt=!1)}}function bm(){return Qo}function Xo(){Qo+=1;for(let e of Ft)try{e()}catch (e28){}}function Yo(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', _226 => _226.metadata, 'optionalAccess', _227 => _227[o]]);i!=null&&(a[o]=i)}),a),{});return{items:e.products.map(a=>({id:a.productID,quantity:a.quantity,priceVersion:a.priceVersion,...a.amount!=null?{amount:a.amount}:{}})),askForNote:!0,countries:e.country?[e.country]:void 0,metadata:n,locale:t}}var Kr=(e,t=_chunkQ337IQNAjs.f.call(void 0, ),n)=>{let a=js();return a!=null&&_chunk6DEKVABTjs.f.call(void 0, a),{async checkIfApplePayIsAvailable(){if(typeof window>"u"||typeof document>"u"||!("ApplePaySession"in window))return!1;try{return(await me.get(_chunk6DEKVABTjs.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 Ys(e);if(_optionalChain([o, 'optionalAccess', _228 => _228.isAvailable])!=!0)return{isAvailable:!1};let i=T();if(i==null)return console.log("checkout is null"),{isAvailable:!1};let d=await it(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(Ue(d))return{isAvailable:!1};let c=await me.get(_chunk6DEKVABTjs.e).getPreOrderDetails({items:d.map(P=>_protobuf.create.call(void 0, _chunk3TUL63ICjs.d,{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', _229 => _229.details, 'optionalAccess', _230 => _230.isDeliverable])==!0)!=null,f=await Do({items:d,googlePayConfig:o,checkout:i,cartRequiresShipping:l,result:c,locale:t,texts:n});return f==null?{isAvailable:!1}:{isAvailable:!0,config:f}}catch(o){return console.error("Error resolving Google Pay configuration",o),{isAvailable:!1}}},async clearCart(){let r=structuredClone(qt);r.country=_optionalChain([T, 'call', _231 => _231(), 'optionalAccess', _232 => _232.country]),V(r),Ie()},async getAvailableCountries(){let r=await fetch(_chunk6DEKVABTjs.c.call(void 0, ot(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 B(o.toString(),"internal")}},async getCountry(){let r=_optionalChain([T, 'call', _233 => _233(), 'optionalAccess', _234 => _234.country]);if(r==null){r="PL";let o=T();o.country=r,V(o)}return r},async getNumberOfElementsInCart(){return _nullishCoalesce(_optionalChain([T, 'call', _235 => _235(), 'optionalAccess', _236 => _236.products, 'optionalAccess', _237 => _237.reduce, 'call', _238 => _238((r,o)=>r+o.quantity,0)]), () => (0))},async getProducts(){return await it(e,{locale:t})},async removeProductFromCart(r){return Vo([r.id])},async setCountry(r){let o=T();o.country=r,V(o)},async setCouponCodeIfPossible(r){let o=T();o.couponCode=r,V(o)},async setPostalCode(r){let o=T();o.postalCode=r,V(o)},async setDeliveryMethod(r){let o=T();o.selectedDeliveryMethod=r,V(o)},async setEmail(r){let o=T();o.email=r,V(o)},async addProduct(r){return await Go(e,[r])},async updateQuantity(r){let o=T();o.products=_optionalChain([o, 'access', _239 => _239.products, 'optionalAccess', _240 => _240.map, 'call', _241 => _241(i=>(i.id===r.id&&(i.quantity=r.quantity),i))]),V(o),Ie()},async getPaymentMethodChoice(){let r=Yo(T(),t);return r==null?null:Jo(r)},async redirectToNextStep(r){let o=Yo(T(),t);if(o==null)return B("cart-is-empty","badInput");_optionalChain([r, 'optionalAccess', _242 => _242.paymentMethod])!=null&&(o.paymentMethod=r.paymentMethod);let i=await Hr(o);return Ue(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=$r(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:zs,name:"",required:!0,answer:!0}]);let i=await Hr(o);return Ue(i)?i:{url:i.url}},async getApplePayPreview(r){let o=T();try{let i=await me.get(_chunk6DEKVABTjs.e).getPreOrderDetails({items:r.items.map(d=>_protobuf.create.call(void 0, _chunk3TUL63ICjs.d,{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?B("pre-order-unavailable","internal"):{countryCode:i.country||o.country||"PL",currencyCode:i.currency,totalAmount:`${j(i.totalAmount/100,2)}`}}catch(i){return console.warn("cannot load the Apple Pay preview",i),B("pre-order-unavailable","internal")}},async completeApplePayPayment(r){let o=T();if(o==null)return B("Checkout not found");let i=await it(e,{locale:t});if(Ue(i))return i;try{let d=_optionalChain([r, 'access', _243 => _243.shippingContact, 'optionalAccess', _244 => _244.givenName]);_optionalChain([r, 'access', _245 => _245.shippingContact, 'optionalAccess', _246 => _246.familyName])!=null?d+=" "+_optionalChain([r, 'access', _247 => _247.shippingContact, 'optionalAccess', _248 => _248.familyName]):_optionalChain([r, 'access', _249 => _249.billingContact, 'optionalAccess', _250 => _250.familyName])!=null&&(d+=" "+_optionalChain([r, 'access', _251 => _251.billingContact, 'optionalAccess', _252 => _252.familyName]));let c={},l=Ht();l!=null&&(c.ref=l);let f=await me.get(_chunk6DEKVABTjs.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, _chunk3TUL63ICjs.e,{items:i.map(P=>({id:P.productID,quantity:P.quantity})),couponCode:o.couponCode,email:_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([r, 'access', _253 => _253.shippingContact, 'optionalAccess', _254 => _254.emailAddress]), () => (_optionalChain([r, 'access', _255 => _255.billingContact, 'optionalAccess', _256 => _256.emailAddress]))), () => (o.email)), () => (void 0)),phone:_nullishCoalesce(_nullishCoalesce(_optionalChain([r, 'access', _257 => _257.shippingContact, 'optionalAccess', _258 => _258.phoneNumber]), () => (_optionalChain([r, 'access', _259 => _259.billingContact, 'optionalAccess', _260 => _260.phoneNumber]))), () => (void 0)),selectedDeliveryMethod:o.selectedDeliveryMethod,postCode:o.postalCode,projectId:e}),shippingAddress:_protobuf.create.call(void 0, _chunk3TUL63ICjs.a,{line1:_nullishCoalesce(_optionalChain([r, 'access', _261 => _261.shippingContact, 'optionalAccess', _262 => _262.addressLines, 'optionalAccess', _263 => _263[0]]), () => ("")),city:_nullishCoalesce(_optionalChain([r, 'access', _264 => _264.shippingContact, 'optionalAccess', _265 => _265.locality]), () => ("")),country:_nullishCoalesce(_optionalChain([r, 'access', _266 => _266.shippingContact, 'optionalAccess', _267 => _267.countryCode]), () => ("")),zipCode:_nullishCoalesce(_optionalChain([r, 'access', _268 => _268.shippingContact, 'optionalAccess', _269 => _269.postalCode]), () => ("")),name:d}),billingAddress:_protobuf.create.call(void 0, _chunk3TUL63ICjs.b,{name:_nullishCoalesce(_optionalChain([r, 'access', _270 => _270.billingContact, 'optionalAccess', _271 => _271.givenName]), () => (" "+(_nullishCoalesce(_optionalChain([r, 'access', _272 => _272.billingContact, 'optionalAccess', _273 => _273.familyName]), () => (""))))),line1:_nullishCoalesce(_optionalChain([r, 'access', _274 => _274.billingContact, 'optionalAccess', _275 => _275.addressLines, 'optionalAccess', _276 => _276[0]]), () => ("")),city:_nullishCoalesce(_optionalChain([r, 'access', _277 => _277.billingContact, 'optionalAccess', _278 => _278.locality]), () => ("")),country:_nullishCoalesce(_optionalChain([r, 'access', _279 => _279.billingContact, 'optionalAccess', _280 => _280.countryCode]), () => ("")),zipCode:_nullishCoalesce(_optionalChain([r, 'access', _281 => _281.billingContact, 'optionalAccess', _282 => _282.postalCode]), () => (""))}),metadata:Object.keys(c).length>0?JSON.stringify(c):void 0});return{isSuccess:f.isSuccess,redirectURL:f.redirectUrl}}catch(d){return console.error(d),B("Failed to authorize payment")}},async completeGooglePayPayment(r){let o=T();if(o==null)return B("Checkout not found");let i=await it(e,{locale:t});if(Ue(i))return i;try{let d=_optionalChain([r, 'access', _283 => _283.paymentData, 'access', _284 => _284.shippingAddress, 'optionalAccess', _285 => _285.name]),c={},l=Ht();l!=null&&(c.ref=l);let f=await me.get(_chunk6DEKVABTjs.e).authorizeOneClickPayment({gateway:1,paymentData:r.paymentData.paymentMethodData.tokenizationData.token,paymentMethod:r.paymentData.paymentMethodData.type,transactionIdentifier:"",order:_protobuf.create.call(void 0, _chunk3TUL63ICjs.e,{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', _286 => _286.paymentData, 'access', _287 => _287.shippingAddress, 'optionalAccess', _288 => _288.phoneNumber]), () => (void 0)),selectedDeliveryMethod:_nullishCoalesce(_optionalChain([r, 'access', _289 => _289.paymentData, 'access', _290 => _290.shippingOptionData, 'optionalAccess', _291 => _291.id]), () => (o.selectedDeliveryMethod)),postCode:_optionalChain([r, 'access', _292 => _292.paymentData, 'access', _293 => _293.shippingAddress, 'optionalAccess', _294 => _294.postalCode]),projectId:e}),shippingAddress:_protobuf.create.call(void 0, _chunk3TUL63ICjs.a,{line1:_nullishCoalesce(_optionalChain([r, 'access', _295 => _295.paymentData, 'access', _296 => _296.shippingAddress, 'optionalAccess', _297 => _297.address1]), () => ("")),city:_nullishCoalesce(_optionalChain([r, 'access', _298 => _298.paymentData, 'access', _299 => _299.shippingAddress, 'optionalAccess', _300 => _300.locality]), () => ("")),country:_nullishCoalesce(_optionalChain([r, 'access', _301 => _301.paymentData, 'access', _302 => _302.shippingAddress, 'optionalAccess', _303 => _303.countryCode]), () => ("")),zipCode:_nullishCoalesce(_optionalChain([r, 'access', _304 => _304.paymentData, 'access', _305 => _305.shippingAddress, 'optionalAccess', _306 => _306.postalCode]), () => ("")),name:d}),billingAddress:_protobuf.create.call(void 0, _chunk3TUL63ICjs.b,{name:_optionalChain([r, 'access', _307 => _307.paymentData, 'access', _308 => _308.paymentMethodData, 'access', _309 => _309.info, 'optionalAccess', _310 => _310.billingAddress, 'optionalAccess', _311 => _311.name]),line1:_nullishCoalesce(_optionalChain([r, 'access', _312 => _312.paymentData, 'access', _313 => _313.paymentMethodData, 'access', _314 => _314.info, 'optionalAccess', _315 => _315.billingAddress, 'optionalAccess', _316 => _316.address1]), () => ("")),city:_nullishCoalesce(_optionalChain([r, 'access', _317 => _317.paymentData, 'access', _318 => _318.paymentMethodData, 'access', _319 => _319.info, 'optionalAccess', _320 => _320.billingAddress, 'optionalAccess', _321 => _321.locality]), () => ("")),country:_nullishCoalesce(_optionalChain([r, 'access', _322 => _322.paymentData, 'access', _323 => _323.paymentMethodData, 'access', _324 => _324.info, 'optionalAccess', _325 => _325.billingAddress, 'optionalAccess', _326 => _326.countryCode]), () => ("")),zipCode:_nullishCoalesce(_optionalChain([r, 'access', _327 => _327.paymentData, 'access', _328 => _328.paymentMethodData, 'access', _329 => _329.info, 'optionalAccess', _330 => _330.billingAddress, 'optionalAccess', _331 => _331.postalCode]), () => (""))}),metadata:Object.keys(c).length>0?JSON.stringify(c):void 0});return{isSuccess:f.isSuccess,redirectURL:f.redirectUrl}}catch(d){return console.error(d),B("Failed to authorize payment")}return{isSuccess:!0}},async getApplePayPaymentRequest(r){let o=T();if(o==null)return B("Checkout not found");r&&r.expectedItems!=null&&r.expectedItems.length>0&&(o.products&&Vo(o.products.map(l=>l.productID)),await Go(e,r.expectedItems));let i=await it(e,{locale:t});if(Ue(i))return i;let d=await me.get(_chunk6DEKVABTjs.e).getPreOrderDetails({items:i.map(l=>_protobuf.create.call(void 0, _chunk3TUL63ICjs.d,{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:`${j(l.quantity*(_nullishCoalesce(_nullishCoalesce(_optionalChain([l, 'access', _332 => _332.details, 'optionalAccess', _333 => _333.pricing, 'optionalAccess', _334 => _334.effectivePrice]), () => (_optionalChain([l, 'access', _335 => _335.details, 'optionalAccess', _336 => _336.price]))), () => (0)))/100,2)}`,label:_optionalChain([l, 'access', _337 => _337.details, 'optionalAccess', _338 => _338.name])+" - "+l.quantity,type:"final"}));if(d.selectedDeliveryMethod!=null){let l=d.methods.find(f=>f.id==d.selectedDeliveryMethod);l!=null&&c.push({amount:`${j(l.amount/100,2)}`,label:l.name,type:"final"})}return d.couponCode!=null&&d.couponValue!=null&&c.push({amount:`-${j(d.couponValue/100,2)}`,label:d.couponCode,type:"final"}),{countryCode:d.country||o.country||"PL",merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],supportedNetworks:["visa","masterCard"],total:{amount:`${j((_nullishCoalesce(d.totalAmount, () => (0)))/100,2)}`,label:_chunkQ337IQNAjs.c.call(void 0, "paymentForCart",t,n),type:"final"},shippingMethods:d.methods.map(l=>({amount:`${j(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', _339 => _339[0], 'optionalAccess', _340 => _340.details, 'optionalAccess', _341 => _341.currency])||"PLN"}}}};async function Ys(e){let t=T();if(_optionalChain([t, 'access', _342 => _342.googlePayConfig, 'optionalAccess', _343 => _343.isAvailable])!=!0){let n=await me.get(_chunk6DEKVABTjs.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 V(t),t.googlePayConfig}function Js(e,t){if(e==t.id){let a=_optionalChain([t, 'access', _344 => _344.variants, 'optionalAccess', _345 => _345.findIndex, 'call', _346 => _346(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', _347 => _347.variants, 'optionalAccess', _348 => _348.find, 'call', _349 => _349(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 Ie(){let e=T(),t=0;if(e==null){at.setState(n=>({...n,numberOfProductsInCart:t}));return}t=_nullishCoalesce(_optionalChain([e, 'access', _350 => _350.products, 'optionalAccess', _351 => _351.reduce, 'call', _352 => _352((n,a)=>n+a.quantity,0)]), () => (0)),at.setState(n=>({...n,numberOfProductsInCart:t}))}var Qs=200,Xs= exports.m ="item-ids-not-found",Pt="internal-error",ea={"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"},el=new Set(["internal","invalid-request"]),tl=new Set(["product-not-available","product-not-found"]);function rl(e){return typeof e=="string"&&Object.hasOwn(ea,e)?ea[e]:void 0}function nl(e){return/<\/?[a-z!?][^>]*>/i.test(e)}function ol(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 al(e){return/Error:/.test(e)||/\n\s+at /.test(e)}function Gr(e){let t=e.trim();if(!(t.length===0||t.length>Qs||/[\r\n]/.test(t)||nl(t)||ol(t)||al(t)))return t}var il=3;function $t(e,t=0){if(typeof e=="object"&&e!=null){if(Array.isArray(e)||t>=il)return{};let n=e,a=$t(n.error,t+1);if(a.message==null&&n.message!=null){let r=$t(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?$t(n,t+1):{}}catch (e29){}return{message:Gr(e)}}function sl(e){let t;try{t=JSON.parse(e)}catch (e30){return{code:Pt,message:Gr(e)}}if(typeof t=="string")return{code:Pt,message:Gr(t)};if(typeof t!="object"||t==null)return{code:Pt};let n=t,{message:a,code:r}=$t(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 Vr(e,t){let{code:n,message:a,itemIds:r}=sl(t),o=r!=null&&r.length>0;if(o&&(n===Pt||tl.has(n)))return B(Xs,"badInput",r);let i={message:a};return o&&(i.itemIds=r),B(n,e>=500?"internal":"badInput",i)}function wm(e,t){let n=rl(e.error);if(n!=null)return t(n);if(e.type==="internal"||typeof e.error=="string"&&el.has(e.error))return t("checkoutFailed");let a=_optionalChain([e, 'access', _353 => _353.data, 'optionalAccess', _354 => _354.message]);return typeof a=="string"&&a.length>0?a:t("checkoutFailed")}var ll=["online","manual","cod"],dl=["bankTransfer","blik"];function ta(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 cl(e){if(typeof e!="object"||e==null)return null;let t=e.choice;if(typeof t!="object"||t==null)return null;let n=ta(t.methods,ll);return n.length<2?null:{methods:n,manualAccountTypes:ta(t.manualAccountTypes,dl)}}function Nm(e){if(e==null)return null;let t=e.methods.filter(n=>n!=="cod");return t.length<2?null:{...e,methods:t}}function Im(e,t){return t!=null&&e.methods.includes(t)?t:e.methods[0]}function Sm(e){let t=e.includes("bankTransfer"),n=e.includes("blik");return n&&!t?"paymentMethodManualBlik":t&&!n?"paymentMethodManualTransfer":"paymentMethodManualBoth"}async function ra(e,t,n=5e3){let a=typeof AbortController>"u"?void 0:new AbortController,r=setTimeout(()=>_optionalChain([a, 'optionalAccess', _355 => _355.abort, 'call', _356 => _356()]),n);try{let o=await fetch(e,{method:"POST",headers:t.headers,body:t.body,signal:_optionalChain([a, 'optionalAccess', _357 => _357.signal])});return o.ok?cl(await o.json()):null}catch (e31){return null}finally{clearTimeout(r)}}var ul;(a=>{async function e(r,o=1,i,d){let c=st();if(c==null)throw new Error("No project ID found");let f=await Kr(c).addProduct({productID:r,quantity:o,metadata:i,...d});if(f!=null)return f}a.addProductToCart=e;function t(){at.setState({isCartVisible:!0})}a.showCart=t;function n(){at.setState({isCartVisible:!1})}a.hideCart=n})(ul = exports.s||={});async function na(e){try{return await e.text()}catch (e32){return""}}function oa(e,t){return t=$r(t),t.locale??=_chunkQ337IQNAjs.f.call(void 0, ),{headers:{..._chunk6DEKVABTjs.a,..._chunkEK3D44XWjs.h.call(void 0, e),"Content-Type":"application/json"},body:JSON.stringify(t)}}async function Jo(e){let t=st();return t==null?null:ra(ot(t,"/payment-methods"),oa(t,e))}async function Hr(e){let t=st();if(t==null)throw new Error("No project ID found");let n=await fetch(ot(t,"/buy"),{method:"POST",...oa(t,e)});if(n.status!=200){let r=Vr(n.status,await na(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 _m(e){let t=st();if(t==null)throw new Error("No project ID found");let n={..._chunk6DEKVABTjs.a,..._chunkEK3D44XWjs.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??=_chunkQ337IQNAjs.f.call(void 0, );let r=await fetch(_chunk6DEKVABTjs.e+a,{method:"POST",headers:n,body:JSON.stringify(e)});return r.ok?{status:"ok",redirectURL:(await r.json()).url}:{...Vr(r.status,await na(r)),status:"error"}}function Ht(){if(typeof localStorage>"u")return;let e=localStorage.getItem("bitsnap-ref");if(e!=null)return e}function $r(e){let t=Ht();return t==null||(e.metadata==null&&(e.metadata={}),e.metadata.ref=t),e}exports.a = me; exports.b = Re; exports.c = je; exports.d = Fe; exports.e = De; exports.f = Fn; exports.g = gt; exports.h = yt; exports.i = Ze; exports.j = Qe; exports.k = Sa; exports.l = Ue; exports.m = Xs; exports.n = wm; exports.o = Nm; exports.p = Im; exports.q = Sm; exports.r = at; exports.s = ul; exports.t = Jo; exports.u = Hr; exports.v = _m; exports.w = Ht; exports.x = $r; exports.y = Tp; exports.z = Ap; exports.A = Rp; exports.B = j; exports.C = Ro; exports.D = Or; exports.E = Op; exports.F = Mr; exports.G = gs; exports.H = zs; exports.I = qr; exports.J = sm; exports.K = st; exports.L = lm; exports.M = dm; exports.N = $s; exports.O = cm; exports.P = um; exports.Q = Vs; exports.R = pm; exports.S = mm; exports.T = fm; exports.U = gm; exports.V = ym; exports.W = hm; exports.X = bm; exports.Y = Yo; exports.Z = Kr;
5
+ //# sourceMappingURL=chunk-TWZQ4CBY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react-panel-key/dist/chunk-TWZQ4CBY.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,sDAAyC,sDAA+F,sDAAyC,sDAAyF,sDAAyF,sDAA+E,sDAAyE,sDAAgE,oDCA5uB,+BAC0C,+CCKrE,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;ACQE,YAAA;ACszBN","file":"/home/emems/.t3/worktrees/bitsnap-react-panel-key/dist/chunk-TWZQ4CBY.js","sourcesContent":[null,"import { useAutoAnimate } from \"@formkit/auto-animate/react\";\nimport { useEffect, useMemo, useRef, useState, type CSSProperties } from \"react\";\nimport { TurnstileChallenge } from \"../../captcha/TurnstileChallenge\";\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 [challengeVisible, setChallengeVisible] = useState(false);\n const challengeWaiter = useRef<((token: string | null) => void) | undefined>(undefined);\n const captchaToken = useRef(\"\");\n const beforeSend = useMemo(() => () => new Promise<boolean>((resolve) => {\n setChallengeVisible(true);\n const timer = window.setTimeout(() => { challengeWaiter.current = undefined; setChallengeVisible(false); resolve(false); }, 5 * 60 * 1000);\n challengeWaiter.current = (token) => { window.clearTimeout(timer); challengeWaiter.current = undefined; setChallengeVisible(false); captchaToken.current = token ?? \"\"; resolve(token !== null); };\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, turnstileToken: captchaToken.current });\n captchaToken.current = \"\";\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 beforeSend,\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 {challengeVisible && <TurnstileChallenge action=\"panel_login\" locale={locale} onToken={(token) => challengeWaiter.current?.(token)} onFailure={() => challengeWaiter.current?.(null)} />}\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"]}