@gymmymac/bob-widget 3.1.3 → 3.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +36 -8
  2. package/dist/index.js +57 -15
  3. package/dist/index.mjs +13015 -3906
  4. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var ys=t=>{throw TypeError(t)};var Wr=(t,e,s)=>e.has(t)||ys("Cannot "+s);var l=(t,e,s)=>(Wr(t,e,"read from private field"),s?s.call(t):e.get(t)),Y=(t,e,s)=>e.has(t)?ys("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),W=(t,e,s,n)=>(Wr(t,e,"write to private field"),n?n.call(t,s):e.set(t,s),s),se=(t,e,s)=>(Wr(t,e,"access private method"),s);var _r=(t,e,s,n)=>({set _(i){W(t,e,i,s)},get _(){return l(t,e,n)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react"),Hr=require("@supabase/supabase-js");function zn(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const s in t)if(s!=="default"){const n=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(e,s,n.get?n:{enumerable:!0,get:()=>t[s]})}}return e.default=t,Object.freeze(e)}const Le=zn(a),et="3.1.3",$n=()=>et;var qr={exports:{}},ir={};/**
1
+ "use strict";var zn=t=>{throw TypeError(t)};var Hs=(t,e,r)=>e.has(t)||zn("Cannot "+r);var x=(t,e,r)=>(Hs(t,e,"read from private field"),r?r.call(t):e.get(t)),Y=(t,e,r)=>e.has(t)?zn("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),M=(t,e,r,s)=>(Hs(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),ae=(t,e,r)=>(Hs(t,e,"access private method"),r);var ms=(t,e,r,s)=>({set _(n){M(t,e,n,r)},get _(){return x(t,e,s)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react");function Ja(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,s.get?s:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const Je=Ja(y),pt="3.1.7",Qa=()=>pt;var rn={exports:{}},Ur={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.min.js
4
4
  *
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var vs;function Un(){if(vs)return ir;vs=1;var t=a,e=Symbol.for("react.element"),s=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,i=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,c={key:!0,ref:!0,__self:!0,__source:!0};function d(u,y,x){var b,p={},g=null,m=null;x!==void 0&&(g=""+x),y.key!==void 0&&(g=""+y.key),y.ref!==void 0&&(m=y.ref);for(b in y)n.call(y,b)&&!c.hasOwnProperty(b)&&(p[b]=y[b]);if(u&&u.defaultProps)for(b in y=u.defaultProps,y)p[b]===void 0&&(p[b]=y[b]);return{$$typeof:e,type:u,key:g,ref:m,props:p,_owner:i.current}}return ir.Fragment=s,ir.jsx=d,ir.jsxs=d,ir}var ar={};/**
9
+ */var Hn;function Ya(){if(Hn)return Ur;Hn=1;var t=y,e=Symbol.for("react.element"),r=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,n=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(l,c,u){var d,p={},f=null,h=null;u!==void 0&&(f=""+u),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(h=c.ref);for(d in c)s.call(c,d)&&!i.hasOwnProperty(d)&&(p[d]=c[d]);if(l&&l.defaultProps)for(d in c=l.defaultProps,c)p[d]===void 0&&(p[d]=c[d]);return{$$typeof:e,type:l,key:f,ref:h,props:p,_owner:n.current}}return Ur.Fragment=r,Ur.jsx=a,Ur.jsxs=a,Ur}var Mr={};/**
10
10
  * @license React
11
11
  * react-jsx-runtime.development.js
12
12
  *
@@ -14,27 +14,69 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */var ws;function Hn(){return ws||(ws=1,process.env.NODE_ENV!=="production"&&function(){var t=a,e=Symbol.for("react.element"),s=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),c=Symbol.for("react.profiler"),d=Symbol.for("react.provider"),u=Symbol.for("react.context"),y=Symbol.for("react.forward_ref"),x=Symbol.for("react.suspense"),b=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),m=Symbol.for("react.offscreen"),S=Symbol.iterator,f="@@iterator";function j(o){if(o===null||typeof o!="object")return null;var T=S&&o[S]||o[f];return typeof T=="function"?T:null}var v=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function w(o){{for(var T=arguments.length,M=new Array(T>1?T-1:0),X=1;X<T;X++)M[X-1]=arguments[X];h("error",o,M)}}function h(o,T,M){{var X=v.ReactDebugCurrentFrame,ee=X.getStackAddendum();ee!==""&&(T+="%s",M=M.concat([ee]));var le=M.map(function(L){return String(L)});le.unshift("Warning: "+T),Function.prototype.apply.call(console[o],console,le)}}var k=!1,R=!1,P=!1,H=!1,B=!1,A;A=Symbol.for("react.module.reference");function _(o){return!!(typeof o=="string"||typeof o=="function"||o===n||o===c||B||o===i||o===x||o===b||H||o===m||k||R||P||typeof o=="object"&&o!==null&&(o.$$typeof===g||o.$$typeof===p||o.$$typeof===d||o.$$typeof===u||o.$$typeof===y||o.$$typeof===A||o.getModuleId!==void 0))}function C(o,T,M){var X=o.displayName;if(X)return X;var ee=T.displayName||T.name||"";return ee!==""?M+"("+ee+")":M}function E(o){return o.displayName||"Context"}function N(o){if(o==null)return null;if(typeof o.tag=="number"&&w("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof o=="function")return o.displayName||o.name||null;if(typeof o=="string")return o;switch(o){case n:return"Fragment";case s:return"Portal";case c:return"Profiler";case i:return"StrictMode";case x:return"Suspense";case b:return"SuspenseList"}if(typeof o=="object")switch(o.$$typeof){case u:var T=o;return E(T)+".Consumer";case d:var M=o;return E(M._context)+".Provider";case y:return C(o,o.render,"ForwardRef");case p:var X=o.displayName||null;return X!==null?X:N(o.type)||"Memo";case g:{var ee=o,le=ee._payload,L=ee._init;try{return N(L(le))}catch{return null}}}return null}var I=Object.assign,U=0,F,J,q,O,D,z,$;function V(){}V.__reactDisabledLog=!0;function Q(){{if(U===0){F=console.log,J=console.info,q=console.warn,O=console.error,D=console.group,z=console.groupCollapsed,$=console.groupEnd;var o={configurable:!0,enumerable:!0,value:V,writable:!0};Object.defineProperties(console,{info:o,log:o,warn:o,error:o,group:o,groupCollapsed:o,groupEnd:o})}U++}}function ue(){{if(U--,U===0){var o={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:I({},o,{value:F}),info:I({},o,{value:J}),warn:I({},o,{value:q}),error:I({},o,{value:O}),group:I({},o,{value:D}),groupCollapsed:I({},o,{value:z}),groupEnd:I({},o,{value:$})})}U<0&&w("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var fe=v.ReactCurrentDispatcher,xe;function oe(o,T,M){{if(xe===void 0)try{throw Error()}catch(ee){var X=ee.stack.trim().match(/\n( *(at )?)/);xe=X&&X[1]||""}return`
18
- `+xe+o}}var ye=!1,Z;{var Be=typeof WeakMap=="function"?WeakMap:Map;Z=new Be}function Ie(o,T){if(!o||ye)return"";{var M=Z.get(o);if(M!==void 0)return M}var X;ye=!0;var ee=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var le;le=fe.current,fe.current=null,Q();try{if(T){var L=function(){throw Error()};if(Object.defineProperty(L.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(L,[])}catch(Ee){X=Ee}Reflect.construct(o,[],L)}else{try{L.call()}catch(Ee){X=Ee}o.call(L.prototype)}}else{try{throw Error()}catch(Ee){X=Ee}o()}}catch(Ee){if(Ee&&X&&typeof Ee.stack=="string"){for(var te=Ee.stack.split(`
19
- `),he=X.stack.split(`
20
- `),ae=te.length-1,ie=he.length-1;ae>=1&&ie>=0&&te[ae]!==he[ie];)ie--;for(;ae>=1&&ie>=0;ae--,ie--)if(te[ae]!==he[ie]){if(ae!==1||ie!==1)do if(ae--,ie--,ie<0||te[ae]!==he[ie]){var ve=`
21
- `+te[ae].replace(" at new "," at ");return o.displayName&&ve.includes("<anonymous>")&&(ve=ve.replace("<anonymous>",o.displayName)),typeof o=="function"&&Z.set(o,ve),ve}while(ae>=1&&ie>=0);break}}}finally{ye=!1,fe.current=le,ue(),Error.prepareStackTrace=ee}var We=o?o.displayName||o.name:"",Ye=We?oe(We):"";return typeof o=="function"&&Z.set(o,Ye),Ye}function re(o,T,M){return Ie(o,!1)}function Ce(o){var T=o.prototype;return!!(T&&T.isReactComponent)}function ge(o,T,M){if(o==null)return"";if(typeof o=="function")return Ie(o,Ce(o));if(typeof o=="string")return oe(o);switch(o){case x:return oe("Suspense");case b:return oe("SuspenseList")}if(typeof o=="object")switch(o.$$typeof){case y:return re(o.render);case p:return ge(o.type,T,M);case g:{var X=o,ee=X._payload,le=X._init;try{return ge(le(ee),T,M)}catch{}}}return""}var He=Object.prototype.hasOwnProperty,rt={},Pr=v.ReactDebugCurrentFrame;function Jt(o){if(o){var T=o._owner,M=ge(o.type,o._source,T?T.type:null);Pr.setExtraStackFrame(M)}else Pr.setExtraStackFrame(null)}function ms(o,T,M,X,ee){{var le=Function.call.bind(He);for(var L in o)if(le(o,L)){var te=void 0;try{if(typeof o[L]!="function"){var he=Error((X||"React class")+": "+M+" type `"+L+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof o[L]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw he.name="Invariant Violation",he}te=o[L](T,L,X,M,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(ae){te=ae}te&&!(te instanceof Error)&&(Jt(ee),w("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",X||"React class",M,L,typeof te),Jt(null)),te instanceof Error&&!(te.message in rt)&&(rt[te.message]=!0,Jt(ee),w("Failed %s type: %s",M,te.message),Jt(null))}}}var xs=Array.isArray;function kr(o){return xs(o)}function Sr(o){{var T=typeof Symbol=="function"&&Symbol.toStringTag,M=T&&o[Symbol.toStringTag]||o.constructor.name||"Object";return M}}function jr(o){try{return Zt(o),!1}catch{return!0}}function Zt(o){return""+o}function er(o){if(jr(o))return w("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Sr(o)),Zt(o)}var G=v.ReactCurrentOwner,de={key:!0,ref:!0,__self:!0,__source:!0},be,je;function st(o){if(He.call(o,"ref")){var T=Object.getOwnPropertyDescriptor(o,"ref").get;if(T&&T.isReactWarning)return!1}return o.ref!==void 0}function tr(o){if(He.call(o,"key")){var T=Object.getOwnPropertyDescriptor(o,"key").get;if(T&&T.isReactWarning)return!1}return o.key!==void 0}function xt(o,T){typeof o.ref=="string"&&G.current}function yt(o,T){{var M=function(){be||(be=!0,w("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",T))};M.isReactWarning=!0,Object.defineProperty(o,"key",{get:M,configurable:!0})}}function Lt(o,T){{var M=function(){je||(je=!0,w("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",T))};M.isReactWarning=!0,Object.defineProperty(o,"ref",{get:M,configurable:!0})}}var vt=function(o,T,M,X,ee,le,L){var te={$$typeof:e,type:o,key:T,ref:M,props:L,_owner:le};return te._store={},Object.defineProperty(te._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(te,"_self",{configurable:!1,enumerable:!1,writable:!1,value:X}),Object.defineProperty(te,"_source",{configurable:!1,enumerable:!1,writable:!1,value:ee}),Object.freeze&&(Object.freeze(te.props),Object.freeze(te)),te};function wt(o,T,M,X,ee){{var le,L={},te=null,he=null;M!==void 0&&(er(M),te=""+M),tr(T)&&(er(T.key),te=""+T.key),st(T)&&(he=T.ref,xt(T,ee));for(le in T)He.call(T,le)&&!de.hasOwnProperty(le)&&(L[le]=T[le]);if(o&&o.defaultProps){var ae=o.defaultProps;for(le in ae)L[le]===void 0&&(L[le]=ae[le])}if(te||he){var ie=typeof o=="function"?o.displayName||o.name||"Unknown":o;te&&yt(L,ie),he&&Lt(L,ie)}return vt(o,te,he,ee,X,G.current,L)}}var Ne=v.ReactCurrentOwner,kt=v.ReactDebugCurrentFrame;function De(o){if(o){var T=o._owner,M=ge(o.type,o._source,T?T.type:null);kt.setExtraStackFrame(M)}else kt.setExtraStackFrame(null)}var Oe;Oe=!1;function nt(o){return typeof o=="object"&&o!==null&&o.$$typeof===e}function St(){{if(Ne.current){var o=N(Ne.current.type);if(o)return`
17
+ */var Kn;function Xa(){return Kn||(Kn=1,process.env.NODE_ENV!=="production"&&function(){var t=y,e=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.provider"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),h=Symbol.for("react.offscreen"),m=Symbol.iterator,g="@@iterator";function _(v){if(v===null||typeof v!="object")return null;var R=m&&v[m]||v[g];return typeof R=="function"?R:null}var w=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function k(v){{for(var R=arguments.length,D=new Array(R>1?R-1:0),X=1;X<R;X++)D[X-1]=arguments[X];b("error",v,D)}}function b(v,R,D){{var X=w.ReactDebugCurrentFrame,se=X.getStackAddendum();se!==""&&(R+="%s",D=D.concat([se]));var de=D.map(function(L){return String(L)});de.unshift("Warning: "+R),Function.prototype.apply.call(console[v],console,de)}}var S=!1,j=!1,C=!1,F=!1,O=!1,B;B=Symbol.for("react.module.reference");function E(v){return!!(typeof v=="string"||typeof v=="function"||v===s||v===i||O||v===n||v===u||v===d||F||v===h||S||j||C||typeof v=="object"&&v!==null&&(v.$$typeof===f||v.$$typeof===p||v.$$typeof===a||v.$$typeof===l||v.$$typeof===c||v.$$typeof===B||v.getModuleId!==void 0))}function A(v,R,D){var X=v.displayName;if(X)return X;var se=R.displayName||R.name||"";return se!==""?D+"("+se+")":D}function T(v){return v.displayName||"Context"}function I(v){if(v==null)return null;if(typeof v.tag=="number"&&k("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof v=="function")return v.displayName||v.name||null;if(typeof v=="string")return v;switch(v){case s:return"Fragment";case r:return"Portal";case i:return"Profiler";case n:return"StrictMode";case u:return"Suspense";case d:return"SuspenseList"}if(typeof v=="object")switch(v.$$typeof){case l:var R=v;return T(R)+".Consumer";case a:var D=v;return T(D._context)+".Provider";case c:return A(v,v.render,"ForwardRef");case p:var X=v.displayName||null;return X!==null?X:I(v.type)||"Memo";case f:{var se=v,de=se._payload,L=se._init;try{return I(L(de))}catch{return null}}}return null}var N=Object.assign,z=0,P,te,K,$,U,W,q;function J(){}J.__reactDisabledLog=!0;function V(){{if(z===0){P=console.log,te=console.info,K=console.warn,$=console.error,U=console.group,W=console.groupCollapsed,q=console.groupEnd;var v={configurable:!0,enumerable:!0,value:J,writable:!0};Object.defineProperties(console,{info:v,log:v,warn:v,error:v,group:v,groupCollapsed:v,groupEnd:v})}z++}}function fe(){{if(z--,z===0){var v={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:N({},v,{value:P}),info:N({},v,{value:te}),warn:N({},v,{value:K}),error:N({},v,{value:$}),group:N({},v,{value:U}),groupCollapsed:N({},v,{value:W}),groupEnd:N({},v,{value:q})})}z<0&&k("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ye=w.ReactCurrentDispatcher,je;function ue(v,R,D){{if(je===void 0)try{throw Error()}catch(se){var X=se.stack.trim().match(/\n( *(at )?)/);je=X&&X[1]||""}return`
18
+ `+je+v}}var Te=!1,re;{var qe=typeof WeakMap=="function"?WeakMap:Map;re=new qe}function ze(v,R){if(!v||Te)return"";{var D=re.get(v);if(D!==void 0)return D}var X;Te=!0;var se=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var de;de=ye.current,ye.current=null,V();try{if(R){var L=function(){throw Error()};if(Object.defineProperty(L.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(L,[])}catch($e){X=$e}Reflect.construct(v,[],L)}else{try{L.call()}catch($e){X=$e}v.call(L.prototype)}}else{try{throw Error()}catch($e){X=$e}v()}}catch($e){if($e&&X&&typeof $e.stack=="string"){for(var ne=$e.stack.split(`
19
+ `),me=X.stack.split(`
20
+ `),ce=ne.length-1,le=me.length-1;ce>=1&&le>=0&&ne[ce]!==me[le];)le--;for(;ce>=1&&le>=0;ce--,le--)if(ne[ce]!==me[le]){if(ce!==1||le!==1)do if(ce--,le--,le<0||ne[ce]!==me[le]){var Re=`
21
+ `+ne[ce].replace(" at new "," at ");return v.displayName&&Re.includes("<anonymous>")&&(Re=Re.replace("<anonymous>",v.displayName)),typeof v=="function"&&re.set(v,Re),Re}while(ce>=1&&le>=0);break}}}finally{Te=!1,ye.current=de,fe(),Error.prepareStackTrace=se}var Ye=v?v.displayName||v.name:"",ct=Ye?ue(Ye):"";return typeof v=="function"&&re.set(v,ct),ct}function ie(v,R,D){return ze(v,!1)}function Le(v){var R=v.prototype;return!!(R&&R.isReactComponent)}function xe(v,R,D){if(v==null)return"";if(typeof v=="function")return ze(v,Le(v));if(typeof v=="string")return ue(v);switch(v){case u:return ue("Suspense");case d:return ue("SuspenseList")}if(typeof v=="object")switch(v.$$typeof){case c:return ie(v.render);case p:return xe(v.type,R,D);case f:{var X=v,se=X._payload,de=X._init;try{return xe(de(se),R,D)}catch{}}}return""}var st=Object.prototype.hasOwnProperty,mt={},Us=w.ReactDebugCurrentFrame;function Pr(v){if(v){var R=v._owner,D=xe(v.type,v._source,R?R.type:null);Us.setExtraStackFrame(D)}else Us.setExtraStackFrame(null)}function Wn(v,R,D,X,se){{var de=Function.call.bind(st);for(var L in v)if(de(v,L)){var ne=void 0;try{if(typeof v[L]!="function"){var me=Error((X||"React class")+": "+D+" type `"+L+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof v[L]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw me.name="Invariant Violation",me}ne=v[L](R,L,X,D,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(ce){ne=ce}ne&&!(ne instanceof Error)&&(Pr(se),k("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",X||"React class",D,L,typeof ne),Pr(null)),ne instanceof Error&&!(ne.message in mt)&&(mt[ne.message]=!0,Pr(se),k("Failed %s type: %s",D,ne.message),Pr(null))}}}var qn=Array.isArray;function ps(v){return qn(v)}function gs(v){{var R=typeof Symbol=="function"&&Symbol.toStringTag,D=R&&v[Symbol.toStringTag]||v.constructor.name||"Object";return D}}function bs(v){try{return Nr(v),!1}catch{return!0}}function Nr(v){return""+v}function Br(v){if(bs(v))return k("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",gs(v)),Nr(v)}var Q=w.ReactCurrentOwner,ge={key:!0,ref:!0,__self:!0,__source:!0},ke,Ne;function yt(v){if(st.call(v,"ref")){var R=Object.getOwnPropertyDescriptor(v,"ref").get;if(R&&R.isReactWarning)return!1}return v.ref!==void 0}function $r(v){if(st.call(v,"key")){var R=Object.getOwnPropertyDescriptor(v,"key").get;if(R&&R.isReactWarning)return!1}return v.key!==void 0}function Bt(v,R){typeof v.ref=="string"&&Q.current}function $t(v,R){{var D=function(){ke||(ke=!0,k("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",R))};D.isReactWarning=!0,Object.defineProperty(v,"key",{get:D,configurable:!0})}}function or(v,R){{var D=function(){Ne||(Ne=!0,k("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",R))};D.isReactWarning=!0,Object.defineProperty(v,"ref",{get:D,configurable:!0})}}var Ft=function(v,R,D,X,se,de,L){var ne={$$typeof:e,type:v,key:R,ref:D,props:L,_owner:de};return ne._store={},Object.defineProperty(ne._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(ne,"_self",{configurable:!1,enumerable:!1,writable:!1,value:X}),Object.defineProperty(ne,"_source",{configurable:!1,enumerable:!1,writable:!1,value:se}),Object.freeze&&(Object.freeze(ne.props),Object.freeze(ne)),ne};function Dt(v,R,D,X,se){{var de,L={},ne=null,me=null;D!==void 0&&(Br(D),ne=""+D),$r(R)&&(Br(R.key),ne=""+R.key),yt(R)&&(me=R.ref,Bt(R,se));for(de in R)st.call(R,de)&&!ge.hasOwnProperty(de)&&(L[de]=R[de]);if(v&&v.defaultProps){var ce=v.defaultProps;for(de in ce)L[de]===void 0&&(L[de]=ce[de])}if(ne||me){var le=typeof v=="function"?v.displayName||v.name||"Unknown":v;ne&&$t(L,le),me&&or(L,le)}return Ft(v,ne,me,se,X,Q.current,L)}}var Ue=w.ReactCurrentOwner,Lt=w.ReactDebugCurrentFrame;function Qe(v){if(v){var R=v._owner,D=xe(v.type,v._source,R?R.type:null);Lt.setExtraStackFrame(D)}else Lt.setExtraStackFrame(null)}var He;He=!1;function vt(v){return typeof v=="object"&&v!==null&&v.$$typeof===e}function Ut(){{if(Ue.current){var v=I(Ue.current.type);if(v)return`
22
22
 
23
- Check the render method of \``+o+"`."}return""}}function it(o){return""}var Fe={};function jt(o){{var T=St();if(!T){var M=typeof o=="string"?o:o.displayName||o.name;M&&(T=`
23
+ Check the render method of \``+v+"`."}return""}}function wt(v){return""}var Me={};function Mt(v){{var R=Ut();if(!R){var D=typeof v=="string"?v:v.displayName||v.name;D&&(R=`
24
24
 
25
- Check the top-level render call using <`+M+">.")}return T}}function me(o,T){{if(!o._store||o._store.validated||o.key!=null)return;o._store.validated=!0;var M=jt(T);if(Fe[M])return;Fe[M]=!0;var X="";o&&o._owner&&o._owner!==Ne.current&&(X=" It was passed a child from "+N(o._owner.type)+"."),De(o),w('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',M,X),De(null)}}function Pe(o,T){{if(typeof o!="object")return;if(kr(o))for(var M=0;M<o.length;M++){var X=o[M];nt(X)&&me(X,T)}else if(nt(o))o._store&&(o._store.validated=!0);else if(o){var ee=j(o);if(typeof ee=="function"&&ee!==o.entries)for(var le=ee.call(o),L;!(L=le.next()).done;)nt(L.value)&&me(L.value,T)}}}function Mr(o){{var T=o.type;if(T==null||typeof T=="string")return;var M;if(typeof T=="function")M=T.propTypes;else if(typeof T=="object"&&(T.$$typeof===y||T.$$typeof===p))M=T.propTypes;else return;if(M){var X=N(T);ms(M,o.props,"prop",X,o)}else if(T.PropTypes!==void 0&&!Oe){Oe=!0;var ee=N(T);w("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",ee||"Unknown")}typeof T.getDefaultProps=="function"&&!T.getDefaultProps.isReactClassApproved&&w("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Ar(o){{for(var T=Object.keys(o.props),M=0;M<T.length;M++){var X=T[M];if(X!=="children"&&X!=="key"){De(o),w("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",X),De(null);break}}o.ref!==null&&(De(o),w("Invalid attribute `ref` supplied to `React.Fragment`."),De(null))}}var qe={};function rr(o,T,M,X,ee,le){{var L=_(o);if(!L){var te="";(o===void 0||typeof o=="object"&&o!==null&&Object.keys(o).length===0)&&(te+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var he=it();he?te+=he:te+=St();var ae;o===null?ae="null":kr(o)?ae="array":o!==void 0&&o.$$typeof===e?(ae="<"+(N(o.type)||"Unknown")+" />",te=" Did you accidentally export a JSX literal instead of a component?"):ae=typeof o,w("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",ae,te)}var ie=wt(o,T,M,ee,le);if(ie==null)return ie;if(L){var ve=T.children;if(ve!==void 0)if(X)if(kr(ve)){for(var We=0;We<ve.length;We++)Pe(ve[We],o);Object.freeze&&Object.freeze(ve)}else w("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Pe(ve,o)}if(He.call(T,"key")){var Ye=N(o),Ee=Object.keys(T).filter(function(Wn){return Wn!=="key"}),Dr=Ee.length>0?"{key: someKey, "+Ee.join(": ..., ")+": ...}":"{key: someKey}";if(!qe[Ye+Dr]){var Dn=Ee.length>0?"{"+Ee.join(": ..., ")+": ...}":"{}";w(`A props object containing a "key" prop is being spread into JSX:
25
+ Check the top-level render call using <`+D+">.")}return R}}function Se(v,R){{if(!v._store||v._store.validated||v.key!=null)return;v._store.validated=!0;var D=Mt(R);if(Me[D])return;Me[D]=!0;var X="";v&&v._owner&&v._owner!==Ue.current&&(X=" It was passed a child from "+I(v._owner.type)+"."),Qe(v),k('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',D,X),Qe(null)}}function Ke(v,R){{if(typeof v!="object")return;if(ps(v))for(var D=0;D<v.length;D++){var X=v[D];vt(X)&&Se(X,R)}else if(vt(v))v._store&&(v._store.validated=!0);else if(v){var se=_(v);if(typeof se=="function"&&se!==v.entries)for(var de=se.call(v),L;!(L=de.next()).done;)vt(L.value)&&Se(L.value,R)}}}function Ms(v){{var R=v.type;if(R==null||typeof R=="string")return;var D;if(typeof R=="function")D=R.propTypes;else if(typeof R=="object"&&(R.$$typeof===c||R.$$typeof===p))D=R.propTypes;else return;if(D){var X=I(R);Wn(D,v.props,"prop",X,v)}else if(R.PropTypes!==void 0&&!He){He=!0;var se=I(R);k("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",se||"Unknown")}typeof R.getDefaultProps=="function"&&!R.getDefaultProps.isReactClassApproved&&k("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Ws(v){{for(var R=Object.keys(v.props),D=0;D<R.length;D++){var X=R[D];if(X!=="children"&&X!=="key"){Qe(v),k("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",X),Qe(null);break}}v.ref!==null&&(Qe(v),k("Invalid attribute `ref` supplied to `React.Fragment`."),Qe(null))}}var nt={};function Fr(v,R,D,X,se,de){{var L=E(v);if(!L){var ne="";(v===void 0||typeof v=="object"&&v!==null&&Object.keys(v).length===0)&&(ne+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var me=wt();me?ne+=me:ne+=Ut();var ce;v===null?ce="null":ps(v)?ce="array":v!==void 0&&v.$$typeof===e?(ce="<"+(I(v.type)||"Unknown")+" />",ne=" Did you accidentally export a JSX literal instead of a component?"):ce=typeof v,k("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",ce,ne)}var le=Dt(v,R,D,se,de);if(le==null)return le;if(L){var Re=R.children;if(Re!==void 0)if(X)if(ps(Re)){for(var Ye=0;Ye<Re.length;Ye++)Ke(Re[Ye],v);Object.freeze&&Object.freeze(Re)}else k("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Ke(Re,v)}if(st.call(R,"key")){var ct=I(v),$e=Object.keys(R).filter(function(Ga){return Ga!=="key"}),zs=$e.length>0?"{key: someKey, "+$e.join(": ..., ")+": ...}":"{key: someKey}";if(!nt[ct+zs]){var Va=$e.length>0?"{"+$e.join(": ..., ")+": ...}":"{}";k(`A props object containing a "key" prop is being spread into JSX:
26
26
  let props = %s;
27
27
  <%s {...props} />
28
28
  React keys must be passed directly to JSX without using spread:
29
29
  let props = %s;
30
- <%s key={someKey} {...props} />`,Dr,Ye,Dn,Ye),qe[Ye+Dr]=!0}}return o===n?Ar(ie):Mr(ie),ie}}function at(o,T,M){return rr(o,T,M,!0)}function sr(o,T,M){return rr(o,T,M,!1)}var nr=sr,Lr=at;ar.Fragment=n,ar.jsx=nr,ar.jsxs=Lr}()),ar}process.env.NODE_ENV==="production"?qr.exports=Un():qr.exports=Hn();var r=qr.exports,vr=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},qn={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},Qe,Et,Us,Qn=(Us=class{constructor(){Y(this,Qe,qn);Y(this,Et,!1)}setTimeoutProvider(t){process.env.NODE_ENV!=="production"&&l(this,Et)&&t!==l(this,Qe)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:l(this,Qe),provider:t}),W(this,Qe,t),process.env.NODE_ENV!=="production"&&W(this,Et,!1)}setTimeout(t,e){return process.env.NODE_ENV!=="production"&&W(this,Et,!0),l(this,Qe).setTimeout(t,e)}clearTimeout(t){l(this,Qe).clearTimeout(t)}setInterval(t,e){return process.env.NODE_ENV!=="production"&&W(this,Et,!0),l(this,Qe).setInterval(t,e)}clearInterval(t){l(this,Qe).clearInterval(t)}},Qe=new WeakMap,Et=new WeakMap,Us),_t=new Qn;function Kn(t){setTimeout(t,0)}var Mt=typeof window>"u"||"Deno"in globalThis;function Re(){}function Vn(t,e){return typeof t=="function"?t(e):t}function Qr(t){return typeof t=="number"&&t>=0&&t!==1/0}function Zs(t,e){return Math.max(t+(e||0)-Date.now(),0)}function mt(t,e){return typeof t=="function"?t(e):t}function Ae(t,e){return typeof t=="function"?t(e):t}function ks(t,e){const{type:s="all",exact:n,fetchStatus:i,predicate:c,queryKey:d,stale:u}=t;if(d){if(n){if(e.queryHash!==ls(d,e.options))return!1}else if(!fr(e.queryKey,d))return!1}if(s!=="all"){const y=e.isActive();if(s==="active"&&!y||s==="inactive"&&y)return!1}return!(typeof u=="boolean"&&e.isStale()!==u||i&&i!==e.state.fetchStatus||c&&!c(e))}function Ss(t,e){const{exact:s,status:n,predicate:i,mutationKey:c}=t;if(c){if(!e.options.mutationKey)return!1;if(s){if(hr(e.options.mutationKey)!==hr(c))return!1}else if(!fr(e.options.mutationKey,c))return!1}return!(n&&e.state.status!==n||i&&!i(e))}function ls(t,e){return((e==null?void 0:e.queryKeyHashFn)||hr)(t)}function hr(t){return JSON.stringify(t,(e,s)=>Gr(s)?Object.keys(s).sort().reduce((n,i)=>(n[i]=s[i],n),{}):s)}function fr(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(s=>fr(t[s],e[s])):!1}var Gn=Object.prototype.hasOwnProperty;function Kr(t,e,s=0){if(t===e)return t;if(s>500)return e;const n=js(t)&&js(e);if(!n&&!(Gr(t)&&Gr(e)))return e;const c=(n?t:Object.keys(t)).length,d=n?e:Object.keys(e),u=d.length,y=n?new Array(u):{};let x=0;for(let b=0;b<u;b++){const p=n?b:d[b],g=t[p],m=e[p];if(g===m){y[p]=g,(n?b<c:Gn.call(t,p))&&x++;continue}if(g===null||m===null||typeof g!="object"||typeof m!="object"){y[p]=m;continue}const S=Kr(g,m,s+1);y[p]=S,S===g&&x++}return c===u&&x===c?t:y}function Vr(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(const s in t)if(t[s]!==e[s])return!1;return!0}function js(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function Gr(t){if(!_s(t))return!1;const e=t.constructor;if(e===void 0)return!0;const s=e.prototype;return!(!_s(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function _s(t){return Object.prototype.toString.call(t)==="[object Object]"}function Yn(t){return new Promise(e=>{_t.setTimeout(e,t)})}function Yr(t,e,s){if(typeof s.structuralSharing=="function")return s.structuralSharing(t,e);if(s.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return Kr(t,e)}catch(n){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${s.queryHash}]: ${n}`),n}return Kr(t,e)}return e}function Xn(t,e,s=0){const n=[...t,e];return s&&n.length>s?n.slice(1):n}function Jn(t,e,s=0){const n=[e,...t];return s&&n.length>s?n.slice(0,-1):n}var Rr=Symbol();function en(t,e){return process.env.NODE_ENV!=="production"&&t.queryFn===Rr&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${t.queryHash}'`),!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===Rr?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function tn(t,e){return typeof t=="function"?t(...e):!!t}function Zn(t,e,s){let n=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(i??(i=e()),n||(n=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i)}),t}var Tt,ct,Wt,Hs,ei=(Hs=class extends vr{constructor(){super();Y(this,Tt);Y(this,ct);Y(this,Wt);W(this,Wt,e=>{if(!Mt&&window.addEventListener){const s=()=>e();return window.addEventListener("visibilitychange",s,!1),()=>{window.removeEventListener("visibilitychange",s)}}})}onSubscribe(){l(this,ct)||this.setEventListener(l(this,Wt))}onUnsubscribe(){var e;this.hasListeners()||((e=l(this,ct))==null||e.call(this),W(this,ct,void 0))}setEventListener(e){var s;W(this,Wt,e),(s=l(this,ct))==null||s.call(this),W(this,ct,e(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(e){l(this,Tt)!==e&&(W(this,Tt,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(s=>{s(e)})}isFocused(){var e;return typeof l(this,Tt)=="boolean"?l(this,Tt):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},Tt=new WeakMap,ct=new WeakMap,Wt=new WeakMap,Hs),cs=new ei;function Xr(){let t,e;const s=new Promise((i,c)=>{t=i,e=c});s.status="pending",s.catch(()=>{});function n(i){Object.assign(s,i),delete s.resolve,delete s.reject}return s.resolve=i=>{n({status:"fulfilled",value:i}),t(i)},s.reject=i=>{n({status:"rejected",reason:i}),e(i)},s}var ti=Kn;function ri(){let t=[],e=0,s=u=>{u()},n=u=>{u()},i=ti;const c=u=>{e?t.push(u):i(()=>{s(u)})},d=()=>{const u=t;t=[],u.length&&i(()=>{n(()=>{u.forEach(y=>{s(y)})})})};return{batch:u=>{let y;e++;try{y=u()}finally{e--,e||d()}return y},batchCalls:u=>(...y)=>{c(()=>{u(...y)})},schedule:c,setNotifyFunction:u=>{s=u},setBatchNotifyFunction:u=>{n=u},setScheduler:u=>{i=u}}}var ke=ri(),zt,ut,$t,qs,si=(qs=class extends vr{constructor(){super();Y(this,zt,!0);Y(this,ut);Y(this,$t);W(this,$t,e=>{if(!Mt&&window.addEventListener){const s=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",s,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",s),window.removeEventListener("offline",n)}}})}onSubscribe(){l(this,ut)||this.setEventListener(l(this,$t))}onUnsubscribe(){var e;this.hasListeners()||((e=l(this,ut))==null||e.call(this),W(this,ut,void 0))}setEventListener(e){var s;W(this,$t,e),(s=l(this,ut))==null||s.call(this),W(this,ut,e(this.setOnline.bind(this)))}setOnline(e){l(this,zt)!==e&&(W(this,zt,e),this.listeners.forEach(n=>{n(e)}))}isOnline(){return l(this,zt)}},zt=new WeakMap,ut=new WeakMap,$t=new WeakMap,qs),Cr=new si;function ni(t){return Math.min(1e3*2**t,3e4)}function rn(t){return(t??"online")==="online"?Cr.isOnline():!0}var Jr=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function sn(t){let e=!1,s=0,n;const i=Xr(),c=()=>i.status!=="pending",d=f=>{var j;if(!c()){const v=new Jr(f);g(v),(j=t.onCancel)==null||j.call(t,v)}},u=()=>{e=!0},y=()=>{e=!1},x=()=>cs.isFocused()&&(t.networkMode==="always"||Cr.isOnline())&&t.canRun(),b=()=>rn(t.networkMode)&&t.canRun(),p=f=>{c()||(n==null||n(),i.resolve(f))},g=f=>{c()||(n==null||n(),i.reject(f))},m=()=>new Promise(f=>{var j;n=v=>{(c()||x())&&f(v)},(j=t.onPause)==null||j.call(t)}).then(()=>{var f;n=void 0,c()||(f=t.onContinue)==null||f.call(t)}),S=()=>{if(c())return;let f;const j=s===0?t.initialPromise:void 0;try{f=j??t.fn()}catch(v){f=Promise.reject(v)}Promise.resolve(f).then(p).catch(v=>{var P;if(c())return;const w=t.retry??(Mt?0:3),h=t.retryDelay??ni,k=typeof h=="function"?h(s,v):h,R=w===!0||typeof w=="number"&&s<w||typeof w=="function"&&w(s,v);if(e||!R){g(v);return}s++,(P=t.onFail)==null||P.call(t,s,v),Yn(k).then(()=>x()?void 0:m()).then(()=>{e?g(v):S()})})};return{promise:i,status:()=>i.status,cancel:d,continue:()=>(n==null||n(),i),cancelRetry:u,continueRetry:y,canStart:b,start:()=>(b()?S():m().then(S),i)}}var Rt,Qs,nn=(Qs=class{constructor(){Y(this,Rt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Qr(this.gcTime)&&W(this,Rt,_t.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(Mt?1/0:5*60*1e3))}clearGcTimeout(){l(this,Rt)&&(_t.clearTimeout(l(this,Rt)),W(this,Rt,void 0))}},Rt=new WeakMap,Qs),Ct,Ut,Me,Nt,we,gr,Ft,$e,Xe,Ks,ii=(Ks=class extends nn{constructor(e){super();Y(this,$e);Y(this,Ct);Y(this,Ut);Y(this,Me);Y(this,Nt);Y(this,we);Y(this,gr);Y(this,Ft);W(this,Ft,!1),W(this,gr,e.defaultOptions),this.setOptions(e.options),this.observers=[],W(this,Nt,e.client),W(this,Me,l(this,Nt).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,W(this,Ct,Ts(this.options)),this.state=e.state??l(this,Ct),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=l(this,we))==null?void 0:e.promise}setOptions(e){if(this.options={...l(this,gr),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const s=Ts(this.options);s.data!==void 0&&(this.setState(Es(s.data,s.dataUpdatedAt)),W(this,Ct,s))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Me).remove(this)}setData(e,s){const n=Yr(this.state.data,e,this.options);return se(this,$e,Xe).call(this,{data:n,type:"success",dataUpdatedAt:s==null?void 0:s.updatedAt,manual:s==null?void 0:s.manual}),n}setState(e,s){se(this,$e,Xe).call(this,{type:"setState",state:e,setStateOptions:s})}cancel(e){var n,i;const s=(n=l(this,we))==null?void 0:n.promise;return(i=l(this,we))==null||i.cancel(e),s?s.then(Re).catch(Re):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(l(this,Ct))}isActive(){return this.observers.some(e=>Ae(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Rr||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>mt(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Zs(this.state.dataUpdatedAt,e)}onFocus(){var s;const e=this.observers.find(n=>n.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(s=l(this,we))==null||s.continue()}onOnline(){var s;const e=this.observers.find(n=>n.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(s=l(this,we))==null||s.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),l(this,Me).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(s=>s!==e),this.observers.length||(l(this,we)&&(l(this,Ft)?l(this,we).cancel({revert:!0}):l(this,we).cancelRetry()),this.scheduleGc()),l(this,Me).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||se(this,$e,Xe).call(this,{type:"invalidate"})}async fetch(e,s){var y,x,b,p,g,m,S,f,j,v,w,h;if(this.state.fetchStatus!=="idle"&&((y=l(this,we))==null?void 0:y.status())!=="rejected"){if(this.state.data!==void 0&&(s!=null&&s.cancelRefetch))this.cancel({silent:!0});else if(l(this,we))return l(this,we).continueRetry(),l(this,we).promise}if(e&&this.setOptions(e),!this.options.queryFn){const k=this.observers.find(R=>R.options.queryFn);k&&this.setOptions(k.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const n=new AbortController,i=k=>{Object.defineProperty(k,"signal",{enumerable:!0,get:()=>(W(this,Ft,!0),n.signal)})},c=()=>{const k=en(this.options,s),P=(()=>{const H={client:l(this,Nt),queryKey:this.queryKey,meta:this.meta};return i(H),H})();return W(this,Ft,!1),this.options.persister?this.options.persister(k,P,this):k(P)},u=(()=>{const k={fetchOptions:s,options:this.options,queryKey:this.queryKey,client:l(this,Nt),state:this.state,fetchFn:c};return i(k),k})();(x=this.options.behavior)==null||x.onFetch(u,this),W(this,Ut,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((b=u.fetchOptions)==null?void 0:b.meta))&&se(this,$e,Xe).call(this,{type:"fetch",meta:(p=u.fetchOptions)==null?void 0:p.meta}),W(this,we,sn({initialPromise:s==null?void 0:s.initialPromise,fn:u.fetchFn,onCancel:k=>{k instanceof Jr&&k.revert&&this.setState({...l(this,Ut),fetchStatus:"idle"}),n.abort()},onFail:(k,R)=>{se(this,$e,Xe).call(this,{type:"failed",failureCount:k,error:R})},onPause:()=>{se(this,$e,Xe).call(this,{type:"pause"})},onContinue:()=>{se(this,$e,Xe).call(this,{type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0}));try{const k=await l(this,we).start();if(k===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(k),(m=(g=l(this,Me).config).onSuccess)==null||m.call(g,k,this),(f=(S=l(this,Me).config).onSettled)==null||f.call(S,k,this.state.error,this),k}catch(k){if(k instanceof Jr){if(k.silent)return l(this,we).promise;if(k.revert){if(this.state.data===void 0)throw k;return this.state.data}}throw se(this,$e,Xe).call(this,{type:"error",error:k}),(v=(j=l(this,Me).config).onError)==null||v.call(j,k,this),(h=(w=l(this,Me).config).onSettled)==null||h.call(w,this.state.data,k,this),k}finally{this.scheduleGc()}}},Ct=new WeakMap,Ut=new WeakMap,Me=new WeakMap,Nt=new WeakMap,we=new WeakMap,gr=new WeakMap,Ft=new WeakMap,$e=new WeakSet,Xe=function(e){const s=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...an(n.data,this.options),fetchMeta:e.meta??null};case"success":const i={...n,...Es(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return W(this,Ut,e.manual?i:void 0),i;case"error":const c=e.error;return{...n,error:c,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:c,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=s(this.state),ke.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),l(this,Me).notify({query:this,type:"updated",action:e})})},Ks);function an(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:rn(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Es(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Ts(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,s=e!==void 0,n=s?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:s?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var Te,ne,br,_e,Bt,Ht,Je,dt,mr,qt,Qt,It,Ot,ht,Kt,ce,cr,Zr,es,ts,rs,ss,ns,is,on,Vs,ai=(Vs=class extends vr{constructor(e,s){super();Y(this,ce);Y(this,Te);Y(this,ne);Y(this,br);Y(this,_e);Y(this,Bt);Y(this,Ht);Y(this,Je);Y(this,dt);Y(this,mr);Y(this,qt);Y(this,Qt);Y(this,It);Y(this,Ot);Y(this,ht);Y(this,Kt,new Set);this.options=s,W(this,Te,e),W(this,dt,null),W(this,Je,Xr()),this.bindMethods(),this.setOptions(s)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,ne).addObserver(this),Rs(l(this,ne),this.options)?se(this,ce,cr).call(this):this.updateResult(),se(this,ce,rs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return as(l(this,ne),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return as(l(this,ne),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,se(this,ce,ss).call(this),se(this,ce,ns).call(this),l(this,ne).removeObserver(this)}setOptions(e){const s=this.options,n=l(this,ne);if(this.options=l(this,Te).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ae(this.options.enabled,l(this,ne))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");se(this,ce,is).call(this),l(this,ne).setOptions(this.options),s._defaulted&&!Vr(this.options,s)&&l(this,Te).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,ne),observer:this});const i=this.hasListeners();i&&Cs(l(this,ne),n,this.options,s)&&se(this,ce,cr).call(this),this.updateResult(),i&&(l(this,ne)!==n||Ae(this.options.enabled,l(this,ne))!==Ae(s.enabled,l(this,ne))||mt(this.options.staleTime,l(this,ne))!==mt(s.staleTime,l(this,ne)))&&se(this,ce,Zr).call(this);const c=se(this,ce,es).call(this);i&&(l(this,ne)!==n||Ae(this.options.enabled,l(this,ne))!==Ae(s.enabled,l(this,ne))||c!==l(this,ht))&&se(this,ce,ts).call(this,c)}getOptimisticResult(e){const s=l(this,Te).getQueryCache().build(l(this,Te),e),n=this.createResult(s,e);return li(this,n)&&(W(this,_e,n),W(this,Ht,this.options),W(this,Bt,l(this,ne).state)),n}getCurrentResult(){return l(this,_e)}trackResult(e,s){return new Proxy(e,{get:(n,i)=>(this.trackProp(i),s==null||s(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&l(this,Je).status==="pending"&&l(this,Je).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,i))})}trackProp(e){l(this,Kt).add(e)}getCurrentQuery(){return l(this,ne)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const s=l(this,Te).defaultQueryOptions(e),n=l(this,Te).getQueryCache().build(l(this,Te),s);return n.fetch().then(()=>this.createResult(n,s))}fetch(e){return se(this,ce,cr).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,_e)))}createResult(e,s){var A;const n=l(this,ne),i=this.options,c=l(this,_e),d=l(this,Bt),u=l(this,Ht),x=e!==n?e.state:l(this,br),{state:b}=e;let p={...b},g=!1,m;if(s._optimisticResults){const _=this.hasListeners(),C=!_&&Rs(e,s),E=_&&Cs(e,n,s,i);(C||E)&&(p={...p,...an(b.data,e.options)}),s._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:S,errorUpdatedAt:f,status:j}=p;m=p.data;let v=!1;if(s.placeholderData!==void 0&&m===void 0&&j==="pending"){let _;c!=null&&c.isPlaceholderData&&s.placeholderData===(u==null?void 0:u.placeholderData)?(_=c.data,v=!0):_=typeof s.placeholderData=="function"?s.placeholderData((A=l(this,Qt))==null?void 0:A.state.data,l(this,Qt)):s.placeholderData,_!==void 0&&(j="success",m=Yr(c==null?void 0:c.data,_,s),g=!0)}if(s.select&&m!==void 0&&!v)if(c&&m===(d==null?void 0:d.data)&&s.select===l(this,mr))m=l(this,qt);else try{W(this,mr,s.select),m=s.select(m),m=Yr(c==null?void 0:c.data,m,s),W(this,qt,m),W(this,dt,null)}catch(_){W(this,dt,_)}l(this,dt)&&(S=l(this,dt),m=l(this,qt),f=Date.now(),j="error");const w=p.fetchStatus==="fetching",h=j==="pending",k=j==="error",R=h&&w,P=m!==void 0,B={status:j,fetchStatus:p.fetchStatus,isPending:h,isSuccess:j==="success",isError:k,isInitialLoading:R,isLoading:R,data:m,dataUpdatedAt:p.dataUpdatedAt,error:S,errorUpdatedAt:f,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:p.dataUpdateCount>0||p.errorUpdateCount>0,isFetchedAfterMount:p.dataUpdateCount>x.dataUpdateCount||p.errorUpdateCount>x.errorUpdateCount,isFetching:w,isRefetching:w&&!h,isLoadingError:k&&!P,isPaused:p.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:k&&P,isStale:us(e,s),refetch:this.refetch,promise:l(this,Je),isEnabled:Ae(s.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const _=B.data!==void 0,C=B.status==="error"&&!_,E=U=>{C?U.reject(B.error):_&&U.resolve(B.data)},N=()=>{const U=W(this,Je,B.promise=Xr());E(U)},I=l(this,Je);switch(I.status){case"pending":e.queryHash===n.queryHash&&E(I);break;case"fulfilled":(C||B.data!==I.value)&&N();break;case"rejected":(!C||B.error!==I.reason)&&N();break}}return B}updateResult(){const e=l(this,_e),s=this.createResult(l(this,ne),this.options);if(W(this,Bt,l(this,ne).state),W(this,Ht,this.options),l(this,Bt).data!==void 0&&W(this,Qt,l(this,ne)),Vr(s,e))return;W(this,_e,s);const n=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,c=typeof i=="function"?i():i;if(c==="all"||!c&&!l(this,Kt).size)return!0;const d=new Set(c??l(this,Kt));return this.options.throwOnError&&d.add("error"),Object.keys(l(this,_e)).some(u=>{const y=u;return l(this,_e)[y]!==e[y]&&d.has(y)})};se(this,ce,on).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&se(this,ce,rs).call(this)}},Te=new WeakMap,ne=new WeakMap,br=new WeakMap,_e=new WeakMap,Bt=new WeakMap,Ht=new WeakMap,Je=new WeakMap,dt=new WeakMap,mr=new WeakMap,qt=new WeakMap,Qt=new WeakMap,It=new WeakMap,Ot=new WeakMap,ht=new WeakMap,Kt=new WeakMap,ce=new WeakSet,cr=function(e){se(this,ce,is).call(this);let s=l(this,ne).fetch(this.options,e);return e!=null&&e.throwOnError||(s=s.catch(Re)),s},Zr=function(){se(this,ce,ss).call(this);const e=mt(this.options.staleTime,l(this,ne));if(Mt||l(this,_e).isStale||!Qr(e))return;const n=Zs(l(this,_e).dataUpdatedAt,e)+1;W(this,It,_t.setTimeout(()=>{l(this,_e).isStale||this.updateResult()},n))},es=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,ne)):this.options.refetchInterval)??!1},ts=function(e){se(this,ce,ns).call(this),W(this,ht,e),!(Mt||Ae(this.options.enabled,l(this,ne))===!1||!Qr(l(this,ht))||l(this,ht)===0)&&W(this,Ot,_t.setInterval(()=>{(this.options.refetchIntervalInBackground||cs.isFocused())&&se(this,ce,cr).call(this)},l(this,ht)))},rs=function(){se(this,ce,Zr).call(this),se(this,ce,ts).call(this,se(this,ce,es).call(this))},ss=function(){l(this,It)&&(_t.clearTimeout(l(this,It)),W(this,It,void 0))},ns=function(){l(this,Ot)&&(_t.clearInterval(l(this,Ot)),W(this,Ot,void 0))},is=function(){const e=l(this,Te).getQueryCache().build(l(this,Te),this.options);if(e===l(this,ne))return;const s=l(this,ne);W(this,ne,e),W(this,br,e.state),this.hasListeners()&&(s==null||s.removeObserver(this),e.addObserver(this))},on=function(e){ke.batch(()=>{e.listeners&&this.listeners.forEach(s=>{s(l(this,_e))}),l(this,Te).getQueryCache().notify({query:l(this,ne),type:"observerResultsUpdated"})})},Vs);function oi(t,e){return Ae(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function Rs(t,e){return oi(t,e)||t.state.data!==void 0&&as(t,e,e.refetchOnMount)}function as(t,e,s){if(Ae(e.enabled,t)!==!1&&mt(e.staleTime,t)!=="static"){const n=typeof s=="function"?s(t):s;return n==="always"||n!==!1&&us(t,e)}return!1}function Cs(t,e,s,n){return(t!==e||Ae(n.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&us(t,s)}function us(t,e){return Ae(e.enabled,t)!==!1&&t.isStaleByTime(mt(e.staleTime,t))}function li(t,e){return!Vr(t.getCurrentResult(),e)}function Ns(t){return{onFetch:(e,s)=>{var b,p,g,m,S;const n=e.options,i=(g=(p=(b=e.fetchOptions)==null?void 0:b.meta)==null?void 0:p.fetchMore)==null?void 0:g.direction,c=((m=e.state.data)==null?void 0:m.pages)||[],d=((S=e.state.data)==null?void 0:S.pageParams)||[];let u={pages:[],pageParams:[]},y=0;const x=async()=>{let f=!1;const j=h=>{Zn(h,()=>e.signal,()=>f=!0)},v=en(e.options,e.fetchOptions),w=async(h,k,R)=>{if(f)return Promise.reject();if(k==null&&h.pages.length)return Promise.resolve(h);const H=(()=>{const C={client:e.client,queryKey:e.queryKey,pageParam:k,direction:R?"backward":"forward",meta:e.options.meta};return j(C),C})(),B=await v(H),{maxPages:A}=e.options,_=R?Jn:Xn;return{pages:_(h.pages,B,A),pageParams:_(h.pageParams,k,A)}};if(i&&c.length){const h=i==="backward",k=h?ci:Fs,R={pages:c,pageParams:d},P=k(n,R);u=await w(R,P,h)}else{const h=t??c.length;do{const k=y===0?d[0]??n.initialPageParam:Fs(n,u);if(y>0&&k==null)break;u=await w(u,k),y++}while(y<h)}return u};e.options.persister?e.fetchFn=()=>{var f,j;return(j=(f=e.options).persister)==null?void 0:j.call(f,x,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},s)}:e.fetchFn=x}}}function Fs(t,{pages:e,pageParams:s}){const n=e.length-1;return e.length>0?t.getNextPageParam(e[n],e,s[n],s):void 0}function ci(t,{pages:e,pageParams:s}){var n;return e.length>0?(n=t.getPreviousPageParam)==null?void 0:n.call(t,e[0],e,s[0],s):void 0}var xr,Ke,Se,Pt,Ve,lt,Gs,ui=(Gs=class extends nn{constructor(e){super();Y(this,Ve);Y(this,xr);Y(this,Ke);Y(this,Se);Y(this,Pt);W(this,xr,e.client),this.mutationId=e.mutationId,W(this,Se,e.mutationCache),W(this,Ke,[]),this.state=e.state||di(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){l(this,Ke).includes(e)||(l(this,Ke).push(e),this.clearGcTimeout(),l(this,Se).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){W(this,Ke,l(this,Ke).filter(s=>s!==e)),this.scheduleGc(),l(this,Se).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){l(this,Ke).length||(this.state.status==="pending"?this.scheduleGc():l(this,Se).remove(this))}continue(){var e;return((e=l(this,Pt))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var d,u,y,x,b,p,g,m,S,f,j,v,w,h,k,R,P,H;const s=()=>{se(this,Ve,lt).call(this,{type:"continue"})},n={client:l(this,xr),meta:this.options.meta,mutationKey:this.options.mutationKey};W(this,Pt,sn({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(B,A)=>{se(this,Ve,lt).call(this,{type:"failed",failureCount:B,error:A})},onPause:()=>{se(this,Ve,lt).call(this,{type:"pause"})},onContinue:s,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,Se).canRun(this)}));const i=this.state.status==="pending",c=!l(this,Pt).canStart();try{if(i)s();else{se(this,Ve,lt).call(this,{type:"pending",variables:e,isPaused:c}),l(this,Se).config.onMutate&&await l(this,Se).config.onMutate(e,this,n);const A=await((u=(d=this.options).onMutate)==null?void 0:u.call(d,e,n));A!==this.state.context&&se(this,Ve,lt).call(this,{type:"pending",context:A,variables:e,isPaused:c})}const B=await l(this,Pt).start();return await((x=(y=l(this,Se).config).onSuccess)==null?void 0:x.call(y,B,e,this.state.context,this,n)),await((p=(b=this.options).onSuccess)==null?void 0:p.call(b,B,e,this.state.context,n)),await((m=(g=l(this,Se).config).onSettled)==null?void 0:m.call(g,B,null,this.state.variables,this.state.context,this,n)),await((f=(S=this.options).onSettled)==null?void 0:f.call(S,B,null,e,this.state.context,n)),se(this,Ve,lt).call(this,{type:"success",data:B}),B}catch(B){try{await((v=(j=l(this,Se).config).onError)==null?void 0:v.call(j,B,e,this.state.context,this,n))}catch(A){Promise.reject(A)}try{await((h=(w=this.options).onError)==null?void 0:h.call(w,B,e,this.state.context,n))}catch(A){Promise.reject(A)}try{await((R=(k=l(this,Se).config).onSettled)==null?void 0:R.call(k,void 0,B,this.state.variables,this.state.context,this,n))}catch(A){Promise.reject(A)}try{await((H=(P=this.options).onSettled)==null?void 0:H.call(P,void 0,B,e,this.state.context,n))}catch(A){Promise.reject(A)}throw se(this,Ve,lt).call(this,{type:"error",error:B}),B}finally{l(this,Se).runNext(this)}}},xr=new WeakMap,Ke=new WeakMap,Se=new WeakMap,Pt=new WeakMap,Ve=new WeakSet,lt=function(e){const s=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=s(this.state),ke.batch(()=>{l(this,Ke).forEach(n=>{n.onMutationUpdate(e)}),l(this,Se).notify({mutation:this,type:"updated",action:e})})},Gs);function di(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ze,Ue,yr,Ys,hi=(Ys=class extends vr{constructor(e={}){super();Y(this,Ze);Y(this,Ue);Y(this,yr);this.config=e,W(this,Ze,new Set),W(this,Ue,new Map),W(this,yr,0)}build(e,s,n){const i=new ui({client:e,mutationCache:this,mutationId:++_r(this,yr)._,options:e.defaultMutationOptions(s),state:n});return this.add(i),i}add(e){l(this,Ze).add(e);const s=Er(e);if(typeof s=="string"){const n=l(this,Ue).get(s);n?n.push(e):l(this,Ue).set(s,[e])}this.notify({type:"added",mutation:e})}remove(e){if(l(this,Ze).delete(e)){const s=Er(e);if(typeof s=="string"){const n=l(this,Ue).get(s);if(n)if(n.length>1){const i=n.indexOf(e);i!==-1&&n.splice(i,1)}else n[0]===e&&l(this,Ue).delete(s)}}this.notify({type:"removed",mutation:e})}canRun(e){const s=Er(e);if(typeof s=="string"){const n=l(this,Ue).get(s),i=n==null?void 0:n.find(c=>c.state.status==="pending");return!i||i===e}else return!0}runNext(e){var n;const s=Er(e);if(typeof s=="string"){const i=(n=l(this,Ue).get(s))==null?void 0:n.find(c=>c!==e&&c.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){ke.batch(()=>{l(this,Ze).forEach(e=>{this.notify({type:"removed",mutation:e})}),l(this,Ze).clear(),l(this,Ue).clear()})}getAll(){return Array.from(l(this,Ze))}find(e){const s={exact:!0,...e};return this.getAll().find(n=>Ss(s,n))}findAll(e={}){return this.getAll().filter(s=>Ss(e,s))}notify(e){ke.batch(()=>{this.listeners.forEach(s=>{s(e)})})}resumePausedMutations(){const e=this.getAll().filter(s=>s.state.isPaused);return ke.batch(()=>Promise.all(e.map(s=>s.continue().catch(Re))))}},Ze=new WeakMap,Ue=new WeakMap,yr=new WeakMap,Ys);function Er(t){var e;return(e=t.options.scope)==null?void 0:e.id}var Ge,Xs,fi=(Xs=class extends vr{constructor(e={}){super();Y(this,Ge);this.config=e,W(this,Ge,new Map)}build(e,s,n){const i=s.queryKey,c=s.queryHash??ls(i,s);let d=this.get(c);return d||(d=new ii({client:e,queryKey:i,queryHash:c,options:e.defaultQueryOptions(s),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(d)),d}add(e){l(this,Ge).has(e.queryHash)||(l(this,Ge).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const s=l(this,Ge).get(e.queryHash);s&&(e.destroy(),s===e&&l(this,Ge).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){ke.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return l(this,Ge).get(e)}getAll(){return[...l(this,Ge).values()]}find(e){const s={exact:!0,...e};return this.getAll().find(n=>ks(s,n))}findAll(e={}){const s=this.getAll();return Object.keys(e).length>0?s.filter(n=>ks(e,n)):s}notify(e){ke.batch(()=>{this.listeners.forEach(s=>{s(e)})})}onFocus(){ke.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ke.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Ge=new WeakMap,Xs),pe,ft,pt,Vt,Gt,gt,Yt,Xt,Js,pi=(Js=class{constructor(t={}){Y(this,pe);Y(this,ft);Y(this,pt);Y(this,Vt);Y(this,Gt);Y(this,gt);Y(this,Yt);Y(this,Xt);W(this,pe,t.queryCache||new fi),W(this,ft,t.mutationCache||new hi),W(this,pt,t.defaultOptions||{}),W(this,Vt,new Map),W(this,Gt,new Map),W(this,gt,0)}mount(){_r(this,gt)._++,l(this,gt)===1&&(W(this,Yt,cs.subscribe(async t=>{t&&(await this.resumePausedMutations(),l(this,pe).onFocus())})),W(this,Xt,Cr.subscribe(async t=>{t&&(await this.resumePausedMutations(),l(this,pe).onOnline())})))}unmount(){var t,e;_r(this,gt)._--,l(this,gt)===0&&((t=l(this,Yt))==null||t.call(this),W(this,Yt,void 0),(e=l(this,Xt))==null||e.call(this),W(this,Xt,void 0))}isFetching(t){return l(this,pe).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return l(this,ft).findAll({...t,status:"pending"}).length}getQueryData(t){var s;const e=this.defaultQueryOptions({queryKey:t});return(s=l(this,pe).get(e.queryHash))==null?void 0:s.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),s=l(this,pe).build(this,e),n=s.state.data;return n===void 0?this.fetchQuery(t):(t.revalidateIfStale&&s.isStaleByTime(mt(e.staleTime,s))&&this.prefetchQuery(e),Promise.resolve(n))}getQueriesData(t){return l(this,pe).findAll(t).map(({queryKey:e,state:s})=>{const n=s.data;return[e,n]})}setQueryData(t,e,s){const n=this.defaultQueryOptions({queryKey:t}),i=l(this,pe).get(n.queryHash),c=i==null?void 0:i.state.data,d=Vn(e,c);if(d!==void 0)return l(this,pe).build(this,n).setData(d,{...s,manual:!0})}setQueriesData(t,e,s){return ke.batch(()=>l(this,pe).findAll(t).map(({queryKey:n})=>[n,this.setQueryData(n,e,s)]))}getQueryState(t){var s;const e=this.defaultQueryOptions({queryKey:t});return(s=l(this,pe).get(e.queryHash))==null?void 0:s.state}removeQueries(t){const e=l(this,pe);ke.batch(()=>{e.findAll(t).forEach(s=>{e.remove(s)})})}resetQueries(t,e){const s=l(this,pe);return ke.batch(()=>(s.findAll(t).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const s={revert:!0,...e},n=ke.batch(()=>l(this,pe).findAll(t).map(i=>i.cancel(s)));return Promise.all(n).then(Re).catch(Re)}invalidateQueries(t,e={}){return ke.batch(()=>(l(this,pe).findAll(t).forEach(s=>{s.invalidate()}),(t==null?void 0:t.refetchType)==="none"?Promise.resolve():this.refetchQueries({...t,type:(t==null?void 0:t.refetchType)??(t==null?void 0:t.type)??"active"},e)))}refetchQueries(t,e={}){const s={...e,cancelRefetch:e.cancelRefetch??!0},n=ke.batch(()=>l(this,pe).findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let c=i.fetch(void 0,s);return s.throwOnError||(c=c.catch(Re)),i.state.fetchStatus==="paused"?Promise.resolve():c}));return Promise.all(n).then(Re)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const s=l(this,pe).build(this,e);return s.isStaleByTime(mt(e.staleTime,s))?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(Re).catch(Re)}fetchInfiniteQuery(t){return t.behavior=Ns(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(Re).catch(Re)}ensureInfiniteQueryData(t){return t.behavior=Ns(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return Cr.isOnline()?l(this,ft).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,pe)}getMutationCache(){return l(this,ft)}getDefaultOptions(){return l(this,pt)}setDefaultOptions(t){W(this,pt,t)}setQueryDefaults(t,e){l(this,Vt).set(hr(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...l(this,Vt).values()],s={};return e.forEach(n=>{fr(t,n.queryKey)&&Object.assign(s,n.defaultOptions)}),s}setMutationDefaults(t,e){l(this,Gt).set(hr(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...l(this,Gt).values()],s={};return e.forEach(n=>{fr(t,n.mutationKey)&&Object.assign(s,n.defaultOptions)}),s}defaultQueryOptions(t){if(t._defaulted)return t;const e={...l(this,pt).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=ls(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===Rr&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...l(this,pt).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){l(this,pe).clear(),l(this,ft).clear()}},pe=new WeakMap,ft=new WeakMap,pt=new WeakMap,Vt=new WeakMap,Gt=new WeakMap,gt=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Js),ln=Le.createContext(void 0),cn=t=>{const e=Le.useContext(ln);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},gi=({client:t,children:e})=>(Le.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),r.jsx(ln.Provider,{value:t,children:e})),un=Le.createContext(!1),bi=()=>Le.useContext(un);un.Provider;function mi(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var xi=Le.createContext(mi()),yi=()=>Le.useContext(xi),vi=(t,e,s)=>{const n=s!=null&&s.state.error&&typeof t.throwOnError=="function"?tn(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||n)&&(e.isReset()||(t.retryOnMount=!1))},wi=t=>{Le.useEffect(()=>{t.clearReset()},[t])},ki=({result:t,errorResetBoundary:e,throwOnError:s,query:n,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&n&&(i&&t.data===void 0||tn(s,[t.error,n])),Si=t=>{if(t.suspense){const s=i=>i==="static"?i:Math.max(i??1e3,1e3),n=t.staleTime;t.staleTime=typeof n=="function"?(...i)=>s(n(...i)):s(n),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},ji=(t,e)=>t.isLoading&&t.isFetching&&!e,_i=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,Bs=(t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()});function Ei(t,e,s){var g,m,S,f;if(process.env.NODE_ENV!=="production"&&(typeof t!="object"||Array.isArray(t)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const n=bi(),i=yi(),c=cn(),d=c.defaultQueryOptions(t);(m=(g=c.getDefaultOptions().queries)==null?void 0:g._experimental_beforeQuery)==null||m.call(g,d);const u=c.getQueryCache().get(d.queryHash);process.env.NODE_ENV!=="production"&&(d.queryFn||console.error(`[${d.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),d._optimisticResults=n?"isRestoring":"optimistic",Si(d),vi(d,i,u),wi(i);const y=!c.getQueryCache().get(d.queryHash),[x]=Le.useState(()=>new e(c,d)),b=x.getOptimisticResult(d),p=!n&&t.subscribed!==!1;if(Le.useSyncExternalStore(Le.useCallback(j=>{const v=p?x.subscribe(ke.batchCalls(j)):Re;return x.updateResult(),v},[x,p]),()=>x.getCurrentResult(),()=>x.getCurrentResult()),Le.useEffect(()=>{x.setOptions(d)},[d,x]),_i(d,b))throw Bs(d,x,i);if(ki({result:b,errorResetBoundary:i,throwOnError:d.throwOnError,query:u,suspense:d.suspense}))throw b.error;if((f=(S=c.getDefaultOptions().queries)==null?void 0:S._experimental_afterQuery)==null||f.call(S,d,b),d.experimental_prefetchInRender&&!Mt&&ji(b,n)){const j=y?Bs(d,x,i):u==null?void 0:u.promise;j==null||j.catch(Re).finally(()=>{x.updateResult()})}return d.notifyOnChangeProps?b:x.trackResult(b)}function wr(t,e){return Ei(t,ai)}const Ti=()=>`bob_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;function dn({ga4Config:t,hostContext:e,callbacks:s,enabled:n=!0}){const i=a.useRef(Ti()),c=a.useRef(!1),d=a.useCallback((h,k)=>{if(!(!(t!=null&&t.measurementId)||typeof window>"u")&&window.gtag){const R={...k,send_to:t.measurementId};t.debug&&console.log("[BobAnalytics] GA4 event:",h,R),window.gtag("event",h,R)}},[t]),u=a.useCallback((h,k={})=>{var P,H,B,A,_,C,E,N;if(!n)return;const R={event_name:h,timestamp:new Date().toISOString(),session_id:i.current,user_email:(P=e==null?void 0:e.user)==null?void 0:P.email,user_id:(H=e==null?void 0:e.user)==null?void 0:H.id,vehicle_id:(_=(A=(B=e==null?void 0:e.vehicle)==null?void 0:B.selectedVehicle)==null?void 0:A.vehicle_id)==null?void 0:_.toString(),rego:(E=(C=e==null?void 0:e.vehicle)==null?void 0:C.selectedVehicle)==null?void 0:E.rego,parameters:k};d(h,{session_id:R.session_id,user_email:R.user_email,vehicle_id:R.vehicle_id,...k}),(N=s==null?void 0:s.onAnalyticsEvent)==null||N.call(s,R),t!=null&&t.debug&&console.log("[BobAnalytics] Event tracked:",R)},[n,e,s,d,t==null?void 0:t.debug]),y=a.useCallback(()=>{var h,k,R;c.current||(c.current=!0,u("bob_session_start",{widget_version:et,has_vehicle:!!((h=e==null?void 0:e.vehicle)!=null&&h.selectedVehicle),has_user:!!((k=e==null?void 0:e.user)!=null&&k.id)||!!((R=e==null?void 0:e.user)!=null&&R.email)}))},[u,e]),x=a.useCallback((h,k)=>{u("bob_message_sent",{message_length:h,has_vehicle:k})},[u]),b=a.useCallback(h=>{u("bob_vehicle_identified",{vehicle_make:h.make||"unknown",vehicle_model:h.model||"unknown",vehicle_year:h.year||"unknown",rego:h.rego})},[u]),p=a.useCallback((h,k)=>{u("bob_parts_viewed",{part_count:h,vehicle_id:k})},[u]),g=a.useCallback(h=>{u("bob_product_clicked",{sku:h.sku,product_name:h.product_name,price:h.price,brand:h.brand})},[u]),m=a.useCallback(h=>{u("bob_product_viewed",{sku:h.sku,product_name:h.product_name,price:h.price,brand:h.brand})},[u]),S=a.useCallback(h=>{u("bob_add_to_cart",{sku:h.sku,product_name:h.product_name,price:h.price,brand:h.brand,quantity:h.quantity??1})},[u]),f=a.useCallback((h,k)=>{u("bob_checkout_started",{cart_value:h,item_count:k})},[u]),j=a.useCallback(h=>{const k=Math.ceil(h/5/150*60);u("bob_speech_played",{text_length:h,duration_estimate:k})},[u]),v=a.useCallback(h=>{u("bob_speech_failed",{text_length:h})},[u]),w=a.useCallback((h,k)=>{u("bob_error",{error_type:h,error_message:k})},[u]);return a.useEffect(()=>{y()},[y]),{trackEvent:u,sessionId:i.current,trackSessionStart:y,trackMessageSent:x,trackVehicleIdentified:b,trackPartsViewed:p,trackProductClicked:g,trackProductViewed:m,trackAddToCart:S,trackCheckoutStarted:f,trackSpeechPlayed:j,trackSpeechFailed:v,trackError:w}}const Fr=a.createContext(null);function ds({children:t,bobConfig:e,hostApiConfig:s,hostContext:n={},callbacks:i={},queryClient:c,ga4Config:d,analyticsEnabled:u=!0,bottomOffset:y=0,zIndexBase:x=50}){const b=a.useMemo(()=>new pi({defaultOptions:{queries:{retry:1,staleTime:3e5}}}),[]),p=c||b,g=!!c;a.useEffect(()=>{console.log(`[BobWidget] v${et} initialized`),console.log(`[BobWidget] QueryClient: ${g?"external (shared)":"internal"}`),console.log(`[BobWidget] Analytics: ${u?"enabled":"disabled"}`),d!=null&&d.measurementId&&console.log(`[BobWidget] GA4: ${d.measurementId}`)},[g,u,d==null?void 0:d.measurementId]);const m=a.useMemo(()=>Hr.createClient(e.supabaseUrl,e.supabaseKey),[e.supabaseUrl,e.supabaseKey]),[S,f]=a.useState(n);a.useEffect(()=>{f(n)},[n]);const j=a.useCallback(w=>{f(h=>({...h,...w}))},[]),v=a.useMemo(()=>({bobSupabase:m,bobConfig:e,hostApiConfig:s,hostContext:S,callbacks:i,updateHostContext:j,ga4Config:d,analyticsEnabled:u,bottomOffset:y,zIndexBase:x}),[m,e,s,S,i,j,d,u,y,x]);return r.jsx(gi,{client:p,children:r.jsx(Fr.Provider,{value:v,children:t})})}function tt(){const t=a.useContext(Fr);if(!t)throw new Error("useBobContext must be used within a BobProvider");return t}function Ri(){const{bobSupabase:t}=tt();return t}function At(){const t=a.useContext(Fr);return(t==null?void 0:t.bobSupabase)||null}function Ci(){const{hostContext:t}=tt();return t}function Ni(){const{hostApiConfig:t}=tt();return t}function Fi(){const{callbacks:t}=tt();return t}function Bi(){const{ga4Config:t,analyticsEnabled:e}=tt();return{ga4Config:t,enabled:e}}function hs(){const t=a.useContext(Fr);return t?{bottomOffset:t.bottomOffset,zIndexBase:t.zIndexBase}:{bottomOffset:0,zIndexBase:50}}const Ii=15e3,Oi={greeting_returning:/ah hey|you again|what you after this time/i,greeting_welcome:/g'?day|welcome.*carfix|bob.*here/i,ask_rego:/need your rego|rego.*get cracking|what('?s| is) your rego/i,vehicle_not_found:/couldn'?t find that|double.?check.*plate/i,no_parts_found:/nothing came up|no results|sorry.*search/i,checkout_ready:/ready to checkout|checkout.*ready|choice.*checkout/i,rego_searching:/let('?s| us) see what car|sweet.*searching|searching for/i},or=new Map,Pi=t=>t.replace(/\bya\b/gi,"you"),hn=({onStart:t,onEnd:e,onFailed:s}={})=>{const{bobConfig:n,bobSupabase:i}=tt(),[c,d]=a.useState(!1),u=a.useRef(null),y=a.useRef(null),x=a.useRef(!1),b=a.useRef([]),p=a.useRef(!1),g=a.useRef(!1),m=a.useRef(null),S=a.useRef(null),f=a.useRef(t),j=a.useRef(e),v=a.useRef(s);a.useEffect(()=>{f.current=t,j.current=e,v.current=s},[t,e,s]);const w=a.useCallback(()=>{y.current&&(clearTimeout(y.current),y.current=null)},[]),h=a.useCallback(()=>{var E;x.current||(x.current=!0,console.log("[BobWidget TTS] Fallback: triggering onStart without audio"),(E=f.current)==null||E.call(f))},[]),k=a.useCallback(async E=>{if(or.has(E)){const N=or.get(E);return console.log(`[BobWidget TTS] Cache hit for clip: ${E}`,N?"found":"null"),N||null}try{console.log(`[BobWidget TTS] Fetching clip from DB: ${E}`);const{data:N,error:I}=await i.from("bob_audio_clips").select("audio_url").eq("clip_key",E).eq("is_active",!0).single();return I||!N?(console.log(`[BobWidget TTS] No clip found for: ${E}`),or.set(E,null),null):(console.log(`[BobWidget TTS] Clip found: ${E} -> ${N.audio_url}`),or.set(E,N),N)}catch(N){return console.warn(`[BobWidget TTS] Clip lookup failed for ${E}:`,N),or.set(E,null),null}},[i]),R=a.useCallback(async E=>{for(const[N,I]of Object.entries(Oi))if(I.test(E)){console.log(`[BobWidget TTS] Pattern matched: ${N}`);const U=await k(N);if(U!=null&&U.audio_url)return U.audio_url}return null},[k]),P=a.useCallback(async()=>{var U,F,J;if(p.current||b.current.length===0)return;p.current=!0;const E=b.current.shift();if(!E){p.current=!1;return}const{text:N,isGreeting:I}=E;I&&(g.current=!0),x.current=!1,w(),u.current&&(u.current.pause(),u.current=null),y.current=setTimeout(()=>{var q,O;console.warn("[BobWidget TTS] Timeout - triggering fallback callbacks"),h(),d(!1),g.current=!1,(q=j.current)==null||q.call(j),(O=v.current)==null||O.call(v),u.current=null,p.current=!1,P()},Ii);try{let q=null;if(q=await R(N),q)console.log("[BobWidget TTS] Using pre-recorded audio (fast path)");else{console.log("[BobWidget TTS] No pre-recorded clip, using ElevenLabs TTS");const D=Pi(N),z=await fetch(`${n.supabaseUrl}/functions/v1/bob-tts-elevenlabs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.supabaseKey}`},body:JSON.stringify({text:D})});if(!z.ok){const V=await z.json().catch(()=>({}));throw console.error("[BobWidget TTS] Request failed:",V),new Error("TTS request failed")}const $=await z.blob();q=URL.createObjectURL($)}const O=new Audio(q);u.current=O,O.onplay=()=>{var D;w(),m.current=null,x.current||(x.current=!0,d(!0),console.log("[BobWidget TTS] Audio playing, triggering onStart (animation: TALKING)"),(D=f.current)==null||D.call(f))},O.onended=()=>{var D;w(),d(!1),g.current=!1,console.log("[BobWidget TTS] Audio ended, triggering onEnd (animation: COMPLETE/IDLE)"),(D=j.current)==null||D.call(j),u.current=null,p.current=!1,P()},O.onerror=D=>{var z,$;w(),console.warn("[BobWidget TTS] Audio playback error:",D),h(),d(!1),g.current=!1,(z=j.current)==null||z.call(j),($=v.current)==null||$.call(v),u.current=null,p.current=!1,P()};try{await O.play()}catch(D){console.warn("[BobWidget TTS] Audio play() failed (autoplay policy):",D),w(),I&&(m.current=N,console.log("[BobWidget TTS] Greeting stored for retry on user interaction")),h(),d(!1),g.current=!1,(U=j.current)==null||U.call(j),p.current=!1,P()}}catch(q){w(),console.error("[BobWidget TTS] Speech synthesis error:",q),h(),d(!1),g.current=!1,(F=j.current)==null||F.call(j),(J=v.current)==null||J.call(v),p.current=!1,P()}},[n.supabaseUrl,n.supabaseKey,w,h,R]),H=a.useCallback((E,N=!1)=>{if(E.trim()){if(N){if(S.current===E){console.log(`[BobWidget TTS] Ignoring duplicate greeting: "${E.substring(0,30)}..."`);return}S.current=E,m.current=null}if(g.current&&!N){console.log("[BobWidget TTS] Greeting playing - queueing message"),b.current.push({text:E,isGreeting:N});return}N?b.current.unshift({text:E,isGreeting:N}):b.current.push({text:E,isGreeting:N}),P()}},[P]),B=a.useCallback(()=>{if(m.current&&!u.current&&!p.current){console.log("[BobWidget TTS] Retrying pending greeting on user interaction");const E=m.current;m.current=null,H(E,!0)}},[H]),A=a.useCallback(()=>{w(),b.current=[],u.current&&(u.current.pause(),u.current=null),d(!1),g.current=!1,p.current=!1},[w]),_=a.useCallback(()=>{var E;(E=u.current)==null||E.pause()},[]),C=a.useCallback(()=>{var E;(E=u.current)==null||E.play()},[]);return a.useEffect(()=>()=>{w(),b.current=[],u.current&&(u.current.pause(),u.current=null)},[w]),{speak:H,stop:A,pause:_,resume:C,isSpeaking:c,isSupported:!0,retryPendingGreeting:B}},Is="bob_last_visit",Mi=30;function fn(t=Mi){const[e,s]=a.useState(!1),[n,i]=a.useState(null);return a.useEffect(()=>{try{const c=localStorage.getItem(Is),d=Date.now();if(c){const u=parseInt(c,10),y=(d-u)/(1e3*60*60*24);y<=t?(s(!0),i(new Date(u)),console.log(`[BobWidget] Returning user detected - last visit ${Math.round(y)} days ago`)):console.log(`[BobWidget] Previous visit was ${Math.round(y)} days ago - treating as new user`)}else console.log("[BobWidget] First time visitor detected");localStorage.setItem(Is,String(d))}catch(c){console.warn("[BobWidget] Could not access localStorage for returning user detection:",c)}},[t]),{isReturningUser:e,lastVisitDate:n,daysSinceLastVisit:n?Math.round((Date.now()-n.getTime())/(1e3*60*60*24)):null}}const os=t=>{if(!t)return t;let e=t;return e=e.replace(/\b(retrieve_parts|lookup_vehicle|search_general_products|retrieve_service_packages|add_to_cart|get_cart|create_checkout|get_customer_context|get_product_details|search_products|check_vehicle_fitment|search_web)\s*\([^)]*\)/gi,""),e=e.replace(/\(\s*(vehicleid|vehicle_id|part_type|query|plate|user_email|sku)\s*=\s*[^)]+\)/gi,""),e=e.replace(/\b(retrieve_parts|lookup_vehicle|search_general_products|retrieve_service_packages|add_to_cart|get_cart|create_checkout|get_customer_context|get_product_details|search_products|check_vehicle_fitment|search_web)\s*\(/gi,""),e=e.replace(/\b(vehicleid|vehicle_id|part_type)\s*=\s*(['"]?[\w\s]+['"]?)\s*,?\s*/gi,""),e=e.replace(/```[\s\S]*?```/g,""),e=e.replace(/\(\s*\)/g,""),e=e.replace(/\s{2,}/g," "),e=e.trim(),e},zr=t=>{let e=os(t);return e=e.replace(/[\[\]{}]/g,""),e=e.replace(/https?:\/\/[^\s]+/g,""),e=e.replace(/\bSKU\s*:?\s*\w+/gi,""),e},Ai=["what version","which version","software version","bob version","your version","current version","running version","version number","what ver","which ver"],Os=["recommend","suggest","need","part","filter","brake","rotor","oil","price","$","stock","available","pads","disc","spark plug","battery","clutch","alternator","starter","muffler","exhaust","service pack","add-on","tyre shine","windscreen wash"],Li=["WIPER BLADE FRONT","WIPER BLADE REAR","WIPER BLADE SET","BRAKE PAD KIT","BRAKE PAD KIT FRONT","BRAKE PAD KIT REAR","BRAKE ROTOR","BRAKE ROTOR FRONT","BRAKE ROTOR REAR","BRAKE DISC","AIR FILTER","OIL FILTER","CABIN FILTER","FUEL FILTER","SPARK PLUG SET","SPARK PLUG","BALL JOINT","TIE ROD END","CONTROL ARM","WHEEL BEARING","CV JOINT","DRIVE SHAFT","TIMING BELT KIT","SERPENTINE BELT","DRIVE BELT","SHOCK ABSORBER","STRUT","COIL SPRING","CLUTCH KIT","CLUTCH PLATE","ALTERNATOR","STARTER MOTOR","WATER PUMP","THERMOSTAT","RADIATOR","RADIATOR HOSE","EXHAUST","MUFFLER","CATALYTIC CONVERTER","brake pads","brake rotors","brake discs","brakes","air filter","oil filter","cabin filter","fuel filter","spark plugs","spark plug","wiper","wipers","battery","batteries","clutch","clutch kit","alternator","starter motor","muffler","exhaust","cv joint","axle","timing belt","serpentine belt","shock absorber","struts","suspension"],pn=({setAnimationState:t,manualMode:e=!1,talkingState:s="talk",thinkingState:n="research",completeState:i="complete",idleState:c="idle",listenState:d="talk_pause",onStreamStart:u,onStreamComplete:y,onShowingProduct:x,onResearchStart:b,onReadyToSpeak:p,onHighlightPart:g,onHighlightProduct:m,onNoPartsFound:S,onAutoFetchComplete:f})=>{var Sr,jr,Zt,er;const{bobConfig:j,hostApiConfig:v,hostContext:w,callbacks:h,ga4Config:k,analyticsEnabled:R}=tt(),P=dn({ga4Config:k,hostContext:w,callbacks:h,enabled:R}),{isReturningUser:H}=fn(),[B,A]=a.useState([]),[_,C]=a.useState(""),[E,N]=a.useState(!1),[I,U]=a.useState(!1),[F,J]=a.useState(null),q=a.useRef(null),O=a.useRef(!1),D=a.useRef(!1),z=a.useRef(""),$=a.useRef(!1),V=a.useRef(null),Q=a.useRef(null),ue=a.useRef([]),fe=a.useRef(!1),xe=a.useRef(null),oe=()=>{V.current&&(clearTimeout(V.current),V.current=null)},{speak:ye,stop:Z,isSpeaking:Be,retryPendingGreeting:Ie}=hn({onStart:()=>{oe(),$.current=!0,console.log("[BobWidget STATE] Speech STARTED - transitioning to TALK state"),P.trackSpeechPlayed(z.current.length),p==null||p(),e||(console.log("[BobWidget STATE] Setting state to:",s),re(s))},onEnd:()=>{oe(),console.log("[BobWidget STATE] Speech ENDED - transitioning out of TALK state");const G=Os.some(de=>z.current.toLowerCase().includes(de.toLowerCase()));e||(G&&x?(console.log("[BobWidget STATE] Has products - calling onShowingProduct"),x()):y?(console.log("[BobWidget STATE] Calling onStreamComplete"),y()):(console.log("[BobWidget STATE] Setting state to:",i),re(i),setTimeout(()=>{console.log("[BobWidget STATE] Post-complete transition to:",d),re(d)},2e3)))},onFailed:()=>{console.warn("[BobWidget] Speech synthesis failed - fallback triggered"),P.trackSpeechFailed(z.current.length)}});a.useEffect(()=>{var G;(G=q.current)==null||G.scrollIntoView({behavior:"smooth"})},[B]),a.useEffect(()=>{var de,be;const G=(de=w.vehicle)==null?void 0:de.selectedVehicle;G&&!F&&(console.log("[BobWidget] Setting vehicle from host context:",G),J(G),(be=h.onVehicleIdentified)==null||be.call(h,G),P.trackVehicleIdentified({make:G.make,model:G.model,year:G.year,rego:G.rego}))},[(Sr=w.vehicle)==null?void 0:Sr.selectedVehicle]),a.useEffect(()=>{var G;if(B.length===0&&!D.current){D.current=!0;const de=(G=w.vehicle)==null?void 0:G.selectedVehicle;let be;H?(be="Ah hey... you again! What you after this time?",console.log("[BobWidget] Using returning user greeting")):de?be=`G'day! Saw you've got the ${`${de.year} ${de.make} ${de.model}`} - choice wagon! What can I help you find for it today?`:be="G'day! Bob from CARFIX here. How can I help ya today?",A([{role:"assistant",content:be}]),I||setTimeout(()=>{console.log("[BobWidget] Speaking initial greeting (priority)"),ye(be,!0)},500)}},[(jr=w.vehicle)==null?void 0:jr.selectedVehicle,B.length,I,ye]),a.useEffect(()=>{const G=()=>{console.log("[BobWidget] User interaction detected - retrying pending greeting"),Ie(),document.removeEventListener("click",G),document.removeEventListener("touchstart",G)};return document.addEventListener("click",G,{once:!0}),document.addEventListener("touchstart",G,{once:!0}),()=>{document.removeEventListener("click",G),document.removeEventListener("touchstart",G)}},[Ie]),a.useEffect(()=>{var xt,yt;const G=(xt=w.vehicle)==null?void 0:xt.selectedVehicle;if(!G||O.current)return;const de=G.vehicle_id??G.id,be=Number.parseInt(String(de),10);if(!Number.isFinite(be)){console.warn("[BobWidget] Vehicle has invalid vehicle_id, cannot auto-fetch:",G);return}O.current=!0;const je={...G,vehicle_id:String(be)},st=(yt=w.user)==null?void 0:yt.email;(async()=>{var vt,wt;const Lt=`${j.supabaseUrl}/functions/v1/bob-chat`;try{const Ne=await fetch(Lt,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${j.supabaseKey}`},body:JSON.stringify({messages:[],vehicleContext:je,customerEmail:st,autoFetchParts:!0,hostConfig:v,hostContext:w})});if(!Ne.ok||!Ne.body){console.error("[BobWidget] Auto-fetch failed:",Ne.status);return}const kt=Ne.body.getReader(),De=new TextDecoder;let Oe="";for(;;){const{done:nt,value:St}=await kt.read();if(nt)break;Oe+=De.decode(St,{stream:!0});let it;for(;(it=Oe.indexOf(`
31
- `))!==-1;){let Fe=Oe.slice(0,it);if(Oe=Oe.slice(it+1),Fe.endsWith("\r")&&(Fe=Fe.slice(0,-1)),Fe.startsWith(":")||Fe.trim()===""||!Fe.startsWith("data: "))continue;const jt=Fe.slice(6).trim();if(jt==="[DONE]")break;try{const me=JSON.parse(jt);me.type==="service_packages_found"&&me.packages&&((vt=h.onServicePackagesFound)==null||vt.call(h,me.packages)),me.type==="parts_found"&&me.parts&&((wt=h.onPartsFound)==null||wt.call(h,me.parts),P.trackPartsViewed(Array.isArray(me.parts)?me.parts.length:0,String(be)))}catch{}}}f==null||f()}catch(Ne){console.error("[BobWidget] Auto-fetch error:",Ne)}})()},[(Zt=w.vehicle)==null?void 0:Zt.selectedVehicle,(er=w.user)==null?void 0:er.email]);const re=G=>{try{t(G)}catch{console.warn(`[BobWidget] State "${G}" not available`)}},Ce=()=>{if(ue.current.length===0){fe.current=!1,e||re(n);return}fe.current=!0;const G=ue.current.shift(),de=new Audio(G);xe.current=de,de.onplay=()=>{console.log("[BobWidget] Searching audio STARTED:",G),e||re(s)},de.onended=()=>{console.log("[BobWidget] Searching audio ENDED, playing next..."),xe.current=null,Ce()},de.onerror=()=>{console.warn("[BobWidget] Searching audio failed:",G),xe.current=null,Ce()},de.play().catch(()=>{console.warn("[BobWidget] Searching audio autoplay blocked:",G),xe.current=null,Ce()})},ge=async G=>{var je,st,tr,xt,yt,Lt,vt,wt,Ne,kt,De,Oe,nt,St,it,Fe,jt;const de=`${j.supabaseUrl}/functions/v1/bob-chat`,be=(je=w.user)==null?void 0:je.email;try{const me={messages:[...B,G],hostConfig:v,hostContext:w};F&&(me.vehicleContext=F),be&&(me.customerEmail=be);const Pe=await fetch(de,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${j.supabaseKey}`},body:JSON.stringify(me)});if(!Pe.ok){if(Pe.status===429){(st=h.onError)==null||st.call(h,new Error("Rate limit exceeded"));return}if(Pe.status===402){(tr=h.onError)==null||tr.call(h,new Error("Payment required"));return}throw new Error("Failed to start stream")}if(!Pe.body)throw new Error("No response body");const Mr=Pe.body.getReader(),Ar=new TextDecoder;let qe="",rr=!1,at="";for(;!rr;){const{done:T,value:M}=await Mr.read();if(T)break;qe+=Ar.decode(M,{stream:!0});let X;for(;(X=qe.indexOf(`
32
- `))!==-1;){let ee=qe.slice(0,X);if(qe=qe.slice(X+1),ee.endsWith("\r")&&(ee=ee.slice(0,-1)),ee.startsWith(":")||ee.trim()===""||!ee.startsWith("data: "))continue;const le=ee.slice(6).trim();if(le==="[DONE]"){rr=!0;break}try{const L=JSON.parse(le);if(L.type==="vehicle_identified"&&L.vehicle){J(L.vehicle),(xt=h.onVehicleIdentified)==null||xt.call(h,L.vehicle),P.trackVehicleIdentified({make:L.vehicle.make,model:L.vehicle.model,year:L.vehicle.year,rego:L.vehicle.rego});continue}if(L.type==="service_packages_found"&&L.packages){(yt=h.onServicePackagesFound)==null||yt.call(h,L.packages);continue}if(L.type==="parts_found"&&L.parts){(Lt=h.onPartsFound)==null||Lt.call(h,L.parts),P.trackPartsViewed(Array.isArray(L.parts)?L.parts.length:0,(vt=F==null?void 0:F.vehicle_id)==null?void 0:vt.toString());continue}if(L.type==="bob_suggestions"&&L.products){console.log("[useBobChat] Received bob_suggestions:",L.products.length,"products",L.title),A(he=>{var ve;const ae=[...he],ie=ae[ae.length-1];return console.log("[useBobChat] Attaching to message:",ie==null?void 0:ie.role,(ve=ie==null?void 0:ie.content)==null?void 0:ve.slice(0,40)),(ie==null?void 0:ie.role)==="assistant"?ae.map((We,Ye)=>Ye===ae.length-1?{...We,suggestedProducts:L.products,suggestionsTitle:L.title}:We):ae}),(wt=h.onPartsFound)==null||wt.call(h,L.products),P.trackPartsViewed(Array.isArray(L.products)?L.products.length:0,(Ne=F==null?void 0:F.vehicle_id)==null?void 0:Ne.toString());continue}if(L.type==="no_parts_found"){(kt=h.onPartsFound)==null||kt.call(h,[]),(De=h.onServicePackagesFound)==null||De.call(h,[]),S==null||S();continue}if(L.type==="audio_hint"&&L.audio_url){console.log("[useBobChat] Audio hint received:",L.clip_key,L.audio_url),Q.current=L.audio_url;continue}if(L.type==="bob_searching"&&L.audio_url){console.log("[useBobChat] Bob searching:",L.search_type,L.clip_key),ue.current.push(L.audio_url),!fe.current&&!I&&Ce();continue}if(L.type==="cart_updated"&&L.items){(Oe=h.onCartUpdated)==null||Oe.call(h,L.items);continue}const te=(it=(St=(nt=L.choices)==null?void 0:nt[0])==null?void 0:St.delta)==null?void 0:it.content;if(te){at+=te;let he=at.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");he=os(he),A(ae=>{const ie=ae[ae.length-1];return(ie==null?void 0:ie.role)==="assistant"?ae.map((ve,We)=>We===ae.length-1?{...ve,content:he}:ve):[...ae,{role:"assistant",content:he}]}),(Fe=h.onBobMessage)==null||Fe.call(h,he)}}catch{qe=ee+`
33
- `+qe;break}}}let sr=at.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");sr=os(sr),z.current=sr;const nr=Os.some(T=>at.toLowerCase().includes(T.toLowerCase())),Lr=at.toLowerCase();for(const T of Li)if(Lr.includes(T.toLowerCase())){const M=T.replace(/s\s*$/i,"").toUpperCase();g==null||g(M);break}const o=at.match(/(?:go with|recommend|suggest|grab|try)\s+(?:the\s+)?(\w+)\s+(?:at|for)\s+\$(\d+(?:\.\d{2})?)/i);if(o){const[,T,M]=o;m==null||m({brand:T,price:parseFloat(M)})}if(!I&&z.current.trim()){if($.current=!1,oe(),Q.current){console.log("[BobWidget] Playing canned audio:",Q.current);const T=new Audio(Q.current);T.onplay=()=>{console.log("[BobWidget] Canned audio STARTED"),$.current=!0,p==null||p(),e||re(s)},T.onended=()=>{console.log("[BobWidget] Canned audio ENDED"),oe(),e||(nr&&x?x():y?y():(re(i),setTimeout(()=>re(d),3e3)))},T.onerror=()=>{console.error("[BobWidget] Canned audio failed, falling back to TTS");const M=zr(z.current);ye(M)},T.play().catch(()=>{console.error("[BobWidget] Canned audio autoplay blocked, falling back to TTS");const M=zr(z.current);ye(M)}),Q.current=null}else{const T=zr(z.current);ye(T)}V.current=setTimeout(()=>{$.current||(console.warn("[BobWidget] Speech fallback after 2s"),p==null||p(),e||(nr&&x?x():y?y():(re(i),setTimeout(()=>re(d),3e3))))},2e3)}else p==null||p(),e||(nr&&x?x():y?y():(re(i),setTimeout(()=>re(d),3e3)))}catch(me){console.error("[BobWidget] Chat error:",me);const Pe=me instanceof Error?me:new Error("Unknown error");(jt=h.onError)==null||jt.call(h,Pe),P.trackError(Pe.name||"ChatError",Pe.message||"Unknown chat error"),e||re(c)}},He=async()=>{if(!_.trim()||E)return;Ie(),Z();const G={role:"user",content:_};A(je=>[...je,G]),C(""),P.trackMessageSent(_.length,!!F);const de=_.toLowerCase();if(Ai.some(je=>de.includes(je))){const je=`G'day mate! I'm running Bob v${et} - she's running sweet as! Anything else I can help ya with?`;A(st=>[...st,{role:"assistant",content:je}]),I||ye(je);return}N(!0),console.log("[BobWidget STATE] User sent message - switching to RESEARCH state:",n),b==null||b(),e||re(n),await ge(G),N(!1)};return{messages:B,input:_,setInput:C,isLoading:E,handleSend:He,handleKeyPress:G=>{G.key==="Enter"&&!G.shiftKey&&(G.preventDefault(),He())},handleInputFocus:()=>{Ie()},handleInputBlur:()=>{},chatEndRef:q,clearMessages:()=>{A([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])},isMuted:I,toggleMute:()=>{U(G=>!G),I||Z()},isSpeaking:Be,identifiedVehicle:F,clearVehicle:()=>{J(null)}}},Di={states:[],configs:[],uploadedImages:[],looks:[],activeLookId:null},gn=t=>{const e=cn(),s=At();return a.useEffect(()=>{if(!s)return;const n=s.channel("animation-states-changes").on("postgres_changes",{event:"*",schema:"public",table:"animation_states"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe(),i=s.channel("bob-animations-changes").on("postgres_changes",{event:"*",schema:"public",table:"bob_animations"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe();return()=>{s.removeChannel(n),s.removeChannel(i)}},[e,s]),wr({queryKey:["bob-animation-data",t],queryFn:async()=>{var h;if(!s)return console.log("[BobAnimation] No supabase client, returning empty data"),Di;const{data:n,error:i}=await s.from("bob_looks").select("*").order("display_order");if(i)throw i;const c=(n||[]).find(k=>k.is_active),d=t||(c==null?void 0:c.id)||n&&((h=n[0])==null?void 0:h.id)||null;if(!d)return console.warn("[BobAnimation] No looks configured in database"),{states:[],configs:[],uploadedImages:[],looks:n||[],activeLookId:null};console.log(`[BobAnimation] Loading animations for look: ${(c==null?void 0:c.name)||d}`);const{data:u,error:y}=await s.from("animation_states").select("*").eq("is_active",!0).eq("look_id",d).order("display_order");if(y)throw y;const{data:x,error:b}=await s.from("bob_animations").select("*").eq("is_active",!0).eq("look_id",d).order("animation_state").order("sequence_order");if(b)throw b;const p=(u||[]).map(k=>k.state_key);console.log(`[BobAnimation] Loaded ${p.length} states: ${p.join(", ")}`);const m=["idle","talking","listening"].filter(k=>{const R=[k,k.replace("ing",""),k+"ing"];return!p.some(P=>R.includes(P))});m.length>0&&console.warn(`[BobAnimation] ⚠️ Missing critical states: ${m.join(", ")}`);const S=new Set(p),f=(x||[]).filter(k=>S.has(k.animation_state));console.log(`[BobAnimation] Loaded ${f.length} animation frames`);const{data:j,error:v}=await s.storage.from("bob-images").list();if(v)throw v;const w=(j||[]).map(k=>{const{data:R}=s.storage.from("bob-images").getPublicUrl(k.name);return R.publicUrl});return f.forEach(k=>{const R=new Image;R.src=k.image_url}),{states:u||[],configs:f,uploadedImages:w,looks:n||[],activeLookId:d}},staleTime:30*1e3,gcTime:5*60*1e3})},bn=(t={})=>{const{isSpeaking:e=!1}=t,[s,n]=a.useState(""),[i,c]=a.useState(0),[d,u]=a.useState(400),[y,x]=a.useState(!1),b=a.useRef(null),p=a.useRef(0),g=a.useRef(e),m=a.useRef(0),S=a.useRef(0),f=a.useRef(!1),j=a.useRef(0),{data:v,isLoading:w}=gn(),h=a.useRef({}),{imageUrlsMap:k,alternateImages:R,offsetsMap:P,scalesMap:H,availableStates:B}=a.useMemo(()=>{if(!v)return{imageUrlsMap:{},alternateImages:{},offsetsMap:{},scalesMap:{},availableStates:[]};const N={},I={},U={},F={},J=v.states.map(q=>q.state_key);return J.forEach(q=>{const O=v.configs.filter(V=>V.animation_state===q),D=O.map(V=>V.image_url),z=O.map(V=>V.vertical_offset||0),$=O.map(V=>V.scale||100);if(D.length>0){const V=v.states.find(Q=>Q.state_key===q);N[q]={url:D[0],animation_speed:(V==null?void 0:V.animation_speed)||400,pause_duration:(V==null?void 0:V.pause_duration)||0,loop_count:(V==null?void 0:V.loop_count)||0},I[q]=D,U[q]=z,F[q]=$}}),{imageUrlsMap:N,alternateImages:I,offsetsMap:U,scalesMap:F,availableStates:J}},[v]);a.useEffect(()=>{h.current=k},[k]),a.useEffect(()=>{const N=g.current;if(g.current=e,N&&!e){const I=s.toLowerCase();(I.includes("talk")||I==="talking")&&(console.log("[useBobAnimation] Speech ended while in talk state - forcing loop completion"),S.current=999)}},[e,s]);const A=a.useCallback(N=>{n(I=>I===N?I:(m.current=0,S.current=0,f.current=!1,c(0),N))},[]);a.useEffect(()=>{B.length>0&&!s&&n(B[0])},[B,s]),a.useEffect(()=>{const N=R[s];if(b.current!==null&&(cancelAnimationFrame(b.current),b.current=null),m.current=0,S.current=0,f.current=!1,p.current=0,c(0),!N||N.length<=1)return;const I=h.current[s],U=(I==null?void 0:I.animation_speed)||d||400,F=(I==null?void 0:I.loop_count)||0,J=(I==null?void 0:I.pause_duration)||0,q=s.toLowerCase().includes("talk"),O=D=>{if(p.current===0&&(p.current=D),f.current){D-j.current>=J&&(f.current=!1,S.current=0,p.current=D),b.current=requestAnimationFrame(O);return}if(D-p.current>=U){p.current=D;const $=(m.current+1)%N.length;$===0?(S.current++,q&&g.current?(m.current=$,c($)):F>0&&S.current>=F?J>0&&(f.current=!0,j.current=D):(m.current=$,c($))):(m.current=$,c($))}b.current=requestAnimationFrame(O)};return b.current=requestAnimationFrame(O),()=>{b.current!==null&&(cancelAnimationFrame(b.current),b.current=null)}},[s,R,d]);const _=a.useCallback(()=>{const N=R[s];if(!N||N.length===0){const I=B.find(U=>{var F;return((F=R[U])==null?void 0:F.length)>0});return I?(console.warn(`[useBobAnimation] No images for "${s}", using fallback: ${I}`),R[I][0]):(console.error("[useBobAnimation] No valid images found for any state!"),"")}return N[i]||N[0]},[R,s,B,i]),C=a.useCallback(()=>{const N=P[s];if(!N||N.length===0){const I=B.find(U=>{var F;return((F=P[U])==null?void 0:F.length)>0});return I?P[I][0]:0}return N[i]||N[0]},[P,s,B,i]),E=a.useCallback(()=>{const N=H[s];if(!N||N.length===0){const I=B.find(U=>{var F;return((F=H[U])==null?void 0:F.length)>0});return I?H[I][0]:100}return N[i]||N[0]},[H,s,B,i]);return{animationState:s,setAnimationState:A,getCurrentImage:_,getCurrentOffset:C,getCurrentScale:E,imageUrls:k,availableStates:B,setTalkSpeed:u,manualMode:y,setManualMode:x,isLoading:w}},mn=()=>{const t=At(),{data:e=[],isLoading:s}=wr({queryKey:["bob-backdrops"],queryFn:async()=>{if(!t)return console.log("[useBobBackdrop] No supabase client, returning empty"),[];const{data:i,error:c}=await t.from("bob_backdrops").select("*").order("display_order",{ascending:!0});if(c)throw c;return i},staleTime:5*60*1e3,gcTime:10*60*1e3}),n=e.find(i=>i.is_active);return{backdrops:e,activeBackdrop:n,isLoading:s}},xn=({currentImage:t,animationState:e,backdropUrl:s,counterOverlayUrl:n,counterHeightPercent:i=12,className:c="",verticalOffset:d=0,scale:u=100})=>{const y=d+i,x=55*(u/100);return r.jsx("div",{className:`flex flex-col items-center justify-center gap-6 w-full ${c}`,children:r.jsxs("div",{className:"relative w-full max-w-[600px] mx-auto aspect-[16/10] overflow-hidden",children:[s&&r.jsx("img",{src:s,alt:"Backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-bottom"}),r.jsx("img",{src:t,alt:`Bob ${e}`,className:"absolute z-10 h-auto object-contain left-1/2 -translate-x-1/2",style:{bottom:`${y}%`,width:`${x}%`,maxWidth:`${220*(u/100)}px`,transformOrigin:"center bottom"}}),n&&r.jsx("img",{src:n,alt:"Counter",className:"absolute z-20 bottom-0 left-0 w-full object-cover object-bottom",style:{height:`${i}%`}})]})})},K={primary:"#0052CC",primaryHover:"#0047B3",secondary:"#38BDF8",foreground:"#0F172A",accent:"#FF8C00",success:"#22C55E",destructive:"#EF4444",performanceRed:"#DC2626",mutedForeground:"#64748B",background:"#FAFAFA",card:"#FFFFFF",border:"#E2E8F0",slateEconomy:"#475569"},Nr={Economy:{icon:"DollarSign",emoji:"💰",textColor:"#475569",background:"#F1F5F9",border:"#CBD5E1",description:"Smart savings"},Standard:{icon:"Star",emoji:"⭐",textColor:"#0052CC",background:"rgba(0,82,204,0.1)",border:"rgba(0,82,204,0.3)",description:"Best value",isRecommended:!0},Premium:{icon:"Award",emoji:"🏆",textColor:"#D97706",background:"#FEF3C7",border:"#FCD34D",description:"Superior quality"},Performance:{icon:"Zap",emoji:"⚡",textColor:"#DC2626",background:"#FEE2E2",border:"#FCA5A5",description:"Maximum power"}},$r={"Oil Change":"Neglecting oil changes leads to engine wear, overheating, and catastrophic failure costing thousands. Quality oil and filters keep your engine running smoothly. Each CFX Oil Change Service Pack includes premium oil and filter matched to your engine specifications.","Front Brake Service":"Your front brakes handle 70% of stopping power. Worn pads dangerously increase stopping distance. Quality brake components ensure confident, safe stops. Each CFX Front Brake Service Pack includes pads and rotors to restore your braking performance.","Rear Brake Service":"Rear brakes provide stability and balance during emergency stops. Worn components cause instability and longer stopping distances. Each CFX Rear Brake Service Pack includes quality pads/shoes and rotors/drums for complete rear brake renewal.","Timing Belt Service":"A snapped timing belt destroys engines instantly, causing $8,000+ in damage. Preventive replacement is essential for peace of mind. Each CFX Timing Belt Service Pack includes the belt, tensioner, and related components.",Wipers:"Worn wipers reduce visibility in rain, compromising safety. Quality blades provide streak-free, clear vision. Each CFX Wipers Service Pack includes the gear you need to change all of your vehicle's wiper blades to restore your driving vision.","Coolant Service":"Old coolant causes overheating, warped cylinder heads, and engine seizure. Fresh coolant protects your entire cooling system. Each CFX Coolant Service Pack includes quality coolant matched to your vehicle's requirements.","Air Filter Service":"Clogged air filters reduce engine performance by 10% and increase fuel consumption. Clean filters improve power and economy. Each CFX Air Filter Service Pack includes a precision-fit filter for optimal airflow.","Spark Plug Service":"Worn spark plugs cause misfires, poor fuel economy, and catalytic converter damage. Fresh plugs restore smooth, efficient running. Each CFX Spark Plug Service Pack includes quality plugs matched to your engine.","Battery Service":"A failing battery leaves you stranded without warning. Reliable power is essential for starting and electronics. Each CFX Battery Service Pack includes a quality battery sized for your vehicle's demands.","Cabin Filter":"Cabin filters clean the air you and your passengers breathe. Replace regularly to remove pollen, dust, and odours. Each CFX Cabin Filter Service Pack includes a quality filter for fresh, clean cabin air.","Fuel Filter Service":"Clogged fuel filters restrict flow, causing poor performance and potential engine damage. Clean fuel is critical for efficiency. Each CFX Fuel Filter Service Pack includes a quality filter for optimal fuel delivery.","Transmission Service":"Old transmission fluid causes rough shifting, slipping, and premature wear. Fresh fluid extends transmission life. Each CFX Transmission Service Pack includes quality fluid matched to your transmission type."},Wi="Keep your vehicle running safely and efficiently with quality parts matched to your specific make and model. Each CFX Service Pack includes everything you need for this essential maintenance.",pr={productImage:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${t}.jpg`,brandLogo:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${t.replace(/\s+/g,"")}.jpg`,carfixImage:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/carfix_images/${t}_1.jpg`},yn={fitsVehicle:{background:"rgba(34,197,94,0.1)",text:"#22C55E",border:"rgba(34,197,94,0.2)",icon:"Check",label:"Fits Your Vehicle"},viscosity:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",icon:"Gauge"},volume:{background:"#ECFEFF",text:"#0E7490",border:"#A5F3FC",icon:"Droplets"},quantity:{background:"#F1F5F9",text:"#475569",border:"#CBD5E1"},partNumber:{background:"transparent",text:"#64748B",border:"transparent"},carfixValue:{background:"rgba(0,82,204,0.1)",text:"#0052CC",border:"rgba(0,82,204,0.2)",icon:"Sparkles",label:"CARFIX Value"},rotorPair:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",label:"Pair"}},ze={packageTitle:{fontSize:"20px",fontWeight:700},partslotName:{fontSize:"14px",fontWeight:600},productName:{fontSize:"14px",fontWeight:500},description:{fontSize:"14px",fontWeight:400},priceMain:{fontSize:"20px",fontWeight:700},priceSecondary:{fontSize:"12px",fontWeight:400},tierLabel:{fontSize:"14px",fontWeight:500},badgeText:{fontSize:"12px",fontWeight:500}};function vn(t){var n;const e=((n=t.name)==null?void 0:n.toLowerCase())||"",s=(t.partslotDescription||t.partslot_description||"").toLowerCase();return e.includes("rotor")||s.includes("disc rotor")||s.includes("brake rotor")||t.per_car_qty===2}function wn(t,e){return e?{displayPrice:t*2,unitPriceLabel:`$${t.toFixed(2)} each`}:{displayPrice:t}}function bt(t){return`$${t.toFixed(2)}`}function kn(t){if($r[t])return $r[t];const e=t.toLowerCase();for(const[s,n]of Object.entries($r))if(e.includes(s.toLowerCase())||s.toLowerCase().includes(e))return n;return Wi}const ur=({type:t,value:e,className:s=""})=>{const n=yn[t],i=e||("label"in n?n.label:""),c=()=>{if(!("icon"in n))return null;const d={width:12,height:12};switch(n.icon){case"Check":return r.jsx("svg",{style:d,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",children:r.jsx("polyline",{points:"20 6 9 17 4 12"})});case"Sparkles":return r.jsxs("svg",{style:d,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[r.jsx("path",{d:"M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3z"}),r.jsx("path",{d:"M5 19l1 3 1-3 3-1-3-1-1-3-1 3-3 1 3 1z"})]});case"Gauge":return r.jsxs("svg",{style:d,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("path",{d:"M12 6v6l4 2"})]});case"Droplets":return r.jsx("svg",{style:d,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:r.jsx("path",{d:"M12 2.69l5.66 5.66a8 8 0 11-11.31 0z"})});default:return null}};return r.jsxs("span",{className:s,style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",fontSize:"12px",fontWeight:500,background:n.background,color:n.text,border:`1px solid ${n.border}`,whiteSpace:"nowrap"},children:[c(),i]})},fs=({products:t,title:e,onProductClick:s,onAddToCart:n})=>!t||t.length===0?null:r.jsxs("div",{style:{marginTop:"16px",width:"100%"},children:[e&&r.jsxs("div",{style:{marginBottom:"12px",fontSize:ze.partslotName.fontSize,fontWeight:ze.partslotName.fontWeight,color:K.foreground,display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("span",{style:{fontSize:"18px"},children:"🚗"}),e]}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:t.slice(0,6).map((i,c)=>r.jsx(zi,{product:i,onProductClick:s,onAddToCart:n,isRecommended:c===0},i.id||i.sku||c))}),t.length>6&&r.jsxs("div",{style:{marginTop:"12px",fontSize:"13px",color:K.mutedForeground,textAlign:"center"},children:["+ ",t.length-6," more options available"]})]}),zi=({product:t,onProductClick:e,onAddToCart:s,isRecommended:n=!1})=>{const[i,c]=a.useState(!1),[d,u]=a.useState(!1),y=t.image_url||t.image||(t.sku?pr.productImage(t.sku):null),x=t.brand?pr.brandLogo(t.brand):null,b=t.brand||"Quality Part",p=t.name||"Product",g=t.price??0,m=t.partNumber||t.part_number,S=vn({name:t.name,partslotDescription:t.partslotDescription,per_car_qty:t.quantity}),{displayPrice:f,unitPriceLabel:j}=wn(g,S);return r.jsxs("div",{style:{background:K.card,borderRadius:"12px",border:`2px solid ${K.border}`,overflow:"hidden",cursor:e?"pointer":"default",transition:"all 0.2s ease"},onClick:()=>e==null?void 0:e(t),onMouseEnter:v=>{v.currentTarget.style.borderColor=`${K.primary}80`,v.currentTarget.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)"},onMouseLeave:v=>{v.currentTarget.style.borderColor=K.border,v.currentTarget.style.boxShadow="none"},children:[t.partslotDescription&&r.jsxs("div",{style:{background:"rgba(0,0,0,0.03)",borderBottom:`1px solid ${K.border}`,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[r.jsx("span",{style:{fontSize:ze.partslotName.fontSize,fontWeight:ze.partslotName.fontWeight,color:K.foreground},children:t.partslotDescription}),n&&r.jsx(ur,{type:"carfixValue"})]}),r.jsxs("div",{style:{padding:"16px",display:"flex",gap:"16px"},children:[r.jsx("div",{style:{width:"96px",minWidth:"96px",height:"96px",borderRadius:"8px",background:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",border:`1px solid ${K.border}`},children:y&&!i?r.jsx("img",{src:y,alt:p,style:{width:"100%",height:"100%",objectFit:"contain",padding:"4px"},onError:()=>c(!0)}):r.jsx("span",{style:{fontSize:"32px",opacity:.5},children:"🔧"})}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:[x&&!d&&r.jsx("img",{src:x,alt:b,style:{height:"16px",width:"auto",objectFit:"contain"},onError:()=>u(!0)}),r.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:K.foreground,textTransform:"uppercase"},children:b})]}),r.jsx("div",{style:{fontSize:ze.productName.fontSize,fontWeight:ze.productName.fontWeight,color:K.foreground,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",lineHeight:"1.4",marginBottom:"8px"},children:p}),r.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"12px"},children:[r.jsx(ur,{type:"fitsVehicle"}),S&&r.jsx(ur,{type:"rotorPair"}),t.quantity&&t.quantity>1&&!S&&r.jsx(ur,{type:"quantity",value:`Qty: ${t.quantity}`}),m&&r.jsxs("span",{style:{fontSize:"12px",color:K.mutedForeground},children:["#",m]})]})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",justifyContent:"space-between",minWidth:"100px"},children:[r.jsxs("div",{style:{textAlign:"right"},children:[r.jsx("div",{style:{fontSize:ze.priceMain.fontSize,fontWeight:ze.priceMain.fontWeight,color:K.foreground},children:bt(f)}),j&&r.jsx("div",{style:{fontSize:ze.priceSecondary.fontSize,color:K.mutedForeground},children:j}),r.jsx("div",{style:{fontSize:ze.priceSecondary.fontSize,color:K.mutedForeground},children:"inc GST"})]}),s&&r.jsx("button",{onClick:v=>{v.stopPropagation(),s(t)},style:{background:K.primary,color:"#FFFFFF",border:"none",borderRadius:"8px",padding:"8px 16px",fontSize:"13px",fontWeight:600,cursor:"pointer",transition:"all 0.2s ease",whiteSpace:"nowrap"},onMouseEnter:v=>{v.currentTarget.style.background=K.primaryHover},onMouseLeave:v=>{v.currentTarget.style.background=K.primary},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.98)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:"Add to Cart"})]})]})]})},Sn=({messages:t,input:e,setInput:s,isLoading:n,onSend:i,onKeyPress:c,onInputFocus:d,onInputBlur:u,chatEndRef:y,isMuted:x=!1,onToggleMute:b,isSpeaking:p=!1,className:g="",onAddToCart:m,onProductClick:S})=>r.jsx("div",{className:g,style:{width:"100%",maxWidth:"72rem",margin:"0 auto",padding:"0 16px 32px 16px"},children:r.jsxs("div",{style:{backgroundColor:"rgba(20, 30, 50, 0.85)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"16px",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.3)",overflow:"hidden"},children:[r.jsx("div",{style:{padding:"16px",borderBottom:"1px solid rgba(255,255,255,0.1)",backgroundColor:"rgba(0,0,0,0.2)"},children:r.jsxs("div",{style:{display:"flex",gap:"8px"},children:[r.jsx("input",{value:e,onChange:f=>s(f.target.value),onKeyPress:c,onFocus:d,onBlur:u,placeholder:"Ask Bob about car parts...",disabled:n,style:{flex:1,padding:"12px 16px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",color:"white",fontSize:"16px",outline:"none"}}),b&&r.jsx("button",{onClick:b,style:{flexShrink:0,padding:"12px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",cursor:"pointer",minHeight:"unset",minWidth:"unset"},title:x?"Unmute Bob's voice":"Mute Bob's voice",children:x?"🔇":"🔊"}),r.jsx("button",{onClick:i,disabled:n||!e.trim(),style:{flexShrink:0,padding:"12px 20px",background:n||!e.trim()?"rgba(0, 102, 204, 0.3)":"linear-gradient(135deg, rgba(0, 102, 204, 0.95), rgba(0, 73, 153, 1))",color:"white",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.2)",cursor:n||!e.trim()?"not-allowed":"pointer",opacity:n||!e.trim()?.5:1,minHeight:"unset",minWidth:"unset",fontWeight:600},children:"Send"})]})}),r.jsxs("div",{style:{overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"12px",height:"400px",background:"rgba(0,0,0,0.1)"},children:[[...t].reverse().map((f,j)=>{var v;return r.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:f.role==="user"?"flex-end":"flex-start"},children:r.jsxs("div",{style:{maxWidth:(v=f.suggestedProducts)!=null&&v.length?"100%":"80%",borderRadius:"16px",padding:"12px 16px",fontSize:"14px",backgroundColor:f.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.1)",background:f.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.08)",color:"white",border:"1px solid rgba(255,255,255,0.15)",boxShadow:"0 2px 8px rgba(0,0,0,0.2)"},children:[f.content,f.role==="assistant"&&f.suggestedProducts&&f.suggestedProducts.length>0&&r.jsx(fs,{products:f.suggestedProducts,title:f.suggestionsTitle,onAddToCart:m,onProductClick:S})]})},j)}),r.jsx("div",{ref:y})]})]})}),$i=768,Ui=1024;function Br(){const[t,e]=a.useState("mobile");return a.useEffect(()=>{const s=()=>{const n=window.innerWidth;n>=Ui?e("desktop"):n>=$i?e("tablet"):e("mobile")};return s(),window.addEventListener("resize",s),()=>window.removeEventListener("resize",s)},[]),t}function ps(){const t=Br();return Hi(t)}function Hi(t){switch(t){case"mobile":return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-55,hiddenPosition:-100};case"tablet":return{bobOffset:.7,productWidth:.85,uiScale:1.1,partialLeftPosition:-25,hiddenPosition:-80};case"desktop":return{bobOffset:.5,productWidth:.6,uiScale:1.2,partialLeftPosition:-5,hiddenPosition:-60};default:return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-20,hiddenPosition:-100}}}const Ir=({currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n=15,scale:i=100,position:c="center",verticalOffset:d=0,hasArrived:u=!0})=>{const y=ps(),b=95*i/100,p=550*i/100,g=()=>{switch(c){case"center":return"50%";case"partial-left":return`${y.partialLeftPosition}%`;case"hidden":return`${y.hiddenPosition}%`;default:return"50%"}},m=()=>c==="center"?"translateX(-50%)":"translateX(0)",S=n-2+d,f=()=>c==="hidden"?"all 0.35s cubic-bezier(0.4, 0, 0.2, 1)":"all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)";return r.jsxs("div",{className:"absolute inset-0 pointer-events-none",style:{overflow:"visible"},children:[r.jsx("div",{className:"absolute z-[60]",style:{bottom:`${S}%`,left:g(),maxHeight:`${100-n-2}%`,transform:m(),width:`${b}%`,maxWidth:`${p}px`,transition:f()+", opacity 0.6s ease-out",willChange:"transform, left, opacity",opacity:u?1:0},children:r.jsx("img",{src:t,alt:`Bob ${e}`,className:"w-full h-auto object-contain",style:{display:"block",maxHeight:"100%"}})}),s&&r.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-[70]",style:{height:`${n}%`,pointerEvents:"none"},children:r.jsx("img",{src:s,alt:"Shop counter",className:"w-full h-full object-cover object-top"})})]})},Tr={background:"rgba(20, 30, 50, 0.92)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"28px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.35), inset 0 0 0 1px rgba(255,255,255,0.1)"},jn={background:"linear-gradient(135deg, rgba(40, 60, 100, 0.95) 0%, rgba(20, 40, 80, 0.98) 100%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(0, 0, 0, 0.35), 0 0 0 1px rgba(255,255,255,0.15), inset 0 1px 0 rgba(255,255,255,0.2)"},Ps={background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(12px) saturate(180%)",WebkitBackdropFilter:"blur(12px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.35)",borderRadius:"24px",boxShadow:"0 10px 40px rgba(255, 149, 0, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},_n={background:"linear-gradient(135deg, rgba(0, 102, 204, 0.95) 0%, rgba(0, 73, 153, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"32px",boxShadow:"0 10px 40px rgba(0, 102, 204, 0.4), inset 0 1px 0 rgba(255,255,255,0.25)"},En={background:"rgba(255, 255, 255, 0.08)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"28px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.3)"},dr={primary:{color:"rgba(255, 255, 255, 1)",textShadow:"0 1px 3px rgba(0,0,0,0.5)"}},qi={background:"rgba(255, 255, 255, 0.12)",borderRadius:"20px",border:"1px solid rgba(255, 255, 255, 0.15)"},Qi={background:"rgba(255, 255, 255, 0.15)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"12px"},Ki={width:"4px",height:"4px",borderRadius:"50%",background:"rgba(255, 255, 255, 0.6)",boxShadow:"0 0 8px rgba(255, 255, 255, 0.4)"},Tn=({product:t,isSpotlighted:e=!1,onProductClick:s,onAddToCart:n})=>{const[i,c]=a.useState(!1),d=()=>{s==null||s(t)},u=x=>{x.stopPropagation(),n==null||n(t)},y=e?jn:Tr;return r.jsxs("div",{onClick:d,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),className:"relative w-full cursor-pointer glass-card",style:{...y,padding:"16px",transform:i?"scale(1.04) translateY(-4px)":"scale(1) translateY(0)",boxShadow:i?"0 16px 56px rgba(0, 0, 0, 0.4), 0 0 24px rgba(255,255,255,0.08)":y.boxShadow,transition:"transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.3s ease-out"},children:[e&&r.jsxs("div",{className:"absolute -top-2.5 -right-2.5 z-10 flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.95) 0%, rgba(0, 73, 153, 1) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"20px",boxShadow:"0 8px 24px rgba(0, 102, 204, 0.5)",color:"white"},children:[r.jsx("svg",{className:"w-3.5 h-3.5",fill:"currentColor",viewBox:"0 0 20 20",children:r.jsx("path",{d:"M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"})}),"Bob's Pick"]}),r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("div",{className:"flex-shrink-0 flex items-center justify-center overflow-hidden",style:{...qi,width:"92px",height:"92px"},children:t.image_url?r.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-2",loading:"lazy"}):r.jsx("div",{className:"flex flex-col items-center justify-center",style:{color:"rgba(255,255,255,0.4)"},children:r.jsx("svg",{className:"w-8 h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"font-bold line-clamp-2 leading-tight",style:{fontSize:"16px",letterSpacing:"-0.01em",...dr.primary},children:t.name}),t.brand&&r.jsx("div",{className:"flex items-center gap-1.5 mt-1.5",children:r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5",style:{...Qi,color:"rgba(255, 255, 255, 0.9)"},children:[r.jsx("svg",{className:"w-2.5 h-2.5",fill:"currentColor",viewBox:"0 0 20 20",children:r.jsx("path",{fillRule:"evenodd",d:"M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),t.brand]})}),r.jsx("p",{className:"font-extrabold mt-2",style:{fontSize:"22px",letterSpacing:"-0.02em",color:"#FFD700",textShadow:"0 2px 6px rgba(0, 0, 0, 0.5), 0 0 12px rgba(255, 215, 0, 0.3)"},children:t.price>0?`$${t.price.toFixed(2)}`:"POA"})]}),r.jsx("button",{onClick:u,className:"flex-shrink-0 flex items-center justify-center glass-button",style:{...Ps,width:"56px",height:"56px",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease-out"},onMouseEnter:x=>{x.currentTarget.style.transform="scale(1.08) translateY(-2px)",x.currentTarget.style.boxShadow="0 14px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.4)"},onMouseLeave:x=>{x.currentTarget.style.transform="scale(1) translateY(0)",x.currentTarget.style.boxShadow=Ps.boxShadow},children:r.jsx("svg",{className:"w-6 h-6 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M12 4v16m8-8H4"})})})]}),t.partslotDescription&&r.jsx("div",{className:"mt-3 pt-3",style:{borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:r.jsx("span",{className:"text-xs font-medium",style:{color:"rgba(255, 255, 255, 0.6)"},children:t.partslotDescription})})]})},Ms=(t,e)=>{if(!t||!e)return!1;const s=t.toLowerCase();return e.toLowerCase().replace(/s\b/g,"").split(/\s+/).filter(Boolean).every(i=>s.includes(i))},Vi=(t,e)=>{var i;const s=((i=t.brand)==null?void 0:i.toLowerCase())===e.brand.toLowerCase(),n=Math.abs(t.price-e.price)<1;return s&&n},Gi=({product:t,isSpotlighted:e,spotlightedRef:s,onProductClick:n,viewportSize:i})=>i==="desktop"?r.jsxs("div",{ref:e?s:void 0,onClick:()=>n==null?void 0:n(t),className:`flex flex-row cursor-pointer transition-all duration-300 bg-white rounded-2xl border relative overflow-hidden hover:shadow-2xl hover:scale-[1.01] hover:-translate-y-0.5 group ${e?"ring-2 ring-blue-500 shadow-xl border-blue-200":"border-gray-100 shadow-lg"}`,style:{minHeight:"140px"},children:[e&&r.jsx(As,{variant:"horizontal"}),r.jsx("div",{className:"w-36 shrink-0 bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center overflow-hidden",children:t.image_url?r.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-3 group-hover:scale-105 transition-transform duration-300"}):r.jsx(Ls,{size:"lg"})}),r.jsxs("div",{className:"flex-1 p-4 flex flex-col justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-base font-semibold text-gray-900 line-clamp-2 mb-1 group-hover:text-blue-700 transition-colors",children:t.name}),t.brand&&r.jsx("div",{className:"flex items-center gap-2 mb-2",children:r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-medium text-gray-600 bg-gray-100 px-2 py-0.5 rounded-full",children:[r.jsx("svg",{className:"w-3 h-3 text-gray-500",fill:"currentColor",viewBox:"0 0 20 20",children:r.jsx("path",{fillRule:"evenodd",d:"M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),t.brand]})})]}),r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsx("span",{className:"text-2xl font-bold text-blue-600",children:t.price>0?`$${t.price.toFixed(2)}`:"POA"}),r.jsx("button",{className:"px-4 py-2 bg-gradient-to-r from-blue-600 to-blue-500 text-white text-sm font-semibold rounded-lg hover:from-blue-700 hover:to-blue-600 transition-all shadow-md",onClick:c=>{c.stopPropagation(),n==null||n(t)},children:"View"})]})]})]}):i==="tablet"?r.jsxs("div",{ref:e?s:void 0,onClick:()=>n==null?void 0:n(t),className:`cursor-pointer transition-all duration-300 bg-white rounded-2xl border relative overflow-hidden hover:shadow-xl hover:scale-[1.02] hover:-translate-y-1 ${e?"ring-2 ring-blue-500 shadow-xl border-blue-200":"border-gray-100 shadow-lg"}`,children:[e&&r.jsx(As,{}),r.jsx("div",{className:"aspect-[4/3] bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center overflow-hidden",children:t.image_url?r.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-4"}):r.jsx(Ls,{size:"md"})}),r.jsxs("div",{className:"p-4",children:[r.jsx("p",{className:"text-base font-semibold text-gray-900 line-clamp-2 mb-1",children:t.name}),t.brand&&r.jsxs("p",{className:"text-sm text-gray-600 font-medium mb-2 flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 bg-blue-500 rounded-full"}),t.brand]}),r.jsx("div",{className:"flex items-center justify-between",children:r.jsx("span",{className:"text-xl font-bold text-blue-600",children:t.price>0?`$${t.price.toFixed(2)}`:"POA"})}),r.jsx("button",{className:"mt-3 w-full bg-gradient-to-r from-blue-600 to-blue-500 text-white text-sm font-semibold py-2.5 rounded-xl hover:from-blue-700 hover:to-blue-600 active:from-blue-800 active:to-blue-700 transition-all shadow-md",onClick:c=>{c.stopPropagation(),n==null||n(t)},children:"View Details"})]})]}):r.jsx("div",{ref:e?s:void 0,children:r.jsx(Tn,{product:t,isSpotlighted:e,onProductClick:n})}),As=({variant:t="default"})=>r.jsxs("span",{className:`absolute bg-gradient-to-r from-blue-600 to-blue-500 text-white text-xs px-2.5 py-1 rounded-full z-20 flex items-center gap-1 font-semibold shadow-md ${t==="horizontal"?"top-2 left-2":"top-3 right-3"}`,children:[r.jsx("svg",{className:"h-3 w-3",fill:"currentColor",viewBox:"0 0 20 20",children:r.jsx("path",{d:"M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"})}),"Bob's Pick"]}),Ls=({size:t})=>{const e={sm:"h-8 w-8",md:"h-10 w-10",lg:"h-12 w-12"};return r.jsxs("div",{className:"flex flex-col items-center justify-center text-gray-400",children:[r.jsx("svg",{className:e[t],fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})}),r.jsx("span",{className:"text-xs font-medium uppercase tracking-wide mt-1",children:"No Image"})]})},Or=({products:t,servicePackages:e,highlightedPartType:s,highlightedProduct:n,onProductClick:i,onPackageSelect:c,isResearching:d,visible:u=!0,counterHeightPercent:y=22,hasVehicle:x=!1,onAddToCart:b})=>{const p=Br();ps();const g=a.useRef(null),m=a.useRef({}),S=a.useRef(null),f=30,j=20,[v,w]=a.useState(f),h=a.useRef(null),[k,R]=a.useState(null),[P,H]=a.useState({});a.useEffect(()=>{w(f)},[t.length]),a.useEffect(()=>{if(!h.current)return;const D=new IntersectionObserver(z=>{z[0].isIntersecting&&v<t.length&&w($=>Math.min($+j,t.length))},{threshold:.1});return D.observe(h.current),()=>D.disconnect()},[v,t.length]);const B=a.useMemo(()=>t.slice(0,v),[t,v]),A=a.useMemo(()=>{const D={};return B.forEach($=>{const V=$.partslotDescription||"Other Parts";D[V]||(D[V]=[]),D[V].push($)}),Object.keys(D).sort(($,V)=>$.localeCompare(V)).map($=>({name:$,products:D[$]}))},[B]);a.useEffect(()=>{var D;if(s){const z=A.find($=>Ms($.name,s));z&&m.current[z.name]&&((D=m.current[z.name])==null||D.scrollIntoView({behavior:"smooth",block:"start"}))}},[s,A]),a.useEffect(()=>{n&&S.current&&S.current.scrollIntoView({behavior:"smooth",block:"center"})},[n]);const[_,C]=a.useState(0),E=D=>{const z=D.currentTarget,$=z.scrollHeight-z.clientHeight;if($>0){const V=z.scrollTop/$;C(Math.max(0,Math.min(1,V)))}},N=t.length>0||e.length>0,I=d&&!N,U=N&&!I,F=u||N,J=p==="mobile"?92:p==="tablet"?65:48,q=p==="desktop"?"580px":p==="tablet"?"500px":"100%",O=p==="mobile"?`calc(${x?"56px":"8px"} + env(safe-area-inset-top, 4px))`:"6px";return r.jsxs(r.Fragment,{children:[N&&u&&r.jsx("div",{style:{position:"fixed",right:"2px",top:`calc(${_*65+18}%)`,...Ki,opacity:.8,transition:"top 0.1s ease-out",zIndex:100,pointerEvents:"none"}}),r.jsxs("div",{ref:g,onScroll:E,className:`absolute overflow-y-auto overflow-x-hidden z-30 flex flex-col gap-3 md:gap-4 transition-all duration-400 ease-out product-scroll ${F?"opacity-100 translate-x-0":"opacity-0 translate-x-12 pointer-events-none"}`,style:{width:`${J}%`,maxWidth:q,right:"0",left:"auto",top:O,bottom:p==="mobile"?"calc(180px + env(safe-area-inset-bottom, 0px))":"52px",paddingTop:"4px",paddingRight:"6px",paddingLeft:"12px",paddingBottom:"8px",scrollbarWidth:"none",msOverflowStyle:"none"},children:[r.jsx("div",{className:"sticky top-0 z-10 -mx-1 px-3 py-2.5",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.85) 0%, rgba(0, 73, 153, 0.9) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"24px",boxShadow:"0 10px 40px rgba(0, 102, 204, 0.4)",border:"1px solid rgba(255, 255, 255, 0.25)"},children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[d&&N?r.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:r.jsx("div",{className:"w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin"})}):r.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:r.jsx("svg",{className:"w-3.5 h-3.5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),r.jsx("span",{style:{...dr.primary,fontWeight:700,fontSize:"14px",letterSpacing:"0.025em"},children:d&&N?"Updating...":"Bob's Shelf"})]}),r.jsxs("span",{style:{color:"rgba(255,255,255,0.8)",fontSize:"12px",fontWeight:500},children:[t.length+e.length," ",t.length+e.length===1?"item":"items"]})]})}),I&&r.jsx("div",{className:"p-5",style:{...Tr},children:r.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(0, 102, 204, 0.2)"},children:r.jsx("div",{className:"w-6 h-6 border-2 border-t-transparent rounded-full animate-spin",style:{borderColor:"rgba(255,255,255,0.8)",borderTopColor:"transparent"}})}),r.jsxs("div",{children:[r.jsx("p",{style:{...dr.primary,fontWeight:600,fontSize:"14px"},children:"Searching shelves..."}),r.jsx("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:"Finding the best parts for you"})]})]})}),!I&&!N&&r.jsx("div",{className:"p-5",style:{...Tr,background:"rgba(255, 149, 0, 0.15)"},children:r.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(255, 149, 0, 0.3)"},children:r.jsx("svg",{className:"w-5 h-5",style:{color:"#FF9500"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),r.jsxs("div",{children:[r.jsx("p",{style:{...dr.primary,fontWeight:600,fontSize:"14px"},children:"No products to display"}),r.jsxs("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:["Products: ",t.length," | Packages: ",e.length]})]})]})}),U&&e.length>0&&r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center gap-2 px-1",children:[r.jsx("div",{className:"w-6 h-6 rounded-lg flex items-center justify-center",style:{background:`linear-gradient(135deg, ${K.primary} 0%, ${K.primaryHover} 100%)`,boxShadow:`0 4px 12px ${K.primary}66`},children:r.jsx("svg",{className:"h-3.5 w-3.5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})})}),r.jsx("span",{className:"text-xs font-bold uppercase tracking-widest",style:{color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.4)"},children:"CFX Service Packs"})]}),e.map(D=>{var oe,ye;const z=(D.preparedTiers||[]).filter(Z=>!Z.isHidden),$=((oe=z.find(Z=>Z.isRecommended))==null?void 0:oe.tierName)||((ye=z[0])==null?void 0:ye.tierName)||"",V=P[D.id]||$,Q=z.find(Z=>Z.tierName===V),fe=kn(D.title).split(".")[0]+".",xe=k===D.id;return r.jsxs("div",{className:"overflow-hidden transition-all duration-300",style:{background:K.card,borderRadius:"16px",border:`1px solid ${K.border}`,boxShadow:"0 4px 20px rgba(0,0,0,0.08)"},children:[r.jsx("div",{className:"px-4 py-3",style:{background:`linear-gradient(135deg, ${K.primary} 0%, ${K.primaryHover} 100%)`},children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 flex items-center justify-center flex-shrink-0",children:r.jsx("svg",{className:"h-5 w-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("h3",{className:"text-white font-bold text-base leading-tight truncate",children:D.title}),D.estimated_time&&r.jsx("div",{className:"flex items-center gap-3 mt-0.5",children:r.jsxs("span",{className:"text-white/70 text-xs flex items-center gap-1",children:[r.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),D.estimated_time]})})]})]})}),r.jsx("div",{className:"px-4 py-3 border-b",style:{borderColor:K.border},children:r.jsx("p",{className:"text-sm leading-relaxed",style:{color:K.mutedForeground},children:fe})}),z.length>0&&r.jsxs("div",{className:"p-3",children:[r.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2 px-1",style:{color:K.mutedForeground},children:"Choose Your Value Level"}),r.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:`repeat(${Math.min(z.length,4)}, 1fr)`},children:z.map(Z=>{const Be=Nr[Z.tierName],Ie=Z.tierName===V;return r.jsxs("div",{onClick:()=>H(re=>({...re,[D.id]:Z.tierName})),className:"relative rounded-xl text-center transition-all cursor-pointer",style:{padding:z.length>=4?"6px 4px":"8px",background:Z.isRecommended?`${K.primary}10`:Ie?`${K.primary}05`:K.background,border:`2px solid ${Z.isRecommended?K.primary:Ie?K.primary+"80":K.border}`},children:[Z.isRecommended&&r.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wide whitespace-nowrap",style:{background:"#22C55E",color:"white"},children:"Recommended"}),r.jsxs("p",{className:"text-sm font-bold mt-1",style:{color:(Be==null?void 0:Be.textColor)||K.foreground},children:[Be==null?void 0:Be.emoji," ",Z.displayName]}),r.jsx("div",{className:"flex flex-col items-center gap-1 mt-2",style:{minHeight:z.length>=4?"40px":"48px"},children:Z.brands.slice(0,1).map((re,Ce)=>{const ge=`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${re.fullName.replace(/\s+/g,"")}.jpg`;return r.jsx("div",{className:"w-full bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{height:z.length>=4?"36px":"44px",maxWidth:z.length>=4?"64px":"80px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",border:"1px solid #F1F5F9"},children:r.jsx("img",{src:re.imageUrl,alt:re.fullName,className:"w-auto object-contain",style:{height:z.length>=4?"26px":"32px"},onError:He=>{const rt=He.target;rt.src!==ge?rt.src=ge:(rt.style.display="none",rt.parentElement.innerHTML=`<span class="text-[10px] font-semibold text-gray-600 truncate px-1">${re.fullName}</span>`)}})},Ce)})}),r.jsxs("p",{className:"text-[10px] mt-2",style:{color:K.mutedForeground},children:[Z.productCount," ",Z.productCount===1?"part":"parts"]}),r.jsx("p",{className:"text-base font-bold mt-1",style:{color:K.foreground},children:bt(Z.totalPrice)}),r.jsx("p",{className:"text-[10px]",style:{color:K.mutedForeground},children:"inc GST"}),r.jsxs("button",{onClick:re=>{re.stopPropagation();const Ce=Z.products.map(ge=>({id:ge.sku,name:ge.name,brand:ge.brand,price:ge.displayPrice,sku:ge.sku,partNumber:ge.partNumber||void 0,image_url:ge.productImageUrl,partslotDescription:ge.partslotName,quantity:1}));b==null||b(Ce)},className:"w-full mt-2 py-1.5 rounded-lg text-[10px] font-semibold transition-all flex items-center justify-center gap-1",style:{background:Z.isRecommended?K.primary:"#F1F5F9",color:Z.isRecommended?"white":"#475569",border:Z.isRecommended?"none":"1px solid #E2E8F0"},children:[r.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"})}),"Add"]})]},Z.tierName)})})]}),r.jsxs("div",{onClick:()=>R(xe?null:D.id),className:"flex items-center justify-center gap-1.5 py-2 cursor-pointer hover:bg-gray-50 transition-colors border-t",style:{borderColor:K.border},children:[r.jsx("span",{className:"text-xs",style:{color:K.mutedForeground},children:xe?"Hide details":"Show details"}),r.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${xe?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",style:{color:K.mutedForeground},children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),xe&&Q&&r.jsx("div",{className:"px-4 pb-4 border-t animate-in slide-in-from-top-2 duration-200",style:{borderColor:K.border},children:r.jsxs("div",{className:"pt-3",children:[r.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide mb-3",style:{color:K.mutedForeground},children:[Q.displayName," Tier Products"]}),r.jsx("div",{className:"space-y-2",children:Q.products.map(Z=>r.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg",style:{background:K.background,border:`1px solid ${K.border}`},children:[r.jsx("div",{className:"w-14 h-14 flex-shrink-0 bg-white rounded-lg overflow-hidden flex items-center justify-center",children:Z.productImageUrl?r.jsx("img",{src:Z.productImageUrl,alt:Z.name,className:"w-full h-full object-contain p-1"}):r.jsx("svg",{className:"w-6 h-6 text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-xs font-medium truncate",style:{color:K.foreground},children:Z.name}),r.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[r.jsx("span",{className:"text-[10px]",style:{color:K.mutedForeground},children:Z.brand}),Z.isRotor&&r.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 font-medium",children:"Pair"})]}),r.jsx("p",{className:"text-[10px] mt-0.5",style:{color:K.mutedForeground},children:Z.partslotName})]}),r.jsxs("div",{className:"text-right flex-shrink-0",children:[r.jsx("p",{className:"text-sm font-bold",style:{color:K.primary},children:bt(Z.displayPrice)}),Z.isRotor&&r.jsxs("p",{className:"text-[9px]",style:{color:K.mutedForeground},children:["$",Z.price.toFixed(2)," ea"]})]})]},Z.sku))})]})})]},D.id)})]}),U&&A.map(({name:D,products:z})=>{const $=s&&Ms(D,s);return r.jsxs("section",{ref:V=>{m.current[D]=V},className:"transition-all duration-300",style:{...$?jn:Tr,background:$?"linear-gradient(135deg, rgba(0, 82, 164, 0.85) 0%, rgba(0, 51, 102, 0.9) 100%)":"rgba(20, 30, 50, 0.75)"},children:[r.jsxs("div",{className:"px-3 py-2.5 flex items-center justify-between",style:{background:$?"rgba(0, 102, 204, 0.8)":"rgba(0, 51, 102, 0.7)",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("div",{className:"w-5 h-5 rounded-md flex items-center justify-center flex-shrink-0",style:{background:$?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 1) 100%)":"rgba(255,255,255,0.2)"},children:r.jsx("svg",{className:"h-3 w-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),r.jsx("span",{className:"text-xs font-bold truncate uppercase tracking-wide",style:{color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)"},children:D})]}),r.jsx("span",{className:"text-[10px] font-bold px-2.5 py-1 rounded-full flex-shrink-0",style:{background:"rgba(255, 149, 0, 0.9)",color:"white",boxShadow:"0 2px 8px rgba(255, 149, 0, 0.4)"},children:z.length})]}),r.jsx("div",{className:"p-3 flex flex-col gap-3",children:z.map((V,Q)=>{const ue=!!(n&&Vi(V,n));return r.jsx(Gi,{product:V,isSpotlighted:ue,spotlightedRef:S,onProductClick:i,viewportSize:p},`${V.id}-${Q}`)})})]},D)}),v<t.length&&r.jsx("div",{ref:h,className:"flex items-center justify-center py-4",children:r.jsxs("div",{className:"flex items-center gap-2 text-sm",style:{color:"rgba(255,255,255,0.6)"},children:[r.jsx("div",{className:"w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"}),r.jsxs("span",{children:["Loading more (",v," of ",t.length,")..."]})]})}),r.jsx("div",{className:"h-4"})]})]})},gs=({onTranscript:t,onSpeechEnd:e,language:s="en-NZ",mode:n="toggle"}={})=>{const[i,c]=a.useState(!1),[d,u]=a.useState(""),[y,x]=a.useState(""),[b,p]=a.useState(null),[g,m]=a.useState(!1),S=a.useRef(null),f=a.useRef(""),j=a.useRef(t),v=a.useRef(e),w=a.useRef(null),h=15e3;a.useEffect(()=>{j.current=t,v.current=e},[t,e]),a.useEffect(()=>{const H=window.SpeechRecognition||window.webkitSpeechRecognition;if(H){m(!0);const B=new H;B.continuous=n==="ptt",B.interimResults=!0,B.lang=s,B.maxAlternatives=1,B.onstart=()=>{c(!0),p(null)},B.onresult=A=>{let _="",C="";for(let E=A.resultIndex;E<A.results.length;E++){const N=A.results[E][0].transcript;A.results[E].isFinal?C+=N:_+=N}C&&(f.current=C,u(C),j.current&&j.current(C)),x(_)},B.onerror=A=>{switch(c(!1),A.error){case"no-speech":p("No speech detected. Please try again.");break;case"audio-capture":p("No microphone found. Please check your device.");break;case"not-allowed":p("Microphone permission denied. Please allow access.");break;default:p("Speech recognition error. Please try again.")}},B.onend=()=>{w.current&&(clearTimeout(w.current),w.current=null),c(!1),x(""),f.current&&v.current&&v.current(f.current),f.current=""},S.current=B}return()=>{S.current&&S.current.stop()}},[s,n]);const k=()=>{S.current&&!i&&(u(""),x(""),p(null),w.current=setTimeout(()=>{console.warn("[SpeechRecognition] Safety timeout - forcing stop after 15s"),S.current&&S.current.abort(),c(!1),x("")},h),S.current.start())},R=()=>{w.current&&(clearTimeout(w.current),w.current=null),S.current&&i&&S.current.stop()};return{isListening:i,transcript:d,interimTranscript:y,error:b,isSupported:g,startListening:k,stopListening:R,toggleListening:()=>{i?R():k()}}},Rn=({messages:t,input:e,setInput:s,isLoading:n,onSend:i,onKeyPress:c,onInputFocus:d,onInputBlur:u,chatEndRef:y,isMuted:x=!1,onToggleMute:b,isSpeaking:p=!1,onAddToCart:g,onProductClick:m})=>{var q;const[S,f]=a.useState(!1),j=a.useRef(null),v=a.useRef(!1),{bottomOffset:w,zIndexBase:h}=hs(),{isListening:k,interimTranscript:R,error:P,isSupported:H,startListening:B,stopListening:A}=gs({onTranscript:O=>s(O),language:"en-NZ",mode:"ptt"});a.useEffect(()=>{R&&s(R)},[R,s]);const _=a.useCallback(()=>{n||v.current||(v.current=!0,navigator.vibrate&&navigator.vibrate(30),B())},[n,B]),C=a.useCallback(()=>{v.current&&(v.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),A(),setTimeout(()=>{i()},150))},[A,i]),E=[...t].reverse().find(O=>O.role==="assistant"),N=((q=E==null?void 0:E.suggestedProducts)==null?void 0:q.length)||0,I=E!=null&&E.content?E.content.length>50?E.content.slice(0,50)+"...":E.content:"Ask Bob about car parts...",U=N>0?` (${N} products)`:"",F={idle:{..._n},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"32px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},J=n?F.disabled:k?F.active:F.idle;return r.jsxs("div",{ref:j,style:{position:"fixed",bottom:`${w}px`,left:0,right:0,...En,borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"all 0.3s ease-out",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:S?"55vh":"auto",zIndex:h+60,paddingBottom:w>0?"8px":"env(safe-area-inset-bottom, 8px)"},children:[r.jsx("button",{onClick:()=>f(!S),style:{position:"absolute",top:"-20px",left:"50%",transform:"translateX(-50%)",background:"rgba(255, 255, 255, 0.15)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"9999px",padding:"6px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)",zIndex:h+70,cursor:"pointer",minHeight:"unset",minWidth:"unset"},"aria-label":S?"Collapse chat":"Expand chat",children:S?r.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}):r.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 15l7-7 7 7"})})}),!S&&r.jsx("div",{onClick:()=>f(!0),style:{padding:"8px 12px 2px 12px",cursor:"pointer"},children:r.jsxs("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[I,U&&r.jsx("span",{style:{color:"rgba(255,200,0,0.9)",fontWeight:600},children:U})]})}),S&&r.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px"},className:"glass-scroll",children:[[...t].reverse().map((O,D)=>{var z;return r.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:O.role==="user"?"flex-end":"flex-start"},children:r.jsxs("div",{style:{maxWidth:(z=O.suggestedProducts)!=null&&z.length?"100%":"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:O.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:[O.content,O.role==="assistant"&&O.suggestedProducts&&O.suggestedProducts.length>0&&r.jsx(fs,{products:O.suggestedProducts,title:O.suggestionsTitle,onAddToCart:g,onProductClick:m})]})},D)}),r.jsx("div",{ref:y})]}),H&&r.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"12px 16px 8px 16px"},children:r.jsx("button",{onTouchStart:_,onTouchEnd:C,onTouchCancel:C,onMouseDown:_,onMouseUp:C,onMouseLeave:C,onClick:k?C:void 0,disabled:n,"aria-label":"Hold to talk to Bob",className:"glass-button",style:{width:"200px",height:"64px",minHeight:"unset",minWidth:"unset",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",touchAction:"none",cursor:n?"not-allowed":"pointer",opacity:n?.6:1,transform:k?"scale(1.04)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease, background 0.15s ease",...J},title:"Hold to talk",children:r.jsx("span",{style:{fontSize:"22px",fontWeight:800,letterSpacing:"0.15em",...dr.primary,textTransform:"uppercase",fontFamily:"system-ui, -apple-system, sans-serif"},children:k?"LISTENING":"TALK"})})}),r.jsxs("div",{style:{padding:"4px 12px 8px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:[P&&r.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:P}),r.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[b&&r.jsx("button",{onClick:b,style:{flexShrink:0,height:"40px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"12px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:p?"#0066CC":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:x?"Unmute":"Mute",children:x?r.jsxs("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):r.jsx("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),r.jsx("input",{type:"text",value:e,onChange:O=>s(O.target.value),onKeyPress:c,onFocus:d,onBlur:u,placeholder:"Or type here...",disabled:n,className:"high-contrast-input",style:{flex:1,height:"40px",fontSize:"16px",padding:"0 14px",background:"rgba(0, 51, 102, 0.85)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"2px solid rgba(255, 255, 255, 0.35)",borderRadius:"20px",color:"white",outline:"none",opacity:n?.5:1}})]})]})]})},Cn=({currentImage:t,animationState:e,backdropUrl:s,counterOverlayUrl:n,counterHeightPercent:i=22,messages:c,input:d,setInput:u,isLoading:y,onSend:x,onKeyPress:b,onInputFocus:p,onInputBlur:g,chatEndRef:m,isMuted:S,onToggleMute:f,isSpeaking:j,products:v,servicePackages:w,highlightedPartType:h,highlightedProduct:k,onProductClick:R,onPackageSelect:P,isResearching:H,vehicle:B,onChangeVehicle:A,bobOffset:_=0,bobScale:C=100,embedded:E=!1})=>{console.log("[MobileBobLayout] Rendering with:",{currentImage:(t==null?void 0:t.substring(0,50))||"EMPTY",backdropUrl:(s==null?void 0:s.substring(0,50))||"NONE",counterOverlayUrl:(n==null?void 0:n.substring(0,50))||"NONE"});const N=typeof window<"u"&&window.self!==window.top,I=Br(),[U,F]=a.useState("center"),[J,q]=a.useState("hidden"),O=v.length>0||w.length>0,$=(()=>{switch(I){case"desktop":return 70;case"tablet":return 80;case"mobile":return 140;default:return 140}})()*C/100;a.useEffect(()=>{if(H&&J!=="loading"&&J!=="visible")q("loading"),U==="center"&&F("left");else if(O&&J!=="visible")if(U==="center"){F("left"),q("transitioning");const Q=setTimeout(()=>{q("visible")},400);return()=>clearTimeout(Q)}else q("visible");else!O&&!H&&J!=="hidden"&&(q("hidden"),F("center"))},[O,H,J,U]);const V=J!=="hidden";return r.jsxs("div",{className:E?"absolute inset-0 overflow-hidden":"fixed inset-0 overflow-hidden",style:{height:E?"100%":"100dvh",touchAction:"manipulation"},children:[s&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"absolute inset-0 z-0",style:{backgroundImage:`url(${s})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:"blur(4px) brightness(0.85)",transform:"scale(1.05)"}}),r.jsx("div",{className:"absolute inset-0 z-[1]",style:{background:"linear-gradient(to bottom, rgba(255,255,255,0.15) 0%, rgba(255,255,255,0.35) 100%)"}})]}),r.jsx(Ir,{currentImage:t,animationState:e,counterOverlayUrl:n,counterHeightPercent:i,scale:$,position:U,verticalOffset:_}),B&&!N&&r.jsx("div",{style:{position:"absolute",top:"8px",left:"8px",right:"8px",zIndex:20},children:r.jsxs("div",{style:{backgroundColor:"rgba(255, 255, 255, 0.9)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)",borderRadius:"8px",padding:"8px 12px",paddingTop:"calc(env(safe-area-inset-top, 4px) + 8px)",border:"1px solid #e5e7eb",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsxs("p",{style:{fontSize:"12px",fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[B.year," ",B.make," ",B.model]}),B.rego&&r.jsx("p",{style:{fontSize:"10px",color:"#6b7280"},children:B.rego})]}),A&&r.jsx("button",{onClick:A,style:{fontSize:"12px",color:"#2563eb",marginLeft:"8px",flexShrink:0,background:"none",border:"none",cursor:"pointer",minHeight:"unset",minWidth:"unset"},children:"Change"})]})}),r.jsx(Or,{products:v,servicePackages:w,highlightedPartType:h,highlightedProduct:k,onProductClick:R,onPackageSelect:P,isResearching:H,visible:V,counterHeightPercent:i,hasVehicle:!!B}),r.jsx(Rn,{messages:c,input:d,setInput:u,isLoading:y,onSend:x,onKeyPress:b,onInputFocus:p,onInputBlur:g,chatEndRef:m,isMuted:S,onToggleMute:f,isSpeaking:j,onAddToCart:R,onProductClick:R})]})},Nn=({messages:t,input:e,setInput:s,isLoading:n,onSend:i,onKeyPress:c,onInputFocus:d,onInputBlur:u,chatEndRef:y,isMuted:x=!1,onToggleMute:b,isSpeaking:p=!1})=>{const[g,m]=a.useState(!1),S=a.useRef(null),f=a.useRef(!1),{bottomOffset:j,zIndexBase:v}=hs(),{isListening:w,interimTranscript:h,error:k,isSupported:R,startListening:P,stopListening:H}=gs({onTranscript:I=>s(I),language:"en-NZ",mode:"ptt"});a.useEffect(()=>{h&&s(h)},[h,s]);const B=a.useCallback(()=>{n||f.current||(f.current=!0,navigator.vibrate&&navigator.vibrate(30),P())},[n,P]),A=a.useCallback(()=>{f.current&&(f.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),H(),setTimeout(()=>{i()},150))},[H,i]),_=[...t].reverse().find(I=>I.role==="assistant"),C=_!=null&&_.content?_.content.length>50?_.content.slice(0,50)+"...":_.content:"Ask Bob about car parts...",E={idle:{..._n},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"50%",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},N=n?E.disabled:w?E.active:E.idle;return r.jsxs("div",{ref:S,style:{position:"absolute",bottom:`${j}px`,left:0,right:0,...En,borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"all 0.3s ease-out",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:g?"55%":"70px",overflow:g?"visible":"hidden",zIndex:v+10,paddingBottom:j>0?"8px":"env(safe-area-inset-bottom, 8px)"},children:[r.jsx("button",{onClick:()=>m(!g),style:{position:"absolute",top:"-20px",left:"50%",transform:"translateX(-50%)",background:"rgba(255, 255, 255, 0.15)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"9999px",padding:"6px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)",zIndex:v+20,cursor:"pointer",minHeight:"unset",minWidth:"unset"},"aria-label":g?"Collapse chat":"Expand chat",children:g?r.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}):r.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 15l7-7 7 7"})})}),!g&&r.jsx("div",{onClick:()=>m(!0),style:{padding:"6px 12px 4px 12px",height:"26px",overflow:"hidden",cursor:"pointer"},children:r.jsx("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C})}),g&&r.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px"},className:"glass-scroll",children:[[...t].reverse().map((I,U)=>r.jsx("div",{style:{display:"flex",justifyContent:I.role==="user"?"flex-end":"flex-start"},children:r.jsx("div",{style:{maxWidth:"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:I.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:I.content})},U)),r.jsx("div",{ref:y})]}),r.jsxs("div",{style:{padding:g?"8px 12px 4px 12px":"4px 12px 4px 12px",borderTop:g?"1px solid rgba(255, 255, 255, 0.15)":"none"},children:[w&&r.jsxs("div",{style:{marginBottom:"8px",fontSize:"12px",color:"rgba(255,255,255,0.7)",display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("span",{style:{display:"inline-block",width:"8px",height:"8px",backgroundColor:"#FF9500",borderRadius:"50%",animation:"pulse 2s infinite"}}),"Listening..."]}),k&&r.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:k}),r.jsxs("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[b&&g&&r.jsx("button",{onClick:b,style:{flexShrink:0,height:"36px",width:"36px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"10px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:p?"#0066CC":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:x?"Unmute":"Mute",children:x?r.jsxs("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):r.jsx("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),r.jsx("input",{type:"text",value:e,onChange:I=>s(I.target.value),onKeyPress:c,onFocus:d,onBlur:u,placeholder:"Message Bob...",disabled:n,className:"high-contrast-input",style:{flex:1,height:"40px",fontSize:"16px",padding:"0 14px",background:"rgba(0, 51, 102, 0.85)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"2px solid rgba(255, 255, 255, 0.35)",borderRadius:"20px",color:"white",outline:"none",opacity:n?.5:1}}),R&&r.jsxs("div",{style:{position:"relative",marginLeft:"4px"},children:[w&&r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"72px",height:"72px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),r.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"72px",height:"72px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),!w&&!n&&r.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"72px",height:"72px",borderRadius:"50%",transform:"translate(-50%, -50%)",animation:"ptt-pulse 2s ease-in-out infinite",pointerEvents:"none"}}),r.jsxs("button",{onTouchStart:B,onTouchEnd:A,onTouchCancel:A,onMouseDown:B,onMouseUp:A,onMouseLeave:A,disabled:n,"aria-label":"Hold to talk to Bob",className:"glass-button",style:{position:"relative",flexShrink:0,height:"72px",width:"72px",minHeight:"unset",minWidth:"unset",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",touchAction:"none",color:"white",border:"none",cursor:n?"not-allowed":"pointer",opacity:n?.6:1,transform:w?"scale(1.08)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease",zIndex:v+25,...N},title:"Hold to talk",children:[r.jsx("svg",{style:{height:"28px",width:"28px",filter:"drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2))"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})}),w&&r.jsx("div",{style:{position:"absolute",top:"8px",right:"8px",width:"12px",height:"12px",borderRadius:"50%",backgroundColor:"#fef3c7",animation:"ptt-dot 0.6s ease-in-out infinite alternate"}})]})]})]})]})]})},Yi=({product:t,onBack:e,onAddToCart:s,onNavigateToProductPage:n})=>{const i=t.productUrl||t.product_url,c=t.partNumber||t.part_number,d=!!i||!!n;return r.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-white/95 backdrop-blur-md overflow-hidden",children:[r.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-gray-200 bg-white/80 backdrop-blur-sm",children:r.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-blue-600 font-medium text-sm hover:text-blue-700 active:scale-95 transition-all",children:[r.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back to Products"]})}),r.jsxs("div",{className:"flex-1 overflow-y-auto",children:[r.jsx("div",{className:"aspect-square bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center",children:t.image_url?r.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-4"}):r.jsxs("div",{className:"flex flex-col items-center justify-center text-gray-400",children:[r.jsx("svg",{className:"h-16 w-16 mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})}),r.jsx("span",{className:"text-sm font-medium uppercase tracking-wide",children:"No Image Available"})]})}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("h1",{className:"text-xl font-bold text-gray-900 mb-1",children:t.name}),t.brand&&r.jsx("p",{className:"text-sm text-gray-600 font-medium",children:t.brand})]}),r.jsxs("div",{className:"bg-blue-50 rounded-xl p-4",children:[r.jsx("p",{className:"text-sm text-gray-600 mb-1",children:"Price"}),r.jsx("p",{className:"text-2xl font-bold text-blue-600",children:t.price>0?`$${t.price.toFixed(2)}`:"Price on Request"}),t.price>0&&r.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Inc. GST"})]}),r.jsxs("div",{className:"space-y-3",children:[t.partslotDescription&&r.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[r.jsx("span",{className:"text-sm text-gray-500",children:"Category"}),r.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.partslotDescription})]}),t.sku&&r.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[r.jsx("span",{className:"text-sm text-gray-500",children:"SKU"}),r.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.sku})]}),c&&r.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[r.jsx("span",{className:"text-sm text-gray-500",children:"Part Number"}),r.jsx("span",{className:"text-sm font-medium text-gray-900",children:c})]})]}),d&&r.jsx("a",{href:i||"#",onClick:u=>{n&&(u.preventDefault(),n(t))},target:i&&!n?"_blank":void 0,rel:i&&!n?"noopener noreferrer":void 0,className:"block text-center text-blue-600 text-sm font-medium hover:underline py-2",children:"View Full Details on CARFIX →"})]})]}),r.jsx("div",{className:"p-4 border-t border-gray-200 bg-white/95 backdrop-blur-sm",children:r.jsx("button",{onClick:()=>s==null?void 0:s(t),className:"w-full bg-blue-600 text-white text-base font-semibold py-3 rounded-xl hover:bg-blue-700 active:bg-blue-800 transition-colors shadow-lg",children:"Add to Cart"})})]})},Fn=({package:t,onBack:e,onAddToCart:s,onNavigateToProductPage:n})=>{var g;const[i,c]=a.useState(!1),d=a.useMemo(()=>!t.preparedTiers||t.preparedTiers.length===0?[]:t.preparedTiers.filter(m=>!m.isHidden),[t.preparedTiers]),u=d.length>0,y=m=>{s==null||s(m.products)},x=m=>m===2?"grid-cols-2":m===3?"grid-cols-3":"grid-cols-2",b=kn(t.title),p=((g=d[0])==null?void 0:g.productCount)||0;return r.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-[#FAFAFA] overflow-hidden",children:[r.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[#E2E8F0] bg-white shadow-sm",children:r.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-[#0052CC] font-medium text-sm hover:text-[#0047B3] active:scale-95 transition-all",children:[r.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]})}),r.jsxs("div",{className:"flex-1 overflow-y-auto",children:[r.jsxs("div",{className:"px-4 pt-4 pb-4",style:{background:"linear-gradient(135deg, rgba(0,82,204,0.05) 0%, rgba(56,189,248,0.05) 100%)"},children:[r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0 bg-white shadow-md",children:t.icon_url?r.jsx("img",{src:t.icon_url,alt:"",className:"w-8 h-8 object-contain"}):r.jsx("svg",{className:"w-7 h-7 text-[#0052CC]",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("h1",{className:"text-xl font-bold text-[#0F172A]",children:t.title}),r.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-[#64748B]",children:[t.estimated_time&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),t.estimated_time]}),t.difficulty_level&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085"})}),t.difficulty_level]})]})]})]}),r.jsx("p",{className:"text-sm text-[#64748B] mt-3 leading-relaxed",children:b})]}),r.jsxs("div",{className:"px-4 py-3 flex items-center justify-center gap-2 border-b border-[#E2E8F0] bg-white",children:[r.jsx("span",{className:"font-semibold text-[#0F172A] text-sm",children:"Choose Your Value Level"}),r.jsx("span",{className:"text-[#64748B] text-xs cursor-help",title:"Select the quality tier that suits your needs",children:"ⓘ"})]}),r.jsx("div",{className:"p-4",children:u?r.jsx("div",{className:`grid ${x(d.length)} gap-3`,children:d.map(m=>{const S=Nr[m.tierName];return r.jsxs("div",{className:"relative rounded-2xl overflow-hidden bg-white shadow-md flex flex-col",style:{border:m.isRecommended?"2px solid #0052CC":"1px solid #E2E8F0"},children:[m.isRecommended&&r.jsx("div",{className:"absolute top-0 left-0 right-0 px-2 py-1 text-[9px] font-bold text-white text-center",style:{background:"linear-gradient(135deg, #0052CC 0%, #38BDF8 100%)"},children:"★ RECOMMENDED"}),r.jsxs("div",{className:`p-3 flex-1 flex flex-col ${m.isRecommended?"pt-7":""}`,children:[r.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[r.jsx("span",{className:"text-lg",children:S==null?void 0:S.emoji}),r.jsxs("div",{children:[r.jsx("span",{className:"font-bold text-sm block",style:{color:(S==null?void 0:S.textColor)||K.foreground},children:m.displayName}),r.jsx("span",{className:"text-[10px] text-[#64748B] hidden md:block",children:m.description||(S==null?void 0:S.description)})]})]}),r.jsx("div",{className:"flex items-center gap-1.5 mb-3 min-h-[42px] flex-wrap",children:m.brands.slice(0,3).map(f=>r.jsx("div",{className:"h-10 px-2 bg-white rounded-xl flex items-center justify-center shadow-md border border-[#F1F5F9]",children:r.jsx("img",{src:f.imageUrl,alt:f.fullName,className:"h-6 w-auto object-contain",onError:j=>{const v=j.target,w=`${pr.storageBase}/brand_images/${f.fullName.replace(/\s+/g,"")}.jpg`;if(v.src!==w)v.src=w;else{const h=v.parentElement;h&&(h.innerHTML=`<span class="text-[10px] font-medium text-slate-700 px-1 truncate max-w-[60px]">${f.name}</span>`)}}})},f.name))}),r.jsxs("p",{className:"text-xs text-[#64748B] hidden md:block mb-2",children:[m.productCount," part",m.productCount!==1?"s":""," included"]}),r.jsxs("div",{className:"mt-auto",children:[r.jsx("p",{className:"text-xl font-bold",style:{color:m.isRecommended?"#0052CC":"#0F172A"},children:bt(m.totalPrice)}),r.jsx("p",{className:"text-[10px] text-[#64748B] hidden md:block",children:"inc GST"})]}),r.jsxs("button",{onClick:()=>y(m),className:`mt-3 w-full px-3 py-2.5 rounded-xl text-xs font-semibold transition-all hover:scale-[1.02] active:scale-95 flex items-center justify-center gap-1.5 ${m.isRecommended?"bg-[#0052CC] text-white shadow-md hover:bg-[#0047B3]":"bg-slate-100 text-slate-700 border border-slate-200 hover:bg-slate-200"}`,children:[r.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"})}),"Add to Cart"]})]})]},m.tierName)})}):r.jsxs("div",{className:"rounded-2xl p-6 bg-white border border-[#E2E8F0] shadow-md text-center",children:[r.jsx("svg",{className:"w-12 h-12 mx-auto text-[#94A3B8] mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),r.jsx("p",{className:"text-sm font-medium text-[#64748B]",children:"Package details not available for this vehicle"}),r.jsx("p",{className:"text-xs text-[#94A3B8] mt-1",children:"Please try refreshing or contact support"})]})}),u&&r.jsxs("div",{className:"px-4 pb-4",children:[r.jsxs("button",{onClick:()=>c(!i),className:"w-full flex items-center justify-between p-3 rounded-xl bg-white border border-[#E2E8F0] hover:bg-slate-50 transition-all shadow-sm",children:[r.jsxs("span",{className:"text-sm font-medium text-[#0F172A]",children:[i?"▼":"▶"," View Product Details"]}),r.jsxs("span",{className:"text-xs text-[#64748B]",children:[p," product",p!==1?"s":""]})]}),i&&r.jsx("div",{className:"mt-3 space-y-4 bg-white rounded-xl border border-[#E2E8F0] p-3",children:d.map(m=>{if(m.products.length===0)return null;const S=Nr[m.tierName];return r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center gap-2 pb-1 border-b border-[#E2E8F0]",children:[r.jsx("span",{className:"text-lg",children:S==null?void 0:S.emoji}),r.jsx("span",{className:"font-semibold text-sm",style:{color:S==null?void 0:S.textColor},children:m.displayName}),r.jsxs("span",{className:"text-xs text-[#64748B]",children:["(",m.products.length," parts)"]})]}),r.jsx("div",{className:"space-y-2",children:m.products.map((f,j)=>{var h;const v=(h=t.carfixValueProducts)==null?void 0:h.includes(f.sku),w=f.unitPrice??f.price;return r.jsxs("div",{className:"flex items-center gap-3 p-2.5 rounded-xl transition-all hover:bg-slate-50 cursor-pointer border border-[#E2E8F0]",onClick:()=>n==null?void 0:n(f.sku),children:[r.jsx("div",{className:"w-14 h-14 flex-shrink-0 rounded-lg bg-white overflow-hidden border border-[#E2E8F0]",children:r.jsx("img",{src:f.productImageUrl||pr.productImage(f.sku),alt:f.name,className:"w-full h-full object-contain p-1.5",onError:k=>{k.target.src="/placeholder.svg"}})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[r.jsx("span",{className:"text-xs font-semibold text-[#0F172A]",children:f.brandFullName||f.brand}),v&&r.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"rgba(0, 82, 204, 0.1)",color:"#0052CC"},children:"CFX VALUE"}),f.isMultiQty&&f.perCarQty>1&&r.jsxs("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#F0FDF4",color:"#15803D"},children:["×",f.perCarQty]}),f.isRotor&&r.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#EFF6FF",color:"#1D4ED8"},children:"Pair"})]}),r.jsx("p",{className:"text-xs text-[#64748B] line-clamp-1",children:f.name})]}),r.jsxs("div",{className:"text-right flex-shrink-0",children:[r.jsx("p",{className:"text-sm font-bold text-[#0F172A]",children:bt(f.displayPrice)}),f.isMultiQty&&f.perCarQty>1&&r.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[f.perCarQty,"× ",bt(w)," each"]}),f.isRotor&&!f.isMultiQty&&r.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[bt(w)," each"]})]})]},`${f.sku}-${j}`)})})]},m.tierName)})})]}),t.bundle_discount_percentage&&t.bundle_discount_percentage>0&&r.jsx("div",{className:"px-4 pb-4",children:r.jsx("div",{className:"rounded-xl p-3 text-center",style:{background:"rgba(34,197,94,0.1)",border:"1px solid rgba(34,197,94,0.2)"},children:r.jsxs("span",{className:"text-sm font-semibold text-[#22C55E]",children:["Bundle saves you ",t.bundle_discount_percentage,"%"]})})})]})]})},Bn=({currentImage:t,animationState:e,backdropUrl:s,counterOverlayUrl:n,counterHeightPercent:i=22,messages:c,input:d,setInput:u,isLoading:y,onSend:x,onKeyPress:b,onInputFocus:p,onInputBlur:g,chatEndRef:m,isMuted:S,onToggleMute:f,isSpeaking:j,products:v,servicePackages:w,highlightedPartType:h,highlightedProduct:k,onProductClick:R,onPackageSelect:P,isResearching:H,onAddToCart:B,onNavigateToProductPage:A,vehicle:_,onChangeVehicle:C,bobOffset:E=0,bobScale:N=100})=>{const[I,U]=a.useState("center"),[F,J]=a.useState("hidden"),[q,O]=a.useState("products"),[D,z]=a.useState(null),[$,V]=a.useState(null),Q=v.length>0||w.length>0,xe=(q==="productDetail"?70:I==="center"&&!Q?140:98)*N/100;a.useEffect(()=>{if(H&&F!=="loading"&&F!=="visible")J("loading"),I==="center"&&U("left");else if(Q&&F!=="visible")if(I==="center"){U("left"),J("transitioning");const re=setTimeout(()=>{J("visible")},400);return()=>clearTimeout(re)}else J("visible");else!Q&&!H&&F!=="hidden"&&(J("hidden"),U("center"))},[Q,H,F,I]);const oe=re=>{if(A){A(re),R==null||R(re);return}z(re),O("productDetail"),R==null||R(re)},ye=()=>{z(null),V(null),O("products")},Z=re=>{console.log("[ContainedMobileBobLayout] Package selected:",re.title),V(re),O("packageDetail"),P==null||P(re)},Be=F!=="hidden"&&q==="products",Ie=F!=="hidden";return r.jsxs("div",{className:"absolute inset-0 overflow-hidden",style:{touchAction:"manipulation"},children:[s&&r.jsx("div",{className:"absolute inset-0 z-0 transition-all duration-500 ease-out",style:{backgroundImage:`url(${s})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:Ie?"blur(8px) brightness(0.9)":"blur(0px) brightness(1)",transform:"scale(1.05)"}}),r.jsx(Ir,{currentImage:t,animationState:e,counterOverlayUrl:n,counterHeightPercent:i,scale:xe,position:I,verticalOffset:E}),_&&q==="products"&&r.jsx("div",{style:{position:"absolute",top:"8px",left:"8px",right:"8px",zIndex:20},children:r.jsxs("div",{style:{backgroundColor:"rgba(255, 255, 255, 0.9)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)",borderRadius:"8px",padding:"8px 12px",border:"1px solid #e5e7eb",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsxs("p",{style:{fontSize:"12px",fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[_.year," ",_.make," ",_.model]}),_.rego&&r.jsx("p",{style:{fontSize:"10px",color:"#6b7280"},children:_.rego})]}),C&&r.jsx("button",{onClick:C,style:{fontSize:"12px",color:"#2563eb",marginLeft:"8px",flexShrink:0,background:"none",border:"none",cursor:"pointer",minHeight:"unset",minWidth:"unset"},children:"Change"})]})}),r.jsx(Or,{products:v,servicePackages:w,highlightedPartType:h,highlightedProduct:k,onProductClick:oe,onPackageSelect:Z,isResearching:H,visible:Be,counterHeightPercent:i,hasVehicle:!!_}),q==="productDetail"&&D&&r.jsx(Yi,{product:D,onBack:ye,onAddToCart:B,onNavigateToProductPage:A}),q==="packageDetail"&&$&&r.jsx(Fn,{package:$,onBack:ye,onNavigateToProductPage:re=>{const Ce=v.find(ge=>ge.sku===re);Ce&&A&&A(Ce)}}),q==="products"&&r.jsx(Nn,{messages:c,input:d,setInput:u,isLoading:y,onSend:x,onKeyPress:b,onInputFocus:p,onInputBlur:g,chatEndRef:m,isMuted:S,onToggleMute:f,isSpeaking:j})]})},bs=({variant:t="inline",initialState:e="idle",showChat:s=!0,className:n="",backdropUrl:i,counterOverlayUrl:c,counterHeightPercent:d,defaultBobImage:u,verticalOffset:y=0,scale:x=100,sessionToken:b,embedded:p=!1})=>{const{callbacks:g}=tt(),[m,S]=a.useState(!1),{animationState:f,setAnimationState:j,getCurrentImage:v,getCurrentOffset:w,getCurrentScale:h,availableStates:k}=bn({isSpeaking:m}),{activeBackdrop:R}=mn(),[P,H]=a.useState([]),[B,A]=a.useState([]),[_,C]=a.useState(null),[E,N]=a.useState(null),[I,U]=a.useState(!1),F=pn({setAnimationState:j,manualMode:!1,onReadyToSpeak:()=>{console.log("[BobWidget] Ready to speak")},onStreamComplete:()=>{j(k.find(Q=>Q.includes("idle"))||"idle")},onResearchStart:()=>{U(!0)},onHighlightPart:Q=>{C(Q),setTimeout(()=>C(null),8e3)},onHighlightProduct:Q=>{N(Q),setTimeout(()=>N(null),8e3)},onAutoFetchComplete:()=>{U(!1)}});a.useEffect(()=>{S(F.isSpeaking)},[F.isSpeaking]),a.useEffect(()=>{const Q=g.onPartsFound,ue=g.onServicePackagesFound;return g.onPartsFound=fe=>{if(U(!1),!fe||fe.length===0){console.log("[Bob] Clearing products (empty array received)"),H([]),Q==null||Q(fe);return}const xe=fe.map((oe,ye)=>({id:oe.SKU||oe.sku||`part-${ye}`,name:oe["Part Product Type"]||oe.partslot_description||oe.name||"Unknown Part",brand:oe.Brand||oe.brand,price:oe["Metro Retail Price"]||oe.price||0,sku:oe.SKU||oe.sku,partNumber:oe["Part Number"]||oe.part_number,partslotDescription:oe["Part Product Type"]||oe.partslot_description,image_url:oe.image_url}));console.log("[Bob] Products mapped and setting state:",xe.length,"products"),H(xe),Q==null||Q(fe)},g.onServicePackagesFound=fe=>{if(!fe||fe.length===0){console.log("[Bob] Clearing service packages (empty array received)"),A([]),ue==null||ue(fe);return}A(fe),ue==null||ue(fe)},()=>{g.onPartsFound=Q,g.onServicePackagesFound=ue}},[g]);const J=i||(R==null?void 0:R.image_url),q=c||(R==null?void 0:R.counter_overlay_url)||void 0,O=d||(R==null?void 0:R.counter_height_percent)||12,D=v()||u||"",z=w(),$=h();if(t==="mobile"||t==="fullscreen")return r.jsx(Cn,{currentImage:D,animationState:f,backdropUrl:J,counterOverlayUrl:q,counterHeightPercent:O,bobOffset:z,bobScale:$,embedded:p,messages:F.messages,input:F.input,setInput:F.setInput,isLoading:F.isLoading,onSend:F.handleSend,onKeyPress:F.handleKeyPress,onInputFocus:F.handleInputFocus,onInputBlur:F.handleInputBlur,chatEndRef:F.chatEndRef,isMuted:F.isMuted,onToggleMute:F.toggleMute,isSpeaking:F.isSpeaking,products:P,servicePackages:B,highlightedPartType:_,highlightedProduct:E,onAddToCart:Q=>{var ue;return(ue=g.onAddToCart)==null?void 0:ue.call(g,{product_id:Q.id,product_name:Q.name,quantity:1,unit_price:Q.price,sku:Q.sku,brand:Q.brand})},onNavigateToProductPage:Q=>{var ue;return(ue=g.onNavigateToProductPage)==null?void 0:ue.call(g,Q)},onPackageSelect:Q=>console.log("[BobWidget] Package selected:",Q),isResearching:I,vehicle:F.identifiedVehicle});if(t==="inline"&&s)return r.jsx("div",{className:`relative w-full h-full ${n}`,children:r.jsx(Bn,{currentImage:D,animationState:f,backdropUrl:J,counterOverlayUrl:q,counterHeightPercent:O,bobOffset:z,bobScale:$,messages:F.messages,input:F.input,setInput:F.setInput,isLoading:F.isLoading,onSend:F.handleSend,onKeyPress:F.handleKeyPress,onInputFocus:F.handleInputFocus,onInputBlur:F.handleInputBlur,chatEndRef:F.chatEndRef,isMuted:F.isMuted,onToggleMute:F.toggleMute,isSpeaking:F.isSpeaking,products:P,servicePackages:B,highlightedPartType:_,highlightedProduct:E,onAddToCart:Q=>{var ue;return(ue=g.onAddToCart)==null?void 0:ue.call(g,{product_id:Q.id,product_name:Q.name,quantity:1,unit_price:Q.price,sku:Q.sku,brand:Q.brand})},onNavigateToProductPage:Q=>{var ue;return(ue=g.onNavigateToProductPage)==null?void 0:ue.call(g,Q)},onPackageSelect:Q=>console.log("[BobWidget] Package selected:",Q),isResearching:I,vehicle:F.identifiedVehicle})});const V={inline:"",floating:"fixed bottom-4 right-4 w-96 z-50 shadow-2xl rounded-lg overflow-hidden"};return r.jsxs("div",{className:`${V[t]||""} ${n}`,children:[D&&r.jsx(xn,{currentImage:D,animationState:f,backdropUrl:J,counterOverlayUrl:q,counterHeightPercent:O,verticalOffset:z,scale:$}),s&&r.jsx(Sn,{messages:F.messages,input:F.input,setInput:F.setInput,isLoading:F.isLoading,onSend:F.handleSend,onKeyPress:F.handleKeyPress,onInputFocus:F.handleInputFocus,onInputBlur:F.handleInputBlur,chatEndRef:F.chatEndRef,isMuted:F.isMuted,onToggleMute:F.toggleMute,isSpeaking:F.isSpeaking})]})},Xi=({bobConfig:t,hostApiConfig:e,hostContext:s,callbacks:n,variant:i="mobile",initialState:c,showChat:d,className:u,backdropUrl:y,counterOverlayUrl:x,counterHeightPercent:b,defaultBobImage:p,verticalOffset:g,scale:m,ga4Config:S,analyticsEnabled:f=!0,bottomOffset:j=0,zIndexBase:v=50,embedded:w=!1})=>(a.useEffect(()=>{console.log("[BobWidget] Initialized",{version:et,variant:i,bottomOffset:j,zIndexBase:v,bobConfigUrl:t.supabaseUrl,hostApiBaseUrl:e.baseUrl,analyticsEnabled:f})},[i,j,v,t.supabaseUrl,e.baseUrl,f]),r.jsx("div",{className:"bob-widget-root",style:{width:"100%",height:"100%"},children:r.jsx(ds,{bobConfig:t,hostApiConfig:e,hostContext:s,callbacks:n,ga4Config:S,analyticsEnabled:f,bottomOffset:j,zIndexBase:v,children:r.jsx(bs,{variant:i,initialState:c,showChat:d,className:u,backdropUrl:y,counterOverlayUrl:x,counterHeightPercent:b,defaultBobImage:p,verticalOffset:g,scale:m,embedded:w})})}));function Ji(t){return t<640?"mobile":t<1024?"tablet":"desktop"}function Zi(){const t=[];if(typeof window>"u")return t;const e=document.querySelector(".bob-widget-root");if(!e)return t.push("bob-widget-root not found in DOM"),t;const s=window.getComputedStyle(e),n=e.parentElement;return n&&window.getComputedStyle(n).overflow==="hidden"&&t.push("Parent has overflow:hidden - may clip Bob"),s.transform!=="none"&&s.transform!=="matrix(1, 0, 0, 1, 0, 0)"&&t.push(`Unexpected transform on root: ${s.transform}`),s.isolation!=="isolate"&&t.push("Isolation not properly set"),t}const In=({partnerConfig:t,sessionToken:e})=>{const[s,n]=a.useState(null),[i,c]=a.useState([]),[d,u]=a.useState(!1);if(a.useEffect(()=>{const x=()=>{var g;const b=window.innerWidth,p=window.innerHeight;n({viewport:{width:b,height:p,deviceType:Ji(b)},origin:window.location.origin,originAllowed:((g=t==null?void 0:t.allowed_origins)==null?void 0:g.some(m=>m===window.location.origin||m.includes("*")))??!1,userAgent:navigator.userAgent.slice(0,50)+"...",timestamp:new Date().toISOString()}),c(Zi())};return x(),window.addEventListener("resize",x),()=>window.removeEventListener("resize",x)},[t]),!s)return null;const y=({ok:x,label:b})=>r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"4px",fontSize:"11px",fontWeight:500,background:x?"rgba(34, 197, 94, 0.2)":"rgba(239, 68, 68, 0.2)",color:x?"#22c55e":"#ef4444"},children:[x?"✓":"✗"," ",b]});return r.jsxs("div",{style:{position:"fixed",top:"8px",right:"8px",zIndex:99999,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace',fontSize:"11px",lineHeight:1.4},children:[r.jsx("button",{onClick:()=>u(!d),style:{position:"absolute",top:0,right:0,width:"24px",height:"24px",background:"rgba(0, 0, 0, 0.8)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"4px",color:"#fff",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1},children:d?"🔍":"✕"}),!d&&r.jsxs("div",{style:{background:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"8px",padding:"12px",color:"#fff",maxWidth:"320px",backdropFilter:"blur(8px)"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"12px",paddingBottom:"8px",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:[r.jsx("span",{style:{fontSize:"14px"},children:"🔧"}),r.jsxs("span",{style:{fontWeight:600},children:["Bob Debug v",et]})]}),r.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px",marginBottom:"12px"},children:[r.jsx(y,{ok:!!t,label:`Partner: ${(t==null?void 0:t.partner_code)||"none"}`}),r.jsx(y,{ok:!!e,label:e?"Session":"No Session"}),r.jsx(y,{ok:s.originAllowed,label:"Origin"})]}),r.jsxs("div",{style:{display:"grid",gap:"6px"},children:[r.jsx(Dt,{label:"Viewport",value:`${s.viewport.width}×${s.viewport.height} (${s.viewport.deviceType})`}),r.jsx(Dt,{label:"Origin",value:s.origin}),r.jsx(Dt,{label:"Bottom Offset",value:`${(t==null?void 0:t.default_bottom_offset)??0}px`}),r.jsx(Dt,{label:"Z-Index Base",value:`${(t==null?void 0:t.default_z_index_base)??50}`}),r.jsx(Dt,{label:"Blur",value:`${(t==null?void 0:t.backdrop_blur_intensity)??8}px`}),r.jsx(Dt,{label:"Overlay",value:`${(((t==null?void 0:t.backdrop_overlay_opacity)??.15)*100).toFixed(0)}%`})]}),(t==null?void 0:t.feature_flags)&&r.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[r.jsx("div",{style:{color:"rgba(255,255,255,0.5)",marginBottom:"4px"},children:"Features:"}),r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:Object.entries(t.feature_flags).map(([x,b])=>r.jsx(y,{ok:!!b,label:x.replace(/([A-Z])/g," $1").trim()},x))})]}),i.length>0&&r.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[r.jsx("div",{style:{color:"#ef4444",marginBottom:"4px"},children:"⚠️ CSS Conflicts:"}),i.map((x,b)=>r.jsxs("div",{style:{color:"#fca5a5",fontSize:"10px"},children:["• ",x]},b))]}),r.jsx("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",color:"rgba(255,255,255,0.4)",fontSize:"10px"},children:s.timestamp})]})]})},Dt=({label:t,value:e})=>r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px"},children:[r.jsxs("span",{style:{color:"rgba(255,255,255,0.5)"},children:[t,":"]}),r.jsx("span",{style:{color:"#fff",textAlign:"right",wordBreak:"break-all"},children:e})]}),Ds="https://gjoguxzstsihhxvdgpto.supabase.co",Ws="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imdqb2d1eHpzdHNpaGh4dmRncHRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjM5MzgyODEsImV4cCI6MjA3OTUxNDI4MX0.detu4TKB7RjC6l6CrVaPYoi0Hhz2asDt6zxNx1cdzq8";function ea(t,e){return t.some(s=>{if(s.includes("*")){const n=s.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}return s===e})}function On(t){const[e,s]=a.useState(null),[n,i]=a.useState(!0),[c,d]=a.useState(null),[u,y]=a.useState(!1),[x,b]=a.useState(null),p=a.useCallback(async()=>{if(!t){i(!1),d(new Error("Partner code is required"));return}i(!0),d(null);try{const g=Hr.createClient(Ds,Ws);console.log(`[BobWidget] Loading partner config for: ${t}`);const{data:m,error:S}=await g.from("bob_partners").select("*").eq("partner_code",t).eq("is_active",!0).maybeSingle();if(S)throw new Error(`Failed to load partner config: ${S.message}`);if(!m)throw new Error(`Partner "${t}" not found or inactive`);const f=m,j=typeof window<"u"?window.location.origin:"",v=ea(f.allowed_origins||[],j);!v&&j&&(console.warn(`[BobWidget] Origin "${j}" not in allowed origins for ${t}`),console.warn("[BobWidget] Allowed origins:",f.allowed_origins));const w=Hr.createClient(f.bob_supabase_url||Ds,f.bob_supabase_key||Ws);console.log("[BobWidget] Partner config loaded:",{partner:f.partner_code,displayName:f.display_name,bottomOffset:f.default_bottom_offset,blurIntensity:f.backdrop_blur_intensity,features:f.feature_flags,originAllowed:v}),s(f),y(v),b(w)}catch(g){const m=g instanceof Error?g:new Error("Unknown error loading partner config");console.error("[BobWidget] Partner config error:",m),d(m)}finally{i(!1)}},[t]);return a.useEffect(()=>{p()},[p]),{config:e,isLoading:n,error:c,isOriginAllowed:u,supabaseClient:x,reload:p}}function Pn(t,e,s){return t!=null&&t.feature_flags?t.feature_flags[e]??s:s}const ta=()=>r.jsxs("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #0a1628 0%, #0f2137 100%)"},children:[r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[r.jsx("div",{style:{width:"48px",height:"48px",border:"4px solid rgba(0, 102, 204, 0.3)",borderTopColor:"#0066cc",borderRadius:"50%",animation:"spin 1s linear infinite"}}),r.jsx("span",{style:{color:"rgba(255,255,255,0.7)",fontSize:"14px"},children:"Loading Bob..."})]}),r.jsx("style",{children:`
30
+ <%s key={someKey} {...props} />`,zs,ct,Va,ct),nt[ct+zs]=!0}}return v===s?Ws(le):Ms(le),le}}function xt(v,R,D){return Fr(v,R,D,!0)}function Dr(v,R,D){return Fr(v,R,D,!1)}var Lr=Dr,qs=xt;Mr.Fragment=s,Mr.jsx=Lr,Mr.jsxs=qs}()),Mr}process.env.NODE_ENV==="production"?rn.exports=Ya():rn.exports=Xa();var o=rn.exports;function Is(t,e){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(r[s[n]]=t[s[n]]);return r}function Za(t,e,r,s){function n(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function l(d){try{u(s.next(d))}catch(p){a(p)}}function c(d){try{u(s.throw(d))}catch(p){a(p)}}function u(d){d.done?i(d.value):n(d.value).then(l,c)}u((s=s.apply(t,e||[])).next())})}const eo=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class An extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}}class to extends An{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Vn extends An{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Gn extends An{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var sn;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(sn||(sn={}));class ro{constructor(e,{headers:r={},customFetch:s,region:n=sn.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=eo(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Za(this,arguments,void 0,function*(r,s={}){var n;let i,a;try{const{headers:l,method:c,body:u,signal:d,timeout:p}=s;let f={},{region:h}=s;h||(h=this.region);const m=new URL(`${this.url}/${r}`);h&&h!=="any"&&(f["x-region"]=h,m.searchParams.set("forceFunctionRegion",h));let g;u&&(l&&!Object.prototype.hasOwnProperty.call(l,"Content-Type")||!l)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",g=u):typeof u=="string"?(f["Content-Type"]="text/plain",g=u):typeof FormData<"u"&&u instanceof FormData?g=u:(f["Content-Type"]="application/json",g=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?g=JSON.stringify(u):g=u;let _=d;p&&(a=new AbortController,i=setTimeout(()=>a.abort(),p),d?(_=a.signal,d.addEventListener("abort",()=>a.abort())):_=a.signal);const w=yield this.fetch(m.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),l),body:g,signal:_}).catch(j=>{throw new to(j)}),k=w.headers.get("x-relay-error");if(k&&k==="true")throw new Vn(w);if(!w.ok)throw new Gn(w);let b=((n=w.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),S;return b==="application/json"?S=yield w.json():b==="application/octet-stream"||b==="application/pdf"?S=yield w.blob():b==="text/event-stream"?S=w:b==="multipart/form-data"?S=yield w.formData():S=yield w.text(),{data:S,error:null,response:w}}catch(l){return{data:null,error:l,response:l instanceof Gn||l instanceof Vn?l.context:void 0}}finally{i&&clearTimeout(i)}})}}var so=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},no=class{constructor(t){var e,r;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const s=this.fetch;let n=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let a=null,l=null,c=null,u=i.status,d=i.statusText;if(i.ok){var p,f;if(r.method!=="HEAD"){var h;const w=await i.text();w===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((h=r.headers.get("Accept"))===null||h===void 0)&&h.includes("application/vnd.pgrst.plan+text"))?l=w:l=JSON.parse(w))}const g=(p=r.headers.get("Prefer"))===null||p===void 0?void 0:p.match(/count=(exact|planned|estimated)/),_=(f=i.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");g&&_&&_.length>1&&(c=parseInt(_[1])),r.isMaybeSingle&&r.method==="GET"&&Array.isArray(l)&&(l.length>1?(a={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,c=null,u=406,d="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{var m;const g=await i.text();try{a=JSON.parse(g),Array.isArray(a)&&i.status===404&&(l=[],a=null,u=200,d="OK")}catch{i.status===404&&g===""?(u=204,d="No Content"):a={message:g}}if(a&&r.isMaybeSingle&&(!(a==null||(m=a.details)===null||m===void 0)&&m.includes("0 rows"))&&(a=null,u=200,d="OK"),a&&r.shouldThrowOnError)throw new so(a)}return{error:a,data:l,count:c,status:u,statusText:d}});return this.shouldThrowOnError||(n=n.catch(i=>{var a;let l="";const c=i==null?void 0:i.cause;if(c){var u,d,p,f;const m=(u=c==null?void 0:c.message)!==null&&u!==void 0?u:"",g=(d=c==null?void 0:c.code)!==null&&d!==void 0?d:"";l=`${(p=i==null?void 0:i.name)!==null&&p!==void 0?p:"FetchError"}: ${i==null?void 0:i.message}`,l+=`
31
+
32
+ Caused by: ${(f=c==null?void 0:c.name)!==null&&f!==void 0?f:"Error"}: ${m}`,g&&(l+=` (${g})`),c!=null&&c.stack&&(l+=`
33
+ ${c.stack}`)}else{var h;l=(h=i==null?void 0:i.stack)!==null&&h!==void 0?h:""}return{error:{message:`${(a=i==null?void 0:i.name)!==null&&a!==void 0?a:"FetchError"}: ${i==null?void 0:i.message}`,details:l,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},io=class extends no{select(t){let e=!1;const r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){const i=n?`${n}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${a?`${a},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){const n=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var a;const l=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${l};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};const Jn=new RegExp("[,()]");var gr=class extends io{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&Jn.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&Jn.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");const i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${i}.${e}`),this}match(t){return Object.entries(t).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},ao=class{constructor(t,{headers:e={},schema:r,fetch:s}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:r=!1,count:s}=e??{},n=r?"HEAD":"GET";let i=!1;const a=(t??"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join(""),{url:l,headers:c}=this.cloneRequestState();return l.searchParams.set("select",a),s&&c.append("Prefer",`count=${s}`),new gr({method:n,url:l,headers:c,schema:this.schema,fetch:this.fetch})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;const n="POST",{url:i,headers:a}=this.cloneRequestState();if(e&&a.append("Prefer",`count=${e}`),r||a.append("Prefer","missing=default"),Array.isArray(t)){const l=t.reduce((c,u)=>c.concat(Object.keys(u)),[]);if(l.length>0){const c=[...new Set(l)].map(u=>`"${u}"`);i.searchParams.set("columns",c.join(","))}}return new gr({method:n,url:i,headers:a,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const a="POST",{url:l,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&l.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),n||c.append("Prefer","missing=default"),Array.isArray(t)){const u=t.reduce((d,p)=>d.concat(Object.keys(p)),[]);if(u.length>0){const d=[...new Set(u)].map(p=>`"${p}"`);l.searchParams.set("columns",d.join(","))}}return new gr({method:a,url:l,headers:c,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}update(t,{count:e}={}){var r;const s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new gr({method:s,url:n,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch})}delete({count:t}={}){var e;const r="DELETE",{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new gr({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch})}},oo=class Vi{constructor(e,{headers:r={},schema:s,fetch:n}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.fetch=n}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new ao(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new Vi(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var a;let l;const c=new URL(`${this.url}/rpc/${e}`);let u;const d=h=>h!==null&&typeof h=="object"&&(!Array.isArray(h)||h.some(d)),p=s&&Object.values(r).some(d);p?(l="POST",u=r):s||n?(l=s?"HEAD":"GET",Object.entries(r).filter(([h,m])=>m!==void 0).map(([h,m])=>[h,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([h,m])=>{c.searchParams.append(h,m)})):(l="POST",u=r);const f=new Headers(this.headers);return p?f.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&f.set("Prefer",`count=${i}`),new gr({method:l,url:c,headers:f,schema:this.schemaName,body:u,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}};class lo{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const r=globalThis.process;if(r){const s=r.versions;if(s&&s.node){const n=s.node,i=parseInt(n.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
34
+ import ws from "ws"
35
+ new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
36
+
37
+ Suggested solution: ${e.workaround}`),new Error(r)}static createWebSocket(e,r){const s=this.getWebSocketConstructor();return new s(e,r)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const co="2.93.2",uo=`realtime-js/${co}`,ho="1.0.0",Gi="2.0.0",Qn=Gi,nn=1e4,fo=1e3,po=100;var St;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(St||(St={}));var Ee;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(Ee||(Ee={}));var rt;(function(t){t.close="phx_close",t.error="phx_error",t.join="phx_join",t.reply="phx_reply",t.leave="phx_leave",t.access_token="access_token"})(rt||(rt={}));var an;(function(t){t.websocket="websocket"})(an||(an={}));var Ht;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(Ht||(Ht={}));class go{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},a=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,a)}_encodeUserBroadcastPush(e,r,s){var n,i;const a=e.topic,l=(n=e.ref)!==null&&n!==void 0?n:"",c=(i=e.join_ref)!==null&&i!==void 0?i:"",u=e.payload.event,d=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},p=Object.keys(d).length===0?"":JSON.stringify(d);if(c.length>255)throw new Error(`joinRef length ${c.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`ref length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`topic length ${a.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(p.length>255)throw new Error(`metadata length ${p.length} exceeds maximum of 255`);const f=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+l.length+a.length+u.length+p.length,h=new ArrayBuffer(this.HEADER_LENGTH+f);let m=new DataView(h),g=0;m.setUint8(g++,this.KINDS.userBroadcastPush),m.setUint8(g++,c.length),m.setUint8(g++,l.length),m.setUint8(g++,a.length),m.setUint8(g++,u.length),m.setUint8(g++,p.length),m.setUint8(g++,r),Array.from(c,w=>m.setUint8(g++,w.charCodeAt(0))),Array.from(l,w=>m.setUint8(g++,w.charCodeAt(0))),Array.from(a,w=>m.setUint8(g++,w.charCodeAt(0))),Array.from(u,w=>m.setUint8(g++,w.charCodeAt(0))),Array.from(p,w=>m.setUint8(g++,w.charCodeAt(0)));var _=new Uint8Array(h.byteLength+s.byteLength);return _.set(new Uint8Array(h),0),_.set(new Uint8Array(s),h.byteLength),_.buffer}decode(e,r){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return r(s)}if(typeof e=="string"){const s=JSON.parse(e),[n,i,a,l,c]=s;return r({join_ref:n,ref:i,topic:a,event:l,payload:c})}return r({})}_binaryDecode(e){const r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;switch(s){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,n)}}_decodeUserBroadcast(e,r,s){const n=r.getUint8(1),i=r.getUint8(2),a=r.getUint8(3),l=r.getUint8(4);let c=this.HEADER_LENGTH+4;const u=s.decode(e.slice(c,c+n));c=c+n;const d=s.decode(e.slice(c,c+i));c=c+i;const p=s.decode(e.slice(c,c+a));c=c+a;const f=e.slice(c,e.byteLength),h=l===this.JSON_ENCODING?JSON.parse(s.decode(f)):f,m={type:this.BROADCAST_EVENT,event:d,payload:h};return a>0&&(m.meta=JSON.parse(p)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:m}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e==null?void 0:e.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>r.includes(s)))}}class Ji{constructor(e,r){this.callback=e,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=r}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var pe;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(pe||(pe={}));const Yn=(t,e,r={})=>{var s;const n=(s=r.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((i,a)=>(i[a]=bo(a,t,e,n),i),{}):{}},bo=(t,e,r,s)=>{const n=e.find(l=>l.name===t),i=n==null?void 0:n.type,a=r[t];return i&&!s.includes(i)?Qi(i,a):on(a)},Qi=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return wo(e,r)}switch(t){case pe.bool:return mo(e);case pe.float4:case pe.float8:case pe.int2:case pe.int4:case pe.int8:case pe.numeric:case pe.oid:return yo(e);case pe.json:case pe.jsonb:return vo(e);case pe.timestamp:return xo(e);case pe.abstime:case pe.date:case pe.daterange:case pe.int4range:case pe.int8range:case pe.money:case pe.reltime:case pe.text:case pe.time:case pe.timestamptz:case pe.timetz:case pe.tsrange:case pe.tstzrange:return on(e);default:return on(e)}},on=t=>t,mo=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},yo=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},vo=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},wo=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let i;const a=t.slice(1,r);try{i=JSON.parse("["+a+"]")}catch{i=a?a.split(","):[]}return i.map(l=>Qi(e,l))}return t},xo=t=>typeof t=="string"?t.replace(" ","T"):t,Yi=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};class Ks{constructor(e,r,s={},n=nn){this.channel=e,this.event=r,this.payload=s,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,r){var s;return this._hasReceived(e)&&r((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:r})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:r}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var Xn;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Xn||(Xn={}));class Gr{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=(r==null?void 0:r.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},n=>{const{onJoin:i,onLeave:a,onSync:l}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Gr.syncState(this.state,n,i,a),this.pendingDiffs.forEach(c=>{this.state=Gr.syncDiff(this.state,c,i,a)}),this.pendingDiffs=[],l()}),this.channel._on(s.diff,{},n=>{const{onJoin:i,onLeave:a,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=Gr.syncDiff(this.state,n,i,a),l())}),this.onJoin((n,i,a)=>{this.channel._trigger("presence",{event:"join",key:n,currentPresences:i,newPresences:a})}),this.onLeave((n,i,a)=>{this.channel._trigger("presence",{event:"leave",key:n,currentPresences:i,leftPresences:a})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,s,n){const i=this.cloneDeep(e),a=this.transformState(r),l={},c={};return this.map(i,(u,d)=>{a[u]||(c[u]=d)}),this.map(a,(u,d)=>{const p=i[u];if(p){const f=d.map(_=>_.presence_ref),h=p.map(_=>_.presence_ref),m=d.filter(_=>h.indexOf(_.presence_ref)<0),g=p.filter(_=>f.indexOf(_.presence_ref)<0);m.length>0&&(l[u]=m),g.length>0&&(c[u]=g)}else l[u]=d}),this.syncDiff(i,{joins:l,leaves:c},s,n)}static syncDiff(e,r,s,n){const{joins:i,leaves:a}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return s||(s=()=>{}),n||(n=()=>{}),this.map(i,(l,c)=>{var u;const d=(u=e[l])!==null&&u!==void 0?u:[];if(e[l]=this.cloneDeep(c),d.length>0){const p=e[l].map(h=>h.presence_ref),f=d.filter(h=>p.indexOf(h.presence_ref)<0);e[l].unshift(...f)}s(l,d,c)}),this.map(a,(l,c)=>{let u=e[l];if(!u)return;const d=c.map(p=>p.presence_ref);u=u.filter(p=>d.indexOf(p.presence_ref)<0),e[l]=u,n(l,u,c),u.length===0&&delete e[l]}),e}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const n=e[s];return"metas"in n?r[s]=n.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[s]=n,r},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var Zn;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Zn||(Zn={}));var Jr;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Jr||(Jr={}));var dt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(dt||(dt={}));class yr{constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.state=Ee.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.timeout=this.socket.timeout,this.joinPush=new Ks(this,rt.join,this.params,this.timeout),this.rejoinTimer=new Ji(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Ee.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=Ee.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=Ee.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Ee.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=Ee.errored,this.rejoinTimer.scheduleTimeout())}),this._on(rt.reply,{},(a,l)=>{this._trigger(this._replyEventName(l),a)}),this.presence=new Gr(this),this.broadcastEndpointURL=Yi(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var s,n,i;if(this.socket.isConnected()||this.socket.connect(),this.state==Ee.closed){const{config:{broadcast:a,presence:l,private:c}}=this.params,u=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(h=>h.filter))!==null&&n!==void 0?n:[],d=!!this.bindings[Jr.PRESENCE]&&this.bindings[Jr.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,p={},f={broadcast:a,presence:Object.assign(Object.assign({},l),{enabled:d}),postgres_changes:u,private:c};this.socket.accessTokenValue&&(p.access_token=this.socket.accessTokenValue),this._onError(h=>e==null?void 0:e(dt.CHANNEL_ERROR,h)),this._onClose(()=>e==null?void 0:e(dt.CLOSED)),this.updateJoinPayload(Object.assign({config:f},p)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:h})=>{var m;if(this.socket._isManualToken()||this.socket.setAuth(),h===void 0){e==null||e(dt.SUBSCRIBED);return}else{const g=this.bindings.postgres_changes,_=(m=g==null?void 0:g.length)!==null&&m!==void 0?m:0,w=[];for(let k=0;k<_;k++){const b=g[k],{filter:{event:S,schema:j,table:C,filter:F}}=b,O=h&&h[k];if(O&&O.event===S&&yr.isFilterValueEqual(O.schema,j)&&yr.isFilterValueEqual(O.table,C)&&yr.isFilterValueEqual(O.filter,F))w.push(Object.assign(Object.assign({},b),{id:O.id}));else{this.unsubscribe(),this.state=Ee.errored,e==null||e(dt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=w,e&&e(dt.SUBSCRIBED);return}}).receive("error",h=>{this.state=Ee.errored,e==null||e(dt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(dt.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){return this.state===Ee.joined&&e===Jr.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,r,s)}async httpSend(e,r,s={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");const i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(l.status===202)return{success:!0};let c=l.statusText;try{const u=await l.json();c=u.error||u.message||c}catch{}return Promise.reject(new Error(c))}async send(e,r={}){var s,n;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:a}=e,l={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(l.Authorization=`Bearer ${this.socket.accessTokenValue}`);const c={method:"POST",headers:l,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:a,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,l,c;const u=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(l=(a=this.params)===null||a===void 0?void 0:a.config)===null||l===void 0?void 0:l.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=Ee.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(rt.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(n=>{s=new Ks(this,rt.leave,{},e),s.receive("ok",()=>{r(),n("ok")}).receive("timeout",()=>{r(),n("timed out")}).receive("error",()=>{n("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{s==null||s.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Ee.closed,this.bindings={}}async _fetchWithTimeout(e,r,s){const n=new AbortController,i=setTimeout(()=>n.abort(),s),a=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(i),a}_push(e,r,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new Ks(this,e,r,s);return this._canPush()?n.send():this._addToPushBuffer(n),n}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>po){const r=this.pushBuffer.shift();r&&(r.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${r.event}`,r.payload))}}_onMessage(e,r,s){return r}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,r,s){var n,i;const a=e.toLocaleLowerCase(),{close:l,error:c,leave:u,join:d}=rt;if(s&&[l,c,u,d].indexOf(a)>=0&&s!==this._joinRef())return;let f=this._onMessage(a,r,s);if(r&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(a)?(n=this.bindings.postgres_changes)===null||n===void 0||n.filter(h=>{var m,g,_;return((m=h.filter)===null||m===void 0?void 0:m.event)==="*"||((_=(g=h.filter)===null||g===void 0?void 0:g.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===a}).map(h=>h.callback(f,s)):(i=this.bindings[a])===null||i===void 0||i.filter(h=>{var m,g,_,w,k,b;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in h){const S=h.id,j=(m=h.filter)===null||m===void 0?void 0:m.event;return S&&((g=r.ids)===null||g===void 0?void 0:g.includes(S))&&(j==="*"||(j==null?void 0:j.toLocaleLowerCase())===((_=r.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{const S=(k=(w=h==null?void 0:h.filter)===null||w===void 0?void 0:w.event)===null||k===void 0?void 0:k.toLocaleLowerCase();return S==="*"||S===((b=r==null?void 0:r.event)===null||b===void 0?void 0:b.toLocaleLowerCase())}else return h.type.toLocaleLowerCase()===a}).map(h=>{if(typeof f=="object"&&"ids"in f){const m=f.data,{schema:g,table:_,commit_timestamp:w,type:k,errors:b}=m;f=Object.assign(Object.assign({},{schema:g,table:_,commit_timestamp:w,eventType:k,new:{},old:{},errors:b}),this._getPayloadRecords(m))}h.callback(f,s)})}_isClosed(){return this.state===Ee.closed}_isJoined(){return this.state===Ee.joined}_isJoining(){return this.state===Ee.joining}_isLeaving(){return this.state===Ee.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,r,s){const n=e.toLocaleLowerCase(),i={type:n,filter:r,callback:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this}_off(e,r){const s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(n=>{var i;return!(((i=n.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===s&&yr.isEqual(n.filter,r))})),this}static isEqual(e,r){if(Object.keys(e).length!==Object.keys(r).length)return!1;for(const s in e)if(e[s]!==r[s])return!1;return!0}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(rt.close,{},e)}_onError(e){this._on(rt.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Ee.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Yn(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Yn(e.columns,e.old_record)),r}}const Vs=()=>{},ys={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},_o=[1e3,2e3,5e3,1e4],ko=1e4,So=`
38
+ addEventListener("message", (e) => {
39
+ if (e.data.event === "start") {
40
+ setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
41
+ }
42
+ });`;class Eo{constructor(e,r){var s;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=nn,this.transport=null,this.heartbeatIntervalMs=ys.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Vs,this.ref=0,this.reconnectTimer=null,this.vsn=Qn,this.logger=Vs,this.conn=null,this.sendBuffer=[],this.serializer=new go,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=n=>n?(...i)=>n(...i):(...i)=>fetch(...i),!(!((s=r==null?void 0:r.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey,this.endPoint=`${e}/${an.websocket}`,this.httpEndpoint=Yi(e),this._initializeOptions(r),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(r==null?void 0:r.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=lo.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const r=e.message;throw r.includes("Node.js")?new Error(`${r}
43
+
44
+ To use Realtime in Node.js, you need to provide a WebSocket implementation:
45
+
46
+ Option 1: Use Node.js 22+ which has native WebSocket support
47
+ Option 2: Install and provide the "ws" package:
48
+
49
+ npm install ws
50
+
51
+ import ws from "ws"
52
+ const client = new RealtimeClient(url, {
53
+ ...options,
54
+ transport: ws
55
+ })`):new Error(`WebSocket not available: ${r}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,r){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const s=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(s),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,r??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const e=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,r,s){this.logger(e,r,s)}connectionState(){switch(this.conn&&this.conn.readyState){case St.connecting:return Ht.Connecting;case St.open:return Ht.Open;case St.closing:return Ht.Closing;default:return Ht.Closed}}isConnected(){return this.connectionState()===Ht.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,r={config:{}}){const s=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===s);if(n)return n;{const i=new yr(`realtime:${e}`,r,this);return this.channels.push(i),i}}push(e){const{topic:r,event:s,payload:n,ref:i}=e,a=()=>{this.encode(e,l=>{var c;(c=this.conn)===null||c===void 0||c.send(l)})};this.log("push",`${r} ${s} (${i})`,n),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(r){this.log("error","error in heartbeat callback",r)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(r){this.log("error","error in heartbeat callback",r)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(fo,"heartbeat timeout"),setTimeout(()=>{var r;this.isConnected()||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout()},ys.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(r){this.log("error","error in heartbeat callback",r)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let r=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${e}"`),r.unsubscribe())}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,r=>{if(r.topic==="phoenix"&&r.event==="phx_reply"&&r.ref&&r.ref===this.pendingHeartbeatRef){const u=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(r.payload.status==="ok"?"ok":"error",u)}catch(d){this.log("error","error in heartbeat callback",d)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:s,event:n,payload:i,ref:a}=r,l=a?`(${a})`:"",c=i.status||"";this.log("receive",`${c} ${s} ${n} ${l}`.trim(),i),this.channels.filter(u=>u._isMember(s)).forEach(u=>u._trigger(n,i,a)),this._triggerStateCallbacks("message",r)})}_clearTimer(e){var r;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((r=this.reconnectTimer)===null||r===void 0||r.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===St.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===St.open||this.conn.readyState===St.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(r=>{this.log("error","error waiting for auth on connect",r),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var r;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(r){this.log("error","error in heartbeat callback",r)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(rt.error))}_appendParams(e,r){if(Object.keys(r).length===0)return e;const s=e.match(/\?/)?"&":"?",n=new URLSearchParams(r);return`${e}${s}${n}`}_workerObjectUrl(e){let r;if(e)r=e;else{const s=new Blob([So],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_setConnectionState(e,r=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=r)}async _performAuth(e=null){let r,s=!1;if(e)r=e,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{const i={access_token:r,version:uo};r&&n.updateJoinPayload(i),n.joinedOnce&&n._isJoined()&&n._push(rt.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_triggerStateCallbacks(e,r){try{this.stateChangeCallbacks[e].forEach(s=>{try{s(r)}catch(n){this.log("error",`error in ${e} callback`,n)}})}catch(s){this.log("error",`error triggering ${e} callbacks`,s)}}_setupReconnectionTimer(){this.reconnectTimer=new Ji(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},ys.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var r,s,n,i,a,l,c,u,d,p,f,h;switch(this.transport=(r=e==null?void 0:e.transport)!==null&&r!==void 0?r:null,this.timeout=(s=e==null?void 0:e.timeout)!==null&&s!==void 0?s:nn,this.heartbeatIntervalMs=(n=e==null?void 0:e.heartbeatIntervalMs)!==null&&n!==void 0?n:ys.HEARTBEAT_INTERVAL,this.worker=(i=e==null?void 0:e.worker)!==null&&i!==void 0?i:!1,this.accessToken=(a=e==null?void 0:e.accessToken)!==null&&a!==void 0?a:null,this.heartbeatCallback=(l=e==null?void 0:e.heartbeatCallback)!==null&&l!==void 0?l:Vs,this.vsn=(c=e==null?void 0:e.vsn)!==null&&c!==void 0?c:Qn,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(u=e==null?void 0:e.reconnectAfterMs)!==null&&u!==void 0?u:m=>_o[m-1]||ko,this.vsn){case ho:this.encode=(d=e==null?void 0:e.encode)!==null&&d!==void 0?d:(m,g)=>g(JSON.stringify(m)),this.decode=(p=e==null?void 0:e.decode)!==null&&p!==void 0?p:(m,g)=>g(JSON.parse(m));break;case Gi:this.encode=(f=e==null?void 0:e.encode)!==null&&f!==void 0?f:this.serializer.encode.bind(this.serializer),this.decode=(h=e==null?void 0:e.decode)!==null&&h!==void 0?h:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}}var Yr=class extends Error{constructor(t,e){var r;super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&((r=e.icebergType)==null?void 0:r.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function jo(t,e,r){const s=new URL(e,t);if(r)for(const[n,i]of Object.entries(r))i!==void 0&&s.searchParams.set(n,i);return s.toString()}async function To(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Ro(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const l=jo(t.baseUrl,s,n),c=await To(t.auth),u=await e(l,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...c,...a},body:i?JSON.stringify(i):void 0}),d=await u.text(),p=(u.headers.get("content-type")||"").includes("application/json"),f=p&&d?JSON.parse(d):d;if(!u.ok){const h=p?f:void 0,m=h==null?void 0:h.error;throw new Yr((m==null?void 0:m.message)??`Request failed with status ${u.status}`,{status:u.status,icebergType:m==null?void 0:m.type,icebergCode:m==null?void 0:m.code,details:h})}return{status:u.status,headers:u.headers,data:f}}}}function vs(t){return t.join("")}var Co=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:vs(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(t,e){const r={namespace:t.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${vs(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${vs(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${vs(t.namespace)}`}),!0}catch(e){if(e instanceof Yr&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof Yr&&r.status===409)return;throw r}}};function lr(t){return t.join("")}var Oo=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${lr(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${lr(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${lr(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${lr(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String((e==null?void 0:e.purge)??!1)}})}async loadTable(t){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${lr(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${lr(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof Yr&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof Yr&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Ao=class{constructor(t){var s;let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Ro({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(s=t.accessDelegation)==null?void 0:s.join(","),this.namespaceOps=new Co(this.client,e),this.tableOps=new Oo(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}},Ps=class extends Error{constructor(t,e="storage",r,s){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}};function Ns(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var ws=class extends Ps{constructor(t,e,r,s="storage"){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},Xi=class extends Ps{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};const Io=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Po=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ln=t=>{if(Array.isArray(t))return t.map(r=>ln(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,s])=>{const n=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[n]=ln(s)}),e},No=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function Xr(t){"@babel/helpers - typeof";return Xr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Xr(t)}function Bo(t,e){if(Xr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Xr(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function $o(t){var e=Bo(t,"string");return Xr(e)=="symbol"?e:e+""}function Fo(t,e,r){return(e=$o(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ei(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function ee(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?ei(Object(r),!0).forEach(function(s){Fo(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):ei(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const ti=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},Do=async(t,e,r,s)=>{if(t&&typeof t=="object"&&"status"in t&&"ok"in t&&typeof t.status=="number"&&!(r!=null&&r.noResolveJson)){const n=t,i=n.status||500;if(typeof n.json=="function")n.json().then(a=>{const l=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||i+"";e(new ws(ti(a),i,l,s))}).catch(()=>{if(s==="vectors"){const a=i+"";e(new ws(n.statusText||`HTTP ${i} error`,i,a,s))}else{const a=i+"";e(new ws(n.statusText||`HTTP ${i} error`,i,a,s))}});else{const a=i+"";e(new ws(n.statusText||`HTTP ${i} error`,i,a,s))}}else e(new Xi(ti(t),t,s))},Lo=(t,e,r,s)=>{const n={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"||t==="HEAD"||!s?ee(ee({},n),r):(Po(s)?(n.headers=ee({"Content-Type":"application/json"},e==null?void 0:e.headers),n.body=JSON.stringify(s)):n.body=s,e!=null&&e.duplex&&(n.duplex=e.duplex),ee(ee({},n),r))};async function Wr(t,e,r,s,n,i,a){return new Promise((l,c)=>{t(r,Lo(e,s,n,i)).then(u=>{if(!u.ok)throw u;if(s!=null&&s.noResolveJson)return u;if(a==="vectors"){const d=u.headers.get("content-type");if(!d||!d.includes("application/json"))return{}}return u.json()}).then(u=>l(u)).catch(u=>Do(u,c,s,a))})}function Uo(t="storage"){return{get:async(e,r,s,n)=>Wr(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>Wr(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>Wr(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>Wr(e,"HEAD",r,ee(ee({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>Wr(e,"DELETE",r,n,i,s,t)}}const Mo=Uo("storage"),{get:Zr,post:be,put:cn,head:Wo,remove:In}=Mo;var Ir=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=Io(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Ns(r))return{data:null,error:r};throw r}}},qo=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ns(e))return{data:null,error:e};throw e}}};let Zi;Zi=Symbol.toStringTag;var zo=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Zi]="BlobDownloadBuilder",this.promise=null}asStream(){return new qo(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ns(e))return{data:null,error:e};throw e}}};const Ho={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ri={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Ko=class extends Ir{constructor(t,e={},r,s){super(t,e,s,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,s){var n=this;return n.handleOperation(async()=>{let i;const a=ee(ee({},ri),s);let l=ee(ee({},n.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const c=a.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",n.encodeMetadata(c)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),c&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(c))):(i=r,l["cache-control"]=`max-age=${a.cacheControl}`,l["content-type"]=a.contentType,c&&(l["x-metadata"]=n.toBase64(n.encodeMetadata(c))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!a.duplex&&(a.duplex="half")),s!=null&&s.headers&&(l=ee(ee({},l),s.headers));const u=n._removeEmptyFolders(e),d=n._getFinalPath(u),p=await(t=="PUT"?cn:be)(n.fetch,`${n.url}/object/${d}`,i,ee({headers:l},a!=null&&a.duplex?{duplex:a.duplex}:{}));return{path:u,id:p.Id,fullPath:p.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var n=this;const i=n._removeEmptyFolders(t),a=n._getFinalPath(i),l=new URL(n.url+`/object/upload/sign/${a}`);return l.searchParams.set("token",e),n.handleOperation(async()=>{let c;const u=ee({upsert:ri.upsert},s),d=ee(ee({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",u.cacheControl)):(c=r,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType),{path:i,fullPath:(await cn(n.fetch,l.toString(),c,{headers:d})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const n=ee({},r.headers);e!=null&&e.upsert&&(n["x-upsert"]="true");const i=await be(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),a=new URL(r.url+i.url),l=a.searchParams.get("token");if(!l)throw new Ps("No token returned by API");return{signedUrl:a.toString(),path:t,token:l}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var s=this;return s.handleOperation(async()=>await be(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await be(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t),i=await be(s.fetch,`${s.url}/object/sign/${n}`,ee({expiresIn:e},r!=null&&r.transform?{transform:r.transform}:{}),{headers:s.headers});const a=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{signedUrl:encodeURI(`${s.url}${i.signedURL}${a}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await be(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),i=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(a=>ee(ee({},a),{},{signedUrl:a.signedURL?encodeURI(`${s.url}${a.signedURL}${i}`):null}))})}download(t,e){const r=typeof(e==null?void 0:e.transform)<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString((e==null?void 0:e.transform)||{}),n=s?`?${s}`:"",i=this._getFinalPath(t),a=()=>Zr(this.fetch,`${this.url}/${r}/${i}${n}`,{headers:this.headers,noResolveJson:!0});return new zo(a,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>ln(await Zr(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await Wo(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(s){if(e.shouldThrowOnError)throw s;if(Ns(s)&&s instanceof Xi){const n=s.originalError;if([400,404].includes(n==null?void 0:n.status))return{data:!1,error:s}}throw s}}getPublicUrl(t,e){const r=this._getFinalPath(t),s=[],n=e!=null&&e.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&s.push(n);const i=typeof(e==null?void 0:e.transform)<"u"?"render/image":"object",a=this.transformOptsToQueryString((e==null?void 0:e.transform)||{});a!==""&&s.push(a);let l=s.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${l}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await In(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var s=this;return s.handleOperation(async()=>{const n=ee(ee(ee({},Ho),e),{},{prefix:t||""});return await be(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const s=ee({},t);return await be(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}};const Vo="2.93.2",ds={"X-Client-Info":`storage-js/${Vo}`};var Go=class extends Ir{constructor(t,e={},r,s){const n=new URL(t);s!=null&&s.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));const i=n.href.replace(/\/$/,""),a=ee(ee({},ds),e);super(i,a,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await Zr(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Zr(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await be(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await cn(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await be(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await In(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},Jo=class extends Ir{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ee(ee({},ds),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await be(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&r.set("limit",t.limit.toString()),(t==null?void 0:t.offset)!==void 0&&r.set("offset",t.offset.toString()),t!=null&&t.sortColumn&&r.set("sortColumn",t.sortColumn),t!=null&&t.sortOrder&&r.set("sortOrder",t.sortOrder),t!=null&&t.search&&r.set("search",t.search);const s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await Zr(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await In(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!No(t))throw new Ps("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new Ao({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,i){const a=n[i];return typeof a!="function"?a:async(...l)=>{try{return{data:await a.apply(n,l),error:null}}catch(c){if(s)throw c;return{data:null,error:c}}}}})}},Qo=class extends Ir{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ee(ee({},ds),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await be(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await be(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await be(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await be(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Yo=class extends Ir{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ee(ee({},ds),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await be(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await be(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await be(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await be(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await be(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Xo=class extends Ir{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ee(ee({},ds),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await be(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await be(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await be(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await be(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Zo=class extends Xo{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new el(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},el=class extends Qo{constructor(t,e,r,s){super(t,e,s),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new tl(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},tl=class extends Yo{constructor(t,e,r,s,n){super(t,e,n),this.vectorBucketName=r,this.indexName=s}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},rl=class extends Go{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new Ko(this.url,this.headers,t,this.fetch)}get vectors(){return new Zo(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Jo(this.url+"/iceberg",this.headers,this.fetch)}};const ea="2.93.2",br=30*1e3,un=3,Gs=un*br,sl="http://localhost:9999",nl="supabase.auth.token",il={"X-Client-Info":`gotrue-js/${ea}`},dn="X-Supabase-Api-Version",ta={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},al=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,ol=10*60*1e3;class es extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}}function H(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class ll extends es{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function cl(t){return H(t)&&t.name==="AuthApiError"}class Kt extends es{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class gt extends es{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class We extends gt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Js(t){return H(t)&&t.name==="AuthSessionMissingError"}class cr extends gt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class xs extends gt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class _s extends gt{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function ul(t){return H(t)&&t.name==="AuthImplicitGrantRedirectError"}class si extends gt{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class dl extends gt{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class hn extends gt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function Qs(t){return H(t)&&t.name==="AuthRetryableFetchError"}class ni extends gt{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}}class fn extends gt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const js="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),ii=`
56
+ \r=`.split(""),hl=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<ii.length;e+=1)t[ii[e].charCodeAt(0)]=-2;for(let e=0;e<js.length;e+=1)t[js[e].charCodeAt(0)]=e;return t})();function ai(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(js[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(js[s]),e.queuedBits-=6}}function ra(t,e,r){const s=hl[t];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function oi(t){const e=[],r=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=a=>{gl(a,s,r)};for(let a=0;a<t.length;a+=1)ra(t.charCodeAt(a),n,i);return e.join("")}function fl(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function pl(t,e){for(let r=0;r<t.length;r+=1){let s=t.charCodeAt(r);if(s>55295&&s<=56319){const n=(s-55296)*1024&65535;s=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}fl(s,e)}}function gl(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let s=1;s<6;s+=1)if(!(t>>7-s&1)){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function vr(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)ra(t.charCodeAt(n),r,s);return new Uint8Array(e)}function bl(t){const e=[];return pl(t,r=>e.push(r)),new Uint8Array(e)}function Vt(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>ai(n,r,s)),ai(null,r,s),e.join("")}function ml(t){return Math.round(Date.now()/1e3)+t}function yl(){return Symbol("auth-callback")}const Ae=()=>typeof window<"u"&&typeof document<"u",Wt={tested:!1,writable:!1},sa=()=>{if(!Ae())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Wt.tested)return Wt.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Wt.tested=!0,Wt.writable=!0}catch{Wt.tested=!0,Wt.writable=!1}return Wt.writable};function vl(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return r.searchParams.forEach((s,n)=>{e[n]=s}),e}const na=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),wl=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",mr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},qt=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Oe=async(t,e)=>{await t.removeItem(e)};class Bs{constructor(){this.promise=new Bs.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}Bs.promiseConstructor=Promise;function ks(t){const e=t.split(".");if(e.length!==3)throw new fn("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!al.test(e[s]))throw new fn("JWT not in base64url format");return{header:JSON.parse(oi(e[0])),payload:JSON.parse(oi(e[1])),signature:vr(e[2]),raw:{header:e[0],payload:e[1]}}}async function xl(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function _l(t,e){return new Promise((s,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{const a=await t(i);if(!e(i,null,a)){s(a);return}}catch(a){if(!e(i,a)){n(a);return}}})()})}function kl(t){return("0"+t.toString(16)).substr(-2)}function Sl(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=r.length;let n="";for(let i=0;i<56;i++)n+=r.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,kl).join("")}async function El(t){const r=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(s);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function jl(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;const r=await El(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ur(t,e,r=!1){const s=Sl();let n=s;r&&(n+="/PASSWORD_RECOVERY"),await mr(t,`${e}-code-verifier`,n);const i=await jl(s);return[i,s===i?"plain":"s256"]}const Tl=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Rl(t){const e=t.headers.get(dn);if(!e||!e.match(Tl))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Cl(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function Ol(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const Al=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function dr(t){if(!Al.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ys(){const t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const s=r.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Il(t,e){return new Proxy(t,{get:(r,s,n)=>{if(s==="__isInsecureUserWarningProxy")return!0;if(typeof s=="symbol"){const i=s.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,s,n)}return!e.value&&typeof s=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,s,n)}})}function li(t){return JSON.parse(JSON.stringify(t))}const zt=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Pl=[502,503,504];async function ci(t){var e;if(!wl(t))throw new hn(zt(t),0);if(Pl.includes(t.status))throw new hn(zt(t),t.status);let r;try{r=await t.json()}catch(i){throw new Kt(zt(i),i)}let s;const n=Rl(t);if(n&&n.getTime()>=ta["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?s=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(s=r.error_code),s){if(s==="weak_password")throw new ni(zt(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new We}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,a)=>i&&typeof a=="string",!0))throw new ni(zt(r),t.status,r.weak_password.reasons);throw new ll(zt(r),t.status||500,s)}const Nl=(t,e,r,s)=>{const n={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))};async function Z(t,e,r,s){var n;const i=Object.assign({},s==null?void 0:s.headers);i[dn]||(i[dn]=ta["2024-01-01"].name),s!=null&&s.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const a=(n=s==null?void 0:s.query)!==null&&n!==void 0?n:{};s!=null&&s.redirectTo&&(a.redirect_to=s.redirectTo);const l=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await Bl(t,e,r+l,{headers:i,noResolveJson:s==null?void 0:s.noResolveJson},{},s==null?void 0:s.body);return s!=null&&s.xform?s==null?void 0:s.xform(c):{data:Object.assign({},c),error:null}}async function Bl(t,e,r,s,n,i){const a=Nl(e,s,n,i);let l;try{l=await t(r,Object.assign({},a))}catch(c){throw console.error(c),new hn(zt(c),0)}if(l.ok||await ci(l),s!=null&&s.noResolveJson)return l;try{return await l.json()}catch(c){await ci(c)}}function Xe(t){var e;let r=null;Dl(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=ml(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function ui(t){const e=Xe(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Et(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function $l(t){return{data:t,error:null}}function Fl(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,a=Is(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},c=Object.assign({},a);return{data:{properties:l,user:c},error:null}}function di(t){return t}function Dl(t){return t.access_token&&t.refresh_token&&t.expires_in}const Xs=["global","local","others"];class Ll{constructor({url:e="",headers:r={},fetch:s}){this.url=e,this.headers=r,this.fetch=na(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,r=Xs[0]){if(Xs.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Xs.join(", ")}`);try{return await Z(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(H(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await Z(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Et})}catch(s){if(H(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=Is(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=s==null?void 0:s.newEmail,delete n.newEmail),await Z(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Fl,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(H(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await Z(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Et})}catch(r){if(H(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,i,a,l,c;try{const u={nextPage:null,lastPage:0,total:0},d=await Z(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e==null?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:di});if(d.error)throw d.error;const p=await d.json(),f=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,h=(c=(l=d.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return h.length>0&&(h.forEach(m=>{const g=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(m.split(";")[1].split("=")[1]);u[`${_}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},p),u),error:null}}catch(u){if(H(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){dr(e);try{return await Z(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Et})}catch(r){if(H(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){dr(e);try{return await Z(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Et})}catch(s){if(H(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){dr(e);try{return await Z(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Et})}catch(s){if(H(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){dr(e.userId);try{const{data:r,error:s}=await Z(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:s}}catch(r){if(H(r))return{data:null,error:r};throw r}}async _deleteFactor(e){dr(e.userId),dr(e.id);try{return{data:await Z(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(H(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,i,a,l,c;try{const u={nextPage:null,lastPage:0,total:0},d=await Z(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e==null?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:di});if(d.error)throw d.error;const p=await d.json(),f=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,h=(c=(l=d.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return h.length>0&&(h.forEach(m=>{const g=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(m.split(";")[1].split("=")[1]);u[`${_}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},p),u),error:null}}catch(u){if(H(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await Z(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(H(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await Z(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(H(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await Z(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(H(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await Z(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(H(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await Z(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(H(r))return{data:null,error:r};throw r}}}function hi(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const hr={debug:!!(globalThis&&sa()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class ia extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Ul extends ia{}async function Ml(t,e,r){hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),hr.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async n=>{if(n){hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,n.name);try{return await r()}finally{hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,n.name)}}else{if(e===0)throw hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Ul(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(hr.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}}))}function Wl(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function aa(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function ql(t){return parseInt(t,16)}function zl(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function Hl(t){var e;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:l,requestId:c,resources:u,scheme:d,uri:p,version:f}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!p)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
57
+ `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const h=aa(t.address),m=d?`${d}://${s}`:s,g=t.statement?`${t.statement}
58
+ `:"",_=`${m} wants you to sign in with your Ethereum account:
59
+ ${h}
60
+
61
+ ${g}`;let w=`URI: ${p}
62
+ Version: ${f}
63
+ Chain ID: ${r}${a?`
64
+ Nonce: ${a}`:""}
65
+ Issued At: ${i.toISOString()}`;if(n&&(w+=`
66
+ Expiration Time: ${n.toISOString()}`),l&&(w+=`
67
+ Not Before: ${l.toISOString()}`),c&&(w+=`
68
+ Request ID: ${c}`),u){let k=`
69
+ Resources:`;for(const b of u){if(!b||typeof b!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${b}`);k+=`
70
+ - ${b}`}w+=k}return`${_}
71
+ ${w}`}class _e extends Error{constructor({message:e,code:r,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}}class Ts extends _e{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function Kl({error:t,options:e}){var r,s,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new _e({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new _e({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new _e({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new _e({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new _e({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new _e({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new _e({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new _e({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const a=window.location.hostname;if(oa(a)){if(i.rp.id!==a)return new _e({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new _e({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new _e({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new _e({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new _e({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Vl({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new _e({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new _e({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(oa(s)){if(r.rpId!==s)return new _e({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new _e({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new _e({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new _e({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class Gl{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const Jl=new Gl;function Ql(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:s}=t,n=Is(t,["challenge","user","excludeCredentials"]),i=vr(e).buffer,a=Object.assign(Object.assign({},r),{id:vr(r.id).buffer}),l=Object.assign(Object.assign({},n),{challenge:i,user:a});if(s&&s.length>0){l.excludeCredentials=new Array(s.length);for(let c=0;c<s.length;c++){const u=s[c];l.excludeCredentials[c]=Object.assign(Object.assign({},u),{id:vr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return l}function Yl(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,s=Is(t,["challenge","allowCredentials"]),n=vr(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let a=0;a<r.length;a++){const l=r[a];i.allowCredentials[a]=Object.assign(Object.assign({},l),{id:vr(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return i}function Xl(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:Vt(new Uint8Array(t.response.attestationObject)),clientDataJSON:Vt(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Zl(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,s=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:Vt(new Uint8Array(n.authenticatorData)),clientDataJSON:Vt(new Uint8Array(n.clientDataJSON)),signature:Vt(new Uint8Array(n.signature)),userHandle:n.userHandle?Vt(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function oa(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function fi(){var t,e;return!!(Ae()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function ec(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ts("Browser returned unexpected credential type",e)}:{data:null,error:new Ts("Empty credential response",e)}}catch(e){return{data:null,error:Kl({error:e,options:t})}}}async function tc(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ts("Browser returned unexpected credential type",e)}:{data:null,error:new Ts("Empty credential response",e)}}catch(e){return{data:null,error:Vl({error:e,options:t})}}}const rc={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},sc={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Rs(...t){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(const n of t)if(n)for(const i in n){const a=n[i];if(a!==void 0)if(Array.isArray(a))s[i]=a;else if(r(a))s[i]=a;else if(e(a)){const l=s[i];e(l)?s[i]=Rs(l,a):s[i]=Rs(a)}else s[i]=a}return s}function nc(t,e){return Rs(rc,t,e||{})}function ic(t,e){return Rs(sc,t,e||{})}class ac{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:s,signal:n},i){try{const{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};const c=n??Jl.createNewAbortSignal();if(a.webauthn.type==="create"){const{user:u}=a.webauthn.credential_options.publicKey;u.name||(u.name=`${u.id}:${s}`),u.displayName||(u.displayName=u.name)}switch(a.webauthn.type){case"create":{const u=nc(a.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:d,error:p}=await ec({publicKey:u,signal:c});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:p}}case"request":{const u=ic(a.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:d,error:p}=await tc(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:c}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:p}}}}catch(a){return H(a)?{data:null,error:a}:{data:null,error:new Kt("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new es("rpId is required for WebAuthn authentication")};try{if(!fi())return{data:null,error:new Kt("Browser does not support WebAuthn",null)};const{data:a,error:l}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!a)return{data:null,error:l};const{webauthn:c}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:c.type,rpId:r,rpOrigins:s,credential_response:c.credential_response}})}catch(a){return H(a)?{data:null,error:a}:{data:null,error:new Kt("Unexpected error in authenticate",a)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new es("rpId is required for WebAuthn registration")};try{if(!fi())return{data:null,error:new Kt("Browser does not support WebAuthn",null)};const{data:a,error:l}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(d=>{var p;return(p=d.data)===null||p===void 0?void 0:p.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d==null?void 0:d.id}):void 0),{data:null,error:l};const{data:c,error:u}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return c?this._verify({factorId:a.id,challengeId:c.challengeId,webauthn:{rpId:r,rpOrigins:s,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(a){return H(a)?{data:null,error:a}:{data:null,error:new Kt("Unexpected error in register",a)}}}}Wl();const oc={url:sl,storageKey:nl,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:il,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function pi(t,e,r){return await r()}const fr={};class ts{get jwks(){var e,r;return(r=(e=fr[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){fr[this.storageKey]=Object.assign(Object.assign({},fr[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=fr[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){fr[this.storageKey]=Object.assign(Object.assign({},fr[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},oc),e);if(this.storageKey=i.storageKey,this.instanceID=(r=ts.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,ts.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&Ae()){const a=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Ll({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=na(i.fetch),this.lock=i.lock||pi,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&Ae()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=Ml:this.lock=pi,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new ac(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:sa()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=hi(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=hi(this.memoryStorage)),Ae()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ea}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},s="none";if(Ae()&&(r=vl(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),Ae()&&this.detectSessionInUrl&&s!=="none"){const{data:n,error:i}=await this._getSessionFromURL(r,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),ul(i)){const c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:a,redirectType:l}=n;return this._debug("#_initialize()","detected session in URL",a,"redirect type",l),await this._saveSession(a),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return H(r)?this._returnResult({error:r}):this._returnResult({error:new Kt("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await Z(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.captchaToken}},xform:Xe}),{data:a,error:l}=i;if(l||!a)return this._returnResult({data:{user:null,session:null},error:l});const c=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(H(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;try{let i;if("email"in e){const{email:d,password:p,options:f}=e;let h=null,m=null;this.flowType==="pkce"&&([h,m]=await ur(this.storage,this.storageKey)),i=await Z(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:d,password:p,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:h,code_challenge_method:m},xform:Xe})}else if("phone"in e){const{phone:d,password:p,options:f}=e;i=await Z(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:p,data:(s=f==null?void 0:f.data)!==null&&s!==void 0?s:{},channel:(n=f==null?void 0:f.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:Xe})}else throw new xs("You must provide either an email or phone number and a password");const{data:a,error:l}=i;if(l||!a)return await Oe(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l});const c=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),H(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:a,options:l}=e;r=await Z(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:ui})}else if("phone"in e){const{phone:i,password:a,options:l}=e;r=await Z(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:ui})}else throw new xs("You must provide either an email or phone number and a password");const{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){const i=new cr;return this._returnResult({data:{user:null,session:null},error:i})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(r){if(H(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,a,l,c,u,d,p,f;let h,m;if("message"in e)h=e.message,m=e.signature;else{const{chain:g,wallet:_,statement:w,options:k}=e;let b;if(Ae())if(typeof _=="object")b=_;else{const B=window;if("ethereum"in B&&typeof B.ethereum=="object"&&"request"in B.ethereum&&typeof B.ethereum.request=="function")b=B.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof _!="object"||!(k!=null&&k.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=_}const S=new URL((r=k==null?void 0:k.url)!==null&&r!==void 0?r:window.location.href),j=await b.request({method:"eth_requestAccounts"}).then(B=>B).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!j||j.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const C=aa(j[0]);let F=(s=k==null?void 0:k.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!F){const B=await b.request({method:"eth_chainId"});F=ql(B)}const O={domain:S.host,address:C,statement:w,uri:S.href,version:"1",chainId:F,nonce:(n=k==null?void 0:k.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(a=(i=k==null?void 0:k.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(l=k==null?void 0:k.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=k==null?void 0:k.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=k==null?void 0:k.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=k==null?void 0:k.signInWithEthereum)===null||d===void 0?void 0:d.resources};h=Hl(O),m=await b.request({method:"personal_sign",params:[zl(h),C]})}try{const{data:g,error:_}=await Z(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:m},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:Xe});if(_)throw _;if(!g||!g.session||!g.user){const w=new cr;return this._returnResult({data:{user:null,session:null},error:w})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:_})}catch(g){if(H(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,s,n,i,a,l,c,u,d,p,f,h;let m,g;if("message"in e)m=e.message,g=e.signature;else{const{chain:_,wallet:w,statement:k,options:b}=e;let S;if(Ae())if(typeof w=="object")S=w;else{const C=window;if("solana"in C&&typeof C.solana=="object"&&("signIn"in C.solana&&typeof C.solana.signIn=="function"||"signMessage"in C.solana&&typeof C.solana.signMessage=="function"))S=C.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof w!="object"||!(b!=null&&b.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=w}const j=new URL((r=b==null?void 0:b.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in S&&S.signIn){const C=await S.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},b==null?void 0:b.signInWithSolana),{version:"1",domain:j.host,uri:j.href}),k?{statement:k}:null));let F;if(Array.isArray(C)&&C[0]&&typeof C[0]=="object")F=C[0];else if(C&&typeof C=="object"&&"signedMessage"in C&&"signature"in C)F=C;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in F&&"signature"in F&&(typeof F.signedMessage=="string"||F.signedMessage instanceof Uint8Array)&&F.signature instanceof Uint8Array)m=typeof F.signedMessage=="string"?F.signedMessage:new TextDecoder().decode(F.signedMessage),g=F.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in S)||typeof S.signMessage!="function"||!("publicKey"in S)||typeof S!="object"||!S.publicKey||!("toBase58"in S.publicKey)||typeof S.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");m=[`${j.host} wants you to sign in with your Solana account:`,S.publicKey.toBase58(),...k?["",k,""]:[""],"Version: 1",`URI: ${j.href}`,`Issued At: ${(n=(s=b==null?void 0:b.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=b==null?void 0:b.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${b.signInWithSolana.notBefore}`]:[],...!((a=b==null?void 0:b.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${b.signInWithSolana.expirationTime}`]:[],...!((l=b==null?void 0:b.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${b.signInWithSolana.chainId}`]:[],...!((c=b==null?void 0:b.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${b.signInWithSolana.nonce}`]:[],...!((u=b==null?void 0:b.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${b.signInWithSolana.requestId}`]:[],...!((p=(d=b==null?void 0:b.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||p===void 0)&&p.length?["Resources",...b.signInWithSolana.resources.map(F=>`- ${F}`)]:[]].join(`
72
+ `);const C=await S.signMessage(new TextEncoder().encode(m),"utf8");if(!C||!(C instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=C}}try{const{data:_,error:w}=await Z(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:m,signature:Vt(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:Xe});if(w)throw w;if(!_||!_.session||!_.user){const k=new cr;return this._returnResult({data:{user:null,session:null},error:k})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:w})}catch(_){if(H(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){const r=await qt(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new dl;const{data:i,error:a}=await Z(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:Xe});if(await Oe(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){const l=new cr;return this._returnResult({data:{user:null,session:null,redirectType:null},error:l})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:a})}catch(i){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),H(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:a}=e,l=await Z(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:Xe}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){const d=new cr;return this._returnResult({data:{user:null,session:null},error:d})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(r){if(H(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,a;try{if("email"in e){const{email:l,options:c}=e;let u=null,d=null;this.flowType==="pkce"&&([u,d]=await ur(this.storage,this.storageKey));const{error:p}=await Z(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(r=c==null?void 0:c.data)!==null&&r!==void 0?r:{},create_user:(s=c==null?void 0:c.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:c==null?void 0:c.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:p})}if("phone"in e){const{phone:l,options:c}=e,{data:u,error:d}=await Z(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(n=c==null?void 0:c.data)!==null&&n!==void 0?n:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(a=c==null?void 0:c.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:d})}throw new xs("You must provide either an email or phone number.")}catch(l){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),H(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:a,error:l}=await Z(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:Xe});if(l)throw l;if(!a)throw new Error("An error occurred on token verification.");const c=a.session,u=a.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(n){if(H(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,a;try{let l=null,c=null;this.flowType==="pkce"&&([l,c]=await ur(this.storage,this.storageKey));const u=await Z(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e==null?void 0:e.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:$l});return!((i=u.data)===null||i===void 0)&&i.url&&Ae()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),H(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new We;const{error:n}=await Z(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(H(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:i}=e,{error:a}=await Z(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in e){const{phone:s,type:n,options:i}=e,{data:a,error:l}=await Z(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:l})}throw new xs("You must provide either an email or phone number and a type")}catch(r){if(H(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await qt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<Gs:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await qt(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=Ys()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=Il(e.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await Z(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Et}):await this._useSession(async r=>{var s,n,i;const{data:a,error:l}=r;if(l)throw l;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new We}:await Z(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:Et})})}catch(r){if(H(r))return Js(r)&&(await this._removeSession(),await Oe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async s=>{const{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new We;const a=n.session;let l=null,c=null;this.flowType==="pkce"&&e.email!=null&&([l,c]=await ur(this.storage,this.storageKey));const{data:u,error:d}=await Z(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:c}),jwt:a.access_token,xform:Et});if(d)throw d;return a.user=u.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(s){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),H(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new We;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=ks(e.access_token);if(a.exp&&(s=a.exp,n=s<=r),n){const{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{const{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(H(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:a,error:l}=r;if(l)throw l;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new We;const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(H(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!Ae())throw new _s("No browser detected.");if(e.error||e.error_description||e.error_code)throw new _s(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new si("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new _s("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new si("No code detected.");const{data:k,error:b}=await this._exchangeCodeForSession(e.code);if(b)throw b;const S=new URL(window.location.href);return S.searchParams.delete("code"),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:k.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:a,expires_in:l,expires_at:c,token_type:u}=e;if(!i||!l||!a||!u)throw new _s("No session defined in URL");const d=Math.round(Date.now()/1e3),p=parseInt(l);let f=d+p;c&&(f=parseInt(c));const h=f-d;h*1e3<=br&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${p}s`);const m=f-p;d-m>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",m,f,d):d-m<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",m,f,d);const{data:g,error:_}=await this._getUser(i);if(_)throw _;const w={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:p,expires_at:f,refresh_token:a,token_type:u,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:w,redirectType:e.type},error:null})}catch(s){if(H(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await qt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i&&!Js(i))return this._returnResult({error:i});const a=(s=n.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:l}=await this.admin.signOut(a,e);if(l&&!(cl(l)&&(l.status===404||l.status===401||l.status===403)||Js(l)))return this._returnResult({error:l})}return e!=="others"&&(await this._removeSession(),await Oe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=yl(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{const{data:{session:i},error:a}=r;if(a)throw a;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await ur(this.storage,this.storageKey,!0));try{return await Z(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),H(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(H(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:s,error:n}=await this._useSession(async i=>{var a,l,c,u,d;const{data:p,error:f}=i;if(f)throw f;const h=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await Z(this.fetch,"GET",h,{headers:this.headers,jwt:(d=(u=p.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(n)throw n;return Ae()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:e.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(H(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:a,provider:l,token:c,access_token:u,nonce:d}=e,p=await Z(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i==null?void 0:i.access_token)!==null&&s!==void 0?s:void 0,body:{provider:l,id_token:c,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Xe}),{data:f,error:h}=p;return h?this._returnResult({data:{user:null,session:null},error:h}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new cr}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:h}))}catch(n){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),H(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)throw a;return await Z(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(H(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const s=Date.now();return await _l(async n=>(n>0&&await xl(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await Z(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Xe})),(n,i)=>{const a=200*Math.pow(2,n);return i&&Qs(i)&&Date.now()+a-s<br})}catch(s){if(this._debug(r,"error",s),H(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),Ae()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await qt(this.storage,this.storageKey);if(n&&this.userStorage){let a=await qt(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await mr(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:Ys()}else if(n&&!n.user&&!n.user){const a=await qt(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(n.user=a.user,await Oe(this.storage,this.storageKey+"-user"),await mr(this.storage,this.storageKey,n)):n.user=Ys()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Gs;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${Gs}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),Qs(a)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:l}=await this._getUser(n.access_token);!l&&(a!=null&&a.user)?(n.user=a.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new We;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Bs;const{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new We;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const l={data:i.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(i){if(this._debug(n,"error",i),H(i)){const a={data:null,error:i};return Qs(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],a=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,r)}catch(c){i.push(c)}});if(await Promise.all(a),i.length>0){for(let l=0;l<i.length;l+=1)console.error(i[l]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Oe(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await mr(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=li(n);await mr(this.storage,this.storageKey,i)}else{const n=li(r);await mr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Oe(this.storage,this.storageKey),await Oe(this.storage,this.storageKey+"-code-verifier"),await Oe(this.storage,this.storageKey+"-user"),this.userStorage&&await Oe(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ae()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),br);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/br);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${br}ms, refresh threshold is ${un} ticks`),n<=un&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof ia)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ae()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){const n=[`provider=${encodeURIComponent(r)}`];if(s!=null&&s.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,a]=await ur(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});n.push(l.toString())}if(s!=null&&s.queryParams){const i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s!=null&&s.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await Z(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(H(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await Z(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((n=c==null?void 0:c.totp)===null||n===void 0)&&n.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(H(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Xl(e.webauthn.credential_response):Zl(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:c}=await Z(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:c}))})}catch(r){if(H(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const a=await Z(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});if(a.error)return a;const{data:l}=a;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:Ql(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:Yl(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(H(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{const{payload:h}=ks(e);let m=null;h.aal&&(m=h.aal);let g=m;const{data:{user:_},error:w}=await this.getUser(e);if(w)return this._returnResult({data:null,error:w});((s=(r=_==null?void 0:_.factors)===null||r===void 0?void 0:r.filter(S=>S.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(g="aal2");const b=h.amr||[];return{data:{currentLevel:m,nextLevel:g,currentAuthenticationMethods:b},error:null}}catch(h){if(H(h))return this._returnResult({data:null,error:h});throw h}const{data:{session:a},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=ks(a.access_token);let u=null;c.aal&&(u=c.aal);let d=u;((i=(n=a.user.factors)===null||n===void 0?void 0:n.filter(h=>h.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(d="aal2");const f=c.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await Z(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new We})})}catch(r){if(H(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new We});const a=await Z(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return a.data&&a.data.redirect_url&&Ae()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(H(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new We});const a=await Z(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return a.data&&a.data.redirect_url&&Ae()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(H(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await Z(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new We})})}catch(e){if(H(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await Z(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new We})})}catch(r){if(H(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(l=>l.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(l=>l.kid===e),s&&this.jwks_cached_at+ol>n)return s;const{data:i,error:a}=await Z(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(l=>l.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:h,error:m}=await this.getSession();if(m||!h.session)return this._returnResult({data:null,error:m});s=h.session.access_token}const{header:n,payload:i,signature:a,raw:{header:l,payload:c}}=ks(s);r!=null&&r.allowExpired||Cl(i.exp);const u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!u){const{error:h}=await this.getUser(s);if(h)throw h;return{data:{claims:i,header:n,signature:a},error:null}}const d=Ol(n.alg),p=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,p,a,bl(`${l}.${c}`)))throw new fn("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(H(s))return this._returnResult({data:null,error:s});throw s}}}ts.nextInstanceID={};const lc=ts,cc="2.93.2";let Hr="";typeof Deno<"u"?Hr="deno":typeof document<"u"?Hr="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Hr="react-native":Hr="node";const uc={"X-Client-Info":`supabase-js-${Hr}/${cc}`},dc={headers:uc},hc={schema:"public"},fc={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},pc={};function rs(t){"@babel/helpers - typeof";return rs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},rs(t)}function gc(t,e){if(rs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(rs(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function bc(t){var e=gc(t,"string");return rs(e)=="symbol"?e:e+""}function mc(t,e,r){return(e=bc(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function gi(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function we(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?gi(Object(r),!0).forEach(function(s){mc(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):gi(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const yc=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),vc=()=>Headers,wc=(t,e,r)=>{const s=yc(r),n=vc();return async(i,a)=>{var l;const c=(l=await e())!==null&&l!==void 0?l:t;let u=new n(a==null?void 0:a.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),s(i,we(we({},a),{},{headers:u}))}};function xc(t){return t.endsWith("/")?t:t+"/"}function _c(t,e){var r,s;const{db:n,auth:i,realtime:a,global:l}=t,{db:c,auth:u,realtime:d,global:p}=e,f={db:we(we({},c),n),auth:we(we({},u),i),realtime:we(we({},d),a),storage:{},global:we(we(we({},p),l),{},{headers:we(we({},(r=p==null?void 0:p.headers)!==null&&r!==void 0?r:{}),(s=l==null?void 0:l.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function kc(t){const e=t==null?void 0:t.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(xc(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Sc=class extends lc{constructor(t){super(t)}},Ec=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=kc(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,l={db:hc,realtime:pc,auth:we(we({},fc),{},{storageKey:a}),global:dc},c=_c(r??{},l);if(this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(d,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=c.auth)!==null&&u!==void 0?u:{},this.headers,c.global.fetch)}this.fetch=wc(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(we({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(d=>this.realtime.setAuth(d)).catch(d=>console.warn("Failed to set initial Realtime auth token:",d)),this.rest=new oo(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this.storage=new rl(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new ro(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:a,lock:l,debug:c,throwOnError:u},d,p){const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Sc({url:this.authUrl.href,headers:we(we({},f),d),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:l,debug:c,throwOnError:u,fetch:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(h=>h.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Eo(this.realtimeUrl.href,we(we({},t),{},{params:we(we({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const pn=(t,e,r)=>new Ec(t,e,r);function jc(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}jc()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var hs=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Tc={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},it,Jt,Fi,Rc=(Fi=class{constructor(){Y(this,it,Tc);Y(this,Jt,!1)}setTimeoutProvider(t){process.env.NODE_ENV!=="production"&&x(this,Jt)&&t!==x(this,it)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:x(this,it),provider:t}),M(this,it,t),process.env.NODE_ENV!=="production"&&M(this,Jt,!1)}setTimeout(t,e){return process.env.NODE_ENV!=="production"&&M(this,Jt,!0),x(this,it).setTimeout(t,e)}clearTimeout(t){x(this,it).clearTimeout(t)}setInterval(t,e){return process.env.NODE_ENV!=="production"&&M(this,Jt,!0),x(this,it).setInterval(t,e)}clearInterval(t){x(this,it).clearInterval(t)}},it=new WeakMap,Jt=new WeakMap,Fi),Gt=new Rc;function Cc(t){setTimeout(t,0)}var ir=typeof window>"u"||"Deno"in globalThis;function De(){}function Oc(t,e){return typeof t=="function"?t(e):t}function gn(t){return typeof t=="number"&&t>=0&&t!==1/0}function la(t,e){return Math.max(t+(e||0)-Date.now(),0)}function Nt(t,e){return typeof t=="function"?t(e):t}function Ge(t,e){return typeof t=="function"?t(e):t}function bi(t,e){const{type:r="all",exact:s,fetchStatus:n,predicate:i,queryKey:a,stale:l}=t;if(a){if(s){if(e.queryHash!==Pn(a,e.options))return!1}else if(!ns(e.queryKey,a))return!1}if(r!=="all"){const c=e.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof l=="boolean"&&e.isStale()!==l||n&&n!==e.state.fetchStatus||i&&!i(e))}function mi(t,e){const{exact:r,status:s,predicate:n,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(r){if(ss(e.options.mutationKey)!==ss(i))return!1}else if(!ns(e.options.mutationKey,i))return!1}return!(s&&e.state.status!==s||n&&!n(e))}function Pn(t,e){return((e==null?void 0:e.queryKeyHashFn)||ss)(t)}function ss(t){return JSON.stringify(t,(e,r)=>yn(r)?Object.keys(r).sort().reduce((s,n)=>(s[n]=r[n],s),{}):r)}function ns(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>ns(t[r],e[r])):!1}var Ac=Object.prototype.hasOwnProperty;function bn(t,e,r=0){if(t===e)return t;if(r>500)return e;const s=yi(t)&&yi(e);if(!s&&!(yn(t)&&yn(e)))return e;const i=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),l=a.length,c=s?new Array(l):{};let u=0;for(let d=0;d<l;d++){const p=s?d:a[d],f=t[p],h=e[p];if(f===h){c[p]=f,(s?d<i:Ac.call(t,p))&&u++;continue}if(f===null||h===null||typeof f!="object"||typeof h!="object"){c[p]=h;continue}const m=bn(f,h,r+1);c[p]=m,m===f&&u++}return i===l&&u===i?t:c}function mn(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(const r in t)if(t[r]!==e[r])return!1;return!0}function yi(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function yn(t){if(!vi(t))return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(!vi(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function vi(t){return Object.prototype.toString.call(t)==="[object Object]"}function Ic(t){return new Promise(e=>{Gt.setTimeout(e,t)})}function vn(t,e,r){if(typeof r.structuralSharing=="function")return r.structuralSharing(t,e);if(r.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return bn(t,e)}catch(s){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${r.queryHash}]: ${s}`),s}return bn(t,e)}return e}function Pc(t,e,r=0){const s=[...t,e];return r&&s.length>r?s.slice(1):s}function Nc(t,e,r=0){const s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}var Cs=Symbol();function ca(t,e){return process.env.NODE_ENV!=="production"&&t.queryFn===Cs&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${t.queryHash}'`),!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===Cs?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function ua(t,e){return typeof t=="function"?t(...e):!!t}function Bc(t,e,r){let s=!1,n;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(n??(n=e()),s||(s=!0,n.aborted?r():n.addEventListener("abort",r,{once:!0})),n)}),t}var Qt,jt,wr,Di,$c=(Di=class extends hs{constructor(){super();Y(this,Qt);Y(this,jt);Y(this,wr);M(this,wr,e=>{if(!ir&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){x(this,jt)||this.setEventListener(x(this,wr))}onUnsubscribe(){var e;this.hasListeners()||((e=x(this,jt))==null||e.call(this),M(this,jt,void 0))}setEventListener(e){var r;M(this,wr,e),(r=x(this,jt))==null||r.call(this),M(this,jt,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){x(this,Qt)!==e&&(M(this,Qt,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof x(this,Qt)=="boolean"?x(this,Qt):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},Qt=new WeakMap,jt=new WeakMap,wr=new WeakMap,Di),Nn=new $c;function wn(){let t,e;const r=new Promise((n,i)=>{t=n,e=i});r.status="pending",r.catch(()=>{});function s(n){Object.assign(r,n),delete r.resolve,delete r.reject}return r.resolve=n=>{s({status:"fulfilled",value:n}),t(n)},r.reject=n=>{s({status:"rejected",reason:n}),e(n)},r}var Fc=Cc;function Dc(){let t=[],e=0,r=l=>{l()},s=l=>{l()},n=Fc;const i=l=>{e?t.push(l):n(()=>{r(l)})},a=()=>{const l=t;t=[],l.length&&n(()=>{s(()=>{l.forEach(c=>{r(c)})})})};return{batch:l=>{let c;e++;try{c=l()}finally{e--,e||a()}return c},batchCalls:l=>(...c)=>{i(()=>{l(...c)})},schedule:i,setNotifyFunction:l=>{r=l},setBatchNotifyFunction:l=>{s=l},setScheduler:l=>{n=l}}}var Ie=Dc(),xr,Tt,_r,Li,Lc=(Li=class extends hs{constructor(){super();Y(this,xr,!0);Y(this,Tt);Y(this,_r);M(this,_r,e=>{if(!ir&&window.addEventListener){const r=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",s)}}})}onSubscribe(){x(this,Tt)||this.setEventListener(x(this,_r))}onUnsubscribe(){var e;this.hasListeners()||((e=x(this,Tt))==null||e.call(this),M(this,Tt,void 0))}setEventListener(e){var r;M(this,_r,e),(r=x(this,Tt))==null||r.call(this),M(this,Tt,e(this.setOnline.bind(this)))}setOnline(e){x(this,xr)!==e&&(M(this,xr,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return x(this,xr)}},xr=new WeakMap,Tt=new WeakMap,_r=new WeakMap,Li),Os=new Lc;function Uc(t){return Math.min(1e3*2**t,3e4)}function da(t){return(t??"online")==="online"?Os.isOnline():!0}var xn=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function ha(t){let e=!1,r=0,s;const n=wn(),i=()=>n.status!=="pending",a=g=>{var _;if(!i()){const w=new xn(g);f(w),(_=t.onCancel)==null||_.call(t,w)}},l=()=>{e=!0},c=()=>{e=!1},u=()=>Nn.isFocused()&&(t.networkMode==="always"||Os.isOnline())&&t.canRun(),d=()=>da(t.networkMode)&&t.canRun(),p=g=>{i()||(s==null||s(),n.resolve(g))},f=g=>{i()||(s==null||s(),n.reject(g))},h=()=>new Promise(g=>{var _;s=w=>{(i()||u())&&g(w)},(_=t.onPause)==null||_.call(t)}).then(()=>{var g;s=void 0,i()||(g=t.onContinue)==null||g.call(t)}),m=()=>{if(i())return;let g;const _=r===0?t.initialPromise:void 0;try{g=_??t.fn()}catch(w){g=Promise.reject(w)}Promise.resolve(g).then(p).catch(w=>{var C;if(i())return;const k=t.retry??(ir?0:3),b=t.retryDelay??Uc,S=typeof b=="function"?b(r,w):b,j=k===!0||typeof k=="number"&&r<k||typeof k=="function"&&k(r,w);if(e||!j){f(w);return}r++,(C=t.onFail)==null||C.call(t,r,w),Ic(S).then(()=>u()?void 0:h()).then(()=>{e?f(w):m()})})};return{promise:n,status:()=>n.status,cancel:a,continue:()=>(s==null||s(),n),cancelRetry:l,continueRetry:c,canStart:d,start:()=>(d()?m():h().then(m),n)}}var Yt,Ui,fa=(Ui=class{constructor(){Y(this,Yt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),gn(this.gcTime)&&M(this,Yt,Gt.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(ir?1/0:5*60*1e3))}clearGcTimeout(){x(this,Yt)&&(Gt.clearTimeout(x(this,Yt)),M(this,Yt,void 0))}},Yt=new WeakMap,Ui),Xt,kr,Ve,Zt,Ce,as,er,et,ut,Mi,Mc=(Mi=class extends fa{constructor(e){super();Y(this,et);Y(this,Xt);Y(this,kr);Y(this,Ve);Y(this,Zt);Y(this,Ce);Y(this,as);Y(this,er);M(this,er,!1),M(this,as,e.defaultOptions),this.setOptions(e.options),this.observers=[],M(this,Zt,e.client),M(this,Ve,x(this,Zt).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,M(this,Xt,xi(this.options)),this.state=e.state??x(this,Xt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=x(this,Ce))==null?void 0:e.promise}setOptions(e){if(this.options={...x(this,as),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=xi(this.options);r.data!==void 0&&(this.setState(wi(r.data,r.dataUpdatedAt)),M(this,Xt,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&x(this,Ve).remove(this)}setData(e,r){const s=vn(this.state.data,e,this.options);return ae(this,et,ut).call(this,{data:s,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),s}setState(e,r){ae(this,et,ut).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var s,n;const r=(s=x(this,Ce))==null?void 0:s.promise;return(n=x(this,Ce))==null||n.cancel(e),r?r.then(De).catch(De):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(x(this,Xt))}isActive(){return this.observers.some(e=>Ge(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Cs||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Nt(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!la(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(s=>s.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=x(this,Ce))==null||r.continue()}onOnline(){var r;const e=this.observers.find(s=>s.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=x(this,Ce))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),x(this,Ve).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(x(this,Ce)&&(x(this,er)?x(this,Ce).cancel({revert:!0}):x(this,Ce).cancelRetry()),this.scheduleGc()),x(this,Ve).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||ae(this,et,ut).call(this,{type:"invalidate"})}async fetch(e,r){var c,u,d,p,f,h,m,g,_,w,k,b;if(this.state.fetchStatus!=="idle"&&((c=x(this,Ce))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(x(this,Ce))return x(this,Ce).continueRetry(),x(this,Ce).promise}if(e&&this.setOptions(e),!this.options.queryFn){const S=this.observers.find(j=>j.options.queryFn);S&&this.setOptions(S.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const s=new AbortController,n=S=>{Object.defineProperty(S,"signal",{enumerable:!0,get:()=>(M(this,er,!0),s.signal)})},i=()=>{const S=ca(this.options,r),C=(()=>{const F={client:x(this,Zt),queryKey:this.queryKey,meta:this.meta};return n(F),F})();return M(this,er,!1),this.options.persister?this.options.persister(S,C,this):S(C)},l=(()=>{const S={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:x(this,Zt),state:this.state,fetchFn:i};return n(S),S})();(u=this.options.behavior)==null||u.onFetch(l,this),M(this,kr,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=l.fetchOptions)==null?void 0:d.meta))&&ae(this,et,ut).call(this,{type:"fetch",meta:(p=l.fetchOptions)==null?void 0:p.meta}),M(this,Ce,ha({initialPromise:r==null?void 0:r.initialPromise,fn:l.fetchFn,onCancel:S=>{S instanceof xn&&S.revert&&this.setState({...x(this,kr),fetchStatus:"idle"}),s.abort()},onFail:(S,j)=>{ae(this,et,ut).call(this,{type:"failed",failureCount:S,error:j})},onPause:()=>{ae(this,et,ut).call(this,{type:"pause"})},onContinue:()=>{ae(this,et,ut).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const S=await x(this,Ce).start();if(S===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(S),(h=(f=x(this,Ve).config).onSuccess)==null||h.call(f,S,this),(g=(m=x(this,Ve).config).onSettled)==null||g.call(m,S,this.state.error,this),S}catch(S){if(S instanceof xn){if(S.silent)return x(this,Ce).promise;if(S.revert){if(this.state.data===void 0)throw S;return this.state.data}}throw ae(this,et,ut).call(this,{type:"error",error:S}),(w=(_=x(this,Ve).config).onError)==null||w.call(_,S,this),(b=(k=x(this,Ve).config).onSettled)==null||b.call(k,this.state.data,S,this),S}finally{this.scheduleGc()}}},Xt=new WeakMap,kr=new WeakMap,Ve=new WeakMap,Zt=new WeakMap,Ce=new WeakMap,as=new WeakMap,er=new WeakMap,et=new WeakSet,ut=function(e){const r=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...pa(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,...wi(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return M(this,kr,e.manual?n:void 0),n;case"error":const i=e.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=r(this.state),Ie.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),x(this,Ve).notify({query:this,type:"updated",action:e})})},Mi);function pa(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:da(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function wi(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function xi(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,r=e!==void 0,s=r?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:r?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var Fe,oe,os,Be,tr,Sr,ht,Rt,ls,Er,jr,rr,sr,Ct,Tr,he,Kr,_n,kn,Sn,En,jn,Tn,Rn,ga,Wi,Wc=(Wi=class extends hs{constructor(e,r){super();Y(this,he);Y(this,Fe);Y(this,oe);Y(this,os);Y(this,Be);Y(this,tr);Y(this,Sr);Y(this,ht);Y(this,Rt);Y(this,ls);Y(this,Er);Y(this,jr);Y(this,rr);Y(this,sr);Y(this,Ct);Y(this,Tr,new Set);this.options=r,M(this,Fe,e),M(this,Rt,null),M(this,ht,wn()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(x(this,oe).addObserver(this),_i(x(this,oe),this.options)?ae(this,he,Kr).call(this):this.updateResult(),ae(this,he,En).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Cn(x(this,oe),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Cn(x(this,oe),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,ae(this,he,jn).call(this),ae(this,he,Tn).call(this),x(this,oe).removeObserver(this)}setOptions(e){const r=this.options,s=x(this,oe);if(this.options=x(this,Fe).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ge(this.options.enabled,x(this,oe))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");ae(this,he,Rn).call(this),x(this,oe).setOptions(this.options),r._defaulted&&!mn(this.options,r)&&x(this,Fe).getQueryCache().notify({type:"observerOptionsUpdated",query:x(this,oe),observer:this});const n=this.hasListeners();n&&ki(x(this,oe),s,this.options,r)&&ae(this,he,Kr).call(this),this.updateResult(),n&&(x(this,oe)!==s||Ge(this.options.enabled,x(this,oe))!==Ge(r.enabled,x(this,oe))||Nt(this.options.staleTime,x(this,oe))!==Nt(r.staleTime,x(this,oe)))&&ae(this,he,_n).call(this);const i=ae(this,he,kn).call(this);n&&(x(this,oe)!==s||Ge(this.options.enabled,x(this,oe))!==Ge(r.enabled,x(this,oe))||i!==x(this,Ct))&&ae(this,he,Sn).call(this,i)}getOptimisticResult(e){const r=x(this,Fe).getQueryCache().build(x(this,Fe),e),s=this.createResult(r,e);return zc(this,s)&&(M(this,Be,s),M(this,Sr,this.options),M(this,tr,x(this,oe).state)),s}getCurrentResult(){return x(this,Be)}trackResult(e,r){return new Proxy(e,{get:(s,n)=>(this.trackProp(n),r==null||r(n),n==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&x(this,ht).status==="pending"&&x(this,ht).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,n))})}trackProp(e){x(this,Tr).add(e)}getCurrentQuery(){return x(this,oe)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=x(this,Fe).defaultQueryOptions(e),s=x(this,Fe).getQueryCache().build(x(this,Fe),r);return s.fetch().then(()=>this.createResult(s,r))}fetch(e){return ae(this,he,Kr).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),x(this,Be)))}createResult(e,r){var B;const s=x(this,oe),n=this.options,i=x(this,Be),a=x(this,tr),l=x(this,Sr),u=e!==s?e.state:x(this,os),{state:d}=e;let p={...d},f=!1,h;if(r._optimisticResults){const E=this.hasListeners(),A=!E&&_i(e,r),T=E&&ki(e,s,r,n);(A||T)&&(p={...p,...pa(d.data,e.options)}),r._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:m,errorUpdatedAt:g,status:_}=p;h=p.data;let w=!1;if(r.placeholderData!==void 0&&h===void 0&&_==="pending"){let E;i!=null&&i.isPlaceholderData&&r.placeholderData===(l==null?void 0:l.placeholderData)?(E=i.data,w=!0):E=typeof r.placeholderData=="function"?r.placeholderData((B=x(this,jr))==null?void 0:B.state.data,x(this,jr)):r.placeholderData,E!==void 0&&(_="success",h=vn(i==null?void 0:i.data,E,r),f=!0)}if(r.select&&h!==void 0&&!w)if(i&&h===(a==null?void 0:a.data)&&r.select===x(this,ls))h=x(this,Er);else try{M(this,ls,r.select),h=r.select(h),h=vn(i==null?void 0:i.data,h,r),M(this,Er,h),M(this,Rt,null)}catch(E){M(this,Rt,E)}x(this,Rt)&&(m=x(this,Rt),h=x(this,Er),g=Date.now(),_="error");const k=p.fetchStatus==="fetching",b=_==="pending",S=_==="error",j=b&&k,C=h!==void 0,O={status:_,fetchStatus:p.fetchStatus,isPending:b,isSuccess:_==="success",isError:S,isInitialLoading:j,isLoading:j,data:h,dataUpdatedAt:p.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:p.dataUpdateCount>0||p.errorUpdateCount>0,isFetchedAfterMount:p.dataUpdateCount>u.dataUpdateCount||p.errorUpdateCount>u.errorUpdateCount,isFetching:k,isRefetching:k&&!b,isLoadingError:S&&!C,isPaused:p.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:S&&C,isStale:Bn(e,r),refetch:this.refetch,promise:x(this,ht),isEnabled:Ge(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const E=O.data!==void 0,A=O.status==="error"&&!E,T=z=>{A?z.reject(O.error):E&&z.resolve(O.data)},I=()=>{const z=M(this,ht,O.promise=wn());T(z)},N=x(this,ht);switch(N.status){case"pending":e.queryHash===s.queryHash&&T(N);break;case"fulfilled":(A||O.data!==N.value)&&I();break;case"rejected":(!A||O.error!==N.reason)&&I();break}}return O}updateResult(){const e=x(this,Be),r=this.createResult(x(this,oe),this.options);if(M(this,tr,x(this,oe).state),M(this,Sr,this.options),x(this,tr).data!==void 0&&M(this,jr,x(this,oe)),mn(r,e))return;M(this,Be,r);const s=()=>{if(!e)return!0;const{notifyOnChangeProps:n}=this.options,i=typeof n=="function"?n():n;if(i==="all"||!i&&!x(this,Tr).size)return!0;const a=new Set(i??x(this,Tr));return this.options.throwOnError&&a.add("error"),Object.keys(x(this,Be)).some(l=>{const c=l;return x(this,Be)[c]!==e[c]&&a.has(c)})};ae(this,he,ga).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&ae(this,he,En).call(this)}},Fe=new WeakMap,oe=new WeakMap,os=new WeakMap,Be=new WeakMap,tr=new WeakMap,Sr=new WeakMap,ht=new WeakMap,Rt=new WeakMap,ls=new WeakMap,Er=new WeakMap,jr=new WeakMap,rr=new WeakMap,sr=new WeakMap,Ct=new WeakMap,Tr=new WeakMap,he=new WeakSet,Kr=function(e){ae(this,he,Rn).call(this);let r=x(this,oe).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(De)),r},_n=function(){ae(this,he,jn).call(this);const e=Nt(this.options.staleTime,x(this,oe));if(ir||x(this,Be).isStale||!gn(e))return;const s=la(x(this,Be).dataUpdatedAt,e)+1;M(this,rr,Gt.setTimeout(()=>{x(this,Be).isStale||this.updateResult()},s))},kn=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(x(this,oe)):this.options.refetchInterval)??!1},Sn=function(e){ae(this,he,Tn).call(this),M(this,Ct,e),!(ir||Ge(this.options.enabled,x(this,oe))===!1||!gn(x(this,Ct))||x(this,Ct)===0)&&M(this,sr,Gt.setInterval(()=>{(this.options.refetchIntervalInBackground||Nn.isFocused())&&ae(this,he,Kr).call(this)},x(this,Ct)))},En=function(){ae(this,he,_n).call(this),ae(this,he,Sn).call(this,ae(this,he,kn).call(this))},jn=function(){x(this,rr)&&(Gt.clearTimeout(x(this,rr)),M(this,rr,void 0))},Tn=function(){x(this,sr)&&(Gt.clearInterval(x(this,sr)),M(this,sr,void 0))},Rn=function(){const e=x(this,Fe).getQueryCache().build(x(this,Fe),this.options);if(e===x(this,oe))return;const r=x(this,oe);M(this,oe,e),M(this,os,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},ga=function(e){Ie.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(x(this,Be))}),x(this,Fe).getQueryCache().notify({query:x(this,oe),type:"observerResultsUpdated"})})},Wi);function qc(t,e){return Ge(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function _i(t,e){return qc(t,e)||t.state.data!==void 0&&Cn(t,e,e.refetchOnMount)}function Cn(t,e,r){if(Ge(e.enabled,t)!==!1&&Nt(e.staleTime,t)!=="static"){const s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&Bn(t,e)}return!1}function ki(t,e,r,s){return(t!==e||Ge(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&Bn(t,r)}function Bn(t,e){return Ge(e.enabled,t)!==!1&&t.isStaleByTime(Nt(e.staleTime,t))}function zc(t,e){return!mn(t.getCurrentResult(),e)}function Si(t){return{onFetch:(e,r)=>{var d,p,f,h,m;const s=e.options,n=(f=(p=(d=e.fetchOptions)==null?void 0:d.meta)==null?void 0:p.fetchMore)==null?void 0:f.direction,i=((h=e.state.data)==null?void 0:h.pages)||[],a=((m=e.state.data)==null?void 0:m.pageParams)||[];let l={pages:[],pageParams:[]},c=0;const u=async()=>{let g=!1;const _=b=>{Bc(b,()=>e.signal,()=>g=!0)},w=ca(e.options,e.fetchOptions),k=async(b,S,j)=>{if(g)return Promise.reject();if(S==null&&b.pages.length)return Promise.resolve(b);const F=(()=>{const A={client:e.client,queryKey:e.queryKey,pageParam:S,direction:j?"backward":"forward",meta:e.options.meta};return _(A),A})(),O=await w(F),{maxPages:B}=e.options,E=j?Nc:Pc;return{pages:E(b.pages,O,B),pageParams:E(b.pageParams,S,B)}};if(n&&i.length){const b=n==="backward",S=b?Hc:Ei,j={pages:i,pageParams:a},C=S(s,j);l=await k(j,C,b)}else{const b=t??i.length;do{const S=c===0?a[0]??s.initialPageParam:Ei(s,l);if(c>0&&S==null)break;l=await k(l,S),c++}while(c<b)}return l};e.options.persister?e.fetchFn=()=>{var g,_;return(_=(g=e.options).persister)==null?void 0:_.call(g,u,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=u}}}function Ei(t,{pages:e,pageParams:r}){const s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,r[s],r):void 0}function Hc(t,{pages:e,pageParams:r}){var s;return e.length>0?(s=t.getPreviousPageParam)==null?void 0:s.call(t,e[0],e,r[0],r):void 0}var cs,at,Pe,nr,ot,kt,qi,Kc=(qi=class extends fa{constructor(e){super();Y(this,ot);Y(this,cs);Y(this,at);Y(this,Pe);Y(this,nr);M(this,cs,e.client),this.mutationId=e.mutationId,M(this,Pe,e.mutationCache),M(this,at,[]),this.state=e.state||Vc(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){x(this,at).includes(e)||(x(this,at).push(e),this.clearGcTimeout(),x(this,Pe).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){M(this,at,x(this,at).filter(r=>r!==e)),this.scheduleGc(),x(this,Pe).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){x(this,at).length||(this.state.status==="pending"?this.scheduleGc():x(this,Pe).remove(this))}continue(){var e;return((e=x(this,nr))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,l,c,u,d,p,f,h,m,g,_,w,k,b,S,j,C,F;const r=()=>{ae(this,ot,kt).call(this,{type:"continue"})},s={client:x(this,cs),meta:this.options.meta,mutationKey:this.options.mutationKey};M(this,nr,ha({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(O,B)=>{ae(this,ot,kt).call(this,{type:"failed",failureCount:O,error:B})},onPause:()=>{ae(this,ot,kt).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>x(this,Pe).canRun(this)}));const n=this.state.status==="pending",i=!x(this,nr).canStart();try{if(n)r();else{ae(this,ot,kt).call(this,{type:"pending",variables:e,isPaused:i}),x(this,Pe).config.onMutate&&await x(this,Pe).config.onMutate(e,this,s);const B=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,e,s));B!==this.state.context&&ae(this,ot,kt).call(this,{type:"pending",context:B,variables:e,isPaused:i})}const O=await x(this,nr).start();return await((u=(c=x(this,Pe).config).onSuccess)==null?void 0:u.call(c,O,e,this.state.context,this,s)),await((p=(d=this.options).onSuccess)==null?void 0:p.call(d,O,e,this.state.context,s)),await((h=(f=x(this,Pe).config).onSettled)==null?void 0:h.call(f,O,null,this.state.variables,this.state.context,this,s)),await((g=(m=this.options).onSettled)==null?void 0:g.call(m,O,null,e,this.state.context,s)),ae(this,ot,kt).call(this,{type:"success",data:O}),O}catch(O){try{await((w=(_=x(this,Pe).config).onError)==null?void 0:w.call(_,O,e,this.state.context,this,s))}catch(B){Promise.reject(B)}try{await((b=(k=this.options).onError)==null?void 0:b.call(k,O,e,this.state.context,s))}catch(B){Promise.reject(B)}try{await((j=(S=x(this,Pe).config).onSettled)==null?void 0:j.call(S,void 0,O,this.state.variables,this.state.context,this,s))}catch(B){Promise.reject(B)}try{await((F=(C=this.options).onSettled)==null?void 0:F.call(C,void 0,O,e,this.state.context,s))}catch(B){Promise.reject(B)}throw ae(this,ot,kt).call(this,{type:"error",error:O}),O}finally{x(this,Pe).runNext(this)}}},cs=new WeakMap,at=new WeakMap,Pe=new WeakMap,nr=new WeakMap,ot=new WeakSet,kt=function(e){const r=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=r(this.state),Ie.batch(()=>{x(this,at).forEach(s=>{s.onMutationUpdate(e)}),x(this,Pe).notify({mutation:this,type:"updated",action:e})})},qi);function Vc(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ft,tt,us,zi,Gc=(zi=class extends hs{constructor(e={}){super();Y(this,ft);Y(this,tt);Y(this,us);this.config=e,M(this,ft,new Set),M(this,tt,new Map),M(this,us,0)}build(e,r,s){const n=new Kc({client:e,mutationCache:this,mutationId:++ms(this,us)._,options:e.defaultMutationOptions(r),state:s});return this.add(n),n}add(e){x(this,ft).add(e);const r=Ss(e);if(typeof r=="string"){const s=x(this,tt).get(r);s?s.push(e):x(this,tt).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(x(this,ft).delete(e)){const r=Ss(e);if(typeof r=="string"){const s=x(this,tt).get(r);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&x(this,tt).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=Ss(e);if(typeof r=="string"){const s=x(this,tt).get(r),n=s==null?void 0:s.find(i=>i.state.status==="pending");return!n||n===e}else return!0}runNext(e){var s;const r=Ss(e);if(typeof r=="string"){const n=(s=x(this,tt).get(r))==null?void 0:s.find(i=>i!==e&&i.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Ie.batch(()=>{x(this,ft).forEach(e=>{this.notify({type:"removed",mutation:e})}),x(this,ft).clear(),x(this,tt).clear()})}getAll(){return Array.from(x(this,ft))}find(e){const r={exact:!0,...e};return this.getAll().find(s=>mi(r,s))}findAll(e={}){return this.getAll().filter(r=>mi(e,r))}notify(e){Ie.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return Ie.batch(()=>Promise.all(e.map(r=>r.continue().catch(De))))}},ft=new WeakMap,tt=new WeakMap,us=new WeakMap,zi);function Ss(t){var e;return(e=t.options.scope)==null?void 0:e.id}var lt,Hi,Jc=(Hi=class extends hs{constructor(e={}){super();Y(this,lt);this.config=e,M(this,lt,new Map)}build(e,r,s){const n=r.queryKey,i=r.queryHash??Pn(n,r);let a=this.get(i);return a||(a=new Mc({client:e,queryKey:n,queryHash:i,options:e.defaultQueryOptions(r),state:s,defaultOptions:e.getQueryDefaults(n)}),this.add(a)),a}add(e){x(this,lt).has(e.queryHash)||(x(this,lt).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=x(this,lt).get(e.queryHash);r&&(e.destroy(),r===e&&x(this,lt).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Ie.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return x(this,lt).get(e)}getAll(){return[...x(this,lt).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(s=>bi(r,s))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(s=>bi(e,s)):r}notify(e){Ie.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){Ie.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ie.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},lt=new WeakMap,Hi),ve,Ot,At,Rr,Cr,It,Or,Ar,Ki,Qc=(Ki=class{constructor(t={}){Y(this,ve);Y(this,Ot);Y(this,At);Y(this,Rr);Y(this,Cr);Y(this,It);Y(this,Or);Y(this,Ar);M(this,ve,t.queryCache||new Jc),M(this,Ot,t.mutationCache||new Gc),M(this,At,t.defaultOptions||{}),M(this,Rr,new Map),M(this,Cr,new Map),M(this,It,0)}mount(){ms(this,It)._++,x(this,It)===1&&(M(this,Or,Nn.subscribe(async t=>{t&&(await this.resumePausedMutations(),x(this,ve).onFocus())})),M(this,Ar,Os.subscribe(async t=>{t&&(await this.resumePausedMutations(),x(this,ve).onOnline())})))}unmount(){var t,e;ms(this,It)._--,x(this,It)===0&&((t=x(this,Or))==null||t.call(this),M(this,Or,void 0),(e=x(this,Ar))==null||e.call(this),M(this,Ar,void 0))}isFetching(t){return x(this,ve).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return x(this,Ot).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=x(this,ve).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=x(this,ve).build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(Nt(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return x(this,ve).findAll(t).map(({queryKey:e,state:r})=>{const s=r.data;return[e,s]})}setQueryData(t,e,r){const s=this.defaultQueryOptions({queryKey:t}),n=x(this,ve).get(s.queryHash),i=n==null?void 0:n.state.data,a=Oc(e,i);if(a!==void 0)return x(this,ve).build(this,s).setData(a,{...r,manual:!0})}setQueriesData(t,e,r){return Ie.batch(()=>x(this,ve).findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,r)]))}getQueryState(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=x(this,ve).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=x(this,ve);Ie.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=x(this,ve);return Ie.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},s=Ie.batch(()=>x(this,ve).findAll(t).map(n=>n.cancel(r)));return Promise.all(s).then(De).catch(De)}invalidateQueries(t,e={}){return Ie.batch(()=>(x(this,ve).findAll(t).forEach(r=>{r.invalidate()}),(t==null?void 0:t.refetchType)==="none"?Promise.resolve():this.refetchQueries({...t,type:(t==null?void 0:t.refetchType)??(t==null?void 0:t.type)??"active"},e)))}refetchQueries(t,e={}){const r={...e,cancelRefetch:e.cancelRefetch??!0},s=Ie.batch(()=>x(this,ve).findAll(t).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let i=n.fetch(void 0,r);return r.throwOnError||(i=i.catch(De)),n.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(De)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=x(this,ve).build(this,e);return r.isStaleByTime(Nt(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(De).catch(De)}fetchInfiniteQuery(t){return t.behavior=Si(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(De).catch(De)}ensureInfiniteQueryData(t){return t.behavior=Si(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return Os.isOnline()?x(this,Ot).resumePausedMutations():Promise.resolve()}getQueryCache(){return x(this,ve)}getMutationCache(){return x(this,Ot)}getDefaultOptions(){return x(this,At)}setDefaultOptions(t){M(this,At,t)}setQueryDefaults(t,e){x(this,Rr).set(ss(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...x(this,Rr).values()],r={};return e.forEach(s=>{ns(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){x(this,Cr).set(ss(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...x(this,Cr).values()],r={};return e.forEach(s=>{ns(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...x(this,At).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=Pn(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===Cs&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...x(this,At).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){x(this,ve).clear(),x(this,Ot).clear()}},ve=new WeakMap,Ot=new WeakMap,At=new WeakMap,Rr=new WeakMap,Cr=new WeakMap,It=new WeakMap,Or=new WeakMap,Ar=new WeakMap,Ki),ba=Je.createContext(void 0),ma=t=>{const e=Je.useContext(ba);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},Yc=({client:t,children:e})=>(Je.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),o.jsx(ba.Provider,{value:t,children:e})),ya=Je.createContext(!1),Xc=()=>Je.useContext(ya);ya.Provider;function Zc(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var eu=Je.createContext(Zc()),tu=()=>Je.useContext(eu),ru=(t,e,r)=>{const s=r!=null&&r.state.error&&typeof t.throwOnError=="function"?ua(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},su=t=>{Je.useEffect(()=>{t.clearReset()},[t])},nu=({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:n})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(n&&t.data===void 0||ua(r,[t.error,s])),iu=t=>{if(t.suspense){const r=n=>n==="static"?n:Math.max(n??1e3,1e3),s=t.staleTime;t.staleTime=typeof s=="function"?(...n)=>r(s(...n)):r(s),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},au=(t,e)=>t.isLoading&&t.isFetching&&!e,ou=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,ji=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function lu(t,e,r){var f,h,m,g;if(process.env.NODE_ENV!=="production"&&(typeof t!="object"||Array.isArray(t)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const s=Xc(),n=tu(),i=ma(),a=i.defaultQueryOptions(t);(h=(f=i.getDefaultOptions().queries)==null?void 0:f._experimental_beforeQuery)==null||h.call(f,a);const l=i.getQueryCache().get(a.queryHash);process.env.NODE_ENV!=="production"&&(a.queryFn||console.error(`[${a.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),a._optimisticResults=s?"isRestoring":"optimistic",iu(a),ru(a,n,l),su(n);const c=!i.getQueryCache().get(a.queryHash),[u]=Je.useState(()=>new e(i,a)),d=u.getOptimisticResult(a),p=!s&&t.subscribed!==!1;if(Je.useSyncExternalStore(Je.useCallback(_=>{const w=p?u.subscribe(Ie.batchCalls(_)):De;return u.updateResult(),w},[u,p]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),Je.useEffect(()=>{u.setOptions(a)},[a,u]),ou(a,d))throw ji(a,u,n);if(nu({result:d,errorResetBoundary:n,throwOnError:a.throwOnError,query:l,suspense:a.suspense}))throw d.error;if((g=(m=i.getDefaultOptions().queries)==null?void 0:m._experimental_afterQuery)==null||g.call(m,a,d),a.experimental_prefetchInRender&&!ir&&au(d,s)){const _=c?ji(a,u,n):l==null?void 0:l.promise;_==null||_.catch(De).finally(()=>{u.updateResult()})}return a.notifyOnChangeProps?d:u.trackResult(d)}function fs(t,e){return lu(t,Wc)}const cu=()=>`bob_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;function va({ga4Config:t,hostContext:e,callbacks:r,enabled:s=!0}){const n=y.useRef(cu()),i=y.useRef(!1),a=y.useCallback((b,S)=>{if(!(!(t!=null&&t.measurementId)||typeof window>"u")&&window.gtag){const j={...S,send_to:t.measurementId};t.debug&&console.log("[BobAnalytics] GA4 event:",b,j),window.gtag("event",b,j)}},[t]),l=y.useCallback((b,S={})=>{var C,F,O,B,E,A,T,I;if(!s)return;const j={event_name:b,timestamp:new Date().toISOString(),session_id:n.current,user_email:(C=e==null?void 0:e.user)==null?void 0:C.email,user_id:(F=e==null?void 0:e.user)==null?void 0:F.id,vehicle_id:(E=(B=(O=e==null?void 0:e.vehicle)==null?void 0:O.selectedVehicle)==null?void 0:B.vehicle_id)==null?void 0:E.toString(),rego:(T=(A=e==null?void 0:e.vehicle)==null?void 0:A.selectedVehicle)==null?void 0:T.rego,parameters:S};a(b,{session_id:j.session_id,user_email:j.user_email,vehicle_id:j.vehicle_id,...S}),(I=r==null?void 0:r.onAnalyticsEvent)==null||I.call(r,j),t!=null&&t.debug&&console.log("[BobAnalytics] Event tracked:",j)},[s,e,r,a,t==null?void 0:t.debug]),c=y.useCallback(()=>{var b,S,j;i.current||(i.current=!0,l("bob_session_start",{widget_version:pt,has_vehicle:!!((b=e==null?void 0:e.vehicle)!=null&&b.selectedVehicle),has_user:!!((S=e==null?void 0:e.user)!=null&&S.id)||!!((j=e==null?void 0:e.user)!=null&&j.email)}))},[l,e]),u=y.useCallback((b,S)=>{l("bob_message_sent",{message_length:b,has_vehicle:S})},[l]),d=y.useCallback(b=>{l("bob_vehicle_identified",{vehicle_make:b.make||"unknown",vehicle_model:b.model||"unknown",vehicle_year:b.year||"unknown",rego:b.rego})},[l]),p=y.useCallback((b,S)=>{l("bob_parts_viewed",{part_count:b,vehicle_id:S})},[l]),f=y.useCallback(b=>{l("bob_product_clicked",{sku:b.sku,product_name:b.product_name,price:b.price,brand:b.brand})},[l]),h=y.useCallback(b=>{l("bob_product_viewed",{sku:b.sku,product_name:b.product_name,price:b.price,brand:b.brand})},[l]),m=y.useCallback(b=>{l("bob_add_to_cart",{sku:b.sku,product_name:b.product_name,price:b.price,brand:b.brand,quantity:b.quantity??1})},[l]),g=y.useCallback((b,S)=>{l("bob_checkout_started",{cart_value:b,item_count:S})},[l]),_=y.useCallback(b=>{const S=Math.ceil(b/5/150*60);l("bob_speech_played",{text_length:b,duration_estimate:S})},[l]),w=y.useCallback(b=>{l("bob_speech_failed",{text_length:b})},[l]),k=y.useCallback((b,S)=>{l("bob_error",{error_type:b,error_message:S})},[l]);return y.useEffect(()=>{c()},[c]),{trackEvent:l,sessionId:n.current,trackSessionStart:c,trackMessageSent:u,trackVehicleIdentified:d,trackPartsViewed:p,trackProductClicked:f,trackProductViewed:h,trackAddToCart:m,trackCheckoutStarted:g,trackSpeechPlayed:_,trackSpeechFailed:w,trackError:k}}const $s=y.createContext(null);function $n({children:t,bobConfig:e,hostApiConfig:r,hostContext:s={},callbacks:n={},queryClient:i,ga4Config:a,analyticsEnabled:l=!0,bottomOffset:c=0,zIndexBase:u=50}){const d=y.useMemo(()=>new Qc({defaultOptions:{queries:{retry:1,staleTime:3e5}}}),[]),p=i||d,f=!!i;y.useEffect(()=>{console.log(`[BobWidget] v${pt} initialized`),console.log(`[BobWidget] QueryClient: ${f?"external (shared)":"internal"}`),console.log(`[BobWidget] Analytics: ${l?"enabled":"disabled"}`),a!=null&&a.measurementId&&console.log(`[BobWidget] GA4: ${a.measurementId}`)},[f,l,a==null?void 0:a.measurementId]);const h=y.useMemo(()=>pn(e.supabaseUrl,e.supabaseKey),[e.supabaseUrl,e.supabaseKey]),[m,g]=y.useState(s);y.useEffect(()=>{g(s)},[s]);const _=y.useCallback(k=>{g(b=>({...b,...k}))},[]),w=y.useMemo(()=>({bobSupabase:h,bobConfig:e,hostApiConfig:r,hostContext:m,callbacks:n,updateHostContext:_,ga4Config:a,analyticsEnabled:l,bottomOffset:c,zIndexBase:u}),[h,e,r,m,n,_,a,l,c,u]);return o.jsx(Yc,{client:p,children:o.jsx($s.Provider,{value:w,children:t})})}function bt(){const t=y.useContext($s);if(!t)throw new Error("useBobContext must be used within a BobProvider");return t}function uu(){const{bobSupabase:t}=bt();return t}function ar(){const t=y.useContext($s);return(t==null?void 0:t.bobSupabase)||null}function du(){const{hostContext:t}=bt();return t}function hu(){const{hostApiConfig:t}=bt();return t}function fu(){const{callbacks:t}=bt();return t}function pu(){const{ga4Config:t,analyticsEnabled:e}=bt();return{ga4Config:t,enabled:e}}function Fn(){const t=y.useContext($s);return t?{bottomOffset:t.bottomOffset,zIndexBase:t.zIndexBase}:{bottomOffset:0,zIndexBase:50}}const gu=15e3,bu={greeting_returning:/ah hey|you again|what you after this time/i,greeting_welcome:/g'?day|welcome.*carfix|bob.*here/i,ask_rego:/need your rego|rego.*get cracking|what('?s| is) your rego/i,vehicle_not_found:/couldn'?t find that|double.?check.*plate/i,no_parts_found:/nothing came up|no results|sorry.*search/i,checkout_ready:/ready to checkout|checkout.*ready|choice.*checkout/i,rego_searching:/let('?s| us) see what car|sweet.*searching|searching for/i},qr=new Map,mu=t=>t.replace(/\bya\b/gi,"you"),wa=({onStart:t,onEnd:e,onFailed:r}={})=>{const{bobConfig:s,bobSupabase:n}=bt(),[i,a]=y.useState(!1),l=y.useRef(null),c=y.useRef(null),u=y.useRef(!1),d=y.useRef([]),p=y.useRef(!1),f=y.useRef(!1),h=y.useRef(null),m=y.useRef(null),g=y.useRef(t),_=y.useRef(e),w=y.useRef(r);y.useEffect(()=>{g.current=t,_.current=e,w.current=r},[t,e,r]);const k=y.useCallback(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]),b=y.useCallback(()=>{var T;u.current||(u.current=!0,console.log("[BobWidget TTS] Fallback: triggering onStart without audio"),(T=g.current)==null||T.call(g))},[]),S=y.useCallback(async T=>{if(qr.has(T)){const I=qr.get(T);return console.log(`[BobWidget TTS] Cache hit for clip: ${T}`,I?"found":"null"),I||null}try{console.log(`[BobWidget TTS] Fetching clip from DB: ${T}`);const{data:I,error:N}=await n.from("bob_audio_clips").select("audio_url").eq("clip_key",T).eq("is_active",!0).single();return N||!I?(console.log(`[BobWidget TTS] No clip found for: ${T}`),qr.set(T,null),null):(console.log(`[BobWidget TTS] Clip found: ${T} -> ${I.audio_url}`),qr.set(T,I),I)}catch(I){return console.warn(`[BobWidget TTS] Clip lookup failed for ${T}:`,I),qr.set(T,null),null}},[n]),j=y.useCallback(async T=>{for(const[I,N]of Object.entries(bu))if(N.test(T)){console.log(`[BobWidget TTS] Pattern matched: ${I}`);const z=await S(I);if(z!=null&&z.audio_url)return z.audio_url}return null},[S]),C=y.useCallback(async()=>{var z,P,te;if(p.current||d.current.length===0)return;p.current=!0;const T=d.current.shift();if(!T){p.current=!1;return}const{text:I,isGreeting:N}=T;N&&(f.current=!0),u.current=!1,k(),l.current&&(l.current.pause(),l.current=null),c.current=setTimeout(()=>{var K,$;console.warn("[BobWidget TTS] Timeout - triggering fallback callbacks"),b(),a(!1),f.current=!1,(K=_.current)==null||K.call(_),($=w.current)==null||$.call(w),l.current=null,p.current=!1,C()},gu);try{let K=null;if(K=await j(I),K)console.log("[BobWidget TTS] Using pre-recorded audio (fast path)");else{console.log("[BobWidget TTS] No pre-recorded clip, using ElevenLabs TTS");const U=mu(I),W=await fetch(`${s.supabaseUrl}/functions/v1/bob-tts-elevenlabs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.supabaseKey}`},body:JSON.stringify({text:U})});if(!W.ok){const J=await W.json().catch(()=>({}));throw console.error("[BobWidget TTS] Request failed:",J),new Error("TTS request failed")}const q=await W.blob();K=URL.createObjectURL(q)}const $=new Audio(K);l.current=$,$.onplay=()=>{var U;k(),h.current=null,u.current||(u.current=!0,a(!0),console.log("[BobWidget TTS] Audio playing, triggering onStart (animation: TALKING)"),(U=g.current)==null||U.call(g))},$.onended=()=>{var U;k(),a(!1),f.current=!1,console.log("[BobWidget TTS] Audio ended, triggering onEnd (animation: COMPLETE/IDLE)"),(U=_.current)==null||U.call(_),l.current=null,p.current=!1,C()},$.onerror=U=>{var W,q;k(),console.warn("[BobWidget TTS] Audio playback error:",U),b(),a(!1),f.current=!1,(W=_.current)==null||W.call(_),(q=w.current)==null||q.call(w),l.current=null,p.current=!1,C()};try{await $.play()}catch(U){console.warn("[BobWidget TTS] Audio play() failed (autoplay policy):",U),k(),N&&(h.current=I,console.log("[BobWidget TTS] Greeting stored for retry on user interaction")),b(),a(!1),f.current=!1,(z=_.current)==null||z.call(_),p.current=!1,C()}}catch(K){k(),console.error("[BobWidget TTS] Speech synthesis error:",K),b(),a(!1),f.current=!1,(P=_.current)==null||P.call(_),(te=w.current)==null||te.call(w),p.current=!1,C()}},[s.supabaseUrl,s.supabaseKey,k,b,j]),F=y.useCallback((T,I=!1)=>{if(T.trim()){if(I){if(m.current===T){console.log(`[BobWidget TTS] Ignoring duplicate greeting: "${T.substring(0,30)}..."`);return}m.current=T,h.current=null}if(f.current&&!I){console.log("[BobWidget TTS] Greeting playing - queueing message"),d.current.push({text:T,isGreeting:I});return}I?d.current.unshift({text:T,isGreeting:I}):d.current.push({text:T,isGreeting:I}),C()}},[C]),O=y.useCallback(()=>{if(h.current&&!l.current&&!p.current){console.log("[BobWidget TTS] Retrying pending greeting on user interaction");const T=h.current;h.current=null,F(T,!0)}},[F]),B=y.useCallback(()=>{k(),d.current=[],l.current&&(l.current.pause(),l.current=null),a(!1),f.current=!1,p.current=!1},[k]),E=y.useCallback(()=>{var T;(T=l.current)==null||T.pause()},[]),A=y.useCallback(()=>{var T;(T=l.current)==null||T.play()},[]);return y.useEffect(()=>()=>{k(),d.current=[],l.current&&(l.current.pause(),l.current=null)},[k]),{speak:F,stop:B,pause:E,resume:A,isSpeaking:i,isSupported:!0,retryPendingGreeting:O}},Ti="bob_last_visit",yu=30;function xa(t=yu){const[e,r]=y.useState(!1),[s,n]=y.useState(null);return y.useEffect(()=>{try{const i=localStorage.getItem(Ti),a=Date.now();if(i){const l=parseInt(i,10),c=(a-l)/(1e3*60*60*24);c<=t?(r(!0),n(new Date(l)),console.log(`[BobWidget] Returning user detected - last visit ${Math.round(c)} days ago`)):console.log(`[BobWidget] Previous visit was ${Math.round(c)} days ago - treating as new user`)}else console.log("[BobWidget] First time visitor detected");localStorage.setItem(Ti,String(a))}catch(i){console.warn("[BobWidget] Could not access localStorage for returning user detection:",i)}},[t]),{isReturningUser:e,lastVisitDate:s,daysSinceLastVisit:s?Math.round((Date.now()-s.getTime())/(1e3*60*60*24)):null}}const On=t=>{if(!t)return t;let e=t;return e=e.replace(/\b(retrieve_parts|lookup_vehicle|search_general_products|retrieve_service_packages|add_to_cart|get_cart|create_checkout|get_customer_context|get_product_details|search_products|check_vehicle_fitment|search_web)\s*\([^)]*\)/gi,""),e=e.replace(/\(\s*(vehicleid|vehicle_id|part_type|query|plate|user_email|sku)\s*=\s*[^)]+\)/gi,""),e=e.replace(/\b(retrieve_parts|lookup_vehicle|search_general_products|retrieve_service_packages|add_to_cart|get_cart|create_checkout|get_customer_context|get_product_details|search_products|check_vehicle_fitment|search_web)\s*\(/gi,""),e=e.replace(/\b(vehicleid|vehicle_id|part_type)\s*=\s*(['"]?[\w\s]+['"]?)\s*,?\s*/gi,""),e=e.replace(/```[\s\S]*?```/g,""),e=e.replace(/\(\s*\)/g,""),e=e.replace(/\s{2,}/g," "),e=e.trim(),e},Zs=t=>{let e=On(t);return e=e.replace(/[\[\]{}]/g,""),e=e.replace(/https?:\/\/[^\s]+/g,""),e=e.replace(/\bSKU\s*:?\s*\w+/gi,""),e},vu=["what version","which version","software version","bob version","your version","current version","running version","version number","what ver","which ver"],Ri=["recommend","suggest","need","part","filter","brake","rotor","oil","price","$","stock","available","pads","disc","spark plug","battery","clutch","alternator","starter","muffler","exhaust","service pack","add-on","tyre shine","windscreen wash"],wu=["WIPER BLADE FRONT","WIPER BLADE REAR","WIPER BLADE SET","BRAKE PAD KIT","BRAKE PAD KIT FRONT","BRAKE PAD KIT REAR","BRAKE ROTOR","BRAKE ROTOR FRONT","BRAKE ROTOR REAR","BRAKE DISC","AIR FILTER","OIL FILTER","CABIN FILTER","FUEL FILTER","SPARK PLUG SET","SPARK PLUG","BALL JOINT","TIE ROD END","CONTROL ARM","WHEEL BEARING","CV JOINT","DRIVE SHAFT","TIMING BELT KIT","SERPENTINE BELT","DRIVE BELT","SHOCK ABSORBER","STRUT","COIL SPRING","CLUTCH KIT","CLUTCH PLATE","ALTERNATOR","STARTER MOTOR","WATER PUMP","THERMOSTAT","RADIATOR","RADIATOR HOSE","EXHAUST","MUFFLER","CATALYTIC CONVERTER","brake pads","brake rotors","brake discs","brakes","air filter","oil filter","cabin filter","fuel filter","spark plugs","spark plug","wiper","wipers","battery","batteries","clutch","clutch kit","alternator","starter motor","muffler","exhaust","cv joint","axle","timing belt","serpentine belt","shock absorber","struts","suspension"],_a=({setAnimationState:t,manualMode:e=!1,talkingState:r="talk",thinkingState:s="research",completeState:n="complete",idleState:i="idle",listenState:a="talk_pause",onStreamStart:l,onStreamComplete:c,onShowingProduct:u,onResearchStart:d,onReadyToSpeak:p,onHighlightPart:f,onHighlightProduct:h,onNoPartsFound:m,onAutoFetchComplete:g})=>{var gs,bs,Nr,Br;const{bobConfig:_,hostApiConfig:w,hostContext:k,callbacks:b,ga4Config:S,analyticsEnabled:j}=bt(),C=va({ga4Config:S,hostContext:k,callbacks:b,enabled:j}),{isReturningUser:F}=xa(),[O,B]=y.useState([]),[E,A]=y.useState(""),[T,I]=y.useState(!1),[N,z]=y.useState(!1),[P,te]=y.useState(null),K=y.useRef(null),$=y.useRef(!1),U=y.useRef(!1),W=y.useRef(""),q=y.useRef(!1),J=y.useRef(null),V=y.useRef(null),fe=y.useRef([]),ye=y.useRef(!1),je=y.useRef(null),ue=()=>{J.current&&(clearTimeout(J.current),J.current=null)},{speak:Te,stop:re,isSpeaking:qe,retryPendingGreeting:ze}=wa({onStart:()=>{ue(),q.current=!0,console.log("[BobWidget STATE] Speech STARTED - transitioning to TALK state"),C.trackSpeechPlayed(W.current.length),p==null||p(),e||(console.log("[BobWidget STATE] Setting state to:",r),ie(r))},onEnd:()=>{ue(),console.log("[BobWidget STATE] Speech ENDED - transitioning out of TALK state");const Q=Ri.some(ge=>W.current.toLowerCase().includes(ge.toLowerCase()));e||(Q&&u?(console.log("[BobWidget STATE] Has products - calling onShowingProduct"),u()):c?(console.log("[BobWidget STATE] Calling onStreamComplete"),c()):(console.log("[BobWidget STATE] Setting state to:",n),ie(n),setTimeout(()=>{console.log("[BobWidget STATE] Post-complete transition to:",a),ie(a)},2e3)))},onFailed:()=>{console.warn("[BobWidget] Speech synthesis failed - fallback triggered"),C.trackSpeechFailed(W.current.length)}});y.useEffect(()=>{var Q;(Q=K.current)==null||Q.scrollIntoView({behavior:"smooth"})},[O]),y.useEffect(()=>{var ge,ke;const Q=(ge=k.vehicle)==null?void 0:ge.selectedVehicle;Q&&!P&&(console.log("[BobWidget] Setting vehicle from host context:",Q),te(Q),(ke=b.onVehicleIdentified)==null||ke.call(b,Q),C.trackVehicleIdentified({make:Q.make,model:Q.model,year:Q.year,rego:Q.rego}))},[(gs=k.vehicle)==null?void 0:gs.selectedVehicle]),y.useEffect(()=>{var Q;if(O.length===0&&!U.current){U.current=!0;const ge=(Q=k.vehicle)==null?void 0:Q.selectedVehicle;let ke;F?(ke="Ah hey... you again! What you after this time?",console.log("[BobWidget] Using returning user greeting")):ge?ke=`G'day! Saw you've got the ${`${ge.year} ${ge.make} ${ge.model}`} - choice wagon! What can I help you find for it today?`:ke="G'day! Bob from CARFIX here. How can I help ya today?",B([{role:"assistant",content:ke}]),N||setTimeout(()=>{console.log("[BobWidget] Speaking initial greeting (priority)"),Te(ke,!0)},500)}},[(bs=k.vehicle)==null?void 0:bs.selectedVehicle,O.length,N,Te]),y.useEffect(()=>{const Q=()=>{console.log("[BobWidget] User interaction detected - retrying pending greeting"),ze(),document.removeEventListener("click",Q),document.removeEventListener("touchstart",Q)};return document.addEventListener("click",Q,{once:!0}),document.addEventListener("touchstart",Q,{once:!0}),()=>{document.removeEventListener("click",Q),document.removeEventListener("touchstart",Q)}},[ze]),y.useEffect(()=>{var Bt,$t;const Q=(Bt=k.vehicle)==null?void 0:Bt.selectedVehicle;if(!Q||$.current)return;const ge=Q.vehicle_id??Q.id,ke=Number.parseInt(String(ge),10);if(!Number.isFinite(ke)){console.warn("[BobWidget] Vehicle has invalid vehicle_id, cannot auto-fetch:",Q);return}$.current=!0;const Ne={...Q,vehicle_id:String(ke)},yt=($t=k.user)==null?void 0:$t.email;(async()=>{var Ft,Dt;const or=`${_.supabaseUrl}/functions/v1/bob-chat`;try{const Ue=await fetch(or,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${_.supabaseKey}`},body:JSON.stringify({messages:[],vehicleContext:Ne,customerEmail:yt,autoFetchParts:!0,hostConfig:w,hostContext:k})});if(!Ue.ok||!Ue.body){console.error("[BobWidget] Auto-fetch failed:",Ue.status);return}const Lt=Ue.body.getReader(),Qe=new TextDecoder;let He="";for(;;){const{done:vt,value:Ut}=await Lt.read();if(vt)break;He+=Qe.decode(Ut,{stream:!0});let wt;for(;(wt=He.indexOf(`
73
+ `))!==-1;){let Me=He.slice(0,wt);if(He=He.slice(wt+1),Me.endsWith("\r")&&(Me=Me.slice(0,-1)),Me.startsWith(":")||Me.trim()===""||!Me.startsWith("data: "))continue;const Mt=Me.slice(6).trim();if(Mt==="[DONE]")break;try{const Se=JSON.parse(Mt);Se.type==="service_packages_found"&&Se.packages&&((Ft=b.onServicePackagesFound)==null||Ft.call(b,Se.packages)),Se.type==="parts_found"&&Se.parts&&((Dt=b.onPartsFound)==null||Dt.call(b,Se.parts),C.trackPartsViewed(Array.isArray(Se.parts)?Se.parts.length:0,String(ke)))}catch{}}}g==null||g()}catch(Ue){console.error("[BobWidget] Auto-fetch error:",Ue)}})()},[(Nr=k.vehicle)==null?void 0:Nr.selectedVehicle,(Br=k.user)==null?void 0:Br.email]);const ie=Q=>{try{t(Q)}catch{console.warn(`[BobWidget] State "${Q}" not available`)}},Le=()=>{if(fe.current.length===0){ye.current=!1,e||ie(s);return}ye.current=!0;const Q=fe.current.shift(),ge=new Audio(Q);je.current=ge,ge.onplay=()=>{console.log("[BobWidget] Searching audio STARTED:",Q),e||ie(r)},ge.onended=()=>{console.log("[BobWidget] Searching audio ENDED, playing next..."),je.current=null,Le()},ge.onerror=()=>{console.warn("[BobWidget] Searching audio failed:",Q),je.current=null,Le()},ge.play().catch(()=>{console.warn("[BobWidget] Searching audio autoplay blocked:",Q),je.current=null,Le()})},xe=async Q=>{var Ne,yt,$r,Bt,$t,or,Ft,Dt,Ue,Lt,Qe,He,vt,Ut,wt,Me,Mt;const ge=`${_.supabaseUrl}/functions/v1/bob-chat`,ke=(Ne=k.user)==null?void 0:Ne.email;try{const Se={messages:[...O,Q],hostConfig:w,hostContext:k};P&&(Se.vehicleContext=P),ke&&(Se.customerEmail=ke);const Ke=await fetch(ge,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${_.supabaseKey}`},body:JSON.stringify(Se)});if(!Ke.ok){if(Ke.status===429){(yt=b.onError)==null||yt.call(b,new Error("Rate limit exceeded"));return}if(Ke.status===402){($r=b.onError)==null||$r.call(b,new Error("Payment required"));return}throw new Error("Failed to start stream")}if(!Ke.body)throw new Error("No response body");const Ms=Ke.body.getReader(),Ws=new TextDecoder;let nt="",Fr=!1,xt="";for(;!Fr;){const{done:R,value:D}=await Ms.read();if(R)break;nt+=Ws.decode(D,{stream:!0});let X;for(;(X=nt.indexOf(`
74
+ `))!==-1;){let se=nt.slice(0,X);if(nt=nt.slice(X+1),se.endsWith("\r")&&(se=se.slice(0,-1)),se.startsWith(":")||se.trim()===""||!se.startsWith("data: "))continue;const de=se.slice(6).trim();if(de==="[DONE]"){Fr=!0;break}try{const L=JSON.parse(de);if(L.type==="vehicle_identified"&&L.vehicle){te(L.vehicle),(Bt=b.onVehicleIdentified)==null||Bt.call(b,L.vehicle),C.trackVehicleIdentified({make:L.vehicle.make,model:L.vehicle.model,year:L.vehicle.year,rego:L.vehicle.rego});continue}if(L.type==="service_packages_found"&&L.packages){($t=b.onServicePackagesFound)==null||$t.call(b,L.packages);continue}if(L.type==="parts_found"&&L.parts){(or=b.onPartsFound)==null||or.call(b,L.parts),C.trackPartsViewed(Array.isArray(L.parts)?L.parts.length:0,(Ft=P==null?void 0:P.vehicle_id)==null?void 0:Ft.toString());continue}if(L.type==="bob_suggestions"&&L.products){console.log("[useBobChat] Received bob_suggestions:",L.products.length,"products",L.title),B(me=>{var Re;const ce=[...me],le=ce[ce.length-1];return console.log("[useBobChat] Attaching to message:",le==null?void 0:le.role,(Re=le==null?void 0:le.content)==null?void 0:Re.slice(0,40)),(le==null?void 0:le.role)==="assistant"?ce.map((Ye,ct)=>ct===ce.length-1?{...Ye,suggestedProducts:L.products,suggestionsTitle:L.title}:Ye):ce}),(Dt=b.onPartsFound)==null||Dt.call(b,L.products),C.trackPartsViewed(Array.isArray(L.products)?L.products.length:0,(Ue=P==null?void 0:P.vehicle_id)==null?void 0:Ue.toString());continue}if(L.type==="no_parts_found"){(Lt=b.onPartsFound)==null||Lt.call(b,[]),(Qe=b.onServicePackagesFound)==null||Qe.call(b,[]),m==null||m();continue}if(L.type==="audio_hint"&&L.audio_url){console.log("[useBobChat] Audio hint received:",L.clip_key,L.audio_url),V.current=L.audio_url;continue}if(L.type==="bob_searching"&&L.audio_url){console.log("[useBobChat] Bob searching:",L.search_type,L.clip_key),fe.current.push(L.audio_url),!ye.current&&!N&&Le();continue}if(L.type==="cart_updated"&&L.items){(He=b.onCartUpdated)==null||He.call(b,L.items);continue}const ne=(wt=(Ut=(vt=L.choices)==null?void 0:vt[0])==null?void 0:Ut.delta)==null?void 0:wt.content;if(ne){xt+=ne;let me=xt.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");me=On(me),B(ce=>{const le=ce[ce.length-1];return(le==null?void 0:le.role)==="assistant"?ce.map((Re,Ye)=>Ye===ce.length-1?{...Re,content:me}:Re):[...ce,{role:"assistant",content:me}]}),(Me=b.onBobMessage)==null||Me.call(b,me)}}catch{nt=se+`
75
+ `+nt;break}}}let Dr=xt.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");Dr=On(Dr),W.current=Dr;const Lr=Ri.some(R=>xt.toLowerCase().includes(R.toLowerCase())),qs=xt.toLowerCase();for(const R of wu)if(qs.includes(R.toLowerCase())){const D=R.replace(/s\s*$/i,"").toUpperCase();f==null||f(D);break}const v=xt.match(/(?:go with|recommend|suggest|grab|try)\s+(?:the\s+)?(\w+)\s+(?:at|for)\s+\$(\d+(?:\.\d{2})?)/i);if(v){const[,R,D]=v;h==null||h({brand:R,price:parseFloat(D)})}if(!N&&W.current.trim()){if(q.current=!1,ue(),V.current){console.log("[BobWidget] Playing canned audio:",V.current);const R=new Audio(V.current);R.onplay=()=>{console.log("[BobWidget] Canned audio STARTED"),q.current=!0,p==null||p(),e||ie(r)},R.onended=()=>{console.log("[BobWidget] Canned audio ENDED"),ue(),e||(Lr&&u?u():c?c():(ie(n),setTimeout(()=>ie(a),3e3)))},R.onerror=()=>{console.error("[BobWidget] Canned audio failed, falling back to TTS");const D=Zs(W.current);Te(D)},R.play().catch(()=>{console.error("[BobWidget] Canned audio autoplay blocked, falling back to TTS");const D=Zs(W.current);Te(D)}),V.current=null}else{const R=Zs(W.current);Te(R)}J.current=setTimeout(()=>{q.current||(console.warn("[BobWidget] Speech fallback after 2s"),p==null||p(),e||(Lr&&u?u():c?c():(ie(n),setTimeout(()=>ie(a),3e3))))},2e3)}else p==null||p(),e||(Lr&&u?u():c?c():(ie(n),setTimeout(()=>ie(a),3e3)))}catch(Se){console.error("[BobWidget] Chat error:",Se);const Ke=Se instanceof Error?Se:new Error("Unknown error");(Mt=b.onError)==null||Mt.call(b,Ke),C.trackError(Ke.name||"ChatError",Ke.message||"Unknown chat error"),e||ie(i)}},st=async()=>{if(!E.trim()||T)return;ze(),re();const Q={role:"user",content:E};B(Ne=>[...Ne,Q]),A(""),C.trackMessageSent(E.length,!!P);const ge=E.toLowerCase();if(vu.some(Ne=>ge.includes(Ne))){const Ne=`G'day mate! I'm running Bob v${pt} - she's running sweet as! Anything else I can help ya with?`;B(yt=>[...yt,{role:"assistant",content:Ne}]),N||Te(Ne);return}I(!0),console.log("[BobWidget STATE] User sent message - switching to RESEARCH state:",s),d==null||d(),e||ie(s),await xe(Q),I(!1)};return{messages:O,input:E,setInput:A,isLoading:T,handleSend:st,handleKeyPress:Q=>{Q.key==="Enter"&&!Q.shiftKey&&(Q.preventDefault(),st())},handleInputFocus:()=>{ze()},handleInputBlur:()=>{},chatEndRef:K,clearMessages:()=>{B([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])},isMuted:N,toggleMute:()=>{z(Q=>!Q),N||re()},isSpeaking:qe,identifiedVehicle:P,clearVehicle:()=>{te(null)}}},xu={states:[],configs:[],uploadedImages:[],looks:[],activeLookId:null},ka=t=>{const e=ma(),r=ar();return y.useEffect(()=>{if(!r)return;const s=r.channel("animation-states-changes").on("postgres_changes",{event:"*",schema:"public",table:"animation_states"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe(),n=r.channel("bob-animations-changes").on("postgres_changes",{event:"*",schema:"public",table:"bob_animations"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe();return()=>{r.removeChannel(s),r.removeChannel(n)}},[e,r]),fs({queryKey:["bob-animation-data",t],queryFn:async()=>{var b;if(!r)return console.log("[BobAnimation] No supabase client, returning empty data"),xu;const{data:s,error:n}=await r.from("bob_looks").select("*").order("display_order");if(n)throw n;const i=(s||[]).find(S=>S.is_active),a=t||(i==null?void 0:i.id)||s&&((b=s[0])==null?void 0:b.id)||null;if(!a)return console.warn("[BobAnimation] No looks configured in database"),{states:[],configs:[],uploadedImages:[],looks:s||[],activeLookId:null};console.log(`[BobAnimation] Loading animations for look: ${(i==null?void 0:i.name)||a}`);const{data:l,error:c}=await r.from("animation_states").select("*").eq("is_active",!0).eq("look_id",a).order("display_order");if(c)throw c;const{data:u,error:d}=await r.from("bob_animations").select("*").eq("is_active",!0).eq("look_id",a).order("animation_state").order("sequence_order");if(d)throw d;const p=(l||[]).map(S=>S.state_key);console.log(`[BobAnimation] Loaded ${p.length} states: ${p.join(", ")}`);const h=["idle","talking","listening"].filter(S=>{const j=[S,S.replace("ing",""),S+"ing"];return!p.some(C=>j.includes(C))});h.length>0&&console.warn(`[BobAnimation] ⚠️ Missing critical states: ${h.join(", ")}`);const m=new Set(p),g=(u||[]).filter(S=>m.has(S.animation_state));console.log(`[BobAnimation] Loaded ${g.length} animation frames`);const{data:_,error:w}=await r.storage.from("bob-images").list();if(w)throw w;const k=(_||[]).map(S=>{const{data:j}=r.storage.from("bob-images").getPublicUrl(S.name);return j.publicUrl});return g.forEach(S=>{const j=new Image;j.src=S.image_url}),{states:l||[],configs:g,uploadedImages:k,looks:s||[],activeLookId:a}},staleTime:30*1e3,gcTime:5*60*1e3})},Sa=(t={})=>{const{isSpeaking:e=!1}=t,[r,s]=y.useState(""),[n,i]=y.useState(0),[a,l]=y.useState(400),[c,u]=y.useState(!1),d=y.useRef(null),p=y.useRef(0),f=y.useRef(e),h=y.useRef(0),m=y.useRef(0),g=y.useRef(!1),_=y.useRef(0),{data:w,isLoading:k}=ka(),b=y.useRef({}),{imageUrlsMap:S,alternateImages:j,offsetsMap:C,scalesMap:F,availableStates:O}=y.useMemo(()=>{if(!w)return{imageUrlsMap:{},alternateImages:{},offsetsMap:{},scalesMap:{},availableStates:[]};const I={},N={},z={},P={},te=w.states.map(K=>K.state_key);return te.forEach(K=>{const $=w.configs.filter(J=>J.animation_state===K),U=$.map(J=>J.image_url),W=$.map(J=>J.vertical_offset||0),q=$.map(J=>J.scale||100);if(U.length>0){const J=w.states.find(V=>V.state_key===K);I[K]={url:U[0],animation_speed:(J==null?void 0:J.animation_speed)||400,pause_duration:(J==null?void 0:J.pause_duration)||0,loop_count:(J==null?void 0:J.loop_count)||0},N[K]=U,z[K]=W,P[K]=q}}),{imageUrlsMap:I,alternateImages:N,offsetsMap:z,scalesMap:P,availableStates:te}},[w]);y.useEffect(()=>{b.current=S},[S]),y.useEffect(()=>{const I=f.current;if(f.current=e,I&&!e){const N=r.toLowerCase();(N.includes("talk")||N==="talking")&&(console.log("[useBobAnimation] Speech ended while in talk state - forcing loop completion"),m.current=999)}},[e,r]);const B=y.useCallback(I=>{s(N=>N===I?N:(h.current=0,m.current=0,g.current=!1,i(0),I))},[]);y.useEffect(()=>{O.length>0&&!r&&s(O[0])},[O,r]),y.useEffect(()=>{const I=j[r];if(d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),h.current=0,m.current=0,g.current=!1,p.current=0,i(0),!I||I.length<=1)return;const N=b.current[r],z=(N==null?void 0:N.animation_speed)||a||400,P=(N==null?void 0:N.loop_count)||0,te=(N==null?void 0:N.pause_duration)||0,K=r.toLowerCase().includes("talk"),$=U=>{if(p.current===0&&(p.current=U),g.current){U-_.current>=te&&(g.current=!1,m.current=0,p.current=U),d.current=requestAnimationFrame($);return}if(U-p.current>=z){p.current=U;const q=(h.current+1)%I.length;q===0?(m.current++,K&&f.current?(h.current=q,i(q)):P>0&&m.current>=P?te>0&&(g.current=!0,_.current=U):(h.current=q,i(q))):(h.current=q,i(q))}d.current=requestAnimationFrame($)};return d.current=requestAnimationFrame($),()=>{d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)}},[r,j,a]);const E=y.useCallback(()=>{const I=j[r];if(!I||I.length===0){const N=O.find(z=>{var P;return((P=j[z])==null?void 0:P.length)>0});return N?(console.warn(`[useBobAnimation] No images for "${r}", using fallback: ${N}`),j[N][0]):(console.error("[useBobAnimation] No valid images found for any state!"),"")}return I[n]||I[0]},[j,r,O,n]),A=y.useCallback(()=>{const I=C[r];if(!I||I.length===0){const N=O.find(z=>{var P;return((P=C[z])==null?void 0:P.length)>0});return N?C[N][0]:0}return I[n]||I[0]},[C,r,O,n]),T=y.useCallback(()=>{const I=F[r];if(!I||I.length===0){const N=O.find(z=>{var P;return((P=F[z])==null?void 0:P.length)>0});return N?F[N][0]:100}return I[n]||I[0]},[F,r,O,n]);return{animationState:r,setAnimationState:B,getCurrentImage:E,getCurrentOffset:A,getCurrentScale:T,imageUrls:S,availableStates:O,setTalkSpeed:l,manualMode:c,setManualMode:u,isLoading:k}},Ea=()=>{const t=ar(),{data:e=[],isLoading:r}=fs({queryKey:["bob-backdrops"],queryFn:async()=>{if(!t)return console.log("[useBobBackdrop] No supabase client, returning empty"),[];const{data:n,error:i}=await t.from("bob_backdrops").select("*").order("display_order",{ascending:!0});if(i)throw i;return n},staleTime:5*60*1e3,gcTime:10*60*1e3}),s=e.find(n=>n.is_active);return{backdrops:e,activeBackdrop:s,isLoading:r}},ja=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=12,className:i="",verticalOffset:a=0,scale:l=100})=>{const c=a+n,u=55*(l/100);return o.jsx("div",{className:`flex flex-col items-center justify-center gap-6 w-full ${i}`,children:o.jsxs("div",{className:"relative w-full max-w-[600px] mx-auto aspect-[16/10] overflow-hidden",children:[r&&o.jsx("img",{src:r,alt:"Backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-bottom"}),o.jsx("img",{src:t,alt:`Bob ${e}`,className:"absolute z-10 h-auto object-contain left-1/2 -translate-x-1/2",style:{bottom:`${c}%`,width:`${u}%`,maxWidth:`${220*(l/100)}px`,transformOrigin:"center bottom"}}),s&&o.jsx("img",{src:s,alt:"Counter",className:"absolute z-20 bottom-0 left-0 w-full object-cover object-bottom",style:{height:`${n}%`}})]})})},G={primary:"#0052CC",primaryHover:"#0047B3",secondary:"#38BDF8",foreground:"#0F172A",accent:"#FF8C00",success:"#22C55E",destructive:"#EF4444",performanceRed:"#DC2626",mutedForeground:"#64748B",background:"#FAFAFA",card:"#FFFFFF",border:"#E2E8F0",slateEconomy:"#475569"},As={Economy:{icon:"DollarSign",emoji:"💰",textColor:"#475569",background:"#F1F5F9",border:"#CBD5E1",description:"Smart savings"},Standard:{icon:"Star",emoji:"⭐",textColor:"#0052CC",background:"rgba(0,82,204,0.1)",border:"rgba(0,82,204,0.3)",description:"Best value",isRecommended:!0},Premium:{icon:"Award",emoji:"🏆",textColor:"#D97706",background:"#FEF3C7",border:"#FCD34D",description:"Superior quality"},Performance:{icon:"Zap",emoji:"⚡",textColor:"#DC2626",background:"#FEE2E2",border:"#FCA5A5",description:"Maximum power"}},en={"Oil Change":"Neglecting oil changes leads to engine wear, overheating, and catastrophic failure costing thousands. Quality oil and filters keep your engine running smoothly. Each CFX Oil Change Service Pack includes premium oil and filter matched to your engine specifications.","Front Brake Service":"Your front brakes handle 70% of stopping power. Worn pads dangerously increase stopping distance. Quality brake components ensure confident, safe stops. Each CFX Front Brake Service Pack includes pads and rotors to restore your braking performance.","Rear Brake Service":"Rear brakes provide stability and balance during emergency stops. Worn components cause instability and longer stopping distances. Each CFX Rear Brake Service Pack includes quality pads/shoes and rotors/drums for complete rear brake renewal.","Timing Belt Service":"A snapped timing belt destroys engines instantly, causing $8,000+ in damage. Preventive replacement is essential for peace of mind. Each CFX Timing Belt Service Pack includes the belt, tensioner, and related components.",Wipers:"Worn wipers reduce visibility in rain, compromising safety. Quality blades provide streak-free, clear vision. Each CFX Wipers Service Pack includes the gear you need to change all of your vehicle's wiper blades to restore your driving vision.","Coolant Service":"Old coolant causes overheating, warped cylinder heads, and engine seizure. Fresh coolant protects your entire cooling system. Each CFX Coolant Service Pack includes quality coolant matched to your vehicle's requirements.","Air Filter Service":"Clogged air filters reduce engine performance by 10% and increase fuel consumption. Clean filters improve power and economy. Each CFX Air Filter Service Pack includes a precision-fit filter for optimal airflow.","Spark Plug Service":"Worn spark plugs cause misfires, poor fuel economy, and catalytic converter damage. Fresh plugs restore smooth, efficient running. Each CFX Spark Plug Service Pack includes quality plugs matched to your engine.","Battery Service":"A failing battery leaves you stranded without warning. Reliable power is essential for starting and electronics. Each CFX Battery Service Pack includes a quality battery sized for your vehicle's demands.","Cabin Filter":"Cabin filters clean the air you and your passengers breathe. Replace regularly to remove pollen, dust, and odours. Each CFX Cabin Filter Service Pack includes a quality filter for fresh, clean cabin air.","Fuel Filter Service":"Clogged fuel filters restrict flow, causing poor performance and potential engine damage. Clean fuel is critical for efficiency. Each CFX Fuel Filter Service Pack includes a quality filter for optimal fuel delivery.","Transmission Service":"Old transmission fluid causes rough shifting, slipping, and premature wear. Fresh fluid extends transmission life. Each CFX Transmission Service Pack includes quality fluid matched to your transmission type."},_u="Keep your vehicle running safely and efficiently with quality parts matched to your specific make and model. Each CFX Service Pack includes everything you need for this essential maintenance.",is={productImage:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${t}.jpg`,brandLogo:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${t.replace(/\s+/g,"")}.jpg`,carfixImage:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/carfix_images/${t}_1.jpg`},Ta={fitsVehicle:{background:"rgba(34,197,94,0.1)",text:"#22C55E",border:"rgba(34,197,94,0.2)",icon:"Check",label:"Fits Your Vehicle"},viscosity:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",icon:"Gauge"},volume:{background:"#ECFEFF",text:"#0E7490",border:"#A5F3FC",icon:"Droplets"},quantity:{background:"#F1F5F9",text:"#475569",border:"#CBD5E1"},partNumber:{background:"transparent",text:"#64748B",border:"transparent"},carfixValue:{background:"rgba(0,82,204,0.1)",text:"#0052CC",border:"rgba(0,82,204,0.2)",icon:"Sparkles",label:"CARFIX Value"},rotorPair:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",label:"Pair"}},Ze={packageTitle:{fontSize:"20px",fontWeight:700},partslotName:{fontSize:"14px",fontWeight:600},productName:{fontSize:"14px",fontWeight:500},description:{fontSize:"14px",fontWeight:400},priceMain:{fontSize:"20px",fontWeight:700},priceSecondary:{fontSize:"12px",fontWeight:400},tierLabel:{fontSize:"14px",fontWeight:500},badgeText:{fontSize:"12px",fontWeight:500}};function Ra(t){var s;const e=((s=t.name)==null?void 0:s.toLowerCase())||"",r=(t.partslotDescription||t.partslot_description||"").toLowerCase();return e.includes("rotor")||r.includes("disc rotor")||r.includes("brake rotor")||t.per_car_qty===2}function Ca(t,e){return e?{displayPrice:t*2,unitPriceLabel:`$${t.toFixed(2)} each`}:{displayPrice:t}}function Pt(t){return`$${t.toFixed(2)}`}function Oa(t){if(en[t])return en[t];const e=t.toLowerCase();for(const[r,s]of Object.entries(en))if(e.includes(r.toLowerCase())||r.toLowerCase().includes(e))return s;return _u}const Vr=({type:t,value:e,className:r=""})=>{const s=Ta[t],n=e||("label"in s?s.label:""),i=()=>{if(!("icon"in s))return null;const a={width:12,height:12};switch(s.icon){case"Check":return o.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",children:o.jsx("polyline",{points:"20 6 9 17 4 12"})});case"Sparkles":return o.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("path",{d:"M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3z"}),o.jsx("path",{d:"M5 19l1 3 1-3 3-1-3-1-1-3-1 3-3 1 3 1z"})]});case"Gauge":return o.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("circle",{cx:"12",cy:"12",r:"10"}),o.jsx("path",{d:"M12 6v6l4 2"})]});case"Droplets":return o.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:o.jsx("path",{d:"M12 2.69l5.66 5.66a8 8 0 11-11.31 0z"})});default:return null}};return o.jsxs("span",{className:r,style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",fontSize:"12px",fontWeight:500,background:s.background,color:s.text,border:`1px solid ${s.border}`,whiteSpace:"nowrap"},children:[i(),n]})},Dn=({products:t,title:e,onProductClick:r,onAddToCart:s})=>!t||t.length===0?null:o.jsxs("div",{style:{marginTop:"16px",width:"100%"},children:[e&&o.jsxs("div",{style:{marginBottom:"12px",fontSize:Ze.partslotName.fontSize,fontWeight:Ze.partslotName.fontWeight,color:G.foreground,display:"flex",alignItems:"center",gap:"8px"},children:[o.jsx("span",{style:{fontSize:"18px"},children:"🚗"}),e]}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:t.slice(0,6).map((n,i)=>o.jsx(ku,{product:n,onProductClick:r,onAddToCart:s,isRecommended:i===0},n.id||n.sku||i))}),t.length>6&&o.jsxs("div",{style:{marginTop:"12px",fontSize:"13px",color:G.mutedForeground,textAlign:"center"},children:["+ ",t.length-6," more options available"]})]}),ku=({product:t,onProductClick:e,onAddToCart:r,isRecommended:s=!1})=>{const[n,i]=y.useState(!1),[a,l]=y.useState(!1),c=t.image_url||t.image||(t.sku?is.productImage(t.sku):null),u=t.brand?is.brandLogo(t.brand):null,d=t.brand||"Quality Part",p=t.name||"Product",f=t.price??0,h=t.partNumber||t.part_number,m=Ra({name:t.name,partslotDescription:t.partslotDescription,per_car_qty:t.quantity}),{displayPrice:g,unitPriceLabel:_}=Ca(f,m);return o.jsxs("div",{style:{background:G.card,borderRadius:"12px",border:`2px solid ${G.border}`,overflow:"hidden",cursor:e?"pointer":"default",transition:"all 0.2s ease"},onClick:()=>e==null?void 0:e(t),onMouseEnter:w=>{w.currentTarget.style.borderColor=`${G.primary}80`,w.currentTarget.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)"},onMouseLeave:w=>{w.currentTarget.style.borderColor=G.border,w.currentTarget.style.boxShadow="none"},children:[t.partslotDescription&&o.jsxs("div",{style:{background:"rgba(0,0,0,0.03)",borderBottom:`1px solid ${G.border}`,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsx("span",{style:{fontSize:Ze.partslotName.fontSize,fontWeight:Ze.partslotName.fontWeight,color:G.foreground},children:t.partslotDescription}),s&&o.jsx(Vr,{type:"carfixValue"})]}),o.jsxs("div",{style:{padding:"16px",display:"flex",gap:"16px"},children:[o.jsx("div",{style:{width:"96px",minWidth:"96px",height:"96px",borderRadius:"8px",background:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",border:`1px solid ${G.border}`},children:c&&!n?o.jsx("img",{src:c,alt:p,style:{width:"100%",height:"100%",objectFit:"contain",padding:"4px"},onError:()=>i(!0)}):o.jsx("span",{style:{fontSize:"32px",opacity:.5},children:"🔧"})}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:[u&&!a&&o.jsx("img",{src:u,alt:d,style:{height:"16px",width:"auto",objectFit:"contain"},onError:()=>l(!0)}),o.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:G.foreground,textTransform:"uppercase"},children:d})]}),o.jsx("div",{style:{fontSize:Ze.productName.fontSize,fontWeight:Ze.productName.fontWeight,color:G.foreground,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",lineHeight:"1.4",marginBottom:"8px"},children:p}),o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"12px"},children:[o.jsx(Vr,{type:"fitsVehicle"}),m&&o.jsx(Vr,{type:"rotorPair"}),t.quantity&&t.quantity>1&&!m&&o.jsx(Vr,{type:"quantity",value:`Qty: ${t.quantity}`}),h&&o.jsxs("span",{style:{fontSize:"12px",color:G.mutedForeground},children:["#",h]})]})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",justifyContent:"space-between",minWidth:"100px"},children:[o.jsxs("div",{style:{textAlign:"right"},children:[o.jsx("div",{style:{fontSize:Ze.priceMain.fontSize,fontWeight:Ze.priceMain.fontWeight,color:G.foreground},children:Pt(g)}),_&&o.jsx("div",{style:{fontSize:Ze.priceSecondary.fontSize,color:G.mutedForeground},children:_}),o.jsx("div",{style:{fontSize:Ze.priceSecondary.fontSize,color:G.mutedForeground},children:"inc GST"})]}),r&&o.jsx("button",{onClick:w=>{w.stopPropagation(),r(t)},style:{background:G.primary,color:"#FFFFFF",border:"none",borderRadius:"8px",padding:"8px 16px",fontSize:"13px",fontWeight:600,cursor:"pointer",transition:"all 0.2s ease",whiteSpace:"nowrap"},onMouseEnter:w=>{w.currentTarget.style.background=G.primaryHover},onMouseLeave:w=>{w.currentTarget.style.background=G.primary},onMouseDown:w=>{w.currentTarget.style.transform="scale(0.98)"},onMouseUp:w=>{w.currentTarget.style.transform="scale(1)"},children:"Add to Cart"})]})]})]})},Aa=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:l,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:p=!1,className:f="",onAddToCart:h,onProductClick:m})=>o.jsx("div",{className:f,style:{width:"100%",maxWidth:"72rem",margin:"0 auto",padding:"0 16px 32px 16px"},children:o.jsxs("div",{style:{backgroundColor:"rgba(20, 30, 50, 0.85)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"16px",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.3)",overflow:"hidden"},children:[o.jsx("div",{style:{padding:"16px",borderBottom:"1px solid rgba(255,255,255,0.1)",backgroundColor:"rgba(0,0,0,0.2)"},children:o.jsxs("div",{style:{display:"flex",gap:"8px"},children:[o.jsx("input",{value:e,onChange:g=>r(g.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Ask Bob about car parts...",disabled:s,style:{flex:1,padding:"12px 16px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",color:"white",fontSize:"16px",outline:"none"}}),d&&o.jsx("button",{onClick:d,style:{flexShrink:0,padding:"12px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",cursor:"pointer",minHeight:"unset",minWidth:"unset"},title:u?"Unmute Bob's voice":"Mute Bob's voice",children:u?"🔇":"🔊"}),o.jsx("button",{onClick:n,disabled:s||!e.trim(),style:{flexShrink:0,padding:"12px 20px",background:s||!e.trim()?"rgba(0, 102, 204, 0.3)":"linear-gradient(135deg, rgba(0, 102, 204, 0.95), rgba(0, 73, 153, 1))",color:"white",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.2)",cursor:s||!e.trim()?"not-allowed":"pointer",opacity:s||!e.trim()?.5:1,minHeight:"unset",minWidth:"unset",fontWeight:600},children:"Send"})]})}),o.jsxs("div",{style:{overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"12px",height:"400px",background:"rgba(0,0,0,0.1)"},children:[[...t].reverse().map((g,_)=>{var w;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:g.role==="user"?"flex-end":"flex-start"},children:o.jsxs("div",{style:{maxWidth:(w=g.suggestedProducts)!=null&&w.length?"100%":"80%",borderRadius:"16px",padding:"12px 16px",fontSize:"14px",backgroundColor:g.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.1)",background:g.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.08)",color:"white",border:"1px solid rgba(255,255,255,0.15)",boxShadow:"0 2px 8px rgba(0,0,0,0.2)"},children:[g.content,g.role==="assistant"&&g.suggestedProducts&&g.suggestedProducts.length>0&&o.jsx(Dn,{products:g.suggestedProducts,title:g.suggestionsTitle,onAddToCart:h,onProductClick:m})]})},_)}),o.jsx("div",{ref:c})]})]})}),Su=768,Eu=1024;function Fs(){const[t,e]=y.useState("mobile");return y.useEffect(()=>{const r=()=>{const s=window.innerWidth;s>=Eu?e("desktop"):s>=Su?e("tablet"):e("mobile")};return r(),window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),t}function Ln(){const t=Fs();return ju(t)}function ju(t){switch(t){case"mobile":return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-55,hiddenPosition:-100};case"tablet":return{bobOffset:.7,productWidth:.85,uiScale:1.1,partialLeftPosition:-25,hiddenPosition:-80};case"desktop":return{bobOffset:.5,productWidth:.6,uiScale:1.2,partialLeftPosition:-5,hiddenPosition:-60};default:return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-20,hiddenPosition:-100}}}const Ds=({currentImage:t,animationState:e,counterOverlayUrl:r,counterHeightPercent:s=15,scale:n=100,position:i="center",verticalOffset:a=0,hasArrived:l=!0})=>{const c=Ln(),d=95*n/100,p=550*n/100,f=()=>{switch(i){case"center":return"50%";case"partial-left":return`${c.partialLeftPosition}%`;case"hidden":return`${c.hiddenPosition}%`;default:return"50%"}},h=()=>i==="center"?"translateX(-50%)":"translateX(0)",m=s-2+a,g=()=>i==="hidden"?"all 0.35s cubic-bezier(0.4, 0, 0.2, 1)":"all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)";return o.jsxs("div",{className:"absolute inset-0 pointer-events-none",style:{overflow:"visible"},children:[o.jsx("div",{className:"absolute z-[60]",style:{bottom:`${m}%`,left:f(),maxHeight:`${100-s-2}%`,transform:h(),width:`${d}%`,maxWidth:`${p}px`,transition:g()+", opacity 0.6s ease-out",willChange:"transform, left, opacity",opacity:l?1:0},children:o.jsx("img",{src:t,alt:`Bob ${e}`,className:"w-full h-auto object-contain",style:{display:"block",maxHeight:"100%"}})}),r&&o.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-[70]",style:{height:`${s}%`,pointerEvents:"none"},children:o.jsx("img",{src:r,alt:"Shop counter",className:"w-full h-full object-cover object-top"})})]})},Es={background:"rgba(20, 30, 50, 0.92)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"28px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.35), inset 0 0 0 1px rgba(255,255,255,0.1)"},Ia={background:"linear-gradient(135deg, rgba(40, 60, 100, 0.95) 0%, rgba(20, 40, 80, 0.98) 100%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(0, 0, 0, 0.35), 0 0 0 1px rgba(255,255,255,0.15), inset 0 1px 0 rgba(255,255,255,0.2)"},Ci={background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(12px) saturate(180%)",WebkitBackdropFilter:"blur(12px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.35)",borderRadius:"24px",boxShadow:"0 10px 40px rgba(255, 149, 0, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},Pa={background:"linear-gradient(135deg, rgba(0, 102, 204, 0.95) 0%, rgba(0, 73, 153, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"32px",boxShadow:"0 10px 40px rgba(0, 102, 204, 0.4), inset 0 1px 0 rgba(255,255,255,0.25)"},Na={background:"rgba(255, 255, 255, 0.08)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"28px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.3)"},Qr={primary:{color:"rgba(255, 255, 255, 1)",textShadow:"0 1px 3px rgba(0,0,0,0.5)"}},Tu={background:"rgba(255, 255, 255, 0.12)",borderRadius:"20px",border:"1px solid rgba(255, 255, 255, 0.15)"},Ru={background:"rgba(255, 255, 255, 0.15)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"12px"},Cu={width:"4px",height:"4px",borderRadius:"50%",background:"rgba(255, 255, 255, 0.6)",boxShadow:"0 0 8px rgba(255, 255, 255, 0.4)"},Ba=({product:t,isSpotlighted:e=!1,onProductClick:r,onAddToCart:s})=>{const[n,i]=y.useState(!1),a=()=>{r==null||r(t)},l=u=>{u.stopPropagation(),s==null||s(t)},c=e?Ia:Es;return o.jsxs("div",{onClick:a,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),className:"relative w-full cursor-pointer glass-card",style:{...c,padding:"16px",transform:n?"scale(1.04) translateY(-4px)":"scale(1) translateY(0)",boxShadow:n?"0 16px 56px rgba(0, 0, 0, 0.4), 0 0 24px rgba(255,255,255,0.08)":c.boxShadow,transition:"transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.3s ease-out"},children:[e&&o.jsxs("div",{className:"absolute -top-2.5 -right-2.5 z-10 flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.95) 0%, rgba(0, 73, 153, 1) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"20px",boxShadow:"0 8px 24px rgba(0, 102, 204, 0.5)",color:"white"},children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"currentColor",viewBox:"0 0 20 20",children:o.jsx("path",{d:"M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"})}),"Bob's Pick"]}),o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsx("div",{className:"flex-shrink-0 flex items-center justify-center overflow-hidden",style:{...Tu,width:"92px",height:"92px"},children:t.image_url?o.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-2",loading:"lazy"}):o.jsx("div",{className:"flex flex-col items-center justify-center",style:{color:"rgba(255,255,255,0.4)"},children:o.jsx("svg",{className:"w-8 h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"font-bold line-clamp-2 leading-tight",style:{fontSize:"16px",letterSpacing:"-0.01em",...Qr.primary},children:t.name}),t.brand&&o.jsx("div",{className:"flex items-center gap-1.5 mt-1.5",children:o.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5",style:{...Ru,color:"rgba(255, 255, 255, 0.9)"},children:[o.jsx("svg",{className:"w-2.5 h-2.5",fill:"currentColor",viewBox:"0 0 20 20",children:o.jsx("path",{fillRule:"evenodd",d:"M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),t.brand]})}),o.jsx("p",{className:"font-extrabold mt-2",style:{fontSize:"22px",letterSpacing:"-0.02em",color:"#FFD700",textShadow:"0 2px 6px rgba(0, 0, 0, 0.5), 0 0 12px rgba(255, 215, 0, 0.3)"},children:t.price>0?`$${t.price.toFixed(2)}`:"POA"})]}),o.jsx("button",{onClick:l,className:"flex-shrink-0 flex items-center justify-center glass-button",style:{...Ci,width:"56px",height:"56px",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease-out"},onMouseEnter:u=>{u.currentTarget.style.transform="scale(1.08) translateY(-2px)",u.currentTarget.style.boxShadow="0 14px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.4)"},onMouseLeave:u=>{u.currentTarget.style.transform="scale(1) translateY(0)",u.currentTarget.style.boxShadow=Ci.boxShadow},children:o.jsx("svg",{className:"w-6 h-6 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M12 4v16m8-8H4"})})})]}),t.partslotDescription&&o.jsx("div",{className:"mt-3 pt-3",style:{borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:o.jsx("span",{className:"text-xs font-medium",style:{color:"rgba(255, 255, 255, 0.6)"},children:t.partslotDescription})})]})},Oi=(t,e)=>{if(!t||!e)return!1;const r=t.toLowerCase();return e.toLowerCase().replace(/s\b/g,"").split(/\s+/).filter(Boolean).every(n=>r.includes(n))},Ou=(t,e)=>{var n;const r=((n=t.brand)==null?void 0:n.toLowerCase())===e.brand.toLowerCase(),s=Math.abs(t.price-e.price)<1;return r&&s},Au=({product:t,isSpotlighted:e,spotlightedRef:r,onProductClick:s,viewportSize:n})=>n==="desktop"?o.jsxs("div",{ref:e?r:void 0,onClick:()=>s==null?void 0:s(t),className:`flex flex-row cursor-pointer transition-all duration-300 bg-white rounded-2xl border relative overflow-hidden hover:shadow-2xl hover:scale-[1.01] hover:-translate-y-0.5 group ${e?"ring-2 ring-blue-500 shadow-xl border-blue-200":"border-gray-100 shadow-lg"}`,style:{minHeight:"140px"},children:[e&&o.jsx(Ai,{variant:"horizontal"}),o.jsx("div",{className:"w-36 shrink-0 bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center overflow-hidden",children:t.image_url?o.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-3 group-hover:scale-105 transition-transform duration-300"}):o.jsx(Ii,{size:"lg"})}),o.jsxs("div",{className:"flex-1 p-4 flex flex-col justify-between",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-base font-semibold text-gray-900 line-clamp-2 mb-1 group-hover:text-blue-700 transition-colors",children:t.name}),t.brand&&o.jsx("div",{className:"flex items-center gap-2 mb-2",children:o.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-medium text-gray-600 bg-gray-100 px-2 py-0.5 rounded-full",children:[o.jsx("svg",{className:"w-3 h-3 text-gray-500",fill:"currentColor",viewBox:"0 0 20 20",children:o.jsx("path",{fillRule:"evenodd",d:"M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),t.brand]})})]}),o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx("span",{className:"text-2xl font-bold text-blue-600",children:t.price>0?`$${t.price.toFixed(2)}`:"POA"}),o.jsx("button",{className:"px-4 py-2 bg-gradient-to-r from-blue-600 to-blue-500 text-white text-sm font-semibold rounded-lg hover:from-blue-700 hover:to-blue-600 transition-all shadow-md",onClick:i=>{i.stopPropagation(),s==null||s(t)},children:"View"})]})]})]}):n==="tablet"?o.jsxs("div",{ref:e?r:void 0,onClick:()=>s==null?void 0:s(t),className:`cursor-pointer transition-all duration-300 bg-white rounded-2xl border relative overflow-hidden hover:shadow-xl hover:scale-[1.02] hover:-translate-y-1 ${e?"ring-2 ring-blue-500 shadow-xl border-blue-200":"border-gray-100 shadow-lg"}`,children:[e&&o.jsx(Ai,{}),o.jsx("div",{className:"aspect-[4/3] bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center overflow-hidden",children:t.image_url?o.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-4"}):o.jsx(Ii,{size:"md"})}),o.jsxs("div",{className:"p-4",children:[o.jsx("p",{className:"text-base font-semibold text-gray-900 line-clamp-2 mb-1",children:t.name}),t.brand&&o.jsxs("p",{className:"text-sm text-gray-600 font-medium mb-2 flex items-center gap-1",children:[o.jsx("span",{className:"w-1.5 h-1.5 bg-blue-500 rounded-full"}),t.brand]}),o.jsx("div",{className:"flex items-center justify-between",children:o.jsx("span",{className:"text-xl font-bold text-blue-600",children:t.price>0?`$${t.price.toFixed(2)}`:"POA"})}),o.jsx("button",{className:"mt-3 w-full bg-gradient-to-r from-blue-600 to-blue-500 text-white text-sm font-semibold py-2.5 rounded-xl hover:from-blue-700 hover:to-blue-600 active:from-blue-800 active:to-blue-700 transition-all shadow-md",onClick:i=>{i.stopPropagation(),s==null||s(t)},children:"View Details"})]})]}):o.jsx("div",{ref:e?r:void 0,children:o.jsx(Ba,{product:t,isSpotlighted:e,onProductClick:s})}),Ai=({variant:t="default"})=>o.jsxs("span",{className:`absolute bg-gradient-to-r from-blue-600 to-blue-500 text-white text-xs px-2.5 py-1 rounded-full z-20 flex items-center gap-1 font-semibold shadow-md ${t==="horizontal"?"top-2 left-2":"top-3 right-3"}`,children:[o.jsx("svg",{className:"h-3 w-3",fill:"currentColor",viewBox:"0 0 20 20",children:o.jsx("path",{d:"M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"})}),"Bob's Pick"]}),Ii=({size:t})=>{const e={sm:"h-8 w-8",md:"h-10 w-10",lg:"h-12 w-12"};return o.jsxs("div",{className:"flex flex-col items-center justify-center text-gray-400",children:[o.jsx("svg",{className:e[t],fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})}),o.jsx("span",{className:"text-xs font-medium uppercase tracking-wide mt-1",children:"No Image"})]})},Ls=({products:t,servicePackages:e,highlightedPartType:r,highlightedProduct:s,onProductClick:n,onPackageSelect:i,isResearching:a,visible:l=!0,counterHeightPercent:c=22,hasVehicle:u=!1,onAddToCart:d})=>{const p=Fs();Ln();const f=y.useRef(null),h=y.useRef({}),m=y.useRef(null),g=30,_=20,[w,k]=y.useState(g),b=y.useRef(null),[S,j]=y.useState(null),[C,F]=y.useState({});y.useEffect(()=>{k(g)},[t.length]),y.useEffect(()=>{if(!b.current)return;const U=new IntersectionObserver(W=>{W[0].isIntersecting&&w<t.length&&k(q=>Math.min(q+_,t.length))},{threshold:.1});return U.observe(b.current),()=>U.disconnect()},[w,t.length]);const O=y.useMemo(()=>t.slice(0,w),[t,w]),B=y.useMemo(()=>{const U={};return O.forEach(q=>{const J=q.partslotDescription||"Other Parts";U[J]||(U[J]=[]),U[J].push(q)}),Object.keys(U).sort((q,J)=>q.localeCompare(J)).map(q=>({name:q,products:U[q]}))},[O]);y.useEffect(()=>{var U;if(r){const W=B.find(q=>Oi(q.name,r));W&&h.current[W.name]&&((U=h.current[W.name])==null||U.scrollIntoView({behavior:"smooth",block:"start"}))}},[r,B]),y.useEffect(()=>{s&&m.current&&m.current.scrollIntoView({behavior:"smooth",block:"center"})},[s]);const[E,A]=y.useState(0),T=U=>{const W=U.currentTarget,q=W.scrollHeight-W.clientHeight;if(q>0){const J=W.scrollTop/q;A(Math.max(0,Math.min(1,J)))}},I=t.length>0||e.length>0,N=a&&!I,z=I&&!N,P=l||I,te=p==="mobile"?92:p==="tablet"?65:48,K=p==="desktop"?"580px":p==="tablet"?"500px":"100%",$=p==="mobile"?`calc(${u?"56px":"8px"} + env(safe-area-inset-top, 4px))`:"6px";return o.jsxs(o.Fragment,{children:[I&&l&&o.jsx("div",{style:{position:"fixed",right:"2px",top:`calc(${E*65+18}%)`,...Cu,opacity:.8,transition:"top 0.1s ease-out",zIndex:100,pointerEvents:"none"}}),o.jsxs("div",{ref:f,onScroll:T,className:`absolute overflow-y-auto overflow-x-hidden z-30 flex flex-col gap-3 md:gap-4 transition-all duration-400 ease-out product-scroll ${P?"opacity-100 translate-x-0":"opacity-0 translate-x-12 pointer-events-none"}`,style:{width:`${te}%`,maxWidth:K,right:"0",left:"auto",top:$,bottom:p==="mobile"?"calc(180px + env(safe-area-inset-bottom, 0px))":"52px",paddingTop:"4px",paddingRight:"6px",paddingLeft:"12px",paddingBottom:"8px",scrollbarWidth:"none",msOverflowStyle:"none"},children:[o.jsx("div",{className:"sticky top-0 z-10 -mx-1 px-3 py-2.5",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.85) 0%, rgba(0, 73, 153, 0.9) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"24px",boxShadow:"0 10px 40px rgba(0, 102, 204, 0.4)",border:"1px solid rgba(255, 255, 255, 0.25)"},children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[a&&I?o.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:o.jsx("div",{className:"w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin"})}):o.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:o.jsx("svg",{className:"w-3.5 h-3.5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),o.jsx("span",{style:{...Qr.primary,fontWeight:700,fontSize:"14px",letterSpacing:"0.025em"},children:a&&I?"Updating...":"Bob's Shelf"})]}),o.jsxs("span",{style:{color:"rgba(255,255,255,0.8)",fontSize:"12px",fontWeight:500},children:[t.length+e.length," ",t.length+e.length===1?"item":"items"]})]})}),N&&o.jsx("div",{className:"p-5",style:{...Es},children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(0, 102, 204, 0.2)"},children:o.jsx("div",{className:"w-6 h-6 border-2 border-t-transparent rounded-full animate-spin",style:{borderColor:"rgba(255,255,255,0.8)",borderTopColor:"transparent"}})}),o.jsxs("div",{children:[o.jsx("p",{style:{...Qr.primary,fontWeight:600,fontSize:"14px"},children:"Searching shelves..."}),o.jsx("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:"Finding the best parts for you"})]})]})}),!N&&!I&&o.jsx("div",{className:"p-5",style:{...Es,background:"rgba(255, 149, 0, 0.15)"},children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(255, 149, 0, 0.3)"},children:o.jsx("svg",{className:"w-5 h-5",style:{color:"#FF9500"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),o.jsxs("div",{children:[o.jsx("p",{style:{...Qr.primary,fontWeight:600,fontSize:"14px"},children:"No products to display"}),o.jsxs("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:["Products: ",t.length," | Packages: ",e.length]})]})]})}),z&&e.length>0&&o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center gap-2 px-1",children:[o.jsx("div",{className:"w-6 h-6 rounded-lg flex items-center justify-center",style:{background:`linear-gradient(135deg, ${G.primary} 0%, ${G.primaryHover} 100%)`,boxShadow:`0 4px 12px ${G.primary}66`},children:o.jsx("svg",{className:"h-3.5 w-3.5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})})}),o.jsx("span",{className:"text-xs font-bold uppercase tracking-widest",style:{color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.4)"},children:"CFX Service Packs"})]}),e.map(U=>{var ue,Te;const W=(U.preparedTiers||[]).filter(re=>!re.isHidden),q=((ue=W.find(re=>re.isRecommended))==null?void 0:ue.tierName)||((Te=W[0])==null?void 0:Te.tierName)||"",J=C[U.id]||q,V=W.find(re=>re.tierName===J),ye=Oa(U.title).split(".")[0]+".",je=S===U.id;return o.jsxs("div",{className:"overflow-hidden transition-all duration-300",style:{background:G.card,borderRadius:"16px",border:`1px solid ${G.border}`,boxShadow:"0 4px 20px rgba(0,0,0,0.08)"},children:[o.jsx("div",{className:"px-4 py-3",style:{background:`linear-gradient(135deg, ${G.primary} 0%, ${G.primaryHover} 100%)`},children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 flex items-center justify-center flex-shrink-0",children:o.jsx("svg",{className:"h-5 w-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h3",{className:"text-white font-bold text-base leading-tight truncate",children:U.title}),U.estimated_time&&o.jsx("div",{className:"flex items-center gap-3 mt-0.5",children:o.jsxs("span",{className:"text-white/70 text-xs flex items-center gap-1",children:[o.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),U.estimated_time]})})]})]})}),o.jsx("div",{className:"px-4 py-3 border-b",style:{borderColor:G.border},children:o.jsx("p",{className:"text-sm leading-relaxed",style:{color:G.mutedForeground},children:ye})}),W.length>0&&o.jsxs("div",{className:"p-3",children:[o.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2 px-1",style:{color:G.mutedForeground},children:"Choose Your Value Level"}),o.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:`repeat(${Math.min(W.length,4)}, 1fr)`},children:W.map(re=>{const qe=As[re.tierName],ze=re.tierName===J;return o.jsxs("div",{onClick:()=>F(ie=>({...ie,[U.id]:re.tierName})),className:"relative rounded-xl text-center transition-all cursor-pointer",style:{padding:W.length>=4?"6px 4px":"8px",background:re.isRecommended?`${G.primary}10`:ze?`${G.primary}05`:G.background,border:`2px solid ${re.isRecommended?G.primary:ze?G.primary+"80":G.border}`},children:[re.isRecommended&&o.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wide whitespace-nowrap",style:{background:"#22C55E",color:"white"},children:"Recommended"}),o.jsxs("p",{className:"text-sm font-bold mt-1",style:{color:(qe==null?void 0:qe.textColor)||G.foreground},children:[qe==null?void 0:qe.emoji," ",re.displayName]}),o.jsx("div",{className:"flex flex-col items-center gap-1 mt-2",style:{minHeight:W.length>=4?"40px":"48px"},children:re.brands.slice(0,1).map((ie,Le)=>{const xe=`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${ie.fullName.replace(/\s+/g,"")}.jpg`;return o.jsx("div",{className:"w-full bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{height:W.length>=4?"36px":"44px",maxWidth:W.length>=4?"64px":"80px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",border:"1px solid #F1F5F9"},children:o.jsx("img",{src:ie.imageUrl,alt:ie.fullName,className:"w-auto object-contain",style:{height:W.length>=4?"26px":"32px"},onError:st=>{const mt=st.target;mt.src!==xe?mt.src=xe:(mt.style.display="none",mt.parentElement.innerHTML=`<span class="text-[10px] font-semibold text-gray-600 truncate px-1">${ie.fullName}</span>`)}})},Le)})}),o.jsxs("p",{className:"text-[10px] mt-2",style:{color:G.mutedForeground},children:[re.productCount," ",re.productCount===1?"part":"parts"]}),o.jsx("p",{className:"text-base font-bold mt-1",style:{color:G.foreground},children:Pt(re.totalPrice)}),o.jsx("p",{className:"text-[10px]",style:{color:G.mutedForeground},children:"inc GST"}),o.jsxs("button",{onClick:ie=>{ie.stopPropagation();const Le=re.products.map(xe=>({id:xe.sku,name:xe.name,brand:xe.brand,price:xe.displayPrice,sku:xe.sku,partNumber:xe.partNumber||void 0,image_url:xe.productImageUrl,partslotDescription:xe.partslotName,quantity:1}));d==null||d(Le)},className:"w-full mt-2 py-1.5 rounded-lg text-[10px] font-semibold transition-all flex items-center justify-center gap-1",style:{background:re.isRecommended?G.primary:"#F1F5F9",color:re.isRecommended?"white":"#475569",border:re.isRecommended?"none":"1px solid #E2E8F0"},children:[o.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"})}),"Add"]})]},re.tierName)})})]}),o.jsxs("div",{onClick:()=>j(je?null:U.id),className:"flex items-center justify-center gap-1.5 py-2 cursor-pointer hover:bg-gray-50 transition-colors border-t",style:{borderColor:G.border},children:[o.jsx("span",{className:"text-xs",style:{color:G.mutedForeground},children:je?"Hide details":"Show details"}),o.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${je?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",style:{color:G.mutedForeground},children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),je&&V&&o.jsx("div",{className:"px-4 pb-4 border-t animate-in slide-in-from-top-2 duration-200",style:{borderColor:G.border},children:o.jsxs("div",{className:"pt-3",children:[o.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide mb-3",style:{color:G.mutedForeground},children:[V.displayName," Tier Products"]}),o.jsx("div",{className:"space-y-2",children:V.products.map(re=>o.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg",style:{background:G.background,border:`1px solid ${G.border}`},children:[o.jsx("div",{className:"w-14 h-14 flex-shrink-0 bg-white rounded-lg overflow-hidden flex items-center justify-center",children:re.productImageUrl?o.jsx("img",{src:re.productImageUrl,alt:re.name,className:"w-full h-full object-contain p-1"}):o.jsx("svg",{className:"w-6 h-6 text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-xs font-medium truncate",style:{color:G.foreground},children:re.name}),o.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[o.jsx("span",{className:"text-[10px]",style:{color:G.mutedForeground},children:re.brand}),re.isRotor&&o.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 font-medium",children:"Pair"})]}),o.jsx("p",{className:"text-[10px] mt-0.5",style:{color:G.mutedForeground},children:re.partslotName})]}),o.jsxs("div",{className:"text-right flex-shrink-0",children:[o.jsx("p",{className:"text-sm font-bold",style:{color:G.primary},children:Pt(re.displayPrice)}),re.isRotor&&o.jsxs("p",{className:"text-[9px]",style:{color:G.mutedForeground},children:["$",re.price.toFixed(2)," ea"]})]})]},re.sku))})]})})]},U.id)})]}),z&&B.map(({name:U,products:W})=>{const q=r&&Oi(U,r);return o.jsxs("section",{ref:J=>{h.current[U]=J},className:"transition-all duration-300",style:{...q?Ia:Es,background:q?"linear-gradient(135deg, rgba(0, 82, 164, 0.85) 0%, rgba(0, 51, 102, 0.9) 100%)":"rgba(20, 30, 50, 0.75)"},children:[o.jsxs("div",{className:"px-3 py-2.5 flex items-center justify-between",style:{background:q?"rgba(0, 102, 204, 0.8)":"rgba(0, 51, 102, 0.7)",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("div",{className:"w-5 h-5 rounded-md flex items-center justify-center flex-shrink-0",style:{background:q?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 1) 100%)":"rgba(255,255,255,0.2)"},children:o.jsx("svg",{className:"h-3 w-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),o.jsx("span",{className:"text-xs font-bold truncate uppercase tracking-wide",style:{color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)"},children:U})]}),o.jsx("span",{className:"text-[10px] font-bold px-2.5 py-1 rounded-full flex-shrink-0",style:{background:"rgba(255, 149, 0, 0.9)",color:"white",boxShadow:"0 2px 8px rgba(255, 149, 0, 0.4)"},children:W.length})]}),o.jsx("div",{className:"p-3 flex flex-col gap-3",children:W.map((J,V)=>{const fe=!!(s&&Ou(J,s));return o.jsx(Au,{product:J,isSpotlighted:fe,spotlightedRef:m,onProductClick:n,viewportSize:p},`${J.id}-${V}`)})})]},U)}),w<t.length&&o.jsx("div",{ref:b,className:"flex items-center justify-center py-4",children:o.jsxs("div",{className:"flex items-center gap-2 text-sm",style:{color:"rgba(255,255,255,0.6)"},children:[o.jsx("div",{className:"w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"}),o.jsxs("span",{children:["Loading more (",w," of ",t.length,")..."]})]})}),o.jsx("div",{className:"h-4"})]})]})},Un=({onTranscript:t,onSpeechEnd:e,language:r="en-NZ",mode:s="toggle"}={})=>{const[n,i]=y.useState(!1),[a,l]=y.useState(""),[c,u]=y.useState(""),[d,p]=y.useState(null),[f,h]=y.useState(!1),m=y.useRef(null),g=y.useRef(""),_=y.useRef(t),w=y.useRef(e),k=y.useRef(null),b=15e3;y.useEffect(()=>{_.current=t,w.current=e},[t,e]),y.useEffect(()=>{if(typeof window<"u"&&window.location.protocol!=="https:"&&window.location.hostname!=="localhost"&&window.location.hostname!=="127.0.0.1"){console.warn("[BobWidget] Speech recognition requires HTTPS. PTT will not work on HTTP."),p("Voice input requires a secure connection (HTTPS)"),h(!1);return}const F=window.SpeechRecognition||window.webkitSpeechRecognition;if(F){h(!0);const O=new F;O.continuous=s==="ptt",O.interimResults=!0,O.lang=r,O.maxAlternatives=1,O.onstart=()=>{i(!0),p(null)},O.onresult=B=>{let E="",A="";for(let T=B.resultIndex;T<B.results.length;T++){const I=B.results[T][0].transcript;B.results[T].isFinal?A+=I:E+=I}A&&(g.current=A,l(A),_.current&&_.current(A)),u(E)},O.onerror=B=>{switch(i(!1),B.error){case"no-speech":p("No speech detected. Please try again.");break;case"audio-capture":p("No microphone found. Please check your device.");break;case"not-allowed":p("Microphone permission denied. Please allow access.");break;default:p("Speech recognition error. Please try again.")}},O.onend=()=>{k.current&&(clearTimeout(k.current),k.current=null),i(!1),u(""),g.current&&w.current&&w.current(g.current),g.current=""},m.current=O}return()=>{m.current&&m.current.stop()}},[r,s]);const S=()=>{m.current&&!n&&(l(""),u(""),p(null),k.current=setTimeout(()=>{console.warn("[SpeechRecognition] Safety timeout - forcing stop after 15s"),m.current&&m.current.abort(),i(!1),u("")},b),m.current.start())},j=()=>{k.current&&(clearTimeout(k.current),k.current=null),m.current&&n&&m.current.stop()};return{isListening:n,transcript:a,interimTranscript:c,error:d,isSupported:f,startListening:S,stopListening:j,toggleListening:()=>{n?j():S()}}},$a=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:l,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:p=!1,onAddToCart:f,onProductClick:h})=>{var K;const[m,g]=y.useState(!1),_=y.useRef(null),w=y.useRef(!1),{bottomOffset:k,zIndexBase:b}=Fn(),{isListening:S,interimTranscript:j,error:C,isSupported:F,startListening:O,stopListening:B}=Un({onTranscript:$=>r($),language:"en-NZ",mode:"ptt"});y.useEffect(()=>{j&&r(j)},[j,r]);const E=y.useCallback(()=>{s||w.current||(w.current=!0,navigator.vibrate&&navigator.vibrate(30),O())},[s,O]),A=y.useCallback(()=>{w.current&&(w.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),B(),setTimeout(()=>{n()},150))},[B,n]),T=[...t].reverse().find($=>$.role==="assistant"),I=((K=T==null?void 0:T.suggestedProducts)==null?void 0:K.length)||0,N=T!=null&&T.content?T.content.length>50?T.content.slice(0,50)+"...":T.content:"Ask Bob about car parts...",z=I>0?` (${I} products)`:"",P={idle:{...Pa},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"32px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},te=s?P.disabled:S?P.active:P.idle;return o.jsxs("div",{ref:_,style:{position:"fixed",bottom:`${k}px`,left:0,right:0,...Na,borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"all 0.3s ease-out",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:m?"55vh":"auto",zIndex:b+60,paddingBottom:k>0?"8px":"env(safe-area-inset-bottom, 8px)"},children:[o.jsx("button",{onClick:()=>g(!m),style:{position:"absolute",top:"-20px",left:"50%",transform:"translateX(-50%)",background:"rgba(255, 255, 255, 0.15)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"9999px",padding:"6px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)",zIndex:b+70,cursor:"pointer",minHeight:"unset",minWidth:"unset"},"aria-label":m?"Collapse chat":"Expand chat",children:m?o.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}):o.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 15l7-7 7 7"})})}),!m&&o.jsx("div",{onClick:()=>g(!0),style:{padding:"8px 12px 2px 12px",cursor:"pointer"},children:o.jsxs("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[N,z&&o.jsx("span",{style:{color:"rgba(255,200,0,0.9)",fontWeight:600},children:z})]})}),m&&o.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px"},className:"glass-scroll",children:[[...t].reverse().map(($,U)=>{var W;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:$.role==="user"?"flex-end":"flex-start"},children:o.jsxs("div",{style:{maxWidth:(W=$.suggestedProducts)!=null&&W.length?"100%":"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:$.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:[$.content,$.role==="assistant"&&$.suggestedProducts&&$.suggestedProducts.length>0&&o.jsx(Dn,{products:$.suggestedProducts,title:$.suggestionsTitle,onAddToCart:f,onProductClick:h})]})},U)}),o.jsx("div",{ref:c})]}),F&&o.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"12px 16px 8px 16px"},children:o.jsx("button",{onTouchStart:E,onTouchEnd:A,onTouchCancel:A,onMouseDown:E,onMouseUp:A,onMouseLeave:A,onClick:S?A:void 0,disabled:s,"aria-label":"Hold to talk to Bob",className:"glass-button",style:{width:"200px",height:"64px",minHeight:"unset",minWidth:"unset",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",touchAction:"none",cursor:s?"not-allowed":"pointer",opacity:s?.6:1,transform:S?"scale(1.04)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease, background 0.15s ease",...te},title:"Hold to talk",children:o.jsx("span",{style:{fontSize:"22px",fontWeight:800,letterSpacing:"0.15em",...Qr.primary,textTransform:"uppercase",fontFamily:"system-ui, -apple-system, sans-serif"},children:S?"LISTENING":"TALK"})})}),o.jsxs("div",{style:{padding:"4px 12px 8px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:[C&&o.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:C}),o.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[d&&o.jsx("button",{onClick:d,style:{flexShrink:0,height:"40px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"12px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:p?"#0066CC":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?o.jsxs("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):o.jsx("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),o.jsx("input",{type:"text",value:e,onChange:$=>r($.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Or type here...",disabled:s,className:"high-contrast-input",style:{flex:1,height:"40px",fontSize:"16px",padding:"0 14px",background:"rgba(0, 51, 102, 0.85)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"2px solid rgba(255, 255, 255, 0.35)",borderRadius:"20px",color:"white",outline:"none",opacity:s?.5:1}})]})]})]})},Fa=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:p,onInputBlur:f,chatEndRef:h,isMuted:m,onToggleMute:g,isSpeaking:_,products:w,servicePackages:k,highlightedPartType:b,highlightedProduct:S,onProductClick:j,onPackageSelect:C,isResearching:F,vehicle:O,onChangeVehicle:B,bobOffset:E=0,bobScale:A=100,embedded:T=!1})=>{console.log("[MobileBobLayout] Rendering with:",{currentImage:(t==null?void 0:t.substring(0,50))||"EMPTY",backdropUrl:(r==null?void 0:r.substring(0,50))||"NONE",counterOverlayUrl:(s==null?void 0:s.substring(0,50))||"NONE"});const I=typeof window<"u"&&window.self!==window.top,N=Fs(),[z,P]=y.useState("center"),[te,K]=y.useState("hidden"),$=w.length>0||k.length>0,q=(()=>{switch(N){case"desktop":return 70;case"tablet":return 80;case"mobile":return 140;default:return 140}})()*A/100;y.useEffect(()=>{if(F&&te!=="loading"&&te!=="visible")K("loading"),z==="center"&&P("left");else if($&&te!=="visible")if(z==="center"){P("left"),K("transitioning");const V=setTimeout(()=>{K("visible")},400);return()=>clearTimeout(V)}else K("visible");else!$&&!F&&te!=="hidden"&&(K("hidden"),P("center"))},[$,F,te,z]);const J=te!=="hidden";return o.jsxs("div",{className:T?"absolute inset-0 overflow-hidden":"fixed inset-0 overflow-hidden",style:{height:T?"100%":"100dvh",touchAction:"manipulation"},children:[r&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"absolute inset-0 z-0",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:"blur(4px) brightness(0.85)",transform:"scale(1.05)"}}),o.jsx("div",{className:"absolute inset-0 z-[1]",style:{background:"linear-gradient(to bottom, rgba(255,255,255,0.15) 0%, rgba(255,255,255,0.35) 100%)"}})]}),o.jsx(Ds,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:q,position:z,verticalOffset:E}),O&&!I&&o.jsx("div",{style:{position:"absolute",top:"8px",left:"8px",right:"8px",zIndex:20},children:o.jsxs("div",{style:{backgroundColor:"rgba(255, 255, 255, 0.9)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)",borderRadius:"8px",padding:"8px 12px",paddingTop:"calc(env(safe-area-inset-top, 4px) + 8px)",border:"1px solid #e5e7eb",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsxs("p",{style:{fontSize:"12px",fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[O.year," ",O.make," ",O.model]}),O.rego&&o.jsx("p",{style:{fontSize:"10px",color:"#6b7280"},children:O.rego})]}),B&&o.jsx("button",{onClick:B,style:{fontSize:"12px",color:"#2563eb",marginLeft:"8px",flexShrink:0,background:"none",border:"none",cursor:"pointer",minHeight:"unset",minWidth:"unset"},children:"Change"})]})}),o.jsx(Ls,{products:w,servicePackages:k,highlightedPartType:b,highlightedProduct:S,onProductClick:j,onPackageSelect:C,isResearching:F,visible:J,counterHeightPercent:n,hasVehicle:!!O}),o.jsx($a,{messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:p,onInputBlur:f,chatEndRef:h,isMuted:m,onToggleMute:g,isSpeaking:_,onAddToCart:j,onProductClick:j})]})},Da=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:l,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:p=!1})=>{const[f,h]=y.useState(!1),m=y.useRef(null),g=y.useRef(!1),{bottomOffset:_,zIndexBase:w}=Fn(),{isListening:k,interimTranscript:b,error:S,isSupported:j,startListening:C,stopListening:F}=Un({onTranscript:N=>r(N),language:"en-NZ",mode:"ptt"});y.useEffect(()=>{b&&r(b)},[b,r]);const O=y.useCallback(()=>{s||g.current||(g.current=!0,navigator.vibrate&&navigator.vibrate(30),C())},[s,C]),B=y.useCallback(()=>{g.current&&(g.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),F(),setTimeout(()=>{n()},150))},[F,n]),E=[...t].reverse().find(N=>N.role==="assistant"),A=E!=null&&E.content?E.content.length>50?E.content.slice(0,50)+"...":E.content:"Ask Bob about car parts...",T={idle:{...Pa},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"50%",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},I=s?T.disabled:k?T.active:T.idle;return o.jsxs("div",{ref:m,style:{position:"absolute",bottom:`${_}px`,left:0,right:0,...Na,borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"all 0.3s ease-out",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:f?"55%":"70px",overflow:f?"visible":"hidden",zIndex:w+10,paddingBottom:_>0?"8px":"env(safe-area-inset-bottom, 8px)"},children:[o.jsx("button",{onClick:()=>h(!f),style:{position:"absolute",top:"-20px",left:"50%",transform:"translateX(-50%)",background:"rgba(255, 255, 255, 0.15)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"9999px",padding:"6px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)",zIndex:w+20,cursor:"pointer",minHeight:"unset",minWidth:"unset"},"aria-label":f?"Collapse chat":"Expand chat",children:f?o.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}):o.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 15l7-7 7 7"})})}),!f&&o.jsx("div",{onClick:()=>h(!0),style:{padding:"6px 12px 4px 12px",height:"26px",overflow:"hidden",cursor:"pointer"},children:o.jsx("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:A})}),f&&o.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px"},className:"glass-scroll",children:[[...t].reverse().map((N,z)=>o.jsx("div",{style:{display:"flex",justifyContent:N.role==="user"?"flex-end":"flex-start"},children:o.jsx("div",{style:{maxWidth:"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:N.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:N.content})},z)),o.jsx("div",{ref:c})]}),o.jsxs("div",{style:{padding:f?"8px 12px 4px 12px":"4px 12px 4px 12px",borderTop:f?"1px solid rgba(255, 255, 255, 0.15)":"none"},children:[k&&o.jsxs("div",{style:{marginBottom:"8px",fontSize:"12px",color:"rgba(255,255,255,0.7)",display:"flex",alignItems:"center",gap:"8px"},children:[o.jsx("span",{style:{display:"inline-block",width:"8px",height:"8px",backgroundColor:"#FF9500",borderRadius:"50%",animation:"pulse 2s infinite"}}),"Listening..."]}),S&&o.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:S}),o.jsxs("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[d&&f&&o.jsx("button",{onClick:d,style:{flexShrink:0,height:"36px",width:"36px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"10px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:p?"#0066CC":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?o.jsxs("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):o.jsx("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),o.jsx("input",{type:"text",value:e,onChange:N=>r(N.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Message Bob...",disabled:s,className:"high-contrast-input",style:{flex:1,height:"40px",fontSize:"16px",padding:"0 14px",background:"rgba(0, 51, 102, 0.85)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"2px solid rgba(255, 255, 255, 0.35)",borderRadius:"20px",color:"white",outline:"none",opacity:s?.5:1}}),j&&o.jsxs("div",{style:{position:"relative",marginLeft:"4px"},children:[k&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"72px",height:"72px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"72px",height:"72px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),!k&&!s&&o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"72px",height:"72px",borderRadius:"50%",transform:"translate(-50%, -50%)",animation:"ptt-pulse 2s ease-in-out infinite",pointerEvents:"none"}}),o.jsxs("button",{onTouchStart:O,onTouchEnd:B,onTouchCancel:B,onMouseDown:O,onMouseUp:B,onMouseLeave:B,disabled:s,"aria-label":"Hold to talk to Bob",className:"glass-button",style:{position:"relative",flexShrink:0,height:"72px",width:"72px",minHeight:"unset",minWidth:"unset",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",touchAction:"none",color:"white",border:"none",cursor:s?"not-allowed":"pointer",opacity:s?.6:1,transform:k?"scale(1.08)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease",zIndex:w+25,...I},title:"Hold to talk",children:[o.jsx("svg",{style:{height:"28px",width:"28px",filter:"drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2))"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})}),k&&o.jsx("div",{style:{position:"absolute",top:"8px",right:"8px",width:"12px",height:"12px",borderRadius:"50%",backgroundColor:"#fef3c7",animation:"ptt-dot 0.6s ease-in-out infinite alternate"}})]})]})]})]})]})},Iu=({product:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{const n=t.productUrl||t.product_url,i=t.partNumber||t.part_number,a=!!n||!!s;return o.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-white/95 backdrop-blur-md overflow-hidden",children:[o.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-gray-200 bg-white/80 backdrop-blur-sm",children:o.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-blue-600 font-medium text-sm hover:text-blue-700 active:scale-95 transition-all",children:[o.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back to Products"]})}),o.jsxs("div",{className:"flex-1 overflow-y-auto",children:[o.jsx("div",{className:"aspect-square bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center",children:t.image_url?o.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-4"}):o.jsxs("div",{className:"flex flex-col items-center justify-center text-gray-400",children:[o.jsx("svg",{className:"h-16 w-16 mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})}),o.jsx("span",{className:"text-sm font-medium uppercase tracking-wide",children:"No Image Available"})]})}),o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-xl font-bold text-gray-900 mb-1",children:t.name}),t.brand&&o.jsx("p",{className:"text-sm text-gray-600 font-medium",children:t.brand})]}),o.jsxs("div",{className:"bg-blue-50 rounded-xl p-4",children:[o.jsx("p",{className:"text-sm text-gray-600 mb-1",children:"Price"}),o.jsx("p",{className:"text-2xl font-bold text-blue-600",children:t.price>0?`$${t.price.toFixed(2)}`:"Price on Request"}),t.price>0&&o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Inc. GST"})]}),o.jsxs("div",{className:"space-y-3",children:[t.partslotDescription&&o.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[o.jsx("span",{className:"text-sm text-gray-500",children:"Category"}),o.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.partslotDescription})]}),t.sku&&o.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[o.jsx("span",{className:"text-sm text-gray-500",children:"SKU"}),o.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.sku})]}),i&&o.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[o.jsx("span",{className:"text-sm text-gray-500",children:"Part Number"}),o.jsx("span",{className:"text-sm font-medium text-gray-900",children:i})]})]}),a&&o.jsx("a",{href:n||"#",onClick:l=>{s&&(l.preventDefault(),s(t))},target:n&&!s?"_blank":void 0,rel:n&&!s?"noopener noreferrer":void 0,className:"block text-center text-blue-600 text-sm font-medium hover:underline py-2",children:"View Full Details on CARFIX →"})]})]}),o.jsx("div",{className:"p-4 border-t border-gray-200 bg-white/95 backdrop-blur-sm",children:o.jsx("button",{onClick:()=>r==null?void 0:r(t),className:"w-full bg-blue-600 text-white text-base font-semibold py-3 rounded-xl hover:bg-blue-700 active:bg-blue-800 transition-colors shadow-lg",children:"Add to Cart"})})]})},La=({package:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{var f;const[n,i]=y.useState(!1),a=y.useMemo(()=>!t.preparedTiers||t.preparedTiers.length===0?[]:t.preparedTiers.filter(h=>!h.isHidden),[t.preparedTiers]),l=a.length>0,c=h=>{r==null||r(h.products)},u=h=>h===2?"grid-cols-2":h===3?"grid-cols-3":"grid-cols-2",d=Oa(t.title),p=((f=a[0])==null?void 0:f.productCount)||0;return o.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-[#FAFAFA] overflow-hidden",children:[o.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[#E2E8F0] bg-white shadow-sm",children:o.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-[#0052CC] font-medium text-sm hover:text-[#0047B3] active:scale-95 transition-all",children:[o.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]})}),o.jsxs("div",{className:"flex-1 overflow-y-auto",children:[o.jsxs("div",{className:"px-4 pt-4 pb-4",style:{background:"linear-gradient(135deg, rgba(0,82,204,0.05) 0%, rgba(56,189,248,0.05) 100%)"},children:[o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0 bg-white shadow-md",children:t.icon_url?o.jsx("img",{src:t.icon_url,alt:"",className:"w-8 h-8 object-contain"}):o.jsx("svg",{className:"w-7 h-7 text-[#0052CC]",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h1",{className:"text-xl font-bold text-[#0F172A]",children:t.title}),o.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-[#64748B]",children:[t.estimated_time&&o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),t.estimated_time]}),t.difficulty_level&&o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085"})}),t.difficulty_level]})]})]})]}),o.jsx("p",{className:"text-sm text-[#64748B] mt-3 leading-relaxed",children:d})]}),o.jsxs("div",{className:"px-4 py-3 flex items-center justify-center gap-2 border-b border-[#E2E8F0] bg-white",children:[o.jsx("span",{className:"font-semibold text-[#0F172A] text-sm",children:"Choose Your Value Level"}),o.jsx("span",{className:"text-[#64748B] text-xs cursor-help",title:"Select the quality tier that suits your needs",children:"ⓘ"})]}),o.jsx("div",{className:"p-4",children:l?o.jsx("div",{className:`grid ${u(a.length)} gap-3`,children:a.map(h=>{const m=As[h.tierName];return o.jsxs("div",{className:"relative rounded-2xl overflow-hidden bg-white shadow-md flex flex-col",style:{border:h.isRecommended?"2px solid #0052CC":"1px solid #E2E8F0"},children:[h.isRecommended&&o.jsx("div",{className:"absolute top-0 left-0 right-0 px-2 py-1 text-[9px] font-bold text-white text-center",style:{background:"linear-gradient(135deg, #0052CC 0%, #38BDF8 100%)"},children:"★ RECOMMENDED"}),o.jsxs("div",{className:`p-3 flex-1 flex flex-col ${h.isRecommended?"pt-7":""}`,children:[o.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[o.jsx("span",{className:"text-lg",children:m==null?void 0:m.emoji}),o.jsxs("div",{children:[o.jsx("span",{className:"font-bold text-sm block",style:{color:(m==null?void 0:m.textColor)||G.foreground},children:h.displayName}),o.jsx("span",{className:"text-[10px] text-[#64748B] hidden md:block",children:h.description||(m==null?void 0:m.description)})]})]}),o.jsx("div",{className:"flex items-center gap-1.5 mb-3 min-h-[42px] flex-wrap",children:h.brands.slice(0,3).map(g=>o.jsx("div",{className:"h-10 px-2 bg-white rounded-xl flex items-center justify-center shadow-md border border-[#F1F5F9]",children:o.jsx("img",{src:g.imageUrl,alt:g.fullName,className:"h-6 w-auto object-contain",onError:_=>{const w=_.target,k=`${is.storageBase}/brand_images/${g.fullName.replace(/\s+/g,"")}.jpg`;if(w.src!==k)w.src=k;else{const b=w.parentElement;b&&(b.innerHTML=`<span class="text-[10px] font-medium text-slate-700 px-1 truncate max-w-[60px]">${g.name}</span>`)}}})},g.name))}),o.jsxs("p",{className:"text-xs text-[#64748B] hidden md:block mb-2",children:[h.productCount," part",h.productCount!==1?"s":""," included"]}),o.jsxs("div",{className:"mt-auto",children:[o.jsx("p",{className:"text-xl font-bold",style:{color:h.isRecommended?"#0052CC":"#0F172A"},children:Pt(h.totalPrice)}),o.jsx("p",{className:"text-[10px] text-[#64748B] hidden md:block",children:"inc GST"})]}),o.jsxs("button",{onClick:()=>c(h),className:`mt-3 w-full px-3 py-2.5 rounded-xl text-xs font-semibold transition-all hover:scale-[1.02] active:scale-95 flex items-center justify-center gap-1.5 ${h.isRecommended?"bg-[#0052CC] text-white shadow-md hover:bg-[#0047B3]":"bg-slate-100 text-slate-700 border border-slate-200 hover:bg-slate-200"}`,children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"})}),"Add to Cart"]})]})]},h.tierName)})}):o.jsxs("div",{className:"rounded-2xl p-6 bg-white border border-[#E2E8F0] shadow-md text-center",children:[o.jsx("svg",{className:"w-12 h-12 mx-auto text-[#94A3B8] mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),o.jsx("p",{className:"text-sm font-medium text-[#64748B]",children:"Package details not available for this vehicle"}),o.jsx("p",{className:"text-xs text-[#94A3B8] mt-1",children:"Please try refreshing or contact support"})]})}),l&&o.jsxs("div",{className:"px-4 pb-4",children:[o.jsxs("button",{onClick:()=>i(!n),className:"w-full flex items-center justify-between p-3 rounded-xl bg-white border border-[#E2E8F0] hover:bg-slate-50 transition-all shadow-sm",children:[o.jsxs("span",{className:"text-sm font-medium text-[#0F172A]",children:[n?"▼":"▶"," View Product Details"]}),o.jsxs("span",{className:"text-xs text-[#64748B]",children:[p," product",p!==1?"s":""]})]}),n&&o.jsx("div",{className:"mt-3 space-y-4 bg-white rounded-xl border border-[#E2E8F0] p-3",children:a.map(h=>{if(h.products.length===0)return null;const m=As[h.tierName];return o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2 pb-1 border-b border-[#E2E8F0]",children:[o.jsx("span",{className:"text-lg",children:m==null?void 0:m.emoji}),o.jsx("span",{className:"font-semibold text-sm",style:{color:m==null?void 0:m.textColor},children:h.displayName}),o.jsxs("span",{className:"text-xs text-[#64748B]",children:["(",h.products.length," parts)"]})]}),o.jsx("div",{className:"space-y-2",children:h.products.map((g,_)=>{var b;const w=(b=t.carfixValueProducts)==null?void 0:b.includes(g.sku),k=g.unitPrice??g.price;return o.jsxs("div",{className:"flex items-center gap-3 p-2.5 rounded-xl transition-all hover:bg-slate-50 cursor-pointer border border-[#E2E8F0]",onClick:()=>s==null?void 0:s(g.sku),children:[o.jsx("div",{className:"w-14 h-14 flex-shrink-0 rounded-lg bg-white overflow-hidden border border-[#E2E8F0]",children:o.jsx("img",{src:g.productImageUrl||is.productImage(g.sku),alt:g.name,className:"w-full h-full object-contain p-1.5",onError:S=>{S.target.src="/placeholder.svg"}})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[o.jsx("span",{className:"text-xs font-semibold text-[#0F172A]",children:g.brandFullName||g.brand}),w&&o.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"rgba(0, 82, 204, 0.1)",color:"#0052CC"},children:"CFX VALUE"}),g.isMultiQty&&g.perCarQty>1&&o.jsxs("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#F0FDF4",color:"#15803D"},children:["×",g.perCarQty]}),g.isRotor&&o.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#EFF6FF",color:"#1D4ED8"},children:"Pair"})]}),o.jsx("p",{className:"text-xs text-[#64748B] line-clamp-1",children:g.name})]}),o.jsxs("div",{className:"text-right flex-shrink-0",children:[o.jsx("p",{className:"text-sm font-bold text-[#0F172A]",children:Pt(g.displayPrice)}),g.isMultiQty&&g.perCarQty>1&&o.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[g.perCarQty,"× ",Pt(k)," each"]}),g.isRotor&&!g.isMultiQty&&o.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[Pt(k)," each"]})]})]},`${g.sku}-${_}`)})})]},h.tierName)})})]}),t.bundle_discount_percentage&&t.bundle_discount_percentage>0&&o.jsx("div",{className:"px-4 pb-4",children:o.jsx("div",{className:"rounded-xl p-3 text-center",style:{background:"rgba(34,197,94,0.1)",border:"1px solid rgba(34,197,94,0.2)"},children:o.jsxs("span",{className:"text-sm font-semibold text-[#22C55E]",children:["Bundle saves you ",t.bundle_discount_percentage,"%"]})})})]})]})},Ua=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:p,onInputBlur:f,chatEndRef:h,isMuted:m,onToggleMute:g,isSpeaking:_,products:w,servicePackages:k,highlightedPartType:b,highlightedProduct:S,onProductClick:j,onPackageSelect:C,isResearching:F,onAddToCart:O,onNavigateToProductPage:B,vehicle:E,onChangeVehicle:A,bobOffset:T=0,bobScale:I=100})=>{const[N,z]=y.useState("center"),[P,te]=y.useState("hidden"),[K,$]=y.useState("products"),[U,W]=y.useState(null),[q,J]=y.useState(null),V=w.length>0||k.length>0,je=(K==="productDetail"?70:N==="center"&&!V?140:98)*I/100;y.useEffect(()=>{if(F&&P!=="loading"&&P!=="visible")te("loading"),N==="center"&&z("left");else if(V&&P!=="visible")if(N==="center"){z("left"),te("transitioning");const ie=setTimeout(()=>{te("visible")},400);return()=>clearTimeout(ie)}else te("visible");else!V&&!F&&P!=="hidden"&&(te("hidden"),z("center"))},[V,F,P,N]);const ue=ie=>{if(B){B(ie),j==null||j(ie);return}W(ie),$("productDetail"),j==null||j(ie)},Te=()=>{W(null),J(null),$("products")},re=ie=>{console.log("[ContainedMobileBobLayout] Package selected:",ie.title),J(ie),$("packageDetail"),C==null||C(ie)},qe=P!=="hidden"&&K==="products",ze=P!=="hidden";return o.jsxs("div",{className:"absolute inset-0 overflow-hidden",style:{touchAction:"manipulation"},children:[r&&o.jsx("div",{className:"absolute inset-0 z-0 transition-all duration-500 ease-out",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:ze?"blur(8px) brightness(0.9)":"blur(0px) brightness(1)",transform:"scale(1.05)"}}),o.jsx(Ds,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:je,position:N,verticalOffset:T}),E&&K==="products"&&o.jsx("div",{style:{position:"absolute",top:"8px",left:"8px",right:"8px",zIndex:20},children:o.jsxs("div",{style:{backgroundColor:"rgba(255, 255, 255, 0.9)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)",borderRadius:"8px",padding:"8px 12px",border:"1px solid #e5e7eb",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsxs("p",{style:{fontSize:"12px",fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[E.year," ",E.make," ",E.model]}),E.rego&&o.jsx("p",{style:{fontSize:"10px",color:"#6b7280"},children:E.rego})]}),A&&o.jsx("button",{onClick:A,style:{fontSize:"12px",color:"#2563eb",marginLeft:"8px",flexShrink:0,background:"none",border:"none",cursor:"pointer",minHeight:"unset",minWidth:"unset"},children:"Change"})]})}),o.jsx(Ls,{products:w,servicePackages:k,highlightedPartType:b,highlightedProduct:S,onProductClick:ue,onPackageSelect:re,isResearching:F,visible:qe,counterHeightPercent:n,hasVehicle:!!E}),K==="productDetail"&&U&&o.jsx(Iu,{product:U,onBack:Te,onAddToCart:O,onNavigateToProductPage:B}),K==="packageDetail"&&q&&o.jsx(La,{package:q,onBack:Te,onNavigateToProductPage:ie=>{const Le=w.find(xe=>xe.sku===ie);Le&&B&&B(Le)}}),K==="products"&&o.jsx(Da,{messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:p,onInputBlur:f,chatEndRef:h,isMuted:m,onToggleMute:g,isSpeaking:_})]})},Mn=({variant:t="inline",initialState:e="idle",showChat:r=!0,className:s="",backdropUrl:n,counterOverlayUrl:i,counterHeightPercent:a,defaultBobImage:l,verticalOffset:c=0,scale:u=100,sessionToken:d,embedded:p=!1})=>{const{callbacks:f}=bt(),[h,m]=y.useState(!1),{animationState:g,setAnimationState:_,getCurrentImage:w,getCurrentOffset:k,getCurrentScale:b,availableStates:S}=Sa({isSpeaking:h}),{activeBackdrop:j}=Ea(),[C,F]=y.useState([]),[O,B]=y.useState([]),[E,A]=y.useState(null),[T,I]=y.useState(null),[N,z]=y.useState(!1),P=_a({setAnimationState:_,manualMode:!1,onReadyToSpeak:()=>{console.log("[BobWidget] Ready to speak")},onStreamComplete:()=>{_(S.find(V=>V.includes("idle"))||"idle")},onResearchStart:()=>{z(!0)},onHighlightPart:V=>{A(V),setTimeout(()=>A(null),8e3)},onHighlightProduct:V=>{I(V),setTimeout(()=>I(null),8e3)},onAutoFetchComplete:()=>{z(!1)}});y.useEffect(()=>{m(P.isSpeaking)},[P.isSpeaking]),y.useEffect(()=>{const V=f.onPartsFound,fe=f.onServicePackagesFound;return f.onPartsFound=ye=>{if(z(!1),!ye||ye.length===0){console.log("[Bob] Clearing products (empty array received)"),F([]),V==null||V(ye);return}const je=ye.map((ue,Te)=>({id:ue.SKU||ue.sku||`part-${Te}`,name:ue["Part Product Type"]||ue.partslot_description||ue.name||"Unknown Part",brand:ue.Brand||ue.brand,price:ue["Metro Retail Price"]||ue.price||0,sku:ue.SKU||ue.sku,partNumber:ue["Part Number"]||ue.part_number,partslotDescription:ue["Part Product Type"]||ue.partslot_description,image_url:ue.image_url}));console.log("[Bob] Products mapped and setting state:",je.length,"products"),F(je),V==null||V(ye)},f.onServicePackagesFound=ye=>{if(!ye||ye.length===0){console.log("[Bob] Clearing service packages (empty array received)"),B([]),fe==null||fe(ye);return}B(ye),fe==null||fe(ye)},()=>{f.onPartsFound=V,f.onServicePackagesFound=fe}},[f]);const te=n||(j==null?void 0:j.image_url),K=i||(j==null?void 0:j.counter_overlay_url)||void 0,$=a||(j==null?void 0:j.counter_height_percent)||12,U=w()||l||"",W=k(),q=b();if(t==="mobile"||t==="fullscreen")return o.jsx(Fa,{currentImage:U,animationState:g,backdropUrl:te,counterOverlayUrl:K,counterHeightPercent:$,bobOffset:W,bobScale:q,embedded:p,messages:P.messages,input:P.input,setInput:P.setInput,isLoading:P.isLoading,onSend:P.handleSend,onKeyPress:P.handleKeyPress,onInputFocus:P.handleInputFocus,onInputBlur:P.handleInputBlur,chatEndRef:P.chatEndRef,isMuted:P.isMuted,onToggleMute:P.toggleMute,isSpeaking:P.isSpeaking,products:C,servicePackages:O,highlightedPartType:E,highlightedProduct:T,onAddToCart:V=>{var fe;return(fe=f.onAddToCart)==null?void 0:fe.call(f,{product_id:V.id,product_name:V.name,quantity:1,unit_price:V.price,sku:V.sku,brand:V.brand})},onNavigateToProductPage:V=>{var fe;return(fe=f.onNavigateToProductPage)==null?void 0:fe.call(f,V)},onPackageSelect:V=>console.log("[BobWidget] Package selected:",V),isResearching:N,vehicle:P.identifiedVehicle});if(t==="inline"&&r)return o.jsx("div",{className:`relative w-full h-full ${s}`,children:o.jsx(Ua,{currentImage:U,animationState:g,backdropUrl:te,counterOverlayUrl:K,counterHeightPercent:$,bobOffset:W,bobScale:q,messages:P.messages,input:P.input,setInput:P.setInput,isLoading:P.isLoading,onSend:P.handleSend,onKeyPress:P.handleKeyPress,onInputFocus:P.handleInputFocus,onInputBlur:P.handleInputBlur,chatEndRef:P.chatEndRef,isMuted:P.isMuted,onToggleMute:P.toggleMute,isSpeaking:P.isSpeaking,products:C,servicePackages:O,highlightedPartType:E,highlightedProduct:T,onAddToCart:V=>{var fe;return(fe=f.onAddToCart)==null?void 0:fe.call(f,{product_id:V.id,product_name:V.name,quantity:1,unit_price:V.price,sku:V.sku,brand:V.brand})},onNavigateToProductPage:V=>{var fe;return(fe=f.onNavigateToProductPage)==null?void 0:fe.call(f,V)},onPackageSelect:V=>console.log("[BobWidget] Package selected:",V),isResearching:N,vehicle:P.identifiedVehicle})});const J={inline:"",floating:"fixed bottom-4 right-4 w-96 z-50 shadow-2xl rounded-lg overflow-hidden"};return o.jsxs("div",{className:`${J[t]||""} ${s}`,children:[U&&o.jsx(ja,{currentImage:U,animationState:g,backdropUrl:te,counterOverlayUrl:K,counterHeightPercent:$,verticalOffset:W,scale:q}),r&&o.jsx(Aa,{messages:P.messages,input:P.input,setInput:P.setInput,isLoading:P.isLoading,onSend:P.handleSend,onKeyPress:P.handleKeyPress,onInputFocus:P.handleInputFocus,onInputBlur:P.handleInputBlur,chatEndRef:P.chatEndRef,isMuted:P.isMuted,onToggleMute:P.toggleMute,isSpeaking:P.isSpeaking})]})},Pu=({bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,variant:n="mobile",initialState:i,showChat:a,className:l,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:p,verticalOffset:f,scale:h,ga4Config:m,analyticsEnabled:g=!0,bottomOffset:_=0,zIndexBase:w=50,embedded:k=!1})=>(y.useEffect(()=>{console.log("[BobWidget] Initialized",{version:pt,variant:n,bottomOffset:_,zIndexBase:w,bobConfigUrl:t.supabaseUrl,hostApiBaseUrl:e.baseUrl,analyticsEnabled:g})},[n,_,w,t.supabaseUrl,e.baseUrl,g]),o.jsx("div",{className:"bob-widget-root",style:{width:"100%",height:"100%"},children:o.jsx($n,{bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,ga4Config:m,analyticsEnabled:g,bottomOffset:_,zIndexBase:w,children:o.jsx(Mn,{variant:n,initialState:i,showChat:a,className:l,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:p,verticalOffset:f,scale:h,embedded:k})})}));function Nu(t){return t<640?"mobile":t<1024?"tablet":"desktop"}function Bu(){const t=[];if(typeof window>"u")return t;const e=document.querySelector(".bob-widget-root");if(!e)return t.push("bob-widget-root not found in DOM"),t;const r=window.getComputedStyle(e),s=e.parentElement;return s&&window.getComputedStyle(s).overflow==="hidden"&&t.push("Parent has overflow:hidden - may clip Bob"),r.transform!=="none"&&r.transform!=="matrix(1, 0, 0, 1, 0, 0)"&&t.push(`Unexpected transform on root: ${r.transform}`),r.isolation!=="isolate"&&t.push("Isolation not properly set"),t}const Ma=({partnerConfig:t,sessionToken:e})=>{const[r,s]=y.useState(null),[n,i]=y.useState([]),[a,l]=y.useState(!1);if(y.useEffect(()=>{const u=()=>{var f;const d=window.innerWidth,p=window.innerHeight;s({viewport:{width:d,height:p,deviceType:Nu(d)},origin:window.location.origin,originAllowed:((f=t==null?void 0:t.allowed_origins)==null?void 0:f.some(h=>h===window.location.origin||h.includes("*")))??!1,userAgent:navigator.userAgent.slice(0,50)+"...",timestamp:new Date().toISOString()}),i(Bu())};return u(),window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[t]),!r)return null;const c=({ok:u,label:d})=>o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"4px",fontSize:"11px",fontWeight:500,background:u?"rgba(34, 197, 94, 0.2)":"rgba(239, 68, 68, 0.2)",color:u?"#22c55e":"#ef4444"},children:[u?"✓":"✗"," ",d]});return o.jsxs("div",{style:{position:"fixed",top:"8px",right:"8px",zIndex:99999,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace',fontSize:"11px",lineHeight:1.4},children:[o.jsx("button",{onClick:()=>l(!a),style:{position:"absolute",top:0,right:0,width:"24px",height:"24px",background:"rgba(0, 0, 0, 0.8)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"4px",color:"#fff",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1},children:a?"🔍":"✕"}),!a&&o.jsxs("div",{style:{background:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"8px",padding:"12px",color:"#fff",maxWidth:"320px",backdropFilter:"blur(8px)"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"12px",paddingBottom:"8px",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:[o.jsx("span",{style:{fontSize:"14px"},children:"🔧"}),o.jsxs("span",{style:{fontWeight:600},children:["Bob Debug v",pt]})]}),o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px",marginBottom:"12px"},children:[o.jsx(c,{ok:!!t,label:`Partner: ${(t==null?void 0:t.partner_code)||"none"}`}),o.jsx(c,{ok:!!e,label:e?"Session":"No Session"}),o.jsx(c,{ok:r.originAllowed,label:"Origin"})]}),o.jsxs("div",{style:{display:"grid",gap:"6px"},children:[o.jsx(pr,{label:"Viewport",value:`${r.viewport.width}×${r.viewport.height} (${r.viewport.deviceType})`}),o.jsx(pr,{label:"Origin",value:r.origin}),o.jsx(pr,{label:"Bottom Offset",value:`${(t==null?void 0:t.default_bottom_offset)??0}px`}),o.jsx(pr,{label:"Z-Index Base",value:`${(t==null?void 0:t.default_z_index_base)??50}`}),o.jsx(pr,{label:"Blur",value:`${(t==null?void 0:t.backdrop_blur_intensity)??8}px`}),o.jsx(pr,{label:"Overlay",value:`${(((t==null?void 0:t.backdrop_overlay_opacity)??.15)*100).toFixed(0)}%`})]}),(t==null?void 0:t.feature_flags)&&o.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[o.jsx("div",{style:{color:"rgba(255,255,255,0.5)",marginBottom:"4px"},children:"Features:"}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:Object.entries(t.feature_flags).map(([u,d])=>o.jsx(c,{ok:!!d,label:u.replace(/([A-Z])/g," $1").trim()},u))})]}),n.length>0&&o.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[o.jsx("div",{style:{color:"#ef4444",marginBottom:"4px"},children:"⚠️ CSS Conflicts:"}),n.map((u,d)=>o.jsxs("div",{style:{color:"#fca5a5",fontSize:"10px"},children:["• ",u]},d))]}),o.jsx("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",color:"rgba(255,255,255,0.4)",fontSize:"10px"},children:r.timestamp})]})]})},pr=({label:t,value:e})=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px"},children:[o.jsxs("span",{style:{color:"rgba(255,255,255,0.5)"},children:[t,":"]}),o.jsx("span",{style:{color:"#fff",textAlign:"right",wordBreak:"break-all"},children:e})]}),Pi="https://gjoguxzstsihhxvdgpto.supabase.co",Ni="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imdqb2d1eHpzdHNpaGh4dmRncHRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjM5MzgyODEsImV4cCI6MjA3OTUxNDI4MX0.detu4TKB7RjC6l6CrVaPYoi0Hhz2asDt6zxNx1cdzq8";function $u(t,e){return t.some(r=>{if(r.includes("*")){const s=r.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${s}$`).test(e)}return r===e})}function Wa(t){const[e,r]=y.useState(null),[s,n]=y.useState(!0),[i,a]=y.useState(null),[l,c]=y.useState(!1),[u,d]=y.useState(null),p=y.useCallback(async()=>{if(!t){n(!1),a(new Error("Partner code is required"));return}n(!0),a(null);try{const f=pn(Pi,Ni);console.log(`[BobWidget] Loading partner config for: ${t}`);const{data:h,error:m}=await f.from("bob_partners").select("*").eq("partner_code",t).eq("is_active",!0).maybeSingle();if(m)throw new Error(`Failed to load partner config: ${m.message}`);if(!h)throw new Error(`Partner "${t}" not found or inactive`);const g=h,_=typeof window<"u"?window.location.origin:"",w=$u(g.allowed_origins||[],_);!w&&_&&(console.warn(`[BobWidget] Origin "${_}" not in allowed origins for ${t}`),console.warn("[BobWidget] Allowed origins:",g.allowed_origins));const k=pn(g.bob_supabase_url||Pi,g.bob_supabase_key||Ni);console.log("[BobWidget] Partner config loaded:",{partner:g.partner_code,displayName:g.display_name,bottomOffset:g.default_bottom_offset,blurIntensity:g.backdrop_blur_intensity,features:g.feature_flags,originAllowed:w}),r(g),c(w),d(k)}catch(f){const h=f instanceof Error?f:new Error("Unknown error loading partner config");console.error("[BobWidget] Partner config error:",h),a(h)}finally{n(!1)}},[t]);return y.useEffect(()=>{p()},[p]),{config:e,isLoading:s,error:i,isOriginAllowed:l,supabaseClient:u,reload:p}}function qa(t,e,r){return t!=null&&t.feature_flags?t.feature_flags[e]??r:r}const Fu=()=>o.jsxs("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #0a1628 0%, #0f2137 100%)"},children:[o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[o.jsx("div",{style:{width:"48px",height:"48px",border:"4px solid rgba(0, 102, 204, 0.3)",borderTopColor:"#0066cc",borderRadius:"50%",animation:"spin 1s linear infinite"}}),o.jsx("span",{style:{color:"rgba(255,255,255,0.7)",fontSize:"14px"},children:"Loading Bob..."})]}),o.jsx("style",{children:`
34
76
  @keyframes spin {
35
77
  to { transform: rotate(360deg); }
36
78
  }
37
- `})]}),ra=({error:t,partner:e})=>r.jsx("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #1a0a0a 0%, #2a1515 100%)",padding:"24px"},children:r.jsxs("div",{style:{maxWidth:"400px",textAlign:"center",color:"white"},children:[r.jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"⚠️"}),r.jsx("h3",{style:{fontSize:"20px",fontWeight:600,marginBottom:"8px"},children:"Bob Widget Error"}),r.jsx("p",{style:{fontSize:"14px",color:"rgba(255,255,255,0.7)",marginBottom:"16px"},children:t.message}),r.jsxs("code",{style:{display:"block",fontSize:"12px",background:"rgba(255,0,0,0.1)",padding:"12px",borderRadius:"8px",color:"#ff6b6b"},children:["Partner: ",e,r.jsx("br",{}),"Origin: ",typeof window<"u"?window.location.origin:"unknown"]})]})}),sa=({partner:t,sessionToken:e,bottomOffset:s,zIndexBase:n,backdropBlurIntensity:i,backdropOverlayOpacity:c,onAddToCart:d,onNavigate:u,onCheckout:y,onError:x,debug:b=!1,className:p=""})=>{const{config:g,isLoading:m,error:S,supabaseClient:f}=On(t);a.useEffect(()=>{console.log("[BobStandalone] Initialized",{version:et,partner:t,sessionToken:e?"present":"none",debug:b})},[t,e,b]);const j=a.useMemo(()=>({onAddToCart:d?R=>d(R):void 0,onCheckoutRequested:y,onError:x,onNavigateToProductPage:u?R=>{const P=R;P!=null&&P.sku&&u(`/product/${P.sku}`)}:void 0}),[d,u,y,x]),v=a.useMemo(()=>({}),[]);if(m)return r.jsx(ta,{});if(S||!g||!f){const R=S||new Error("Failed to initialize Bob");return x==null||x(R),r.jsx(ra,{error:R,partner:t})}const w=s??g.default_bottom_offset,h=n??g.default_z_index_base,k=b||Pn(g,"showDebugOverlay",!1);return r.jsx("div",{className:`bob-widget-root ${p}`,style:{width:"100%",height:"100%","--bob-blur-intensity":`${i??g.backdrop_blur_intensity}px`,"--bob-overlay-opacity":c??g.backdrop_overlay_opacity,"--bob-z-base":h},children:r.jsxs(ds,{bobConfig:{supabaseUrl:g.bob_supabase_url,supabaseKey:g.bob_supabase_key},hostApiConfig:{baseUrl:g.api_base_url,apiKey:"",partnerCode:g.partner_code},hostContext:v,callbacks:j,bottomOffset:w,zIndexBase:h,children:[r.jsx(bs,{variant:"mobile",sessionToken:e}),k&&r.jsx(In,{partnerConfig:g,sessionToken:e})]})})},na=({children:t,isSpeaking:e=!1,hasProducts:s=!1,onVisibilityChange:n,onPositionChange:i,currentPosition:c="center"})=>{const[d,u]=a.useState(!1),[y,x]=a.useState(0),b=a.useRef(null),p=a.useRef(0),g=a.useRef(0),m=a.useRef(!1),S=.25;a.useEffect(()=>{e&&c==="hidden"&&(i==null||i("partial-left"),n==null||n(!0))},[e,c,i,n]);const f=a.useCallback(k=>{p.current=k.touches[0].clientX,g.current=k.touches[0].clientY,m.current=!1,u(!0)},[]),j=a.useCallback(k=>{if(!d)return;const R=k.touches[0].clientX,P=k.touches[0].clientY,H=R-p.current,B=P-g.current;!m.current&&Math.abs(H)>10&&(m.current=Math.abs(H)>Math.abs(B)),m.current&&(k.preventDefault(),x(H))},[d]),v=a.useCallback(()=>{var B;if(!d)return;u(!1);const k=((B=b.current)==null?void 0:B.offsetWidth)||300,R=Math.abs(y)/k,P=y<0,H=y>0;P?c==="center"&&R>S?(i==null||i("partial-left"),n==null||n(!0)):c==="partial-left"&&R>S&&(i==null||i("hidden"),n==null||n(!1)):H&&(c==="hidden"&&R>S?(i==null||i("partial-left"),n==null||n(!0)):c==="partial-left"&&R>S&&!s&&(i==null||i("center"),n==null||n(!0))),x(0)},[d,y,c,s,i,n]),w=a.useCallback(()=>{i==null||i("partial-left"),n==null||n(!0)},[i,n]),h=()=>d&&y!==0?`translateX(${Math.max(-100,Math.min(100,y))}px)`:"translateX(0)";return r.jsxs(r.Fragment,{children:[r.jsxs("div",{ref:b,style:{position:"fixed",inset:0,width:"100vw",height:"100dvh",transform:h(),transition:d?"none":"transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)",willChange:"transform"},onTouchStart:f,onTouchMove:j,onTouchEnd:v,children:[t,c==="center"&&!d&&r.jsx("div",{className:"absolute left-2 top-1/2 -translate-y-1/2 pointer-events-none",style:{animation:"swipeHint 3s ease-in-out 2s 1",opacity:0},children:r.jsx("svg",{className:"w-6 h-6 text-white/50",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})})]}),c==="hidden"&&r.jsx("button",{onClick:w,className:"fixed left-0 top-1/2 -translate-y-1/2 z-50 flex items-center justify-center",style:{writingMode:"vertical-rl",textOrientation:"mixed",background:"linear-gradient(180deg, #0066CC 0%, #004999 100%)",padding:"16px 8px",borderTopRightRadius:"12px",borderBottomRightRadius:"12px",boxShadow:"4px 0 12px rgba(0, 102, 204, 0.3)",animation:"slideInFromLeft 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)",border:"none",cursor:"pointer"},children:r.jsx("span",{className:"text-white font-bold text-lg tracking-wider",children:"BOB"})}),r.jsx("style",{children:`
79
+ `})]}),Du=({error:t,partner:e})=>o.jsx("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #1a0a0a 0%, #2a1515 100%)",padding:"24px"},children:o.jsxs("div",{style:{maxWidth:"400px",textAlign:"center",color:"white"},children:[o.jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"⚠️"}),o.jsx("h3",{style:{fontSize:"20px",fontWeight:600,marginBottom:"8px"},children:"Bob Widget Error"}),o.jsx("p",{style:{fontSize:"14px",color:"rgba(255,255,255,0.7)",marginBottom:"16px"},children:t.message}),o.jsxs("code",{style:{display:"block",fontSize:"12px",background:"rgba(255,0,0,0.1)",padding:"12px",borderRadius:"8px",color:"#ff6b6b"},children:["Partner: ",e,o.jsx("br",{}),"Origin: ",typeof window<"u"?window.location.origin:"unknown"]})]})}),Lu=({partner:t,sessionToken:e,bottomOffset:r,zIndexBase:s,backdropBlurIntensity:n,backdropOverlayOpacity:i,onAddToCart:a,onNavigate:l,onCheckout:c,onError:u,debug:d=!1,className:p=""})=>{const{config:f,isLoading:h,error:m,supabaseClient:g}=Wa(t);y.useEffect(()=>{console.log("[BobStandalone] Initialized",{version:pt,partner:t,sessionToken:e?"present":"none",debug:d})},[t,e,d]);const _=y.useMemo(()=>({onAddToCart:a?j=>a(j):void 0,onCheckoutRequested:c,onError:u,onNavigateToProductPage:l?j=>{const C=j;C!=null&&C.sku&&l(`/product/${C.sku}`)}:void 0}),[a,l,c,u]),w=y.useMemo(()=>({}),[]);if(h)return o.jsx(Fu,{});if(m||!f||!g){const j=m||new Error("Failed to initialize Bob");return u==null||u(j),o.jsx(Du,{error:j,partner:t})}const k=r??f.default_bottom_offset,b=s??f.default_z_index_base,S=d||qa(f,"showDebugOverlay",!1);return o.jsx("div",{className:`bob-widget-root ${p}`,style:{width:"100%",height:"100%","--bob-blur-intensity":`${n??f.backdrop_blur_intensity}px`,"--bob-overlay-opacity":i??f.backdrop_overlay_opacity,"--bob-z-base":b},children:o.jsxs($n,{bobConfig:{supabaseUrl:f.bob_supabase_url,supabaseKey:f.bob_supabase_key},hostApiConfig:{baseUrl:f.api_base_url,apiKey:"",partnerCode:f.partner_code},hostContext:w,callbacks:_,bottomOffset:k,zIndexBase:b,children:[o.jsx(Mn,{variant:"mobile",sessionToken:e}),S&&o.jsx(Ma,{partnerConfig:f,sessionToken:e})]})})},Uu=({children:t,isSpeaking:e=!1,hasProducts:r=!1,onVisibilityChange:s,onPositionChange:n,currentPosition:i="center"})=>{const[a,l]=y.useState(!1),[c,u]=y.useState(0),d=y.useRef(null),p=y.useRef(0),f=y.useRef(0),h=y.useRef(!1),m=.25;y.useEffect(()=>{e&&i==="hidden"&&(n==null||n("partial-left"),s==null||s(!0))},[e,i,n,s]);const g=y.useCallback(S=>{p.current=S.touches[0].clientX,f.current=S.touches[0].clientY,h.current=!1,l(!0)},[]),_=y.useCallback(S=>{if(!a)return;const j=S.touches[0].clientX,C=S.touches[0].clientY,F=j-p.current,O=C-f.current;!h.current&&Math.abs(F)>10&&(h.current=Math.abs(F)>Math.abs(O)),h.current&&(S.preventDefault(),u(F))},[a]),w=y.useCallback(()=>{var O;if(!a)return;l(!1);const S=((O=d.current)==null?void 0:O.offsetWidth)||300,j=Math.abs(c)/S,C=c<0,F=c>0;C?i==="center"&&j>m?(n==null||n("partial-left"),s==null||s(!0)):i==="partial-left"&&j>m&&(n==null||n("hidden"),s==null||s(!1)):F&&(i==="hidden"&&j>m?(n==null||n("partial-left"),s==null||s(!0)):i==="partial-left"&&j>m&&!r&&(n==null||n("center"),s==null||s(!0))),u(0)},[a,c,i,r,n,s]),k=y.useCallback(()=>{n==null||n("partial-left"),s==null||s(!0)},[n,s]),b=()=>a&&c!==0?`translateX(${Math.max(-100,Math.min(100,c))}px)`:"translateX(0)";return o.jsxs(o.Fragment,{children:[o.jsxs("div",{ref:d,style:{position:"fixed",inset:0,width:"100vw",height:"100dvh",transform:b(),transition:a?"none":"transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)",willChange:"transform"},onTouchStart:g,onTouchMove:_,onTouchEnd:w,children:[t,i==="center"&&!a&&o.jsx("div",{className:"absolute left-2 top-1/2 -translate-y-1/2 pointer-events-none",style:{animation:"swipeHint 3s ease-in-out 2s 1",opacity:0},children:o.jsx("svg",{className:"w-6 h-6 text-white/50",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})})]}),i==="hidden"&&o.jsx("button",{onClick:k,className:"fixed left-0 top-1/2 -translate-y-1/2 z-50 flex items-center justify-center",style:{writingMode:"vertical-rl",textOrientation:"mixed",background:"linear-gradient(180deg, #0066CC 0%, #004999 100%)",padding:"16px 8px",borderTopRightRadius:"12px",borderBottomRightRadius:"12px",boxShadow:"4px 0 12px rgba(0, 102, 204, 0.3)",animation:"slideInFromLeft 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)",border:"none",cursor:"pointer"},children:o.jsx("span",{className:"text-white font-bold text-lg tracking-wider",children:"BOB"})}),o.jsx("style",{children:`
38
80
  @keyframes slideInFromLeft {
39
81
  from {
40
82
  transform: translateX(-100%) translateY(-50%);
@@ -56,4 +98,4 @@ React keys must be passed directly to JSX without using spread:
56
98
  transform: translateX(-10px) translateY(-50%);
57
99
  }
58
100
  }
59
- `})]})},ot={primary:"216 100% 40%",secondary:"199 95% 74%",success:"33 100% 50%",background:"223 46% 13%",backgroundMode:"dark",sparkDealColor:"33 100% 50%",primaryHex:"#0066CC",secondaryHex:"#7DD3FC",successHex:"#FF9500",backgroundHex:"#111827",sparkDealHex:"#FF9500"};function lr(t){const e=t.match(/(\d+\.?\d*)\s+(\d+\.?\d*)%?\s+(\d+\.?\d*)%?/);if(!e)return"#000000";const s=parseFloat(e[1]),n=parseFloat(e[2])/100,i=parseFloat(e[3])/100,c=(1-Math.abs(2*i-1))*n,d=c*(1-Math.abs(s/60%2-1)),u=i-c/2;let y=0,x=0,b=0;s<60?(y=c,x=d):s<120?(y=d,x=c):s<180?(x=c,b=d):s<240?(x=d,b=c):s<300?(y=d,b=c):(y=c,b=d);const p=g=>Math.round((g+u)*255).toString(16).padStart(2,"0");return`#${p(y)}${p(x)}${p(b)}`}function Mn(){const t=At();return wr({queryKey:["bob-theme-settings"],queryFn:async()=>{var b,p,g,m,S,f,j,v,w,h,k;if(!t)return console.log("[useThemeSettings] No supabase client, using defaults"),ot;const{data:e,error:s}=await t.from("bob_theme_settings").select("setting_key, color_value, hex_preview").in("setting_key",["matrix_primary","matrix_secondary","matrix_success","matrix_background","matrix_background_mode","matrix_spark_deal_color"]);if(s)return console.error("[useThemeSettings] Error fetching:",s),ot;if(!e||e.length===0)return ot;const n=new Map(e.map(R=>[R.setting_key,R])),i=((b=n.get("matrix_primary"))==null?void 0:b.color_value)||ot.primary,c=((p=n.get("matrix_secondary"))==null?void 0:p.color_value)||ot.secondary,d=((g=n.get("matrix_success"))==null?void 0:g.color_value)||ot.success,u=((m=n.get("matrix_background"))==null?void 0:m.color_value)||ot.background,y=((S=n.get("matrix_spark_deal_color"))==null?void 0:S.color_value)||ot.sparkDealColor,x=((f=n.get("matrix_background_mode"))==null?void 0:f.color_value)||"dark";return{primary:i,secondary:c,success:d,background:u,backgroundMode:x,sparkDealColor:y,primaryHex:((j=n.get("matrix_primary"))==null?void 0:j.hex_preview)||lr(i),secondaryHex:((v=n.get("matrix_secondary"))==null?void 0:v.hex_preview)||lr(c),successHex:((w=n.get("matrix_success"))==null?void 0:w.hex_preview)||lr(d),backgroundHex:((h=n.get("matrix_background"))==null?void 0:h.hex_preview)||lr(u),sparkDealHex:((k=n.get("matrix_spark_deal_color"))==null?void 0:k.hex_preview)||lr(y)}},staleTime:60*1e3,gcTime:5*60*1e3})}const Ur={enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500,bobCommentary:!1};function ia(){const t=At();return wr({queryKey:["spark-deals-settings"],queryFn:async()=>{if(!t)return Ur;const{data:e,error:s}=await t.from("bob_settings").select("setting_key, setting_value").like("setting_key","spark_deals_%");if(s)return console.error("[useSparkDealsSettings] Error:",s),Ur;if(!e||e.length===0)return Ur;const n=new Map(e.map(i=>[i.setting_key,i.setting_value]));return{enabled:n.get("spark_deals_enabled")==="true",inRain:n.get("spark_deals_in_rain")==="true",rainFrequency:parseFloat(n.get("spark_deals_rain_frequency")||"0.15"),primingEnabled:n.get("spark_deals_priming_enabled")==="true",bannerEnabled:n.get("spark_deals_banner_enabled")==="true",delayMs:parseInt(n.get("spark_deals_delay_ms")||"2000",10),scrollSpeed:parseInt(n.get("spark_deals_scroll_speed")||"5000",10),maxPerSession:parseInt(n.get("spark_deals_max_per_session")||"3",10),minResearchTime:parseInt(n.get("spark_deals_min_research_time")||"1500",10),bobCommentary:n.get("spark_deals_bob_commentary")==="true"}},staleTime:60*1e3,gcTime:5*60*1e3})}function An(t=!0){const e=At();return wr({queryKey:["spark-deals"],queryFn:async()=>{if(!e)return console.log("[useSparkDeals] No supabase client"),[];try{return console.error("[useSparkDeals] Missing VITE_SUPABASE_URL"),[]}catch(s){return console.error("[useSparkDeals] Error:",s),[]}},enabled:t,staleTime:5*60*1e3,gcTime:10*60*1e3})}function aa(t){const e=[];return t.forEach(s=>{e.push(`$${s.price.toFixed(0)}`),s.brand&&e.push(s.brand.toUpperCase());const n=s.product_name.split(" ")[0];n&&n.length>2&&e.push(n.toUpperCase())}),e}const Ln=({deals:t,currentDealIndex:e,onDealChange:s,onDealClick:n,scrollSpeed:i,theme:c})=>{const[d,u]=a.useState(!1),[y,x]=a.useState(100),b=t[e],p=c.sparkDealHex||"#FF9500",g=c.backgroundMode!=="light";a.useEffect(()=>{if(!b)return;u(!0),x(100);const f=setTimeout(()=>{x(0)},50),j=setTimeout(()=>{x(-100)},i-500),v=setTimeout(()=>{const w=(e+1)%t.length;s(w),u(!1)},i);return()=>{clearTimeout(f),clearTimeout(j),clearTimeout(v)}},[e,b,i,t.length,s]);const m=a.useCallback(()=>{b&&n(b)},[b,n]);if(!b)return null;const S=b.original_price?Math.round((1-b.price/b.original_price)*100):null;return r.jsxs("div",{className:"absolute bottom-20 left-0 right-0 z-20 overflow-hidden pointer-events-none",style:{height:"72px"},children:[r.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-auto",style:{transform:`translateX(${y}%)`,transition:"transform 0.5s ease-out"},children:r.jsxs("button",{onClick:m,className:"group flex items-center gap-4 px-6 py-3 rounded-xl shadow-2xl transition-all hover:scale-105 active:scale-95",style:{background:g?"linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(17, 24, 39, 0.9) 100%)":"linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.98) 100%)",border:`2px solid ${p}`,boxShadow:`0 8px 32px -4px ${p}40, 0 4px 16px -2px rgba(0,0,0,0.2)`},children:[r.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center shrink-0",style:{background:`${p}20`},children:r.jsx("svg",{className:"w-5 h-5",fill:p,viewBox:"0 0 24 24",children:r.jsx("path",{d:"M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z"})})}),r.jsxs("div",{className:"flex flex-col items-start min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs font-bold uppercase tracking-wider",style:{color:p},children:"⚡ Spark Deal"}),S&&S>0&&r.jsxs("span",{className:"text-xs font-bold px-2 py-0.5 rounded-full",style:{background:p,color:g?"#000":"#fff"},children:[S,"% OFF"]})]}),r.jsxs("p",{className:"text-sm font-semibold truncate max-w-[200px]",style:{color:g?"#fff":"#111827"},children:[b.brand," ",b.product_name]})]}),r.jsxs("div",{className:"flex flex-col items-end shrink-0",children:[b.original_price&&b.original_price>b.price&&r.jsxs("span",{className:"text-xs line-through",style:{color:g?"#9ca3af":"#6b7280"},children:["$",b.original_price.toFixed(2)]}),r.jsxs("span",{className:"text-xl font-bold",style:{color:p},children:["$",b.price.toFixed(2)]})]}),r.jsx("svg",{className:"w-5 h-5 opacity-60 group-hover:opacity-100 group-hover:translate-x-1 transition-all",fill:"none",stroke:p,strokeWidth:2,viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.25 4.5l7.5 7.5-7.5 7.5"})})]})}),t.length>1&&r.jsx("div",{className:"absolute bottom-1 left-0 right-0 flex justify-center gap-1.5",children:t.map((f,j)=>r.jsx("div",{className:"w-1.5 h-1.5 rounded-full transition-all",style:{background:j===e?p:`${p}40`,transform:j===e?"scale(1.3)":"scale(1)"}},j))})]})},zs=["*",":","=",">","<","+","-","|","•","○","●","◆","◇","0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","K","M","N","P","R","S","T","X","Z","#","@","$","%","&","~","^","/","\\","[","]","{","}"],$s=["BR","KE","OI","FI","LT","SP","RK","EN","GN","PT","CL","UT","AX","WH","EL","TI","RE","PA","DS","RO","TR","BT","HP","CV","XL"],oa=({phase:t,message:e,onComplete:s,onSparkDealClick:n,subliminalBrands:i=[]})=>{const c=a.useRef(null),d=a.useRef(),u=a.useRef([]),y=a.useRef(0),[x,b]=a.useState(0),[p,g]=a.useState(!1),[m,S]=a.useState(0),{data:f}=Mn(),{data:j}=ia(),{data:v}=An(t!=="hidden"&&(j==null?void 0:j.enabled)),w=f||{primaryHex:"#0066CC",secondaryHex:"#004999",successHex:"#FF9500",backgroundHex:"#111827",sparkDealHex:"#FF9500",backgroundMode:"dark"},h=j||{enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500},k=v&&h.inRain?[...aa(v),...i]:i,R=.08,P=a.useCallback(()=>k.length>0&&Math.random()<R?{char:k[Math.floor(Math.random()*k.length)],isSubliminal:!0}:Math.random()<.15?{char:$s[Math.floor(Math.random()*$s.length)],isSubliminal:!1}:{char:zs[Math.floor(Math.random()*zs.length)],isSubliminal:!1},[k]),H=a.useCallback((C,E)=>C.isSubliminal?w.sparkDealHex:t==="success"?w.successHex:Math.sin(E*2+C.x*.01)*.5+.5>.5?w.primaryHex:w.secondaryHex,[t,w]),B=a.useCallback((C,E)=>{const N=[],I=Math.floor(C/25);for(let U=0;U<I;U++){const{char:F,isSubliminal:J}=P();N.push({x:U*25+12,y:Math.random()*E,speed:1.5+Math.random()*3.5,char:F,isSubliminal:J,opacity:.2+Math.random()*.6,size:J?13:9+Math.random()*3,glowIntensity:J?.6:0,changeCounter:Math.floor(Math.random()*30)})}u.current=N},[P]);a.useEffect(()=>{if(t==="hidden"){d.current&&cancelAnimationFrame(d.current);return}const C=c.current;if(!C)return;const E=C.getContext("2d");if(!E)return;const N=()=>{C.width=C.offsetWidth*window.devicePixelRatio,C.height=C.offsetHeight*window.devicePixelRatio,E.scale(window.devicePixelRatio,window.devicePixelRatio),B(C.offsetWidth,C.offsetHeight)};N(),y.current=Date.now();const I=()=>{const U=C.offsetWidth,F=C.offsetHeight,q=(Date.now()-y.current)/1e3;if(E.clearRect(0,0,U,F),u.current.forEach(O=>{const D=H(O,q);if(E.font=`bold ${O.size}px monospace`,E.fillStyle=D,E.globalAlpha=O.opacity,O.isSubliminal&&O.glowIntensity>0?(E.shadowColor=w.sparkDealHex,E.shadowBlur=8*O.glowIntensity):E.shadowBlur=0,E.fillText(O.char,O.x,O.y),O.y+=O.speed,O.changeCounter++,O.changeCounter>20+Math.random()*40){const{char:z,isSubliminal:$}=P();O.char=z,O.isSubliminal=$,O.size=$?13:9+Math.random()*3,O.glowIntensity=$?.6:0,O.changeCounter=0}if(O.y>F+20){const{char:z,isSubliminal:$}=P();O.y=-20,O.char=z,O.isSubliminal=$,O.speed=1.5+Math.random()*3.5,O.opacity=.2+Math.random()*.6,O.size=$?13:9+Math.random()*3,O.glowIntensity=$?.6:0,O.changeCounter=0}}),E.globalAlpha=1,E.shadowBlur=0,t==="success"){const O=Math.max(0,1-q*2);O>0&&(E.fillStyle=`rgba(255, 149, 0, ${O*.3})`,E.fillRect(0,0,U,F)),q>.5&&s&&s()}d.current=requestAnimationFrame(I)};return I(),window.addEventListener("resize",N),()=>{d.current&&cancelAnimationFrame(d.current),window.removeEventListener("resize",N)}},[t,w,P,H,B,s]),a.useEffect(()=>{if(t==="hidden"||!v||v.length===0||!h.bannerEnabled){g(!1);return}if(m>=h.maxPerSession)return;const C=setTimeout(()=>{g(!0)},h.delayMs);return()=>clearTimeout(C)},[t,v,h,m]);const A=a.useCallback(C=>{b(C),S(E=>E+1)},[]),_=a.useCallback(C=>{console.log("[MatrixLoader] Spark deal clicked:",C.product_name),n==null||n(C)},[n]);return t==="hidden"?null:r.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center overflow-hidden pointer-events-none",style:{background:"transparent"},children:[r.jsx("canvas",{ref:c,className:"absolute inset-0 w-full h-full",style:{opacity:.85}}),p&&v&&v.length>0&&r.jsx(Ln,{deals:v.slice(0,h.maxPerSession),currentDealIndex:x,onDealChange:A,onDealClick:_,scrollSpeed:h.scrollSpeed,theme:w})]})},la=({currentImage:t,animationState:e,backdropUrl:s,counterOverlayUrl:n,counterHeightPercent:i=22,products:c,servicePackages:d,highlightedPartType:u,highlightedProduct:y,onProductClick:x,onPackageSelect:b,isResearching:p,vehicle:g,onChangeVehicle:m,bobOffset:S=0,bobScale:f=100,bobHasArrived:j=!0,externalBobPosition:v,onBobPositionChange:w})=>{const h=typeof window<"u"&&window.self!==window.top,k=Br(),R=ps(),[P,H]=a.useState("center"),[B,A]=a.useState("hidden"),_=v??P,C=a.useCallback(q=>{H(q),w==null||w(q)},[w]),E=c.length>0||d.length>0,U=(()=>{switch(k){case"desktop":return 80*R.uiScale;case"tablet":return 90*R.uiScale;case"mobile":return 140;default:return 140}})()*f/100;a.useEffect(()=>{if(p&&B!=="loading"&&B!=="visible")A("loading"),_==="center"&&C("partial-left");else if(E&&B!=="visible")if(_==="center"){C("partial-left"),A("transitioning");const q=setTimeout(()=>{A("visible")},400);return()=>clearTimeout(q)}else A("visible");else!E&&!p&&B!=="hidden"&&(A("hidden"),C("center"))},[E,p,B,_,C]);const F=B!=="hidden",J=F&&E;return r.jsxs("div",{className:"absolute inset-0 overflow-hidden",style:{width:"100%",height:"100%",touchAction:"manipulation"},children:[s&&r.jsxs(r.Fragment,{children:[r.jsx("img",{src:s,alt:"Shop backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-center transition-all duration-500",style:{pointerEvents:"none",filter:J?"blur(8px)":"none",transform:J?"scale(1.02)":"scale(1)"}}),r.jsx("div",{className:"absolute inset-0 z-[1] transition-opacity duration-500 pointer-events-none",style:{background:"rgba(0, 0, 0, 0.15)",opacity:J?1:0}})]}),r.jsx(Ir,{currentImage:t,animationState:e,counterOverlayUrl:n,counterHeightPercent:i,scale:U,position:_,verticalOffset:S,hasArrived:j}),g&&!h&&r.jsx("div",{style:{position:"absolute",top:"8px",left:"8px",right:"8px",zIndex:20},children:r.jsxs("div",{style:{backgroundColor:"rgba(255, 255, 255, 0.9)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)",borderRadius:"8px",padding:"8px 12px",paddingTop:"calc(env(safe-area-inset-top, 4px) + 8px)",border:"1px solid #e5e7eb",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsxs("p",{style:{fontSize:"12px",fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[g.year," ",g.make," ",g.model]}),g.rego&&r.jsx("p",{style:{fontSize:"10px",color:"#6b7280"},children:g.rego})]}),m&&r.jsx("button",{onClick:m,style:{fontSize:"12px",color:"#2563eb",marginLeft:"8px",flexShrink:0,background:"none",border:"none",cursor:"pointer",minHeight:"unset",minWidth:"unset"},children:"Change"})]})}),r.jsx(Or,{products:c,servicePackages:d,highlightedPartType:u,highlightedProduct:y,onProductClick:x,onPackageSelect:b,isResearching:p,visible:F,counterHeightPercent:i,hasVehicle:!!g})]})},ca=6e4,ua=({states:t,setAnimationState:e,manualMode:s})=>{const[n,i]=a.useState("page_load"),[c,d]=a.useState(!1),u=a.useRef(null),y=a.useCallback(_=>{const C=t.find(E=>E.chat_trigger===_&&E.is_active);return console.log(`[StateTransitions] Looking for trigger: "${_}" -> found:`,(C==null?void 0:C.state_key)||"none"),C},[t]),x=a.useCallback(()=>t.find(_=>_.chat_trigger==="processing_input"||_.state_key==="research"||_.state_key==="researching"||_.title.toLowerCase().includes("research")||_.title.toLowerCase().includes("thinking")),[t]),b=a.useCallback(()=>t.find(_=>_.chat_trigger==="streaming_response"||_.state_key==="talk"||_.state_key==="talking"||_.title.toLowerCase().includes("talk")),[t]),p=a.useCallback(()=>t.find(_=>_.chat_trigger==="awaiting_input"||_.state_key==="talk_pause"||_.state_key==="listening"||_.title.toLowerCase().includes("listen")||_.title.toLowerCase().includes("pause")),[t]),g=a.useCallback(()=>{const _=t.find(C=>C.chat_trigger==="response_complete"||C.state_key==="complete"||C.title.toLowerCase().includes("complete"));return _||t.find(C=>C.state_key==="idle"||C.title.toLowerCase().includes("idle"))},[t]),m=a.useCallback(()=>t.find(_=>_.chat_trigger==="idle"||_.state_key==="idle"||_.title.toLowerCase().includes("idle")),[t]),S=a.useCallback(_=>{const C=t.find(E=>E.state_key===_);return{speed:(C==null?void 0:C.animation_speed)||400,pauseDuration:(C==null?void 0:C.pause_duration)||0,loopCount:(C==null?void 0:C.loop_count)||0}},[t]),f=a.useCallback(()=>{u.current&&(clearTimeout(u.current),u.current=null)},[]),j=a.useCallback(()=>{f(),!s&&(u.current=setTimeout(()=>{const _=m();_&&(i("idle"),e(_.state_key))},ca))},[s,m,e,f]),v=a.useCallback(_=>{if(s)return;const C=y(_);C&&e(C.state_key)},[s,y,e]),w=a.useCallback(()=>{if(s)return;const _=p();_&&(i("awaiting_input"),e(_.state_key),j())},[s,p,e,j]),h=a.useCallback(()=>{c||s||(d(!0),i("page_load"),v("page_load"),setTimeout(()=>{w()},3e3))},[c,s,v,w]),k=a.useCallback(()=>{if(s)return;f(),i("processing_input");const _=x();console.log("[StateTransitions] User input - switching to RESEARCH:",_==null?void 0:_.state_key),_?e(_.state_key):v("processing_input")},[s,f,x,e,v]),R=a.useCallback(()=>{if(s)return;f(),i("streaming_response");const _=b();console.log("[StateTransitions] Speech started - switching to TALK:",_==null?void 0:_.state_key),_&&e(_.state_key)},[s,f,b,e]),P=a.useCallback(()=>{if(s)return;const _=g();console.log("[StateTransitions] Speech ended - switching to COMPLETE:",_==null?void 0:_.state_key),_&&e(_.state_key),setTimeout(()=>{s||w()},2e3)},[s,g,e,w]),H=a.useCallback(()=>{f(),i("streaming_response"),console.log("[StateTransitions] Stream started (API response)")},[f]),B=a.useCallback(()=>{i("response_complete"),console.log("[StateTransitions] Stream complete (API finished)");const _=g();_&&e(_.state_key),setTimeout(()=>{w()},2e3)},[g,e,w]),A=a.useCallback(()=>{if(s)return;i("showing_product"),console.log("[StateTransitions] Showing products");const _=t.find(C=>C.chat_trigger==="showing_product"||C.state_key==="showing_product");_&&e(_.state_key),setTimeout(()=>{w()},3e3)},[s,t,e,w]);return a.useEffect(()=>()=>f(),[f]),{chatStage:n,initialize:h,onUserInput:k,onSpeechStart:R,onSpeechEnd:P,onStreamStart:H,onStreamComplete:B,onShowingProduct:A,getStateSettings:S}},da=()=>{const t=At();return{checkHealth:async()=>{if(!t)return{healthy:!1,reason:"No Supabase client available - ensure BobProvider is configured",stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};try{const{data:s,error:n}=await t.from("bob_looks").select("id, name, is_active").eq("is_active",!0).limit(1);if(n)return{healthy:!1,reason:`Database error fetching looks: ${n.message}`,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const i=s==null?void 0:s[0];if(!i)return{healthy:!1,reason:"No active look configured in bob_looks table",stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const{data:c,error:d}=await t.from("animation_states").select("state_key").eq("is_active",!0).eq("look_id",i.id);if(d)return{healthy:!1,reason:`Database error fetching states: ${d.message}`,activeLookId:i.id,activeLookName:i.name,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const u=(c==null?void 0:c.map(S=>S.state_key))||[],x=["idle","talking","listening"].filter(S=>{const f=[S,S.replace("ing",""),S+"ing"];return!u.some(j=>f.includes(j))}),{data:b,error:p}=await t.from("bob_animations").select("id").eq("is_active",!0).eq("look_id",i.id),g=p?0:(b==null?void 0:b.length)||0,m=u.length>=4&&g>0&&x.length===0;return{healthy:m,reason:m?void 0:`Missing critical states: ${x.join(", ")}`,activeLookId:i.id,activeLookName:i.name,stateCount:u.length,states:u,missingCritical:x,frameCount:g}}catch(s){return{healthy:!1,reason:`Unexpected error: ${s instanceof Error?s.message:"Unknown"}`,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0}}}}};console.log(`[BobWidget] Package loaded - v${et}`);exports.BADGE_CONFIG=yn;exports.BOB_VERSION=et;exports.Bob=bs;exports.BobCharacter=xn;exports.BobDebugOverlay=In;exports.BobProvider=ds;exports.BobStandalone=sa;exports.BobSuggestions=fs;exports.BobWidget=Xi;exports.CARFIX_COLORS=K;exports.ChatInterface=Sn;exports.ContainedChatDrawer=Nn;exports.ContainedMobileBobLayout=Bn;exports.IMAGE_URLS=pr;exports.MatrixProductLoader=oa;exports.MobileBobCharacter=Ir;exports.MobileBobLayout=Cn;exports.MobileBobLayoutCore=la;exports.MobileChatDrawer=Rn;exports.MobileProductColumn=Or;exports.ProductBadge=ur;exports.ProductTile=Tn;exports.QUALITY_TIER_CONFIG=Nr;exports.ServicePackageDetailView=Fn;exports.SparkDealBanner=Ln;exports.SwipeableBob=na;exports.TYPOGRAPHY=ze;exports.formatNZD=bt;exports.getBobVersion=$n;exports.getDisplayPrice=wn;exports.getFeatureFlag=Pn;exports.isRotorProduct=vn;exports.useBobAnalytics=dn;exports.useBobAnalyticsConfig=Bi;exports.useBobAnimation=bn;exports.useBobAnimationData=gn;exports.useBobBackdrop=mn;exports.useBobCallbacks=Fi;exports.useBobChat=pn;exports.useBobContext=tt;exports.useBobHealthCheck=da;exports.useBobLayoutConfig=hs;exports.useBobStateTransitions=ua;exports.useBobSupabase=Ri;exports.useBobSupabaseSafe=At;exports.useHostApiConfig=Ni;exports.useHostContext=Ci;exports.usePartnerConfig=On;exports.useReturningUser=fn;exports.useSparkDeals=An;exports.useSpeechRecognition=gs;exports.useSpeechSynthesis=hn;exports.useThemeSettings=Mn;
101
+ `})]})},_t={primary:"216 100% 40%",secondary:"199 95% 74%",success:"33 100% 50%",background:"223 46% 13%",backgroundMode:"dark",sparkDealColor:"33 100% 50%",primaryHex:"#0066CC",secondaryHex:"#7DD3FC",successHex:"#FF9500",backgroundHex:"#111827",sparkDealHex:"#FF9500"};function zr(t){const e=t.match(/(\d+\.?\d*)\s+(\d+\.?\d*)%?\s+(\d+\.?\d*)%?/);if(!e)return"#000000";const r=parseFloat(e[1]),s=parseFloat(e[2])/100,n=parseFloat(e[3])/100,i=(1-Math.abs(2*n-1))*s,a=i*(1-Math.abs(r/60%2-1)),l=n-i/2;let c=0,u=0,d=0;r<60?(c=i,u=a):r<120?(c=a,u=i):r<180?(u=i,d=a):r<240?(u=a,d=i):r<300?(c=a,d=i):(c=i,d=a);const p=f=>Math.round((f+l)*255).toString(16).padStart(2,"0");return`#${p(c)}${p(u)}${p(d)}`}function za(){const t=ar();return fs({queryKey:["bob-theme-settings"],queryFn:async()=>{var d,p,f,h,m,g,_,w,k,b,S;if(!t)return console.log("[useThemeSettings] No supabase client, using defaults"),_t;const{data:e,error:r}=await t.from("bob_theme_settings").select("setting_key, color_value, hex_preview").in("setting_key",["matrix_primary","matrix_secondary","matrix_success","matrix_background","matrix_background_mode","matrix_spark_deal_color"]);if(r)return console.error("[useThemeSettings] Error fetching:",r),_t;if(!e||e.length===0)return _t;const s=new Map(e.map(j=>[j.setting_key,j])),n=((d=s.get("matrix_primary"))==null?void 0:d.color_value)||_t.primary,i=((p=s.get("matrix_secondary"))==null?void 0:p.color_value)||_t.secondary,a=((f=s.get("matrix_success"))==null?void 0:f.color_value)||_t.success,l=((h=s.get("matrix_background"))==null?void 0:h.color_value)||_t.background,c=((m=s.get("matrix_spark_deal_color"))==null?void 0:m.color_value)||_t.sparkDealColor,u=((g=s.get("matrix_background_mode"))==null?void 0:g.color_value)||"dark";return{primary:n,secondary:i,success:a,background:l,backgroundMode:u,sparkDealColor:c,primaryHex:((_=s.get("matrix_primary"))==null?void 0:_.hex_preview)||zr(n),secondaryHex:((w=s.get("matrix_secondary"))==null?void 0:w.hex_preview)||zr(i),successHex:((k=s.get("matrix_success"))==null?void 0:k.hex_preview)||zr(a),backgroundHex:((b=s.get("matrix_background"))==null?void 0:b.hex_preview)||zr(l),sparkDealHex:((S=s.get("matrix_spark_deal_color"))==null?void 0:S.hex_preview)||zr(c)}},staleTime:60*1e3,gcTime:5*60*1e3})}const tn={enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500,bobCommentary:!1};function Mu(){const t=ar();return fs({queryKey:["spark-deals-settings"],queryFn:async()=>{if(!t)return tn;const{data:e,error:r}=await t.from("bob_settings").select("setting_key, setting_value").like("setting_key","spark_deals_%");if(r)return console.error("[useSparkDealsSettings] Error:",r),tn;if(!e||e.length===0)return tn;const s=new Map(e.map(n=>[n.setting_key,n.setting_value]));return{enabled:s.get("spark_deals_enabled")==="true",inRain:s.get("spark_deals_in_rain")==="true",rainFrequency:parseFloat(s.get("spark_deals_rain_frequency")||"0.15"),primingEnabled:s.get("spark_deals_priming_enabled")==="true",bannerEnabled:s.get("spark_deals_banner_enabled")==="true",delayMs:parseInt(s.get("spark_deals_delay_ms")||"2000",10),scrollSpeed:parseInt(s.get("spark_deals_scroll_speed")||"5000",10),maxPerSession:parseInt(s.get("spark_deals_max_per_session")||"3",10),minResearchTime:parseInt(s.get("spark_deals_min_research_time")||"1500",10),bobCommentary:s.get("spark_deals_bob_commentary")==="true"}},staleTime:60*1e3,gcTime:5*60*1e3})}function Ha(t=!0){const e=ar();return fs({queryKey:["spark-deals"],queryFn:async()=>{if(!e)return console.log("[useSparkDeals] No supabase client"),[];try{return console.error("[useSparkDeals] Missing VITE_SUPABASE_URL"),[]}catch(r){return console.error("[useSparkDeals] Error:",r),[]}},enabled:t,staleTime:5*60*1e3,gcTime:10*60*1e3})}function Wu(t){const e=[];return t.forEach(r=>{e.push(`$${r.price.toFixed(0)}`),r.brand&&e.push(r.brand.toUpperCase());const s=r.product_name.split(" ")[0];s&&s.length>2&&e.push(s.toUpperCase())}),e}const Ka=({deals:t,currentDealIndex:e,onDealChange:r,onDealClick:s,scrollSpeed:n,theme:i})=>{const[a,l]=y.useState(!1),[c,u]=y.useState(100),d=t[e],p=i.sparkDealHex||"#FF9500",f=i.backgroundMode!=="light";y.useEffect(()=>{if(!d)return;l(!0),u(100);const g=setTimeout(()=>{u(0)},50),_=setTimeout(()=>{u(-100)},n-500),w=setTimeout(()=>{const k=(e+1)%t.length;r(k),l(!1)},n);return()=>{clearTimeout(g),clearTimeout(_),clearTimeout(w)}},[e,d,n,t.length,r]);const h=y.useCallback(()=>{d&&s(d)},[d,s]);if(!d)return null;const m=d.original_price?Math.round((1-d.price/d.original_price)*100):null;return o.jsxs("div",{className:"absolute bottom-20 left-0 right-0 z-20 overflow-hidden pointer-events-none",style:{height:"72px"},children:[o.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-auto",style:{transform:`translateX(${c}%)`,transition:"transform 0.5s ease-out"},children:o.jsxs("button",{onClick:h,className:"group flex items-center gap-4 px-6 py-3 rounded-xl shadow-2xl transition-all hover:scale-105 active:scale-95",style:{background:f?"linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(17, 24, 39, 0.9) 100%)":"linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.98) 100%)",border:`2px solid ${p}`,boxShadow:`0 8px 32px -4px ${p}40, 0 4px 16px -2px rgba(0,0,0,0.2)`},children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center shrink-0",style:{background:`${p}20`},children:o.jsx("svg",{className:"w-5 h-5",fill:p,viewBox:"0 0 24 24",children:o.jsx("path",{d:"M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z"})})}),o.jsxs("div",{className:"flex flex-col items-start min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs font-bold uppercase tracking-wider",style:{color:p},children:"⚡ Spark Deal"}),m&&m>0&&o.jsxs("span",{className:"text-xs font-bold px-2 py-0.5 rounded-full",style:{background:p,color:f?"#000":"#fff"},children:[m,"% OFF"]})]}),o.jsxs("p",{className:"text-sm font-semibold truncate max-w-[200px]",style:{color:f?"#fff":"#111827"},children:[d.brand," ",d.product_name]})]}),o.jsxs("div",{className:"flex flex-col items-end shrink-0",children:[d.original_price&&d.original_price>d.price&&o.jsxs("span",{className:"text-xs line-through",style:{color:f?"#9ca3af":"#6b7280"},children:["$",d.original_price.toFixed(2)]}),o.jsxs("span",{className:"text-xl font-bold",style:{color:p},children:["$",d.price.toFixed(2)]})]}),o.jsx("svg",{className:"w-5 h-5 opacity-60 group-hover:opacity-100 group-hover:translate-x-1 transition-all",fill:"none",stroke:p,strokeWidth:2,viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.25 4.5l7.5 7.5-7.5 7.5"})})]})}),t.length>1&&o.jsx("div",{className:"absolute bottom-1 left-0 right-0 flex justify-center gap-1.5",children:t.map((g,_)=>o.jsx("div",{className:"w-1.5 h-1.5 rounded-full transition-all",style:{background:_===e?p:`${p}40`,transform:_===e?"scale(1.3)":"scale(1)"}},_))})]})},Bi=["*",":","=",">","<","+","-","|","•","○","●","◆","◇","0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","K","M","N","P","R","S","T","X","Z","#","@","$","%","&","~","^","/","\\","[","]","{","}"],$i=["BR","KE","OI","FI","LT","SP","RK","EN","GN","PT","CL","UT","AX","WH","EL","TI","RE","PA","DS","RO","TR","BT","HP","CV","XL"],qu=({phase:t,message:e,onComplete:r,onSparkDealClick:s,subliminalBrands:n=[]})=>{const i=y.useRef(null),a=y.useRef(),l=y.useRef([]),c=y.useRef(0),[u,d]=y.useState(0),[p,f]=y.useState(!1),[h,m]=y.useState(0),{data:g}=za(),{data:_}=Mu(),{data:w}=Ha(t!=="hidden"&&(_==null?void 0:_.enabled)),k=g||{primaryHex:"#0066CC",secondaryHex:"#004999",successHex:"#FF9500",backgroundHex:"#111827",sparkDealHex:"#FF9500",backgroundMode:"dark"},b=_||{enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500},S=w&&b.inRain?[...Wu(w),...n]:n,j=.08,C=y.useCallback(()=>S.length>0&&Math.random()<j?{char:S[Math.floor(Math.random()*S.length)],isSubliminal:!0}:Math.random()<.15?{char:$i[Math.floor(Math.random()*$i.length)],isSubliminal:!1}:{char:Bi[Math.floor(Math.random()*Bi.length)],isSubliminal:!1},[S]),F=y.useCallback((A,T)=>A.isSubliminal?k.sparkDealHex:t==="success"?k.successHex:Math.sin(T*2+A.x*.01)*.5+.5>.5?k.primaryHex:k.secondaryHex,[t,k]),O=y.useCallback((A,T)=>{const I=[],N=Math.floor(A/25);for(let z=0;z<N;z++){const{char:P,isSubliminal:te}=C();I.push({x:z*25+12,y:Math.random()*T,speed:1.5+Math.random()*3.5,char:P,isSubliminal:te,opacity:.2+Math.random()*.6,size:te?13:9+Math.random()*3,glowIntensity:te?.6:0,changeCounter:Math.floor(Math.random()*30)})}l.current=I},[C]);y.useEffect(()=>{if(t==="hidden"){a.current&&cancelAnimationFrame(a.current);return}const A=i.current;if(!A)return;const T=A.getContext("2d");if(!T)return;const I=()=>{A.width=A.offsetWidth*window.devicePixelRatio,A.height=A.offsetHeight*window.devicePixelRatio,T.scale(window.devicePixelRatio,window.devicePixelRatio),O(A.offsetWidth,A.offsetHeight)};I(),c.current=Date.now();const N=()=>{const z=A.offsetWidth,P=A.offsetHeight,K=(Date.now()-c.current)/1e3;if(T.clearRect(0,0,z,P),l.current.forEach($=>{const U=F($,K);if(T.font=`bold ${$.size}px monospace`,T.fillStyle=U,T.globalAlpha=$.opacity,$.isSubliminal&&$.glowIntensity>0?(T.shadowColor=k.sparkDealHex,T.shadowBlur=8*$.glowIntensity):T.shadowBlur=0,T.fillText($.char,$.x,$.y),$.y+=$.speed,$.changeCounter++,$.changeCounter>20+Math.random()*40){const{char:W,isSubliminal:q}=C();$.char=W,$.isSubliminal=q,$.size=q?13:9+Math.random()*3,$.glowIntensity=q?.6:0,$.changeCounter=0}if($.y>P+20){const{char:W,isSubliminal:q}=C();$.y=-20,$.char=W,$.isSubliminal=q,$.speed=1.5+Math.random()*3.5,$.opacity=.2+Math.random()*.6,$.size=q?13:9+Math.random()*3,$.glowIntensity=q?.6:0,$.changeCounter=0}}),T.globalAlpha=1,T.shadowBlur=0,t==="success"){const $=Math.max(0,1-K*2);$>0&&(T.fillStyle=`rgba(255, 149, 0, ${$*.3})`,T.fillRect(0,0,z,P)),K>.5&&r&&r()}a.current=requestAnimationFrame(N)};return N(),window.addEventListener("resize",I),()=>{a.current&&cancelAnimationFrame(a.current),window.removeEventListener("resize",I)}},[t,k,C,F,O,r]),y.useEffect(()=>{if(t==="hidden"||!w||w.length===0||!b.bannerEnabled){f(!1);return}if(h>=b.maxPerSession)return;const A=setTimeout(()=>{f(!0)},b.delayMs);return()=>clearTimeout(A)},[t,w,b,h]);const B=y.useCallback(A=>{d(A),m(T=>T+1)},[]),E=y.useCallback(A=>{console.log("[MatrixLoader] Spark deal clicked:",A.product_name),s==null||s(A)},[s]);return t==="hidden"?null:o.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center overflow-hidden pointer-events-none",style:{background:"transparent"},children:[o.jsx("canvas",{ref:i,className:"absolute inset-0 w-full h-full",style:{opacity:.85}}),p&&w&&w.length>0&&o.jsx(Ka,{deals:w.slice(0,b.maxPerSession),currentDealIndex:u,onDealChange:B,onDealClick:E,scrollSpeed:b.scrollSpeed,theme:k})]})},zu=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,products:i,servicePackages:a,highlightedPartType:l,highlightedProduct:c,onProductClick:u,onPackageSelect:d,isResearching:p,vehicle:f,onChangeVehicle:h,bobOffset:m=0,bobScale:g=100,bobHasArrived:_=!0,externalBobPosition:w,onBobPositionChange:k})=>{const b=typeof window<"u"&&window.self!==window.top,S=Fs(),j=Ln(),[C,F]=y.useState("center"),[O,B]=y.useState("hidden"),E=w??C,A=y.useCallback(K=>{F(K),k==null||k(K)},[k]),T=i.length>0||a.length>0,z=(()=>{switch(S){case"desktop":return 80*j.uiScale;case"tablet":return 90*j.uiScale;case"mobile":return 140;default:return 140}})()*g/100;y.useEffect(()=>{if(p&&O!=="loading"&&O!=="visible")B("loading"),E==="center"&&A("partial-left");else if(T&&O!=="visible")if(E==="center"){A("partial-left"),B("transitioning");const K=setTimeout(()=>{B("visible")},400);return()=>clearTimeout(K)}else B("visible");else!T&&!p&&O!=="hidden"&&(B("hidden"),A("center"))},[T,p,O,E,A]);const P=O!=="hidden",te=P&&T;return o.jsxs("div",{className:"absolute inset-0 overflow-hidden",style:{width:"100%",height:"100%",touchAction:"manipulation"},children:[r&&o.jsxs(o.Fragment,{children:[o.jsx("img",{src:r,alt:"Shop backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-center transition-all duration-500",style:{pointerEvents:"none",filter:te?"blur(8px)":"none",transform:te?"scale(1.02)":"scale(1)"}}),o.jsx("div",{className:"absolute inset-0 z-[1] transition-opacity duration-500 pointer-events-none",style:{background:"rgba(0, 0, 0, 0.15)",opacity:te?1:0}})]}),o.jsx(Ds,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:z,position:E,verticalOffset:m,hasArrived:_}),f&&!b&&o.jsx("div",{style:{position:"absolute",top:"8px",left:"8px",right:"8px",zIndex:20},children:o.jsxs("div",{style:{backgroundColor:"rgba(255, 255, 255, 0.9)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)",borderRadius:"8px",padding:"8px 12px",paddingTop:"calc(env(safe-area-inset-top, 4px) + 8px)",border:"1px solid #e5e7eb",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsxs("p",{style:{fontSize:"12px",fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[f.year," ",f.make," ",f.model]}),f.rego&&o.jsx("p",{style:{fontSize:"10px",color:"#6b7280"},children:f.rego})]}),h&&o.jsx("button",{onClick:h,style:{fontSize:"12px",color:"#2563eb",marginLeft:"8px",flexShrink:0,background:"none",border:"none",cursor:"pointer",minHeight:"unset",minWidth:"unset"},children:"Change"})]})}),o.jsx(Ls,{products:i,servicePackages:a,highlightedPartType:l,highlightedProduct:c,onProductClick:u,onPackageSelect:d,isResearching:p,visible:P,counterHeightPercent:n,hasVehicle:!!f})]})},Hu=6e4,Ku=({states:t,setAnimationState:e,manualMode:r})=>{const[s,n]=y.useState("page_load"),[i,a]=y.useState(!1),l=y.useRef(null),c=y.useCallback(E=>{const A=t.find(T=>T.chat_trigger===E&&T.is_active);return console.log(`[StateTransitions] Looking for trigger: "${E}" -> found:`,(A==null?void 0:A.state_key)||"none"),A},[t]),u=y.useCallback(()=>t.find(E=>E.chat_trigger==="processing_input"||E.state_key==="research"||E.state_key==="researching"||E.title.toLowerCase().includes("research")||E.title.toLowerCase().includes("thinking")),[t]),d=y.useCallback(()=>t.find(E=>E.chat_trigger==="streaming_response"||E.state_key==="talk"||E.state_key==="talking"||E.title.toLowerCase().includes("talk")),[t]),p=y.useCallback(()=>t.find(E=>E.chat_trigger==="awaiting_input"||E.state_key==="talk_pause"||E.state_key==="listening"||E.title.toLowerCase().includes("listen")||E.title.toLowerCase().includes("pause")),[t]),f=y.useCallback(()=>{const E=t.find(A=>A.chat_trigger==="response_complete"||A.state_key==="complete"||A.title.toLowerCase().includes("complete"));return E||t.find(A=>A.state_key==="idle"||A.title.toLowerCase().includes("idle"))},[t]),h=y.useCallback(()=>t.find(E=>E.chat_trigger==="idle"||E.state_key==="idle"||E.title.toLowerCase().includes("idle")),[t]),m=y.useCallback(E=>{const A=t.find(T=>T.state_key===E);return{speed:(A==null?void 0:A.animation_speed)||400,pauseDuration:(A==null?void 0:A.pause_duration)||0,loopCount:(A==null?void 0:A.loop_count)||0}},[t]),g=y.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null)},[]),_=y.useCallback(()=>{g(),!r&&(l.current=setTimeout(()=>{const E=h();E&&(n("idle"),e(E.state_key))},Hu))},[r,h,e,g]),w=y.useCallback(E=>{if(r)return;const A=c(E);A&&e(A.state_key)},[r,c,e]),k=y.useCallback(()=>{if(r)return;const E=p();E&&(n("awaiting_input"),e(E.state_key),_())},[r,p,e,_]),b=y.useCallback(()=>{i||r||(a(!0),n("page_load"),w("page_load"),setTimeout(()=>{k()},3e3))},[i,r,w,k]),S=y.useCallback(()=>{if(r)return;g(),n("processing_input");const E=u();console.log("[StateTransitions] User input - switching to RESEARCH:",E==null?void 0:E.state_key),E?e(E.state_key):w("processing_input")},[r,g,u,e,w]),j=y.useCallback(()=>{if(r)return;g(),n("streaming_response");const E=d();console.log("[StateTransitions] Speech started - switching to TALK:",E==null?void 0:E.state_key),E&&e(E.state_key)},[r,g,d,e]),C=y.useCallback(()=>{if(r)return;const E=f();console.log("[StateTransitions] Speech ended - switching to COMPLETE:",E==null?void 0:E.state_key),E&&e(E.state_key),setTimeout(()=>{r||k()},2e3)},[r,f,e,k]),F=y.useCallback(()=>{g(),n("streaming_response"),console.log("[StateTransitions] Stream started (API response)")},[g]),O=y.useCallback(()=>{n("response_complete"),console.log("[StateTransitions] Stream complete (API finished)");const E=f();E&&e(E.state_key),setTimeout(()=>{k()},2e3)},[f,e,k]),B=y.useCallback(()=>{if(r)return;n("showing_product"),console.log("[StateTransitions] Showing products");const E=t.find(A=>A.chat_trigger==="showing_product"||A.state_key==="showing_product");E&&e(E.state_key),setTimeout(()=>{k()},3e3)},[r,t,e,k]);return y.useEffect(()=>()=>g(),[g]),{chatStage:s,initialize:b,onUserInput:S,onSpeechStart:j,onSpeechEnd:C,onStreamStart:F,onStreamComplete:O,onShowingProduct:B,getStateSettings:m}},Vu=()=>{const t=ar();return{checkHealth:async()=>{if(!t)return{healthy:!1,reason:"No Supabase client available - ensure BobProvider is configured",stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};try{const{data:r,error:s}=await t.from("bob_looks").select("id, name, is_active").eq("is_active",!0).limit(1);if(s)return{healthy:!1,reason:`Database error fetching looks: ${s.message}`,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const n=r==null?void 0:r[0];if(!n)return{healthy:!1,reason:"No active look configured in bob_looks table",stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const{data:i,error:a}=await t.from("animation_states").select("state_key").eq("is_active",!0).eq("look_id",n.id);if(a)return{healthy:!1,reason:`Database error fetching states: ${a.message}`,activeLookId:n.id,activeLookName:n.name,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const l=(i==null?void 0:i.map(m=>m.state_key))||[],u=["idle","talking","listening"].filter(m=>{const g=[m,m.replace("ing",""),m+"ing"];return!l.some(_=>g.includes(_))}),{data:d,error:p}=await t.from("bob_animations").select("id").eq("is_active",!0).eq("look_id",n.id),f=p?0:(d==null?void 0:d.length)||0,h=l.length>=4&&f>0&&u.length===0;return{healthy:h,reason:h?void 0:`Missing critical states: ${u.join(", ")}`,activeLookId:n.id,activeLookName:n.name,stateCount:l.length,states:l,missingCritical:u,frameCount:f}}catch(r){return{healthy:!1,reason:`Unexpected error: ${r instanceof Error?r.message:"Unknown"}`,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0}}}}};console.log(`[BobWidget] Package loaded - v${pt}`);exports.BADGE_CONFIG=Ta;exports.BOB_VERSION=pt;exports.Bob=Mn;exports.BobCharacter=ja;exports.BobDebugOverlay=Ma;exports.BobProvider=$n;exports.BobStandalone=Lu;exports.BobSuggestions=Dn;exports.BobWidget=Pu;exports.CARFIX_COLORS=G;exports.ChatInterface=Aa;exports.ContainedChatDrawer=Da;exports.ContainedMobileBobLayout=Ua;exports.IMAGE_URLS=is;exports.MatrixProductLoader=qu;exports.MobileBobCharacter=Ds;exports.MobileBobLayout=Fa;exports.MobileBobLayoutCore=zu;exports.MobileChatDrawer=$a;exports.MobileProductColumn=Ls;exports.ProductBadge=Vr;exports.ProductTile=Ba;exports.QUALITY_TIER_CONFIG=As;exports.ServicePackageDetailView=La;exports.SparkDealBanner=Ka;exports.SwipeableBob=Uu;exports.TYPOGRAPHY=Ze;exports.formatNZD=Pt;exports.getBobVersion=Qa;exports.getDisplayPrice=Ca;exports.getFeatureFlag=qa;exports.isRotorProduct=Ra;exports.useBobAnalytics=va;exports.useBobAnalyticsConfig=pu;exports.useBobAnimation=Sa;exports.useBobAnimationData=ka;exports.useBobBackdrop=Ea;exports.useBobCallbacks=fu;exports.useBobChat=_a;exports.useBobContext=bt;exports.useBobHealthCheck=Vu;exports.useBobLayoutConfig=Fn;exports.useBobStateTransitions=Ku;exports.useBobSupabase=uu;exports.useBobSupabaseSafe=ar;exports.useHostApiConfig=hu;exports.useHostContext=du;exports.usePartnerConfig=Wa;exports.useReturningUser=xa;exports.useSparkDeals=Ha;exports.useSpeechRecognition=Un;exports.useSpeechSynthesis=wa;exports.useThemeSettings=za;