@traiyani/chatsdk-react 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.
@@ -0,0 +1,3989 @@
1
+ import de from "axios";
2
+ import { io as Ye } from "socket.io-client";
3
+ import { jsxs as M, jsx as u, Fragment as Je } from "react/jsx-runtime";
4
+ import * as q from "react";
5
+ import Qe, { useState as T, useRef as le, useCallback as De, useEffect as Y, createContext as Ze, useContext as Xe } from "react";
6
+ class et {
7
+ constructor(e) {
8
+ this.api = null, this.config = null, this.chatSDK = e;
9
+ }
10
+ /**
11
+ * Initialize AuthManager with configuration
12
+ */
13
+ async init(e) {
14
+ this.config = e, this.api = de.create({
15
+ baseURL: e.apiBaseUrl,
16
+ headers: {
17
+ "Content-Type": "application/json"
18
+ },
19
+ timeout: e.timeout || 3e4
20
+ }), this.api.interceptors.request.use(
21
+ (t) => {
22
+ const a = this.getToken();
23
+ return a && (t.headers.Authorization = `Bearer ${a}`), t;
24
+ },
25
+ (t) => Promise.reject(t)
26
+ ), this.api.interceptors.response.use(
27
+ (t) => t,
28
+ (t) => {
29
+ var a, s, n;
30
+ if (((a = t.response) == null ? void 0 : a.status) === 401) {
31
+ const r = (((s = t.config) == null ? void 0 : s.url) || "").includes("/api/auth/me");
32
+ this.clearToken(), r || (n = this.chatSDK.events) == null || n.emit("auth.logout", { reason: "unauthorized" });
33
+ }
34
+ return Promise.reject(t);
35
+ }
36
+ );
37
+ }
38
+ /**
39
+ * ✅ NEW: Authenticate chat user (unified login/register)
40
+ * This is the primary method for chat user authentication
41
+ * @param externalUserId - External user ID from your app
42
+ * @param appId - Application ID
43
+ * @param name - Display name
44
+ * @param email - Email address
45
+ */
46
+ async authenticate(e, t, a, s) {
47
+ var n, o, r, i, l, d;
48
+ if (!this.api)
49
+ throw new Error("AuthManager not initialized");
50
+ try {
51
+ const h = await this.api.post("/api/chat-users/authenticate", {
52
+ externalUserId: e,
53
+ appId: t,
54
+ name: a,
55
+ email: s
56
+ }), m = this.parseAuthResponse(h.data);
57
+ return (n = this.config) != null && n.enableLogging && console.log("🔐 AuthManager: Authentication successful", {
58
+ userId: m.id,
59
+ externalUserId: m.externalUserId,
60
+ name: m.name
61
+ }), (o = this.chatSDK.events) == null || o.emit("auth.login", { user: m }), m;
62
+ } catch (h) {
63
+ throw (r = this.config) != null && r.enableLogging && console.error("❌ AuthManager: Authentication failed", ((i = h.response) == null ? void 0 : i.data) || h.message), new Error(((d = (l = h.response) == null ? void 0 : l.data) == null ? void 0 : d.message) || "Authentication failed");
64
+ }
65
+ }
66
+ /**
67
+ * ✅ UPDATED: Login user with email and password (backward compatibility)
68
+ * @param email - User email
69
+ * @param password - User password
70
+ */
71
+ async login(e, t) {
72
+ var a, s, n, o, r, i;
73
+ if (!this.api)
74
+ throw new Error("AuthManager not initialized");
75
+ try {
76
+ const l = await this.api.post("/api/auth/signin", {
77
+ email: e,
78
+ password: t
79
+ }), { token: d, user: h } = l.data;
80
+ return this.setToken(d), (a = this.config) != null && a.enableLogging && console.log("🔐 AuthManager: Login successful", { userId: h.id, email: h.email }), (s = this.chatSDK.events) == null || s.emit("auth.login", { user: h }), h;
81
+ } catch (l) {
82
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ AuthManager: Login failed", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Login failed");
83
+ }
84
+ }
85
+ /**
86
+ * ✅ NEW: Chat user login (backward compatibility)
87
+ * @param externalUserId - External user ID
88
+ * @param appId - Application ID
89
+ */
90
+ async chatUserLogin(e, t) {
91
+ var a, s, n, o, r, i;
92
+ if (!this.api)
93
+ throw new Error("AuthManager not initialized");
94
+ try {
95
+ const l = await this.api.post("/api/chat-users/login", {
96
+ externalUserId: e,
97
+ appId: t
98
+ }), d = this.parseAuthResponse(l.data);
99
+ return (a = this.config) != null && a.enableLogging && console.log("🔐 AuthManager: Chat user login successful", {
100
+ userId: d.id,
101
+ externalUserId: d.externalUserId
102
+ }), (s = this.chatSDK.events) == null || s.emit("auth.login", { user: d }), d;
103
+ } catch (l) {
104
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ AuthManager: Chat user login failed", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Chat user login failed");
105
+ }
106
+ }
107
+ /**
108
+ * Register new user
109
+ * @param email - User email
110
+ * @param password - User password
111
+ * @param name - User name
112
+ * @param metadata - Additional user data
113
+ */
114
+ async register(e, t, a, s = {}) {
115
+ var n, o, r, i, l, d;
116
+ if (!this.api)
117
+ throw new Error("AuthManager not initialized");
118
+ try {
119
+ const h = await this.api.post("/api/auth/signup", {
120
+ email: e,
121
+ password: t,
122
+ name: a,
123
+ ...s
124
+ }), { token: m, user: p } = h.data;
125
+ return this.setToken(m), (n = this.config) != null && n.enableLogging && console.log("🔐 AuthManager: Registration successful", { userId: p.id, email: p.email }), (o = this.chatSDK.events) == null || o.emit("auth.register", { user: p }), p;
126
+ } catch (h) {
127
+ throw (r = this.config) != null && r.enableLogging && console.error("❌ AuthManager: Registration failed", ((i = h.response) == null ? void 0 : i.data) || h.message), new Error(((d = (l = h.response) == null ? void 0 : l.data) == null ? void 0 : d.message) || "Registration failed");
128
+ }
129
+ }
130
+ /**
131
+ * ✅ NEW: Chat user register (backward compatibility)
132
+ * @param externalUserId - External user ID
133
+ * @param appId - Application ID
134
+ * @param name - Display name
135
+ * @param email - Email address
136
+ */
137
+ async chatUserRegister(e, t, a, s) {
138
+ var n, o, r, i, l, d;
139
+ if (!this.api)
140
+ throw new Error("AuthManager not initialized");
141
+ try {
142
+ const h = await this.api.post("/api/chat-users/register", {
143
+ externalUserId: e,
144
+ appId: t,
145
+ name: a,
146
+ email: s
147
+ }), m = this.parseAuthResponse(h.data);
148
+ return (n = this.config) != null && n.enableLogging && console.log("🔐 AuthManager: Chat user registration successful", {
149
+ userId: m.id,
150
+ externalUserId: m.externalUserId,
151
+ name: m.name
152
+ }), (o = this.chatSDK.events) == null || o.emit("auth.register", { user: m }), m;
153
+ } catch (h) {
154
+ throw (r = this.config) != null && r.enableLogging && console.error("❌ AuthManager: Chat user registration failed", ((i = h.response) == null ? void 0 : i.data) || h.message), new Error(((d = (l = h.response) == null ? void 0 : l.data) == null ? void 0 : d.message) || "Chat user registration failed");
155
+ }
156
+ }
157
+ /**
158
+ * ✅ NEW: Parse authentication response from server
159
+ * Handles our server's response format:
160
+ * {
161
+ * "success": true,
162
+ * "data": {
163
+ * "token": "jwt_token",
164
+ * "user": { user_data },
165
+ * "auth": { auth_info }
166
+ * }
167
+ * }
168
+ */
169
+ parseAuthResponse(e) {
170
+ if (!e.success)
171
+ throw new Error(e.message || "Authentication failed");
172
+ if (!e.data)
173
+ throw new Error("Invalid response format: missing data");
174
+ const { token: t, user: a, auth: s } = e.data, n = t || (s == null ? void 0 : s.accessToken);
175
+ return n && this.setToken(n), {
176
+ id: a.id,
177
+ externalUserId: a.externalUserId,
178
+ appId: a.appId || process.env.REACT_APP_APP_ID || "",
179
+ name: a.name,
180
+ email: a.email,
181
+ avatarUrl: a.avatarUrl,
182
+ status: a.status || "offline",
183
+ isOnline: a.isOnline || !1,
184
+ lastSeen: a.lastSeen,
185
+ isRegistered: !0,
186
+ createdAt: a.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
187
+ updatedAt: a.updatedAt || (/* @__PURE__ */ new Date()).toISOString()
188
+ };
189
+ }
190
+ /**
191
+ * Logout current user
192
+ */
193
+ async logout() {
194
+ var e, t, a;
195
+ if (!this.api)
196
+ throw new Error("AuthManager not initialized");
197
+ try {
198
+ await this.api.post("/api/auth/signout");
199
+ } catch {
200
+ (e = this.config) != null && e.enableLogging && console.warn("⚠️ AuthManager: Logout API call failed, continuing with local logout");
201
+ }
202
+ this.clearToken(), (t = this.config) != null && t.enableLogging && console.log("👋 AuthManager: Logout successful"), (a = this.chatSDK.events) == null || a.emit("auth.logout", { reason: "user_initiated" });
203
+ }
204
+ /**
205
+ * Get current user information
206
+ */
207
+ async getCurrentUser() {
208
+ var e, t, a, s;
209
+ if (!this.api)
210
+ throw new Error("AuthManager not initialized");
211
+ if (!this.hasValidToken())
212
+ throw new Error("No valid token found. Please login first.");
213
+ try {
214
+ const n = await this.api.get("/api/auth/me");
215
+ return this.parseAuthResponse(n.data);
216
+ } catch (n) {
217
+ throw (e = this.config) != null && e.enableLogging && console.error("❌ AuthManager: Get current user failed", ((t = n.response) == null ? void 0 : t.data) || n.message), new Error(((s = (a = n.response) == null ? void 0 : a.data) == null ? void 0 : s.message) || "Failed to get current user");
218
+ }
219
+ }
220
+ /**
221
+ * Verify email with token
222
+ */
223
+ async verifyEmail(e) {
224
+ var t, a, s, n, o;
225
+ if (!this.api)
226
+ throw new Error("AuthManager not initialized");
227
+ try {
228
+ await this.api.post("/api/auth/verify-email", { token: e }), (t = this.config) != null && t.enableLogging && console.log("✅ AuthManager: Email verified successfully");
229
+ } catch (r) {
230
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ AuthManager: Email verification failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Email verification failed");
231
+ }
232
+ }
233
+ /**
234
+ * Request password reset
235
+ */
236
+ async forgotPassword(e) {
237
+ var t, a, s, n, o;
238
+ if (!this.api)
239
+ throw new Error("AuthManager not initialized");
240
+ try {
241
+ await this.api.post("/api/auth/forgot-password", { email: e }), (t = this.config) != null && t.enableLogging && console.log("📧 AuthManager: Password reset email sent");
242
+ } catch (r) {
243
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ AuthManager: Forgot password failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Failed to send password reset email");
244
+ }
245
+ }
246
+ /**
247
+ * Reset password with token
248
+ */
249
+ async resetPassword(e, t) {
250
+ var a, s, n, o, r;
251
+ if (!this.api)
252
+ throw new Error("AuthManager not initialized");
253
+ try {
254
+ await this.api.post("/api/auth/reset-password", { token: e, password: t }), (a = this.config) != null && a.enableLogging && console.log("🔐 AuthManager: Password reset successful");
255
+ } catch (i) {
256
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ AuthManager: Password reset failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Password reset failed");
257
+ }
258
+ }
259
+ /**
260
+ * Check if user has valid token
261
+ */
262
+ hasValidToken() {
263
+ return !!this.getToken();
264
+ }
265
+ /**
266
+ * Get stored token
267
+ */
268
+ getToken() {
269
+ return localStorage.getItem("chatSDKToken");
270
+ }
271
+ /**
272
+ * Store token
273
+ */
274
+ setToken(e) {
275
+ localStorage.setItem("chatSDKToken", e);
276
+ }
277
+ /**
278
+ * Clear stored token
279
+ */
280
+ clearToken() {
281
+ localStorage.removeItem("chatSDKToken");
282
+ }
283
+ }
284
+ class tt {
285
+ constructor(e) {
286
+ this.api = null, this.config = null, this.chatSDK = e;
287
+ }
288
+ /**
289
+ * Initialize ChatUserManager with configuration
290
+ */
291
+ async init(e) {
292
+ this.config = e, this.api = de.create({
293
+ baseURL: e.apiBaseUrl,
294
+ headers: {
295
+ "Content-Type": "application/json"
296
+ },
297
+ timeout: e.timeout || 3e4
298
+ }), this.api.interceptors.request.use(
299
+ (t) => {
300
+ const a = this.getToken();
301
+ return a && (t.headers.Authorization = `Bearer ${a}`), t;
302
+ },
303
+ (t) => Promise.reject(t)
304
+ ), this.api.interceptors.response.use(
305
+ (t) => t,
306
+ (t) => {
307
+ var a, s;
308
+ return ((a = t.response) == null ? void 0 : a.status) === 401 && (this.clearToken(), (s = this.chatSDK.events) == null || s.emit("chatUser.logout", { reason: "unauthorized" })), Promise.reject(t);
309
+ }
310
+ );
311
+ }
312
+ /**
313
+ * Login chat user with external user ID
314
+ * @param externalUserId - External user ID
315
+ * @param appId - Application ID
316
+ * @param saveToken - Whether to save the token (default: true)
317
+ */
318
+ async login(e, t, a = !0) {
319
+ var s, n, o, r, i, l, d;
320
+ if (!this.api)
321
+ throw new Error("ChatUserManager not initialized");
322
+ try {
323
+ const h = await this.api.post("/api/chat-users/login", {
324
+ externalUserId: e,
325
+ appId: t
326
+ }), { token: m, user: p } = h.data.data;
327
+ return a ? (this.setToken(m), (s = this.config) != null && s.enableLogging && console.log("🔐 ChatUserManager: Chat user login successful with token saved", { userId: p.id, email: p.email }), (n = this.chatSDK.events) == null || n.emit("chatUser.login", { user: p })) : (o = this.config) != null && o.enableLogging && console.log("👤 ChatUserManager: Chat user verified (no token saved)", { userId: p.id, email: p.email }), p;
328
+ } catch (h) {
329
+ throw (r = this.config) != null && r.enableLogging && console.error("❌ ChatUserManager: Chat user login failed", ((i = h.response) == null ? void 0 : i.data) || h.message), new Error(((d = (l = h.response) == null ? void 0 : l.data) == null ? void 0 : d.message) || "Chat user login failed");
330
+ }
331
+ }
332
+ /**
333
+ * Register new chat user
334
+ * @param userData - User data for registration
335
+ * @param saveToken - Whether to save the token (default: true)
336
+ */
337
+ async register(e, t = !0) {
338
+ var a, s, n, o, r, i, l;
339
+ if (!this.api)
340
+ throw new Error("ChatUserManager not initialized");
341
+ try {
342
+ const d = await this.api.post("/api/chat-users/register", e), { token: h, user: m } = d.data.data;
343
+ return t ? (this.setToken(h), (a = this.config) != null && a.enableLogging && console.log("📝 ChatUserManager: Chat user registration successful with token saved", { userId: m.id, email: m.email }), (s = this.chatSDK.events) == null || s.emit("chatUser.register", { user: m })) : (n = this.config) != null && n.enableLogging && console.log("👤 ChatUserManager: Chat user registered (no token saved)", { userId: m.id, email: m.email }), m;
344
+ } catch (d) {
345
+ throw (o = this.config) != null && o.enableLogging && console.error("❌ ChatUserManager: Chat user registration failed", ((r = d.response) == null ? void 0 : r.data) || d.message), new Error(((l = (i = d.response) == null ? void 0 : i.data) == null ? void 0 : l.message) || "Chat user registration failed");
346
+ }
347
+ }
348
+ /**
349
+ * Login or register chat user (try login first, register if fails)
350
+ * @param externalUserId - External user ID
351
+ * @param appId - Application ID
352
+ * @param name - User display name
353
+ * @param email - User email
354
+ * @param isLoggedinUser - Whether to save token (true for login, false for user existence check)
355
+ */
356
+ async authenticate(e, t, a, s, n = !0) {
357
+ try {
358
+ return await this.login(e, t, n);
359
+ } catch {
360
+ try {
361
+ return await this.register({
362
+ externalUserId: e,
363
+ appId: t,
364
+ name: a,
365
+ email: s
366
+ }, n);
367
+ } catch (r) {
368
+ throw new Error("Failed to authenticate chat user: " + r);
369
+ }
370
+ }
371
+ }
372
+ /**
373
+ * Logout current chat user
374
+ */
375
+ async logout() {
376
+ var e, t;
377
+ this.clearToken(), (e = this.config) != null && e.enableLogging && console.log("👋 ChatUserManager: Chat user logout successful"), (t = this.chatSDK.events) == null || t.emit("chatUser.logout", { reason: "manual" });
378
+ }
379
+ /**
380
+ * Get current chat user token
381
+ */
382
+ getToken() {
383
+ return localStorage.getItem("chatSDKToken");
384
+ }
385
+ /**
386
+ * Set chat user token
387
+ */
388
+ setToken(e) {
389
+ localStorage.setItem("chatSDKToken", e);
390
+ }
391
+ /**
392
+ * Clear chat user token
393
+ */
394
+ clearToken() {
395
+ localStorage.removeItem("chatSDKToken");
396
+ }
397
+ /**
398
+ * Check if chat user is authenticated
399
+ */
400
+ isAuthenticated() {
401
+ return !!this.getToken();
402
+ }
403
+ /**
404
+ * Register FCM token with ChatSDK server
405
+ * @param fcmToken - FCM token from Firebase
406
+ * @param platform - Platform (android/ios)
407
+ */
408
+ async registerFcmToken(e, t = "android") {
409
+ var a, s, n, o, r, i;
410
+ if (!this.api)
411
+ throw new Error("ChatUserManager not initialized");
412
+ if (!this.isAuthenticated())
413
+ throw new Error("User must be authenticated to register FCM token");
414
+ try {
415
+ const l = await this.api.post("/api/chat-users/fcm-token", {
416
+ fcmToken: e,
417
+ platform: t
418
+ });
419
+ (a = this.config) != null && a.enableLogging && console.log("📱 ChatUserManager: FCM token registered successfully", { fcmToken: e, platform: t }), (s = this.chatSDK.events) == null || s.emit("chatUser.fcmTokenRegistered", { fcmToken: e, platform: t });
420
+ } catch (l) {
421
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ ChatUserManager: Failed to register FCM token", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Failed to register FCM token");
422
+ }
423
+ }
424
+ /**
425
+ * Unregister FCM token from ChatSDK server
426
+ * @param fcmToken - FCM token to remove
427
+ */
428
+ async unregisterFcmToken(e) {
429
+ var t, a, s, n, o, r;
430
+ if (!this.api)
431
+ throw new Error("ChatUserManager not initialized");
432
+ if (!this.isAuthenticated())
433
+ throw new Error("User must be authenticated to unregister FCM token");
434
+ try {
435
+ const i = await this.api.delete("/api/chat-users/fcm-token", {
436
+ data: { fcmToken: e }
437
+ });
438
+ (t = this.config) != null && t.enableLogging && console.log("🗑️ ChatUserManager: FCM token unregistered successfully", { fcmToken: e }), (a = this.chatSDK.events) == null || a.emit("chatUser.fcmTokenUnregistered", { fcmToken: e });
439
+ } catch (i) {
440
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ ChatUserManager: Failed to unregister FCM token", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to unregister FCM token");
441
+ }
442
+ }
443
+ /**
444
+ * Get current FCM tokens for user
445
+ */
446
+ async getFcmTokens() {
447
+ var e, t, a, s, n, o, r;
448
+ if (!this.api)
449
+ throw new Error("ChatUserManager not initialized");
450
+ if (!this.isAuthenticated())
451
+ throw new Error("User must be authenticated to get FCM tokens");
452
+ try {
453
+ const l = ((t = (e = (await this.api.get("/api/chat-users/fcm-tokens")).data) == null ? void 0 : e.data) == null ? void 0 : t.fcmTokens) || [];
454
+ return (a = this.config) != null && a.enableLogging && console.log("📱 ChatUserManager: Retrieved FCM tokens", { tokenCount: l.length }), l;
455
+ } catch (i) {
456
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ ChatUserManager: Failed to get FCM tokens", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to get FCM tokens");
457
+ }
458
+ }
459
+ // ===================================
460
+ // 📊 CONVERSATION METHODS
461
+ // ===================================
462
+ /**
463
+ * Get conversations for current chat user
464
+ * @param options - List options
465
+ */
466
+ async getConversations(e = {}) {
467
+ var t, a, s, n, o;
468
+ if (!this.api)
469
+ throw new Error("ChatUserManager not initialized");
470
+ try {
471
+ const r = new URLSearchParams();
472
+ e.limit && r.append("limit", e.limit.toString()), e.offset && r.append("offset", e.offset.toString()), e.type && r.append("type", e.type), e.unreadOnly && r.append("unreadOnly", "true");
473
+ const i = await this.api.get(`/api/chat-users/chats?${r.toString()}`), l = i.data.data || i.data.conversations || i.data || [];
474
+ return (t = this.config) != null && t.enableLogging && console.log("📋 ChatUserManager: Conversations fetched successfully", {
475
+ count: l.length
476
+ }), l;
477
+ } catch (r) {
478
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ ChatUserManager: Get conversations failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Failed to get conversations");
479
+ }
480
+ }
481
+ /**
482
+ * ⚡ OPTIMIZED: Start a direct chat with external group ID
483
+ * @param externalGroupId - External group ID (GUID) for fast room lookup
484
+ * @param userId - User ID to start chat with
485
+ */
486
+ async startChat(e, t) {
487
+ var a, s, n, o, r, i, l;
488
+ if (!this.api)
489
+ throw new Error("ChatUserManager not initialized");
490
+ if (!e)
491
+ throw new Error("External Group ID is required");
492
+ try {
493
+ const d = await this.api.post("/api/chat-users/chats", {
494
+ type: "direct",
495
+ participants: [t],
496
+ externalGroupId: e
497
+ }), h = d.data.data || d.data.conversation || d.data;
498
+ return (a = this.config) != null && a.enableLogging && console.log("💬 ChatUserManager: Direct chat started successfully", {
499
+ conversationId: h.id,
500
+ userId: t,
501
+ externalGroupId: e
502
+ }), (s = this.chatSDK.socket) != null && s.isConnected() && this.chatSDK.socket.joinRoom(h.id), (n = this.chatSDK.events) == null || n.emit("conversation.created", { conversation: h }), h;
503
+ } catch (d) {
504
+ throw (o = this.config) != null && o.enableLogging && console.error("❌ ChatUserManager: Start chat failed", ((r = d.response) == null ? void 0 : r.data) || d.message), new Error(((l = (i = d.response) == null ? void 0 : i.data) == null ? void 0 : l.message) || "Failed to start chat");
505
+ }
506
+ }
507
+ /**
508
+ * ⚡ OPTIMIZED: Start a direct chat with product context
509
+ * @param externalGroupId - External group ID (GUID) for fast room lookup
510
+ * @param userId - User ID to start chat with
511
+ * @param productContext - Product information to associate with the conversation (camelCase format)
512
+ * @param chatMetadata - Optional chat-specific metadata
513
+ */
514
+ async startChatWithProduct(e, t, a, s) {
515
+ var n, o, r, i, l, d, h;
516
+ if (!this.api)
517
+ throw new Error("ChatUserManager not initialized");
518
+ if (!e)
519
+ throw new Error("External Group ID is required");
520
+ try {
521
+ const m = {
522
+ type: "direct",
523
+ participants: [t],
524
+ externalGroupId: e,
525
+ metadata: {
526
+ productContext: {
527
+ productId: a.productId,
528
+ productName: a.productName,
529
+ productImage: a.productImage,
530
+ price: a.price,
531
+ currency: a.currency,
532
+ category: a.category,
533
+ productMetadata: a.productMetadata
534
+ }
535
+ }
536
+ };
537
+ s && Object.keys(s).length > 0 && (m.chatMetadata = s);
538
+ const p = await this.api.post("/api/chat-users/chats", m), E = p.data.data || p.data.conversation || p.data;
539
+ return (n = this.config) != null && n.enableLogging && console.log("💬 ChatUserManager: Product chat started successfully", {
540
+ conversationId: E.id,
541
+ userId: t,
542
+ productId: a.productId,
543
+ productName: a.productName
544
+ }), (o = this.chatSDK.socket) != null && o.isConnected() && this.chatSDK.socket.joinRoom(E.id), (r = this.chatSDK.events) == null || r.emit("conversation.created", { conversation: E }), E;
545
+ } catch (m) {
546
+ throw (i = this.config) != null && i.enableLogging && console.error("❌ ChatUserManager: Start product chat failed", ((l = m.response) == null ? void 0 : l.data) || m.message), new Error(((h = (d = m.response) == null ? void 0 : d.data) == null ? void 0 : h.message) || "Failed to start product chat");
547
+ }
548
+ }
549
+ // ===================================
550
+ // 📊 UNREAD MESSAGES METHODS
551
+ // ===================================
552
+ /**
553
+ * Get count of conversations with unread messages
554
+ */
555
+ async getUnreadConversationsCount() {
556
+ var e, t, a, s, n;
557
+ if (!this.api)
558
+ throw new Error("ChatUserManager not initialized");
559
+ try {
560
+ const r = (await this.api.get("/api/chat-users/unread/conversations-count")).data.data.unreadConversationsCount || 0;
561
+ return (e = this.config) != null && e.enableLogging && console.log("📊 ChatUserManager: Unread conversations count fetched", { count: r }), r;
562
+ } catch (o) {
563
+ throw (t = this.config) != null && t.enableLogging && console.error("❌ ChatUserManager: Get unread conversations count failed", ((a = o.response) == null ? void 0 : a.data) || o.message), new Error(((n = (s = o.response) == null ? void 0 : s.data) == null ? void 0 : n.message) || "Failed to get unread conversations count");
564
+ }
565
+ }
566
+ /**
567
+ * Get total count of unread messages across all conversations
568
+ */
569
+ async getTotalUnreadCount() {
570
+ var e, t, a, s, n;
571
+ if (!this.api)
572
+ throw new Error("ChatUserManager not initialized");
573
+ try {
574
+ const r = (await this.api.get("/api/chat-users/unread/total-count")).data.data.totalUnreadCount || 0;
575
+ return (e = this.config) != null && e.enableLogging && console.log("📊 ChatUserManager: Total unread count fetched", { count: r }), r;
576
+ } catch (o) {
577
+ throw (t = this.config) != null && t.enableLogging && console.error("❌ ChatUserManager: Get total unread count failed", ((a = o.response) == null ? void 0 : a.data) || o.message), new Error(((n = (s = o.response) == null ? void 0 : s.data) == null ? void 0 : n.message) || "Failed to get total unread count");
578
+ }
579
+ }
580
+ /**
581
+ * Get detailed unread messages summary
582
+ */
583
+ async getUnreadSummary() {
584
+ var e, t, a, s, n;
585
+ if (!this.api)
586
+ throw new Error("ChatUserManager not initialized");
587
+ try {
588
+ const r = (await this.api.get("/api/chat-users/unread/summary")).data.data;
589
+ return (e = this.config) != null && e.enableLogging && console.log("📊 ChatUserManager: Unread summary fetched", {
590
+ conversations: r.totalConversationsWithUnread,
591
+ totalMessages: r.totalUnreadMessages
592
+ }), r;
593
+ } catch (o) {
594
+ throw (t = this.config) != null && t.enableLogging && console.error("❌ ChatUserManager: Get unread summary failed", ((a = o.response) == null ? void 0 : a.data) || o.message), new Error(((n = (s = o.response) == null ? void 0 : s.data) == null ? void 0 : n.message) || "Failed to get unread summary");
595
+ }
596
+ }
597
+ /**
598
+ * Mark all messages in a room as read
599
+ * Uses socket (fast) with API fallback (reliable)
600
+ * @param conversationId - Conversation ID
601
+ */
602
+ async markRoomMessagesRead(e) {
603
+ var t, a, s, n, o, r, i, l, d, h, m;
604
+ if (!this.api)
605
+ throw new Error("ChatUserManager not initialized");
606
+ try {
607
+ if ((t = this.config) != null && t.enableLogging && console.log("📖 ChatUserManager: Marking room as read", { conversationId: e }), (a = this.chatSDK.socket) != null && a.isConnected())
608
+ return this.chatSDK.socket.emit("mark_room_read", { roomId: e }), (s = this.config) != null && s.enableLogging && console.log("📡 ChatUserManager: mark_room_read sent via socket", { roomId: e }), (n = this.chatSDK.events) == null || n.emit("conversation.read", { conversationId: e, markedCount: 0 }), 0;
609
+ (o = this.config) != null && o.enableLogging && console.log("📡 ChatUserManager: Socket not connected, falling back to API");
610
+ const E = (await this.api.post(`/api/chat-users/chats/${e}/mark-read`)).data.data.markedAsReadCount || 0;
611
+ return (r = this.config) != null && r.enableLogging && console.log("✅ ChatUserManager: Room messages marked as read via API", { conversationId: e, markedCount: E }), (i = this.chatSDK.events) == null || i.emit("conversation.read", { conversationId: e, markedCount: E }), E;
612
+ } catch (p) {
613
+ throw console.error("❌ ChatUserManager: Mark room messages as read failed", {
614
+ conversationId: e,
615
+ error: ((l = p.response) == null ? void 0 : l.data) || p.message,
616
+ status: (d = p.response) == null ? void 0 : d.status
617
+ }), new Error(((m = (h = p.response) == null ? void 0 : h.data) == null ? void 0 : m.message) || p.message || "Failed to mark room messages as read");
618
+ }
619
+ }
620
+ /**
621
+ * Mark specific message as read
622
+ * Uses socket (fast) with API fallback (reliable)
623
+ * @param messageId - Message ID
624
+ */
625
+ async markMessageRead(e) {
626
+ var t, a, s, n, o, r, i, l, d, h;
627
+ if (!this.api)
628
+ throw new Error("ChatUserManager not initialized");
629
+ try {
630
+ if ((t = this.chatSDK.socket) != null && t.isConnected())
631
+ return this.chatSDK.socket.emit("mark_message_read", { messageId: e }), (a = this.config) != null && a.enableLogging && console.log("📡 ChatUserManager: mark_message_read sent via socket", { messageId: e }), (s = this.chatSDK.events) == null || s.emit("message.read", { messageId: e, wasUnread: !0 }), !0;
632
+ (n = this.config) != null && n.enableLogging && console.log("📡 ChatUserManager: Socket not connected, falling back to API for mark-message-read");
633
+ const p = (await this.api.post(`/api/chat-users/messages/${e}/mark-read`)).data.data.wasUnread || !1;
634
+ return (o = this.config) != null && o.enableLogging && console.log("✅ ChatUserManager: Message marked as read via API", { messageId: e, wasUnread: p }), (r = this.chatSDK.events) == null || r.emit("message.read", { messageId: e, wasUnread: p }), p;
635
+ } catch (m) {
636
+ throw console.error("❌ ChatUserManager: Mark message as read failed", {
637
+ messageId: e,
638
+ error: ((i = m.response) == null ? void 0 : i.data) || m.message,
639
+ status: (l = m.response) == null ? void 0 : l.status
640
+ }), new Error(((h = (d = m.response) == null ? void 0 : d.data) == null ? void 0 : h.message) || m.message || "Failed to mark message as read");
641
+ }
642
+ }
643
+ /**
644
+ * Start viewing a conversation (auto-marks messages as read)
645
+ * @param conversationId - Conversation ID
646
+ */
647
+ startViewingConversation(e) {
648
+ var t, a;
649
+ (t = this.chatSDK.socket) != null && t.isConnected() && (this.chatSDK.socket.emit("viewing_conversation", {
650
+ roomId: e,
651
+ isViewing: !0
652
+ }), (a = this.config) != null && a.enableLogging && console.log("👀 ChatUserManager: Started viewing conversation", { conversationId: e }));
653
+ }
654
+ /**
655
+ * Stop viewing a conversation
656
+ * @param conversationId - Conversation ID
657
+ */
658
+ stopViewingConversation(e) {
659
+ var t, a;
660
+ (t = this.chatSDK.socket) != null && t.isConnected() && (this.chatSDK.socket.emit("viewing_conversation", {
661
+ roomId: e,
662
+ isViewing: !1
663
+ }), (a = this.config) != null && a.enableLogging && console.log("👁️ ChatUserManager: Stopped viewing conversation", { conversationId: e }));
664
+ }
665
+ }
666
+ class at {
667
+ constructor(e) {
668
+ this.api = null, this.config = null, this.chatSDK = e;
669
+ }
670
+ /**
671
+ * Initialize UserManager with configuration
672
+ */
673
+ async init(e) {
674
+ this.config = e, this.api = de.create({
675
+ baseURL: e.apiBaseUrl,
676
+ headers: {
677
+ "Content-Type": "application/json"
678
+ },
679
+ timeout: e.timeout || 3e4
680
+ }), this.api.interceptors.request.use(
681
+ (t) => {
682
+ const a = localStorage.getItem("chatSDKToken");
683
+ return a && (t.headers.Authorization = `Bearer ${a}`), t;
684
+ },
685
+ (t) => Promise.reject(t)
686
+ );
687
+ }
688
+ /**
689
+ * Get user by ID
690
+ * @param userId - User ID to fetch
691
+ */
692
+ async getUser(e) {
693
+ var t, a, s, n, o;
694
+ if (!this.api)
695
+ throw new Error("UserManager not initialized");
696
+ try {
697
+ const r = await this.api.get(`/api/users/${e}`);
698
+ return (t = this.config) != null && t.enableLogging && console.log("👤 UserManager: User fetched successfully", { userId: e }), r.data.user;
699
+ } catch (r) {
700
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ UserManager: Get user failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Failed to get user");
701
+ }
702
+ }
703
+ /**
704
+ * Search for users
705
+ * @param options - Search options
706
+ */
707
+ async searchUsers(e = {}) {
708
+ var t, a, s, n, o, r;
709
+ if (!this.api)
710
+ throw new Error("UserManager not initialized");
711
+ try {
712
+ const i = new URLSearchParams();
713
+ e.query && i.append("q", e.query), e.limit && i.append("limit", e.limit.toString()), e.offset && i.append("offset", e.offset.toString()), e.role && i.append("role", e.role), e.status && i.append("status", e.status);
714
+ const l = await this.api.get(`/api/users/search?${i.toString()}`);
715
+ return (t = this.config) != null && t.enableLogging && console.log("🔍 UserManager: Users searched successfully", {
716
+ query: e.query,
717
+ count: ((a = l.data.users) == null ? void 0 : a.length) || 0
718
+ }), l.data.users || [];
719
+ } catch (i) {
720
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ UserManager: Search users failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to search users");
721
+ }
722
+ }
723
+ /**
724
+ * Get all users (paginated)
725
+ * @param limit - Number of users to fetch
726
+ * @param offset - Offset for pagination
727
+ */
728
+ async getAllUsers(e = 20, t = 0) {
729
+ var a, s, n, o, r, i;
730
+ if (!this.api)
731
+ throw new Error("UserManager not initialized");
732
+ try {
733
+ const l = await this.api.get(`/api/users?limit=${e}&offset=${t}`);
734
+ return (a = this.config) != null && a.enableLogging && console.log("👥 UserManager: All users fetched successfully", {
735
+ count: ((s = l.data.users) == null ? void 0 : s.length) || 0,
736
+ limit: e,
737
+ offset: t
738
+ }), l.data.users || [];
739
+ } catch (l) {
740
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ UserManager: Get all users failed", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Failed to get users");
741
+ }
742
+ }
743
+ /**
744
+ * Update current user's profile
745
+ * @param updateData - Data to update
746
+ */
747
+ async updateCurrentUser(e) {
748
+ var t, a, s, n, o, r;
749
+ if (!this.api)
750
+ throw new Error("UserManager not initialized");
751
+ try {
752
+ const i = await this.api.put("/api/users/me", e);
753
+ return (t = this.config) != null && t.enableLogging && console.log("✏️ UserManager: User profile updated successfully"), (a = this.chatSDK.events) == null || a.emit("user.updated", { user: i.data.user }), i.data.user;
754
+ } catch (i) {
755
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ UserManager: Update user failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to update user");
756
+ }
757
+ }
758
+ /**
759
+ * Update user status (online, offline, away, busy)
760
+ * @param status - New status
761
+ */
762
+ async updateStatus(e) {
763
+ var t, a, s, n, o, r;
764
+ if (!this.api)
765
+ throw new Error("UserManager not initialized");
766
+ try {
767
+ await this.api.put("/api/users/me/status", { status: e }), (t = this.config) != null && t.enableLogging && console.log("📊 UserManager: User status updated successfully", { status: e }), (a = this.chatSDK.events) == null || a.emit("user.status.updated", { status: e });
768
+ } catch (i) {
769
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ UserManager: Update status failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to update status");
770
+ }
771
+ }
772
+ /**
773
+ * Block a user
774
+ * @param userId - User ID to block
775
+ */
776
+ async blockUser(e) {
777
+ var t, a, s, n, o, r;
778
+ if (!this.api)
779
+ throw new Error("UserManager not initialized");
780
+ try {
781
+ await this.api.post(`/api/users/${e}/block`), (t = this.config) != null && t.enableLogging && console.log("🚫 UserManager: User blocked successfully", { userId: e }), (a = this.chatSDK.events) == null || a.emit("user.blocked", { userId: e });
782
+ } catch (i) {
783
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ UserManager: Block user failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to block user");
784
+ }
785
+ }
786
+ /**
787
+ * Unblock a user
788
+ * @param userId - User ID to unblock
789
+ */
790
+ async unblockUser(e) {
791
+ var t, a, s, n, o, r;
792
+ if (!this.api)
793
+ throw new Error("UserManager not initialized");
794
+ try {
795
+ await this.api.delete(`/api/users/${e}/block`), (t = this.config) != null && t.enableLogging && console.log("✅ UserManager: User unblocked successfully", { userId: e }), (a = this.chatSDK.events) == null || a.emit("user.unblocked", { userId: e });
796
+ } catch (i) {
797
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ UserManager: Unblock user failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to unblock user");
798
+ }
799
+ }
800
+ /**
801
+ * Get blocked users list
802
+ */
803
+ async getBlockedUsers() {
804
+ var e, t, a, s, n, o;
805
+ if (!this.api)
806
+ throw new Error("UserManager not initialized");
807
+ try {
808
+ const r = await this.api.get("/api/users/me/blocked");
809
+ return (e = this.config) != null && e.enableLogging && console.log("📋 UserManager: Blocked users fetched successfully", {
810
+ count: ((t = r.data.users) == null ? void 0 : t.length) || 0
811
+ }), r.data.users || [];
812
+ } catch (r) {
813
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ UserManager: Get blocked users failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Failed to get blocked users");
814
+ }
815
+ }
816
+ /**
817
+ * Get user's online status
818
+ * @param userId - User ID to check
819
+ */
820
+ async getUserStatus(e) {
821
+ var t, a, s, n;
822
+ if (!this.api)
823
+ throw new Error("UserManager not initialized");
824
+ try {
825
+ return (await this.api.get(`/api/users/${e}/status`)).data.status;
826
+ } catch (o) {
827
+ throw (t = this.config) != null && t.enableLogging && console.error("❌ UserManager: Get user status failed", ((a = o.response) == null ? void 0 : a.data) || o.message), new Error(((n = (s = o.response) == null ? void 0 : s.data) == null ? void 0 : n.message) || "Failed to get user status");
828
+ }
829
+ }
830
+ /**
831
+ * Get multiple users by IDs
832
+ * @param userIds - Array of user IDs
833
+ */
834
+ async getUsersByIds(e) {
835
+ var t, a, s, n, o, r;
836
+ if (!this.api)
837
+ throw new Error("UserManager not initialized");
838
+ try {
839
+ const i = await this.api.post("/api/users/batch", { userIds: e });
840
+ return (t = this.config) != null && t.enableLogging && console.log("👥 UserManager: Users fetched by IDs successfully", {
841
+ requestedCount: e.length,
842
+ receivedCount: ((a = i.data.users) == null ? void 0 : a.length) || 0
843
+ }), i.data.users || [];
844
+ } catch (i) {
845
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ UserManager: Get users by IDs failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to get users by IDs");
846
+ }
847
+ }
848
+ }
849
+ class st {
850
+ constructor(e) {
851
+ this.api = null, this.config = null, this.chatSDK = e;
852
+ }
853
+ /**
854
+ * Initialize ConversationManager with configuration
855
+ */
856
+ async init(e) {
857
+ this.config = e, this.api = de.create({
858
+ baseURL: e.apiBaseUrl,
859
+ headers: {
860
+ "Content-Type": "application/json"
861
+ },
862
+ timeout: e.timeout || 3e4
863
+ }), this.api.interceptors.request.use(
864
+ (t) => {
865
+ const a = localStorage.getItem("chatSDKToken");
866
+ return a && (t.headers.Authorization = `Bearer ${a}`), t;
867
+ },
868
+ (t) => Promise.reject(t)
869
+ );
870
+ }
871
+ /**
872
+ * ⚡ OPTIMIZED: Start a direct chat with external group ID
873
+ * @param externalGroupId - External group ID (GUID) for fast room lookup
874
+ * @param userId - User ID to start chat with
875
+ */
876
+ async startChat(e, t) {
877
+ var a, s, n, o, r, i, l, d;
878
+ if (!this.api)
879
+ throw new Error("ConversationManager not initialized");
880
+ if (!e)
881
+ throw new Error("External Group ID is required");
882
+ try {
883
+ const h = await this.api.post("/api/chat-users/chats", {
884
+ type: "direct",
885
+ participants: [t],
886
+ externalGroupId: e
887
+ });
888
+ (a = this.config) != null && a.enableLogging && console.log("⚡ Using externalGroupId:", e), console.log("📡 Server response:", h.data);
889
+ const m = h.data.data || h.data.conversation || h.data;
890
+ return (s = this.config) != null && s.enableLogging && console.log("💬 ConversationManager: Direct chat started successfully", {
891
+ conversationId: m.id,
892
+ userId: t
893
+ }), (n = this.chatSDK.socket) != null && n.isConnected() && this.chatSDK.socket.joinRoom(m.id), (o = this.chatSDK.events) == null || o.emit("conversation.created", { conversation: m }), m;
894
+ } catch (h) {
895
+ throw (r = this.config) != null && r.enableLogging && console.error("❌ ConversationManager: Start chat failed", ((i = h.response) == null ? void 0 : i.data) || h.message), new Error(((d = (l = h.response) == null ? void 0 : l.data) == null ? void 0 : d.message) || "Failed to start chat");
896
+ }
897
+ }
898
+ /**
899
+ * ⚡ OPTIMIZED: Start a direct chat with product context
900
+ * @param externalGroupId - External group ID (GUID) for fast room lookup
901
+ * @param userId - User ID to start chat with
902
+ * @param productContext - Product information to associate with the conversation (camelCase format)
903
+ * @param chatMetadata - Optional chat-specific metadata
904
+ */
905
+ async startChatWithProduct(e, t, a, s) {
906
+ var n, o, r, i, l, d, h, m;
907
+ if (!this.api)
908
+ throw new Error("ConversationManager not initialized");
909
+ if (!e)
910
+ throw new Error("External Group ID is required");
911
+ try {
912
+ const p = {
913
+ type: "direct",
914
+ participants: [t],
915
+ externalGroupId: e,
916
+ metadata: {
917
+ productContext: {
918
+ productId: a.productId,
919
+ productName: a.productName,
920
+ productImage: a.productImage,
921
+ price: a.price,
922
+ currency: a.currency,
923
+ category: a.category,
924
+ productMetadata: a.productMetadata
925
+ }
926
+ }
927
+ };
928
+ s && Object.keys(s).length > 0 && (p.chatMetadata = s), (n = this.config) != null && n.enableLogging && console.log("⚡ Using externalGroupId:", e);
929
+ const E = await this.api.post("/api/chat-users/chats", p);
930
+ console.log("📡 Server response:", E.data);
931
+ const P = E.data.data || E.data.conversation || E.data;
932
+ return (o = this.config) != null && o.enableLogging && console.log("💬 ConversationManager: Product chat started successfully", {
933
+ conversationId: P.id,
934
+ userId: t,
935
+ productId: a.productId,
936
+ productName: a.productName
937
+ }), (r = this.chatSDK.socket) != null && r.isConnected() && this.chatSDK.socket.joinRoom(P.id), (i = this.chatSDK.events) == null || i.emit("conversation.created", { conversation: P }), P;
938
+ } catch (p) {
939
+ throw (l = this.config) != null && l.enableLogging && console.error("❌ ConversationManager: Start product chat failed", ((d = p.response) == null ? void 0 : d.data) || p.message), new Error(((m = (h = p.response) == null ? void 0 : h.data) == null ? void 0 : m.message) || "Failed to start product chat");
940
+ }
941
+ }
942
+ /**
943
+ * Create a group conversation
944
+ * @param options - Group creation options
945
+ */
946
+ async createGroup(e) {
947
+ var t, a, s, n, o, r;
948
+ if (!this.api)
949
+ throw new Error("ConversationManager not initialized");
950
+ try {
951
+ const i = await this.api.post("/api/conversations", e);
952
+ console.log("📡 Group creation response:", i.data);
953
+ const l = i.data.data || i.data.conversation || i.data;
954
+ return (t = this.config) != null && t.enableLogging && console.log("👥 ConversationManager: Group created successfully", {
955
+ conversationId: l.id,
956
+ participantCount: e.participantIds.length
957
+ }), (a = this.chatSDK.events) == null || a.emit("conversation.created", { conversation: l }), l;
958
+ } catch (i) {
959
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ ConversationManager: Create group failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to create group");
960
+ }
961
+ }
962
+ /**
963
+ * Get conversation list
964
+ * @param options - List options
965
+ */
966
+ async getConversations(e = {}) {
967
+ var t, a, s, n, o;
968
+ if (!this.api)
969
+ throw new Error("ConversationManager not initialized");
970
+ try {
971
+ const r = new URLSearchParams();
972
+ e.limit && r.append("limit", e.limit.toString()), e.offset && r.append("offset", e.offset.toString()), e.type && r.append("type", e.type), e.unreadOnly && r.append("unreadOnly", "true");
973
+ const i = await this.api.get(`/api/chat-users/chats?${r.toString()}`);
974
+ console.log("📡 Conversations response:", i.data);
975
+ const l = i.data.data || i.data.conversations || i.data || [];
976
+ return (t = this.config) != null && t.enableLogging && console.log("📋 ConversationManager: Conversations fetched successfully", {
977
+ count: l.length
978
+ }), l;
979
+ } catch (r) {
980
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ ConversationManager: Get conversations failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Failed to get conversations");
981
+ }
982
+ }
983
+ /**
984
+ * Get conversation by ID
985
+ * @param conversationId - Conversation ID
986
+ */
987
+ async getConversation(e) {
988
+ var t, a, s, n, o;
989
+ if (!this.api)
990
+ throw new Error("ConversationManager not initialized");
991
+ try {
992
+ const r = await this.api.get(`/api/chat-users/chats/${e}`);
993
+ return (t = this.config) != null && t.enableLogging && console.log("💬 ConversationManager: Conversation fetched successfully", { conversationId: e }), r.data.conversation || r.data;
994
+ } catch (r) {
995
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ ConversationManager: Get conversation failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Failed to get conversation");
996
+ }
997
+ }
998
+ /**
999
+ * Update conversation (name, description, etc.)
1000
+ * @param conversationId - Conversation ID
1001
+ * @param updateData - Data to update
1002
+ */
1003
+ async updateConversation(e, t) {
1004
+ var a, s, n, o, r, i;
1005
+ if (!this.api)
1006
+ throw new Error("ConversationManager not initialized");
1007
+ try {
1008
+ const d = (await this.api.put(`/api/conversations/${e}`, t)).data.conversation;
1009
+ return (a = this.config) != null && a.enableLogging && console.log("✏️ ConversationManager: Conversation updated successfully", { conversationId: e }), (s = this.chatSDK.events) == null || s.emit("conversation.updated", { conversation: d }), d;
1010
+ } catch (l) {
1011
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ ConversationManager: Update conversation failed", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Failed to update conversation");
1012
+ }
1013
+ }
1014
+ /**
1015
+ * Add participants to group conversation
1016
+ * @param conversationId - Conversation ID
1017
+ * @param userIds - User IDs to add
1018
+ */
1019
+ async addParticipants(e, t) {
1020
+ var a, s, n, o, r, i;
1021
+ if (!this.api)
1022
+ throw new Error("ConversationManager not initialized");
1023
+ try {
1024
+ const d = (await this.api.post(`/api/conversations/${e}/participants`, {
1025
+ userIds: t
1026
+ })).data.conversation;
1027
+ return (a = this.config) != null && a.enableLogging && console.log("➕ ConversationManager: Participants added successfully", {
1028
+ conversationId: e,
1029
+ addedCount: t.length
1030
+ }), (s = this.chatSDK.events) == null || s.emit("conversation.participants.added", {
1031
+ conversation: d,
1032
+ addedUserIds: t
1033
+ }), d;
1034
+ } catch (l) {
1035
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ ConversationManager: Add participants failed", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Failed to add participants");
1036
+ }
1037
+ }
1038
+ /**
1039
+ * Remove participants from group conversation
1040
+ * @param conversationId - Conversation ID
1041
+ * @param userIds - User IDs to remove
1042
+ */
1043
+ async removeParticipants(e, t) {
1044
+ var a, s, n, o, r, i;
1045
+ if (!this.api)
1046
+ throw new Error("ConversationManager not initialized");
1047
+ try {
1048
+ const d = (await this.api.delete(`/api/conversations/${e}/participants`, {
1049
+ data: { userIds: t }
1050
+ })).data.conversation;
1051
+ return (a = this.config) != null && a.enableLogging && console.log("➖ ConversationManager: Participants removed successfully", {
1052
+ conversationId: e,
1053
+ removedCount: t.length
1054
+ }), (s = this.chatSDK.events) == null || s.emit("conversation.participants.removed", {
1055
+ conversation: d,
1056
+ removedUserIds: t
1057
+ }), d;
1058
+ } catch (l) {
1059
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ ConversationManager: Remove participants failed", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Failed to remove participants");
1060
+ }
1061
+ }
1062
+ /**
1063
+ * Leave conversation
1064
+ * @param conversationId - Conversation ID
1065
+ */
1066
+ async leaveConversation(e) {
1067
+ var t, a, s, n, o, r;
1068
+ if (!this.api)
1069
+ throw new Error("ConversationManager not initialized");
1070
+ try {
1071
+ await this.api.post(`/api/conversations/${e}/leave`), (t = this.config) != null && t.enableLogging && console.log("🚪 ConversationManager: Left conversation successfully", { conversationId: e }), (a = this.chatSDK.events) == null || a.emit("conversation.left", { conversationId: e });
1072
+ } catch (i) {
1073
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ ConversationManager: Leave conversation failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to leave conversation");
1074
+ }
1075
+ }
1076
+ /**
1077
+ * Delete conversation
1078
+ * @param conversationId - Conversation ID
1079
+ */
1080
+ async deleteConversation(e) {
1081
+ var t, a, s, n, o, r;
1082
+ if (!this.api)
1083
+ throw new Error("ConversationManager not initialized");
1084
+ try {
1085
+ await this.api.delete(`/api/conversations/${e}`), (t = this.config) != null && t.enableLogging && console.log("🗑️ ConversationManager: Conversation deleted successfully", { conversationId: e }), (a = this.chatSDK.events) == null || a.emit("conversation.deleted", { conversationId: e });
1086
+ } catch (i) {
1087
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ ConversationManager: Delete conversation failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to delete conversation");
1088
+ }
1089
+ }
1090
+ /**
1091
+ * Mark conversation as read
1092
+ * @param conversationId - Conversation ID
1093
+ */
1094
+ async markAsRead(e) {
1095
+ var t, a, s, n, o, r;
1096
+ if (!this.api)
1097
+ throw new Error("ConversationManager not initialized");
1098
+ try {
1099
+ await this.api.post(`/api/chat-users/chats/${e}/mark-read`), (t = this.config) != null && t.enableLogging && console.log("👁️ ConversationManager: Conversation marked as read", { conversationId: e }), (a = this.chatSDK.events) == null || a.emit("conversation.read", { conversationId: e });
1100
+ } catch (i) {
1101
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ ConversationManager: Mark as read failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to mark conversation as read");
1102
+ }
1103
+ }
1104
+ // ===================================
1105
+ // 📊 UNREAD MESSAGES METHODS
1106
+ // ===================================
1107
+ /**
1108
+ * Get count of conversations with unread messages
1109
+ */
1110
+ async getUnreadConversationsCount() {
1111
+ var e, t, a, s, n;
1112
+ if (!this.api)
1113
+ throw new Error("ConversationManager not initialized");
1114
+ try {
1115
+ const r = (await this.api.get("/api/chat-users/unread/conversations-count")).data.data.unreadConversationsCount || 0;
1116
+ return (e = this.config) != null && e.enableLogging && console.log("📊 ConversationManager: Unread conversations count fetched", { count: r }), r;
1117
+ } catch (o) {
1118
+ throw (t = this.config) != null && t.enableLogging && console.error("❌ ConversationManager: Get unread conversations count failed", ((a = o.response) == null ? void 0 : a.data) || o.message), new Error(((n = (s = o.response) == null ? void 0 : s.data) == null ? void 0 : n.message) || "Failed to get unread conversations count");
1119
+ }
1120
+ }
1121
+ /**
1122
+ * Get total count of unread messages across all conversations
1123
+ */
1124
+ async getTotalUnreadCount() {
1125
+ var e, t, a, s, n;
1126
+ if (!this.api)
1127
+ throw new Error("ConversationManager not initialized");
1128
+ try {
1129
+ const r = (await this.api.get("/api/chat-users/unread/total-count")).data.data.totalUnreadCount || 0;
1130
+ return (e = this.config) != null && e.enableLogging && console.log("📊 ConversationManager: Total unread count fetched", { count: r }), r;
1131
+ } catch (o) {
1132
+ throw (t = this.config) != null && t.enableLogging && console.error("❌ ConversationManager: Get total unread count failed", ((a = o.response) == null ? void 0 : a.data) || o.message), new Error(((n = (s = o.response) == null ? void 0 : s.data) == null ? void 0 : n.message) || "Failed to get total unread count");
1133
+ }
1134
+ }
1135
+ /**
1136
+ * Get detailed unread messages summary
1137
+ */
1138
+ async getUnreadSummary() {
1139
+ var e, t, a, s, n;
1140
+ if (!this.api)
1141
+ throw new Error("ConversationManager not initialized");
1142
+ try {
1143
+ const r = (await this.api.get("/api/chat-users/unread/summary")).data.data;
1144
+ return (e = this.config) != null && e.enableLogging && console.log("📊 ConversationManager: Unread summary fetched", {
1145
+ conversations: r.totalConversationsWithUnread,
1146
+ totalMessages: r.totalUnreadMessages
1147
+ }), r;
1148
+ } catch (o) {
1149
+ throw (t = this.config) != null && t.enableLogging && console.error("❌ ConversationManager: Get unread summary failed", ((a = o.response) == null ? void 0 : a.data) || o.message), new Error(((n = (s = o.response) == null ? void 0 : s.data) == null ? void 0 : n.message) || "Failed to get unread summary");
1150
+ }
1151
+ }
1152
+ /**
1153
+ * Mark all messages in a room as read
1154
+ * Uses socket (fast) with API fallback (reliable)
1155
+ * @param conversationId - Conversation ID
1156
+ */
1157
+ async markRoomMessagesRead(e) {
1158
+ var t, a, s, n, o, r, i, l, d, h;
1159
+ if (!this.api)
1160
+ throw new Error("ConversationManager not initialized");
1161
+ try {
1162
+ if ((t = this.chatSDK.socket) != null && t.isConnected())
1163
+ return this.chatSDK.socket.emit("mark_room_read", { roomId: e }), (a = this.config) != null && a.enableLogging && console.log("📡 ConversationManager: mark_room_read sent via socket", { roomId: e }), (s = this.chatSDK.events) == null || s.emit("conversation.read", { conversationId: e, markedCount: 0 }), 0;
1164
+ (n = this.config) != null && n.enableLogging && console.log("📡 ConversationManager: Socket not connected, falling back to API");
1165
+ const p = (await this.api.post(`/api/chat-users/chats/${e}/mark-read`)).data.data.markedAsReadCount || 0;
1166
+ return (o = this.config) != null && o.enableLogging && console.log("✅ ConversationManager: Room messages marked as read via API", { conversationId: e, markedCount: p }), (r = this.chatSDK.events) == null || r.emit("conversation.read", { conversationId: e, markedCount: p }), p;
1167
+ } catch (m) {
1168
+ throw (i = this.config) != null && i.enableLogging && console.error("❌ ConversationManager: Mark room messages as read failed", ((l = m.response) == null ? void 0 : l.data) || m.message), new Error(((h = (d = m.response) == null ? void 0 : d.data) == null ? void 0 : h.message) || "Failed to mark room messages as read");
1169
+ }
1170
+ }
1171
+ /**
1172
+ * Mark specific message as read
1173
+ * Uses socket (fast) with API fallback (reliable)
1174
+ * @param messageId - Message ID
1175
+ */
1176
+ async markMessageRead(e) {
1177
+ var t, a, s, n, o, r, i, l, d, h;
1178
+ if (!this.api)
1179
+ throw new Error("ConversationManager not initialized");
1180
+ try {
1181
+ if ((t = this.chatSDK.socket) != null && t.isConnected())
1182
+ return this.chatSDK.socket.emit("mark_message_read", { messageId: e }), (a = this.config) != null && a.enableLogging && console.log("📡 ConversationManager: mark_message_read sent via socket", { messageId: e }), (s = this.chatSDK.events) == null || s.emit("message.read", { messageId: e, wasUnread: !0 }), !0;
1183
+ (n = this.config) != null && n.enableLogging && console.log("📡 ConversationManager: Socket not connected, falling back to API for mark-message-read");
1184
+ const p = (await this.api.post(`/api/chat-users/messages/${e}/mark-read`)).data.data.wasUnread || !1;
1185
+ return (o = this.config) != null && o.enableLogging && console.log("✅ ConversationManager: Message marked as read via API", { messageId: e, wasUnread: p }), (r = this.chatSDK.events) == null || r.emit("message.read", { messageId: e, wasUnread: p }), p;
1186
+ } catch (m) {
1187
+ throw (i = this.config) != null && i.enableLogging && console.error("❌ ConversationManager: Mark message as read failed", ((l = m.response) == null ? void 0 : l.data) || m.message), new Error(((h = (d = m.response) == null ? void 0 : d.data) == null ? void 0 : h.message) || "Failed to mark message as read");
1188
+ }
1189
+ }
1190
+ /**
1191
+ * Start viewing a conversation (auto-marks messages as read)
1192
+ * @param conversationId - Conversation ID
1193
+ */
1194
+ startViewingConversation(e) {
1195
+ var t, a;
1196
+ (t = this.chatSDK.socket) != null && t.isConnected() && (this.chatSDK.socket.emit("viewing_conversation", {
1197
+ roomId: e,
1198
+ isViewing: !0
1199
+ }), (a = this.config) != null && a.enableLogging && console.log("👀 ConversationManager: Started viewing conversation", { conversationId: e }));
1200
+ }
1201
+ /**
1202
+ * Stop viewing a conversation
1203
+ * @param conversationId - Conversation ID
1204
+ */
1205
+ stopViewingConversation(e) {
1206
+ var t, a;
1207
+ (t = this.chatSDK.socket) != null && t.isConnected() && (this.chatSDK.socket.emit("viewing_conversation", {
1208
+ roomId: e,
1209
+ isViewing: !1
1210
+ }), (a = this.config) != null && a.enableLogging && console.log("👁️ ConversationManager: Stopped viewing conversation", { conversationId: e }));
1211
+ }
1212
+ // ===================================
1213
+ // 🚫 USER BLOCKING METHODS (Chat-Specific)
1214
+ // ===================================
1215
+ /**
1216
+ * Block a user in a specific chat
1217
+ * @param chatId - Chat/Conversation ID
1218
+ * @param userId - User ID to block
1219
+ */
1220
+ async blockUserInChat(e, t) {
1221
+ var a, s, n, o, r, i;
1222
+ if (!this.api)
1223
+ throw new Error("ConversationManager not initialized");
1224
+ try {
1225
+ const l = await this.api.post(`/api/chat-users/chats/${e}/block-user`, {
1226
+ userId: t
1227
+ });
1228
+ (a = this.config) != null && a.enableLogging && console.log("🚫 ConversationManager: User blocked in chat", { chatId: e, userId: t }), (s = this.chatSDK.events) == null || s.emit("user.blocked", { chatId: e, userId: t });
1229
+ } catch (l) {
1230
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ ConversationManager: Block user in chat failed", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Failed to block user in chat");
1231
+ }
1232
+ }
1233
+ /**
1234
+ * Unblock a user in a specific chat
1235
+ * @param chatId - Chat/Conversation ID
1236
+ * @param userId - User ID to unblock
1237
+ */
1238
+ async unblockUserInChat(e, t) {
1239
+ var a, s, n, o, r, i;
1240
+ if (!this.api)
1241
+ throw new Error("ConversationManager not initialized");
1242
+ try {
1243
+ const l = await this.api.post(`/api/chat-users/chats/${e}/unblock-user`, {
1244
+ userId: t
1245
+ });
1246
+ (a = this.config) != null && a.enableLogging && console.log("✅ ConversationManager: User unblocked in chat", { chatId: e, userId: t }), (s = this.chatSDK.events) == null || s.emit("user.unblocked", { chatId: e, userId: t });
1247
+ } catch (l) {
1248
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ ConversationManager: Unblock user in chat failed", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Failed to unblock user in chat");
1249
+ }
1250
+ }
1251
+ /**
1252
+ * Get block status for a chat
1253
+ * @param chatId - Chat/Conversation ID
1254
+ * @returns Block status information
1255
+ */
1256
+ async getBlockStatus(e) {
1257
+ var t, a, s, n, o;
1258
+ if (!this.api)
1259
+ throw new Error("ConversationManager not initialized");
1260
+ try {
1261
+ const r = await this.api.get(`/api/chat-users/chats/${e}/block-status`);
1262
+ return (t = this.config) != null && t.enableLogging && console.log("📊 ConversationManager: Block status fetched", { chatId: e }), r.data.data;
1263
+ } catch (r) {
1264
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ ConversationManager: Get block status failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Failed to get block status");
1265
+ }
1266
+ }
1267
+ }
1268
+ class nt {
1269
+ constructor(e) {
1270
+ this.api = null, this.config = null, this.chatSDK = e;
1271
+ }
1272
+ /**
1273
+ * Initialize MessageManager with configuration
1274
+ */
1275
+ async init(e) {
1276
+ this.config = e, this.api = de.create({
1277
+ baseURL: e.apiBaseUrl,
1278
+ headers: {
1279
+ "Content-Type": "application/json"
1280
+ },
1281
+ timeout: e.timeout || 3e4
1282
+ }), this.api.interceptors.request.use(
1283
+ (t) => {
1284
+ const a = localStorage.getItem("chatSDKToken");
1285
+ return a && (t.headers.Authorization = `Bearer ${a}`), t;
1286
+ },
1287
+ (t) => Promise.reject(t)
1288
+ );
1289
+ }
1290
+ /**
1291
+ * Send a text message
1292
+ * @param conversationId - Conversation ID
1293
+ * @param content - Message content
1294
+ * @param metadata - Optional metadata
1295
+ */
1296
+ async sendMessage(e, t, a) {
1297
+ return this.sendMessageWithOptions({
1298
+ conversationId: e,
1299
+ content: t,
1300
+ type: "text",
1301
+ metadata: a
1302
+ });
1303
+ }
1304
+ /**
1305
+ * Send a message with full options
1306
+ * @param options - Send message options
1307
+ */
1308
+ async sendMessageWithOptions(e) {
1309
+ var t;
1310
+ if (!this.api)
1311
+ throw new Error("MessageManager not initialized");
1312
+ if (this.chatSDK.socket && this.chatSDK.socket.isConnected())
1313
+ try {
1314
+ return await this.sendMessageViaSocket(e);
1315
+ } catch (a) {
1316
+ (t = this.config) != null && t.enableLogging && console.warn("⚠️ Socket send failed, falling back to HTTP:", a);
1317
+ }
1318
+ return this.sendMessageViaHttp(e);
1319
+ }
1320
+ /**
1321
+ * Send message via socket
1322
+ */
1323
+ async sendMessageViaSocket(e) {
1324
+ return new Promise((t, a) => {
1325
+ var i, l, d;
1326
+ if (!this.chatSDK.socket || !this.chatSDK.socket.isConnected()) {
1327
+ a(new Error("Socket not connected"));
1328
+ return;
1329
+ }
1330
+ const s = this.chatSDK.getCurrentUser();
1331
+ if (!s) {
1332
+ a(new Error("User not authenticated"));
1333
+ return;
1334
+ }
1335
+ const n = {
1336
+ conversationId: e.conversationId,
1337
+ content: e.content,
1338
+ messageType: e.type || "text",
1339
+ metadata: e.metadata,
1340
+ senderId: s.id,
1341
+ senderName: s.name,
1342
+ senderEmail: s.email
1343
+ }, o = (h) => {
1344
+ this.chatSDK.socket.off("message-sent", o), this.chatSDK.socket.off("message-error", r), t(h);
1345
+ }, r = (h) => {
1346
+ this.chatSDK.socket.off("message-sent", o), this.chatSDK.socket.off("message-error", r), a(new Error(h.message || "Socket send failed"));
1347
+ };
1348
+ this.chatSDK.socket.on("message-sent", o), this.chatSDK.socket.on("message-error", r), this.chatSDK.socket.emit("send_message", n), (i = this.config) != null && i.enableLogging && console.log("📤 MessageManager: Message sent via socket", {
1349
+ conversationId: e.conversationId,
1350
+ content: ((l = e.content) == null ? void 0 : l.substring(0, 50)) + (((d = e.content) == null ? void 0 : d.length) > 50 ? "..." : ""),
1351
+ type: e.type || "text"
1352
+ }), setTimeout(() => {
1353
+ this.chatSDK.socket.off("message-sent", o), this.chatSDK.socket.off("message-error", r), a(new Error("Socket send timeout"));
1354
+ }, 1e4);
1355
+ });
1356
+ }
1357
+ /**
1358
+ * Send message via HTTP (fallback)
1359
+ */
1360
+ async sendMessageViaHttp(e) {
1361
+ var t, a, s, n, o, r, i, l;
1362
+ if (!this.api)
1363
+ throw new Error("MessageManager not initialized");
1364
+ try {
1365
+ const d = await this.api.post("/api/chat-users/messages", {
1366
+ roomId: e.conversationId,
1367
+ content: e.content,
1368
+ messageType: e.type || "text",
1369
+ metadata: e.metadata,
1370
+ replyToMessageId: e.replyToMessageId
1371
+ }), h = d.data.data || d.data.message || d.data;
1372
+ return (t = this.config) != null && t.enableLogging && console.log("📡 Message sent via HTTP:", {
1373
+ id: h.id,
1374
+ content: ((a = h.content) == null ? void 0 : a.substring(0, 50)) + (((s = h.content) == null ? void 0 : s.length) > 50 ? "..." : ""),
1375
+ type: h.type || "text"
1376
+ }), (n = this.chatSDK.events) == null || n.emit("message.sent", { message: h }), h;
1377
+ } catch (d) {
1378
+ throw (o = this.config) != null && o.enableLogging && console.error("❌ MessageManager: HTTP send failed", ((r = d.response) == null ? void 0 : r.data) || d.message), new Error(((l = (i = d.response) == null ? void 0 : i.data) == null ? void 0 : l.message) || "Failed to send message");
1379
+ }
1380
+ }
1381
+ /**
1382
+ * Get message history for a conversation
1383
+ * @param options - Message list options
1384
+ */
1385
+ async getMessages(e) {
1386
+ var t, a, s, n, o;
1387
+ if (!this.api)
1388
+ throw new Error("MessageManager not initialized");
1389
+ try {
1390
+ const r = new URLSearchParams();
1391
+ e.limit && r.append("limit", e.limit.toString()), e.offset && r.append("offset", e.offset.toString()), e.before && r.append("before", e.before), e.after && r.append("after", e.after);
1392
+ const i = await this.api.get(
1393
+ `/api/chat-users/messages/${e.conversationId}?${r.toString()}`
1394
+ );
1395
+ console.log("📡 Get messages response:", i.data), console.log("📡 Raw server messages:", JSON.stringify(i.data, null, 2));
1396
+ const l = i.data.data || i.data.messages || i.data || [];
1397
+ (t = this.config) != null && t.enableLogging && console.log("📥 MessageManager: Messages fetched successfully", {
1398
+ conversationId: e.conversationId,
1399
+ count: l.length
1400
+ });
1401
+ const d = l.map((h) => ({
1402
+ ...h,
1403
+ type: h.messageType || h.type || "text",
1404
+ // ✅ Map messageType to type
1405
+ conversationId: h.roomId || h.conversationId,
1406
+ // ✅ Map roomId to conversationId
1407
+ timestamp: h.createdAt || h.timestamp || (/* @__PURE__ */ new Date()).toISOString()
1408
+ // ✅ Ensure timestamp
1409
+ }));
1410
+ return console.log("📥 Final processed messages:", d), d;
1411
+ } catch (r) {
1412
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ MessageManager: Get messages failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Failed to get messages");
1413
+ }
1414
+ }
1415
+ /**
1416
+ * Get a specific message by ID
1417
+ * @param messageId - Message ID
1418
+ */
1419
+ async getMessage(e) {
1420
+ var t, a, s, n, o;
1421
+ if (!this.api)
1422
+ throw new Error("MessageManager not initialized");
1423
+ try {
1424
+ const r = await this.api.get(`/api/messages/${e}`);
1425
+ return (t = this.config) != null && t.enableLogging && console.log("📄 MessageManager: Message fetched successfully", { messageId: e }), r.data.message;
1426
+ } catch (r) {
1427
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ MessageManager: Get message failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Failed to get message");
1428
+ }
1429
+ }
1430
+ /**
1431
+ * Update a message (edit)
1432
+ * @param messageId - Message ID to update
1433
+ * @param content - New content
1434
+ * @param metadata - Updated metadata
1435
+ */
1436
+ async updateMessage(e, t, a) {
1437
+ var s, n, o, r, i, l;
1438
+ if (!this.api)
1439
+ throw new Error("MessageManager not initialized");
1440
+ try {
1441
+ const h = (await this.api.put(`/api/messages/${e}`, {
1442
+ content: t,
1443
+ metadata: a
1444
+ })).data.message;
1445
+ return (s = this.config) != null && s.enableLogging && console.log("✏️ MessageManager: Message updated successfully", { messageId: e }), (n = this.chatSDK.events) == null || n.emit("message.updated", { message: h }), h;
1446
+ } catch (d) {
1447
+ throw (o = this.config) != null && o.enableLogging && console.error("❌ MessageManager: Update message failed", ((r = d.response) == null ? void 0 : r.data) || d.message), new Error(((l = (i = d.response) == null ? void 0 : i.data) == null ? void 0 : l.message) || "Failed to update message");
1448
+ }
1449
+ }
1450
+ /**
1451
+ * Delete a message
1452
+ * @param messageId - Message ID to delete
1453
+ * @param deleteForEveryone - Whether to delete for all participants
1454
+ */
1455
+ async deleteMessage(e, t = !1) {
1456
+ var a, s, n, o, r, i;
1457
+ if (!this.api)
1458
+ throw new Error("MessageManager not initialized");
1459
+ try {
1460
+ await this.api.delete(`/api/messages/${e}`, {
1461
+ data: { deleteForEveryone: t }
1462
+ }), (a = this.config) != null && a.enableLogging && console.log("🗑️ MessageManager: Message deleted successfully", {
1463
+ messageId: e,
1464
+ deleteForEveryone: t
1465
+ }), (s = this.chatSDK.events) == null || s.emit("message.deleted", { messageId: e, deleteForEveryone: t });
1466
+ } catch (l) {
1467
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ MessageManager: Delete message failed", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Failed to delete message");
1468
+ }
1469
+ }
1470
+ /**
1471
+ * Mark messages as read
1472
+ * @param conversationId - Conversation ID
1473
+ * @param messageIds - Message IDs to mark as read (optional, marks all if not provided)
1474
+ */
1475
+ async markAsRead(e, t) {
1476
+ var a, s, n, o, r, i;
1477
+ if (!this.api)
1478
+ throw new Error("MessageManager not initialized");
1479
+ try {
1480
+ await this.api.put(`/api/conversations/${e}/messages/read`, {
1481
+ messageIds: t
1482
+ }), (a = this.config) != null && a.enableLogging && console.log("👁️ MessageManager: Messages marked as read", {
1483
+ conversationId: e,
1484
+ messageCount: (t == null ? void 0 : t.length) || "all"
1485
+ }), (s = this.chatSDK.events) == null || s.emit("messages.read", { conversationId: e, messageIds: t });
1486
+ } catch (l) {
1487
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ MessageManager: Mark as read failed", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Failed to mark messages as read");
1488
+ }
1489
+ }
1490
+ /**
1491
+ * Search messages
1492
+ * @param options - Search options
1493
+ */
1494
+ async searchMessages(e) {
1495
+ var t, a, s, n, o;
1496
+ if (!this.api)
1497
+ throw new Error("MessageManager not initialized");
1498
+ try {
1499
+ const r = new URLSearchParams();
1500
+ r.append("q", e.query), e.conversationId && r.append("conversationId", e.conversationId), e.limit && r.append("limit", e.limit.toString()), e.offset && r.append("offset", e.offset.toString()), e.messageType && r.append("type", e.messageType);
1501
+ const l = (await this.api.get(`/api/messages/search?${r.toString()}`)).data.messages || [];
1502
+ return (t = this.config) != null && t.enableLogging && console.log("🔍 MessageManager: Messages searched successfully", {
1503
+ query: e.query,
1504
+ count: l.length
1505
+ }), l;
1506
+ } catch (r) {
1507
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ MessageManager: Search messages failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Failed to search messages");
1508
+ }
1509
+ }
1510
+ /**
1511
+ * Send typing indicator
1512
+ * @param conversationId - Conversation ID
1513
+ * @param isTyping - Whether user is typing
1514
+ */
1515
+ async sendTypingIndicator(e, t) {
1516
+ var a, s, n, o;
1517
+ if (!this.api)
1518
+ throw new Error("MessageManager not initialized");
1519
+ try {
1520
+ await this.api.post(`/api/conversations/${e}/typing`, {
1521
+ isTyping: t
1522
+ }), (a = this.config) != null && a.enableLogging && t && console.log("⌨️ MessageManager: Typing indicator sent", { conversationId: e }), (s = this.chatSDK.events) == null || s.emit("typing.indicator", { conversationId: e, isTyping: t });
1523
+ } catch (r) {
1524
+ (n = this.config) != null && n.enableLogging && console.error("❌ MessageManager: Send typing indicator failed", ((o = r.response) == null ? void 0 : o.data) || r.message);
1525
+ }
1526
+ }
1527
+ /**
1528
+ * React to a message (like, heart, etc.)
1529
+ * @param messageId - Message ID
1530
+ * @param reaction - Reaction type
1531
+ */
1532
+ async reactToMessage(e, t) {
1533
+ var a, s, n, o, r, i;
1534
+ if (!this.api)
1535
+ throw new Error("MessageManager not initialized");
1536
+ try {
1537
+ await this.api.post(`/api/messages/${e}/reactions`, {
1538
+ reaction: t
1539
+ }), (a = this.config) != null && a.enableLogging && console.log("😊 MessageManager: Message reaction sent", { messageId: e, reaction: t }), (s = this.chatSDK.events) == null || s.emit("message.reaction", { messageId: e, reaction: t });
1540
+ } catch (l) {
1541
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ MessageManager: React to message failed", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Failed to react to message");
1542
+ }
1543
+ }
1544
+ /**
1545
+ * Remove reaction from a message
1546
+ * @param messageId - Message ID
1547
+ * @param reaction - Reaction type to remove
1548
+ */
1549
+ async removeReaction(e, t) {
1550
+ var a, s, n, o, r, i;
1551
+ if (!this.api)
1552
+ throw new Error("MessageManager not initialized");
1553
+ try {
1554
+ await this.api.delete(`/api/messages/${e}/reactions/${t}`), (a = this.config) != null && a.enableLogging && console.log("🗑️ MessageManager: Message reaction removed", { messageId: e, reaction: t }), (s = this.chatSDK.events) == null || s.emit("message.reaction.removed", { messageId: e, reaction: t });
1555
+ } catch (l) {
1556
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ MessageManager: Remove reaction failed", ((o = l.response) == null ? void 0 : o.data) || l.message), new Error(((i = (r = l.response) == null ? void 0 : r.data) == null ? void 0 : i.message) || "Failed to remove reaction");
1557
+ }
1558
+ }
1559
+ }
1560
+ class rt {
1561
+ constructor(e) {
1562
+ this.api = null, this.config = null, this.maxFileSize = 50 * 1024 * 1024, this.allowedTypes = [
1563
+ "image/jpeg",
1564
+ "image/png",
1565
+ "image/gif",
1566
+ "image/webp",
1567
+ "video/mp4",
1568
+ "video/webm",
1569
+ "video/quicktime",
1570
+ "audio/mpeg",
1571
+ "audio/wav",
1572
+ "audio/ogg",
1573
+ "application/pdf",
1574
+ "application/msword",
1575
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1576
+ "application/vnd.ms-excel",
1577
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1578
+ "text/plain"
1579
+ ], this.chatSDK = e;
1580
+ }
1581
+ /**
1582
+ * Initialize MediaManager with configuration
1583
+ */
1584
+ async init(e) {
1585
+ this.config = e, this.api = de.create({
1586
+ baseURL: e.apiBaseUrl,
1587
+ headers: {
1588
+ "Content-Type": "application/json"
1589
+ },
1590
+ timeout: e.timeout || 3e4
1591
+ }), this.api.interceptors.request.use(
1592
+ (t) => {
1593
+ const a = localStorage.getItem("chatSDKToken");
1594
+ return a && (t.headers.Authorization = `Bearer ${a}`), t;
1595
+ },
1596
+ (t) => Promise.reject(t)
1597
+ );
1598
+ }
1599
+ /**
1600
+ * Upload a file/media
1601
+ * @param options - Upload options
1602
+ */
1603
+ async uploadMedia(e) {
1604
+ var t, a, s, n, o, r;
1605
+ if (!this.api)
1606
+ throw new Error("MediaManager not initialized");
1607
+ this.validateFile(e.file);
1608
+ try {
1609
+ const i = new FormData();
1610
+ i.append("file", e.file), i.append("type", e.type), e.conversationId && i.append("chatId", e.conversationId), e.caption && i.append("caption", e.caption), e.metadata && i.append("metadata", JSON.stringify(e.metadata));
1611
+ const d = (await this.api.post("/api/chat-users/upload", i, {
1612
+ headers: {
1613
+ "Content-Type": "multipart/form-data"
1614
+ },
1615
+ onUploadProgress: (h) => {
1616
+ if (e.onProgress && h.total) {
1617
+ const m = Math.round(h.loaded * 100 / h.total);
1618
+ e.onProgress(m);
1619
+ }
1620
+ },
1621
+ timeout: 300 * 1e3
1622
+ // 5 minutes for file upload
1623
+ })).data.data;
1624
+ return (t = this.config) != null && t.enableLogging && console.log("📎 MediaManager: File uploaded successfully", {
1625
+ url: d.fileUrl,
1626
+ fileName: d.fileName,
1627
+ fileSize: d.fileSize,
1628
+ mimeType: d.mimeType,
1629
+ type: e.type
1630
+ }), (a = this.chatSDK.events) == null || a.emit("media.uploaded", { media: d }), d;
1631
+ } catch (i) {
1632
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ MediaManager: Upload failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to upload file");
1633
+ }
1634
+ }
1635
+ /**
1636
+ * Upload image and send as message
1637
+ * @param conversationId - Conversation ID
1638
+ * @param file - Image file
1639
+ * @param caption - Optional caption
1640
+ */
1641
+ async sendImage(e, t, a) {
1642
+ return this.uploadMedia({
1643
+ file: t,
1644
+ type: "image",
1645
+ conversationId: e,
1646
+ caption: a
1647
+ });
1648
+ }
1649
+ /**
1650
+ * Upload video and send as message
1651
+ * @param conversationId - Conversation ID
1652
+ * @param file - Video file
1653
+ * @param caption - Optional caption
1654
+ */
1655
+ async sendVideo(e, t, a) {
1656
+ return this.uploadMedia({
1657
+ file: t,
1658
+ type: "video",
1659
+ conversationId: e,
1660
+ caption: a
1661
+ });
1662
+ }
1663
+ /**
1664
+ * Upload audio and send as message
1665
+ * @param conversationId - Conversation ID
1666
+ * @param file - Audio file
1667
+ * @param caption - Optional caption
1668
+ */
1669
+ async sendAudio(e, t, a) {
1670
+ return this.uploadMedia({
1671
+ file: t,
1672
+ type: "audio",
1673
+ conversationId: e,
1674
+ caption: a
1675
+ });
1676
+ }
1677
+ /**
1678
+ * Upload document and send as message
1679
+ * @param conversationId - Conversation ID
1680
+ * @param file - Document file
1681
+ * @param caption - Optional caption
1682
+ */
1683
+ async sendDocument(e, t, a) {
1684
+ return this.uploadMedia({
1685
+ file: t,
1686
+ type: "document",
1687
+ conversationId: e,
1688
+ caption: a
1689
+ });
1690
+ }
1691
+ /**
1692
+ * Get media information
1693
+ * @param mediaId - Media ID
1694
+ */
1695
+ async getMedia(e) {
1696
+ var t, a, s, n, o;
1697
+ if (!this.api)
1698
+ throw new Error("MediaManager not initialized");
1699
+ try {
1700
+ const r = await this.api.get(`/api/media/${e}`);
1701
+ return (t = this.config) != null && t.enableLogging && console.log("📄 MediaManager: Media info fetched successfully", { mediaId: e }), r.data.media;
1702
+ } catch (r) {
1703
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ MediaManager: Get media failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Failed to get media");
1704
+ }
1705
+ }
1706
+ /**
1707
+ * Get download URL for media
1708
+ * @param options - Download options
1709
+ */
1710
+ async getDownloadUrl(e) {
1711
+ var t, a, s, n, o;
1712
+ if (!this.api)
1713
+ throw new Error("MediaManager not initialized");
1714
+ try {
1715
+ const r = new URLSearchParams();
1716
+ e.quality && r.append("quality", e.quality);
1717
+ const l = (await this.api.get(
1718
+ `/api/media/${e.mediaId}/download?${r.toString()}`
1719
+ )).data.url;
1720
+ return (t = this.config) != null && t.enableLogging && console.log("🔗 MediaManager: Download URL generated", {
1721
+ mediaId: e.mediaId,
1722
+ quality: e.quality
1723
+ }), l;
1724
+ } catch (r) {
1725
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ MediaManager: Get download URL failed", ((s = r.response) == null ? void 0 : s.data) || r.message), new Error(((o = (n = r.response) == null ? void 0 : n.data) == null ? void 0 : o.message) || "Failed to get download URL");
1726
+ }
1727
+ }
1728
+ /**
1729
+ * Delete media
1730
+ * @param mediaId - Media ID to delete
1731
+ */
1732
+ async deleteMedia(e) {
1733
+ var t, a, s, n, o, r;
1734
+ if (!this.api)
1735
+ throw new Error("MediaManager not initialized");
1736
+ try {
1737
+ await this.api.delete(`/api/media/${e}`), (t = this.config) != null && t.enableLogging && console.log("🗑️ MediaManager: Media deleted successfully", { mediaId: e }), (a = this.chatSDK.events) == null || a.emit("media.deleted", { mediaId: e });
1738
+ } catch (i) {
1739
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ MediaManager: Delete media failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to delete media");
1740
+ }
1741
+ }
1742
+ /**
1743
+ * Generate thumbnail for media
1744
+ * @param mediaId - Media ID
1745
+ * @param size - Thumbnail size
1746
+ */
1747
+ async generateThumbnail(e, t = "medium") {
1748
+ var a, s, n, o, r;
1749
+ if (!this.api)
1750
+ throw new Error("MediaManager not initialized");
1751
+ try {
1752
+ const l = (await this.api.post(`/api/media/${e}/thumbnail`, { size: t })).data.thumbnailUrl;
1753
+ return (a = this.config) != null && a.enableLogging && console.log("🖼️ MediaManager: Thumbnail generated", { mediaId: e, size: t }), l;
1754
+ } catch (i) {
1755
+ throw (s = this.config) != null && s.enableLogging && console.error("❌ MediaManager: Generate thumbnail failed", ((n = i.response) == null ? void 0 : n.data) || i.message), new Error(((r = (o = i.response) == null ? void 0 : o.data) == null ? void 0 : r.message) || "Failed to generate thumbnail");
1756
+ }
1757
+ }
1758
+ /**
1759
+ * Set maximum file size
1760
+ * @param sizeInBytes - Maximum file size in bytes
1761
+ */
1762
+ setMaxFileSize(e) {
1763
+ var t;
1764
+ this.maxFileSize = e, (t = this.config) != null && t.enableLogging && console.log("📏 MediaManager: Max file size updated", {
1765
+ sizeInMB: Math.round(e / (1024 * 1024))
1766
+ });
1767
+ }
1768
+ /**
1769
+ * Set allowed file types
1770
+ * @param mimeTypes - Array of allowed MIME types
1771
+ */
1772
+ setAllowedTypes(e) {
1773
+ var t;
1774
+ this.allowedTypes = e, (t = this.config) != null && t.enableLogging && console.log("📋 MediaManager: Allowed types updated", { types: e });
1775
+ }
1776
+ /**
1777
+ * Validate file before upload
1778
+ * @param file - File to validate
1779
+ */
1780
+ validateFile(e) {
1781
+ if (e.size > this.maxFileSize)
1782
+ throw new Error(`File size exceeds maximum allowed size of ${Math.round(this.maxFileSize / (1024 * 1024))}MB`);
1783
+ if (!this.allowedTypes.includes(e.type))
1784
+ throw new Error(`File type ${e.type} is not allowed`);
1785
+ if (!e.name || e.name.trim().length === 0)
1786
+ throw new Error("File must have a valid name");
1787
+ }
1788
+ /**
1789
+ * Check if file type is supported
1790
+ * @param mimeType - MIME type to check
1791
+ */
1792
+ isTypeSupported(e) {
1793
+ return this.allowedTypes.includes(e);
1794
+ }
1795
+ /**
1796
+ * Get file type category from MIME type
1797
+ * @param mimeType - MIME type
1798
+ */
1799
+ getFileTypeCategory(e) {
1800
+ return e.startsWith("image/") ? "image" : e.startsWith("video/") ? "video" : e.startsWith("audio/") ? "audio" : "document";
1801
+ }
1802
+ /**
1803
+ * Format file size in human readable format
1804
+ * @param bytes - File size in bytes
1805
+ */
1806
+ formatFileSize(e) {
1807
+ if (e === 0) return "0 Bytes";
1808
+ const t = 1024, a = ["Bytes", "KB", "MB", "GB"], s = Math.floor(Math.log(e) / Math.log(t));
1809
+ return parseFloat((e / Math.pow(t, s)).toFixed(2)) + " " + a[s];
1810
+ }
1811
+ }
1812
+ class ot {
1813
+ constructor(e) {
1814
+ this.config = null, this.socket = null, this.eventListeners = /* @__PURE__ */ new Map(), this.isConnected = !1, this.reconnectAttempts = 0, this.maxReconnectAttempts = 5, this.reconnectDelay = 1e3, this.heartbeatInterval = null, this.connectionTimeout = null, this.chatSDK = e;
1815
+ }
1816
+ /**
1817
+ * Initialize EventManager with configuration
1818
+ */
1819
+ async init(e) {
1820
+ var t;
1821
+ this.config = e, (t = this.config) != null && t.enableLogging && console.log("📡 EventManager: Initialized");
1822
+ }
1823
+ /**
1824
+ * Connect to WebSocket for real-time events
1825
+ * NOTE: Disabled - using Socket.io SocketManager instead
1826
+ */
1827
+ async connect() {
1828
+ var e;
1829
+ if (!this.config)
1830
+ throw new Error("EventManager not initialized");
1831
+ return (e = this.config) != null && e.enableLogging && console.log("📡 EventManager: Skipping native WebSocket connection (using Socket.io instead)"), this.isConnected = !0, Promise.resolve();
1832
+ }
1833
+ /**
1834
+ * Disconnect from WebSocket
1835
+ * NOTE: Disabled - using Socket.io SocketManager instead
1836
+ */
1837
+ async disconnect() {
1838
+ var e;
1839
+ return (e = this.config) != null && e.enableLogging && console.log("📡 EventManager: Skipping native WebSocket disconnection (using Socket.io instead)"), this.isConnected = !1, Promise.resolve();
1840
+ }
1841
+ /**
1842
+ * Add event listener
1843
+ * @param event - Event name
1844
+ * @param callback - Callback function
1845
+ */
1846
+ on(e, t) {
1847
+ var a;
1848
+ this.eventListeners.has(e) || this.eventListeners.set(e, []), this.eventListeners.get(e).push(t), (a = this.config) != null && a.enableLogging && console.log("👂 EventManager: Event listener added", { event: e });
1849
+ }
1850
+ /**
1851
+ * Remove event listener
1852
+ * @param event - Event name
1853
+ * @param callback - Callback function to remove
1854
+ */
1855
+ off(e, t) {
1856
+ var s;
1857
+ if (!t) {
1858
+ this.eventListeners.delete(e);
1859
+ return;
1860
+ }
1861
+ const a = this.eventListeners.get(e);
1862
+ if (a) {
1863
+ const n = a.indexOf(t);
1864
+ n > -1 && a.splice(n, 1), a.length === 0 && this.eventListeners.delete(e);
1865
+ }
1866
+ (s = this.config) != null && s.enableLogging && console.log("🔇 EventManager: Event listener removed", { event: e });
1867
+ }
1868
+ /**
1869
+ * Emit local event
1870
+ * @param event - Event name
1871
+ * @param data - Event data
1872
+ */
1873
+ emit(e, t) {
1874
+ var s;
1875
+ const a = this.eventListeners.get(e);
1876
+ a && a.forEach((n) => {
1877
+ var o;
1878
+ try {
1879
+ n(t);
1880
+ } catch (r) {
1881
+ (o = this.config) != null && o.enableLogging && console.error("❌ EventManager: Error in event callback", { event: e, error: r });
1882
+ }
1883
+ }), (s = this.config) != null && s.enableLogging && console.log("📢 EventManager: Event emitted", { event: e, data: t });
1884
+ }
1885
+ /**
1886
+ * Send message through WebSocket
1887
+ * @param type - Message type
1888
+ * @param data - Message data
1889
+ */
1890
+ send(e, t) {
1891
+ var s, n, o;
1892
+ if (!this.isConnected || !this.socket) {
1893
+ (s = this.config) != null && s.enableLogging && console.warn("⚠️ EventManager: Cannot send message - not connected");
1894
+ return;
1895
+ }
1896
+ const a = {
1897
+ type: e,
1898
+ data: t,
1899
+ timestamp: Date.now()
1900
+ };
1901
+ try {
1902
+ this.socket.send(JSON.stringify(a)), (n = this.config) != null && n.enableLogging && console.log("📤 EventManager: Message sent", { type: e, data: t });
1903
+ } catch (r) {
1904
+ (o = this.config) != null && o.enableLogging && console.error("❌ EventManager: Failed to send message", { type: e, error: r });
1905
+ }
1906
+ }
1907
+ /**
1908
+ * Check if connected to WebSocket
1909
+ */
1910
+ isSocketConnected() {
1911
+ var e;
1912
+ return this.isConnected && ((e = this.socket) == null ? void 0 : e.readyState) === WebSocket.OPEN;
1913
+ }
1914
+ /**
1915
+ * Get connection status
1916
+ */
1917
+ getConnectionStatus() {
1918
+ if (!this.socket) return "disconnected";
1919
+ switch (this.socket.readyState) {
1920
+ case WebSocket.CONNECTING:
1921
+ return "connecting";
1922
+ case WebSocket.OPEN:
1923
+ return "connected";
1924
+ case WebSocket.CLOSING:
1925
+ case WebSocket.CLOSED:
1926
+ return "disconnected";
1927
+ default:
1928
+ return "error";
1929
+ }
1930
+ }
1931
+ // Private methods for WebSocket event handling
1932
+ handleOpen(e) {
1933
+ var t;
1934
+ this.isConnected = !0, this.reconnectAttempts = 0, this.reconnectDelay = 1e3, this.connectionTimeout && (clearTimeout(this.connectionTimeout), this.connectionTimeout = null), this.startHeartbeat(), (t = this.config) != null && t.enableLogging && console.log("✅ EventManager: WebSocket connected"), this.emit("connection.open", { timestamp: Date.now() });
1935
+ }
1936
+ handleMessage(e) {
1937
+ var t, a;
1938
+ try {
1939
+ const s = JSON.parse(e.data);
1940
+ if ((t = this.config) != null && t.enableLogging && console.log("📥 EventManager: Message received", s), s.type === "heartbeat") {
1941
+ this.send("heartbeat", { timestamp: Date.now() });
1942
+ return;
1943
+ }
1944
+ this.emit(s.type, s.data), this.emit("message.received", s);
1945
+ } catch (s) {
1946
+ (a = this.config) != null && a.enableLogging && console.error("❌ EventManager: Failed to parse message", { data: e.data, error: s });
1947
+ }
1948
+ }
1949
+ handleClose(e) {
1950
+ var t;
1951
+ this.isConnected = !1, this.heartbeatInterval && (clearInterval(this.heartbeatInterval), this.heartbeatInterval = null), (t = this.config) != null && t.enableLogging && console.log("🔌 EventManager: WebSocket closed", {
1952
+ code: e.code,
1953
+ reason: e.reason,
1954
+ wasClean: e.wasClean
1955
+ }), this.emit("connection.close", {
1956
+ code: e.code,
1957
+ reason: e.reason,
1958
+ timestamp: Date.now()
1959
+ }), !e.wasClean && this.reconnectAttempts < this.maxReconnectAttempts && this.attemptReconnect();
1960
+ }
1961
+ handleError(e) {
1962
+ var t;
1963
+ (t = this.config) != null && t.enableLogging && console.error("❌ EventManager: WebSocket error", e), this.emit("connection.error", {
1964
+ error: e,
1965
+ timestamp: Date.now()
1966
+ });
1967
+ }
1968
+ startHeartbeat() {
1969
+ this.heartbeatInterval && clearInterval(this.heartbeatInterval), this.heartbeatInterval = setInterval(() => {
1970
+ this.isConnected && this.send("ping", { timestamp: Date.now() });
1971
+ }, 3e4);
1972
+ }
1973
+ attemptReconnect() {
1974
+ var e, t;
1975
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
1976
+ (e = this.config) != null && e.enableLogging && console.error("❌ EventManager: Max reconnection attempts reached"), this.emit("connection.failed", {
1977
+ attempts: this.reconnectAttempts,
1978
+ timestamp: Date.now()
1979
+ });
1980
+ return;
1981
+ }
1982
+ this.reconnectAttempts++, (t = this.config) != null && t.enableLogging && console.log(`🔄 EventManager: Attempting reconnection ${this.reconnectAttempts}/${this.maxReconnectAttempts}`), setTimeout(() => {
1983
+ this.connect().catch((a) => {
1984
+ var s;
1985
+ (s = this.config) != null && s.enableLogging && console.error("❌ EventManager: Reconnection failed", a), this.attemptReconnect();
1986
+ });
1987
+ }, this.reconnectDelay), this.reconnectDelay = Math.min(this.reconnectDelay * 2, 3e4);
1988
+ }
1989
+ /**
1990
+ * Set maximum reconnection attempts
1991
+ * @param attempts - Maximum number of attempts
1992
+ */
1993
+ setMaxReconnectAttempts(e) {
1994
+ this.maxReconnectAttempts = e;
1995
+ }
1996
+ /**
1997
+ * Clear all event listeners
1998
+ */
1999
+ clearAllListeners() {
2000
+ var e;
2001
+ this.eventListeners.clear(), (e = this.config) != null && e.enableLogging && console.log("🧹 EventManager: All event listeners cleared");
2002
+ }
2003
+ /**
2004
+ * Get list of active event listeners
2005
+ */
2006
+ getActiveListeners() {
2007
+ return Array.from(this.eventListeners.keys());
2008
+ }
2009
+ }
2010
+ class Ue {
2011
+ /**
2012
+ * Parse user data - handles standard server format only
2013
+ * @param data User data from server
2014
+ * @returns Validated ChatSDKUser object
2015
+ */
2016
+ static parseUser(e) {
2017
+ if (!e)
2018
+ throw new Error("User data is required");
2019
+ return {
2020
+ id: e.id,
2021
+ externalUserId: e.externalUserId,
2022
+ appId: e.appId,
2023
+ name: e.name,
2024
+ username: e.username,
2025
+ displayName: e.displayName,
2026
+ email: e.email,
2027
+ avatar: e.avatar,
2028
+ avatarUrl: e.avatarUrl,
2029
+ status: e.status || "offline",
2030
+ isOnline: e.isOnline || !1,
2031
+ isRegistered: e.isRegistered || !0,
2032
+ lastSeen: e.lastSeen,
2033
+ createdAt: e.createdAt,
2034
+ updatedAt: e.updatedAt,
2035
+ metadata: e.metadata || {},
2036
+ // Include any other server fields as-is
2037
+ ...e
2038
+ };
2039
+ }
2040
+ /**
2041
+ * Parse message data - handles WebSocket and HTTP API formats only
2042
+ * @param data Message data from server
2043
+ * @returns Validated ChatSDKMessage object
2044
+ */
2045
+ static parseMessage(e) {
2046
+ var s, n, o;
2047
+ if (!e)
2048
+ throw new Error("Message data is required");
2049
+ let t = e.type || "text";
2050
+ if (t === "text" && ((s = e.metadata) != null && s.fileUrl) && ((n = e.metadata) != null && n.mimeType)) {
2051
+ const r = e.metadata.mimeType;
2052
+ r.startsWith("image/") ? t = "image" : r.startsWith("video/") ? t = "video" : r.startsWith("audio/") ? t = "audio" : t = "file";
2053
+ }
2054
+ const a = {
2055
+ id: e.id,
2056
+ content: e.content,
2057
+ senderId: e.senderId,
2058
+ // Use standard camelCase - only the keys that actually come from server
2059
+ roomId: e.roomId || e.conversationId,
2060
+ // Keep this minimal fallback for WebSocket vs HTTP
2061
+ conversationId: e.conversationId || e.roomId,
2062
+ // Required by ChatSDKMessage type
2063
+ // Sender info (only standard camelCase fields)
2064
+ senderName: e.senderName,
2065
+ senderEmail: e.senderEmail,
2066
+ senderAvatar: e.senderAvatar,
2067
+ senderExternalUserId: e.senderExternalUserId,
2068
+ // Use the determined message type
2069
+ messageType: t,
2070
+ type: t,
2071
+ // Required status fields
2072
+ status: e.status || "sent",
2073
+ isRead: e.isRead || !1,
2074
+ isDelivered: e.isDelivered || !1,
2075
+ // Timestamps (standard fields only)
2076
+ timestamp: e.timestamp,
2077
+ createdAt: e.createdAt,
2078
+ updatedAt: e.updatedAt,
2079
+ // Keep metadata as-is - file info stays in metadata where ChatWindow expects it
2080
+ metadata: e.metadata || {}
2081
+ };
2082
+ return console.log("✅ ParseUtils: Parsed message:", {
2083
+ id: a.id,
2084
+ type: a.type,
2085
+ messageType: a.messageType,
2086
+ roomId: a.roomId,
2087
+ hasMetadata: !!a.metadata,
2088
+ metadataKeys: Object.keys(a.metadata || {}),
2089
+ fileUrl: (o = a.metadata) == null ? void 0 : o.fileUrl
2090
+ }), a;
2091
+ }
2092
+ /**
2093
+ * Parse conversation data - handles standard server format only
2094
+ * @param data Conversation data from server
2095
+ * @returns Validated ChatSDKConversation object
2096
+ */
2097
+ static parseConversation(e) {
2098
+ if (!e)
2099
+ throw new Error("Conversation data is required");
2100
+ return {
2101
+ id: e.id,
2102
+ conversationId: e.conversationId || e.id,
2103
+ name: e.name,
2104
+ description: e.description,
2105
+ type: e.type || "direct",
2106
+ avatar: e.avatar,
2107
+ participants: Array.isArray(e.participants) ? e.participants.map((t) => this.parseUser(t)) : [],
2108
+ lastMessage: e.lastMessage ? this.parseMessage(e.lastMessage) : null,
2109
+ productContext: e.productContext ? this.parseProductContext(e.productContext) : void 0,
2110
+ metadata: e.metadata || {},
2111
+ createdAt: e.createdAt,
2112
+ updatedAt: e.updatedAt,
2113
+ // Include any other server fields as-is
2114
+ ...e
2115
+ };
2116
+ }
2117
+ /**
2118
+ * Parse product context - handles standard server format only
2119
+ * @param data Product context data from server
2120
+ * @returns Validated ProductContext object or undefined
2121
+ */
2122
+ static parseProductContext(e) {
2123
+ if (e)
2124
+ return {
2125
+ productId: e.productId,
2126
+ productName: e.productName,
2127
+ productImage: e.productImage,
2128
+ price: e.price,
2129
+ currency: e.currency,
2130
+ category: e.category,
2131
+ productMetadata: e.productMetadata || {},
2132
+ // Include any other server fields as-is
2133
+ ...e
2134
+ };
2135
+ }
2136
+ /**
2137
+ * Simple array validation - server returns consistent data
2138
+ */
2139
+ static parseMessages(e) {
2140
+ return Array.isArray(e) ? e : [];
2141
+ }
2142
+ static parseConversations(e) {
2143
+ return Array.isArray(e) ? e : [];
2144
+ }
2145
+ static parseUsers(e) {
2146
+ return Array.isArray(e) ? e : [];
2147
+ }
2148
+ }
2149
+ class it {
2150
+ constructor(e) {
2151
+ this.socket = null, this.config = null, this.currentUserId = null, this.joinedRooms = /* @__PURE__ */ new Set(), this.chatSDK = e;
2152
+ }
2153
+ /**
2154
+ * Initialize SocketManager with configuration
2155
+ */
2156
+ async init(e) {
2157
+ var t, a, s, n;
2158
+ this.config = e, (t = this.config) != null && t.enableLogging && console.log("🔌 SocketManager: Starting initialization...", {
2159
+ apiBaseUrl: e.apiBaseUrl,
2160
+ enableLogging: e.enableLogging
2161
+ });
2162
+ try {
2163
+ let o = e.wsUrl;
2164
+ !o && e.apiBaseUrl && (o = e.apiBaseUrl.replace(/\/api\/?$/, "")), o || (o = e.environment === "production" ? "https://chatsdk-mzad-admin.onrender.com" : "http://localhost:5001"), (a = this.config) != null && a.enableLogging && console.log("🔌 SocketManager: Creating socket connection to:", o, {
2165
+ wsUrl: e.wsUrl,
2166
+ apiBaseUrl: e.apiBaseUrl,
2167
+ environment: e.environment
2168
+ }), this.socket = Ye(o, {
2169
+ transports: ["websocket", "polling"],
2170
+ // Try websocket first, fallback to polling
2171
+ autoConnect: !1,
2172
+ forceNew: !0,
2173
+ // ✅ Connection & Keep-Alive Settings - Match server configuration
2174
+ timeout: 45e3,
2175
+ // 45 seconds - initial connection timeout (matches server)
2176
+ reconnection: !0,
2177
+ // Enable automatic reconnection
2178
+ reconnectionAttempts: 10,
2179
+ // Try up to 10 times
2180
+ reconnectionDelay: 2e3,
2181
+ // 2 seconds - initial delay
2182
+ reconnectionDelayMax: 1e4,
2183
+ // 10 seconds - max delay with exponential backoff
2184
+ // ✅ Additional settings for stability
2185
+ upgrade: !0,
2186
+ // Allow upgrade from polling to websocket
2187
+ rememberUpgrade: !1
2188
+ // Don't remember upgrade preference (test each time)
2189
+ }), this.setupEventListeners(), (s = this.config) != null && s.enableLogging && console.log("✅ SocketManager: Initialized successfully with socket:", !!this.socket);
2190
+ } catch (o) {
2191
+ throw (n = this.config) != null && n.enableLogging && console.error("❌ SocketManager: Initialization failed", o), o;
2192
+ }
2193
+ }
2194
+ /**
2195
+ * Connect to WebSocket server
2196
+ */
2197
+ async connect(e) {
2198
+ var a, s, n, o, r, i, l;
2199
+ if (!this.socket)
2200
+ throw new Error("SocketManager not initialized");
2201
+ this.currentUserId = e;
2202
+ let t = (a = this.config) == null ? void 0 : a.wsUrl;
2203
+ return !t && ((s = this.config) != null && s.apiBaseUrl) && (t = this.config.apiBaseUrl.replace(/\/api\/?$/, "")), t || (t = ((n = this.config) == null ? void 0 : n.environment) === "production" ? "https://chatsdk-mzad-admin.onrender.com" : "http://localhost:5001"), (o = this.config) != null && o.enableLogging && console.log("🔌 SocketManager: Attempting to connect to WebSocket server...", {
2204
+ userId: e,
2205
+ socketUrl: t,
2206
+ wsUrl: (r = this.config) == null ? void 0 : r.wsUrl,
2207
+ apiBaseUrl: (i = this.config) == null ? void 0 : i.apiBaseUrl,
2208
+ environment: (l = this.config) == null ? void 0 : l.environment,
2209
+ hasSocket: !!this.socket
2210
+ }), new Promise((d, h) => {
2211
+ const m = setTimeout(() => {
2212
+ var p;
2213
+ (p = this.config) != null && p.enableLogging && console.error("❌ SocketManager: Connection timeout after 10 seconds"), h(new Error("Connection timeout"));
2214
+ }, 1e4);
2215
+ this.socket.connect(), this.socket.on("connect", () => {
2216
+ var p, E, P;
2217
+ clearTimeout(m), (p = this.config) != null && p.enableLogging && console.log("✅ SocketManager: Connected to WebSocket server successfully!"), this.socket.emit("authenticate", { userId: e, appId: (E = this.config) == null ? void 0 : E.appId }), (P = this.config) != null && P.enableLogging && console.log("🔐 SocketManager: Sent authentication for user:", e), d();
2218
+ }), this.socket.on("connect_error", (p) => {
2219
+ var E;
2220
+ clearTimeout(m), (E = this.config) != null && E.enableLogging && console.error("❌ SocketManager: Connection failed with error:", p), h(p);
2221
+ }), this.socket.on("disconnect", (p) => {
2222
+ var E;
2223
+ (E = this.config) != null && E.enableLogging && console.log("🔌 SocketManager: Disconnected from server, reason:", p);
2224
+ });
2225
+ });
2226
+ }
2227
+ /**
2228
+ * Disconnect from WebSocket server
2229
+ */
2230
+ disconnect() {
2231
+ var e;
2232
+ this.socket && (this.socket.disconnect(), this.joinedRooms.clear(), (e = this.config) != null && e.enableLogging && console.log("�� SocketManager: Disconnected from WebSocket server"));
2233
+ }
2234
+ /**
2235
+ * Join a conversation for real-time messages
2236
+ */
2237
+ joinConversation(e) {
2238
+ var t, a, s;
2239
+ if (!this.socket || !this.socket.connected) {
2240
+ (t = this.config) != null && t.enableLogging && console.warn("SocketManager: Cannot join conversation - not connected");
2241
+ return;
2242
+ }
2243
+ this.joinedRooms.has(e) || (this.socket.emit("join_conversation", {
2244
+ conversationId: e,
2245
+ appId: (a = this.config) == null ? void 0 : a.appId
2246
+ }), this.joinedRooms.add(e), (s = this.config) != null && s.enableLogging && console.log(`🏠 SocketManager: Joined conversation ${e}`));
2247
+ }
2248
+ /**
2249
+ * Leave a conversation
2250
+ */
2251
+ leaveConversation(e) {
2252
+ var t;
2253
+ !this.socket || !this.socket.connected || this.joinedRooms.has(e) && (this.socket.emit("leave_conversation", { conversationId: e }), this.joinedRooms.delete(e), (t = this.config) != null && t.enableLogging && console.log(`🏠 SocketManager: Left conversation ${e}`));
2254
+ }
2255
+ /**
2256
+ * Send typing indicator
2257
+ */
2258
+ sendTypingIndicator(e, t) {
2259
+ var a, s;
2260
+ if (!this.socket || !this.socket.connected) {
2261
+ (a = this.config) != null && a.enableLogging && console.warn("SocketManager: Cannot send typing indicator - not connected");
2262
+ return;
2263
+ }
2264
+ this.socket.emit("typing_indicator", {
2265
+ conversationId: e,
2266
+ isTyping: t,
2267
+ userId: this.currentUserId
2268
+ }), (s = this.config) != null && s.enableLogging && console.log(`⌨️ SocketManager: Typing indicator sent: ${t} for conversation ${e}`);
2269
+ }
2270
+ /**
2271
+ * Send a real-time message
2272
+ */
2273
+ sendMessage(e) {
2274
+ var a, s;
2275
+ if (!this.socket || !this.socket.connected) {
2276
+ (a = this.config) != null && a.enableLogging && console.warn("SocketManager: Cannot send message - not connected");
2277
+ return;
2278
+ }
2279
+ const t = {
2280
+ ...e,
2281
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2282
+ senderId: this.currentUserId || e.senderId
2283
+ };
2284
+ this.socket.emit("send-message", t), (s = this.config) != null && s.enableLogging && console.log("📤 SocketManager: Message sent via WebSocket", t);
2285
+ }
2286
+ /**
2287
+ * Set up event listeners for real-time events
2288
+ */
2289
+ setupEventListeners() {
2290
+ this.socket && (this.socket.on("message_received", (e) => {
2291
+ var t, a, s;
2292
+ try {
2293
+ const n = Ue.parseMessage(e);
2294
+ (t = this.chatSDK.events) == null || t.emit("message.received", { message: n });
2295
+ } catch (n) {
2296
+ (a = this.config) != null && a.enableLogging && console.error("❌ SocketManager: Failed to parse received message", n), (s = this.chatSDK.events) == null || s.emit("message.received", { message: e });
2297
+ }
2298
+ }), this.socket.on("typing_indicator", (e) => {
2299
+ var t, a, s, n;
2300
+ try {
2301
+ const o = {
2302
+ userId: e.userId || e.user_id,
2303
+ conversationId: e.conversationId || e.conversation_id || e.room_id,
2304
+ isTyping: e.isTyping || e.is_typing,
2305
+ timestamp: e.timestamp || e.created_at
2306
+ };
2307
+ (t = this.config) != null && t.enableLogging && console.log("⌨️ SocketManager: Typing indicator received", o), (a = this.chatSDK.events) == null || a.emit("typing.indicator", o);
2308
+ } catch (o) {
2309
+ (s = this.config) != null && s.enableLogging && console.error("❌ SocketManager: Failed to process typing indicator", o), (n = this.chatSDK.events) == null || n.emit("typing.indicator", e);
2310
+ }
2311
+ }), this.socket.on("user_status_changed", (e) => {
2312
+ var t, a, s, n;
2313
+ try {
2314
+ const o = {
2315
+ userId: e.userId || e.user_id,
2316
+ status: e.status,
2317
+ timestamp: e.timestamp || e.updated_at || e.last_seen
2318
+ };
2319
+ (t = this.config) != null && t.enableLogging && console.log("👤 SocketManager: User status update", o), (a = this.chatSDK.events) == null || a.emit("user.status.changed", o);
2320
+ } catch (o) {
2321
+ (s = this.config) != null && s.enableLogging && console.error("❌ SocketManager: Failed to process user status update", o), (n = this.chatSDK.events) == null || n.emit("user.status.changed", e);
2322
+ }
2323
+ }), this.socket.on("conversation_updated", (e) => {
2324
+ var t, a, s, n;
2325
+ try {
2326
+ const o = {
2327
+ conversationId: e.conversationId || e.conversation_id || e.room_id,
2328
+ lastMessage: e.lastMessage || e.last_message,
2329
+ unreadCount: e.unreadCount || e.unread_count,
2330
+ timestamp: e.timestamp || e.updated_at
2331
+ };
2332
+ (t = this.config) != null && t.enableLogging && console.log("💬 SocketManager: Conversation update", o), (a = this.chatSDK.events) == null || a.emit("conversation.updated", o);
2333
+ } catch (o) {
2334
+ (s = this.config) != null && s.enableLogging && console.error("❌ SocketManager: Failed to process conversation update", o), (n = this.chatSDK.events) == null || n.emit("conversation.updated", e);
2335
+ }
2336
+ }), this.socket.on("user-joined-room", (e) => {
2337
+ var t, a;
2338
+ (t = this.config) != null && t.enableLogging && console.log("🏠 SocketManager: User joined room", e), (a = this.chatSDK.events) == null || a.emit("room.user.joined", e);
2339
+ }), this.socket.on("user-left-room", (e) => {
2340
+ var t, a;
2341
+ (t = this.config) != null && t.enableLogging && console.log("🚪 SocketManager: User left room", e), (a = this.chatSDK.events) == null || a.emit("room.user.left", e);
2342
+ }), this.socket.on("online-users", (e) => {
2343
+ var t, a, s, n;
2344
+ try {
2345
+ const o = Ue.parseUsers(e);
2346
+ (t = this.config) != null && t.enableLogging && console.log("🌐 SocketManager: Online users update", { count: o.length }), (a = this.chatSDK.events) == null || a.emit("users.online", { users: o });
2347
+ } catch (o) {
2348
+ (s = this.config) != null && s.enableLogging && console.error("❌ SocketManager: Failed to parse online users", o), (n = this.chatSDK.events) == null || n.emit("users.online", { users: e });
2349
+ }
2350
+ }), this.socket.on("conversation_block_status", (e) => {
2351
+ var t, a;
2352
+ (t = this.config) != null && t.enableLogging && console.log("🚫 SocketManager: Conversation block status update", e), (a = this.chatSDK.events) == null || a.emit("conversation.block_status", e);
2353
+ }), this.socket.on("message_read_receipt", (e) => {
2354
+ var t, a, s, n;
2355
+ try {
2356
+ (t = this.config) != null && t.enableLogging && console.log("✅ SocketManager: Message read receipt received", e), (a = this.chatSDK.events) == null || a.emit("message.read.receipt", e);
2357
+ } catch (o) {
2358
+ (s = this.config) != null && s.enableLogging && console.error("❌ SocketManager: Failed to process read receipt", o), (n = this.chatSDK.events) == null || n.emit("message.read.receipt", e);
2359
+ }
2360
+ }), this.socket.on("messages_read_receipt", (e) => {
2361
+ var t, a, s, n, o, r, i, l;
2362
+ try {
2363
+ (t = this.config) != null && t.enableLogging && console.log("📥 SocketManager: messages_read_receipt received from server", {
2364
+ roomId: e.roomId,
2365
+ messageIds: e.messageIds,
2366
+ messageCount: (a = e.messageIds) == null ? void 0 : a.length,
2367
+ readBy: e.readBy,
2368
+ isRead: e.isRead
2369
+ }), (s = this.config) != null && s.enableLogging && console.log("✅ SocketManager: Messages read receipt received", e), (n = this.config) != null && n.enableLogging && console.log("📤 SocketManager: Emitting messages.read.receipt to chatSDK.events"), (o = this.chatSDK.events) == null || o.emit("messages.read.receipt", e), (r = this.config) != null && r.enableLogging && console.log("✅ SocketManager: Successfully emitted messages.read.receipt");
2370
+ } catch (d) {
2371
+ (i = this.config) != null && i.enableLogging && console.error("❌ SocketManager: Failed to process read receipts", d), (l = this.chatSDK.events) == null || l.emit("messages.read.receipt", e);
2372
+ }
2373
+ }));
2374
+ }
2375
+ /**
2376
+ * Check if socket is connected
2377
+ */
2378
+ isConnected() {
2379
+ var e;
2380
+ return ((e = this.socket) == null ? void 0 : e.connected) || !1;
2381
+ }
2382
+ /**
2383
+ * Get socket connection status
2384
+ */
2385
+ getStatus() {
2386
+ return {
2387
+ connected: this.isConnected(),
2388
+ userId: this.currentUserId,
2389
+ rooms: Array.from(this.joinedRooms)
2390
+ };
2391
+ }
2392
+ // Legacy methods for backward compatibility
2393
+ joinRoom(e) {
2394
+ this.joinConversation(e);
2395
+ }
2396
+ leaveRoom(e) {
2397
+ this.leaveConversation(e);
2398
+ }
2399
+ /**
2400
+ * Emit a socket event
2401
+ */
2402
+ emit(e, t) {
2403
+ var a, s;
2404
+ this.socket && this.socket.connected ? (this.socket.emit(e, t), (a = this.config) != null && a.enableLogging && console.log("📤 SocketManager: Emitted event:", e, t)) : (s = this.config) != null && s.enableLogging && console.warn("⚠️ SocketManager: Cannot emit event - not connected:", e);
2405
+ }
2406
+ /**
2407
+ * Listen to a socket event
2408
+ */
2409
+ on(e, t) {
2410
+ var a, s;
2411
+ this.socket ? (this.socket.on(e, t), (a = this.config) != null && a.enableLogging && console.log("👂 SocketManager: Listening to event:", e)) : (s = this.config) != null && s.enableLogging && console.warn("⚠️ SocketManager: Cannot listen to event - socket not available:", e);
2412
+ }
2413
+ /**
2414
+ * Stop listening to a socket event
2415
+ */
2416
+ off(e, t) {
2417
+ var a;
2418
+ this.socket && (this.socket.off(e, t), (a = this.config) != null && a.enableLogging && console.log("🔇 SocketManager: Stopped listening to event:", e));
2419
+ }
2420
+ }
2421
+ const ie = class ie {
2422
+ constructor() {
2423
+ this.config = null, this.isInitialized = !1, this.currentUser = null, this.auth = new et(this), this.chatUsers = new tt(this), this.users = new at(this), this.conversations = new st(this), this.messages = new nt(this), this.media = new rt(this), this.events = new ot(this), this.socket = new it(this);
2424
+ }
2425
+ /**
2426
+ * Get singleton instance of ChatSDK
2427
+ */
2428
+ static getInstance() {
2429
+ return ie.instance || (ie.instance = new ie()), ie.instance;
2430
+ }
2431
+ /**
2432
+ * Initialize ChatSDK with configuration
2433
+ * @param config - ChatSDK configuration
2434
+ */
2435
+ async init(e) {
2436
+ try {
2437
+ this.config = {
2438
+ enableLogging: !0,
2439
+ autoConnect: !0,
2440
+ timeout: 3e4,
2441
+ ...e
2442
+ }, this.config.enableLogging && console.log("🚀 ChatSDK: Initializing...", this.config), await this.auth.init(this.config), await this.chatUsers.init(this.config), await this.users.init(this.config), await this.conversations.init(this.config), await this.messages.init(this.config), await this.media.init(this.config), await this.events.init(this.config), await this.socket.init(this.config), this.isInitialized = !0, this.config.enableLogging && console.log("✅ ChatSDK: Initialized successfully"), this.config.autoConnect && this.auth.hasValidToken() && await this.connect();
2443
+ } catch (t) {
2444
+ throw console.error("❌ ChatSDK: Initialization failed", t), new Error(`ChatSDK initialization failed: ${t}`);
2445
+ }
2446
+ }
2447
+ /**
2448
+ * Connect to chat services
2449
+ */
2450
+ async connect(e) {
2451
+ var t, a;
2452
+ this.ensureInitialized();
2453
+ try {
2454
+ let s;
2455
+ e ? (console.log("🔌 ChatSDK: Using provided userId for connection:", e), s = {
2456
+ id: e,
2457
+ externalUserId: e,
2458
+ appId: process.env.REACT_APP_APP_ID || "",
2459
+ name: "Chat User",
2460
+ email: `${e}@example.com`,
2461
+ status: "online",
2462
+ isOnline: !0,
2463
+ isRegistered: !0,
2464
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2465
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2466
+ }, this.currentUser = s) : (s = await this.auth.getCurrentUser(), this.currentUser = s), await this.events.connect();
2467
+ try {
2468
+ console.log("🔌 ChatSDK: Attempting WebSocket connection for user:", s.id), await this.socket.connect(s.id), console.log("✅ ChatSDK: WebSocket connected successfully");
2469
+ } catch (n) {
2470
+ console.warn("⚠️ ChatSDK: WebSocket connection failed, continuing without real-time features:", n);
2471
+ }
2472
+ return (t = this.config) != null && t.enableLogging && console.log("🔗 ChatSDK: Connected successfully", s), s;
2473
+ } catch (s) {
2474
+ throw (a = this.config) != null && a.enableLogging && console.error("❌ ChatSDK: Connection failed", s), await this.auth.logout(), this.currentUser = null, s;
2475
+ }
2476
+ }
2477
+ /**
2478
+ * Disconnect from chat services
2479
+ */
2480
+ async disconnect() {
2481
+ var e;
2482
+ try {
2483
+ await this.events.disconnect(), this.socket.disconnect(), this.currentUser = null, (e = this.config) != null && e.enableLogging && console.log("🔌 ChatSDK: Disconnected");
2484
+ } catch (t) {
2485
+ throw console.error("❌ ChatSDK: Disconnect failed", t), t;
2486
+ }
2487
+ }
2488
+ /**
2489
+ * Login user with email and password
2490
+ * @param email - User email
2491
+ * @param password - User password
2492
+ */
2493
+ async login(e, t) {
2494
+ return this.ensureInitialized(), await this.auth.login(e, t);
2495
+ }
2496
+ /**
2497
+ * Register new user
2498
+ * @param email - User email
2499
+ * @param password - User password
2500
+ * @param name - User name
2501
+ * @param metadata - Additional user data
2502
+ */
2503
+ async register(e, t, a, s) {
2504
+ return this.ensureInitialized(), await this.auth.register(e, t, a, s);
2505
+ }
2506
+ /**
2507
+ * Logout current user
2508
+ */
2509
+ async logout() {
2510
+ this.ensureInitialized(), await this.auth.logout(), await this.disconnect();
2511
+ }
2512
+ /**
2513
+ * Get current logged in user
2514
+ */
2515
+ getCurrentUser() {
2516
+ return this.currentUser;
2517
+ }
2518
+ /**
2519
+ * Check if SDK is initialized
2520
+ */
2521
+ isSDKInitialized() {
2522
+ return this.isInitialized;
2523
+ }
2524
+ /**
2525
+ * Get SDK configuration
2526
+ */
2527
+ getConfig() {
2528
+ return this.config;
2529
+ }
2530
+ /**
2531
+ * Enable/disable logging
2532
+ */
2533
+ setLogging(e) {
2534
+ this.config && (this.config.enableLogging = e);
2535
+ }
2536
+ /**
2537
+ * Get SDK version
2538
+ */
2539
+ getVersion() {
2540
+ return "1.0.0";
2541
+ }
2542
+ // Private helper methods
2543
+ ensureInitialized() {
2544
+ if (!this.isInitialized)
2545
+ throw new Error("ChatSDK not initialized. Call ChatSDK.init() first.");
2546
+ }
2547
+ };
2548
+ ie.instance = null;
2549
+ let R = ie;
2550
+ R.getInstance();
2551
+ const ct = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
2552
+ __proto__: null,
2553
+ ChatSDK: R
2554
+ }, Symbol.toStringTag, { value: "Module" }));
2555
+ let lt = { data: "" }, dt = (c) => typeof window == "object" ? ((c ? c.querySelector("#_goober") : window._goober) || Object.assign((c || document.head).appendChild(document.createElement("style")), { innerHTML: " ", id: "_goober" })).firstChild : c || lt, gt = /(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g, ht = /\/\*[^]*?\*\/| +/g, Fe = /\n+/g, se = (c, e) => {
2556
+ let t = "", a = "", s = "";
2557
+ for (let n in c) {
2558
+ let o = c[n];
2559
+ n[0] == "@" ? n[1] == "i" ? t = n + " " + o + ";" : a += n[1] == "f" ? se(o, n) : n + "{" + se(o, n[1] == "k" ? "" : e) + "}" : typeof o == "object" ? a += se(o, e ? e.replace(/([^,])+/g, (r) => n.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g, (i) => /&/.test(i) ? i.replace(/&/g, r) : r ? r + " " + i : i)) : n) : o != null && (n = /^--/.test(n) ? n : n.replace(/[A-Z]/g, "-$&").toLowerCase(), s += se.p ? se.p(n, o) : n + ":" + o + ";");
2560
+ }
2561
+ return t + (e && s ? e + "{" + s + "}" : s) + a;
2562
+ }, X = {}, xe = (c) => {
2563
+ if (typeof c == "object") {
2564
+ let e = "";
2565
+ for (let t in c) e += t + xe(c[t]);
2566
+ return e;
2567
+ }
2568
+ return c;
2569
+ }, ut = (c, e, t, a, s) => {
2570
+ let n = xe(c), o = X[n] || (X[n] = ((i) => {
2571
+ let l = 0, d = 11;
2572
+ for (; l < i.length; ) d = 101 * d + i.charCodeAt(l++) >>> 0;
2573
+ return "go" + d;
2574
+ })(n));
2575
+ if (!X[o]) {
2576
+ let i = n !== c ? c : ((l) => {
2577
+ let d, h, m = [{}];
2578
+ for (; d = gt.exec(l.replace(ht, "")); ) d[4] ? m.shift() : d[3] ? (h = d[3].replace(Fe, " ").trim(), m.unshift(m[0][h] = m[0][h] || {})) : m[0][d[1]] = d[2].replace(Fe, " ").trim();
2579
+ return m[0];
2580
+ })(c);
2581
+ X[o] = se(s ? { ["@keyframes " + o]: i } : i, t ? "" : "." + o);
2582
+ }
2583
+ let r = t && X.g ? X.g : null;
2584
+ return t && (X.g = X[o]), ((i, l, d, h) => {
2585
+ h ? l.data = l.data.replace(h, i) : l.data.indexOf(i) === -1 && (l.data = d ? i + l.data : l.data + i);
2586
+ })(X[o], e, a, r), o;
2587
+ }, mt = (c, e, t) => c.reduce((a, s, n) => {
2588
+ let o = e[n];
2589
+ if (o && o.call) {
2590
+ let r = o(t), i = r && r.props && r.props.className || /^go/.test(r) && r;
2591
+ o = i ? "." + i : r && typeof r == "object" ? r.props ? "" : se(r, "") : r === !1 ? "" : r;
2592
+ }
2593
+ return a + s + (o ?? "");
2594
+ }, "");
2595
+ function me(c) {
2596
+ let e = this || {}, t = c.call ? c(e.p) : c;
2597
+ return ut(t.unshift ? t.raw ? mt(t, [].slice.call(arguments, 1), e.p) : t.reduce((a, s) => Object.assign(a, s && s.call ? s(e.p) : s), {}) : t, dt(e.target), e.g, e.o, e.k);
2598
+ }
2599
+ let Ne, ke, ye;
2600
+ me.bind({ g: 1 });
2601
+ let ee = me.bind({ k: 1 });
2602
+ function ft(c, e, t, a) {
2603
+ se.p = e, Ne = c, ke = t, ye = a;
2604
+ }
2605
+ function ne(c, e) {
2606
+ let t = this || {};
2607
+ return function() {
2608
+ let a = arguments;
2609
+ function s(n, o) {
2610
+ let r = Object.assign({}, n), i = r.className || s.className;
2611
+ t.p = Object.assign({ theme: ke && ke() }, r), t.o = / *go\d+/.test(i), r.className = me.apply(t, a) + (i ? " " + i : "");
2612
+ let l = c;
2613
+ return c[0] && (l = r.as || c, delete r.as), ye && l[0] && ye(r), Ne(l, r);
2614
+ }
2615
+ return s;
2616
+ };
2617
+ }
2618
+ var pt = (c) => typeof c == "function", ve = (c, e) => pt(c) ? c(e) : c, wt = /* @__PURE__ */ (() => {
2619
+ let c = 0;
2620
+ return () => (++c).toString();
2621
+ })(), kt = /* @__PURE__ */ (() => {
2622
+ let c;
2623
+ return () => {
2624
+ if (c === void 0 && typeof window < "u") {
2625
+ let e = matchMedia("(prefers-reduced-motion: reduce)");
2626
+ c = !e || e.matches;
2627
+ }
2628
+ return c;
2629
+ };
2630
+ })(), yt = 20, Te = (c, e) => {
2631
+ switch (e.type) {
2632
+ case 0:
2633
+ return { ...c, toasts: [e.toast, ...c.toasts].slice(0, yt) };
2634
+ case 1:
2635
+ return { ...c, toasts: c.toasts.map((n) => n.id === e.toast.id ? { ...n, ...e.toast } : n) };
2636
+ case 2:
2637
+ let { toast: t } = e;
2638
+ return Te(c, { type: c.toasts.find((n) => n.id === t.id) ? 1 : 0, toast: t });
2639
+ case 3:
2640
+ let { toastId: a } = e;
2641
+ return { ...c, toasts: c.toasts.map((n) => n.id === a || a === void 0 ? { ...n, dismissed: !0, visible: !1 } : n) };
2642
+ case 4:
2643
+ return e.toastId === void 0 ? { ...c, toasts: [] } : { ...c, toasts: c.toasts.filter((n) => n.id !== e.toastId) };
2644
+ case 5:
2645
+ return { ...c, pausedAt: e.time };
2646
+ case 6:
2647
+ let s = e.time - (c.pausedAt || 0);
2648
+ return { ...c, pausedAt: void 0, toasts: c.toasts.map((n) => ({ ...n, pauseDuration: n.pauseDuration + s })) };
2649
+ }
2650
+ }, vt = [], we = { toasts: [], pausedAt: void 0 }, Me = (c) => {
2651
+ we = Te(we, c), vt.forEach((e) => {
2652
+ e(we);
2653
+ });
2654
+ }, bt = (c, e = "blank", t) => ({ createdAt: Date.now(), visible: !0, dismissed: !1, type: e, ariaProps: { role: "status", "aria-live": "polite" }, message: c, pauseDuration: 0, ...t, id: (t == null ? void 0 : t.id) || wt() }), ue = (c) => (e, t) => {
2655
+ let a = bt(e, c, t);
2656
+ return Me({ type: 2, toast: a }), a.id;
2657
+ }, V = (c, e) => ue("blank")(c, e);
2658
+ V.error = ue("error");
2659
+ V.success = ue("success");
2660
+ V.loading = ue("loading");
2661
+ V.custom = ue("custom");
2662
+ V.dismiss = (c) => {
2663
+ Me({ type: 3, toastId: c });
2664
+ };
2665
+ V.remove = (c) => Me({ type: 4, toastId: c });
2666
+ V.promise = (c, e, t) => {
2667
+ let a = V.loading(e.loading, { ...t, ...t == null ? void 0 : t.loading });
2668
+ return typeof c == "function" && (c = c()), c.then((s) => {
2669
+ let n = e.success ? ve(e.success, s) : void 0;
2670
+ return n ? V.success(n, { id: a, ...t, ...t == null ? void 0 : t.success }) : V.dismiss(a), s;
2671
+ }).catch((s) => {
2672
+ let n = e.error ? ve(e.error, s) : void 0;
2673
+ n ? V.error(n, { id: a, ...t, ...t == null ? void 0 : t.error }) : V.dismiss(a);
2674
+ }), c;
2675
+ };
2676
+ var Mt = ee`
2677
+ from {
2678
+ transform: scale(0) rotate(45deg);
2679
+ opacity: 0;
2680
+ }
2681
+ to {
2682
+ transform: scale(1) rotate(45deg);
2683
+ opacity: 1;
2684
+ }`, Ct = ee`
2685
+ from {
2686
+ transform: scale(0);
2687
+ opacity: 0;
2688
+ }
2689
+ to {
2690
+ transform: scale(1);
2691
+ opacity: 1;
2692
+ }`, _t = ee`
2693
+ from {
2694
+ transform: scale(0) rotate(90deg);
2695
+ opacity: 0;
2696
+ }
2697
+ to {
2698
+ transform: scale(1) rotate(90deg);
2699
+ opacity: 1;
2700
+ }`, St = ne("div")`
2701
+ width: 20px;
2702
+ opacity: 0;
2703
+ height: 20px;
2704
+ border-radius: 10px;
2705
+ background: ${(c) => c.primary || "#ff4b4b"};
2706
+ position: relative;
2707
+ transform: rotate(45deg);
2708
+
2709
+ animation: ${Mt} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
2710
+ forwards;
2711
+ animation-delay: 100ms;
2712
+
2713
+ &:after,
2714
+ &:before {
2715
+ content: '';
2716
+ animation: ${Ct} 0.15s ease-out forwards;
2717
+ animation-delay: 150ms;
2718
+ position: absolute;
2719
+ border-radius: 3px;
2720
+ opacity: 0;
2721
+ background: ${(c) => c.secondary || "#fff"};
2722
+ bottom: 9px;
2723
+ left: 4px;
2724
+ height: 2px;
2725
+ width: 12px;
2726
+ }
2727
+
2728
+ &:before {
2729
+ animation: ${_t} 0.15s ease-out forwards;
2730
+ animation-delay: 180ms;
2731
+ transform: rotate(90deg);
2732
+ }
2733
+ `, Lt = ee`
2734
+ from {
2735
+ transform: rotate(0deg);
2736
+ }
2737
+ to {
2738
+ transform: rotate(360deg);
2739
+ }
2740
+ `, Et = ne("div")`
2741
+ width: 12px;
2742
+ height: 12px;
2743
+ box-sizing: border-box;
2744
+ border: 2px solid;
2745
+ border-radius: 100%;
2746
+ border-color: ${(c) => c.secondary || "#e0e0e0"};
2747
+ border-right-color: ${(c) => c.primary || "#616161"};
2748
+ animation: ${Lt} 1s linear infinite;
2749
+ `, Dt = ee`
2750
+ from {
2751
+ transform: scale(0) rotate(45deg);
2752
+ opacity: 0;
2753
+ }
2754
+ to {
2755
+ transform: scale(1) rotate(45deg);
2756
+ opacity: 1;
2757
+ }`, Ut = ee`
2758
+ 0% {
2759
+ height: 0;
2760
+ width: 0;
2761
+ opacity: 0;
2762
+ }
2763
+ 40% {
2764
+ height: 0;
2765
+ width: 6px;
2766
+ opacity: 1;
2767
+ }
2768
+ 100% {
2769
+ opacity: 1;
2770
+ height: 10px;
2771
+ }`, Ft = ne("div")`
2772
+ width: 20px;
2773
+ opacity: 0;
2774
+ height: 20px;
2775
+ border-radius: 10px;
2776
+ background: ${(c) => c.primary || "#61d345"};
2777
+ position: relative;
2778
+ transform: rotate(45deg);
2779
+
2780
+ animation: ${Dt} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
2781
+ forwards;
2782
+ animation-delay: 100ms;
2783
+ &:after {
2784
+ content: '';
2785
+ box-sizing: border-box;
2786
+ animation: ${Ut} 0.2s ease-out forwards;
2787
+ opacity: 0;
2788
+ animation-delay: 200ms;
2789
+ position: absolute;
2790
+ border-right: 2px solid;
2791
+ border-bottom: 2px solid;
2792
+ border-color: ${(c) => c.secondary || "#fff"};
2793
+ bottom: 6px;
2794
+ left: 6px;
2795
+ height: 10px;
2796
+ width: 6px;
2797
+ }
2798
+ `, It = ne("div")`
2799
+ position: absolute;
2800
+ `, At = ne("div")`
2801
+ position: relative;
2802
+ display: flex;
2803
+ justify-content: center;
2804
+ align-items: center;
2805
+ min-width: 20px;
2806
+ min-height: 20px;
2807
+ `, xt = ee`
2808
+ from {
2809
+ transform: scale(0.6);
2810
+ opacity: 0.4;
2811
+ }
2812
+ to {
2813
+ transform: scale(1);
2814
+ opacity: 1;
2815
+ }`, Nt = ne("div")`
2816
+ position: relative;
2817
+ transform: scale(0.6);
2818
+ opacity: 0.4;
2819
+ min-width: 20px;
2820
+ animation: ${xt} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275)
2821
+ forwards;
2822
+ `, Tt = ({ toast: c }) => {
2823
+ let { icon: e, type: t, iconTheme: a } = c;
2824
+ return e !== void 0 ? typeof e == "string" ? q.createElement(Nt, null, e) : e : t === "blank" ? null : q.createElement(At, null, q.createElement(Et, { ...a }), t !== "loading" && q.createElement(It, null, t === "error" ? q.createElement(St, { ...a }) : q.createElement(Ft, { ...a })));
2825
+ }, Kt = (c) => `
2826
+ 0% {transform: translate3d(0,${c * -200}%,0) scale(.6); opacity:.5;}
2827
+ 100% {transform: translate3d(0,0,0) scale(1); opacity:1;}
2828
+ `, zt = (c) => `
2829
+ 0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;}
2830
+ 100% {transform: translate3d(0,${c * -150}%,-1px) scale(.6); opacity:0;}
2831
+ `, Rt = "0%{opacity:0;} 100%{opacity:1;}", Bt = "0%{opacity:1;} 100%{opacity:0;}", $t = ne("div")`
2832
+ display: flex;
2833
+ align-items: center;
2834
+ background: #fff;
2835
+ color: #363636;
2836
+ line-height: 1.3;
2837
+ will-change: transform;
2838
+ box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05);
2839
+ max-width: 350px;
2840
+ pointer-events: auto;
2841
+ padding: 8px 10px;
2842
+ border-radius: 8px;
2843
+ `, Pt = ne("div")`
2844
+ display: flex;
2845
+ justify-content: center;
2846
+ margin: 4px 10px;
2847
+ color: inherit;
2848
+ flex: 1 1 auto;
2849
+ white-space: pre-line;
2850
+ `, Ot = (c, e) => {
2851
+ let t = c.includes("top") ? 1 : -1, [a, s] = kt() ? [Rt, Bt] : [Kt(t), zt(t)];
2852
+ return { animation: e ? `${ee(a)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards` : `${ee(s)} 0.4s forwards cubic-bezier(.06,.71,.55,1)` };
2853
+ };
2854
+ q.memo(({ toast: c, position: e, style: t, children: a }) => {
2855
+ let s = c.height ? Ot(c.position || e || "top-center", c.visible) : { opacity: 0 }, n = q.createElement(Tt, { toast: c }), o = q.createElement(Pt, { ...c.ariaProps }, ve(c.message, c));
2856
+ return q.createElement($t, { className: c.className, style: { ...s, ...t, ...c.style } }, typeof a == "function" ? a({ icon: n, message: o }) : q.createElement(q.Fragment, null, n, o));
2857
+ });
2858
+ ft(q.createElement);
2859
+ me`
2860
+ z-index: 9999;
2861
+ > * {
2862
+ pointer-events: auto;
2863
+ }
2864
+ `;
2865
+ var z = V;
2866
+ const jt = {
2867
+ // General
2868
+ send: "Send",
2869
+ // Conversations
2870
+ conversations_title: "Chats",
2871
+ no_conversations_title: "No conversations yet",
2872
+ no_conversations_message: "Start chatting with product owners to see conversations here",
2873
+ loading_conversations: "Loading conversations...",
2874
+ error_load_conversations: "Failed to load conversations",
2875
+ select_conversation: "Select a conversation",
2876
+ select_conversation_message: "Choose a conversation from the list to start chatting",
2877
+ select_conversation_tip: "💡 Tip: Click on any conversation in the sidebar to open it here",
2878
+ // Chat
2879
+ message_hint: "Start typing a message",
2880
+ attach_file: "Attach file",
2881
+ loading_messages: "Loading messages...",
2882
+ // Messages
2883
+ file_sent_successfully: "File uploaded and sent!",
2884
+ uploading: "Uploading...",
2885
+ sent: "Sent",
2886
+ read: "Read",
2887
+ // Errors
2888
+ error_load_messages: "Failed to load messages",
2889
+ error_send_message: "Failed to send message",
2890
+ error_file_upload: "Failed to upload file",
2891
+ error_unknown: "Unknown error",
2892
+ error_user_blocked: "Your account has been blocked by administrator",
2893
+ error_registration_failed: "Registration failed. Please try again.",
2894
+ // Success messages
2895
+ login_successful: "Login successful!",
2896
+ registration_successful: "Registration and login successful!",
2897
+ complete_profile_info: "Please complete your profile information.",
2898
+ // Block/Unblock
2899
+ block_user: "Block User",
2900
+ unblock_user: "Unblock",
2901
+ user_blocked: "User blocked",
2902
+ user_unblocked: "User unblocked",
2903
+ block_user_confirm: "Are you sure you want to block this user?",
2904
+ unblock_user_confirm: "Are you sure you want to unblock this user?",
2905
+ you_are_blocked: "You have been blocked in this chat",
2906
+ you_have_blocked: "You've blocked {{userName}}",
2907
+ you_have_blocked_submessage: "You can't message them in this chat, and you won't receive their messages.",
2908
+ blocked_by_user: "You have been blocked by {{userName}}",
2909
+ blocked_by_user_submessage: "You can't send messages in this chat.",
2910
+ user_is_blocked: "This user is blocked in this chat",
2911
+ failed_to_block: "Failed to block user",
2912
+ failed_to_unblock: "Failed to unblock user",
2913
+ user_not_found: "User not found",
2914
+ user_id_not_found: "User ID not found",
2915
+ cannot_block_self: "You cannot block yourself",
2916
+ // Additional UI strings
2917
+ loading: "Loading...",
2918
+ unknown_user: "Unknown User",
2919
+ image: "Image",
2920
+ file: "File",
2921
+ no_messages_yet: "No messages yet",
2922
+ yesterday: "Yesterday",
2923
+ unknown_size: "Unknown size",
2924
+ download: "Download",
2925
+ search: "Search",
2926
+ back: "Back",
2927
+ call: "Call",
2928
+ options: "Options",
2929
+ close: "Close",
2930
+ no_phone_number: "No phone number available",
2931
+ number_copied: "Phone number copied to clipboard",
2932
+ no_search_results: "No conversations found",
2933
+ // Demo app UI
2934
+ demo_title: "ChatSDK Demo",
2935
+ welcome: "Welcome",
2936
+ logout: "Logout",
2937
+ products: "Products",
2938
+ all_products: "All Products",
2939
+ my_products: "My Products",
2940
+ conversations: "Conversations",
2941
+ sdk_tester: "SDK Tester",
2942
+ sdk_tester_desc: "SDK testing tools will be available here",
2943
+ loading_products: "Loading products...",
2944
+ no_products_listed: "You haven't listed any products yet.",
2945
+ realtime_active: "Real-time Chat Active",
2946
+ http_only: "HTTP Only",
2947
+ failed_to_load_products: "Failed to load products",
2948
+ failed_to_start_chat: "Failed to start chat",
2949
+ cannot_chat_self: "You cannot start a chat with yourself!",
2950
+ starting_chat: "Starting chat with product owner...",
2951
+ chat_opened: "Chat popup opened!",
2952
+ failed_init: "Failed to initialize app",
2953
+ // Login / Registration
2954
+ login: "Login",
2955
+ login_as: "Login as",
2956
+ checking: "Checking...",
2957
+ registering: "Registering...",
2958
+ complete_registration: "Complete Registration",
2959
+ back_to_login: "Back to Login",
2960
+ quick_demo_login: "Quick Demo Login (with sample conversations):",
2961
+ external_user_id: "External User ID:",
2962
+ app_id_label: "App ID:",
2963
+ full_name: "Full Name:",
2964
+ email_label: "Email:",
2965
+ welcome_demo: "Welcome to the ChatSDK Demo Application",
2966
+ enter_user_id: "Enter your user ID (e.g., user1)",
2967
+ enter_app_id: "Enter app ID",
2968
+ enter_full_name: "Enter your full name",
2969
+ enter_email: "Enter your email",
2970
+ // Product card
2971
+ chat_with_owner: "Chat with Owner",
2972
+ your_product: "Your Product",
2973
+ owner_label: "Owner:"
2974
+ }, Wt = {
2975
+ // General
2976
+ send: "إرسال",
2977
+ // Conversations
2978
+ conversations_title: "الدردشة",
2979
+ no_conversations_title: "لا توجد محادثات بعد",
2980
+ no_conversations_message: "ابدأ الدردشة مع مالكي المنتجات لمشاهدة محادثاتك هنا",
2981
+ loading_conversations: "جاري تحميل المحادثات...",
2982
+ error_load_conversations: "فشل تحميل المحادثات",
2983
+ select_conversation: "اختر محادثة",
2984
+ select_conversation_message: "اختر محادثة من القائمة لبدء الدردشة",
2985
+ select_conversation_tip: "💡 نصيحة: انقر على أي محادثة في الشريط الجانبي لفتحها هنا",
2986
+ // Chat
2987
+ message_hint: "اكتب رسالة هنا",
2988
+ attach_file: "إرفاق ملف",
2989
+ loading_messages: "جاري تحميل الرسائل...",
2990
+ // Messages
2991
+ file_sent_successfully: "تم إرسال الملف بنجاح!",
2992
+ uploading: "جاري الرفع...",
2993
+ sent: "تم الإرسال",
2994
+ read: "تم القراءة",
2995
+ // Errors
2996
+ error_load_messages: "فشل تحميل الرسائل",
2997
+ error_send_message: "فشل إرسال الرسالة",
2998
+ error_file_upload: "فشل رفع الملف",
2999
+ error_unknown: "خطأ غير معروف",
3000
+ error_user_blocked: "تم حظر حسابك من قبل المسؤول",
3001
+ error_registration_failed: "فشل التسجيل. يرجى المحاولة مرة أخرى.",
3002
+ // Success messages
3003
+ login_successful: "تم تسجيل الدخول بنجاح!",
3004
+ registration_successful: "تم التسجيل وتسجيل الدخول بنجاح!",
3005
+ complete_profile_info: "يرجى إكمال معلومات ملفك الشخصي.",
3006
+ // Block/Unblock
3007
+ block_user: "حظر المستخدم",
3008
+ unblock_user: "إلغاء الحظر",
3009
+ user_blocked: "تم حظر المستخدم",
3010
+ user_unblocked: "تم إلغاء حظر المستخدم",
3011
+ block_user_confirm: "هل أنت متأكد أنك تريد حظر هذا المستخدم؟",
3012
+ unblock_user_confirm: "هل أنت متأكد أنك تريد إلغاء حظر هذا المستخدم؟",
3013
+ you_are_blocked: "تم حظرك في هذه المحادثة",
3014
+ you_have_blocked: "لقد قمت بحظر {{userName}}",
3015
+ you_have_blocked_submessage: "لا يمكنك مراسلتهم في هذه المحادثة، ولن تتلقى رسائلهم.",
3016
+ blocked_by_user: "تم حظرك من قبل {{userName}}",
3017
+ blocked_by_user_submessage: "لا يمكنك إرسال الرسائل في هذه المحادثة.",
3018
+ user_is_blocked: "هذا المستخدم محظور في هذه المحادثة",
3019
+ failed_to_block: "فشل حظر المستخدم",
3020
+ failed_to_unblock: "فشل إلغاء حظر المستخدم",
3021
+ user_not_found: "المستخدم غير موجود",
3022
+ user_id_not_found: "معرف المستخدم غير موجود",
3023
+ cannot_block_self: "لا يمكنك حظر نفسك",
3024
+ // Additional UI strings
3025
+ loading: "جاري التحميل...",
3026
+ unknown_user: "مستخدم غير معروف",
3027
+ image: "صورة",
3028
+ file: "ملف",
3029
+ no_messages_yet: "لا توجد رسائل بعد",
3030
+ yesterday: "أمس",
3031
+ unknown_size: "حجم غير معروف",
3032
+ download: "تنزيل",
3033
+ search: "بحث",
3034
+ back: "رجوع",
3035
+ call: "اتصال",
3036
+ options: "خيارات",
3037
+ close: "إغلاق",
3038
+ no_phone_number: "لا يوجد رقم هاتف متاح",
3039
+ number_copied: "تم نسخ رقم الهاتف",
3040
+ no_search_results: "لم يتم العثور على محادثات",
3041
+ // Demo app UI
3042
+ demo_title: "عرض ChatSDK",
3043
+ welcome: "مرحبًا",
3044
+ logout: "تسجيل الخروج",
3045
+ products: "المنتجات",
3046
+ all_products: "كل المنتجات",
3047
+ my_products: "منتجاتي",
3048
+ conversations: "المحادثات",
3049
+ sdk_tester: "اختبار SDK",
3050
+ sdk_tester_desc: "ستتوفر أدوات اختبار SDK هنا",
3051
+ loading_products: "جاري تحميل المنتجات...",
3052
+ no_products_listed: "لم تقم بنشر أي منتجات بعد.",
3053
+ realtime_active: "الدردشة المباشرة نشطة",
3054
+ http_only: "HTTP فقط",
3055
+ failed_to_load_products: "فشل تحميل المنتجات",
3056
+ failed_to_start_chat: "فشل بدء الدردشة",
3057
+ cannot_chat_self: "لا يمكنك بدء محادثة مع نفسك!",
3058
+ starting_chat: "جاري بدء الدردشة مع مالك المنتج...",
3059
+ chat_opened: "تم فتح نافذة الدردشة!",
3060
+ failed_init: "فشل تهيئة التطبيق",
3061
+ // Login / Registration
3062
+ login: "تسجيل الدخول",
3063
+ login_as: "تسجيل الدخول كـ",
3064
+ checking: "جاري التحقق...",
3065
+ registering: "جاري التسجيل...",
3066
+ complete_registration: "إكمال التسجيل",
3067
+ back_to_login: "العودة لتسجيل الدخول",
3068
+ quick_demo_login: "تسجيل دخول سريع (مع محادثات تجريبية):",
3069
+ external_user_id: "معرف المستخدم الخارجي:",
3070
+ app_id_label: "معرف التطبيق:",
3071
+ full_name: "الاسم الكامل:",
3072
+ email_label: "البريد الإلكتروني:",
3073
+ welcome_demo: "مرحبًا بك في تطبيق عرض ChatSDK",
3074
+ enter_user_id: "أدخل معرف المستخدم (مثل user1)",
3075
+ enter_app_id: "أدخل معرف التطبيق",
3076
+ enter_full_name: "أدخل اسمك الكامل",
3077
+ enter_email: "أدخل بريدك الإلكتروني",
3078
+ // Product card
3079
+ chat_with_owner: "الدردشة مع المالك",
3080
+ your_product: "منتجك",
3081
+ owner_label: "المالك:"
3082
+ }, be = {
3083
+ en: jt,
3084
+ ar: Wt
3085
+ };
3086
+ let he = "en";
3087
+ const Ie = (c) => {
3088
+ be[c] ? (he = c, document.documentElement.lang = c, document.documentElement.dir = qt() ? "rtl" : "ltr", localStorage.setItem("chatSDK_language", c)) : (console.warn(`Locale "${c}" not found, falling back to "en".`), he = "en", document.documentElement.lang = "en", document.documentElement.dir = "ltr");
3089
+ }, Zt = () => he, qt = () => he === "ar", w = (c, e) => {
3090
+ let t = be[he][c] || be.en[c] || c;
3091
+ if (e)
3092
+ for (const a in e)
3093
+ t = t.replace(
3094
+ new RegExp(`{{${a}}}`, "g"),
3095
+ String(e[a])
3096
+ );
3097
+ return t;
3098
+ }, Ae = localStorage.getItem("chatSDK_language");
3099
+ Ie(Ae || "en");
3100
+ const Xt = ({ conversation: c, currentUser: e, onClose: t, onBack: a }) => {
3101
+ var Se;
3102
+ const [s, n] = T([]), [o, r] = T(""), [i, l] = T(!1), [d, h] = T(!1), [m, p] = T({}), [E, P] = T(!1), [Ce, ge] = T(!0), [y, C] = T(1), [O, G] = T(null), [B, J] = T(!1), [D, F] = T(!1), [N, x] = T(!1), [K, j] = T(null), [te, ae] = T(!1), Q = le(null), ce = le(null), $ = le(null), H = le(null), re = 20, oe = De(() => {
3103
+ if (!c || !e) return null;
3104
+ const g = c.participants || [];
3105
+ if (g.length === 0) return null;
3106
+ const f = e.id || e.userId, b = e.externalUserId || e.external_user_id;
3107
+ return g.find((v) => {
3108
+ const S = v.id || v.userId, k = v.externalUserId || v.external_user_id;
3109
+ return !(f && S && S === f || b && k && k === b) && (S || k);
3110
+ }) || null;
3111
+ }, [c, e]), U = oe(), W = De(() => {
3112
+ if (!c) return { userName: w("conversations_title"), productName: null, productImage: null, productMetadata: null };
3113
+ const g = U && (U.name || U.userName || U.displayName || U.externalUserId) || w("unknown_user"), f = c.productContext || c.product_context;
3114
+ return f ? {
3115
+ userName: g,
3116
+ productName: f.productName || f.product_name,
3117
+ productImage: f.productImage || f.product_image,
3118
+ productId: f.productId || f.product_id,
3119
+ productMetadata: f.productMetadata || f.product_metadata
3120
+ } : { userName: g, productName: null, productImage: null, productMetadata: null };
3121
+ }, [c, U])();
3122
+ Y(() => (c && (x(!1), qe(1, !1), ze(), R.getInstance().chatUsers.startViewingConversation(c.id)), () => {
3123
+ c && (Re(), R.getInstance().chatUsers.stopViewingConversation(c.id));
3124
+ }), [c]), Y(() => {
3125
+ const g = R.getInstance(), f = (k) => {
3126
+ const _ = k.message;
3127
+ _.roomId === (c == null ? void 0 : c.id) && n((I) => I.some((L) => L.id === _.id) ? I : (_.senderId !== e.id && g.chatUsers.markMessageRead(_.id).catch((L) => {
3128
+ console.warn("ChatWindow: Failed to mark message as read:", L);
3129
+ }), [...I, {
3130
+ id: _.id,
3131
+ content: _.content,
3132
+ senderId: _.senderId,
3133
+ senderName: _.senderName,
3134
+ timestamp: _.createdAt || _.timestamp,
3135
+ conversationId: _.roomId,
3136
+ type: _.messageType || _.type || "text",
3137
+ metadata: _.metadata || void 0,
3138
+ isRead: _.isRead !== void 0 ? _.isRead : _.senderId !== e.id,
3139
+ isDelivered: _.isDelivered !== void 0 ? _.isDelivered : !0,
3140
+ status: _.status || "sent"
3141
+ }]));
3142
+ }, b = (k) => {
3143
+ !k.messageId || k.roomId !== (c == null ? void 0 : c.id) || n((_) => _.map(
3144
+ (I) => I.id === k.messageId && I.senderId === e.id ? { ...I, isRead: k.isRead } : I
3145
+ ));
3146
+ }, v = (k) => {
3147
+ if (k.roomId !== (c == null ? void 0 : c.id)) return;
3148
+ const _ = e == null ? void 0 : e.id;
3149
+ if (!k.messageIds || k.messageIds.length === 0) {
3150
+ n((A) => A.map((L) => L.senderId === _ && !L.isRead ? { ...L, isRead: k.isRead } : L));
3151
+ return;
3152
+ }
3153
+ const I = new Set(k.messageIds);
3154
+ n((A) => A.map((L) => I.has(L.id) && L.senderId === _ ? { ...L, isRead: k.isRead } : L));
3155
+ }, S = (k) => {
3156
+ if (!c || ((k == null ? void 0 : k.conversationId) || (k == null ? void 0 : k.chatId) || (k == null ? void 0 : k.roomId)) !== c.id) return;
3157
+ const I = (k == null ? void 0 : k.blockedUsers) || {};
3158
+ c.metadata = {
3159
+ ...c.metadata || {},
3160
+ blockedUsers: I
3161
+ };
3162
+ const A = e.id || e.userId, L = oe(), Z = L ? L.id || L.userId || L.externalUserId || L.external_user_id : null;
3163
+ J(I[A] === 1), F(Z ? I[Z] === 1 : !1);
3164
+ };
3165
+ return g.events.on("message.received", f), g.events.on("message.read.receipt", b), g.events.on("messages.read.receipt", v), g.events.on("conversation.block_status", S), () => {
3166
+ g.events.off("message.received", f), g.events.off("message.read.receipt", b), g.events.off("messages.read.receipt", v), g.events.off("conversation.block_status", S);
3167
+ };
3168
+ }, [c == null ? void 0 : c.id, e == null ? void 0 : e.id]), Y(() => {
3169
+ if (!c || !e) {
3170
+ J(!1), F(!1), G(null);
3171
+ return;
3172
+ }
3173
+ const f = (c.metadata || {}).blockedUsers || {}, b = e.id || e.userId, v = oe(), S = v ? v.id || v.userId || v.externalUserId || v.external_user_id : null;
3174
+ J(f[b] === 1), F(S ? f[S] === 1 : !1), G({
3175
+ chatId: c.id,
3176
+ currentUserId: b,
3177
+ isBlockedByOther: f[b] === 1,
3178
+ usersBlockedByMe: Object.keys(f).filter((k) => f[k] === 1),
3179
+ blockedUsers: f
3180
+ });
3181
+ }, [c == null ? void 0 : c.id, JSON.stringify(c == null ? void 0 : c.metadata), e == null ? void 0 : e.id]), Y(() => {
3182
+ Be();
3183
+ }, [s]), Y(() => {
3184
+ const g = (f) => {
3185
+ f.target.closest(".chat-options-wrapper") || x(!1);
3186
+ };
3187
+ return document.addEventListener("click", g), () => {
3188
+ document.removeEventListener("click", g), H.current && clearTimeout(H.current);
3189
+ };
3190
+ }, []);
3191
+ const ze = () => {
3192
+ c && R.getInstance().socket.joinRoom(c.id);
3193
+ }, Re = () => {
3194
+ c && R.getInstance().socket.leaveRoom(c.id);
3195
+ }, Be = () => {
3196
+ var g;
3197
+ (g = Q.current) == null || g.scrollIntoView({ behavior: "smooth" });
3198
+ }, $e = (g) => new Date(g).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }), pe = (g) => {
3199
+ const f = new Date(g), b = /* @__PURE__ */ new Date(), v = new Date(b.getFullYear(), b.getMonth(), b.getDate()), S = new Date(f.getFullYear(), f.getMonth(), f.getDate()), k = Math.floor((v.getTime() - S.getTime()) / (1e3 * 60 * 60 * 24));
3200
+ if (k === 0) return "Today";
3201
+ if (k === 1) return "Yesterday";
3202
+ const _ = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], I = f.getDate().toString().padStart(2, "0"), A = (f.getMonth() + 1).toString().padStart(2, "0");
3203
+ return k < 7 ? `${_[f.getDay()]}, ${I}/${A}` : `${I}/${A}/${f.getFullYear()}`;
3204
+ }, Pe = (g, f) => {
3205
+ if (f === 0) return !0;
3206
+ const b = s[f - 1], v = new Date(b.timestamp).toDateString(), S = new Date(g.timestamp).toDateString();
3207
+ return v !== S;
3208
+ }, Oe = (g) => g ? g.includes("pdf") ? "📄" : g.includes("word") ? "📝" : g.includes("excel") ? "📊" : g.includes("audio") ? "🎵" : g.includes("video") ? "🎥" : "📎" : "📎", je = () => {
3209
+ if (!$.current) return;
3210
+ const g = $.current, f = g.querySelectorAll(".date-divider[data-date]");
3211
+ if (f.length === 0) return;
3212
+ let b = null;
3213
+ const v = g.getBoundingClientRect().top;
3214
+ for (let S = f.length - 1; S >= 0; S--) {
3215
+ const k = f[S];
3216
+ if (k.getBoundingClientRect().top <= v + 50) {
3217
+ b = k.getAttribute("data-date");
3218
+ break;
3219
+ }
3220
+ }
3221
+ !b && s.length > 0 && (b = pe(s[0].timestamp)), b && (j(b), ae(!0), H.current && clearTimeout(H.current), H.current = setTimeout(() => {
3222
+ ae(!1);
3223
+ }, 2e3));
3224
+ }, We = () => {
3225
+ if (!U) return;
3226
+ const g = U, f = g.phone || g.phoneNumber || g.mobile || g.externalUserId || "";
3227
+ if (!f) {
3228
+ z.error(w("no_phone_number") || "No phone number available");
3229
+ return;
3230
+ }
3231
+ /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? window.location.href = `tel:${f}` : navigator.clipboard.writeText(f).then(() => {
3232
+ z.success(w("number_copied") || `Phone number copied: ${f}`);
3233
+ }).catch(() => {
3234
+ const v = document.createElement("textarea");
3235
+ v.value = f, document.body.appendChild(v), v.select(), document.execCommand("copy"), document.body.removeChild(v), z.success(w("number_copied") || `Phone number copied: ${f}`);
3236
+ });
3237
+ }, qe = async (g = 1, f = !1) => {
3238
+ if (c) {
3239
+ g === 1 ? (l(!0), n([]), C(1), ge(!0)) : P(!0);
3240
+ try {
3241
+ const v = await R.getInstance().messages.getMessages({
3242
+ conversationId: c.id,
3243
+ limit: re,
3244
+ offset: (g - 1) * re
3245
+ }), S = v.sort(
3246
+ (k, _) => new Date(k.timestamp).getTime() - new Date(_.timestamp).getTime()
3247
+ );
3248
+ f && g > 1 ? n((k) => [...S, ...k]) : n(S), ge(v.length === re), C(g);
3249
+ } catch {
3250
+ z.error(w("error_load_messages"));
3251
+ } finally {
3252
+ l(!1), P(!1);
3253
+ }
3254
+ }
3255
+ }, Ve = async (g) => {
3256
+ if (g.preventDefault(), !c || !o.trim() || B) {
3257
+ B && z.error(w("you_are_blocked"));
3258
+ return;
3259
+ }
3260
+ const f = o.trim();
3261
+ r("");
3262
+ try {
3263
+ await R.getInstance().messages.sendMessage(c.id, f);
3264
+ } catch {
3265
+ r(f), z.error(w("error_send_message"));
3266
+ }
3267
+ }, Ge = async (g) => {
3268
+ if (!c) return;
3269
+ const f = `temp_${Date.now()}`, b = {
3270
+ id: f,
3271
+ conversationId: c.id,
3272
+ senderId: e.id,
3273
+ senderName: e.name,
3274
+ content: `${g.name}`,
3275
+ type: g.type.startsWith("image/") ? "image" : "file",
3276
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3277
+ status: "sending",
3278
+ isRead: !1,
3279
+ isDelivered: !1,
3280
+ isUploading: !0,
3281
+ uploadProgress: 0,
3282
+ localFileUri: URL.createObjectURL(g),
3283
+ metadata: {
3284
+ fileName: g.name,
3285
+ fileSize: g.size,
3286
+ mimeType: g.type
3287
+ }
3288
+ };
3289
+ n((v) => [...v, b]), p((v) => ({ ...v, [f]: 0 }));
3290
+ try {
3291
+ h(!0);
3292
+ const v = R.getInstance(), S = v.media.getFileTypeCategory(g.type), k = await v.media.uploadMedia({
3293
+ file: g,
3294
+ type: S,
3295
+ conversationId: c.id,
3296
+ onProgress: (A) => {
3297
+ p((L) => ({ ...L, [f]: A })), n((L) => L.map(
3298
+ (Z) => Z.id === f ? { ...Z, uploadProgress: A } : Z
3299
+ ));
3300
+ }
3301
+ });
3302
+ p((A) => ({ ...A, [f]: 100 }));
3303
+ const _ = S === "document" ? "file" : S === "image" ? "image" : "file", I = {
3304
+ fileUrl: k.fileUrl,
3305
+ fileName: k.fileName,
3306
+ fileSize: k.fileSize,
3307
+ mimeType: k.mimeType || g.type
3308
+ };
3309
+ await v.messages.sendMessageWithOptions({
3310
+ conversationId: c.id,
3311
+ content: `${g.name}`,
3312
+ type: _,
3313
+ metadata: I
3314
+ }), setTimeout(() => {
3315
+ n((A) => A.filter((L) => L.id !== f)), p((A) => {
3316
+ const L = { ...A };
3317
+ return delete L[f], L;
3318
+ });
3319
+ }, 200), z.success(w("file_sent_successfully"));
3320
+ } catch (v) {
3321
+ n((S) => S.filter((k) => k.id !== f)), p((S) => {
3322
+ const k = { ...S };
3323
+ return delete k[f], k;
3324
+ }), z.error(w("error_file_upload") + ": " + (v.message || w("error_unknown")));
3325
+ } finally {
3326
+ h(!1);
3327
+ }
3328
+ }, He = async () => {
3329
+ if (x(!1), !(!c || !e) && window.confirm(w("block_user_confirm")))
3330
+ try {
3331
+ const g = R.getInstance();
3332
+ if (!U) {
3333
+ z.error(w("user_not_found"));
3334
+ return;
3335
+ }
3336
+ const f = e.id || e.userId, b = U.id || U.userId || U.externalUserId || U.external_user_id;
3337
+ if (!b) {
3338
+ z.error(w("user_id_not_found"));
3339
+ return;
3340
+ }
3341
+ if (b === f) {
3342
+ z.error(w("cannot_block_self"));
3343
+ return;
3344
+ }
3345
+ await g.conversations.blockUserInChat(c.id, b);
3346
+ const v = c.metadata || {}, S = v.blockedUsers || {};
3347
+ S[b] = 1, c && (c.metadata = { ...v, blockedUsers: S }), F(!0), z.success(w("user_blocked"));
3348
+ } catch {
3349
+ z.error(w("failed_to_block"));
3350
+ }
3351
+ }, _e = async () => {
3352
+ if (x(!1), !(!c || !e) && window.confirm(w("unblock_user_confirm")))
3353
+ try {
3354
+ const g = R.getInstance();
3355
+ if (!U) {
3356
+ z.error(w("user_not_found"));
3357
+ return;
3358
+ }
3359
+ const f = U.id || U.userId || U.externalUserId || U.external_user_id;
3360
+ if (!f) {
3361
+ z.error(w("user_id_not_found"));
3362
+ return;
3363
+ }
3364
+ await g.conversations.unblockUserInChat(c.id, f);
3365
+ const b = c.metadata || {}, v = b.blockedUsers || {};
3366
+ delete v[f], c && (c.metadata = { ...b, blockedUsers: v }), F(!1), z.success(w("user_unblocked"));
3367
+ } catch {
3368
+ z.error(w("failed_to_unblock"));
3369
+ }
3370
+ };
3371
+ return i && s.length === 0 ? /* @__PURE__ */ M("div", { className: "chat-window", children: [
3372
+ /* @__PURE__ */ M("div", { className: "chat-header", children: [
3373
+ /* @__PURE__ */ u("div", { className: "chat-header-left", children: /* @__PURE__ */ u("h3", { style: { margin: 0 }, children: w("loading") }) }),
3374
+ /* @__PURE__ */ u("div", { className: "chat-header-actions", children: t && /* @__PURE__ */ u("button", { onClick: t, className: "close-button", children: "×" }) })
3375
+ ] }),
3376
+ /* @__PURE__ */ u("div", { className: "loading-messages", children: w("loading_messages") })
3377
+ ] }) : /* @__PURE__ */ M("div", { className: "chat-window", children: [
3378
+ /* @__PURE__ */ M("div", { className: "chat-header", children: [
3379
+ /* @__PURE__ */ M("div", { className: "chat-header-left", children: [
3380
+ a && /* @__PURE__ */ u("button", { className: "chat-back-btn", onClick: a, title: w("back") || "Back", children: /* @__PURE__ */ u("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ u("polyline", { points: "15 18 9 12 15 6" }) }) }),
3381
+ /* @__PURE__ */ u("div", { className: "chat-header-avatar", children: /* @__PURE__ */ u("div", { className: "avatar-placeholder", children: W.userName ? W.userName.charAt(0).toUpperCase() : "?" }) }),
3382
+ /* @__PURE__ */ u("div", { className: "chat-header-info", children: /* @__PURE__ */ u("h3", { className: "chat-participant-name", children: W.userName }) })
3383
+ ] }),
3384
+ /* @__PURE__ */ M("div", { className: "chat-header-actions", children: [
3385
+ U && /* @__PURE__ */ u("button", { onClick: We, className: "chat-action-btn", title: w("call") || "Call", children: /* @__PURE__ */ u("svg", { viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ u("path", { d: "M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z" }) }) }),
3386
+ t && /* @__PURE__ */ u("button", { onClick: t, className: "chat-action-btn", title: w("close") || "Close", children: /* @__PURE__ */ u("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: /* @__PURE__ */ u("path", { d: "M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7" }) }) }),
3387
+ c && U && /* @__PURE__ */ M("div", { className: "chat-options-wrapper", children: [
3388
+ /* @__PURE__ */ u("button", { onClick: () => x(!N), className: "chat-action-btn", title: w("options") || "Options", children: /* @__PURE__ */ M("svg", { viewBox: "0 0 24 24", fill: "currentColor", children: [
3389
+ /* @__PURE__ */ u("circle", { cx: "12", cy: "5", r: "2" }),
3390
+ /* @__PURE__ */ u("circle", { cx: "12", cy: "12", r: "2" }),
3391
+ /* @__PURE__ */ u("circle", { cx: "12", cy: "19", r: "2" })
3392
+ ] }) }),
3393
+ N && /* @__PURE__ */ M("div", { className: "chat-options-menu", children: [
3394
+ !B && !D && /* @__PURE__ */ M("button", { onClick: He, className: "danger", children: [
3395
+ /* @__PURE__ */ M("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: [
3396
+ /* @__PURE__ */ u("circle", { cx: "12", cy: "12", r: "10" }),
3397
+ /* @__PURE__ */ u("line", { x1: "4.93", y1: "4.93", x2: "19.07", y2: "19.07" })
3398
+ ] }),
3399
+ w("block_user")
3400
+ ] }),
3401
+ D && /* @__PURE__ */ M("button", { onClick: _e, children: [
3402
+ /* @__PURE__ */ M("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: [
3403
+ /* @__PURE__ */ u("circle", { cx: "12", cy: "12", r: "10" }),
3404
+ /* @__PURE__ */ u("path", { d: "M2 12h20" })
3405
+ ] }),
3406
+ w("unblock_user")
3407
+ ] })
3408
+ ] })
3409
+ ] })
3410
+ ] })
3411
+ ] }),
3412
+ W.productName && /* @__PURE__ */ M("div", { className: "chat-product-bar", children: [
3413
+ W.productImage && /* @__PURE__ */ u("img", { src: W.productImage, alt: W.productName }),
3414
+ /* @__PURE__ */ M("div", { className: "chat-product-bar-info", children: [
3415
+ /* @__PURE__ */ u("p", { className: "chat-product-bar-name", children: W.productName }),
3416
+ ((Se = W.productMetadata) == null ? void 0 : Se.price) && /* @__PURE__ */ M("p", { className: "chat-product-bar-price", children: [
3417
+ W.productMetadata.price,
3418
+ " ",
3419
+ W.productMetadata.currency || "QAR"
3420
+ ] })
3421
+ ] })
3422
+ ] }),
3423
+ /* @__PURE__ */ M("div", { className: "chat-messages", ref: $, onScroll: je, onClick: () => x(!1), children: [
3424
+ K && !i && s.length > 0 && /* @__PURE__ */ u("div", { className: `sticky-date-header ${te ? "sticky-date-visible" : ""}`, children: /* @__PURE__ */ u("span", { className: "sticky-date-pill", children: K }) }),
3425
+ i ? /* @__PURE__ */ u("div", { className: "loading-messages", children: w("loading_messages") }) : /* @__PURE__ */ M(Je, { children: [
3426
+ s.map((g, f) => {
3427
+ var b, v, S, k, _, I, A, L, Z, Le;
3428
+ return /* @__PURE__ */ M(Qe.Fragment, { children: [
3429
+ Pe(g, f) && /* @__PURE__ */ M("div", { className: "date-divider", "data-date": pe(g.timestamp), children: [
3430
+ /* @__PURE__ */ u("div", { className: "date-divider-line" }),
3431
+ /* @__PURE__ */ u("span", { className: "date-divider-text", children: pe(g.timestamp) }),
3432
+ /* @__PURE__ */ u("div", { className: "date-divider-line" })
3433
+ ] }),
3434
+ /* @__PURE__ */ u("div", { className: `message ${g.senderId === e.id ? "sent" : "received"}`, children: /* @__PURE__ */ M("div", { className: "message-content", children: [
3435
+ g.isUploading && g.uploadProgress !== void 0 && /* @__PURE__ */ u("div", { className: "upload-progress-bar", children: /* @__PURE__ */ u("div", { className: "upload-progress-fill", style: { width: `${g.uploadProgress}%` } }) }),
3436
+ g.type === "image" && ((b = g.metadata) != null && b.fileUrl || g.localFileUri) ? /* @__PURE__ */ M("div", { className: "message-attachment image-attachment", children: [
3437
+ /* @__PURE__ */ u(
3438
+ "img",
3439
+ {
3440
+ src: g.isUploading ? g.localFileUri : (v = g.metadata) == null ? void 0 : v.fileUrl,
3441
+ alt: ((S = g.metadata) == null ? void 0 : S.fileName) || w("image"),
3442
+ className: g.isUploading ? "uploading-image" : "",
3443
+ onClick: () => {
3444
+ var Ee;
3445
+ return !g.isUploading && ((Ee = g.metadata) == null ? void 0 : Ee.fileUrl) && window.open(g.metadata.fileUrl, "_blank");
3446
+ }
3447
+ }
3448
+ ),
3449
+ /* @__PURE__ */ M("div", { className: "attachment-info", children: [
3450
+ ((k = g.metadata) == null ? void 0 : k.fileName) || w("image"),
3451
+ ((_ = g.metadata) == null ? void 0 : _.fileSize) && /* @__PURE__ */ M("span", { children: [
3452
+ " • ",
3453
+ Math.round(g.metadata.fileSize / 1024),
3454
+ " KB"
3455
+ ] })
3456
+ ] })
3457
+ ] }) : g.type === "file" && ((I = g.metadata) != null && I.fileUrl) ? (
3458
+ /* File Message */
3459
+ /* @__PURE__ */ M("div", { className: "message-attachment file-attachment", children: [
3460
+ /* @__PURE__ */ M("div", { className: "file-info", children: [
3461
+ /* @__PURE__ */ u("div", { className: "file-icon", children: Oe((A = g.metadata) == null ? void 0 : A.mimeType) }),
3462
+ /* @__PURE__ */ M("div", { className: "file-details", children: [
3463
+ /* @__PURE__ */ u("div", { className: "file-name", children: ((L = g.metadata) == null ? void 0 : L.fileName) || w("file") }),
3464
+ /* @__PURE__ */ u("div", { className: "file-size", children: (Z = g.metadata) != null && Z.fileSize ? `${Math.round(g.metadata.fileSize / 1024)} KB` : w("unknown_size") })
3465
+ ] })
3466
+ ] }),
3467
+ /* @__PURE__ */ u(
3468
+ "a",
3469
+ {
3470
+ href: ((Le = g.metadata) == null ? void 0 : Le.fileUrl) || "#",
3471
+ target: "_blank",
3472
+ rel: "noopener noreferrer",
3473
+ className: "download-btn",
3474
+ children: w("download")
3475
+ }
3476
+ )
3477
+ ] })
3478
+ ) : (
3479
+ /* Text Message */
3480
+ g.content
3481
+ ),
3482
+ /* @__PURE__ */ M("div", { className: "message-footer", children: [
3483
+ /* @__PURE__ */ u("span", { className: "message-time", children: $e(g.timestamp) }),
3484
+ g.senderId === e.id && /* @__PURE__ */ u("span", { className: "message-status", children: /* @__PURE__ */ u("span", { className: "read-status", children: g.isRead ? /* @__PURE__ */ M("svg", { className: "read-check is-read", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.5", strokeLinecap: "round", strokeLinejoin: "round", width: "20", height: "20", children: [
3485
+ /* @__PURE__ */ u("polyline", { points: "1 13 5 17 11 9" }),
3486
+ /* @__PURE__ */ u("polyline", { points: "7 13 11 17 17 9" })
3487
+ ] }) : /* @__PURE__ */ u("svg", { className: "read-check", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.5", strokeLinecap: "round", strokeLinejoin: "round", width: "20", height: "20", children: /* @__PURE__ */ u("polyline", { points: "4 13 8 17 16 9" }) }) }) })
3488
+ ] })
3489
+ ] }) })
3490
+ ] }, g.id);
3491
+ }),
3492
+ /* @__PURE__ */ u("div", { ref: Q })
3493
+ ] })
3494
+ ] }),
3495
+ D && /* @__PURE__ */ M("div", { className: "blocked-ui blocked-by-me", children: [
3496
+ /* @__PURE__ */ u("div", { className: "blocked-title", children: w("you_have_blocked", { userName: W.userName || w("unknown_user") }) }),
3497
+ /* @__PURE__ */ u("div", { className: "blocked-message", children: w("you_have_blocked_submessage") }),
3498
+ /* @__PURE__ */ u("button", { onClick: _e, className: "unblock-btn", children: w("unblock_user") })
3499
+ ] }),
3500
+ B && !D && /* @__PURE__ */ M("div", { className: "blocked-ui blocked-by-other", children: [
3501
+ /* @__PURE__ */ u("div", { className: "blocked-title", children: w("blocked_by_user", { userName: W.userName || w("unknown_user") }) }),
3502
+ /* @__PURE__ */ u("div", { className: "blocked-message", children: w("blocked_by_user_submessage") })
3503
+ ] }),
3504
+ !D && !B && /* @__PURE__ */ M("form", { onSubmit: Ve, className: "chat-input", children: [
3505
+ /* @__PURE__ */ u(
3506
+ "button",
3507
+ {
3508
+ type: "button",
3509
+ onClick: () => {
3510
+ var g;
3511
+ return (g = ce.current) == null ? void 0 : g.click();
3512
+ },
3513
+ disabled: i || d || B,
3514
+ className: "attachment-btn",
3515
+ title: w("attach_file"),
3516
+ children: d ? /* @__PURE__ */ u("span", { children: "⌛" }) : /* @__PURE__ */ u("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ u("path", { d: "M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48" }) })
3517
+ }
3518
+ ),
3519
+ /* @__PURE__ */ u(
3520
+ "input",
3521
+ {
3522
+ ref: ce,
3523
+ type: "file",
3524
+ style: { display: "none" },
3525
+ accept: "image/*,video/*,audio/*,.pdf,.doc,.docx,.txt",
3526
+ onChange: (g) => {
3527
+ var b;
3528
+ const f = (b = g.target.files) == null ? void 0 : b[0];
3529
+ f && (Ge(f), g.target.value = "");
3530
+ }
3531
+ }
3532
+ ),
3533
+ /* @__PURE__ */ u(
3534
+ "input",
3535
+ {
3536
+ type: "text",
3537
+ value: o,
3538
+ onChange: (g) => r(g.target.value),
3539
+ placeholder: w(B ? "you_are_blocked" : d ? "uploading" : "message_hint"),
3540
+ disabled: i || d || B
3541
+ }
3542
+ ),
3543
+ /* @__PURE__ */ u("button", { type: "submit", disabled: !o.trim() || i || d || B, className: "send-btn", children: w(d ? "uploading" : "send") })
3544
+ ] })
3545
+ ] });
3546
+ }, ea = ({
3547
+ currentUser: c,
3548
+ onSelectConversation: e,
3549
+ selectedConversationId: t
3550
+ }) => {
3551
+ const [a, s] = T([]), [n, o] = T(!1), [r, i] = T(""), l = le(t), d = le(c.id);
3552
+ Y(() => {
3553
+ l.current = t;
3554
+ }, [t]), Y(() => {
3555
+ d.current = c.id;
3556
+ }, [c.id]), Y(() => {
3557
+ m();
3558
+ }, []), Y(() => {
3559
+ c && (s([]), m());
3560
+ }, [c.id]), Y(() => {
3561
+ var J;
3562
+ const y = R.getInstance(), C = (D) => {
3563
+ const F = D.message, N = F.roomId || F.conversationId;
3564
+ s(
3565
+ (x) => x.map((K) => {
3566
+ if (K.id === N) {
3567
+ const j = F.senderId !== d.current, te = l.current !== N;
3568
+ return {
3569
+ ...K,
3570
+ lastMessage: F,
3571
+ unreadCount: j && te ? K.unreadCount + 1 : K.unreadCount
3572
+ };
3573
+ }
3574
+ return K;
3575
+ }).sort((K, j) => {
3576
+ var Q, ce;
3577
+ const te = ((Q = K.lastMessage) == null ? void 0 : Q.timestamp) || K.createdAt, ae = ((ce = j.lastMessage) == null ? void 0 : ce.timestamp) || j.createdAt;
3578
+ return new Date(ae).getTime() - new Date(te).getTime();
3579
+ })
3580
+ ), F.senderId !== d.current && l.current === N && R.getInstance().chatUsers.markMessageRead(F.id).then(() => {
3581
+ s(
3582
+ (K) => K.map(
3583
+ (j) => j.id === N ? { ...j, unreadCount: 0 } : j
3584
+ )
3585
+ );
3586
+ }).catch((K) => {
3587
+ console.warn("Failed to auto-mark message as read:", K);
3588
+ });
3589
+ }, O = (D) => {
3590
+ var K, j, te, ae;
3591
+ const F = D.conversationId || ((K = D.conversation) == null ? void 0 : K.id) || ((j = D.conversation) == null ? void 0 : j.conversationId);
3592
+ if (!F) return;
3593
+ const N = D.lastMessage || ((te = D.conversation) == null ? void 0 : te.lastMessage), x = (ae = D.conversation) == null ? void 0 : ae.unreadCount;
3594
+ s((Q) => Q.some(($) => $.id === F) ? Q.map(($) => {
3595
+ if ($.id !== F) return $;
3596
+ const H = l.current === F, re = d.current;
3597
+ if (typeof x == "number")
3598
+ return {
3599
+ ...$,
3600
+ lastMessage: N || $.lastMessage,
3601
+ unreadCount: H ? 0 : x
3602
+ };
3603
+ const oe = (N == null ? void 0 : N.senderId) && N.senderId !== re, U = !!N && oe && !H;
3604
+ return {
3605
+ ...$,
3606
+ lastMessage: N || $.lastMessage,
3607
+ unreadCount: H ? 0 : U ? $.unreadCount + 1 : $.unreadCount
3608
+ };
3609
+ }).sort(($, H) => {
3610
+ var U, fe;
3611
+ const re = ((U = $.lastMessage) == null ? void 0 : U.timestamp) || $.createdAt, oe = ((fe = H.lastMessage) == null ? void 0 : fe.timestamp) || H.createdAt;
3612
+ return new Date(oe).getTime() - new Date(re).getTime();
3613
+ }) : (m(), Q));
3614
+ }, G = (D) => {
3615
+ const F = D.conversationId || D.roomId;
3616
+ F && s(
3617
+ (N) => N.map(
3618
+ (x) => x.id === F ? { ...x, unreadCount: 0 } : x
3619
+ )
3620
+ );
3621
+ }, B = (D) => {
3622
+ const F = D.roomId || D.conversationId;
3623
+ F && s(
3624
+ (N) => N.map(
3625
+ (x) => x.id === F ? { ...x, unreadCount: 0 } : x
3626
+ )
3627
+ );
3628
+ };
3629
+ return y.events.on("message.received", C), y.events.on("conversation.updated", O), y.events.on("conversation.read", G), (J = y.socket) != null && J.isConnected() && (y.socket.on("auto_marked_read", B), y.socket.on("room_marked_read", G)), () => {
3630
+ var D;
3631
+ y.events.off("message.received", C), y.events.off("conversation.updated", O), y.events.off("conversation.read", G), (D = y.socket) != null && D.isConnected() && (y.socket.off("auto_marked_read", B), y.socket.off("room_marked_read", G));
3632
+ };
3633
+ }, []);
3634
+ const h = async (y) => {
3635
+ try {
3636
+ if (y.unreadCount > 0) {
3637
+ const C = R.getInstance();
3638
+ await C.chatUsers.markRoomMessagesRead(y.id), C.chatUsers.startViewingConversation(y.id);
3639
+ }
3640
+ e(y);
3641
+ } catch (C) {
3642
+ console.error("Failed to mark conversation as read:", C), e(y);
3643
+ }
3644
+ }, m = async () => {
3645
+ o(!0);
3646
+ try {
3647
+ const C = await R.getInstance().chatUsers.getConversations();
3648
+ let O = C;
3649
+ C && typeof C == "object" && !Array.isArray(C) && (O = C.conversations || C.data || []), s(Array.isArray(O) ? O : []);
3650
+ } catch {
3651
+ z.error(w("error_load_conversations"));
3652
+ } finally {
3653
+ o(!1);
3654
+ }
3655
+ }, p = (y) => y.participants.find((C) => C.id !== c.id), E = (y) => {
3656
+ const C = p(y);
3657
+ return (C == null ? void 0 : C.name) || w("unknown_user");
3658
+ }, P = (y) => {
3659
+ var C;
3660
+ return ((C = y.lastMessage) == null ? void 0 : C.content) || w("no_messages_yet");
3661
+ }, Ce = (y) => {
3662
+ const C = new Date(y), G = ((/* @__PURE__ */ new Date()).getTime() - C.getTime()) / (1e3 * 60 * 60), B = G / 24;
3663
+ return G < 24 ? C.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : B < 7 ? `${Math.floor(B)}d ago` : `${C.getDate()} ${["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][C.getMonth()]}`;
3664
+ }, ge = r.trim() ? a.filter((y) => {
3665
+ var J, D;
3666
+ const C = r.toLowerCase().trim(), O = E(y).toLowerCase(), G = ((D = (J = y.productContext) == null ? void 0 : J.productName) == null ? void 0 : D.toLowerCase()) || "", B = P(y).toLowerCase();
3667
+ return O.includes(C) || G.includes(C) || B.includes(C);
3668
+ }) : a;
3669
+ return n ? /* @__PURE__ */ u("div", { className: "conversation-list loading", children: /* @__PURE__ */ u("div", { className: "loading-spinner", children: w("loading_conversations") }) }) : /* @__PURE__ */ M("div", { className: "conversation-list", children: [
3670
+ /* @__PURE__ */ u("div", { className: "conversation-list-header", children: /* @__PURE__ */ u("h3", { children: w("conversations_title") }) }),
3671
+ /* @__PURE__ */ u("div", { className: "conversation-search", children: /* @__PURE__ */ M("div", { className: "conversation-search-input", children: [
3672
+ /* @__PURE__ */ u("span", { className: "search-icon", children: /* @__PURE__ */ M("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
3673
+ /* @__PURE__ */ u("circle", { cx: "11", cy: "11", r: "8" }),
3674
+ /* @__PURE__ */ u("line", { x1: "21", y1: "21", x2: "16.65", y2: "16.65" })
3675
+ ] }) }),
3676
+ /* @__PURE__ */ u(
3677
+ "input",
3678
+ {
3679
+ value: r,
3680
+ onChange: (y) => i(y.target.value),
3681
+ type: "text",
3682
+ placeholder: w("search") || "Search"
3683
+ }
3684
+ )
3685
+ ] }) }),
3686
+ /* @__PURE__ */ u("div", { className: "conversations", children: ge.length === 0 ? /* @__PURE__ */ M("div", { className: "empty-conversations", children: [
3687
+ /* @__PURE__ */ u("p", { children: r ? w("no_search_results") || "No results found" : w("no_conversations_title") }),
3688
+ !r && /* @__PURE__ */ u("p", { children: w("no_conversations_message") })
3689
+ ] }) : ge.map((y) => {
3690
+ var O;
3691
+ const C = t === y.id;
3692
+ return /* @__PURE__ */ M(
3693
+ "div",
3694
+ {
3695
+ className: `conversation-item ${C ? "selected" : ""} ${y.unreadCount > 0 ? "has-unread" : ""}`,
3696
+ onClick: () => h(y),
3697
+ children: [
3698
+ /* @__PURE__ */ u("div", { className: "conversation-avatar", children: (O = y.productContext) != null && O.productImage ? /* @__PURE__ */ u(
3699
+ "img",
3700
+ {
3701
+ src: y.productContext.productImage,
3702
+ alt: y.productContext.productName,
3703
+ className: "product-image"
3704
+ }
3705
+ ) : /* @__PURE__ */ u("div", { className: "avatar-placeholder", children: E(y).charAt(0).toUpperCase() }) }),
3706
+ /* @__PURE__ */ M("div", { className: "conversation-content", children: [
3707
+ /* @__PURE__ */ M("div", { className: "conversation-header", children: [
3708
+ /* @__PURE__ */ u("div", { className: "conversation-title-wrapper", children: /* @__PURE__ */ u("h4", { className: "conversation-participant-name", children: E(y) }) }),
3709
+ y.lastMessage && /* @__PURE__ */ u("span", { className: "conversation-time", children: Ce(y.lastMessage.timestamp) })
3710
+ ] }),
3711
+ /* @__PURE__ */ M("div", { className: "conversation-details", children: [
3712
+ /* @__PURE__ */ u("p", { className: "conversation-last-message", children: P(y) }),
3713
+ y.unreadCount > 0 && /* @__PURE__ */ u("span", { className: "unread-badge", children: y.unreadCount })
3714
+ ] })
3715
+ ] })
3716
+ ]
3717
+ },
3718
+ y.id
3719
+ );
3720
+ }) })
3721
+ ] });
3722
+ }, Vt = () => {
3723
+ const [c, e] = T(() => typeof window < "u" && localStorage.getItem("chatSDK-theme") || "auto"), [t, a] = T(() => typeof window < "u" && window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"), s = c === "auto" ? t : c;
3724
+ Y(() => {
3725
+ if (typeof window > "u" || !window.matchMedia) return;
3726
+ const r = window.matchMedia("(prefers-color-scheme: dark)"), i = (l) => {
3727
+ a(l.matches ? "dark" : "light");
3728
+ };
3729
+ return r.addEventListener("change", i), () => r.removeEventListener("change", i);
3730
+ }, []), Y(() => {
3731
+ if (typeof window > "u") return;
3732
+ const r = document.documentElement;
3733
+ r.classList.remove("theme-light", "theme-dark"), r.removeAttribute("data-theme"), r.classList.add(`theme-${s}`), r.setAttribute("data-theme", s);
3734
+ }, [s]);
3735
+ const n = (r) => {
3736
+ e(r), typeof window < "u" && localStorage.setItem("chatSDK-theme", r);
3737
+ };
3738
+ return {
3739
+ theme: c,
3740
+ actualTheme: s,
3741
+ setTheme: n,
3742
+ toggleTheme: () => {
3743
+ n(c === "auto" ? t === "light" ? "dark" : "light" : s === "light" ? "dark" : "light");
3744
+ }
3745
+ };
3746
+ }, Ke = Ze(void 0), ta = ({ children: c }) => {
3747
+ const e = Vt();
3748
+ return /* @__PURE__ */ u(Ke.Provider, { value: e, children: c });
3749
+ }, Gt = () => {
3750
+ const c = Xe(Ke);
3751
+ if (!c)
3752
+ throw new Error("useThemeContext must be used within a ThemeProvider");
3753
+ return c;
3754
+ }, aa = ({
3755
+ className: c = "",
3756
+ showLabel: e = !1
3757
+ }) => {
3758
+ const { theme: t, actualTheme: a, setTheme: s } = Gt(), n = () => {
3759
+ switch (t) {
3760
+ case "light":
3761
+ return /* @__PURE__ */ u("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ u("path", { d: "M12 2.25a.75.75 0 01.75.75v2.25a.75.75 0 01-1.5 0V3a.75.75 0 01.75-.75zM7.5 12a4.5 4.5 0 119 0 4.5 4.5 0 01-9 0zM18.894 6.166a.75.75 0 00-1.06-1.06l-1.591 1.59a.75.75 0 101.06 1.061l1.591-1.59zM21.75 12a.75.75 0 01-.75.75h-2.25a.75.75 0 010-1.5H21a.75.75 0 01.75.75zM17.834 18.894a.75.75 0 001.06-1.06l-1.59-1.591a.75.75 0 10-1.061 1.06l1.59 1.591zM12 18a.75.75 0 01.75.75V21a.75.75 0 01-1.5 0v-2.25A.75.75 0 0112 18zM7.758 17.303a.75.75 0 00-1.061-1.06l-1.591 1.59a.75.75 0 001.06 1.061l1.591-1.59zM6 12a.75.75 0 01-.75.75H3a.75.75 0 010-1.5h2.25A.75.75 0 016 12zM6.697 7.757a.75.75 0 001.06-1.06l-1.59-1.591a.75.75 0 00-1.061 1.06l1.59 1.591z" }) });
3762
+ case "dark":
3763
+ return /* @__PURE__ */ u("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ u("path", { fillRule: "evenodd", d: "M9.528 1.718a.75.75 0 01.162.819A8.97 8.97 0 009 6a9 9 0 009 9 8.97 8.97 0 003.463-.69.75.75 0 01.981.98 10.503 10.503 0 01-9.694 6.46c-5.799 0-10.5-4.701-10.5-10.5 0-4.368 2.667-8.112 6.46-9.694a.75.75 0 01.818.162z", clipRule: "evenodd" }) });
3764
+ case "auto":
3765
+ return /* @__PURE__ */ u("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ u("path", { fillRule: "evenodd", d: "M2.25 6a3 3 0 013-3h13.5a3 3 0 013 3v12a3 3 0 01-3 3H5.25a3 3 0 01-3-3V6zm3.97.97a.75.75 0 011.06 0l2.25 2.25a.75.75 0 010 1.06l-2.25 2.25a.75.75 0 01-1.06-1.06l1.72-1.72-1.72-1.72a.75.75 0 010-1.06zm4.28 4.28a.75.75 0 000 1.5h3a.75.75 0 000-1.5h-3z", clipRule: "evenodd" }) });
3766
+ default:
3767
+ return null;
3768
+ }
3769
+ }, o = () => {
3770
+ switch (t) {
3771
+ case "light":
3772
+ return "Light";
3773
+ case "dark":
3774
+ return "Dark";
3775
+ case "auto":
3776
+ return `Auto (${a})`;
3777
+ default:
3778
+ return "";
3779
+ }
3780
+ };
3781
+ return /* @__PURE__ */ M(
3782
+ "button",
3783
+ {
3784
+ type: "button",
3785
+ onClick: () => {
3786
+ switch (t) {
3787
+ case "light":
3788
+ s("dark");
3789
+ break;
3790
+ case "dark":
3791
+ s("auto");
3792
+ break;
3793
+ case "auto":
3794
+ s("light");
3795
+ break;
3796
+ }
3797
+ },
3798
+ className: `
3799
+ inline-flex items-center gap-2 px-3 py-2 rounded-md
3800
+ text-on-surface bg-surface-variant hover:bg-primary hover:text-on-primary
3801
+ border border-figma-separator transition-colors duration-200
3802
+ focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2
3803
+ ${c}
3804
+ `,
3805
+ title: `Current theme: ${o()}. Click to cycle.`,
3806
+ "aria-label": `Switch theme. Current: ${o()}`,
3807
+ children: [
3808
+ n(),
3809
+ e && /* @__PURE__ */ u("span", { className: "text-sm font-medium", children: o() })
3810
+ ]
3811
+ }
3812
+ );
3813
+ }, sa = () => {
3814
+ var s;
3815
+ const c = localStorage.getItem("chatSDK-theme"), e = (s = window.matchMedia) == null ? void 0 : s.call(window, "(prefers-color-scheme: dark)").matches, t = c || "auto", a = t === "auto" ? e ? "dark" : "light" : t;
3816
+ document.documentElement.classList.add(`theme-${a}`), document.documentElement.setAttribute("data-theme", a);
3817
+ }, na = {
3818
+ // Material Design 3 Primary Colors
3819
+ primary: {
3820
+ main: "#2196F3",
3821
+ onPrimary: "#FFFFFF",
3822
+ container: "#BBDEFB",
3823
+ onContainer: "#0D47A1",
3824
+ dark: "#1976D2"
3825
+ },
3826
+ // Material Design 3 Secondary Colors
3827
+ secondary: {
3828
+ main: "#FF4081",
3829
+ onSecondary: "#FFFFFF",
3830
+ container: "#FCE4EC",
3831
+ onContainer: "#880E4F"
3832
+ },
3833
+ // Surface Colors
3834
+ surface: {
3835
+ main: "#FFFFFF",
3836
+ onSurface: "#212121",
3837
+ variant: "#F5F5F5",
3838
+ onVariant: "#757575"
3839
+ },
3840
+ // Background Colors
3841
+ background: {
3842
+ main: "#FFFFFF",
3843
+ onBackground: "#212121"
3844
+ },
3845
+ // Error Colors
3846
+ error: {
3847
+ main: "#F44336",
3848
+ onError: "#FFFFFF",
3849
+ container: "#FFEBEE",
3850
+ onContainer: "#B71C1C"
3851
+ },
3852
+ // Status Colors
3853
+ status: {
3854
+ success: "#4CAF50",
3855
+ warning: "#FF9800",
3856
+ error: "#F44336",
3857
+ info: "#2196F3"
3858
+ },
3859
+ // Figma Design Colors
3860
+ figma: {
3861
+ background: "#F0F0F0",
3862
+ textPrimary: "#1E1E1E",
3863
+ textProduct: "#95265B",
3864
+ textTimestamp: "#878787",
3865
+ separator: "#C4C4C4",
3866
+ onlineIndicator: "#4CAF50"
3867
+ },
3868
+ // Chat Colors
3869
+ chat: {
3870
+ background: "#F4F4F4",
3871
+ productText: "#923060",
3872
+ messageReceived: "#FFFFFF",
3873
+ messageSent: "#C4C4C4",
3874
+ inputBackground: "#FBFBFB",
3875
+ inputPlaceholder: "#C4C4C4",
3876
+ timestamp: "#878787",
3877
+ primaryText: "#1E1E1E"
3878
+ },
3879
+ // Component Colors
3880
+ message: {
3881
+ sentBackground: "#2196F3",
3882
+ receivedBackground: "#F5F5F5"
3883
+ },
3884
+ avatar: {
3885
+ background: "#E0E0E0",
3886
+ border: "#BDBDBD"
3887
+ },
3888
+ input: {
3889
+ background: "#FAFAFA",
3890
+ border: "#E0E0E0"
3891
+ },
3892
+ badge: {
3893
+ unreadBackground: "#F44336"
3894
+ },
3895
+ // Common Colors
3896
+ common: {
3897
+ white: "#FFFFFF",
3898
+ black: "#000000",
3899
+ transparent: "transparent"
3900
+ }
3901
+ }, ra = {
3902
+ primary: {
3903
+ main: "#90CAF9",
3904
+ onPrimary: "#0D47A1",
3905
+ container: "#1565C0",
3906
+ onContainer: "#E3F2FD",
3907
+ dark: "#42A5F5"
3908
+ },
3909
+ secondary: {
3910
+ main: "#F8BBD9",
3911
+ onSecondary: "#4A148C",
3912
+ container: "#7B1FA2",
3913
+ onContainer: "#FCE4EC"
3914
+ },
3915
+ surface: {
3916
+ main: "#121212",
3917
+ onSurface: "#FFFFFF",
3918
+ variant: "#1E1E1E",
3919
+ onVariant: "#BDBDBD"
3920
+ },
3921
+ background: {
3922
+ main: "#121212",
3923
+ onBackground: "#FFFFFF"
3924
+ },
3925
+ error: {
3926
+ main: "#CF6679",
3927
+ onError: "#000000",
3928
+ container: "#B00020",
3929
+ onContainer: "#FECDD3"
3930
+ },
3931
+ figma: {
3932
+ background: "#1E1E1E",
3933
+ textPrimary: "#FFFFFF",
3934
+ textProduct: "#F8BBD9",
3935
+ textTimestamp: "#BDBDBD",
3936
+ separator: "#424242",
3937
+ onlineIndicator: "#4CAF50"
3938
+ },
3939
+ chat: {
3940
+ background: "#121212",
3941
+ productText: "#F8BBD9",
3942
+ messageReceived: "#2C2C2C",
3943
+ messageSent: "#424242",
3944
+ inputBackground: "#1E1E1E",
3945
+ inputPlaceholder: "#757575",
3946
+ timestamp: "#BDBDBD",
3947
+ primaryText: "#FFFFFF"
3948
+ }
3949
+ }, oa = {
3950
+ async init(c) {
3951
+ const { ChatSDK: e } = await Promise.resolve().then(() => ct);
3952
+ return e.getInstance().init(c);
3953
+ },
3954
+ formatFileSize(c) {
3955
+ if (c === 0) return "0 Bytes";
3956
+ const e = 1024, t = ["Bytes", "KB", "MB", "GB"], a = Math.floor(Math.log(c) / Math.log(e));
3957
+ return parseFloat((c / Math.pow(e, a)).toFixed(2)) + " " + t[a];
3958
+ },
3959
+ formatTimeAgo(c) {
3960
+ const e = new Date(c), a = (/* @__PURE__ */ new Date()).getTime() - e.getTime(), s = Math.floor(a / 6e4), n = Math.floor(a / 36e5), o = Math.floor(a / 864e5);
3961
+ return s < 1 ? "now" : s < 60 ? `${s}m ago` : n < 24 ? `${n}h ago` : o < 7 ? `${o}d ago` : e.toLocaleDateString();
3962
+ }
3963
+ };
3964
+ export {
3965
+ et as AuthManager,
3966
+ R as ChatSDK,
3967
+ oa as ChatSDKHelpers,
3968
+ Xt as ChatWindow,
3969
+ ea as ConversationList,
3970
+ st as ConversationManager,
3971
+ ot as EventManager,
3972
+ rt as MediaManager,
3973
+ nt as MessageManager,
3974
+ Ue as ParseUtils,
3975
+ it as SocketManager,
3976
+ ta as ThemeProvider,
3977
+ aa as ThemeToggle,
3978
+ at as UserManager,
3979
+ Ie as changeLanguage,
3980
+ ra as darkThemeConfig,
3981
+ Zt as getCurrentLanguage,
3982
+ sa as initializeTheme,
3983
+ qt as isRTL,
3984
+ w as t,
3985
+ na as themeConfig,
3986
+ Vt as useTheme,
3987
+ Gt as useThemeContext
3988
+ };
3989
+ //# sourceMappingURL=chatsdk-react.mjs.map