@gymmymac/bob-widget 1.1.0 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,47 +1,87 @@
1
- # @carfix/bob-widget
1
+ # @gymmymac/bob-widget
2
2
 
3
3
  AI-powered automotive parts assistant widget for integration into partner websites.
4
4
 
5
5
  ## Installation
6
6
 
7
7
  ```bash
8
- npm install @carfix/bob-widget
8
+ npm install @gymmymac/bob-widget
9
9
  ```
10
10
 
11
11
  ## Quick Start
12
12
 
13
13
  ```tsx
14
- import { BobProvider, Bob } from '@carfix/bob-widget';
14
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
15
+ import { BobProvider, Bob } from '@gymmymac/bob-widget';
16
+
17
+ const queryClient = new QueryClient();
15
18
 
16
19
  function App() {
17
20
  return (
18
- <BobProvider
19
- bobConfig={{
20
- supabaseUrl: 'https://gjoguxzstsihhxvdgpto.supabase.co',
21
- supabaseKey: 'eyJhbGciOiJI...', // Bob's public anon key
22
- }}
23
- hostApiConfig={{
24
- baseUrl: 'https://api.yoursite.com',
25
- apiKey: process.env.CARFIX_PARTNER_API_KEY!,
26
- partnerCode: 'YOUR_PARTNER_CODE',
27
- }}
28
- hostContext={{
29
- user: { id: user?.id, email: user?.email, name: user?.name },
30
- vehicle: { selectedVehicle: currentVehicle },
31
- }}
32
- callbacks={{
33
- onVehicleIdentified: (vehicle) => saveVehicle(vehicle),
34
- onPartsFound: (parts) => displayParts(parts),
35
- onAddToCart: (item) => addToCart(item),
36
- }}
37
- >
38
- <YourApp />
39
- <Bob variant="floating" />
40
- </BobProvider>
21
+ <QueryClientProvider client={queryClient}>
22
+ <BobProvider
23
+ bobConfig={{
24
+ supabaseUrl: 'https://gjoguxzstsihhxvdgpto.supabase.co',
25
+ supabaseKey: 'eyJhbGciOiJI...', // Bob's public anon key
26
+ }}
27
+ hostApiConfig={{
28
+ baseUrl: 'https://api.yoursite.com',
29
+ apiKey: process.env.CARFIX_PARTNER_API_KEY!,
30
+ partnerCode: 'YOUR_PARTNER_CODE',
31
+ }}
32
+ hostContext={{
33
+ user: { id: user?.id, email: user?.email, name: user?.name },
34
+ vehicle: { selectedVehicle: currentVehicle },
35
+ }}
36
+ callbacks={{
37
+ onVehicleIdentified: (vehicle) => saveVehicle(vehicle),
38
+ onPartsFound: (parts) => displayParts(parts),
39
+ onAddToCart: (item) => addToCart(item),
40
+ }}
41
+ >
42
+ <YourApp />
43
+ <Bob variant="floating" />
44
+ </BobProvider>
45
+ </QueryClientProvider>
41
46
  );
42
47
  }
43
48
  ```
44
49
 
50
+ ## Troubleshooting
51
+
52
+ ### "No QueryClient set" Error
53
+
54
+ If you see this error, ensure:
55
+
56
+ 1. **Install `@tanstack/react-query`** as a peer dependency:
57
+ ```bash
58
+ npm install @tanstack/react-query
59
+ ```
60
+
61
+ 2. **Wrap `BobProvider` inside `QueryClientProvider`**:
62
+ ```tsx
63
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
64
+
65
+ const queryClient = new QueryClient();
66
+
67
+ <QueryClientProvider client={queryClient}>
68
+ <BobProvider ...>
69
+ ...
70
+ </BobProvider>
71
+ </QueryClientProvider>
72
+ ```
73
+
74
+ ### Checking Bob's Version
75
+
76
+ You can ask Bob directly: "What version are you running?"
77
+
78
+ Or programmatically:
79
+ ```tsx
80
+ import { BOB_VERSION, getBobVersion } from '@gymmymac/bob-widget';
81
+
82
+ console.log(`Bob Widget Version: ${getBobVersion()}`); // e.g., "1.1.3"
83
+ ```
84
+
45
85
  ## Configuration
46
86
 
47
87
  ### BobProvider Props
@@ -118,7 +158,7 @@ import {
118
158
  useBobContext,
119
159
  useHostContext,
120
160
  useBobCallbacks,
121
- } from '@carfix/bob-widget';
161
+ } from '@gymmymac/bob-widget';
122
162
 
123
163
  function MyComponent() {
124
164
  const { hostContext, updateHostContext } = useBobContext();
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * AI-powered automotive parts assistant widget - Full immersive experience
5
5
  */
6
+ export { BOB_VERSION, getBobVersion } from './version';
6
7
  export { BobProvider, useBobContext, useBobSupabase, useHostContext, useHostApiConfig, useBobCallbacks, } from './BobProvider';
7
8
  export { Bob } from './components/Bob';
8
9
  export type { BobVariant } from './components/Bob';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Zt=e=>{throw TypeError(e)};var Bt=(e,t,s)=>t.has(e)||Zt("Cannot "+s);var c=(e,t,s)=>(Bt(e,t,"read from private field"),s?s.call(e):t.get(e)),Q=(e,t,s)=>t.has(e)?Zt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,s),F=(e,t,s,n)=>(Bt(e,t,"write to private field"),n?n.call(e,s):t.set(e,s),s),G=(e,t,s)=>(Bt(e,t,"access private method"),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("react"),$r=require("@supabase/supabase-js");function Wr(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const s in e)if(s!=="default"){const n=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,n.get?n:{enumerable:!0,get:()=>e[s]})}}return t.default=e,Object.freeze(t)}const ve=Wr(o);var Ft={exports:{}},vt={};/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react"),It=require("@supabase/supabase-js"),rt=require("@tanstack/react-query"),st="1.1.3",Nt=()=>st;var nt={exports:{}},Ke={};/**
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 er;function Vr(){if(er)return vt;er=1;var e=o,t=Symbol.for("react.element"),s=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,i=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,h={key:!0,ref:!0,__self:!0,__source:!0};function f(g,d,x){var p,u={},y=null,E=null;x!==void 0&&(y=""+x),d.key!==void 0&&(y=""+d.key),d.ref!==void 0&&(E=d.ref);for(p in d)n.call(d,p)&&!h.hasOwnProperty(p)&&(u[p]=d[p]);if(g&&g.defaultProps)for(p in d=g.defaultProps,d)u[p]===void 0&&(u[p]=d[p]);return{$$typeof:t,type:g,key:y,ref:E,props:u,_owner:i.current}}return vt.Fragment=s,vt.jsx=f,vt.jsxs=f,vt}var yt={};/**
9
+ */var it;function Ot(){if(it)return Ke;it=1;var s=r,l=Symbol.for("react.element"),c=Symbol.for("react.fragment"),p=Object.prototype.hasOwnProperty,f=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,E={key:!0,ref:!0,__self:!0,__source:!0};function v(C,g,y){var d,h={},b=null,R=null;y!==void 0&&(b=""+y),g.key!==void 0&&(b=""+g.key),g.ref!==void 0&&(R=g.ref);for(d in g)p.call(g,d)&&!E.hasOwnProperty(d)&&(h[d]=g[d]);if(C&&C.defaultProps)for(d in g=C.defaultProps,g)h[d]===void 0&&(h[d]=g[d]);return{$$typeof:l,type:C,key:b,ref:R,props:h,_owner:f.current}}return Ke.Fragment=c,Ke.jsx=v,Ke.jsxs=v,Ke}var ze={};/**
10
10
  * @license React
11
11
  * react-jsx-runtime.development.js
12
12
  *
@@ -14,20 +14,20 @@
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 tr;function Kr(){return tr||(tr=1,process.env.NODE_ENV!=="production"&&function(){var e=o,t=Symbol.for("react.element"),s=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),h=Symbol.for("react.profiler"),f=Symbol.for("react.provider"),g=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),x=Symbol.for("react.suspense"),p=Symbol.for("react.suspense_list"),u=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),E=Symbol.for("react.offscreen"),O=Symbol.iterator,P="@@iterator";function R(r){if(r===null||typeof r!="object")return null;var l=O&&r[O]||r[P];return typeof l=="function"?l:null}var N=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function b(r){{for(var l=arguments.length,w=new Array(l>1?l-1:0),I=1;I<l;I++)w[I-1]=arguments[I];S("error",r,w)}}function S(r,l,w){{var I=N.ReactDebugCurrentFrame,V=I.getStackAddendum();V!==""&&(l+="%s",w=w.concat([V]));var z=w.map(function(W){return String(W)});z.unshift("Warning: "+l),Function.prototype.apply.call(console[r],console,z)}}var _=!1,m=!1,v=!1,T=!1,j=!1,L;L=Symbol.for("react.module.reference");function k(r){return!!(typeof r=="string"||typeof r=="function"||r===n||r===h||j||r===i||r===x||r===p||T||r===E||_||m||v||typeof r=="object"&&r!==null&&(r.$$typeof===y||r.$$typeof===u||r.$$typeof===f||r.$$typeof===g||r.$$typeof===d||r.$$typeof===L||r.getModuleId!==void 0))}function C(r,l,w){var I=r.displayName;if(I)return I;var V=l.displayName||l.name||"";return V!==""?w+"("+V+")":w}function B(r){return r.displayName||"Context"}function D(r){if(r==null)return null;if(typeof r.tag=="number"&&b("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case n:return"Fragment";case s:return"Portal";case h:return"Profiler";case i:return"StrictMode";case x:return"Suspense";case p:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case g:var l=r;return B(l)+".Consumer";case f:var w=r;return B(w._context)+".Provider";case d:return C(r,r.render,"ForwardRef");case u:var I=r.displayName||null;return I!==null?I:D(r.type)||"Memo";case y:{var V=r,z=V._payload,W=V._init;try{return D(W(z))}catch{return null}}}return null}var M=Object.assign,Z=0,Ee,q,ne,oe,_e,Y,Be;function _t(){}_t.__reactDisabledLog=!0;function fe(){{if(Z===0){Ee=console.log,q=console.info,ne=console.warn,oe=console.error,_e=console.group,Y=console.groupCollapsed,Be=console.groupEnd;var r={configurable:!0,enumerable:!0,value:_t,writable:!0};Object.defineProperties(console,{info:r,log:r,warn:r,error:r,group:r,groupCollapsed:r,groupEnd:r})}Z++}}function Nt(){{if(Z--,Z===0){var r={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:M({},r,{value:Ee}),info:M({},r,{value:q}),warn:M({},r,{value:ne}),error:M({},r,{value:oe}),group:M({},r,{value:_e}),groupCollapsed:M({},r,{value:Y}),groupEnd:M({},r,{value:Be})})}Z<0&&b("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var Xe=N.ReactCurrentDispatcher,Ct;function ft(r,l,w){{if(Ct===void 0)try{throw Error()}catch(V){var I=V.stack.trim().match(/\n( *(at )?)/);Ct=I&&I[1]||""}return`
18
- `+Ct+r}}var Tt=!1,dt;{var Xt=typeof WeakMap=="function"?WeakMap:Map;dt=new Xt}function Pt(r,l){if(!r||Tt)return"";{var w=dt.get(r);if(w!==void 0)return w}var I;Tt=!0;var V=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var z;z=Xe.current,Xe.current=null,fe();try{if(l){var W=function(){throw Error()};if(Object.defineProperty(W.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(W,[])}catch(ie){I=ie}Reflect.construct(r,[],W)}else{try{W.call()}catch(ie){I=ie}r.call(W.prototype)}}else{try{throw Error()}catch(ie){I=ie}r()}}catch(ie){if(ie&&I&&typeof ie.stack=="string"){for(var A=ie.stack.split(`
19
- `),re=I.stack.split(`
20
- `),H=A.length-1,J=re.length-1;H>=1&&J>=0&&A[H]!==re[J];)J--;for(;H>=1&&J>=0;H--,J--)if(A[H]!==re[J]){if(H!==1||J!==1)do if(H--,J--,J<0||A[H]!==re[J]){var ue=`
21
- `+A[H].replace(" at new "," at ");return r.displayName&&ue.includes("<anonymous>")&&(ue=ue.replace("<anonymous>",r.displayName)),typeof r=="function"&&dt.set(r,ue),ue}while(H>=1&&J>=0);break}}}finally{Tt=!1,Xe.current=z,Nt(),Error.prepareStackTrace=V}var st=r?r.displayName||r.name:"",ze=st?ft(st):"";return typeof r=="function"&&dt.set(r,ze),ze}function jt(r,l,w){return Pt(r,!1)}function kt(r){var l=r.prototype;return!!(l&&l.isReactComponent)}function Fe(r,l,w){if(r==null)return"";if(typeof r=="function")return Pt(r,kt(r));if(typeof r=="string")return ft(r);switch(r){case x:return ft("Suspense");case p:return ft("SuspenseList")}if(typeof r=="object")switch(r.$$typeof){case d:return jt(r.render);case u:return Fe(r.type,l,w);case y:{var I=r,V=I._payload,z=I._init;try{return Fe(z(V),l,w)}catch{}}}return""}var Ce=Object.prototype.hasOwnProperty,U={},X=N.ReactDebugCurrentFrame;function te(r){if(r){var l=r._owner,w=Fe(r.type,r._source,l?l.type:null);X.setExtraStackFrame(w)}else X.setExtraStackFrame(null)}function Ze(r,l,w,I,V){{var z=Function.call.bind(Ce);for(var W in r)if(z(r,W)){var A=void 0;try{if(typeof r[W]!="function"){var re=Error((I||"React class")+": "+w+" type `"+W+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof r[W]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw re.name="Invariant Violation",re}A=r[W](l,W,I,w,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(H){A=H}A&&!(A instanceof Error)&&(te(V),b("%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).",I||"React class",w,W,typeof A),te(null)),A instanceof Error&&!(A.message in U)&&(U[A.message]=!0,te(V),b("Failed %s type: %s",w,A.message),te(null))}}}var et=Array.isArray;function Ae(r){return et(r)}function De(r){{var l=typeof Symbol=="function"&&Symbol.toStringTag,w=l&&r[Symbol.toStringTag]||r.constructor.name||"Object";return w}}function Ue(r){try{return $e(r),!1}catch{return!0}}function $e(r){return""+r}function Te(r){if(Ue(r))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",De(r)),$e(r)}var je=N.ReactCurrentOwner,de={key:!0,ref:!0,__self:!0,__source:!0},We,Ve;function ye(r){if(Ce.call(r,"ref")){var l=Object.getOwnPropertyDescriptor(r,"ref").get;if(l&&l.isReactWarning)return!1}return r.ref!==void 0}function he(r){if(Ce.call(r,"key")){var l=Object.getOwnPropertyDescriptor(r,"key").get;if(l&&l.isReactWarning)return!1}return r.key!==void 0}function Se(r,l){typeof r.ref=="string"&&je.current}function Ke(r,l){{var w=function(){We||(We=!0,b("%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)",l))};w.isReactWarning=!0,Object.defineProperty(r,"key",{get:w,configurable:!0})}}function pe(r,l){{var w=function(){Ve||(Ve=!0,b("%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)",l))};w.isReactWarning=!0,Object.defineProperty(r,"ref",{get:w,configurable:!0})}}var ce=function(r,l,w,I,V,z,W){var A={$$typeof:t,type:r,key:l,ref:w,props:W,_owner:z};return A._store={},Object.defineProperty(A._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(A,"_self",{configurable:!1,enumerable:!1,writable:!1,value:I}),Object.defineProperty(A,"_source",{configurable:!1,enumerable:!1,writable:!1,value:V}),Object.freeze&&(Object.freeze(A.props),Object.freeze(A)),A};function be(r,l,w,I,V){{var z,W={},A=null,re=null;w!==void 0&&(Te(w),A=""+w),he(l)&&(Te(l.key),A=""+l.key),ye(l)&&(re=l.ref,Se(l,V));for(z in l)Ce.call(l,z)&&!de.hasOwnProperty(z)&&(W[z]=l[z]);if(r&&r.defaultProps){var H=r.defaultProps;for(z in H)W[z]===void 0&&(W[z]=H[z])}if(A||re){var J=typeof r=="function"?r.displayName||r.name||"Unknown":r;A&&Ke(W,J),re&&pe(W,J)}return ce(r,A,re,V,I,je.current,W)}}var xe=N.ReactCurrentOwner,ht=N.ReactDebugCurrentFrame;function ke(r){if(r){var l=r._owner,w=Fe(r.type,r._source,l?l.type:null);ht.setExtraStackFrame(w)}else ht.setExtraStackFrame(null)}var tt;tt=!1;function le(r){return typeof r=="object"&&r!==null&&r.$$typeof===t}function Oe(){{if(xe.current){var r=D(xe.current.type);if(r)return`
17
+ */var ct;function Bt(){return ct||(ct=1,process.env.NODE_ENV!=="production"&&function(){var s=r,l=Symbol.for("react.element"),c=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),f=Symbol.for("react.strict_mode"),E=Symbol.for("react.profiler"),v=Symbol.for("react.provider"),C=Symbol.for("react.context"),g=Symbol.for("react.forward_ref"),y=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),b=Symbol.for("react.lazy"),R=Symbol.for("react.offscreen"),j=Symbol.iterator,L="@@iterator";function S(e){if(e===null||typeof e!="object")return null;var n=j&&e[j]||e[L];return typeof n=="function"?n:null}var N=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function a(e){{for(var n=arguments.length,u=new Array(n>1?n-1:0),T=1;T<n;T++)u[T-1]=arguments[T];m("error",e,u)}}function m(e,n,u){{var T=N.ReactDebugCurrentFrame,F=T.getStackAddendum();F!==""&&(n+="%s",u=u.concat([F]));var V=u.map(function(M){return String(M)});V.unshift("Warning: "+n),Function.prototype.apply.call(console[e],console,V)}}var x=!1,o=!1,i=!1,_=!1,k=!1,O;O=Symbol.for("react.module.reference");function B(e){return!!(typeof e=="string"||typeof e=="function"||e===p||e===E||k||e===f||e===y||e===d||_||e===R||x||o||i||typeof e=="object"&&e!==null&&(e.$$typeof===b||e.$$typeof===h||e.$$typeof===v||e.$$typeof===C||e.$$typeof===g||e.$$typeof===O||e.getModuleId!==void 0))}function w(e,n,u){var T=e.displayName;if(T)return T;var F=n.displayName||n.name||"";return F!==""?u+"("+F+")":u}function $(e){return e.displayName||"Context"}function D(e){if(e==null)return null;if(typeof e.tag=="number"&&a("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case p:return"Fragment";case c:return"Portal";case E:return"Profiler";case f:return"StrictMode";case y:return"Suspense";case d:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case C:var n=e;return $(n)+".Consumer";case v:var u=e;return $(u._context)+".Provider";case g:return w(e,e.render,"ForwardRef");case h:var T=e.displayName||null;return T!==null?T:D(e.type)||"Memo";case b:{var F=e,V=F._payload,M=F._init;try{return D(M(V))}catch{return null}}}return null}var I=Object.assign,Y=0,fe,W,X,Z,he,U,_e;function qe(){}qe.__reactDisabledLog=!0;function se(){{if(Y===0){fe=console.log,W=console.info,X=console.warn,Z=console.error,he=console.group,U=console.groupCollapsed,_e=console.groupEnd;var e={configurable:!0,enumerable:!0,value:qe,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}Y++}}function Qe(){{if(Y--,Y===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:I({},e,{value:fe}),info:I({},e,{value:W}),warn:I({},e,{value:X}),error:I({},e,{value:Z}),group:I({},e,{value:he}),groupCollapsed:I({},e,{value:U}),groupEnd:I({},e,{value:_e})})}Y<0&&a("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var Be=N.ReactCurrentDispatcher,Ye;function Me(e,n,u){{if(Ye===void 0)try{throw Error()}catch(F){var T=F.stack.trim().match(/\n( *(at )?)/);Ye=T&&T[1]||""}return`
18
+ `+Ye+e}}var He=!1,$e;{var ot=typeof WeakMap=="function"?WeakMap:Map;$e=new ot}function Ze(e,n){if(!e||He)return"";{var u=$e.get(e);if(u!==void 0)return u}var T;He=!0;var F=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var V;V=Be.current,Be.current=null,se();try{if(n){var M=function(){throw Error()};if(Object.defineProperty(M.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(M,[])}catch(Q){T=Q}Reflect.construct(e,[],M)}else{try{M.call()}catch(Q){T=Q}e.call(M.prototype)}}else{try{throw Error()}catch(Q){T=Q}e()}}catch(Q){if(Q&&T&&typeof Q.stack=="string"){for(var P=Q.stack.split(`
19
+ `),J=T.stack.split(`
20
+ `),K=P.length-1,z=J.length-1;K>=1&&z>=0&&P[K]!==J[z];)z--;for(;K>=1&&z>=0;K--,z--)if(P[K]!==J[z]){if(K!==1||z!==1)do if(K--,z--,z<0||P[K]!==J[z]){var ne=`
21
+ `+P[K].replace(" at new "," at ");return e.displayName&&ne.includes("<anonymous>")&&(ne=ne.replace("<anonymous>",e.displayName)),typeof e=="function"&&$e.set(e,ne),ne}while(K>=1&&z>=0);break}}}finally{He=!1,Be.current=V,Qe(),Error.prepareStackTrace=F}var Ae=e?e.displayName||e.name:"",Oe=Ae?Me(Ae):"";return typeof e=="function"&&$e.set(e,Oe),Oe}function Ge(e,n,u){return Ze(e,!1)}function Je(e){var n=e.prototype;return!!(n&&n.isReactComponent)}function Ee(e,n,u){if(e==null)return"";if(typeof e=="function")return Ze(e,Je(e));if(typeof e=="string")return Me(e);switch(e){case y:return Me("Suspense");case d:return Me("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case g:return Ge(e.render);case h:return Ee(e.type,n,u);case b:{var T=e,F=T._payload,V=T._init;try{return Ee(V(F),n,u)}catch{}}}return""}var be=Object.prototype.hasOwnProperty,A={},q=N.ReactDebugCurrentFrame;function G(e){if(e){var n=e._owner,u=Ee(e.type,e._source,n?n.type:null);q.setExtraStackFrame(u)}else q.setExtraStackFrame(null)}function ee(e,n,u,T,F){{var V=Function.call.bind(be);for(var M in e)if(V(e,M)){var P=void 0;try{if(typeof e[M]!="function"){var J=Error((T||"React class")+": "+u+" type `"+M+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[M]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw J.name="Invariant Violation",J}P=e[M](n,M,T,u,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(K){P=K}P&&!(P instanceof Error)&&(G(F),a("%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).",T||"React class",u,M,typeof P),G(null)),P instanceof Error&&!(P.message in A)&&(A[P.message]=!0,G(F),a("Failed %s type: %s",u,P.message),G(null))}}}var ge=Array.isArray;function Te(e){return ge(e)}function Ce(e){{var n=typeof Symbol=="function"&&Symbol.toStringTag,u=n&&e[Symbol.toStringTag]||e.constructor.name||"Object";return u}}function Re(e){try{return Se(e),!1}catch{return!0}}function Se(e){return""+e}function me(e){if(Re(e))return a("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Ce(e)),Se(e)}var ve=N.ReactCurrentOwner,ae={key:!0,ref:!0,__self:!0,__source:!0},je,ke;function ue(e){if(be.call(e,"ref")){var n=Object.getOwnPropertyDescriptor(e,"ref").get;if(n&&n.isReactWarning)return!1}return e.ref!==void 0}function oe(e){if(be.call(e,"key")){var n=Object.getOwnPropertyDescriptor(e,"key").get;if(n&&n.isReactWarning)return!1}return e.key!==void 0}function pe(e,n){typeof e.ref=="string"&&ve.current}function Ie(e,n){{var u=function(){je||(je=!0,a("%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)",n))};u.isReactWarning=!0,Object.defineProperty(e,"key",{get:u,configurable:!0})}}function ie(e,n){{var u=function(){ke||(ke=!0,a("%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)",n))};u.isReactWarning=!0,Object.defineProperty(e,"ref",{get:u,configurable:!0})}}var te=function(e,n,u,T,F,V,M){var P={$$typeof:l,type:e,key:n,ref:u,props:M,_owner:V};return P._store={},Object.defineProperty(P._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(P,"_self",{configurable:!1,enumerable:!1,writable:!1,value:T}),Object.defineProperty(P,"_source",{configurable:!1,enumerable:!1,writable:!1,value:F}),Object.freeze&&(Object.freeze(P.props),Object.freeze(P)),P};function ce(e,n,u,T,F){{var V,M={},P=null,J=null;u!==void 0&&(me(u),P=""+u),oe(n)&&(me(n.key),P=""+n.key),ue(n)&&(J=n.ref,pe(n,F));for(V in n)be.call(n,V)&&!ae.hasOwnProperty(V)&&(M[V]=n[V]);if(e&&e.defaultProps){var K=e.defaultProps;for(V in K)M[V]===void 0&&(M[V]=K[V])}if(P||J){var z=typeof e=="function"?e.displayName||e.name||"Unknown":e;P&&Ie(M,z),J&&ie(M,z)}return te(e,P,J,F,T,ve.current,M)}}var de=N.ReactCurrentOwner,De=N.ReactDebugCurrentFrame;function xe(e){if(e){var n=e._owner,u=Ee(e.type,e._source,n?n.type:null);De.setExtraStackFrame(u)}else De.setExtraStackFrame(null)}var Pe;Pe=!1;function re(e){return typeof e=="object"&&e!==null&&e.$$typeof===l}function ye(){{if(de.current){var e=D(de.current.type);if(e)return`
22
22
 
23
- Check the render method of \``+r+"`."}return""}}function pt(r){return""}var ge={};function Ot(r){{var l=Oe();if(!l){var w=typeof r=="string"?r:r.displayName||r.name;w&&(l=`
23
+ Check the render method of \``+e+"`."}return""}}function Fe(e){return""}var le={};function Xe(e){{var n=ye();if(!n){var u=typeof e=="string"?e:e.displayName||e.name;u&&(n=`
24
24
 
25
- Check the top-level render call using <`+w+">.")}return l}}function ee(r,l){{if(!r._store||r._store.validated||r.key!=null)return;r._store.validated=!0;var w=Ot(l);if(ge[w])return;ge[w]=!0;var I="";r&&r._owner&&r._owner!==xe.current&&(I=" It was passed a child from "+D(r._owner.type)+"."),ke(r),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',w,I),ke(null)}}function bt(r,l){{if(typeof r!="object")return;if(Ae(r))for(var w=0;w<r.length;w++){var I=r[w];le(I)&&ee(I,l)}else if(le(r))r._store&&(r._store.validated=!0);else if(r){var V=R(r);if(typeof V=="function"&&V!==r.entries)for(var z=V.call(r),W;!(W=z.next()).done;)le(W.value)&&ee(W.value,l)}}}function gt(r){{var l=r.type;if(l==null||typeof l=="string")return;var w;if(typeof l=="function")w=l.propTypes;else if(typeof l=="object"&&(l.$$typeof===d||l.$$typeof===u))w=l.propTypes;else return;if(w){var I=D(l);Ze(w,r.props,"prop",I,r)}else if(l.PropTypes!==void 0&&!tt){tt=!0;var V=D(l);b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",V||"Unknown")}typeof l.getDefaultProps=="function"&&!l.getDefaultProps.isReactClassApproved&&b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function qe(r){{for(var l=Object.keys(r.props),w=0;w<l.length;w++){var I=l[w];if(I!=="children"&&I!=="key"){ke(r),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",I),ke(null);break}}r.ref!==null&&(ke(r),b("Invalid attribute `ref` supplied to `React.Fragment`."),ke(null))}}var rt={};function mt(r,l,w,I,V,z){{var W=k(r);if(!W){var A="";(r===void 0||typeof r=="object"&&r!==null&&Object.keys(r).length===0)&&(A+=" 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 re=pt();re?A+=re:A+=Oe();var H;r===null?H="null":Ae(r)?H="array":r!==void 0&&r.$$typeof===t?(H="<"+(D(r.type)||"Unknown")+" />",A=" Did you accidentally export a JSX literal instead of a component?"):H=typeof r,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",H,A)}var J=be(r,l,w,V,z);if(J==null)return J;if(W){var ue=l.children;if(ue!==void 0)if(I)if(Ae(ue)){for(var st=0;st<ue.length;st++)bt(ue[st],r);Object.freeze&&Object.freeze(ue)}else b("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 bt(ue,r)}if(Ce.call(l,"key")){var ze=D(r),ie=Object.keys(l).filter(function(Ur){return Ur!=="key"}),Mt=ie.length>0?"{key: someKey, "+ie.join(": ..., ")+": ...}":"{key: someKey}";if(!rt[ze+Mt]){var Dr=ie.length>0?"{"+ie.join(": ..., ")+": ...}":"{}";b(`A props object containing a "key" prop is being spread into JSX:
25
+ Check the top-level render call using <`+u+">.")}return n}}function H(e,n){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var u=Xe(n);if(le[u])return;le[u]=!0;var T="";e&&e._owner&&e._owner!==de.current&&(T=" It was passed a child from "+D(e._owner.type)+"."),xe(e),a('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',u,T),xe(null)}}function We(e,n){{if(typeof e!="object")return;if(Te(e))for(var u=0;u<e.length;u++){var T=e[u];re(T)&&H(T,n)}else if(re(e))e._store&&(e._store.validated=!0);else if(e){var F=S(e);if(typeof F=="function"&&F!==e.entries)for(var V=F.call(e),M;!(M=V.next()).done;)re(M.value)&&H(M.value,n)}}}function Ve(e){{var n=e.type;if(n==null||typeof n=="string")return;var u;if(typeof n=="function")u=n.propTypes;else if(typeof n=="object"&&(n.$$typeof===g||n.$$typeof===h))u=n.propTypes;else return;if(u){var T=D(n);ee(u,e.props,"prop",T,e)}else if(n.PropTypes!==void 0&&!Pe){Pe=!0;var F=D(n);a("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",F||"Unknown")}typeof n.getDefaultProps=="function"&&!n.getDefaultProps.isReactClassApproved&&a("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Ne(e){{for(var n=Object.keys(e.props),u=0;u<n.length;u++){var T=n[u];if(T!=="children"&&T!=="key"){xe(e),a("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",T),xe(null);break}}e.ref!==null&&(xe(e),a("Invalid attribute `ref` supplied to `React.Fragment`."),xe(null))}}var Le={};function Ue(e,n,u,T,F,V){{var M=B(e);if(!M){var P="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(P+=" 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 J=Fe();J?P+=J:P+=ye();var K;e===null?K="null":Te(e)?K="array":e!==void 0&&e.$$typeof===l?(K="<"+(D(e.type)||"Unknown")+" />",P=" Did you accidentally export a JSX literal instead of a component?"):K=typeof e,a("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",K,P)}var z=ce(e,n,u,F,V);if(z==null)return z;if(M){var ne=n.children;if(ne!==void 0)if(T)if(Te(ne)){for(var Ae=0;Ae<ne.length;Ae++)We(ne[Ae],e);Object.freeze&&Object.freeze(ne)}else a("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 We(ne,e)}if(be.call(n,"key")){var Oe=D(e),Q=Object.keys(n).filter(function(kt){return kt!=="key"}),tt=Q.length>0?"{key: someKey, "+Q.join(": ..., ")+": ...}":"{key: someKey}";if(!Le[Oe+tt]){var jt=Q.length>0?"{"+Q.join(": ..., ")+": ...}":"{}";a(`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} />`,Mt,ze,Dr,ze),rt[ze+Mt]=!0}}return r===n?qe(J):gt(J),J}}function Lt(r,l,w){return mt(r,l,w,!0)}function Br(r,l,w){return mt(r,l,w,!1)}var Fr=Br,Ar=Lt;yt.Fragment=n,yt.jsx=Fr,yt.jsxs=Ar}()),yt}process.env.NODE_ENV==="production"?Ft.exports=Vr():Ft.exports=Kr();var a=Ft.exports;const vr=o.createContext(null);function qr({children:e,bobConfig:t,hostApiConfig:s,hostContext:n={},callbacks:i={}}){const h=o.useMemo(()=>$r.createClient(t.supabaseUrl,t.supabaseKey),[t.supabaseUrl,t.supabaseKey]),[f,g]=o.useState(n);o.useEffect(()=>{g(n)},[n]);const d=o.useCallback(p=>{g(u=>({...u,...p}))},[]),x=o.useMemo(()=>({bobSupabase:h,bobConfig:t,hostApiConfig:s,hostContext:f,callbacks:i,updateHostContext:d}),[h,t,s,f,i,d]);return a.jsx(vr.Provider,{value:x,children:e})}function Me(){const e=o.useContext(vr);if(!e)throw new Error("useBobContext must be used within a BobProvider");return e}function Yt(){const{bobSupabase:e}=Me();return e}function zr(){const{hostContext:e}=Me();return e}function Qr(){const{hostApiConfig:e}=Me();return e}function Hr(){const{callbacks:e}=Me();return e}const rr=5e3,yr=({onStart:e,onEnd:t,onFailed:s}={})=>{const{bobConfig:n}=Me(),[i,h]=o.useState(!1),f=o.useRef(null),g=o.useRef(null),d=o.useRef(!1),x=o.useRef(e),p=o.useRef(t),u=o.useRef(s);o.useEffect(()=>{x.current=e,p.current=t,u.current=s},[e,t,s]);const y=o.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null)},[]),E=o.useCallback(()=>{var b;d.current||(d.current=!0,console.log("[BobWidget TTS] Fallback: triggering onStart without audio"),(b=x.current)==null||b.call(x))},[]),O=o.useCallback(async b=>{var S,_,m,v;if(b.trim()){d.current=!1,y(),f.current&&(f.current.pause(),f.current=null),g.current=setTimeout(()=>{var T,j;console.warn("[BobWidget TTS] Timeout after 5s - triggering fallback callbacks"),E(),h(!1),(T=p.current)==null||T.call(p),(j=u.current)==null||j.call(u),f.current=null},rr);try{const T=new AbortController,j=setTimeout(()=>T.abort(),rr-1e3),L=await fetch(`${n.supabaseUrl}/functions/v1/bob-tts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.supabaseKey}`},body:JSON.stringify({text:b}),signal:T.signal});if(clearTimeout(j),!L.ok){const B=await L.json().catch(()=>({}));throw console.error("[BobWidget TTS] Request failed:",B),new Error("TTS request failed")}const{audioContent:k}=await L.json(),C=new Audio(`data:audio/mp3;base64,${k}`);f.current=C,C.onplay=()=>{var B;y(),d.current||(d.current=!0,h(!0),console.log("[BobWidget TTS] Audio playing, triggering onStart"),(B=x.current)==null||B.call(x))},C.onended=()=>{var B;y(),h(!1),(B=p.current)==null||B.call(p),f.current=null},C.onerror=B=>{var D,M;y(),console.warn("[BobWidget TTS] Audio playback error:",B),E(),h(!1),(D=p.current)==null||D.call(p),(M=u.current)==null||M.call(u),f.current=null};try{await C.play()}catch(B){console.warn("[BobWidget TTS] Audio play() failed (likely autoplay policy):",B),y(),E(),h(!1),(S=p.current)==null||S.call(p),(_=u.current)==null||_.call(u),f.current=null}}catch(T){y(),console.error("[BobWidget TTS] Speech synthesis error:",T),E(),h(!1),(m=p.current)==null||m.call(p),(v=u.current)==null||v.call(u)}}},[n.supabaseUrl,n.supabaseKey,y,E]),P=o.useCallback(()=>{y(),f.current&&(f.current.pause(),f.current=null),h(!1)},[y]),R=o.useCallback(()=>{var b;(b=f.current)==null||b.pause()},[]),N=o.useCallback(()=>{var b;(b=f.current)==null||b.play()},[]);return o.useEffect(()=>()=>{y(),f.current&&(f.current.pause(),f.current=null)},[y]),{speak:O,stop:P,pause:R,resume:N,isSpeaking:i,isSupported:!0}},sr=["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"],Yr=["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"],xr=({setAnimationState:e,manualMode:t=!1,talkingState:s="talk",thinkingState:n="research",completeState:i="complete",idleState:h="idle",listenState:f="talk_pause",onStreamStart:g,onStreamComplete:d,onShowingProduct:x,onResearchStart:p,onReadyToSpeak:u,onHighlightPart:y,onHighlightProduct:E,onNoPartsFound:O,onAutoFetchComplete:P})=>{var jt,kt,Fe,Ce;const{bobConfig:R,hostApiConfig:N,hostContext:b,callbacks:S}=Me(),[_,m]=o.useState([]),[v,T]=o.useState(""),[j,L]=o.useState(!1),[k,C]=o.useState(!1),[B,D]=o.useState(null),M=o.useRef(null),Z=o.useRef(!1),Ee=o.useRef(!1),q=o.useRef(""),ne=o.useRef(!1),oe=o.useRef(null),_e=()=>{oe.current&&(clearTimeout(oe.current),oe.current=null)},{speak:Y,stop:Be,isSpeaking:_t}=yr({onStart:()=>{_e(),ne.current=!0,console.log("[BobWidget] Speech started - revealing products"),u==null||u(),t||fe(s)},onEnd:()=>{_e();const U=sr.some(X=>q.current.toLowerCase().includes(X.toLowerCase()));t||(U&&x?x():d?d():(fe(i),setTimeout(()=>fe(f),3e3)))},onFailed:()=>{console.warn("[BobWidget] Speech synthesis failed - fallback triggered")}});o.useEffect(()=>{var U;(U=M.current)==null||U.scrollIntoView({behavior:"smooth"})},[_]),o.useEffect(()=>{var X,te;const U=(X=b.vehicle)==null?void 0:X.selectedVehicle;U&&!B&&(console.log("[BobWidget] Setting vehicle from host context:",U),D(U),(te=S.onVehicleIdentified)==null||te.call(S,U))},[(jt=b.vehicle)==null?void 0:jt.selectedVehicle]),o.useEffect(()=>{var U;if(_.length===0&&!Ee.current){const X=(U=b.vehicle)==null?void 0:U.selectedVehicle;if(X){Ee.current=!0;const te=`${X.year} ${X.make} ${X.model}`;m([{role:"assistant",content:`G'day! Saw you've got the ${te} - choice wagon! What can I help you find for it today?`}])}else m([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])}},[(kt=b.vehicle)==null?void 0:kt.selectedVehicle,_.length]),o.useEffect(()=>{var De,Ue;const U=(De=b.vehicle)==null?void 0:De.selectedVehicle;if(!U||Z.current)return;const X=U.vehicle_id??U.id,te=Number.parseInt(String(X),10);if(!Number.isFinite(te)){console.warn("[BobWidget] Vehicle has invalid vehicle_id, cannot auto-fetch:",U);return}Z.current=!0;const Ze={...U,vehicle_id:String(te)},et=(Ue=b.user)==null?void 0:Ue.email;(async()=>{var Te,je;const $e=`${R.supabaseUrl}/functions/v1/bob-chat`;try{const de=await fetch($e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${R.supabaseKey}`},body:JSON.stringify({messages:[],vehicleContext:Ze,customerEmail:et,autoFetchParts:!0,hostConfig:N,hostContext:b})});if(!de.ok||!de.body){console.error("[BobWidget] Auto-fetch failed:",de.status);return}const We=de.body.getReader(),Ve=new TextDecoder;let ye="";for(;;){const{done:he,value:Se}=await We.read();if(he)break;ye+=Ve.decode(Se,{stream:!0});let Ke;for(;(Ke=ye.indexOf(`
31
- `))!==-1;){let pe=ye.slice(0,Ke);if(ye=ye.slice(Ke+1),pe.endsWith("\r")&&(pe=pe.slice(0,-1)),pe.startsWith(":")||pe.trim()===""||!pe.startsWith("data: "))continue;const ce=pe.slice(6).trim();if(ce==="[DONE]")break;try{const be=JSON.parse(ce);be.type==="service_packages_found"&&be.packages&&((Te=S.onServicePackagesFound)==null||Te.call(S,be.packages)),be.type==="parts_found"&&be.parts&&((je=S.onPartsFound)==null||je.call(S,be.parts))}catch{}}}P==null||P()}catch(de){console.error("[BobWidget] Auto-fetch error:",de)}})()},[(Fe=b.vehicle)==null?void 0:Fe.selectedVehicle,(Ce=b.user)==null?void 0:Ce.email]);const fe=U=>{try{e(U)}catch{console.warn(`[BobWidget] State "${U}" not available`)}},Nt=async U=>{var Ze,et,Ae,De,Ue,$e,Te,je,de,We,Ve,ye;const X=`${R.supabaseUrl}/functions/v1/bob-chat`,te=(Ze=b.user)==null?void 0:Ze.email;try{const he={messages:[..._,U],hostConfig:N,hostContext:b};B&&(he.vehicleContext=B),te&&(he.customerEmail=te);const Se=await fetch(X,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${R.supabaseKey}`},body:JSON.stringify(he)});if(!Se.ok){if(Se.status===429){(et=S.onError)==null||et.call(S,new Error("Rate limit exceeded"));return}if(Se.status===402){(Ae=S.onError)==null||Ae.call(S,new Error("Payment required"));return}throw new Error("Failed to start stream")}if(!Se.body)throw new Error("No response body");const Ke=Se.body.getReader(),pe=new TextDecoder;let ce="",be=!1,xe="";for(;!be;){const{done:le,value:Oe}=await Ke.read();if(le)break;ce+=pe.decode(Oe,{stream:!0});let pt;for(;(pt=ce.indexOf(`
32
- `))!==-1;){let ge=ce.slice(0,pt);if(ce=ce.slice(pt+1),ge.endsWith("\r")&&(ge=ge.slice(0,-1)),ge.startsWith(":")||ge.trim()===""||!ge.startsWith("data: "))continue;const Ot=ge.slice(6).trim();if(Ot==="[DONE]"){be=!0;break}try{const ee=JSON.parse(Ot);if(ee.type==="vehicle_identified"&&ee.vehicle){D(ee.vehicle),(De=S.onVehicleIdentified)==null||De.call(S,ee.vehicle);continue}if(ee.type==="service_packages_found"&&ee.packages){(Ue=S.onServicePackagesFound)==null||Ue.call(S,ee.packages);continue}if(ee.type==="parts_found"&&ee.parts){($e=S.onPartsFound)==null||$e.call(S,ee.parts);continue}if(ee.type==="no_parts_found"){O==null||O();continue}if(ee.type==="cart_updated"&&ee.items){(Te=S.onCartUpdated)==null||Te.call(S,ee.items);continue}const bt=(We=(de=(je=ee.choices)==null?void 0:je[0])==null?void 0:de.delta)==null?void 0:We.content;if(bt){xe+=bt;const gt=xe.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");m(qe=>{const rt=qe[qe.length-1];return(rt==null?void 0:rt.role)==="assistant"?qe.map((mt,Lt)=>Lt===qe.length-1?{...mt,content:gt}:mt):[...qe,{role:"assistant",content:gt}]}),(Ve=S.onBobMessage)==null||Ve.call(S,gt)}}catch{ce=ge+`
33
- `+ce;break}}}q.current=xe.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");const ht=sr.some(le=>xe.toLowerCase().includes(le.toLowerCase())),ke=xe.toLowerCase();for(const le of Yr)if(ke.includes(le.toLowerCase())){const Oe=le.replace(/s\s*$/i,"").toUpperCase();y==null||y(Oe);break}const tt=xe.match(/(?:go with|recommend|suggest|grab|try)\s+(?:the\s+)?(\w+)\s+(?:at|for)\s+\$(\d+(?:\.\d{2})?)/i);if(tt){const[,le,Oe]=tt;E==null||E({brand:le,price:parseFloat(Oe)})}!k&&q.current.trim()?(ne.current=!1,_e(),Y(q.current),oe.current=setTimeout(()=>{ne.current||(console.warn("[BobWidget] Speech fallback after 2s"),u==null||u(),t||(ht&&x?x():d?d():(fe(i),setTimeout(()=>fe(f),3e3))))},2e3)):(u==null||u(),t||(ht&&x?x():d?d():(fe(i),setTimeout(()=>fe(f),3e3))))}catch(he){console.error("[BobWidget] Chat error:",he),(ye=S.onError)==null||ye.call(S,he instanceof Error?he:new Error("Unknown error")),t||fe(h)}},Xe=async()=>{if(!v.trim()||j)return;Be();const U={role:"user",content:v};m(X=>[...X,U]),T(""),L(!0),p==null||p(),t||fe(n),await Nt(U),L(!1)};return{messages:_,input:v,setInput:T,isLoading:j,handleSend:Xe,handleKeyPress:U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),Xe())},handleInputFocus:()=>{},handleInputBlur:()=>{},chatEndRef:M,clearMessages:()=>{m([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])},isMuted:k,toggleMute:()=>{C(U=>!U),k||Be()},isSpeaking:_t,identifiedVehicle:B,clearVehicle:()=>{D(null)}}};var Jt=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Jr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},we,Qe,pr,Gr=(pr=class{constructor(){Q(this,we,Jr);Q(this,Qe,!1)}setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&c(this,Qe)&&e!==c(this,we)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:c(this,we),provider:e}),F(this,we,e),process.env.NODE_ENV!=="production"&&F(this,Qe,!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&F(this,Qe,!0),c(this,we).setTimeout(e,t)}clearTimeout(e){c(this,we).clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&F(this,Qe,!0),c(this,we).setInterval(e,t)}clearInterval(e){c(this,we).clearInterval(e)}},we=new WeakMap,Qe=new WeakMap,pr),It=new Gr;function Xr(e){setTimeout(e,0)}var Et=typeof window>"u"||"Deno"in globalThis;function At(){}function nr(e){return typeof e=="number"&&e>=0&&e!==1/0}function Zr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function wt(e,t){return typeof e=="function"?e(t):e}function me(e,t){return typeof e=="function"?e(t):e}var es=Object.prototype.hasOwnProperty;function Dt(e,t){if(e===t)return e;const s=ir(e)&&ir(t);if(!s&&!(ar(e)&&ar(t)))return t;const i=(s?e:Object.keys(e)).length,h=s?t:Object.keys(t),f=h.length,g=s?new Array(f):{};let d=0;for(let x=0;x<f;x++){const p=s?x:h[x],u=e[p],y=t[p];if(u===y){g[p]=u,(s?x<i:es.call(e,p))&&d++;continue}if(u===null||y===null||typeof u!="object"||typeof y!="object"){g[p]=y;continue}const E=Dt(u,y);g[p]=E,E===u&&d++}return i===f&&d===i?e:g}function Ut(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}function ir(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ar(e){if(!or(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!or(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function or(e){return Object.prototype.toString.call(e)==="[object Object]"}function cr(e,t,s){if(typeof s.structuralSharing=="function")return s.structuralSharing(e,t);if(s.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return Dt(e,t)}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 Dt(e,t)}return t}function ts(e,t){return typeof e=="function"?e(...t):!!e}var He,Ie,nt,br,rs=(br=class extends Jt{constructor(){super();Q(this,He);Q(this,Ie);Q(this,nt);F(this,nt,t=>{if(!Et&&window.addEventListener){const s=()=>t();return window.addEventListener("visibilitychange",s,!1),()=>{window.removeEventListener("visibilitychange",s)}}})}onSubscribe(){c(this,Ie)||this.setEventListener(c(this,nt))}onUnsubscribe(){var t;this.hasListeners()||((t=c(this,Ie))==null||t.call(this),F(this,Ie,void 0))}setEventListener(t){var s;F(this,nt,t),(s=c(this,Ie))==null||s.call(this),F(this,Ie,t(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(t){c(this,He)!==t&&(F(this,He,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(s=>{s(t)})}isFocused(){var t;return typeof c(this,He)=="boolean"?c(this,He):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},He=new WeakMap,Ie=new WeakMap,nt=new WeakMap,br),ss=new rs;function lr(){let e,t;const s=new Promise((i,h)=>{e=i,t=h});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}),e(i)},s.reject=i=>{n({status:"rejected",reason:i}),t(i)},s}var ns=Xr;function is(){let e=[],t=0,s=g=>{g()},n=g=>{g()},i=ns;const h=g=>{t?e.push(g):i(()=>{s(g)})},f=()=>{const g=e;e=[],g.length&&i(()=>{n(()=>{g.forEach(d=>{s(d)})})})};return{batch:g=>{let d;t++;try{d=g()}finally{t--,t||f()}return d},batchCalls:g=>(...d)=>{h(()=>{g(...d)})},schedule:h,setNotifyFunction:g=>{s=g},setBatchNotifyFunction:g=>{n=g},setScheduler:g=>{i=g}}}var wr=is(),it,Ne,at,gr,as=(gr=class extends Jt{constructor(){super();Q(this,it,!0);Q(this,Ne);Q(this,at);F(this,at,t=>{if(!Et&&window.addEventListener){const s=()=>t(!0),n=()=>t(!1);return window.addEventListener("online",s,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",s),window.removeEventListener("offline",n)}}})}onSubscribe(){c(this,Ne)||this.setEventListener(c(this,at))}onUnsubscribe(){var t;this.hasListeners()||((t=c(this,Ne))==null||t.call(this),F(this,Ne,void 0))}setEventListener(t){var s;F(this,at,t),(s=c(this,Ne))==null||s.call(this),F(this,Ne,t(this.setOnline.bind(this)))}setOnline(t){c(this,it)!==t&&(F(this,it,t),this.listeners.forEach(n=>{n(t)}))}isOnline(){return c(this,it)}},it=new WeakMap,Ne=new WeakMap,at=new WeakMap,gr),os=new as;function cs(e){return(e??"online")==="online"?os.isOnline():!0}function ls(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:cs(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}var ae,$,St,se,Ye,ot,Re,Pe,Rt,ct,lt,Je,Ge,Le,ut,K,xt,$t,Wt,Vt,Kt,qt,zt,Qt,Er,mr,us=(mr=class extends Jt{constructor(t,s){super();Q(this,K);Q(this,ae);Q(this,$);Q(this,St);Q(this,se);Q(this,Ye);Q(this,ot);Q(this,Re);Q(this,Pe);Q(this,Rt);Q(this,ct);Q(this,lt);Q(this,Je);Q(this,Ge);Q(this,Le);Q(this,ut,new Set);this.options=s,F(this,ae,t),F(this,Pe,null),F(this,Re,lr()),this.bindMethods(),this.setOptions(s)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(c(this,$).addObserver(this),ur(c(this,$),this.options)?G(this,K,xt).call(this):this.updateResult(),G(this,K,Kt).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ht(c(this,$),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ht(c(this,$),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,G(this,K,qt).call(this),G(this,K,zt).call(this),c(this,$).removeObserver(this)}setOptions(t){const s=this.options,n=c(this,$);if(this.options=c(this,ae).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof me(this.options.enabled,c(this,$))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");G(this,K,Qt).call(this),c(this,$).setOptions(this.options),s._defaulted&&!Ut(this.options,s)&&c(this,ae).getQueryCache().notify({type:"observerOptionsUpdated",query:c(this,$),observer:this});const i=this.hasListeners();i&&fr(c(this,$),n,this.options,s)&&G(this,K,xt).call(this),this.updateResult(),i&&(c(this,$)!==n||me(this.options.enabled,c(this,$))!==me(s.enabled,c(this,$))||wt(this.options.staleTime,c(this,$))!==wt(s.staleTime,c(this,$)))&&G(this,K,$t).call(this);const h=G(this,K,Wt).call(this);i&&(c(this,$)!==n||me(this.options.enabled,c(this,$))!==me(s.enabled,c(this,$))||h!==c(this,Le))&&G(this,K,Vt).call(this,h)}getOptimisticResult(t){const s=c(this,ae).getQueryCache().build(c(this,ae),t),n=this.createResult(s,t);return ds(this,n)&&(F(this,se,n),F(this,ot,this.options),F(this,Ye,c(this,$).state)),n}getCurrentResult(){return c(this,se)}trackResult(t,s){return new Proxy(t,{get:(n,i)=>(this.trackProp(i),s==null||s(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&c(this,Re).status==="pending"&&c(this,Re).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,i))})}trackProp(t){c(this,ut).add(t)}getCurrentQuery(){return c(this,$)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const s=c(this,ae).defaultQueryOptions(t),n=c(this,ae).getQueryCache().build(c(this,ae),s);return n.fetch().then(()=>this.createResult(n,s))}fetch(t){return G(this,K,xt).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),c(this,se)))}createResult(t,s){var L;const n=c(this,$),i=this.options,h=c(this,se),f=c(this,Ye),g=c(this,ot),x=t!==n?t.state:c(this,St),{state:p}=t;let u={...p},y=!1,E;if(s._optimisticResults){const k=this.hasListeners(),C=!k&&ur(t,s),B=k&&fr(t,n,s,i);(C||B)&&(u={...u,...ls(p.data,t.options)}),s._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:O,errorUpdatedAt:P,status:R}=u;E=u.data;let N=!1;if(s.placeholderData!==void 0&&E===void 0&&R==="pending"){let k;h!=null&&h.isPlaceholderData&&s.placeholderData===(g==null?void 0:g.placeholderData)?(k=h.data,N=!0):k=typeof s.placeholderData=="function"?s.placeholderData((L=c(this,lt))==null?void 0:L.state.data,c(this,lt)):s.placeholderData,k!==void 0&&(R="success",E=cr(h==null?void 0:h.data,k,s),y=!0)}if(s.select&&E!==void 0&&!N)if(h&&E===(f==null?void 0:f.data)&&s.select===c(this,Rt))E=c(this,ct);else try{F(this,Rt,s.select),E=s.select(E),E=cr(h==null?void 0:h.data,E,s),F(this,ct,E),F(this,Pe,null)}catch(k){F(this,Pe,k)}c(this,Pe)&&(O=c(this,Pe),E=c(this,ct),P=Date.now(),R="error");const b=u.fetchStatus==="fetching",S=R==="pending",_=R==="error",m=S&&b,v=E!==void 0,j={status:R,fetchStatus:u.fetchStatus,isPending:S,isSuccess:R==="success",isError:_,isInitialLoading:m,isLoading:m,data:E,dataUpdatedAt:u.dataUpdatedAt,error:O,errorUpdatedAt:P,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>x.dataUpdateCount||u.errorUpdateCount>x.errorUpdateCount,isFetching:b,isRefetching:b&&!S,isLoadingError:_&&!v,isPaused:u.fetchStatus==="paused",isPlaceholderData:y,isRefetchError:_&&v,isStale:Gt(t,s),refetch:this.refetch,promise:c(this,Re),isEnabled:me(s.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const k=D=>{j.status==="error"?D.reject(j.error):j.data!==void 0&&D.resolve(j.data)},C=()=>{const D=F(this,Re,j.promise=lr());k(D)},B=c(this,Re);switch(B.status){case"pending":t.queryHash===n.queryHash&&k(B);break;case"fulfilled":(j.status==="error"||j.data!==B.value)&&C();break;case"rejected":(j.status!=="error"||j.error!==B.reason)&&C();break}}return j}updateResult(){const t=c(this,se),s=this.createResult(c(this,$),this.options);if(F(this,Ye,c(this,$).state),F(this,ot,this.options),c(this,Ye).data!==void 0&&F(this,lt,c(this,$)),Ut(s,t))return;F(this,se,s);const n=()=>{if(!t)return!0;const{notifyOnChangeProps:i}=this.options,h=typeof i=="function"?i():i;if(h==="all"||!h&&!c(this,ut).size)return!0;const f=new Set(h??c(this,ut));return this.options.throwOnError&&f.add("error"),Object.keys(c(this,se)).some(g=>{const d=g;return c(this,se)[d]!==t[d]&&f.has(d)})};G(this,K,Er).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&G(this,K,Kt).call(this)}},ae=new WeakMap,$=new WeakMap,St=new WeakMap,se=new WeakMap,Ye=new WeakMap,ot=new WeakMap,Re=new WeakMap,Pe=new WeakMap,Rt=new WeakMap,ct=new WeakMap,lt=new WeakMap,Je=new WeakMap,Ge=new WeakMap,Le=new WeakMap,ut=new WeakMap,K=new WeakSet,xt=function(t){G(this,K,Qt).call(this);let s=c(this,$).fetch(this.options,t);return t!=null&&t.throwOnError||(s=s.catch(At)),s},$t=function(){G(this,K,qt).call(this);const t=wt(this.options.staleTime,c(this,$));if(Et||c(this,se).isStale||!nr(t))return;const n=Zr(c(this,se).dataUpdatedAt,t)+1;F(this,Je,It.setTimeout(()=>{c(this,se).isStale||this.updateResult()},n))},Wt=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(c(this,$)):this.options.refetchInterval)??!1},Vt=function(t){G(this,K,zt).call(this),F(this,Le,t),!(Et||me(this.options.enabled,c(this,$))===!1||!nr(c(this,Le))||c(this,Le)===0)&&F(this,Ge,It.setInterval(()=>{(this.options.refetchIntervalInBackground||ss.isFocused())&&G(this,K,xt).call(this)},c(this,Le)))},Kt=function(){G(this,K,$t).call(this),G(this,K,Vt).call(this,G(this,K,Wt).call(this))},qt=function(){c(this,Je)&&(It.clearTimeout(c(this,Je)),F(this,Je,void 0))},zt=function(){c(this,Ge)&&(It.clearInterval(c(this,Ge)),F(this,Ge,void 0))},Qt=function(){const t=c(this,ae).getQueryCache().build(c(this,ae),this.options);if(t===c(this,$))return;const s=c(this,$);F(this,$,t),F(this,St,t.state),this.hasListeners()&&(s==null||s.removeObserver(this),t.addObserver(this))},Er=function(t){wr.batch(()=>{t.listeners&&this.listeners.forEach(s=>{s(c(this,se))}),c(this,ae).getQueryCache().notify({query:c(this,$),type:"observerResultsUpdated"})})},mr);function fs(e,t){return me(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function ur(e,t){return fs(e,t)||e.state.data!==void 0&&Ht(e,t,t.refetchOnMount)}function Ht(e,t,s){if(me(t.enabled,e)!==!1&&wt(t.staleTime,e)!=="static"){const n=typeof s=="function"?s(e):s;return n==="always"||n!==!1&&Gt(e,t)}return!1}function fr(e,t,s,n){return(e!==t||me(n.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&Gt(e,s)}function Gt(e,t){return me(t.enabled,e)!==!1&&e.isStaleByTime(wt(t.staleTime,e))}function ds(e,t){return!Ut(e.getCurrentResult(),t)}var hs=ve.createContext(void 0),Sr=e=>{const t=ve.useContext(hs);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Rr=ve.createContext(!1),ps=()=>ve.useContext(Rr);Rr.Provider;function bs(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var gs=ve.createContext(bs()),ms=()=>ve.useContext(gs),vs=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},ys=e=>{ve.useEffect(()=>{e.clearReset()},[e])},xs=({result:e,errorResetBoundary:t,throwOnError:s,query:n,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&n&&(i&&e.data===void 0||ts(s,[e.error,n])),ws=e=>{if(e.suspense){const s=i=>i==="static"?i:Math.max(i??1e3,1e3),n=e.staleTime;e.staleTime=typeof n=="function"?(...i)=>s(n(...i)):s(n),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Es=(e,t)=>e.isLoading&&e.isFetching&&!t,Ss=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,dr=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function Rs(e,t,s){var u,y,E,O,P;if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))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=ps(),i=ms(),h=Sr(),f=h.defaultQueryOptions(e);(y=(u=h.getDefaultOptions().queries)==null?void 0:u._experimental_beforeQuery)==null||y.call(u,f),process.env.NODE_ENV!=="production"&&(f.queryFn||console.error(`[${f.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`)),f._optimisticResults=n?"isRestoring":"optimistic",ws(f),vs(f,i),ys(i);const g=!h.getQueryCache().get(f.queryHash),[d]=ve.useState(()=>new t(h,f)),x=d.getOptimisticResult(f),p=!n&&e.subscribed!==!1;if(ve.useSyncExternalStore(ve.useCallback(R=>{const N=p?d.subscribe(wr.batchCalls(R)):At;return d.updateResult(),N},[d,p]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),ve.useEffect(()=>{d.setOptions(f)},[f,d]),Ss(f,x))throw dr(f,d,i);if(xs({result:x,errorResetBoundary:i,throwOnError:f.throwOnError,query:h.getQueryCache().get(f.queryHash),suspense:f.suspense}))throw x.error;if((O=(E=h.getDefaultOptions().queries)==null?void 0:E._experimental_afterQuery)==null||O.call(E,f,x),f.experimental_prefetchInRender&&!Et&&Es(x,n)){const R=g?dr(f,d,i):(P=h.getQueryCache().get(f.queryHash))==null?void 0:P.promise;R==null||R.catch(At).finally(()=>{d.updateResult()})}return f.notifyOnChangeProps?x:d.trackResult(x)}function _r(e,t){return Rs(e,us)}const Cr=e=>{const t=Sr(),s=Yt();return o.useEffect(()=>{const n=s.channel("animation-states-changes").on("postgres_changes",{event:"*",schema:"public",table:"animation_states"},()=>{t.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe(),i=s.channel("bob-animations-changes").on("postgres_changes",{event:"*",schema:"public",table:"bob_animations"},()=>{t.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe();return()=>{s.removeChannel(n),s.removeChannel(i)}},[t,s]),_r({queryKey:["bob-animation-data",e],queryFn:async()=>{var R;const{data:n,error:i}=await s.from("bob_looks").select("*").order("display_order");if(i)throw i;const h=(n||[]).find(N=>N.is_active),f=e||(h==null?void 0:h.id)||n&&((R=n[0])==null?void 0:R.id)||null;if(!f)return{states:[],configs:[],uploadedImages:[],looks:n||[],activeLookId:null};const{data:g,error:d}=await s.from("animation_states").select("*").eq("is_active",!0).eq("look_id",f).order("display_order");if(d)throw d;const{data:x,error:p}=await s.from("bob_animations").select("*").eq("is_active",!0).eq("look_id",f).order("animation_state").order("sequence_order");if(p)throw p;const u=new Set((g||[]).map(N=>N.state_key)),y=(x||[]).filter(N=>u.has(N.animation_state)),{data:E,error:O}=await s.storage.from("bob-images").list();if(O)throw O;const P=(E||[]).map(N=>{const{data:b}=s.storage.from("bob-images").getPublicUrl(N.name);return b.publicUrl});return y.forEach(N=>{const b=new Image;b.src=N.image_url}),{states:g||[],configs:y,uploadedImages:P,looks:n||[],activeLookId:f}},staleTime:30*1e3,gcTime:5*60*1e3})},Tr=()=>{const[e,t]=o.useState(""),[s,n]=o.useState(0),[i,h]=o.useState(400),[f,g]=o.useState(!1),d=o.useRef(),{data:x,isLoading:p}=Cr(),u=o.useRef({}),{imageUrlsMap:y,alternateImages:E,offsetsMap:O,scalesMap:P,availableStates:R}=o.useMemo(()=>{if(!x)return{imageUrlsMap:{},alternateImages:{},offsetsMap:{},scalesMap:{},availableStates:[]};const _={},m={},v={},T={},j=x.states.map(L=>L.state_key);return j.forEach(L=>{const k=x.configs.filter(M=>M.animation_state===L),C=k.map(M=>M.image_url),B=k.map(M=>M.vertical_offset||0),D=k.map(M=>M.scale||100);if(C.length>0){const M=x.states.find(Z=>Z.state_key===L);_[L]={url:C[0],animation_speed:(M==null?void 0:M.animation_speed)||400,pause_duration:(M==null?void 0:M.pause_duration)||0,loop_count:(M==null?void 0:M.loop_count)||0},m[L]=C,v[L]=B,T[L]=D}}),{imageUrlsMap:_,alternateImages:m,offsetsMap:v,scalesMap:T,availableStates:j}},[x]);return o.useEffect(()=>{u.current=y},[y]),o.useEffect(()=>{R.length>0&&!e&&t(R[0])},[R,e]),o.useEffect(()=>{const _=E[e];if(d.current&&clearInterval(d.current),_&&_.length>1){n(0);const m=u.current[e],v=(m==null?void 0:m.animation_speed)||i||400,T=(m==null?void 0:m.loop_count)||0,j=(m==null?void 0:m.pause_duration)||0;let L=0,k=!1;const C=()=>{d.current=setInterval(()=>{k||n(B=>{const D=(B+1)%_.length;return D===0&&(L++,T>0&&L>=T)?(clearInterval(d.current),j>0&&(k=!0,setTimeout(()=>{L=0,k=!1,C()},j)),B):D})},v)};C()}else n(0);return()=>{d.current&&clearInterval(d.current)}},[e,E]),{animationState:e,setAnimationState:t,getCurrentImage:()=>{const _=E[e];if(!_||_.length===0){const m=R.find(v=>{var T;return((T=E[v])==null?void 0:T.length)>0});return m?E[m][0]:""}return _[s]||_[0]},getCurrentOffset:()=>{const _=O[e];if(!_||_.length===0){const m=R.find(v=>{var T;return((T=O[v])==null?void 0:T.length)>0});return m?O[m][0]:0}return _[s]||_[0]},getCurrentScale:()=>{const _=P[e];if(!_||_.length===0){const m=R.find(v=>{var T;return((T=P[v])==null?void 0:T.length)>0});return m?P[m][0]:100}return _[s]||_[0]},imageUrls:y,availableStates:R,setTalkSpeed:h,manualMode:f,setManualMode:g,isLoading:p}},jr=()=>{const e=Yt(),{data:t=[],isLoading:s}=_r({queryKey:["bob-backdrops"],queryFn:async()=>{const{data:i,error:h}=await e.from("bob_backdrops").select("*").order("display_order",{ascending:!0});if(h)throw h;return i},staleTime:5*60*1e3,gcTime:10*60*1e3}),n=t.find(i=>i.is_active);return{backdrops:t,activeBackdrop:n,isLoading:s}},kr=({currentImage:e,animationState:t,backdropUrl:s,counterOverlayUrl:n,counterHeightPercent:i=12,className:h="",verticalOffset:f=0,scale:g=100})=>{const d=f+i,x=55*(g/100);return a.jsx("div",{className:`flex flex-col items-center justify-center gap-6 w-full ${h}`,children:a.jsxs("div",{className:"relative w-full max-w-[600px] mx-auto aspect-[16/10] overflow-hidden",children:[s&&a.jsx("img",{src:s,alt:"Backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-bottom"}),a.jsx("img",{src:e,alt:`Bob ${t}`,className:"absolute z-10 h-auto object-contain left-1/2 -translate-x-1/2",style:{bottom:`${d}%`,width:`${x}%`,maxWidth:`${220*(g/100)}px`,transformOrigin:"center bottom"}}),n&&a.jsx("img",{src:n,alt:"Counter",className:"absolute z-20 bottom-0 left-0 w-full object-cover object-bottom",style:{height:`${i}%`}})]})})},Or=({messages:e,input:t,setInput:s,isLoading:n,onSend:i,onKeyPress:h,onInputFocus:f,onInputBlur:g,chatEndRef:d,isMuted:x=!1,onToggleMute:p,isSpeaking:u=!1,className:y=""})=>a.jsx("div",{className:`w-full max-w-6xl mx-auto px-4 pb-8 ${y}`,children:a.jsxs("div",{className:"bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg overflow-hidden",children:[a.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{value:t,onChange:E=>s(E.target.value),onKeyPress:h,onFocus:f,onBlur:g,placeholder:"Ask Bob about car parts...",disabled:n,className:"flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500"}),p&&a.jsx("button",{onClick:p,className:`shrink-0 p-2 border border-gray-300 dark:border-gray-600 rounded-md ${u?"animate-pulse":""}`,title:x?"Unmute Bob's voice":"Mute Bob's voice",children:x?"🔇":"🔊"}),a.jsx("button",{onClick:i,disabled:n||!t.trim(),className:"shrink-0 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed",children:"Send"})]})}),a.jsxs("div",{className:"overflow-y-auto p-4 space-y-3 h-[300px] md:h-[400px]",children:[[...e].reverse().map((E,O)=>a.jsx("div",{className:`flex ${E.role==="user"?"justify-end":"justify-start"}`,children:a.jsx("div",{className:`max-w-[80%] rounded-lg px-4 py-2 text-sm md:text-base ${E.role==="user"?"bg-blue-600 text-white":"bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-gray-100"}`,children:E.content})},O)),a.jsx("div",{ref:d})]})]})}),Ir=({currentImage:e,animationState:t,counterOverlayUrl:s,counterHeightPercent:n=15,scale:i=100,position:h="center"})=>{const f=85*i/100,g=400*i/100,d=h==="center"?"-20%":"-35%";return a.jsxs("div",{className:"absolute inset-0 pointer-events-none overflow-hidden",children:[a.jsx("div",{className:"absolute left-0 z-40",style:{bottom:`${n-2}%`,transform:`translateX(${d})`,width:`${f}%`,maxWidth:`${g}px`,transition:"transform 0.4s ease-out"},children:a.jsx("img",{src:e,alt:`Bob ${t}`,className:"w-full h-auto object-contain",style:{display:"block"}})}),s&&a.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-50",style:{height:`${n}%`},children:a.jsx("img",{src:s,alt:"Shop counter",className:"w-full h-full object-cover object-top"})})]})},hr=(e,t)=>{if(!e||!t)return!1;const s=e.toLowerCase();return t.toLowerCase().replace(/s\b/g,"").split(/\s+/).filter(Boolean).every(i=>s.includes(i))},_s=(e,t)=>{var i;const s=((i=e.brand)==null?void 0:i.toLowerCase())===t.brand.toLowerCase(),n=Math.abs(e.price-t.price)<1;return s&&n},Nr=({products:e,servicePackages:t,highlightedPartType:s,highlightedProduct:n,onProductClick:i,onPackageSelect:h,isResearching:f,visible:g=!0,counterHeightPercent:d=22,hasVehicle:x=!1})=>{const p=o.useRef(null),u=o.useRef({}),y=o.useRef(null),E=o.useMemo(()=>{const b={};return e.forEach(_=>{const m=_.partslotDescription||"Other Parts";b[m]||(b[m]=[]),b[m].push(_)}),Object.keys(b).sort((_,m)=>_.localeCompare(m)).map(_=>({name:_,products:b[_]}))},[e]);o.useEffect(()=>{var b;if(s){const S=E.find(_=>hr(_.name,s));S&&u.current[S.name]&&((b=u.current[S.name])==null||b.scrollIntoView({behavior:"smooth",block:"start"}))}},[s,E]),o.useEffect(()=>{n&&y.current&&y.current.scrollIntoView({behavior:"smooth",block:"center"})},[n]);const O=e.length>0||t.length>0,P=f,R=O&&!f,N=x?"56px":"8px";return a.jsxs("div",{ref:p,className:`absolute right-2 w-[52%] max-w-[220px] overflow-y-auto overflow-x-hidden z-30 flex flex-col gap-2 pb-4 transition-all duration-300 ease-out ${g?"opacity-100 translate-x-0":"opacity-0 translate-x-8 pointer-events-none"}`,style:{top:N,bottom:`calc(${d}% + 16px)`,paddingTop:"env(safe-area-inset-top, 4px)"},children:[P&&a.jsx("div",{className:"rounded-lg p-3",children:a.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[a.jsx("div",{className:"w-4 h-4 border-2 border-blue-600 border-t-transparent rounded-full animate-spin"}),a.jsx("span",{children:"Finding parts..."})]})}),R&&t.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"text-xs font-semibold text-blue-600 flex items-center gap-1 px-1",children:[a.jsx("svg",{className:"h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),"Service Packages"]}),t.map(b=>a.jsxs("div",{onClick:()=>h==null?void 0:h(b),className:"cursor-pointer hover:shadow-md transition-all bg-white/80 rounded-lg border border-gray-200 p-2",children:[a.jsx("p",{className:"text-xs font-medium line-clamp-1",children:b.title}),a.jsxs("p",{className:"text-sm font-bold text-blue-600",children:["$",b.from_price.toFixed(0)]})]},b.id))]}),R&&E.map(({name:b,products:S},_)=>{const m=s&&hr(b,s);return a.jsxs("section",{ref:v=>{u.current[b]=v},className:`rounded-lg transition-all border border-transparent ${m?"ring-2 ring-blue-600 p-2 bg-blue-50/50 shadow-lg":""}`,children:[a.jsxs("h3",{className:"text-xs font-semibold mb-2 flex items-center gap-1 px-1 text-gray-900",children:[a.jsx("svg",{className:"h-3 w-3 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("span",{className:"truncate",children:b}),a.jsxs("span",{className:"text-[10px] text-gray-500",children:["(",S.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:S.map((v,T)=>{const j=n&&_s(v,n);return a.jsxs("div",{ref:j?y:void 0,onClick:()=>i==null?void 0:i(v),className:`cursor-pointer transition-all bg-white/80 rounded-lg border border-gray-200 relative ${j?"ring-4 ring-blue-600 scale-105 z-10":"hover:shadow-md"}`,children:[j&&a.jsxs("span",{className:"absolute -top-2 -right-2 bg-blue-600 text-white text-[8px] px-1 py-0.5 rounded z-20 flex items-center",children:[a.jsx("svg",{className:"h-2 w-2 mr-0.5",fill:"currentColor",viewBox:"0 0 20 20",children:a.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"})}),"Pick"]}),a.jsxs("div",{className:"p-2",children:[a.jsx("div",{className:"aspect-square bg-gray-100 rounded-md mb-1 flex items-center justify-center overflow-hidden",children:v.image_url?a.jsx("img",{src:v.image_url,alt:v.name,className:"w-full h-full object-contain"}):a.jsx("svg",{className:"h-8 w-8 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),a.jsx("p",{className:"text-xs font-medium line-clamp-2",children:v.name}),v.brand&&a.jsx("p",{className:"text-[10px] text-gray-500",children:v.brand})]}),a.jsx("div",{className:"px-2 pb-2",children:a.jsx("span",{className:"text-sm font-bold text-blue-600",children:v.price>0?`$${v.price.toFixed(2)}`:"Price on request"})}),a.jsx("div",{className:"px-2 pb-2",children:a.jsx("button",{className:"w-full bg-blue-600 text-white text-xs py-1.5 rounded-md hover:bg-blue-700",onClick:L=>{L.stopPropagation(),i==null||i(v)},children:"Buy Now"})})]},`${v.id}-${T}`)})})]},b)})]})},Pr=({onTranscript:e,onSpeechEnd:t,language:s="en-NZ",mode:n="toggle"}={})=>{const[i,h]=o.useState(!1),[f,g]=o.useState(""),[d,x]=o.useState(""),[p,u]=o.useState(null),[y,E]=o.useState(!1),O=o.useRef(null),P=o.useRef(""),R=o.useRef(e),N=o.useRef(t);o.useEffect(()=>{R.current=e,N.current=t},[e,t]),o.useEffect(()=>{const m=window.SpeechRecognition||window.webkitSpeechRecognition;if(m){E(!0);const v=new m;v.continuous=n==="ptt",v.interimResults=!0,v.lang=s,v.maxAlternatives=1,v.onstart=()=>{h(!0),u(null)},v.onresult=T=>{let j="",L="";for(let k=T.resultIndex;k<T.results.length;k++){const C=T.results[k][0].transcript;T.results[k].isFinal?L+=C:j+=C}L&&(P.current=L,g(L),R.current&&R.current(L)),x(j)},v.onerror=T=>{switch(h(!1),T.error){case"no-speech":u("No speech detected. Please try again.");break;case"audio-capture":u("No microphone found. Please check your device.");break;case"not-allowed":u("Microphone permission denied. Please allow access.");break;default:u("Speech recognition error. Please try again.")}},v.onend=()=>{h(!1),x(""),P.current&&N.current&&N.current(P.current),P.current=""},O.current=v}return()=>{O.current&&O.current.stop()}},[s,n]);const b=()=>{O.current&&!i&&(g(""),x(""),u(null),O.current.start())},S=()=>{O.current&&i&&O.current.stop()};return{isListening:i,transcript:f,interimTranscript:d,error:p,isSupported:y,startListening:b,stopListening:S,toggleListening:()=>{i?S():b()}}},Lr=({messages:e,input:t,setInput:s,isLoading:n,onSend:i,onKeyPress:h,onInputFocus:f,onInputBlur:g,chatEndRef:d,isMuted:x=!1,onToggleMute:p,isSpeaking:u=!1})=>{const[y,E]=o.useState(!1),O=o.useRef(null),P=o.useRef(!1),{isListening:R,interimTranscript:N,error:b,isSupported:S,startListening:_,stopListening:m}=Pr({onTranscript:k=>s(k),language:"en-NZ",mode:"ptt"});o.useEffect(()=>{N&&s(N)},[N,s]);const v=o.useCallback(()=>{n||P.current||(P.current=!0,navigator.vibrate&&navigator.vibrate(10),_())},[n,_]),T=o.useCallback(()=>{P.current&&(P.current=!1,navigator.vibrate&&navigator.vibrate(10),m(),setTimeout(()=>{i()},150))},[m,i]),j=[...e].reverse().find(k=>k.role==="assistant"),L=j!=null&&j.content?j.content.length>50?j.content.slice(0,50)+"...":j.content:"Ask Bob about car parts...";return a.jsxs("div",{ref:O,className:`fixed bottom-0 left-0 right-0 bg-white/95 backdrop-blur-md border-t border-gray-200 transition-all duration-300 ease-out shadow-[0_-4px_20px_rgba(0,0,0,0.15)] ${y?"h-[55vh]":"h-auto"}`,style:{zIndex:60,paddingBottom:"env(safe-area-inset-bottom, 8px)"},children:[a.jsx("button",{onClick:()=>E(!y),className:"absolute -top-5 left-1/2 -translate-x-1/2 bg-white border border-gray-200 rounded-full p-1.5 shadow-lg z-40","aria-label":y?"Collapse chat":"Expand chat",children:y?a.jsx("svg",{className:"h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}):a.jsx("svg",{className:"h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 15l7-7 7 7"})})}),!y&&a.jsx("div",{className:"px-3 pt-2 pb-0.5",onClick:()=>E(!0),children:a.jsx("p",{className:"text-xs text-gray-500 line-clamp-1",children:L})}),y&&a.jsxs("div",{className:"h-[calc(100%-100px)] overflow-y-auto p-4 space-y-2",children:[[...e].reverse().map((k,C)=>a.jsx("div",{className:`flex ${k.role==="user"?"justify-end":"justify-start"}`,children:a.jsx("div",{className:`max-w-[85%] rounded-lg px-3 py-2 text-sm ${k.role==="user"?"bg-blue-600 text-white":"bg-gray-100 text-gray-900"}`,children:k.content})},C)),a.jsx("div",{ref:d})]}),a.jsxs("div",{className:`px-2 pb-1.5 ${y?"pt-2 border-t border-gray-200":"pt-0.5"}`,children:[R&&a.jsxs("div",{className:"mb-2 text-xs text-gray-500 flex items-center gap-2",children:[a.jsx("span",{className:"inline-block w-2 h-2 bg-red-500 rounded-full animate-pulse"}),"Listening..."]}),b&&a.jsx("div",{className:"mb-2 text-xs text-red-500",children:b}),a.jsxs("div",{className:"flex gap-1.5 items-center",children:[p&&y&&a.jsx("button",{onClick:p,className:`shrink-0 h-9 w-9 flex items-center justify-center rounded-md hover:bg-gray-100 ${u?"text-blue-600 animate-pulse":"text-gray-600"}`,title:x?"Unmute":"Mute",children:x?a.jsxs("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[a.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"}),a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):a.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),a.jsx("input",{type:"text",value:t,onChange:k=>s(k.target.value),onKeyPress:h,onFocus:f,onBlur:g,placeholder:"Message Bob...",disabled:n,className:"flex-1 h-10 text-base px-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"}),S&&a.jsx("button",{onTouchStart:v,onTouchEnd:T,onTouchCancel:T,onMouseDown:v,onMouseUp:T,onMouseLeave:T,disabled:n,className:`shrink-0 h-12 w-12 rounded-full flex items-center justify-center select-none touch-none ${R?"bg-red-500 text-white animate-pulse ring-2 ring-red-300 scale-110":"bg-blue-600 text-white"} disabled:opacity-50`,title:"Hold to talk",children:a.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,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"})})})]})]})]})},Mr=({currentImage:e,animationState:t,backdropUrl:s,counterOverlayUrl:n,counterHeightPercent:i=22,messages:h,input:f,setInput:g,isLoading:d,onSend:x,onKeyPress:p,onInputFocus:u,onInputBlur:y,chatEndRef:E,isMuted:O,onToggleMute:P,isSpeaking:R,products:N,servicePackages:b,highlightedPartType:S,highlightedProduct:_,onProductClick:m,onPackageSelect:v,isResearching:T,vehicle:j,onChangeVehicle:L})=>{const k=typeof window<"u"&&window.self!==window.top,[C,B]=o.useState("center"),[D,M]=o.useState("hidden"),Z=N.length>0||b.length>0;o.useEffect(()=>{if(T&&D!=="loading"&&D!=="visible")M("loading"),C==="center"&&B("left");else if(Z&&D!=="visible")if(C==="center"){B("left"),M("transitioning");const q=setTimeout(()=>{M("visible")},400);return()=>clearTimeout(q)}else M("visible");else!Z&&!T&&D!=="hidden"&&(M("hidden"),B("center"))},[Z,T,D,C]);const Ee=D!=="hidden";return a.jsxs("div",{className:"fixed inset-0 overflow-hidden",style:{height:"100dvh",touchAction:"manipulation"},children:[s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"absolute inset-0 z-0",style:{backgroundImage:`url(${s})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:"blur(12px) brightness(0.7)",transform:"scale(1.1)"}}),a.jsx("div",{className:"absolute inset-0 z-[1]",style:{background:"linear-gradient(to bottom, rgba(255,255,255,0.3) 0%, rgba(255,255,255,0.6) 100%)"}})]}),a.jsx(Ir,{currentImage:e,animationState:t,counterOverlayUrl:n,counterHeightPercent:i,scale:200,position:C}),j&&!k&&a.jsx("div",{className:"absolute top-2 left-2 right-2 z-20",children:a.jsxs("div",{className:"bg-white/90 backdrop-blur-sm rounded-lg px-3 py-2 border border-gray-200 shadow-lg flex items-center justify-between",style:{paddingTop:"calc(env(safe-area-inset-top, 4px) + 8px)"},children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("p",{className:"text-xs font-medium text-gray-900 truncate",children:[j.year," ",j.make," ",j.model]}),j.rego&&a.jsx("p",{className:"text-[10px] text-gray-500",children:j.rego})]}),L&&a.jsx("button",{onClick:L,className:"text-xs text-blue-600 hover:underline ml-2 shrink-0",children:"Change"})]})}),a.jsx(Nr,{products:N,servicePackages:b,highlightedPartType:S,highlightedProduct:_,onProductClick:m,onPackageSelect:v,isResearching:T,visible:Ee,counterHeightPercent:i,hasVehicle:!!j}),a.jsx(Lr,{messages:h,input:f,setInput:g,isLoading:d,onSend:x,onKeyPress:p,onInputFocus:u,onInputBlur:y,chatEndRef:E,isMuted:O,onToggleMute:P,isSpeaking:R})]})},Cs=({variant:e="inline",initialState:t="idle",showChat:s=!0,className:n="",backdropUrl:i,counterOverlayUrl:h,counterHeightPercent:f,defaultBobImage:g,verticalOffset:d=0,scale:x=100})=>{const{callbacks:p}=Me(),{animationState:u,setAnimationState:y,getCurrentImage:E,availableStates:O,isLoading:P}=Tr(),{activeBackdrop:R}=jr(),[N,b]=o.useState([]),[S,_]=o.useState([]),[m,v]=o.useState(null),[T,j]=o.useState(null),[L,k]=o.useState(!1),C=xr({setAnimationState:y,manualMode:!1,onReadyToSpeak:()=>{console.log("[BobWidget] Ready to speak")},onStreamComplete:()=>{y(O.find(q=>q.includes("idle"))||"idle")},onResearchStart:()=>{k(!0)},onHighlightPart:q=>{v(q),setTimeout(()=>v(null),8e3)},onHighlightProduct:q=>{j(q),setTimeout(()=>j(null),8e3)},onAutoFetchComplete:()=>{k(!1)}});o.useEffect(()=>{const q=p.onPartsFound,ne=p.onServicePackagesFound;return p.onPartsFound=oe=>{k(!1);const _e=oe.map((Y,Be)=>({id:Y.SKU||Y.sku||`part-${Be}`,name:Y["Part Product Type"]||Y.partslot_description||"Unknown Part",brand:Y.Brand||Y.brand,price:Y["Metro Retail Price"]||Y.price||0,sku:Y.SKU||Y.sku,partNumber:Y["Part Number"]||Y.part_number,partslotDescription:Y["Part Product Type"]||Y.partslot_description,image_url:Y.image_url}));b(_e),q==null||q(oe)},p.onServicePackagesFound=oe=>{_(oe),ne==null||ne(oe)},()=>{p.onPartsFound=q,p.onServicePackagesFound=ne}},[p]);const B=i||(R==null?void 0:R.image_url),D=h||(R==null?void 0:R.counter_overlay_url)||void 0,M=f||(R==null?void 0:R.counter_height_percent)||12,Z=E()||g||"";if(e==="mobile"||e==="fullscreen")return a.jsx(Mr,{currentImage:Z,animationState:u,backdropUrl:B,counterOverlayUrl:D,counterHeightPercent:M,messages:C.messages,input:C.input,setInput:C.setInput,isLoading:C.isLoading,onSend:C.handleSend,onKeyPress:C.handleKeyPress,onInputFocus:C.handleInputFocus,onInputBlur:C.handleInputBlur,chatEndRef:C.chatEndRef,isMuted:C.isMuted,onToggleMute:C.toggleMute,isSpeaking:C.isSpeaking,products:N,servicePackages:S,highlightedPartType:m,highlightedProduct:T,onProductClick:q=>{var ne;return(ne=p.onAddToCart)==null?void 0:ne.call(p,{product_id:q.id,product_name:q.name,quantity:1,unit_price:q.price,sku:q.sku,brand:q.brand})},onPackageSelect:q=>console.log("[BobWidget] Package selected:",q),isResearching:L,vehicle:C.identifiedVehicle});const Ee={inline:"",floating:"fixed bottom-4 right-4 w-96 z-50 shadow-2xl rounded-lg overflow-hidden",fullscreen:"fixed inset-0 z-50 bg-black/80",mobile:""};return a.jsxs("div",{className:`${Ee[e]} ${n}`,children:[Z&&a.jsx(kr,{currentImage:Z,animationState:u,backdropUrl:B,counterOverlayUrl:D,counterHeightPercent:M,verticalOffset:d,scale:x}),s&&a.jsx(Or,{messages:C.messages,input:C.input,setInput:C.setInput,isLoading:C.isLoading,onSend:C.handleSend,onKeyPress:C.handleKeyPress,onInputFocus:C.handleInputFocus,onInputBlur:C.handleInputBlur,chatEndRef:C.chatEndRef,isMuted:C.isMuted,onToggleMute:C.toggleMute,isSpeaking:C.isSpeaking})]})},Ts=6e4,js=({states:e,setAnimationState:t,manualMode:s})=>{const[n,i]=o.useState("page_load"),[h,f]=o.useState(!1),g=o.useRef(null),d=o.useCallback(m=>e.find(v=>v.chat_trigger===m&&v.is_active),[e]),x=o.useCallback(()=>e.find(m=>m.chat_trigger==="awaiting_input"||m.state_key==="talk_pause"||m.title.toLowerCase().includes("listen")||m.title.toLowerCase().includes("pause")),[e]),p=o.useCallback(()=>e.find(m=>m.state_key==="idle"||m.title.toLowerCase().includes("idle")),[e]),u=o.useCallback(m=>{const v=e.find(T=>T.state_key===m);return{speed:(v==null?void 0:v.animation_speed)||400,pauseDuration:(v==null?void 0:v.pause_duration)||0,loopCount:(v==null?void 0:v.loop_count)||0}},[e]),y=o.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null)},[]),E=o.useCallback(()=>{y(),!s&&(g.current=setTimeout(()=>{const m=p();m&&(i("idle"),t(m.state_key))},Ts))},[s,p,t,y]),O=o.useCallback(m=>{if(s)return;const v=d(m);v&&t(v.state_key)},[s,d,t]),P=o.useCallback(()=>{if(s)return;const m=x();m&&(i("awaiting_input"),t(m.state_key),E())},[s,x,t,E]),R=o.useCallback(()=>{h||s||(f(!0),i("page_load"),O("page_load"),setTimeout(()=>{P()},3e3))},[h,s,O,P]),N=o.useCallback(()=>{y(),i("processing_input"),O("processing_input")},[O,y]),b=o.useCallback(()=>{y(),i("streaming_response"),O("streaming_response")},[O,y]),S=o.useCallback(()=>{i("response_complete"),O("response_complete"),setTimeout(()=>{P()},3e3)},[O,P]),_=o.useCallback(()=>{i("showing_product");const m=e.find(v=>v.chat_trigger==="showing_product"||v.state_key==="showing_product");m&&t(m.state_key),setTimeout(()=>{P()},4e3)},[e,t,P]);return o.useEffect(()=>()=>y(),[y]),{chatStage:n,initialize:R,onUserInput:N,onStreamStart:b,onStreamComplete:S,onShowingProduct:_,getStateSettings:u}};exports.Bob=Cs;exports.BobCharacter=kr;exports.BobProvider=qr;exports.ChatInterface=Or;exports.MobileBobCharacter=Ir;exports.MobileBobLayout=Mr;exports.MobileChatDrawer=Lr;exports.MobileProductColumn=Nr;exports.useBobAnimation=Tr;exports.useBobAnimationData=Cr;exports.useBobBackdrop=jr;exports.useBobCallbacks=Hr;exports.useBobChat=xr;exports.useBobContext=Me;exports.useBobStateTransitions=js;exports.useBobSupabase=Yt;exports.useHostApiConfig=Qr;exports.useHostContext=zr;exports.useSpeechRecognition=Pr;exports.useSpeechSynthesis=yr;
30
+ <%s key={someKey} {...props} />`,tt,Oe,jt,Oe),Le[Oe+tt]=!0}}return e===p?Ne(z):Ve(z),z}}function et(e,n,u){return Ue(e,n,u,!0)}function Ct(e,n,u){return Ue(e,n,u,!1)}var Rt=Ct,St=et;ze.Fragment=p,ze.jsx=Rt,ze.jsxs=St}()),ze}process.env.NODE_ENV==="production"?nt.exports=Ot():nt.exports=Bt();var t=nt.exports;const ft=r.createContext(null);function Pt({children:s,bobConfig:l,hostApiConfig:c,hostContext:p={},callbacks:f={}}){const E=r.useMemo(()=>It.createClient(l.supabaseUrl,l.supabaseKey),[l.supabaseUrl,l.supabaseKey]),[v,C]=r.useState(p);r.useEffect(()=>{C(p)},[p]);const g=r.useCallback(d=>{C(h=>({...h,...d}))},[]),y=r.useMemo(()=>({bobSupabase:E,bobConfig:l,hostApiConfig:c,hostContext:v,callbacks:f,updateHostContext:g}),[E,l,c,v,f,g]);return t.jsx(ft.Provider,{value:y,children:s})}function we(){const s=r.useContext(ft);if(!s)throw new Error("useBobContext must be used within a BobProvider");return s}function at(){const{bobSupabase:s}=we();return s}function Lt(){const{hostContext:s}=we();return s}function At(){const{hostApiConfig:s}=we();return s}function Mt(){const{callbacks:s}=we();return s}const lt=5e3,pt=({onStart:s,onEnd:l,onFailed:c}={})=>{const{bobConfig:p}=we(),[f,E]=r.useState(!1),v=r.useRef(null),C=r.useRef(null),g=r.useRef(!1),y=r.useRef(s),d=r.useRef(l),h=r.useRef(c);r.useEffect(()=>{y.current=s,d.current=l,h.current=c},[s,l,c]);const b=r.useCallback(()=>{C.current&&(clearTimeout(C.current),C.current=null)},[]),R=r.useCallback(()=>{var a;g.current||(g.current=!0,console.log("[BobWidget TTS] Fallback: triggering onStart without audio"),(a=y.current)==null||a.call(y))},[]),j=r.useCallback(async a=>{var m,x,o,i;if(a.trim()){g.current=!1,b(),v.current&&(v.current.pause(),v.current=null),C.current=setTimeout(()=>{var _,k;console.warn("[BobWidget TTS] Timeout after 5s - triggering fallback callbacks"),R(),E(!1),(_=d.current)==null||_.call(d),(k=h.current)==null||k.call(h),v.current=null},lt);try{const _=new AbortController,k=setTimeout(()=>_.abort(),lt-1e3),O=await fetch(`${p.supabaseUrl}/functions/v1/bob-tts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p.supabaseKey}`},body:JSON.stringify({text:a}),signal:_.signal});if(clearTimeout(k),!O.ok){const $=await O.json().catch(()=>({}));throw console.error("[BobWidget TTS] Request failed:",$),new Error("TTS request failed")}const{audioContent:B}=await O.json(),w=new Audio(`data:audio/mp3;base64,${B}`);v.current=w,w.onplay=()=>{var $;b(),g.current||(g.current=!0,E(!0),console.log("[BobWidget TTS] Audio playing, triggering onStart"),($=y.current)==null||$.call(y))},w.onended=()=>{var $;b(),E(!1),($=d.current)==null||$.call(d),v.current=null},w.onerror=$=>{var D,I;b(),console.warn("[BobWidget TTS] Audio playback error:",$),R(),E(!1),(D=d.current)==null||D.call(d),(I=h.current)==null||I.call(h),v.current=null};try{await w.play()}catch($){console.warn("[BobWidget TTS] Audio play() failed (likely autoplay policy):",$),b(),R(),E(!1),(m=d.current)==null||m.call(d),(x=h.current)==null||x.call(h),v.current=null}}catch(_){b(),console.error("[BobWidget TTS] Speech synthesis error:",_),R(),E(!1),(o=d.current)==null||o.call(d),(i=h.current)==null||i.call(h)}}},[p.supabaseUrl,p.supabaseKey,b,R]),L=r.useCallback(()=>{b(),v.current&&(v.current.pause(),v.current=null),E(!1)},[b]),S=r.useCallback(()=>{var a;(a=v.current)==null||a.pause()},[]),N=r.useCallback(()=>{var a;(a=v.current)==null||a.play()},[]);return r.useEffect(()=>()=>{b(),v.current&&(v.current.pause(),v.current=null)},[b]),{speak:j,stop:L,pause:S,resume:N,isSpeaking:f,isSupported:!0}},$t=["what version","which version","software version","bob version","your version","current version","running version","version number","what ver","which ver"],ut=["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"],Dt=["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"],ht=({setAnimationState:s,manualMode:l=!1,talkingState:c="talk",thinkingState:p="research",completeState:f="complete",idleState:E="idle",listenState:v="talk_pause",onStreamStart:C,onStreamComplete:g,onShowingProduct:y,onResearchStart:d,onReadyToSpeak:h,onHighlightPart:b,onHighlightProduct:R,onNoPartsFound:j,onAutoFetchComplete:L})=>{var Ge,Je,Ee,be;const{bobConfig:S,hostApiConfig:N,hostContext:a,callbacks:m}=we(),[x,o]=r.useState([]),[i,_]=r.useState(""),[k,O]=r.useState(!1),[B,w]=r.useState(!1),[$,D]=r.useState(null),I=r.useRef(null),Y=r.useRef(!1),fe=r.useRef(!1),W=r.useRef(""),X=r.useRef(!1),Z=r.useRef(null),he=()=>{Z.current&&(clearTimeout(Z.current),Z.current=null)},{speak:U,stop:_e,isSpeaking:qe}=pt({onStart:()=>{he(),X.current=!0,console.log("[BobWidget] Speech started - revealing products"),h==null||h(),l||se(c)},onEnd:()=>{he();const A=ut.some(q=>W.current.toLowerCase().includes(q.toLowerCase()));l||(A&&y?y():g?g():(se(f),setTimeout(()=>se(v),3e3)))},onFailed:()=>{console.warn("[BobWidget] Speech synthesis failed - fallback triggered")}});r.useEffect(()=>{var A;(A=I.current)==null||A.scrollIntoView({behavior:"smooth"})},[x]),r.useEffect(()=>{var q,G;const A=(q=a.vehicle)==null?void 0:q.selectedVehicle;A&&!$&&(console.log("[BobWidget] Setting vehicle from host context:",A),D(A),(G=m.onVehicleIdentified)==null||G.call(m,A))},[(Ge=a.vehicle)==null?void 0:Ge.selectedVehicle]),r.useEffect(()=>{var A;if(x.length===0&&!fe.current){const q=(A=a.vehicle)==null?void 0:A.selectedVehicle;if(q){fe.current=!0;const G=`${q.year} ${q.make} ${q.model}`;o([{role:"assistant",content:`G'day! Saw you've got the ${G} - choice wagon! What can I help you find for it today?`}])}else o([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])}},[(Je=a.vehicle)==null?void 0:Je.selectedVehicle,x.length]),r.useEffect(()=>{var Ce,Re;const A=(Ce=a.vehicle)==null?void 0:Ce.selectedVehicle;if(!A||Y.current)return;const q=A.vehicle_id??A.id,G=Number.parseInt(String(q),10);if(!Number.isFinite(G)){console.warn("[BobWidget] Vehicle has invalid vehicle_id, cannot auto-fetch:",A);return}Y.current=!0;const ee={...A,vehicle_id:String(G)},ge=(Re=a.user)==null?void 0:Re.email;(async()=>{var me,ve;const Se=`${S.supabaseUrl}/functions/v1/bob-chat`;try{const ae=await fetch(Se,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S.supabaseKey}`},body:JSON.stringify({messages:[],vehicleContext:ee,customerEmail:ge,autoFetchParts:!0,hostConfig:N,hostContext:a})});if(!ae.ok||!ae.body){console.error("[BobWidget] Auto-fetch failed:",ae.status);return}const je=ae.body.getReader(),ke=new TextDecoder;let ue="";for(;;){const{done:oe,value:pe}=await je.read();if(oe)break;ue+=ke.decode(pe,{stream:!0});let Ie;for(;(Ie=ue.indexOf(`
31
+ `))!==-1;){let ie=ue.slice(0,Ie);if(ue=ue.slice(Ie+1),ie.endsWith("\r")&&(ie=ie.slice(0,-1)),ie.startsWith(":")||ie.trim()===""||!ie.startsWith("data: "))continue;const te=ie.slice(6).trim();if(te==="[DONE]")break;try{const ce=JSON.parse(te);ce.type==="service_packages_found"&&ce.packages&&((me=m.onServicePackagesFound)==null||me.call(m,ce.packages)),ce.type==="parts_found"&&ce.parts&&((ve=m.onPartsFound)==null||ve.call(m,ce.parts))}catch{}}}L==null||L()}catch(ae){console.error("[BobWidget] Auto-fetch error:",ae)}})()},[(Ee=a.vehicle)==null?void 0:Ee.selectedVehicle,(be=a.user)==null?void 0:be.email]);const se=A=>{try{s(A)}catch{console.warn(`[BobWidget] State "${A}" not available`)}},Qe=async A=>{var ee,ge,Te,Ce,Re,Se,me,ve,ae,je,ke,ue;const q=`${S.supabaseUrl}/functions/v1/bob-chat`,G=(ee=a.user)==null?void 0:ee.email;try{const oe={messages:[...x,A],hostConfig:N,hostContext:a};$&&(oe.vehicleContext=$),G&&(oe.customerEmail=G);const pe=await fetch(q,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S.supabaseKey}`},body:JSON.stringify(oe)});if(!pe.ok){if(pe.status===429){(ge=m.onError)==null||ge.call(m,new Error("Rate limit exceeded"));return}if(pe.status===402){(Te=m.onError)==null||Te.call(m,new Error("Payment required"));return}throw new Error("Failed to start stream")}if(!pe.body)throw new Error("No response body");const Ie=pe.body.getReader(),ie=new TextDecoder;let te="",ce=!1,de="";for(;!ce;){const{done:re,value:ye}=await Ie.read();if(re)break;te+=ie.decode(ye,{stream:!0});let Fe;for(;(Fe=te.indexOf(`
32
+ `))!==-1;){let le=te.slice(0,Fe);if(te=te.slice(Fe+1),le.endsWith("\r")&&(le=le.slice(0,-1)),le.startsWith(":")||le.trim()===""||!le.startsWith("data: "))continue;const Xe=le.slice(6).trim();if(Xe==="[DONE]"){ce=!0;break}try{const H=JSON.parse(Xe);if(H.type==="vehicle_identified"&&H.vehicle){D(H.vehicle),(Ce=m.onVehicleIdentified)==null||Ce.call(m,H.vehicle);continue}if(H.type==="service_packages_found"&&H.packages){(Re=m.onServicePackagesFound)==null||Re.call(m,H.packages);continue}if(H.type==="parts_found"&&H.parts){(Se=m.onPartsFound)==null||Se.call(m,H.parts);continue}if(H.type==="no_parts_found"){j==null||j();continue}if(H.type==="cart_updated"&&H.items){(me=m.onCartUpdated)==null||me.call(m,H.items);continue}const We=(je=(ae=(ve=H.choices)==null?void 0:ve[0])==null?void 0:ae.delta)==null?void 0:je.content;if(We){de+=We;const Ve=de.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");o(Ne=>{const Le=Ne[Ne.length-1];return(Le==null?void 0:Le.role)==="assistant"?Ne.map((Ue,et)=>et===Ne.length-1?{...Ue,content:Ve}:Ue):[...Ne,{role:"assistant",content:Ve}]}),(ke=m.onBobMessage)==null||ke.call(m,Ve)}}catch{te=le+`
33
+ `+te;break}}}W.current=de.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");const De=ut.some(re=>de.toLowerCase().includes(re.toLowerCase())),xe=de.toLowerCase();for(const re of Dt)if(xe.includes(re.toLowerCase())){const ye=re.replace(/s\s*$/i,"").toUpperCase();b==null||b(ye);break}const Pe=de.match(/(?:go with|recommend|suggest|grab|try)\s+(?:the\s+)?(\w+)\s+(?:at|for)\s+\$(\d+(?:\.\d{2})?)/i);if(Pe){const[,re,ye]=Pe;R==null||R({brand:re,price:parseFloat(ye)})}!B&&W.current.trim()?(X.current=!1,he(),U(W.current),Z.current=setTimeout(()=>{X.current||(console.warn("[BobWidget] Speech fallback after 2s"),h==null||h(),l||(De&&y?y():g?g():(se(f),setTimeout(()=>se(v),3e3))))},2e3)):(h==null||h(),l||(De&&y?y():g?g():(se(f),setTimeout(()=>se(v),3e3))))}catch(oe){console.error("[BobWidget] Chat error:",oe),(ue=m.onError)==null||ue.call(m,oe instanceof Error?oe:new Error("Unknown error")),l||se(E)}},Be=async()=>{if(!i.trim()||k)return;_e();const A={role:"user",content:i};o(ee=>[...ee,A]),_("");const q=i.toLowerCase();if($t.some(ee=>q.includes(ee))){const ee=`G'day mate! I'm running Bob v${st} - she's running sweet as! Anything else I can help ya with?`;o(ge=>[...ge,{role:"assistant",content:ee}]),B||U(ee);return}O(!0),d==null||d(),l||se(p),await Qe(A),O(!1)};return{messages:x,input:i,setInput:_,isLoading:k,handleSend:Be,handleKeyPress:A=>{A.key==="Enter"&&!A.shiftKey&&(A.preventDefault(),Be())},handleInputFocus:()=>{},handleInputBlur:()=>{},chatEndRef:I,clearMessages:()=>{o([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])},isMuted:B,toggleMute:()=>{w(A=>!A),B||_e()},isSpeaking:qe,identifiedVehicle:$,clearVehicle:()=>{D(null)}}},bt=s=>{const l=rt.useQueryClient(),c=at();return r.useEffect(()=>{const p=c.channel("animation-states-changes").on("postgres_changes",{event:"*",schema:"public",table:"animation_states"},()=>{l.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe(),f=c.channel("bob-animations-changes").on("postgres_changes",{event:"*",schema:"public",table:"bob_animations"},()=>{l.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe();return()=>{c.removeChannel(p),c.removeChannel(f)}},[l,c]),rt.useQuery({queryKey:["bob-animation-data",s],queryFn:async()=>{var S;const{data:p,error:f}=await c.from("bob_looks").select("*").order("display_order");if(f)throw f;const E=(p||[]).find(N=>N.is_active),v=s||(E==null?void 0:E.id)||p&&((S=p[0])==null?void 0:S.id)||null;if(!v)return{states:[],configs:[],uploadedImages:[],looks:p||[],activeLookId:null};const{data:C,error:g}=await c.from("animation_states").select("*").eq("is_active",!0).eq("look_id",v).order("display_order");if(g)throw g;const{data:y,error:d}=await c.from("bob_animations").select("*").eq("is_active",!0).eq("look_id",v).order("animation_state").order("sequence_order");if(d)throw d;const h=new Set((C||[]).map(N=>N.state_key)),b=(y||[]).filter(N=>h.has(N.animation_state)),{data:R,error:j}=await c.storage.from("bob-images").list();if(j)throw j;const L=(R||[]).map(N=>{const{data:a}=c.storage.from("bob-images").getPublicUrl(N.name);return a.publicUrl});return b.forEach(N=>{const a=new Image;a.src=N.image_url}),{states:C||[],configs:b,uploadedImages:L,looks:p||[],activeLookId:v}},staleTime:30*1e3,gcTime:5*60*1e3})},gt=()=>{const[s,l]=r.useState(""),[c,p]=r.useState(0),[f,E]=r.useState(400),[v,C]=r.useState(!1),g=r.useRef(),{data:y,isLoading:d}=bt(),h=r.useRef({}),{imageUrlsMap:b,alternateImages:R,offsetsMap:j,scalesMap:L,availableStates:S}=r.useMemo(()=>{if(!y)return{imageUrlsMap:{},alternateImages:{},offsetsMap:{},scalesMap:{},availableStates:[]};const x={},o={},i={},_={},k=y.states.map(O=>O.state_key);return k.forEach(O=>{const B=y.configs.filter(I=>I.animation_state===O),w=B.map(I=>I.image_url),$=B.map(I=>I.vertical_offset||0),D=B.map(I=>I.scale||100);if(w.length>0){const I=y.states.find(Y=>Y.state_key===O);x[O]={url:w[0],animation_speed:(I==null?void 0:I.animation_speed)||400,pause_duration:(I==null?void 0:I.pause_duration)||0,loop_count:(I==null?void 0:I.loop_count)||0},o[O]=w,i[O]=$,_[O]=D}}),{imageUrlsMap:x,alternateImages:o,offsetsMap:i,scalesMap:_,availableStates:k}},[y]);return r.useEffect(()=>{h.current=b},[b]),r.useEffect(()=>{S.length>0&&!s&&l(S[0])},[S,s]),r.useEffect(()=>{const x=R[s];if(g.current&&clearInterval(g.current),x&&x.length>1){p(0);const o=h.current[s],i=(o==null?void 0:o.animation_speed)||f||400,_=(o==null?void 0:o.loop_count)||0,k=(o==null?void 0:o.pause_duration)||0;let O=0,B=!1;const w=()=>{g.current=setInterval(()=>{B||p($=>{const D=($+1)%x.length;return D===0&&(O++,_>0&&O>=_)?(clearInterval(g.current),k>0&&(B=!0,setTimeout(()=>{O=0,B=!1,w()},k)),$):D})},i)};w()}else p(0);return()=>{g.current&&clearInterval(g.current)}},[s,R]),{animationState:s,setAnimationState:l,getCurrentImage:()=>{const x=R[s];if(!x||x.length===0){const o=S.find(i=>{var _;return((_=R[i])==null?void 0:_.length)>0});return o?R[o][0]:""}return x[c]||x[0]},getCurrentOffset:()=>{const x=j[s];if(!x||x.length===0){const o=S.find(i=>{var _;return((_=j[i])==null?void 0:_.length)>0});return o?j[o][0]:0}return x[c]||x[0]},getCurrentScale:()=>{const x=L[s];if(!x||x.length===0){const o=S.find(i=>{var _;return((_=L[i])==null?void 0:_.length)>0});return o?L[o][0]:100}return x[c]||x[0]},imageUrls:b,availableStates:S,setTalkSpeed:E,manualMode:v,setManualMode:C,isLoading:d}},mt=()=>{const s=at(),{data:l=[],isLoading:c}=rt.useQuery({queryKey:["bob-backdrops"],queryFn:async()=>{const{data:f,error:E}=await s.from("bob_backdrops").select("*").order("display_order",{ascending:!0});if(E)throw E;return f},staleTime:5*60*1e3,gcTime:10*60*1e3}),p=l.find(f=>f.is_active);return{backdrops:l,activeBackdrop:p,isLoading:c}},vt=({currentImage:s,animationState:l,backdropUrl:c,counterOverlayUrl:p,counterHeightPercent:f=12,className:E="",verticalOffset:v=0,scale:C=100})=>{const g=v+f,y=55*(C/100);return t.jsx("div",{className:`flex flex-col items-center justify-center gap-6 w-full ${E}`,children:t.jsxs("div",{className:"relative w-full max-w-[600px] mx-auto aspect-[16/10] overflow-hidden",children:[c&&t.jsx("img",{src:c,alt:"Backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-bottom"}),t.jsx("img",{src:s,alt:`Bob ${l}`,className:"absolute z-10 h-auto object-contain left-1/2 -translate-x-1/2",style:{bottom:`${g}%`,width:`${y}%`,maxWidth:`${220*(C/100)}px`,transformOrigin:"center bottom"}}),p&&t.jsx("img",{src:p,alt:"Counter",className:"absolute z-20 bottom-0 left-0 w-full object-cover object-bottom",style:{height:`${f}%`}})]})})},xt=({messages:s,input:l,setInput:c,isLoading:p,onSend:f,onKeyPress:E,onInputFocus:v,onInputBlur:C,chatEndRef:g,isMuted:y=!1,onToggleMute:d,isSpeaking:h=!1,className:b=""})=>t.jsx("div",{className:`w-full max-w-6xl mx-auto px-4 pb-8 ${b}`,children:t.jsxs("div",{className:"bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg overflow-hidden",children:[t.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800",children:t.jsxs("div",{className:"flex gap-2",children:[t.jsx("input",{value:l,onChange:R=>c(R.target.value),onKeyPress:E,onFocus:v,onBlur:C,placeholder:"Ask Bob about car parts...",disabled:p,className:"flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500"}),d&&t.jsx("button",{onClick:d,className:`shrink-0 p-2 border border-gray-300 dark:border-gray-600 rounded-md ${h?"animate-pulse":""}`,title:y?"Unmute Bob's voice":"Mute Bob's voice",children:y?"🔇":"🔊"}),t.jsx("button",{onClick:f,disabled:p||!l.trim(),className:"shrink-0 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed",children:"Send"})]})}),t.jsxs("div",{className:"overflow-y-auto p-4 space-y-3 h-[300px] md:h-[400px]",children:[[...s].reverse().map((R,j)=>t.jsx("div",{className:`flex ${R.role==="user"?"justify-end":"justify-start"}`,children:t.jsx("div",{className:`max-w-[80%] rounded-lg px-4 py-2 text-sm md:text-base ${R.role==="user"?"bg-blue-600 text-white":"bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-gray-100"}`,children:R.content})},j)),t.jsx("div",{ref:g})]})]})}),yt=({currentImage:s,animationState:l,counterOverlayUrl:c,counterHeightPercent:p=15,scale:f=100,position:E="center"})=>{const v=85*f/100,C=400*f/100,g=E==="center"?"-20%":"-35%";return t.jsxs("div",{className:"absolute inset-0 pointer-events-none overflow-hidden",children:[t.jsx("div",{className:"absolute left-0 z-40",style:{bottom:`${p-2}%`,transform:`translateX(${g})`,width:`${v}%`,maxWidth:`${C}px`,transition:"transform 0.4s ease-out"},children:t.jsx("img",{src:s,alt:`Bob ${l}`,className:"w-full h-auto object-contain",style:{display:"block"}})}),c&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-50",style:{height:`${p}%`},children:t.jsx("img",{src:c,alt:"Shop counter",className:"w-full h-full object-cover object-top"})})]})},dt=(s,l)=>{if(!s||!l)return!1;const c=s.toLowerCase();return l.toLowerCase().replace(/s\b/g,"").split(/\s+/).filter(Boolean).every(f=>c.includes(f))},Ft=(s,l)=>{var f;const c=((f=s.brand)==null?void 0:f.toLowerCase())===l.brand.toLowerCase(),p=Math.abs(s.price-l.price)<1;return c&&p},wt=({products:s,servicePackages:l,highlightedPartType:c,highlightedProduct:p,onProductClick:f,onPackageSelect:E,isResearching:v,visible:C=!0,counterHeightPercent:g=22,hasVehicle:y=!1})=>{const d=r.useRef(null),h=r.useRef({}),b=r.useRef(null),R=r.useMemo(()=>{const a={};return s.forEach(x=>{const o=x.partslotDescription||"Other Parts";a[o]||(a[o]=[]),a[o].push(x)}),Object.keys(a).sort((x,o)=>x.localeCompare(o)).map(x=>({name:x,products:a[x]}))},[s]);r.useEffect(()=>{var a;if(c){const m=R.find(x=>dt(x.name,c));m&&h.current[m.name]&&((a=h.current[m.name])==null||a.scrollIntoView({behavior:"smooth",block:"start"}))}},[c,R]),r.useEffect(()=>{p&&b.current&&b.current.scrollIntoView({behavior:"smooth",block:"center"})},[p]);const j=s.length>0||l.length>0,L=v,S=j&&!v,N=y?"56px":"8px";return t.jsxs("div",{ref:d,className:`absolute right-2 w-[52%] max-w-[220px] overflow-y-auto overflow-x-hidden z-30 flex flex-col gap-2 pb-4 transition-all duration-300 ease-out ${C?"opacity-100 translate-x-0":"opacity-0 translate-x-8 pointer-events-none"}`,style:{top:N,bottom:`calc(${g}% + 16px)`,paddingTop:"env(safe-area-inset-top, 4px)"},children:[L&&t.jsx("div",{className:"rounded-lg p-3",children:t.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[t.jsx("div",{className:"w-4 h-4 border-2 border-blue-600 border-t-transparent rounded-full animate-spin"}),t.jsx("span",{children:"Finding parts..."})]})}),S&&l.length>0&&t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"text-xs font-semibold text-blue-600 flex items-center gap-1 px-1",children:[t.jsx("svg",{className:"h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),"Service Packages"]}),l.map(a=>t.jsxs("div",{onClick:()=>E==null?void 0:E(a),className:"cursor-pointer hover:shadow-md transition-all bg-white/80 rounded-lg border border-gray-200 p-2",children:[t.jsx("p",{className:"text-xs font-medium line-clamp-1",children:a.title}),t.jsxs("p",{className:"text-sm font-bold text-blue-600",children:["$",a.from_price.toFixed(0)]})]},a.id))]}),S&&R.map(({name:a,products:m},x)=>{const o=c&&dt(a,c);return t.jsxs("section",{ref:i=>{h.current[a]=i},className:`rounded-lg transition-all border border-transparent ${o?"ring-2 ring-blue-600 p-2 bg-blue-50/50 shadow-lg":""}`,children:[t.jsxs("h3",{className:"text-xs font-semibold mb-2 flex items-center gap-1 px-1 text-gray-900",children:[t.jsx("svg",{className:"h-3 w-3 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),t.jsx("span",{className:"truncate",children:a}),t.jsxs("span",{className:"text-[10px] text-gray-500",children:["(",m.length,")"]})]}),t.jsx("div",{className:"space-y-2",children:m.map((i,_)=>{const k=p&&Ft(i,p);return t.jsxs("div",{ref:k?b:void 0,onClick:()=>f==null?void 0:f(i),className:`cursor-pointer transition-all bg-white/80 rounded-lg border border-gray-200 relative ${k?"ring-4 ring-blue-600 scale-105 z-10":"hover:shadow-md"}`,children:[k&&t.jsxs("span",{className:"absolute -top-2 -right-2 bg-blue-600 text-white text-[8px] px-1 py-0.5 rounded z-20 flex items-center",children:[t.jsx("svg",{className:"h-2 w-2 mr-0.5",fill:"currentColor",viewBox:"0 0 20 20",children:t.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"})}),"Pick"]}),t.jsxs("div",{className:"p-2",children:[t.jsx("div",{className:"aspect-square bg-gray-100 rounded-md mb-1 flex items-center justify-center overflow-hidden",children:i.image_url?t.jsx("img",{src:i.image_url,alt:i.name,className:"w-full h-full object-contain"}):t.jsx("svg",{className:"h-8 w-8 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),t.jsx("p",{className:"text-xs font-medium line-clamp-2",children:i.name}),i.brand&&t.jsx("p",{className:"text-[10px] text-gray-500",children:i.brand})]}),t.jsx("div",{className:"px-2 pb-2",children:t.jsx("span",{className:"text-sm font-bold text-blue-600",children:i.price>0?`$${i.price.toFixed(2)}`:"Price on request"})}),t.jsx("div",{className:"px-2 pb-2",children:t.jsx("button",{className:"w-full bg-blue-600 text-white text-xs py-1.5 rounded-md hover:bg-blue-700",onClick:O=>{O.stopPropagation(),f==null||f(i)},children:"Buy Now"})})]},`${i.id}-${_}`)})})]},a)})]})},_t=({onTranscript:s,onSpeechEnd:l,language:c="en-NZ",mode:p="toggle"}={})=>{const[f,E]=r.useState(!1),[v,C]=r.useState(""),[g,y]=r.useState(""),[d,h]=r.useState(null),[b,R]=r.useState(!1),j=r.useRef(null),L=r.useRef(""),S=r.useRef(s),N=r.useRef(l);r.useEffect(()=>{S.current=s,N.current=l},[s,l]),r.useEffect(()=>{const o=window.SpeechRecognition||window.webkitSpeechRecognition;if(o){R(!0);const i=new o;i.continuous=p==="ptt",i.interimResults=!0,i.lang=c,i.maxAlternatives=1,i.onstart=()=>{E(!0),h(null)},i.onresult=_=>{let k="",O="";for(let B=_.resultIndex;B<_.results.length;B++){const w=_.results[B][0].transcript;_.results[B].isFinal?O+=w:k+=w}O&&(L.current=O,C(O),S.current&&S.current(O)),y(k)},i.onerror=_=>{switch(E(!1),_.error){case"no-speech":h("No speech detected. Please try again.");break;case"audio-capture":h("No microphone found. Please check your device.");break;case"not-allowed":h("Microphone permission denied. Please allow access.");break;default:h("Speech recognition error. Please try again.")}},i.onend=()=>{E(!1),y(""),L.current&&N.current&&N.current(L.current),L.current=""},j.current=i}return()=>{j.current&&j.current.stop()}},[c,p]);const a=()=>{j.current&&!f&&(C(""),y(""),h(null),j.current.start())},m=()=>{j.current&&f&&j.current.stop()};return{isListening:f,transcript:v,interimTranscript:g,error:d,isSupported:b,startListening:a,stopListening:m,toggleListening:()=>{f?m():a()}}},Et=({messages:s,input:l,setInput:c,isLoading:p,onSend:f,onKeyPress:E,onInputFocus:v,onInputBlur:C,chatEndRef:g,isMuted:y=!1,onToggleMute:d,isSpeaking:h=!1})=>{const[b,R]=r.useState(!1),j=r.useRef(null),L=r.useRef(!1),{isListening:S,interimTranscript:N,error:a,isSupported:m,startListening:x,stopListening:o}=_t({onTranscript:B=>c(B),language:"en-NZ",mode:"ptt"});r.useEffect(()=>{N&&c(N)},[N,c]);const i=r.useCallback(()=>{p||L.current||(L.current=!0,navigator.vibrate&&navigator.vibrate(10),x())},[p,x]),_=r.useCallback(()=>{L.current&&(L.current=!1,navigator.vibrate&&navigator.vibrate(10),o(),setTimeout(()=>{f()},150))},[o,f]),k=[...s].reverse().find(B=>B.role==="assistant"),O=k!=null&&k.content?k.content.length>50?k.content.slice(0,50)+"...":k.content:"Ask Bob about car parts...";return t.jsxs("div",{ref:j,className:`fixed bottom-0 left-0 right-0 bg-white/95 backdrop-blur-md border-t border-gray-200 transition-all duration-300 ease-out shadow-[0_-4px_20px_rgba(0,0,0,0.15)] ${b?"h-[55vh]":"h-auto"}`,style:{zIndex:60,paddingBottom:"env(safe-area-inset-bottom, 8px)"},children:[t.jsx("button",{onClick:()=>R(!b),className:"absolute -top-5 left-1/2 -translate-x-1/2 bg-white border border-gray-200 rounded-full p-1.5 shadow-lg z-40","aria-label":b?"Collapse chat":"Expand chat",children:b?t.jsx("svg",{className:"h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}):t.jsx("svg",{className:"h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 15l7-7 7 7"})})}),!b&&t.jsx("div",{className:"px-3 pt-2 pb-0.5",onClick:()=>R(!0),children:t.jsx("p",{className:"text-xs text-gray-500 line-clamp-1",children:O})}),b&&t.jsxs("div",{className:"h-[calc(100%-100px)] overflow-y-auto p-4 space-y-2",children:[[...s].reverse().map((B,w)=>t.jsx("div",{className:`flex ${B.role==="user"?"justify-end":"justify-start"}`,children:t.jsx("div",{className:`max-w-[85%] rounded-lg px-3 py-2 text-sm ${B.role==="user"?"bg-blue-600 text-white":"bg-gray-100 text-gray-900"}`,children:B.content})},w)),t.jsx("div",{ref:g})]}),t.jsxs("div",{className:`px-2 pb-1.5 ${b?"pt-2 border-t border-gray-200":"pt-0.5"}`,children:[S&&t.jsxs("div",{className:"mb-2 text-xs text-gray-500 flex items-center gap-2",children:[t.jsx("span",{className:"inline-block w-2 h-2 bg-red-500 rounded-full animate-pulse"}),"Listening..."]}),a&&t.jsx("div",{className:"mb-2 text-xs text-red-500",children:a}),t.jsxs("div",{className:"flex gap-1.5 items-center",children:[d&&b&&t.jsx("button",{onClick:d,className:`shrink-0 h-9 w-9 flex items-center justify-center rounded-md hover:bg-gray-100 ${h?"text-blue-600 animate-pulse":"text-gray-600"}`,title:y?"Unmute":"Mute",children:y?t.jsxs("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t.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"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.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"})})}),t.jsx("input",{type:"text",value:l,onChange:B=>c(B.target.value),onKeyPress:E,onFocus:v,onBlur:C,placeholder:"Message Bob...",disabled:p,className:"flex-1 h-10 text-base px-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"}),m&&t.jsx("button",{onTouchStart:i,onTouchEnd:_,onTouchCancel:_,onMouseDown:i,onMouseUp:_,onMouseLeave:_,disabled:p,className:`shrink-0 h-12 w-12 rounded-full flex items-center justify-center select-none touch-none ${S?"bg-red-500 text-white animate-pulse ring-2 ring-red-300 scale-110":"bg-blue-600 text-white"} disabled:opacity-50`,title:"Hold to talk",children:t.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,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"})})})]})]})]})},Tt=({currentImage:s,animationState:l,backdropUrl:c,counterOverlayUrl:p,counterHeightPercent:f=22,messages:E,input:v,setInput:C,isLoading:g,onSend:y,onKeyPress:d,onInputFocus:h,onInputBlur:b,chatEndRef:R,isMuted:j,onToggleMute:L,isSpeaking:S,products:N,servicePackages:a,highlightedPartType:m,highlightedProduct:x,onProductClick:o,onPackageSelect:i,isResearching:_,vehicle:k,onChangeVehicle:O})=>{const B=typeof window<"u"&&window.self!==window.top,[w,$]=r.useState("center"),[D,I]=r.useState("hidden"),Y=N.length>0||a.length>0;r.useEffect(()=>{if(_&&D!=="loading"&&D!=="visible")I("loading"),w==="center"&&$("left");else if(Y&&D!=="visible")if(w==="center"){$("left"),I("transitioning");const W=setTimeout(()=>{I("visible")},400);return()=>clearTimeout(W)}else I("visible");else!Y&&!_&&D!=="hidden"&&(I("hidden"),$("center"))},[Y,_,D,w]);const fe=D!=="hidden";return t.jsxs("div",{className:"fixed inset-0 overflow-hidden",style:{height:"100dvh",touchAction:"manipulation"},children:[c&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"absolute inset-0 z-0",style:{backgroundImage:`url(${c})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:"blur(12px) brightness(0.7)",transform:"scale(1.1)"}}),t.jsx("div",{className:"absolute inset-0 z-[1]",style:{background:"linear-gradient(to bottom, rgba(255,255,255,0.3) 0%, rgba(255,255,255,0.6) 100%)"}})]}),t.jsx(yt,{currentImage:s,animationState:l,counterOverlayUrl:p,counterHeightPercent:f,scale:200,position:w}),k&&!B&&t.jsx("div",{className:"absolute top-2 left-2 right-2 z-20",children:t.jsxs("div",{className:"bg-white/90 backdrop-blur-sm rounded-lg px-3 py-2 border border-gray-200 shadow-lg flex items-center justify-between",style:{paddingTop:"calc(env(safe-area-inset-top, 4px) + 8px)"},children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("p",{className:"text-xs font-medium text-gray-900 truncate",children:[k.year," ",k.make," ",k.model]}),k.rego&&t.jsx("p",{className:"text-[10px] text-gray-500",children:k.rego})]}),O&&t.jsx("button",{onClick:O,className:"text-xs text-blue-600 hover:underline ml-2 shrink-0",children:"Change"})]})}),t.jsx(wt,{products:N,servicePackages:a,highlightedPartType:m,highlightedProduct:x,onProductClick:o,onPackageSelect:i,isResearching:_,visible:fe,counterHeightPercent:f,hasVehicle:!!k}),t.jsx(Et,{messages:E,input:v,setInput:C,isLoading:g,onSend:y,onKeyPress:d,onInputFocus:h,onInputBlur:b,chatEndRef:R,isMuted:j,onToggleMute:L,isSpeaking:S})]})},Wt=({variant:s="inline",initialState:l="idle",showChat:c=!0,className:p="",backdropUrl:f,counterOverlayUrl:E,counterHeightPercent:v,defaultBobImage:C,verticalOffset:g=0,scale:y=100})=>{const{callbacks:d}=we(),{animationState:h,setAnimationState:b,getCurrentImage:R,availableStates:j,isLoading:L}=gt(),{activeBackdrop:S}=mt(),[N,a]=r.useState([]),[m,x]=r.useState([]),[o,i]=r.useState(null),[_,k]=r.useState(null),[O,B]=r.useState(!1),w=ht({setAnimationState:b,manualMode:!1,onReadyToSpeak:()=>{console.log("[BobWidget] Ready to speak")},onStreamComplete:()=>{b(j.find(W=>W.includes("idle"))||"idle")},onResearchStart:()=>{B(!0)},onHighlightPart:W=>{i(W),setTimeout(()=>i(null),8e3)},onHighlightProduct:W=>{k(W),setTimeout(()=>k(null),8e3)},onAutoFetchComplete:()=>{B(!1)}});r.useEffect(()=>{const W=d.onPartsFound,X=d.onServicePackagesFound;return d.onPartsFound=Z=>{B(!1);const he=Z.map((U,_e)=>({id:U.SKU||U.sku||`part-${_e}`,name:U["Part Product Type"]||U.partslot_description||"Unknown Part",brand:U.Brand||U.brand,price:U["Metro Retail Price"]||U.price||0,sku:U.SKU||U.sku,partNumber:U["Part Number"]||U.part_number,partslotDescription:U["Part Product Type"]||U.partslot_description,image_url:U.image_url}));a(he),W==null||W(Z)},d.onServicePackagesFound=Z=>{x(Z),X==null||X(Z)},()=>{d.onPartsFound=W,d.onServicePackagesFound=X}},[d]);const $=f||(S==null?void 0:S.image_url),D=E||(S==null?void 0:S.counter_overlay_url)||void 0,I=v||(S==null?void 0:S.counter_height_percent)||12,Y=R()||C||"";if(s==="mobile"||s==="fullscreen")return t.jsx(Tt,{currentImage:Y,animationState:h,backdropUrl:$,counterOverlayUrl:D,counterHeightPercent:I,messages:w.messages,input:w.input,setInput:w.setInput,isLoading:w.isLoading,onSend:w.handleSend,onKeyPress:w.handleKeyPress,onInputFocus:w.handleInputFocus,onInputBlur:w.handleInputBlur,chatEndRef:w.chatEndRef,isMuted:w.isMuted,onToggleMute:w.toggleMute,isSpeaking:w.isSpeaking,products:N,servicePackages:m,highlightedPartType:o,highlightedProduct:_,onProductClick:W=>{var X;return(X=d.onAddToCart)==null?void 0:X.call(d,{product_id:W.id,product_name:W.name,quantity:1,unit_price:W.price,sku:W.sku,brand:W.brand})},onPackageSelect:W=>console.log("[BobWidget] Package selected:",W),isResearching:O,vehicle:w.identifiedVehicle});const fe={inline:"",floating:"fixed bottom-4 right-4 w-96 z-50 shadow-2xl rounded-lg overflow-hidden",fullscreen:"fixed inset-0 z-50 bg-black/80",mobile:""};return t.jsxs("div",{className:`${fe[s]} ${p}`,children:[Y&&t.jsx(vt,{currentImage:Y,animationState:h,backdropUrl:$,counterOverlayUrl:D,counterHeightPercent:I,verticalOffset:g,scale:y}),c&&t.jsx(xt,{messages:w.messages,input:w.input,setInput:w.setInput,isLoading:w.isLoading,onSend:w.handleSend,onKeyPress:w.handleKeyPress,onInputFocus:w.handleInputFocus,onInputBlur:w.handleInputBlur,chatEndRef:w.chatEndRef,isMuted:w.isMuted,onToggleMute:w.toggleMute,isSpeaking:w.isSpeaking})]})},Vt=6e4,Ut=({states:s,setAnimationState:l,manualMode:c})=>{const[p,f]=r.useState("page_load"),[E,v]=r.useState(!1),C=r.useRef(null),g=r.useCallback(o=>s.find(i=>i.chat_trigger===o&&i.is_active),[s]),y=r.useCallback(()=>s.find(o=>o.chat_trigger==="awaiting_input"||o.state_key==="talk_pause"||o.title.toLowerCase().includes("listen")||o.title.toLowerCase().includes("pause")),[s]),d=r.useCallback(()=>s.find(o=>o.state_key==="idle"||o.title.toLowerCase().includes("idle")),[s]),h=r.useCallback(o=>{const i=s.find(_=>_.state_key===o);return{speed:(i==null?void 0:i.animation_speed)||400,pauseDuration:(i==null?void 0:i.pause_duration)||0,loopCount:(i==null?void 0:i.loop_count)||0}},[s]),b=r.useCallback(()=>{C.current&&(clearTimeout(C.current),C.current=null)},[]),R=r.useCallback(()=>{b(),!c&&(C.current=setTimeout(()=>{const o=d();o&&(f("idle"),l(o.state_key))},Vt))},[c,d,l,b]),j=r.useCallback(o=>{if(c)return;const i=g(o);i&&l(i.state_key)},[c,g,l]),L=r.useCallback(()=>{if(c)return;const o=y();o&&(f("awaiting_input"),l(o.state_key),R())},[c,y,l,R]),S=r.useCallback(()=>{E||c||(v(!0),f("page_load"),j("page_load"),setTimeout(()=>{L()},3e3))},[E,c,j,L]),N=r.useCallback(()=>{b(),f("processing_input"),j("processing_input")},[j,b]),a=r.useCallback(()=>{b(),f("streaming_response"),j("streaming_response")},[j,b]),m=r.useCallback(()=>{f("response_complete"),j("response_complete"),setTimeout(()=>{L()},3e3)},[j,L]),x=r.useCallback(()=>{f("showing_product");const o=s.find(i=>i.chat_trigger==="showing_product"||i.state_key==="showing_product");o&&l(o.state_key),setTimeout(()=>{L()},4e3)},[s,l,L]);return r.useEffect(()=>()=>b(),[b]),{chatStage:p,initialize:S,onUserInput:N,onStreamStart:a,onStreamComplete:m,onShowingProduct:x,getStateSettings:h}};exports.BOB_VERSION=st;exports.Bob=Wt;exports.BobCharacter=vt;exports.BobProvider=Pt;exports.ChatInterface=xt;exports.MobileBobCharacter=yt;exports.MobileBobLayout=Tt;exports.MobileChatDrawer=Et;exports.MobileProductColumn=wt;exports.getBobVersion=Nt;exports.useBobAnimation=gt;exports.useBobAnimationData=bt;exports.useBobBackdrop=mt;exports.useBobCallbacks=Mt;exports.useBobChat=ht;exports.useBobContext=we;exports.useBobStateTransitions=Ut;exports.useBobSupabase=at;exports.useHostApiConfig=At;exports.useHostContext=Lt;exports.useSpeechRecognition=_t;exports.useSpeechSynthesis=pt;