bitmax-crm-widget 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,415 @@
1
+ # Chat CRM Widget
2
+
3
+ Universal chat widget that works on **any website** - React, Vue, HTML, WordPress, Shopify, and more!
4
+
5
+ ## ✨ Features
6
+
7
+ - 🚀 **Universal**: Works with React, Vue, Angular, HTML, WordPress, etc.
8
+ - 👤 **Smart User Detection**: Automatically supports both logged-in users and guests
9
+ - 🎨 **Fully Customizable**: Colors, position, theme, welcome message
10
+ - 📱 **Responsive**: Mobile-first design
11
+ - 🌙 **Dark Mode**: Built-in dark theme support
12
+ - 🔔 **Notifications**: Unread message badges and sound alerts
13
+ - ⚡ **Real-time**: Socket.IO powered instant messaging
14
+ - 🔒 **Secure**: API key based authentication
15
+ - 📦 **Lightweight**: < 50KB gzipped
16
+
17
+ ---
18
+
19
+ ## 📦 Installation
20
+
21
+ ### Option 1: NPM (for React/Vue/Node projects)
22
+
23
+ ```bash
24
+ npm install @bitmax-crm/widget
25
+ ```
26
+
27
+ ### Option 2: CDN (for HTML/WordPress/any website)
28
+
29
+ ```html
30
+ <script src="https://unpkg.com/@bitmax-crm/widget/dist/chat-widget.min.js"></script>
31
+ ```
32
+
33
+ ---
34
+
35
+ ## 🚀 Quick Start
36
+
37
+ ### React / MERN Application
38
+
39
+ ```jsx
40
+ import { ChatCRMWidget } from '@bitmax-crm/widget';
41
+
42
+ function App() {
43
+ return (
44
+ <>
45
+ {/* Your app content */}
46
+
47
+ <ChatCRMWidget
48
+ apiKey="your_api_key_here"
49
+ apiUrl="https://chat-crm-backend-7mzo.onrender.com"
50
+ primaryColor="#4F46E5"
51
+ />
52
+ </>
53
+ );
54
+ }
55
+ ```
56
+
57
+ ### HTML / Vanilla JavaScript
58
+
59
+ ```html
60
+ <!DOCTYPE html>
61
+ <html>
62
+ <head>
63
+ <title>My Website</title>
64
+ </head>
65
+ <body>
66
+ <!-- Your website content -->
67
+
68
+ <!-- Chat Widget -->
69
+ <script src="https://unpkg.com/@bitmax-crm/widget/dist/chat-widget.min.js"></script>
70
+ <script>
71
+ ChatCRMWidget.init({
72
+ apiKey: 'your_api_key_here',
73
+ apiUrl: 'https://chat-crm-backend-7mzo.onrender.com',
74
+ primaryColor: '#4F46E5'
75
+ });
76
+ </script>
77
+ </body>
78
+ </html>
79
+ ```
80
+
81
+ ---
82
+
83
+ ## 👤 User Detection (Logged-in vs Guest)
84
+
85
+ ### Automatic Guest Users
86
+
87
+ By default, all visitors are treated as guests:
88
+
89
+ ```jsx
90
+ <ChatCRMWidget apiKey="your_key" />
91
+ ```
92
+
93
+ **What your agents see:**
94
+ - Name: "Guest User"
95
+ - Email: Not provided
96
+ - Status: Guest
97
+
98
+ ---
99
+
100
+ ### Logged-in Users (Pre-fill Data)
101
+
102
+ Pass user data for logged-in customers:
103
+
104
+ ```jsx
105
+ import { ChatCRMWidget } from '@bitmax-crm/widget';
106
+ import { useAuth } from './context/AuthContext'; // Your auth system
107
+
108
+ function App() {
109
+ const { user, isLoggedIn } = useAuth();
110
+
111
+ return (
112
+ <ChatCRMWidget
113
+ apiKey="your_api_key"
114
+ userData={isLoggedIn ? {
115
+ name: user.name,
116
+ email: user.email,
117
+ phone: user.phone,
118
+ userId: user.id // Your internal user ID
119
+ } : null}
120
+ />
121
+ );
122
+ }
123
+ ```
124
+
125
+ **What your agents see:**
126
+ - Name: "John Doe"
127
+ - Email: "john@example.com"
128
+ - Phone: "+1234567890"
129
+ - User ID: "USER_12345"
130
+
131
+ ---
132
+
133
+ ## ⚙️ Configuration Options
134
+
135
+ | Option | Type | Default | Description |
136
+ |--------|------|---------|-------------|
137
+ | `apiKey` | string | **Required** | Your organization's API key |
138
+ | `apiUrl` | string | Backend URL | Chat CRM backend URL |
139
+ | `primaryColor` | string | `#4F46E5` | Brand color (hex) |
140
+ | `position` | string | `bottom-right` | Widget position |
141
+ | `userData` | object | `null` | Logged-in user data |
142
+ | `welcomeMessage` | string | Welcome text | First message shown |
143
+ | `companyName` | string | `Support` | Header title |
144
+ | `autoOpen` | boolean | `false` | Auto-open on load |
145
+ | `showNotifications` | boolean | `true` | Show unread badges |
146
+ | `playSound` | boolean | `false` | Play notification sound |
147
+ | `theme` | string | `light` | `light`, `dark`, or `auto` |
148
+ | `zIndex` | number | `9999` | CSS z-index |
149
+
150
+ ### Position Options
151
+
152
+ - `bottom-right` (default)
153
+ - `bottom-left`
154
+ - `top-right`
155
+ - `top-left`
156
+
157
+ ---
158
+
159
+ ## 🎨 Customization Examples
160
+
161
+ ### Custom Branding
162
+
163
+ ```jsx
164
+ <ChatCRMWidget
165
+ apiKey="bitmax_key"
166
+ primaryColor="#FF6B35"
167
+ companyName="Bitmax Support"
168
+ welcomeMessage="👋 Hi! Need help with Bitmax?"
169
+ position="bottom-left"
170
+ />
171
+ ```
172
+
173
+ ### Dark Theme
174
+
175
+ ```jsx
176
+ <ChatCRMWidget
177
+ apiKey="your_key"
178
+ theme="dark"
179
+ primaryColor="#8B5CF6"
180
+ />
181
+ ```
182
+
183
+ ### Auto-open with Sound
184
+
185
+ ```jsx
186
+ <ChatCRMWidget
187
+ apiKey="your_key"
188
+ autoOpen={true}
189
+ playSound={true}
190
+ showNotifications={true}
191
+ />
192
+ ```
193
+
194
+ ---
195
+
196
+ ## 🌐 Platform-Specific Integration
197
+
198
+ ### Next.js
199
+
200
+ ```jsx
201
+ // components/ChatWidget.js
202
+ 'use client'; // For Next.js 13+ App Router
203
+
204
+ import { ChatCRMWidget } from '@chat-crm/widget';
205
+
206
+ export default function ChatWidget() {
207
+ return (
208
+ <ChatCRMWidget
209
+ apiKey={process.env.NEXT_PUBLIC_CHAT_API_KEY}
210
+ />
211
+ );
212
+ }
213
+ ```
214
+
215
+ ```jsx
216
+ // app/layout.js
217
+ import ChatWidget from '@/components/ChatWidget';
218
+
219
+ export default function RootLayout({ children }) {
220
+ return (
221
+ <html>
222
+ <body>
223
+ {children}
224
+ <ChatWidget />
225
+ </body>
226
+ </html>
227
+ );
228
+ }
229
+ ```
230
+
231
+ ### Vue.js
232
+
233
+ ```vue
234
+ <template>
235
+ <div id="app">
236
+ <!-- Your app content -->
237
+ <ChatCRMWidget
238
+ :apiKey="chatApiKey"
239
+ :userData="currentUser"
240
+ />
241
+ </div>
242
+ </template>
243
+
244
+ <script>
245
+ import { ChatCRMWidget } from '@bitmax-crm/widget';
246
+
247
+ export default {
248
+ components: { ChatCRMWidget },
249
+ data() {
250
+ return {
251
+ chatApiKey: process.env.VUE_APP_CHAT_KEY,
252
+ currentUser: null
253
+ };
254
+ }
255
+ };
256
+ </script>
257
+ ```
258
+
259
+ ### WordPress
260
+
261
+ Add to your theme's `footer.php`:
262
+
263
+ ```php
264
+ <!-- Before </body> tag -->
265
+ <script src="https://unpkg.com/@bitmax-crm/widget/dist/chat-widget.min.js"></script>
266
+ <script>
267
+ ChatCRMWidget.init({
268
+ apiKey: '<?php echo get_option('chat_crm_api_key'); ?>',
269
+ <?php if (is_user_logged_in()): ?>
270
+ userData: {
271
+ name: '<?php echo wp_get_current_user()->display_name; ?>',
272
+ email: '<?php echo wp_get_current_user()->user_email; ?>',
273
+ userId: '<?php echo get_current_user_id(); ?>'
274
+ }
275
+ <?php endif; ?>
276
+ });
277
+ </script>
278
+ ```
279
+
280
+ ---
281
+
282
+ ## 📱 Mobile Apps
283
+
284
+ ### React Native (WebView)
285
+
286
+ ```jsx
287
+ import { WebView } from 'react-native-webview';
288
+
289
+ const injectedJS = `
290
+ (function() {
291
+ const script = document.createElement('script');
292
+ script.src = 'https://unpkg.com/@bitmax-crm/widget/dist/chat-widget.min.js';
293
+ script.onload = function() {
294
+ ChatCRMWidget.init({
295
+ apiKey: 'your_key',
296
+ userData: ${JSON.stringify(userData)}
297
+ });
298
+ };
299
+ document.body.appendChild(script);
300
+ })();
301
+ `;
302
+
303
+ <WebView
304
+ source={{ uri: 'https://yourwebsite.com' }}
305
+ injectedJavaScript={injectedJS}
306
+ />
307
+ ```
308
+
309
+ ---
310
+
311
+ ## 🔐 Security Best Practices
312
+
313
+ ### Environment Variables
314
+
315
+ ```env
316
+ # .env
317
+ VITE_CHAT_API_KEY=your_api_key_here
318
+ VITE_CHAT_API_URL=https://chat-crm-backend-7mzo.onrender.com
319
+ ```
320
+
321
+ ```jsx
322
+ <ChatCRMWidget
323
+ apiKey={import.meta.env.VITE_CHAT_API_KEY}
324
+ apiUrl={import.meta.env.VITE_CHAT_API_URL}
325
+ />
326
+ ```
327
+
328
+ ### Domain Restrictions
329
+
330
+ Contact your Chat CRM admin to whitelist only your domains.
331
+
332
+ ---
333
+
334
+ ## 🧪 Testing
335
+
336
+ ### Development Mode
337
+
338
+ ```jsx
339
+ <ChatCRMWidget
340
+ apiKey="test_key"
341
+ apiUrl="http://localhost:5000"
342
+ autoOpen={true} // Opens automatically for testing
343
+ />
344
+ ```
345
+
346
+ ### Check Console
347
+
348
+ Open browser DevTools → Console:
349
+ - ✅ "Connected to Chat CRM" = Working
350
+ - ❌ Errors = Check API key and URL
351
+
352
+ ---
353
+
354
+ ## 📊 What Your Agents See
355
+
356
+ When a user chats via the widget, your CRM dashboard shows:
357
+
358
+ ### Guest User:
359
+ ```
360
+ 📋 New Query
361
+ Name: Guest User
362
+ Email: Not provided
363
+ Message: "How much does it cost?"
364
+ Organization: [Your Organization]
365
+ ```
366
+
367
+ ### Logged-in User:
368
+ ```
369
+ 📋 New Query
370
+ Name: John Doe ✅
371
+ Email: john@example.com ✅
372
+ Phone: +1234567890 ✅
373
+ User ID: USER_12345
374
+ Message: "Where is my order?"
375
+ Organization: [Your Organization]
376
+ ```
377
+
378
+ ---
379
+
380
+ ## 🔄 Updates
381
+
382
+ Widget auto-updates when you refresh the page (CDN version).
383
+
384
+ For NPM version:
385
+ ```bash
386
+ npm update @bitmax-crm/widget
387
+ ```
388
+
389
+ ---
390
+
391
+ ## 📝 License
392
+
393
+ MIT License - Free to use in commercial projects
394
+
395
+ ---
396
+
397
+ ## 🆘 Support
398
+
399
+ - Documentation: https://docs.chat-crm.com
400
+ - Issues: https://github.com/your-org/chat-crm-widget/issues
401
+ - Email: support@chat-crm.com
402
+
403
+ ---
404
+
405
+ ## 🎉 That's It!
406
+
407
+ You now have a professional chat widget supporting both **guest users** and **logged-in customers**!
408
+
409
+ **Test it:**
410
+ 1. Add widget to your site
411
+ 2. Open it and send a message
412
+ 3. Check your CRM dashboard - message appears there!
413
+ 4. Reply from CRM - user sees it instantly!
414
+
415
+ Enjoy! 🚀
@@ -0,0 +1,4 @@
1
+ !function(){"use strict";function t(t,e,n,s,i,r,o){try{var a=t[r](o),c=a.value}catch(t){return void n(t)}a.done?e(c):Promise.resolve(c).then(s,i)}function e(e){return function(){var n=this,s=arguments;return new Promise(function(i,r){var o=e.apply(n,s);function a(e){t(o,i,r,a,c,"next",e)}function c(e){t(o,i,r,a,c,"throw",e)}a(void 0)})}}function n(t,e,n){return e&&function(t,e){for(var n=0;n<e.length;n++){var s=e[n];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,c(s.key),s)}}(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function s(t,e,n){return(e=c(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function i(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,s)}return n}function r(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?i(Object(n),!0).forEach(function(e){s(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function o(){
2
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
3
+ var t,e,n="function"==typeof Symbol?Symbol:{},s=n.iterator||"@@iterator",i=n.toStringTag||"@@toStringTag";function r(n,s,i,r){var o=s&&s.prototype instanceof h?s:h,u=Object.create(o.prototype);return a(u,"_invoke",function(n,s,i){var r,o,a,h=0,u=i||[],p=!1,l={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,n){return r=e,o=0,a=t,l.n=n,c}};function d(n,s){for(o=n,a=s,e=0;!p&&h&&!i&&e<u.length;e++){var i,r=u[e],d=l.p,f=r[2];n>3?(i=f===s)&&(a=r[(o=r[4])?5:(o=3,3)],r[4]=r[5]=t):r[0]<=d&&((i=n<2&&d<r[1])?(o=0,l.v=s,l.n=r[1]):d<f&&(i=n<3||r[0]>s||s>f)&&(r[4]=n,r[5]=s,l.n=f,o=0))}if(i||n>1)return c;throw p=!0,s}return function(i,u,f){if(h>1)throw TypeError("Generator is already running");for(p&&1===u&&d(u,f),o=u,a=f;(e=o<2?t:a)||!p;){r||(o?o<3?(o>1&&(l.n=-1),d(o,a)):l.n=a:l.v=a);try{if(h=2,r){if(o||(i="next"),e=r[i]){if(!(e=e.call(r,a)))throw TypeError("iterator result is not an object");if(!e.done)return e;a=e.value,o<2&&(o=0)}else 1===o&&(e=r.return)&&e.call(r),o<2&&(a=TypeError("The iterator does not provide a '"+i+"' method"),o=1);r=t}else if((e=(p=l.n<0)?a:n.call(s,l))!==c)break}catch(e){r=t,o=1,a=e}finally{h=1}}return{value:e,done:p}}}(n,i,r),!0),u}var c={};function h(){}function u(){}function p(){}e=Object.getPrototypeOf;var l=[][s]?e(e([][s]())):(a(e={},s,function(){return this}),e),d=p.prototype=h.prototype=Object.create(l);function f(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,p):(t.__proto__=p,a(t,i,"GeneratorFunction")),t.prototype=Object.create(d),t}return u.prototype=p,a(d,"constructor",p),a(p,"constructor",u),u.displayName="GeneratorFunction",a(p,i,"GeneratorFunction"),a(d),a(d,i,"Generator"),a(d,s,function(){return this}),a(d,"toString",function(){return"[object Generator]"}),(o=function(){return{w:r,m:f}})()}function a(t,e,n,s){var i=Object.defineProperty;try{i({},"",{})}catch(t){i=0}a=function(t,e,n,s){function r(e,n){a(t,e,function(t){return this._invoke(e,n,t)})}e?i?i(t,e,{value:n,enumerable:!s,configurable:!s,writable:!s}):t[e]=n:(r("next",0),r("throw",1),r("return",2))},a(t,e,n,s)}function c(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var s=n.call(t,e);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}const h=Object.create(null);h.open="0",h.close="1",h.ping="2",h.pong="3",h.message="4",h.upgrade="5",h.noop="6";const u=Object.create(null);Object.keys(h).forEach(t=>{u[h[t]]=t});const p={type:"error",data:"parser error"},l="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),d="function"==typeof ArrayBuffer,f=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,m=({type:t,data:e},n,s)=>l&&e instanceof Blob?n?s(e):y(e,s):d&&(e instanceof ArrayBuffer||f(e))?n?s(e):y(new Blob([e]),s):s(h[t]+(e||"")),y=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function g(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let b;const v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)_[v.charCodeAt(t)]=t;const w="function"==typeof ArrayBuffer,k=(t,e)=>{if("string"!=typeof t)return{type:"message",data:O(t,e)};const n=t.charAt(0);if("b"===n)return{type:"message",data:E(t.substring(1),e)};return u[n]?t.length>1?{type:u[n],data:t.substring(1)}:{type:u[n]}:p},E=(t,e)=>{if(w){const n=(t=>{let e,n,s,i,r,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),u=new Uint8Array(h);for(e=0;e<a;e+=4)n=_[t.charCodeAt(e)],s=_[t.charCodeAt(e+1)],i=_[t.charCodeAt(e+2)],r=_[t.charCodeAt(e+3)],u[c++]=n<<2|s>>4,u[c++]=(15&s)<<4|i>>2,u[c++]=(3&i)<<6|63&r;return h})(t);return O(n,e)}return{base64:!0,data:t}},O=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,C=String.fromCharCode(30);function T(){return new TransformStream({transform(t,e){!function(t,e){l&&t.data instanceof Blob?t.data.arrayBuffer().then(g).then(e):d&&(t.data instanceof ArrayBuffer||f(t.data))?e(g(t.data)):m(t,!1,t=>{b||(b=new TextEncoder),e(b.encode(t))})}(t,n=>{const s=n.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,s)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(s))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),e.enqueue(n)})}})}let A;function S(t){return t.reduce((t,e)=>t+e.length,0)}function B(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let s=0;for(let i=0;i<e;i++)n[i]=t[0][s++],s===t[0].length&&(t.shift(),s=0);return t.length&&s<t[0].length&&(t[0]=t[0].slice(s)),n}function R(t){if(t)return function(t){for(var e in R.prototype)t[e]=R.prototype[e];return t}(t)}R.prototype.on=R.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},R.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},R.prototype.off=R.prototype.removeListener=R.prototype.removeAllListeners=R.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,s=this._callbacks["$"+t];if(!s)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i<s.length;i++)if((n=s[i])===e||n.fn===e){s.splice(i,1);break}return 0===s.length&&delete this._callbacks["$"+t],this},R.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(n){s=0;for(var i=(n=n.slice(0)).length;s<i;++s)n[s].apply(this,e)}return this},R.prototype.emitReserved=R.prototype.emit,R.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},R.prototype.hasListeners=function(t){return!!this.listeners(t).length};const x="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),N="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function L(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const I=N.setTimeout,P=N.clearTimeout;function j(t,e){e.useNativeTimers?(t.setTimeoutFn=I.bind(N),t.clearTimeoutFn=P.bind(N)):(t.setTimeoutFn=N.setTimeout.bind(N),t.clearTimeoutFn=N.clearTimeout.bind(N))}function q(t){return"string"==typeof t?function(t){let e=0,n=0;for(let s=0,i=t.length;s<i;s++)e=t.charCodeAt(s),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(s++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))}function D(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class U extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class M extends R{constructor(t){super(),this.writable=!1,j(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new U(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=k(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=function(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}(t);return e.length?"?"+e:""}}class F extends M{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const n=t.split(C),s=[];for(let t=0;t<n.length;t++){const i=k(n[t],e);if(s.push(i),"error"===i.type)break}return s})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const n=t.length,s=new Array(n);let i=0;t.forEach((t,r)=>{m(t,!1,t=>{s[r]=t,++i===n&&e(s.join(C))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=D()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let H=!1;try{H="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const V=H;function K(){}class z extends F{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class W extends R{constructor(t,e,n){super(),this.createRequest=t,j(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var t;const e=L(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=W.requestsCount++,W.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=K,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete W.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(W.requestsCount=0,W.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Y);else if("function"==typeof addEventListener){addEventListener("onpagehide"in N?"pagehide":"unload",Y,!1)}function Y(){for(let t in W.requests)W.requests.hasOwnProperty(t)&&W.requests[t].abort()}const G=function(){const t=J({xdomain:!1});return t&&null!==t.responseType}();function J(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||V))return new XMLHttpRequest}catch(t){}if(!e)try{return new(N[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const $="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Q extends M{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=$?{}:L(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],s=e===t.length-1;m(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}s&&x(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=D()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const X=N.WebSocket||N.MozWebSocket;const Z={websocket:class extends Q{createSocket(t,e,n){return $?new X(t,e,n):e?new X(t,e):new X(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends M{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=function(t,e){A||(A=new TextDecoder);const n=[];let s=0,i=-1,r=!1;return new TransformStream({transform(o,a){for(n.push(o);;){if(0===s){if(S(n)<1)break;const t=B(n,1);r=!(128&~t[0]),i=127&t[0],s=i<126?3:126===i?1:2}else if(1===s){if(S(n)<2)break;const t=B(n,2);i=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),s=3}else if(2===s){if(S(n)<8)break;const t=B(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),r=e.getUint32(0);if(r>Math.pow(2,21)-1){a.enqueue(p);break}i=r*Math.pow(2,32)+e.getUint32(4),s=3}else{if(S(n)<i)break;const t=B(n,i);a.enqueue(k(r?t:A.decode(t),e)),s=0}if(0===i||i>t){a.enqueue(p);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),s=T();s.readable.pipeTo(t.writable),this._writer=s.writable.getWriter();const i=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),i())}).catch(t=>{})};i();const r={type:"open"};this.query.sid&&(r.data=`{"sid":"${this.query.sid}"}`),this._writer.write(r).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],s=e===t.length-1;this._writer.write(n).then(()=>{s&&x(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends z{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=G&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new W(J,this.uri(),t)}}},tt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,et=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function nt(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),s=t.indexOf("]");-1!=n&&-1!=s&&(t=t.substring(0,n)+t.substring(n,s).replace(/:/g,";")+t.substring(s,t.length));let i=tt.exec(t||""),r={},o=14;for(;o--;)r[et[o]]=i[o]||"";return-1!=n&&-1!=s&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const n=/\/{2,9}/g,s=e.replace(n,"/").split("/");"/"!=e.slice(0,1)&&0!==e.length||s.splice(0,1);"/"==e.slice(-1)&&s.splice(s.length-1,1);return s}(0,r.path),r.queryKey=function(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,s){e&&(n[e]=s)}),n}(0,r.query),r}const st="function"==typeof addEventListener&&"function"==typeof removeEventListener,it=[];st&&addEventListener("offline",()=>{it.forEach(t=>t())},!1);class rt extends R{constructor(t,e){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const n=nt(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=nt(e.host).host);j(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},n=t.split("&");for(let t=0,s=n.length;t<s;t++){let s=n[t].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}(this.opts.query)),st&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},it.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&rt.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",rt.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const n=this.writeBuffer[e].data;if(n&&(t+=q(n)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,x(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,s){if("function"==typeof e&&(s=e,e=void 0),"function"==typeof n&&(s=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(rt.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),st&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=it.indexOf(this._offlineEventListener);-1!==t&&it.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}rt.protocol=4;class ot extends rt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;rt.priorWebsocketSuccess=!1;const s=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;rt.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function i(){n||(n=!0,h(),e.close(),e=null)}const r=t=>{const n=new Error("probe error: "+t);n.transport=e.name,i(),this.emitReserved("upgradeError",n)};function o(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&i()}const h=()=>{e.removeListener("open",s),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",s),e.once("error",r),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let at=class extends ot{constructor(t,e={}){const n="object"==typeof t?t:e;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(t=>Z[t]).filter(t=>!!t)),super(t,n)}};const ct="function"==typeof ArrayBuffer,ht=Object.prototype.toString,ut="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ht.call(Blob),pt="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ht.call(File);function lt(t){return ct&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||ut&&t instanceof Blob||pt&&t instanceof File}function dt(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(dt(t[e]))return!0;return!1}if(lt(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return dt(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&dt(t[e]))return!0;return!1}function ft(t){const e=[],n=t.data,s=t;return s.data=mt(n,e),s.attachments=e.length,{packet:s,buffers:e}}function mt(t,e){if(!t)return t;if(lt(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let s=0;s<t.length;s++)n[s]=mt(t[s],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=mt(t[s],e));return n}return t}function yt(t,e){return t.data=gt(t.data,e),delete t.attachments,t}function gt(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=gt(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=gt(t[n],e));return t}const bt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var vt;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(vt||(vt={}));function _t(t){return"[object Object]"===Object.prototype.toString.call(t)}class wt extends R{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===vt.BINARY_EVENT;n||e.type===vt.BINARY_ACK?(e.type=n?vt.EVENT:vt.ACK,this.reconstructor=new kt(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!lt(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(void 0===vt[n.type])throw new Error("unknown packet type "+n.type);if(n.type===vt.BINARY_EVENT||n.type===vt.BINARY_ACK){const s=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(s,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===t.charAt(e+1)){const s=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}n.nsp=t.substring(s,e)}else n.nsp="/";const s=t.charAt(e+1);if(""!==s&&Number(s)==s){const s=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(s,e+1))}if(t.charAt(++e)){const s=this.tryParse(t.substr(e));if(!wt.isPayloadValid(n.type,s))throw new Error("invalid payload");n.data=s}return n}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case vt.CONNECT:return _t(e);case vt.DISCONNECT:return void 0===e;case vt.CONNECT_ERROR:return"string"==typeof e||_t(e);case vt.EVENT:case vt.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===bt.indexOf(e[0]));case vt.ACK:case vt.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class kt{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=yt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Et=Object.freeze({__proto__:null,Decoder:wt,Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==vt.EVENT&&t.type!==vt.ACK||!dt(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===vt.EVENT?vt.BINARY_EVENT:vt.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==vt.BINARY_EVENT&&t.type!==vt.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=ft(t),n=this.encodeAsString(e.packet),s=e.buffers;return s.unshift(n),s}},get PacketType(){return vt},protocol:5});function Ot(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const Ct=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Tt extends R{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[Ot(t,"open",this.onopen.bind(this)),Ot(t,"packet",this.onpacket.bind(this)),Ot(t,"error",this.onerror.bind(this)),Ot(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,s,i;if(Ct.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const r={type:vt.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),r.id=t}const o=null===(s=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===s?void 0:s.writable,a=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(t,e){var n;const s=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===s)return void(this.acks[t]=e);const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},s),r=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((n,s)=>{const i=(t,e)=>t?s(t):n(e);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...s)=>{if(n!==this._queue[0])return;return null!==t?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...s)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:vt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case vt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case vt.EVENT:case vt.BINARY_EVENT:this.onevent(t);break;case vt.ACK:case vt.BINARY_ACK:this.onack(t);break;case vt.DISCONNECT:this.ondisconnect();break;case vt.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...s){n||(n=!0,e.packet({type:vt.ACK,id:t,data:s}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:vt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function At(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}At.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},At.prototype.reset=function(){this.attempts=0},At.prototype.setMin=function(t){this.ms=t},At.prototype.setMax=function(t){this.max=t},At.prototype.setJitter=function(t){this.jitter=t};class St extends R{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,j(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new At({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const s=e.parser||Et;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new at(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const s=Ot(e,"open",function(){n.onopen(),t&&t()}),i=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=Ot(e,"error",i);if(!1!==this._timeout){const t=this._timeout,n=this.setTimeoutFn(()=>{s(),i(new Error("timeout")),e.close()},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(s),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Ot(t,"ping",this.onping.bind(this)),Ot(t,"data",this.ondata.bind(this)),Ot(t,"error",this.onerror.bind(this)),Ot(t,"close",this.onclose.bind(this)),Ot(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){x(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Tt(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const t of e){if(this.nsps[t].active)return}this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Bt={};function Rt(t,e){"object"==typeof t&&(e=t,t=void 0);const n=function(t,e="",n){let s=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),s=nt(t)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+e,s.href=s.protocol+"://"+i+(n&&n.port===s.port?"":":"+s.port),s}(t,(e=e||{}).path||"/socket.io"),s=n.source,i=n.id,r=n.path,o=Bt[i]&&r in Bt[i].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new St(s,e):(Bt[i]||(Bt[i]=new St(s,e)),a=Bt[i]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}Object.assign(Rt,{Manager:St,Socket:Tt,io:Rt,connect:Rt}),function(){var t=document.createElement("style");t.textContent="/* Styles will be injected by Rollup */",document.head.appendChild(t);var s=function(){return n(function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.config={apiKey:e.apiKey||"",apiUrl:e.apiUrl||"https://chat-crm-backend-7mzo.onrender.com",primaryColor:e.primaryColor||"#4F46E5",position:e.position||"bottom-right",userData:e.userData||null,welcomeMessage:e.welcomeMessage||"👋 Welcome! How can we help you today?",companyName:e.companyName||"Support",autoOpen:e.autoOpen||!1,showNotifications:!1!==e.showNotifications,playSound:e.playSound||!1,theme:e.theme||"light",zIndex:e.zIndex||9999},this.state={isOpen:this.config.autoOpen,messages:[],isConnected:!1,isTyping:!1,agentName:"Support Agent",guestId:null,conversationId:null,unreadCount:0,socket:null},this.init()},[{key:"init",value:function(){this.createWidget(),this.attachEventListeners(),this.config.autoOpen&&this.openChat()}},{key:"getUserData",value:function(){return this.config.userData?{name:this.config.userData.name||"Guest User",email:this.config.userData.email||null,phone:this.config.userData.phone||null,userId:this.config.userData.userId||null}:{name:localStorage.getItem("chatGuestName")||"Guest User",email:localStorage.getItem("chatGuestEmail")||null,phone:localStorage.getItem("chatGuestPhone")||null,userId:localStorage.getItem("chatUserId")||null}}},{key:"createWidget",value:function(){var t=document.createElement("div");t.id="chat-crm-widget-root",t.className="crm-widget-container",t.style.zIndex=this.config.zIndex,t.innerHTML=this.getWidgetHTML(),document.body.appendChild(t)}},{key:"getWidgetHTML",value:function(){var t=this.getPositionClass();return'\n <button id="crm-chat-button" class="crm-chat-button '.concat(t,'" style="background-color: ').concat(this.config.primaryColor,'">\n <svg class="crm-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />\n </svg>\n <span id="crm-badge" class="crm-badge" style="display: none;">0</span>\n </button>\n\n <div id="crm-chat-window" class="crm-chat-window ').concat(t,'" style="display: none;">\n <div class="crm-header" style="background-color: ').concat(this.config.primaryColor,'">\n <div class="crm-header-content">\n <div class="crm-avatar">💬</div>\n <div>\n <h3 class="crm-title">').concat(this.config.companyName,'</h3>\n <div class="crm-status">\n <div id="crm-status-dot" class="crm-status-dot crm-offline"></div>\n <span id="crm-status-text">Connecting...</span>\n </div>\n </div>\n </div>\n <button id="crm-close-btn" class="crm-close-btn">\n <svg class="crm-icon-sm" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />\n </svg>\n </button>\n </div>\n\n <div id="crm-messages" class="crm-messages">\n <div class="crm-welcome-message">\n <p>').concat(this.config.welcomeMessage,'</p>\n </div>\n </div>\n\n <div class="crm-input-container">\n <div class="crm-input-wrapper">\n <textarea \n id="crm-input" \n class="crm-input" \n placeholder="Type your message..." \n rows="1"\n disabled\n ></textarea>\n <button id="crm-send-btn" class="crm-send-btn" style="background-color: ').concat(this.config.primaryColor,'" disabled>\n <svg class="crm-icon-sm" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />\n </svg>\n </button>\n </div>\n <p class="crm-input-hint">Press Enter to send • Shift+Enter for new line</p>\n </div>\n </div>\n ')}},{key:"getPositionClass",value:function(){var t={"bottom-right":"crm-bottom-6 crm-right-6","bottom-left":"crm-bottom-6 crm-left-6","top-right":"crm-top-6 crm-right-6","top-left":"crm-top-6 crm-left-6"};return t[this.config.position]||t["bottom-right"]}},{key:"attachEventListeners",value:function(){var t=this;document.getElementById("crm-chat-button").addEventListener("click",function(){return t.openChat()}),document.getElementById("crm-close-btn").addEventListener("click",function(){return t.closeChat()}),document.getElementById("crm-send-btn").addEventListener("click",function(){return t.sendMessage()}),document.getElementById("crm-input").addEventListener("keypress",function(e){"Enter"!==e.key||e.shiftKey||(e.preventDefault(),t.sendMessage())})}},{key:"openChat",value:(i=e(o().m(function t(){return o().w(function(t){for(;;)switch(t.n){case 0:if(this.state.isOpen=!0,this.state.unreadCount=0,document.getElementById("crm-chat-window").style.display="flex",document.getElementById("crm-badge").style.display="none",this.state.socket){t.n=1;break}return t.n=1,this.initializeChat();case 1:return t.a(2)}},t,this)})),function(){return i.apply(this,arguments)})},{key:"closeChat",value:function(){this.state.isOpen=!1,document.getElementById("crm-chat-window").style.display="none"}},{key:"initializeChat",value:(s=e(o().m(function t(){var e,n,s,i;return o().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,e=this.getUserData(),t.n=1,fetch("".concat(this.config.apiUrl,"/api/v1/webhook/guest-conversation"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:this.config.apiKey,guestName:e.name,guestEmail:e.email,guestPhone:e.phone,customUserId:e.userId})});case 1:return n=t.v,t.n=2,n.json();case 2:(s=t.v).status&&(this.state.guestId=s.data.guestId,this.state.conversationId=s.data.conversationId,localStorage.setItem("chatGuestId",this.state.guestId),localStorage.setItem("chatConversationId",this.state.conversationId),this.connectSocket()),t.n=4;break;case 3:t.p=3,i=t.v,console.error("❌ Chat initialization error:",i),alert("Failed to connect to chat. Please try again.");case 4:return t.a(2)}},t,this,[[0,3]])})),function(){return s.apply(this,arguments)})},{key:"connectSocket",value:function(){var t=this;this.state.socket=Rt(this.config.apiUrl,{query:{guestId:this.state.guestId,conversationId:this.state.conversationId,apiKey:this.config.apiKey},transports:["websocket","polling"]}),this.state.socket.on("connect",function(){t.state.isConnected=!0,t.updateConnectionStatus(!0),document.getElementById("crm-input").disabled=!1,document.getElementById("crm-send-btn").disabled=!1}),this.state.socket.on("disconnect",function(){t.state.isConnected=!1,t.updateConnectionStatus(!1)}),this.state.socket.on("new-message",function(e){t.addMessage(r(r({},e),{},{sender:"agent",timestamp:new Date})),!t.state.isOpen&&t.config.showNotifications&&(t.state.unreadCount++,t.updateBadge(),t.config.playSound&&t.playNotificationSound())}),this.state.socket.on("agent-typing",function(e){t.state.agentName=e.agentName||"Support Agent",t.showTypingIndicator()})}},{key:"updateConnectionStatus",value:function(t){var e=document.getElementById("crm-status-dot"),n=document.getElementById("crm-status-text");t?(e.classList.remove("crm-offline"),e.classList.add("crm-online"),n.textContent="Online"):(e.classList.remove("crm-online"),e.classList.add("crm-offline"),n.textContent="Connecting...")}},{key:"updateBadge",value:function(){var t=document.getElementById("crm-badge");this.state.unreadCount>0?(t.textContent=this.state.unreadCount,t.style.display="flex"):t.style.display="none"}},{key:"addMessage",value:function(t){this.state.messages.push(t);var e=document.getElementById("crm-messages"),n=document.createElement("div");n.className="crm-message crm-message-".concat(t.sender);var s="guest"===t.sender?'style="background-color: '.concat(this.config.primaryColor,'"'):"";n.innerHTML='\n <div class="crm-message-bubble" '.concat(s,">\n ").concat("agent"===t.sender?'<p class="crm-agent-name">'.concat(this.state.agentName,"</p>"):"",'\n <p class="crm-message-text">').concat(this.escapeHtml(t.message),'</p>\n <p class="crm-message-time">').concat(this.formatTime(t.timestamp),"</p>\n </div>\n "),e.appendChild(n),e.scrollTop=e.scrollHeight}},{key:"sendMessage",value:(t=e(o().m(function t(){var e,n,s,i;return o().w(function(t){for(;;)switch(t.p=t.n){case 0:if(e=document.getElementById("crm-input"),(n=e.value.trim())&&this.state.isConnected){t.n=1;break}return t.a(2);case 1:return s={guestId:this.state.guestId,conversationId:this.state.conversationId,message:n,timestamp:new Date},t.p=2,this.addMessage(r(r({},s),{},{sender:"guest"})),e.value="",this.state.socket.emit("send-message",s),t.n=3,fetch("".concat(this.config.apiUrl,"/api/v1/webhook/send-message"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:this.config.apiKey,guestId:this.state.guestId,conversationId:this.state.conversationId,message:n})});case 3:t.n=5;break;case 4:t.p=4,i=t.v,console.error("❌ Send message error:",i),alert("Failed to send message. Please try again.");case 5:return t.a(2)}},t,this,[[2,4]])})),function(){return t.apply(this,arguments)})},{key:"showTypingIndicator",value:function(){var t=this;this.state.isTyping=!0,setTimeout(function(){t.state.isTyping=!1},3e3)}},{key:"playNotificationSound",value:function(){try{var t=new(window.AudioContext||window.webkitAudioContext),e=t.createOscillator(),n=t.createGain();e.connect(n),n.connect(t.destination),e.frequency.value=800,e.type="sine",n.gain.value=.1,e.start(),setTimeout(function(){return e.stop()},200)}catch(t){console.log("Sound playback not available")}}},{key:"formatTime",value:function(t){return new Date(t).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})}},{key:"escapeHtml",value:function(t){var e=document.createElement("div");return e.textContent=t,e.innerHTML}}]);var t,s,i}();window.ChatCRMWidget={init:function(t){return new s(t)}}}()}();
4
+ //# sourceMappingURL=chat-widget.min.js.map