bitsnap-react 1.19.0 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/BitsnapCart-V4S4EXYV.js +2 -0
- package/dist/BitsnapCart-V4S4EXYV.js.map +1 -0
- package/dist/BitsnapCart-Z6JFYNH2.mjs +2 -0
- package/dist/CartProvider-5NP4WACK.js +2 -0
- package/dist/CartProvider-5NP4WACK.js.map +1 -0
- package/dist/CartProvider-G7FQUPXL.mjs +2 -0
- package/dist/PanelModelFiles-EKQRLF46.js.map +1 -1
- package/dist/analytics.js +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/analytics.mjs +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/chat.d.mts +10 -9
- package/dist/chat.d.ts +10 -9
- package/dist/chat.js +1 -1
- package/dist/chat.js.map +1 -1
- package/dist/chat.mjs +1 -1
- package/dist/chat.mjs.map +1 -1
- package/dist/{chunk-WG54EHST.mjs → chunk-2G46TAUX.mjs} +2 -2
- package/dist/chunk-2G46TAUX.mjs.map +1 -0
- package/dist/{chunk-DOJICJCQ.js → chunk-4Y233NII.js} +2 -2
- package/dist/chunk-4Y233NII.js.map +1 -0
- package/dist/chunk-5M3OUOMU.mjs +5 -0
- package/dist/chunk-5M3OUOMU.mjs.map +1 -0
- package/dist/chunk-6Q3VGPSF.js.map +1 -1
- package/dist/{chunk-DDIEFKNP.mjs → chunk-A2ZDFN3J.mjs} +2 -2
- package/dist/{chunk-GJOGATP6.js → chunk-AQYHQY2Y.js} +2 -2
- package/dist/chunk-AQYHQY2Y.js.map +1 -0
- package/dist/{chunk-N523LFAM.mjs → chunk-BTERIY6N.mjs} +2 -2
- package/dist/{chunk-MWWEPEU2.js → chunk-C736F727.js} +2 -2
- package/dist/chunk-C736F727.js.map +1 -0
- package/dist/{chunk-LGPNJ5XE.js → chunk-EFN4OW2C.js} +2 -2
- package/dist/chunk-EFN4OW2C.js.map +1 -0
- package/dist/{chunk-GQ5OKU74.js → chunk-GHBRR665.js} +2 -2
- package/dist/chunk-GHBRR665.js.map +1 -0
- package/dist/chunk-HKRH6FI6.mjs +2 -0
- package/dist/chunk-HKRH6FI6.mjs.map +1 -0
- package/dist/chunk-HP3I6D2R.js +2 -0
- package/dist/chunk-HP3I6D2R.js.map +1 -0
- package/dist/{chunk-D2ASWUXM.js → chunk-IRZJIPUF.js} +2 -2
- package/dist/chunk-IRZJIPUF.js.map +1 -0
- package/dist/{chunk-5M6M7FAR.mjs → chunk-IXQCN7MR.mjs} +2 -2
- package/dist/chunk-IXX6SUMB.mjs +2 -0
- package/dist/chunk-IXX6SUMB.mjs.map +1 -0
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/chunk-KDL35KEI.js +2 -0
- package/dist/chunk-KDL35KEI.js.map +1 -0
- package/dist/{chunk-OR566YJI.mjs → chunk-KO7ZERN5.mjs} +2 -2
- package/dist/chunk-KO7ZERN5.mjs.map +1 -0
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/chunk-KZWCVKLU.js +5 -0
- package/dist/chunk-KZWCVKLU.js.map +1 -0
- package/dist/{chunk-SCEWYZUZ.mjs → chunk-LHNTSQYO.mjs} +2 -2
- package/dist/{chunk-5JRUPLXY.mjs → chunk-LHQEM3CU.mjs} +2 -2
- package/dist/chunk-MDAFPGPA.js.map +1 -1
- package/dist/chunk-Q337IQNA.js.map +1 -1
- package/dist/{chunk-YV2C276H.js → chunk-RJPQMDIQ.js} +2 -2
- package/dist/chunk-RJPQMDIQ.js.map +1 -0
- package/dist/{chunk-SSSF64M7.mjs → chunk-TW25G7XX.mjs} +2 -2
- package/dist/{chunk-SSSF64M7.mjs.map → chunk-TW25G7XX.mjs.map} +1 -1
- package/dist/{chunk-MMLBQHBM.mjs → chunk-URQBHNJK.mjs} +2 -2
- package/dist/chunk-W3RGQYPD.js.map +1 -1
- package/dist/{chunk-2FD2QP4Y.js → chunk-YPA6MMGJ.js} +2 -2
- package/dist/chunk-YPA6MMGJ.js.map +1 -0
- package/dist/chunk-Z3YOJ6NZ.js +2 -0
- package/dist/chunk-Z3YOJ6NZ.js.map +1 -0
- package/dist/consent.js.map +1 -1
- package/dist/course.d.mts +1 -1
- package/dist/course.d.ts +1 -1
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/embed/analytics.js +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.mts +37 -34
- package/dist/index.d.ts +37 -34
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/internal.js.map +1 -1
- package/dist/methods-33CWGKNA.mjs +2 -0
- package/dist/methods-4GB652MQ.js +2 -0
- package/dist/methods-4GB652MQ.js.map +1 -0
- package/dist/model-files-client-P4PORZJ6.js.map +1 -1
- package/dist/models.js.map +1 -1
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/dist/{types-B-sjyZQs.d.mts → types-CjWyHunk.d.mts} +2 -0
- package/dist/{types-iRe6ix2y.d.ts → types-DfqzDP9k.d.ts} +2 -0
- package/dist/viewer3d.js.map +1 -1
- package/dist/viewer3d.mjs +2 -2
- package/dist/{widgets-BVOSj9fU.d.ts → widgets-Bsojw94g.d.ts} +10 -1
- package/dist/{widgets-BT2LN2Nq.d.mts → widgets-u7xMJbsY.d.mts} +10 -1
- package/package.json +2 -2
- package/dist/BitsnapCart-E72W5RRZ.mjs +0 -2
- package/dist/BitsnapCart-Q2HER6GU.js +0 -2
- package/dist/BitsnapCart-Q2HER6GU.js.map +0 -1
- package/dist/CartProvider-677CE2FI.js +0 -2
- package/dist/CartProvider-677CE2FI.js.map +0 -1
- package/dist/CartProvider-YPDOFSYC.mjs +0 -2
- package/dist/chunk-2FD2QP4Y.js.map +0 -1
- package/dist/chunk-AAC576BC.mjs +0 -5
- package/dist/chunk-AAC576BC.mjs.map +0 -1
- package/dist/chunk-AB37DWOK.mjs +0 -2
- package/dist/chunk-AB37DWOK.mjs.map +0 -1
- package/dist/chunk-BUYTK7KM.js +0 -2
- package/dist/chunk-BUYTK7KM.js.map +0 -1
- package/dist/chunk-D2ASWUXM.js.map +0 -1
- package/dist/chunk-DOJICJCQ.js.map +0 -1
- package/dist/chunk-GJOGATP6.js.map +0 -1
- package/dist/chunk-GQ5OKU74.js.map +0 -1
- package/dist/chunk-KHQEDQYF.js +0 -5
- package/dist/chunk-KHQEDQYF.js.map +0 -1
- package/dist/chunk-LGPNJ5XE.js.map +0 -1
- package/dist/chunk-MWWEPEU2.js.map +0 -1
- package/dist/chunk-NWXZ45TV.js +0 -2
- package/dist/chunk-NWXZ45TV.js.map +0 -1
- package/dist/chunk-OR566YJI.mjs.map +0 -1
- package/dist/chunk-WG54EHST.mjs.map +0 -1
- package/dist/chunk-YV2C276H.js.map +0 -1
- package/dist/methods-64D5DD6K.js +0 -2
- package/dist/methods-64D5DD6K.js.map +0 -1
- package/dist/methods-NQA3DFLE.mjs +0 -2
- /package/dist/{BitsnapCart-E72W5RRZ.mjs.map → BitsnapCart-Z6JFYNH2.mjs.map} +0 -0
- /package/dist/{CartProvider-YPDOFSYC.mjs.map → CartProvider-G7FQUPXL.mjs.map} +0 -0
- /package/dist/{chunk-DDIEFKNP.mjs.map → chunk-A2ZDFN3J.mjs.map} +0 -0
- /package/dist/{chunk-N523LFAM.mjs.map → chunk-BTERIY6N.mjs.map} +0 -0
- /package/dist/{chunk-5M6M7FAR.mjs.map → chunk-IXQCN7MR.mjs.map} +0 -0
- /package/dist/{chunk-SCEWYZUZ.mjs.map → chunk-LHNTSQYO.mjs.map} +0 -0
- /package/dist/{chunk-5JRUPLXY.mjs.map → chunk-LHQEM3CU.mjs.map} +0 -0
- /package/dist/{chunk-MMLBQHBM.mjs.map → chunk-URQBHNJK.mjs.map} +0 -0
- /package/dist/{methods-NQA3DFLE.mjs.map → methods-33CWGKNA.mjs.map} +0 -0
package/dist/chunk-KHQEDQYF.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
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 _chunkBUYTK7KMjs = require('./chunk-BUYTK7KM.js');var _chunkNWXZ45TVjs = require('./chunk-NWXZ45TV.js');var _chunk2FD2QP4Yjs = require('./chunk-2FD2QP4Y.js');var _chunkMDAFPGPAjs = require('./chunk-MDAFPGPA.js');var _chunkLGPNJ5XEjs = require('./chunk-LGPNJ5XE.js');var _chunkDOJICJCQjs = require('./chunk-DOJICJCQ.js');var _chunkD2ASWUXMjs = require('./chunk-D2ASWUXM.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:_chunkDOJICJCQjs.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:_chunkDOJICJCQjs.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:_chunkDOJICJCQjs.g.call(void 0, "leading-none font-semibold",e),...t})}function Mn({className:e,...t}){return _jsxruntime.jsx.call(void 0, "div",{"data-slot":"card-description",className:_chunkDOJICJCQjs.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:_chunkDOJICJCQjs.g.call(void 0, "px-6",e),...t})}var _lucidereact = require('lucide-react');var ua="text-muted-foreground text-xs leading-5",pa="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",ma=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 On({login:e,texts:t,allowHaveCode:n=!0,emailPlaceholder:o,emailInputId:r,codeInputId:a,className:i,buttonClassName:d,children:u}){let l=_react3.useId.call(void 0, ),g=_nullishCoalesce(r, () => (`${l}-email`)),b=_nullishCoalesce(a, () => (`${l}-code`)),w=`${l}-notice`,x=`${l}-hint`,{notice:f}=e,c=_optionalChain([f, 'optionalAccess', _2 => _2.kind])==="error",m=e.busy==="send",p=e.busy==="verify",v=e.busy==="resend",z=_chunkDOJICJCQjs.g.call(void 0, "h-11 w-full",d),ee=_optionalChain([f, 'optionalAccess', _3 => _3.kind])==="success",T=_jsxruntime.jsxs.call(void 0, "div",{id:w,className:"min-h-10 text-sm leading-5",children:[_jsxruntime.jsx.call(void 0, "p",{role:"alert",className:"font-medium text-red-700 dark:text-red-400",children:c?f.text:null}),_jsxruntime.jsxs.call(void 0, "p",{role:"status",className:_chunkDOJICJCQjs.g.call(void 0, "flex items-start gap-1.5",ee?"font-medium text-emerald-700 dark:text-emerald-400":"text-foreground"),children:[ee&&_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:f!=null&&!c?f.text:null})]})]}),ce=c&&e.step==="email"&&(f.failure==null||ma.has(f.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, _chunkBUYTK7KMjs.d,{htmlFor:g,children:t.emailLabel}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.l,{id:g,ref:e.emailRef,name:"email",type:"email",autoComplete:"email",inputMode:"email",autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,autoFocus:!0,required:!0,className:_chunkDOJICJCQjs.g.call(void 0, "h-11 text-base disabled:opacity-100 disabled:text-foreground/70",pa),placeholder:_nullishCoalesce(o, () => (t.emailPlaceholder)),value:e.email,disabled:e.isBusy,"aria-invalid":ce?!0:void 0,"aria-describedby":w,onChange:J=>e.setEmail(J.target.value)})]});if(e.step==="email")return _jsxruntime.jsxs.call(void 0, "form",{noValidate:!0,className:_chunkDOJICJCQjs.g.call(void 0, "flex flex-col gap-4",i),onSubmit:J=>{J.preventDefault(),e.sendCode()},children:[Se,oe,T,_jsxruntime.jsxs.call(void 0, _chunk2FD2QP4Yjs.k,{type:"submit",disabled:e.isBusy,"aria-busy":m,className:z,children:[m&&_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.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}"),I=e.dead!=null,ge=I?t.resendNew:e.secondsLeft>0?_chunkBUYTK7KMjs.i.call(void 0, t.resendIn,{seconds:e.secondsLeft}):t.resend;return _jsxruntime.jsxs.call(void 0, "form",{noValidate:!0,className:_chunkDOJICJCQjs.g.call(void 0, "flex flex-col gap-4",i),onSubmit:J=>{J.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:_chunkDOJICJCQjs.g.call(void 0, ur,"-ml-1 shrink-0"),disabled:e.isBusy,onClick:e.changeEmail,children:t.changeEmail})]}),u,_jsxruntime.jsxs.call(void 0, "div",{className:"grid gap-2",children:[_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.d,{htmlFor:b,children:t.codeLabel}),_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.k,{id:b,name:"code",inputRef:e.codeRef,value:e.code,onChange:e.setCode,onComplete:J=>void e.submitCode(J),disabled:e.isBusy||I,invalid:c&&!e.needsEmail,"aria-describedby":`${w} ${x}`}),_jsxruntime.jsxs.call(void 0, "p",{id:x,className:ua,children:[t.validity," ",t.spamHint]})]}),T,_jsxruntime.jsxs.call(void 0, _chunk2FD2QP4Yjs.k,{type:"submit",disabled:e.isBusy||I,"aria-busy":p,className:z,children:[p&&_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.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, _chunk2FD2QP4Yjs.k,{type:"button",variant:I?"default":"outline",disabled:e.isBusy||!I&&e.secondsLeft>0,"aria-busy":v,className:I?z:"h-11 w-full",onClick:()=>void e.resend(),children:[v&&_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.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 12:return"deliveryFailed";case 11:return"deliveryUnavailable";default:return"unknown"}}var fa={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 Un(e=_chunkQ337IQNAjs.f.call(void 0, ),t){return{..._chunkBUYTK7KMjs.h.call(void 0, e,t),..._chunkQ337IQNAjs.a.call(void 0, fa,e),...ga(t,["title","description","codeTitle","codeDescription"])}}function ga(e,t){let n={};for(let o of t){let r=_optionalChain([e, 'optionalAccess', _4 => _4[o]]);r!=null&&(n[o]=r)}return n}var ya="return_url",mr="__return_url",ha="accessToken";function gt(e){let t=new URLSearchParams(e).get(ya);return t?_n(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?_n(e):null}function ba(e,t){return t.some(n=>{if(e===n)return!0;let o=new URL(n).hostname,r=new URL(e).hostname;return r.endsWith(`.${o}`)||r===o})}function _n(e){try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"||!ba(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(ha,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 va=({texts:e,projectID:t,host:n,locale:o,logo:r})=>{let a=_chunkD2ASWUXMjs.m.call(void 0, ),{mutateAsync:i}=_chunk2FD2QP4Yjs.g.call(void 0, _chunk2FD2QP4Yjs.e.publicApi.userPanelLogin),{mutateAsync:d}=_chunk2FD2QP4Yjs.g.call(void 0, _chunk2FD2QP4Yjs.e.publicApi.userPanelLoginWithCode),u=_react3.useMemo.call(void 0, ()=>({async send(x){try{let f=await i({email:x});return f.result.case==="success"?{ok:!0,retryIn:f.result.value.retryIn||void 0,challengeId:f.result.value.challengeId||void 0}:{ok:!1,kind:pr(f.result.case==="failure"?f.result.value:0)}}catch(f){return{ok:!1,kind:_chunkBUYTK7KMjs.a.call(void 0, f),cause:f}}},async verify({email:x,code:f,challengeId:c}){try{let m=await d({code:parseInt(f,10),email:x,challengeId:c});return m.result.case==="accessToken"&&m.result.value?{ok:!0,value:{accessToken:m.result.value}}:{ok:!1,kind:pr(m.result.case==="failure"?m.result.value:0)}}catch(m){return{ok:!1,kind:_chunkBUYTK7KMjs.a.call(void 0, m),cause:m}}}}),[i,d]),l=_chunkBUYTK7KMjs.j.call(void 0, {adapter:u,texts:e,storageKey:_chunkBUYTK7KMjs.f.call(void 0, "panel",t,n),onVerified:({accessToken:x},f)=>{a.track("panel_login",{}),_chunkMDAFPGPAjs.j.call(void 0, t,x,f,n);let c=typeof window<"u"?Ze():null;setTimeout(()=>{if(c){window.location.href=Qe(c,x);return}window.location.reload()},100)}}),g=l.step==="code",b=g&&!l.needsEmail?e.codeTitle:e.title,w=g&&!l.needsEmail?e.codeDescription:e.description;return _jsxruntime.jsx.call(void 0, "main",{className:"mx-auto flex w-full max-w-sm flex-1 flex-col justify-start pt-4 sm:pt-[12vh]",children:_jsxruntime.jsxs.call(void 0, Re,{children:[_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.c,{projectId:t,locale:o,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:b}),_jsxruntime.jsx.call(void 0, Mn,{children:w})]}),_jsxruntime.jsx.call(void 0, De,{className:"px-4 sm:px-6",children:_jsxruntime.jsx.call(void 0, On,{login:l,texts:e,emailInputId:"email",codeInputId:"verify-code"})})]})})},ka=({analytics:e,texts:t,locale:n,showLogo:o,logoUrl:r,logoDarkUrl:a})=>{let{theme:i,allowedReturnOrigins:d,projectID:u,host:l}=_chunkNWXZ45TVjs.b.call(void 0, ),g=_chunkD2ASWUXMjs.n.call(void 0, u,e,"panel"),b=_react3.useMemo.call(void 0, ()=>Un(_nullishCoalesce(n, () => (_chunkQ337IQNAjs.f.call(void 0, ))),t),[n,t]),w={"--button-background-color":_nullishCoalesce(_optionalChain([i, 'optionalAccess', _5 => _5.colors, 'optionalAccess', _6 => _6.brand]), () => ("#FFFFFF")),"--button-background-color-dark":_nullishCoalesce(_optionalChain([i, 'optionalAccess', _7 => _7.colors, 'optionalAccess', _8 => _8.brandDark]), () => ("#000000")),"--button-text-color":_nullishCoalesce(_optionalChain([i, 'optionalAccess', _9 => _9.colors, 'optionalAccess', _10 => _10.brandDark]), () => ("#000000")),"--button-text-color-dark":_nullishCoalesce(_optionalChain([i, 'optionalAccess', _11 => _11.colors, 'optionalAccess', _12 => _12.brand]), () => ("#FFFFFF"))},[x]=_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, u,l)!=null&&(window.location.href=window.location.href.replaceAll("login",""))},[u,l]),_react3.useEffect.call(void 0, ()=>{if(typeof window>"u"||window.parent!==window)return;let f=gt(window.location.search);f&&yt(f);let c=_nullishCoalesce(f, () => (Ze()));if(!c)return;let m=_chunkMDAFPGPAjs.i.call(void 0, u,l);m&&(window.location.href=Qe(c,m))},[d,u,l]),_jsxruntime.jsx.call(void 0, _chunkD2ASWUXMjs.l,{value:g,children:_jsxruntime.jsx.call(void 0, "div",{className:"bg-white text-black dark:bg-black dark:text-white",children:_jsxruntime.jsx.call(void 0, "div",{className:"font-inter flex min-h-screen w-full flex-col p-4",style:w,ref:x,children:_jsxruntime.jsx.call(void 0, va,{texts:b,projectID:u,host:l,locale:n,logo:{showLogo:o,logoUrl:_nullishCoalesce(r, () => (_optionalChain([i, 'optionalAccess', _13 => _13.logoURL]))),logoDarkUrl:_nullishCoalesce(a, () => (_optionalChain([i, 'optionalAccess', _14 => _14.logoDarkURL])))}})})})})},xa= exports.k =(e={})=>_jsxruntime.jsx.call(void 0, ka,{...e});function qn(e){let[t,n]=_react3.useState.call(void 0, ()=>{if(typeof window>"u")return e;let r=new URLSearchParams(window.location.search),a={};return Object.keys(e).forEach(i=>{let d=r.get(i);if(d!==null)try{a[i]=JSON.parse(d)}catch (e3){a[i]=d}}),{...e,...a}}),o=_react3.useCallback.call(void 0, r=>{n(a=>{let i={...a,...r};if(typeof window<"u"){let d=new URLSearchParams;Object.keys(i).forEach(l=>{let g=i[l];g!=null&&d.set(l,JSON.stringify(g))});let u=`${window.location.pathname}?${d.toString()}`;window.history.pushState({},"",u)}return i})},[]);return _react3.useEffect.call(void 0, ()=>{let r=()=>{let a=new URLSearchParams(window.location.search),i={};Object.keys(e).forEach(d=>{let u=a.get(d);if(u!==null)try{i[d]=JSON.parse(u)}catch (e4){i[d]=u}}),n({...e,...i})};return window.addEventListener("popstate",r),()=>window.removeEventListener("popstate",r)},[e]),[t,o]}function Hn(e,t){if(e!=null)return e;let n=_optionalChain([t, 'optionalAccess', _15 => _15.trim, 'call', _16 => _16()]);if(!(n==null||n===""))return{tokens:_chunk2FD2QP4Yjs.n.call(void 0, n)}}var Ia={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, Ia,e)}function fr({}){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 La=e=>new Date(e*1e3).toLocaleDateString(_chunkQ337IQNAjs.f.call(void 0, ),{year:"numeric",month:"short",day:"numeric"}),Ta=(e,t)=>new Intl.NumberFormat(_chunkQ337IQNAjs.f.call(void 0, ),{style:"currency",currency:t.toUpperCase()}).format(e/100),Aa={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 Ra({openOrderDetails:e,projectID:t,accessToken:n}){let o=pe(),r={draft:o.statusDraft,unpaid:o.statusUnpaid,paid:o.statusPaid,overdue:o.statusOverdue,cancelled:o.statusCancelled,completed:o.statusCompleted,processing:o.statusProcessing,refunded:o.statusRefunded},[a,i]=_react3.useState.call(void 0, 0),d=20,{data:u,isFetching:l,isError:g,refetch:b}=_chunk2FD2QP4Yjs.f.call(void 0, _chunk2FD2QP4Yjs.e.publicApi.getOrders,{projectId:t,accessToken:n,offset:a,limit:d}),w=_nullishCoalesce(_optionalChain([u, 'optionalAccess', _17 => _17.orders]), () => ([])),x=_nullishCoalesce(_optionalChain([u, 'optionalAccess', _18 => _18.totalCount]), () => (0)),f=Math.floor(a/d)+1,c=Math.ceil(x/d),m=p=>{i(p)};return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-2xl",children:o.ordersHeading}),_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-500 dark:text-neutral-400",children:o.ordersDescription}),l?_jsxruntime.jsx.call(void 0, "div",{className:"mt-6 flex w-full flex-col gap-3",children:[...Array(5)].map((p,v)=>_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, _chunk2FD2QP4Yjs.o,{className:"h-4 w-24"}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.o,{className:"h-3 w-32"})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"space-y-2 text-right",children:[_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.o,{className:"ml-auto h-4 w-16"}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.o,{className:"ml-auto h-3 w-12"})]})]}),_jsxruntime.jsx.call(void 0, "div",{className:"mt-3",children:_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.o,{className:"h-3 w-40"})})]},v))}):g?_jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:"mt-6 space-y-3",children:[_jsxruntime.jsx.call(void 0, "p",{children:o.ordersError}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.k,{onClick:()=>void b(),className:"min-h-11 focus-visible:outline-2 focus-visible:outline-current",children:o.retry})]}):w.length===0?_jsxruntime.jsx.call(void 0, "div",{className:"mt-6 text-sm text-neutral-600 dark:text-neutral-400",children:o.ordersEmpty}):_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "div",{className:"mt-6 flex w-full flex-col gap-3",children:w.map(p=>_jsxruntime.jsxs.call(void 0, "button",{onClick:()=>e(p.id),className:"block min-h-11 focus-visible:outline-2 focus-visible:outline-current rounded-xl bg-white p-4 text-left shadow-sm transition-colors hover:bg-neutral-50 dark:bg-neutral-800 dark:hover:bg-neutral-700",children:[_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-center justify-between gap-3",children:[_jsxruntime.jsxs.call(void 0, "div",{className:"min-w-0 break-words",children:[_jsxruntime.jsxs.call(void 0, "p",{className:"font-medium",children:[o.orderLabel," #",p.id]}),_jsxruntime.jsx.call(void 0, "p",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:p.customerName||o.customerLabel})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"shrink-0 text-right",children:[_jsxruntime.jsx.call(void 0, "p",{className:"font-semibold",children:Ta(p.totalAmount,p.currency)}),_jsxruntime.jsx.call(void 0, "p",{className:`text-xs font-medium ${_nullishCoalesce(Aa[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:[o.dateLabel,":"," ",p.createdAt?La(Number(p.createdAt.seconds)):"-"]})})]},p.id))}),f>=c&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-6 text-center text-sm text-neutral-600 dark:text-neutral-400",children:o.ordersEnd}),c>1&&_jsxruntime.jsxs.call(void 0, "nav",{"aria-label":o.paginationLabel,className:"mt-4 flex flex-wrap items-center justify-center gap-2",children:[f>1&&_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.k,{variant:"outline",className:"min-h-11",onClick:()=>m(a-d),children:o.previousPage}),Array.from(new Set([1,f-1,f,f+1,c])).filter(p=>p>0&&p<=c).sort((p,v)=>p-v).map(p=>_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.k,{variant:p===f?"secondary":"ghost",className:"min-h-11 min-w-11","aria-current":p===f?"page":void 0,onClick:()=>m((p-1)*d),children:p},p)),f<c&&_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.k,{variant:"outline",className:"min-h-11",onClick:()=>m(a+d),children:o.nextPage})]})]})]})}var Bn=Ra;function gr({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 Ua(e,t,n,o){typeof window>"u"||(t&&_chunkMDAFPGPAjs.l.call(void 0, n,o),window.location.href=e)}function _a({projectID:e,host:t,loginURL:n,screen:o,params:r,setParams:a,setActiveScreen:i}){let{status:d,exchangeError:u}=_chunkBUYTK7KMjs.t.call(void 0, "PanelReturns"),l=_chunkBUYTK7KMjs.r.call(void 0, ),g=d==="anonymous"&&(u==null||_chunkBUYTK7KMjs.p.call(void 0, u));_react3.useEffect.call(void 0, ()=>{g&&Ua(n,u!=null,e,t)},[g,n,u,e,t]);let[b,w]=_react3.useState.call(void 0, "orders"),[x,f]=_react3.useState.call(void 0, {items:[],note:""}),[c,m]=_react3.useState.call(void 0, );if(d==="anonymous"&&!g)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(_chunkBUYTK7KMjs.q.call(void 0, u))}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.k,{type:"button",onClick:()=>window.location.reload(),children:l("errorRetry")})]});if(d!=="authenticated")return _jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.C,{});let p=v=>{w(v),a({state:"returns",orderId:void 0,returnId:void 0}),i("returns")};if(o==="return-details"&&r.returnId)return _jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.K,{returnId:r.returnId,onBack:()=>p("myReturns")});if(b==="myReturns")return _jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.J,{onBack:()=>p("orders"),onSelectReturn:v=>{a({state:"return-details",returnId:v,orderId:void 0}),i("return-details")}});if(b==="result"&&c!=null)return _jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.I,{returnId:c,onContinue:()=>p("orders"),onOpenMyReturns:()=>p("myReturns")});if(r.orderId){let v=r.orderId;return b==="confirmation"?_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.H,{orderId:v,items:x.items,note:x.note,onBack:()=>w("orders"),onSubmitted:z=>{m(z),f({items:[],note:""}),w("result"),a({orderId:void 0})}}):_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.G,{orderId:v,initialItems:x.items.length>0?x.items:void 0,initialNote:x.note,onBack:()=>{f({items:[],note:""}),a({orderId:void 0})},onContinue:z=>{f(z),w("confirmation")}})}return _jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.F,{showLogout:!1,onSelectOrder:v=>{f({items:[],note:""}),w("orders"),a({orderId:v})},onOpenMyReturns:()=>p("myReturns")})}function hr({accessToken:e,appearance:t,texts:n,...o}){return _jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.u,{projectID:o.projectID,host:o.host,appearance:t,texts:n,panelAccessToken:e,children:_jsxruntime.jsx.call(void 0, _a,{...o})})}var ja={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"},Fa={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")?Fa:ja}var qa=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g,Ha=e=>[...e.matchAll(qa)].map(n=>({url:n[0],startIndex:n.index,endIndex:n.index+n[0].length-1})),$a=(e,t)=>{let n="",o=0;t.sort((r,a)=>r.startIndex-a.startIndex);for(let{startIndex:r,endIndex:a,replacementText:i}of t)n+=e.slice(o,r),n+=i,o=a+1;return n+=e.slice(o),n},Gn=e=>{let t=Ha(e);return _jsxruntime.jsx.call(void 0, "p",{dangerouslySetInnerHTML:{__html:$a(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 Ka(){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=Ka;var Wa=[401,403],Vn="networkError",Wn="mediaError";function Ya(e,t){if(e==null||e.fatal!==!0)return{action:"ignore"};let n=_optionalChain([e, 'access', _19 => _19.response, 'optionalAccess', _20 => _20.code]),o=e.type===Vn?"network":e.type===Wn?"media":"unknown",r=n==null?{kind:o}:{kind:o,status:n};return n!=null&&Wa.includes(n)?{action:"expired",error:{kind:"network",status:n}}:e.type===Vn&&!t.network?{action:"restart-load"}:e.type===Wn&&!t.media?{action:"recover-media"}:{action:"fail",error:r}}function Yn(e){let t=_nullishCoalesce(e.HlsCtor, () => (_hlsjs2.default)),n=new t,o,r=!1,a=!1;return n.attachMedia(e.media),n.on(t.Events.ERROR,(i,d)=>{let u=Ya(d,{network:r,media:a});switch(u.action){case"expired":_optionalChain([e, 'access', _21 => _21.handlers, 'optionalAccess', _22 => _22.onExpiredUrl, 'optionalCall', _23 => _23()]),_optionalChain([e, 'access', _24 => _24.handlers, 'optionalAccess', _25 => _25.onError, 'optionalCall', _26 => _26(u.error)]);break;case"restart-load":r=!0,n.startLoad();break;case"recover-media":a=!0,n.recoverMediaError();break;case"fail":_optionalChain([e, 'access', _27 => _27.handlers, 'optionalAccess', _28 => _28.onError, 'optionalCall', _29 => _29(u.error)]);break;case"ignore":break}}),{load(i){o=i,r=!1,a=!1,n.loadSource(i)},retry(){o!=null&&(r=!1,a=!1,n.loadSource(o))},destroy(){n.destroy()},get src(){return o}}}function Jn(e){try{return e.canPlayType("application/vnd.apple.mpegurl")!==""}catch (e5){return!1}}function Zn(e){switch(_optionalChain([e, 'optionalAccess', _30 => _30.code])){case 2:return{kind:"network"};case 3:case 4:return{kind:"media"};default:return{kind:"unknown"}}}var Ja={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",avif:"image/avif",svg:"image/svg+xml"},Pr="512x512";function et(){return typeof navigator<"u"&&typeof navigator.mediaSession<"u"}function Za(e){if(typeof e!="string"||e.length===0)return{src:e,sizes:Pr};let t=e.split(/[?#]/)[0],n=t.includes(".")?t.slice(t.lastIndexOf(".")+1).toLowerCase():"",o=Ja[n],r={src:e,sizes:Pr};return o!=null&&(r.type=o),r}function Qa(e){if(e==null)return;let t=Array.isArray(e)?e:[e],n=[];for(let o of t){if(typeof o=="string"){o.length>0&&n.push(Za(o));continue}o!=null&&o.src.length>0&&n.push({src:o.src,sizes:_nullishCoalesce(o.sizes, () => (Pr)),...o.type!=null?{type:o.type}:{}})}return n.length>0?n:void 0}function vr(e){!et()||typeof MediaMetadata>"u"||(navigator.mediaSession.metadata=new MediaMetadata({title:e.title,album:e.album,artist:e.artist,artwork:Qa(e.artwork)}))}function Qn(){et()&&(navigator.mediaSession.playbackState="playing")}function Xn(){et()&&(navigator.mediaSession.playbackState="paused")}function eo(e,t,n=1){if(!et()||e==null||!Number.isFinite(e)||e<=0||t!=null&&isNaN(t))return;let o=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:o})}catch (e6){}}var to=["play","pause","stop","seekbackward","seekforward","seekto","previoustrack","nexttrack"];function ro(e){if(et()){vr({title:e.title,album:e.album,artist:e.artist,artwork:e.artwork});for(let t of to)try{navigator.mediaSession.setActionHandler(t,n=>{e.action(n)})}catch (e7){}}}function no(){if(et()){navigator.mediaSession.metadata=null;for(let e of to)try{navigator.mediaSession.setActionHandler(e,null)}catch (e8){}}}var ti={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"},ri={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")?ri:ti}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 W={get(e){try{return localStorage.getItem(e)}catch (e10){return null}},set(e,t){try{localStorage.setItem(e,t)}catch (e11){}},remove(e){try{localStorage.removeItem(e)}catch (e12){}}},kr="__player__speed",Dt=[.75,1,1.25,1.5,1.75,2];var ui=_react3.forwardRef.call(void 0, ({chapters:e,locale:t,styles:n,updateCurrentTime:o,setCurrentTimeHandler:r,title:a,imageURL:i,coverShownBeside:d,author:u,uniqueProductID:l,onChapterChange:g,onError:b,onExpiredUrl:w,onFinished:x},f)=>{let c=Rt(t),[m,p]=_react3.useState.call(void 0, 1),v=_react3.useRef.call(void 0, 1),[z,ee]=_react3.useState.call(void 0, ),[T,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 I(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),v.current=s,W.set(kr,String(s)),U.current&&(U.current.playbackRate=s),B())}_react3.useEffect.call(void 0, ()=>{let s=Number(W.get(kr));Dt.includes(s)&&ge(s);let h=setInterval(()=>{let{mode:k,deadline:A}=te.current;if(k==="off"||k==="chapter")return;let Pe=Math.max(0,Math.ceil((A-Date.now())/1e3));oe(Pe),Pe===0&&(ze.current=!1,xt(),fe())},1e3);return()=>clearInterval(h)},[]);let J;(k=>(k[k.Playing=0]="Playing",k[k.Paused=1]="Paused"))(J||={});let[_e,lt]=_react3.useState.call(void 0, 1),[Bt,Ee]=_react3.useState.call(void 0, void 0),[C,ye]=_react3.useState.call(void 0, void 0),[Be,ue]=_react3.useState.call(void 0, !1),[vt,Kr]=_react3.useState.call(void 0, null),U=_react3.useRef.call(void 0, null),he=_react3.useRef.call(void 0, null),kt=_react3.useRef.call(void 0, void 0),ta=_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),Gr=_react3.useRef.call(void 0, null),ne=_react3.useRef.call(void 0, {onChapterChange:g,onError:b,onExpiredUrl:w,onFinished:x,updateCurrentTime:o,title:a,imageURL:i,author:u});ne.current={onChapterChange:g,onError:b,onExpiredUrl:w,onFinished:x,updateCurrentTime:o,title:a,imageURL:i,author:u};function Wt(s){!Ke.current||!Number.isFinite(s)||s<0||W.set(`__player__${l}_${_optionalChain([re, 'access', _31 => _31.current, 'optionalAccess', _32 => _32.id])}`,`${Math.floor(s)}`)}function ra(){let s=W.get(`__player__${l}_${_optionalChain([re, 'access', _33 => _33.current, 'optionalAccess', _34 => _34.id])}`);if(s!=null)try{let h=parseInt(s);return isNaN(h)||h<0?void 0:h}catch (e13){return}}function na(){let s=W.get(`__player__${l}_last_chapter`);if(s!=null)return s}function Vr(s){W.set(`__player__${l}_last_chapter`,s)}function Wr(s){W.remove(`__player__${l}_${s}`)}function Yt(s){vr({title:_nullishCoalesce(_nullishCoalesce(_optionalChain([s, 'optionalAccess', _35 => _35.name]), () => (ne.current.title)), () => ("")),album:ne.current.title,artist:ne.current.author,artwork:ne.current.imageURL})}function Yr(s){Kt.current=s,Kr(s),ue(!1),_optionalChain([ne, 'access', _36 => _36.current, 'access', _37 => _37.onError, 'optionalCall', _38 => _38(s)])}function Jr(){Kt.current=null,Kr(null)}function Zr(){let s=U.current;if(s==null)return;let h=s.play();h!=null&&typeof h.catch=="function"&&h.catch(()=>{}),B()}function Qr(){Zr()}function xt(){_optionalChain([U, 'access', _39 => _39.current, 'optionalAccess', _40 => _40.pause, 'call', _41 => _41()]),B()}function oa(){if(_e===0){xt();return}Qr()}function Le(s){let h=U.current;if(h==null||!Number.isFinite(s))return;let k=Number.isFinite(h.duration)?h.duration:0,A=k>0?Math.min(Math.max(s,0),k):Math.max(s,0);Ee(A),h.currentTime=A,B()}function wt(s){let h=U.current;if(h==null)return;let k=Number.isFinite(h.duration)?h.duration:void 0,A=Math.max(h.currentTime+s,0);k!=null&&A>k&&(A=k),Le(A)}function Jt(s){let h=U.current;if(h!=null){if(Jr(),ue(!0),Jn(h)){Zt(),h.src=s,h.load();return}if(_hlsjs2.default.isSupported()){he.current==null&&(he.current=Yn({media:h,handlers:{onError:k=>{Yr(k)},onExpiredUrl:()=>{_optionalChain([ne, 'access', _42 => _42.current, 'access', _43 => _43.onExpiredUrl, 'optionalCall', _44 => _44()])}}})),he.current.load(s);return}Zt(),h.src=s,h.load()}}function Zt(){_optionalChain([he, 'access', _45 => _45.current, 'optionalAccess', _46 => _46.destroy, 'call', _47 => _47()]),he.current=null}function Ct(s,h){let k=_optionalChain([h, 'optionalAccess', _48 => _48.play])===!0;re.current&&U.current&&!U.current.ended&&Wt(U.current.currentTime),Ke.current=!1,dt.current=null,ze.current=k,re.current=s,ee(s.id),Ee(0),ye(s.duration),Jt(s.publicUrl),Yt(s),_optionalChain([ne, 'access', _49 => _49.current, 'access', _50 => _50.onChapterChange, 'optionalCall', _51 => _51(s)]),Vr(s.id)}function Qt(s){if(s.length===0)return;let h=na(),k=_nullishCoalesce((h!=null?s.find(A=>A.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 A=k+1;if(A>=s.length){aa(h);return}Ct(s[A],{play:!0})}function Xr(){let s=Vt.current,h=re.current;if(h==null)return;let k=U.current;if(k!=null&&k.currentTime>3){Le(0);return}let A=s==null?-1:s.findIndex(Pe=>Pe.id===h.id);if(A>0){Ct(s[A-1],{play:!0});return}Le(0)}function aa(s){Wr(s.id),ze.current=!1,_optionalChain([U, 'access', _52 => _52.current, 'optionalAccess', _53 => _53.pause, 'call', _54 => _54()]),lt(1),_optionalChain([ne, 'access', _55 => _55.current, 'access', _56 => _56.onFinished, 'optionalCall', _57 => _57()])}function en(){let s=re.current;if(s!=null){if(W.set(`__player__${l}_${s.id}_completed`,"true"),Wr(s.id),te.current.mode==="chapter"){ze.current=!1,xt(),fe();return}Xt(),B()}}function tn(){let s=U.current;if(s!=null){if(ue(!1),s.playbackRate=v.current,Gt.current=null,!Ke.current){Ke.current=!0;let h=dt.current;if(dt.current=null,h!=null)Le(h);else{let k=ra();k!=null&&Le(k)}}ze.current&&(ze.current=!1,Zr())}}function rn(){let s=_optionalChain([U, 'access', _58 => _58.current, 'optionalAccess', _59 => _59.error]),h=_optionalChain([re, 'access', _60 => _60.current, 'optionalAccess', _61 => _61.publicUrl]);(_optionalChain([s, 'optionalAccess', _62 => _62.code])===2||_optionalChain([s, 'optionalAccess', _63 => _63.code])===4)&&he.current==null&&h!=null&&Gt.current!==h&&(Gt.current=h,_optionalChain([ne, 'access', _64 => _64.current, 'access', _65 => _65.onExpiredUrl, 'optionalCall', _66 => _66()])),Yr(Zn(s))}function nn(){let h=_nullishCoalesce(_optionalChain([re, 'access', _67 => _67.current, 'optionalAccess', _68 => _68.publicUrl]), () => (_optionalChain([he, 'access', _69 => _69.current, 'optionalAccess', _70 => _70.src])));if(h==null)return;let A=_nullishCoalesce(_optionalChain([U, 'access', _71 => _71.current, 'optionalAccess', _72 => _72.currentTime]), () => (0));Jr(),Ke.current=!1,dt.current=A>0?A:null,Ee(A),he.current!=null?he.current.retry():Jt(h)}function ia(s){switch(s.action){case"play":Qr();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":Xr();break;case"nexttrack":Xt();break;default:break}}_react3.useImperativeHandle.call(void 0, f,()=>({selectChapter:s=>{Ct(s,{play:!0})},retry:nn,getError:()=>Kt.current}));function B(){let s=U.current;s!=null&&(lt(s.paused?1:0),ye(s.duration),Ee(s.currentTime),s.ended||Wt(s.currentTime),eo(s.duration,s.currentTime,s.playbackRate),s.networkState===s.NETWORK_LOADING&&s.readyState<=s.HAVE_FUTURE_DATA?ue(!0):ue(!1),_optionalChain([ne, 'access', _73 => _73.current, 'access', _74 => _74.updateCurrentTime, 'optionalCall', _75 => _75(s.currentTime)]))}_react3.useEffect.call(void 0, ()=>(ro({title:_nullishCoalesce(a, () => ("")),album:a,artist:u,artwork:i,action:ia}),()=>{no()}),[]),_react3.useEffect.call(void 0, ()=>{Yt(re.current)},[a,u,i]),_react3.useEffect.call(void 0, ()=>{let s=U.current;if(s!=null)return s.addEventListener("loadeddata",tn),s.addEventListener("ended",en),s.addEventListener("error",rn),s.addEventListener("timeupdate",B),s.addEventListener("play",B),s.addEventListener("pause",B),s.addEventListener("ratechange",B),B(),kt.current=setInterval(B,500),()=>{s.removeEventListener("loadeddata",tn),s.removeEventListener("ended",en),s.removeEventListener("error",rn),s.removeEventListener("timeupdate",B),s.removeEventListener("play",B),s.removeEventListener("pause",B),s.removeEventListener("ratechange",B),kt.current!=null&&(clearInterval(kt.current),kt.current=void 0),s.ended||Wt(s.currentTime),Ee(void 0),s.pause(),Zt(),s.removeAttribute("src"),s.load()}},[]),_react3.useEffect.call(void 0, ()=>{_optionalChain([r, 'optionalCall', _76 => _76(Le)])},[]);let er=e.map(s=>`${s.id}|${_nullishCoalesce(s.publicUrl, () => (""))}`).join(`
|
|
4
|
-
`);_react3.useEffect.call(void 0, ()=>{Vt.current=e;let s=Gr.current;if(s===er)return;if(Gr.current=er,s==null){Qt(e);return}let h=re.current;if(h==null){Qt(e);return}let k=e.find(A=>A.id===h.id);if(!(k!=null&&k.publicUrl===h.publicUrl)){if(k!=null){let A=U.current,Pe=_nullishCoalesce(_optionalChain([A, 'optionalAccess', _77 => _77.currentTime]), () => (0)),la=A!=null&&!A.paused;re.current=k,Ke.current=!1,dt.current=Pe>0?Pe:null,ze.current=la,Jt(k.publicUrl),Yt(k),_optionalChain([ne, 'access', _78 => _78.current, 'access', _79 => _79.onChapterChange, 'optionalCall', _80 => _80(k)]),Vr(k.id);return}Qt(e)}},[er]),_react3.useEffect.call(void 0, ()=>{switch(_e){case 0:Qn();break;case 1:Xn();break}},[_e]);let Ge=e.findIndex(s=>s.id===z),be=Number.isFinite(C)&&C>0?C:_nullishCoalesce(_optionalChain([e, 'access', _81 => _81[Ge], 'optionalAccess', _82 => _82.duration]), () => (0)),ct=Math.min(Math.max(_nullishCoalesce(Bt, () => (0)),0),be||1/0),on=e.length>0&&e.every(s=>Number.isFinite(s.duration)&&s.duration>0),sa=Math.max(0,be-ct+(on?e.slice(Ge+1).reduce((s,h)=>s+h.duration,0):0))/m,tr=Math.ceil(sa/60),an=`${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:ta,"data-player-error":_optionalChain([vt, 'optionalAccess', _83 => _83.kind]),children:[_jsxruntime.jsx.call(void 0, "video",{ref:U,className:"hidden",poster:i,title:a}),_jsxruntime.jsxs.call(void 0, "div",{className:_chunkDOJICJCQjs.g.call(void 0, "flex min-w-0 items-center gap-3",d&&"lg:hidden"),children:[i&&_jsxruntime.jsx.call(void 0, "img",{src:i,alt:"",className:"h-16 w-16 shrink-0 rounded object-contain"}),_jsxruntime.jsxs.call(void 0, "div",{className:"min-w-0 break-words",children:[_jsxruntime.jsx.call(void 0, "p",{className:"font-semibold",children:_nullishCoalesce(_optionalChain([e, 'access', _84 => _84[Ge], 'optionalAccess', _85 => _85.name]), () => (a))}),u&&_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-600 dark:text-neutral-300",children:u})]})]}),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:c.error}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.k,{variant:"outline",onClick:nn,children:c.retry})]}),_jsxruntime.jsx.call(void 0, "input",{type:"range",min:"0",max:be||100,value:ct,disabled:!be,"aria-label":c.progress,"aria-valuetext":`${xe(ct)} ${c.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:[c.left==="left"?`${an} ${c.left}`:`${c.left} ${an}`," ","\xB7 ",on?c.book:c.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, _chunk2FD2QP4Yjs.k,{variant:"outline",onClick:Xr,disabled:Ge<0,"aria-label":c.previous,children:_jsxruntime.jsx.call(void 0, _lucidereact.SkipBack,{className:"h-5 w-5"})}),_jsxruntime.jsxs.call(void 0, _chunk2FD2QP4Yjs.k,{variant:"outline",onClick:()=>wt(-10),"aria-label":c.rewind,children:["\u2212",10]}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.k,{variant:"outline",onClick:oa,"aria-label":_e===1?c.play:c.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, _chunk2FD2QP4Yjs.k,{variant:"outline",onClick:()=>wt(10),"aria-label":c.forward,children:["+",10]}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.k,{variant:"outline",onClick:Xt,disabled:Ge<0||Ge>=e.length-1,"aria-label":c.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:[c.speed,_jsxruntime.jsx.call(void 0, "select",{"aria-label":c.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:[c.sleep,_jsxruntime.jsxs.call(void 0, "select",{"aria-label":c.sleep,value:T,onChange:s=>I(s.target.value),children:[_jsxruntime.jsx.call(void 0, "option",{value:"off",children:c.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:c.end})]})]})]}),T!=="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:T==="chapter"?c.end:xe(Se)}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.k,{variant:"outline",onClick:fe,children:c.cancel})]}),Be&&_jsxruntime.jsx.call(void 0, "div",{role:"status",className:"flex justify-center",children:_jsxruntime.jsx.call(void 0, ke,{})})]})}),oo=ui;function xr({chapters:e,currentID:t,productID:n,onSelect:o,downloadable:r,onDownload:a,loading:i,locale:d}){let u=Rt(d),[l,g]=_react3.useState.call(void 0, null),[b,w]=_react3.useState.call(void 0, []);_react3.useEffect.call(void 0, ()=>{let c=`__player__${n}_`,m=W.get(`${c}last_chapter`),p=Number(m&&W.get(`${c}${m}`));g(m&&p>0&&Number.isFinite(p)?{id:m,time:p}:null),w((_nullishCoalesce(e, () => ([]))).filter(v=>W.get(`${c}${v.id}_completed`)==="true"||Number(W.get(`${c}${v.id}`))>0).map(v=>v.id))},[e,n,t]);let x=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _86 => _86.findIndex, 'call', _87 => _87(c=>c.id===_optionalChain([l, 'optionalAccess', _88 => _88.id]))]), () => (-1)),f=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _89 => _89.findIndex, 'call', _90 => _90(c=>c.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:u.chapters}),i?_jsxruntime.jsx.call(void 0, "p",{role:"status",children:u.loading}):_optionalChain([e, 'optionalAccess', _91 => _91.length])?_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[l&&x>=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:()=>o(e[x]),children:[u.resume,": ",u.chapterName," ",x+1,","," ",xe(l.time)]}),_jsxruntime.jsx.call(void 0, "ul",{className:"flex w-full flex-col gap-2",children:e.map((c,m)=>{let p=c.id===t,v=m<f||b.includes(c.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:()=>o(c),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":u.playing}):v?_jsxruntime.jsx.call(void 0, _lucidereact.Check,{className:"size-4 shrink-0","aria-label":u.played}):null,_jsxruntime.jsx.call(void 0, "span",{className:"min-w-0 flex-1 break-words text-sm font-medium",children:c.name}),!!c.duration&&_jsxruntime.jsx.call(void 0, "span",{className:"shrink-0 text-xs tabular-nums text-neutral-600 dark:text-neutral-300",children:xe(c.duration)})]}),c.description&&_jsxruntime.jsx.call(void 0, "span",{className:"mt-2 block text-xs",children:c.description})]}),r&&c.downloadableUrl&&_jsxruntime.jsx.call(void 0, "a",{href:c.downloadableUrl,onClick:a,"aria-label":`${u.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"})})]},c.id)})})]}):_jsxruntime.jsx.call(void 0, "p",{children:u.empty})]})}function Ce(e,...t){console.warn(e,...t)}function wr(e){console.error(e)}var vi=({accessToken:e,product:t,styles:n,reveal:o})=>{let r=Xe(),a=t.productType,i=_chunkD2ASWUXMjs.m.call(void 0, ),d=()=>i.track("panel_download",{},{product_id:t.productId.length<=64?t.productId:null}),u=_react3.useRef.call(void 0, null),[l]=_react.useAutoAnimate.call(void 0, ),[g,b]=_react3.useState.call(void 0, !1),[w,x]=_react3.useState.call(void 0, null),{mutateAsync:f,isPending:c}=_chunk2FD2QP4Yjs.g.call(void 0, _chunk2FD2QP4Yjs.e.publicApi.userPanelGetFileDetails),m=_react3.useRef.call(void 0, void 0),[p,v]=_react3.useState.call(void 0, null),[z,ee]=_react3.useState.call(void 0, null),[T,ce]=_react3.useState.call(void 0, !1),{mutateAsync:Se,isPending:oe}=_chunk2FD2QP4Yjs.g.call(void 0, _chunk2FD2QP4Yjs.e.publicApi.userPanelGetAudiobookDetails),{mutateAsync:te,isPending:fe}=_chunk2FD2QP4Yjs.g.call(void 0, _chunk2FD2QP4Yjs.e.publicApi.userPanelGetAudiobookDetailsDownloadURLs),[I,ge]=_react3.useState.call(void 0, null),[J,_e]=_react3.useState.call(void 0, null);async function lt(){b(!1);try{let C=await f({accessId:t.accessId,accessToken:e});if(C.result.case==="success"){x(C.result.value.files);return}else b(!0),Ce("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),Ce("Kod b\u0142\u0119du: ",C.result.value)}catch(C){b(!0),Ce("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),wr("B\u0142\u0105d podczas pobierania danych:"+C)}}async function Bt(){try{let C=await Se({accessId:t.accessId,accessToken:e});if(C.result.case==="audiobook"){v(C.result.value);return}else Ce("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),Ce("Kod b\u0142\u0119du: ",C.result.value)}catch(C){Ce("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),wr("B\u0142\u0105d podczas pobierania danych:"+C)}}async function Ee(){try{let C=await te({accessId:t.accessId,accessToken:e,isBrowser:!0});if(C.result.case==="success"){ee(C.result.value.audiobookDownloadDetails),ce(C.result.value.isAvailableToDownloadInMobileApp===!0);return}else Ce("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),Ce("Kod b\u0142\u0119du: ",C.result.value)}catch(C){Ce("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),wr("B\u0142\u0105d podczas pobierania danych:"+C)}}return _react3.useEffect.call(void 0, ()=>{a===2&<(),a===1&&(Bt().then().catch(),Ee().then().catch())},[]),_react3.useEffect.call(void 0, ()=>{if(p!=null&&z!=null){let C=p.chapters;if(!C)return;let ye=C.map(Be=>{let ue=_optionalChain([z, 'optionalAccess', _92 => _92.find, 'call', _93 => _93(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,z]),_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, _chunk2FD2QP4Yjs.k,{onClick:()=>o(),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:[a===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}),c&&_jsxruntime.jsx.call(void 0, "div",{role:"status","aria-label":r.loading,children:_jsxruntime.jsx.call(void 0, ke,{})}),g&&_jsxruntime.jsxs.call(void 0, "div",{role:"alert",children:[_jsxruntime.jsx.call(void 0, "p",{children:r.fileError}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.k,{className:"min-h-11",onClick:lt,children:r.retry})]}),_optionalChain([w, 'optionalAccess', _94 => _94.length])===0&&_jsxruntime.jsx.call(void 0, "p",{children:r.noFiles}),w&&_jsxruntime.jsx.call(void 0, "ul",{className:"flex flex-col gap-3",children:w.map((C,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:lo(C)||`${r.file} ${ye+1}`}),_jsxruntime.jsxs.call(void 0, "a",{target:"_blank",rel:"noopener noreferrer",href:C,download:!0,onClick:d,className:"inline-flex min-h-11 items-center gap-2 rounded-md bg-neutral-900 px-3 py-2 text-sm text-white focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 dark:bg-neutral-100 dark:text-neutral-900","aria-label":`${r.download}: ${lo(C)||`${r.file} ${ye+1}`}`,children:[r.download,_jsxruntime.jsx.call(void 0, _lucidereact.Download,{className:"size-4","aria-hidden":"true"})]})]},C))})]}),a===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})]}),a===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([I, 'optionalAccess', _95 => _95.name]), () => ("Odtwarzacz"))}),_optionalChain([I, 'optionalAccess', _96 => _96.description])&&_jsxruntime.jsx.call(void 0, "p",{className:"text-sm",children:_optionalChain([I, 'optionalAccess', _97 => _97.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:J!=null?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:_jsxruntime.jsx.call(void 0, oo,{ref:u,coverShownBeside:!0,chapters:J,author:typeof _optionalChain([p, 'optionalAccess', _98 => _98.author])=="string"?p.author:void 0,onExpiredUrl:()=>{Ee()},title:_nullishCoalesce(_nullishCoalesce(_optionalChain([p, 'optionalAccess', _99 => _99.name]), () => (t.productName)), () => (void 0)),imageURL:_nullishCoalesce(_nullishCoalesce(_optionalChain([p, 'optionalAccess', _100 => _100.coverImage]), () => (t.productImageUrl)), () => (void 0)),styles:n,setCurrentTimeHandler:C=>{m.current=C},uniqueProductID:t.productId,onChapterChange:C=>{ge(C)}})}):_jsxruntime.jsx.call(void 0, "p",{className:"mt-2",children:"Wybierz rozdzia\u0142, kt\xF3ry ci\u0119 interesuje."})})}),_jsxruntime.jsxs.call(void 0, "div",{className:"rounded-xl bg-neutral-100 p-3 dark:bg-neutral-800",children:[_jsxruntime.jsx.call(void 0, "p",{className:"mt-3 mb-3 text-xs",children:T?"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:a===1&&_jsxruntime.jsx.call(void 0, xr,{chapters:J,currentID:_optionalChain([I, 'optionalAccess', _101 => _101.id]),productID:t.productId,loading:oe,downloadable:_optionalChain([p, 'optionalAccess', _102 => _102.isDownloadable])===!0,onDownload:d,onSelect:C=>_optionalChain([u, 'access', _103 => _103.current, 'optionalAccess', _104 => _104.selectChapter, 'call', _105 => _105(C)])})})]}),_jsxruntime.jsx.call(void 0, "section",{className:"rounded-xl border border-neutral-200 bg-white p-4 dark:border-neutral-700 dark:bg-neutral-900",children:_jsxruntime.jsx.call(void 0, "p",{className:"whitespace-pre-wrap text-sm text-neutral-600 dark:text-neutral-300",children:t.productDescription})})]})]})},co=vi;function lo(e){try{return decodeURIComponent(new URL(e,"https://bitsnap.pl").pathname.split("/").pop()||"")}catch (e14){return""}}var _connectquery = require('@connectrpc/connect-query');function uo(e,t){let n=_connectquery.useTransport.call(void 0, ),[o,r]=_react3.useState.call(void 0, {status:"loading"});return _react3.useEffect.call(void 0, ()=>{if(!e){r({status:"hidden"});return}let a=!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=>{a||r(i)}),()=>{a=!0}},[n,e,t]),o}var Mi=_react3.lazy.call(void 0, ()=>Promise.resolve().then(() => _interopRequireWildcard(require("./PanelModelFiles-EKQRLF46.js")))),Oi=({accessToken:e,projectID:t,loginURL:n,styles:o,activeScreen:r,params:a,setParams:i,openCourse:d,openMessages:u})=>{let{host:l}=_chunkNWXZ45TVjs.b.call(void 0, ),{data:g,isLoading:b,error:w,refetch:x}=_chunk2FD2QP4Yjs.f.call(void 0, _chunk2FD2QP4Yjs.e.publicApi.userPanelGetProducts,{accessToken:e}),f=uo(e,t),c=Ui({products:b?{status:"loading"}:w!=null?{status:"error"}:_optionalChain([g, 'optionalAccess', _106 => _106.result, 'access', _107 => _107.case])==="success"?{status:"ok",count:g.result.value.products.length}:_optionalChain([g, 'optionalAccess', _108 => _108.result, 'access', _109 => _109.case])==="failure"?{status:"failure",unauthorized:g.result.value===9}:{status:"error"},modelFiles:f});if(_react3.useEffect.call(void 0, ()=>{c.kind==="signed-out"&&(_chunkMDAFPGPAjs.l.call(void 0, t,l),window.location.href=n)},[c.kind,t,l,n]),c.kind==="loading"||c.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},(z,ee)=>_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"},ee))});let m=g&&g.result.case==="success"?g.result.value.products:[],p=f.status==="ready"?f.models:[],v=p.length>0?_jsxruntime.jsx.call(void 0, _react3.Suspense,{fallback:null,children:_jsxruntime.jsx.call(void 0, Mi,{accessToken:e,models:p,buttonStyle:o})}):null;return c.kind==="error"?_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, zi,{onRetry:()=>void x()}),v]}):c.kind==="empty"?_jsxruntime.jsx.call(void 0, _i,{}):_jsxruntime.jsx.call(void 0, ji,{accessToken:e,products:m,styles:o,activeScreen:r,params:a,setParams:i,openCourse:d,openMessages:u,filesSection:v})};function Ui({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 _i(){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 zi({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, _chunk2FD2QP4Yjs.k,{type:"button",onClick:e,className:"text-sm",children:t?"Try again":"Spr\xF3buj ponownie"})]})}var fo=Oi;function po(e){return e.productType===5||e.productType===6}var ji=({accessToken:e,products:t,styles:n,filesSection:o,activeScreen:r,params:a,setParams:i,openCourse:d,openMessages:u})=>{let l=Xe(),[g,b]=_react3.useState.call(void 0, ()=>mo(a.product,t));_react3.useEffect.call(void 0, ()=>{b(mo(a.product,t))},[a.product,t]);let w=f=>{b(f),i({product:f?f.accessId||f.productId:void 0,state:"products"})};_react3.useEffect.call(void 0, ()=>{r==="products"&&_optionalChain([g, 'optionalAccess', _110 => _110.productType])===4?d(g.accessId):r==="products"&&g&&po(g)&&u&&u()},[r,g,d,u]);function x(f){if(po(f)&&u){u();return}if(f.productType===4){d(f.accessId);return}w(f)}return r==="products"&&_optionalChain([g, 'optionalAccess', _111 => _111.productType])===4?null:r==="products"&&g!=null?_jsxruntime.jsx.call(void 0, co,{accessToken:e,product:g,styles:n,reveal:w,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(f=>{let[c,m,p]=f.productType===1?[l.audio,l.listen,_lucidereact.Headphones]:f.productType===4?[l.course,l.openCourse,_lucidereact.BookOpen]:f.productType===5?[l.chat,l.openMessages,_lucidereact.MessageCircle]:f.productType===6?[l.community,l.openMessages,_lucidereact.Users]:f.productType===3?[l.ticket,l.showTicket,_lucidereact.Ticket]:[l.files,l.downloadFiles,_lucidereact.Files];return _jsxruntime.jsxs.call(void 0, "button",{type:"button",onClick:()=>x(f),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"}),c]}),_jsxruntime.jsx.call(void 0, "img",{src:f.productImageUrl,alt:f.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:f.productName}),_jsxruntime.jsx.call(void 0, "span",{className:"line-clamp-2 text-sm text-neutral-600 dark:text-neutral-300",children:Gn(f.productDescription)}),_jsxruntime.jsx.call(void 0, "span",{className:"mt-auto pt-2 text-sm font-medium underline underline-offset-4",children:m})]})]},f.accessId||f.productId)})}),o]})};function mo(e,t){if(!e)return;let n=t.find(o=>(o.accessId||o.productId)===e||o.productId===e);if(n)return n;try{let o=_protobuf.fromJsonString.call(void 0, _chunkLGPNJ5XEjs.f,e);return t.find(r=>o.accessId?r.accessId===o.accessId:r.productId===o.productId)}catch (e15){return}}var yo=[{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 ho(e){return e==="course"?"products":e==="order-details"?"orders":e==="return-details"?"returns":e}function Nr({activeScreen:e,setActiveScreen:t,setParams:n,theme:o,logout:r,email:a,projectID:i,showMessages:d=!1}){let u=pe(),{data:l}=_chunkBUYTK7KMjs.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, _chunkBUYTK7KMjs.c,{projectId:i,logoUrl:_optionalChain([o, 'optionalAccess', _112 => _112.logoURL]),logoDarkUrl:_optionalChain([o, 'optionalAccess', _113 => _113.logoDarkURL]),name:_optionalChain([l, 'optionalAccess', _114 => _114.name]),className:"shrink-0"}),_optionalChain([l, 'optionalAccess', _115 => _115.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":u.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:yo.filter(({screen:g})=>g!=="messages"||d).map(({screen:g,label:b,icon:w})=>{let x=ho(e)===g;return _jsxruntime.jsxs.call(void 0, "button",{type:"button","aria-current":x?"page":void 0,onClick:()=>{t(g),n({product:void 0,state:g})},className:_chunkDOJICJCQjs.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",x?"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, w,{className:"h-5 w-5 shrink-0","aria-hidden":"true"}),_jsxruntime.jsx.call(void 0, "span",{children:u[b]})]},g)})}),_jsxruntime.jsxs.call(void 0, "div",{className:"hidden border-t border-neutral-200 pt-4 md:block dark:border-neutral-800",children:[a&&_jsxruntime.jsx.call(void 0, "p",{title:a,className:"mb-3 truncate text-sm text-neutral-600 dark:text-neutral-400",children:a}),_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"}),u.logout]})]})]})}function Ir({email:e,logout:t,onLocaleChange:n}){let[o,r]=_react3.useState.call(void 0, _chunkQ337IQNAjs.f),a=pe(o);return _jsxruntime.jsxs.call(void 0, "section",{className:"w-full max-w-xl",children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-2xl",children:a.accountNavLabel}),_jsxruntime.jsx.call(void 0, "h4",{className:"mt-6 mb-2 text-sm font-medium text-neutral-600 dark:text-neutral-400",children:a.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:a.emailLabel}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-1 break-words",children:e||a.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:a.languageLabel}),_jsxruntime.jsxs.call(void 0, "select",{value:o.toLowerCase().startsWith("en")?"en-US":"pl-PL",onChange:i=>{_chunkQ337IQNAjs.e.call(void 0, i.target.value),r(i.target.value),_optionalChain([n, 'optionalCall', _116 => _116()])},className:"min-h-11 rounded-md border border-neutral-300 bg-white px-3 focus-visible:outline-2 focus-visible:outline-current dark:border-neutral-700 dark:bg-neutral-900",children:[_jsxruntime.jsx.call(void 0, "option",{value:"pl-PL",children:a.polishLanguage}),_jsxruntime.jsx.call(void 0, "option",{value:"en-US",children:a.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"}),a.logout]})]})}var Ji=_react3.lazy.call(void 0, ()=>Promise.resolve().then(() => _interopRequireWildcard(require("./course.js"))).then(e=>({default:e.PanelCourse})));function Sr(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, Ji,{...e})})})}var Xi=_react3.lazy.call(void 0, ()=>Promise.resolve().then(() => _interopRequireWildcard(require("./chat.js"))).then(e=>({default:e.PanelMessages})));function Er(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, Xi,{...e})})}function es(e,t){return!!t||e.some(n=>n.productType===5||n.productType===6)}function bo(e){let{data:t}=_chunk2FD2QP4Yjs.f.call(void 0, _chunk2FD2QP4Yjs.e.publicApi.userPanelGetProducts,{accessToken:_nullishCoalesce(e, () => (""))},{enabled:!!e}),n=_optionalChain([t, 'optionalAccess', _117 => _117.result, 'access', _118 => _118.case])==="success"?t.result.value:void 0,o=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _119 => _119.products]), () => ([])),r=_optionalChain([n, 'optionalAccess', _120 => _120.chatApiUrl])||void 0;return{visible:es(o,r),products:o,chatApiUrl:r}}function os({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,o=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:[o&&_jsxruntime.jsx.call(void 0, o,{className:"h-4 w-4"}),r[e]||e]})}function as({orderID:e,email:t}){let[n,o]=_react3.useState.call(void 0, ""),r=_chunk2FD2QP4Yjs.g.call(void 0, _chunk2FD2QP4Yjs.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}),o("")}catch(d){console.error("Failed to add comment:",d)}},className:"mt-4 space-y-2",children:[_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.d,{htmlFor:"comment",children:"Dodaj komentarz"}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.p,{id:"comment",value:n,onChange:i=>o(i.target.value),placeholder:"Wpisz komentarz...",rows:3,disabled:r.isPending}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.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 ko(e){return e?new Date(Number(e.seconds)*1e3).toLocaleDateString("pl-PL",{year:"numeric",month:"long",day:"numeric"}):"N/A"}function xo(e,t){return new Intl.NumberFormat("pl-PL",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function is({orderID:e,initialEmail:t,onBack:n,accessToken:o,analytics:r}){let{theme:a,projectID:i}=_chunkNWXZ45TVjs.b.call(void 0, ),d=_chunkD2ASWUXMjs.n.call(void 0, i,r,"order"),[u,l]=_react3.useState.call(void 0, t||""),[g,b]=_react3.useState.call(void 0, !1),{data:w,isLoading:x,error:f,refetch:c}=_chunk2FD2QP4Yjs.f.call(void 0, _chunk2FD2QP4Yjs.e.publicApi.getPublicOrderDetails,{projectId:_nullishCoalesce(i, () => ("")),orderId:e,email:u||void 0,accessToken:o},{enabled:!!e}),m=_optionalChain([w, 'optionalAccess', _121 => _121.result, 'access', _122 => _122.case])==="order"?w.result.value:null,p=_nullishCoalesce(_optionalChain([m, 'optionalAccess', _123 => _123.isVerified]), () => (!1)),v=m!=null;_react3.useEffect.call(void 0, ()=>{v&&d.track("panel_order_viewed",{},{order_ref:null})},[d,v]);let z=()=>{c(),b(!1)},ee={"--button-background-color":_nullishCoalesce(_optionalChain([a, 'optionalAccess', _124 => _124.colors, 'optionalAccess', _125 => _125.brand]), () => ("#000000")),"--button-background-color-dark":_nullishCoalesce(_optionalChain([a, 'optionalAccess', _126 => _126.colors, 'optionalAccess', _127 => _127.brandDark]), () => ("#ffffff")),"--button-text-color":_nullishCoalesce(_optionalChain([a, 'optionalAccess', _128 => _128.colors, 'optionalAccess', _129 => _129.brandDark]), () => ("#000000")),"--button-text-color-dark":_nullishCoalesce(_optionalChain([a, 'optionalAccess', _130 => _130.colors, 'optionalAccess', _131 => _131.brand]), () => ("#000000"))};return x?_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..."})]})}):f||!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:ee,children:_jsxruntime.jsxs.call(void 0, "div",{className:"w-full px-4",children:[n&&_jsxruntime.jsxs.call(void 0, _chunk2FD2QP4Yjs.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([a, 'optionalAccess', _132 => _132.logoURL])&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, "img",{src:a.logoURL,alt:"Project logo",className:`h-12 w-auto ${a.logoDarkURL?"dark:hidden":""}`}),a.logoDarkURL&&_jsxruntime.jsx.call(void 0, "img",{src:a.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, os,{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 ",ko(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, _chunk2FD2QP4Yjs.k,{onClick:()=>b(!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((T,ce)=>_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-center gap-4",children:[T.imageUrl&&_jsxruntime.jsx.call(void 0, "img",{src:T.imageUrl,alt:T.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:T.name}),_jsxruntime.jsxs.call(void 0, "p",{className:"text-sm text-neutral-600",children:["Ilo\u015B\u0107: ",T.quantity]})]}),_jsxruntime.jsx.call(void 0, "div",{className:"text-right",children:_jsxruntime.jsx.call(void 0, "p",{className:"font-medium",children:xo(Number(T.price),T.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:xo(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(T=>_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:T.authorName||"System"}),_jsxruntime.jsx.call(void 0, "span",{className:"text-xs text-neutral-500",children:ko(T.createdAt)}),T.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:T.message})]},T.id))}):_jsxruntime.jsx.call(void 0, "p",{className:"text-neutral-600",children:"Brak komentarzy."}),p?_jsxruntime.jsx.call(void 0, as,{orderID:m.orderId,email:u}):_jsxruntime.jsx.call(void 0, "div",{className:"mt-4",children:_jsxruntime.jsxs.call(void 0, _chunk2FD2QP4Yjs.k,{onClick:()=>b(!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"]})})]})]}),g&&_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, _chunkBUYTK7KMjs.d,{htmlFor:"verify-email",children:"Adres email"}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.l,{id:"verify-email",type:"email",placeholder:"twoj@email.com",value:u,onChange:T=>l(T.target.value)})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex gap-2",children:[_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.k,{variant:"outline",onClick:()=>b(!1),className:"flex-1",children:"Anuluj"}),_jsxruntime.jsx.call(void 0, _chunk2FD2QP4Yjs.k,{onClick:z,className:"flex-1",children:"Zweryfikuj"})]})]})]})})]})})}function ss(e){return _jsxruntime.jsx.call(void 0, is,{...e})}var Ar=ss;var ds=({returnsAppearance:e,returnsTexts:t,analytics:n}={})=>{let{projectID:o,theme:r,loginURL:a,host:i}=_chunkNWXZ45TVjs.b.call(void 0, ),[,d]=_react3.useState.call(void 0, 0),u=_chunkD2ASWUXMjs.n.call(void 0, o,n,"panel"),l=_chunkMDAFPGPAjs.i.call(void 0, o,i),g=_chunkMDAFPGPAjs.k.call(void 0, o,i),{mutateAsync:b}=_chunk2FD2QP4Yjs.g.call(void 0, _chunk2FD2QP4Yjs.e.publicApi.userPanelLogout);async function w(){l&&await b({accessToken:l}),typeof window<"u"&&(_chunkMDAFPGPAjs.l.call(void 0, o,i),window.location.reload())}let[x]=_react.useAutoAnimate.call(void 0, ),f=I=>["products","notifications","profile","plans","orders","order-details","returns","return-details","course","messages"].includes(I),[c,m]=qn({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,v]=_react3.useState.call(void 0, f(c.state)?c.state:"products"),z=I=>{m({state:"order-details",orderId:I}),v("order-details")},ee=()=>{m({state:"orders",orderId:void 0}),v("orders")},T=I=>m({orderId:void 0,returnId:void 0,course:void 0,item:void 0,chatProject:void 0,thread:void 0,channel:void 0,...I}),ce=I=>{m({state:"course",course:I,item:void 0,product:void 0}),v("course")},Se=()=>{m({state:"products",course:void 0,item:void 0,product:void 0}),v("products")},oe=()=>{m({state:"messages",product:void 0,chatProject:void 0,thread:void 0,channel:void 0}),v("messages")},te=bo(l);_react3.useEffect.call(void 0, ()=>{f(c.state)&&(c.state==="course"||p==="course"||c.state==="messages"||p==="messages")&&v(c.state)},[c.state]);let fe={"--button-background-color":_nullishCoalesce(_optionalChain([r, 'optionalAccess', _133 => _133.colors, 'optionalAccess', _134 => _134.brand]), () => ("#000000")),"--button-background-color-dark":_nullishCoalesce(_optionalChain([r, 'optionalAccess', _135 => _135.colors, 'optionalAccess', _136 => _136.brandDark]), () => ("#ffffff")),"--button-text-color":_nullishCoalesce(_optionalChain([r, 'optionalAccess', _137 => _137.colors, 'optionalAccess', _138 => _138.brandDark]), () => ("#000000")),"--button-text-color-dark":_nullishCoalesce(_optionalChain([r, 'optionalAccess', _139 => _139.colors, 'optionalAccess', _140 => _140.brand]), () => ("#000000"))};return _react3.useEffect.call(void 0, ()=>{if(l==null||l.length===0){window.location.href=_nullishCoalesce(a, () => ("/panel/login"));return}},[]),_react3.useEffect.call(void 0, ()=>{if(l==null||l.length===0){window.location.href=_nullishCoalesce(a, () => ("/panel/login"));return}},[p]),_react3.useEffect.call(void 0, ()=>{if(typeof window>"u"||window.parent!==window||!l)return;let I=gt(window.location.search);I&&yt(I);let ge=_nullishCoalesce(I, () => (Ze()));ge&&(window.location.href=Qe(ge,l))},[l]),_jsxruntime.jsx.call(void 0, _chunkD2ASWUXMjs.l,{value:u,children:_jsxruntime.jsxs.call(void 0, "div",{ref:x,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, Nr,{activeScreen:p,setActiveScreen:v,setParams:T,styles:fe,theme:r,logout:w,email:g,projectID:o,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, fo,{projectID:_nullishCoalesce(o, () => ("")),accessToken:l,loginURL:_nullishCoalesce(a, () => ("/panel/login")),styles:fe,activeScreen:p,params:c,setParams:m,openCourse:ce,openMessages:oe}),p==="messages"&&l&&_jsxruntime.jsx.call(void 0, Er,{accessToken:l,products:te.products,chatApiUrl:te.chatApiUrl,projectID:o,host:i,selection:{chatProject:c.chatProject,thread:c.thread,channel:c.channel},onSelect:I=>m({chatProject:I.chatProject,thread:I.thread,channel:I.channel})}),p==="course"&&c.course&&l&&_jsxruntime.jsx.call(void 0, Sr,{accessId:c.course,accessToken:l,theme:r,itemId:c.item,onItemChange:I=>m({item:I}),onBack:Se}),p==="notifications"&&_jsxruntime.jsx.call(void 0, fr,{}),p==="plans"&&_jsxruntime.jsx.call(void 0, gr,{projectID:_nullishCoalesce(o, () => (""))}),p==="orders"&&_jsxruntime.jsx.call(void 0, Bn,{projectID:_nullishCoalesce(o, () => ("")),accessToken:_nullishCoalesce(l, () => ("")),openOrderDetails:z}),p==="order-details"&&c.orderId&&_jsxruntime.jsx.call(void 0, Ar,{orderID:c.orderId,onBack:ee}),(p==="returns"||p==="return-details")&&l&&_jsxruntime.jsx.call(void 0, hr,{projectID:_nullishCoalesce(o, () => ("")),host:i,accessToken:l,loginURL:_nullishCoalesce(a, () => ("/panel/login")),appearance:Hn(e,_optionalChain([r, 'optionalAccess', _141 => _141.colors, 'optionalAccess', _142 => _142.brand])),texts:t,screen:p,params:c,setParams:m,setActiveScreen:v}),p==="profile"&&_jsxruntime.jsx.call(void 0, Ir,{email:g,logout:w,onLocaleChange:()=>d(I=>I+1)})]})]})})},cs= exports.G =ds;var _reactquery = require('@tanstack/react-query');var _connect = require('@connectrpc/connect');var _connectweb = require('@connectrpc/connect-web');var me;(o=>{function e(r){return _connect.createClient.call(void 0, _chunkLGPNJ5XEjs.g,n(r))}o.get=e;let t=new Map;function n(r){let a=t.get(r);return a==null&&(a=_connectweb.createConnectTransport.call(void 0, {useBinaryFormat:!0,baseUrl:r+"/api/rpc",interceptors:[_chunkDOJICJCQjs.b]}),t.set(r,a)),a}})(me = exports.a||={});var _zod = require('zod'); var _zod2 = _interopRequireDefault(_zod);function _(e,t=2){return+(Math.round(+(e+"e+"+t))+"e-"+t)}function Eo(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 cp=_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 Rr(e){typeof window>"u"||(ms(e),gs(e),ys(e))}function ms(e){try{typeof window.dataLayer>"u"&&(window.dataLayer=[]);let t=fs(e);window.dataLayer.push(t)}catch(t){console.warn("cannot send google analytics event",t)}}function fs(e){let t=_nullishCoalesce(_nullishCoalesce(e.value, () => (_optionalChain([e, 'access', _143 => _143.items, 'optionalAccess', _144 => _144.reduce, 'call', _145 => _145((a,i)=>a+(i.price||0)*(i.quantity||1),0)]))), () => (0)),n=_optionalChain([e, 'access', _146 => _146.items, 'optionalAccess', _147 => _147.map, 'call', _148 => _148(a=>({item_id:a.id,item_name:a.name||a.id,price:_((a.price||0)/100,2),quantity:a.quantity||1}))]),o={currency:e.currency||"PLN",value:_(t/100,2)};n&&n.length>0&&(o.items=n);let r;switch(e.event){case"purchase":r="purchase",o.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:o,...e.step&&{step:e.step},...e.content_name&&{content_name:e.content_name}}}function gs(e){if(typeof window.fbq>"u")return;let t="",n="",o={};switch(e.event){case"purchase":t="track",n="Purchase",o={category_name:e.step,...e};break;case"lead":t="track",n="Lead",o={category_name:e.step,...e};break;case"addToCart":t="track",n="Add to Cart",o={category_name:e.step,...e};break;case"customizeProduct":t="track",n="Customize Product",o={category_name:e.step,...e};break;case"viewCart":t="track",n="View Cart",o={category_name:e.step,...e};break;case"removeFromCart":t="track",n="Remove from Cart",o={category_name:e.step,...e};break;case"initiateCheckout":t="track",n="Initiate Checkout",o={category_name:e.step,...e};break;default:break}window.location.search.includes("analytics")&&console.log("Pushing FB event",t,n,o),window.fbq(t,n,o)}function ys(e){try{if(typeof window.ttq>"u")return;let t=hs(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 hs(e){let t=_nullishCoalesce(_nullishCoalesce(e.value, () => (_optionalChain([e, 'access', _149 => _149.items, 'optionalAccess', _150 => _150.reduce, 'call', _151 => _151((a,i)=>a+(i.price||0)*(i.quantity||1),0)]))), () => (0)),n=_optionalChain([e, 'access', _152 => _152.items, 'optionalAccess', _153 => _153.map, 'call', _154 => _154(a=>({content_id:a.id,content_type:"product",content_name:a.name||a.id,quantity:a.quantity||1,price:_((a.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:_(t/100,2)});let o={currency:e.currency||"PLN",value:_(t/100,2)};n.length>0&&(o.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:o}}function Lo(e){let{items:t,googlePayConfig:n,checkout:o,result:r,cartRequiresShipping:a}=e,i=_nullishCoalesce(e.locale, () => (_chunkQ337IQNAjs.f.call(void 0, )));if(r.totalAmount==null)return;let d=[];return a&&(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:a},shippingAddressRequired:a,shippingOptionRequired:a,shippingOptionParameters:a?{shippingOptions:r.methods.slice(0,5).map(l=>({id:l.id,label:l.name+` - ${Eo(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:`${_(r.totalAmount/100,2)}`,currencyCode:r.currency,countryCode:r.country,checkoutOption:"COMPLETE_IMMEDIATE_PURCHASE",displayItems:bs(t,r.methods,_nullishCoalesce(r.selectedDeliveryMethod, () => ((r.methods.length>0?r.methods[0].id:void 0))),o.couponCode,r.couponValue,_chunkQ337IQNAjs.c.call(void 0, "coupon",i,e.texts))}}}function bs(e,t,n,o,r,a="Coupon"){let i=[],d=0;for(let l of e){if(l.details==null)continue;let g=_nullishCoalesce(_optionalChain([l, 'access', _155 => _155.details, 'access', _156 => _156.pricing, 'optionalAccess', _157 => _157.effectivePrice]), () => (l.details.price));d+=g*l.quantity,i.push({label:l.details.name+" x "+l.quantity,price:`${_(g/100,2)}`,type:"LINE_ITEM",status:"FINAL"})}let u=t.find(l=>l.id===n);return u!=null&&i.push({label:u.name,price:`${_(u.amount/100,2)}`,type:"SHIPPING_OPTION",status:"FINAL"}),o!=null&&r!=null&&i.push({label:`${a} ${o}`,price:`${_(r/100,2)}`,type:"DISCOUNT",status:"FINAL"}),d>0&&i.push({label:"Subtotal",price:`${_(d/100,2)}`,type:"SUBTOTAL",status:"FINAL"}),i}function ot(e,t){return`${_chunkDOJICJCQjs.e}/api/integrations/${e}/public-commerce${t}`}function Ue(e){return typeof e=="object"&&e!=null&&"ERR"in e}function $(e,t,n){return{ERR:!0,error:e,type:t,data:n}}function To(e,t){return _optionalChain([t, 'optionalAccess', _158 => _158.find, 'call', _159 => _159(n=>n.id===e||(_nullishCoalesce(_optionalChain([n, 'access', _160 => _160.variants, 'optionalAccess', _161 => _161.some, 'call', _162 => _162(o=>o.id===e)]), () => (!1))))])}function Ao(e,t){let n=new Set(t.map(o=>o.productID));return Array.from(new Set(e.filter(o=>!n.has(o))))}function Ro(e,t){let n=_optionalChain([e, 'optionalAccess', _163 => _163.trim, 'call', _164 => _164()]);if(!(n==null||n.length===0))try{let o=new URL(n,t);return o.protocol!=="http:"&&o.protocol!=="https:"?void 0:o.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 Np({texts:e,locale:t,children:n}){let o=_react3.useMemo.call(void 0, ()=>({texts:e,locale:t}),[e,t]);return _jsxruntime.jsx.call(void 0, _t.Provider,{value:o,children:n})}function Mo(){return _react3.useContext.call(void 0, _t)}function Ip(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 Sp(){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, ()=>o=>_chunkQ337IQNAjs.c.call(void 0, o,n,e),[n,e])}var Or="bitsnap-pending-order";function _o(e,t){let n=new Map;for(let r of t)n.set(r.id,(_nullishCoalesce(n.get(r.id), () => (0)))+r.quantity);let o=[];for(let r of e){let a=n.get(r.id);a==null?o.push(r):r.quantity>a&&o.push({...r,quantity:r.quantity-a})}return o}var xs=60*1e3;function zo(e,t=Date.now,n=xs){let o;return r=>{let a=`${r.orderId}:${r.ts}`,i=t();return _optionalChain([o, 'optionalAccess', _165 => _165.key])===a&&i-o.at<n?Promise.reject(new Error("pending order was asked about recently")):(o={key:a,at:i},e(r))}}function ws(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 Cs(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 Ns(e,t=Date.now(),n={}){if(Cs(e.url))return;let o=ws(e.url),r=_nullishCoalesce(Oo(e.orderId), () => (_optionalChain([o, 'optionalAccess', _166 => _166.orderId]))),a=_nullishCoalesce(Oo(e.projectId), () => (_optionalChain([o, 'optionalAccess', _167 => _167.projectId])));if(!(r==null||a==null))return{orderId:r,projectId:a,...n.cartProjectId!=null?{cartProjectId:n.cartProjectId}:{},lines:_nullishCoalesce(n.lines, () => ([])),ts:t}}function Tp(e,t={}){let n=Ns(e,t.now,t);return n!=null&&Is(n,t.storage)}function Oo(e){return e!=null&&e.length>0?e:void 0}function zt(){try{return typeof localStorage>"u"?void 0:localStorage}catch (e19){return}}function Is(e,t=zt()){try{return _optionalChain([t, 'optionalAccess', _168 => _168.setItem, 'call', _169 => _169(Or,JSON.stringify(e))]),t!=null}catch (e20){return!1}}function Uo(e=zt()){try{let t=_optionalChain([e, 'optionalAccess', _170 => _170.getItem, 'call', _171 => _171(Or)]);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:o,projectId:r,cartProjectId:a,ts:i,lines:d}=n;return{orderId:o,projectId:r,...typeof a=="string"?{cartProjectId:a}:{},lines:Array.isArray(d)?d.filter(u=>typeof _optionalChain([u, 'optionalAccess', _172 => _172.id])=="string"&&typeof u.quantity=="number"):[],ts:i}}}catch (e21){}Mr(e)}function Mr(e=zt()){try{_optionalChain([e, 'optionalAccess', _173 => _173.removeItem, 'call', _174 => _174(Or)])}catch (e22){}}function jo(e){let t=_nullishCoalesce(_optionalChain([e, 'access', _175 => _175.details, 'optionalAccess', _176 => _176.status]), () => (Ss(_optionalChain([e, 'access', _177 => _177.details, 'optionalAccess', _178 => _178.$unknown]))));return t==="created"||t==="placed"||t==="paid"||t==="canceled"?t:"unknown"}function Ss(e){if(Array.isArray(e)){for(let t of e)if(_optionalChain([t, 'optionalAccess', _179 => _179.no])===3&&t.wireType===2&&t.data instanceof Uint8Array){let n=0,o=0;for(let r=0;o<t.data.length&&r<35;r+=7){let a=t.data[o++];if(n|=(a&127)<<r,!(a&128))break}if(o+n!==t.data.length)return;try{return new TextDecoder().decode(t.data.subarray(o))}catch (e23){return}}}}async function Fo(e){let t=_nullishCoalesce(e.storage, () => (zt())),n=Uo(t);if(n==null)return"none";if((_nullishCoalesce(e.now, () => (Date.now)))()-n.ts>864e5)return Mr(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 a=Uo(t);if(_optionalChain([a, 'optionalAccess', _180 => _180.orderId])!==n.orderId||a.ts!==n.ts)return"pending";if(r==="paid"||r==="placed"){try{await e.removeLines(n.lines)}catch (e25){return"pending"}return Mr(t),"paid"}return"pending"}var Ds="__m_a",Vo=_react3.createContext.call(void 0, void 0),jr= exports.I =void 0;function rm(e){_chunkMDAFPGPAjs.a.call(void 0, {projectID:e}),jr= exports.I =e,typeof window<"u"&&_chunkMDAFPGPAjs.g.call(void 0, [window.location.origin])}function st(){return _nullishCoalesce(_nullishCoalesce(jr, () => (_optionalChain([document, 'access', _181 => _181.querySelector, 'call', _182 => _182('script[data-id][data-name="internal-cart"]'), 'optionalAccess', _183 => _183.getAttribute, 'call', _184 => _184("data-id")]))), () => (void 0))}function Ms(){return _nullishCoalesce(_optionalChain([document, 'access', _185 => _185.querySelector, 'call', _186 => _186('script[data-id][data-name="internal-cart"]'), 'optionalAccess', _187 => _187.getAttribute, 'call', _188 => _188("data-custom-host")]), () => (void 0))}var Os=({children:e,locale:t})=>{let[n]=_react3.useState.call(void 0, ()=>new _reactquery.QueryClient),o=Mo();_react3.useEffect.call(void 0, ()=>{Ie()},[]);let r=st();if(_react3.useEffect.call(void 0, ()=>{if(r==null)return;let i=()=>{zs(r).then(u=>{u==="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 a=Hr(r,_nullishCoalesce(t, () => (o.locale)),o.texts);return _jsxruntime.jsx.call(void 0, _reactquery.QueryClientProvider,{client:n,children:_jsxruntime.jsx.call(void 0, Vo.Provider,{value:a,children:e})})},Ur,Us=zo(async e=>jo(await me.get(_chunkDOJICJCQjs.e).getOrder({id:e.orderId,projectId:e.projectId})));function nm(){let{country:e,couponCode:t,selectedDeliveryMethod:n,postalCode:o}=_nullishCoalesce(E(), () => (Ht));return{country:e,couponCode:t,selectedDeliveryMethod:n,postalCode:o}}function om(){return(_nullishCoalesce(_optionalChain([E, 'call', _189 => _189(), 'optionalAccess', _190 => _190.products]), () => ([]))).map(e=>({id:e.id,quantity:e.quantity}))}function _s(e){let t=E();G({...t,products:_o(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _191 => _191.products]), () => ([])),e)}),Ie()}function zs(e){return Ur??=Fo({projectId:e,fetchStatus:Us,removeLines:_s}).catch(t=>{console.warn("cannot check the pending order",t)}).finally(()=>{Ur=void 0}),Ur}var it=async(e,t)=>{let n=[];_optionalChain([t, 'optionalAccess', _192 => _192.items])!=null&&t.items.length>0?n=t.items:n=_nullishCoalesce(_optionalChain([E, 'call', _193 => _193(), 'optionalAccess', _194 => _194.products]), () => ([]));let o=Array.from(new Set(n.map(i=>i.productID)));if(o.length===0)return[];let r=new URLSearchParams;r.set("ids",o.join(",")),r.set("locale",_nullishCoalesce(_optionalChain([t, 'optionalAccess', _195 => _195.locale]), () => (_chunkQ337IQNAjs.f.call(void 0, ))));let a;try{let i=await fetch(_chunkDOJICJCQjs.c.call(void 0, ot(e,`/products?${r.toString()}`)),{method:"GET"});if(i.status!=200)return $("products-load-failed","internal");a=await i.json()}catch(i){return console.warn("cannot load the products of the cart",i),$("products-load-failed","internal")}return n.flatMap(i=>{let d=To(i.productID,a.result);return d==null?[]:[{...i,details:Ks(i.productID,d),catalogProductID:d.id}]})},am= exports.O =()=>{let e=_react3.useContext.call(void 0, Vo);if(e===void 0)throw new Error("useCartProvider must be used within a CartProvider");return e},im= exports.P =Os,js=_zod2.default.object({isAvailable:_zod2.default.boolean(),merchantId:_zod2.default.string(),merchantName:_zod2.default.string(),gateway:_zod2.default.string(),gatewayId:_zod2.default.string()}),Fs=_zod2.default.object({id:_zod2.default.string(),productID:_zod2.default.string(),quantity:_zod2.default.number(),priceVersion:_zod2.default.string().optional(),metadata:_zod2.default.record(_zod2.default.string(),_zod2.default.string().optional()).optional(),url:_zod2.default.string().optional()}),qs=_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(Fs).optional(),googlePayConfig:js.optional()}),Ht={country:void 0,couponCode:void 0,email:void 0,selectedDeliveryMethod:void 0,postalCode:void 0,products:[],googlePayConfig:void 0},qr="checkout";function Hs(){return typeof localStorage>"u"?[]:(_nullishCoalesce(E().products, () => ([]))).map(e=>({...e}))}function sm(){return Hs().map(e=>`${e.productID}:${e.quantity}`).sort().join(",")}function lm(e){let t=E();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}:{}})),...t.country!=null?{countries:[t.country]}:{},...t.couponCode!=null?{couponCode:t.couponCode}:{},...t.selectedDeliveryMethod!=null?{deliveryMethod:t.selectedDeliveryMethod}:{},locale:e}}function dm(e){let t=E(),n=new Map;for(let o of _nullishCoalesce(t.products, () => ([]))){let r=_nullishCoalesce(n.get(o.productID), () => ([]));r.push(o),n.set(o.productID,r)}t.products=e.map(o=>{let r=_optionalChain([n, 'access', _196 => _196.get, 'call', _197 => _197(o.productId), 'optionalAccess', _198 => _198.shift, 'call', _199 => _199()]);return{id:Math.random().toString(36).substring(7),productID:o.productId,quantity:o.quantity,..._optionalChain([r, 'optionalAccess', _200 => _200.priceVersion])!=null?{priceVersion:r.priceVersion}:{},..._optionalChain([r, 'optionalAccess', _201 => _201.metadata])!=null?{metadata:r.metadata}:{},..._optionalChain([r, 'optionalAccess', _202 => _202.url])!=null?{url:r.url}:{}}}),G(t),Ie()}function cm(e){let t=new Map;for(let r of e)t.set(r.id,(_nullishCoalesce(t.get(r.id), () => (0)))+r.quantity);let n=E(),o=(_nullishCoalesce(n.products, () => ([]))).flatMap(r=>{let a=t.get(r.productID);return a==null?[r]:r.quantity<=a?[]:[{...r,quantity:r.quantity-a}]});G({...n,products:o}),Ie()}function um(e){let t=E();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});G(t),Ie()}function E(){try{let e=localStorage.getItem(qr);return e==null?Ht:qs.parse(JSON.parse(e))}catch (e26){return Ht}}async function Ho(e,t){let n=await it(e,{items:t.map((a,i)=>({...a,id:`price-check-${i}`}))});if(Ue(n))return n;let o=Ao(t.map(a=>a.productID),n);if(o.length>0)return $("item-ids-not-found","notFound",o);let r=E();r.products==null&&(r.products=[]),r.products.push(...t.map(a=>({id:Math.random().toString(36).substring(7),productID:a.productID,quantity:a.quantity,priceVersion:_optionalChain([n, 'access', _203 => _203.find, 'call', _204 => _204(i=>i.productID===a.productID), 'optionalAccess', _205 => _205.details, 'optionalAccess', _206 => _206.pricing, 'optionalAccess', _207 => _207.priceVersion]),metadata:a.metadata,url:Ro(a.url,typeof window<"u"?window.location.href:void 0)}))),$s(t,n),Rr({event:"addToCart",currency:"PLN",items:t.map(a=>({id:a.productID,name:_nullishCoalesce(a.name, () => ("")),price:_nullishCoalesce(a.price, () => (0)),quantity:a.quantity,currency:_nullishCoalesce(a.currency, () => ("PLN"))}))}),G(r),Ie()}function $s(e,t){for(let n of e)try{let o=t.find(d=>d.productID===n.productID),r=_nullishCoalesce(_nullishCoalesce(_optionalChain([o, 'optionalAccess', _208 => _208.details, 'optionalAccess', _209 => _209.pricing, 'optionalAccess', _210 => _210.effectivePrice]), () => (_optionalChain([o, 'optionalAccess', _211 => _211.details, 'optionalAccess', _212 => _212.price]))), () => (n.price)),a=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _213 => _213.details, 'optionalAccess', _214 => _214.currency]), () => (n.currency));if(r==null||a==null)continue;let i=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _215 => _215.catalogProductID]), () => (n.productID));(_nullishCoalesce(n.analytics, () => (_chunkD2ASWUXMjs.o.call(void 0, )))).track("add_to_cart",{qty:n.quantity,value_minor:Math.round(r*n.quantity),currency:a},{product_id:i,variant_id:i!==n.productID?n.productID:null})}catch (e27){}}function $o(e){let t=E(),n={...t,products:_optionalChain([t, 'optionalAccess', _216 => _216.products, 'optionalAccess', _217 => _217.filter, 'call', _218 => _218(o=>!e.includes(o.productID)&&!e.includes(o.id))])};Rr({event:"removeFromCart",items:e.map(o=>({id:o,name:"",price:0,quantity:1,currency:"PLN"}))}),G(n),Ie()}function G(e){localStorage.setItem(qr,JSON.stringify(e)),Yo()}var Ft=new Set,Wo=0,jt=!1;function Bo(e){e.key===qr&&Yo()}function pm(e){return Ft.add(e),!jt&&typeof window<"u"&&(window.addEventListener("storage",Bo),jt=!0),()=>{Ft.delete(e),Ft.size===0&&jt&&(window.removeEventListener("storage",Bo),jt=!1)}}function mm(){return Wo}function Yo(){Wo+=1;for(let e of Ft)try{e()}catch (e28){}}function Ko(e,t){if(e.products==null||e.products.length==0)return;let n=e.products.reduce((o,r)=>(r.metadata!=null&&Object.keys(r.metadata).forEach(a=>{let i=_optionalChain([r, 'access', _219 => _219.metadata, 'optionalAccess', _220 => _220[a]]);i!=null&&(o[a]=i)}),o),{});return{items:e.products.map(o=>({id:o.productID,quantity:o.quantity,priceVersion:o.priceVersion})),askForNote:!0,countries:e.country?[e.country]:void 0,metadata:n,locale:t}}var Hr=(e,t=_chunkQ337IQNAjs.f.call(void 0, ),n)=>{let o=Ms();return o!=null&&_chunkDOJICJCQjs.f.call(void 0, o),{async checkIfApplePayIsAvailable(){if(typeof window>"u"||typeof document>"u"||!("ApplePaySession"in window))return!1;try{return(await me.get(_chunkDOJICJCQjs.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 a=await Bs(e);if(_optionalChain([a, 'optionalAccess', _221 => _221.isAvailable])!=!0)return{isAvailable:!1};let i=E();if(i==null)return console.log("checkout is null"),{isAvailable:!1};let d=await it(e,{locale:t,items:r.items.map(b=>({id:Math.random().toString(36).substring(7),quantity:b.quantity,metadata:b.metadata,productID:b.productID}))});if(Ue(d))return{isAvailable:!1};let u=await me.get(_chunkDOJICJCQjs.e).getPreOrderDetails({items:d.map(b=>_protobuf.create.call(void 0, _chunkLGPNJ5XEjs.d,{id:b.productID,quantity:b.quantity})),projectId:e,postCode:i.postalCode,couponCode:i.couponCode,countryCode:i.country,selectedDeliveryMethod:i.selectedDeliveryMethod});if(u.totalAmount==null)return{isAvailable:!1};let l=d.find(b=>_optionalChain([b, 'access', _222 => _222.details, 'optionalAccess', _223 => _223.isDeliverable])==!0)!=null,g=await Lo({items:d,googlePayConfig:a,checkout:i,cartRequiresShipping:l,result:u,locale:t,texts:n});return g==null?{isAvailable:!1}:{isAvailable:!0,config:g}}catch(a){return console.error("Error resolving Google Pay configuration",a),{isAvailable:!1}}},async clearCart(){let r=structuredClone(Ht);r.country=_optionalChain([E, 'call', _224 => _224(), 'optionalAccess', _225 => _225.country]),G(r),Ie()},async getAvailableCountries(){let r=await fetch(_chunkDOJICJCQjs.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(a){return $(a.toString(),"internal")}},async getCountry(){let r=_optionalChain([E, 'call', _226 => _226(), 'optionalAccess', _227 => _227.country]);if(r==null){r="PL";let a=E();a.country=r,G(a)}return r},async getNumberOfElementsInCart(){return _nullishCoalesce(_optionalChain([E, 'call', _228 => _228(), 'optionalAccess', _229 => _229.products, 'optionalAccess', _230 => _230.reduce, 'call', _231 => _231((r,a)=>r+a.quantity,0)]), () => (0))},async getProducts(){return await it(e,{locale:t})},async removeProductFromCart(r){return $o([r.id])},async setCountry(r){let a=E();a.country=r,G(a)},async setCouponCodeIfPossible(r){let a=E();a.couponCode=r,G(a)},async setPostalCode(r){let a=E();a.postalCode=r,G(a)},async setDeliveryMethod(r){let a=E();a.selectedDeliveryMethod=r,G(a)},async setEmail(r){let a=E();a.email=r,G(a)},async addProduct(r){return await Ho(e,[r])},async updateQuantity(r){let a=E();a.products=_optionalChain([a, 'access', _232 => _232.products, 'optionalAccess', _233 => _233.map, 'call', _234 => _234(i=>(i.id===r.id&&(i.quantity=r.quantity),i))]),G(a),Ie()},async getPaymentMethodChoice(){let r=Ko(E(),t);return r==null?null:Go(r)},async redirectToNextStep(r){let a=Ko(E(),t);if(a==null)return $("cart-is-empty","badInput");_optionalChain([r, 'optionalAccess', _235 => _235.paymentMethod])!=null&&(a.paymentMethod=r.paymentMethod);let i=await zr(a);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 a={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))};a=Fr(a),r.country==null&&(r.country="pl"),a.details==null&&(a.details={}),a.details.address==null&&(a.details.address={}),a.details.address.country=r.country,r.marketingAgreement===!0&&(a.additionalAgreements=[{id:Ds,name:"",required:!0,answer:!0}]);let i=await zr(a);return Ue(i)?i:{url:i.url}},async getApplePayPreview(r){let a=E();try{let i=await me.get(_chunkDOJICJCQjs.e).getPreOrderDetails({items:r.items.map(d=>_protobuf.create.call(void 0, _chunkLGPNJ5XEjs.d,{id:d.productID,quantity:d.quantity})),projectId:e,postCode:a.postalCode,couponCode:a.couponCode,countryCode:a.country,selectedDeliveryMethod:a.selectedDeliveryMethod});return i.totalAmount==null||i.currency.length===0?$("pre-order-unavailable","internal"):{countryCode:i.country||a.country||"PL",currencyCode:i.currency,totalAmount:`${_(i.totalAmount/100,2)}`}}catch(i){return console.warn("cannot load the Apple Pay preview",i),$("pre-order-unavailable","internal")}},async completeApplePayPayment(r){let a=E();if(a==null)return $("Checkout not found");let i=await it(e,{locale:t});if(Ue(i))return i;try{let d=_optionalChain([r, 'access', _236 => _236.shippingContact, 'optionalAccess', _237 => _237.givenName]);_optionalChain([r, 'access', _238 => _238.shippingContact, 'optionalAccess', _239 => _239.familyName])!=null?d+=" "+_optionalChain([r, 'access', _240 => _240.shippingContact, 'optionalAccess', _241 => _241.familyName]):_optionalChain([r, 'access', _242 => _242.billingContact, 'optionalAccess', _243 => _243.familyName])!=null&&(d+=" "+_optionalChain([r, 'access', _244 => _244.billingContact, 'optionalAccess', _245 => _245.familyName]));let u={},l=qt();l!=null&&(u.ref=l);let g=await me.get(_chunkDOJICJCQjs.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, _chunkLGPNJ5XEjs.e,{items:i.map(b=>({id:b.productID,quantity:b.quantity})),couponCode:a.couponCode,email:_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([r, 'access', _246 => _246.shippingContact, 'optionalAccess', _247 => _247.emailAddress]), () => (_optionalChain([r, 'access', _248 => _248.billingContact, 'optionalAccess', _249 => _249.emailAddress]))), () => (a.email)), () => (void 0)),phone:_nullishCoalesce(_nullishCoalesce(_optionalChain([r, 'access', _250 => _250.shippingContact, 'optionalAccess', _251 => _251.phoneNumber]), () => (_optionalChain([r, 'access', _252 => _252.billingContact, 'optionalAccess', _253 => _253.phoneNumber]))), () => (void 0)),selectedDeliveryMethod:a.selectedDeliveryMethod,postCode:a.postalCode,projectId:e}),shippingAddress:_protobuf.create.call(void 0, _chunkLGPNJ5XEjs.a,{line1:_nullishCoalesce(_optionalChain([r, 'access', _254 => _254.shippingContact, 'optionalAccess', _255 => _255.addressLines, 'optionalAccess', _256 => _256[0]]), () => ("")),city:_nullishCoalesce(_optionalChain([r, 'access', _257 => _257.shippingContact, 'optionalAccess', _258 => _258.locality]), () => ("")),country:_nullishCoalesce(_optionalChain([r, 'access', _259 => _259.shippingContact, 'optionalAccess', _260 => _260.countryCode]), () => ("")),zipCode:_nullishCoalesce(_optionalChain([r, 'access', _261 => _261.shippingContact, 'optionalAccess', _262 => _262.postalCode]), () => ("")),name:d}),billingAddress:_protobuf.create.call(void 0, _chunkLGPNJ5XEjs.b,{name:_nullishCoalesce(_optionalChain([r, 'access', _263 => _263.billingContact, 'optionalAccess', _264 => _264.givenName]), () => (" "+(_nullishCoalesce(_optionalChain([r, 'access', _265 => _265.billingContact, 'optionalAccess', _266 => _266.familyName]), () => (""))))),line1:_nullishCoalesce(_optionalChain([r, 'access', _267 => _267.billingContact, 'optionalAccess', _268 => _268.addressLines, 'optionalAccess', _269 => _269[0]]), () => ("")),city:_nullishCoalesce(_optionalChain([r, 'access', _270 => _270.billingContact, 'optionalAccess', _271 => _271.locality]), () => ("")),country:_nullishCoalesce(_optionalChain([r, 'access', _272 => _272.billingContact, 'optionalAccess', _273 => _273.countryCode]), () => ("")),zipCode:_nullishCoalesce(_optionalChain([r, 'access', _274 => _274.billingContact, 'optionalAccess', _275 => _275.postalCode]), () => (""))}),metadata:Object.keys(u).length>0?JSON.stringify(u):void 0});return{isSuccess:g.isSuccess,redirectURL:g.redirectUrl}}catch(d){return console.error(d),$("Failed to authorize payment")}},async completeGooglePayPayment(r){let a=E();if(a==null)return $("Checkout not found");let i=await it(e,{locale:t});if(Ue(i))return i;try{let d=_optionalChain([r, 'access', _276 => _276.paymentData, 'access', _277 => _277.shippingAddress, 'optionalAccess', _278 => _278.name]),u={},l=qt();l!=null&&(u.ref=l);let g=await me.get(_chunkDOJICJCQjs.e).authorizeOneClickPayment({gateway:1,paymentData:r.paymentData.paymentMethodData.tokenizationData.token,paymentMethod:r.paymentData.paymentMethodData.type,transactionIdentifier:"",order:_protobuf.create.call(void 0, _chunkLGPNJ5XEjs.e,{items:i.map(b=>({id:b.productID,quantity:b.quantity})),couponCode:a.couponCode,email:_nullishCoalesce(r.paymentData.email, () => (void 0)),phone:_nullishCoalesce(_optionalChain([r, 'access', _279 => _279.paymentData, 'access', _280 => _280.shippingAddress, 'optionalAccess', _281 => _281.phoneNumber]), () => (void 0)),selectedDeliveryMethod:_nullishCoalesce(_optionalChain([r, 'access', _282 => _282.paymentData, 'access', _283 => _283.shippingOptionData, 'optionalAccess', _284 => _284.id]), () => (a.selectedDeliveryMethod)),postCode:_optionalChain([r, 'access', _285 => _285.paymentData, 'access', _286 => _286.shippingAddress, 'optionalAccess', _287 => _287.postalCode]),projectId:e}),shippingAddress:_protobuf.create.call(void 0, _chunkLGPNJ5XEjs.a,{line1:_nullishCoalesce(_optionalChain([r, 'access', _288 => _288.paymentData, 'access', _289 => _289.shippingAddress, 'optionalAccess', _290 => _290.address1]), () => ("")),city:_nullishCoalesce(_optionalChain([r, 'access', _291 => _291.paymentData, 'access', _292 => _292.shippingAddress, 'optionalAccess', _293 => _293.locality]), () => ("")),country:_nullishCoalesce(_optionalChain([r, 'access', _294 => _294.paymentData, 'access', _295 => _295.shippingAddress, 'optionalAccess', _296 => _296.countryCode]), () => ("")),zipCode:_nullishCoalesce(_optionalChain([r, 'access', _297 => _297.paymentData, 'access', _298 => _298.shippingAddress, 'optionalAccess', _299 => _299.postalCode]), () => ("")),name:d}),billingAddress:_protobuf.create.call(void 0, _chunkLGPNJ5XEjs.b,{name:_optionalChain([r, 'access', _300 => _300.paymentData, 'access', _301 => _301.paymentMethodData, 'access', _302 => _302.info, 'optionalAccess', _303 => _303.billingAddress, 'optionalAccess', _304 => _304.name]),line1:_nullishCoalesce(_optionalChain([r, 'access', _305 => _305.paymentData, 'access', _306 => _306.paymentMethodData, 'access', _307 => _307.info, 'optionalAccess', _308 => _308.billingAddress, 'optionalAccess', _309 => _309.address1]), () => ("")),city:_nullishCoalesce(_optionalChain([r, 'access', _310 => _310.paymentData, 'access', _311 => _311.paymentMethodData, 'access', _312 => _312.info, 'optionalAccess', _313 => _313.billingAddress, 'optionalAccess', _314 => _314.locality]), () => ("")),country:_nullishCoalesce(_optionalChain([r, 'access', _315 => _315.paymentData, 'access', _316 => _316.paymentMethodData, 'access', _317 => _317.info, 'optionalAccess', _318 => _318.billingAddress, 'optionalAccess', _319 => _319.countryCode]), () => ("")),zipCode:_nullishCoalesce(_optionalChain([r, 'access', _320 => _320.paymentData, 'access', _321 => _321.paymentMethodData, 'access', _322 => _322.info, 'optionalAccess', _323 => _323.billingAddress, 'optionalAccess', _324 => _324.postalCode]), () => (""))}),metadata:Object.keys(u).length>0?JSON.stringify(u):void 0});return{isSuccess:g.isSuccess,redirectURL:g.redirectUrl}}catch(d){return console.error(d),$("Failed to authorize payment")}return{isSuccess:!0}},async getApplePayPaymentRequest(r){let a=E();if(a==null)return $("Checkout not found");r&&r.expectedItems!=null&&r.expectedItems.length>0&&(a.products&&$o(a.products.map(l=>l.productID)),await Ho(e,r.expectedItems));let i=await it(e,{locale:t});if(Ue(i))return i;let d=await me.get(_chunkDOJICJCQjs.e).getPreOrderDetails({items:i.map(l=>_protobuf.create.call(void 0, _chunkLGPNJ5XEjs.d,{id:l.productID,quantity:l.quantity})),projectId:e,postCode:a.postalCode,couponCode:a.couponCode,countryCode:a.country,selectedDeliveryMethod:a.selectedDeliveryMethod}),u=i.map(l=>({amount:`${_(l.quantity*(_nullishCoalesce(_nullishCoalesce(_optionalChain([l, 'access', _325 => _325.details, 'optionalAccess', _326 => _326.pricing, 'optionalAccess', _327 => _327.effectivePrice]), () => (_optionalChain([l, 'access', _328 => _328.details, 'optionalAccess', _329 => _329.price]))), () => (0)))/100,2)}`,label:_optionalChain([l, 'access', _330 => _330.details, 'optionalAccess', _331 => _331.name])+" - "+l.quantity,type:"final"}));if(d.selectedDeliveryMethod!=null){let l=d.methods.find(g=>g.id==d.selectedDeliveryMethod);l!=null&&u.push({amount:`${_(l.amount/100,2)}`,label:l.name,type:"final"})}return d.couponCode!=null&&d.couponValue!=null&&u.push({amount:`-${_(d.couponValue/100,2)}`,label:d.couponCode,type:"final"}),{countryCode:d.country||a.country||"PL",merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],supportedNetworks:["visa","masterCard"],total:{amount:`${_((_nullishCoalesce(d.totalAmount, () => (0)))/100,2)}`,label:_chunkQ337IQNAjs.c.call(void 0, "paymentForCart",t,n),type:"final"},shippingMethods:d.methods.map(l=>({amount:`${_(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:u,currencyCode:d.currency||_optionalChain([i, 'access', _332 => _332[0], 'optionalAccess', _333 => _333.details, 'optionalAccess', _334 => _334.currency])||"PLN"}}}};async function Bs(e){let t=E();if(_optionalChain([t, 'access', _335 => _335.googlePayConfig, 'optionalAccess', _336 => _336.isAvailable])!=!0){let n=await me.get(_chunkDOJICJCQjs.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 G(t),t.googlePayConfig}function Ks(e,t){if(e==t.id){let o=_optionalChain([t, 'access', _337 => _337.variants, 'optionalAccess', _338 => _338.findIndex, 'call', _339 => _339(r=>r.id===e)]);if(o!=null&&o!=-1){let r=t.variants[o];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', _340 => _340.variants, 'optionalAccess', _341 => _341.find, 'call', _342 => _342(o=>o.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=E(),t=0;if(e==null){at.setState(n=>({...n,numberOfProductsInCart:t}));return}t=_nullishCoalesce(_optionalChain([e, 'access', _343 => _343.products, 'optionalAccess', _344 => _344.reduce, 'call', _345 => _345((n,o)=>n+o.quantity,0)]), () => (0)),at.setState(n=>({...n,numberOfProductsInCart:t}))}var Vs=200,Ws= exports.m ="item-ids-not-found",Pt="internal-error",Jo={"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"},Ys=new Set(["internal","invalid-request"]),Js=new Set(["product-not-available","product-not-found"]);function Zs(e){return typeof e=="string"&&Object.hasOwn(Jo,e)?Jo[e]:void 0}function Qs(e){return/<\/?[a-z!?][^>]*>/i.test(e)}function Xs(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 el(e){return/Error:/.test(e)||/\n\s+at /.test(e)}function $r(e){let t=e.trim();if(!(t.length===0||t.length>Vs||/[\r\n]/.test(t)||Qs(t)||Xs(t)||el(t)))return t}var tl=3;function $t(e,t=0){if(typeof e=="object"&&e!=null){if(Array.isArray(e)||t>=tl)return{};let n=e,o=$t(n.error,t+1);if(o.message==null&&n.message!=null){let r=$t(n.message,t+1);o={...r,code:_nullishCoalesce(o.code, () => (r.code))}}return typeof n.code=="string"&&n.code.length>0&&(o.code=n.code),o}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:$r(e)}}function rl(e){let t;try{t=JSON.parse(e)}catch (e30){return{code:Pt,message:$r(e)}}if(typeof t=="string")return{code:Pt,message:$r(t)};if(typeof t!="object"||t==null)return{code:Pt};let n=t,{message:o,code:r}=$t(n.error),a={code:typeof n.code=="string"&&n.code.length>0?n.code:_nullishCoalesce(r, () => (Pt)),message:o};return Array.isArray(n.itemIds)&&(a.itemIds=n.itemIds.filter(i=>typeof i=="string")),a}function Br(e,t){let{code:n,message:o,itemIds:r}=rl(t),a=r!=null&&r.length>0;if(a&&(n===Pt||Js.has(n)))return $(Ws,"badInput",r);let i={message:o};return a&&(i.itemIds=r),$(n,e>=500?"internal":"badInput",i)}function bm(e,t){let n=Zs(e.error);if(n!=null)return t(n);if(e.type==="internal"||typeof e.error=="string"&&Ys.has(e.error))return t("checkoutFailed");let o=_optionalChain([e, 'access', _346 => _346.data, 'optionalAccess', _347 => _347.message]);return typeof o=="string"&&o.length>0?o:t("checkoutFailed")}var nl=["online","manual","cod"],ol=["bankTransfer","blik"];function Zo(e,t){if(!Array.isArray(e))return[];let n=[];for(let o of e)t.includes(o)&&!n.includes(o)&&n.push(o);return n}function al(e){if(typeof e!="object"||e==null)return null;let t=e.choice;if(typeof t!="object"||t==null)return null;let n=Zo(t.methods,nl);return n.length<2?null:{methods:n,manualAccountTypes:Zo(t.manualAccountTypes,ol)}}function vm(e){if(e==null)return null;let t=e.methods.filter(n=>n!=="cod");return t.length<2?null:{...e,methods:t}}function km(e,t){return t!=null&&e.methods.includes(t)?t:e.methods[0]}function xm(e){let t=e.includes("bankTransfer"),n=e.includes("blik");return n&&!t?"paymentMethodManualBlik":t&&!n?"paymentMethodManualTransfer":"paymentMethodManualBoth"}async function Qo(e,t,n=5e3){let o=typeof AbortController>"u"?void 0:new AbortController,r=setTimeout(()=>_optionalChain([o, 'optionalAccess', _348 => _348.abort, 'call', _349 => _349()]),n);try{let a=await fetch(e,{method:"POST",headers:t.headers,body:t.body,signal:_optionalChain([o, 'optionalAccess', _350 => _350.signal])});return a.ok?al(await a.json()):null}catch (e31){return null}finally{clearTimeout(r)}}var il;(o=>{async function e(r,a=1,i,d){let u=st();if(u==null)throw new Error("No project ID found");let g=await Hr(u).addProduct({productID:r,quantity:a,metadata:i,...d});if(g!=null)return g}o.addProductToCart=e;function t(){at.setState({isCartVisible:!0})}o.showCart=t;function n(){at.setState({isCartVisible:!1})}o.hideCart=n})(il = exports.s||={});async function Xo(e){try{return await e.text()}catch (e32){return""}}function ea(e,t){return t=Fr(t),t.locale??=_chunkQ337IQNAjs.f.call(void 0, ),{headers:{..._chunkDOJICJCQjs.a,..._chunkD2ASWUXMjs.h.call(void 0, e),"Content-Type":"application/json"},body:JSON.stringify(t)}}async function Go(e){let t=st();return t==null?null:Qo(ot(t,"/payment-methods"),ea(t,e))}async function zr(e){let t=st();if(t==null)throw new Error("No project ID found");let n=await fetch(ot(t,"/buy"),{method:"POST",...ea(t,e)});if(n.status!=200){let r=Br(n.status,await Xo(n));return console.warn("cannot create payment URL",n.status,r.error),r}let o=await n.json();return{url:o.url,...o.orderId!=null?{orderId:o.orderId}:{},...o.projectId!=null?{projectId:o.projectId}:{}}}async function Rm(e){let t=st();if(t==null)throw new Error("No project ID found");let n={..._chunkDOJICJCQjs.a,..._chunkD2ASWUXMjs.h.call(void 0, t),"Content-Type":"application/json",...e.apiKey!=null?{Authorization:`Bearer ${e.apiKey}`}:{}},o=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(_chunkDOJICJCQjs.e+o,{method:"POST",headers:n,body:JSON.stringify(e)});return r.ok?{status:"ok",redirectURL:(await r.json()).url}:{...Br(r.status,await Xo(r)),status:"error"}}function qt(){if(typeof localStorage>"u")return;let e=localStorage.getItem("bitsnap-ref");if(e!=null)return e}function Fr(e){let t=qt();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 = On; exports.g = gt; exports.h = yt; exports.i = Ze; exports.j = Qe; exports.k = xa; exports.l = Ue; exports.m = Ws; exports.n = bm; exports.o = vm; exports.p = km; exports.q = xm; exports.r = at; exports.s = il; exports.t = Go; exports.u = zr; exports.v = Rm; exports.w = qt; exports.x = Fr; exports.y = Np; exports.z = Ip; exports.A = Sp; exports.B = _; exports.C = Eo; exports.D = Rr; exports.E = Tp; exports.F = Ar; exports.G = cs; exports.H = Ds; exports.I = jr; exports.J = rm; exports.K = st; exports.L = nm; exports.M = om; exports.N = zs; exports.O = am; exports.P = im; exports.Q = Hs; exports.R = sm; exports.S = lm; exports.T = dm; exports.U = cm; exports.V = um; exports.W = pm; exports.X = mm; exports.Y = Hr;
|
|
5
|
-
//# sourceMappingURL=chunk-KHQEDQYF.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/emems-chat-v1/dist/chunk-KHQEDQYF.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","t"],"mappings":"AAAA,ylCAAgN,sDAAyC,sDAA+F,sDAAyF,sDAAiF,sDAA+E,sDAAyE,sDAAgE,oDCA3rB,+BACwB,+CCKnD,SAFKA,EAAAA,CAAK,CAAE,SAAA,CAAAC,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CAClE,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,MAAA,CACV,SAAA,CAAWC,gCAAAA,mFACT,CACAH,CACF,CAAA,CACC,GAAGC,CAAAA,CACN,CAEJ,CAEA,SAASG,EAAAA,CAAW,CAAE,SAAA,CAAAJ,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CACxE,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,aAAA,CACV,SAAA,CAAWC,gCAAAA,0JACT,CACAH,CACF,CAAA,CACC,GAAGC,CAAAA,CACN,CAEJ,CAEA,SAASI,EAAAA,CAAU,CAAE,SAAA,CAAAL,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CACvE,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,YAAA,CACV,SAAA,CAAWC,gCAAAA,4BAAG,CAA8BH,CAAS,CAAA,CACpD,GAAGC,CAAAA,CACN,CAEJ,CAEA,SAASK,EAAAA,CAAgB,CAAE,SAAA,CAAAN,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CAC7E,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,kBAAA,CACV,SAAA,CAAWC,gCAAAA,+BAAG,CAAiCH,CAAS,CAAA,CACvD,GAAGC,CAAAA,CACN,CAEJ,CAeA,SAASM,EAAAA,CAAY,CAAE,SAAA,CAAAP,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CACzE,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,cAAA,CACV,SAAA,CAAWC,gCAAAA,MAAG,CAAQH,CAAS,CAAA,CAC9B,GAAGC,CAAAA,CACN,CAEJ,CCvEA,2CAA4B,IA6BtBO,EAAAA,CAAQ,yCAAA,CAERC,EAAAA,CACJ,0MAAA,CAEIC,EAAAA,CAAiB,IAAI,GAAA,CAAI,CAAC,cAAA,CAAgB,eAAA,CAAiB,qBAAqB,CAAC,CAAA,CACjFC,EAAAA,CACJ,sNAAA,CAOK,SAASC,EAAAA,CAAmB,CACjC,KAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CAAgB,CAAA,CAAA,CAChB,gBAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,SAAA,CAAAlB,CAAAA,CACA,eAAA,CAAAmB,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAA4B,CAC1B,IAAMC,CAAAA,CAAMC,2BAAAA,CAAM,CACZC,CAAAA,kBAAUN,CAAAA,SAAgB,CAAA,EAAA;ACGlB,QAAA;ACLmC,YAAA;AC4zB3BO","file":"/home/emems/.t3/worktrees/bitsnap-react/emems-chat-v1/dist/chunk-KHQEDQYF.js","sourcesContent":[null,"import { useAutoAnimate } from \"@formkit/auto-animate/react\";\nimport { useEffect, useMemo, type CSSProperties } from \"react\";\nimport {\n InstrumentProvider,\n useInstrument,\n useInstrumentContext,\n type AnalyticsOption,\n} from \"../../analytics/instrument\";\nimport { getLocale } from \"../../components/checkout/locale\";\nimport { rpcProvider, useMutation } from \"../../rpc-provider\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"../../ui/card\";\nimport { kindFromRpcError } from \"../../ui/email-code-login/errors\";\nimport {\n LoginBrandLogo,\n type LoginLogoOptions,\n} from \"../../ui/email-code-login/LoginBrandLogo\";\nimport { EmailCodeLoginForm } from \"../../ui/email-code-login/EmailCodeLoginForm\";\nimport { pendingLoginKey } from \"../../ui/email-code-login/pending\";\nimport {\n useEmailCodeLogin,\n type EmailCodeAdapter,\n} from \"../../ui/email-code-login/useEmailCodeLogin\";\nimport {\n getAllowedReturnOrigins,\n setAllowedReturnOrigins,\n} from \"../config\";\nimport { panelFailureKind } from \"../login-adapter\";\nimport { resolvePanelLoginTexts, type PanelLoginTexts } from \"../login-texts\";\nimport { usePanelConfig } from \"../PanelProvider\";\nimport type { PanelLoginProps } from \"../types\";\nimport {\n buildAccessTokenRedirect,\n getReturnURLFromSearch,\n persistReturnURL,\n readPersistedReturnURL,\n} from \"../return-url\";\nimport { getPanelSession, savePanelSession } from \"../session-storage\";\n\nif (typeof window !== \"undefined\") {\n const currentOrigin = window.location.origin;\n const knownSiblings = [\n currentOrigin,\n \"https://bitsnap.pl\",\n \"https://kursy.bitsnap.pl\",\n ];\n if (getAllowedReturnOrigins().length === 0) {\n setAllowedReturnOrigins(Array.from(new Set(knownSiblings)));\n }\n}\n\n\n/** Props of {@link PanelLogin}; `PanelLoginProps` of the package is a superset. */\nexport type PanelLoginComponentProps = Pick<\n PanelLoginProps,\n \"analytics\" | \"texts\" | \"locale\" | \"showLogo\" | \"logoUrl\" | \"logoDarkUrl\"\n>;\n\ntype PanelLoginResult = { accessToken: string };\n\nconst PanelLoginForm = ({\n texts,\n projectID,\n host,\n locale,\n logo,\n}: {\n texts: PanelLoginTexts;\n projectID?: string;\n host?: string;\n locale?: string;\n logo: LoginLogoOptions;\n}) => {\n const instrument = useInstrumentContext();\n const { mutateAsync: loginUserAsync } = useMutation(\n rpcProvider.publicApi.userPanelLogin,\n );\n const { mutateAsync: verifyCodeAsync } = useMutation(\n rpcProvider.publicApi.userPanelLoginWithCode,\n );\n\n const adapter = useMemo<EmailCodeAdapter<PanelLoginResult>>(\n () => ({\n async send(email) {\n try {\n const response = await loginUserAsync({ email });\n if (response.result.case === \"success\") {\n return {\n ok: true,\n retryIn: response.result.value.retryIn || undefined,\n challengeId: response.result.value.challengeId || undefined,\n };\n }\n return {\n ok: false,\n kind: panelFailureKind(\n response.result.case === \"failure\" ? response.result.value : 0,\n ),\n };\n } catch (cause) {\n return { ok: false, kind: kindFromRpcError(cause), cause };\n }\n },\n async verify({ email, code, challengeId }) {\n try {\n const response = await verifyCodeAsync({\n code: parseInt(code, 10),\n email,\n challengeId,\n });\n if (response.result.case === \"accessToken\" && response.result.value) {\n return { ok: true, value: { accessToken: response.result.value } };\n }\n return {\n ok: false,\n kind: panelFailureKind(\n response.result.case === \"failure\" ? response.result.value : 0,\n ),\n };\n } catch (cause) {\n return { ok: false, kind: kindFromRpcError(cause), cause };\n }\n },\n }),\n [loginUserAsync, verifyCodeAsync],\n );\n\n const login = useEmailCodeLogin<PanelLoginResult>({\n adapter,\n texts,\n storageKey: pendingLoginKey(\"panel\", projectID, host),\n onVerified: ({ accessToken }, email) => {\n instrument.track(\"panel_login\", {});\n savePanelSession(projectID, accessToken, email, host);\n const returnURL =\n typeof window !== \"undefined\" ? readPersistedReturnURL() : null;\n setTimeout(() => {\n if (returnURL) {\n window.location.href = buildAccessTokenRedirect(returnURL, accessToken);\n return;\n }\n window.location.reload();\n }, 100);\n },\n });\n\n const onCodeStep = login.step === \"code\";\n const title = onCodeStep && !login.needsEmail ? texts.codeTitle : texts.title;\n const description =\n onCodeStep && !login.needsEmail ? texts.codeDescription : texts.description;\n\n return (\n // Top-aligned: a vertically centred card moved when the step changed height.\n <main className=\"mx-auto flex w-full max-w-sm flex-1 flex-col justify-start pt-4 sm:pt-[12vh]\">\n <Card>\n <LoginBrandLogo\n projectId={projectID}\n locale={locale}\n className=\"px-4 sm:px-6\"\n {...logo}\n />\n <CardHeader className=\"px-4 sm:px-6\">\n <CardTitle role=\"heading\" aria-level={1} className=\"text-2xl\">\n {title}\n </CardTitle>\n <CardDescription>{description}</CardDescription>\n </CardHeader>\n <CardContent className=\"px-4 sm:px-6\">\n <EmailCodeLoginForm\n login={login}\n texts={texts}\n emailInputId=\"email\"\n codeInputId=\"verify-code\"\n />\n </CardContent>\n </Card>\n </main>\n );\n};\n\nconst PanelLoginComponentWrapper = ({\n analytics,\n texts: textOverrides,\n locale,\n showLogo,\n logoUrl,\n logoDarkUrl,\n}: PanelLoginComponentProps) => {\n const { theme, allowedReturnOrigins, projectID, host } = usePanelConfig();\n const instrument = useInstrument(projectID, analytics, \"panel\");\n const texts = useMemo(\n () => resolvePanelLoginTexts(locale ?? getLocale(), textOverrides),\n [locale, textOverrides],\n );\n\n const styles = {\n \"--button-background-color\": theme?.colors?.brand ?? \"#FFFFFF\",\n \"--button-background-color-dark\": theme?.colors?.brandDark ?? \"#000000\",\n \"--button-text-color\": theme?.colors?.brandDark ?? \"#000000\",\n \"--button-text-color-dark\": theme?.colors?.brand ?? \"#FFFFFF\",\n } as CSSProperties;\n\n const [parent] = useAutoAnimate({\n duration: 300,\n easing: \"ease-in-out\",\n disrespectUserMotionPreference: false,\n });\n\n // Already signed in: leave the login page. Declared before the return URL\n // effect below, so that one (a token redirect) wins when both apply.\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n if (getPanelSession(projectID, host) != null) {\n window.location.href = window.location.href.replaceAll(\"login\", \"\");\n }\n }, [projectID, host]);\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n if (window.parent !== window) return;\n\n const queryReturnURL = getReturnURLFromSearch(window.location.search);\n if (queryReturnURL) {\n persistReturnURL(queryReturnURL);\n }\n\n const returnURL = queryReturnURL ?? readPersistedReturnURL();\n if (!returnURL) return;\n\n const existingToken = getPanelSession(projectID, host);\n if (!existingToken) return;\n\n window.location.href = buildAccessTokenRedirect(returnURL, existingToken);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [allowedReturnOrigins, projectID, host]);\n\n return (\n <InstrumentProvider value={instrument}>\n <div className=\"bg-white text-black dark:bg-black dark:text-white\">\n <div\n className=\"font-inter flex min-h-screen w-full flex-col p-4\"\n style={styles}\n ref={parent}\n >\n <PanelLoginForm\n texts={texts}\n projectID={projectID}\n host={host}\n locale={locale}\n logo={{\n showLogo,\n logoUrl: logoUrl ?? theme?.logoURL,\n logoDarkUrl: logoDarkUrl ?? theme?.logoDarkURL,\n }}\n />\n </div>\n </div>\n </InstrumentProvider>\n );\n};\n\nexport const PanelLogin = (props: PanelLoginComponentProps = {}) => {\n return <PanelLoginComponentWrapper {...props} />;\n};\n","import * as React from \"react\"\n\nimport { cn } from \"@/src/lib/utils\"\n\nfunction Card({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card\"\n className={cn(\n \"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\"leading-none font-semibold\", className)}\n {...props}\n />\n )\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-muted-foreground text-sm\", className)}\n {...props}\n />\n )\n}\n\nfunction CardAction({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-action\"\n className={cn(\n \"col-start-2 row-span-2 row-start-1 self-start justify-self-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"px-6\", className)}\n {...props}\n />\n )\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\"flex items-center px-6 [.border-t]:pt-6\", className)}\n {...props}\n />\n )\n}\n\nexport {\n Card,\n CardHeader,\n CardFooter,\n CardTitle,\n CardAction,\n CardDescription,\n CardContent,\n}\n","import { CircleCheck } from \"lucide-react\";\nimport { useId, type FormEvent, type ReactNode } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport { Button } from \"../button\";\nimport { Input } from \"../input\";\nimport { Label } from \"../label\";\nimport { Spinner } from \"../spinner\";\nimport { OtpCodeField } from \"./OtpCodeField\";\nimport { fillText, type EmailCodeTexts } from \"./texts\";\nimport { type EmailCodeLogin } from \"./useEmailCodeLogin\";\n\nexport type EmailCodeLoginFormProps = {\n login: EmailCodeLogin;\n texts: EmailCodeTexts;\n /** Offers \"I already have a code\" under the e-mail step. */\n allowHaveCode?: boolean;\n /** Overrides the e-mail input placeholder. */\n emailPlaceholder?: string;\n /** `id` of the e-mail input; unique per instance by default. */\n emailInputId?: string;\n /** `id` of the code input; unique per instance by default. */\n codeInputId?: string;\n className?: string;\n /** Classes of the two primary buttons (brand colors). */\n buttonClassName?: string;\n /** Shown above the fields of the code step, after the \"sent to\" line. */\n children?: ReactNode;\n};\n\nconst MUTED = \"text-muted-foreground text-xs leading-5\";\n/** Borders of the dark theme: the `input` token is nearly the card colour. */\nconst DARK_FIELD =\n \"dark:border-foreground/30 dark:focus-visible:border-foreground/70 dark:focus-visible:ring-foreground/25 dark:aria-invalid:border-destructive-foreground dark:aria-invalid:ring-destructive-foreground/30\";\n/** Failures about the address itself; a throttled or failed send is not. */\nconst EMAIL_FAILURES = new Set([\"invalidEmail\", \"emailNotFound\", \"deliveryUnavailable\"]);\nconst LINK =\n \"inline-flex min-h-11 items-center px-1 text-sm underline underline-offset-4 hover:no-underline focus-visible:ring-[3px] focus-visible:ring-ring/50 rounded-sm outline-none disabled:opacity-50 disabled:no-underline\";\n\n/**\n * The two steps of the shared e-mail-code login. Markup only: all state comes\n * from {@link useEmailCodeLogin}. The surface wraps it in its own card or\n * dialog and renders the titles.\n */\nexport function EmailCodeLoginForm({\n login,\n texts,\n allowHaveCode = true,\n emailPlaceholder,\n emailInputId,\n codeInputId,\n className,\n buttonClassName,\n children,\n}: EmailCodeLoginFormProps) {\n const uid = useId();\n const emailId = emailInputId ?? `${uid}-email`;\n const codeId = codeInputId ?? `${uid}-code`;\n const noticeId = `${uid}-notice`;\n const hintId = `${uid}-hint`;\n\n const { notice } = login;\n const isError = notice?.kind === \"error\";\n const sending = login.busy === \"send\";\n const verifying = login.busy === \"verify\";\n const resending = login.busy === \"resend\";\n const buttonBase = cn(\"h-11 w-full\", buttonClassName);\n\n // Both live regions stay mounted (empty) so that a screen reader has\n // registered them before a message is put in; only their text changes.\n // The area reserves two lines, so a longer message does not push the buttons.\n const success = notice?.kind === \"success\";\n const noticeArea = (\n <div id={noticeId} className=\"min-h-10 text-sm leading-5\">\n <p\n role=\"alert\"\n className=\"font-medium text-red-700 dark:text-red-400\"\n >\n {isError ? notice.text : null}\n </p>\n <p\n role=\"status\"\n className={cn(\n \"flex items-start gap-1.5\",\n success\n ? \"font-medium text-emerald-700 dark:text-emerald-400\"\n : \"text-foreground\",\n )}\n >\n {success && <CircleCheck aria-hidden className=\"mt-0.5 size-4 shrink-0\" />}\n <span>{notice != null && !isError ? notice.text : null}</span>\n </p>\n </div>\n );\n const emailInvalid =\n isError &&\n login.step === \"email\" &&\n (notice.failure == null || EMAIL_FAILURES.has(notice.failure));\n\n const announcer = (\n <p className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n {login.announcement}\n </p>\n );\n\n const emailField = (\n <div className=\"grid gap-2\">\n <Label htmlFor={emailId}>{texts.emailLabel}</Label>\n <Input\n id={emailId}\n ref={login.emailRef}\n name=\"email\"\n type=\"email\"\n autoComplete=\"email\"\n inputMode=\"email\"\n autoCapitalize=\"none\"\n autoCorrect=\"off\"\n spellCheck={false}\n autoFocus\n required\n className={cn(\n \"h-11 text-base disabled:opacity-100 disabled:text-foreground/70\",\n DARK_FIELD,\n )}\n placeholder={emailPlaceholder ?? texts.emailPlaceholder}\n value={login.email}\n disabled={login.isBusy}\n aria-invalid={emailInvalid ? true : undefined}\n aria-describedby={noticeId}\n onChange={(event) => login.setEmail(event.target.value)}\n />\n </div>\n );\n\n if (login.step === \"email\") {\n return (\n <form\n noValidate\n className={cn(\"flex flex-col gap-4\", className)}\n onSubmit={(event: FormEvent) => {\n event.preventDefault();\n void login.sendCode();\n }}\n >\n {announcer}\n {emailField}\n {noticeArea}\n <Button\n type=\"submit\"\n disabled={login.isBusy}\n aria-busy={sending}\n className={buttonBase}\n >\n {sending && <Spinner aria-hidden />}\n {sending ? texts.sending : texts.sendCode}\n </Button>\n {allowHaveCode && (\n <p className=\"flex flex-wrap items-center justify-center text-center text-sm\">\n {texts.haveCodePrompt !== \"\" && <span>{texts.haveCodePrompt}</span>}\n <button\n type=\"button\"\n className={LINK}\n disabled={login.isBusy}\n onClick={login.haveCode}\n >\n {texts.haveCode}\n </button>\n </p>\n )}\n </form>\n );\n }\n\n const [before, after] = texts.codeSentTo.split(\"{email}\");\n const dead = login.dead != null;\n const resendLabel = dead\n ? texts.resendNew\n : login.secondsLeft > 0\n ? fillText(texts.resendIn, { seconds: login.secondsLeft })\n : texts.resend;\n\n return (\n <form\n noValidate\n className={cn(\"flex flex-col gap-4\", className)}\n onSubmit={(event: FormEvent) => {\n event.preventDefault();\n void login.submitCode();\n }}\n >\n {announcer}\n {login.needsEmail ? (\n emailField\n ) : (\n <div className=\"flex flex-wrap items-center justify-between gap-x-2\">\n {/* The address moves to its own line before it is cut; the word\n joiner keeps the full stop with it. */}\n <p className=\"min-w-0 flex-[1_1_14rem] text-sm leading-5 break-words\">\n {before}\n <strong className=\"font-semibold\">{login.email}</strong>\n {\"\\u2060\"}\n {after}\n </p>\n <button\n type=\"button\"\n className={cn(LINK, \"-ml-1 shrink-0\")}\n disabled={login.isBusy}\n onClick={login.changeEmail}\n >\n {texts.changeEmail}\n </button>\n </div>\n )}\n {children}\n <div className=\"grid gap-2\">\n <Label htmlFor={codeId}>{texts.codeLabel}</Label>\n <OtpCodeField\n id={codeId}\n name=\"code\"\n inputRef={login.codeRef}\n value={login.code}\n onChange={login.setCode}\n onComplete={(value) => void login.submitCode(value)}\n disabled={login.isBusy || dead}\n invalid={isError && !login.needsEmail}\n aria-describedby={`${noticeId} ${hintId}`}\n />\n <p id={hintId} className={MUTED}>\n {texts.validity} {texts.spamHint}\n </p>\n </div>\n {noticeArea}\n <Button\n type=\"submit\"\n disabled={login.isBusy || dead}\n aria-busy={verifying}\n className={buttonBase}\n >\n {verifying && <Spinner aria-hidden />}\n {verifying ? texts.verifying : texts.verify}\n </Button>\n {login.needsEmail ? (\n <div className=\"flex justify-center\">\n <button\n type=\"button\"\n className={LINK}\n disabled={login.isBusy}\n onClick={login.changeEmail}\n >\n {texts.noCode}\n </button>\n </div>\n ) : (\n <Button\n type=\"button\"\n variant={dead ? \"default\" : \"outline\"}\n disabled={login.isBusy || (!dead && login.secondsLeft > 0)}\n aria-busy={resending}\n className={dead ? buttonBase : \"h-11 w-full\"}\n onClick={() => void login.resend()}\n >\n {resending && <Spinner aria-hidden />}\n {resendLabel}\n </Button>\n )}\n </form>\n );\n}\n","const URL_REGEX =\n /https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)/g;\n\ntype Replacements = {\n url: string;\n startIndex: number;\n endIndex: number;\n replacementText?: string;\n};\n\nconst findURLIndices = (text: string) => {\n const matches = [...text.matchAll(URL_REGEX)];\n return matches.map(\n (match) =>\n ({\n url: match[0],\n startIndex: match.index,\n endIndex: match.index + match[0].length - 1,\n }) as Replacements,\n );\n};\n\nconst replaceTextByIndices = (\n originalText: string,\n replacements: Replacements[],\n) => {\n let result = \"\";\n let lastIndex = 0;\n\n // Sort replacements by startIndex to handle them in order\n replacements.sort((a, b) => a.startIndex - b.startIndex);\n\n for (const { startIndex, endIndex, replacementText } of replacements) {\n // Append text before the current replacement\n result += originalText.slice(lastIndex, startIndex);\n // Append the replacement text\n result += replacementText;\n // Update lastIndex to after the replaced segment\n lastIndex = endIndex + 1;\n }\n\n // Append any remaining text after the last replacement\n result += originalText.slice(lastIndex);\n\n return result;\n};\n\nexport const renderText = (txt: string) => {\n const urlIndices = findURLIndices(txt);\n\n return (\n <p\n dangerouslySetInnerHTML={{\n __html: replaceTextByIndices(\n txt,\n urlIndices.map((el) => {\n el[\"replacementText\"] =\n `<a key=${el.url} href=${el.url} style=\"text-decoration: underline;\" target=\"_blank\">\n ${el.url}\n </a>`;\n return el;\n }),\n ),\n }}\n ></p>\n );\n};\n","/** Skip length of the player buttons and of the lock-screen skip handlers. */\nexport const SEEK_STEP_SECONDS = 10;\n\n/** Under this position \"previous track\" restarts the chapter instead of going back. */\nexport const PREVIOUS_TRACK_RESTART_SECONDS = 3;\n\nexport type MediaSessionArtwork = {\n src: string;\n sizes?: string;\n type?: string;\n};\n\nexport type MediaSessionMetadata = {\n title: string;\n album?: string;\n artist?: string;\n artwork?: string | MediaSessionArtwork | (string | MediaSessionArtwork)[];\n};\n\nconst MIME_BY_EXTENSION: Record<string, string> = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n avif: \"image/avif\",\n svg: \"image/svg+xml\",\n};\n\n/** Lock-screen artwork size we declare; the player does not decode the image. */\nconst ARTWORK_SIZES = \"512x512\";\n\nfunction mediaSessionAvailable(): boolean {\n return (\n typeof navigator != \"undefined\" &&\n typeof navigator.mediaSession != \"undefined\"\n );\n}\n\n/**\n * Turns an image URL into a media-session artwork entry. The `type` comes from\n * the file extension and is omitted when the extension is unknown, so the\n * browser does not get a wrong MIME type.\n */\nexport function mediaSessionArtworkFromUrl(url: string): MediaSessionArtwork {\n if (typeof url != \"string\" || url.length === 0) {\n return { src: url, sizes: ARTWORK_SIZES };\n }\n const withoutQuery = url.split(/[?#]/)[0];\n const extension = withoutQuery.includes(\".\")\n ? withoutQuery.slice(withoutQuery.lastIndexOf(\".\") + 1).toLowerCase()\n : \"\";\n const type = MIME_BY_EXTENSION[extension];\n const artwork: MediaSessionArtwork = { src: url, sizes: ARTWORK_SIZES };\n if (type != null) {\n artwork.type = type;\n }\n return artwork;\n}\n\nfunction normalizeArtwork(\n artwork: MediaSessionMetadata[\"artwork\"],\n): MediaSessionArtwork[] | undefined {\n if (artwork == null) {\n return undefined;\n }\n const entries = Array.isArray(artwork) ? artwork : [artwork];\n const normalized: MediaSessionArtwork[] = [];\n for (const entry of entries) {\n if (typeof entry === \"string\") {\n if (entry.length > 0) {\n normalized.push(mediaSessionArtworkFromUrl(entry));\n }\n continue;\n }\n if (entry != null && entry.src.length > 0) {\n normalized.push({\n src: entry.src,\n sizes: entry.sizes ?? ARTWORK_SIZES,\n ...(entry.type != null ? { type: entry.type } : {}),\n });\n }\n }\n return normalized.length > 0 ? normalized : undefined;\n}\n\nexport function mediaSessionSetMetadata(metadata: MediaSessionMetadata) {\n if (\n !mediaSessionAvailable() ||\n typeof MediaMetadata == \"undefined\"\n ) {\n return;\n }\n navigator.mediaSession.metadata = new MediaMetadata({\n title: metadata.title,\n album: metadata.album,\n artist: metadata.artist,\n artwork: normalizeArtwork(metadata.artwork),\n });\n}\n\nexport function mediaSessionPlay() {\n if (!mediaSessionAvailable()) return;\n navigator.mediaSession.playbackState = \"playing\";\n}\n\nexport function mediaSessionPause() {\n if (!mediaSessionAvailable()) return;\n navigator.mediaSession.playbackState = \"paused\";\n}\n\n/**\n * Reports duration, position and the real playback rate to the lock screen.\n * `setPositionState` throws on values it does not accept (no duration yet,\n * position past the end), so those calls are skipped or clamped.\n */\nexport function mediaSessionUpdateDurationAndPosition(\n duration: number | undefined,\n currentTime: number | undefined,\n playbackRate = 1,\n) {\n if (!mediaSessionAvailable()) return;\n if (duration == null || !Number.isFinite(duration) || duration <= 0) {\n return;\n }\n if (currentTime != null && isNaN(currentTime)) {\n return;\n }\n const position = Math.min(Math.max(currentTime ?? 0, 0), duration);\n const rate =\n Number.isFinite(playbackRate) && playbackRate > 0 ? playbackRate : 1;\n try {\n navigator.mediaSession.setPositionState({\n playbackRate: rate,\n duration,\n position,\n });\n } catch (e) {\n // Older browsers reject some combinations; the lock screen just keeps the\n // previous state.\n }\n}\n\nconst MEDIA_SESSION_ACTIONS: MediaSessionAction[] = [\n \"play\",\n \"pause\",\n \"stop\",\n \"seekbackward\",\n \"seekforward\",\n \"seekto\",\n \"previoustrack\",\n \"nexttrack\",\n];\n\nexport function startMediaSessionCoordinator(args: {\n title: string;\n album?: string;\n artist?: string;\n artwork?: MediaSessionMetadata[\"artwork\"];\n\n action: (details: MediaSessionActionDetails) => void;\n}) {\n if (!mediaSessionAvailable()) return;\n\n mediaSessionSetMetadata({\n title: args.title,\n album: args.album,\n artist: args.artist,\n artwork: args.artwork,\n });\n\n for (const action of MEDIA_SESSION_ACTIONS) {\n try {\n navigator.mediaSession.setActionHandler(action, (details) => {\n args.action(details);\n });\n } catch (e) {\n // The browser does not support this action (e.g. nexttrack).\n }\n }\n}\n\nexport function stopMediaSessionCoordinator() {\n if (!mediaSessionAvailable()) return;\n navigator.mediaSession.metadata = null;\n for (const action of MEDIA_SESSION_ACTIONS) {\n try {\n navigator.mediaSession.setActionHandler(action, null);\n } catch (e) {\n // Unsupported action; nothing to clear.\n }\n }\n}\n","import Hls from \"hls.js\";\nimport { Pause, Play, SkipBack, SkipForward } from \"lucide-react\";\nimport {\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n type CSSProperties,\n} from \"react\";\nimport { cn } from \"../../lib/utils\";\nimport { Button } from \"../../ui/button\";\nimport LoadingIndicator from \"../LoadingIndicator\";\nimport {\n createHlsSource,\n playerErrorFromMediaError,\n prefersNativeHls,\n type HlsSource,\n type PlayerError,\n} from \"./hls-engine\";\nimport {\n PREVIOUS_TRACK_RESTART_SECONDS,\n SEEK_STEP_SECONDS,\n mediaSessionPause,\n mediaSessionPlay,\n mediaSessionSetMetadata,\n mediaSessionUpdateDurationAndPosition,\n startMediaSessionCoordinator,\n stopMediaSessionCoordinator,\n} from \"./media.session.coordinator\";\n\nimport \"./audio-player.css\";\nimport { useAudioTexts, formatTime } from \"./texts\";\nimport { playerStorage, SPEED_KEY, SPEEDS } from \"./storage\";\n\nexport type ChapterWithPublicUrl = {\n id: string;\n multimediaId?: string;\n name: string;\n description?: string;\n publicUrl: string;\n downloadableUrl?: string;\n duration?: number;\n};\n\n/** What the player could not play; `status` is the HTTP status when known. */\nexport type AudioPlayerError = PlayerError;\n\nexport type AudioPlayerMethods = {\n selectChapter: (chapter: ChapterWithPublicUrl) => void;\n /** Loads the current chapter again after an error, keeping the position. */\n retry: () => void;\n /** The error currently shown, if any. */\n getError: () => AudioPlayerError | null;\n};\n\ntype AudioPlayerProps = {\n locale?: string;\n chapters: ChapterWithPublicUrl[];\n styles: CSSProperties;\n updateCurrentTime?: (currentTime: number) => void;\n\n title?: string;\n imageURL?: string;\n /** Hide the repeated visual heading when the desktop details show the cover beside it. */\n coverShownBeside?: boolean;\n /** Book author, used as the lock-screen artist. */\n author?: string;\n\n setCurrentTimeHandler?: (seekTo: (second: number) => void) => void;\n uniqueProductID: string;\n\n onChapterChange?: (chapter: ChapterWithPublicUrl) => void;\n /** A fatal playback error the player could not recover from. */\n onError?: (error: AudioPlayerError) => void;\n /** The signed URL returned 401/403; the owner should refetch the chapters. */\n onExpiredUrl?: () => void;\n /** The last chapter ended. */\n onFinished?: () => void;\n};\n\nconst AudioPlayer = forwardRef<AudioPlayerMethods, AudioPlayerProps>(\n (\n {\n chapters,\n locale,\n styles,\n updateCurrentTime,\n setCurrentTimeHandler,\n title,\n imageURL,\n coverShownBeside,\n author,\n uniqueProductID,\n onChapterChange,\n onError,\n onExpiredUrl,\n onFinished,\n },\n ref,\n ) => {\n const t = useAudioTexts(locale);\n const [speed, setSpeed] = useState(1);\n const speedRef = useRef(1);\n const [chapterID, setChapterID] = useState<string>();\n const [sleepMode, setSleepMode] = useState(\"off\");\n const [sleepRemaining, setSleepRemaining] = useState(0);\n const sleepRef = useRef<{ mode: string; deadline: number }>({\n mode: \"off\",\n deadline: 0,\n });\n\n function cancelSleep() {\n sleepRef.current = { mode: \"off\", deadline: 0 };\n setSleepMode(\"off\");\n setSleepRemaining(0);\n }\n function changeSleep(mode: string) {\n const seconds = Number(mode) * 60;\n sleepRef.current = {\n mode,\n deadline: Number.isFinite(seconds) ? Date.now() + seconds * 1000 : 0,\n };\n setSleepMode(mode);\n setSleepRemaining(Number.isFinite(seconds) ? seconds : 0);\n }\n function changeSpeed(rate: number) {\n if (!SPEEDS.includes(rate)) return;\n setSpeed(rate);\n speedRef.current = rate;\n playerStorage.set(SPEED_KEY, String(rate));\n if (videoRef.current) videoRef.current.playbackRate = rate;\n updatePlayerDetails();\n }\n useEffect(() => {\n const saved = Number(playerStorage.get(SPEED_KEY));\n if (SPEEDS.includes(saved)) changeSpeed(saved);\n const timer = setInterval(() => {\n const { mode, deadline } = sleepRef.current;\n if (mode === \"off\" || mode === \"chapter\") return;\n const remaining = Math.max(\n 0,\n Math.ceil((deadline - Date.now()) / 1000),\n );\n setSleepRemaining(remaining);\n if (remaining === 0) {\n playWhenReadyRef.current = false;\n pause();\n cancelSleep();\n }\n }, 1000);\n return () => clearInterval(timer);\n }, []);\n\n enum PlayState {\n Playing,\n Paused,\n }\n\n const [playState, setPlayState] = useState<PlayState>(PlayState.Paused);\n const [currentTime, setCurrentTime] = useState<number | undefined>(\n undefined,\n );\n const [duration, setDuration] = useState<number | undefined>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n const [playerError, setPlayerError] = useState<AudioPlayerError | null>(\n null,\n );\n\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const hlsRef = useRef<HlsSource | null>(null);\n const timerRef = useRef<ReturnType<typeof setInterval> | undefined>(\n undefined,\n );\n\n const audioPlayerContainerRef = useRef<HTMLDivElement>(null!);\n\n const currentChapterRef = useRef<ChapterWithPublicUrl | null>(null);\n const playerErrorRef = useRef<AudioPlayerError | null>(null);\n\n /** Set by a user action; the next `loadeddata` starts playback once. */\n const playWhenReadyRef = useRef(false);\n /** Position restored for the chapter that is loading, once. */\n const resumedRef = useRef(false);\n /** Position to restore instead of the remembered one (URL refresh, retry). */\n const pendingSeekRef = useRef<number | null>(null);\n /** Chapter URL that already asked the owner for a fresh signed URL. */\n const expiredUrlRef = useRef<string | null>(null);\n const chaptersRef = useRef(chapters);\n const chaptersSignatureRef = useRef<string | null>(null);\n\n // The owner passes new callbacks on every render; the player must keep the\n // current ones without restarting playback.\n const callbacksRef = useRef({\n onChapterChange,\n onError,\n onExpiredUrl,\n onFinished,\n updateCurrentTime,\n title,\n imageURL,\n author,\n });\n callbacksRef.current = {\n onChapterChange,\n onError,\n onExpiredUrl,\n onFinished,\n updateCurrentTime,\n title,\n imageURL,\n author,\n };\n\n function saveLastPlayedTime(timeInSeconds: number) {\n if (\n !resumedRef.current ||\n !Number.isFinite(timeInSeconds) ||\n timeInSeconds < 0\n ) {\n return;\n }\n playerStorage.set(\n `__player__${uniqueProductID}_${currentChapterRef.current?.id}`,\n `${Math.floor(timeInSeconds)}`,\n );\n }\n\n function getLastPlayedTime(): number | undefined {\n const time = playerStorage.get(\n `__player__${uniqueProductID}_${currentChapterRef.current?.id}`,\n );\n\n if (time == null) {\n return undefined;\n }\n try {\n const result = parseInt(time);\n\n if (isNaN(result) || result < 0) {\n return undefined;\n }\n\n return result;\n } catch (e) {\n return undefined;\n }\n }\n\n function getLastSelectedChapterID(): string | undefined {\n const lastSelectedChapterID = playerStorage.get(\n `__player__${uniqueProductID}_last_chapter`,\n );\n if (lastSelectedChapterID == null) {\n return undefined;\n }\n return lastSelectedChapterID;\n }\n\n function setLastSelectedChapterID(chapterID: string) {\n playerStorage.set(`__player__${uniqueProductID}_last_chapter`, chapterID);\n }\n\n function deleteMemoryChapter(chapterID: string) {\n playerStorage.remove(`__player__${uniqueProductID}_${chapterID}`);\n }\n\n function syncMediaSessionMetadata(chapter: ChapterWithPublicUrl | null) {\n mediaSessionSetMetadata({\n title: chapter?.name ?? callbacksRef.current.title ?? \"\",\n album: callbacksRef.current.title,\n artist: callbacksRef.current.author,\n artwork: callbacksRef.current.imageURL,\n });\n }\n\n function reportError(error: AudioPlayerError) {\n playerErrorRef.current = error;\n setPlayerError(error);\n setIsLoading(false);\n callbacksRef.current.onError?.(error);\n }\n\n function clearError() {\n playerErrorRef.current = null;\n setPlayerError(null);\n }\n\n function attemptPlay() {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n const result = video.play() as Promise<void> | undefined;\n if (result != null && typeof result.catch == \"function\") {\n result.catch(() => {\n // The browser blocked playback; the user presses play.\n });\n }\n updatePlayerDetails();\n }\n\n function play() {\n attemptPlay();\n }\n\n function pause() {\n videoRef.current?.pause();\n updatePlayerDetails();\n }\n\n function togglePlayState() {\n if (playState === PlayState.Playing) {\n pause();\n return;\n }\n play();\n }\n\n function seekTo(toSecond: number) {\n const video = videoRef.current;\n if (video == null || !Number.isFinite(toSecond)) {\n return;\n }\n const knownDuration = Number.isFinite(video.duration)\n ? video.duration\n : 0;\n const target =\n knownDuration > 0\n ? Math.min(Math.max(toSecond, 0), knownDuration)\n : Math.max(toSecond, 0);\n setCurrentTime(target);\n video.currentTime = target;\n updatePlayerDetails();\n }\n\n function seekBy(seconds: number) {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n const knownDuration = Number.isFinite(video.duration)\n ? video.duration\n : undefined;\n let target = Math.max(video.currentTime + seconds, 0);\n if (knownDuration != null && target > knownDuration) {\n target = knownDuration;\n }\n seekTo(target);\n }\n\n function loadSource(src: string) {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n clearError();\n setIsLoading(true);\n\n if (prefersNativeHls(video)) {\n destroyHls();\n video.src = src;\n video.load();\n return;\n }\n\n if (Hls.isSupported()) {\n if (hlsRef.current == null) {\n hlsRef.current = createHlsSource({\n media: video,\n handlers: {\n onError: (error) => {\n reportError(error);\n },\n onExpiredUrl: () => {\n callbacksRef.current.onExpiredUrl?.();\n },\n },\n });\n }\n hlsRef.current.load(src);\n return;\n }\n\n // No Media Source and no native HLS: let the browser try the URL itself.\n destroyHls();\n video.src = src;\n video.load();\n }\n\n function destroyHls() {\n hlsRef.current?.destroy();\n hlsRef.current = null;\n }\n\n function playChapter(\n chapter: ChapterWithPublicUrl,\n options?: { play?: boolean },\n ) {\n const shouldPlay = options?.play === true;\n if (\n currentChapterRef.current &&\n videoRef.current &&\n !videoRef.current.ended\n ) {\n saveLastPlayedTime(videoRef.current.currentTime);\n }\n resumedRef.current = false;\n pendingSeekRef.current = null;\n playWhenReadyRef.current = shouldPlay;\n currentChapterRef.current = chapter;\n setChapterID(chapter.id);\n setCurrentTime(0);\n setDuration(chapter.duration);\n loadSource(chapter.publicUrl);\n syncMediaSessionMetadata(chapter);\n callbacksRef.current.onChapterChange?.(chapter);\n setLastSelectedChapterID(chapter.id);\n }\n\n function loadChapters(list: ChapterWithPublicUrl[]) {\n if (list.length === 0) {\n return;\n }\n\n const chapterID = getLastSelectedChapterID();\n const chapter =\n (chapterID != null\n ? list.find((candidate) => candidate.id === chapterID)\n : undefined) ?? list[0];\n\n // Mount and content changes never start playback on their own.\n playChapter(chapter, { play: false });\n }\n\n function playNextChapter() {\n const list = chaptersRef.current;\n const current = currentChapterRef.current;\n if (list == null || list.length === 0 || current == null) {\n return;\n }\n const currentChapterIndex = list.findIndex(\n (chapter) => chapter.id === current.id,\n );\n if (currentChapterIndex === -1) {\n return;\n }\n const nextChapterIndex = currentChapterIndex + 1;\n if (nextChapterIndex >= list.length) {\n finishPlayback(current);\n return;\n }\n playChapter(list[nextChapterIndex], { play: true });\n }\n\n function playPreviousChapter() {\n const list = chaptersRef.current;\n const current = currentChapterRef.current;\n if (current == null) {\n return;\n }\n const video = videoRef.current;\n if (video != null && video.currentTime > PREVIOUS_TRACK_RESTART_SECONDS) {\n seekTo(0);\n return;\n }\n const currentChapterIndex =\n list == null\n ? -1\n : list.findIndex((chapter) => chapter.id === current.id);\n if (currentChapterIndex > 0) {\n playChapter(list[currentChapterIndex - 1], { play: true });\n return;\n }\n seekTo(0);\n }\n\n function finishPlayback(chapter: ChapterWithPublicUrl) {\n // The chapter is done: no resume point, and the element stays at the end.\n deleteMemoryChapter(chapter.id);\n playWhenReadyRef.current = false;\n videoRef.current?.pause();\n setPlayState(PlayState.Paused);\n callbacksRef.current.onFinished?.();\n }\n\n function handleEnded() {\n const current = currentChapterRef.current;\n if (current == null) {\n return;\n }\n playerStorage.set(\n `__player__${uniqueProductID}_${current.id}_completed`,\n \"true\",\n );\n deleteMemoryChapter(current.id);\n if (sleepRef.current.mode === \"chapter\") {\n playWhenReadyRef.current = false;\n pause();\n cancelSleep();\n return;\n }\n playNextChapter();\n updatePlayerDetails();\n }\n\n function handleLoadedData() {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n setIsLoading(false);\n video.playbackRate = speedRef.current;\n expiredUrlRef.current = null;\n if (!resumedRef.current) {\n resumedRef.current = true;\n const pending = pendingSeekRef.current;\n pendingSeekRef.current = null;\n if (pending != null) {\n seekTo(pending);\n } else {\n const lastPlayedTime = getLastPlayedTime();\n if (lastPlayedTime != null) {\n seekTo(lastPlayedTime);\n }\n }\n }\n if (playWhenReadyRef.current) {\n playWhenReadyRef.current = false;\n attemptPlay();\n }\n }\n\n function handleMediaElementError() {\n const mediaError = videoRef.current?.error;\n const src = currentChapterRef.current?.publicUrl;\n // Safari plays HLS itself and reports an expired signed URL as a network\n // error (2) or an unsupported source (4). Ask for a fresh URL once per\n // URL; an error that repeats after that refresh is a real error.\n const refreshable = mediaError?.code === 2 || mediaError?.code === 4;\n if (\n refreshable &&\n hlsRef.current == null &&\n src != null &&\n expiredUrlRef.current !== src\n ) {\n expiredUrlRef.current = src;\n callbacksRef.current.onExpiredUrl?.();\n }\n reportError(playerErrorFromMediaError(mediaError));\n }\n\n function retry() {\n const chapter = currentChapterRef.current;\n const src = chapter?.publicUrl ?? hlsRef.current?.src;\n if (src == null) {\n return;\n }\n const video = videoRef.current;\n const position = video?.currentTime ?? 0;\n clearError();\n resumedRef.current = false;\n pendingSeekRef.current = position > 0 ? position : null;\n setCurrentTime(position);\n if (hlsRef.current != null) {\n hlsRef.current.retry();\n } else {\n loadSource(src);\n }\n }\n\n function handleMediaSessionAction(details: MediaSessionActionDetails) {\n switch (details.action) {\n case \"play\":\n play();\n break;\n case \"pause\":\n case \"stop\":\n pause();\n break;\n case \"seekbackward\":\n seekBy(-(details.seekOffset ?? SEEK_STEP_SECONDS));\n break;\n case \"seekforward\":\n seekBy(details.seekOffset ?? SEEK_STEP_SECONDS);\n break;\n case \"seekto\":\n // A seek to 0 is valid: only a missing time is ignored.\n if (details.seekTime != null) {\n seekTo(details.seekTime);\n }\n break;\n case \"previoustrack\":\n playPreviousChapter();\n break;\n case \"nexttrack\":\n playNextChapter();\n break;\n default:\n break;\n }\n }\n\n useImperativeHandle(ref, () => {\n return {\n selectChapter: (chapter: ChapterWithPublicUrl) => {\n playChapter(chapter, { play: true });\n },\n retry,\n getError: () => playerErrorRef.current,\n };\n });\n\n function updatePlayerDetails() {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n setPlayState(video.paused ? PlayState.Paused : PlayState.Playing);\n setDuration(video.duration);\n setCurrentTime(video.currentTime);\n if (!video.ended) {\n saveLastPlayedTime(video.currentTime);\n }\n mediaSessionUpdateDurationAndPosition(\n video.duration,\n video.currentTime,\n video.playbackRate,\n );\n if (\n video.networkState === video.NETWORK_LOADING &&\n video.readyState <= video.HAVE_FUTURE_DATA\n ) {\n setIsLoading(true);\n } else {\n setIsLoading(false);\n }\n callbacksRef.current.updateCurrentTime?.(video.currentTime);\n }\n\n // Lock-screen handlers are registered once; they read refs, so they always\n // see the current chapters and callbacks.\n useEffect(() => {\n startMediaSessionCoordinator({\n title: title ?? \"\",\n album: title,\n artist: author,\n artwork: imageURL,\n action: handleMediaSessionAction,\n });\n\n return () => {\n stopMediaSessionCoordinator();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // The book title, cover or author arrive after the details request.\n useEffect(() => {\n syncMediaSessionMetadata(currentChapterRef.current);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [title, author, imageURL]);\n\n useEffect(() => {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n video.addEventListener(\"loadeddata\", handleLoadedData);\n video.addEventListener(\"ended\", handleEnded);\n video.addEventListener(\"error\", handleMediaElementError);\n video.addEventListener(\"timeupdate\", updatePlayerDetails);\n video.addEventListener(\"play\", updatePlayerDetails);\n video.addEventListener(\"pause\", updatePlayerDetails);\n video.addEventListener(\"ratechange\", updatePlayerDetails);\n\n updatePlayerDetails();\n timerRef.current = setInterval(updatePlayerDetails, 500);\n\n return () => {\n video.removeEventListener(\"loadeddata\", handleLoadedData);\n video.removeEventListener(\"ended\", handleEnded);\n video.removeEventListener(\"error\", handleMediaElementError);\n video.removeEventListener(\"timeupdate\", updatePlayerDetails);\n video.removeEventListener(\"play\", updatePlayerDetails);\n video.removeEventListener(\"pause\", updatePlayerDetails);\n video.removeEventListener(\"ratechange\", updatePlayerDetails);\n if (timerRef.current != null) {\n clearInterval(timerRef.current);\n timerRef.current = undefined;\n }\n if (!video.ended) saveLastPlayedTime(video.currentTime);\n setCurrentTime(undefined);\n video.pause();\n destroyHls();\n video.removeAttribute(\"src\");\n video.load();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (setCurrentTimeHandler != null) {\n setCurrentTimeHandler(seekTo);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Compare by chapter ids and URLs: a new array with the same content must\n // not reload the stream or restart playback.\n const chaptersSignature = chapters\n .map((chapter) => `${chapter.id}|${chapter.publicUrl ?? \"\"}`)\n .join(\"\\n\");\n\n useEffect(() => {\n chaptersRef.current = chapters;\n const previousSignature = chaptersSignatureRef.current;\n if (previousSignature === chaptersSignature) {\n return;\n }\n chaptersSignatureRef.current = chaptersSignature;\n\n if (previousSignature == null) {\n loadChapters(chapters);\n return;\n }\n\n const current = currentChapterRef.current;\n if (current == null) {\n loadChapters(chapters);\n return;\n }\n const replacement = chapters.find((chapter) => chapter.id === current.id);\n if (replacement != null && replacement.publicUrl === current.publicUrl) {\n // Same stream, different array: keep playing.\n return;\n }\n if (replacement != null) {\n // A fresh signed URL for the chapter that is playing: keep the position\n // and whether it was playing.\n const video = videoRef.current;\n const position = video?.currentTime ?? 0;\n const wasPlaying = video != null && !video.paused;\n currentChapterRef.current = replacement;\n resumedRef.current = false;\n pendingSeekRef.current = position > 0 ? position : null;\n playWhenReadyRef.current = wasPlaying;\n loadSource(replacement.publicUrl);\n syncMediaSessionMetadata(replacement);\n callbacksRef.current.onChapterChange?.(replacement);\n setLastSelectedChapterID(replacement.id);\n return;\n }\n loadChapters(chapters);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [chaptersSignature]);\n\n useEffect(() => {\n switch (playState) {\n case PlayState.Playing:\n mediaSessionPlay();\n break;\n case PlayState.Paused:\n mediaSessionPause();\n break;\n }\n }, [playState]);\n\n const currentIndex = chapters.findIndex(\n (chapter) => chapter.id === chapterID,\n );\n const knownDuration =\n Number.isFinite(duration) && duration! > 0\n ? duration!\n : (chapters[currentIndex]?.duration ?? 0);\n const position = Math.min(\n Math.max(currentTime ?? 0, 0),\n knownDuration || Infinity,\n );\n const wholeBookKnown =\n chapters.length > 0 &&\n chapters.every(\n (chapter) => Number.isFinite(chapter.duration) && chapter.duration! > 0,\n );\n const remaining =\n Math.max(\n 0,\n knownDuration -\n position +\n (wholeBookKnown\n ? chapters\n .slice(currentIndex + 1)\n .reduce((sum, chapter) => sum + chapter.duration!, 0)\n : 0),\n ) / speed;\n const minutesLeft = Math.ceil(remaining / 60);\n const leftText = `${Math.floor(minutesLeft / 60) > 0 ? `${Math.floor(minutesLeft / 60)} h ` : \"\"}${minutesLeft % 60} min`;\n\n return (\n <div\n id=\"audio-player-container\"\n className=\"bitsnap-audio-player flex min-w-0 flex-col gap-3 text-neutral-900 dark:text-neutral-100\"\n style={\n {\n ...styles,\n \"--seek-before-width\": `${knownDuration > 0 ? (position / knownDuration) * 100 : 0}%`,\n } as CSSProperties\n }\n ref={audioPlayerContainerRef}\n data-player-error={playerError?.kind}\n >\n <video\n ref={videoRef}\n className=\"hidden\"\n poster={imageURL}\n title={title}\n />\n <div className={cn(\"flex min-w-0 items-center gap-3\", coverShownBeside && \"lg:hidden\")}>\n {imageURL && (\n <img\n src={imageURL}\n alt=\"\"\n className=\"h-16 w-16 shrink-0 rounded object-contain\"\n />\n )}\n <div className=\"min-w-0 break-words\">\n <p className=\"font-semibold\">\n {chapters[currentIndex]?.name ?? title}\n </p>\n {author && (\n <p className=\"text-sm text-neutral-600 dark:text-neutral-300\">\n {author}\n </p>\n )}\n </div>\n </div>\n {playerError && (\n <div\n role=\"alert\"\n className=\"rounded-lg bg-red-50 p-3 text-red-800 dark:bg-red-950 dark:text-red-200\"\n >\n <p>{t.error}</p>\n <Button variant=\"outline\" onClick={retry}>\n {t.retry}\n </Button>\n </div>\n )}\n <input\n type=\"range\"\n min=\"0\"\n max={knownDuration || 100}\n value={position}\n disabled={!knownDuration}\n aria-label={t.progress}\n aria-valuetext={`${formatTime(position)} ${t.of} ${formatTime(knownDuration)}`}\n onChange={(event) => seekTo(Number(event.target.value))}\n />\n <section className=\"flex w-full justify-between text-sm tabular-nums\">\n <span id=\"current-time\">{formatTime(position)}</span>\n <span id=\"duration\">{formatTime(knownDuration)}</span>\n </section>\n {knownDuration > 0 && (\n <p className=\"text-sm text-neutral-600 dark:text-neutral-300\">\n {t.left === \"left\"\n ? `${leftText} ${t.left}`\n : `${t.left} ${leftText}`}{\" \"}\n · {wholeBookKnown ? t.book : t.chapter} ({speed}×)\n </p>\n )}\n <div className=\"flex flex-wrap items-center justify-center gap-2\">\n <Button\n variant=\"outline\"\n onClick={playPreviousChapter}\n disabled={currentIndex < 0}\n aria-label={t.previous}\n >\n <SkipBack className=\"h-5 w-5\" />\n </Button>\n <Button\n variant=\"outline\"\n onClick={() => seekBy(-SEEK_STEP_SECONDS)}\n aria-label={t.rewind}\n >\n −{SEEK_STEP_SECONDS}\n </Button>\n <Button\n variant=\"outline\"\n onClick={togglePlayState}\n aria-label={playState === PlayState.Paused ? t.play : t.pause}\n >\n {playState === PlayState.Paused ? (\n <Play className=\"h-5 w-5\" />\n ) : (\n <Pause className=\"h-5 w-5\" />\n )}\n </Button>\n <Button\n variant=\"outline\"\n onClick={() => seekBy(SEEK_STEP_SECONDS)}\n aria-label={t.forward}\n >\n +{SEEK_STEP_SECONDS}\n </Button>\n <Button\n variant=\"outline\"\n onClick={playNextChapter}\n disabled={currentIndex < 0 || currentIndex >= chapters.length - 1}\n aria-label={t.next}\n >\n <SkipForward className=\"h-5 w-5\" />\n </Button>\n </div>\n <div className=\"flex flex-wrap gap-3 md:grid md:grid-cols-2\">\n <label className=\"flex flex-1 items-center gap-2 text-sm md:flex-col md:items-start md:whitespace-nowrap\">\n {t.speed}\n <select\n aria-label={t.speed}\n value={speed}\n onChange={(event) => changeSpeed(Number(event.target.value))}\n >\n {SPEEDS.map((rate) => (\n <option key={rate} value={rate}>\n {rate}×\n </option>\n ))}\n </select>\n </label>\n <label className=\"flex flex-1 items-center gap-2 text-sm md:flex-col md:items-start md:whitespace-nowrap\">\n {t.sleep}\n <select\n aria-label={t.sleep}\n value={sleepMode}\n onChange={(event) => changeSleep(event.target.value)}\n >\n <option value=\"off\">{t.off}</option>\n {[15, 30, 45, 60].map((minutes) => (\n <option key={minutes} value={minutes}>\n {minutes} min\n </option>\n ))}\n <option value=\"chapter\">{t.end}</option>\n </select>\n </label>\n </div>\n {sleepMode !== \"off\" && (\n <div className=\"flex items-center justify-between gap-2 text-sm\">\n <span role=\"timer\">\n {sleepMode === \"chapter\" ? t.end : formatTime(sleepRemaining)}\n </span>\n <Button variant=\"outline\" onClick={cancelSleep}>\n {t.cancel}\n </Button>\n </div>\n )}\n {isLoading && (\n <div role=\"status\" className=\"flex justify-center\">\n <LoadingIndicator />\n </div>\n )}\n </div>\n );\n },\n);\n\nexport default AudioPlayer;\n"]}
|