@blockspark/chat-widget 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -123,6 +123,42 @@ function App() {
123
123
  }
124
124
  ```
125
125
 
126
+ ### Using Environment Variables
127
+
128
+ You can configure the backend API URLs for Human Support Mode using environment variables. Create a `.env` file in the project root:
129
+
130
+ ```bash
131
+ # .env file
132
+ REACT_APP_BACKEND_BASE_URL=http://localhost:8012
133
+ REACT_APP_BACKEND_WS_URL=ws://localhost:8012
134
+ ```
135
+
136
+ Or pass them as props:
137
+
138
+ ```tsx
139
+ <ChatWidget
140
+ dfProjectId="your-project-id"
141
+ dfAgentId="your-agent-id"
142
+ serviceAccountKey={serviceAccountKey}
143
+ backendBaseUrl="http://your-backend-url:8012"
144
+ backendWsUrl="ws://your-backend-url:8012"
145
+ />
146
+ ```
147
+
148
+ **Note**: Props take precedence over environment variables.
149
+
150
+ ### Human Support Mode
151
+
152
+ The widget supports automatic handoff from bot to human agents. When Dialogflow returns `{"handoff": true}`, the widget will:
153
+
154
+ 1. Switch from Bot Mode to Human Support Mode
155
+ 2. Create a support chat session
156
+ 3. Connect via WebSocket for real-time messaging
157
+ 4. Load message history
158
+ 5. Route messages to the backend API instead of Dialogflow
159
+
160
+ The widget displays mode indicators and connection status in the chat header.
161
+
126
162
  ### Import Types (TypeScript)
127
163
 
128
164
  ```tsx
@@ -150,6 +186,8 @@ import ChatWidget, { ChatWidgetProps, DialogflowConfig } from '@blockspark/chat-
150
186
  | `inputPlaceholder` | `string` | No | `"Type your message..."` | Input field placeholder |
151
187
  | `emptyStateMessage` | `string` | No | `"Hi! I'm BlockSpark..."` | Empty state message |
152
188
  | `debug` | `boolean` | No | `false` | Enable debug logging |
189
+ | `backendBaseUrl` | `string` | No | `process.env.REACT_APP_BACKEND_BASE_URL` or `"http://localhost:8012"` | Backend REST API base URL for Human Support Mode |
190
+ | `backendWsUrl` | `string` | No | `process.env.REACT_APP_BACKEND_WS_URL` or `"ws://localhost:8012"` | Backend WebSocket URL for Human Support Mode |
153
191
 
154
192
  \* Either `serviceAccountKey` or `accessToken` must be provided.
155
193
 
@@ -34,6 +34,10 @@ export interface ChatWidgetProps {
34
34
  accessToken?: string;
35
35
  /** Language code for Dialogflow */
36
36
  languageCode?: string;
37
+ /** Backend API base URL (default: http://localhost:8012) */
38
+ backendBaseUrl?: string;
39
+ /** WebSocket URL (default: ws://localhost:8012) */
40
+ backendWsUrl?: string;
37
41
  }
38
- export default function ChatWidget({ title, subtitle, welcomeTitle, welcomeMessage, welcomeCta, showWelcomePopup: enableWelcomePopup, welcomePopupDelay, fallbackWelcomeMessage, inputPlaceholder, emptyStateMessage, debug, dfProjectId, dfLocation, dfAgentId, serviceAccountKey, accessToken, languageCode, }: ChatWidgetProps): import("react/jsx-runtime").JSX.Element;
42
+ export default function ChatWidget({ title, subtitle, welcomeTitle, welcomeMessage, welcomeCta, showWelcomePopup: enableWelcomePopup, welcomePopupDelay, fallbackWelcomeMessage, inputPlaceholder, emptyStateMessage, debug, dfProjectId, dfLocation, dfAgentId, serviceAccountKey, accessToken, languageCode, backendBaseUrl, backendWsUrl, }: ChatWidgetProps): import("react/jsx-runtime").JSX.Element;
39
43
  //# sourceMappingURL=ChatWidget.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ChatWidget.d.ts","sourceRoot":"","sources":["../../src/components/ChatWidget.tsx"],"names":[],"mappings":"AAQA,OAAO,0BAA0B,CAAC;AAsBlC,MAAM,WAAW,eAAe;IAC9B,uCAAuC;IACvC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,0CAA0C;IAC1C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0BAA0B;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,4BAA4B;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,6BAA6B;IAC7B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,wCAAwC;IACxC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,yDAAyD;IACzD,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,4CAA4C;IAC5C,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,uCAAuC;IACvC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,iCAAiC;IACjC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,mCAAmC;IACnC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,4BAA4B;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,gDAAgD;IAChD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,0BAA0B;IAC1B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mDAAmD;IACnD,iBAAiB,CAAC,EAAE,GAAG,CAAC;IACxB,sDAAsD;IACtD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mCAAmC;IACnC,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,CAAC,OAAO,UAAU,UAAU,CAAC,EACjC,KAAoC,EACpC,QAA+B,EAC/B,YAAyC,EACzC,cAAyE,EACzE,UAA+C,EAC/C,gBAAgB,EAAE,kBAAyB,EAC3C,iBAAwB,EACxB,sBAAwF,EACxF,gBAAyC,EACzC,iBAAgF,EAChF,KAAa,EACb,WAAW,EACX,UAA0B,EAC1B,SAAS,EACT,iBAAiB,EACjB,WAAW,EACX,YAAmB,GACpB,EAAE,eAAe,2CA6bjB"}
1
+ {"version":3,"file":"ChatWidget.d.ts","sourceRoot":"","sources":["../../src/components/ChatWidget.tsx"],"names":[],"mappings":"AAWA,OAAO,0BAA0B,CAAC;AAsBlC,MAAM,WAAW,eAAe;IAC9B,uCAAuC;IACvC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,0CAA0C;IAC1C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0BAA0B;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,4BAA4B;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,6BAA6B;IAC7B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,wCAAwC;IACxC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,yDAAyD;IACzD,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,4CAA4C;IAC5C,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,uCAAuC;IACvC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,iCAAiC;IACjC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,mCAAmC;IACnC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,4BAA4B;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,gDAAgD;IAChD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,0BAA0B;IAC1B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mDAAmD;IACnD,iBAAiB,CAAC,EAAE,GAAG,CAAC;IACxB,sDAAsD;IACtD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mCAAmC;IACnC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,4DAA4D;IAC5D,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,mDAAmD;IACnD,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,CAAC,OAAO,UAAU,UAAU,CAAC,EACjC,KAAoC,EACpC,QAA+B,EAC/B,YAAyC,EACzC,cAAyE,EACzE,UAA+C,EAC/C,gBAAgB,EAAE,kBAAyB,EAC3C,iBAAwB,EACxB,sBAAwF,EACxF,gBAAyC,EACzC,iBAAgF,EAChF,KAAa,EACb,WAAW,EACX,UAA0B,EAC1B,SAAS,EACT,iBAAiB,EACjB,WAAW,EACX,YAAmB,EACnB,cAAc,EACd,YAAY,GACb,EAAE,eAAe,2CA03CjB"}
@@ -0,0 +1,17 @@
1
+ import type { ChatResponse } from "../services/dialogflowClient";
2
+ export type ChatMode = "BOT" | "HUMAN";
3
+ export interface UseChatModeReturn {
4
+ currentMode: ChatMode;
5
+ switchToHumanMode: () => void;
6
+ switchToBotMode: () => void;
7
+ isHandoffTriggered: (dialogflowResponse: ChatResponse) => boolean;
8
+ chatId: string | null;
9
+ sessionId: string | null;
10
+ setChatId: (id: string | null) => void;
11
+ setSessionId: (id: string | null) => void;
12
+ }
13
+ /**
14
+ * Hook to manage chat mode (BOT or HUMAN)
15
+ */
16
+ export declare function useChatMode(): UseChatModeReturn;
17
+ //# sourceMappingURL=useChatMode.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useChatMode.d.ts","sourceRoot":"","sources":["../../src/hooks/useChatMode.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAEjE,MAAM,MAAM,QAAQ,GAAG,KAAK,GAAG,OAAO,CAAC;AAMvC,MAAM,WAAW,iBAAiB;IAChC,WAAW,EAAE,QAAQ,CAAC;IACtB,iBAAiB,EAAE,MAAM,IAAI,CAAC;IAC9B,eAAe,EAAE,MAAM,IAAI,CAAC;IAC5B,kBAAkB,EAAE,CAAC,kBAAkB,EAAE,YAAY,KAAK,OAAO,CAAC;IAClE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,KAAK,IAAI,CAAC;IACvC,YAAY,EAAE,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,KAAK,IAAI,CAAC;CAC3C;AAED;;GAEG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAmF/C"}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /*! For license information please see index.js.LICENSE.txt */
2
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.BlockSparkChatWidget=t(require("react")):e.BlockSparkChatWidget=t(e.React)}(this,e=>(()=>{"use strict";var t={12(t){t.exports=e},20(e,t,r){var s=r(12),o=Symbol.for("react.element"),n=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,i=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,c={key:!0,ref:!0,__self:!0,__source:!0};function l(e,t,r){var s,n={},l=null,d=null;for(s in void 0!==r&&(l=""+r),void 0!==t.key&&(l=""+t.key),void 0!==t.ref&&(d=t.ref),t)a.call(t,s)&&!c.hasOwnProperty(s)&&(n[s]=t[s]);if(e&&e.defaultProps)for(s in t=e.defaultProps)void 0===n[s]&&(n[s]=t[s]);return{$$typeof:o,type:e,key:l,ref:d,props:n,_owner:i.current}}t.Fragment=n,t.jsx=l,t.jsxs=l},848(e,t,r){e.exports=r(20)}},r={};function s(e){var o=r[e];if(void 0!==o)return o.exports;var n=r[e]={exports:{}};return t[e](n,n.exports,s),n.exports}s.d=(e,t)=>{for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var o={};s.d(o,{default:()=>X});var n=s(848),a=s(12);const i=crypto,c=e=>e instanceof CryptoKey;class l extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}l.code="ERR_JOSE_GENERIC",class extends l{constructor(e,t,r="unspecified",s="unspecified"){super(e,{cause:{claim:r,reason:s,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=s,this.payload=t}}.code="ERR_JWT_CLAIM_VALIDATION_FAILED",class extends l{constructor(e,t,r="unspecified",s="unspecified"){super(e,{cause:{claim:r,reason:s,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=s,this.payload=t}}.code="ERR_JWT_EXPIRED",class extends l{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}.code="ERR_JOSE_ALG_NOT_ALLOWED";class d extends l{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}d.code="ERR_JOSE_NOT_SUPPORTED",class extends l{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}.code="ERR_JWE_DECRYPTION_FAILED",class extends l{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}.code="ERR_JWE_INVALID";class u extends l{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}u.code="ERR_JWS_INVALID";class h extends l{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}h.code="ERR_JWT_INVALID",class extends l{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}.code="ERR_JWK_INVALID",class extends l{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}.code="ERR_JWKS_INVALID",class extends l{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}.code="ERR_JWKS_NO_MATCHING_KEY",Symbol.asyncIterator,class extends l{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",class extends l{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}.code="ERR_JWKS_TIMEOUT",class extends l{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const p=(e,t,r=0)=>{0===r&&(t.unshift(t.length),t.unshift(6));const s=e.indexOf(t[0],r);if(-1===s)return!1;const o=e.subarray(s,s+t.length);return o.length===t.length&&(o.every((e,r)=>e===t[r])||p(e,t,s+1))},m=e=>{switch(!0){case p(e,[42,134,72,206,61,3,1,7]):return"P-256";case p(e,[43,129,4,0,34]):return"P-384";case p(e,[43,129,4,0,35]):return"P-521";case p(e,[43,101,110]):return"X25519";case p(e,[43,101,111]):return"X448";case p(e,[43,101,112]):return"Ed25519";case p(e,[43,101,113]):return"Ed448";default:throw new d("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}};async function y(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return((e,t,r)=>(async(e,t,r,s,o)=>{let n,a;const c=new Uint8Array(atob(r.replace(e,"")).split("").map(e=>e.charCodeAt(0))),l="spki"===t;switch(s){case"PS256":case"PS384":case"PS512":n={name:"RSA-PSS",hash:`SHA-${s.slice(-3)}`},a=l?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":n={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.slice(-3)}`},a=l?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":n={name:"RSA-OAEP",hash:`SHA-${parseInt(s.slice(-3),10)||1}`},a=l?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"},a=l?["verify"]:["sign"];break;case"ES384":n={name:"ECDSA",namedCurve:"P-384"},a=l?["verify"]:["sign"];break;case"ES512":n={name:"ECDSA",namedCurve:"P-521"},a=l?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=m(c);n=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},a=l?[]:["deriveBits"];break}case"Ed25519":n={name:"Ed25519"},a=l?["verify"]:["sign"];break;case"EdDSA":n={name:m(c)},a=l?["verify"]:["sign"];break;default:throw new d('Invalid or unsupported "alg" (Algorithm) value')}return i.subtle.importKey(t,c,n,o?.extractable??!1,a)})(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r))(e,t,r)}const f=new TextEncoder,g=new TextDecoder;const w=e=>(e=>{let t=e;"string"==typeof t&&(t=f.encode(t));const r=[];for(let e=0;e<t.length;e+=32768)r.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(r.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),E=e=>{let t=e;t instanceof Uint8Array&&(t=g.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};function S(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function b(e,t){return e.name===t}function A(e){return parseInt(e.name.slice(4),10)}function _(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!b(e.algorithm,"HMAC"))throw S("HMAC");const r=parseInt(t.slice(2),10);if(A(e.algorithm.hash)!==r)throw S(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!b(e.algorithm,"RSASSA-PKCS1-v1_5"))throw S("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(A(e.algorithm.hash)!==r)throw S(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!b(e.algorithm,"RSA-PSS"))throw S("RSA-PSS");const r=parseInt(t.slice(2),10);if(A(e.algorithm.hash)!==r)throw S(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw S("Ed25519 or Ed448");break;case"Ed25519":if(!b(e.algorithm,"Ed25519"))throw S("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!b(e.algorithm,"ECDSA"))throw S("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw S(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}function v(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const k=(e,...t)=>v("Key must be ",e,...t);function P(e,t,...r){return v(`Key for the ${e} algorithm must be `,t,...r)}const I=e=>!!c(e)||"KeyObject"===e?.[Symbol.toStringTag],R=["CryptoKey"];function C(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}function x(e){return C(e)&&"string"==typeof e.kty}const T=e=>E(e);let D;const j=e=>"KeyObject"===e?.[Symbol.toStringTag],N=async(e,t,r,s,o=!1)=>{let n=e.get(t);if(n?.[s])return n[s];const a=await(async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new d('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new d('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new d('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new d('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),s=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,i.subtle.importKey("jwk",o,...s)})({...r,alg:s});return o&&Object.freeze(t),n?n[s]=a:e.set(t,{[s]:a}),a},H=async(e,t,r)=>{const s=await async function(e,t,r){if(t=await((e,t)=>{if(j(e)){let r=e.export({format:"jwk"});return r.k?T(r.k):(D||(D=new WeakMap),N(D,e,r,t))}return x(e)?e.k?E(e.k):(D||(D=new WeakMap),N(D,e,e,t,!0)):e})(t,e),c(t))return _(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(k(t,...R));return i.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(k(t,...R,"Uint8Array","JSON Web Key"))}(e,t,"sign");((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}})(e,s);const o=await i.subtle.sign(function(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,s.algorithm),s,r);return new Uint8Array(o)},K=e=>e?.[Symbol.toStringTag],O=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function $(e,t,r,s){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,r,s)=>{if(!(t instanceof Uint8Array)){if(s&&x(t)){if(function(e){return x(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&O(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!I(t))throw new TypeError(P(e,t,...R,"Uint8Array",s?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${K(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,r,s,e):((e,t,r,s)=>{if(s&&x(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&O(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&O(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!I(t))throw new TypeError(P(e,t,...R,s?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${K(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${K(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${K(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${K(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${K(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,s,e)}$.bind(void 0,!1);const W=$.bind(void 0,!0);class J{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new u("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new u("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let s=!0;if(function(e,t,r,s,o){if(void 0!==o.crit&&void 0===s?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!s||void 0===s.crit)return new Set;if(!Array.isArray(s.crit)||0===s.crit.length||s.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let n;n=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of s.crit){if(!n.has(t))throw new d(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(n.get(t)&&void 0===s[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(s.crit)}(u,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(s=this._protectedHeader.b64,"boolean"!=typeof s))throw new u('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=r;if("string"!=typeof o||!o)throw new u('JWS "alg" (Algorithm) Header Parameter missing or invalid');W(o,e,"sign");let n,a=this._payload;s&&(a=f.encode(w(a))),n=this._protectedHeader?f.encode(w(JSON.stringify(this._protectedHeader))):f.encode("");const i=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let s=0;for(const t of e)r.set(t,s),s+=t.length;return r}(n,f.encode("."),a),c=await H(o,e,i),l={signature:w(c),payload:""};return s&&(l.payload=g.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=g.decode(n)),l}}class L{constructor(e){this._flattened=new J(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}const M=e=>Math.floor(e.getTime()/1e3),V=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,U=e=>{const t=V.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let s;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(3600*r);break;case"day":case"days":case"d":s=Math.round(86400*r);break;case"week":case"weeks":case"w":s=Math.round(604800*r);break;default:s=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-s:s};function B(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class F{constructor(e={}){if(!C(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:B("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:B("setNotBefore",M(e))}:this._payload={...this._payload,nbf:M(new Date)+U(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:B("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:B("setExpirationTime",M(e))}:this._payload={...this._payload,exp:M(new Date)+U(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:M(new Date)}:e instanceof Date?this._payload={...this._payload,iat:B("setIssuedAt",M(e))}:this._payload="string"==typeof e?{...this._payload,iat:B("setIssuedAt",M(new Date)+U(e))}:{...this._payload,iat:B("setIssuedAt",e)},this}}class G extends F{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new L(f.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new h("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}async function q(e){if(e.accessToken)return e.accessToken;if(!e.serviceAccountKey)throw new Error("Either serviceAccountKey or accessToken must be provided");return await async function(e){const t=Math.floor(Date.now()/1e3);let r=e.private_key;if(!r)throw new Error("Private key is missing from service account key");if(r=r.trim(),r.includes("-----BEGIN")){if(r=r.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r.includes("BEGIN RSA PRIVATE KEY"))throw new Error("Private key is in PKCS#1 format (RSA PRIVATE KEY). Please download a new service account key from Google Cloud Console. The key should be in PKCS#8 format (PRIVATE KEY).");const e=r.match(/-----BEGIN PRIVATE KEY-----\n?([\s\S]*?)\n?-----END PRIVATE KEY-----/);if(e){const t=e[1].replace(/\s/g,"");(!t.includes("\n")||t.length>64)&&(r=`-----BEGIN PRIVATE KEY-----\n${t.match(/.{1,64}/g)?.join("\n")||t}\n-----END PRIVATE KEY-----`)}}else{const e=r.replace(/\s/g,"");r=`-----BEGIN PRIVATE KEY-----\n${e.match(/.{1,64}/g)?.join("\n")||e}\n-----END PRIVATE KEY-----`}try{const s=await y(r,"RS256"),o=await new G({scope:"https://www.googleapis.com/auth/cloud-platform"}).setProtectedHeader({alg:"RS256"}).setIssuedAt(t).setExpirationTime(t+3600).setIssuer(e.client_email).setSubject(e.client_email).setAudience("https://oauth2.googleapis.com/token").sign(s),n=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o})});if(!n.ok){const e=await n.json();throw new Error(e.error_description||"Failed to get access token")}return(await n.json()).access_token}catch(e){if(e.message&&e.message.includes("pkcs8"))throw new Error("Invalid private key format. The service account key must be in PKCS#8 format. Please ensure your service account key JSON file has a properly formatted private_key field. If you downloaded the key from Google Cloud Console, it should already be in the correct format.");throw e}}(e.serviceAccountKey)}function Y(e,t,r,s){return`projects/${e}/locations/${t}/agents/${r}/sessions/${s}`}function z(e){let t=null;for(const r of e)if(r.payload){if(r.payload.richContent){t=r.payload.richContent;break}if(r.payload.fields&&r.payload.fields.richContent){const e=r.payload.fields.richContent;e.listValue&&e.listValue.values?t=e.listValue.values.map(e=>e.listValue&&e.listValue.values?e.listValue.values.map(e=>{if(e.structValue&&e.structValue.fields){const t=e.structValue.fields;if(t.type&&t.options)return{type:t.type.stringValue||t.type,options:t.options.listValue?t.options.listValue.values.map(e=>({text:e.structValue?.fields?.text?.stringValue||"",payload:e.structValue?.fields?.payload?.stringValue||""})):[]}}return e}):e):"object"!=typeof e||e.listValue||(t=e);break}}return t}const X=function({title:e="💬 BlockSpark AI Assistant",subtitle:t="We're here to help",welcomeTitle:r="👋 Welcome to Blockspark",welcomeMessage:s="My name is BlockSpark AI Assistant and I'll guide you.",welcomeCta:o="💬 Click here to start chatting!",showWelcomePopup:i=!0,welcomePopupDelay:c=1500,fallbackWelcomeMessage:l="Hello! I'm BlockSpark AI Assistant. How can I help you today?",inputPlaceholder:d="Type your message...",emptyStateMessage:u="Hi! I'm BlockSpark AI Assistant. How can I help you today?",debug:h=!1,dfProjectId:p,dfLocation:m="us-central1",dfAgentId:y,serviceAccountKey:f,accessToken:g,languageCode:w="en"}){const[E,S]=(0,a.useState)(!1),[b,A]=(0,a.useState)(!1),[_,v]=(0,a.useState)([]),[k,P]=(0,a.useState)(""),[I,R]=(0,a.useState)(!1),[C,x]=(0,a.useState)(null),[T,D]=(0,a.useState)(!1),j=(0,a.useRef)(null),N=()=>{if(p&&y)return{dfProjectId:p,dfLocation:m||"us-central1",dfAgentId:y,serviceAccountKey:f,accessToken:g,languageCode:w||"en"}};(0,a.useEffect)(()=>{if(!i)return;const e=setTimeout(()=>{A(!0)},c);return()=>clearTimeout(e)},[i,c]),(0,a.useEffect)(()=>{j.current?.scrollIntoView({behavior:"smooth"})},[_]);const H=async()=>{if(C)return C;try{D(!0);const e=N();if(!e)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.");const t=await async function(e){try{const t=await q(e),r=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=e.dfLocation.split(" ")[0].trim(),o=`https://${s}-dialogflow.googleapis.com/v3/${Y(e.dfProjectId,s,e.dfAgentId,r)}:detectIntent`,n={queryInput:{text:{text:"hello"},languageCode:e.languageCode||"en"}},a=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.error?.message||`HTTP error! status: ${a.status}`)}const i=await a.json();let c="Hello! I'm BlockSpark AI Assistant. How can I help you today?",l=null;if(i.queryResult?.responseMessages){const e=i.queryResult.responseMessages.filter(e=>e.text).map(e=>e.text.text.join(" "));e.length>0&&(c=e.join(" ")),l=z(i.queryResult.responseMessages)}else i.queryResult?.fulfillmentText&&(c=i.queryResult.fulfillmentText);return{session_id:r,message:c,...l&&{richContent:l}}}catch(e){console.error("Error creating Dialogflow session:",e);const t=e.message||"Failed to create session";if(t.includes("401")||t.includes("Unauthorized"))throw new Error("Authentication failed. Please check your service account key or access token.");if(t.includes("403")||t.includes("Forbidden"))throw new Error("Access forbidden. Please check your Dialogflow API permissions.");if(t.includes("404")||t.includes("Not Found"))throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");throw new Error(t)}}(e);if(x(t.session_id),t.message){h&&(console.log("Session response richContent:",t.richContent),console.log("Full session response:",t));const e={id:`welcome-${Date.now()}`,text:t.message,sender:"bot",timestamp:new Date,richContent:t.richContent};v([e])}return t.session_id}catch(e){console.error("Error creating session:",e),h&&console.error("Full error details:",{message:e.message,stack:e.stack,config:N()});const t={id:`error-${Date.now()}`,text:h?`Error: ${e.message||"Failed to create session. Please check your Dialogflow configuration."}`:l,sender:"bot",timestamp:new Date};return v([t]),null}finally{D(!1)}},K=async(e,t,r=!1)=>{if(!e.trim())return;let s=C;if(!s)try{if(s=await H(),!s){const e={id:Date.now().toString(),text:h?"Failed to create session. Please check the console for details.":"Sorry, I'm having trouble connecting. Please try again.",sender:"bot",timestamp:new Date};return void v(t=>[...t,e])}}catch(e){console.error("Error in createSession:",e);const t={id:Date.now().toString(),text:h?`Connection Error: ${e.message||"Please check your Dialogflow configuration."}`:"Sorry, I'm having trouble connecting. Please check your configuration.",sender:"bot",timestamp:new Date};return void v(e=>[...e,t])}if(!r){const r={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};v(e=>[...e,r])}P(""),R(!0);try{const t=N();if(!t)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.");const r=await async function(e,t,r){try{const s=await q(r),o=r.dfLocation.split(" ")[0].trim(),n=`https://${o}-dialogflow.googleapis.com/v3/${Y(r.dfProjectId,o,r.dfAgentId,t)}:detectIntent`,a={queryInput:{text:{text:e.trim()},languageCode:r.languageCode||"en"}},i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok){const e=await i.text();let t={};try{t=JSON.parse(e)}catch{t={message:e||`HTTP ${i.status}`}}const r=t.error?.message||t.message||`HTTP error! status: ${i.status}`;throw console.error("Dialogflow API Error (sendMessage):",{status:i.status,statusText:i.statusText,error:t,endpoint:n}),new Error(r)}const c=await i.json();let l="I'm sorry, I didn't understand that. Could you please rephrase?",d=null;if(c.queryResult?.responseMessages){const e=c.queryResult.responseMessages.filter(e=>e.text).map(e=>e.text.text.join(" "));e.length>0&&(l=e.join(" ")),d=z(c.queryResult.responseMessages)}else c.queryResult?.fulfillmentText&&(l=c.queryResult.fulfillmentText);return{response:l,session_id:t,source:"dialogflow",timestamp:(new Date).toISOString(),...d&&{richContent:d}}}catch(e){console.error("Error sending message to Dialogflow:",e);const t=e.message||"Failed to send message";if(t.includes("401")||t.includes("Unauthorized"))throw new Error("Authentication failed. Please check your service account key or access token.");if(t.includes("403")||t.includes("Forbidden"))throw new Error("Access forbidden. Please check your Dialogflow API permissions.");if(t.includes("404")||t.includes("Not Found"))throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");if(t.includes("CORS"))throw new Error("CORS error. Dialogflow API may not allow browser requests. Consider using a backend proxy.");throw new Error(t)}}(e.trim(),s,t);h&&(console.log("Chat response richContent:",r.richContent),console.log("Full chat response:",r));const o={id:(Date.now()+1).toString(),text:r.response,sender:"bot",timestamp:new Date(r.timestamp||Date.now()),richContent:r.richContent};v(e=>[...e,o])}catch(e){console.error("Error sending message:",e),h&&console.error("Full error details:",{message:e.message,stack:e.stack,sessionId:s,config:N()});const t={id:(Date.now()+1).toString(),text:h?`Error: ${e.message||"Failed to send message. Please check your Dialogflow configuration."}`:e.message?.includes("Failed to fetch")||e.message?.includes("CORS")?"Unable to connect to Dialogflow. Please check your configuration and network.":"Sorry, I'm having trouble processing your message. Please try again.",sender:"bot",timestamp:new Date};v(e=>[...e,t])}finally{R(!1)}},O=async()=>{S(!0),A(!1),C||await H()};return(0,n.jsxs)(n.Fragment,{children:[b&&!E&&(0,n.jsxs)("div",{className:"custom-welcome-popup",onClick:O,children:[(0,n.jsxs)("div",{className:"custom-welcome-header",children:[(0,n.jsx)("div",{className:"custom-welcome-title",children:r}),(0,n.jsx)("button",{className:"custom-close-popup",onClick:e=>{e.stopPropagation(),A(!1)},children:"×"})]}),(0,n.jsx)("div",{className:"custom-welcome-message",children:s}),(0,n.jsx)("div",{className:"custom-welcome-cta",children:o})]}),!E&&(0,n.jsx)("button",{className:"custom-chat-toggle-btn",onClick:O,"aria-label":"Open chat",children:(0,n.jsx)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),E&&(0,n.jsxs)("div",{className:"custom-chat-window",children:[(0,n.jsxs)("div",{className:"custom-chat-header",children:[(0,n.jsxs)("div",{className:"custom-chat-header-content",children:[(0,n.jsx)("div",{className:"custom-chat-title",children:e}),(0,n.jsx)("div",{className:"custom-chat-subtitle",children:t})]}),(0,n.jsx)("button",{className:"custom-chat-close-btn",onClick:()=>{S(!1)},"aria-label":"Close chat",children:"×"})]}),(0,n.jsxs)("div",{className:"custom-chat-messages",children:[T&&0===_.length&&(0,n.jsxs)("div",{className:"custom-chat-empty",children:[(0,n.jsxs)("div",{className:"custom-typing-indicator",children:[(0,n.jsx)("span",{}),(0,n.jsx)("span",{}),(0,n.jsx)("span",{})]}),(0,n.jsx)("p",{children:"Initializing chat..."})]}),!T&&0===_.length&&(0,n.jsxs)("div",{className:"custom-chat-empty",children:[(0,n.jsx)("div",{className:"custom-chat-empty-icon",children:"👋"}),(0,n.jsx)("p",{children:u})]}),_.map(e=>(0,n.jsxs)("div",{className:`custom-message custom-message-${e.sender}`,children:[(0,n.jsx)("div",{className:"custom-message-content",children:e.text}),(h&&e.richContent&&(console.log("Rendering message with richContent:",e.richContent),console.log("richContent type:",typeof e.richContent),console.log("richContent is array:",Array.isArray(e.richContent)),console.log("richContent length:",e.richContent?.length)),e.richContent&&Array.isArray(e.richContent)&&e.richContent.length>0?(0,n.jsx)("div",{className:"custom-chips-container",children:e.richContent.map((e,t)=>{if(h&&console.log(`Processing contentGroup ${t}:`,e),!Array.isArray(e)){const r=e;return r&&"chips"===r.type&&r.options?(0,n.jsx)("div",{className:"custom-chips-group",children:r.options.map((e,t)=>(0,n.jsx)("button",{className:"custom-chip-button",onClick:()=>{const t={id:Date.now().toString(),text:e.text,sender:"user",timestamp:new Date};v(e=>[...e,t]),K(e.text,e.text,!0)},type:"button",children:e.text},t))},t):null}return e.map((e,r)=>(h&&console.log(`Processing content ${t}-${r}:`,e),e&&"chips"===e.type&&e.options?(0,n.jsx)("div",{className:"custom-chips-group",children:e.options.map((e,t)=>(0,n.jsx)("button",{className:"custom-chip-button",onClick:()=>{const t={id:Date.now().toString(),text:e.text,sender:"user",timestamp:new Date};v(e=>[...e,t]),K(e.text,e.text,!0)},type:"button",children:e.text},t))},`${t}-${r}`):null))})}):null),(0,n.jsx)("div",{className:"custom-message-time",children:e.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]},e.id)),I&&(0,n.jsx)("div",{className:"custom-message custom-message-bot",children:(0,n.jsxs)("div",{className:"custom-typing-indicator",children:[(0,n.jsx)("span",{}),(0,n.jsx)("span",{}),(0,n.jsx)("span",{})]})}),(0,n.jsx)("div",{ref:j})]}),(0,n.jsxs)("form",{className:"custom-chat-input-form",onSubmit:e=>{e.preventDefault(),K(k)},children:[(0,n.jsx)("input",{type:"text",className:"custom-chat-input",value:k,onChange:e=>P(e.target.value),placeholder:d,disabled:I||T}),(0,n.jsx)("button",{type:"submit",className:"custom-chat-send-btn",disabled:!k.trim()||I||T,children:(0,n.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),(0,n.jsx)("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]})]})]})};return o.default})());
2
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.BlockSparkChatWidget=t(require("react")):e.BlockSparkChatWidget=t(e.React)}(this,e=>(()=>{"use strict";var t={12(t){t.exports=e},20(e,t,s){var n=s(12),r=Symbol.for("react.element"),o=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,i=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,c={key:!0,ref:!0,__self:!0,__source:!0};function l(e,t,s){var n,o={},l=null,d=null;for(n in void 0!==s&&(l=""+s),void 0!==t.key&&(l=""+t.key),void 0!==t.ref&&(d=t.ref),t)a.call(t,n)&&!c.hasOwnProperty(n)&&(o[n]=t[n]);if(e&&e.defaultProps)for(n in t=e.defaultProps)void 0===o[n]&&(o[n]=t[n]);return{$$typeof:r,type:e,key:l,ref:d,props:o,_owner:i.current}}t.Fragment=o,t.jsx=l,t.jsxs=l},848(e,t,s){e.exports=s(20)}},s={};function n(e){var r=s[e];if(void 0!==r)return r.exports;var o=s[e]={exports:{}};return t[e](o,o.exports,n),o.exports}n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var r={};n.d(r,{default:()=>Xt});var o=n(848),a=n(12);const i="numeric",c="ascii",l="alpha",d="asciinumeric",u="alphanumeric",h="domain",m="emoji",p="scheme",g="slashscheme",f="whitespace";function y(e,t){return e in t||(t[e]=[]),t[e]}function w(e,t,s){t[i]&&(t[d]=!0,t[u]=!0),t[c]&&(t[d]=!0,t[l]=!0),t[d]&&(t[u]=!0),t[l]&&(t[u]=!0),t[u]&&(t[h]=!0),t[m]&&(t[h]=!0);for(const n in t){const t=y(n,s);t.indexOf(e)<0&&t.push(e)}}function S(e=null){this.j={},this.jr=[],this.jd=null,this.t=e}S.groups={},S.prototype={accepts(){return!!this.t},go(e){const t=this,s=t.j[e];if(s)return s;for(let s=0;s<t.jr.length;s++){const n=t.jr[s][0],r=t.jr[s][1];if(r&&n.test(e))return r}return t.jd},has(e,t=!1){return t?e in this.j:!!this.go(e)},ta(e,t,s,n){for(let r=0;r<e.length;r++)this.tt(e[r],t,s,n)},tr(e,t,s,n){let r;return n=n||S.groups,t&&t.j?r=t:(r=new S(t),s&&n&&w(t,s,n)),this.jr.push([e,r]),r},ts(e,t,s,n){let r=this;const o=e.length;if(!o)return r;for(let t=0;t<o-1;t++)r=r.tt(e[t]);return r.tt(e[o-1],t,s,n)},tt(e,t,s,n){n=n||S.groups;const r=this;if(t&&t.j)return r.j[e]=t,t;const o=t;let a,i=r.go(e);if(i?(a=new S,Object.assign(a.j,i.j),a.jr.push.apply(a.jr,i.jr),a.jd=i.jd,a.t=i.t):a=new S,o){if(n)if(a.t&&"string"==typeof a.t){const e=Object.assign(function(e,t){const s={};for(const n in t)t[n].indexOf(e)>=0&&(s[n]=!0);return s}(a.t,n),s);w(o,e,n)}else s&&w(o,s,n);a.t=o}return r.j[e]=a,a}};const E=(e,t,s,n,r)=>e.ta(t,s,n,r),b=(e,t,s,n,r)=>e.tr(t,s,n,r),k=(e,t,s,n,r)=>e.ts(t,s,n,r),A=(e,t,s,n,r)=>e.tt(t,s,n,r),_="WORD",v="UWORD",I="ASCIINUMERICAL",C="ALPHANUMERICAL",R="LOCALHOST",T="TLD",x="UTLD",P="SCHEME",N="SLASH_SCHEME",D="NUM",j="WS",H="NL",O="OPENBRACE",L="CLOSEBRACE",W="OPENBRACKET",$="CLOSEBRACKET",M="OPENPAREN",K="CLOSEPAREN",U="OPENANGLEBRACKET",J="CLOSEANGLEBRACKET",F="FULLWIDTHLEFTPAREN",B="FULLWIDTHRIGHTPAREN",V="LEFTCORNERBRACKET",z="RIGHTCORNERBRACKET",q="LEFTWHITECORNERBRACKET",G="RIGHTWHITECORNERBRACKET",Y="FULLWIDTHLESSTHAN",X="FULLWIDTHGREATERTHAN",Q="AMPERSAND",Z="APOSTROPHE",ee="ASTERISK",te="AT",se="BACKSLASH",ne="BACKTICK",re="CARET",oe="COLON",ae="COMMA",ie="DOLLAR",ce="DOT",le="EQUALS",de="EXCLAMATION",ue="HYPHEN",he="PERCENT",me="PIPE",pe="PLUS",ge="POUND",fe="QUERY",ye="QUOTE",we="FULLWIDTHMIDDLEDOT",Se="SEMI",Ee="SLASH",be="TILDE",ke="UNDERSCORE",Ae="EMOJI",_e="SYM";var ve=Object.freeze({__proto__:null,ALPHANUMERICAL:C,AMPERSAND:Q,APOSTROPHE:Z,ASCIINUMERICAL:I,ASTERISK:ee,AT:te,BACKSLASH:se,BACKTICK:ne,CARET:re,CLOSEANGLEBRACKET:J,CLOSEBRACE:L,CLOSEBRACKET:$,CLOSEPAREN:K,COLON:oe,COMMA:ae,DOLLAR:ie,DOT:ce,EMOJI:Ae,EQUALS:le,EXCLAMATION:de,FULLWIDTHGREATERTHAN:X,FULLWIDTHLEFTPAREN:F,FULLWIDTHLESSTHAN:Y,FULLWIDTHMIDDLEDOT:we,FULLWIDTHRIGHTPAREN:B,HYPHEN:ue,LEFTCORNERBRACKET:V,LEFTWHITECORNERBRACKET:q,LOCALHOST:R,NL:H,NUM:D,OPENANGLEBRACKET:U,OPENBRACE:O,OPENBRACKET:W,OPENPAREN:M,PERCENT:he,PIPE:me,PLUS:pe,POUND:ge,QUERY:fe,QUOTE:ye,RIGHTCORNERBRACKET:z,RIGHTWHITECORNERBRACKET:G,SCHEME:P,SEMI:Se,SLASH:Ee,SLASH_SCHEME:N,SYM:_e,TILDE:be,TLD:T,UNDERSCORE:ke,UTLD:x,UWORD:v,WORD:_,WS:j});const Ie=/[a-z]/,Ce=/\p{L}/u,Re=/\p{Emoji}/u,Te=/\d/,xe=/\s/;let Pe=null,Ne=null;function De(e,t){const s=function(e){const t=[],s=e.length;let n=0;for(;n<s;){let r,o=e.charCodeAt(n),a=o<55296||o>56319||n+1===s||(r=e.charCodeAt(n+1))<56320||r>57343?e[n]:e.slice(n,n+2);t.push(a),n+=a.length}return t}(t.replace(/[A-Z]/g,e=>e.toLowerCase())),n=s.length,r=[];let o=0,a=0;for(;a<n;){let i=e,c=null,l=0,d=null,u=-1,h=-1;for(;a<n&&(c=i.go(s[a]));)i=c,i.accepts()?(u=0,h=0,d=i):u>=0&&(u+=s[a].length,h++),l+=s[a].length,o+=s[a].length,a++;o-=u,a-=h,l-=u,r.push({t:d.t,v:t.slice(o-l,o),s:o-l,e:o})}return r}function je(e,t,s,n,r){let o;const a=t.length;for(let s=0;s<a-1;s++){const a=t[s];e.j[a]?o=e.j[a]:(o=new S(n),o.jr=r.slice(),e.j[a]=o),e=o}return o=new S(s),o.jr=r.slice(),e.j[t[a-1]]=o,o}function He(e){const t=[],s=[];let n=0;for(;n<e.length;){let r=0;for(;"0123456789".indexOf(e[n+r])>=0;)r++;if(r>0){t.push(s.join(""));for(let t=parseInt(e.substring(n,n+r),10);t>0;t--)s.pop();n+=r}else s.push(e[n]),n++}return t}const Oe={defaultProtocol:"http",events:null,format:We,formatHref:We,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Le(e,t=null){let s=Object.assign({},Oe);e&&(s=Object.assign(s,e instanceof Le?e.o:e));const n=s.ignoreTags,r=[];for(let e=0;e<n.length;e++)r.push(n[e].toUpperCase());this.o=s,t&&(this.defaultRender=t),this.ignoreTags=r}function We(e){return e}function $e(e,t){this.t="token",this.v=e,this.tk=t}function Me(e,t){class s extends $e{constructor(t,s){super(t,s),this.t=e}}for(const e in t)s.prototype[e]=t[e];return s.t=e,s}Le.prototype={o:Oe,ignoreTags:[],defaultRender:e=>e,check(e){return this.get("validate",e.toString(),e)},get(e,t,s){const n=null!=t;let r=this.o[e];return r?("object"==typeof r?(r=s.t in r?r[s.t]:Oe[e],"function"==typeof r&&n&&(r=r(t,s))):"function"==typeof r&&n&&(r=r(t,s.t,s)),r):r},getObj(e,t,s){let n=this.o[e];return"function"==typeof n&&null!=t&&(n=n(t,s.t,s)),n},render(e){const t=e.render(this);return(this.get("render",null,e)||this.defaultRender)(t,e.t,e)}},$e.prototype={isLink:!1,toString(){return this.v},toHref(e){return this.toString()},toFormattedString(e){const t=this.toString(),s=e.get("truncate",t,this),n=e.get("format",t,this);return s&&n.length>s?n.substring(0,s)+"…":n},toFormattedHref(e){return e.get("formatHref",this.toHref(e.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(e=Oe.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(e),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(e){return{type:this.t,value:this.toFormattedString(e),isLink:this.isLink,href:this.toFormattedHref(e),start:this.startIndex(),end:this.endIndex()}},validate(e){return e.get("validate",this.toString(),this)},render(e){const t=this,s=this.toHref(e.get("defaultProtocol")),n=e.get("formatHref",s,this),r=e.get("tagName",s,t),o=this.toFormattedString(e),a={},i=e.get("className",s,t),c=e.get("target",s,t),l=e.get("rel",s,t),d=e.getObj("attributes",s,t),u=e.getObj("events",s,t);return a.href=n,i&&(a.class=i),c&&(a.target=c),l&&(a.rel=l),d&&Object.assign(a,d),{tagName:r,attributes:a,content:o,eventListeners:u}}};const Ke=Me("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),Ue=Me("text"),Je=Me("nl"),Fe=Me("url",{isLink:!0,toHref(e=Oe.defaultProtocol){return this.hasProtocol()?this.v:`${e}://${this.v}`},hasProtocol(){const e=this.tk;return e.length>=2&&e[0].t!==R&&e[1].t===oe}}),Be=e=>new S(e);function Ve(e,t,s){const n=s[0].s,r=s[s.length-1].e;return new e(t.slice(n,r),s)}"undefined"!=typeof console&&console&&console.warn;const ze={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function qe(e){return ze.initialized||function(){ze.scanner=function(e=[]){const t={};S.groups=t;const s=new S;null==Pe&&(Pe=He("aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2")),null==Ne&&(Ne=He("ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2")),A(s,"'",Z),A(s,"{",O),A(s,"}",L),A(s,"[",W),A(s,"]",$),A(s,"(",M),A(s,")",K),A(s,"<",U),A(s,">",J),A(s,"(",F),A(s,")",B),A(s,"「",V),A(s,"」",z),A(s,"『",q),A(s,"』",G),A(s,"<",Y),A(s,">",X),A(s,"&",Q),A(s,"*",ee),A(s,"@",te),A(s,"`",ne),A(s,"^",re),A(s,":",oe),A(s,",",ae),A(s,"$",ie),A(s,".",ce),A(s,"=",le),A(s,"!",de),A(s,"-",ue),A(s,"%",he),A(s,"|",me),A(s,"+",pe),A(s,"#",ge),A(s,"?",fe),A(s,'"',ye),A(s,"/",Ee),A(s,";",Se),A(s,"~",be),A(s,"_",ke),A(s,"\\",se),A(s,"・",we);const n=b(s,Te,D,{[i]:!0});b(n,Te,n);const r=b(n,Ie,I,{[d]:!0}),o=b(n,Ce,C,{[u]:!0}),a=b(s,Ie,_,{[c]:!0});b(a,Te,r),b(a,Ie,a),b(r,Te,r),b(r,Ie,r);const y=b(s,Ce,v,{[l]:!0});b(y,Ie),b(y,Te,o),b(y,Ce,y),b(o,Te,o),b(o,Ie),b(o,Ce,o);const E=A(s,"\n",H,{[f]:!0}),De=A(s,"\r",j,{[f]:!0}),Oe=b(s,xe,j,{[f]:!0});A(s,"",Oe),A(De,"\n",E),A(De,"",Oe),b(De,xe,Oe),A(Oe,"\r"),A(Oe,"\n"),b(Oe,xe,Oe),A(Oe,"",Oe);const Le=b(s,Re,Ae,{[m]:!0});A(Le,"#"),b(Le,Re,Le),A(Le,"️",Le);const We=A(Le,"‍");A(We,"#"),b(We,Re,Le);const $e=[[Ie,a],[Te,r]],Me=[[Ie,null],[Ce,y],[Te,o]];for(let e=0;e<Pe.length;e++)je(s,Pe[e],T,_,$e);for(let e=0;e<Ne.length;e++)je(s,Ne[e],x,v,Me);w(T,{tld:!0,ascii:!0},t),w(x,{utld:!0,alpha:!0},t),je(s,"file",P,_,$e),je(s,"mailto",P,_,$e),je(s,"http",N,_,$e),je(s,"https",N,_,$e),je(s,"ftp",N,_,$e),je(s,"ftps",N,_,$e),w(P,{scheme:!0,ascii:!0},t),w(N,{slashscheme:!0,ascii:!0},t),e=e.sort((e,t)=>e[0]>t[0]?1:-1);for(let t=0;t<e.length;t++){const n=e[t][0],r=e[t][1]?{[p]:!0}:{[g]:!0};n.indexOf("-")>=0?r[h]=!0:Ie.test(n)?Te.test(n)?r[d]=!0:r[c]=!0:r[i]=!0,k(s,n,n,r)}return k(s,"localhost",R,{ascii:!0}),s.jd=new S(_e),{start:s,tokens:Object.assign({groups:t},ve)}}(ze.customSchemes);for(let e=0;e<ze.tokenQueue.length;e++)ze.tokenQueue[e][1]({scanner:ze.scanner});ze.parser=function({groups:e}){const t=e.domain.concat([Q,ee,te,se,ne,re,ie,le,ue,D,he,me,pe,ge,Ee,_e,be,ke]),s=[Z,oe,ae,ce,de,he,fe,ye,Se,U,J,O,L,$,W,M,K,F,B,V,z,q,G,Y,X],n=[Q,Z,ee,se,ne,re,ie,le,ue,O,L,he,me,pe,ge,fe,Ee,_e,be,ke],r=Be(),o=A(r,be);E(o,n,o),E(o,e.domain,o);const a=Be(),i=Be(),c=Be();E(r,e.domain,a),E(r,e.scheme,i),E(r,e.slashscheme,c),E(a,n,o),E(a,e.domain,a);const l=A(a,te);A(o,te,l),A(i,te,l),A(c,te,l);const d=A(o,ce);E(d,n,o),E(d,e.domain,o);const u=Be();E(l,e.domain,u),E(u,e.domain,u);const h=A(u,ce);E(h,e.domain,u);const m=Be(Ke);E(h,e.tld,m),E(h,e.utld,m),A(l,R,m);const p=A(u,ue);A(p,ue,p),E(p,e.domain,u),E(m,e.domain,u),A(m,ce,h),A(m,ue,p);const g=A(m,oe);E(g,e.numeric,Ke);const f=A(a,ue),y=A(a,ce);A(f,ue,f),E(f,e.domain,a),E(y,n,o),E(y,e.domain,a);const w=Be(Fe);E(y,e.tld,w),E(y,e.utld,w),E(w,e.domain,a),E(w,n,o),A(w,ce,y),A(w,ue,f),A(w,te,l);const S=A(w,oe),b=Be(Fe);E(S,e.numeric,b);const k=Be(Fe),_=Be();E(k,t,k),E(k,s,_),E(_,t,k),E(_,s,_),A(w,Ee,k),A(b,Ee,k);const v=A(i,oe),I=A(c,oe),C=A(I,Ee),T=A(C,Ee);E(i,e.domain,a),A(i,ce,y),A(i,ue,f),E(c,e.domain,a),A(c,ce,y),A(c,ue,f),E(v,e.domain,k),A(v,Ee,k),A(v,fe,k),E(T,e.domain,k),E(T,t,k),A(T,Ee,k);const x=[[O,L],[W,$],[M,K],[U,J],[F,B],[V,z],[q,G],[Y,X]];for(let e=0;e<x.length;e++){const[n,r]=x[e],o=A(k,n);A(_,n,o),A(o,r,k);const a=Be(Fe);E(o,t,a);const i=Be();E(o,s),E(a,t,a),E(a,s,i),E(i,t,a),E(i,s,i),A(a,r,k),A(i,r,k)}return A(r,R,w),A(r,H,Je),{start:r,tokens:ve}}(ze.scanner.tokens);for(let e=0;e<ze.pluginQueue.length;e++)ze.pluginQueue[e][1]({scanner:ze.scanner,parser:ze.parser});ze.initialized=!0}(),function(e,t,s){let n=s.length,r=0,o=[],a=[];for(;r<n;){let i=e,c=null,l=null,d=0,u=null,h=-1;for(;r<n&&!(c=i.go(s[r].t));)a.push(s[r++]);for(;r<n&&(l=c||i.go(s[r].t));)c=null,i=l,i.accepts()?(h=0,u=i):h>=0&&h++,r++,d++;if(h<0)r-=d,r<n&&(a.push(s[r]),r++);else{a.length>0&&(o.push(Ve(Ue,t,a)),a=[]),r-=h,d-=h;const e=u.t,n=s.slice(r-d,r);o.push(Ve(e,t,n))}}return a.length>0&&o.push(Ve(Ue,t,a)),o}(ze.parser.start,e,De(ze.scanner.start,e))}function Ge(e,t,s){if(0===a.Children.count(e.props.children))return e;const n=[];a.Children.forEach(e.props.children,e=>{"string"==typeof e?n.push.apply(n,function(e,t,s){const n=qe(e),r=[];for(let e=0;e<n.length;e++){const o=n[e];if("nl"===o.t&&t.get("nl2br")){const e="__linkify-el-"+s.elementId++;r.push(a.createElement("br",{key:e}))}else if(o.isLink&&t.check(o)){let e=t.render(o);if(!("key"in e.props)){const t="__linkify-el-"+s.elementId++,n=Object.assign({key:t},e.props);e=a.cloneElement(e,n)}r.push(e)}else r.push(o.toString())}return r}(e,t,s)):a.isValidElement(e)?"string"==typeof e.type&&t.ignoreTags.indexOf(e.type.toUpperCase())>=0?n.push(e):n.push(Ge(e,t,s)):n.push(e)});const r="__linkify-el-"+s.elementId++,o=Object.assign({key:r},e.props);return a.cloneElement(e,o,n)}qe.scan=De;const Ye=e=>{let t=0;const s={key:"__linkify-wrapper"};for(const t in e)"options"!==t&&"as"!==t&&"tagName"!==t&&"children"!==t&&(s[t]=e[t]);const n=new Le(e.options,({tagName:e,attributes:s,content:n})=>(s.key="__linkify-lnk-"+t++,s.class&&(s.className=s.class,delete s.class),a.createElement(e,s,n))),r=e.as||e.tagName||a.Fragment||"span",o=e.children;return Ge(a.createElement(r,s,o),n,{elementId:0})},Xe=crypto,Qe=e=>e instanceof CryptoKey;class Ze extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}Ze.code="ERR_JOSE_GENERIC",class extends Ze{constructor(e,t,s="unspecified",n="unspecified"){super(e,{cause:{claim:s,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=s,this.reason=n,this.payload=t}}.code="ERR_JWT_CLAIM_VALIDATION_FAILED",class extends Ze{constructor(e,t,s="unspecified",n="unspecified"){super(e,{cause:{claim:s,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=s,this.reason=n,this.payload=t}}.code="ERR_JWT_EXPIRED",class extends Ze{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}.code="ERR_JOSE_ALG_NOT_ALLOWED";class et extends Ze{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}et.code="ERR_JOSE_NOT_SUPPORTED",class extends Ze{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}.code="ERR_JWE_DECRYPTION_FAILED",class extends Ze{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}.code="ERR_JWE_INVALID";class tt extends Ze{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}tt.code="ERR_JWS_INVALID";class st extends Ze{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}st.code="ERR_JWT_INVALID",class extends Ze{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}.code="ERR_JWK_INVALID",class extends Ze{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}.code="ERR_JWKS_INVALID",class extends Ze{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}.code="ERR_JWKS_NO_MATCHING_KEY",Symbol.asyncIterator,class extends Ze{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",class extends Ze{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}.code="ERR_JWKS_TIMEOUT",class extends Ze{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const nt=(e,t,s=0)=>{0===s&&(t.unshift(t.length),t.unshift(6));const n=e.indexOf(t[0],s);if(-1===n)return!1;const r=e.subarray(n,n+t.length);return r.length===t.length&&(r.every((e,s)=>e===t[s])||nt(e,t,n+1))},rt=e=>{switch(!0){case nt(e,[42,134,72,206,61,3,1,7]):return"P-256";case nt(e,[43,129,4,0,34]):return"P-384";case nt(e,[43,129,4,0,35]):return"P-521";case nt(e,[43,101,110]):return"X25519";case nt(e,[43,101,111]):return"X448";case nt(e,[43,101,112]):return"Ed25519";case nt(e,[43,101,113]):return"Ed448";default:throw new et("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}};async function ot(e,t,s){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return((e,t,s)=>(async(e,t,s,n,r)=>{let o,a;const i=new Uint8Array(atob(s.replace(e,"")).split("").map(e=>e.charCodeAt(0))),c="spki"===t;switch(n){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},a=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},a=c?["verify"]:["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},a=c?["verify"]:["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},a=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=rt(i);o=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},a=c?[]:["deriveBits"];break}case"Ed25519":o={name:"Ed25519"},a=c?["verify"]:["sign"];break;case"EdDSA":o={name:rt(i)},a=c?["verify"]:["sign"];break;default:throw new et('Invalid or unsupported "alg" (Algorithm) value')}return Xe.subtle.importKey(t,i,o,r?.extractable??!1,a)})(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,s))(e,t,s)}const at=new TextEncoder,it=new TextDecoder;const ct=e=>(e=>{let t=e;"string"==typeof t&&(t=at.encode(t));const s=[];for(let e=0;e<t.length;e+=32768)s.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(s.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),lt=e=>{let t=e;t instanceof Uint8Array&&(t=it.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};function dt(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ut(e,t){return e.name===t}function ht(e){return parseInt(e.name.slice(4),10)}function mt(e,t,...s){switch(t){case"HS256":case"HS384":case"HS512":{if(!ut(e.algorithm,"HMAC"))throw dt("HMAC");const s=parseInt(t.slice(2),10);if(ht(e.algorithm.hash)!==s)throw dt(`SHA-${s}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ut(e.algorithm,"RSASSA-PKCS1-v1_5"))throw dt("RSASSA-PKCS1-v1_5");const s=parseInt(t.slice(2),10);if(ht(e.algorithm.hash)!==s)throw dt(`SHA-${s}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ut(e.algorithm,"RSA-PSS"))throw dt("RSA-PSS");const s=parseInt(t.slice(2),10);if(ht(e.algorithm.hash)!==s)throw dt(`SHA-${s}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw dt("Ed25519 or Ed448");break;case"Ed25519":if(!ut(e.algorithm,"Ed25519"))throw dt("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!ut(e.algorithm,"ECDSA"))throw dt("ECDSA");const s=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==s)throw dt(s,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const s=t.pop();e+=`one of ${t.join(", ")}, or ${s}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,s)}function pt(e,t,...s){if((s=s.filter(Boolean)).length>2){const t=s.pop();e+=`one of type ${s.join(", ")}, or ${t}.`}else 2===s.length?e+=`one of type ${s[0]} or ${s[1]}.`:e+=`of type ${s[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const gt=(e,...t)=>pt("Key must be ",e,...t);function ft(e,t,...s){return pt(`Key for the ${e} algorithm must be `,t,...s)}const yt=e=>!!Qe(e)||"KeyObject"===e?.[Symbol.toStringTag],wt=["CryptoKey"];function St(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let s=e;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return Object.getPrototypeOf(e)===s}function Et(e){return St(e)&&"string"==typeof e.kty}const bt=e=>lt(e);let kt;const At=e=>"KeyObject"===e?.[Symbol.toStringTag],_t=async(e,t,s,n,r=!1)=>{let o=e.get(t);if(o?.[n])return o[n];const a=await(async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:s}=function(e){let t,s;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},s=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},s=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},s=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new et('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},s=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},s=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},s=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},s=e.d?["deriveBits"]:[];break;default:throw new et('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},s=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},s=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},s=e.d?["deriveBits"]:[];break;default:throw new et('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new et('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:s}}(e),n=[t,e.ext??!1,e.key_ops??s],r={...e};return delete r.alg,delete r.use,Xe.subtle.importKey("jwk",r,...n)})({...s,alg:n});return r&&Object.freeze(t),o?o[n]=a:e.set(t,{[n]:a}),a},vt=async(e,t,s)=>{const n=await async function(e,t,s){if(t=await((e,t)=>{if(At(e)){let s=e.export({format:"jwk"});return s.k?bt(s.k):(kt||(kt=new WeakMap),_t(kt,e,s,t))}return Et(e)?e.k?lt(e.k):(kt||(kt=new WeakMap),_t(kt,e,e,t,!0)):e})(t,e),Qe(t))return mt(t,e,s),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(gt(t,...wt));return Xe.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[s])}throw new TypeError(gt(t,...wt,"Uint8Array","JSON Web Key"))}(e,t,"sign");((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:s}=t.algorithm;if("number"!=typeof s||s<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}})(e,n);const r=await Xe.subtle.sign(function(e,t){const s=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:s,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:s,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:s,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:s,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new et(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,n.algorithm),n,s);return new Uint8Array(r)},It=e=>e?.[Symbol.toStringTag],Ct=(e,t,s)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(s))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${s}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function Rt(e,t,s,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,s,n)=>{if(!(t instanceof Uint8Array)){if(n&&Et(t)){if(function(e){return Et(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&Ct(e,t,s))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!yt(t))throw new TypeError(ft(e,t,...wt,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${It(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,s,n,e):((e,t,s,n)=>{if(n&&Et(t))switch(s){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&Ct(e,t,s))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&Ct(e,t,s))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!yt(t))throw new TypeError(ft(e,t,...wt,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${It(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===s&&"public"===t.type)throw new TypeError(`${It(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===s&&"public"===t.type)throw new TypeError(`${It(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===s&&"private"===t.type)throw new TypeError(`${It(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===s&&"private"===t.type)throw new TypeError(`${It(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,s,n,e)}Rt.bind(void 0,!1);const Tt=Rt.bind(void 0,!0);class xt{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new tt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let s;for(const e of t){const t=Object.keys(e);if(s&&0!==s.size)for(const e of t){if(s.has(e))return!1;s.add(e)}else s=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new tt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(function(e,t,s,n,r){if(void 0!==r.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=void 0!==s?new Map([...Object.entries(s),...t.entries()]):t;for(const t of n.crit){if(!o.has(t))throw new et(`Extension Header Parameter "${t}" is not recognized`);if(void 0===r[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}(tt,new Map([["b64",!0]]),t?.crit,this._protectedHeader,s).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new tt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:r}=s;if("string"!=typeof r||!r)throw new tt('JWS "alg" (Algorithm) Header Parameter missing or invalid');Tt(r,e,"sign");let o,a=this._payload;n&&(a=at.encode(ct(a))),o=this._protectedHeader?at.encode(ct(JSON.stringify(this._protectedHeader))):at.encode("");const i=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),s=new Uint8Array(t);let n=0;for(const t of e)s.set(t,n),n+=t.length;return s}(o,at.encode("."),a),c=await vt(r,e,i),l={signature:ct(c),payload:""};return n&&(l.payload=it.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=it.decode(o)),l}}class Pt{constructor(e){this._flattened=new xt(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const s=await this._flattened.sign(e,t);if(void 0===s.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${s.protected}.${s.payload}.${s.signature}`}}const Nt=e=>Math.floor(e.getTime()/1e3),Dt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,jt=e=>{const t=Dt.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const s=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(s);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*s);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*s);break;case"day":case"days":case"d":n=Math.round(86400*s);break;case"week":case"weeks":case"w":n=Math.round(604800*s);break;default:n=Math.round(31557600*s)}return"-"===t[1]||"ago"===t[4]?-n:n};function Ht(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class Ot{constructor(e={}){if(!St(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:Ht("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:Ht("setNotBefore",Nt(e))}:this._payload={...this._payload,nbf:Nt(new Date)+jt(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:Ht("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:Ht("setExpirationTime",Nt(e))}:this._payload={...this._payload,exp:Nt(new Date)+jt(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:Nt(new Date)}:e instanceof Date?this._payload={...this._payload,iat:Ht("setIssuedAt",Nt(e))}:this._payload="string"==typeof e?{...this._payload,iat:Ht("setIssuedAt",Nt(new Date)+jt(e))}:{...this._payload,iat:Ht("setIssuedAt",e)},this}}class Lt extends Ot{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const s=new Pt(at.encode(JSON.stringify(this._payload)));if(s.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new st("JWTs MUST NOT use unencoded payload");return s.sign(e,t)}}async function Wt(e){if(e.accessToken)return e.accessToken;if(!e.serviceAccountKey)throw new Error("Either serviceAccountKey or accessToken must be provided");return await async function(e){const t=Math.floor(Date.now()/1e3);let s=e.private_key;if(!s)throw new Error("Private key is missing from service account key");if(s=s.trim(),s.includes("-----BEGIN")){if(s=s.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),s.includes("BEGIN RSA PRIVATE KEY"))throw new Error("Private key is in PKCS#1 format (RSA PRIVATE KEY). Please download a new service account key from Google Cloud Console. The key should be in PKCS#8 format (PRIVATE KEY).");const e=s.match(/-----BEGIN PRIVATE KEY-----\n?([\s\S]*?)\n?-----END PRIVATE KEY-----/);if(e){const t=e[1].replace(/\s/g,"");(!t.includes("\n")||t.length>64)&&(s=`-----BEGIN PRIVATE KEY-----\n${t.match(/.{1,64}/g)?.join("\n")||t}\n-----END PRIVATE KEY-----`)}}else{const e=s.replace(/\s/g,"");s=`-----BEGIN PRIVATE KEY-----\n${e.match(/.{1,64}/g)?.join("\n")||e}\n-----END PRIVATE KEY-----`}try{const n=await ot(s,"RS256"),r=await new Lt({scope:"https://www.googleapis.com/auth/cloud-platform"}).setProtectedHeader({alg:"RS256"}).setIssuedAt(t).setExpirationTime(t+3600).setIssuer(e.client_email).setSubject(e.client_email).setAudience("https://oauth2.googleapis.com/token").sign(n),o=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:r})});if(!o.ok){const e=await o.json();throw new Error(e.error_description||"Failed to get access token")}return(await o.json()).access_token}catch(e){if(e.message&&e.message.includes("pkcs8"))throw new Error("Invalid private key format. The service account key must be in PKCS#8 format. Please ensure your service account key JSON file has a properly formatted private_key field. If you downloaded the key from Google Cloud Console, it should already be in the correct format.");throw e}}(e.serviceAccountKey)}function $t(e,t,s,n){return`projects/${e}/locations/${t}/agents/${s}/sessions/${n}`}function Mt(e){let t=null;for(const s of e)if(s.payload){if(s.payload.richContent){t=s.payload.richContent;break}if(s.payload.fields&&s.payload.fields.richContent){const e=s.payload.fields.richContent;e.listValue&&e.listValue.values?t=e.listValue.values.map(e=>e.listValue&&e.listValue.values?e.listValue.values.map(e=>{if(e.structValue&&e.structValue.fields){const t=e.structValue.fields;if(t.type&&t.options)return{type:t.type.stringValue||t.type,options:t.options.listValue?t.options.listValue.values.map(e=>({text:e.structValue?.fields?.text?.stringValue||"",payload:e.structValue?.fields?.payload?.stringValue||""})):[]}}return e}):e):"object"!=typeof e||e.listValue||(t=e);break}}return t}const Kt="blockspark_chat_mode",Ut="blockspark_chat_id",Jt="blockspark_session_id",Ft="chat_session_id";class Bt{constructor(){this.sessionId=null,this.sessionId=this.loadSessionId()}loadSessionId(){return"undefined"!=typeof localStorage?localStorage.getItem(Ft):null}saveSessionId(e){this.sessionId=e,"undefined"!=typeof localStorage&&(e?localStorage.setItem(Ft,e):localStorage.removeItem(Ft))}updateSessionFromResponse(e){const t=e?.data?.session_id||e?.session_id;t&&"string"==typeof t&&this.saveSessionId(t)}getSessionId(){return this.sessionId||""}getSessionHeader(){return{"X-Session-ID":this.getSessionId()}}}let Vt=null;class zt extends Error{constructor(e="chat_resolved"){super(e),this.reason="chat_resolved",this.name="ChatResolvedError"}}const qt="undefined"!=typeof process&&"MISSING_ENV_VAR"?.REACT_APP_BACKEND_BASE_URL,Gt="undefined"!=typeof process&&"MISSING_ENV_VAR"?.REACT_APP_BACKEND_WS_URL;class Yt{constructor(e={}){this.ws=null,this.wsReconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=null,this.pingInterval=null,this.currentChatId=null,this.currentSessionId=null,this.messageHandlers=new Set,this.connectionHandlers=new Set,this.baseUrl=e.baseUrl||qt,this.wsUrl=e.wsUrl||Gt,this.debug=e.debug||!1,this.sessionManager=(Vt||(Vt=new Bt),Vt)}async startSupportChat(e,t,s,n){try{const r={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};e&&(r["X-Session-ID"]=e);const o={};t&&(o.name=t),s&&(o.email=s),n&&(o.mobile=n);const a=await fetch(`${this.baseUrl}/api/support/chat/start`,{method:"POST",headers:r,body:JSON.stringify(o)});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${a.status}`)}const i=await a.json();if(this.sessionManager.updateSessionFromResponse(i),i.status&&i.data)return{chat_id:i.data.chat_id,session_id:i.data.session_id};if(i.chat_id&&i.session_id)return{chat_id:i.chat_id,session_id:i.session_id};throw new Error("Invalid response format from chat start endpoint")}catch(e){throw console.error("Error starting support chat:",e),new Error(e.message||"Failed to start support chat session")}}async requestHandoff(e,t,s,n,r,o,a){if(!e||"undefined"===e||"null"===e)throw new Error("Invalid chat_id. Chat must be initialized first.");try{const i={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t?i["X-Session-ID"]=t:n&&(i["X-Session-ID"]=n);const c={};s&&(c.reason=s),r&&(c.name=r),o&&(c.email=o),a&&(c.mobile=a);const l=await fetch(`${this.baseUrl}/api/support/chat/${e}/handoff`,{method:"POST",headers:i,body:JSON.stringify(c)});if(400===l.status||404===l.status){const e=await l.json().catch(()=>({}));throw new Error(e.message||"Invalid chat_id. Chat may have expired.")}if(!l.ok){const e=await l.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${l.status}`)}const d=await l.json();return this.sessionManager.updateSessionFromResponse(d),d.status?{success:!0,message:d.message||d.data?.message}:{success:!0,message:d.message}}catch(e){throw console.error("Error requesting handoff:",e),e}}async sendMessageToAgent(e,t,s){try{const n={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t&&(n["X-Session-ID"]=t);const r=await fetch(`${this.baseUrl}/api/support/chat/${e}/message`,{method:"POST",headers:n,body:JSON.stringify({content:s})});if(401===r.status||404===r.status){const e=await r.json().catch(()=>({}));throw new Error(e.message||"Chat not found or unauthorized")}if(!r.ok){const e=await r.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${r.status}`)}const o=await r.json();if(this.sessionManager.updateSessionFromResponse(o),!0===o?.ignored&&"chat_resolved"===o?.reason)throw new zt;return{id:o.id,sender_type:"customer",content:s,timestamp:o.timestamp||(new Date).toISOString()}}catch(e){if(e instanceof zt||"ChatResolvedError"===e?.name)throw e;throw console.error("Error sending message to agent:",e),new Error(e.message||"Failed to send message to agent")}}async ensureChatInitialized(e,t,s,n,r,o){return e&&"undefined"!==e&&"null"!==e&&t?{chat_id:e,session_id:t}:await this.startSupportChat(s||null,n||null,r||null,o||null)}async loadMessageHistory(e,t){try{const s={...this.sessionManager.getSessionHeader()};t&&(s["X-Session-ID"]=t);const n=await fetch(`${this.baseUrl}/api/support/chat/${e}/messages`,{method:"GET",headers:s});if(401===n.status||404===n.status){const e=await n.json().catch(()=>({}));throw new Error(e.message||"Chat not found or unauthorized")}if(!n.ok){const e=await n.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${n.status}`)}const r=await n.json();return this.sessionManager.updateSessionFromResponse(r),r.messages||[]}catch(e){throw console.error("Error loading message history:",e),new Error(e.message||"Failed to load message history")}}connectWebSocket(e,t,s,n,r){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&this.ws.readyState===WebSocket.OPEN)return void(this.debug&&console.log("WebSocket already connected"));this.currentChatId=e,this.currentSessionId=t,s&&this.messageHandlers.add(s),n&&this.connectionHandlers.add(n);const o=t||this.sessionManager.getSessionId()||"",a=`${this.wsUrl}/ws/support/${e}?X-Session-ID=${encodeURIComponent(o)}`;try{this.ws=new WebSocket(a),this.ws.onopen=()=>{this.debug&&console.log("WebSocket connected to:",a),console.log("✅ Customer WebSocket connected:",{chatId:e,sessionId:t,wsUrl:a}),this.wsReconnectAttempts=0,this.connectionHandlers.forEach(e=>e(!0)),this.startPingInterval()},this.ws.onmessage=e=>{try{const t=JSON.parse(e.data);if(this.debug&&(console.log("WebSocket raw message received:",e.data),console.log("WebSocket parsed message:",t)),t.session_id&&this.sessionManager.updateSessionFromResponse({session_id:t.session_id}),"agent_accepted"!==t.type&&"chat_resolved"!==t.type&&"chat_ended"!==t.type||console.log("🔔 Received notification message:",{type:t.type,chat_id:t.chat_id,timestamp:t.timestamp,to_agent:t.to_agent,to_agent_id:t.to_agent_id}),"pong"===t.type)return;this.debug&&"message"===t.type&&console.log("Processing message type:",{type:t.type,sender_type:t.sender_type,content:t.content?.substring(0,50)+"...",id:t.id}),this.messageHandlers.forEach(e=>e(t))}catch(t){console.error("Error parsing WebSocket message:",t),this.debug&&console.error("Raw message data:",e.data)}},this.ws.onerror=e=>{console.error("❌ WebSocket error:",e),this.connectionHandlers.forEach(e=>e(!1))},this.ws.onclose=t=>{if(this.debug&&console.log("WebSocket closed:",t.code,t.reason),console.log("🔌 Customer WebSocket closed:",{code:t.code,reason:t.reason,chatId:e}),this.stopPingInterval(),this.connectionHandlers.forEach(e=>e(!1)),this.ws=null,r?.(t),4e3===t.code)return this.wsReconnectAttempts=this.maxReconnectAttempts,this.currentChatId=null,void(this.currentSessionId=null);if(this.wsReconnectAttempts<this.maxReconnectAttempts&&this.currentChatId&&this.currentSessionId){this.wsReconnectAttempts++;const e=Math.min(1e3*Math.pow(2,this.wsReconnectAttempts),3e4);this.debug&&console.log(`Reconnecting in ${e}ms (attempt ${this.wsReconnectAttempts}/${this.maxReconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.currentChatId&&this.currentSessionId&&this.connectWebSocket(this.currentChatId,this.currentSessionId,s,n,r)},e)}else this.debug&&console.error("Max reconnection attempts reached")}}catch(e){console.error("Error creating WebSocket connection:",e),this.connectionHandlers.forEach(e=>e(!1))}}sendMessageViaWebSocket(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return!1;try{return this.ws.send(JSON.stringify({type:"message",content:e})),!0}catch(e){return console.error("Error sending message via WebSocket:",e),!1}}sendTypingIndicator(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return!1;try{return this.ws.send(JSON.stringify({type:e})),!0}catch(t){return console.error(`Error sending ${e} via WebSocket:`,t),!1}}startPingInterval(){this.stopPingInterval(),this.pingInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"ping"}))}catch(e){console.error("Error sending ping:",e)}},3e4)}stopPingInterval(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}disconnectWebSocket(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.stopPingInterval(),this.ws&&(this.ws.close(),this.ws=null),this.messageHandlers.clear(),this.connectionHandlers.clear(),this.wsReconnectAttempts=0,this.currentChatId=null,this.currentSessionId=null}isWebSocketConnected(){return null!==this.ws&&this.ws.readyState===WebSocket.OPEN}removeMessageHandler(e){this.messageHandlers.delete(e)}removeConnectionHandler(e){this.connectionHandlers.delete(e)}}const Xt=function({title:e="💬 BlockSpark AI Assistant",subtitle:t="We're here to help",welcomeTitle:s="👋 Welcome to Blockspark",welcomeMessage:n="My name is BlockSpark AI Assistant and I'll guide you.",welcomeCta:r="💬 Click here to start chatting!",showWelcomePopup:i=!0,welcomePopupDelay:c=1500,fallbackWelcomeMessage:l="Hello! I'm BlockSpark AI Assistant. How can I help you today?",inputPlaceholder:d="Type your message...",emptyStateMessage:u="Hi! I'm BlockSpark AI Assistant. How can I help you today?",debug:h=!1,dfProjectId:m,dfLocation:p="us-central1",dfAgentId:g,serviceAccountKey:f,accessToken:y,languageCode:w="en",backendBaseUrl:S,backendWsUrl:E}){const[b,k]=(0,a.useState)(!1),[A,_]=(0,a.useState)(!1),[v,I]=(0,a.useState)([]),[C,R]=(0,a.useState)(""),[T,x]=(0,a.useState)(!1),[P,N]=(0,a.useState)(null),[D,j]=(0,a.useState)(!1),[H,O]=(0,a.useState)(!1),[L,W]=(0,a.useState)(!1),[$,M]=(0,a.useState)(!1),[K,U]=(0,a.useState)({name:"Agent"}),[J,F]=(0,a.useState)(!1),[B,V]=(0,a.useState)(!1),[z,q]=(0,a.useState)(!1),[G,Y]=(0,a.useState)(!1),[X,Q]=(0,a.useState)(null),[Z,ee]=(0,a.useState)(""),[te,se]=(0,a.useState)(""),[ne,re]=(0,a.useState)(""),oe=(0,a.useRef)(""),ae=(0,a.useRef)(null),ie=(0,a.useRef)(null),ce=(0,a.useRef)(null),le=(0,a.useRef)((de={baseUrl:S||"undefined"!=typeof process&&"MISSING_ENV_VAR"?.REACT_APP_BACKEND_BASE_URL,wsUrl:E||"undefined"!=typeof process&&"MISSING_ENV_VAR"?.REACT_APP_BACKEND_WS_URL,debug:h},new Yt(de)));var de;const ue=(0,a.useRef)(null),{currentMode:he,switchToHumanMode:me,switchToBotMode:pe,chatId:ge,sessionId:fe,setChatId:ye,setSessionId:we}=function(){const[e,t]=(0,a.useState)(()=>"HUMAN"===localStorage.getItem(Kt)?"HUMAN":"BOT"),[s,n]=(0,a.useState)(()=>localStorage.getItem(Ut)),[r,o]=(0,a.useState)(()=>localStorage.getItem(Jt));(0,a.useEffect)(()=>{localStorage.setItem(Kt,e)},[e]);const i=(0,a.useCallback)(e=>{n(e),e?localStorage.setItem(Ut,e):localStorage.removeItem(Ut)},[]),c=(0,a.useCallback)(e=>{o(e),e?localStorage.setItem(Jt,e):localStorage.removeItem(Jt)},[]),l=(0,a.useCallback)(()=>{t("HUMAN")},[]),d=(0,a.useCallback)(()=>{t("BOT")},[]),u=(0,a.useCallback)(e=>!1,[]);return{currentMode:e,switchToHumanMode:l,switchToBotMode:d,isHandoffTriggered:u,chatId:s,sessionId:r,setChatId:i,setSessionId:c}}(),Se=(0,a.useCallback)(e=>{V(!0),O(!1),Y(!1),M(!1),ce.current&&(clearTimeout(ce.current),ce.current=null),le.current.disconnectWebSocket(),ye(null),we(null);const t={id:`resolved-${Date.now()}`,text:"Thank you for contacting us!",sender:"bot",timestamp:new Date};I(e=>[...e,t]),setTimeout(()=>{pe(),V(!1),I([]),F(!1),Q(null),ee(""),se(""),re(""),oe.current="",Ie().catch(console.error)},2e3)},[ye,we,pe]),Ee=((0,a.useCallback)(async()=>{if(!z){q(!0);try{const e=oe.current||Z||null,t=te||null,s=ne||null,n=await le.current.startSupportChat(P||null,e,t,s);me(),ye(n.chat_id),we(n.session_id),V(!1),R("")}catch(e){console.error("Error starting new chat:",e),I(t=>[...t,{id:`error-new-chat-${Date.now()}`,text:h?`Error: ${e?.message||"Failed to start a new chat."}`:"Sorry, I couldn't start a new chat. Please try again.",sender:"bot",timestamp:new Date}])}finally{q(!1)}}},[te,ne,Z,h,z,P,ye,we,me]),()=>{if(m&&g)return{dfProjectId:m,dfLocation:p||"us-central1",dfAgentId:g,serviceAccountKey:f,accessToken:y,languageCode:w||"en"}});(0,a.useEffect)(()=>{if(!i)return;const e=setTimeout(()=>{_(!0)},c);return()=>clearTimeout(e)},[i,c]),(0,a.useEffect)(()=>{ae.current?.scrollIntoView({behavior:"smooth"})},[v]);const be=(0,a.useCallback)(e=>{if(e.to_agent){U({id:e.to_agent_id,name:e.to_agent});const t={id:`system-${Date.now()}`,text:e.from_agent?`Chat has been transferred from ${e.from_agent} to ${e.to_agent}`:`Chat has been transferred to ${e.to_agent}`,sender:"bot",timestamp:new Date};I(e=>[...e,t]),h&&console.log("Agent changed:",{from:e.from_agent,to:e.to_agent,reason:e.reason})}},[h]),ke=(0,a.useCallback)(e=>{switch(e.type){case"message":if(e.content)if("agent"!==e.sender_type&&e.sender_type)h&&"customer"===e.sender_type&&console.log("Ignoring customer message from WebSocket (already added)");else{const t={id:e.id||`agent-${Date.now()}`,text:e.content,sender:"agent",timestamp:new Date(e.timestamp||Date.now())};I(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),M(!1),ce.current&&(clearTimeout(ce.current),ce.current=null)}else h&&console.warn("WebSocket message received without content:",e);break;case"typing_start":"agent"===e.sender_type&&(M(!0),ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>{M(!1)},3e3));break;case"typing_stop":"agent"===e.sender_type&&(M(!1),ce.current&&(clearTimeout(ce.current),ce.current=null));break;case"agent_changed":be(e);break;case"chat_info":h&&console.log("Chat info:",e),"active"===e.status?(O(!1),Y(!0)):"resolved"!==e.status&&"ended"!==e.status||Se(e.chat_id||null),e.agent_id&&U(t=>({...t,id:e.agent_id}));break;case"agent_accepted":Y(!0),O(!1);const t={id:e.id||`agent-accepted-${e.chat_id||Date.now()}-${Date.now()}`,text:"You can chat now, the agent has accepted your request.",sender:"bot",timestamp:e.timestamp?new Date(e.timestamp):new Date};I(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),e.to_agent&&U({name:e.to_agent,id:e.to_agent_id}),h&&console.log("Agent accepted chat:",e);break;case"chat_resolved":case"chat_ended":Se(e.chat_id||null),h&&console.log("Chat resolved/ended:",e);break;case"error":console.error("WebSocket error:",e.error);const s={id:`error-${Date.now()}`,text:e.error||"An error occurred. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,s]);break;case"pong":break;default:h&&console.log("Unknown message type:",e.type)}},[h,Se,be]),Ae=(0,a.useCallback)(e=>{4e3===e.code&&Se(ge)},[ge,Se]),_e=(0,a.useCallback)(e=>{W(e),e&&O(!1)},[]);(0,a.useEffect)(()=>{if("HUMAN"===he&&ge&&fe)return le.current.connectWebSocket(ge,fe,ke,_e,Ae),()=>{le.current.disconnectWebSocket()}},[he,ge,fe,ke,_e,Ae]);const ve=(0,a.useCallback)(async(e=!0)=>{if(ge&&fe)try{x(!0);const t=(await le.current.loadMessageHistory(ge,fe)).map(e=>({id:e.id||`msg-${Date.now()}-${Math.random()}`,text:e.content,sender:"agent"===e.sender_type?"agent":"user",timestamp:new Date(e.timestamp)}));I(e?e=>{const s=new Set(e.map(e=>e.id)),n=t.filter(e=>!s.has(e.id));return[...e,...n].sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}:t)}catch(e){if(console.error("Error loading message history:",e),h){const t={id:`error-${Date.now()}`,text:`Failed to load chat history: ${e.message}`,sender:"bot",timestamp:new Date};I(e=>[...e,t])}}finally{x(!1)}},[ge,fe,h]);(0,a.useEffect)(()=>{if("HUMAN"===he&&ge&&fe){const e=`${ge}-${fe}`;ue.current!==e&&(ue.current=e,setTimeout(()=>{0===v.length&&ve(!1).catch(console.error)},0))}else"BOT"===he&&(ue.current=null)},[he,ge,fe,ve,v.length]);const Ie=async()=>{if(P)return P;try{j(!0);const e=Ee();if(!e)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.");const t=await async function(e){try{const t=await Wt(e),s=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n=e.dfLocation.split(" ")[0].trim(),r=`https://${n}-dialogflow.googleapis.com/v3/${$t(e.dfProjectId,n,e.dfAgentId,s)}:detectIntent`,o={queryInput:{text:{text:"hello"},languageCode:e.languageCode||"en"}},a=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.error?.message||`HTTP error! status: ${a.status}`)}const i=await a.json();let c="Hello! I'm BlockSpark AI Assistant. How can I help you today?",l=null;if(i.queryResult?.responseMessages){const e=i.queryResult.responseMessages.filter(e=>e.text).map(e=>e.text.text.join(" "));e.length>0&&(c=e.join(" ")),l=Mt(i.queryResult.responseMessages)}else i.queryResult?.fulfillmentText&&(c=i.queryResult.fulfillmentText);return{session_id:s,message:c,...l&&{richContent:l}}}catch(e){console.error("Error creating Dialogflow session:",e);const t=e.message||"Failed to create session";if(t.includes("401")||t.includes("Unauthorized"))throw new Error("Authentication failed. Please check your service account key or access token.");if(t.includes("403")||t.includes("Forbidden"))throw new Error("Access forbidden. Please check your Dialogflow API permissions.");if(t.includes("404")||t.includes("Not Found"))throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");throw new Error(t)}}(e);if(N(t.session_id),t.message){h&&(console.log("Session response richContent:",t.richContent),console.log("Full session response:",t));const e={id:`welcome-${Date.now()}`,text:t.message,sender:"bot",timestamp:new Date,richContent:t.richContent};I([e])}return t.session_id}catch(e){console.error("Error creating session:",e),h&&console.error("Full error details:",{message:e.message,stack:e.stack,config:Ee()});const t={id:`error-${Date.now()}`,text:h?`Error: ${e.message||"Failed to create session. Please check your Dialogflow configuration."}`:l,sender:"bot",timestamp:new Date};return I([t]),null}finally{j(!1)}},Ce=async(e,t,s=!1)=>{if(!e.trim())return;if(J){if("name"===X){const t=e.trim();ee(t),oe.current=t,Q("email");const s={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};I(e=>[...e,s]);const n={id:(Date.now()+1).toString(),text:"Thank you! Now please provide your email address:",sender:"bot",timestamp:new Date};return I(e=>[...e,n]),void R("")}if("email"===X){const t=e.trim();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){const e={id:(Date.now()+1).toString(),text:"Please provide a valid email address:",sender:"bot",timestamp:new Date};return I(t=>[...t,e]),void R("")}se(t),Q("mobile");const s={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};I(e=>[...e,s]);const n={id:(Date.now()+1).toString(),text:"Thank you! Now please provide your mobile number:",sender:"bot",timestamp:new Date};return I(e=>[...e,n]),void R("")}if("mobile"===X){const t=e.trim();if(!/^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,9}$/.test(t)||t.length<10){const e={id:(Date.now()+1).toString(),text:"Please provide a valid mobile number (e.g., +1234567890):",sender:"bot",timestamp:new Date};return I(t=>[...t,e]),void R("")}re(t);const s={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};I(e=>[...e,s]);const n=oe.current,r=te;return F(!1),Q(null),oe.current="",await(async(e,t,s)=>{try{O(!0);const n=P,r=await le.current.ensureChatInitialized(ge,fe,n||null,e||null,t||null,s||null);if(!r||!r.chat_id)throw new Error("Failed to initialize chat session");const o=r.chat_id,a=r.session_id;o!==ge&&(ye(o),we(a),h&&console.log("✅ Chat initialized:",{chatId:o,sessionId:a}));try{await le.current.requestHandoff(o,a,"Customer requested human agent",n||null,e||null,t||null,s||null),h&&console.log("✅ Handoff requested successfully")}catch(r){if(!(r.message?.includes("Invalid chat_id")||r.message?.includes("Chat not found")||r.message?.includes("unauthorized")||r.message?.includes("400")||r.message?.includes("401")||r.message?.includes("404")||r.message?.includes("expired")))throw r;{h&&console.log("⚠️ Chat expired or not found. Re-initializing chat..."),ye(null),we(null);const r=await le.current.startSupportChat(n||null,e||null,t||null,s||null);if(!r||!r.chat_id)throw new Error("Failed to re-initialize chat session");const o=r.chat_id,a=r.session_id;ye(o),we(a),await le.current.requestHandoff(o,a,"Customer requested human agent",n||null,e||null,t||null,s||null),h&&console.log("✅ Handoff requested successfully after retry");const i=`${o}-${a}`;ue.current!==i&&(ue.current=i,await ve(!0))}}me(),V(!1),Y(!1);const i={id:`connecting-${Date.now()}`,text:"Connecting you to a human agent...",sender:"bot",timestamp:new Date};I(e=>[...e,i]);const c=`${o}-${a}`;ue.current=c}catch(e){console.error("Error handling handoff:",e);const t={id:`error-${Date.now()}`,text:h?`Handoff error: ${e.message}`:"Failed to connect to agent. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,t]),O(!1)}})(n,r,t),void R("")}}if("HUMAN"===he){if(!ge||!fe){const e={id:Date.now().toString(),text:"Chat session not initialized. Please try again.",sender:"bot",timestamp:new Date};return void I(t=>[...t,e])}if(!s){const s={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};I(e=>[...e,s])}le.current.sendTypingIndicator("typing_stop"),ie.current&&(clearTimeout(ie.current),ie.current=null),R(""),x(!0);try{le.current.sendMessageViaWebSocket(e.trim())||await le.current.sendMessageToAgent(ge,fe,e.trim())}catch(t){if(t instanceof zt||"ChatResolvedError"===t?.name||"chat_resolved"===t?.message)return void Se(ge);if(console.error("Error sending message to agent:",t),t.message?.includes("Chat not found")||t.message?.includes("unauthorized")||t.message?.includes("401")||t.message?.includes("404")){h&&console.log("⚠️ Chat expired. Re-initializing..."),ye(null),we(null);try{const t=await le.current.startSupportChat(P||null,null,null,null);ye(t.chat_id),we(t.session_id);try{await le.current.sendMessageToAgent(t.chat_id,t.session_id,e.trim())}catch(e){if(e instanceof zt||"ChatResolvedError"===e?.name||"chat_resolved"===e?.message)return void Se(t.chat_id);throw e}return}catch(e){if(e instanceof zt||"ChatResolvedError"===e?.name||"chat_resolved"===e?.message)return void Se(ge);const t={id:(Date.now()+1).toString(),text:h?`Error: ${e.message||"Failed to send message."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,t])}}else{const e={id:(Date.now()+1).toString(),text:h?`Error: ${t.message||"Failed to send message to agent."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};I(t=>[...t,e])}}finally{x(!1)}return}let n=P;if(!n)try{if(n=await Ie(),!n){const e={id:Date.now().toString(),text:h?"Failed to create session. Please check the console for details.":"Sorry, I'm having trouble connecting. Please try again.",sender:"bot",timestamp:new Date};return void I(t=>[...t,e])}}catch(e){console.error("Error in createSession:",e);const t={id:Date.now().toString(),text:h?`Connection Error: ${e.message||"Please check your Dialogflow configuration."}`:"Sorry, I'm having trouble connecting. Please check your configuration.",sender:"bot",timestamp:new Date};return void I(e=>[...e,t])}if(!s){const s={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};I(e=>[...e,s])}R(""),x(!0);try{const t=Ee();if(!t)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.");const s=await async function(e,t,s){try{const n=await Wt(s),r=s.dfLocation.split(" ")[0].trim(),o=`https://${r}-dialogflow.googleapis.com/v3/${$t(s.dfProjectId,r,s.dfAgentId,t)}:detectIntent`,a={queryInput:{text:{text:e.trim()},languageCode:s.languageCode||"en"}},i=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok){const e=await i.text();let t={};try{t=JSON.parse(e)}catch{t={message:e||`HTTP ${i.status}`}}const s=t.error?.message||t.message||`HTTP error! status: ${i.status}`;throw console.error("Dialogflow API Error (sendMessage):",{status:i.status,statusText:i.statusText,error:t,endpoint:o}),new Error(s)}const c=await i.json();let l="I'm sorry, I didn't understand that. Could you please rephrase?",d=null,u=!1;if(!0===c.queryResult?.parameters?.fields?.handoff?.boolValue)u=!0;else if(c.queryResult?.responseMessages)for(const e of c.queryResult.responseMessages)if(e.payload&&"object"==typeof e.payload){if(!0===e.payload.handoff){u=!0;break}if(!0===e.payload.fields?.handoff?.boolValue){u=!0;break}}if(!0===c.handoff&&(u=!0),c.queryResult?.responseMessages){const e=c.queryResult.responseMessages.filter(e=>e.text).map(e=>e.text.text.join(" "));e.length>0&&(l=e.join(" ")),d=Mt(c.queryResult.responseMessages)}else c.queryResult?.fulfillmentText&&(l=c.queryResult.fulfillmentText);return{response:l,session_id:t,source:"dialogflow",timestamp:(new Date).toISOString(),...d&&{richContent:d},...u&&{handoff:!0}}}catch(e){console.error("Error sending message to Dialogflow:",e);const t=e.message||"Failed to send message";if(t.includes("401")||t.includes("Unauthorized"))throw new Error("Authentication failed. Please check your service account key or access token.");if(t.includes("403")||t.includes("Forbidden"))throw new Error("Access forbidden. Please check your Dialogflow API permissions.");if(t.includes("404")||t.includes("Not Found"))throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");if(t.includes("CORS"))throw new Error("CORS error. Dialogflow API may not allow browser requests. Consider using a backend proxy.");throw new Error(t)}}(e.trim(),n,t);if(h&&(console.log("Chat response richContent:",s.richContent),console.log("Full chat response:",s),console.log("Handoff detected:",s.handoff)),!0===s.handoff){const e={id:(Date.now()+1).toString(),text:s.response,sender:"bot",timestamp:new Date(s.timestamp||Date.now()),richContent:s.richContent};I(t=>[...t,e]),F(!0),Q("name"),ee(""),se(""),oe.current="";const t={id:(Date.now()+2).toString(),text:"To connect you with a human agent, I'll need some information. Please provide your name:",sender:"bot",timestamp:new Date};return void I(e=>[...e,t])}const r={id:(Date.now()+1).toString(),text:s.response,sender:"bot",timestamp:new Date(s.timestamp||Date.now()),richContent:s.richContent};I(e=>[...e,r])}catch(e){console.error("Error sending message:",e),h&&console.error("Full error details:",{message:e.message,stack:e.stack,sessionId:n,config:Ee()});const t={id:(Date.now()+1).toString(),text:h?`Error: ${e.message||"Failed to send message. Please check your Dialogflow configuration."}`:e.message?.includes("Failed to fetch")||e.message?.includes("CORS")?"Unable to connect to Dialogflow. Please check your configuration and network.":"Sorry, I'm having trouble processing your message. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,t])}finally{x(!1)}};(0,a.useEffect)(()=>()=>{ie.current&&clearTimeout(ie.current),ce.current&&clearTimeout(ce.current)},[]);const Re=async()=>{k(!0),_(!1),P||await Ie()};return(0,a.useEffect)(()=>()=>{le.current.disconnectWebSocket()},[]),(0,o.jsxs)(o.Fragment,{children:[A&&!b&&(0,o.jsxs)("div",{className:"custom-welcome-popup",onClick:Re,children:[(0,o.jsxs)("div",{className:"custom-welcome-header",children:[(0,o.jsx)("div",{className:"custom-welcome-title",children:s}),(0,o.jsx)("button",{className:"custom-close-popup",onClick:e=>{e.stopPropagation(),_(!1)},children:"×"})]}),(0,o.jsx)("div",{className:"custom-welcome-message",children:n}),(0,o.jsx)("div",{className:"custom-welcome-cta",children:r})]}),!b&&(0,o.jsx)("button",{className:"custom-chat-toggle-btn",onClick:Re,"aria-label":"Open chat",children:(0,o.jsx)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,o.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),b&&(0,o.jsxs)("div",{className:"custom-chat-window",children:[(0,o.jsxs)("div",{className:"custom-chat-header",children:[(0,o.jsxs)("div",{className:"custom-chat-header-content",children:[(0,o.jsx)("div",{className:"custom-chat-title",children:e}),(0,o.jsxs)("div",{className:"custom-chat-subtitle",children:[t,"HUMAN"===he&&(0,o.jsxs)("span",{className:"custom-mode-indicator",children:[" ","• ",L?"🟢 Connected":"🟡 Connecting..."]})]}),"HUMAN"===he&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:"custom-mode-badge",children:"Human Support Mode"}),(0,o.jsxs)("div",{className:"custom-agent-info",children:[(0,o.jsx)("span",{className:"custom-agent-label",children:"Agent:"}),(0,o.jsx)("span",{className:"custom-agent-name",children:K.name})]})]}),"BOT"===he&&(0,o.jsx)("div",{className:"custom-mode-badge",children:"Bot Mode"})]}),(0,o.jsx)("button",{className:"custom-chat-close-btn",onClick:()=>{k(!1),"HUMAN"===he&&le.current.disconnectWebSocket()},"aria-label":"Close chat",children:"×"})]}),(0,o.jsxs)("div",{className:"custom-chat-messages",children:[D&&0===v.length&&(0,o.jsxs)("div",{className:"custom-chat-empty",children:[(0,o.jsxs)("div",{className:"custom-typing-indicator",children:[(0,o.jsx)("span",{}),(0,o.jsx)("span",{}),(0,o.jsx)("span",{})]}),(0,o.jsx)("p",{children:"Initializing chat..."})]}),!D&&0===v.length&&(0,o.jsxs)("div",{className:"custom-chat-empty",children:[(0,o.jsx)("div",{className:"custom-chat-empty-icon",children:"👋"}),(0,o.jsx)("p",{children:u})]}),v.map(e=>(0,o.jsxs)("div",{className:`custom-message custom-message-${e.sender}`,children:[(0,o.jsx)("div",{className:"custom-message-content",children:(0,o.jsx)(Ye,{options:{defaultProtocol:"https",target:{url:"_blank"},attributes:{rel:"noopener noreferrer"}},children:e.text})}),(h&&e.richContent&&(console.log("Rendering message with richContent:",e.richContent),console.log("richContent type:",typeof e.richContent),console.log("richContent is array:",Array.isArray(e.richContent)),console.log("richContent length:",e.richContent?.length)),e.richContent&&Array.isArray(e.richContent)&&e.richContent.length>0?(0,o.jsx)("div",{className:"custom-chips-container",children:e.richContent.map((e,t)=>{if(h&&console.log(`Processing contentGroup ${t}:`,e),!Array.isArray(e)){const s=e;return s&&"chips"===s.type&&s.options?(0,o.jsx)("div",{className:"custom-chips-group",children:s.options.map((e,t)=>(0,o.jsx)("button",{className:"custom-chip-button",onClick:()=>{const t={id:Date.now().toString(),text:e.text,sender:"user",timestamp:new Date};I(e=>[...e,t]),Ce(e.text,e.text,!0)},type:"button",children:e.text},t))},t):null}return e.map((e,s)=>(h&&console.log(`Processing content ${t}-${s}:`,e),e&&"chips"===e.type&&e.options?(0,o.jsx)("div",{className:"custom-chips-group",children:e.options.map((e,t)=>(0,o.jsx)("button",{className:"custom-chip-button",onClick:()=>{const t={id:Date.now().toString(),text:e.text,sender:"user",timestamp:new Date};I(e=>[...e,t]),Ce(e.text,e.text,!0)},type:"button",children:e.text},t))},`${t}-${s}`):null))})}):null),(0,o.jsx)("div",{className:"custom-message-time",children:e.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]},e.id)),T&&(0,o.jsx)("div",{className:"custom-message custom-message-bot",children:(0,o.jsxs)("div",{className:"custom-typing-indicator",children:[(0,o.jsx)("span",{}),(0,o.jsx)("span",{}),(0,o.jsx)("span",{})]})}),H&&(0,o.jsxs)("div",{className:"custom-message custom-message-bot",children:[(0,o.jsxs)("div",{className:"custom-typing-indicator",children:[(0,o.jsx)("span",{}),(0,o.jsx)("span",{}),(0,o.jsx)("span",{})]}),(0,o.jsx)("div",{className:"custom-message-content",children:"Connecting to agent..."})]}),"HUMAN"===he&&$&&(0,o.jsxs)("div",{className:"custom-agent-typing-indicator",children:[(0,o.jsxs)("span",{className:"custom-typing-dots",children:[(0,o.jsx)("span",{}),(0,o.jsx)("span",{}),(0,o.jsx)("span",{})]}),(0,o.jsx)("span",{className:"custom-typing-text",children:"Agent is typing..."})]}),(0,o.jsx)("div",{ref:ae})]}),(0,o.jsxs)("form",{className:"custom-chat-input-form",onSubmit:e=>{e.preventDefault(),Ce(C)},children:[(0,o.jsx)("input",{type:"text",className:"custom-chat-input",value:C,onChange:e=>{const t=e.target.value;R(t),"HUMAN"===he&&L&&(le.current.sendTypingIndicator("typing_start"),ie.current&&clearTimeout(ie.current),ie.current=setTimeout(()=>{le.current.sendTypingIndicator("typing_stop"),ie.current=null},2e3))},placeholder:d,disabled:T||D||z}),(0,o.jsx)("button",{type:"submit",className:"custom-chat-send-btn",disabled:!C.trim()||T||D||z,children:(0,o.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,o.jsx)("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),(0,o.jsx)("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]})]})]})};return r.default})());
@@ -0,0 +1,144 @@
1
+ export interface SupportChatSession {
2
+ chat_id: string;
3
+ session_id: string;
4
+ }
5
+ export interface SupportMessage {
6
+ id?: string;
7
+ sender_type: "customer" | "agent";
8
+ content: string;
9
+ timestamp: string;
10
+ }
11
+ export interface ChatInfo {
12
+ status: "waiting" | "active";
13
+ agent_id?: string;
14
+ }
15
+ export interface WebSocketMessage {
16
+ type: "message" | "chat_info" | "error" | "typing_start" | "typing_stop" | "agent_changed" | "agent_accepted" | "chat_resolved" | "chat_ended" | "ping" | "pong";
17
+ id?: string;
18
+ chat_id?: string;
19
+ sender_type?: "customer" | "agent";
20
+ sender_id?: string;
21
+ content?: string;
22
+ timestamp?: string;
23
+ status?: "waiting" | "active" | "resolved" | "ended";
24
+ agent_id?: string;
25
+ error?: string;
26
+ from_agent?: string;
27
+ to_agent?: string;
28
+ to_agent_id?: string;
29
+ reason?: string;
30
+ message?: string;
31
+ }
32
+ export declare class ChatResolvedError extends Error {
33
+ reason: "chat_resolved";
34
+ constructor(message?: string);
35
+ }
36
+ export interface ChatServiceConfig {
37
+ baseUrl?: string;
38
+ wsUrl?: string;
39
+ debug?: boolean;
40
+ }
41
+ export interface StartSupportChatOptions {
42
+ dialogflowSessionId?: string | null;
43
+ customerName?: string | null;
44
+ customerEmail?: string | null;
45
+ customerMobile?: string | null;
46
+ }
47
+ declare class ChatService {
48
+ private baseUrl;
49
+ private wsUrl;
50
+ private debug;
51
+ private ws;
52
+ private wsReconnectAttempts;
53
+ private maxReconnectAttempts;
54
+ private reconnectTimeout;
55
+ private pingInterval;
56
+ private currentChatId;
57
+ private currentSessionId;
58
+ private messageHandlers;
59
+ private connectionHandlers;
60
+ private sessionManager;
61
+ constructor(config?: ChatServiceConfig);
62
+ /**
63
+ * Start a new support chat session
64
+ * @param dialogflowSessionId - Optional: Dialogflow session ID
65
+ * @param customerName - Optional: Customer name
66
+ * @param customerEmail - Optional: Customer email
67
+ * @param customerMobile - Optional: Customer mobile number
68
+ */
69
+ startSupportChat(dialogflowSessionId?: string | null, customerName?: string | null, customerEmail?: string | null, customerMobile?: string | null): Promise<SupportChatSession>;
70
+ /**
71
+ * Request handoff to human agent
72
+ * @param chatId - Chat ID (must be valid, not undefined)
73
+ * @param sessionId - Session ID
74
+ * @param reason - Optional: Reason for handoff
75
+ * @param dialogflowSessionId - Optional: Dialogflow session ID
76
+ * @param customerName - Optional: Customer name
77
+ * @param customerEmail - Optional: Customer email
78
+ * @param customerMobile - Optional: Customer mobile number
79
+ */
80
+ requestHandoff(chatId: string, sessionId: string, reason?: string, dialogflowSessionId?: string | null, customerName?: string | null, customerEmail?: string | null, customerMobile?: string | null): Promise<{
81
+ success: boolean;
82
+ message?: string;
83
+ }>;
84
+ /**
85
+ * Send message to agent via REST API
86
+ */
87
+ sendMessageToAgent(chatId: string, sessionId: string, message: string): Promise<SupportMessage>;
88
+ /**
89
+ * Ensure chat is initialized - helper method
90
+ * Returns existing chat_id if valid, otherwise initializes new chat
91
+ * @param existingChatId - Existing chat ID to validate
92
+ * @param existingSessionId - Existing session ID
93
+ * @param dialogflowSessionId - Optional: Dialogflow session ID
94
+ * @param customerName - Optional: Customer name
95
+ * @param customerEmail - Optional: Customer email
96
+ * @param customerMobile - Optional: Customer mobile number
97
+ * @returns Promise with chat_id and session_id
98
+ */
99
+ ensureChatInitialized(existingChatId?: string | null, existingSessionId?: string | null, dialogflowSessionId?: string | null, customerName?: string | null, customerEmail?: string | null, customerMobile?: string | null): Promise<SupportChatSession>;
100
+ /**
101
+ * Load message history
102
+ */
103
+ loadMessageHistory(chatId: string, sessionId: string): Promise<SupportMessage[]>;
104
+ /**
105
+ * Connect to WebSocket
106
+ */
107
+ connectWebSocket(chatId: string, sessionId: string, onMessage?: (message: WebSocketMessage) => void, onConnectionChange?: (connected: boolean) => void, onClose?: (event: CloseEvent) => void): void;
108
+ /**
109
+ * Send message via WebSocket
110
+ */
111
+ sendMessageViaWebSocket(message: string): boolean;
112
+ /**
113
+ * Send typing indicator via WebSocket
114
+ */
115
+ sendTypingIndicator(type: "typing_start" | "typing_stop"): boolean;
116
+ /**
117
+ * Start ping interval to keep connection alive
118
+ */
119
+ private startPingInterval;
120
+ /**
121
+ * Stop ping interval
122
+ */
123
+ private stopPingInterval;
124
+ /**
125
+ * Disconnect WebSocket
126
+ */
127
+ disconnectWebSocket(): void;
128
+ /**
129
+ * Check if WebSocket is connected
130
+ */
131
+ isWebSocketConnected(): boolean;
132
+ /**
133
+ * Remove message handler
134
+ */
135
+ removeMessageHandler(handler: (message: WebSocketMessage) => void): void;
136
+ /**
137
+ * Remove connection handler
138
+ */
139
+ removeConnectionHandler(handler: (connected: boolean) => void): void;
140
+ }
141
+ export declare function getChatService(config?: ChatServiceConfig): ChatService;
142
+ export declare function createChatService(config: ChatServiceConfig): ChatService;
143
+ export {};
144
+ //# sourceMappingURL=chatService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chatService.d.ts","sourceRoot":"","sources":["../../src/services/chatService.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,cAAc;IAC7B,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,WAAW,EAAE,UAAU,GAAG,OAAO,CAAC;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,QAAQ;IACvB,MAAM,EAAE,SAAS,GAAG,QAAQ,CAAC;IAC7B,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,SAAS,GAAG,WAAW,GAAG,OAAO,GAAG,cAAc,GAAG,aAAa,GAAG,eAAe,GAAG,gBAAgB,GAAG,eAAe,GAAG,YAAY,GAAG,MAAM,GAAG,MAAM,CAAC;IACjK,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC;IACnC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,SAAS,GAAG,QAAQ,GAAG,UAAU,GAAG,OAAO,CAAC;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,MAAM,EAAG,eAAe,CAAU;gBACtB,OAAO,SAAkB;CAItC;AAED,MAAM,WAAW,iBAAiB;IAChC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,uBAAuB;IACtC,mBAAmB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACpC,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAUD,cAAM,WAAW;IACf,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,KAAK,CAAU;IACvB,OAAO,CAAC,EAAE,CAA0B;IACpC,OAAO,CAAC,mBAAmB,CAAK;IAChC,OAAO,CAAC,oBAAoB,CAAK;IACjC,OAAO,CAAC,gBAAgB,CAA+B;IACvD,OAAO,CAAC,YAAY,CAA+B;IACnD,OAAO,CAAC,aAAa,CAAuB;IAC5C,OAAO,CAAC,gBAAgB,CAAuB;IAC/C,OAAO,CAAC,eAAe,CAAuD;IAC9E,OAAO,CAAC,kBAAkB,CAAgD;IAC1E,OAAO,CAAC,cAAc,CAAuC;gBAEjD,MAAM,GAAE,iBAAsB;IAO1C;;;;;;OAMG;IACG,gBAAgB,CACpB,mBAAmB,CAAC,EAAE,MAAM,GAAG,IAAI,EACnC,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,EAC5B,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,EAC7B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,GAC7B,OAAO,CAAC,kBAAkB,CAAC;IAuD9B;;;;;;;;;OASG;IACG,cAAc,CAClB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,MAAM,EACf,mBAAmB,CAAC,EAAE,MAAM,GAAG,IAAI,EACnC,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,EAC5B,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,EAC7B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,GAC7B,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAkElD;;OAEG;IACG,kBAAkB,CACtB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,cAAc,CAAC;IA4D1B;;;;;;;;;;OAUG;IACG,qBAAqB,CACzB,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,EAC9B,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,EACjC,mBAAmB,CAAC,EAAE,MAAM,GAAG,IAAI,EACnC,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,EAC5B,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,EAC7B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,GAC7B,OAAO,CAAC,kBAAkB,CAAC;IAqB9B;;OAEG;IACG,kBAAkB,CACtB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,cAAc,EAAE,CAAC;IA0C5B;;OAEG;IACH,gBAAgB,CACd,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,IAAI,EAC/C,kBAAkB,CAAC,EAAE,CAAC,SAAS,EAAE,OAAO,KAAK,IAAI,EACjD,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,GACpC,IAAI;IA4IP;;OAEG;IACH,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO;IAmBjD;;OAEG;IACH,mBAAmB,CAAC,IAAI,EAAE,cAAc,GAAG,aAAa,GAAG,OAAO;IAkBlE;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAazB;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAOxB;;OAEG;IACH,mBAAmB,IAAI,IAAI;IAqB3B;;OAEG;IACH,oBAAoB,IAAI,OAAO;IAI/B;;OAEG;IACH,oBAAoB,CAAC,OAAO,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,IAAI,GAAG,IAAI;IAIxE;;OAEG;IACH,uBAAuB,CAAC,OAAO,EAAE,CAAC,SAAS,EAAE,OAAO,KAAK,IAAI,GAAG,IAAI;CAGrE;AAKD,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,iBAAiB,GAAG,WAAW,CAKtE;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,iBAAiB,GAAG,WAAW,CAExE"}
@@ -17,6 +17,7 @@ export interface ChatResponse {
17
17
  source: string;
18
18
  timestamp: string;
19
19
  richContent?: any;
20
+ handoff?: boolean;
20
21
  }
21
22
  /**
22
23
  * Create a new Dialogflow session
@@ -1 +1 @@
1
- {"version":3,"file":"dialogflowClient.d.ts","sourceRoot":"","sources":["../../src/services/dialogflowClient.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,iBAAiB,CAAC,EAAE,GAAG,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,GAAG,CAAC;CACnB;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,GAAG,CAAC;CACnB;AAiKD;;;;GAIG;AACH,wBAAsB,uBAAuB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,eAAe,CAAC,CA0EhG;AAED;;;;;;GAMG;AACH,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,gBAAgB,GACvB,OAAO,CAAC,YAAY,CAAC,CAyFvB"}
1
+ {"version":3,"file":"dialogflowClient.d.ts","sourceRoot":"","sources":["../../src/services/dialogflowClient.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,iBAAiB,CAAC,EAAE,GAAG,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,GAAG,CAAC;CACnB;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,GAAG,CAAC;IAClB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAiKD;;;;GAIG;AACH,wBAAsB,uBAAuB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,eAAe,CAAC,CA0EhG;AAED;;;;;;GAMG;AACH,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,gBAAgB,GACvB,OAAO,CAAC,YAAY,CAAC,CAqHvB"}
@@ -0,0 +1,13 @@
1
+ declare class ChatSessionManager {
2
+ private sessionId;
3
+ constructor();
4
+ loadSessionId(): string | null;
5
+ saveSessionId(sessionId: string | null): void;
6
+ updateSessionFromResponse(responseData: any): void;
7
+ getSessionId(): string;
8
+ getSessionHeader(): Record<string, string>;
9
+ }
10
+ export declare function getSessionManager(): ChatSessionManager;
11
+ export declare function createSessionManager(): ChatSessionManager;
12
+ export default ChatSessionManager;
13
+ //# sourceMappingURL=sessionManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sessionManager.d.ts","sourceRoot":"","sources":["../../src/services/sessionManager.ts"],"names":[],"mappings":"AAIA,cAAM,kBAAkB;IACtB,OAAO,CAAC,SAAS,CAAuB;;IAMxC,aAAa,IAAI,MAAM,GAAG,IAAI;IAO9B,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;IAW7C,yBAAyB,CAAC,YAAY,EAAE,GAAG,GAAG,IAAI;IAOlD,YAAY,IAAI,MAAM;IAItB,gBAAgB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;CAK3C;AAKD,wBAAgB,iBAAiB,IAAI,kBAAkB,CAKtD;AAED,wBAAgB,oBAAoB,IAAI,kBAAkB,CAEzD;AAED,eAAe,kBAAkB,CAAC"}
package/dist/styles.css CHANGED
@@ -7,7 +7,7 @@
7
7
  position: fixed;
8
8
  bottom: 20px;
9
9
  right: 90px;
10
- background: linear-gradient(135deg, #2d7a4f 0%, #1f5937 100%);
10
+ background: linear-gradient(135deg, #091e3e 0%, #091e3e 100%);
11
11
  color: white;
12
12
  padding: 20px;
13
13
  border-radius: 12px;
@@ -90,7 +90,7 @@
90
90
  width: 60px;
91
91
  height: 60px;
92
92
  border-radius: 50%;
93
- background: linear-gradient(135deg, #2d7a4f 0%, #1f5937 100%);
93
+ background: linear-gradient(135deg, #091e3e 0%, #091e3e 100%);
94
94
  color: white;
95
95
  border: none;
96
96
  cursor: pointer;
@@ -142,7 +142,7 @@
142
142
 
143
143
  /* Chat Header */
144
144
  .custom-chat-header {
145
- background: linear-gradient(135deg, #2d7a4f 0%, #1f5937 100%);
145
+ background: #091E3E;
146
146
  color: white;
147
147
  padding: 20px;
148
148
  display: flex;
@@ -165,6 +165,40 @@
165
165
  font-size: 12px;
166
166
  opacity: 0.9;
167
167
  }
168
+
169
+ .custom-mode-indicator {
170
+ font-size: 11px;
171
+ margin-left: 4px;
172
+ opacity: 0.85;
173
+ }
174
+
175
+ .custom-mode-badge {
176
+ font-size: 10px;
177
+ margin-top: 6px;
178
+ padding: 4px 8px;
179
+ background: rgba(255, 255, 255, 0.15);
180
+ border-radius: 12px;
181
+ display: inline-block;
182
+ font-weight: 500;
183
+ letter-spacing: 0.5px;
184
+ }
185
+
186
+ .custom-agent-info {
187
+ font-size: 11px;
188
+ margin-top: 4px;
189
+ opacity: 0.9;
190
+ display: flex;
191
+ align-items: center;
192
+ gap: 4px;
193
+ }
194
+
195
+ .custom-agent-label {
196
+ opacity: 0.8;
197
+ }
198
+
199
+ .custom-agent-name {
200
+ font-weight: 500;
201
+ }
168
202
 
169
203
  .custom-chat-close-btn {
170
204
  background: none;
@@ -264,6 +298,10 @@
264
298
  align-self: flex-start;
265
299
  }
266
300
 
301
+ .custom-message-agent {
302
+ align-self: flex-start;
303
+ }
304
+
267
305
  .custom-message-content {
268
306
  padding: 12px 16px;
269
307
  border-radius: 16px;
@@ -273,7 +311,7 @@
273
311
  }
274
312
 
275
313
  .custom-message-user .custom-message-content {
276
- background: linear-gradient(135deg, #2d7a4f 0%, #1f5937 100%);
314
+ background: #091E3E;
277
315
  color: white;
278
316
  border-bottom-right-radius: 4px;
279
317
  }
@@ -285,6 +323,13 @@
285
323
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
286
324
  }
287
325
 
326
+ .custom-message-agent .custom-message-content {
327
+ background: white;
328
+ color: #333;
329
+ border-bottom-left-radius: 4px;
330
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
331
+ }
332
+
288
333
  .custom-message-time {
289
334
  font-size: 10px;
290
335
  color: #999;
@@ -308,8 +353,8 @@
308
353
 
309
354
  .custom-chip-button {
310
355
  background: white;
311
- border: 1.5px solid #2d7a4f;
312
- color: #2d7a4f;
356
+ border: 1.5px solid #091e3e;
357
+ color: #091e3e;
313
358
  padding: 8px 16px;
314
359
  border-radius: 20px;
315
360
  font-size: 13px;
@@ -321,7 +366,7 @@
321
366
  }
322
367
 
323
368
  .custom-chip-button:hover {
324
- background: linear-gradient(135deg, #2d7a4f 0%, #1f5937 100%);
369
+ background: linear-gradient(135deg, #091e3e 0%, #091e3e 100%);
325
370
  color: white;
326
371
  transform: translateY(-1px);
327
372
  box-shadow: 0 2px 6px rgba(45, 122, 79, 0.3);
@@ -372,6 +417,44 @@
372
417
  opacity: 1;
373
418
  }
374
419
  }
420
+
421
+ /* Agent Typing Indicator */
422
+ .custom-agent-typing-indicator {
423
+ display: flex;
424
+ align-items: center;
425
+ gap: 8px;
426
+ padding: 8px 16px;
427
+ margin: 4px 0;
428
+ color: #666;
429
+ font-size: 14px;
430
+ font-style: italic;
431
+ }
432
+
433
+ .custom-typing-dots {
434
+ display: inline-flex;
435
+ gap: 2px;
436
+ }
437
+
438
+ .custom-typing-dots span {
439
+ display: inline-block;
440
+ width: 4px;
441
+ height: 4px;
442
+ border-radius: 50%;
443
+ background-color: #666;
444
+ animation: customTypingBounce 1.4s infinite ease-in-out;
445
+ }
446
+
447
+ .custom-typing-dots span:nth-child(2) {
448
+ animation-delay: -0.16s;
449
+ }
450
+
451
+ .custom-typing-dots span:nth-child(3) {
452
+ animation-delay: -0.32s;
453
+ }
454
+
455
+ .custom-typing-text {
456
+ color: #666;
457
+ }
375
458
 
376
459
  /* Chat Input Form */
377
460
  .custom-chat-input-form {
@@ -382,6 +465,47 @@
382
465
  gap: 8px;
383
466
  flex-shrink: 0;
384
467
  }
468
+
469
+ /* Resolved (terminal) banner */
470
+ .custom-chat-resolved-banner {
471
+ display: flex;
472
+ align-items: center;
473
+ justify-content: space-between;
474
+ gap: 12px;
475
+ padding: 12px 16px;
476
+ border-top: 1px solid #e0e0e0;
477
+ background: #f6f8ff;
478
+ color: #1f2a44;
479
+ flex-shrink: 0;
480
+ }
481
+
482
+ .custom-chat-resolved-text {
483
+ flex: 1;
484
+ font-size: 13px;
485
+ line-height: 1.35;
486
+ }
487
+
488
+ .custom-chat-resolved-btn {
489
+ background: #091e3e;
490
+ color: white;
491
+ border: none;
492
+ border-radius: 10px;
493
+ padding: 10px 12px;
494
+ font-size: 12px;
495
+ font-weight: 600;
496
+ cursor: pointer;
497
+ transition: transform 0.15s, opacity 0.15s;
498
+ flex-shrink: 0;
499
+ }
500
+
501
+ .custom-chat-resolved-btn:hover:not(:disabled) {
502
+ transform: scale(1.02);
503
+ }
504
+
505
+ .custom-chat-resolved-btn:disabled {
506
+ opacity: 0.6;
507
+ cursor: not-allowed;
508
+ }
385
509
 
386
510
  .custom-chat-input {
387
511
  flex: 1;
@@ -395,7 +519,7 @@
395
519
  }
396
520
 
397
521
  .custom-chat-input:focus {
398
- border-color: #2d7a4f;
522
+ border-color: #091e3e;
399
523
  }
400
524
 
401
525
  .custom-chat-input:disabled {
@@ -407,7 +531,7 @@
407
531
  width: 44px;
408
532
  height: 44px;
409
533
  border-radius: 50%;
410
- background: linear-gradient(135deg, #2d7a4f 0%, #1f5937 100%);
534
+ background: #091e3e;
411
535
  color: white;
412
536
  border: none;
413
537
  cursor: pointer;
package/dist/types.d.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  export type { DialogflowConfig, SessionResponse, ChatResponse, } from './services/dialogflowClient';
2
+ export type { SupportChatSession, SupportMessage, ChatInfo, WebSocketMessage, ChatServiceConfig, } from './services/chatService';
2
3
  export type { ChatWidgetProps } from './components/ChatWidget';
4
+ export type { ChatMode, UseChatModeReturn } from './hooks/useChatMode';
3
5
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AACA,YAAY,EACV,gBAAgB,EAChB,eAAe,EACf,YAAY,GACb,MAAM,6BAA6B,CAAC;AAGrC,YAAY,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AACA,YAAY,EACV,gBAAgB,EAChB,eAAe,EACf,YAAY,GACb,MAAM,6BAA6B,CAAC;AAErC,YAAY,EACV,kBAAkB,EAClB,cAAc,EACd,QAAQ,EACR,gBAAgB,EAChB,iBAAiB,GAClB,MAAM,wBAAwB,CAAC;AAGhC,YAAY,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAG/D,YAAY,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC"}
@@ -0,0 +1,31 @@
1
+ export interface DialogflowResponse {
2
+ queryResult?: {
3
+ responseMessages?: any[];
4
+ fulfillmentText?: string;
5
+ parameters?: {
6
+ fields?: {
7
+ [key: string]: any;
8
+ };
9
+ };
10
+ intent?: {
11
+ displayName?: string;
12
+ };
13
+ };
14
+ [key: string]: any;
15
+ }
16
+ export interface ProcessedDialogflowResponse {
17
+ response: string;
18
+ richContent?: any;
19
+ handoff: boolean;
20
+ timestamp: string;
21
+ }
22
+ /**
23
+ * Check if Dialogflow response contains handoff trigger
24
+ * Handoff is triggered when response contains {"handoff": true}
25
+ */
26
+ export declare function checkForHandoff(response: DialogflowResponse): boolean;
27
+ /**
28
+ * Process Dialogflow response and extract relevant information
29
+ */
30
+ export declare function processDialogflowResponse(response: DialogflowResponse): ProcessedDialogflowResponse;
31
+ //# sourceMappingURL=dialogflowHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dialogflowHandler.d.ts","sourceRoot":"","sources":["../../src/utils/dialogflowHandler.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,kBAAkB;IACjC,WAAW,CAAC,EAAE;QACZ,gBAAgB,CAAC,EAAE,GAAG,EAAE,CAAC;QACzB,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,UAAU,CAAC,EAAE;YACX,MAAM,CAAC,EAAE;gBACP,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;aACpB,CAAC;SACH,CAAC;QACF,MAAM,CAAC,EAAE;YACP,WAAW,CAAC,EAAE,MAAM,CAAC;SACtB,CAAC;KACH,CAAC;IACF,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,GAAG,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,kBAAkB,GAAG,OAAO,CAqCrE;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,kBAAkB,GAC3B,2BAA2B,CA4B7B"}
package/package.json CHANGED
@@ -1,36 +1,39 @@
1
1
  {
2
2
  "name": "@blockspark/chat-widget",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "BlockSpark AI Chat Widget - A reusable React chat component",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.esm.js",
7
7
  "types": "dist/index.d.ts",
8
8
  "files": [
9
- "dist",
10
- "README.md"
9
+ "dist",
10
+ "README.md"
11
11
  ],
12
12
  "scripts": {
13
- "build": "webpack --mode production",
14
- "dev": "webpack --mode development --watch",
15
- "prepublishOnly": "npm run build"
13
+ "build": "webpack --mode production",
14
+ "dev": "webpack --mode development --watch",
15
+ "prepublishOnly": "npm run build"
16
16
  },
17
17
  "peerDependencies": {
18
- "react": "^16.8.0 || ^17.0.0 || ^18.0.0",
19
- "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
18
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0",
19
+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
20
20
  },
21
21
  "dependencies": {
22
- "jose": "^5.0.0"
22
+ "jose": "^5.0.0",
23
+ "linkify-react": "^4.3.2",
24
+ "linkifyjs": "^4.3.2"
23
25
  },
24
26
  "devDependencies": {
25
- "@types/react": "^18.3.5",
26
- "@types/react-dom": "^18.3.0",
27
- "typescript": "^5.6.2",
28
- "webpack": "^5.94.0",
29
- "webpack-cli": "^5.1.4",
30
- "ts-loader": "^9.5.1",
31
- "css-loader": "^7.1.2",
32
- "style-loader": "^4.0.0",
33
- "mini-css-extract-plugin": "^2.9.0"
27
+ "@types/react": "^18.3.5",
28
+ "@types/react-dom": "^18.3.0",
29
+ "css-loader": "^7.1.2",
30
+ "dotenv-webpack": "^8.1.1",
31
+ "mini-css-extract-plugin": "^2.9.0",
32
+ "style-loader": "^4.0.0",
33
+ "ts-loader": "^9.5.1",
34
+ "typescript": "^5.6.2",
35
+ "webpack": "^5.94.0",
36
+ "webpack-cli": "^5.1.4"
34
37
  },
35
38
  "keywords": [
36
39
  "chat",
@@ -45,4 +48,4 @@
45
48
  "publishConfig": {
46
49
  "access": "public"
47
50
  }
48
- }
51
+ }