@gymmymac/bob-widget 3.2.2 → 3.2.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/CHANGELOG.md CHANGED
@@ -5,6 +5,13 @@ All notable changes to the `@gymmymac/bob-widget` package will be documented in
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [v3.2.3] - 2026-02-16
9
+
10
+ ### Fixed
11
+ - 🎨 **Chat Drawer Background Bleed-Through**: Increased chat drawer background opacity to `rgba(15, 23, 42, 0.92)` in both `ContainedChatDrawer` and `MobileChatDrawer` — prevents host-site orange/coloured backgrounds from bleeding through and tinting the PTT button and chat input
12
+
13
+ ---
14
+
8
15
  ## [v3.2.2] - 2026-02-15
9
16
 
10
17
  ### Fixed
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Vn=t=>{throw TypeError(t)};var Gs=(t,e,r)=>e.has(t)||Vn("Cannot "+r);var S=(t,e,r)=>(Gs(t,e,"read from private field"),r?r.call(t):e.get(t)),re=(t,e,r)=>e.has(t)?Vn("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),q=(t,e,r,s)=>(Gs(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),ue=(t,e,r)=>(Gs(t,e,"access private method"),r);var Ss=(t,e,r,s)=>({set _(n){q(t,e,n,r)},get _(){return S(t,e,s)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("react");function Ya(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,s.get?s:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const st=Ya(g),St="3.2.2",Xa=()=>St;var an={exports:{}},Vr={};/**
1
+ "use strict";var Vn=t=>{throw TypeError(t)};var Gs=(t,e,r)=>e.has(t)||Vn("Cannot "+r);var S=(t,e,r)=>(Gs(t,e,"read from private field"),r?r.call(t):e.get(t)),re=(t,e,r)=>e.has(t)?Vn("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),q=(t,e,r,s)=>(Gs(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),ue=(t,e,r)=>(Gs(t,e,"access private method"),r);var Ss=(t,e,r,s)=>({set _(n){q(t,e,n,r)},get _(){return S(t,e,s)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("react");function Ya(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,s.get?s:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const st=Ya(g),St="3.2.3",Xa=()=>St;var an={exports:{}},Vr={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.min.js
4
4
  *
@@ -72,7 +72,7 @@ ${y}`}class Ie extends Error{constructor({message:e,code:r,cause:s,name:n}){var
72
72
  `);const A=await w.signMessage(new TextEncoder().encode(v),"utf8");if(!A||!(A instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=A}}try{const{data:b,error:y}=await se(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:v,signature:tr(m)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:at});if(y)throw y;if(!b||!b.session||!b.user){const _=new vr;return this._returnResult({data:{user:null,session:null},error:_})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:y})}catch(b){if(G(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async _exchangeCodeForSession(e){const r=await Yt(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new gl;const{data:i,error:a}=await se(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:at});if(await $e(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){const l=new vr;return this._returnResult({data:{user:null,session:null,redirectType:null},error:l})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:a})}catch(i){if(await $e(this.storage,`${this.storageKey}-code-verifier`),G(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:a}=e,l=await se(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:at}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){const d=new vr;return this._returnResult({data:{user:null,session:null},error:d})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(r){if(G(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,a;try{if("email"in e){const{email:l,options:c}=e;let u=null,d=null;this.flowType==="pkce"&&([u,d]=await wr(this.storage,this.storageKey));const{error:h}=await se(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(r=c==null?void 0:c.data)!==null&&r!==void 0?r:{},create_user:(s=c==null?void 0:c.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:c==null?void 0:c.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:l,options:c}=e,{data:u,error:d}=await se(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(n=c==null?void 0:c.data)!==null&&n!==void 0?n:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(a=c==null?void 0:c.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:d})}throw new Cs("You must provide either an email or phone number.")}catch(l){if(await $e(this.storage,`${this.storageKey}-code-verifier`),G(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:a,error:l}=await se(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:at});if(l)throw l;if(!a)throw new Error("An error occurred on token verification.");const c=a.session,u=a.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(n){if(G(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,a;try{let l=null,c=null;this.flowType==="pkce"&&([l,c]=await wr(this.storage,this.storageKey));const u=await se(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e==null?void 0:e.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:Ul});return!((i=u.data)===null||i===void 0)&&i.url&&De()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await $e(this.storage,`${this.storageKey}-code-verifier`),G(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new Xe;const{error:n}=await se(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(G(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:i}=e,{error:a}=await se(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in e){const{phone:s,type:n,options:i}=e,{data:a,error:l}=await se(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:l})}throw new Cs("You must provide either an email or phone number and a type")}catch(r){if(G(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await Yt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<Ys:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await Yt(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=en()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=Fl(e.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await se(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Lt}):await this._useSession(async r=>{var s,n,i;const{data:a,error:l}=r;if(l)throw l;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Xe}:await se(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:Lt})})}catch(r){if(G(r))return Xs(r)&&(await this._removeSession(),await $e(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async s=>{const{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new Xe;const a=n.session;let l=null,c=null;this.flowType==="pkce"&&e.email!=null&&([l,c]=await wr(this.storage,this.storageKey));const{data:u,error:d}=await se(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:c}),jwt:a.access_token,xform:Lt});if(d)throw d;return a.user=u.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(s){if(await $e(this.storage,`${this.storageKey}-code-verifier`),G(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Xe;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=Os(e.access_token);if(a.exp&&(s=a.exp,n=s<=r),n){const{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{const{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(G(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:a,error:l}=r;if(l)throw l;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new Xe;const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(G(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!De())throw new As("No browser detected.");if(e.error||e.error_description||e.error_code)throw new As(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new oi("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new As("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new oi("No code detected.");const{data:_,error:k}=await this._exchangeCodeForSession(e.code);if(k)throw k;const w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.toString()),{data:{session:_.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:a,expires_in:l,expires_at:c,token_type:u}=e;if(!i||!l||!a||!u)throw new As("No session defined in URL");const d=Math.round(Date.now()/1e3),h=parseInt(l);let f=d+h;c&&(f=parseInt(c));const p=f-d;p*1e3<=jr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const v=f-h;d-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,f,d):d-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",v,f,d);const{data:m,error:b}=await this._getUser(i);if(b)throw b;const y={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:h,expires_at:f,refresh_token:a,token_type:u,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(s){if(G(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await Yt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i&&!Xs(i))return this._returnResult({error:i});const a=(s=n.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:l}=await this.admin.signOut(a,e);if(l&&!(fl(l)&&(l.status===404||l.status===401||l.status===403)||Xs(l)))return this._returnResult({error:l})}return e!=="others"&&(await this._removeSession(),await $e(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=_l(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{const{data:{session:i},error:a}=r;if(a)throw a;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await wr(this.storage,this.storageKey,!0));try{return await se(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await $e(this.storage,`${this.storageKey}-code-verifier`),G(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(G(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:s,error:n}=await this._useSession(async i=>{var a,l,c,u,d;const{data:h,error:f}=i;if(f)throw f;const p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await se(this.fetch,"GET",p,{headers:this.headers,jwt:(d=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(n)throw n;return De()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:e.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(G(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:a,provider:l,token:c,access_token:u,nonce:d}=e,h=await se(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i==null?void 0:i.access_token)!==null&&s!==void 0?s:void 0,body:{provider:l,id_token:c,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:at}),{data:f,error:p}=h;return p?this._returnResult({data:{user:null,session:null},error:p}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new vr}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:p}))}catch(n){if(await $e(this.storage,`${this.storageKey}-code-verifier`),G(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)throw a;return await se(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(G(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const s=Date.now();return await jl(async n=>(n>0&&await El(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await se(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:at})),(n,i)=>{const a=200*Math.pow(2,n);return i&&Zs(i)&&Date.now()+a-s<jr})}catch(s){if(this._debug(r,"error",s),G(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),De()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await Yt(this.storage,this.storageKey);if(n&&this.userStorage){let a=await Yt(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await Tr(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:en()}else if(n&&!n.user&&!n.user){const a=await Yt(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(n.user=a.user,await $e(this.storage,this.storageKey+"-user"),await Tr(this.storage,this.storageKey,n)):n.user=en()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Ys;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${Ys}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),Zs(a)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:l}=await this._getUser(n.access_token);!l&&(a!=null&&a.user)?(n.user=a.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new Xe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Ws;const{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new Xe;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const l={data:i.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(i){if(this._debug(n,"error",i),G(i)){const a={data:null,error:i};return Zs(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],a=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,r)}catch(c){i.push(c)}});if(await Promise.all(a),i.length>0){for(let l=0;l<i.length;l+=1)console.error(i[l]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await $e(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await Tr(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=hi(n);await Tr(this.storage,this.storageKey,i)}else{const n=hi(r);await Tr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await $e(this.storage,this.storageKey),await $e(this.storage,this.storageKey+"-code-verifier"),await $e(this.storage,this.storageKey+"-user"),this.userStorage&&await $e(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&De()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),jr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/jr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${jr}ms, refresh threshold is ${fn} ticks`),n<=fn&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof oa)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!De()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){const n=[`provider=${encodeURIComponent(r)}`];if(s!=null&&s.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,a]=await wr(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});n.push(l.toString())}if(s!=null&&s.queryParams){const i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s!=null&&s.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await se(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(G(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await se(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((n=c==null?void 0:c.totp)===null||n===void 0)&&n.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(G(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?rc(e.webauthn.credential_response):sc(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:c}=await se(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:c}))})}catch(r){if(G(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const a=await se(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});if(a.error)return a;const{data:l}=a;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:ec(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:tc(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(G(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{const{payload:p}=Os(e);let v=null;p.aal&&(v=p.aal);let m=v;const{data:{user:b},error:y}=await this.getUser(e);if(y)return this._returnResult({data:null,error:y});((s=(r=b==null?void 0:b.factors)===null||r===void 0?void 0:r.filter(w=>w.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(m="aal2");const k=p.amr||[];return{data:{currentLevel:v,nextLevel:m,currentAuthenticationMethods:k},error:null}}catch(p){if(G(p))return this._returnResult({data:null,error:p});throw p}const{data:{session:a},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=Os(a.access_token);let u=null;c.aal&&(u=c.aal);let d=u;((i=(n=a.user.factors)===null||n===void 0?void 0:n.filter(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(d="aal2");const f=c.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await se(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Xe})})}catch(r){if(G(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new Xe});const a=await se(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return a.data&&a.data.redirect_url&&De()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(G(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new Xe});const a=await se(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return a.data&&a.data.redirect_url&&De()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(G(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await se(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new Xe})})}catch(e){if(G(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await se(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Xe})})}catch(r){if(G(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(l=>l.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(l=>l.kid===e),s&&this.jwks_cached_at+dl>n)return s;const{data:i,error:a}=await se(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(l=>l.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:p,error:v}=await this.getSession();if(v||!p.session)return this._returnResult({data:null,error:v});s=p.session.access_token}const{header:n,payload:i,signature:a,raw:{header:l,payload:c}}=Os(s);r!=null&&r.allowExpired||Il(i.exp);const u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!u){const{error:p}=await this.getUser(s);if(p)throw p;return{data:{claims:i,header:n,signature:a},error:null}}const d=Nl(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,a,wl(`${l}.${c}`)))throw new bn("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(G(s))return this._returnResult({data:null,error:s});throw s}}}cs.nextInstanceID={};const hc=cs,fc="2.95.3";let Xr="";typeof Deno<"u"?Xr="deno":typeof document<"u"?Xr="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Xr="react-native":Xr="node";const pc={"X-Client-Info":`supabase-js-${Xr}/${fc}`},gc={headers:pc},bc={schema:"public"},mc={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},yc={};function us(t){"@babel/helpers - typeof";return us=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},us(t)}function vc(t,e){if(us(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(us(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function wc(t){var e=vc(t,"string");return us(e)=="symbol"?e:e+""}function xc(t,e,r){return(e=wc(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function vi(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function Ce(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?vi(Object(r),!0).forEach(function(s){xc(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):vi(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const _c=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),kc=()=>Headers,Sc=(t,e,r)=>{const s=_c(r),n=kc();return async(i,a)=>{var l;const c=(l=await e())!==null&&l!==void 0?l:t;let u=new n(a==null?void 0:a.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),s(i,Ce(Ce({},a),{},{headers:u}))}};function Ec(t){return t.endsWith("/")?t:t+"/"}function jc(t,e){var r,s;const{db:n,auth:i,realtime:a,global:l}=t,{db:c,auth:u,realtime:d,global:h}=e,f={db:Ce(Ce({},c),n),auth:Ce(Ce({},u),i),realtime:Ce(Ce({},d),a),storage:{},global:Ce(Ce(Ce({},h),l),{},{headers:Ce(Ce({},(r=h==null?void 0:h.headers)!==null&&r!==void 0?r:{}),(s=l==null?void 0:l.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function Tc(t){const e=t==null?void 0:t.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Ec(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Rc=class extends hc{constructor(t){super(t)}},Cc=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=Tc(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,l={db:bc,realtime:yc,auth:Ce(Ce({},mc),{},{storageKey:a}),global:gc},c=jc(r??{},l);if(this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(d,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=c.auth)!==null&&u!==void 0?u:{},this.headers,c.global.fetch)}this.fetch=Sc(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Ce({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(d=>this.realtime.setAuth(d)).catch(d=>console.warn("Failed to set initial Realtime auth token:",d)),this.rest=new fo(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new al(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new no(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:a,lock:l,debug:c,throwOnError:u},d,h){const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Rc({url:this.authUrl.href,headers:Ce(Ce({},f),d),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:l,debug:c,throwOnError:u,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(p=>p.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Ao(this.realtimeUrl.href,Ce(Ce({},t),{},{params:Ce(Ce({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const mn=(t,e,r)=>new Cc(t,e,r);function Ac(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}Ac()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var ws=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Oc={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},pt,sr,$i,Pc=($i=class{constructor(){re(this,pt,Oc);re(this,sr,!1)}setTimeoutProvider(t){process.env.NODE_ENV!=="production"&&S(this,sr)&&t!==S(this,pt)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:S(this,pt),provider:t}),q(this,pt,t),process.env.NODE_ENV!=="production"&&q(this,sr,!1)}setTimeout(t,e){return process.env.NODE_ENV!=="production"&&q(this,sr,!0),S(this,pt).setTimeout(t,e)}clearTimeout(t){S(this,pt).clearTimeout(t)}setInterval(t,e){return process.env.NODE_ENV!=="production"&&q(this,sr,!0),S(this,pt).setInterval(t,e)}clearInterval(t){S(this,pt).clearInterval(t)}},pt=new WeakMap,sr=new WeakMap,$i),rr=new Pc;function Ic(t){setTimeout(t,0)}var fr=typeof window>"u"||"Deno"in globalThis;function Ve(){}function Nc(t,e){return typeof t=="function"?t(e):t}function yn(t){return typeof t=="number"&&t>=0&&t!==1/0}function ua(t,e){return Math.max(t+(e||0)-Date.now(),0)}function Ht(t,e){return typeof t=="function"?t(e):t}function rt(t,e){return typeof t=="function"?t(e):t}function wi(t,e){const{type:r="all",exact:s,fetchStatus:n,predicate:i,queryKey:a,stale:l}=t;if(a){if(s){if(e.queryHash!==Fn(a,e.options))return!1}else if(!hs(e.queryKey,a))return!1}if(r!=="all"){const c=e.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof l=="boolean"&&e.isStale()!==l||n&&n!==e.state.fetchStatus||i&&!i(e))}function xi(t,e){const{exact:r,status:s,predicate:n,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(r){if(ds(e.options.mutationKey)!==ds(i))return!1}else if(!hs(e.options.mutationKey,i))return!1}return!(s&&e.state.status!==s||n&&!n(e))}function Fn(t,e){return((e==null?void 0:e.queryKeyHashFn)||ds)(t)}function ds(t){return JSON.stringify(t,(e,r)=>xn(r)?Object.keys(r).sort().reduce((s,n)=>(s[n]=r[n],s),{}):r)}function hs(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>hs(t[r],e[r])):!1}var Bc=Object.prototype.hasOwnProperty;function vn(t,e,r=0){if(t===e)return t;if(r>500)return e;const s=_i(t)&&_i(e);if(!s&&!(xn(t)&&xn(e)))return e;const i=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),l=a.length,c=s?new Array(l):{};let u=0;for(let d=0;d<l;d++){const h=s?d:a[d],f=t[h],p=e[h];if(f===p){c[h]=f,(s?d<i:Bc.call(t,h))&&u++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){c[h]=p;continue}const v=vn(f,p,r+1);c[h]=v,v===f&&u++}return i===l&&u===i?t:c}function wn(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(const r in t)if(t[r]!==e[r])return!1;return!0}function _i(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function xn(t){if(!ki(t))return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(!ki(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function ki(t){return Object.prototype.toString.call(t)==="[object Object]"}function Fc(t){return new Promise(e=>{rr.setTimeout(e,t)})}function _n(t,e,r){if(typeof r.structuralSharing=="function")return r.structuralSharing(t,e);if(r.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return vn(t,e)}catch(s){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${r.queryHash}]: ${s}`),s}return vn(t,e)}return e}function Lc(t,e,r=0){const s=[...t,e];return r&&s.length>r?s.slice(1):s}function $c(t,e,r=0){const s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}var Fs=Symbol();function da(t,e){return process.env.NODE_ENV!=="production"&&t.queryFn===Fs&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${t.queryHash}'`),!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===Fs?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function ha(t,e){return typeof t=="function"?t(...e):!!t}function Dc(t,e,r){let s=!1,n;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(n??(n=e()),s||(s=!0,n.aborted?r():n.addEventListener("abort",r,{once:!0})),n)}),t}var nr,$t,Ar,Di,Uc=(Di=class extends ws{constructor(){super();re(this,nr);re(this,$t);re(this,Ar);q(this,Ar,e=>{if(!fr&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){S(this,$t)||this.setEventListener(S(this,Ar))}onUnsubscribe(){var e;this.hasListeners()||((e=S(this,$t))==null||e.call(this),q(this,$t,void 0))}setEventListener(e){var r;q(this,Ar,e),(r=S(this,$t))==null||r.call(this),q(this,$t,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){S(this,nr)!==e&&(q(this,nr,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof S(this,nr)=="boolean"?S(this,nr):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},nr=new WeakMap,$t=new WeakMap,Ar=new WeakMap,Di),Ln=new Uc;function kn(){let t,e;const r=new Promise((n,i)=>{t=n,e=i});r.status="pending",r.catch(()=>{});function s(n){Object.assign(r,n),delete r.resolve,delete r.reject}return r.resolve=n=>{s({status:"fulfilled",value:n}),t(n)},r.reject=n=>{s({status:"rejected",reason:n}),e(n)},r}var Mc=Ic;function Wc(){let t=[],e=0,r=l=>{l()},s=l=>{l()},n=Mc;const i=l=>{e?t.push(l):n(()=>{r(l)})},a=()=>{const l=t;t=[],l.length&&n(()=>{s(()=>{l.forEach(c=>{r(c)})})})};return{batch:l=>{let c;e++;try{c=l()}finally{e--,e||a()}return c},batchCalls:l=>(...c)=>{i(()=>{l(...c)})},schedule:i,setNotifyFunction:l=>{r=l},setBatchNotifyFunction:l=>{s=l},setScheduler:l=>{n=l}}}var Ue=Wc(),Or,Dt,Pr,Ui,qc=(Ui=class extends ws{constructor(){super();re(this,Or,!0);re(this,Dt);re(this,Pr);q(this,Pr,e=>{if(!fr&&window.addEventListener){const r=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",s)}}})}onSubscribe(){S(this,Dt)||this.setEventListener(S(this,Pr))}onUnsubscribe(){var e;this.hasListeners()||((e=S(this,Dt))==null||e.call(this),q(this,Dt,void 0))}setEventListener(e){var r;q(this,Pr,e),(r=S(this,Dt))==null||r.call(this),q(this,Dt,e(this.setOnline.bind(this)))}setOnline(e){S(this,Or)!==e&&(q(this,Or,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return S(this,Or)}},Or=new WeakMap,Dt=new WeakMap,Pr=new WeakMap,Ui),Ls=new qc;function zc(t){return Math.min(1e3*2**t,3e4)}function fa(t){return(t??"online")==="online"?Ls.isOnline():!0}var Sn=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function pa(t){let e=!1,r=0,s;const n=kn(),i=()=>n.status!=="pending",a=m=>{var b;if(!i()){const y=new Sn(m);f(y),(b=t.onCancel)==null||b.call(t,y)}},l=()=>{e=!0},c=()=>{e=!1},u=()=>Ln.isFocused()&&(t.networkMode==="always"||Ls.isOnline())&&t.canRun(),d=()=>fa(t.networkMode)&&t.canRun(),h=m=>{i()||(s==null||s(),n.resolve(m))},f=m=>{i()||(s==null||s(),n.reject(m))},p=()=>new Promise(m=>{var b;s=y=>{(i()||u())&&m(y)},(b=t.onPause)==null||b.call(t)}).then(()=>{var m;s=void 0,i()||(m=t.onContinue)==null||m.call(t)}),v=()=>{if(i())return;let m;const b=r===0?t.initialPromise:void 0;try{m=b??t.fn()}catch(y){m=Promise.reject(y)}Promise.resolve(m).then(h).catch(y=>{var A;if(i())return;const _=t.retry??(fr?0:3),k=t.retryDelay??zc,w=typeof k=="function"?k(r,y):k,E=_===!0||typeof _=="number"&&r<_||typeof _=="function"&&_(r,y);if(e||!E){f(y);return}r++,(A=t.onFail)==null||A.call(t,r,y),Fc(w).then(()=>u()?void 0:p()).then(()=>{e?f(y):v()})})};return{promise:n,status:()=>n.status,cancel:a,continue:()=>(s==null||s(),n),cancelRetry:l,continueRetry:c,canStart:d,start:()=>(d()?v():p().then(v),n)}}var ir,Mi,ga=(Mi=class{constructor(){re(this,ir)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),yn(this.gcTime)&&q(this,ir,rr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(fr?1/0:5*60*1e3))}clearGcTimeout(){S(this,ir)&&(rr.clearTimeout(S(this,ir)),q(this,ir,void 0))}},ir=new WeakMap,Mi),ar,Ir,tt,or,Le,ps,lr,ct,wt,Wi,Hc=(Wi=class extends ga{constructor(e){super();re(this,ct);re(this,ar);re(this,Ir);re(this,tt);re(this,or);re(this,Le);re(this,ps);re(this,lr);q(this,lr,!1),q(this,ps,e.defaultOptions),this.setOptions(e.options),this.observers=[],q(this,or,e.client),q(this,tt,S(this,or).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,q(this,ar,Ei(this.options)),this.state=e.state??S(this,ar),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=S(this,Le))==null?void 0:e.promise}setOptions(e){if(this.options={...S(this,ps),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=Ei(this.options);r.data!==void 0&&(this.setState(Si(r.data,r.dataUpdatedAt)),q(this,ar,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&S(this,tt).remove(this)}setData(e,r){const s=_n(this.state.data,e,this.options);return ue(this,ct,wt).call(this,{data:s,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),s}setState(e,r){ue(this,ct,wt).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var s,n;const r=(s=S(this,Le))==null?void 0:s.promise;return(n=S(this,Le))==null||n.cancel(e),r?r.then(Ve).catch(Ve):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(S(this,ar))}isActive(){return this.observers.some(e=>rt(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Fs||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ht(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!ua(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(s=>s.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=S(this,Le))==null||r.continue()}onOnline(){var r;const e=this.observers.find(s=>s.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=S(this,Le))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),S(this,tt).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(S(this,Le)&&(S(this,lr)?S(this,Le).cancel({revert:!0}):S(this,Le).cancelRetry()),this.scheduleGc()),S(this,tt).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||ue(this,ct,wt).call(this,{type:"invalidate"})}async fetch(e,r){var c,u,d,h,f,p,v,m,b,y,_,k;if(this.state.fetchStatus!=="idle"&&((c=S(this,Le))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(S(this,Le))return S(this,Le).continueRetry(),S(this,Le).promise}if(e&&this.setOptions(e),!this.options.queryFn){const w=this.observers.find(E=>E.options.queryFn);w&&this.setOptions(w.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const s=new AbortController,n=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(q(this,lr,!0),s.signal)})},i=()=>{const w=da(this.options,r),A=(()=>{const F={client:S(this,or),queryKey:this.queryKey,meta:this.meta};return n(F),F})();return q(this,lr,!1),this.options.persister?this.options.persister(w,A,this):w(A)},l=(()=>{const w={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:S(this,or),state:this.state,fetchFn:i};return n(w),w})();(u=this.options.behavior)==null||u.onFetch(l,this),q(this,Ir,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=l.fetchOptions)==null?void 0:d.meta))&&ue(this,ct,wt).call(this,{type:"fetch",meta:(h=l.fetchOptions)==null?void 0:h.meta}),q(this,Le,pa({initialPromise:r==null?void 0:r.initialPromise,fn:l.fetchFn,onCancel:w=>{w instanceof Sn&&w.revert&&this.setState({...S(this,Ir),fetchStatus:"idle"}),s.abort()},onFail:(w,E)=>{ue(this,ct,wt).call(this,{type:"failed",failureCount:w,error:E})},onPause:()=>{ue(this,ct,wt).call(this,{type:"pause"})},onContinue:()=>{ue(this,ct,wt).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const w=await S(this,Le).start();if(w===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(w),(p=(f=S(this,tt).config).onSuccess)==null||p.call(f,w,this),(m=(v=S(this,tt).config).onSettled)==null||m.call(v,w,this.state.error,this),w}catch(w){if(w instanceof Sn){if(w.silent)return S(this,Le).promise;if(w.revert){if(this.state.data===void 0)throw w;return this.state.data}}throw ue(this,ct,wt).call(this,{type:"error",error:w}),(y=(b=S(this,tt).config).onError)==null||y.call(b,w,this),(k=(_=S(this,tt).config).onSettled)==null||k.call(_,this.state.data,w,this),w}finally{this.scheduleGc()}}},ar=new WeakMap,Ir=new WeakMap,tt=new WeakMap,or=new WeakMap,Le=new WeakMap,ps=new WeakMap,lr=new WeakMap,ct=new WeakSet,wt=function(e){const r=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...ba(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,...Si(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return q(this,Ir,e.manual?n:void 0),n;case"error":const i=e.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=r(this.state),Ue.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),S(this,tt).notify({query:this,type:"updated",action:e})})},Wi);function ba(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:fa(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Si(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Ei(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,r=e!==void 0,s=r?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:r?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var Ke,de,gs,ze,cr,Nr,_t,Ut,bs,Br,Fr,ur,dr,Mt,Lr,ge,Zr,En,jn,Tn,Rn,Cn,An,On,ma,qi,Kc=(qi=class extends ws{constructor(e,r){super();re(this,ge);re(this,Ke);re(this,de);re(this,gs);re(this,ze);re(this,cr);re(this,Nr);re(this,_t);re(this,Ut);re(this,bs);re(this,Br);re(this,Fr);re(this,ur);re(this,dr);re(this,Mt);re(this,Lr,new Set);this.options=r,q(this,Ke,e),q(this,Ut,null),q(this,_t,kn()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(S(this,de).addObserver(this),ji(S(this,de),this.options)?ue(this,ge,Zr).call(this):this.updateResult(),ue(this,ge,Rn).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Pn(S(this,de),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Pn(S(this,de),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,ue(this,ge,Cn).call(this),ue(this,ge,An).call(this),S(this,de).removeObserver(this)}setOptions(e){const r=this.options,s=S(this,de);if(this.options=S(this,Ke).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof rt(this.options.enabled,S(this,de))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");ue(this,ge,On).call(this),S(this,de).setOptions(this.options),r._defaulted&&!wn(this.options,r)&&S(this,Ke).getQueryCache().notify({type:"observerOptionsUpdated",query:S(this,de),observer:this});const n=this.hasListeners();n&&Ti(S(this,de),s,this.options,r)&&ue(this,ge,Zr).call(this),this.updateResult(),n&&(S(this,de)!==s||rt(this.options.enabled,S(this,de))!==rt(r.enabled,S(this,de))||Ht(this.options.staleTime,S(this,de))!==Ht(r.staleTime,S(this,de)))&&ue(this,ge,En).call(this);const i=ue(this,ge,jn).call(this);n&&(S(this,de)!==s||rt(this.options.enabled,S(this,de))!==rt(r.enabled,S(this,de))||i!==S(this,Mt))&&ue(this,ge,Tn).call(this,i)}getOptimisticResult(e){const r=S(this,Ke).getQueryCache().build(S(this,Ke),e),s=this.createResult(r,e);return Gc(this,s)&&(q(this,ze,s),q(this,Nr,this.options),q(this,cr,S(this,de).state)),s}getCurrentResult(){return S(this,ze)}trackResult(e,r){return new Proxy(e,{get:(s,n)=>(this.trackProp(n),r==null||r(n),n==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&S(this,_t).status==="pending"&&S(this,_t).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,n))})}trackProp(e){S(this,Lr).add(e)}getCurrentQuery(){return S(this,de)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=S(this,Ke).defaultQueryOptions(e),s=S(this,Ke).getQueryCache().build(S(this,Ke),r);return s.fetch().then(()=>this.createResult(s,r))}fetch(e){return ue(this,ge,Zr).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),S(this,ze)))}createResult(e,r){var U;const s=S(this,de),n=this.options,i=S(this,ze),a=S(this,cr),l=S(this,Nr),u=e!==s?e.state:S(this,gs),{state:d}=e;let h={...d},f=!1,p;if(r._optimisticResults){const j=this.hasListeners(),R=!j&&ji(e,r),T=j&&Ti(e,s,r,n);(R||T)&&(h={...h,...ba(d.data,e.options)}),r._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:v,errorUpdatedAt:m,status:b}=h;p=h.data;let y=!1;if(r.placeholderData!==void 0&&p===void 0&&b==="pending"){let j;i!=null&&i.isPlaceholderData&&r.placeholderData===(l==null?void 0:l.placeholderData)?(j=i.data,y=!0):j=typeof r.placeholderData=="function"?r.placeholderData((U=S(this,Fr))==null?void 0:U.state.data,S(this,Fr)):r.placeholderData,j!==void 0&&(b="success",p=_n(i==null?void 0:i.data,j,r),f=!0)}if(r.select&&p!==void 0&&!y)if(i&&p===(a==null?void 0:a.data)&&r.select===S(this,bs))p=S(this,Br);else try{q(this,bs,r.select),p=r.select(p),p=_n(i==null?void 0:i.data,p,r),q(this,Br,p),q(this,Ut,null)}catch(j){q(this,Ut,j)}S(this,Ut)&&(v=S(this,Ut),p=S(this,Br),m=Date.now(),b="error");const _=h.fetchStatus==="fetching",k=b==="pending",w=b==="error",E=k&&_,A=p!==void 0,N={status:b,fetchStatus:h.fetchStatus,isPending:k,isSuccess:b==="success",isError:w,isInitialLoading:E,isLoading:E,data:p,dataUpdatedAt:h.dataUpdatedAt,error:v,errorUpdatedAt:m,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:_,isRefetching:_&&!k,isLoadingError:w&&!A,isPaused:h.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:w&&A,isStale:$n(e,r),refetch:this.refetch,promise:S(this,_t),isEnabled:rt(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const j=N.data!==void 0,R=N.status==="error"&&!j,T=K=>{R?K.reject(N.error):j&&K.resolve(N.data)},C=()=>{const K=q(this,_t,N.promise=kn());T(K)},B=S(this,_t);switch(B.status){case"pending":e.queryHash===s.queryHash&&T(B);break;case"fulfilled":(R||N.data!==B.value)&&C();break;case"rejected":(!R||N.error!==B.reason)&&C();break}}return N}updateResult(){const e=S(this,ze),r=this.createResult(S(this,de),this.options);if(q(this,cr,S(this,de).state),q(this,Nr,this.options),S(this,cr).data!==void 0&&q(this,Fr,S(this,de)),wn(r,e))return;q(this,ze,r);const s=()=>{if(!e)return!0;const{notifyOnChangeProps:n}=this.options,i=typeof n=="function"?n():n;if(i==="all"||!i&&!S(this,Lr).size)return!0;const a=new Set(i??S(this,Lr));return this.options.throwOnError&&a.add("error"),Object.keys(S(this,ze)).some(l=>{const c=l;return S(this,ze)[c]!==e[c]&&a.has(c)})};ue(this,ge,ma).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&ue(this,ge,Rn).call(this)}},Ke=new WeakMap,de=new WeakMap,gs=new WeakMap,ze=new WeakMap,cr=new WeakMap,Nr=new WeakMap,_t=new WeakMap,Ut=new WeakMap,bs=new WeakMap,Br=new WeakMap,Fr=new WeakMap,ur=new WeakMap,dr=new WeakMap,Mt=new WeakMap,Lr=new WeakMap,ge=new WeakSet,Zr=function(e){ue(this,ge,On).call(this);let r=S(this,de).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(Ve)),r},En=function(){ue(this,ge,Cn).call(this);const e=Ht(this.options.staleTime,S(this,de));if(fr||S(this,ze).isStale||!yn(e))return;const s=ua(S(this,ze).dataUpdatedAt,e)+1;q(this,ur,rr.setTimeout(()=>{S(this,ze).isStale||this.updateResult()},s))},jn=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(S(this,de)):this.options.refetchInterval)??!1},Tn=function(e){ue(this,ge,An).call(this),q(this,Mt,e),!(fr||rt(this.options.enabled,S(this,de))===!1||!yn(S(this,Mt))||S(this,Mt)===0)&&q(this,dr,rr.setInterval(()=>{(this.options.refetchIntervalInBackground||Ln.isFocused())&&ue(this,ge,Zr).call(this)},S(this,Mt)))},Rn=function(){ue(this,ge,En).call(this),ue(this,ge,Tn).call(this,ue(this,ge,jn).call(this))},Cn=function(){S(this,ur)&&(rr.clearTimeout(S(this,ur)),q(this,ur,void 0))},An=function(){S(this,dr)&&(rr.clearInterval(S(this,dr)),q(this,dr,void 0))},On=function(){const e=S(this,Ke).getQueryCache().build(S(this,Ke),this.options);if(e===S(this,de))return;const r=S(this,de);q(this,de,e),q(this,gs,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},ma=function(e){Ue.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(S(this,ze))}),S(this,Ke).getQueryCache().notify({query:S(this,de),type:"observerResultsUpdated"})})},qi);function Vc(t,e){return rt(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function ji(t,e){return Vc(t,e)||t.state.data!==void 0&&Pn(t,e,e.refetchOnMount)}function Pn(t,e,r){if(rt(e.enabled,t)!==!1&&Ht(e.staleTime,t)!=="static"){const s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&$n(t,e)}return!1}function Ti(t,e,r,s){return(t!==e||rt(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&$n(t,r)}function $n(t,e){return rt(e.enabled,t)!==!1&&t.isStaleByTime(Ht(e.staleTime,t))}function Gc(t,e){return!wn(t.getCurrentResult(),e)}function Ri(t){return{onFetch:(e,r)=>{var d,h,f,p,v;const s=e.options,n=(f=(h=(d=e.fetchOptions)==null?void 0:d.meta)==null?void 0:h.fetchMore)==null?void 0:f.direction,i=((p=e.state.data)==null?void 0:p.pages)||[],a=((v=e.state.data)==null?void 0:v.pageParams)||[];let l={pages:[],pageParams:[]},c=0;const u=async()=>{let m=!1;const b=k=>{Dc(k,()=>e.signal,()=>m=!0)},y=da(e.options,e.fetchOptions),_=async(k,w,E)=>{if(m)return Promise.reject();if(w==null&&k.pages.length)return Promise.resolve(k);const F=(()=>{const R={client:e.client,queryKey:e.queryKey,pageParam:w,direction:E?"backward":"forward",meta:e.options.meta};return b(R),R})(),N=await y(F),{maxPages:U}=e.options,j=E?$c:Lc;return{pages:j(k.pages,N,U),pageParams:j(k.pageParams,w,U)}};if(n&&i.length){const k=n==="backward",w=k?Jc:Ci,E={pages:i,pageParams:a},A=w(s,E);l=await _(E,A,k)}else{const k=t??i.length;do{const w=c===0?a[0]??s.initialPageParam:Ci(s,l);if(c>0&&w==null)break;l=await _(l,w),c++}while(c<k)}return l};e.options.persister?e.fetchFn=()=>{var m,b;return(b=(m=e.options).persister)==null?void 0:b.call(m,u,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=u}}}function Ci(t,{pages:e,pageParams:r}){const s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,r[s],r):void 0}function Jc(t,{pages:e,pageParams:r}){var s;return e.length>0?(s=t.getPreviousPageParam)==null?void 0:s.call(t,e[0],e,r[0],r):void 0}var ms,gt,We,hr,bt,Bt,zi,Qc=(zi=class extends ga{constructor(e){super();re(this,bt);re(this,ms);re(this,gt);re(this,We);re(this,hr);q(this,ms,e.client),this.mutationId=e.mutationId,q(this,We,e.mutationCache),q(this,gt,[]),this.state=e.state||Yc(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){S(this,gt).includes(e)||(S(this,gt).push(e),this.clearGcTimeout(),S(this,We).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){q(this,gt,S(this,gt).filter(r=>r!==e)),this.scheduleGc(),S(this,We).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){S(this,gt).length||(this.state.status==="pending"?this.scheduleGc():S(this,We).remove(this))}continue(){var e;return((e=S(this,hr))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,l,c,u,d,h,f,p,v,m,b,y,_,k,w,E,A,F;const r=()=>{ue(this,bt,Bt).call(this,{type:"continue"})},s={client:S(this,ms),meta:this.options.meta,mutationKey:this.options.mutationKey};q(this,hr,pa({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(N,U)=>{ue(this,bt,Bt).call(this,{type:"failed",failureCount:N,error:U})},onPause:()=>{ue(this,bt,Bt).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>S(this,We).canRun(this)}));const n=this.state.status==="pending",i=!S(this,hr).canStart();try{if(n)r();else{ue(this,bt,Bt).call(this,{type:"pending",variables:e,isPaused:i}),S(this,We).config.onMutate&&await S(this,We).config.onMutate(e,this,s);const U=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,e,s));U!==this.state.context&&ue(this,bt,Bt).call(this,{type:"pending",context:U,variables:e,isPaused:i})}const N=await S(this,hr).start();return await((u=(c=S(this,We).config).onSuccess)==null?void 0:u.call(c,N,e,this.state.context,this,s)),await((h=(d=this.options).onSuccess)==null?void 0:h.call(d,N,e,this.state.context,s)),await((p=(f=S(this,We).config).onSettled)==null?void 0:p.call(f,N,null,this.state.variables,this.state.context,this,s)),await((m=(v=this.options).onSettled)==null?void 0:m.call(v,N,null,e,this.state.context,s)),ue(this,bt,Bt).call(this,{type:"success",data:N}),N}catch(N){try{await((y=(b=S(this,We).config).onError)==null?void 0:y.call(b,N,e,this.state.context,this,s))}catch(U){Promise.reject(U)}try{await((k=(_=this.options).onError)==null?void 0:k.call(_,N,e,this.state.context,s))}catch(U){Promise.reject(U)}try{await((E=(w=S(this,We).config).onSettled)==null?void 0:E.call(w,void 0,N,this.state.variables,this.state.context,this,s))}catch(U){Promise.reject(U)}try{await((F=(A=this.options).onSettled)==null?void 0:F.call(A,void 0,N,e,this.state.context,s))}catch(U){Promise.reject(U)}throw ue(this,bt,Bt).call(this,{type:"error",error:N}),N}finally{S(this,We).runNext(this)}}},ms=new WeakMap,gt=new WeakMap,We=new WeakMap,hr=new WeakMap,bt=new WeakSet,Bt=function(e){const r=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=r(this.state),Ue.batch(()=>{S(this,gt).forEach(s=>{s.onMutationUpdate(e)}),S(this,We).notify({mutation:this,type:"updated",action:e})})},zi);function Yc(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var kt,ut,ys,Hi,Xc=(Hi=class extends ws{constructor(e={}){super();re(this,kt);re(this,ut);re(this,ys);this.config=e,q(this,kt,new Set),q(this,ut,new Map),q(this,ys,0)}build(e,r,s){const n=new Qc({client:e,mutationCache:this,mutationId:++Ss(this,ys)._,options:e.defaultMutationOptions(r),state:s});return this.add(n),n}add(e){S(this,kt).add(e);const r=Ps(e);if(typeof r=="string"){const s=S(this,ut).get(r);s?s.push(e):S(this,ut).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(S(this,kt).delete(e)){const r=Ps(e);if(typeof r=="string"){const s=S(this,ut).get(r);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&S(this,ut).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=Ps(e);if(typeof r=="string"){const s=S(this,ut).get(r),n=s==null?void 0:s.find(i=>i.state.status==="pending");return!n||n===e}else return!0}runNext(e){var s;const r=Ps(e);if(typeof r=="string"){const n=(s=S(this,ut).get(r))==null?void 0:s.find(i=>i!==e&&i.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Ue.batch(()=>{S(this,kt).forEach(e=>{this.notify({type:"removed",mutation:e})}),S(this,kt).clear(),S(this,ut).clear()})}getAll(){return Array.from(S(this,kt))}find(e){const r={exact:!0,...e};return this.getAll().find(s=>xi(r,s))}findAll(e={}){return this.getAll().filter(r=>xi(e,r))}notify(e){Ue.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return Ue.batch(()=>Promise.all(e.map(r=>r.continue().catch(Ve))))}},kt=new WeakMap,ut=new WeakMap,ys=new WeakMap,Hi);function Ps(t){var e;return(e=t.options.scope)==null?void 0:e.id}var mt,Ki,Zc=(Ki=class extends ws{constructor(e={}){super();re(this,mt);this.config=e,q(this,mt,new Map)}build(e,r,s){const n=r.queryKey,i=r.queryHash??Fn(n,r);let a=this.get(i);return a||(a=new Hc({client:e,queryKey:n,queryHash:i,options:e.defaultQueryOptions(r),state:s,defaultOptions:e.getQueryDefaults(n)}),this.add(a)),a}add(e){S(this,mt).has(e.queryHash)||(S(this,mt).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=S(this,mt).get(e.queryHash);r&&(e.destroy(),r===e&&S(this,mt).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Ue.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return S(this,mt).get(e)}getAll(){return[...S(this,mt).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(s=>wi(r,s))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(s=>wi(e,s)):r}notify(e){Ue.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){Ue.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ue.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},mt=new WeakMap,Ki),Re,Wt,qt,$r,Dr,zt,Ur,Mr,Vi,eu=(Vi=class{constructor(t={}){re(this,Re);re(this,Wt);re(this,qt);re(this,$r);re(this,Dr);re(this,zt);re(this,Ur);re(this,Mr);q(this,Re,t.queryCache||new Zc),q(this,Wt,t.mutationCache||new Xc),q(this,qt,t.defaultOptions||{}),q(this,$r,new Map),q(this,Dr,new Map),q(this,zt,0)}mount(){Ss(this,zt)._++,S(this,zt)===1&&(q(this,Ur,Ln.subscribe(async t=>{t&&(await this.resumePausedMutations(),S(this,Re).onFocus())})),q(this,Mr,Ls.subscribe(async t=>{t&&(await this.resumePausedMutations(),S(this,Re).onOnline())})))}unmount(){var t,e;Ss(this,zt)._--,S(this,zt)===0&&((t=S(this,Ur))==null||t.call(this),q(this,Ur,void 0),(e=S(this,Mr))==null||e.call(this),q(this,Mr,void 0))}isFetching(t){return S(this,Re).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return S(this,Wt).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=S(this,Re).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=S(this,Re).build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(Ht(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return S(this,Re).findAll(t).map(({queryKey:e,state:r})=>{const s=r.data;return[e,s]})}setQueryData(t,e,r){const s=this.defaultQueryOptions({queryKey:t}),n=S(this,Re).get(s.queryHash),i=n==null?void 0:n.state.data,a=Nc(e,i);if(a!==void 0)return S(this,Re).build(this,s).setData(a,{...r,manual:!0})}setQueriesData(t,e,r){return Ue.batch(()=>S(this,Re).findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,r)]))}getQueryState(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=S(this,Re).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=S(this,Re);Ue.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=S(this,Re);return Ue.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},s=Ue.batch(()=>S(this,Re).findAll(t).map(n=>n.cancel(r)));return Promise.all(s).then(Ve).catch(Ve)}invalidateQueries(t,e={}){return Ue.batch(()=>(S(this,Re).findAll(t).forEach(r=>{r.invalidate()}),(t==null?void 0:t.refetchType)==="none"?Promise.resolve():this.refetchQueries({...t,type:(t==null?void 0:t.refetchType)??(t==null?void 0:t.type)??"active"},e)))}refetchQueries(t,e={}){const r={...e,cancelRefetch:e.cancelRefetch??!0},s=Ue.batch(()=>S(this,Re).findAll(t).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let i=n.fetch(void 0,r);return r.throwOnError||(i=i.catch(Ve)),n.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(Ve)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=S(this,Re).build(this,e);return r.isStaleByTime(Ht(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(Ve).catch(Ve)}fetchInfiniteQuery(t){return t.behavior=Ri(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(Ve).catch(Ve)}ensureInfiniteQueryData(t){return t.behavior=Ri(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return Ls.isOnline()?S(this,Wt).resumePausedMutations():Promise.resolve()}getQueryCache(){return S(this,Re)}getMutationCache(){return S(this,Wt)}getDefaultOptions(){return S(this,qt)}setDefaultOptions(t){q(this,qt,t)}setQueryDefaults(t,e){S(this,$r).set(ds(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...S(this,$r).values()],r={};return e.forEach(s=>{hs(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){S(this,Dr).set(ds(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...S(this,Dr).values()],r={};return e.forEach(s=>{hs(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...S(this,qt).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=Fn(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===Fs&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...S(this,qt).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){S(this,Re).clear(),S(this,Wt).clear()}},Re=new WeakMap,Wt=new WeakMap,qt=new WeakMap,$r=new WeakMap,Dr=new WeakMap,zt=new WeakMap,Ur=new WeakMap,Mr=new WeakMap,Vi),ya=st.createContext(void 0),va=t=>{const e=st.useContext(ya);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},tu=({client:t,children:e})=>(st.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),o.jsx(ya.Provider,{value:t,children:e})),wa=st.createContext(!1),ru=()=>st.useContext(wa);wa.Provider;function su(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var nu=st.createContext(su()),iu=()=>st.useContext(nu),au=(t,e,r)=>{const s=r!=null&&r.state.error&&typeof t.throwOnError=="function"?ha(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},ou=t=>{st.useEffect(()=>{t.clearReset()},[t])},lu=({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:n})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(n&&t.data===void 0||ha(r,[t.error,s])),cu=t=>{if(t.suspense){const r=n=>n==="static"?n:Math.max(n??1e3,1e3),s=t.staleTime;t.staleTime=typeof s=="function"?(...n)=>r(s(...n)):r(s),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},uu=(t,e)=>t.isLoading&&t.isFetching&&!e,du=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,Ai=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function hu(t,e,r){var f,p,v,m;if(process.env.NODE_ENV!=="production"&&(typeof t!="object"||Array.isArray(t)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const s=ru(),n=iu(),i=va(),a=i.defaultQueryOptions(t);(p=(f=i.getDefaultOptions().queries)==null?void 0:f._experimental_beforeQuery)==null||p.call(f,a);const l=i.getQueryCache().get(a.queryHash);process.env.NODE_ENV!=="production"&&(a.queryFn||console.error(`[${a.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),a._optimisticResults=s?"isRestoring":"optimistic",cu(a),au(a,n,l),ou(n);const c=!i.getQueryCache().get(a.queryHash),[u]=st.useState(()=>new e(i,a)),d=u.getOptimisticResult(a),h=!s&&t.subscribed!==!1;if(st.useSyncExternalStore(st.useCallback(b=>{const y=h?u.subscribe(Ue.batchCalls(b)):Ve;return u.updateResult(),y},[u,h]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),st.useEffect(()=>{u.setOptions(a)},[a,u]),du(a,d))throw Ai(a,u,n);if(lu({result:d,errorResetBoundary:n,throwOnError:a.throwOnError,query:l,suspense:a.suspense}))throw d.error;if((m=(v=i.getDefaultOptions().queries)==null?void 0:v._experimental_afterQuery)==null||m.call(v,a,d),a.experimental_prefetchInRender&&!fr&&uu(d,s)){const b=c?Ai(a,u,n):l==null?void 0:l.promise;b==null||b.catch(Ve).finally(()=>{u.updateResult()})}return a.notifyOnChangeProps?d:u.trackResult(d)}function xs(t,e){return hu(t,Kc)}const fu=()=>`bob_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;function xa({ga4Config:t,hostContext:e,callbacks:r,enabled:s=!0}){const n=g.useRef(fu()),i=g.useRef(!1),a=g.useCallback((k,w)=>{if(!(!(t!=null&&t.measurementId)||typeof window>"u")&&window.gtag){const E={...w,send_to:t.measurementId};t.debug&&console.log("[BobAnalytics] GA4 event:",k,E),window.gtag("event",k,E)}},[t]),l=g.useCallback((k,w={})=>{var A,F,N,U,j,R,T,C;if(!s)return;const E={event_name:k,timestamp:new Date().toISOString(),session_id:n.current,user_email:(A=e==null?void 0:e.user)==null?void 0:A.email,user_id:(F=e==null?void 0:e.user)==null?void 0:F.id,vehicle_id:(j=(U=(N=e==null?void 0:e.vehicle)==null?void 0:N.selectedVehicle)==null?void 0:U.vehicle_id)==null?void 0:j.toString(),rego:(T=(R=e==null?void 0:e.vehicle)==null?void 0:R.selectedVehicle)==null?void 0:T.rego,parameters:w};a(k,{session_id:E.session_id,user_email:E.user_email,vehicle_id:E.vehicle_id,...w}),(C=r==null?void 0:r.onAnalyticsEvent)==null||C.call(r,E),t!=null&&t.debug&&console.log("[BobAnalytics] Event tracked:",E)},[s,e,r,a,t==null?void 0:t.debug]),c=g.useCallback(()=>{var k,w,E;i.current||(i.current=!0,l("bob_session_start",{widget_version:St,has_vehicle:!!((k=e==null?void 0:e.vehicle)!=null&&k.selectedVehicle),has_user:!!((w=e==null?void 0:e.user)!=null&&w.id)||!!((E=e==null?void 0:e.user)!=null&&E.email)}))},[l,e]),u=g.useCallback((k,w)=>{l("bob_message_sent",{message_length:k,has_vehicle:w})},[l]),d=g.useCallback(k=>{l("bob_vehicle_identified",{vehicle_make:k.make||"unknown",vehicle_model:k.model||"unknown",vehicle_year:k.year||"unknown",rego:k.rego})},[l]),h=g.useCallback((k,w)=>{l("bob_parts_viewed",{part_count:k,vehicle_id:w})},[l]),f=g.useCallback(k=>{l("bob_product_clicked",{sku:k.sku,product_name:k.product_name,price:k.price,brand:k.brand})},[l]),p=g.useCallback(k=>{l("bob_product_viewed",{sku:k.sku,product_name:k.product_name,price:k.price,brand:k.brand})},[l]),v=g.useCallback(k=>{l("bob_add_to_cart",{sku:k.sku,product_name:k.product_name,price:k.price,brand:k.brand,quantity:k.quantity??1})},[l]),m=g.useCallback((k,w)=>{l("bob_checkout_started",{cart_value:k,item_count:w})},[l]),b=g.useCallback(k=>{const w=Math.ceil(k/5/150*60);l("bob_speech_played",{text_length:k,duration_estimate:w})},[l]),y=g.useCallback(k=>{l("bob_speech_failed",{text_length:k})},[l]),_=g.useCallback((k,w)=>{l("bob_error",{error_type:k,error_message:w})},[l]);return g.useEffect(()=>{c()},[c]),{trackEvent:l,sessionId:n.current,trackSessionStart:c,trackMessageSent:u,trackVehicleIdentified:d,trackPartsViewed:h,trackProductClicked:f,trackProductViewed:p,trackAddToCart:v,trackCheckoutStarted:m,trackSpeechPlayed:b,trackSpeechFailed:y,trackError:_}}const qs=g.createContext(null);function Dn({children:t,bobConfig:e,hostApiConfig:r,hostContext:s={},callbacks:n={},queryClient:i,ga4Config:a,analyticsEnabled:l=!0,bottomOffset:c=0,zIndexBase:u=50}){const d=g.useMemo(()=>new eu({defaultOptions:{queries:{retry:1,staleTime:3e5}}}),[]),h=i||d,f=!!i;g.useEffect(()=>{console.log(`[BobWidget] v${St} initialized`),console.log(`[BobWidget] QueryClient: ${f?"external (shared)":"internal"}`),console.log(`[BobWidget] Analytics: ${l?"enabled":"disabled"}`),a!=null&&a.measurementId&&console.log(`[BobWidget] GA4: ${a.measurementId}`)},[f,l,a==null?void 0:a.measurementId]);const p=g.useMemo(()=>mn(e.supabaseUrl,e.supabaseKey),[e.supabaseUrl,e.supabaseKey]),[v,m]=g.useState(s);g.useEffect(()=>{m(s)},[s]);const b=g.useCallback(_=>{m(k=>({...k,..._}))},[]),y=g.useMemo(()=>({bobSupabase:p,bobConfig:e,hostApiConfig:r,hostContext:v,callbacks:n,updateHostContext:b,ga4Config:a,analyticsEnabled:l,bottomOffset:c,zIndexBase:u}),[p,e,r,v,n,b,a,l,c,u]);return o.jsx(tu,{client:h,children:o.jsx(qs.Provider,{value:y,children:t})})}function jt(){const t=g.useContext(qs);if(!t)throw new Error("useBobContext must be used within a BobProvider");return t}function pu(){const{bobSupabase:t}=jt();return t}function pr(){const t=g.useContext(qs);return(t==null?void 0:t.bobSupabase)||null}function gu(){const{hostContext:t}=jt();return t}function bu(){const{hostApiConfig:t}=jt();return t}function mu(){const{callbacks:t}=jt();return t}function yu(){const{ga4Config:t,analyticsEnabled:e}=jt();return{ga4Config:t,enabled:e}}function Un(){const t=g.useContext(qs);return t?{bottomOffset:t.bottomOffset,zIndexBase:t.zIndexBase}:{bottomOffset:0,zIndexBase:50}}const vu=15e3,wu={greeting_returning:/ah hey|you again|what you after this time/i,greeting_welcome:/g'?day|welcome.*carfix|bob.*here/i,ask_rego:/need your rego|rego.*get cracking|what('?s| is) your rego/i,vehicle_not_found:/couldn'?t find that|double.?check.*plate/i,no_parts_found:/nothing came up|no results|sorry.*search/i,checkout_ready:/ready to checkout|checkout.*ready|choice.*checkout/i,rego_searching:/let('?s| us) see what car|sweet.*searching|searching for/i},Qr=new Map,xu=t=>t.replace(/\bya\b/gi,"you"),_a=({onStart:t,onEnd:e,onFailed:r}={})=>{const{bobConfig:s,bobSupabase:n}=jt(),[i,a]=g.useState(!1),l=g.useRef(null),c=g.useRef(null),u=g.useRef(!1),d=g.useRef([]),h=g.useRef(!1),f=g.useRef(!1),p=g.useRef(null),v=g.useRef(null),m=g.useRef(t),b=g.useRef(e),y=g.useRef(r);g.useEffect(()=>{m.current=t,b.current=e,y.current=r},[t,e,r]);const _=g.useCallback(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]),k=g.useCallback(()=>{var T;u.current||(u.current=!0,console.log("[BobWidget TTS] Fallback: triggering onStart without audio"),(T=m.current)==null||T.call(m))},[]),w=g.useCallback(async T=>{if(Qr.has(T)){const C=Qr.get(T);return console.log(`[BobWidget TTS] Cache hit for clip: ${T}`,C?"found":"null"),C||null}try{console.log(`[BobWidget TTS] Fetching clip from DB: ${T}`);const{data:C,error:B}=await n.from("bob_audio_clips").select("audio_url").eq("clip_key",T).eq("is_active",!0).single();return B||!C?(console.log(`[BobWidget TTS] No clip found for: ${T}`),Qr.set(T,null),null):(console.log(`[BobWidget TTS] Clip found: ${T} -> ${C.audio_url}`),Qr.set(T,C),C)}catch(C){return console.warn(`[BobWidget TTS] Clip lookup failed for ${T}:`,C),Qr.set(T,null),null}},[n]),E=g.useCallback(async T=>{for(const[C,B]of Object.entries(wu))if(B.test(T)){console.log(`[BobWidget TTS] Pattern matched: ${C}`);const K=await w(C);if(K!=null&&K.audio_url)return K.audio_url}return null},[w]),A=g.useCallback(async()=>{var K,Y,te;if(h.current||d.current.length===0)return;h.current=!0;const T=d.current.shift();if(!T){h.current=!1;return}const{text:C,isGreeting:B}=T;B&&(f.current=!0),u.current=!1,_(),l.current&&(l.current.pause(),l.current=null),c.current=setTimeout(()=>{var $,M;console.warn("[BobWidget TTS] Timeout - triggering fallback callbacks"),k(),a(!1),f.current=!1,($=b.current)==null||$.call(b),(M=y.current)==null||M.call(y),l.current=null,h.current=!1,A()},vu);try{let $=null;if($=await E(C),$)console.log("[BobWidget TTS] Using pre-recorded audio (fast path)");else{console.log("[BobWidget TTS] No pre-recorded clip, using ElevenLabs TTS");const J=xu(C),oe=await fetch(`${s.supabaseUrl}/functions/v1/bob-tts-elevenlabs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.supabaseKey}`},body:JSON.stringify({text:J})});if(!oe.ok){const P=await oe.json().catch(()=>({}));throw console.error("[BobWidget TTS] Request failed:",P),new Error("TTS request failed")}const X=await oe.blob();$=URL.createObjectURL(X)}const M=new Audio($);l.current=M,M.onplay=()=>{var J;_(),p.current=null,u.current||(u.current=!0,a(!0),console.log("[BobWidget TTS] Audio playing, triggering onStart (animation: TALKING)"),(J=m.current)==null||J.call(m))},M.onended=()=>{var J;_(),a(!1),f.current=!1,console.log("[BobWidget TTS] Audio ended, triggering onEnd (animation: COMPLETE/IDLE)"),(J=b.current)==null||J.call(b),l.current=null,h.current=!1,A()},M.onerror=J=>{var oe,X;_(),console.warn("[BobWidget TTS] Audio playback error:",J),k(),a(!1),f.current=!1,(oe=b.current)==null||oe.call(b),(X=y.current)==null||X.call(y),l.current=null,h.current=!1,A()};try{await M.play()}catch(J){console.warn("[BobWidget TTS] Audio play() failed (autoplay policy):",J),_(),B&&(p.current=C,console.log("[BobWidget TTS] Greeting stored for retry on user interaction")),k(),a(!1),f.current=!1,(K=b.current)==null||K.call(b),h.current=!1,A()}}catch($){_(),console.error("[BobWidget TTS] Speech synthesis error:",$),k(),a(!1),f.current=!1,(Y=b.current)==null||Y.call(b),(te=y.current)==null||te.call(y),h.current=!1,A()}},[s.supabaseUrl,s.supabaseKey,_,k,E]),F=g.useCallback((T,C=!1)=>{if(T.trim()){if(C){if(v.current===T){console.log(`[BobWidget TTS] Ignoring duplicate greeting: "${T.substring(0,30)}..."`);return}v.current=T,p.current=null}if(f.current&&!C){console.log("[BobWidget TTS] Greeting playing - queueing message"),d.current.push({text:T,isGreeting:C});return}C?d.current.unshift({text:T,isGreeting:C}):d.current.push({text:T,isGreeting:C}),A()}},[A]),N=g.useCallback(()=>{if(p.current&&!l.current&&!h.current){console.log("[BobWidget TTS] Retrying pending greeting on user interaction");const T=p.current;p.current=null,F(T,!0)}},[F]),U=g.useCallback(()=>{_(),d.current=[],l.current&&(l.current.pause(),l.current=null),a(!1),f.current=!1,h.current=!1},[_]),j=g.useCallback(()=>{var T;(T=l.current)==null||T.pause()},[]),R=g.useCallback(()=>{var T;(T=l.current)==null||T.play()},[]);return g.useEffect(()=>()=>{_(),d.current=[],l.current&&(l.current.pause(),l.current=null)},[_]),{speak:F,stop:U,pause:j,resume:R,isSpeaking:i,isSupported:!0,retryPendingGreeting:N}},Oi="bob_last_visit",_u=30;function ka(t=_u){const[e,r]=g.useState(!1),[s,n]=g.useState(null);return g.useEffect(()=>{try{const i=localStorage.getItem(Oi),a=Date.now();if(i){const l=parseInt(i,10),c=(a-l)/(1e3*60*60*24);c<=t?(r(!0),n(new Date(l)),console.log(`[BobWidget] Returning user detected - last visit ${Math.round(c)} days ago`)):console.log(`[BobWidget] Previous visit was ${Math.round(c)} days ago - treating as new user`)}else console.log("[BobWidget] First time visitor detected");localStorage.setItem(Oi,String(a))}catch(i){console.warn("[BobWidget] Could not access localStorage for returning user detection:",i)}},[t]),{isReturningUser:e,lastVisitDate:s,daysSinceLastVisit:s?Math.round((Date.now()-s.getTime())/(1e3*60*60*24)):null}}const In=t=>{if(!t)return t;let e=t;return e=e.replace(/\b(retrieve_parts|lookup_vehicle|search_general_products|retrieve_service_packages|add_to_cart|get_cart|create_checkout|get_customer_context|get_product_details|search_products|check_vehicle_fitment|search_web)\s*\([^)]*\)/gi,""),e=e.replace(/\(\s*(vehicleid|vehicle_id|part_type|query|plate|user_email|sku)\s*=\s*[^)]+\)/gi,""),e=e.replace(/\b(retrieve_parts|lookup_vehicle|search_general_products|retrieve_service_packages|add_to_cart|get_cart|create_checkout|get_customer_context|get_product_details|search_products|check_vehicle_fitment|search_web)\s*\(/gi,""),e=e.replace(/\b(vehicleid|vehicle_id|part_type)\s*=\s*(['"]?[\w\s]+['"]?)\s*,?\s*/gi,""),e=e.replace(/```[\s\S]*?```/g,""),e=e.replace(/\(\s*\)/g,""),e=e.replace(/\s{2,}/g," "),e=e.trim(),e},ku=t=>{let e=In(t);return e=e.replace(/[\[\]{}]/g,""),e=e.replace(/https?:\/\/[^\s]+/g,""),e=e.replace(/\bSKU\s*:?\s*\w+/gi,""),e},Su=["what version","which version","software version","bob version","your version","current version","running version","version number","what ver","which ver"],rn=["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"],Eu=["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"],Sa=({setAnimationState:t,manualMode:e=!1,talkingState:r="talking",thinkingState:s="researching",completeState:n="idle",idleState:i="idle",listenState:a="listening",onStreamStart:l,onStreamComplete:c,onShowingProduct:u,onResearchStart:d,onReadyToSpeak:h,onHighlightPart:f,onHighlightProduct:p,onNoPartsFound:v,onAutoFetchComplete:m,onVariantSelectionRequired:b})=>{var qr,zr,Hr,_s;const{bobConfig:y,hostApiConfig:_,hostContext:k,callbacks:w,ga4Config:E,analyticsEnabled:A}=jt(),F=xa({ga4Config:E,hostContext:k,callbacks:w,enabled:A}),{isReturningUser:N}=ka(),[U,j]=g.useState([]),[R,T]=g.useState(""),[C,B]=g.useState(!1),[K,Y]=g.useState(!1),[te,$]=g.useState(null),M=g.useRef(null),J=g.useRef(!1),oe=g.useRef(!1),X=g.useRef(""),P=g.useRef(!1),D=g.useRef(null);g.useRef(null);const V=g.useRef({source:"none",isPlaying:!1,hasCannedAudio:!1,cannedUrl:null,currentAudio:null,searchingQueue:[]}),Q=g.useRef([]),_e=g.useRef("AWAITING_REGO"),Te=()=>{const z=V.current;if(z.currentAudio){try{z.currentAudio.pause(),z.currentAudio.currentTime=0}catch(fe){console.warn("[BobWidget] Error stopping audio:",fe)}z.currentAudio=null}z.isPlaying=!1,z.source="none",z.searchingQueue=[],Qe()},Ae=(z,fe,ye)=>{const pe=V.current;if(pe.isPlaying){if(fe==="canned"||fe==="searching"&&pe.source==="tts")Te();else if(pe.source==="canned"){console.log("[BobWidget Audio] Skipping lower priority audio while canned is playing");return}}const He=new Audio(z);pe.currentAudio=He,pe.source=fe,pe.isPlaying=!0,He.onplay=()=>{console.log(`[BobWidget Audio] ${fe} STARTED:`,z.split("/").pop()),e||ee(r)},He.onended=()=>{console.log(`[BobWidget Audio] ${fe} ENDED`),pe.currentAudio=null,pe.isPlaying=!1,pe.source="none",ye==null||ye()},He.onerror=()=>{console.warn(`[BobWidget Audio] ${fe} FAILED:`,z),pe.currentAudio=null,pe.isPlaying=!1,pe.source="none",ye==null||ye()},He.play().catch(Kt=>{console.warn(`[BobWidget Audio] ${fe} autoplay blocked:`,Kt),pe.currentAudio=null,pe.isPlaying=!1,pe.source="none",ye==null||ye()})},Be=()=>{const z=V.current;if(z.hasCannedAudio||z.source==="canned"){console.log("[BobWidget Audio] Skipping searching audio - canned audio takes priority"),z.searchingQueue=[];return}if(z.searchingQueue.length===0){!e&&z.source==="searching"&&ee(s);return}const fe=z.searchingQueue.shift();Ae(fe,"searching",()=>{Be()})},Je=()=>{D.current&&(clearTimeout(D.current),D.current=null)},{speak:qe,stop:Qe,isSpeaking:nt,retryPendingGreeting:O}=_a({onStart:()=>{Je(),P.current=!0,console.log("[BobWidget STATE] Speech STARTED - transitioning to TALK state"),F.trackSpeechPlayed(X.current.length),h==null||h(),e||(console.log("[BobWidget STATE] Setting state to:",r),ee(r))},onEnd:()=>{Je(),console.log("[BobWidget STATE] Speech ENDED - transitioning out of TALK state");const z=rn.some(fe=>X.current.toLowerCase().includes(fe.toLowerCase()));e||(z&&u?(console.log("[BobWidget STATE] Has products - calling onShowingProduct"),u()):c?(console.log("[BobWidget STATE] Calling onStreamComplete"),c()):(console.log("[BobWidget STATE] Setting state to:",n),ee(n),setTimeout(()=>{console.log("[BobWidget STATE] Post-complete transition to:",a),ee(a)},2e3)))},onFailed:()=>{console.warn("[BobWidget] Speech synthesis failed - fallback triggered"),F.trackSpeechFailed(X.current.length)}});g.useEffect(()=>{var z;(z=M.current)==null||z.scrollIntoView({behavior:"smooth"})},[U]),g.useEffect(()=>{var fe,ye;const z=(fe=k.vehicle)==null?void 0:fe.selectedVehicle;z&&!te&&(console.log("[BobWidget] Setting vehicle from host context:",z),$(z),(ye=w.onVehicleIdentified)==null||ye.call(w,z),F.trackVehicleIdentified({make:z.make,model:z.model,year:z.year,rego:z.rego}))},[(qr=k.vehicle)==null?void 0:qr.selectedVehicle]),g.useEffect(()=>{var z;if(U.length===0&&!oe.current){oe.current=!0;const fe=(z=k.vehicle)==null?void 0:z.selectedVehicle;let ye;N?(ye="Ah hey... you again! What you after this time?",console.log("[BobWidget] Using returning user greeting")):fe?ye=`G'day! Saw you've got the ${`${fe.year} ${fe.make} ${fe.model}`} - choice wagon! What can I help you find for it today?`:ye="G'day! Bob from CARFIX here. How can I help ya today?",j([{role:"assistant",content:ye}]),K||setTimeout(()=>{console.log("[BobWidget] Speaking initial greeting (priority)"),qe(ye,!0)},500)}},[(zr=k.vehicle)==null?void 0:zr.selectedVehicle,U.length,K,qe]),g.useEffect(()=>{const z=()=>{console.log("[BobWidget] User interaction detected - retrying pending greeting"),O(),document.removeEventListener("click",z),document.removeEventListener("touchstart",z)};return document.addEventListener("click",z,{once:!0}),document.addEventListener("touchstart",z,{once:!0}),()=>{document.removeEventListener("click",z),document.removeEventListener("touchstart",z)}},[O]),g.useEffect(()=>{var Vt,Gt;const z=(Vt=k.vehicle)==null?void 0:Vt.selectedVehicle;if(!z||J.current)return;const fe=z.vehicle_id??z.id,ye=Number.parseInt(String(fe),10);if(!Number.isFinite(ye)){console.warn("[BobWidget] Vehicle has invalid vehicle_id, cannot auto-fetch:",z);return}J.current=!0;const pe={...z,vehicle_id:String(ye)},He=(Gt=k.user)==null?void 0:Gt.email;(async()=>{var yt,Tt;const gr=`${y.supabaseUrl}/functions/v1/bob-chat`;try{const Me=await fetch(gr,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y.supabaseKey}`},body:JSON.stringify({messages:[],vehicleContext:pe,customerEmail:He,autoFetchParts:!0,hostConfig:_,hostContext:k})});if(!Me.ok||!Me.body){console.error("[BobWidget] Auto-fetch failed:",Me.status);return}const Rt=Me.body.getReader(),Ct=new TextDecoder;let it="";for(;;){const{done:br,value:Jt}=await Rt.read();if(br)break;it+=Ct.decode(Jt,{stream:!0});let At;for(;(At=it.indexOf(`
73
73
  `))!==-1;){let Ye=it.slice(0,At);if(it=it.slice(At+1),Ye.endsWith("\r")&&(Ye=Ye.slice(0,-1)),Ye.startsWith(":")||Ye.trim()===""||!Ye.startsWith("data: "))continue;const Ot=Ye.slice(6).trim();if(Ot==="[DONE]")break;try{const Se=JSON.parse(Ot);Se.type==="service_packages_found"&&Se.packages&&(console.log("[useBobChat autoFetch] Received service_packages_found:",Se.packages.length,"packages"),(yt=w.onServicePackagesFound)==null||yt.call(w,Se.packages)),Se.type==="parts_found"&&Se.parts&&(console.log("[useBobChat autoFetch] Received parts_found:",Se.parts.length,"parts"),(Tt=w.onPartsFound)==null||Tt.call(w,Se.parts),F.trackPartsViewed(Array.isArray(Se.parts)?Se.parts.length:0,String(ye)))}catch{}}}m==null||m()}catch(Me){console.error("[BobWidget] Auto-fetch error:",Me)}})()},[(Hr=k.vehicle)==null?void 0:Hr.selectedVehicle,(_s=k.user)==null?void 0:_s.email]);const ee=z=>{try{t(z)}catch{console.warn(`[BobWidget] State "${z}" not available`)}},Oe=async z=>{var pe,He,Kt,Vt,Gt,gr,yt,Tt,Me,Rt,Ct,it,br,Jt,At,Ye,Ot;const fe=`${y.supabaseUrl}/functions/v1/bob-chat`,ye=(pe=k.user)==null?void 0:pe.email;if(te&&!K){const Se=z.content.toLowerCase();if(rn.some(ft=>Se.includes(ft.toLowerCase()))){console.log("[useBobChat] 🎵 Playing optimistic searching audio");const ft=V.current;if(!ft.hasCannedAudio&&ft.source!=="canned"){const mr=`${y.supabaseUrl}/storage/v1/object/public/bob-audio/parts_searching.mp3`;ft.searchingQueue.push(mr),Be()}}}try{const Se={messages:[...U,z],hostConfig:_,hostContext:k};te&&(Se.vehicleContext=te),ye&&(Se.customerEmail=ye),console.log("[useBobChat DEBUG] vehicleCandidatesRef.current:",JSON.stringify((He=Q.current)==null?void 0:He.slice(0,2))),console.log("[useBobChat DEBUG] vehicleCandidatesRef.current.length:",(Kt=Q.current)==null?void 0:Kt.length),console.log("[useBobChat DEBUG] conversationStateRef.current:",_e.current),Q.current&&Q.current.length>0?(Se.vehicleCandidates=Q.current,console.log("[useBobChat] ✅ Including",Q.current.length,"vehicle candidates in request")):console.log("[useBobChat] ⚠️ No vehicle candidates to include - ref is empty");const et=await fetch(fe,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y.supabaseKey}`},body:JSON.stringify(Se)});if(!et.ok){if(et.status===429){(Vt=w.onError)==null||Vt.call(w,new Error("Rate limit exceeded"));return}if(et.status===402){(Gt=w.onError)==null||Gt.call(w,new Error("Payment required"));return}throw new Error("Failed to start stream")}if(!et.body)throw new Error("No response body");const ft=et.body.getReader(),mr=new TextDecoder;let vt="",ks=!1,Pt="";for(;!ks;){const{done:le,value:he}=await ft.read();if(le)break;vt+=mr.decode(he,{stream:!0});let ce;for(;(ce=vt.indexOf(`
74
74
  `))!==-1;){let ae=vt.slice(0,ce);if(vt=vt.slice(ce+1),ae.endsWith("\r")&&(ae=ae.slice(0,-1)),ae.startsWith(":")||ae.trim()===""||!ae.startsWith("data: "))continue;const Fe=ae.slice(6).trim();if(Fe==="[DONE]"){ks=!0;break}try{const L=JSON.parse(Fe);if(L.type==="conversation_state"){console.log("[useBobChat] 🔄 conversation_state event received:",L.state),_e.current=L.state,L.candidates&&Array.isArray(L.candidates)?(Q.current=L.candidates,console.log("[useBobChat] ✅ Stored",L.candidates.length,"vehicle candidates from state event"),console.log("[useBobChat] First candidate:",JSON.stringify(L.candidates[0]))):console.log("[useBobChat] ⚠️ conversation_state had no candidates array");continue}if(L.type==="variant_selection_required"){const be=Array.isArray(L.candidates)?L.candidates.length:0;console.log("[useBobChat] 🎴 variant_selection_required event received:",be,"cards"),Array.isArray(L.candidates)?b==null||b(L.candidates,typeof L.make=="string"?L.make:"",typeof L.model=="string"?L.model:""):console.warn("[useBobChat] ⚠️ variant_selection_required had no candidates array");continue}if(L.type==="vehicle_identified"&&L.vehicle){$(L.vehicle),Q.current=[],_e.current="VEHICLE_CONFIRMED",(gr=w.onVehicleIdentified)==null||gr.call(w,L.vehicle),F.trackVehicleIdentified({make:L.vehicle.make,model:L.vehicle.model,year:L.vehicle.year,rego:L.vehicle.rego});continue}if(L.type==="vehicle_candidates_found"&&L.candidates){console.log("[useBobChat] 📦 vehicle_candidates_found event received:",L.candidates.length,"candidates"),Q.current=L.candidates,console.log("[useBobChat] ✅ Candidates stored in ref. First:",JSON.stringify(L.candidates[0]));continue}if(L.type==="service_packages_found"&&L.packages){(yt=w.onServicePackagesFound)==null||yt.call(w,L.packages);continue}if(L.type==="parts_found"&&L.parts){console.log("[useBobChat] Received parts_found event:",L.parts.length,"parts"),(Tt=w.onPartsFound)==null||Tt.call(w,L.parts),F.trackPartsViewed(Array.isArray(L.parts)?L.parts.length:0,(Me=te==null?void 0:te.vehicle_id)==null?void 0:Me.toString());continue}if(L.type==="bob_suggestions"&&L.products){console.log("[useBobChat] Received bob_suggestions:",L.products.length,"products",L.title),j(be=>{var Pe;const je=[...be],ve=je[je.length-1];return console.log("[useBobChat] Attaching to message:",ve==null?void 0:ve.role,(Pe=ve==null?void 0:ve.content)==null?void 0:Pe.slice(0,40)),(ve==null?void 0:ve.role)==="assistant"?je.map((It,Vs)=>Vs===je.length-1?{...It,suggestedProducts:L.products,suggestionsTitle:L.title}:It):je}),console.log("[useBobChat] bob_suggestions processed for inline display only");continue}if(L.type==="no_parts_found"){(Rt=w.onPartsFound)==null||Rt.call(w,[]),(Ct=w.onServicePackagesFound)==null||Ct.call(w,[]),v==null||v();continue}if(L.type==="audio_hint"&&L.audio_url){console.log("[useBobChat] Audio hint received:",L.clip_key,L.audio_url);const be=V.current;be.hasCannedAudio=!0,be.cannedUrl=L.audio_url,Te();continue}if(L.type==="bob_searching"&&L.audio_url){console.log("[useBobChat] Bob searching:",L.search_type,L.clip_key),L.transcript&&j(je=>{const ve=je[je.length-1];return(ve==null?void 0:ve.role)!=="assistant"||(ve==null?void 0:ve.content)!==L.transcript?[...je,{role:"assistant",content:L.transcript}]:je});const be=V.current;be.searchingQueue.push(L.audio_url),!be.isPlaying&&!be.hasCannedAudio&&!K&&Be();continue}if(L.type==="cart_updated"&&L.items){(it=w.onCartUpdated)==null||it.call(w,L.items);continue}const Ee=(At=(Jt=(br=L.choices)==null?void 0:br[0])==null?void 0:Jt.delta)==null?void 0:At.content;if(Ee){Pt+=Ee;let be=Pt.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");be=In(be),j(je=>{const ve=je[je.length-1];return(ve==null?void 0:ve.role)==="assistant"?je.map((Pe,It)=>It===je.length-1?{...Pe,content:be}:Pe):[...je,{role:"assistant",content:be}]}),(Ye=w.onBobMessage)==null||Ye.call(w,be)}}catch{vt=ae+`
75
- `+vt;break}}}let Kr=Pt.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");Kr=In(Kr),X.current=Kr;const x=rn.some(le=>Pt.toLowerCase().includes(le.toLowerCase())),I=Pt.toLowerCase();for(const le of Eu)if(I.includes(le.toLowerCase())){const he=le.replace(/s\s*$/i,"").toUpperCase();f==null||f(he);break}const W=Pt.match(/(?:go with|recommend|suggest|grab|try)\s+(?:the\s+)?(\w+)\s+(?:at|for)\s+\$(\d+(?:\.\d{2})?)/i);if(W){const[,le,he]=W;p==null||p({brand:le,price:parseFloat(he)})}const Z=V.current;if(!K&&X.current.trim()){if(P.current=!1,Je(),Z.hasCannedAudio&&Z.cannedUrl)console.log("[BobWidget] Playing canned audio (priority):",Z.cannedUrl),Te(),Ae(Z.cannedUrl,"canned",()=>{Z.hasCannedAudio=!1,Z.cannedUrl=null,Je(),e||(x&&u?u():c?c():(ee(n),setTimeout(()=>ee(a),3e3)))}),P.current=!0,h==null||h();else if(Z.isPlaying)console.log("[BobWidget] Skipping TTS - audio already playing:",Z.source);else{const le=ku(X.current);console.log("[BobWidget] Playing TTS (no canned audio)"),qe(le)}D.current=setTimeout(()=>{P.current||(console.warn("[BobWidget] Speech fallback after 5s"),h==null||h(),e||(x&&u?u():c?c():(ee(n),setTimeout(()=>ee(a),3e3))))},5e3)}else h==null||h(),e||(x&&u?u():c?c():(ee(n),setTimeout(()=>ee(a),3e3)))}catch(Se){console.error("[BobWidget] Chat error:",Se);const et=Se instanceof Error?Se:new Error("Unknown error");(Ot=w.onError)==null||Ot.call(w,et),F.trackError(et.name||"ChatError",et.message||"Unknown chat error"),e||ee(i)}},we=async()=>{if(!R.trim()||C)return;O(),Qe();const z={role:"user",content:R};j(pe=>[...pe,z]),T(""),F.trackMessageSent(R.length,!!te);const fe=R.toLowerCase();if(Su.some(pe=>fe.includes(pe))){const pe=`G'day mate! I'm running Bob v${St} - she's running sweet as! Anything else I can help ya with?`;j(He=>[...He,{role:"assistant",content:pe}]),K||qe(pe);return}B(!0),console.log("[BobWidget STATE] User sent message - switching to RESEARCH state:",s),d==null||d(),e||ee(s),await Oe(z),B(!1)};return{messages:U,input:R,setInput:T,isLoading:C,handleSend:we,handleKeyPress:z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),we())},handleInputFocus:()=>{O()},handleInputBlur:()=>{},chatEndRef:M,clearMessages:()=>{j([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])},isMuted:K,toggleMute:()=>{Y(z=>!z),K||Qe()},isSpeaking:nt,identifiedVehicle:te,clearVehicle:()=>{$(null)}}},ju={states:[],configs:[],uploadedImages:[],looks:[],activeLookId:null},Ea=t=>{const e=va(),r=pr();return g.useEffect(()=>{if(!r)return;const s=r.channel("animation-states-changes").on("postgres_changes",{event:"*",schema:"public",table:"animation_states"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe(),n=r.channel("bob-animations-changes").on("postgres_changes",{event:"*",schema:"public",table:"bob_animations"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe();return()=>{r.removeChannel(s),r.removeChannel(n)}},[e,r]),xs({queryKey:["bob-animation-data",t],queryFn:async()=>{var k;if(!r)return console.log("[BobAnimation] No supabase client, returning empty data"),ju;const{data:s,error:n}=await r.from("bob_looks").select("*").order("display_order");if(n)throw n;const i=(s||[]).find(w=>w.is_active),a=t||(i==null?void 0:i.id)||s&&((k=s[0])==null?void 0:k.id)||null;if(!a)return console.warn("[BobAnimation] No looks configured in database"),{states:[],configs:[],uploadedImages:[],looks:s||[],activeLookId:null};console.log(`[BobAnimation] Loading animations for look: ${(i==null?void 0:i.name)||a}`);const{data:l,error:c}=await r.from("animation_states").select("*").eq("is_active",!0).eq("look_id",a).order("display_order");if(c)throw c;const{data:u,error:d}=await r.from("bob_animations").select("*").eq("is_active",!0).eq("look_id",a).order("animation_state").order("sequence_order");if(d)throw d;const h=(l||[]).map(w=>w.state_key);console.log(`[BobAnimation] Loaded ${h.length} states: ${h.join(", ")}`);const p=["idle","talking","listening"].filter(w=>{const E=[w,w.replace("ing",""),w+"ing"];return!h.some(A=>E.includes(A))});p.length>0&&console.warn(`[BobAnimation] ⚠️ Missing critical states: ${p.join(", ")}`);const v=new Set(h),m=(u||[]).filter(w=>v.has(w.animation_state));console.log(`[BobAnimation] Loaded ${m.length} animation frames`);const{data:b,error:y}=await r.storage.from("bob-images").list();if(y)throw y;const _=(b||[]).map(w=>{const{data:E}=r.storage.from("bob-images").getPublicUrl(w.name);return E.publicUrl});return m.forEach(w=>{const E=new Image;E.src=w.image_url}),{states:l||[],configs:m,uploadedImages:_,looks:s||[],activeLookId:a}},staleTime:30*1e3,gcTime:5*60*1e3})},ja=(t={})=>{const{isSpeaking:e=!1}=t,[r,s]=g.useState(""),[n,i]=g.useState(0),[a,l]=g.useState(400),[c,u]=g.useState(!1),d=g.useRef(null),h=g.useRef(0),f=g.useRef(e),p=g.useRef(0),v=g.useRef(0),m=g.useRef(!1),b=g.useRef(0),{data:y,isLoading:_}=Ea(),k=g.useRef({}),{imageUrlsMap:w,alternateImages:E,offsetsMap:A,scalesMap:F,availableStates:N}=g.useMemo(()=>{if(!y)return{imageUrlsMap:{},alternateImages:{},offsetsMap:{},scalesMap:{},availableStates:[]};const C={},B={},K={},Y={},te=y.states.map($=>$.state_key);return te.forEach($=>{const M=y.configs.filter(P=>P.animation_state===$),J=M.map(P=>P.image_url),oe=M.map(P=>P.vertical_offset||0),X=M.map(P=>P.scale||100);if(J.length>0){const P=y.states.find(D=>D.state_key===$);C[$]={url:J[0],animation_speed:(P==null?void 0:P.animation_speed)||400,pause_duration:(P==null?void 0:P.pause_duration)||0,loop_count:(P==null?void 0:P.loop_count)||0},B[$]=J,K[$]=oe,Y[$]=X}}),{imageUrlsMap:C,alternateImages:B,offsetsMap:K,scalesMap:Y,availableStates:te}},[y]);g.useEffect(()=>{k.current=w},[w]),g.useEffect(()=>{const C=f.current;if(f.current=e,C&&!e){const B=r.toLowerCase();(B.includes("talk")||B==="talking")&&(console.log("[useBobAnimation] Speech ended while in talk state - forcing loop completion"),v.current=999)}},[e,r]);const U=g.useCallback(C=>{s(B=>B===C?B:(p.current=0,v.current=0,m.current=!1,i(0),C))},[]);g.useEffect(()=>{N.length>0&&!r&&s(N[0])},[N,r]),g.useEffect(()=>{const C=E[r];if(d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),p.current=0,v.current=0,m.current=!1,h.current=0,i(0),!C||C.length<=1)return;const B=k.current[r],K=(B==null?void 0:B.animation_speed)||a||400,Y=(B==null?void 0:B.loop_count)||0,te=(B==null?void 0:B.pause_duration)||0,$=r.toLowerCase().includes("talk"),M=J=>{if(h.current===0&&(h.current=J),m.current){J-b.current>=te&&(m.current=!1,v.current=0,h.current=J),d.current=requestAnimationFrame(M);return}if(J-h.current>=K){h.current=J;const X=(p.current+1)%C.length;X===0?(v.current++,$&&f.current?(p.current=X,i(X)):Y>0&&v.current>=Y?te>0&&(m.current=!0,b.current=J):(p.current=X,i(X))):(p.current=X,i(X))}d.current=requestAnimationFrame(M)};return d.current=requestAnimationFrame(M),()=>{d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)}},[r,E,a]);const j=g.useCallback(()=>{const C=E[r];if(!C||C.length===0){const B=N.find(K=>{var Y;return((Y=E[K])==null?void 0:Y.length)>0});return B?(console.warn(`[useBobAnimation] No images for "${r}", using fallback: ${B}`),E[B][0]):(console.error("[useBobAnimation] No valid images found for any state!"),"")}return C[n]||C[0]},[E,r,N,n]),R=g.useCallback(()=>{const C=A[r];if(!C||C.length===0){const B=N.find(K=>{var Y;return((Y=A[K])==null?void 0:Y.length)>0});return B?A[B][0]:0}return C[n]||C[0]},[A,r,N,n]),T=g.useCallback(()=>{const C=F[r];if(!C||C.length===0){const B=N.find(K=>{var Y;return((Y=F[K])==null?void 0:Y.length)>0});return B?F[B][0]:100}return C[n]||C[0]},[F,r,N,n]);return{animationState:r,setAnimationState:U,getCurrentImage:j,getCurrentOffset:R,getCurrentScale:T,imageUrls:w,availableStates:N,setTalkSpeed:l,manualMode:c,setManualMode:u,isLoading:_}},Ta=()=>{const t=pr(),{data:e=[],isLoading:r}=xs({queryKey:["bob-backdrops"],queryFn:async()=>{if(!t)return console.log("[useBobBackdrop] No supabase client, returning empty"),[];const{data:n,error:i}=await t.from("bob_backdrops").select("*").order("display_order",{ascending:!0});if(i)throw i;return n},staleTime:5*60*1e3,gcTime:10*60*1e3}),s=e.find(n=>n.is_active);return{backdrops:e,activeBackdrop:s,isLoading:r}},Ra=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=12,className:i="",verticalOffset:a=0,scale:l=100})=>{const c=a+n,u=55*(l/100);return o.jsx("div",{className:`flex flex-col items-center justify-center gap-6 w-full ${i}`,children:o.jsxs("div",{className:"relative w-full max-w-[600px] mx-auto aspect-[16/10] overflow-hidden",children:[r&&o.jsx("img",{src:r,alt:"Backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-bottom"}),o.jsx("img",{src:t,alt:`Bob ${e}`,className:"absolute z-10 h-auto object-contain left-1/2 -translate-x-1/2",style:{bottom:`${c}%`,width:`${u}%`,maxWidth:`${220*(l/100)}px`,transformOrigin:"center bottom"}}),s&&o.jsx("img",{src:s,alt:"Counter",className:"absolute z-20 bottom-0 left-0 w-full object-cover object-bottom",style:{height:`${n}%`}})]})})},H={primary:"#0052CC",primaryHover:"#0047B3",secondary:"#38BDF8",foreground:"#0F172A",accent:"#FF8C00",success:"#22C55E",destructive:"#EF4444",performanceRed:"#DC2626",mutedForeground:"#64748B",background:"#FAFAFA",card:"#FFFFFF",border:"#E2E8F0",slateEconomy:"#475569"},$s={Economy:{icon:"DollarSign",emoji:"💰",textColor:"#475569",background:"#F1F5F9",border:"#CBD5E1",description:"Smart savings"},Standard:{icon:"Star",emoji:"⭐",textColor:"#0052CC",background:"rgba(0,82,204,0.1)",border:"rgba(0,82,204,0.3)",description:"Best value",isRecommended:!0},Premium:{icon:"Award",emoji:"🏆",textColor:"#D97706",background:"#FEF3C7",border:"#FCD34D",description:"Superior quality"},Performance:{icon:"Zap",emoji:"⚡",textColor:"#DC2626",background:"#FEE2E2",border:"#FCA5A5",description:"Maximum power"}},sn={"Oil Change":"Neglecting oil changes leads to engine wear, overheating, and catastrophic failure costing thousands. Quality oil and filters keep your engine running smoothly. Each CARFIX Oil Change Service Pack includes premium oil and filter matched to your engine specifications.","Front Brake Service":"Your front brakes handle 70% of stopping power. Worn pads dangerously increase stopping distance. Quality brake components ensure confident, safe stops. Each CARFIX Front Brake Service Pack includes pads and rotors to restore your braking performance.","Rear Brake Service":"Rear brakes provide stability and balance during emergency stops. Worn components cause instability and longer stopping distances. Each CARFIX Rear Brake Service Pack includes quality pads/shoes and rotors/drums for complete rear brake renewal.","Timing Belt Service":"A snapped timing belt destroys engines instantly, causing $8,000+ in damage. Preventive replacement is essential for peace of mind. Each CARFIX Timing Belt Service Pack includes the belt, tensioner, and related components.",Wipers:"Worn wipers reduce visibility in rain, compromising safety. Quality blades provide streak-free, clear vision. Each CARFIX Wipers Service Pack includes the gear you need to change all of your vehicle's wiper blades to restore your driving vision.","Coolant Service":"Old coolant causes overheating, warped cylinder heads, and engine seizure. Fresh coolant protects your entire cooling system. Each CARFIX Coolant Service Pack includes quality coolant matched to your vehicle's requirements.","Air Filter Service":"Clogged air filters reduce engine performance by 10% and increase fuel consumption. Clean filters improve power and economy. Each CARFIX Air Filter Service Pack includes a precision-fit filter for optimal airflow.","Spark Plug Service":"Worn spark plugs cause misfires, poor fuel economy, and catalytic converter damage. Fresh plugs restore smooth, efficient running. Each CARFIX Spark Plug Service Pack includes quality plugs matched to your engine.","Battery Service":"A failing battery leaves you stranded without warning. Reliable power is essential for starting and electronics. Each CARFIX Battery Service Pack includes a quality battery sized for your vehicle's demands.","Cabin Filter":"Cabin filters clean the air you and your passengers breathe. Replace regularly to remove pollen, dust, and odours. Each CARFIX Cabin Filter Service Pack includes a quality filter for fresh, clean cabin air.","Fuel Filter Service":"Clogged fuel filters restrict flow, causing poor performance and potential engine damage. Clean fuel is critical for efficiency. Each CARFIX Fuel Filter Service Pack includes a quality filter for optimal fuel delivery.","Transmission Service":"Old transmission fluid causes rough shifting, slipping, and premature wear. Fresh fluid extends transmission life. Each CARFIX Transmission Service Pack includes quality fluid matched to your transmission type."},Tu="Keep your vehicle running safely and efficiently with quality parts matched to your specific make and model. Each CARFIX Service Pack includes everything you need for this essential maintenance.",fs={storageBase:"https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public",productImage:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${t}.jpg`,brandLogo:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${t.replace(/\s+/g,"")}.jpg`,carfixImage:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/carfix_images/${t}_1.jpg`},Ca={fitsVehicle:{background:"rgba(34,197,94,0.1)",text:"#22C55E",border:"rgba(34,197,94,0.2)",icon:"Check",label:"Fits Your Vehicle"},viscosity:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",icon:"Gauge"},volume:{background:"#ECFEFF",text:"#0E7490",border:"#A5F3FC",icon:"Droplets"},quantity:{background:"#F1F5F9",text:"#475569",border:"#CBD5E1"},partNumber:{background:"transparent",text:"#64748B",border:"transparent"},carfixValue:{background:"rgba(0,82,204,0.1)",text:"#0052CC",border:"rgba(0,82,204,0.2)",icon:"Sparkles",label:"CARFIX Value"},rotorPair:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",label:"Pair"}},lt={packageTitle:{fontSize:"20px",fontWeight:700},partslotName:{fontSize:"14px",fontWeight:600},productName:{fontSize:"14px",fontWeight:500},description:{fontSize:"14px",fontWeight:400},priceMain:{fontSize:"20px",fontWeight:700},priceSecondary:{fontSize:"12px",fontWeight:400},tierLabel:{fontSize:"14px",fontWeight:500},badgeText:{fontSize:"12px",fontWeight:500}};function Aa(t){var s;const e=((s=t.name)==null?void 0:s.toLowerCase())||"",r=(t.partslotDescription||t.partslot_description||"").toLowerCase();return e.includes("rotor")||r.includes("disc rotor")||r.includes("brake rotor")||t.per_car_qty===2}function Oa(t,e){return e?{displayPrice:t*2,unitPriceLabel:`$${t.toFixed(2)} each`}:{displayPrice:t}}function Ge(t){return`$${t.toFixed(2)}`}function Pa(t){if(sn[t])return sn[t];const e=t.toLowerCase();for(const[r,s]of Object.entries(sn))if(e.includes(r.toLowerCase())||r.toLowerCase().includes(e))return s;return Tu}const es=({type:t,value:e,className:r=""})=>{const s=Ca[t],n=e||("label"in s?s.label:""),i=()=>{if(!("icon"in s))return null;const a={width:12,height:12};switch(s.icon){case"Check":return o.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",children:o.jsx("polyline",{points:"20 6 9 17 4 12"})});case"Sparkles":return o.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("path",{d:"M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3z"}),o.jsx("path",{d:"M5 19l1 3 1-3 3-1-3-1-1-3-1 3-3 1 3 1z"})]});case"Gauge":return o.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("circle",{cx:"12",cy:"12",r:"10"}),o.jsx("path",{d:"M12 6v6l4 2"})]});case"Droplets":return o.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:o.jsx("path",{d:"M12 2.69l5.66 5.66a8 8 0 11-11.31 0z"})});default:return null}};return o.jsxs("span",{className:r,style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",fontSize:"12px",fontWeight:500,background:s.background,color:s.text,border:`1px solid ${s.border}`,whiteSpace:"nowrap"},children:[i(),n]})},Mn=({products:t,title:e,onProductClick:r,onAddToCart:s})=>!t||t.length===0?null:o.jsxs("div",{style:{marginTop:"16px",width:"100%"},children:[e&&o.jsxs("div",{style:{marginBottom:"12px",fontSize:lt.partslotName.fontSize,fontWeight:lt.partslotName.fontWeight,color:H.foreground,display:"flex",alignItems:"center",gap:"8px"},children:[o.jsx("span",{style:{fontSize:"18px"},children:"🚗"}),e]}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:t.slice(0,6).map((n,i)=>o.jsx(Ru,{product:n,onProductClick:r,onAddToCart:s,isRecommended:i===0},n.id||n.sku||i))}),t.length>6&&o.jsxs("div",{style:{marginTop:"12px",fontSize:"13px",color:H.mutedForeground,textAlign:"center"},children:["+ ",t.length-6," more options available"]})]}),Ru=({product:t,onProductClick:e,onAddToCart:r,isRecommended:s=!1})=>{const[n,i]=g.useState(!1),[a,l]=g.useState(!1),c=t.image_url||t.image||(t.sku?fs.productImage(t.sku):null),u=t.brand?fs.brandLogo(t.brand):null,d=t.brand||"Quality Part",h=t.name||"Product",f=t.price??0,p=t.partNumber||t.part_number,v=Aa({name:t.name,partslotDescription:t.partslotDescription,per_car_qty:t.quantity}),{displayPrice:m,unitPriceLabel:b}=Oa(f,v);return o.jsxs("div",{style:{background:H.card,borderRadius:"12px",border:`2px solid ${H.border}`,overflow:"hidden",cursor:e?"pointer":"default",transition:"all 0.2s ease"},onClick:()=>e==null?void 0:e(t),onMouseEnter:y=>{y.currentTarget.style.borderColor=`${H.primary}80`,y.currentTarget.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)"},onMouseLeave:y=>{y.currentTarget.style.borderColor=H.border,y.currentTarget.style.boxShadow="none"},children:[t.partslotDescription&&o.jsxs("div",{style:{background:"rgba(0,0,0,0.03)",borderBottom:`1px solid ${H.border}`,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsx("span",{style:{fontSize:lt.partslotName.fontSize,fontWeight:lt.partslotName.fontWeight,color:H.foreground},children:t.partslotDescription}),s&&o.jsx(es,{type:"carfixValue"})]}),o.jsxs("div",{style:{padding:"16px",display:"flex",gap:"16px"},children:[o.jsx("div",{style:{width:"96px",minWidth:"96px",height:"96px",borderRadius:"8px",background:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",border:`1px solid ${H.border}`},children:c&&!n?o.jsx("img",{src:c,alt:h,style:{width:"100%",height:"100%",objectFit:"contain",padding:"4px"},onError:()=>i(!0)}):o.jsx("span",{style:{fontSize:"32px",opacity:.5},children:"🔧"})}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:[u&&!a&&o.jsx("img",{src:u,alt:d,style:{height:"16px",width:"auto",objectFit:"contain"},onError:()=>l(!0)}),o.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:H.foreground,textTransform:"uppercase"},children:d})]}),o.jsx("div",{style:{fontSize:lt.productName.fontSize,fontWeight:lt.productName.fontWeight,color:H.foreground,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",lineHeight:"1.4",marginBottom:"8px"},children:h}),o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"12px"},children:[o.jsx(es,{type:"fitsVehicle"}),v&&o.jsx(es,{type:"rotorPair"}),t.quantity&&t.quantity>1&&!v&&o.jsx(es,{type:"quantity",value:`Qty: ${t.quantity}`}),p&&o.jsxs("span",{style:{fontSize:"12px",color:H.mutedForeground},children:["#",p]})]})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",justifyContent:"space-between",minWidth:"100px"},children:[o.jsxs("div",{style:{textAlign:"right"},children:[o.jsx("div",{style:{fontSize:lt.priceMain.fontSize,fontWeight:lt.priceMain.fontWeight,color:H.foreground},children:Ge(m)}),b&&o.jsx("div",{style:{fontSize:lt.priceSecondary.fontSize,color:H.mutedForeground},children:b}),o.jsx("div",{style:{fontSize:lt.priceSecondary.fontSize,color:H.mutedForeground},children:"inc GST"})]}),r&&o.jsx("button",{onClick:y=>{y.stopPropagation(),r(t)},style:{background:H.primary,color:"#FFFFFF",border:"none",borderRadius:"8px",padding:"8px 16px",fontSize:"13px",fontWeight:600,cursor:"pointer",transition:"all 0.2s ease",whiteSpace:"nowrap"},onMouseEnter:y=>{y.currentTarget.style.background=H.primaryHover},onMouseLeave:y=>{y.currentTarget.style.background=H.primary},onMouseDown:y=>{y.currentTarget.style.transform="scale(0.98)"},onMouseUp:y=>{y.currentTarget.style.transform="scale(1)"},children:"Add to Cart"})]})]})]})},Ia=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:l,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,className:f="",onAddToCart:p,onProductClick:v})=>o.jsx("div",{className:f,style:{width:"100%",maxWidth:"72rem",margin:"0 auto",padding:"0 16px 32px 16px"},children:o.jsxs("div",{style:{backgroundColor:"rgba(20, 30, 50, 0.85)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"16px",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.3)",overflow:"hidden"},children:[o.jsx("div",{style:{padding:"16px",borderBottom:"1px solid rgba(255,255,255,0.1)",backgroundColor:"rgba(0,0,0,0.2)"},children:o.jsxs("div",{style:{display:"flex",gap:"8px"},children:[o.jsx("input",{value:e,onChange:m=>r(m.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Ask Bob about car parts...",disabled:s,style:{flex:1,padding:"12px 16px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",color:"white",fontSize:"16px",outline:"none"}}),d&&o.jsx("button",{onClick:d,style:{flexShrink:0,padding:"12px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",cursor:"pointer",minHeight:"unset",minWidth:"unset"},title:u?"Unmute Bob's voice":"Mute Bob's voice",children:u?"🔇":"🔊"}),o.jsx("button",{onClick:n,disabled:s||!e.trim(),style:{flexShrink:0,padding:"12px 20px",background:s||!e.trim()?"rgba(0, 102, 204, 0.3)":"linear-gradient(135deg, rgba(0, 102, 204, 0.95), rgba(0, 73, 153, 1))",color:"white",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.2)",cursor:s||!e.trim()?"not-allowed":"pointer",opacity:s||!e.trim()?.5:1,minHeight:"unset",minWidth:"unset",fontWeight:600},children:"Send"})]})}),o.jsxs("div",{style:{overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"12px",height:"400px",background:"rgba(0,0,0,0.1)"},children:[[...t].reverse().map((m,b)=>{var y;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:m.role==="user"?"flex-end":"flex-start"},children:o.jsxs("div",{style:{maxWidth:(y=m.suggestedProducts)!=null&&y.length?"100%":"80%",borderRadius:"16px",padding:"12px 16px",fontSize:"14px",backgroundColor:m.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.1)",background:m.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.08)",color:"white",border:"1px solid rgba(255,255,255,0.15)",boxShadow:"0 2px 8px rgba(0,0,0,0.2)"},children:[m.content,m.role==="assistant"&&m.suggestedProducts&&m.suggestedProducts.length>0&&o.jsx(Mn,{products:m.suggestedProducts,title:m.suggestionsTitle,onAddToCart:p,onProductClick:v})]})},b)}),o.jsx("div",{ref:c})]})]})}),Cu=768,Au=1024;function zs(){const[t,e]=g.useState("mobile");return g.useEffect(()=>{const r=()=>{const s=window.innerWidth;s>=Au?e("desktop"):s>=Cu?e("tablet"):e("mobile")};return r(),window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),t}function Wn(){const t=zs();return Ou(t)}function Ou(t){switch(t){case"mobile":return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-30,hiddenPosition:-100};case"tablet":return{bobOffset:.7,productWidth:.85,uiScale:1.1,partialLeftPosition:-25,hiddenPosition:-80};case"desktop":return{bobOffset:.5,productWidth:.7,uiScale:1.2,partialLeftPosition:-5,hiddenPosition:-60};default:return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-20,hiddenPosition:-100}}}const Hs=({currentImage:t,animationState:e,counterOverlayUrl:r,counterHeightPercent:s=15,scale:n=100,position:i="center",verticalOffset:a=0,hasArrived:l=!0})=>{const c=Wn(),d=95*n/100,h=550*n/100,f=()=>{switch(i){case"center":return"50%";case"partial-left":return`${c.partialLeftPosition}%`;case"hidden":return`${c.hiddenPosition}%`;default:return"50%"}},p=()=>i==="center"?"translateX(-50%)":"translateX(0)",v=s+a,m=()=>i==="hidden"?"all 0.35s cubic-bezier(0.4, 0, 0.2, 1)":"all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)";return o.jsxs("div",{className:"absolute inset-0 pointer-events-none",style:{overflow:"visible"},children:[o.jsx("div",{className:"absolute z-[60]",style:{bottom:`${v}%`,left:f(),maxHeight:`${100-s-2}%`,transform:p(),width:`${d}%`,maxWidth:`${h}px`,transition:m()+", opacity 0.6s ease-out",willChange:"transform, left, opacity",opacity:l?1:0},children:o.jsx("img",{src:t,alt:`Bob ${e}`,className:"w-full h-auto object-contain",style:{display:"block",maxHeight:"100%",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1})}),r&&o.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-[70]",style:{height:`${s}%`,pointerEvents:"none"},children:o.jsx("img",{src:r,alt:"Shop counter",className:"w-full h-full",style:{objectFit:"fill",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1})})]})},Pu={background:"rgba(20, 30, 50, 0.92)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"28px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.35), inset 0 0 0 1px rgba(255,255,255,0.1)"},Iu={background:"linear-gradient(135deg, rgba(40, 60, 100, 0.95) 0%, rgba(20, 40, 80, 0.98) 100%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(0, 0, 0, 0.35), 0 0 0 1px rgba(255,255,255,0.15), inset 0 1px 0 rgba(255,255,255,0.2)"},Na={background:"rgba(255, 255, 255, 0.08)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"28px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.3)"},ss={primary:{color:"rgba(255, 255, 255, 1)",textShadow:"0 1px 3px rgba(0,0,0,0.5)"}},Nu={background:"rgba(255, 255, 255, 0.12)",borderRadius:"20px",border:"1px solid rgba(255, 255, 255, 0.15)"},Pi={background:"rgba(255, 255, 255, 0.15)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"12px"},Bu={width:"4px",height:"4px",borderRadius:"50%",background:"rgba(255, 255, 255, 0.6)",boxShadow:"0 0 8px rgba(255, 255, 255, 0.4)"},Ba=({product:t,isSpotlighted:e=!1,onProductClick:r,onAddToCart:s})=>{const[n,i]=g.useState(!1),[a,l]=g.useState(0),c=()=>{r==null||r(t)},u=v=>{v.stopPropagation(),s==null||s(t)},d=()=>{a===0&&t.brandImageUrl?l(1):l(2)},h=a===0?t.image_url:a===1?t.brandImageUrl:void 0,f=e?Iu:Pu,p=t.webDescription||t.name;return o.jsxs("div",{onClick:c,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),className:"relative w-full cursor-pointer glass-card",style:{...f,padding:"16px",paddingBottom:"60px",position:"relative",transform:n?"scale(1.04) translateY(-4px)":"scale(1) translateY(0)",boxShadow:n?"0 16px 56px rgba(0, 0, 0, 0.4), 0 0 24px rgba(255,255,255,0.08)":f.boxShadow,transition:"transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.3s ease-out"},children:[e&&o.jsxs("div",{className:"absolute -top-2.5 -right-2.5 z-10 flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.95) 0%, rgba(0, 73, 153, 1) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"20px",boxShadow:"0 8px 24px rgba(0, 102, 204, 0.5)",color:"white"},children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"currentColor",viewBox:"0 0 20 20",children:o.jsx("path",{d:"M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"})}),"Bob's Pick"]}),o.jsxs("div",{className:"flex items-start gap-4",children:[o.jsx("div",{className:"flex-shrink-0 flex items-center justify-center overflow-hidden",style:{...Nu,width:"92px",height:"92px",backgroundColor:"#ffffff"},children:h&&a<2?o.jsx("img",{src:h,alt:t.name,className:"w-full h-full object-contain p-2",loading:"lazy",onError:d}):o.jsx("div",{className:"flex flex-col items-center justify-center",style:{color:"rgba(255,255,255,0.4)"},children:o.jsx("svg",{className:"w-8 h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"font-bold leading-tight",style:{fontSize:"15px",letterSpacing:"-0.01em",...ss.primary},children:p}),t.partNumber&&o.jsx("p",{className:"mt-0.5 text-xs",style:{color:"rgba(255,255,255,0.5)"},children:t.partNumber}),o.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[t.brand&&o.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5",style:{...Pi,color:"rgba(255, 255, 255, 0.9)"},children:[o.jsx("svg",{className:"w-2.5 h-2.5",fill:"currentColor",viewBox:"0 0 20 20",children:o.jsx("path",{fillRule:"evenodd",d:"M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),t.brand]}),t.perCarQty&&t.perCarQty>1&&o.jsxs("span",{className:"inline-flex items-center text-xs font-semibold px-2 py-0.5",style:{...Pi,color:"rgba(255, 200, 50, 0.95)"},children:["Qty: ",t.perCarQty]})]}),(t.viscosity||t.volume)&&o.jsx("p",{className:"mt-1 text-xs font-medium",style:{color:"rgba(255, 255, 255, 0.7)"},children:[t.viscosity,t.volume].filter(Boolean).join(" / ")}),o.jsx("p",{className:"font-extrabold mt-2",style:{fontSize:"22px",letterSpacing:"-0.02em",color:"#FFD700",textShadow:"0 2px 6px rgba(0, 0, 0, 0.5), 0 0 12px rgba(255, 215, 0, 0.3)"},children:t.price>0?`$${t.price.toFixed(2)}`:"POA"})]})]}),o.jsx("button",{onClick:u,className:"absolute flex items-center justify-center cursor-pointer",style:{bottom:"12px",right:"12px",background:"linear-gradient(135deg, #22C55E 0%, #16A34A 100%)",border:"1px solid rgba(255, 255, 255, 0.35)",borderRadius:"22px",boxShadow:"0 10px 40px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)",width:"44px",height:"44px",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease-out"},onMouseEnter:v=>{v.currentTarget.style.transform="scale(1.08) translateY(-2px)",v.currentTarget.style.boxShadow="0 14px 48px rgba(34, 197, 94, 0.5), inset 0 1px 0 rgba(255,255,255,0.4)"},onMouseLeave:v=>{v.currentTarget.style.transform="scale(1) translateY(0)",v.currentTarget.style.boxShadow="0 10px 40px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},children:o.jsx("svg",{className:"w-5 h-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M12 4v16m8-8H4"})})}),t.partslotDescription&&o.jsx("div",{className:"mt-3 pt-3",style:{borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:o.jsx("span",{className:"text-xs font-medium",style:{color:"rgba(255, 255, 255, 0.6)"},children:t.partslotDescription})})]})},Fu=["SHOE","DRUM"],Lu=["PAD","ROTOR"];function Fa(t){var s,n;const e=((s=t.id)==null?void 0:s.toLowerCase())||"",r=((n=t.title)==null?void 0:n.toLowerCase())||"";return e.includes("rear-brake")||r.includes("rear brake")}function La(t,e){const r=e==="disc"?Fu:Lu;return t.filter(s=>{const n=s.partslotName.toUpperCase();return!r.some(i=>n.includes(i))})}function $a(t){return t.reduce((e,r)=>e+r.displayPrice,0)}const Ii=(t,e)=>{if(!t||!e)return!1;const r=t.toLowerCase();return e.toLowerCase().replace(/s\b/g,"").split(/\s+/).filter(Boolean).every(n=>r.includes(n))},$u=(t,e)=>{var n;const r=((n=t.brand)==null?void 0:n.toLowerCase())===e.brand.toLowerCase(),s=Math.abs(t.price-e.price)<1;return r&&s},Du=({product:t,isSpotlighted:e,spotlightedRef:r,onProductClick:s})=>o.jsx("div",{ref:e?r:void 0,children:o.jsx(Ba,{product:t,isSpotlighted:e,onProductClick:s})}),Ks=({products:t,servicePackages:e,highlightedPartType:r,highlightedProduct:s,onProductClick:n,onPackageSelect:i,isResearching:a,visible:l=!0,counterHeightPercent:c=22,hasVehicle:u=!1,onAddToCart:d,vehicleMakeModel:h,pendingVariants:f,pendingVariantMake:p,pendingVariantModel:v,onVariantSelect:m})=>{const b=h||"Bob's Shelf",y=zs();Wn();const _=g.useRef(null),k=g.useRef({}),w=g.useRef(null),[E,A]=g.useState(null),[F,N]=g.useState({}),[U,j]=g.useState({}),R=g.useMemo(()=>{const P={};return t.forEach(V=>{const Q=V.partslotDescription||"Other Parts";P[Q]||(P[Q]=[]),P[Q].push(V)}),Object.keys(P).sort((V,Q)=>V.localeCompare(Q)).map(V=>({name:V,products:P[V]}))},[t]);g.useEffect(()=>{if(!r)return;const P=setTimeout(()=>{const D=Object.entries(k.current);for(const[V,Q]of D)if(Q&&Ii(V,r)){Q.scrollIntoView({behavior:"smooth",block:"start"});break}},300);return()=>clearTimeout(P)},[r]);const[T,C]=g.useState(0),B=P=>{const D=P.currentTarget,V=D.scrollHeight-D.clientHeight;if(V>0){const Q=D.scrollTop/V;C(Math.max(0,Math.min(1,Q)))}},K=((f==null?void 0:f.length)??0)>0,Y=t.length>0||e.length>0||K,te=a&&!Y,$=Y&&!te,M=l||Y,J=y==="mobile"?92:y==="tablet"?65:70,oe=y==="desktop"?"900px":y==="tablet"?"500px":"100%",X=y==="mobile"?"calc(8px + env(safe-area-inset-top, 4px))":"6px";return o.jsxs(o.Fragment,{children:[Y&&l&&o.jsx("div",{style:{position:"fixed",right:"2px",top:`calc(${T*65+18}%)`,...Bu,opacity:.8,transition:"top 0.1s ease-out",zIndex:100,pointerEvents:"none"}}),o.jsxs("div",{ref:_,onScroll:B,className:`absolute overflow-y-auto overflow-x-hidden flex flex-col gap-3 md:gap-4 transition-all duration-400 ease-out product-scroll ${M?"opacity-100 translate-x-0":"opacity-0 translate-x-12 pointer-events-none"}`,style:{width:`${J}%`,maxWidth:oe,right:"0",left:"auto",top:X,bottom:y==="mobile"?"calc(100px + env(safe-area-inset-bottom, 0px))":"52px",paddingTop:"4px",paddingRight:"16px",paddingLeft:"16px",paddingBottom:"8px",zIndex:55,pointerEvents:"auto",touchAction:"pan-y",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"},children:[o.jsx("div",{className:"sticky top-0 z-10 -mx-1 px-3 py-2.5",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.85) 0%, rgba(0, 73, 153, 0.9) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"24px",boxShadow:"0 10px 40px rgba(0, 102, 204, 0.4)",border:"1px solid rgba(255, 255, 255, 0.25)"},children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[a&&Y?o.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:o.jsx("div",{className:"w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin"})}):o.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:o.jsx("svg",{className:"w-3.5 h-3.5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),o.jsx("span",{style:{...ss.primary,fontWeight:700,fontSize:"14px",letterSpacing:"0.025em"},children:a&&Y?"Updating...":b})]}),o.jsxs("span",{style:{color:"rgba(255,255,255,0.8)",fontSize:"12px",fontWeight:500},children:[t.length+e.length," ",t.length+e.length===1?"item":"items"]})]})}),te&&o.jsx("div",{className:"p-5",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(0, 102, 204, 0.3)"},children:o.jsx("div",{className:"w-6 h-6 border-2 border-t-transparent rounded-full animate-spin",style:{borderColor:"rgba(255,255,255,0.8)",borderTopColor:"transparent"}})}),o.jsxs("div",{children:[o.jsx("p",{style:{...ss.primary,fontWeight:600,fontSize:"14px"},children:"Searching shelves..."}),o.jsx("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:"Finding the best parts for you"})]})]})}),K&&f&&m&&o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsx("div",{className:"sticky top-0 z-10 px-4 py-3",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"20px",boxShadow:"0 8px 32px rgba(0, 102, 204, 0.35)",border:"1px solid rgba(255, 255, 255, 0.2)"},children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:o.jsx("svg",{className:"w-4 h-4 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),o.jsxs("div",{children:[o.jsxs("span",{className:"text-white font-semibold text-sm",children:["Which ",p," ",v,"?"]}),o.jsx("span",{className:"text-white/70 text-xs block",children:"Tap your variant to continue"})]})]})}),o.jsx("div",{className:"flex flex-col gap-2 px-1",children:(()=>{const P=(f||[]).map(V=>[V.engineCode,V.kw?`${V.kw}kW`:null,V.ccDisplay||(V.cc?`${V.cc}cc`:null),V.fuelType].filter(Boolean).join(" · ")||V.displayTitle),D=P.reduce((V,Q)=>(V[Q]=(V[Q]||0)+1,V),{});return(f||[]).map((V,Q)=>{const _e=P[Q],Ae=D[_e]>1&&V.displaySubtitle?V.displaySubtitle:_e;return o.jsx("button",{type:"button",onClick:()=>m(V),className:"w-full text-left transition-all duration-200 cursor-pointer rounded-2xl overflow-hidden focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 active:scale-[0.98]",style:{background:"linear-gradient(135deg, rgba(255, 255, 255, 0.92) 0%, rgba(255, 255, 255, 0.85) 100%)",backdropFilter:"blur(12px) saturate(150%)",WebkitBackdropFilter:"blur(12px) saturate(150%)",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.12)",border:"1px solid rgba(255, 255, 255, 0.4)",minHeight:"72px"},children:o.jsxs("div",{className:"flex items-center gap-3 p-4",children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center shrink-0 font-bold text-lg text-white",style:{background:"linear-gradient(135deg, #0066CC 0%, #0052A3 100%)",boxShadow:"0 2px 8px rgba(0, 102, 204, 0.4)"},children:V.optionNumber}),o.jsx("div",{className:"flex-1 min-w-0",children:o.jsx("p",{className:"font-semibold text-gray-900 text-base leading-tight",children:Ae})}),o.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{background:"rgba(0, 102, 204, 0.1)"},children:o.jsx("svg",{className:"w-4 h-4 text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M9 5l7 7-7 7"})})})]})},V.vehicle_id)})})()})]}),!te&&!Y&&o.jsx("div",{className:"p-5",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(255, 149, 0, 0.3)"},children:o.jsx("svg",{className:"w-5 h-5",style:{color:"#FF9500"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),o.jsxs("div",{children:[o.jsx("p",{style:{...ss.primary,fontWeight:600,fontSize:"14px"},children:"No products to display"}),o.jsxs("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:["Products: ",t.length," | Packages: ",e.length]})]})]})}),$&&e.length>0&&o.jsx("div",{className:"space-y-4",children:e.map(P=>{var Qe,nt;const D=Fa(P),V=U[P.id]||"disc";let Q=(P.preparedTiers||[]).filter(O=>!O.isHidden);D&&(Q=Q.map(O=>{const ee=La(O.products,V);return{...O,products:ee,totalPrice:$a(ee),productCount:ee.length}}));const _e=((Qe=Q.find(O=>O.isRecommended))==null?void 0:Qe.tierName)||((nt=Q[0])==null?void 0:nt.tierName)||"",Te=F[P.id]||_e,Ae=Q.find(O=>O.tierName===Te),Je=Pa(P.title).split(".")[0]+".",qe=E===P.id;return o.jsxs("div",{className:"overflow-hidden transition-all duration-300",style:{background:H.card,borderRadius:"16px",border:`1px solid ${H.border}`,boxShadow:"0 4px 20px rgba(0,0,0,0.08)"},children:[o.jsx("div",{className:"px-4 py-3",style:{background:`linear-gradient(135deg, ${H.primary} 0%, ${H.primaryHover} 100%)`},children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 flex items-center justify-center flex-shrink-0",children:o.jsx("svg",{className:"h-5 w-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h3",{className:"text-white font-bold text-base leading-tight truncate",children:P.title}),P.estimated_time&&o.jsx("div",{className:"flex items-center gap-3 mt-0.5",children:o.jsxs("span",{className:"text-white/70 text-xs flex items-center gap-1",children:[o.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),P.estimated_time]})})]})]})}),o.jsxs("div",{className:"px-4 py-3 border-b",style:{borderColor:H.border},children:[o.jsx("p",{className:"text-sm leading-relaxed",style:{color:H.mutedForeground},children:Je}),D&&o.jsxs("div",{className:"mt-2 mb-1",children:[o.jsx("p",{className:"text-[11px] mb-1.5",style:{color:H.mutedForeground},children:"Select your vehicle's rear brake type"}),o.jsxs("div",{className:"flex rounded-xl overflow-hidden border",style:{borderColor:H.border},children:[o.jsx("button",{onClick:()=>j(O=>({...O,[P.id]:"disc"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:V==="disc"?H.primary:"transparent",color:V==="disc"?"#FFFFFF":H.mutedForeground},children:"Disc Brakes (Pads + Rotors)"}),o.jsx("button",{onClick:()=>j(O=>({...O,[P.id]:"drum"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:V==="drum"?H.primary:"transparent",color:V==="drum"?"#FFFFFF":H.mutedForeground},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),Q.length>0&&o.jsxs("div",{className:"p-3",children:[o.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2 px-1",style:{color:H.mutedForeground},children:"Choose Your Value Level"}),o.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:`repeat(${Math.min(Q.length,4)}, 1fr)`},children:Q.map(O=>{const ee=$s[O.tierName],Oe=O.tierName===Te;return o.jsxs("div",{onClick:()=>N(we=>({...we,[P.id]:O.tierName})),className:"relative rounded-xl text-center transition-all cursor-pointer",style:{padding:Q.length>=4?"6px 4px":"8px",background:O.isRecommended?`${H.primary}10`:Oe?`${H.primary}05`:H.background,border:`2px solid ${O.isRecommended?H.primary:Oe?H.primary+"80":H.border}`},children:[O.isRecommended&&o.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wide whitespace-nowrap",style:{background:H.primary,color:"white"},children:"Carfix Value"}),o.jsxs("p",{className:"text-sm font-bold mt-1",style:{color:(ee==null?void 0:ee.textColor)||H.foreground},children:[ee==null?void 0:ee.emoji," ",O.displayName]}),o.jsx("div",{className:"flex flex-col items-center gap-1 mt-2",style:{minHeight:Q.length>=4?"40px":"48px"},children:O.brands.slice(0,1).map((we,me)=>{const ie=`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${we.fullName.replace(/\s+/g,"")}.jpg`;return o.jsx("div",{className:"w-full bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{height:Q.length>=4?"36px":"44px",maxWidth:Q.length>=4?"64px":"80px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",border:"1px solid #F1F5F9"},children:o.jsx("img",{src:we.imageUrl,alt:we.fullName,className:"w-auto object-contain",style:{height:Q.length>=4?"26px":"32px"},onError:ht=>{const ke=ht.target;ke.src!==ie?ke.src=ie:(ke.style.display="none",ke.parentElement.innerHTML=`<span class="text-[10px] font-semibold text-gray-600 truncate px-1">${we.fullName}</span>`)}})},me)})}),o.jsxs("p",{className:"text-[10px] mt-2",style:{color:H.mutedForeground},children:[O.productCount," ",O.productCount===1?"part":"parts"]}),O.savingsAmount&&O.savingsAmount>0?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-[11px] line-through",style:{color:H.mutedForeground},children:Ge(O.originalTotalPrice)}),o.jsx("p",{className:"text-base font-bold",style:{color:H.success},children:Ge(O.totalPrice)}),o.jsxs("p",{className:"text-[9px] font-semibold px-1.5 py-0.5 rounded-full mt-0.5",style:{background:`${H.success}15`,color:H.success},children:["SAVE ",Ge(O.savingsAmount)," — ",O.bundleDiscountPercentage,"% Bundle Deal"]})]}):o.jsx("p",{className:"text-base font-bold mt-1",style:{color:H.foreground},children:Ge(O.totalPrice)}),o.jsx("p",{className:"text-[10px]",style:{color:H.mutedForeground},children:"inc GST"}),o.jsx("button",{onClick:we=>{we.stopPropagation();const me=O.bundleDiscountPercentage||0,ie=1-me/100,ht=O.products.map(ke=>({id:ke.sku,name:ke.name,brand:ke.brand,price:me>0?Math.round(ke.displayPrice*ie*100)/100:ke.displayPrice,sku:ke.sku,partNumber:ke.partNumber||void 0,image_url:ke.productImageUrl,partslotDescription:ke.partslotName,quantity:1}));d==null||d(ht)},className:"w-full mt-2 py-1.5 rounded-lg text-[10px] font-semibold transition-all",style:{background:O.isRecommended?H.success:"#F1F5F9",color:O.isRecommended?"white":H.success,border:O.isRecommended?"none":"1px solid #E2E8F0",textAlign:"center"},children:"Add"})]},O.tierName)})})]}),o.jsxs("div",{onClick:()=>A(qe?null:P.id),className:"flex items-center justify-center gap-1.5 py-2 cursor-pointer hover:bg-gray-50 transition-colors border-t",style:{borderColor:H.border},children:[o.jsx("span",{className:"text-xs",style:{color:H.mutedForeground},children:qe?"Hide details":"Show details"}),o.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${qe?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",style:{color:H.mutedForeground},children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),qe&&Ae&&o.jsx("div",{className:"px-4 pb-4 border-t animate-in slide-in-from-top-2 duration-200",style:{borderColor:H.border},children:o.jsxs("div",{className:"pt-3",children:[o.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide mb-3",style:{color:H.mutedForeground},children:[Ae.displayName," Tier Products"]}),o.jsx("div",{className:"space-y-2",children:Ae.products.map(O=>o.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg",style:{background:H.background,border:`1px solid ${H.border}`},children:[o.jsx("div",{className:"w-14 h-14 flex-shrink-0 bg-white rounded-lg overflow-hidden flex items-center justify-center",children:O.productImageUrl?o.jsx("img",{src:O.productImageUrl,alt:O.name,className:"w-full h-full object-contain p-1"}):o.jsx("svg",{className:"w-6 h-6 text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-xs font-medium truncate",style:{color:H.foreground},children:O.name}),o.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[o.jsx("span",{className:"text-[10px]",style:{color:H.mutedForeground},children:O.brand}),O.isRotor&&o.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 font-medium",children:"Pair"})]}),o.jsx("p",{className:"text-[10px] mt-0.5",style:{color:H.mutedForeground},children:O.partslotName})]}),o.jsxs("div",{className:"text-right flex-shrink-0",children:[o.jsx("p",{className:"text-sm font-bold",style:{color:H.primary},children:Ge(O.displayPrice)}),O.isRotor&&o.jsxs("p",{className:"text-[9px]",style:{color:H.mutedForeground},children:["$",O.price.toFixed(2)," ea"]})]})]},O.sku))})]})})]},P.id)})}),$&&R.map(({name:P,products:D})=>{const V=r&&Ii(P,r);return o.jsxs("section",{ref:Q=>{k.current[P]=Q},className:"transition-all duration-300",style:{background:"transparent",borderRadius:"24px"},children:[o.jsxs("div",{"data-testid":"partslot-header","data-partslot-name":P,className:"px-3 py-2.5 flex items-center justify-between",style:{background:V?"rgba(0, 102, 204, 0.95)":"rgba(0, 51, 102, 0.9)",borderRadius:"16px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",marginBottom:"8px"},children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("div",{className:"w-5 h-5 rounded-md flex items-center justify-center flex-shrink-0",style:{background:V?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 1) 100%)":"rgba(255,255,255,0.2)"},children:o.jsx("svg",{className:"h-3 w-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),o.jsx("span",{className:"text-xs font-bold truncate uppercase tracking-wide",style:{color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)"},children:P})]}),o.jsx("span",{className:"text-[10px] font-bold px-2.5 py-1 rounded-full flex-shrink-0",style:{background:"rgba(255, 149, 0, 0.9)",color:"white",boxShadow:"0 2px 8px rgba(255, 149, 0, 0.4)"},children:D.length})]}),o.jsx("div",{className:"flex flex-col gap-3",children:D.map((Q,_e)=>{const Te=!!(s&&$u(Q,s));return o.jsx("div",{"data-testid":"partslot-product",children:o.jsx(Du,{product:Q,isSpotlighted:Te,spotlightedRef:w,onProductClick:n,viewportSize:y})},`${Q.id}-${_e}`)})})]},P)}),o.jsx("div",{className:"h-4"})]})]})},qn=({onTranscript:t,onSpeechEnd:e,language:r="en-NZ",mode:s="toggle"}={})=>{const[n,i]=g.useState(!1),[a,l]=g.useState(""),[c,u]=g.useState(""),[d,h]=g.useState(null),[f,p]=g.useState(!1),v=g.useRef(null),m=g.useRef(""),b=g.useRef(t),y=g.useRef(e),_=g.useRef(null),k=15e3;g.useEffect(()=>{b.current=t,y.current=e},[t,e]),g.useEffect(()=>{if(typeof window<"u"&&window.location.protocol!=="https:"&&window.location.hostname!=="localhost"&&window.location.hostname!=="127.0.0.1"){console.warn("[BobWidget] Speech recognition requires HTTPS. PTT will not work on HTTP."),h("Voice input requires a secure connection (HTTPS)"),p(!1);return}const F=window.SpeechRecognition||window.webkitSpeechRecognition;if(F){p(!0);const N=new F;N.continuous=s==="ptt",N.interimResults=!0,N.lang=r,N.maxAlternatives=1,N.onstart=()=>{i(!0),h(null)},N.onresult=U=>{let j="",R="";for(let T=U.resultIndex;T<U.results.length;T++){const C=U.results[T][0].transcript;U.results[T].isFinal?R+=C:j+=C}R&&(m.current=R,l(R),b.current&&b.current(R)),u(j)},N.onerror=U=>{switch(i(!1),U.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.")}},N.onend=()=>{_.current&&(clearTimeout(_.current),_.current=null),i(!1),u(""),m.current&&y.current&&y.current(m.current),m.current=""},v.current=N}return()=>{v.current&&v.current.stop()}},[r,s]);const w=()=>{v.current&&!n&&(l(""),u(""),h(null),_.current=setTimeout(()=>{console.warn("[SpeechRecognition] Safety timeout - forcing stop after 15s"),v.current&&v.current.abort(),i(!1),u("")},k),v.current.start())},E=()=>{_.current&&(clearTimeout(_.current),_.current=null),v.current&&n&&v.current.stop()};return{isListening:n,transcript:a,interimTranscript:c,error:d,isSupported:f,startListening:w,stopListening:E,toggleListening:()=>{n?E():w()}}},Da=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:l,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,onAddToCart:f,onProductClick:p,counterHeightPercent:v=22})=>{var X;const[m,b]=g.useState(!1),y=g.useRef(null),_=g.useRef(!1),{bottomOffset:k,zIndexBase:w}=Un(),{isListening:E,interimTranscript:A,error:F,isSupported:N,startListening:U,stopListening:j}=qn({onTranscript:P=>r(P),language:"en-NZ",mode:"ptt"});g.useEffect(()=>{A&&r(A)},[A,r]);const R=g.useCallback(P=>{P.preventDefault(),!(s||_.current)&&(_.current=!0,navigator.vibrate&&navigator.vibrate(30),U())},[s,U]),T=g.useCallback(()=>{_.current&&(_.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),j(),setTimeout(()=>{n()},150))},[j,n]),C=[...t].reverse().find(P=>P.role==="assistant"),B=((X=C==null?void 0:C.suggestedProducts)==null?void 0:X.length)||0,K=C!=null&&C.content?C.content.length>50?C.content.slice(0,50)+"...":C.content:"Ask Bob about car parts...",Y=B>0?` (${B} products)`:"",te={idle:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 8px 32px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"32px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},$=h?"speaking":s?"processing":E?"listening":"idle",J={idle:te.idle,listening:te.active,processing:te.disabled,speaking:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.95) 0%, rgba(22, 163, 74, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"}}[$],oe={idle:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-breathe 2s ease-in-out infinite"},listening:null,processing:{border:"2px solid rgba(156, 163, 175, 0.6)",animation:"ring-processing 1.5s ease-in-out infinite"},speaking:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-speaking 1.8s ease-in-out infinite"}};return o.jsxs("div",{ref:y,style:{position:"fixed",bottom:k,left:0,right:0,...Na,borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"all 0.3s ease-out",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:m?"55vh":"90px",zIndex:w+80,paddingBottom:"env(safe-area-inset-bottom, 8px)"},children:[o.jsx("button",{onClick:()=>b(!m),style:{position:"absolute",top:"-20px",left:"50%",transform:"translateX(-50%)",background:"rgba(255, 255, 255, 0.15)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"9999px",padding:"6px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)",zIndex:w+90,cursor:"pointer",minHeight:"unset",minWidth:"unset"},"aria-label":m?"Collapse chat":"Expand chat",children:m?o.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}):o.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 15l7-7 7 7"})})}),!m&&o.jsx("div",{onClick:()=>b(!0),style:{padding:"8px 12px 2px 12px",cursor:"pointer"},children:o.jsxs("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[K,Y&&o.jsx("span",{style:{color:"rgba(255,200,0,0.9)",fontWeight:600},children:Y})]})}),m&&o.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px"},className:"glass-scroll",children:[[...t].reverse().map((P,D)=>{var V;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:P.role==="user"?"flex-end":"flex-start"},children:o.jsxs("div",{style:{maxWidth:(V=P.suggestedProducts)!=null&&V.length?"100%":"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:P.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:[P.content,P.role==="assistant"&&P.suggestedProducts&&P.suggestedProducts.length>0&&o.jsx(Mn,{products:P.suggestedProducts,title:P.suggestionsTitle,onAddToCart:f,onProductClick:p})]})},D)}),o.jsx("div",{ref:c})]}),N&&o.jsxs("div",{style:{display:"flex",justifyContent:"center",padding:"12px 16px 8px 16px",position:"relative"},children:[$==="listening"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),$!=="listening"&&oe[$]&&o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:oe[$].border,transform:"translate(-50%, -50%)",animation:oe[$].animation,pointerEvents:"none"}}),o.jsx("button",{onTouchStart:R,onTouchEnd:T,onTouchCancel:T,onMouseDown:R,onMouseUp:T,onMouseLeave:T,onClick:E?T:void 0,disabled:$==="processing","aria-label":"Hold to talk to Bob",className:"glass-button bob-ptt-btn",style:{width:"200px",height:"64px",minHeight:"unset",minWidth:"unset",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",touchAction:"none",cursor:$==="processing"?"not-allowed":"pointer",opacity:$==="processing"?.6:1,transform:$==="listening"?"scale(1.04)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease, background 0.3s ease",backdropFilter:J.backdropFilter,WebkitBackdropFilter:J.WebkitBackdropFilter,"--bob-ptt-bg":J.background,"--bob-ptt-shadow":J.boxShadow,"--bob-ptt-border":J.border,"--bob-ptt-radius":"32px"},title:"Hold to talk",children:o.jsx("span",{style:{fontSize:"22px",fontWeight:800,letterSpacing:"0.15em",...ss.primary,textTransform:"uppercase",fontFamily:"system-ui, -apple-system, sans-serif"},children:$==="listening"?"LISTENING":$==="processing"?"THINKING":$==="speaking"?"PLAYING":"TALK"})})]}),o.jsxs("div",{style:{padding:"4px 12px 8px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:[F&&o.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:F}),o.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[d&&o.jsx("button",{onClick:d,style:{flexShrink:0,height:"40px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"12px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:h?"#0066CC":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?o.jsxs("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):o.jsx("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),o.jsxs("div",{style:{flex:1,position:"relative",height:"40px"},children:[o.jsx("input",{type:"text",value:e,onChange:P=>r(P.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Message Bob...",disabled:$!=="idle",className:"high-contrast-input bob-chat-input",style:{width:"100%",height:"40px",fontSize:"16px",padding:"0 14px",background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",color:"#0F172A",outline:"none",opacity:$!=="idle"?0:1,transition:"opacity 0.15s ease"}}),$!=="idle"&&o.jsxs("div",{className:"bob-state-overlay",style:{position:"absolute",inset:0,background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",display:"flex",alignItems:"center",padding:"0 14px",gap:"8px"},children:[$==="listening"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#FF8C00",animation:"dot-pulse 1s ease-in-out infinite",flexShrink:0}}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Listening..."})]}),$==="processing"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{width:"18px",height:"18px",flexShrink:0,border:"2px solid rgba(15, 23, 42, 0.15)",borderTop:"2px solid #0F172A",borderRadius:"50%",animation:"processing-spin 0.8s linear infinite"}}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is researching your input."})]}),$==="speaking"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{display:"flex",alignItems:"center",gap:"2px",height:"20px",flexShrink:0},children:[0,.15,.3,.45,.6].map((P,D)=>o.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${P}s infinite`}},D))}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is talking..."}),u&&o.jsxs("svg",{style:{height:"16px",width:"16px",color:"#ef4444",marginLeft:"auto",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]})]})]})]})]})]})]})},Ua=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:f,chatEndRef:p,isMuted:v,onToggleMute:m,isSpeaking:b,products:y,servicePackages:_,highlightedPartType:k,highlightedProduct:w,onProductClick:E,onPackageSelect:A,isResearching:F,vehicle:N,onChangeVehicle:U,pendingVariants:j,pendingVariantMake:R,pendingVariantModel:T,onVariantSelect:C,bobOffset:B=0,bobScale:K=100,embedded:Y=!1})=>{console.log("[MobileBobLayout] Rendering with:",{currentImage:(t==null?void 0:t.substring(0,50))||"EMPTY",backdropUrl:(r==null?void 0:r.substring(0,50))||"NONE",counterOverlayUrl:(s==null?void 0:s.substring(0,50))||"NONE"});const te=zs(),[$,M]=g.useState("center"),[J,oe]=g.useState("hidden"),X=y.length>0||_.length>0,P=((j==null?void 0:j.length)??0)>0,D=X||P,_e=(()=>{switch(te){case"desktop":return 70;case"tablet":return 80;case"mobile":return 140;default:return 140}})()*K/100;g.useEffect(()=>{if(F&&J!=="loading"&&J!=="visible")oe("loading"),$==="center"&&M("partial-left");else if(D&&J!=="visible")if($==="center"){M("partial-left"),oe("transitioning");const Ae=setTimeout(()=>{oe("visible")},400);return()=>clearTimeout(Ae)}else oe("visible");else!D&&!F&&J!=="hidden"&&(oe("hidden"),M("center"))},[D,F,J,$]);const Te=J!=="hidden";return o.jsxs("div",{className:Y?"absolute inset-0 overflow-hidden":"fixed inset-0 overflow-hidden",style:{height:Y?"100%":"100dvh",touchAction:"manipulation"},children:[r&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"absolute inset-0 z-0",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)",transform:"scale(1.02)"}}),o.jsx("div",{className:"absolute inset-0 z-[1]",style:{background:"rgba(0, 0, 0, var(--bob-overlay-opacity, 0.1))"}})]}),o.jsx(Hs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:_e,position:$,verticalOffset:B}),o.jsx(Ks,{products:y,servicePackages:_,highlightedPartType:k,highlightedProduct:w,onProductClick:E,onPackageSelect:A,isResearching:F,visible:Te,counterHeightPercent:n,hasVehicle:!!N,pendingVariants:j,pendingVariantMake:R,pendingVariantModel:T,onVariantSelect:C}),o.jsx(Da,{messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:f,chatEndRef:p,isMuted:v,onToggleMute:m,isSpeaking:b,onAddToCart:E,onProductClick:E,counterHeightPercent:n})]})},Ma=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:l,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,counterHeightPercent:f=22})=>{const[p,v]=g.useState(!1),m=g.useRef(null),b=g.useRef(!1),{bottomOffset:y,zIndexBase:_}=Un(),{isListening:k,interimTranscript:w,error:E,isSupported:A,startListening:F,stopListening:N}=qn({onTranscript:$=>r($),language:"en-NZ",mode:"ptt"});g.useEffect(()=>{w&&r(w)},[w,r]);const U=g.useCallback($=>{$.preventDefault(),!(s||b.current)&&(b.current=!0,navigator.vibrate&&navigator.vibrate(30),F())},[s,F]),j=g.useCallback(()=>{b.current&&(b.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),N(),setTimeout(()=>{n()},150))},[N,n]),R=[...t].reverse().find($=>$.role==="assistant"),T=R!=null&&R.content?R.content.length>50?R.content.slice(0,50)+"...":R.content:"Ask Bob about car parts...",C={idle:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 8px 32px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"50%",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},B=h?"speaking":s?"processing":k?"listening":"idle",Y={idle:C.idle,listening:C.active,processing:C.disabled,speaking:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 12px 48px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"}}[B],te={idle:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-breathe 2s ease-in-out infinite"},listening:null,processing:{border:"2px solid rgba(156, 163, 175, 0.6)",animation:"ring-processing 1.5s ease-in-out infinite"},speaking:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-speaking 1.8s ease-in-out infinite"}};return o.jsxs("div",{ref:m,style:{position:"absolute",bottom:0,left:0,right:0,top:"auto",contain:"layout",transform:"translateZ(0)",WebkitTransform:"translateZ(0)",backfaceVisibility:"hidden",WebkitBackfaceVisibility:"hidden",isolation:"isolate",...Na,borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"height 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:p?"55%":"110px",overflow:"visible",zIndex:_+30,paddingBottom:"calc(8px + env(safe-area-inset-bottom, 0px))",pointerEvents:"none"},children:[o.jsx("button",{onClick:()=>v(!p),style:{position:"absolute",top:"-24px",left:"50%",transform:"translateX(-50%)",background:"rgba(0, 102, 204, 0.9)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"2px solid rgba(255, 255, 255, 0.35)",borderRadius:"9999px",padding:"8px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.3)",zIndex:_+40,cursor:"pointer",minHeight:"32px",minWidth:"32px",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto"},"aria-label":p?"Collapse chat":"Expand chat",children:p?o.jsx("svg",{style:{height:"16px",width:"16px",color:"white"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 9l-7 7-7-7"})}):o.jsx("svg",{style:{height:"16px",width:"16px",color:"white"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M5 15l7-7 7 7"})})}),!p&&o.jsx("div",{onClick:()=>v(!0),style:{padding:"6px 12px 4px 12px",height:"26px",overflow:"hidden",cursor:"pointer",pointerEvents:"auto"},children:o.jsx("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T})}),p&&o.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px",pointerEvents:"auto"},className:"glass-scroll",children:[[...t].reverse().map(($,M)=>o.jsx("div",{style:{display:"flex",justifyContent:$.role==="user"?"flex-end":"flex-start"},children:o.jsx("div",{style:{maxWidth:"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:$.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:$.content})},M)),o.jsx("div",{ref:c})]}),o.jsxs("div",{style:{padding:p?"8px 12px 4px 12px":"4px 12px 4px 12px",borderTop:p?"1px solid rgba(255, 255, 255, 0.15)":"none",pointerEvents:"auto"},children:[E&&o.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:E}),o.jsxs("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[d&&p&&o.jsx("button",{onClick:d,style:{flexShrink:0,height:"36px",width:"36px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"10px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:h?"#22c55e":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?o.jsxs("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):o.jsx("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),o.jsxs("div",{style:{flex:1,position:"relative",height:"40px"},children:[o.jsx("input",{type:"text",value:e,onChange:$=>r($.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Message Bob...",disabled:B!=="idle",className:"high-contrast-input bob-chat-input",style:{width:"100%",height:"40px",fontSize:"16px",padding:"0 14px",background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",color:"#0F172A",outline:"none",opacity:B!=="idle"?0:1,transition:"opacity 0.15s ease"}}),B!=="idle"&&o.jsxs("div",{className:"bob-state-overlay",style:{position:"absolute",inset:0,background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",display:"flex",alignItems:"center",padding:"0 14px",gap:"8px"},children:[B==="listening"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#FF8C00",animation:"dot-pulse 1s ease-in-out infinite",flexShrink:0}}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Listening..."})]}),B==="processing"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{width:"18px",height:"18px",flexShrink:0,border:"2px solid rgba(15, 23, 42, 0.15)",borderTop:"2px solid #0F172A",borderRadius:"50%",animation:"processing-spin 0.8s linear infinite"}}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is researching your input."})]}),B==="speaking"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{display:"flex",alignItems:"center",gap:"2px",height:"20px",flexShrink:0},children:[0,.15,.3,.45,.6].map(($,M)=>o.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${$}s infinite`}},M))}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is talking..."}),u&&o.jsxs("svg",{style:{height:"16px",width:"16px",color:"#ef4444",marginLeft:"auto",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]})]})]})]}),A&&o.jsxs("div",{style:{position:"relative",marginLeft:"4px"},children:[B==="listening"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),B!=="listening"&&te[B]&&o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:te[B].border,transform:"translate(-50%, -50%)",animation:te[B].animation,pointerEvents:"none"}}),o.jsxs("button",{onTouchStart:U,onTouchEnd:j,onTouchCancel:j,onMouseDown:U,onMouseUp:j,onMouseLeave:j,disabled:B==="processing","aria-label":"Hold to talk to Bob",className:"glass-button bob-ptt-btn",style:{position:"relative",flexShrink:0,height:"72px",width:"72px",minHeight:"unset",minWidth:"unset",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",touchAction:"none",color:"white",cursor:B==="processing"?"not-allowed":"pointer",opacity:B==="processing"?.6:1,transform:B==="listening"?"scale(1.08)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease, background 0.3s ease",zIndex:_+45,backdropFilter:Y.backdropFilter,WebkitBackdropFilter:Y.WebkitBackdropFilter,"--bob-ptt-bg":Y.background,"--bob-ptt-shadow":Y.boxShadow,"--bob-ptt-border":Y.border,"--bob-ptt-radius":"50%"},title:"Hold to talk",children:[o.jsx("svg",{style:{height:"28px",width:"28px",filter:"drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2))"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})}),B==="listening"&&o.jsx("div",{style:{position:"absolute",top:"8px",right:"8px",width:"12px",height:"12px",borderRadius:"50%",backgroundColor:"#fef3c7",animation:"ptt-dot 0.6s ease-in-out infinite alternate"}})]})]})]})]})]})},Uu=({product:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{const n=t.productUrl||t.product_url,i=t.partNumber||t.part_number,a=!!n||!!s;return o.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-white/95 backdrop-blur-md overflow-hidden",children:[o.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-gray-200 bg-white/80 backdrop-blur-sm",children:o.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-blue-600 font-medium text-sm hover:text-blue-700 active:scale-95 transition-all",children:[o.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back to Products"]})}),o.jsxs("div",{className:"flex-1 overflow-y-auto",children:[o.jsx("div",{className:"aspect-square bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center",children:t.image_url?o.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-4"}):o.jsxs("div",{className:"flex flex-col items-center justify-center text-gray-400",children:[o.jsx("svg",{className:"h-16 w-16 mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})}),o.jsx("span",{className:"text-sm font-medium uppercase tracking-wide",children:"No Image Available"})]})}),o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-xl font-bold text-gray-900 mb-1",children:t.name}),t.brand&&o.jsx("p",{className:"text-sm text-gray-600 font-medium",children:t.brand})]}),o.jsxs("div",{className:"bg-blue-50 rounded-xl p-4",children:[o.jsx("p",{className:"text-sm text-gray-600 mb-1",children:"Price"}),o.jsx("p",{className:"text-2xl font-bold text-blue-600",children:t.price>0?`$${t.price.toFixed(2)}`:"Price on Request"}),t.price>0&&o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Inc. GST"})]}),o.jsxs("div",{className:"space-y-3",children:[t.partslotDescription&&o.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[o.jsx("span",{className:"text-sm text-gray-500",children:"Category"}),o.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.partslotDescription})]}),t.sku&&o.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[o.jsx("span",{className:"text-sm text-gray-500",children:"SKU"}),o.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.sku})]}),i&&o.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[o.jsx("span",{className:"text-sm text-gray-500",children:"Part Number"}),o.jsx("span",{className:"text-sm font-medium text-gray-900",children:i})]})]}),a&&o.jsx("a",{href:n||"#",onClick:l=>{s&&(l.preventDefault(),s(t))},target:n&&!s?"_blank":void 0,rel:n&&!s?"noopener noreferrer":void 0,className:"block text-center text-blue-600 text-sm font-medium hover:underline py-2",children:"View Full Details on CARFIX →"})]})]}),o.jsx("div",{className:"p-4 border-t border-gray-200 bg-white/95 backdrop-blur-sm",children:o.jsx("button",{onClick:()=>r==null?void 0:r(t),className:"w-full bg-blue-600 text-white text-base font-semibold py-3 rounded-xl hover:bg-blue-700 active:bg-blue-800 transition-colors shadow-lg",children:"Add to Cart"})})]})},Wa=({package:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{var m;const[n,i]=g.useState(!1),[a,l]=g.useState("disc"),c=g.useMemo(()=>Fa(t),[t.id,t.title]),u=g.useMemo(()=>{if(!t.preparedTiers||t.preparedTiers.length===0)return[];const b=t.preparedTiers.filter(y=>!y.isHidden);return c?b.map(y=>{const _=La(y.products,a);return{...y,products:_,totalPrice:$a(_),productCount:_.length}}):b},[t.preparedTiers,c,a]),d=u.length>0,h=b=>{const y=b.bundleDiscountPercentage||0;if(y>0){const _=1-y/100,k=b.products.map(w=>({...w,displayPrice:Math.round(w.displayPrice*_*100)/100}));r==null||r(k)}else r==null||r(b.products)},f=b=>b===2?"grid-cols-2":b===3?"grid-cols-3":"grid-cols-2",p=Pa(t.title),v=((m=u[0])==null?void 0:m.productCount)||0;return o.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-[#FAFAFA] overflow-hidden",children:[o.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[#E2E8F0] bg-white shadow-sm",children:o.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-[#0052CC] font-medium text-sm hover:text-[#0047B3] active:scale-95 transition-all",children:[o.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]})}),o.jsxs("div",{className:"flex-1 overflow-y-auto",children:[o.jsxs("div",{className:"px-4 pt-4 pb-4",style:{background:"linear-gradient(135deg, rgba(0,82,204,0.05) 0%, rgba(56,189,248,0.05) 100%)"},children:[o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0 bg-white shadow-md",children:t.icon_url?o.jsx("img",{src:t.icon_url,alt:"",className:"w-8 h-8 object-contain"}):o.jsx("svg",{className:"w-7 h-7 text-[#0052CC]",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h1",{className:"text-xl font-bold text-[#0F172A]",children:t.title}),o.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-[#64748B]",children:[t.estimated_time&&o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),t.estimated_time]}),t.difficulty_level&&o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085"})}),t.difficulty_level]})]})]})]}),o.jsx("p",{className:"text-sm text-[#64748B] mt-3 leading-relaxed",children:p}),c&&o.jsxs("div",{className:"mt-3",children:[o.jsx("p",{className:"text-[11px] text-[#94A3B8] mb-1.5",children:"Select your vehicle's rear brake type"}),o.jsxs("div",{className:"flex rounded-xl overflow-hidden border border-[#E2E8F0] bg-white",children:[o.jsx("button",{onClick:()=>l("disc"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:a==="disc"?H.primary:"transparent",color:a==="disc"?"#FFFFFF":"#64748B"},children:"Disc Brakes (Pads + Rotors)"}),o.jsx("button",{onClick:()=>l("drum"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:a==="drum"?H.primary:"transparent",color:a==="drum"?"#FFFFFF":"#64748B"},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),o.jsxs("div",{className:"px-4 py-3 flex items-center justify-center gap-2 border-b border-[#E2E8F0] bg-white",children:[o.jsx("span",{className:"font-semibold text-[#0F172A] text-sm",children:"Choose Your Value Level"}),o.jsx("span",{className:"text-[#64748B] text-xs cursor-help",title:"Select the quality tier that suits your needs",children:"ⓘ"})]}),o.jsx("div",{className:"p-4",children:d?o.jsx("div",{className:`grid ${f(u.length)} gap-3`,children:u.map(b=>{const y=$s[b.tierName];return o.jsxs("div",{className:"relative rounded-2xl overflow-hidden bg-white shadow-md flex flex-col",style:{border:b.isRecommended?"2px solid #0052CC":"1px solid #E2E8F0"},children:[b.isRecommended&&o.jsx("div",{className:"absolute top-0 left-0 right-0 px-2 py-1 text-[9px] font-bold text-white text-center",style:{background:H.primary},children:"★ CARFIX VALUE"}),o.jsxs("div",{className:`p-3 flex-1 flex flex-col ${b.isRecommended?"pt-7":""}`,children:[o.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[o.jsx("span",{className:"text-lg",children:y==null?void 0:y.emoji}),o.jsxs("div",{children:[o.jsx("span",{className:"font-bold text-sm block",style:{color:(y==null?void 0:y.textColor)||H.foreground},children:b.displayName}),o.jsx("span",{className:"text-[10px] text-[#64748B] hidden md:block",children:b.description||(y==null?void 0:y.description)})]})]}),o.jsx("div",{className:"flex items-center gap-1.5 mb-3 min-h-[42px] flex-wrap",children:b.brands.slice(0,3).map(_=>o.jsx("div",{className:"h-10 px-2 bg-white rounded-xl flex items-center justify-center shadow-md border border-[#F1F5F9]",children:o.jsx("img",{src:_.imageUrl,alt:_.fullName,className:"h-6 w-auto object-contain",onError:k=>{const w=k.target,E=`${fs.storageBase}/brand_images/${_.fullName.replace(/\s+/g,"")}.jpg`;if(w.src!==E)w.src=E;else{const A=w.parentElement;A&&(A.innerHTML=`<span class="text-[10px] font-medium text-slate-700 px-1 truncate max-w-[60px]">${_.name}</span>`)}}})},_.name))}),o.jsxs("p",{className:"text-xs text-[#64748B] hidden md:block mb-2",children:[b.productCount," part",b.productCount!==1?"s":""," included"]}),o.jsx("div",{className:"mt-auto",children:b.savingsAmount&&b.savingsAmount>0?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-xs line-through text-[#94A3B8]",children:Ge(b.originalTotalPrice)}),o.jsx("p",{className:"text-xl font-bold",style:{color:"#22C55E"},children:Ge(b.totalPrice)}),o.jsxs("p",{className:"text-[10px] font-semibold text-[#22C55E] bg-[#22C55E]/10 inline-block px-1.5 py-0.5 rounded-full mt-0.5",children:["SAVE ",Ge(b.savingsAmount)," — ",b.bundleDiscountPercentage,"% Bundle Deal"]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-xl font-bold",style:{color:b.isRecommended?"#0052CC":"#0F172A"},children:Ge(b.totalPrice)}),o.jsx("p",{className:"text-[10px] text-[#64748B] hidden md:block",children:"inc GST"})]})}),o.jsx("button",{onClick:()=>h(b),className:`mt-3 w-full px-3 py-2.5 rounded-xl text-xs font-semibold transition-all hover:scale-[1.02] active:scale-95 flex items-center justify-center ${b.isRecommended?"bg-[#22C55E] text-white shadow-md hover:bg-[#16A34A]":"bg-slate-100 text-[#22C55E] border border-slate-200 hover:bg-slate-200"}`,children:"Add to Cart"})]})]},b.tierName)})}):o.jsxs("div",{className:"rounded-2xl p-6 bg-white border border-[#E2E8F0] shadow-md text-center",children:[o.jsx("svg",{className:"w-12 h-12 mx-auto text-[#94A3B8] mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),o.jsx("p",{className:"text-sm font-medium text-[#64748B]",children:"Package details not available for this vehicle"}),o.jsx("p",{className:"text-xs text-[#94A3B8] mt-1",children:"Please try refreshing or contact support"})]})}),d&&o.jsxs("div",{className:"px-4 pb-4",children:[o.jsxs("button",{onClick:()=>i(!n),className:"w-full flex items-center justify-between p-3 rounded-xl bg-white border border-[#E2E8F0] hover:bg-slate-50 transition-all shadow-sm",children:[o.jsxs("span",{className:"text-sm font-medium text-[#0F172A]",children:[n?"▼":"▶"," View Product Details"]}),o.jsxs("span",{className:"text-xs text-[#64748B]",children:[v," product",v!==1?"s":""]})]}),n&&o.jsx("div",{className:"mt-3 space-y-4 bg-white rounded-xl border border-[#E2E8F0] p-3",children:u.map(b=>{if(b.products.length===0)return null;const y=$s[b.tierName];return o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2 pb-1 border-b border-[#E2E8F0]",children:[o.jsx("span",{className:"text-lg",children:y==null?void 0:y.emoji}),o.jsx("span",{className:"font-semibold text-sm",style:{color:y==null?void 0:y.textColor},children:b.displayName}),o.jsxs("span",{className:"text-xs text-[#64748B]",children:["(",b.products.length," parts)"]})]}),o.jsx("div",{className:"space-y-2",children:b.products.map((_,k)=>{var A;const w=(A=t.carfixValueProducts)==null?void 0:A.includes(_.sku),E=_.unitPrice??_.price;return o.jsxs("div",{className:"flex items-center gap-3 p-2.5 rounded-xl transition-all hover:bg-slate-50 cursor-pointer border border-[#E2E8F0]",onClick:()=>s==null?void 0:s(_.sku),children:[o.jsx("div",{className:"w-14 h-14 flex-shrink-0 rounded-lg bg-white overflow-hidden border border-[#E2E8F0]",children:o.jsx("img",{src:_.productImageUrl||fs.productImage(_.sku),alt:_.name,className:"w-full h-full object-contain p-1.5",onError:F=>{F.target.src="/placeholder.svg"}})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[o.jsx("span",{className:"text-xs font-semibold text-[#0F172A]",children:_.brandFullName||_.brand}),w&&o.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"rgba(0, 82, 204, 0.1)",color:"#0052CC"},children:"CFX VALUE"}),_.isMultiQty&&_.perCarQty>1&&o.jsxs("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#F0FDF4",color:"#15803D"},children:["×",_.perCarQty]}),_.isRotor&&o.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#EFF6FF",color:"#1D4ED8"},children:"Pair"})]}),o.jsx("p",{className:"text-xs text-[#64748B] line-clamp-1",children:_.name})]}),o.jsxs("div",{className:"text-right flex-shrink-0",children:[o.jsx("p",{className:"text-sm font-bold text-[#0F172A]",children:Ge(_.displayPrice)}),_.isMultiQty&&_.perCarQty>1&&o.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[_.perCarQty,"× ",Ge(E)," each"]}),_.isRotor&&!_.isMultiQty&&o.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[Ge(E)," each"]})]})]},`${_.sku}-${k}`)})})]},b.tierName)})})]}),t.bundle_discount_percentage&&t.bundle_discount_percentage>0&&o.jsx("div",{className:"px-4 pb-4",children:o.jsx("div",{className:"rounded-xl p-3 text-center",style:{background:"rgba(34,197,94,0.1)",border:"1px solid rgba(34,197,94,0.2)"},children:o.jsxs("span",{className:"text-sm font-semibold text-[#22C55E]",children:["Bundle saves you ",t.bundle_discount_percentage,"%"]})})})]})]})},qa=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:f,chatEndRef:p,isMuted:v,onToggleMute:m,isSpeaking:b,products:y,servicePackages:_,highlightedPartType:k,highlightedProduct:w,onProductClick:E,onPackageSelect:A,isResearching:F,onAddToCart:N,onNavigateToProductPage:U,vehicle:j,onChangeVehicle:R,pendingVariants:T,pendingVariantMake:C,pendingVariantModel:B,onVariantSelect:K,bobOffset:Y=0,bobScale:te=100})=>{const[$,M]=g.useState("center"),[J,oe]=g.useState("hidden"),[X,P]=g.useState("products"),[D,V]=g.useState(null),[Q,_e]=g.useState(null),Te=y.length>0||_.length>0,Ae=((T==null?void 0:T.length)??0)>0,Be=Te||Ae,Qe=(X==="productDetail"?70:$==="center"&&!Be?140:98)*te/100;g.useEffect(()=>{if(F&&J!=="loading"&&J!=="visible")oe("loading"),$==="center"&&M("partial-left");else if(Be&&J!=="visible")if($==="center"){M("partial-left"),oe("transitioning");const me=setTimeout(()=>{oe("visible")},400);return()=>clearTimeout(me)}else oe("visible");else!Be&&!F&&J!=="hidden"&&(oe("hidden"),M("center"))},[Be,F,J,$]);const nt=me=>{if(U){U(me),E==null||E(me);return}V(me),P("productDetail"),E==null||E(me)},O=()=>{V(null),_e(null),P("products")},ee=me=>{console.log("[ContainedMobileBobLayout] Package selected:",me.title),_e(me),P("packageDetail"),A==null||A(me)},Oe=J!=="hidden"&&X==="products",we=J!=="hidden";return o.jsxs("div",{className:"absolute inset-0",style:{overflow:"clip",isolation:"isolate"},onContextMenu:me=>me.preventDefault(),children:[r&&o.jsx("div",{className:"absolute inset-0 z-0 transition-all duration-500 ease-out",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:we?"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)":"none",transform:we?"scale(1.02)":"scale(1)",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"}}),o.jsx(Hs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:Qe,position:$,verticalOffset:Y}),o.jsx(Ks,{products:y,servicePackages:_,highlightedPartType:k,highlightedProduct:w,onProductClick:nt,onPackageSelect:ee,isResearching:F,visible:Oe,counterHeightPercent:n,hasVehicle:!!j,vehicleMakeModel:j?`${j.make||""} ${j.model||""}`.trim():void 0,pendingVariants:T,pendingVariantMake:C,pendingVariantModel:B,onVariantSelect:K}),X==="productDetail"&&D&&o.jsx(Uu,{product:D,onBack:O,onAddToCart:N,onNavigateToProductPage:U}),X==="packageDetail"&&Q&&o.jsx(Wa,{package:Q,onBack:O,onNavigateToProductPage:me=>{const ie=y.find(ht=>ht.sku===me);ie&&U&&U(ie)}}),X==="products"&&o.jsx(Ma,{messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:f,chatEndRef:p,isMuted:v,onToggleMute:m,isSpeaking:b,counterHeightPercent:n})]})},zn=({variant:t="inline",initialState:e="idle",showChat:r=!0,className:s="",backdropUrl:n,counterOverlayUrl:i,counterHeightPercent:a,defaultBobImage:l,verticalOffset:c=0,scale:u=100,sessionToken:d,embedded:h=!1})=>{var Qe,nt;const{callbacks:f}=jt(),[p,v]=g.useState(!1),{animationState:m,setAnimationState:b,getCurrentImage:y,getCurrentOffset:_,getCurrentScale:k,availableStates:w}=ja({isSpeaking:p}),{activeBackdrop:E}=Ta(),[A,F]=g.useState([]),[N,U]=g.useState([]),[j,R]=g.useState(null),[T,C]=g.useState(null),[B,K]=g.useState(!1),[Y,te]=g.useState([]),[$,M]=g.useState(""),[J,oe]=g.useState(""),X=g.useRef(null),P=g.useRef(null);g.useEffect(()=>{X.current=O=>{if(K(!1),!O||O.length===0){console.log("[Bob] Clearing products (empty array received)"),F([]);return}const ee=O[0];console.log("[Bob] First part raw keys:",Object.keys(ee));const Oe=O.map((ie,ht)=>{const ke=ie.Brand||ie.brand||"";return{id:ie.SKU||ie.sku||`part-${ht}`,name:ie["Part Product Type"]||ie.partslot_description||ie.name||"Unknown Part",brand:ke,price:ie["Metro Retail Price"]||ie.price||0,sku:ie.SKU||ie.sku,partNumber:ie["Part Number"]||ie.part_number||null,partslotDescription:ie["Part Product Type"]||ie.partslot_description||ie.partslotDescription||ie.part_type||ie.category||"General Parts",image_url:ie.image_url||(ie.SKU||ie.sku?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${ie.SKU||ie.sku}.jpg`:void 0),webDescription:ie["Web Part Description"]||ie.web_description||null,brandDescription:ie["Brand Description"]||ie.brand_description||null,perCarQty:ie["Per Car Qty"]||ie.per_car_qty||1,volume:ie.volume||null,viscosity:ie.viscosity||null,brandImageUrl:ke?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${ke.replace(/\s+/g,"")}.jpg`:void 0}}),we=new Set,me=Oe.filter(ie=>!ie.sku||we.has(ie.sku)?!1:(we.add(ie.sku),!0));console.log("[Bob] Products mapped:",Oe.length,"-> deduped:",me.length),F(me)},P.current=O=>{if(!O||O.length===0){console.log("[Bob] Clearing service packages (empty array received)"),U([]);return}console.log("[Bob] Service packages received via stable ref:",O.length),U(O)}},[]);const D=Sa({setAnimationState:b,manualMode:!1,onReadyToSpeak:()=>{console.log("[BobWidget] Ready to speak")},onStreamComplete:()=>{b(w.find(O=>O.includes("idle"))||"idle")},onResearchStart:()=>{K(!0),te([]),M(""),oe("")},onVariantSelectionRequired:(O,ee,Oe)=>{K(!1),te(O),M(ee),oe(Oe)},onHighlightPart:O=>{R(O),setTimeout(()=>R(null),8e3)},onHighlightProduct:O=>{C(O),setTimeout(()=>C(null),8e3)},onAutoFetchComplete:()=>{K(!1)}});g.useEffect(()=>{D.identifiedVehicle&&(te([]),M(""),oe(""))},[(Qe=D.identifiedVehicle)==null?void 0:Qe.vehicle_id,(nt=D.identifiedVehicle)==null?void 0:nt.id]);const V=O=>{te([]),D.setInput(`Option ${O.optionNumber}`),setTimeout(()=>{D.handleSend()},80)};g.useEffect(()=>{v(D.isSpeaking)},[D.isSpeaking]),g.useEffect(()=>{const O=f.onPartsFound,ee=f.onServicePackagesFound;return f.onPartsFound=Oe=>{var we;(we=X.current)==null||we.call(X,Oe),O==null||O(Oe)},f.onServicePackagesFound=Oe=>{var we;(we=P.current)==null||we.call(P,Oe),ee==null||ee(Oe)},()=>{f.onPartsFound=O,f.onServicePackagesFound=ee}},[f]);const Q=n||(E==null?void 0:E.image_url),_e=i||(E==null?void 0:E.counter_overlay_url)||void 0,Te=a||(E==null?void 0:E.counter_height_percent)||12,Ae=y()||l||"",Be=_(),Je=k();if(t==="mobile"||t==="fullscreen")return o.jsx(Ua,{currentImage:Ae,animationState:m,backdropUrl:Q,counterOverlayUrl:_e,counterHeightPercent:Te,bobOffset:Be,bobScale:Je,embedded:h,messages:D.messages,input:D.input,setInput:D.setInput,isLoading:D.isLoading,onSend:D.handleSend,onKeyPress:D.handleKeyPress,onInputFocus:D.handleInputFocus,onInputBlur:D.handleInputBlur,chatEndRef:D.chatEndRef,isMuted:D.isMuted,onToggleMute:D.toggleMute,isSpeaking:D.isSpeaking,products:A,servicePackages:N,highlightedPartType:j,highlightedProduct:T,onAddToCart:O=>{var ee;return(ee=f.onAddToCart)==null?void 0:ee.call(f,{product_id:O.id,product_name:O.name,quantity:1,unit_price:O.price,sku:O.sku,brand:O.brand})},onNavigateToProductPage:O=>{var ee;return(ee=f.onNavigateToProductPage)==null?void 0:ee.call(f,O)},onPackageSelect:O=>console.log("[BobWidget] Package selected:",O),isResearching:B,vehicle:D.identifiedVehicle,pendingVariants:Y,pendingVariantMake:$,pendingVariantModel:J,onVariantSelect:V});if(t==="inline"&&r)return o.jsx("div",{className:`relative w-full h-full ${s}`,children:o.jsx(qa,{currentImage:Ae,animationState:m,backdropUrl:Q,counterOverlayUrl:_e,counterHeightPercent:Te,bobOffset:Be,bobScale:Je,messages:D.messages,input:D.input,setInput:D.setInput,isLoading:D.isLoading,onSend:D.handleSend,onKeyPress:D.handleKeyPress,onInputFocus:D.handleInputFocus,onInputBlur:D.handleInputBlur,chatEndRef:D.chatEndRef,isMuted:D.isMuted,onToggleMute:D.toggleMute,isSpeaking:D.isSpeaking,products:A,servicePackages:N,highlightedPartType:j,highlightedProduct:T,onAddToCart:O=>{var ee;return(ee=f.onAddToCart)==null?void 0:ee.call(f,{product_id:O.id,product_name:O.name,quantity:1,unit_price:O.price,sku:O.sku,brand:O.brand})},onNavigateToProductPage:O=>{var ee;return(ee=f.onNavigateToProductPage)==null?void 0:ee.call(f,O)},onPackageSelect:O=>console.log("[BobWidget] Package selected:",O),isResearching:B,vehicle:D.identifiedVehicle,pendingVariants:Y,pendingVariantMake:$,pendingVariantModel:J,onVariantSelect:V})});const qe={inline:"",floating:"fixed bottom-4 right-4 w-96 z-50 shadow-2xl rounded-lg overflow-hidden"};return o.jsxs("div",{className:`${qe[t]||""} ${s}`,children:[Ae&&o.jsx(Ra,{currentImage:Ae,animationState:m,backdropUrl:Q,counterOverlayUrl:_e,counterHeightPercent:Te,verticalOffset:Be,scale:Je}),r&&o.jsx(Ia,{messages:D.messages,input:D.input,setInput:D.setInput,isLoading:D.isLoading,onSend:D.handleSend,onKeyPress:D.handleKeyPress,onInputFocus:D.handleInputFocus,onInputBlur:D.handleInputBlur,chatEndRef:D.chatEndRef,isMuted:D.isMuted,onToggleMute:D.toggleMute,isSpeaking:D.isSpeaking})]})},Mu=({bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,variant:n="mobile",initialState:i,showChat:a,className:l,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:f,scale:p,ga4Config:v,analyticsEnabled:m=!0,bottomOffset:b=0,zIndexBase:y=50,embedded:_=!1})=>(g.useEffect(()=>{console.log("[BobWidget] Initialized",{version:St,variant:n,bottomOffset:b,zIndexBase:y,bobConfigUrl:t.supabaseUrl,hostApiBaseUrl:e.baseUrl,analyticsEnabled:m})},[n,b,y,t.supabaseUrl,e.baseUrl,m]),o.jsx("div",{className:"bob-widget-root",style:{width:"100%",height:"100%"},children:o.jsx(Dn,{bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,ga4Config:v,analyticsEnabled:m,bottomOffset:b,zIndexBase:y,children:o.jsx(zn,{variant:n,initialState:i,showChat:a,className:l,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:f,scale:p,embedded:_})})}));function Wu(t){return t<640?"mobile":t<1024?"tablet":"desktop"}function qu(){const t=[];if(typeof window>"u")return t;const e=document.querySelector(".bob-widget-root");if(!e)return t.push("bob-widget-root not found in DOM"),t;const r=window.getComputedStyle(e),s=e.parentElement;return s&&window.getComputedStyle(s).overflow==="hidden"&&t.push("Parent has overflow:hidden - may clip Bob"),r.transform!=="none"&&r.transform!=="matrix(1, 0, 0, 1, 0, 0)"&&t.push(`Unexpected transform on root: ${r.transform}`),r.isolation!=="isolate"&&t.push("Isolation not properly set"),t}const za=({partnerConfig:t,sessionToken:e})=>{const[r,s]=g.useState(null),[n,i]=g.useState([]),[a,l]=g.useState(!1);if(g.useEffect(()=>{const u=()=>{var f;const d=window.innerWidth,h=window.innerHeight;s({viewport:{width:d,height:h,deviceType:Wu(d)},origin:window.location.origin,originAllowed:((f=t==null?void 0:t.allowed_origins)==null?void 0:f.some(p=>p===window.location.origin||p.includes("*")))??!1,userAgent:navigator.userAgent.slice(0,50)+"...",timestamp:new Date().toISOString()}),i(qu())};return u(),window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[t]),!r)return null;const c=({ok:u,label:d})=>o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"4px",fontSize:"11px",fontWeight:500,background:u?"rgba(34, 197, 94, 0.2)":"rgba(239, 68, 68, 0.2)",color:u?"#22c55e":"#ef4444"},children:[u?"✓":"✗"," ",d]});return o.jsxs("div",{style:{position:"fixed",top:"8px",right:"8px",zIndex:99999,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace',fontSize:"11px",lineHeight:1.4},children:[o.jsx("button",{onClick:()=>l(!a),style:{position:"absolute",top:0,right:0,width:"24px",height:"24px",background:"rgba(0, 0, 0, 0.8)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"4px",color:"#fff",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1},children:a?"🔍":"✕"}),!a&&o.jsxs("div",{style:{background:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"8px",padding:"12px",color:"#fff",maxWidth:"320px",backdropFilter:"blur(8px)"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"12px",paddingBottom:"8px",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:[o.jsx("span",{style:{fontSize:"14px"},children:"🔧"}),o.jsxs("span",{style:{fontWeight:600},children:["Bob Debug v",St]})]}),o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px",marginBottom:"12px"},children:[o.jsx(c,{ok:!!t,label:`Partner: ${(t==null?void 0:t.partner_code)||"none"}`}),o.jsx(c,{ok:!!e,label:e?"Session":"No Session"}),o.jsx(c,{ok:r.originAllowed,label:"Origin"})]}),o.jsxs("div",{style:{display:"grid",gap:"6px"},children:[o.jsx(Sr,{label:"Viewport",value:`${r.viewport.width}×${r.viewport.height} (${r.viewport.deviceType})`}),o.jsx(Sr,{label:"Origin",value:r.origin}),o.jsx(Sr,{label:"Bottom Offset",value:`${(t==null?void 0:t.default_bottom_offset)??0}px`}),o.jsx(Sr,{label:"Z-Index Base",value:`${(t==null?void 0:t.default_z_index_base)??50}`}),o.jsx(Sr,{label:"Blur",value:`${(t==null?void 0:t.backdrop_blur_intensity)??8}px`}),o.jsx(Sr,{label:"Overlay",value:`${(((t==null?void 0:t.backdrop_overlay_opacity)??.15)*100).toFixed(0)}%`})]}),(t==null?void 0:t.feature_flags)&&o.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[o.jsx("div",{style:{color:"rgba(255,255,255,0.5)",marginBottom:"4px"},children:"Features:"}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:Object.entries(t.feature_flags).map(([u,d])=>o.jsx(c,{ok:!!d,label:u.replace(/([A-Z])/g," $1").trim()},u))})]}),n.length>0&&o.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[o.jsx("div",{style:{color:"#ef4444",marginBottom:"4px"},children:"⚠️ CSS Conflicts:"}),n.map((u,d)=>o.jsxs("div",{style:{color:"#fca5a5",fontSize:"10px"},children:["• ",u]},d))]}),o.jsx("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",color:"rgba(255,255,255,0.4)",fontSize:"10px"},children:r.timestamp})]})]})},Sr=({label:t,value:e})=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px"},children:[o.jsxs("span",{style:{color:"rgba(255,255,255,0.5)"},children:[t,":"]}),o.jsx("span",{style:{color:"#fff",textAlign:"right",wordBreak:"break-all"},children:e})]}),Ni="https://gjoguxzstsihhxvdgpto.supabase.co",Bi="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imdqb2d1eHpzdHNpaGh4dmRncHRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjM5MzgyODEsImV4cCI6MjA3OTUxNDI4MX0.detu4TKB7RjC6l6CrVaPYoi0Hhz2asDt6zxNx1cdzq8";function zu(t,e){return t.some(r=>{if(r.includes("*")){const s=r.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${s}$`).test(e)}return r===e})}function Ha(t){const[e,r]=g.useState(null),[s,n]=g.useState(!0),[i,a]=g.useState(null),[l,c]=g.useState(!1),[u,d]=g.useState(null),h=g.useCallback(async()=>{if(!t){n(!1),a(new Error("Partner code is required"));return}n(!0),a(null);try{const f=mn(Ni,Bi);console.log(`[BobWidget] Loading partner config for: ${t}`);const{data:p,error:v}=await f.from("bob_partners").select("*").eq("partner_code",t).eq("is_active",!0).maybeSingle();if(v)throw new Error(`Failed to load partner config: ${v.message}`);if(!p)throw new Error(`Partner "${t}" not found or inactive`);const m=p,b=typeof window<"u"?window.location.origin:"",y=zu(m.allowed_origins||[],b);!y&&b&&(console.warn(`[BobWidget] Origin "${b}" not in allowed origins for ${t}`),console.warn("[BobWidget] Allowed origins:",m.allowed_origins));const _=mn(m.bob_supabase_url||Ni,m.bob_supabase_key||Bi,{auth:{storageKey:`bobwidget_${m.partner_code.toLowerCase()}`,persistSession:!1,autoRefreshToken:!1}});console.log("[BobWidget] Partner config loaded:",{partner:m.partner_code,displayName:m.display_name,bottomOffset:m.default_bottom_offset,blurIntensity:m.backdrop_blur_intensity,features:m.feature_flags,originAllowed:y}),r(m),c(y),d(_)}catch(f){const p=f instanceof Error?f:new Error("Unknown error loading partner config");console.error("[BobWidget] Partner config error:",p),a(p)}finally{n(!1)}},[t]);return g.useEffect(()=>{h()},[h]),{config:e,isLoading:s,error:i,isOriginAllowed:l,supabaseClient:u,reload:h}}function Ka(t,e,r){return t!=null&&t.feature_flags?t.feature_flags[e]??r:r}const Hu=()=>o.jsxs("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #0a1628 0%, #0f2137 100%)"},children:[o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[o.jsx("div",{style:{width:"48px",height:"48px",border:"4px solid rgba(0, 102, 204, 0.3)",borderTopColor:"#0066cc",borderRadius:"50%",animation:"spin 1s linear infinite"}}),o.jsx("span",{style:{color:"rgba(255,255,255,0.7)",fontSize:"14px"},children:"Loading Bob..."})]}),o.jsx("style",{children:`
75
+ `+vt;break}}}let Kr=Pt.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");Kr=In(Kr),X.current=Kr;const x=rn.some(le=>Pt.toLowerCase().includes(le.toLowerCase())),I=Pt.toLowerCase();for(const le of Eu)if(I.includes(le.toLowerCase())){const he=le.replace(/s\s*$/i,"").toUpperCase();f==null||f(he);break}const W=Pt.match(/(?:go with|recommend|suggest|grab|try)\s+(?:the\s+)?(\w+)\s+(?:at|for)\s+\$(\d+(?:\.\d{2})?)/i);if(W){const[,le,he]=W;p==null||p({brand:le,price:parseFloat(he)})}const Z=V.current;if(!K&&X.current.trim()){if(P.current=!1,Je(),Z.hasCannedAudio&&Z.cannedUrl)console.log("[BobWidget] Playing canned audio (priority):",Z.cannedUrl),Te(),Ae(Z.cannedUrl,"canned",()=>{Z.hasCannedAudio=!1,Z.cannedUrl=null,Je(),e||(x&&u?u():c?c():(ee(n),setTimeout(()=>ee(a),3e3)))}),P.current=!0,h==null||h();else if(Z.isPlaying)console.log("[BobWidget] Skipping TTS - audio already playing:",Z.source);else{const le=ku(X.current);console.log("[BobWidget] Playing TTS (no canned audio)"),qe(le)}D.current=setTimeout(()=>{P.current||(console.warn("[BobWidget] Speech fallback after 5s"),h==null||h(),e||(x&&u?u():c?c():(ee(n),setTimeout(()=>ee(a),3e3))))},5e3)}else h==null||h(),e||(x&&u?u():c?c():(ee(n),setTimeout(()=>ee(a),3e3)))}catch(Se){console.error("[BobWidget] Chat error:",Se);const et=Se instanceof Error?Se:new Error("Unknown error");(Ot=w.onError)==null||Ot.call(w,et),F.trackError(et.name||"ChatError",et.message||"Unknown chat error"),e||ee(i)}},we=async()=>{if(!R.trim()||C)return;O(),Qe();const z={role:"user",content:R};j(pe=>[...pe,z]),T(""),F.trackMessageSent(R.length,!!te);const fe=R.toLowerCase();if(Su.some(pe=>fe.includes(pe))){const pe=`G'day mate! I'm running Bob v${St} - she's running sweet as! Anything else I can help ya with?`;j(He=>[...He,{role:"assistant",content:pe}]),K||qe(pe);return}B(!0),console.log("[BobWidget STATE] User sent message - switching to RESEARCH state:",s),d==null||d(),e||ee(s),await Oe(z),B(!1)};return{messages:U,input:R,setInput:T,isLoading:C,handleSend:we,handleKeyPress:z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),we())},handleInputFocus:()=>{O()},handleInputBlur:()=>{},chatEndRef:M,clearMessages:()=>{j([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])},isMuted:K,toggleMute:()=>{Y(z=>!z),K||Qe()},isSpeaking:nt,identifiedVehicle:te,clearVehicle:()=>{$(null)}}},ju={states:[],configs:[],uploadedImages:[],looks:[],activeLookId:null},Ea=t=>{const e=va(),r=pr();return g.useEffect(()=>{if(!r)return;const s=r.channel("animation-states-changes").on("postgres_changes",{event:"*",schema:"public",table:"animation_states"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe(),n=r.channel("bob-animations-changes").on("postgres_changes",{event:"*",schema:"public",table:"bob_animations"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe();return()=>{r.removeChannel(s),r.removeChannel(n)}},[e,r]),xs({queryKey:["bob-animation-data",t],queryFn:async()=>{var k;if(!r)return console.log("[BobAnimation] No supabase client, returning empty data"),ju;const{data:s,error:n}=await r.from("bob_looks").select("*").order("display_order");if(n)throw n;const i=(s||[]).find(w=>w.is_active),a=t||(i==null?void 0:i.id)||s&&((k=s[0])==null?void 0:k.id)||null;if(!a)return console.warn("[BobAnimation] No looks configured in database"),{states:[],configs:[],uploadedImages:[],looks:s||[],activeLookId:null};console.log(`[BobAnimation] Loading animations for look: ${(i==null?void 0:i.name)||a}`);const{data:l,error:c}=await r.from("animation_states").select("*").eq("is_active",!0).eq("look_id",a).order("display_order");if(c)throw c;const{data:u,error:d}=await r.from("bob_animations").select("*").eq("is_active",!0).eq("look_id",a).order("animation_state").order("sequence_order");if(d)throw d;const h=(l||[]).map(w=>w.state_key);console.log(`[BobAnimation] Loaded ${h.length} states: ${h.join(", ")}`);const p=["idle","talking","listening"].filter(w=>{const E=[w,w.replace("ing",""),w+"ing"];return!h.some(A=>E.includes(A))});p.length>0&&console.warn(`[BobAnimation] ⚠️ Missing critical states: ${p.join(", ")}`);const v=new Set(h),m=(u||[]).filter(w=>v.has(w.animation_state));console.log(`[BobAnimation] Loaded ${m.length} animation frames`);const{data:b,error:y}=await r.storage.from("bob-images").list();if(y)throw y;const _=(b||[]).map(w=>{const{data:E}=r.storage.from("bob-images").getPublicUrl(w.name);return E.publicUrl});return m.forEach(w=>{const E=new Image;E.src=w.image_url}),{states:l||[],configs:m,uploadedImages:_,looks:s||[],activeLookId:a}},staleTime:30*1e3,gcTime:5*60*1e3})},ja=(t={})=>{const{isSpeaking:e=!1}=t,[r,s]=g.useState(""),[n,i]=g.useState(0),[a,l]=g.useState(400),[c,u]=g.useState(!1),d=g.useRef(null),h=g.useRef(0),f=g.useRef(e),p=g.useRef(0),v=g.useRef(0),m=g.useRef(!1),b=g.useRef(0),{data:y,isLoading:_}=Ea(),k=g.useRef({}),{imageUrlsMap:w,alternateImages:E,offsetsMap:A,scalesMap:F,availableStates:N}=g.useMemo(()=>{if(!y)return{imageUrlsMap:{},alternateImages:{},offsetsMap:{},scalesMap:{},availableStates:[]};const C={},B={},K={},Y={},te=y.states.map($=>$.state_key);return te.forEach($=>{const M=y.configs.filter(P=>P.animation_state===$),J=M.map(P=>P.image_url),oe=M.map(P=>P.vertical_offset||0),X=M.map(P=>P.scale||100);if(J.length>0){const P=y.states.find(D=>D.state_key===$);C[$]={url:J[0],animation_speed:(P==null?void 0:P.animation_speed)||400,pause_duration:(P==null?void 0:P.pause_duration)||0,loop_count:(P==null?void 0:P.loop_count)||0},B[$]=J,K[$]=oe,Y[$]=X}}),{imageUrlsMap:C,alternateImages:B,offsetsMap:K,scalesMap:Y,availableStates:te}},[y]);g.useEffect(()=>{k.current=w},[w]),g.useEffect(()=>{const C=f.current;if(f.current=e,C&&!e){const B=r.toLowerCase();(B.includes("talk")||B==="talking")&&(console.log("[useBobAnimation] Speech ended while in talk state - forcing loop completion"),v.current=999)}},[e,r]);const U=g.useCallback(C=>{s(B=>B===C?B:(p.current=0,v.current=0,m.current=!1,i(0),C))},[]);g.useEffect(()=>{N.length>0&&!r&&s(N[0])},[N,r]),g.useEffect(()=>{const C=E[r];if(d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),p.current=0,v.current=0,m.current=!1,h.current=0,i(0),!C||C.length<=1)return;const B=k.current[r],K=(B==null?void 0:B.animation_speed)||a||400,Y=(B==null?void 0:B.loop_count)||0,te=(B==null?void 0:B.pause_duration)||0,$=r.toLowerCase().includes("talk"),M=J=>{if(h.current===0&&(h.current=J),m.current){J-b.current>=te&&(m.current=!1,v.current=0,h.current=J),d.current=requestAnimationFrame(M);return}if(J-h.current>=K){h.current=J;const X=(p.current+1)%C.length;X===0?(v.current++,$&&f.current?(p.current=X,i(X)):Y>0&&v.current>=Y?te>0&&(m.current=!0,b.current=J):(p.current=X,i(X))):(p.current=X,i(X))}d.current=requestAnimationFrame(M)};return d.current=requestAnimationFrame(M),()=>{d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)}},[r,E,a]);const j=g.useCallback(()=>{const C=E[r];if(!C||C.length===0){const B=N.find(K=>{var Y;return((Y=E[K])==null?void 0:Y.length)>0});return B?(console.warn(`[useBobAnimation] No images for "${r}", using fallback: ${B}`),E[B][0]):(console.error("[useBobAnimation] No valid images found for any state!"),"")}return C[n]||C[0]},[E,r,N,n]),R=g.useCallback(()=>{const C=A[r];if(!C||C.length===0){const B=N.find(K=>{var Y;return((Y=A[K])==null?void 0:Y.length)>0});return B?A[B][0]:0}return C[n]||C[0]},[A,r,N,n]),T=g.useCallback(()=>{const C=F[r];if(!C||C.length===0){const B=N.find(K=>{var Y;return((Y=F[K])==null?void 0:Y.length)>0});return B?F[B][0]:100}return C[n]||C[0]},[F,r,N,n]);return{animationState:r,setAnimationState:U,getCurrentImage:j,getCurrentOffset:R,getCurrentScale:T,imageUrls:w,availableStates:N,setTalkSpeed:l,manualMode:c,setManualMode:u,isLoading:_}},Ta=()=>{const t=pr(),{data:e=[],isLoading:r}=xs({queryKey:["bob-backdrops"],queryFn:async()=>{if(!t)return console.log("[useBobBackdrop] No supabase client, returning empty"),[];const{data:n,error:i}=await t.from("bob_backdrops").select("*").order("display_order",{ascending:!0});if(i)throw i;return n},staleTime:5*60*1e3,gcTime:10*60*1e3}),s=e.find(n=>n.is_active);return{backdrops:e,activeBackdrop:s,isLoading:r}},Ra=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=12,className:i="",verticalOffset:a=0,scale:l=100})=>{const c=a+n,u=55*(l/100);return o.jsx("div",{className:`flex flex-col items-center justify-center gap-6 w-full ${i}`,children:o.jsxs("div",{className:"relative w-full max-w-[600px] mx-auto aspect-[16/10] overflow-hidden",children:[r&&o.jsx("img",{src:r,alt:"Backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-bottom"}),o.jsx("img",{src:t,alt:`Bob ${e}`,className:"absolute z-10 h-auto object-contain left-1/2 -translate-x-1/2",style:{bottom:`${c}%`,width:`${u}%`,maxWidth:`${220*(l/100)}px`,transformOrigin:"center bottom"}}),s&&o.jsx("img",{src:s,alt:"Counter",className:"absolute z-20 bottom-0 left-0 w-full object-cover object-bottom",style:{height:`${n}%`}})]})})},H={primary:"#0052CC",primaryHover:"#0047B3",secondary:"#38BDF8",foreground:"#0F172A",accent:"#FF8C00",success:"#22C55E",destructive:"#EF4444",performanceRed:"#DC2626",mutedForeground:"#64748B",background:"#FAFAFA",card:"#FFFFFF",border:"#E2E8F0",slateEconomy:"#475569"},$s={Economy:{icon:"DollarSign",emoji:"💰",textColor:"#475569",background:"#F1F5F9",border:"#CBD5E1",description:"Smart savings"},Standard:{icon:"Star",emoji:"⭐",textColor:"#0052CC",background:"rgba(0,82,204,0.1)",border:"rgba(0,82,204,0.3)",description:"Best value",isRecommended:!0},Premium:{icon:"Award",emoji:"🏆",textColor:"#D97706",background:"#FEF3C7",border:"#FCD34D",description:"Superior quality"},Performance:{icon:"Zap",emoji:"⚡",textColor:"#DC2626",background:"#FEE2E2",border:"#FCA5A5",description:"Maximum power"}},sn={"Oil Change":"Neglecting oil changes leads to engine wear, overheating, and catastrophic failure costing thousands. Quality oil and filters keep your engine running smoothly. Each CARFIX Oil Change Service Pack includes premium oil and filter matched to your engine specifications.","Front Brake Service":"Your front brakes handle 70% of stopping power. Worn pads dangerously increase stopping distance. Quality brake components ensure confident, safe stops. Each CARFIX Front Brake Service Pack includes pads and rotors to restore your braking performance.","Rear Brake Service":"Rear brakes provide stability and balance during emergency stops. Worn components cause instability and longer stopping distances. Each CARFIX Rear Brake Service Pack includes quality pads/shoes and rotors/drums for complete rear brake renewal.","Timing Belt Service":"A snapped timing belt destroys engines instantly, causing $8,000+ in damage. Preventive replacement is essential for peace of mind. Each CARFIX Timing Belt Service Pack includes the belt, tensioner, and related components.",Wipers:"Worn wipers reduce visibility in rain, compromising safety. Quality blades provide streak-free, clear vision. Each CARFIX Wipers Service Pack includes the gear you need to change all of your vehicle's wiper blades to restore your driving vision.","Coolant Service":"Old coolant causes overheating, warped cylinder heads, and engine seizure. Fresh coolant protects your entire cooling system. Each CARFIX Coolant Service Pack includes quality coolant matched to your vehicle's requirements.","Air Filter Service":"Clogged air filters reduce engine performance by 10% and increase fuel consumption. Clean filters improve power and economy. Each CARFIX Air Filter Service Pack includes a precision-fit filter for optimal airflow.","Spark Plug Service":"Worn spark plugs cause misfires, poor fuel economy, and catalytic converter damage. Fresh plugs restore smooth, efficient running. Each CARFIX Spark Plug Service Pack includes quality plugs matched to your engine.","Battery Service":"A failing battery leaves you stranded without warning. Reliable power is essential for starting and electronics. Each CARFIX Battery Service Pack includes a quality battery sized for your vehicle's demands.","Cabin Filter":"Cabin filters clean the air you and your passengers breathe. Replace regularly to remove pollen, dust, and odours. Each CARFIX Cabin Filter Service Pack includes a quality filter for fresh, clean cabin air.","Fuel Filter Service":"Clogged fuel filters restrict flow, causing poor performance and potential engine damage. Clean fuel is critical for efficiency. Each CARFIX Fuel Filter Service Pack includes a quality filter for optimal fuel delivery.","Transmission Service":"Old transmission fluid causes rough shifting, slipping, and premature wear. Fresh fluid extends transmission life. Each CARFIX Transmission Service Pack includes quality fluid matched to your transmission type."},Tu="Keep your vehicle running safely and efficiently with quality parts matched to your specific make and model. Each CARFIX Service Pack includes everything you need for this essential maintenance.",fs={storageBase:"https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public",productImage:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${t}.jpg`,brandLogo:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${t.replace(/\s+/g,"")}.jpg`,carfixImage:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/carfix_images/${t}_1.jpg`},Ca={fitsVehicle:{background:"rgba(34,197,94,0.1)",text:"#22C55E",border:"rgba(34,197,94,0.2)",icon:"Check",label:"Fits Your Vehicle"},viscosity:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",icon:"Gauge"},volume:{background:"#ECFEFF",text:"#0E7490",border:"#A5F3FC",icon:"Droplets"},quantity:{background:"#F1F5F9",text:"#475569",border:"#CBD5E1"},partNumber:{background:"transparent",text:"#64748B",border:"transparent"},carfixValue:{background:"rgba(0,82,204,0.1)",text:"#0052CC",border:"rgba(0,82,204,0.2)",icon:"Sparkles",label:"CARFIX Value"},rotorPair:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",label:"Pair"}},lt={packageTitle:{fontSize:"20px",fontWeight:700},partslotName:{fontSize:"14px",fontWeight:600},productName:{fontSize:"14px",fontWeight:500},description:{fontSize:"14px",fontWeight:400},priceMain:{fontSize:"20px",fontWeight:700},priceSecondary:{fontSize:"12px",fontWeight:400},tierLabel:{fontSize:"14px",fontWeight:500},badgeText:{fontSize:"12px",fontWeight:500}};function Aa(t){var s;const e=((s=t.name)==null?void 0:s.toLowerCase())||"",r=(t.partslotDescription||t.partslot_description||"").toLowerCase();return e.includes("rotor")||r.includes("disc rotor")||r.includes("brake rotor")||t.per_car_qty===2}function Oa(t,e){return e?{displayPrice:t*2,unitPriceLabel:`$${t.toFixed(2)} each`}:{displayPrice:t}}function Ge(t){return`$${t.toFixed(2)}`}function Pa(t){if(sn[t])return sn[t];const e=t.toLowerCase();for(const[r,s]of Object.entries(sn))if(e.includes(r.toLowerCase())||r.toLowerCase().includes(e))return s;return Tu}const es=({type:t,value:e,className:r=""})=>{const s=Ca[t],n=e||("label"in s?s.label:""),i=()=>{if(!("icon"in s))return null;const a={width:12,height:12};switch(s.icon){case"Check":return o.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",children:o.jsx("polyline",{points:"20 6 9 17 4 12"})});case"Sparkles":return o.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("path",{d:"M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3z"}),o.jsx("path",{d:"M5 19l1 3 1-3 3-1-3-1-1-3-1 3-3 1 3 1z"})]});case"Gauge":return o.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("circle",{cx:"12",cy:"12",r:"10"}),o.jsx("path",{d:"M12 6v6l4 2"})]});case"Droplets":return o.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:o.jsx("path",{d:"M12 2.69l5.66 5.66a8 8 0 11-11.31 0z"})});default:return null}};return o.jsxs("span",{className:r,style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",fontSize:"12px",fontWeight:500,background:s.background,color:s.text,border:`1px solid ${s.border}`,whiteSpace:"nowrap"},children:[i(),n]})},Mn=({products:t,title:e,onProductClick:r,onAddToCart:s})=>!t||t.length===0?null:o.jsxs("div",{style:{marginTop:"16px",width:"100%"},children:[e&&o.jsxs("div",{style:{marginBottom:"12px",fontSize:lt.partslotName.fontSize,fontWeight:lt.partslotName.fontWeight,color:H.foreground,display:"flex",alignItems:"center",gap:"8px"},children:[o.jsx("span",{style:{fontSize:"18px"},children:"🚗"}),e]}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:t.slice(0,6).map((n,i)=>o.jsx(Ru,{product:n,onProductClick:r,onAddToCart:s,isRecommended:i===0},n.id||n.sku||i))}),t.length>6&&o.jsxs("div",{style:{marginTop:"12px",fontSize:"13px",color:H.mutedForeground,textAlign:"center"},children:["+ ",t.length-6," more options available"]})]}),Ru=({product:t,onProductClick:e,onAddToCart:r,isRecommended:s=!1})=>{const[n,i]=g.useState(!1),[a,l]=g.useState(!1),c=t.image_url||t.image||(t.sku?fs.productImage(t.sku):null),u=t.brand?fs.brandLogo(t.brand):null,d=t.brand||"Quality Part",h=t.name||"Product",f=t.price??0,p=t.partNumber||t.part_number,v=Aa({name:t.name,partslotDescription:t.partslotDescription,per_car_qty:t.quantity}),{displayPrice:m,unitPriceLabel:b}=Oa(f,v);return o.jsxs("div",{style:{background:H.card,borderRadius:"12px",border:`2px solid ${H.border}`,overflow:"hidden",cursor:e?"pointer":"default",transition:"all 0.2s ease"},onClick:()=>e==null?void 0:e(t),onMouseEnter:y=>{y.currentTarget.style.borderColor=`${H.primary}80`,y.currentTarget.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)"},onMouseLeave:y=>{y.currentTarget.style.borderColor=H.border,y.currentTarget.style.boxShadow="none"},children:[t.partslotDescription&&o.jsxs("div",{style:{background:"rgba(0,0,0,0.03)",borderBottom:`1px solid ${H.border}`,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsx("span",{style:{fontSize:lt.partslotName.fontSize,fontWeight:lt.partslotName.fontWeight,color:H.foreground},children:t.partslotDescription}),s&&o.jsx(es,{type:"carfixValue"})]}),o.jsxs("div",{style:{padding:"16px",display:"flex",gap:"16px"},children:[o.jsx("div",{style:{width:"96px",minWidth:"96px",height:"96px",borderRadius:"8px",background:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",border:`1px solid ${H.border}`},children:c&&!n?o.jsx("img",{src:c,alt:h,style:{width:"100%",height:"100%",objectFit:"contain",padding:"4px"},onError:()=>i(!0)}):o.jsx("span",{style:{fontSize:"32px",opacity:.5},children:"🔧"})}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:[u&&!a&&o.jsx("img",{src:u,alt:d,style:{height:"16px",width:"auto",objectFit:"contain"},onError:()=>l(!0)}),o.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:H.foreground,textTransform:"uppercase"},children:d})]}),o.jsx("div",{style:{fontSize:lt.productName.fontSize,fontWeight:lt.productName.fontWeight,color:H.foreground,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",lineHeight:"1.4",marginBottom:"8px"},children:h}),o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"12px"},children:[o.jsx(es,{type:"fitsVehicle"}),v&&o.jsx(es,{type:"rotorPair"}),t.quantity&&t.quantity>1&&!v&&o.jsx(es,{type:"quantity",value:`Qty: ${t.quantity}`}),p&&o.jsxs("span",{style:{fontSize:"12px",color:H.mutedForeground},children:["#",p]})]})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",justifyContent:"space-between",minWidth:"100px"},children:[o.jsxs("div",{style:{textAlign:"right"},children:[o.jsx("div",{style:{fontSize:lt.priceMain.fontSize,fontWeight:lt.priceMain.fontWeight,color:H.foreground},children:Ge(m)}),b&&o.jsx("div",{style:{fontSize:lt.priceSecondary.fontSize,color:H.mutedForeground},children:b}),o.jsx("div",{style:{fontSize:lt.priceSecondary.fontSize,color:H.mutedForeground},children:"inc GST"})]}),r&&o.jsx("button",{onClick:y=>{y.stopPropagation(),r(t)},style:{background:H.primary,color:"#FFFFFF",border:"none",borderRadius:"8px",padding:"8px 16px",fontSize:"13px",fontWeight:600,cursor:"pointer",transition:"all 0.2s ease",whiteSpace:"nowrap"},onMouseEnter:y=>{y.currentTarget.style.background=H.primaryHover},onMouseLeave:y=>{y.currentTarget.style.background=H.primary},onMouseDown:y=>{y.currentTarget.style.transform="scale(0.98)"},onMouseUp:y=>{y.currentTarget.style.transform="scale(1)"},children:"Add to Cart"})]})]})]})},Ia=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:l,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,className:f="",onAddToCart:p,onProductClick:v})=>o.jsx("div",{className:f,style:{width:"100%",maxWidth:"72rem",margin:"0 auto",padding:"0 16px 32px 16px"},children:o.jsxs("div",{style:{backgroundColor:"rgba(20, 30, 50, 0.85)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"16px",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.3)",overflow:"hidden"},children:[o.jsx("div",{style:{padding:"16px",borderBottom:"1px solid rgba(255,255,255,0.1)",backgroundColor:"rgba(0,0,0,0.2)"},children:o.jsxs("div",{style:{display:"flex",gap:"8px"},children:[o.jsx("input",{value:e,onChange:m=>r(m.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Ask Bob about car parts...",disabled:s,style:{flex:1,padding:"12px 16px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",color:"white",fontSize:"16px",outline:"none"}}),d&&o.jsx("button",{onClick:d,style:{flexShrink:0,padding:"12px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",cursor:"pointer",minHeight:"unset",minWidth:"unset"},title:u?"Unmute Bob's voice":"Mute Bob's voice",children:u?"🔇":"🔊"}),o.jsx("button",{onClick:n,disabled:s||!e.trim(),style:{flexShrink:0,padding:"12px 20px",background:s||!e.trim()?"rgba(0, 102, 204, 0.3)":"linear-gradient(135deg, rgba(0, 102, 204, 0.95), rgba(0, 73, 153, 1))",color:"white",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.2)",cursor:s||!e.trim()?"not-allowed":"pointer",opacity:s||!e.trim()?.5:1,minHeight:"unset",minWidth:"unset",fontWeight:600},children:"Send"})]})}),o.jsxs("div",{style:{overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"12px",height:"400px",background:"rgba(0,0,0,0.1)"},children:[[...t].reverse().map((m,b)=>{var y;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:m.role==="user"?"flex-end":"flex-start"},children:o.jsxs("div",{style:{maxWidth:(y=m.suggestedProducts)!=null&&y.length?"100%":"80%",borderRadius:"16px",padding:"12px 16px",fontSize:"14px",backgroundColor:m.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.1)",background:m.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.08)",color:"white",border:"1px solid rgba(255,255,255,0.15)",boxShadow:"0 2px 8px rgba(0,0,0,0.2)"},children:[m.content,m.role==="assistant"&&m.suggestedProducts&&m.suggestedProducts.length>0&&o.jsx(Mn,{products:m.suggestedProducts,title:m.suggestionsTitle,onAddToCart:p,onProductClick:v})]})},b)}),o.jsx("div",{ref:c})]})]})}),Cu=768,Au=1024;function zs(){const[t,e]=g.useState("mobile");return g.useEffect(()=>{const r=()=>{const s=window.innerWidth;s>=Au?e("desktop"):s>=Cu?e("tablet"):e("mobile")};return r(),window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),t}function Wn(){const t=zs();return Ou(t)}function Ou(t){switch(t){case"mobile":return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-30,hiddenPosition:-100};case"tablet":return{bobOffset:.7,productWidth:.85,uiScale:1.1,partialLeftPosition:-25,hiddenPosition:-80};case"desktop":return{bobOffset:.5,productWidth:.7,uiScale:1.2,partialLeftPosition:-5,hiddenPosition:-60};default:return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-20,hiddenPosition:-100}}}const Hs=({currentImage:t,animationState:e,counterOverlayUrl:r,counterHeightPercent:s=15,scale:n=100,position:i="center",verticalOffset:a=0,hasArrived:l=!0})=>{const c=Wn(),d=95*n/100,h=550*n/100,f=()=>{switch(i){case"center":return"50%";case"partial-left":return`${c.partialLeftPosition}%`;case"hidden":return`${c.hiddenPosition}%`;default:return"50%"}},p=()=>i==="center"?"translateX(-50%)":"translateX(0)",v=s+a,m=()=>i==="hidden"?"all 0.35s cubic-bezier(0.4, 0, 0.2, 1)":"all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)";return o.jsxs("div",{className:"absolute inset-0 pointer-events-none",style:{overflow:"visible"},children:[o.jsx("div",{className:"absolute z-[60]",style:{bottom:`${v}%`,left:f(),maxHeight:`${100-s-2}%`,transform:p(),width:`${d}%`,maxWidth:`${h}px`,transition:m()+", opacity 0.6s ease-out",willChange:"transform, left, opacity",opacity:l?1:0},children:o.jsx("img",{src:t,alt:`Bob ${e}`,className:"w-full h-auto object-contain",style:{display:"block",maxHeight:"100%",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1})}),r&&o.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-[70]",style:{height:`${s}%`,pointerEvents:"none"},children:o.jsx("img",{src:r,alt:"Shop counter",className:"w-full h-full",style:{objectFit:"fill",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1})})]})},Pu={background:"rgba(20, 30, 50, 0.92)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"28px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.35), inset 0 0 0 1px rgba(255,255,255,0.1)"},Iu={background:"linear-gradient(135deg, rgba(40, 60, 100, 0.95) 0%, rgba(20, 40, 80, 0.98) 100%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(0, 0, 0, 0.35), 0 0 0 1px rgba(255,255,255,0.15), inset 0 1px 0 rgba(255,255,255,0.2)"},Na={background:"rgba(255, 255, 255, 0.08)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"28px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.3)"},ss={primary:{color:"rgba(255, 255, 255, 1)",textShadow:"0 1px 3px rgba(0,0,0,0.5)"}},Nu={background:"rgba(255, 255, 255, 0.12)",borderRadius:"20px",border:"1px solid rgba(255, 255, 255, 0.15)"},Pi={background:"rgba(255, 255, 255, 0.15)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"12px"},Bu={width:"4px",height:"4px",borderRadius:"50%",background:"rgba(255, 255, 255, 0.6)",boxShadow:"0 0 8px rgba(255, 255, 255, 0.4)"},Ba=({product:t,isSpotlighted:e=!1,onProductClick:r,onAddToCart:s})=>{const[n,i]=g.useState(!1),[a,l]=g.useState(0),c=()=>{r==null||r(t)},u=v=>{v.stopPropagation(),s==null||s(t)},d=()=>{a===0&&t.brandImageUrl?l(1):l(2)},h=a===0?t.image_url:a===1?t.brandImageUrl:void 0,f=e?Iu:Pu,p=t.webDescription||t.name;return o.jsxs("div",{onClick:c,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),className:"relative w-full cursor-pointer glass-card",style:{...f,padding:"16px",paddingBottom:"60px",position:"relative",transform:n?"scale(1.04) translateY(-4px)":"scale(1) translateY(0)",boxShadow:n?"0 16px 56px rgba(0, 0, 0, 0.4), 0 0 24px rgba(255,255,255,0.08)":f.boxShadow,transition:"transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.3s ease-out"},children:[e&&o.jsxs("div",{className:"absolute -top-2.5 -right-2.5 z-10 flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.95) 0%, rgba(0, 73, 153, 1) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"20px",boxShadow:"0 8px 24px rgba(0, 102, 204, 0.5)",color:"white"},children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"currentColor",viewBox:"0 0 20 20",children:o.jsx("path",{d:"M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"})}),"Bob's Pick"]}),o.jsxs("div",{className:"flex items-start gap-4",children:[o.jsx("div",{className:"flex-shrink-0 flex items-center justify-center overflow-hidden",style:{...Nu,width:"92px",height:"92px",backgroundColor:"#ffffff"},children:h&&a<2?o.jsx("img",{src:h,alt:t.name,className:"w-full h-full object-contain p-2",loading:"lazy",onError:d}):o.jsx("div",{className:"flex flex-col items-center justify-center",style:{color:"rgba(255,255,255,0.4)"},children:o.jsx("svg",{className:"w-8 h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"font-bold leading-tight",style:{fontSize:"15px",letterSpacing:"-0.01em",...ss.primary},children:p}),t.partNumber&&o.jsx("p",{className:"mt-0.5 text-xs",style:{color:"rgba(255,255,255,0.5)"},children:t.partNumber}),o.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[t.brand&&o.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5",style:{...Pi,color:"rgba(255, 255, 255, 0.9)"},children:[o.jsx("svg",{className:"w-2.5 h-2.5",fill:"currentColor",viewBox:"0 0 20 20",children:o.jsx("path",{fillRule:"evenodd",d:"M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),t.brand]}),t.perCarQty&&t.perCarQty>1&&o.jsxs("span",{className:"inline-flex items-center text-xs font-semibold px-2 py-0.5",style:{...Pi,color:"rgba(255, 200, 50, 0.95)"},children:["Qty: ",t.perCarQty]})]}),(t.viscosity||t.volume)&&o.jsx("p",{className:"mt-1 text-xs font-medium",style:{color:"rgba(255, 255, 255, 0.7)"},children:[t.viscosity,t.volume].filter(Boolean).join(" / ")}),o.jsx("p",{className:"font-extrabold mt-2",style:{fontSize:"22px",letterSpacing:"-0.02em",color:"#FFD700",textShadow:"0 2px 6px rgba(0, 0, 0, 0.5), 0 0 12px rgba(255, 215, 0, 0.3)"},children:t.price>0?`$${t.price.toFixed(2)}`:"POA"})]})]}),o.jsx("button",{onClick:u,className:"absolute flex items-center justify-center cursor-pointer",style:{bottom:"12px",right:"12px",background:"linear-gradient(135deg, #22C55E 0%, #16A34A 100%)",border:"1px solid rgba(255, 255, 255, 0.35)",borderRadius:"22px",boxShadow:"0 10px 40px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)",width:"44px",height:"44px",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease-out"},onMouseEnter:v=>{v.currentTarget.style.transform="scale(1.08) translateY(-2px)",v.currentTarget.style.boxShadow="0 14px 48px rgba(34, 197, 94, 0.5), inset 0 1px 0 rgba(255,255,255,0.4)"},onMouseLeave:v=>{v.currentTarget.style.transform="scale(1) translateY(0)",v.currentTarget.style.boxShadow="0 10px 40px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},children:o.jsx("svg",{className:"w-5 h-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M12 4v16m8-8H4"})})}),t.partslotDescription&&o.jsx("div",{className:"mt-3 pt-3",style:{borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:o.jsx("span",{className:"text-xs font-medium",style:{color:"rgba(255, 255, 255, 0.6)"},children:t.partslotDescription})})]})},Fu=["SHOE","DRUM"],Lu=["PAD","ROTOR"];function Fa(t){var s,n;const e=((s=t.id)==null?void 0:s.toLowerCase())||"",r=((n=t.title)==null?void 0:n.toLowerCase())||"";return e.includes("rear-brake")||r.includes("rear brake")}function La(t,e){const r=e==="disc"?Fu:Lu;return t.filter(s=>{const n=s.partslotName.toUpperCase();return!r.some(i=>n.includes(i))})}function $a(t){return t.reduce((e,r)=>e+r.displayPrice,0)}const Ii=(t,e)=>{if(!t||!e)return!1;const r=t.toLowerCase();return e.toLowerCase().replace(/s\b/g,"").split(/\s+/).filter(Boolean).every(n=>r.includes(n))},$u=(t,e)=>{var n;const r=((n=t.brand)==null?void 0:n.toLowerCase())===e.brand.toLowerCase(),s=Math.abs(t.price-e.price)<1;return r&&s},Du=({product:t,isSpotlighted:e,spotlightedRef:r,onProductClick:s})=>o.jsx("div",{ref:e?r:void 0,children:o.jsx(Ba,{product:t,isSpotlighted:e,onProductClick:s})}),Ks=({products:t,servicePackages:e,highlightedPartType:r,highlightedProduct:s,onProductClick:n,onPackageSelect:i,isResearching:a,visible:l=!0,counterHeightPercent:c=22,hasVehicle:u=!1,onAddToCart:d,vehicleMakeModel:h,pendingVariants:f,pendingVariantMake:p,pendingVariantModel:v,onVariantSelect:m})=>{const b=h||"Bob's Shelf",y=zs();Wn();const _=g.useRef(null),k=g.useRef({}),w=g.useRef(null),[E,A]=g.useState(null),[F,N]=g.useState({}),[U,j]=g.useState({}),R=g.useMemo(()=>{const P={};return t.forEach(V=>{const Q=V.partslotDescription||"Other Parts";P[Q]||(P[Q]=[]),P[Q].push(V)}),Object.keys(P).sort((V,Q)=>V.localeCompare(Q)).map(V=>({name:V,products:P[V]}))},[t]);g.useEffect(()=>{if(!r)return;const P=setTimeout(()=>{const D=Object.entries(k.current);for(const[V,Q]of D)if(Q&&Ii(V,r)){Q.scrollIntoView({behavior:"smooth",block:"start"});break}},300);return()=>clearTimeout(P)},[r]);const[T,C]=g.useState(0),B=P=>{const D=P.currentTarget,V=D.scrollHeight-D.clientHeight;if(V>0){const Q=D.scrollTop/V;C(Math.max(0,Math.min(1,Q)))}},K=((f==null?void 0:f.length)??0)>0,Y=t.length>0||e.length>0||K,te=a&&!Y,$=Y&&!te,M=l||Y,J=y==="mobile"?92:y==="tablet"?65:70,oe=y==="desktop"?"900px":y==="tablet"?"500px":"100%",X=y==="mobile"?"calc(8px + env(safe-area-inset-top, 4px))":"6px";return o.jsxs(o.Fragment,{children:[Y&&l&&o.jsx("div",{style:{position:"fixed",right:"2px",top:`calc(${T*65+18}%)`,...Bu,opacity:.8,transition:"top 0.1s ease-out",zIndex:100,pointerEvents:"none"}}),o.jsxs("div",{ref:_,onScroll:B,className:`absolute overflow-y-auto overflow-x-hidden flex flex-col gap-3 md:gap-4 transition-all duration-400 ease-out product-scroll ${M?"opacity-100 translate-x-0":"opacity-0 translate-x-12 pointer-events-none"}`,style:{width:`${J}%`,maxWidth:oe,right:"0",left:"auto",top:X,bottom:y==="mobile"?"calc(100px + env(safe-area-inset-bottom, 0px))":"52px",paddingTop:"4px",paddingRight:"16px",paddingLeft:"16px",paddingBottom:"8px",zIndex:55,pointerEvents:"auto",touchAction:"pan-y",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"},children:[o.jsx("div",{className:"sticky top-0 z-10 -mx-1 px-3 py-2.5",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.85) 0%, rgba(0, 73, 153, 0.9) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"24px",boxShadow:"0 10px 40px rgba(0, 102, 204, 0.4)",border:"1px solid rgba(255, 255, 255, 0.25)"},children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[a&&Y?o.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:o.jsx("div",{className:"w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin"})}):o.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:o.jsx("svg",{className:"w-3.5 h-3.5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),o.jsx("span",{style:{...ss.primary,fontWeight:700,fontSize:"14px",letterSpacing:"0.025em"},children:a&&Y?"Updating...":b})]}),o.jsxs("span",{style:{color:"rgba(255,255,255,0.8)",fontSize:"12px",fontWeight:500},children:[t.length+e.length," ",t.length+e.length===1?"item":"items"]})]})}),te&&o.jsx("div",{className:"p-5",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(0, 102, 204, 0.3)"},children:o.jsx("div",{className:"w-6 h-6 border-2 border-t-transparent rounded-full animate-spin",style:{borderColor:"rgba(255,255,255,0.8)",borderTopColor:"transparent"}})}),o.jsxs("div",{children:[o.jsx("p",{style:{...ss.primary,fontWeight:600,fontSize:"14px"},children:"Searching shelves..."}),o.jsx("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:"Finding the best parts for you"})]})]})}),K&&f&&m&&o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsx("div",{className:"sticky top-0 z-10 px-4 py-3",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"20px",boxShadow:"0 8px 32px rgba(0, 102, 204, 0.35)",border:"1px solid rgba(255, 255, 255, 0.2)"},children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:o.jsx("svg",{className:"w-4 h-4 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),o.jsxs("div",{children:[o.jsxs("span",{className:"text-white font-semibold text-sm",children:["Which ",p," ",v,"?"]}),o.jsx("span",{className:"text-white/70 text-xs block",children:"Tap your variant to continue"})]})]})}),o.jsx("div",{className:"flex flex-col gap-2 px-1",children:(()=>{const P=(f||[]).map(V=>[V.engineCode,V.kw?`${V.kw}kW`:null,V.ccDisplay||(V.cc?`${V.cc}cc`:null),V.fuelType].filter(Boolean).join(" · ")||V.displayTitle),D=P.reduce((V,Q)=>(V[Q]=(V[Q]||0)+1,V),{});return(f||[]).map((V,Q)=>{const _e=P[Q],Ae=D[_e]>1&&V.displaySubtitle?V.displaySubtitle:_e;return o.jsx("button",{type:"button",onClick:()=>m(V),className:"w-full text-left transition-all duration-200 cursor-pointer rounded-2xl overflow-hidden focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 active:scale-[0.98]",style:{background:"linear-gradient(135deg, rgba(255, 255, 255, 0.92) 0%, rgba(255, 255, 255, 0.85) 100%)",backdropFilter:"blur(12px) saturate(150%)",WebkitBackdropFilter:"blur(12px) saturate(150%)",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.12)",border:"1px solid rgba(255, 255, 255, 0.4)",minHeight:"72px"},children:o.jsxs("div",{className:"flex items-center gap-3 p-4",children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center shrink-0 font-bold text-lg text-white",style:{background:"linear-gradient(135deg, #0066CC 0%, #0052A3 100%)",boxShadow:"0 2px 8px rgba(0, 102, 204, 0.4)"},children:V.optionNumber}),o.jsx("div",{className:"flex-1 min-w-0",children:o.jsx("p",{className:"font-semibold text-gray-900 text-base leading-tight",children:Ae})}),o.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{background:"rgba(0, 102, 204, 0.1)"},children:o.jsx("svg",{className:"w-4 h-4 text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M9 5l7 7-7 7"})})})]})},V.vehicle_id)})})()})]}),!te&&!Y&&o.jsx("div",{className:"p-5",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(255, 149, 0, 0.3)"},children:o.jsx("svg",{className:"w-5 h-5",style:{color:"#FF9500"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),o.jsxs("div",{children:[o.jsx("p",{style:{...ss.primary,fontWeight:600,fontSize:"14px"},children:"No products to display"}),o.jsxs("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:["Products: ",t.length," | Packages: ",e.length]})]})]})}),$&&e.length>0&&o.jsx("div",{className:"space-y-4",children:e.map(P=>{var Qe,nt;const D=Fa(P),V=U[P.id]||"disc";let Q=(P.preparedTiers||[]).filter(O=>!O.isHidden);D&&(Q=Q.map(O=>{const ee=La(O.products,V);return{...O,products:ee,totalPrice:$a(ee),productCount:ee.length}}));const _e=((Qe=Q.find(O=>O.isRecommended))==null?void 0:Qe.tierName)||((nt=Q[0])==null?void 0:nt.tierName)||"",Te=F[P.id]||_e,Ae=Q.find(O=>O.tierName===Te),Je=Pa(P.title).split(".")[0]+".",qe=E===P.id;return o.jsxs("div",{className:"overflow-hidden transition-all duration-300",style:{background:H.card,borderRadius:"16px",border:`1px solid ${H.border}`,boxShadow:"0 4px 20px rgba(0,0,0,0.08)"},children:[o.jsx("div",{className:"px-4 py-3",style:{background:`linear-gradient(135deg, ${H.primary} 0%, ${H.primaryHover} 100%)`},children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 flex items-center justify-center flex-shrink-0",children:o.jsx("svg",{className:"h-5 w-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h3",{className:"text-white font-bold text-base leading-tight truncate",children:P.title}),P.estimated_time&&o.jsx("div",{className:"flex items-center gap-3 mt-0.5",children:o.jsxs("span",{className:"text-white/70 text-xs flex items-center gap-1",children:[o.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),P.estimated_time]})})]})]})}),o.jsxs("div",{className:"px-4 py-3 border-b",style:{borderColor:H.border},children:[o.jsx("p",{className:"text-sm leading-relaxed",style:{color:H.mutedForeground},children:Je}),D&&o.jsxs("div",{className:"mt-2 mb-1",children:[o.jsx("p",{className:"text-[11px] mb-1.5",style:{color:H.mutedForeground},children:"Select your vehicle's rear brake type"}),o.jsxs("div",{className:"flex rounded-xl overflow-hidden border",style:{borderColor:H.border},children:[o.jsx("button",{onClick:()=>j(O=>({...O,[P.id]:"disc"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:V==="disc"?H.primary:"transparent",color:V==="disc"?"#FFFFFF":H.mutedForeground},children:"Disc Brakes (Pads + Rotors)"}),o.jsx("button",{onClick:()=>j(O=>({...O,[P.id]:"drum"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:V==="drum"?H.primary:"transparent",color:V==="drum"?"#FFFFFF":H.mutedForeground},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),Q.length>0&&o.jsxs("div",{className:"p-3",children:[o.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2 px-1",style:{color:H.mutedForeground},children:"Choose Your Value Level"}),o.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:`repeat(${Math.min(Q.length,4)}, 1fr)`},children:Q.map(O=>{const ee=$s[O.tierName],Oe=O.tierName===Te;return o.jsxs("div",{onClick:()=>N(we=>({...we,[P.id]:O.tierName})),className:"relative rounded-xl text-center transition-all cursor-pointer",style:{padding:Q.length>=4?"6px 4px":"8px",background:O.isRecommended?`${H.primary}10`:Oe?`${H.primary}05`:H.background,border:`2px solid ${O.isRecommended?H.primary:Oe?H.primary+"80":H.border}`},children:[O.isRecommended&&o.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wide whitespace-nowrap",style:{background:H.primary,color:"white"},children:"Carfix Value"}),o.jsxs("p",{className:"text-sm font-bold mt-1",style:{color:(ee==null?void 0:ee.textColor)||H.foreground},children:[ee==null?void 0:ee.emoji," ",O.displayName]}),o.jsx("div",{className:"flex flex-col items-center gap-1 mt-2",style:{minHeight:Q.length>=4?"40px":"48px"},children:O.brands.slice(0,1).map((we,me)=>{const ie=`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${we.fullName.replace(/\s+/g,"")}.jpg`;return o.jsx("div",{className:"w-full bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{height:Q.length>=4?"36px":"44px",maxWidth:Q.length>=4?"64px":"80px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",border:"1px solid #F1F5F9"},children:o.jsx("img",{src:we.imageUrl,alt:we.fullName,className:"w-auto object-contain",style:{height:Q.length>=4?"26px":"32px"},onError:ht=>{const ke=ht.target;ke.src!==ie?ke.src=ie:(ke.style.display="none",ke.parentElement.innerHTML=`<span class="text-[10px] font-semibold text-gray-600 truncate px-1">${we.fullName}</span>`)}})},me)})}),o.jsxs("p",{className:"text-[10px] mt-2",style:{color:H.mutedForeground},children:[O.productCount," ",O.productCount===1?"part":"parts"]}),O.savingsAmount&&O.savingsAmount>0?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-[11px] line-through",style:{color:H.mutedForeground},children:Ge(O.originalTotalPrice)}),o.jsx("p",{className:"text-base font-bold",style:{color:H.success},children:Ge(O.totalPrice)}),o.jsxs("p",{className:"text-[9px] font-semibold px-1.5 py-0.5 rounded-full mt-0.5",style:{background:`${H.success}15`,color:H.success},children:["SAVE ",Ge(O.savingsAmount)," — ",O.bundleDiscountPercentage,"% Bundle Deal"]})]}):o.jsx("p",{className:"text-base font-bold mt-1",style:{color:H.foreground},children:Ge(O.totalPrice)}),o.jsx("p",{className:"text-[10px]",style:{color:H.mutedForeground},children:"inc GST"}),o.jsx("button",{onClick:we=>{we.stopPropagation();const me=O.bundleDiscountPercentage||0,ie=1-me/100,ht=O.products.map(ke=>({id:ke.sku,name:ke.name,brand:ke.brand,price:me>0?Math.round(ke.displayPrice*ie*100)/100:ke.displayPrice,sku:ke.sku,partNumber:ke.partNumber||void 0,image_url:ke.productImageUrl,partslotDescription:ke.partslotName,quantity:1}));d==null||d(ht)},className:"w-full mt-2 py-1.5 rounded-lg text-[10px] font-semibold transition-all",style:{background:O.isRecommended?H.success:"#F1F5F9",color:O.isRecommended?"white":H.success,border:O.isRecommended?"none":"1px solid #E2E8F0",textAlign:"center"},children:"Add"})]},O.tierName)})})]}),o.jsxs("div",{onClick:()=>A(qe?null:P.id),className:"flex items-center justify-center gap-1.5 py-2 cursor-pointer hover:bg-gray-50 transition-colors border-t",style:{borderColor:H.border},children:[o.jsx("span",{className:"text-xs",style:{color:H.mutedForeground},children:qe?"Hide details":"Show details"}),o.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${qe?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",style:{color:H.mutedForeground},children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),qe&&Ae&&o.jsx("div",{className:"px-4 pb-4 border-t animate-in slide-in-from-top-2 duration-200",style:{borderColor:H.border},children:o.jsxs("div",{className:"pt-3",children:[o.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide mb-3",style:{color:H.mutedForeground},children:[Ae.displayName," Tier Products"]}),o.jsx("div",{className:"space-y-2",children:Ae.products.map(O=>o.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg",style:{background:H.background,border:`1px solid ${H.border}`},children:[o.jsx("div",{className:"w-14 h-14 flex-shrink-0 bg-white rounded-lg overflow-hidden flex items-center justify-center",children:O.productImageUrl?o.jsx("img",{src:O.productImageUrl,alt:O.name,className:"w-full h-full object-contain p-1"}):o.jsx("svg",{className:"w-6 h-6 text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-xs font-medium truncate",style:{color:H.foreground},children:O.name}),o.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[o.jsx("span",{className:"text-[10px]",style:{color:H.mutedForeground},children:O.brand}),O.isRotor&&o.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 font-medium",children:"Pair"})]}),o.jsx("p",{className:"text-[10px] mt-0.5",style:{color:H.mutedForeground},children:O.partslotName})]}),o.jsxs("div",{className:"text-right flex-shrink-0",children:[o.jsx("p",{className:"text-sm font-bold",style:{color:H.primary},children:Ge(O.displayPrice)}),O.isRotor&&o.jsxs("p",{className:"text-[9px]",style:{color:H.mutedForeground},children:["$",O.price.toFixed(2)," ea"]})]})]},O.sku))})]})})]},P.id)})}),$&&R.map(({name:P,products:D})=>{const V=r&&Ii(P,r);return o.jsxs("section",{ref:Q=>{k.current[P]=Q},className:"transition-all duration-300",style:{background:"transparent",borderRadius:"24px"},children:[o.jsxs("div",{"data-testid":"partslot-header","data-partslot-name":P,className:"px-3 py-2.5 flex items-center justify-between",style:{background:V?"rgba(0, 102, 204, 0.95)":"rgba(0, 51, 102, 0.9)",borderRadius:"16px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",marginBottom:"8px"},children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("div",{className:"w-5 h-5 rounded-md flex items-center justify-center flex-shrink-0",style:{background:V?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 1) 100%)":"rgba(255,255,255,0.2)"},children:o.jsx("svg",{className:"h-3 w-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),o.jsx("span",{className:"text-xs font-bold truncate uppercase tracking-wide",style:{color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)"},children:P})]}),o.jsx("span",{className:"text-[10px] font-bold px-2.5 py-1 rounded-full flex-shrink-0",style:{background:"rgba(255, 149, 0, 0.9)",color:"white",boxShadow:"0 2px 8px rgba(255, 149, 0, 0.4)"},children:D.length})]}),o.jsx("div",{className:"flex flex-col gap-3",children:D.map((Q,_e)=>{const Te=!!(s&&$u(Q,s));return o.jsx("div",{"data-testid":"partslot-product",children:o.jsx(Du,{product:Q,isSpotlighted:Te,spotlightedRef:w,onProductClick:n,viewportSize:y})},`${Q.id}-${_e}`)})})]},P)}),o.jsx("div",{className:"h-4"})]})]})},qn=({onTranscript:t,onSpeechEnd:e,language:r="en-NZ",mode:s="toggle"}={})=>{const[n,i]=g.useState(!1),[a,l]=g.useState(""),[c,u]=g.useState(""),[d,h]=g.useState(null),[f,p]=g.useState(!1),v=g.useRef(null),m=g.useRef(""),b=g.useRef(t),y=g.useRef(e),_=g.useRef(null),k=15e3;g.useEffect(()=>{b.current=t,y.current=e},[t,e]),g.useEffect(()=>{if(typeof window<"u"&&window.location.protocol!=="https:"&&window.location.hostname!=="localhost"&&window.location.hostname!=="127.0.0.1"){console.warn("[BobWidget] Speech recognition requires HTTPS. PTT will not work on HTTP."),h("Voice input requires a secure connection (HTTPS)"),p(!1);return}const F=window.SpeechRecognition||window.webkitSpeechRecognition;if(F){p(!0);const N=new F;N.continuous=s==="ptt",N.interimResults=!0,N.lang=r,N.maxAlternatives=1,N.onstart=()=>{i(!0),h(null)},N.onresult=U=>{let j="",R="";for(let T=U.resultIndex;T<U.results.length;T++){const C=U.results[T][0].transcript;U.results[T].isFinal?R+=C:j+=C}R&&(m.current=R,l(R),b.current&&b.current(R)),u(j)},N.onerror=U=>{switch(i(!1),U.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.")}},N.onend=()=>{_.current&&(clearTimeout(_.current),_.current=null),i(!1),u(""),m.current&&y.current&&y.current(m.current),m.current=""},v.current=N}return()=>{v.current&&v.current.stop()}},[r,s]);const w=()=>{v.current&&!n&&(l(""),u(""),h(null),_.current=setTimeout(()=>{console.warn("[SpeechRecognition] Safety timeout - forcing stop after 15s"),v.current&&v.current.abort(),i(!1),u("")},k),v.current.start())},E=()=>{_.current&&(clearTimeout(_.current),_.current=null),v.current&&n&&v.current.stop()};return{isListening:n,transcript:a,interimTranscript:c,error:d,isSupported:f,startListening:w,stopListening:E,toggleListening:()=>{n?E():w()}}},Da=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:l,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,onAddToCart:f,onProductClick:p,counterHeightPercent:v=22})=>{var X;const[m,b]=g.useState(!1),y=g.useRef(null),_=g.useRef(!1),{bottomOffset:k,zIndexBase:w}=Un(),{isListening:E,interimTranscript:A,error:F,isSupported:N,startListening:U,stopListening:j}=qn({onTranscript:P=>r(P),language:"en-NZ",mode:"ptt"});g.useEffect(()=>{A&&r(A)},[A,r]);const R=g.useCallback(P=>{P.preventDefault(),!(s||_.current)&&(_.current=!0,navigator.vibrate&&navigator.vibrate(30),U())},[s,U]),T=g.useCallback(()=>{_.current&&(_.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),j(),setTimeout(()=>{n()},150))},[j,n]),C=[...t].reverse().find(P=>P.role==="assistant"),B=((X=C==null?void 0:C.suggestedProducts)==null?void 0:X.length)||0,K=C!=null&&C.content?C.content.length>50?C.content.slice(0,50)+"...":C.content:"Ask Bob about car parts...",Y=B>0?` (${B} products)`:"",te={idle:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 8px 32px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"32px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},$=h?"speaking":s?"processing":E?"listening":"idle",J={idle:te.idle,listening:te.active,processing:te.disabled,speaking:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.95) 0%, rgba(22, 163, 74, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"}}[$],oe={idle:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-breathe 2s ease-in-out infinite"},listening:null,processing:{border:"2px solid rgba(156, 163, 175, 0.6)",animation:"ring-processing 1.5s ease-in-out infinite"},speaking:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-speaking 1.8s ease-in-out infinite"}};return o.jsxs("div",{ref:y,style:{position:"fixed",bottom:k,left:0,right:0,...Na,background:"rgba(15, 23, 42, 0.92)",borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"all 0.3s ease-out",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:m?"55vh":"90px",zIndex:w+80,paddingBottom:"env(safe-area-inset-bottom, 8px)"},children:[o.jsx("button",{onClick:()=>b(!m),style:{position:"absolute",top:"-20px",left:"50%",transform:"translateX(-50%)",background:"rgba(255, 255, 255, 0.15)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"9999px",padding:"6px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)",zIndex:w+90,cursor:"pointer",minHeight:"unset",minWidth:"unset"},"aria-label":m?"Collapse chat":"Expand chat",children:m?o.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}):o.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 15l7-7 7 7"})})}),!m&&o.jsx("div",{onClick:()=>b(!0),style:{padding:"8px 12px 2px 12px",cursor:"pointer"},children:o.jsxs("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[K,Y&&o.jsx("span",{style:{color:"rgba(255,200,0,0.9)",fontWeight:600},children:Y})]})}),m&&o.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px"},className:"glass-scroll",children:[[...t].reverse().map((P,D)=>{var V;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:P.role==="user"?"flex-end":"flex-start"},children:o.jsxs("div",{style:{maxWidth:(V=P.suggestedProducts)!=null&&V.length?"100%":"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:P.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:[P.content,P.role==="assistant"&&P.suggestedProducts&&P.suggestedProducts.length>0&&o.jsx(Mn,{products:P.suggestedProducts,title:P.suggestionsTitle,onAddToCart:f,onProductClick:p})]})},D)}),o.jsx("div",{ref:c})]}),N&&o.jsxs("div",{style:{display:"flex",justifyContent:"center",padding:"12px 16px 8px 16px",position:"relative"},children:[$==="listening"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),$!=="listening"&&oe[$]&&o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:oe[$].border,transform:"translate(-50%, -50%)",animation:oe[$].animation,pointerEvents:"none"}}),o.jsx("button",{onTouchStart:R,onTouchEnd:T,onTouchCancel:T,onMouseDown:R,onMouseUp:T,onMouseLeave:T,onClick:E?T:void 0,disabled:$==="processing","aria-label":"Hold to talk to Bob",className:"glass-button bob-ptt-btn",style:{width:"200px",height:"64px",minHeight:"unset",minWidth:"unset",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",touchAction:"none",cursor:$==="processing"?"not-allowed":"pointer",opacity:$==="processing"?.6:1,transform:$==="listening"?"scale(1.04)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease, background 0.3s ease",backdropFilter:J.backdropFilter,WebkitBackdropFilter:J.WebkitBackdropFilter,"--bob-ptt-bg":J.background,"--bob-ptt-shadow":J.boxShadow,"--bob-ptt-border":J.border,"--bob-ptt-radius":"32px"},title:"Hold to talk",children:o.jsx("span",{style:{fontSize:"22px",fontWeight:800,letterSpacing:"0.15em",...ss.primary,textTransform:"uppercase",fontFamily:"system-ui, -apple-system, sans-serif"},children:$==="listening"?"LISTENING":$==="processing"?"THINKING":$==="speaking"?"PLAYING":"TALK"})})]}),o.jsxs("div",{style:{padding:"4px 12px 8px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:[F&&o.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:F}),o.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[d&&o.jsx("button",{onClick:d,style:{flexShrink:0,height:"40px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"12px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:h?"#0066CC":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?o.jsxs("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):o.jsx("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),o.jsxs("div",{style:{flex:1,position:"relative",height:"40px"},children:[o.jsx("input",{type:"text",value:e,onChange:P=>r(P.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Message Bob...",disabled:$!=="idle",className:"high-contrast-input bob-chat-input",style:{width:"100%",height:"40px",fontSize:"16px",padding:"0 14px",background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",color:"#0F172A",outline:"none",opacity:$!=="idle"?0:1,transition:"opacity 0.15s ease"}}),$!=="idle"&&o.jsxs("div",{className:"bob-state-overlay",style:{position:"absolute",inset:0,background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",display:"flex",alignItems:"center",padding:"0 14px",gap:"8px"},children:[$==="listening"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#FF8C00",animation:"dot-pulse 1s ease-in-out infinite",flexShrink:0}}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Listening..."})]}),$==="processing"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{width:"18px",height:"18px",flexShrink:0,border:"2px solid rgba(15, 23, 42, 0.15)",borderTop:"2px solid #0F172A",borderRadius:"50%",animation:"processing-spin 0.8s linear infinite"}}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is researching your input."})]}),$==="speaking"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{display:"flex",alignItems:"center",gap:"2px",height:"20px",flexShrink:0},children:[0,.15,.3,.45,.6].map((P,D)=>o.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${P}s infinite`}},D))}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is talking..."}),u&&o.jsxs("svg",{style:{height:"16px",width:"16px",color:"#ef4444",marginLeft:"auto",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]})]})]})]})]})]})]})},Ua=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:f,chatEndRef:p,isMuted:v,onToggleMute:m,isSpeaking:b,products:y,servicePackages:_,highlightedPartType:k,highlightedProduct:w,onProductClick:E,onPackageSelect:A,isResearching:F,vehicle:N,onChangeVehicle:U,pendingVariants:j,pendingVariantMake:R,pendingVariantModel:T,onVariantSelect:C,bobOffset:B=0,bobScale:K=100,embedded:Y=!1})=>{console.log("[MobileBobLayout] Rendering with:",{currentImage:(t==null?void 0:t.substring(0,50))||"EMPTY",backdropUrl:(r==null?void 0:r.substring(0,50))||"NONE",counterOverlayUrl:(s==null?void 0:s.substring(0,50))||"NONE"});const te=zs(),[$,M]=g.useState("center"),[J,oe]=g.useState("hidden"),X=y.length>0||_.length>0,P=((j==null?void 0:j.length)??0)>0,D=X||P,_e=(()=>{switch(te){case"desktop":return 70;case"tablet":return 80;case"mobile":return 140;default:return 140}})()*K/100;g.useEffect(()=>{if(F&&J!=="loading"&&J!=="visible")oe("loading"),$==="center"&&M("partial-left");else if(D&&J!=="visible")if($==="center"){M("partial-left"),oe("transitioning");const Ae=setTimeout(()=>{oe("visible")},400);return()=>clearTimeout(Ae)}else oe("visible");else!D&&!F&&J!=="hidden"&&(oe("hidden"),M("center"))},[D,F,J,$]);const Te=J!=="hidden";return o.jsxs("div",{className:Y?"absolute inset-0 overflow-hidden":"fixed inset-0 overflow-hidden",style:{height:Y?"100%":"100dvh",touchAction:"manipulation"},children:[r&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"absolute inset-0 z-0",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)",transform:"scale(1.02)"}}),o.jsx("div",{className:"absolute inset-0 z-[1]",style:{background:"rgba(0, 0, 0, var(--bob-overlay-opacity, 0.1))"}})]}),o.jsx(Hs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:_e,position:$,verticalOffset:B}),o.jsx(Ks,{products:y,servicePackages:_,highlightedPartType:k,highlightedProduct:w,onProductClick:E,onPackageSelect:A,isResearching:F,visible:Te,counterHeightPercent:n,hasVehicle:!!N,pendingVariants:j,pendingVariantMake:R,pendingVariantModel:T,onVariantSelect:C}),o.jsx(Da,{messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:f,chatEndRef:p,isMuted:v,onToggleMute:m,isSpeaking:b,onAddToCart:E,onProductClick:E,counterHeightPercent:n})]})},Ma=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:l,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,counterHeightPercent:f=22})=>{const[p,v]=g.useState(!1),m=g.useRef(null),b=g.useRef(!1),{bottomOffset:y,zIndexBase:_}=Un(),{isListening:k,interimTranscript:w,error:E,isSupported:A,startListening:F,stopListening:N}=qn({onTranscript:$=>r($),language:"en-NZ",mode:"ptt"});g.useEffect(()=>{w&&r(w)},[w,r]);const U=g.useCallback($=>{$.preventDefault(),!(s||b.current)&&(b.current=!0,navigator.vibrate&&navigator.vibrate(30),F())},[s,F]),j=g.useCallback(()=>{b.current&&(b.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),N(),setTimeout(()=>{n()},150))},[N,n]),R=[...t].reverse().find($=>$.role==="assistant"),T=R!=null&&R.content?R.content.length>50?R.content.slice(0,50)+"...":R.content:"Ask Bob about car parts...",C={idle:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 8px 32px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"50%",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},B=h?"speaking":s?"processing":k?"listening":"idle",Y={idle:C.idle,listening:C.active,processing:C.disabled,speaking:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 12px 48px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"}}[B],te={idle:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-breathe 2s ease-in-out infinite"},listening:null,processing:{border:"2px solid rgba(156, 163, 175, 0.6)",animation:"ring-processing 1.5s ease-in-out infinite"},speaking:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-speaking 1.8s ease-in-out infinite"}};return o.jsxs("div",{ref:m,style:{position:"absolute",bottom:0,left:0,right:0,top:"auto",contain:"layout",transform:"translateZ(0)",WebkitTransform:"translateZ(0)",backfaceVisibility:"hidden",WebkitBackfaceVisibility:"hidden",isolation:"isolate",...Na,background:"rgba(15, 23, 42, 0.92)",borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"height 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:p?"55%":"110px",overflow:"visible",zIndex:_+30,paddingBottom:"calc(8px + env(safe-area-inset-bottom, 0px))",pointerEvents:"none"},children:[o.jsx("button",{onClick:()=>v(!p),style:{position:"absolute",top:"-24px",left:"50%",transform:"translateX(-50%)",background:"rgba(0, 102, 204, 0.9)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"2px solid rgba(255, 255, 255, 0.35)",borderRadius:"9999px",padding:"8px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.3)",zIndex:_+40,cursor:"pointer",minHeight:"32px",minWidth:"32px",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto"},"aria-label":p?"Collapse chat":"Expand chat",children:p?o.jsx("svg",{style:{height:"16px",width:"16px",color:"white"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 9l-7 7-7-7"})}):o.jsx("svg",{style:{height:"16px",width:"16px",color:"white"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M5 15l7-7 7 7"})})}),!p&&o.jsx("div",{onClick:()=>v(!0),style:{padding:"6px 12px 4px 12px",height:"26px",overflow:"hidden",cursor:"pointer",pointerEvents:"auto"},children:o.jsx("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T})}),p&&o.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px",pointerEvents:"auto"},className:"glass-scroll",children:[[...t].reverse().map(($,M)=>o.jsx("div",{style:{display:"flex",justifyContent:$.role==="user"?"flex-end":"flex-start"},children:o.jsx("div",{style:{maxWidth:"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:$.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:$.content})},M)),o.jsx("div",{ref:c})]}),o.jsxs("div",{style:{padding:p?"8px 12px 4px 12px":"4px 12px 4px 12px",borderTop:p?"1px solid rgba(255, 255, 255, 0.15)":"none",pointerEvents:"auto"},children:[E&&o.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:E}),o.jsxs("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[d&&p&&o.jsx("button",{onClick:d,style:{flexShrink:0,height:"36px",width:"36px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"10px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:h?"#22c55e":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?o.jsxs("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):o.jsx("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),o.jsxs("div",{style:{flex:1,position:"relative",height:"40px"},children:[o.jsx("input",{type:"text",value:e,onChange:$=>r($.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Message Bob...",disabled:B!=="idle",className:"high-contrast-input bob-chat-input",style:{width:"100%",height:"40px",fontSize:"16px",padding:"0 14px",background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",color:"#0F172A",outline:"none",opacity:B!=="idle"?0:1,transition:"opacity 0.15s ease"}}),B!=="idle"&&o.jsxs("div",{className:"bob-state-overlay",style:{position:"absolute",inset:0,background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",display:"flex",alignItems:"center",padding:"0 14px",gap:"8px"},children:[B==="listening"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#FF8C00",animation:"dot-pulse 1s ease-in-out infinite",flexShrink:0}}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Listening..."})]}),B==="processing"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{width:"18px",height:"18px",flexShrink:0,border:"2px solid rgba(15, 23, 42, 0.15)",borderTop:"2px solid #0F172A",borderRadius:"50%",animation:"processing-spin 0.8s linear infinite"}}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is researching your input."})]}),B==="speaking"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{display:"flex",alignItems:"center",gap:"2px",height:"20px",flexShrink:0},children:[0,.15,.3,.45,.6].map(($,M)=>o.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${$}s infinite`}},M))}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is talking..."}),u&&o.jsxs("svg",{style:{height:"16px",width:"16px",color:"#ef4444",marginLeft:"auto",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]})]})]})]}),A&&o.jsxs("div",{style:{position:"relative",marginLeft:"4px"},children:[B==="listening"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),B!=="listening"&&te[B]&&o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:te[B].border,transform:"translate(-50%, -50%)",animation:te[B].animation,pointerEvents:"none"}}),o.jsxs("button",{onTouchStart:U,onTouchEnd:j,onTouchCancel:j,onMouseDown:U,onMouseUp:j,onMouseLeave:j,disabled:B==="processing","aria-label":"Hold to talk to Bob",className:"glass-button bob-ptt-btn",style:{position:"relative",flexShrink:0,height:"72px",width:"72px",minHeight:"unset",minWidth:"unset",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",touchAction:"none",color:"white",cursor:B==="processing"?"not-allowed":"pointer",opacity:B==="processing"?.6:1,transform:B==="listening"?"scale(1.08)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease, background 0.3s ease",zIndex:_+45,backdropFilter:Y.backdropFilter,WebkitBackdropFilter:Y.WebkitBackdropFilter,"--bob-ptt-bg":Y.background,"--bob-ptt-shadow":Y.boxShadow,"--bob-ptt-border":Y.border,"--bob-ptt-radius":"50%"},title:"Hold to talk",children:[o.jsx("svg",{style:{height:"28px",width:"28px",filter:"drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2))"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})}),B==="listening"&&o.jsx("div",{style:{position:"absolute",top:"8px",right:"8px",width:"12px",height:"12px",borderRadius:"50%",backgroundColor:"#fef3c7",animation:"ptt-dot 0.6s ease-in-out infinite alternate"}})]})]})]})]})]})},Uu=({product:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{const n=t.productUrl||t.product_url,i=t.partNumber||t.part_number,a=!!n||!!s;return o.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-white/95 backdrop-blur-md overflow-hidden",children:[o.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-gray-200 bg-white/80 backdrop-blur-sm",children:o.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-blue-600 font-medium text-sm hover:text-blue-700 active:scale-95 transition-all",children:[o.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back to Products"]})}),o.jsxs("div",{className:"flex-1 overflow-y-auto",children:[o.jsx("div",{className:"aspect-square bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center",children:t.image_url?o.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-4"}):o.jsxs("div",{className:"flex flex-col items-center justify-center text-gray-400",children:[o.jsx("svg",{className:"h-16 w-16 mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})}),o.jsx("span",{className:"text-sm font-medium uppercase tracking-wide",children:"No Image Available"})]})}),o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-xl font-bold text-gray-900 mb-1",children:t.name}),t.brand&&o.jsx("p",{className:"text-sm text-gray-600 font-medium",children:t.brand})]}),o.jsxs("div",{className:"bg-blue-50 rounded-xl p-4",children:[o.jsx("p",{className:"text-sm text-gray-600 mb-1",children:"Price"}),o.jsx("p",{className:"text-2xl font-bold text-blue-600",children:t.price>0?`$${t.price.toFixed(2)}`:"Price on Request"}),t.price>0&&o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Inc. GST"})]}),o.jsxs("div",{className:"space-y-3",children:[t.partslotDescription&&o.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[o.jsx("span",{className:"text-sm text-gray-500",children:"Category"}),o.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.partslotDescription})]}),t.sku&&o.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[o.jsx("span",{className:"text-sm text-gray-500",children:"SKU"}),o.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.sku})]}),i&&o.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[o.jsx("span",{className:"text-sm text-gray-500",children:"Part Number"}),o.jsx("span",{className:"text-sm font-medium text-gray-900",children:i})]})]}),a&&o.jsx("a",{href:n||"#",onClick:l=>{s&&(l.preventDefault(),s(t))},target:n&&!s?"_blank":void 0,rel:n&&!s?"noopener noreferrer":void 0,className:"block text-center text-blue-600 text-sm font-medium hover:underline py-2",children:"View Full Details on CARFIX →"})]})]}),o.jsx("div",{className:"p-4 border-t border-gray-200 bg-white/95 backdrop-blur-sm",children:o.jsx("button",{onClick:()=>r==null?void 0:r(t),className:"w-full bg-blue-600 text-white text-base font-semibold py-3 rounded-xl hover:bg-blue-700 active:bg-blue-800 transition-colors shadow-lg",children:"Add to Cart"})})]})},Wa=({package:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{var m;const[n,i]=g.useState(!1),[a,l]=g.useState("disc"),c=g.useMemo(()=>Fa(t),[t.id,t.title]),u=g.useMemo(()=>{if(!t.preparedTiers||t.preparedTiers.length===0)return[];const b=t.preparedTiers.filter(y=>!y.isHidden);return c?b.map(y=>{const _=La(y.products,a);return{...y,products:_,totalPrice:$a(_),productCount:_.length}}):b},[t.preparedTiers,c,a]),d=u.length>0,h=b=>{const y=b.bundleDiscountPercentage||0;if(y>0){const _=1-y/100,k=b.products.map(w=>({...w,displayPrice:Math.round(w.displayPrice*_*100)/100}));r==null||r(k)}else r==null||r(b.products)},f=b=>b===2?"grid-cols-2":b===3?"grid-cols-3":"grid-cols-2",p=Pa(t.title),v=((m=u[0])==null?void 0:m.productCount)||0;return o.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-[#FAFAFA] overflow-hidden",children:[o.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[#E2E8F0] bg-white shadow-sm",children:o.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-[#0052CC] font-medium text-sm hover:text-[#0047B3] active:scale-95 transition-all",children:[o.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]})}),o.jsxs("div",{className:"flex-1 overflow-y-auto",children:[o.jsxs("div",{className:"px-4 pt-4 pb-4",style:{background:"linear-gradient(135deg, rgba(0,82,204,0.05) 0%, rgba(56,189,248,0.05) 100%)"},children:[o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0 bg-white shadow-md",children:t.icon_url?o.jsx("img",{src:t.icon_url,alt:"",className:"w-8 h-8 object-contain"}):o.jsx("svg",{className:"w-7 h-7 text-[#0052CC]",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h1",{className:"text-xl font-bold text-[#0F172A]",children:t.title}),o.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-[#64748B]",children:[t.estimated_time&&o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),t.estimated_time]}),t.difficulty_level&&o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085"})}),t.difficulty_level]})]})]})]}),o.jsx("p",{className:"text-sm text-[#64748B] mt-3 leading-relaxed",children:p}),c&&o.jsxs("div",{className:"mt-3",children:[o.jsx("p",{className:"text-[11px] text-[#94A3B8] mb-1.5",children:"Select your vehicle's rear brake type"}),o.jsxs("div",{className:"flex rounded-xl overflow-hidden border border-[#E2E8F0] bg-white",children:[o.jsx("button",{onClick:()=>l("disc"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:a==="disc"?H.primary:"transparent",color:a==="disc"?"#FFFFFF":"#64748B"},children:"Disc Brakes (Pads + Rotors)"}),o.jsx("button",{onClick:()=>l("drum"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:a==="drum"?H.primary:"transparent",color:a==="drum"?"#FFFFFF":"#64748B"},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),o.jsxs("div",{className:"px-4 py-3 flex items-center justify-center gap-2 border-b border-[#E2E8F0] bg-white",children:[o.jsx("span",{className:"font-semibold text-[#0F172A] text-sm",children:"Choose Your Value Level"}),o.jsx("span",{className:"text-[#64748B] text-xs cursor-help",title:"Select the quality tier that suits your needs",children:"ⓘ"})]}),o.jsx("div",{className:"p-4",children:d?o.jsx("div",{className:`grid ${f(u.length)} gap-3`,children:u.map(b=>{const y=$s[b.tierName];return o.jsxs("div",{className:"relative rounded-2xl overflow-hidden bg-white shadow-md flex flex-col",style:{border:b.isRecommended?"2px solid #0052CC":"1px solid #E2E8F0"},children:[b.isRecommended&&o.jsx("div",{className:"absolute top-0 left-0 right-0 px-2 py-1 text-[9px] font-bold text-white text-center",style:{background:H.primary},children:"★ CARFIX VALUE"}),o.jsxs("div",{className:`p-3 flex-1 flex flex-col ${b.isRecommended?"pt-7":""}`,children:[o.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[o.jsx("span",{className:"text-lg",children:y==null?void 0:y.emoji}),o.jsxs("div",{children:[o.jsx("span",{className:"font-bold text-sm block",style:{color:(y==null?void 0:y.textColor)||H.foreground},children:b.displayName}),o.jsx("span",{className:"text-[10px] text-[#64748B] hidden md:block",children:b.description||(y==null?void 0:y.description)})]})]}),o.jsx("div",{className:"flex items-center gap-1.5 mb-3 min-h-[42px] flex-wrap",children:b.brands.slice(0,3).map(_=>o.jsx("div",{className:"h-10 px-2 bg-white rounded-xl flex items-center justify-center shadow-md border border-[#F1F5F9]",children:o.jsx("img",{src:_.imageUrl,alt:_.fullName,className:"h-6 w-auto object-contain",onError:k=>{const w=k.target,E=`${fs.storageBase}/brand_images/${_.fullName.replace(/\s+/g,"")}.jpg`;if(w.src!==E)w.src=E;else{const A=w.parentElement;A&&(A.innerHTML=`<span class="text-[10px] font-medium text-slate-700 px-1 truncate max-w-[60px]">${_.name}</span>`)}}})},_.name))}),o.jsxs("p",{className:"text-xs text-[#64748B] hidden md:block mb-2",children:[b.productCount," part",b.productCount!==1?"s":""," included"]}),o.jsx("div",{className:"mt-auto",children:b.savingsAmount&&b.savingsAmount>0?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-xs line-through text-[#94A3B8]",children:Ge(b.originalTotalPrice)}),o.jsx("p",{className:"text-xl font-bold",style:{color:"#22C55E"},children:Ge(b.totalPrice)}),o.jsxs("p",{className:"text-[10px] font-semibold text-[#22C55E] bg-[#22C55E]/10 inline-block px-1.5 py-0.5 rounded-full mt-0.5",children:["SAVE ",Ge(b.savingsAmount)," — ",b.bundleDiscountPercentage,"% Bundle Deal"]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-xl font-bold",style:{color:b.isRecommended?"#0052CC":"#0F172A"},children:Ge(b.totalPrice)}),o.jsx("p",{className:"text-[10px] text-[#64748B] hidden md:block",children:"inc GST"})]})}),o.jsx("button",{onClick:()=>h(b),className:`mt-3 w-full px-3 py-2.5 rounded-xl text-xs font-semibold transition-all hover:scale-[1.02] active:scale-95 flex items-center justify-center ${b.isRecommended?"bg-[#22C55E] text-white shadow-md hover:bg-[#16A34A]":"bg-slate-100 text-[#22C55E] border border-slate-200 hover:bg-slate-200"}`,children:"Add to Cart"})]})]},b.tierName)})}):o.jsxs("div",{className:"rounded-2xl p-6 bg-white border border-[#E2E8F0] shadow-md text-center",children:[o.jsx("svg",{className:"w-12 h-12 mx-auto text-[#94A3B8] mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),o.jsx("p",{className:"text-sm font-medium text-[#64748B]",children:"Package details not available for this vehicle"}),o.jsx("p",{className:"text-xs text-[#94A3B8] mt-1",children:"Please try refreshing or contact support"})]})}),d&&o.jsxs("div",{className:"px-4 pb-4",children:[o.jsxs("button",{onClick:()=>i(!n),className:"w-full flex items-center justify-between p-3 rounded-xl bg-white border border-[#E2E8F0] hover:bg-slate-50 transition-all shadow-sm",children:[o.jsxs("span",{className:"text-sm font-medium text-[#0F172A]",children:[n?"▼":"▶"," View Product Details"]}),o.jsxs("span",{className:"text-xs text-[#64748B]",children:[v," product",v!==1?"s":""]})]}),n&&o.jsx("div",{className:"mt-3 space-y-4 bg-white rounded-xl border border-[#E2E8F0] p-3",children:u.map(b=>{if(b.products.length===0)return null;const y=$s[b.tierName];return o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2 pb-1 border-b border-[#E2E8F0]",children:[o.jsx("span",{className:"text-lg",children:y==null?void 0:y.emoji}),o.jsx("span",{className:"font-semibold text-sm",style:{color:y==null?void 0:y.textColor},children:b.displayName}),o.jsxs("span",{className:"text-xs text-[#64748B]",children:["(",b.products.length," parts)"]})]}),o.jsx("div",{className:"space-y-2",children:b.products.map((_,k)=>{var A;const w=(A=t.carfixValueProducts)==null?void 0:A.includes(_.sku),E=_.unitPrice??_.price;return o.jsxs("div",{className:"flex items-center gap-3 p-2.5 rounded-xl transition-all hover:bg-slate-50 cursor-pointer border border-[#E2E8F0]",onClick:()=>s==null?void 0:s(_.sku),children:[o.jsx("div",{className:"w-14 h-14 flex-shrink-0 rounded-lg bg-white overflow-hidden border border-[#E2E8F0]",children:o.jsx("img",{src:_.productImageUrl||fs.productImage(_.sku),alt:_.name,className:"w-full h-full object-contain p-1.5",onError:F=>{F.target.src="/placeholder.svg"}})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[o.jsx("span",{className:"text-xs font-semibold text-[#0F172A]",children:_.brandFullName||_.brand}),w&&o.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"rgba(0, 82, 204, 0.1)",color:"#0052CC"},children:"CFX VALUE"}),_.isMultiQty&&_.perCarQty>1&&o.jsxs("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#F0FDF4",color:"#15803D"},children:["×",_.perCarQty]}),_.isRotor&&o.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#EFF6FF",color:"#1D4ED8"},children:"Pair"})]}),o.jsx("p",{className:"text-xs text-[#64748B] line-clamp-1",children:_.name})]}),o.jsxs("div",{className:"text-right flex-shrink-0",children:[o.jsx("p",{className:"text-sm font-bold text-[#0F172A]",children:Ge(_.displayPrice)}),_.isMultiQty&&_.perCarQty>1&&o.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[_.perCarQty,"× ",Ge(E)," each"]}),_.isRotor&&!_.isMultiQty&&o.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[Ge(E)," each"]})]})]},`${_.sku}-${k}`)})})]},b.tierName)})})]}),t.bundle_discount_percentage&&t.bundle_discount_percentage>0&&o.jsx("div",{className:"px-4 pb-4",children:o.jsx("div",{className:"rounded-xl p-3 text-center",style:{background:"rgba(34,197,94,0.1)",border:"1px solid rgba(34,197,94,0.2)"},children:o.jsxs("span",{className:"text-sm font-semibold text-[#22C55E]",children:["Bundle saves you ",t.bundle_discount_percentage,"%"]})})})]})]})},qa=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:f,chatEndRef:p,isMuted:v,onToggleMute:m,isSpeaking:b,products:y,servicePackages:_,highlightedPartType:k,highlightedProduct:w,onProductClick:E,onPackageSelect:A,isResearching:F,onAddToCart:N,onNavigateToProductPage:U,vehicle:j,onChangeVehicle:R,pendingVariants:T,pendingVariantMake:C,pendingVariantModel:B,onVariantSelect:K,bobOffset:Y=0,bobScale:te=100})=>{const[$,M]=g.useState("center"),[J,oe]=g.useState("hidden"),[X,P]=g.useState("products"),[D,V]=g.useState(null),[Q,_e]=g.useState(null),Te=y.length>0||_.length>0,Ae=((T==null?void 0:T.length)??0)>0,Be=Te||Ae,Qe=(X==="productDetail"?70:$==="center"&&!Be?140:98)*te/100;g.useEffect(()=>{if(F&&J!=="loading"&&J!=="visible")oe("loading"),$==="center"&&M("partial-left");else if(Be&&J!=="visible")if($==="center"){M("partial-left"),oe("transitioning");const me=setTimeout(()=>{oe("visible")},400);return()=>clearTimeout(me)}else oe("visible");else!Be&&!F&&J!=="hidden"&&(oe("hidden"),M("center"))},[Be,F,J,$]);const nt=me=>{if(U){U(me),E==null||E(me);return}V(me),P("productDetail"),E==null||E(me)},O=()=>{V(null),_e(null),P("products")},ee=me=>{console.log("[ContainedMobileBobLayout] Package selected:",me.title),_e(me),P("packageDetail"),A==null||A(me)},Oe=J!=="hidden"&&X==="products",we=J!=="hidden";return o.jsxs("div",{className:"absolute inset-0",style:{overflow:"clip",isolation:"isolate"},onContextMenu:me=>me.preventDefault(),children:[r&&o.jsx("div",{className:"absolute inset-0 z-0 transition-all duration-500 ease-out",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:we?"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)":"none",transform:we?"scale(1.02)":"scale(1)",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"}}),o.jsx(Hs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:Qe,position:$,verticalOffset:Y}),o.jsx(Ks,{products:y,servicePackages:_,highlightedPartType:k,highlightedProduct:w,onProductClick:nt,onPackageSelect:ee,isResearching:F,visible:Oe,counterHeightPercent:n,hasVehicle:!!j,vehicleMakeModel:j?`${j.make||""} ${j.model||""}`.trim():void 0,pendingVariants:T,pendingVariantMake:C,pendingVariantModel:B,onVariantSelect:K}),X==="productDetail"&&D&&o.jsx(Uu,{product:D,onBack:O,onAddToCart:N,onNavigateToProductPage:U}),X==="packageDetail"&&Q&&o.jsx(Wa,{package:Q,onBack:O,onNavigateToProductPage:me=>{const ie=y.find(ht=>ht.sku===me);ie&&U&&U(ie)}}),X==="products"&&o.jsx(Ma,{messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:f,chatEndRef:p,isMuted:v,onToggleMute:m,isSpeaking:b,counterHeightPercent:n})]})},zn=({variant:t="inline",initialState:e="idle",showChat:r=!0,className:s="",backdropUrl:n,counterOverlayUrl:i,counterHeightPercent:a,defaultBobImage:l,verticalOffset:c=0,scale:u=100,sessionToken:d,embedded:h=!1})=>{var Qe,nt;const{callbacks:f}=jt(),[p,v]=g.useState(!1),{animationState:m,setAnimationState:b,getCurrentImage:y,getCurrentOffset:_,getCurrentScale:k,availableStates:w}=ja({isSpeaking:p}),{activeBackdrop:E}=Ta(),[A,F]=g.useState([]),[N,U]=g.useState([]),[j,R]=g.useState(null),[T,C]=g.useState(null),[B,K]=g.useState(!1),[Y,te]=g.useState([]),[$,M]=g.useState(""),[J,oe]=g.useState(""),X=g.useRef(null),P=g.useRef(null);g.useEffect(()=>{X.current=O=>{if(K(!1),!O||O.length===0){console.log("[Bob] Clearing products (empty array received)"),F([]);return}const ee=O[0];console.log("[Bob] First part raw keys:",Object.keys(ee));const Oe=O.map((ie,ht)=>{const ke=ie.Brand||ie.brand||"";return{id:ie.SKU||ie.sku||`part-${ht}`,name:ie["Part Product Type"]||ie.partslot_description||ie.name||"Unknown Part",brand:ke,price:ie["Metro Retail Price"]||ie.price||0,sku:ie.SKU||ie.sku,partNumber:ie["Part Number"]||ie.part_number||null,partslotDescription:ie["Part Product Type"]||ie.partslot_description||ie.partslotDescription||ie.part_type||ie.category||"General Parts",image_url:ie.image_url||(ie.SKU||ie.sku?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${ie.SKU||ie.sku}.jpg`:void 0),webDescription:ie["Web Part Description"]||ie.web_description||null,brandDescription:ie["Brand Description"]||ie.brand_description||null,perCarQty:ie["Per Car Qty"]||ie.per_car_qty||1,volume:ie.volume||null,viscosity:ie.viscosity||null,brandImageUrl:ke?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${ke.replace(/\s+/g,"")}.jpg`:void 0}}),we=new Set,me=Oe.filter(ie=>!ie.sku||we.has(ie.sku)?!1:(we.add(ie.sku),!0));console.log("[Bob] Products mapped:",Oe.length,"-> deduped:",me.length),F(me)},P.current=O=>{if(!O||O.length===0){console.log("[Bob] Clearing service packages (empty array received)"),U([]);return}console.log("[Bob] Service packages received via stable ref:",O.length),U(O)}},[]);const D=Sa({setAnimationState:b,manualMode:!1,onReadyToSpeak:()=>{console.log("[BobWidget] Ready to speak")},onStreamComplete:()=>{b(w.find(O=>O.includes("idle"))||"idle")},onResearchStart:()=>{K(!0),te([]),M(""),oe("")},onVariantSelectionRequired:(O,ee,Oe)=>{K(!1),te(O),M(ee),oe(Oe)},onHighlightPart:O=>{R(O),setTimeout(()=>R(null),8e3)},onHighlightProduct:O=>{C(O),setTimeout(()=>C(null),8e3)},onAutoFetchComplete:()=>{K(!1)}});g.useEffect(()=>{D.identifiedVehicle&&(te([]),M(""),oe(""))},[(Qe=D.identifiedVehicle)==null?void 0:Qe.vehicle_id,(nt=D.identifiedVehicle)==null?void 0:nt.id]);const V=O=>{te([]),D.setInput(`Option ${O.optionNumber}`),setTimeout(()=>{D.handleSend()},80)};g.useEffect(()=>{v(D.isSpeaking)},[D.isSpeaking]),g.useEffect(()=>{const O=f.onPartsFound,ee=f.onServicePackagesFound;return f.onPartsFound=Oe=>{var we;(we=X.current)==null||we.call(X,Oe),O==null||O(Oe)},f.onServicePackagesFound=Oe=>{var we;(we=P.current)==null||we.call(P,Oe),ee==null||ee(Oe)},()=>{f.onPartsFound=O,f.onServicePackagesFound=ee}},[f]);const Q=n||(E==null?void 0:E.image_url),_e=i||(E==null?void 0:E.counter_overlay_url)||void 0,Te=a||(E==null?void 0:E.counter_height_percent)||12,Ae=y()||l||"",Be=_(),Je=k();if(t==="mobile"||t==="fullscreen")return o.jsx(Ua,{currentImage:Ae,animationState:m,backdropUrl:Q,counterOverlayUrl:_e,counterHeightPercent:Te,bobOffset:Be,bobScale:Je,embedded:h,messages:D.messages,input:D.input,setInput:D.setInput,isLoading:D.isLoading,onSend:D.handleSend,onKeyPress:D.handleKeyPress,onInputFocus:D.handleInputFocus,onInputBlur:D.handleInputBlur,chatEndRef:D.chatEndRef,isMuted:D.isMuted,onToggleMute:D.toggleMute,isSpeaking:D.isSpeaking,products:A,servicePackages:N,highlightedPartType:j,highlightedProduct:T,onAddToCart:O=>{var ee;return(ee=f.onAddToCart)==null?void 0:ee.call(f,{product_id:O.id,product_name:O.name,quantity:1,unit_price:O.price,sku:O.sku,brand:O.brand})},onNavigateToProductPage:O=>{var ee;return(ee=f.onNavigateToProductPage)==null?void 0:ee.call(f,O)},onPackageSelect:O=>console.log("[BobWidget] Package selected:",O),isResearching:B,vehicle:D.identifiedVehicle,pendingVariants:Y,pendingVariantMake:$,pendingVariantModel:J,onVariantSelect:V});if(t==="inline"&&r)return o.jsx("div",{className:`relative w-full h-full ${s}`,children:o.jsx(qa,{currentImage:Ae,animationState:m,backdropUrl:Q,counterOverlayUrl:_e,counterHeightPercent:Te,bobOffset:Be,bobScale:Je,messages:D.messages,input:D.input,setInput:D.setInput,isLoading:D.isLoading,onSend:D.handleSend,onKeyPress:D.handleKeyPress,onInputFocus:D.handleInputFocus,onInputBlur:D.handleInputBlur,chatEndRef:D.chatEndRef,isMuted:D.isMuted,onToggleMute:D.toggleMute,isSpeaking:D.isSpeaking,products:A,servicePackages:N,highlightedPartType:j,highlightedProduct:T,onAddToCart:O=>{var ee;return(ee=f.onAddToCart)==null?void 0:ee.call(f,{product_id:O.id,product_name:O.name,quantity:1,unit_price:O.price,sku:O.sku,brand:O.brand})},onNavigateToProductPage:O=>{var ee;return(ee=f.onNavigateToProductPage)==null?void 0:ee.call(f,O)},onPackageSelect:O=>console.log("[BobWidget] Package selected:",O),isResearching:B,vehicle:D.identifiedVehicle,pendingVariants:Y,pendingVariantMake:$,pendingVariantModel:J,onVariantSelect:V})});const qe={inline:"",floating:"fixed bottom-4 right-4 w-96 z-50 shadow-2xl rounded-lg overflow-hidden"};return o.jsxs("div",{className:`${qe[t]||""} ${s}`,children:[Ae&&o.jsx(Ra,{currentImage:Ae,animationState:m,backdropUrl:Q,counterOverlayUrl:_e,counterHeightPercent:Te,verticalOffset:Be,scale:Je}),r&&o.jsx(Ia,{messages:D.messages,input:D.input,setInput:D.setInput,isLoading:D.isLoading,onSend:D.handleSend,onKeyPress:D.handleKeyPress,onInputFocus:D.handleInputFocus,onInputBlur:D.handleInputBlur,chatEndRef:D.chatEndRef,isMuted:D.isMuted,onToggleMute:D.toggleMute,isSpeaking:D.isSpeaking})]})},Mu=({bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,variant:n="mobile",initialState:i,showChat:a,className:l,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:f,scale:p,ga4Config:v,analyticsEnabled:m=!0,bottomOffset:b=0,zIndexBase:y=50,embedded:_=!1})=>(g.useEffect(()=>{console.log("[BobWidget] Initialized",{version:St,variant:n,bottomOffset:b,zIndexBase:y,bobConfigUrl:t.supabaseUrl,hostApiBaseUrl:e.baseUrl,analyticsEnabled:m})},[n,b,y,t.supabaseUrl,e.baseUrl,m]),o.jsx("div",{className:"bob-widget-root",style:{width:"100%",height:"100%"},children:o.jsx(Dn,{bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,ga4Config:v,analyticsEnabled:m,bottomOffset:b,zIndexBase:y,children:o.jsx(zn,{variant:n,initialState:i,showChat:a,className:l,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:f,scale:p,embedded:_})})}));function Wu(t){return t<640?"mobile":t<1024?"tablet":"desktop"}function qu(){const t=[];if(typeof window>"u")return t;const e=document.querySelector(".bob-widget-root");if(!e)return t.push("bob-widget-root not found in DOM"),t;const r=window.getComputedStyle(e),s=e.parentElement;return s&&window.getComputedStyle(s).overflow==="hidden"&&t.push("Parent has overflow:hidden - may clip Bob"),r.transform!=="none"&&r.transform!=="matrix(1, 0, 0, 1, 0, 0)"&&t.push(`Unexpected transform on root: ${r.transform}`),r.isolation!=="isolate"&&t.push("Isolation not properly set"),t}const za=({partnerConfig:t,sessionToken:e})=>{const[r,s]=g.useState(null),[n,i]=g.useState([]),[a,l]=g.useState(!1);if(g.useEffect(()=>{const u=()=>{var f;const d=window.innerWidth,h=window.innerHeight;s({viewport:{width:d,height:h,deviceType:Wu(d)},origin:window.location.origin,originAllowed:((f=t==null?void 0:t.allowed_origins)==null?void 0:f.some(p=>p===window.location.origin||p.includes("*")))??!1,userAgent:navigator.userAgent.slice(0,50)+"...",timestamp:new Date().toISOString()}),i(qu())};return u(),window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[t]),!r)return null;const c=({ok:u,label:d})=>o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"4px",fontSize:"11px",fontWeight:500,background:u?"rgba(34, 197, 94, 0.2)":"rgba(239, 68, 68, 0.2)",color:u?"#22c55e":"#ef4444"},children:[u?"✓":"✗"," ",d]});return o.jsxs("div",{style:{position:"fixed",top:"8px",right:"8px",zIndex:99999,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace',fontSize:"11px",lineHeight:1.4},children:[o.jsx("button",{onClick:()=>l(!a),style:{position:"absolute",top:0,right:0,width:"24px",height:"24px",background:"rgba(0, 0, 0, 0.8)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"4px",color:"#fff",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1},children:a?"🔍":"✕"}),!a&&o.jsxs("div",{style:{background:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"8px",padding:"12px",color:"#fff",maxWidth:"320px",backdropFilter:"blur(8px)"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"12px",paddingBottom:"8px",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:[o.jsx("span",{style:{fontSize:"14px"},children:"🔧"}),o.jsxs("span",{style:{fontWeight:600},children:["Bob Debug v",St]})]}),o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px",marginBottom:"12px"},children:[o.jsx(c,{ok:!!t,label:`Partner: ${(t==null?void 0:t.partner_code)||"none"}`}),o.jsx(c,{ok:!!e,label:e?"Session":"No Session"}),o.jsx(c,{ok:r.originAllowed,label:"Origin"})]}),o.jsxs("div",{style:{display:"grid",gap:"6px"},children:[o.jsx(Sr,{label:"Viewport",value:`${r.viewport.width}×${r.viewport.height} (${r.viewport.deviceType})`}),o.jsx(Sr,{label:"Origin",value:r.origin}),o.jsx(Sr,{label:"Bottom Offset",value:`${(t==null?void 0:t.default_bottom_offset)??0}px`}),o.jsx(Sr,{label:"Z-Index Base",value:`${(t==null?void 0:t.default_z_index_base)??50}`}),o.jsx(Sr,{label:"Blur",value:`${(t==null?void 0:t.backdrop_blur_intensity)??8}px`}),o.jsx(Sr,{label:"Overlay",value:`${(((t==null?void 0:t.backdrop_overlay_opacity)??.15)*100).toFixed(0)}%`})]}),(t==null?void 0:t.feature_flags)&&o.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[o.jsx("div",{style:{color:"rgba(255,255,255,0.5)",marginBottom:"4px"},children:"Features:"}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:Object.entries(t.feature_flags).map(([u,d])=>o.jsx(c,{ok:!!d,label:u.replace(/([A-Z])/g," $1").trim()},u))})]}),n.length>0&&o.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[o.jsx("div",{style:{color:"#ef4444",marginBottom:"4px"},children:"⚠️ CSS Conflicts:"}),n.map((u,d)=>o.jsxs("div",{style:{color:"#fca5a5",fontSize:"10px"},children:["• ",u]},d))]}),o.jsx("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",color:"rgba(255,255,255,0.4)",fontSize:"10px"},children:r.timestamp})]})]})},Sr=({label:t,value:e})=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px"},children:[o.jsxs("span",{style:{color:"rgba(255,255,255,0.5)"},children:[t,":"]}),o.jsx("span",{style:{color:"#fff",textAlign:"right",wordBreak:"break-all"},children:e})]}),Ni="https://gjoguxzstsihhxvdgpto.supabase.co",Bi="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imdqb2d1eHpzdHNpaGh4dmRncHRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjM5MzgyODEsImV4cCI6MjA3OTUxNDI4MX0.detu4TKB7RjC6l6CrVaPYoi0Hhz2asDt6zxNx1cdzq8";function zu(t,e){return t.some(r=>{if(r.includes("*")){const s=r.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${s}$`).test(e)}return r===e})}function Ha(t){const[e,r]=g.useState(null),[s,n]=g.useState(!0),[i,a]=g.useState(null),[l,c]=g.useState(!1),[u,d]=g.useState(null),h=g.useCallback(async()=>{if(!t){n(!1),a(new Error("Partner code is required"));return}n(!0),a(null);try{const f=mn(Ni,Bi);console.log(`[BobWidget] Loading partner config for: ${t}`);const{data:p,error:v}=await f.from("bob_partners").select("*").eq("partner_code",t).eq("is_active",!0).maybeSingle();if(v)throw new Error(`Failed to load partner config: ${v.message}`);if(!p)throw new Error(`Partner "${t}" not found or inactive`);const m=p,b=typeof window<"u"?window.location.origin:"",y=zu(m.allowed_origins||[],b);!y&&b&&(console.warn(`[BobWidget] Origin "${b}" not in allowed origins for ${t}`),console.warn("[BobWidget] Allowed origins:",m.allowed_origins));const _=mn(m.bob_supabase_url||Ni,m.bob_supabase_key||Bi,{auth:{storageKey:`bobwidget_${m.partner_code.toLowerCase()}`,persistSession:!1,autoRefreshToken:!1}});console.log("[BobWidget] Partner config loaded:",{partner:m.partner_code,displayName:m.display_name,bottomOffset:m.default_bottom_offset,blurIntensity:m.backdrop_blur_intensity,features:m.feature_flags,originAllowed:y}),r(m),c(y),d(_)}catch(f){const p=f instanceof Error?f:new Error("Unknown error loading partner config");console.error("[BobWidget] Partner config error:",p),a(p)}finally{n(!1)}},[t]);return g.useEffect(()=>{h()},[h]),{config:e,isLoading:s,error:i,isOriginAllowed:l,supabaseClient:u,reload:h}}function Ka(t,e,r){return t!=null&&t.feature_flags?t.feature_flags[e]??r:r}const Hu=()=>o.jsxs("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #0a1628 0%, #0f2137 100%)"},children:[o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[o.jsx("div",{style:{width:"48px",height:"48px",border:"4px solid rgba(0, 102, 204, 0.3)",borderTopColor:"#0066cc",borderRadius:"50%",animation:"spin 1s linear infinite"}}),o.jsx("span",{style:{color:"rgba(255,255,255,0.7)",fontSize:"14px"},children:"Loading Bob..."})]}),o.jsx("style",{children:`
76
76
  @keyframes spin {
77
77
  to { transform: rotate(360deg); }
78
78
  }
package/dist/index.mjs CHANGED
@@ -13,7 +13,7 @@ var Ts = (t, e, r, s) => ({
13
13
  });
14
14
  import * as at from "react";
15
15
  import mr, { useRef as te, useCallback as V, useEffect as he, createContext as Pa, useMemo as Tt, useContext as Ln, useState as H } from "react";
16
- const Gt = "3.2.2", Yu = () => Gt;
16
+ const Gt = "3.2.3", Yu = () => Gt;
17
17
  var ln = { exports: {} }, Xr = {};
18
18
  /**
19
19
  * @license React
@@ -14708,6 +14708,8 @@ const Ni = (t, e) => {
14708
14708
  left: 0,
14709
14709
  right: 0,
14710
14710
  ...ja,
14711
+ // v3.2.2: Opaque dark background to prevent backdrop bleed-through
14712
+ background: "rgba(15, 23, 42, 0.92)",
14711
14713
  borderRadius: "28px 28px 0 0",
14712
14714
  borderBottom: "none",
14713
14715
  transition: "all 0.3s ease-out",
@@ -15252,6 +15254,8 @@ const Ni = (t, e) => {
15252
15254
  WebkitBackfaceVisibility: "hidden",
15253
15255
  isolation: "isolate",
15254
15256
  ...ja,
15257
+ // v3.2.2: Opaque dark background to prevent backdrop bleed-through (orange shelf behind)
15258
+ background: "rgba(15, 23, 42, 0.92)",
15255
15259
  borderRadius: "28px 28px 0 0",
15256
15260
  borderBottom: "none",
15257
15261
  // v3.2.1: Strictly scoped transitions - only height changes, no position animation
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gymmymac/bob-widget",
3
- "version": "3.2.2",
3
+ "version": "3.2.3",
4
4
  "description": "Bob - AI-powered automotive parts assistant widget with multi-tenant support, RAF animations, swipeable interactions, and GA4 analytics",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",