@traiyani/chatsdk-react 1.0.3 → 1.0.5

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.
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ie=require("axios"),tt=require("socket.io-client"),d=require("react/jsx-runtime"),M=require("react");function st(c){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(c){for(const t in c)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(c,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>c[t]})}}return e.default=c,Object.freeze(e)}const W=st(M);class De{constructor(e){this.api=null,this.config=null,this.chatSDK=e}async init(e){this.config=e,this.api=ie.create({baseURL:e.apiBaseUrl,headers:{"Content-Type":"application/json"},timeout:e.timeout||3e4}),this.api.interceptors.request.use(t=>{const s=this.getToken();return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t)),this.api.interceptors.response.use(t=>t,t=>{var s,a,n;if(((s=t.response)==null?void 0:s.status)===401){const r=(((a=t.config)==null?void 0:a.url)||"").includes("/api/auth/me");this.clearToken(),r||(n=this.chatSDK.events)==null||n.emit("auth.logout",{reason:"unauthorized"})}return Promise.reject(t)})}async authenticate(e,t,s,a){var n,o,r,i,l,g;if(!this.api)throw new Error("AuthManager not initialized");try{const u=await this.api.post("/api/chat-users/authenticate",{externalUserId:e,appId:t,name:s,email:a}),m=this.parseAuthResponse(u.data);return(n=this.config)!=null&&n.enableLogging&&console.log("🔐 AuthManager: Authentication successful",{userId:m.id,externalUserId:m.externalUserId,name:m.name}),(o=this.chatSDK.events)==null||o.emit("auth.login",{user:m}),m}catch(u){throw(r=this.config)!=null&&r.enableLogging&&console.error("❌ AuthManager: Authentication failed",((i=u.response)==null?void 0:i.data)||u.message),new Error(((g=(l=u.response)==null?void 0:l.data)==null?void 0:g.message)||"Authentication failed")}}async login(e,t){var s,a,n,o,r,i;if(!this.api)throw new Error("AuthManager not initialized");try{const l=await this.api.post("/api/auth/signin",{email:e,password:t}),{token:g,user:u}=l.data;return this.setToken(g),(s=this.config)!=null&&s.enableLogging&&console.log("🔐 AuthManager: Login successful",{userId:u.id,email:u.email}),(a=this.chatSDK.events)==null||a.emit("auth.login",{user:u}),u}catch(l){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")}}async chatUserLogin(e,t){var s,a,n,o,r,i;if(!this.api)throw new Error("AuthManager not initialized");try{const l=await this.api.post("/api/chat-users/login",{externalUserId:e,appId:t}),g=this.parseAuthResponse(l.data);return(s=this.config)!=null&&s.enableLogging&&console.log("🔐 AuthManager: Chat user login successful",{userId:g.id,externalUserId:g.externalUserId}),(a=this.chatSDK.events)==null||a.emit("auth.login",{user:g}),g}catch(l){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")}}async register(e,t,s,a={}){var n,o,r,i,l,g;if(!this.api)throw new Error("AuthManager not initialized");try{const u=await this.api.post("/api/auth/signup",{email:e,password:t,name:s,...a}),{token:m,user:p}=u.data;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}catch(u){throw(r=this.config)!=null&&r.enableLogging&&console.error("❌ AuthManager: Registration failed",((i=u.response)==null?void 0:i.data)||u.message),new Error(((g=(l=u.response)==null?void 0:l.data)==null?void 0:g.message)||"Registration failed")}}async chatUserRegister(e,t,s,a){var n,o,r,i,l,g;if(!this.api)throw new Error("AuthManager not initialized");try{const u=await this.api.post("/api/chat-users/register",{externalUserId:e,appId:t,name:s,email:a}),m=this.parseAuthResponse(u.data);return(n=this.config)!=null&&n.enableLogging&&console.log("🔐 AuthManager: Chat user registration successful",{userId:m.id,externalUserId:m.externalUserId,name:m.name}),(o=this.chatSDK.events)==null||o.emit("auth.register",{user:m}),m}catch(u){throw(r=this.config)!=null&&r.enableLogging&&console.error("❌ AuthManager: Chat user registration failed",((i=u.response)==null?void 0:i.data)||u.message),new Error(((g=(l=u.response)==null?void 0:l.data)==null?void 0:g.message)||"Chat user registration failed")}}parseAuthResponse(e){if(!e.success)throw new Error(e.message||"Authentication failed");if(!e.data)throw new Error("Invalid response format: missing data");const{token:t,user:s,auth:a}=e.data,n=t||(a==null?void 0:a.accessToken);return n&&this.setToken(n),{id:s.id,externalUserId:s.externalUserId,appId:s.appId||process.env.REACT_APP_APP_ID||"",name:s.name,email:s.email,avatarUrl:s.avatarUrl,status:s.status||"offline",isOnline:s.isOnline||!1,lastSeen:s.lastSeen,isRegistered:!0,createdAt:s.createdAt||new Date().toISOString(),updatedAt:s.updatedAt||new Date().toISOString()}}async logout(){var e,t,s;if(!this.api)throw new Error("AuthManager not initialized");try{await this.api.post("/api/auth/signout")}catch{(e=this.config)!=null&&e.enableLogging&&console.warn("⚠️ AuthManager: Logout API call failed, continuing with local logout")}this.clearToken(),(t=this.config)!=null&&t.enableLogging&&console.log("👋 AuthManager: Logout successful"),(s=this.chatSDK.events)==null||s.emit("auth.logout",{reason:"user_initiated"})}async getCurrentUser(){var e,t,s,a;if(!this.api)throw new Error("AuthManager not initialized");if(!this.hasValidToken())throw new Error("No valid token found. Please login first.");try{const n=await this.api.get("/api/auth/me");return this.parseAuthResponse(n.data)}catch(n){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(((a=(s=n.response)==null?void 0:s.data)==null?void 0:a.message)||"Failed to get current user")}}async verifyEmail(e){var t,s,a,n,o;if(!this.api)throw new Error("AuthManager not initialized");try{await this.api.post("/api/auth/verify-email",{token:e}),(t=this.config)!=null&&t.enableLogging&&console.log("✅ AuthManager: Email verified successfully")}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ AuthManager: Email verification failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Email verification failed")}}async forgotPassword(e){var t,s,a,n,o;if(!this.api)throw new Error("AuthManager not initialized");try{await this.api.post("/api/auth/forgot-password",{email:e}),(t=this.config)!=null&&t.enableLogging&&console.log("📧 AuthManager: Password reset email sent")}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ AuthManager: Forgot password failed",((a=r.response)==null?void 0:a.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")}}async resetPassword(e,t){var s,a,n,o,r;if(!this.api)throw new Error("AuthManager not initialized");try{await this.api.post("/api/auth/reset-password",{token:e,password:t}),(s=this.config)!=null&&s.enableLogging&&console.log("🔐 AuthManager: Password reset successful")}catch(i){throw(a=this.config)!=null&&a.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")}}hasValidToken(){return!!this.getToken()}getToken(){return localStorage.getItem("chatSDKToken")}setToken(e){localStorage.setItem("chatSDKToken",e)}clearToken(){localStorage.removeItem("chatSDKToken")}}class at{constructor(e){this.api=null,this.config=null,this.chatSDK=e}async init(e){this.config=e,this.api=ie.create({baseURL:e.apiBaseUrl,headers:{"Content-Type":"application/json"},timeout:e.timeout||3e4}),this.api.interceptors.request.use(t=>{const s=this.getToken();return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t)),this.api.interceptors.response.use(t=>t,t=>{var s,a;return((s=t.response)==null?void 0:s.status)===401&&(this.clearToken(),(a=this.chatSDK.events)==null||a.emit("chatUser.logout",{reason:"unauthorized"})),Promise.reject(t)})}async login(e,t,s=!0){var a,n,o,r,i,l,g;if(!this.api)throw new Error("ChatUserManager not initialized");try{const u=await this.api.post("/api/chat-users/login",{externalUserId:e,appId:t}),{token:m,user:p}=u.data.data;return s?(this.setToken(m),(a=this.config)!=null&&a.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}catch(u){throw(r=this.config)!=null&&r.enableLogging&&console.error("❌ ChatUserManager: Chat user login failed",((i=u.response)==null?void 0:i.data)||u.message),new Error(((g=(l=u.response)==null?void 0:l.data)==null?void 0:g.message)||"Chat user login failed")}}async register(e,t=!0){var s,a,n,o,r,i,l;if(!this.api)throw new Error("ChatUserManager not initialized");try{const g=await this.api.post("/api/chat-users/register",e),{token:u,user:m}=g.data.data;return t?(this.setToken(u),(s=this.config)!=null&&s.enableLogging&&console.log("📝 ChatUserManager: Chat user registration successful with token saved",{userId:m.id,email:m.email}),(a=this.chatSDK.events)==null||a.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}catch(g){throw(o=this.config)!=null&&o.enableLogging&&console.error("❌ ChatUserManager: Chat user registration failed",((r=g.response)==null?void 0:r.data)||g.message),new Error(((l=(i=g.response)==null?void 0:i.data)==null?void 0:l.message)||"Chat user registration failed")}}async authenticate(e,t,s,a,n=!0){try{return await this.login(e,t,n)}catch{try{return await this.register({externalUserId:e,appId:t,name:s,email:a},n)}catch(r){throw new Error("Failed to authenticate chat user: "+r)}}}async logout(){var e,t;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"})}getToken(){return localStorage.getItem("chatSDKToken")}setToken(e){localStorage.setItem("chatSDKToken",e)}clearToken(){localStorage.removeItem("chatSDKToken")}isAuthenticated(){return!!this.getToken()}async registerFcmToken(e,t="android"){var s,a,n,o,r,i;if(!this.api)throw new Error("ChatUserManager not initialized");if(!this.isAuthenticated())throw new Error("User must be authenticated to register FCM token");try{const l=await this.api.post("/api/chat-users/fcm-token",{fcmToken:e,platform:t});(s=this.config)!=null&&s.enableLogging&&console.log("📱 ChatUserManager: FCM token registered successfully",{fcmToken:e,platform:t}),(a=this.chatSDK.events)==null||a.emit("chatUser.fcmTokenRegistered",{fcmToken:e,platform:t})}catch(l){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")}}async unregisterFcmToken(e){var t,s,a,n,o,r;if(!this.api)throw new Error("ChatUserManager not initialized");if(!this.isAuthenticated())throw new Error("User must be authenticated to unregister FCM token");try{const i=await this.api.delete("/api/chat-users/fcm-token",{data:{fcmToken:e}});(t=this.config)!=null&&t.enableLogging&&console.log("🗑️ ChatUserManager: FCM token unregistered successfully",{fcmToken:e}),(s=this.chatSDK.events)==null||s.emit("chatUser.fcmTokenUnregistered",{fcmToken:e})}catch(i){throw(a=this.config)!=null&&a.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")}}async getFcmTokens(){var e,t,s,a,n,o,r;if(!this.api)throw new Error("ChatUserManager not initialized");if(!this.isAuthenticated())throw new Error("User must be authenticated to get FCM tokens");try{const l=((t=(e=(await this.api.get("/api/chat-users/fcm-tokens")).data)==null?void 0:e.data)==null?void 0:t.fcmTokens)||[];return(s=this.config)!=null&&s.enableLogging&&console.log("📱 ChatUserManager: Retrieved FCM tokens",{tokenCount:l.length}),l}catch(i){throw(a=this.config)!=null&&a.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")}}async getConversations(e={}){var t,s,a,n,o;if(!this.api)throw new Error("ChatUserManager not initialized");try{const r=new URLSearchParams;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");const i=await this.api.get(`/api/chat-users/chats?${r.toString()}`),l=i.data.data||i.data.conversations||i.data||[];return(t=this.config)!=null&&t.enableLogging&&console.log("📋 ChatUserManager: Conversations fetched successfully",{count:l.length}),l}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ ChatUserManager: Get conversations failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get conversations")}}async startChat(e,t){var s,a,n,o,r,i,l;if(!this.api)throw new Error("ChatUserManager not initialized");if(!e)throw new Error("External Group ID is required");try{const g=await this.api.post("/api/chat-users/chats",{type:"direct",participants:[t],externalGroupId:e}),u=g.data.data||g.data.conversation||g.data;return(s=this.config)!=null&&s.enableLogging&&console.log("💬 ChatUserManager: Direct chat started successfully",{conversationId:u.id,userId:t,externalGroupId:e}),(a=this.chatSDK.socket)!=null&&a.isConnected()&&this.chatSDK.socket.joinRoom(u.id),(n=this.chatSDK.events)==null||n.emit("conversation.created",{conversation:u}),u}catch(g){throw(o=this.config)!=null&&o.enableLogging&&console.error("❌ ChatUserManager: Start chat failed",((r=g.response)==null?void 0:r.data)||g.message),new Error(((l=(i=g.response)==null?void 0:i.data)==null?void 0:l.message)||"Failed to start chat")}}async startChatWithProduct(e,t,s,a){var n,o,r,i,l,g,u;if(!this.api)throw new Error("ChatUserManager not initialized");if(!e)throw new Error("External Group ID is required");try{const m={type:"direct",participants:[t],externalGroupId:e,metadata:{productContext:{productId:s.productId,productName:s.productName,productImage:s.productImage,price:s.price,currency:s.currency,category:s.category,productMetadata:s.productMetadata}}};a&&Object.keys(a).length>0&&(m.chatMetadata=a);const p=await this.api.post("/api/chat-users/chats",m),x=p.data.data||p.data.conversation||p.data;return(n=this.config)!=null&&n.enableLogging&&console.log("💬 ChatUserManager: Product chat started successfully",{conversationId:x.id,userId:t,productId:s.productId,productName:s.productName}),(o=this.chatSDK.socket)!=null&&o.isConnected()&&this.chatSDK.socket.joinRoom(x.id),(r=this.chatSDK.events)==null||r.emit("conversation.created",{conversation:x}),x}catch(m){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(((u=(g=m.response)==null?void 0:g.data)==null?void 0:u.message)||"Failed to start product chat")}}async getUnreadConversationsCount(){var e,t,s,a,n;if(!this.api)throw new Error("ChatUserManager not initialized");try{const r=(await this.api.get("/api/chat-users/unread/conversations-count")).data.data.unreadConversationsCount||0;return(e=this.config)!=null&&e.enableLogging&&console.log("📊 ChatUserManager: Unread conversations count fetched",{count:r}),r}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ ChatUserManager: Get unread conversations count failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get unread conversations count")}}async getTotalUnreadCount(){var e,t,s,a,n;if(!this.api)throw new Error("ChatUserManager not initialized");try{const r=(await this.api.get("/api/chat-users/unread/total-count")).data.data.totalUnreadCount||0;return(e=this.config)!=null&&e.enableLogging&&console.log("📊 ChatUserManager: Total unread count fetched",{count:r}),r}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ ChatUserManager: Get total unread count failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get total unread count")}}async getUnreadSummary(){var e,t,s,a,n;if(!this.api)throw new Error("ChatUserManager not initialized");try{const r=(await this.api.get("/api/chat-users/unread/summary")).data.data;return(e=this.config)!=null&&e.enableLogging&&console.log("📊 ChatUserManager: Unread summary fetched",{conversations:r.totalConversationsWithUnread,totalMessages:r.totalUnreadMessages}),r}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ ChatUserManager: Get unread summary failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get unread summary")}}async markRoomMessagesRead(e){var t,s,a,n,o,r,i,l,g,u,m;if(!this.api)throw new Error("ChatUserManager not initialized");try{if((t=this.config)!=null&&t.enableLogging&&console.log("📖 ChatUserManager: Marking room as read",{conversationId:e}),(s=this.chatSDK.socket)!=null&&s.isConnected())return this.chatSDK.socket.emit("mark_room_read",{roomId:e}),(a=this.config)!=null&&a.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;(o=this.config)!=null&&o.enableLogging&&console.log("📡 ChatUserManager: Socket not connected, falling back to API");const x=(await this.api.post(`/api/chat-users/chats/${e}/mark-read`)).data.data.markedAsReadCount||0;return(r=this.config)!=null&&r.enableLogging&&console.log("✅ ChatUserManager: Room messages marked as read via API",{conversationId:e,markedCount:x}),(i=this.chatSDK.events)==null||i.emit("conversation.read",{conversationId:e,markedCount:x}),x}catch(p){throw console.error("❌ ChatUserManager: Mark room messages as read failed",{conversationId:e,error:((l=p.response)==null?void 0:l.data)||p.message,status:(g=p.response)==null?void 0:g.status}),new Error(((m=(u=p.response)==null?void 0:u.data)==null?void 0:m.message)||p.message||"Failed to mark room messages as read")}}async markMessageRead(e){var t,s,a,n,o,r,i,l,g,u;if(!this.api)throw new Error("ChatUserManager not initialized");try{if((t=this.chatSDK.socket)!=null&&t.isConnected())return this.chatSDK.socket.emit("mark_message_read",{messageId:e}),(s=this.config)!=null&&s.enableLogging&&console.log("📡 ChatUserManager: mark_message_read sent via socket",{messageId:e}),(a=this.chatSDK.events)==null||a.emit("message.read",{messageId:e,wasUnread:!0}),!0;(n=this.config)!=null&&n.enableLogging&&console.log("📡 ChatUserManager: Socket not connected, falling back to API for mark-message-read");const p=(await this.api.post(`/api/chat-users/messages/${e}/mark-read`)).data.data.wasUnread||!1;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}catch(m){throw console.error("❌ ChatUserManager: Mark message as read failed",{messageId:e,error:((i=m.response)==null?void 0:i.data)||m.message,status:(l=m.response)==null?void 0:l.status}),new Error(((u=(g=m.response)==null?void 0:g.data)==null?void 0:u.message)||m.message||"Failed to mark message as read")}}startViewingConversation(e){var t,s;(t=this.chatSDK.socket)!=null&&t.isConnected()&&(this.chatSDK.socket.emit("viewing_conversation",{roomId:e,isViewing:!0}),(s=this.config)!=null&&s.enableLogging&&console.log("👀 ChatUserManager: Started viewing conversation",{conversationId:e}))}stopViewingConversation(e){var t,s;(t=this.chatSDK.socket)!=null&&t.isConnected()&&(this.chatSDK.socket.emit("viewing_conversation",{roomId:e,isViewing:!1}),(s=this.config)!=null&&s.enableLogging&&console.log("👁️ ChatUserManager: Stopped viewing conversation",{conversationId:e}))}}class Ue{constructor(e){this.api=null,this.config=null,this.chatSDK=e}async init(e){this.config=e,this.api=ie.create({baseURL:e.apiBaseUrl,headers:{"Content-Type":"application/json"},timeout:e.timeout||3e4}),this.api.interceptors.request.use(t=>{const s=localStorage.getItem("chatSDKToken");return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t))}async getUser(e){var t,s,a,n,o;if(!this.api)throw new Error("UserManager not initialized");try{const r=await this.api.get(`/api/users/${e}`);return(t=this.config)!=null&&t.enableLogging&&console.log("👤 UserManager: User fetched successfully",{userId:e}),r.data.user}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ UserManager: Get user failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get user")}}async searchUsers(e={}){var t,s,a,n,o,r;if(!this.api)throw new Error("UserManager not initialized");try{const i=new URLSearchParams;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);const l=await this.api.get(`/api/users/search?${i.toString()}`);return(t=this.config)!=null&&t.enableLogging&&console.log("🔍 UserManager: Users searched successfully",{query:e.query,count:((s=l.data.users)==null?void 0:s.length)||0}),l.data.users||[]}catch(i){throw(a=this.config)!=null&&a.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")}}async getAllUsers(e=20,t=0){var s,a,n,o,r,i;if(!this.api)throw new Error("UserManager not initialized");try{const l=await this.api.get(`/api/users?limit=${e}&offset=${t}`);return(s=this.config)!=null&&s.enableLogging&&console.log("👥 UserManager: All users fetched successfully",{count:((a=l.data.users)==null?void 0:a.length)||0,limit:e,offset:t}),l.data.users||[]}catch(l){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")}}async updateCurrentUser(e){var t,s,a,n,o,r;if(!this.api)throw new Error("UserManager not initialized");try{const i=await this.api.put("/api/users/me",e);return(t=this.config)!=null&&t.enableLogging&&console.log("✏️ UserManager: User profile updated successfully"),(s=this.chatSDK.events)==null||s.emit("user.updated",{user:i.data.user}),i.data.user}catch(i){throw(a=this.config)!=null&&a.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")}}async updateStatus(e){var t,s,a,n,o,r;if(!this.api)throw new Error("UserManager not initialized");try{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}),(s=this.chatSDK.events)==null||s.emit("user.status.updated",{status:e})}catch(i){throw(a=this.config)!=null&&a.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")}}async blockUser(e){var t,s,a,n,o,r;if(!this.api)throw new Error("UserManager not initialized");try{await this.api.post(`/api/users/${e}/block`),(t=this.config)!=null&&t.enableLogging&&console.log("🚫 UserManager: User blocked successfully",{userId:e}),(s=this.chatSDK.events)==null||s.emit("user.blocked",{userId:e})}catch(i){throw(a=this.config)!=null&&a.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")}}async unblockUser(e){var t,s,a,n,o,r;if(!this.api)throw new Error("UserManager not initialized");try{await this.api.delete(`/api/users/${e}/block`),(t=this.config)!=null&&t.enableLogging&&console.log("✅ UserManager: User unblocked successfully",{userId:e}),(s=this.chatSDK.events)==null||s.emit("user.unblocked",{userId:e})}catch(i){throw(a=this.config)!=null&&a.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")}}async getBlockedUsers(){var e,t,s,a,n,o;if(!this.api)throw new Error("UserManager not initialized");try{const r=await this.api.get("/api/users/me/blocked");return(e=this.config)!=null&&e.enableLogging&&console.log("📋 UserManager: Blocked users fetched successfully",{count:((t=r.data.users)==null?void 0:t.length)||0}),r.data.users||[]}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ UserManager: Get blocked users failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get blocked users")}}async getUserStatus(e){var t,s,a,n;if(!this.api)throw new Error("UserManager not initialized");try{return(await this.api.get(`/api/users/${e}/status`)).data.status}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ UserManager: Get user status failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get user status")}}async getUsersByIds(e){var t,s,a,n,o,r;if(!this.api)throw new Error("UserManager not initialized");try{const i=await this.api.post("/api/users/batch",{userIds:e});return(t=this.config)!=null&&t.enableLogging&&console.log("👥 UserManager: Users fetched by IDs successfully",{requestedCount:e.length,receivedCount:((s=i.data.users)==null?void 0:s.length)||0}),i.data.users||[]}catch(i){throw(a=this.config)!=null&&a.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")}}}class Fe{constructor(e){this.api=null,this.config=null,this.chatSDK=e}async init(e){this.config=e,this.api=ie.create({baseURL:e.apiBaseUrl,headers:{"Content-Type":"application/json"},timeout:e.timeout||3e4}),this.api.interceptors.request.use(t=>{const s=localStorage.getItem("chatSDKToken");return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t))}async startChat(e,t){var s,a,n,o,r,i,l,g;if(!this.api)throw new Error("ConversationManager not initialized");if(!e)throw new Error("External Group ID is required");try{const u=await this.api.post("/api/chat-users/chats",{type:"direct",participants:[t],externalGroupId:e});(s=this.config)!=null&&s.enableLogging&&console.log("⚡ Using externalGroupId:",e),console.log("📡 Server response:",u.data);const m=u.data.data||u.data.conversation||u.data;return(a=this.config)!=null&&a.enableLogging&&console.log("💬 ConversationManager: Direct chat started successfully",{conversationId:m.id,userId:t}),(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}catch(u){throw(r=this.config)!=null&&r.enableLogging&&console.error("❌ ConversationManager: Start chat failed",((i=u.response)==null?void 0:i.data)||u.message),new Error(((g=(l=u.response)==null?void 0:l.data)==null?void 0:g.message)||"Failed to start chat")}}async startChatWithProduct(e,t,s,a){var n,o,r,i,l,g,u,m;if(!this.api)throw new Error("ConversationManager not initialized");if(!e)throw new Error("External Group ID is required");try{const p={type:"direct",participants:[t],externalGroupId:e,metadata:{productContext:{productId:s.productId,productName:s.productName,productImage:s.productImage,price:s.price,currency:s.currency,category:s.category,productMetadata:s.productMetadata}}};a&&Object.keys(a).length>0&&(p.chatMetadata=a),(n=this.config)!=null&&n.enableLogging&&console.log("⚡ Using externalGroupId:",e);const x=await this.api.post("/api/chat-users/chats",p);console.log("📡 Server response:",x.data);const B=x.data.data||x.data.conversation||x.data;return(o=this.config)!=null&&o.enableLogging&&console.log("💬 ConversationManager: Product chat started successfully",{conversationId:B.id,userId:t,productId:s.productId,productName:s.productName}),(r=this.chatSDK.socket)!=null&&r.isConnected()&&this.chatSDK.socket.joinRoom(B.id),(i=this.chatSDK.events)==null||i.emit("conversation.created",{conversation:B}),B}catch(p){throw(l=this.config)!=null&&l.enableLogging&&console.error("❌ ConversationManager: Start product chat failed",((g=p.response)==null?void 0:g.data)||p.message),new Error(((m=(u=p.response)==null?void 0:u.data)==null?void 0:m.message)||"Failed to start product chat")}}async createGroup(e){var t,s,a,n,o,r;if(!this.api)throw new Error("ConversationManager not initialized");try{const i=await this.api.post("/api/conversations",e);console.log("📡 Group creation response:",i.data);const l=i.data.data||i.data.conversation||i.data;return(t=this.config)!=null&&t.enableLogging&&console.log("👥 ConversationManager: Group created successfully",{conversationId:l.id,participantCount:e.participantIds.length}),(s=this.chatSDK.events)==null||s.emit("conversation.created",{conversation:l}),l}catch(i){throw(a=this.config)!=null&&a.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")}}async getConversations(e={}){var t,s,a,n,o;if(!this.api)throw new Error("ConversationManager not initialized");try{const r=new URLSearchParams;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");const i=await this.api.get(`/api/chat-users/chats?${r.toString()}`);console.log("📡 Conversations response:",i.data);const l=i.data.data||i.data.conversations||i.data||[];return(t=this.config)!=null&&t.enableLogging&&console.log("📋 ConversationManager: Conversations fetched successfully",{count:l.length}),l}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ ConversationManager: Get conversations failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get conversations")}}async getConversation(e){var t,s,a,n,o;if(!this.api)throw new Error("ConversationManager not initialized");try{const r=await this.api.get(`/api/chat-users/chats/${e}`);return(t=this.config)!=null&&t.enableLogging&&console.log("💬 ConversationManager: Conversation fetched successfully",{conversationId:e}),r.data.conversation||r.data}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ ConversationManager: Get conversation failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get conversation")}}async updateConversation(e,t){var s,a,n,o,r,i;if(!this.api)throw new Error("ConversationManager not initialized");try{const g=(await this.api.put(`/api/conversations/${e}`,t)).data.conversation;return(s=this.config)!=null&&s.enableLogging&&console.log("✏️ ConversationManager: Conversation updated successfully",{conversationId:e}),(a=this.chatSDK.events)==null||a.emit("conversation.updated",{conversation:g}),g}catch(l){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")}}async addParticipants(e,t){var s,a,n,o,r,i;if(!this.api)throw new Error("ConversationManager not initialized");try{const g=(await this.api.post(`/api/conversations/${e}/participants`,{userIds:t})).data.conversation;return(s=this.config)!=null&&s.enableLogging&&console.log("➕ ConversationManager: Participants added successfully",{conversationId:e,addedCount:t.length}),(a=this.chatSDK.events)==null||a.emit("conversation.participants.added",{conversation:g,addedUserIds:t}),g}catch(l){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")}}async removeParticipants(e,t){var s,a,n,o,r,i;if(!this.api)throw new Error("ConversationManager not initialized");try{const g=(await this.api.delete(`/api/conversations/${e}/participants`,{data:{userIds:t}})).data.conversation;return(s=this.config)!=null&&s.enableLogging&&console.log("➖ ConversationManager: Participants removed successfully",{conversationId:e,removedCount:t.length}),(a=this.chatSDK.events)==null||a.emit("conversation.participants.removed",{conversation:g,removedUserIds:t}),g}catch(l){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")}}async leaveConversation(e){var t,s,a,n,o,r;if(!this.api)throw new Error("ConversationManager not initialized");try{await this.api.post(`/api/conversations/${e}/leave`),(t=this.config)!=null&&t.enableLogging&&console.log("🚪 ConversationManager: Left conversation successfully",{conversationId:e}),(s=this.chatSDK.events)==null||s.emit("conversation.left",{conversationId:e})}catch(i){throw(a=this.config)!=null&&a.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")}}async deleteConversation(e){var t,s,a,n,o,r;if(!this.api)throw new Error("ConversationManager not initialized");try{await this.api.delete(`/api/conversations/${e}`),(t=this.config)!=null&&t.enableLogging&&console.log("🗑️ ConversationManager: Conversation deleted successfully",{conversationId:e}),(s=this.chatSDK.events)==null||s.emit("conversation.deleted",{conversationId:e})}catch(i){throw(a=this.config)!=null&&a.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")}}async markAsRead(e){var t,s,a,n,o,r;if(!this.api)throw new Error("ConversationManager not initialized");try{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}),(s=this.chatSDK.events)==null||s.emit("conversation.read",{conversationId:e})}catch(i){throw(a=this.config)!=null&&a.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")}}async getUnreadConversationsCount(){var e,t,s,a,n;if(!this.api)throw new Error("ConversationManager not initialized");try{const r=(await this.api.get("/api/chat-users/unread/conversations-count")).data.data.unreadConversationsCount||0;return(e=this.config)!=null&&e.enableLogging&&console.log("📊 ConversationManager: Unread conversations count fetched",{count:r}),r}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ ConversationManager: Get unread conversations count failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get unread conversations count")}}async getTotalUnreadCount(){var e,t,s,a,n;if(!this.api)throw new Error("ConversationManager not initialized");try{const r=(await this.api.get("/api/chat-users/unread/total-count")).data.data.totalUnreadCount||0;return(e=this.config)!=null&&e.enableLogging&&console.log("📊 ConversationManager: Total unread count fetched",{count:r}),r}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ ConversationManager: Get total unread count failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get total unread count")}}async getUnreadSummary(){var e,t,s,a,n;if(!this.api)throw new Error("ConversationManager not initialized");try{const r=(await this.api.get("/api/chat-users/unread/summary")).data.data;return(e=this.config)!=null&&e.enableLogging&&console.log("📊 ConversationManager: Unread summary fetched",{conversations:r.totalConversationsWithUnread,totalMessages:r.totalUnreadMessages}),r}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ ConversationManager: Get unread summary failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get unread summary")}}async markRoomMessagesRead(e){var t,s,a,n,o,r,i,l,g,u;if(!this.api)throw new Error("ConversationManager not initialized");try{if((t=this.chatSDK.socket)!=null&&t.isConnected())return this.chatSDK.socket.emit("mark_room_read",{roomId:e}),(s=this.config)!=null&&s.enableLogging&&console.log("📡 ConversationManager: mark_room_read sent via socket",{roomId:e}),(a=this.chatSDK.events)==null||a.emit("conversation.read",{conversationId:e,markedCount:0}),0;(n=this.config)!=null&&n.enableLogging&&console.log("📡 ConversationManager: Socket not connected, falling back to API");const p=(await this.api.post(`/api/chat-users/chats/${e}/mark-read`)).data.data.markedAsReadCount||0;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}catch(m){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(((u=(g=m.response)==null?void 0:g.data)==null?void 0:u.message)||"Failed to mark room messages as read")}}async markMessageRead(e){var t,s,a,n,o,r,i,l,g,u;if(!this.api)throw new Error("ConversationManager not initialized");try{if((t=this.chatSDK.socket)!=null&&t.isConnected())return this.chatSDK.socket.emit("mark_message_read",{messageId:e}),(s=this.config)!=null&&s.enableLogging&&console.log("📡 ConversationManager: mark_message_read sent via socket",{messageId:e}),(a=this.chatSDK.events)==null||a.emit("message.read",{messageId:e,wasUnread:!0}),!0;(n=this.config)!=null&&n.enableLogging&&console.log("📡 ConversationManager: Socket not connected, falling back to API for mark-message-read");const p=(await this.api.post(`/api/chat-users/messages/${e}/mark-read`)).data.data.wasUnread||!1;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}catch(m){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(((u=(g=m.response)==null?void 0:g.data)==null?void 0:u.message)||"Failed to mark message as read")}}startViewingConversation(e){var t,s;(t=this.chatSDK.socket)!=null&&t.isConnected()&&(this.chatSDK.socket.emit("viewing_conversation",{roomId:e,isViewing:!0}),(s=this.config)!=null&&s.enableLogging&&console.log("👀 ConversationManager: Started viewing conversation",{conversationId:e}))}stopViewingConversation(e){var t,s;(t=this.chatSDK.socket)!=null&&t.isConnected()&&(this.chatSDK.socket.emit("viewing_conversation",{roomId:e,isViewing:!1}),(s=this.config)!=null&&s.enableLogging&&console.log("👁️ ConversationManager: Stopped viewing conversation",{conversationId:e}))}async blockUserInChat(e,t){var s,a,n,o,r,i;if(!this.api)throw new Error("ConversationManager not initialized");try{const l=await this.api.post(`/api/chat-users/chats/${e}/block-user`,{userId:t});(s=this.config)!=null&&s.enableLogging&&console.log("🚫 ConversationManager: User blocked in chat",{chatId:e,userId:t}),(a=this.chatSDK.events)==null||a.emit("user.blocked",{chatId:e,userId:t})}catch(l){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")}}async unblockUserInChat(e,t){var s,a,n,o,r,i;if(!this.api)throw new Error("ConversationManager not initialized");try{const l=await this.api.post(`/api/chat-users/chats/${e}/unblock-user`,{userId:t});(s=this.config)!=null&&s.enableLogging&&console.log("✅ ConversationManager: User unblocked in chat",{chatId:e,userId:t}),(a=this.chatSDK.events)==null||a.emit("user.unblocked",{chatId:e,userId:t})}catch(l){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")}}async getBlockStatus(e){var t,s,a,n,o;if(!this.api)throw new Error("ConversationManager not initialized");try{const r=await this.api.get(`/api/chat-users/chats/${e}/block-status`);return(t=this.config)!=null&&t.enableLogging&&console.log("📊 ConversationManager: Block status fetched",{chatId:e}),r.data.data}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ ConversationManager: Get block status failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get block status")}}}class Ie{constructor(e){this.api=null,this.config=null,this.chatSDK=e}async init(e){this.config=e,this.api=ie.create({baseURL:e.apiBaseUrl,headers:{"Content-Type":"application/json"},timeout:e.timeout||3e4}),this.api.interceptors.request.use(t=>{const s=localStorage.getItem("chatSDKToken");return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t))}async sendMessage(e,t,s){return this.sendMessageWithOptions({conversationId:e,content:t,type:"text",metadata:s})}async sendMessageWithOptions(e){var t;if(!this.api)throw new Error("MessageManager not initialized");if(this.chatSDK.socket&&this.chatSDK.socket.isConnected())try{return await this.sendMessageViaSocket(e)}catch(s){(t=this.config)!=null&&t.enableLogging&&console.warn("⚠️ Socket send failed, falling back to HTTP:",s)}return this.sendMessageViaHttp(e)}async sendMessageViaSocket(e){return new Promise((t,s)=>{var i,l,g;if(!this.chatSDK.socket||!this.chatSDK.socket.isConnected()){s(new Error("Socket not connected"));return}const a=this.chatSDK.getCurrentUser();if(!a){s(new Error("User not authenticated"));return}const n={conversationId:e.conversationId,content:e.content,messageType:e.type||"text",metadata:e.metadata,senderId:a.id,senderName:a.name,senderEmail:a.email},o=u=>{this.chatSDK.socket.off("message-sent",o),this.chatSDK.socket.off("message-error",r),t(u)},r=u=>{this.chatSDK.socket.off("message-sent",o),this.chatSDK.socket.off("message-error",r),s(new Error(u.message||"Socket send failed"))};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",{conversationId:e.conversationId,content:((l=e.content)==null?void 0:l.substring(0,50))+(((g=e.content)==null?void 0:g.length)>50?"...":""),type:e.type||"text"}),setTimeout(()=>{this.chatSDK.socket.off("message-sent",o),this.chatSDK.socket.off("message-error",r),s(new Error("Socket send timeout"))},1e4)})}async sendMessageViaHttp(e){var t,s,a,n,o,r,i,l;if(!this.api)throw new Error("MessageManager not initialized");try{const g=await this.api.post("/api/chat-users/messages",{roomId:e.conversationId,content:e.content,messageType:e.type||"text",metadata:e.metadata,replyToMessageId:e.replyToMessageId}),u=g.data.data||g.data.message||g.data;return(t=this.config)!=null&&t.enableLogging&&console.log("📡 Message sent via HTTP:",{id:u.id,content:((s=u.content)==null?void 0:s.substring(0,50))+(((a=u.content)==null?void 0:a.length)>50?"...":""),type:u.type||"text"}),(n=this.chatSDK.events)==null||n.emit("message.sent",{message:u}),u}catch(g){throw(o=this.config)!=null&&o.enableLogging&&console.error("❌ MessageManager: HTTP send failed",((r=g.response)==null?void 0:r.data)||g.message),new Error(((l=(i=g.response)==null?void 0:i.data)==null?void 0:l.message)||"Failed to send message")}}async getMessages(e){var t,s,a,n,o;if(!this.api)throw new Error("MessageManager not initialized");try{const r=new URLSearchParams;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);const i=await this.api.get(`/api/chat-users/messages/${e.conversationId}?${r.toString()}`);console.log("📡 Get messages response:",i.data),console.log("📡 Raw server messages:",JSON.stringify(i.data,null,2));const l=i.data.data||i.data.messages||i.data||[];(t=this.config)!=null&&t.enableLogging&&console.log("📥 MessageManager: Messages fetched successfully",{conversationId:e.conversationId,count:l.length});const g=l.map(u=>({...u,type:u.messageType||u.type||"text",conversationId:u.roomId||u.conversationId,timestamp:u.createdAt||u.timestamp||new Date().toISOString()}));return console.log("📥 Final processed messages:",g),g}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ MessageManager: Get messages failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get messages")}}async getMessage(e){var t,s,a,n,o;if(!this.api)throw new Error("MessageManager not initialized");try{const r=await this.api.get(`/api/messages/${e}`);return(t=this.config)!=null&&t.enableLogging&&console.log("📄 MessageManager: Message fetched successfully",{messageId:e}),r.data.message}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ MessageManager: Get message failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get message")}}async updateMessage(e,t,s){var a,n,o,r,i,l;if(!this.api)throw new Error("MessageManager not initialized");try{const u=(await this.api.put(`/api/messages/${e}`,{content:t,metadata:s})).data.message;return(a=this.config)!=null&&a.enableLogging&&console.log("✏️ MessageManager: Message updated successfully",{messageId:e}),(n=this.chatSDK.events)==null||n.emit("message.updated",{message:u}),u}catch(g){throw(o=this.config)!=null&&o.enableLogging&&console.error("❌ MessageManager: Update message failed",((r=g.response)==null?void 0:r.data)||g.message),new Error(((l=(i=g.response)==null?void 0:i.data)==null?void 0:l.message)||"Failed to update message")}}async deleteMessage(e,t=!1){var s,a,n,o,r,i;if(!this.api)throw new Error("MessageManager not initialized");try{await this.api.delete(`/api/messages/${e}`,{data:{deleteForEveryone:t}}),(s=this.config)!=null&&s.enableLogging&&console.log("🗑️ MessageManager: Message deleted successfully",{messageId:e,deleteForEveryone:t}),(a=this.chatSDK.events)==null||a.emit("message.deleted",{messageId:e,deleteForEveryone:t})}catch(l){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")}}async markAsRead(e,t){var s,a,n,o,r,i;if(!this.api)throw new Error("MessageManager not initialized");try{await this.api.put(`/api/conversations/${e}/messages/read`,{messageIds:t}),(s=this.config)!=null&&s.enableLogging&&console.log("👁️ MessageManager: Messages marked as read",{conversationId:e,messageCount:(t==null?void 0:t.length)||"all"}),(a=this.chatSDK.events)==null||a.emit("messages.read",{conversationId:e,messageIds:t})}catch(l){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")}}async searchMessages(e){var t,s,a,n,o;if(!this.api)throw new Error("MessageManager not initialized");try{const r=new URLSearchParams;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);const l=(await this.api.get(`/api/messages/search?${r.toString()}`)).data.messages||[];return(t=this.config)!=null&&t.enableLogging&&console.log("🔍 MessageManager: Messages searched successfully",{query:e.query,count:l.length}),l}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ MessageManager: Search messages failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to search messages")}}async sendTypingIndicator(e,t){var s,a,n,o;if(!this.api)throw new Error("MessageManager not initialized");try{await this.api.post(`/api/conversations/${e}/typing`,{isTyping:t}),(s=this.config)!=null&&s.enableLogging&&t&&console.log("⌨️ MessageManager: Typing indicator sent",{conversationId:e}),(a=this.chatSDK.events)==null||a.emit("typing.indicator",{conversationId:e,isTyping:t})}catch(r){(n=this.config)!=null&&n.enableLogging&&console.error("❌ MessageManager: Send typing indicator failed",((o=r.response)==null?void 0:o.data)||r.message)}}async reactToMessage(e,t){var s,a,n,o,r,i;if(!this.api)throw new Error("MessageManager not initialized");try{await this.api.post(`/api/messages/${e}/reactions`,{reaction:t}),(s=this.config)!=null&&s.enableLogging&&console.log("😊 MessageManager: Message reaction sent",{messageId:e,reaction:t}),(a=this.chatSDK.events)==null||a.emit("message.reaction",{messageId:e,reaction:t})}catch(l){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")}}async removeReaction(e,t){var s,a,n,o,r,i;if(!this.api)throw new Error("MessageManager not initialized");try{await this.api.delete(`/api/messages/${e}/reactions/${t}`),(s=this.config)!=null&&s.enableLogging&&console.log("🗑️ MessageManager: Message reaction removed",{messageId:e,reaction:t}),(a=this.chatSDK.events)==null||a.emit("message.reaction.removed",{messageId:e,reaction:t})}catch(l){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")}}}class je{constructor(e){this.api=null,this.config=null,this.maxFileSize=50*1024*1024,this.allowedTypes=["image/jpeg","image/png","image/gif","image/webp","video/mp4","video/webm","video/quicktime","audio/mpeg","audio/wav","audio/ogg","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain"],this.chatSDK=e}async init(e){this.config=e,this.api=ie.create({baseURL:e.apiBaseUrl,headers:{"Content-Type":"application/json"},timeout:e.timeout||3e4}),this.api.interceptors.request.use(t=>{const s=localStorage.getItem("chatSDKToken");return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t))}async uploadMedia(e){var t,s,a,n,o,r;if(!this.api)throw new Error("MediaManager not initialized");this.validateFile(e.file);try{const i=new FormData;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));const g=(await this.api.post("/api/chat-users/upload",i,{headers:{"Content-Type":"multipart/form-data"},onUploadProgress:u=>{if(e.onProgress&&u.total){const m=Math.round(u.loaded*100/u.total);e.onProgress(m)}},timeout:300*1e3})).data.data;return(t=this.config)!=null&&t.enableLogging&&console.log("📎 MediaManager: File uploaded successfully",{url:g.fileUrl,fileName:g.fileName,fileSize:g.fileSize,mimeType:g.mimeType,type:e.type}),(s=this.chatSDK.events)==null||s.emit("media.uploaded",{media:g}),g}catch(i){throw(a=this.config)!=null&&a.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")}}async sendImage(e,t,s){return this.uploadMedia({file:t,type:"image",conversationId:e,caption:s})}async sendVideo(e,t,s){return this.uploadMedia({file:t,type:"video",conversationId:e,caption:s})}async sendAudio(e,t,s){return this.uploadMedia({file:t,type:"audio",conversationId:e,caption:s})}async sendDocument(e,t,s){return this.uploadMedia({file:t,type:"document",conversationId:e,caption:s})}async getMedia(e){var t,s,a,n,o;if(!this.api)throw new Error("MediaManager not initialized");try{const r=await this.api.get(`/api/media/${e}`);return(t=this.config)!=null&&t.enableLogging&&console.log("📄 MediaManager: Media info fetched successfully",{mediaId:e}),r.data.media}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ MediaManager: Get media failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get media")}}async getDownloadUrl(e){var t,s,a,n,o;if(!this.api)throw new Error("MediaManager not initialized");try{const r=new URLSearchParams;e.quality&&r.append("quality",e.quality);const l=(await this.api.get(`/api/media/${e.mediaId}/download?${r.toString()}`)).data.url;return(t=this.config)!=null&&t.enableLogging&&console.log("🔗 MediaManager: Download URL generated",{mediaId:e.mediaId,quality:e.quality}),l}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ MediaManager: Get download URL failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get download URL")}}async deleteMedia(e){var t,s,a,n,o,r;if(!this.api)throw new Error("MediaManager not initialized");try{await this.api.delete(`/api/media/${e}`),(t=this.config)!=null&&t.enableLogging&&console.log("🗑️ MediaManager: Media deleted successfully",{mediaId:e}),(s=this.chatSDK.events)==null||s.emit("media.deleted",{mediaId:e})}catch(i){throw(a=this.config)!=null&&a.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")}}async generateThumbnail(e,t="medium"){var s,a,n,o,r;if(!this.api)throw new Error("MediaManager not initialized");try{const l=(await this.api.post(`/api/media/${e}/thumbnail`,{size:t})).data.thumbnailUrl;return(s=this.config)!=null&&s.enableLogging&&console.log("🖼️ MediaManager: Thumbnail generated",{mediaId:e,size:t}),l}catch(i){throw(a=this.config)!=null&&a.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")}}setMaxFileSize(e){var t;this.maxFileSize=e,(t=this.config)!=null&&t.enableLogging&&console.log("📏 MediaManager: Max file size updated",{sizeInMB:Math.round(e/(1024*1024))})}setAllowedTypes(e){var t;this.allowedTypes=e,(t=this.config)!=null&&t.enableLogging&&console.log("📋 MediaManager: Allowed types updated",{types:e})}validateFile(e){if(e.size>this.maxFileSize)throw new Error(`File size exceeds maximum allowed size of ${Math.round(this.maxFileSize/(1024*1024))}MB`);if(!this.allowedTypes.includes(e.type))throw new Error(`File type ${e.type} is not allowed`);if(!e.name||e.name.trim().length===0)throw new Error("File must have a valid name")}isTypeSupported(e){return this.allowedTypes.includes(e)}getFileTypeCategory(e){return e.startsWith("image/")?"image":e.startsWith("video/")?"video":e.startsWith("audio/")?"audio":"document"}formatFileSize(e){if(e===0)return"0 Bytes";const t=1024,s=["Bytes","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,a)).toFixed(2))+" "+s[a]}}class Ae{constructor(e){this.config=null,this.socket=null,this.eventListeners=new Map,this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectDelay=1e3,this.heartbeatInterval=null,this.connectionTimeout=null,this.chatSDK=e}async init(e){var t;this.config=e,(t=this.config)!=null&&t.enableLogging&&console.log("📡 EventManager: Initialized")}async connect(){var e;if(!this.config)throw new Error("EventManager not initialized");return(e=this.config)!=null&&e.enableLogging&&console.log("📡 EventManager: Skipping native WebSocket connection (using Socket.io instead)"),this.isConnected=!0,Promise.resolve()}async disconnect(){var e;return(e=this.config)!=null&&e.enableLogging&&console.log("📡 EventManager: Skipping native WebSocket disconnection (using Socket.io instead)"),this.isConnected=!1,Promise.resolve()}on(e,t){var s;this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),(s=this.config)!=null&&s.enableLogging&&console.log("👂 EventManager: Event listener added",{event:e})}off(e,t){var a;if(!t){this.eventListeners.delete(e);return}const s=this.eventListeners.get(e);if(s){const n=s.indexOf(t);n>-1&&s.splice(n,1),s.length===0&&this.eventListeners.delete(e)}(a=this.config)!=null&&a.enableLogging&&console.log("🔇 EventManager: Event listener removed",{event:e})}emit(e,t){var a;const s=this.eventListeners.get(e);s&&s.forEach(n=>{var o;try{n(t)}catch(r){(o=this.config)!=null&&o.enableLogging&&console.error("❌ EventManager: Error in event callback",{event:e,error:r})}}),(a=this.config)!=null&&a.enableLogging&&console.log("📢 EventManager: Event emitted",{event:e,data:t})}send(e,t){var a,n,o;if(!this.isConnected||!this.socket){(a=this.config)!=null&&a.enableLogging&&console.warn("⚠️ EventManager: Cannot send message - not connected");return}const s={type:e,data:t,timestamp:Date.now()};try{this.socket.send(JSON.stringify(s)),(n=this.config)!=null&&n.enableLogging&&console.log("📤 EventManager: Message sent",{type:e,data:t})}catch(r){(o=this.config)!=null&&o.enableLogging&&console.error("❌ EventManager: Failed to send message",{type:e,error:r})}}isSocketConnected(){var e;return this.isConnected&&((e=this.socket)==null?void 0:e.readyState)===WebSocket.OPEN}getConnectionStatus(){if(!this.socket)return"disconnected";switch(this.socket.readyState){case WebSocket.CONNECTING:return"connecting";case WebSocket.OPEN:return"connected";case WebSocket.CLOSING:case WebSocket.CLOSED:return"disconnected";default:return"error"}}handleOpen(e){var t;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()})}handleMessage(e){var t,s;try{const a=JSON.parse(e.data);if((t=this.config)!=null&&t.enableLogging&&console.log("📥 EventManager: Message received",a),a.type==="heartbeat"){this.send("heartbeat",{timestamp:Date.now()});return}this.emit(a.type,a.data),this.emit("message.received",a)}catch(a){(s=this.config)!=null&&s.enableLogging&&console.error("❌ EventManager: Failed to parse message",{data:e.data,error:a})}}handleClose(e){var t;this.isConnected=!1,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),(t=this.config)!=null&&t.enableLogging&&console.log("🔌 EventManager: WebSocket closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}),this.emit("connection.close",{code:e.code,reason:e.reason,timestamp:Date.now()}),!e.wasClean&&this.reconnectAttempts<this.maxReconnectAttempts&&this.attemptReconnect()}handleError(e){var t;(t=this.config)!=null&&t.enableLogging&&console.error("❌ EventManager: WebSocket error",e),this.emit("connection.error",{error:e,timestamp:Date.now()})}startHeartbeat(){this.heartbeatInterval&&clearInterval(this.heartbeatInterval),this.heartbeatInterval=setInterval(()=>{this.isConnected&&this.send("ping",{timestamp:Date.now()})},3e4)}attemptReconnect(){var e,t;if(this.reconnectAttempts>=this.maxReconnectAttempts){(e=this.config)!=null&&e.enableLogging&&console.error("❌ EventManager: Max reconnection attempts reached"),this.emit("connection.failed",{attempts:this.reconnectAttempts,timestamp:Date.now()});return}this.reconnectAttempts++,(t=this.config)!=null&&t.enableLogging&&console.log(`🔄 EventManager: Attempting reconnection ${this.reconnectAttempts}/${this.maxReconnectAttempts}`),setTimeout(()=>{this.connect().catch(s=>{var a;(a=this.config)!=null&&a.enableLogging&&console.error("❌ EventManager: Reconnection failed",s),this.attemptReconnect()})},this.reconnectDelay),this.reconnectDelay=Math.min(this.reconnectDelay*2,3e4)}setMaxReconnectAttempts(e){this.maxReconnectAttempts=e}clearAllListeners(){var e;this.eventListeners.clear(),(e=this.config)!=null&&e.enableLogging&&console.log("🧹 EventManager: All event listeners cleared")}getActiveListeners(){return Array.from(this.eventListeners.keys())}}class fe{static parseUser(e){if(!e)throw new Error("User data is required");return{id:e.id,externalUserId:e.externalUserId,appId:e.appId,name:e.name,username:e.username,displayName:e.displayName,email:e.email,avatar:e.avatar,avatarUrl:e.avatarUrl,status:e.status||"offline",isOnline:e.isOnline||!1,isRegistered:e.isRegistered||!0,lastSeen:e.lastSeen,createdAt:e.createdAt,updatedAt:e.updatedAt,metadata:e.metadata||{},...e}}static parseMessage(e){var a,n,o;if(!e)throw new Error("Message data is required");let t=e.type||"text";if(t==="text"&&((a=e.metadata)!=null&&a.fileUrl)&&((n=e.metadata)!=null&&n.mimeType)){const r=e.metadata.mimeType;r.startsWith("image/")?t="image":r.startsWith("video/")?t="video":r.startsWith("audio/")?t="audio":t="file"}const s={id:e.id,content:e.content,senderId:e.senderId,roomId:e.roomId||e.conversationId,conversationId:e.conversationId||e.roomId,senderName:e.senderName,senderEmail:e.senderEmail,senderAvatar:e.senderAvatar,senderExternalUserId:e.senderExternalUserId,messageType:t,type:t,status:e.status||"sent",isRead:e.isRead||!1,isDelivered:e.isDelivered||!1,timestamp:e.timestamp,createdAt:e.createdAt,updatedAt:e.updatedAt,metadata:e.metadata||{}};return console.log("✅ ParseUtils: Parsed message:",{id:s.id,type:s.type,messageType:s.messageType,roomId:s.roomId,hasMetadata:!!s.metadata,metadataKeys:Object.keys(s.metadata||{}),fileUrl:(o=s.metadata)==null?void 0:o.fileUrl}),s}static parseConversation(e){if(!e)throw new Error("Conversation data is required");return{id:e.id,conversationId:e.conversationId||e.id,name:e.name,description:e.description,type:e.type||"direct",avatar:e.avatar,participants:Array.isArray(e.participants)?e.participants.map(t=>this.parseUser(t)):[],lastMessage:e.lastMessage?this.parseMessage(e.lastMessage):null,productContext:e.productContext?this.parseProductContext(e.productContext):void 0,metadata:e.metadata||{},createdAt:e.createdAt,updatedAt:e.updatedAt,...e}}static parseProductContext(e){if(e)return{productId:e.productId,productName:e.productName,productImage:e.productImage,price:e.price,currency:e.currency,category:e.category,productMetadata:e.productMetadata||{},...e}}static parseMessages(e){return Array.isArray(e)?e:[]}static parseConversations(e){return Array.isArray(e)?e:[]}static parseUsers(e){return Array.isArray(e)?e:[]}}class Te{constructor(e){this.socket=null,this.config=null,this.currentUserId=null,this.joinedRooms=new Set,this.chatSDK=e}async init(e){var t,s,a,n;this.config=e,(t=this.config)!=null&&t.enableLogging&&console.log("🔌 SocketManager: Starting initialization...",{apiBaseUrl:e.apiBaseUrl,enableLogging:e.enableLogging});try{let o=e.wsUrl;!o&&e.apiBaseUrl&&(o=e.apiBaseUrl.replace(/\/api\/?$/,"")),o||(o=e.environment==="production"?"https://chatsdk-mzad-admin.onrender.com":"http://localhost:5001"),(s=this.config)!=null&&s.enableLogging&&console.log("🔌 SocketManager: Creating socket connection to:",o,{wsUrl:e.wsUrl,apiBaseUrl:e.apiBaseUrl,environment:e.environment}),this.socket=tt.io(o,{transports:["websocket","polling"],autoConnect:!1,forceNew:!0,timeout:45e3,reconnection:!0,reconnectionAttempts:10,reconnectionDelay:2e3,reconnectionDelayMax:1e4,upgrade:!0,rememberUpgrade:!1}),this.setupEventListeners(),(a=this.config)!=null&&a.enableLogging&&console.log("✅ SocketManager: Initialized successfully with socket:",!!this.socket)}catch(o){throw(n=this.config)!=null&&n.enableLogging&&console.error("❌ SocketManager: Initialization failed",o),o}}async connect(e){var s,a,n,o,r,i,l;if(!this.socket)throw new Error("SocketManager not initialized");this.currentUserId=e;let t=(s=this.config)==null?void 0:s.wsUrl;return!t&&((a=this.config)!=null&&a.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...",{userId:e,socketUrl:t,wsUrl:(r=this.config)==null?void 0:r.wsUrl,apiBaseUrl:(i=this.config)==null?void 0:i.apiBaseUrl,environment:(l=this.config)==null?void 0:l.environment,hasSocket:!!this.socket}),new Promise((g,u)=>{const m=setTimeout(()=>{var p;(p=this.config)!=null&&p.enableLogging&&console.error("❌ SocketManager: Connection timeout after 10 seconds"),u(new Error("Connection timeout"))},1e4);this.socket.connect(),this.socket.on("connect",()=>{var p,x,B;clearTimeout(m),(p=this.config)!=null&&p.enableLogging&&console.log("✅ SocketManager: Connected to WebSocket server successfully!"),this.socket.emit("authenticate",{userId:e,appId:(x=this.config)==null?void 0:x.appId}),(B=this.config)!=null&&B.enableLogging&&console.log("🔐 SocketManager: Sent authentication for user:",e),g()}),this.socket.on("connect_error",p=>{var x;clearTimeout(m),(x=this.config)!=null&&x.enableLogging&&console.error("❌ SocketManager: Connection failed with error:",p),u(p)}),this.socket.on("disconnect",p=>{var x;(x=this.config)!=null&&x.enableLogging&&console.log("🔌 SocketManager: Disconnected from server, reason:",p)})})}disconnect(){var e;this.socket&&(this.socket.disconnect(),this.joinedRooms.clear(),(e=this.config)!=null&&e.enableLogging&&console.log("�� SocketManager: Disconnected from WebSocket server"))}joinConversation(e){var t,s,a;if(!this.socket||!this.socket.connected){(t=this.config)!=null&&t.enableLogging&&console.warn("SocketManager: Cannot join conversation - not connected");return}this.joinedRooms.has(e)||(this.socket.emit("join_conversation",{conversationId:e,appId:(s=this.config)==null?void 0:s.appId}),this.joinedRooms.add(e),(a=this.config)!=null&&a.enableLogging&&console.log(`🏠 SocketManager: Joined conversation ${e}`))}leaveConversation(e){var t;!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}`))}sendTypingIndicator(e,t){var s,a;if(!this.socket||!this.socket.connected){(s=this.config)!=null&&s.enableLogging&&console.warn("SocketManager: Cannot send typing indicator - not connected");return}this.socket.emit("typing_indicator",{conversationId:e,isTyping:t,userId:this.currentUserId}),(a=this.config)!=null&&a.enableLogging&&console.log(`⌨️ SocketManager: Typing indicator sent: ${t} for conversation ${e}`)}sendMessage(e){var s,a;if(!this.socket||!this.socket.connected){(s=this.config)!=null&&s.enableLogging&&console.warn("SocketManager: Cannot send message - not connected");return}const t={...e,timestamp:new Date().toISOString(),senderId:this.currentUserId||e.senderId};this.socket.emit("send-message",t),(a=this.config)!=null&&a.enableLogging&&console.log("📤 SocketManager: Message sent via WebSocket",t)}setupEventListeners(){this.socket&&(this.socket.on("message_received",e=>{var t,s,a;try{const n=fe.parseMessage(e);(t=this.chatSDK.events)==null||t.emit("message.received",{message:n})}catch(n){(s=this.config)!=null&&s.enableLogging&&console.error("❌ SocketManager: Failed to parse received message",n),(a=this.chatSDK.events)==null||a.emit("message.received",{message:e})}}),this.socket.on("typing_indicator",e=>{var t,s,a,n;try{const o={userId:e.userId||e.user_id,conversationId:e.conversationId||e.conversation_id||e.room_id,isTyping:e.isTyping||e.is_typing,timestamp:e.timestamp||e.created_at};(t=this.config)!=null&&t.enableLogging&&console.log("⌨️ SocketManager: Typing indicator received",o),(s=this.chatSDK.events)==null||s.emit("typing.indicator",o)}catch(o){(a=this.config)!=null&&a.enableLogging&&console.error("❌ SocketManager: Failed to process typing indicator",o),(n=this.chatSDK.events)==null||n.emit("typing.indicator",e)}}),this.socket.on("user_status_changed",e=>{var t,s,a,n;try{const o={userId:e.userId||e.user_id,status:e.status,timestamp:e.timestamp||e.updated_at||e.last_seen};(t=this.config)!=null&&t.enableLogging&&console.log("👤 SocketManager: User status update",o),(s=this.chatSDK.events)==null||s.emit("user.status.changed",o)}catch(o){(a=this.config)!=null&&a.enableLogging&&console.error("❌ SocketManager: Failed to process user status update",o),(n=this.chatSDK.events)==null||n.emit("user.status.changed",e)}}),this.socket.on("conversation_updated",e=>{var t,s,a,n;try{const o={conversationId:e.conversationId||e.conversation_id||e.room_id,lastMessage:e.lastMessage||e.last_message,unreadCount:e.unreadCount||e.unread_count,timestamp:e.timestamp||e.updated_at};(t=this.config)!=null&&t.enableLogging&&console.log("💬 SocketManager: Conversation update",o),(s=this.chatSDK.events)==null||s.emit("conversation.updated",o)}catch(o){(a=this.config)!=null&&a.enableLogging&&console.error("❌ SocketManager: Failed to process conversation update",o),(n=this.chatSDK.events)==null||n.emit("conversation.updated",e)}}),this.socket.on("user-joined-room",e=>{var t,s;(t=this.config)!=null&&t.enableLogging&&console.log("🏠 SocketManager: User joined room",e),(s=this.chatSDK.events)==null||s.emit("room.user.joined",e)}),this.socket.on("user-left-room",e=>{var t,s;(t=this.config)!=null&&t.enableLogging&&console.log("🚪 SocketManager: User left room",e),(s=this.chatSDK.events)==null||s.emit("room.user.left",e)}),this.socket.on("online-users",e=>{var t,s,a,n;try{const o=fe.parseUsers(e);(t=this.config)!=null&&t.enableLogging&&console.log("🌐 SocketManager: Online users update",{count:o.length}),(s=this.chatSDK.events)==null||s.emit("users.online",{users:o})}catch(o){(a=this.config)!=null&&a.enableLogging&&console.error("❌ SocketManager: Failed to parse online users",o),(n=this.chatSDK.events)==null||n.emit("users.online",{users:e})}}),this.socket.on("conversation_block_status",e=>{var t,s;(t=this.config)!=null&&t.enableLogging&&console.log("🚫 SocketManager: Conversation block status update",e),(s=this.chatSDK.events)==null||s.emit("conversation.block_status",e)}),this.socket.on("message_read_receipt",e=>{var t,s,a,n;try{(t=this.config)!=null&&t.enableLogging&&console.log("✅ SocketManager: Message read receipt received",e),(s=this.chatSDK.events)==null||s.emit("message.read.receipt",e)}catch(o){(a=this.config)!=null&&a.enableLogging&&console.error("❌ SocketManager: Failed to process read receipt",o),(n=this.chatSDK.events)==null||n.emit("message.read.receipt",e)}}),this.socket.on("messages_read_receipt",e=>{var t,s,a,n,o,r,i,l;try{(t=this.config)!=null&&t.enableLogging&&console.log("📥 SocketManager: messages_read_receipt received from server",{roomId:e.roomId,messageIds:e.messageIds,messageCount:(s=e.messageIds)==null?void 0:s.length,readBy:e.readBy,isRead:e.isRead}),(a=this.config)!=null&&a.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")}catch(g){(i=this.config)!=null&&i.enableLogging&&console.error("❌ SocketManager: Failed to process read receipts",g),(l=this.chatSDK.events)==null||l.emit("messages.read.receipt",e)}}))}isConnected(){var e;return((e=this.socket)==null?void 0:e.connected)||!1}getStatus(){return{connected:this.isConnected(),userId:this.currentUserId,rooms:Array.from(this.joinedRooms)}}joinRoom(e){this.joinConversation(e)}leaveRoom(e){this.leaveConversation(e)}emit(e,t){var s,a;this.socket&&this.socket.connected?(this.socket.emit(e,t),(s=this.config)!=null&&s.enableLogging&&console.log("📤 SocketManager: Emitted event:",e,t)):(a=this.config)!=null&&a.enableLogging&&console.warn("⚠️ SocketManager: Cannot emit event - not connected:",e)}on(e,t){var s,a;this.socket?(this.socket.on(e,t),(s=this.config)!=null&&s.enableLogging&&console.log("👂 SocketManager: Listening to event:",e)):(a=this.config)!=null&&a.enableLogging&&console.warn("⚠️ SocketManager: Cannot listen to event - socket not available:",e)}off(e,t){var s;this.socket&&(this.socket.off(e,t),(s=this.config)!=null&&s.enableLogging&&console.log("🔇 SocketManager: Stopped listening to event:",e))}}const re=class re{constructor(){this.config=null,this.isInitialized=!1,this.currentUser=null,this.auth=new De(this),this.chatUsers=new at(this),this.users=new Ue(this),this.conversations=new Fe(this),this.messages=new Ie(this),this.media=new je(this),this.events=new Ae(this),this.socket=new Te(this)}static getInstance(){return re.instance||(re.instance=new re),re.instance}async init(e){try{this.config={enableLogging:!0,autoConnect:!0,timeout:3e4,...e},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()}catch(t){throw console.error("❌ ChatSDK: Initialization failed",t),new Error(`ChatSDK initialization failed: ${t}`)}}async connect(e){var t,s;this.ensureInitialized();try{let a;e?(console.log("🔌 ChatSDK: Using provided userId for connection:",e),a={id:e,externalUserId:e,appId:process.env.REACT_APP_APP_ID||"",name:"Chat User",email:`${e}@example.com`,status:"online",isOnline:!0,isRegistered:!0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},this.currentUser=a):(a=await this.auth.getCurrentUser(),this.currentUser=a),await this.events.connect();try{console.log("🔌 ChatSDK: Attempting WebSocket connection for user:",a.id),await this.socket.connect(a.id),console.log("✅ ChatSDK: WebSocket connected successfully")}catch(n){console.warn("⚠️ ChatSDK: WebSocket connection failed, continuing without real-time features:",n)}return(t=this.config)!=null&&t.enableLogging&&console.log("🔗 ChatSDK: Connected successfully",a),a}catch(a){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ ChatSDK: Connection failed",a),await this.auth.logout(),this.currentUser=null,a}}async disconnect(){var e;try{await this.events.disconnect(),this.socket.disconnect(),this.currentUser=null,(e=this.config)!=null&&e.enableLogging&&console.log("🔌 ChatSDK: Disconnected")}catch(t){throw console.error("❌ ChatSDK: Disconnect failed",t),t}}async login(e,t){return this.ensureInitialized(),await this.auth.login(e,t)}async register(e,t,s,a){return this.ensureInitialized(),await this.auth.register(e,t,s,a)}async logout(){this.ensureInitialized(),await this.auth.logout(),await this.disconnect()}getCurrentUser(){return this.currentUser}isSDKInitialized(){return this.isInitialized}getConfig(){return this.config}setLogging(e){this.config&&(this.config.enableLogging=e)}getVersion(){return"1.0.0"}ensureInitialized(){if(!this.isInitialized)throw new Error("ChatSDK not initialized. Call ChatSDK.init() first.")}};re.instance=null;let T=re;T.getInstance();const nt=Object.freeze(Object.defineProperty({__proto__:null,ChatSDK:T},Symbol.toStringTag,{value:"Module"}));let rt={data:""},ot=c=>typeof window=="object"?((c?c.querySelector("#_goober"):window._goober)||Object.assign((c||document.head).appendChild(document.createElement("style")),{innerHTML:" ",id:"_goober"})).firstChild:c||rt,it=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,ct=/\/\*[^]*?\*\/| +/g,xe=/\n+/g,te=(c,e)=>{let t="",s="",a="";for(let n in c){let o=c[n];n[0]=="@"?n[1]=="i"?t=n+" "+o+";":s+=n[1]=="f"?te(o,n):n+"{"+te(o,n[1]=="k"?"":e)+"}":typeof o=="object"?s+=te(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(),a+=te.p?te.p(n,o):n+":"+o+";")}return t+(e&&a?e+"{"+a+"}":a)+s},Q={},Ne=c=>{if(typeof c=="object"){let e="";for(let t in c)e+=t+Ne(c[t]);return e}return c},lt=(c,e,t,s,a)=>{let n=Ne(c),o=Q[n]||(Q[n]=(i=>{let l=0,g=11;for(;l<i.length;)g=101*g+i.charCodeAt(l++)>>>0;return"go"+g})(n));if(!Q[o]){let i=n!==c?c:(l=>{let g,u,m=[{}];for(;g=it.exec(l.replace(ct,""));)g[4]?m.shift():g[3]?(u=g[3].replace(xe," ").trim(),m.unshift(m[0][u]=m[0][u]||{})):m[0][g[1]]=g[2].replace(xe," ").trim();return m[0]})(c);Q[o]=te(a?{["@keyframes "+o]:i}:i,t?"":"."+o)}let r=t&&Q.g?Q.g:null;return t&&(Q.g=Q[o]),((i,l,g,u)=>{u?l.data=l.data.replace(u,i):l.data.indexOf(i)===-1&&(l.data=g?i+l.data:l.data+i)})(Q[o],e,s,r),o},dt=(c,e,t)=>c.reduce((s,a,n)=>{let o=e[n];if(o&&o.call){let r=o(t),i=r&&r.props&&r.props.className||/^go/.test(r)&&r;o=i?"."+i:r&&typeof r=="object"?r.props?"":te(r,""):r===!1?"":r}return s+a+(o??"")},"");function ge(c){let e=this||{},t=c.call?c(e.p):c;return lt(t.unshift?t.raw?dt(t,[].slice.call(arguments,1),e.p):t.reduce((s,a)=>Object.assign(s,a&&a.call?a(e.p):a),{}):t,ot(e.target),e.g,e.o,e.k)}let Ke,pe,we;ge.bind({g:1});let Z=ge.bind({k:1});function gt(c,e,t,s){te.p=e,Ke=c,pe=t,we=s}function se(c,e){let t=this||{};return function(){let s=arguments;function a(n,o){let r=Object.assign({},n),i=r.className||a.className;t.p=Object.assign({theme:pe&&pe()},r),t.o=/ *go\d+/.test(i),r.className=ge.apply(t,s)+(i?" "+i:"");let l=c;return c[0]&&(l=r.as||c,delete r.as),we&&l[0]&&we(r),Ke(l,r)}return a}}var ht=c=>typeof c=="function",ke=(c,e)=>ht(c)?c(e):c,ut=(()=>{let c=0;return()=>(++c).toString()})(),mt=(()=>{let c;return()=>{if(c===void 0&&typeof window<"u"){let e=matchMedia("(prefers-reduced-motion: reduce)");c=!e||e.matches}return c}})(),ft=20,ze=(c,e)=>{switch(e.type){case 0:return{...c,toasts:[e.toast,...c.toasts].slice(0,ft)};case 1:return{...c,toasts:c.toasts.map(n=>n.id===e.toast.id?{...n,...e.toast}:n)};case 2:let{toast:t}=e;return ze(c,{type:c.toasts.find(n=>n.id===t.id)?1:0,toast:t});case 3:let{toastId:s}=e;return{...c,toasts:c.toasts.map(n=>n.id===s||s===void 0?{...n,dismissed:!0,visible:!1}:n)};case 4:return e.toastId===void 0?{...c,toasts:[]}:{...c,toasts:c.toasts.filter(n=>n.id!==e.toastId)};case 5:return{...c,pausedAt:e.time};case 6:let a=e.time-(c.pausedAt||0);return{...c,pausedAt:void 0,toasts:c.toasts.map(n=>({...n,pauseDuration:n.pauseDuration+a}))}}},pt=[],me={toasts:[],pausedAt:void 0},be=c=>{me=ze(me,c),pt.forEach(e=>{e(me)})},wt=(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)||ut()}),de=c=>(e,t)=>{let s=wt(e,c,t);return be({type:2,toast:s}),s.id},q=(c,e)=>de("blank")(c,e);q.error=de("error");q.success=de("success");q.loading=de("loading");q.custom=de("custom");q.dismiss=c=>{be({type:3,toastId:c})};q.remove=c=>be({type:4,toastId:c});q.promise=(c,e,t)=>{let s=q.loading(e.loading,{...t,...t==null?void 0:t.loading});return typeof c=="function"&&(c=c()),c.then(a=>{let n=e.success?ke(e.success,a):void 0;return n?q.success(n,{id:s,...t,...t==null?void 0:t.success}):q.dismiss(s),a}).catch(a=>{let n=e.error?ke(e.error,a):void 0;n?q.error(n,{id:s,...t,...t==null?void 0:t.error}):q.dismiss(s)}),c};var kt=Z`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ce=require("axios"),rt=require("socket.io-client"),d=require("react/jsx-runtime"),v=require("react");function ot(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const W=ot(v);class Ie{constructor(e){this.api=null,this.config=null,this.chatSDK=e}async init(e){this.config=e,this.api=ce.create({baseURL:e.apiBaseUrl,headers:{"Content-Type":"application/json"},timeout:e.timeout||3e4}),this.api.interceptors.request.use(t=>{const s=this.getToken();return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t)),this.api.interceptors.response.use(t=>t,t=>{var s,a,n;if(((s=t.response)==null?void 0:s.status)===401){const r=(((a=t.config)==null?void 0:a.url)||"").includes("/api/auth/me");this.clearToken(),r||(n=this.chatSDK.events)==null||n.emit("auth.logout",{reason:"unauthorized"})}return Promise.reject(t)})}async authenticate(e,t,s,a){var n,o,r,c,l,g;if(!this.api)throw new Error("AuthManager not initialized");try{const u=await this.api.post("/api/chat-users/authenticate",{externalUserId:e,appId:t,name:s,email:a}),m=this.parseAuthResponse(u.data);return(n=this.config)!=null&&n.enableLogging&&console.log("🔐 AuthManager: Authentication successful",{userId:m.id,externalUserId:m.externalUserId,name:m.name}),(o=this.chatSDK.events)==null||o.emit("auth.login",{user:m}),m}catch(u){throw(r=this.config)!=null&&r.enableLogging&&console.error("❌ AuthManager: Authentication failed",((c=u.response)==null?void 0:c.data)||u.message),new Error(((g=(l=u.response)==null?void 0:l.data)==null?void 0:g.message)||"Authentication failed")}}async login(e,t){var s,a,n,o,r,c;if(!this.api)throw new Error("AuthManager not initialized");try{const l=await this.api.post("/api/auth/signin",{email:e,password:t}),{token:g,user:u}=l.data;return this.setToken(g),(s=this.config)!=null&&s.enableLogging&&console.log("🔐 AuthManager: Login successful",{userId:u.id,email:u.email}),(a=this.chatSDK.events)==null||a.emit("auth.login",{user:u}),u}catch(l){throw(n=this.config)!=null&&n.enableLogging&&console.error("❌ AuthManager: Login failed",((o=l.response)==null?void 0:o.data)||l.message),new Error(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Login failed")}}async chatUserLogin(e,t){var s,a,n,o,r,c;if(!this.api)throw new Error("AuthManager not initialized");try{const l=await this.api.post("/api/chat-users/login",{externalUserId:e,appId:t}),g=this.parseAuthResponse(l.data);return(s=this.config)!=null&&s.enableLogging&&console.log("🔐 AuthManager: Chat user login successful",{userId:g.id,externalUserId:g.externalUserId}),(a=this.chatSDK.events)==null||a.emit("auth.login",{user:g}),g}catch(l){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(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Chat user login failed")}}async register(e,t,s,a={}){var n,o,r,c,l,g;if(!this.api)throw new Error("AuthManager not initialized");try{const u=await this.api.post("/api/auth/signup",{email:e,password:t,name:s,...a}),{token:m,user:p}=u.data;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}catch(u){throw(r=this.config)!=null&&r.enableLogging&&console.error("❌ AuthManager: Registration failed",((c=u.response)==null?void 0:c.data)||u.message),new Error(((g=(l=u.response)==null?void 0:l.data)==null?void 0:g.message)||"Registration failed")}}async chatUserRegister(e,t,s,a){var n,o,r,c,l,g;if(!this.api)throw new Error("AuthManager not initialized");try{const u=await this.api.post("/api/chat-users/register",{externalUserId:e,appId:t,name:s,email:a}),m=this.parseAuthResponse(u.data);return(n=this.config)!=null&&n.enableLogging&&console.log("🔐 AuthManager: Chat user registration successful",{userId:m.id,externalUserId:m.externalUserId,name:m.name}),(o=this.chatSDK.events)==null||o.emit("auth.register",{user:m}),m}catch(u){throw(r=this.config)!=null&&r.enableLogging&&console.error("❌ AuthManager: Chat user registration failed",((c=u.response)==null?void 0:c.data)||u.message),new Error(((g=(l=u.response)==null?void 0:l.data)==null?void 0:g.message)||"Chat user registration failed")}}parseAuthResponse(e){if(!e.success)throw new Error(e.message||"Authentication failed");if(!e.data)throw new Error("Invalid response format: missing data");const{token:t,user:s,auth:a}=e.data,n=t||(a==null?void 0:a.accessToken);return n&&this.setToken(n),{id:s.id,externalUserId:s.externalUserId,appId:s.appId||process.env.REACT_APP_APP_ID||"",name:s.name,email:s.email,avatarUrl:s.avatarUrl,status:s.status||"offline",isOnline:s.isOnline||!1,lastSeen:s.lastSeen,isRegistered:!0,createdAt:s.createdAt||new Date().toISOString(),updatedAt:s.updatedAt||new Date().toISOString()}}async logout(){var e,t,s;if(!this.api)throw new Error("AuthManager not initialized");try{await this.api.post("/api/auth/signout")}catch{(e=this.config)!=null&&e.enableLogging&&console.warn("⚠️ AuthManager: Logout API call failed, continuing with local logout")}this.clearToken(),(t=this.config)!=null&&t.enableLogging&&console.log("👋 AuthManager: Logout successful"),(s=this.chatSDK.events)==null||s.emit("auth.logout",{reason:"user_initiated"})}async getCurrentUser(){var e,t,s,a;if(!this.api)throw new Error("AuthManager not initialized");if(!this.hasValidToken())throw new Error("No valid token found. Please login first.");try{const n=await this.api.get("/api/auth/me");return this.parseAuthResponse(n.data)}catch(n){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(((a=(s=n.response)==null?void 0:s.data)==null?void 0:a.message)||"Failed to get current user")}}async verifyEmail(e){var t,s,a,n,o;if(!this.api)throw new Error("AuthManager not initialized");try{await this.api.post("/api/auth/verify-email",{token:e}),(t=this.config)!=null&&t.enableLogging&&console.log("✅ AuthManager: Email verified successfully")}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ AuthManager: Email verification failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Email verification failed")}}async forgotPassword(e){var t,s,a,n,o;if(!this.api)throw new Error("AuthManager not initialized");try{await this.api.post("/api/auth/forgot-password",{email:e}),(t=this.config)!=null&&t.enableLogging&&console.log("📧 AuthManager: Password reset email sent")}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ AuthManager: Forgot password failed",((a=r.response)==null?void 0:a.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")}}async resetPassword(e,t){var s,a,n,o,r;if(!this.api)throw new Error("AuthManager not initialized");try{await this.api.post("/api/auth/reset-password",{token:e,password:t}),(s=this.config)!=null&&s.enableLogging&&console.log("🔐 AuthManager: Password reset successful")}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ AuthManager: Password reset failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Password reset failed")}}hasValidToken(){return!!this.getToken()}getToken(){return localStorage.getItem("chatSDKToken")}setToken(e){localStorage.setItem("chatSDKToken",e)}clearToken(){localStorage.removeItem("chatSDKToken")}}class it{constructor(e){this.api=null,this.config=null,this.chatSDK=e}async init(e){this.config=e,this.api=ce.create({baseURL:e.apiBaseUrl,headers:{"Content-Type":"application/json"},timeout:e.timeout||3e4}),this.api.interceptors.request.use(t=>{const s=this.getToken();return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t)),this.api.interceptors.response.use(t=>t,t=>{var s,a;return((s=t.response)==null?void 0:s.status)===401&&(this.clearToken(),(a=this.chatSDK.events)==null||a.emit("chatUser.logout",{reason:"unauthorized"})),Promise.reject(t)})}async login(e,t,s=!0){var a,n,o,r,c,l,g;if(!this.api)throw new Error("ChatUserManager not initialized");try{const u=await this.api.post("/api/chat-users/login",{externalUserId:e,appId:t}),{token:m,user:p}=u.data.data;return s?(this.setToken(m),(a=this.config)!=null&&a.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}catch(u){throw(r=this.config)!=null&&r.enableLogging&&console.error("❌ ChatUserManager: Chat user login failed",((c=u.response)==null?void 0:c.data)||u.message),new Error(((g=(l=u.response)==null?void 0:l.data)==null?void 0:g.message)||"Chat user login failed")}}async register(e,t=!0){var s,a,n,o,r,c,l;if(!this.api)throw new Error("ChatUserManager not initialized");try{const g=await this.api.post("/api/chat-users/register",e),{token:u,user:m}=g.data.data;return t?(this.setToken(u),(s=this.config)!=null&&s.enableLogging&&console.log("📝 ChatUserManager: Chat user registration successful with token saved",{userId:m.id,email:m.email}),(a=this.chatSDK.events)==null||a.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}catch(g){throw(o=this.config)!=null&&o.enableLogging&&console.error("❌ ChatUserManager: Chat user registration failed",((r=g.response)==null?void 0:r.data)||g.message),new Error(((l=(c=g.response)==null?void 0:c.data)==null?void 0:l.message)||"Chat user registration failed")}}async authenticate(e,t,s,a,n=!0){try{return await this.login(e,t,n)}catch{try{return await this.register({externalUserId:e,appId:t,name:s,email:a},n)}catch(r){throw new Error("Failed to authenticate chat user: "+r)}}}async logout(){var e,t;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"})}getToken(){return localStorage.getItem("chatSDKToken")}setToken(e){localStorage.setItem("chatSDKToken",e)}clearToken(){localStorage.removeItem("chatSDKToken")}isAuthenticated(){return!!this.getToken()}async registerFcmToken(e,t="android"){var s,a,n,o,r,c;if(!this.api)throw new Error("ChatUserManager not initialized");if(!this.isAuthenticated())throw new Error("User must be authenticated to register FCM token");try{const l=await this.api.post("/api/chat-users/fcm-token",{fcmToken:e,platform:t});(s=this.config)!=null&&s.enableLogging&&console.log("📱 ChatUserManager: FCM token registered successfully",{fcmToken:e,platform:t}),(a=this.chatSDK.events)==null||a.emit("chatUser.fcmTokenRegistered",{fcmToken:e,platform:t})}catch(l){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(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Failed to register FCM token")}}async unregisterFcmToken(e){var t,s,a,n,o,r;if(!this.api)throw new Error("ChatUserManager not initialized");if(!this.isAuthenticated())throw new Error("User must be authenticated to unregister FCM token");try{const c=await this.api.delete("/api/chat-users/fcm-token",{data:{fcmToken:e}});(t=this.config)!=null&&t.enableLogging&&console.log("🗑️ ChatUserManager: FCM token unregistered successfully",{fcmToken:e}),(s=this.chatSDK.events)==null||s.emit("chatUser.fcmTokenUnregistered",{fcmToken:e})}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ ChatUserManager: Failed to unregister FCM token",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to unregister FCM token")}}async getFcmTokens(){var e,t,s,a,n,o,r;if(!this.api)throw new Error("ChatUserManager not initialized");if(!this.isAuthenticated())throw new Error("User must be authenticated to get FCM tokens");try{const l=((t=(e=(await this.api.get("/api/chat-users/fcm-tokens")).data)==null?void 0:e.data)==null?void 0:t.fcmTokens)||[];return(s=this.config)!=null&&s.enableLogging&&console.log("📱 ChatUserManager: Retrieved FCM tokens",{tokenCount:l.length}),l}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ ChatUserManager: Failed to get FCM tokens",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to get FCM tokens")}}async getConversations(e={}){var t,s,a,n,o;if(!this.api)throw new Error("ChatUserManager not initialized");try{const r=new URLSearchParams;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");const c=await this.api.get(`/api/chat-users/chats?${r.toString()}`),l=c.data.data||c.data.conversations||c.data||[];return(t=this.config)!=null&&t.enableLogging&&console.log("📋 ChatUserManager: Conversations fetched successfully",{count:l.length}),l}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ ChatUserManager: Get conversations failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get conversations")}}async startChat(e,t){var s,a,n,o,r,c,l;if(!this.api)throw new Error("ChatUserManager not initialized");if(!e)throw new Error("External Group ID is required");try{const g=await this.api.post("/api/chat-users/chats",{type:"direct",participants:[t],externalGroupId:e}),u=g.data.data||g.data.conversation||g.data;return(s=this.config)!=null&&s.enableLogging&&console.log("💬 ChatUserManager: Direct chat started successfully",{conversationId:u.id,userId:t,externalGroupId:e}),(a=this.chatSDK.socket)!=null&&a.isConnected()&&this.chatSDK.socket.joinRoom(u.id),(n=this.chatSDK.events)==null||n.emit("conversation.created",{conversation:u}),u}catch(g){throw(o=this.config)!=null&&o.enableLogging&&console.error("❌ ChatUserManager: Start chat failed",((r=g.response)==null?void 0:r.data)||g.message),new Error(((l=(c=g.response)==null?void 0:c.data)==null?void 0:l.message)||"Failed to start chat")}}async startChatWithProduct(e,t,s,a){var n,o,r,c,l,g,u;if(!this.api)throw new Error("ChatUserManager not initialized");if(!e)throw new Error("External Group ID is required");try{const m={type:"direct",participants:[t],externalGroupId:e,metadata:{productContext:{productId:s.productId,productName:s.productName,productImage:s.productImage,price:s.price,currency:s.currency,category:s.category,productMetadata:s.productMetadata}}};a&&Object.keys(a).length>0&&(m.chatMetadata=a);const p=await this.api.post("/api/chat-users/chats",m),x=p.data.data||p.data.conversation||p.data;return(n=this.config)!=null&&n.enableLogging&&console.log("💬 ChatUserManager: Product chat started successfully",{conversationId:x.id,userId:t,productId:s.productId,productName:s.productName}),(o=this.chatSDK.socket)!=null&&o.isConnected()&&this.chatSDK.socket.joinRoom(x.id),(r=this.chatSDK.events)==null||r.emit("conversation.created",{conversation:x}),x}catch(m){throw(c=this.config)!=null&&c.enableLogging&&console.error("❌ ChatUserManager: Start product chat failed",((l=m.response)==null?void 0:l.data)||m.message),new Error(((u=(g=m.response)==null?void 0:g.data)==null?void 0:u.message)||"Failed to start product chat")}}async getUnreadConversationsCount(){var e,t,s,a,n;if(!this.api)throw new Error("ChatUserManager not initialized");try{const r=(await this.api.get("/api/chat-users/unread/conversations-count")).data.data.unreadConversationsCount||0;return(e=this.config)!=null&&e.enableLogging&&console.log("📊 ChatUserManager: Unread conversations count fetched",{count:r}),r}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ ChatUserManager: Get unread conversations count failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get unread conversations count")}}async getTotalUnreadCount(){var e,t,s,a,n;if(!this.api)throw new Error("ChatUserManager not initialized");try{const r=(await this.api.get("/api/chat-users/unread/total-count")).data.data.totalUnreadCount||0;return(e=this.config)!=null&&e.enableLogging&&console.log("📊 ChatUserManager: Total unread count fetched",{count:r}),r}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ ChatUserManager: Get total unread count failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get total unread count")}}async getUnreadSummary(){var e,t,s,a,n;if(!this.api)throw new Error("ChatUserManager not initialized");try{const r=(await this.api.get("/api/chat-users/unread/summary")).data.data;return(e=this.config)!=null&&e.enableLogging&&console.log("📊 ChatUserManager: Unread summary fetched",{conversations:r.totalConversationsWithUnread,totalMessages:r.totalUnreadMessages}),r}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ ChatUserManager: Get unread summary failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get unread summary")}}async markRoomMessagesRead(e){var t,s,a,n,o,r,c,l,g,u,m;if(!this.api)throw new Error("ChatUserManager not initialized");try{if((t=this.config)!=null&&t.enableLogging&&console.log("📖 ChatUserManager: Marking room as read",{conversationId:e}),(s=this.chatSDK.socket)!=null&&s.isConnected())return this.chatSDK.socket.emit("mark_room_read",{roomId:e}),(a=this.config)!=null&&a.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;(o=this.config)!=null&&o.enableLogging&&console.log("📡 ChatUserManager: Socket not connected, falling back to API");const x=(await this.api.post(`/api/chat-users/chats/${e}/mark-read`)).data.data.markedAsReadCount||0;return(r=this.config)!=null&&r.enableLogging&&console.log("✅ ChatUserManager: Room messages marked as read via API",{conversationId:e,markedCount:x}),(c=this.chatSDK.events)==null||c.emit("conversation.read",{conversationId:e,markedCount:x}),x}catch(p){throw console.error("❌ ChatUserManager: Mark room messages as read failed",{conversationId:e,error:((l=p.response)==null?void 0:l.data)||p.message,status:(g=p.response)==null?void 0:g.status}),new Error(((m=(u=p.response)==null?void 0:u.data)==null?void 0:m.message)||p.message||"Failed to mark room messages as read")}}async markMessageRead(e){var t,s,a,n,o,r,c,l,g,u;if(!this.api)throw new Error("ChatUserManager not initialized");try{if((t=this.chatSDK.socket)!=null&&t.isConnected())return this.chatSDK.socket.emit("mark_message_read",{messageId:e}),(s=this.config)!=null&&s.enableLogging&&console.log("📡 ChatUserManager: mark_message_read sent via socket",{messageId:e}),(a=this.chatSDK.events)==null||a.emit("message.read",{messageId:e,wasUnread:!0}),!0;(n=this.config)!=null&&n.enableLogging&&console.log("📡 ChatUserManager: Socket not connected, falling back to API for mark-message-read");const p=(await this.api.post(`/api/chat-users/messages/${e}/mark-read`)).data.data.wasUnread||!1;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}catch(m){throw console.error("❌ ChatUserManager: Mark message as read failed",{messageId:e,error:((c=m.response)==null?void 0:c.data)||m.message,status:(l=m.response)==null?void 0:l.status}),new Error(((u=(g=m.response)==null?void 0:g.data)==null?void 0:u.message)||m.message||"Failed to mark message as read")}}startViewingConversation(e){var t,s;(t=this.chatSDK.socket)!=null&&t.isConnected()&&(this.chatSDK.socket.emit("viewing_conversation",{roomId:e,isViewing:!0}),(s=this.config)!=null&&s.enableLogging&&console.log("👀 ChatUserManager: Started viewing conversation",{conversationId:e}))}stopViewingConversation(e){var t,s;(t=this.chatSDK.socket)!=null&&t.isConnected()&&(this.chatSDK.socket.emit("viewing_conversation",{roomId:e,isViewing:!1}),(s=this.config)!=null&&s.enableLogging&&console.log("👁️ ChatUserManager: Stopped viewing conversation",{conversationId:e}))}}class je{constructor(e){this.api=null,this.config=null,this.chatSDK=e}async init(e){this.config=e,this.api=ce.create({baseURL:e.apiBaseUrl,headers:{"Content-Type":"application/json"},timeout:e.timeout||3e4}),this.api.interceptors.request.use(t=>{const s=localStorage.getItem("chatSDKToken");return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t))}async getUser(e){var t,s,a,n,o;if(!this.api)throw new Error("UserManager not initialized");try{const r=await this.api.get(`/api/users/${e}`);return(t=this.config)!=null&&t.enableLogging&&console.log("👤 UserManager: User fetched successfully",{userId:e}),r.data.user}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ UserManager: Get user failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get user")}}async searchUsers(e={}){var t,s,a,n,o,r;if(!this.api)throw new Error("UserManager not initialized");try{const c=new URLSearchParams;e.query&&c.append("q",e.query),e.limit&&c.append("limit",e.limit.toString()),e.offset&&c.append("offset",e.offset.toString()),e.role&&c.append("role",e.role),e.status&&c.append("status",e.status);const l=await this.api.get(`/api/users/search?${c.toString()}`);return(t=this.config)!=null&&t.enableLogging&&console.log("🔍 UserManager: Users searched successfully",{query:e.query,count:((s=l.data.users)==null?void 0:s.length)||0}),l.data.users||[]}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ UserManager: Search users failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to search users")}}async getAllUsers(e=20,t=0){var s,a,n,o,r,c;if(!this.api)throw new Error("UserManager not initialized");try{const l=await this.api.get(`/api/users?limit=${e}&offset=${t}`);return(s=this.config)!=null&&s.enableLogging&&console.log("👥 UserManager: All users fetched successfully",{count:((a=l.data.users)==null?void 0:a.length)||0,limit:e,offset:t}),l.data.users||[]}catch(l){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(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Failed to get users")}}async updateCurrentUser(e){var t,s,a,n,o,r;if(!this.api)throw new Error("UserManager not initialized");try{const c=await this.api.put("/api/users/me",e);return(t=this.config)!=null&&t.enableLogging&&console.log("✏️ UserManager: User profile updated successfully"),(s=this.chatSDK.events)==null||s.emit("user.updated",{user:c.data.user}),c.data.user}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ UserManager: Update user failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to update user")}}async updateStatus(e){var t,s,a,n,o,r;if(!this.api)throw new Error("UserManager not initialized");try{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}),(s=this.chatSDK.events)==null||s.emit("user.status.updated",{status:e})}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ UserManager: Update status failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to update status")}}async blockUser(e){var t,s,a,n,o,r;if(!this.api)throw new Error("UserManager not initialized");try{await this.api.post(`/api/users/${e}/block`),(t=this.config)!=null&&t.enableLogging&&console.log("🚫 UserManager: User blocked successfully",{userId:e}),(s=this.chatSDK.events)==null||s.emit("user.blocked",{userId:e})}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ UserManager: Block user failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to block user")}}async unblockUser(e){var t,s,a,n,o,r;if(!this.api)throw new Error("UserManager not initialized");try{await this.api.delete(`/api/users/${e}/block`),(t=this.config)!=null&&t.enableLogging&&console.log("✅ UserManager: User unblocked successfully",{userId:e}),(s=this.chatSDK.events)==null||s.emit("user.unblocked",{userId:e})}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ UserManager: Unblock user failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to unblock user")}}async getBlockedUsers(){var e,t,s,a,n,o;if(!this.api)throw new Error("UserManager not initialized");try{const r=await this.api.get("/api/users/me/blocked");return(e=this.config)!=null&&e.enableLogging&&console.log("📋 UserManager: Blocked users fetched successfully",{count:((t=r.data.users)==null?void 0:t.length)||0}),r.data.users||[]}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ UserManager: Get blocked users failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get blocked users")}}async getUserStatus(e){var t,s,a,n;if(!this.api)throw new Error("UserManager not initialized");try{return(await this.api.get(`/api/users/${e}/status`)).data.status}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ UserManager: Get user status failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get user status")}}async getUsersByIds(e){var t,s,a,n,o,r;if(!this.api)throw new Error("UserManager not initialized");try{const c=await this.api.post("/api/users/batch",{userIds:e});return(t=this.config)!=null&&t.enableLogging&&console.log("👥 UserManager: Users fetched by IDs successfully",{requestedCount:e.length,receivedCount:((s=c.data.users)==null?void 0:s.length)||0}),c.data.users||[]}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ UserManager: Get users by IDs failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to get users by IDs")}}}class Ae{constructor(e){this.api=null,this.config=null,this.chatSDK=e}async init(e){this.config=e,this.api=ce.create({baseURL:e.apiBaseUrl,headers:{"Content-Type":"application/json"},timeout:e.timeout||3e4}),this.api.interceptors.request.use(t=>{const s=localStorage.getItem("chatSDKToken");return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t))}async startChat(e,t){var s,a,n,o,r,c,l,g;if(!this.api)throw new Error("ConversationManager not initialized");if(!e)throw new Error("External Group ID is required");try{const u=await this.api.post("/api/chat-users/chats",{type:"direct",participants:[t],externalGroupId:e});(s=this.config)!=null&&s.enableLogging&&console.log("⚡ Using externalGroupId:",e),console.log("📡 Server response:",u.data);const m=u.data.data||u.data.conversation||u.data;return(a=this.config)!=null&&a.enableLogging&&console.log("💬 ConversationManager: Direct chat started successfully",{conversationId:m.id,userId:t}),(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}catch(u){throw(r=this.config)!=null&&r.enableLogging&&console.error("❌ ConversationManager: Start chat failed",((c=u.response)==null?void 0:c.data)||u.message),new Error(((g=(l=u.response)==null?void 0:l.data)==null?void 0:g.message)||"Failed to start chat")}}async startChatWithProduct(e,t,s,a){var n,o,r,c,l,g,u,m;if(!this.api)throw new Error("ConversationManager not initialized");if(!e)throw new Error("External Group ID is required");try{const p={type:"direct",participants:[t],externalGroupId:e,metadata:{productContext:{productId:s.productId,productName:s.productName,productImage:s.productImage,price:s.price,currency:s.currency,category:s.category,productMetadata:s.productMetadata}}};a&&Object.keys(a).length>0&&(p.chatMetadata=a),(n=this.config)!=null&&n.enableLogging&&console.log("⚡ Using externalGroupId:",e);const x=await this.api.post("/api/chat-users/chats",p);console.log("📡 Server response:",x.data);const B=x.data.data||x.data.conversation||x.data;return(o=this.config)!=null&&o.enableLogging&&console.log("💬 ConversationManager: Product chat started successfully",{conversationId:B.id,userId:t,productId:s.productId,productName:s.productName}),(r=this.chatSDK.socket)!=null&&r.isConnected()&&this.chatSDK.socket.joinRoom(B.id),(c=this.chatSDK.events)==null||c.emit("conversation.created",{conversation:B}),B}catch(p){throw(l=this.config)!=null&&l.enableLogging&&console.error("❌ ConversationManager: Start product chat failed",((g=p.response)==null?void 0:g.data)||p.message),new Error(((m=(u=p.response)==null?void 0:u.data)==null?void 0:m.message)||"Failed to start product chat")}}async createGroup(e){var t,s,a,n,o,r;if(!this.api)throw new Error("ConversationManager not initialized");try{const c=await this.api.post("/api/conversations",e);console.log("📡 Group creation response:",c.data);const l=c.data.data||c.data.conversation||c.data;return(t=this.config)!=null&&t.enableLogging&&console.log("👥 ConversationManager: Group created successfully",{conversationId:l.id,participantCount:e.participantIds.length}),(s=this.chatSDK.events)==null||s.emit("conversation.created",{conversation:l}),l}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ ConversationManager: Create group failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to create group")}}async getConversations(e={}){var t,s,a,n,o;if(!this.api)throw new Error("ConversationManager not initialized");try{const r=new URLSearchParams;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");const c=await this.api.get(`/api/chat-users/chats?${r.toString()}`);console.log("📡 Conversations response:",c.data);const l=c.data.data||c.data.conversations||c.data||[];return(t=this.config)!=null&&t.enableLogging&&console.log("📋 ConversationManager: Conversations fetched successfully",{count:l.length}),l}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ ConversationManager: Get conversations failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get conversations")}}async getConversation(e){var t,s,a,n,o;if(!this.api)throw new Error("ConversationManager not initialized");try{const r=await this.api.get(`/api/chat-users/chats/${e}`);return(t=this.config)!=null&&t.enableLogging&&console.log("💬 ConversationManager: Conversation fetched successfully",{conversationId:e}),r.data.conversation||r.data}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ ConversationManager: Get conversation failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get conversation")}}async updateConversation(e,t){var s,a,n,o,r,c;if(!this.api)throw new Error("ConversationManager not initialized");try{const g=(await this.api.put(`/api/conversations/${e}`,t)).data.conversation;return(s=this.config)!=null&&s.enableLogging&&console.log("✏️ ConversationManager: Conversation updated successfully",{conversationId:e}),(a=this.chatSDK.events)==null||a.emit("conversation.updated",{conversation:g}),g}catch(l){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(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Failed to update conversation")}}async addParticipants(e,t){var s,a,n,o,r,c;if(!this.api)throw new Error("ConversationManager not initialized");try{const g=(await this.api.post(`/api/conversations/${e}/participants`,{userIds:t})).data.conversation;return(s=this.config)!=null&&s.enableLogging&&console.log("➕ ConversationManager: Participants added successfully",{conversationId:e,addedCount:t.length}),(a=this.chatSDK.events)==null||a.emit("conversation.participants.added",{conversation:g,addedUserIds:t}),g}catch(l){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(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Failed to add participants")}}async removeParticipants(e,t){var s,a,n,o,r,c;if(!this.api)throw new Error("ConversationManager not initialized");try{const g=(await this.api.delete(`/api/conversations/${e}/participants`,{data:{userIds:t}})).data.conversation;return(s=this.config)!=null&&s.enableLogging&&console.log("➖ ConversationManager: Participants removed successfully",{conversationId:e,removedCount:t.length}),(a=this.chatSDK.events)==null||a.emit("conversation.participants.removed",{conversation:g,removedUserIds:t}),g}catch(l){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(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Failed to remove participants")}}async leaveConversation(e){var t,s,a,n,o,r;if(!this.api)throw new Error("ConversationManager not initialized");try{await this.api.post(`/api/conversations/${e}/leave`),(t=this.config)!=null&&t.enableLogging&&console.log("🚪 ConversationManager: Left conversation successfully",{conversationId:e}),(s=this.chatSDK.events)==null||s.emit("conversation.left",{conversationId:e})}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ ConversationManager: Leave conversation failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to leave conversation")}}async deleteConversation(e){var t,s,a,n,o,r;if(!this.api)throw new Error("ConversationManager not initialized");try{await this.api.delete(`/api/conversations/${e}`),(t=this.config)!=null&&t.enableLogging&&console.log("🗑️ ConversationManager: Conversation deleted successfully",{conversationId:e}),(s=this.chatSDK.events)==null||s.emit("conversation.deleted",{conversationId:e})}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ ConversationManager: Delete conversation failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to delete conversation")}}async markAsRead(e){var t,s,a,n,o,r;if(!this.api)throw new Error("ConversationManager not initialized");try{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}),(s=this.chatSDK.events)==null||s.emit("conversation.read",{conversationId:e})}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ ConversationManager: Mark as read failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to mark conversation as read")}}async getUnreadConversationsCount(){var e,t,s,a,n;if(!this.api)throw new Error("ConversationManager not initialized");try{const r=(await this.api.get("/api/chat-users/unread/conversations-count")).data.data.unreadConversationsCount||0;return(e=this.config)!=null&&e.enableLogging&&console.log("📊 ConversationManager: Unread conversations count fetched",{count:r}),r}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ ConversationManager: Get unread conversations count failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get unread conversations count")}}async getTotalUnreadCount(){var e,t,s,a,n;if(!this.api)throw new Error("ConversationManager not initialized");try{const r=(await this.api.get("/api/chat-users/unread/total-count")).data.data.totalUnreadCount||0;return(e=this.config)!=null&&e.enableLogging&&console.log("📊 ConversationManager: Total unread count fetched",{count:r}),r}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ ConversationManager: Get total unread count failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get total unread count")}}async getUnreadSummary(){var e,t,s,a,n;if(!this.api)throw new Error("ConversationManager not initialized");try{const r=(await this.api.get("/api/chat-users/unread/summary")).data.data;return(e=this.config)!=null&&e.enableLogging&&console.log("📊 ConversationManager: Unread summary fetched",{conversations:r.totalConversationsWithUnread,totalMessages:r.totalUnreadMessages}),r}catch(o){throw(t=this.config)!=null&&t.enableLogging&&console.error("❌ ConversationManager: Get unread summary failed",((s=o.response)==null?void 0:s.data)||o.message),new Error(((n=(a=o.response)==null?void 0:a.data)==null?void 0:n.message)||"Failed to get unread summary")}}async markRoomMessagesRead(e){var t,s,a,n,o,r,c,l,g,u;if(!this.api)throw new Error("ConversationManager not initialized");try{if((t=this.chatSDK.socket)!=null&&t.isConnected())return this.chatSDK.socket.emit("mark_room_read",{roomId:e}),(s=this.config)!=null&&s.enableLogging&&console.log("📡 ConversationManager: mark_room_read sent via socket",{roomId:e}),(a=this.chatSDK.events)==null||a.emit("conversation.read",{conversationId:e,markedCount:0}),0;(n=this.config)!=null&&n.enableLogging&&console.log("📡 ConversationManager: Socket not connected, falling back to API");const p=(await this.api.post(`/api/chat-users/chats/${e}/mark-read`)).data.data.markedAsReadCount||0;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}catch(m){throw(c=this.config)!=null&&c.enableLogging&&console.error("❌ ConversationManager: Mark room messages as read failed",((l=m.response)==null?void 0:l.data)||m.message),new Error(((u=(g=m.response)==null?void 0:g.data)==null?void 0:u.message)||"Failed to mark room messages as read")}}async markMessageRead(e){var t,s,a,n,o,r,c,l,g,u;if(!this.api)throw new Error("ConversationManager not initialized");try{if((t=this.chatSDK.socket)!=null&&t.isConnected())return this.chatSDK.socket.emit("mark_message_read",{messageId:e}),(s=this.config)!=null&&s.enableLogging&&console.log("📡 ConversationManager: mark_message_read sent via socket",{messageId:e}),(a=this.chatSDK.events)==null||a.emit("message.read",{messageId:e,wasUnread:!0}),!0;(n=this.config)!=null&&n.enableLogging&&console.log("📡 ConversationManager: Socket not connected, falling back to API for mark-message-read");const p=(await this.api.post(`/api/chat-users/messages/${e}/mark-read`)).data.data.wasUnread||!1;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}catch(m){throw(c=this.config)!=null&&c.enableLogging&&console.error("❌ ConversationManager: Mark message as read failed",((l=m.response)==null?void 0:l.data)||m.message),new Error(((u=(g=m.response)==null?void 0:g.data)==null?void 0:u.message)||"Failed to mark message as read")}}startViewingConversation(e){var t,s;(t=this.chatSDK.socket)!=null&&t.isConnected()&&(this.chatSDK.socket.emit("viewing_conversation",{roomId:e,isViewing:!0}),(s=this.config)!=null&&s.enableLogging&&console.log("👀 ConversationManager: Started viewing conversation",{conversationId:e}))}stopViewingConversation(e){var t,s;(t=this.chatSDK.socket)!=null&&t.isConnected()&&(this.chatSDK.socket.emit("viewing_conversation",{roomId:e,isViewing:!1}),(s=this.config)!=null&&s.enableLogging&&console.log("👁️ ConversationManager: Stopped viewing conversation",{conversationId:e}))}async blockUserInChat(e,t){var s,a,n,o,r,c;if(!this.api)throw new Error("ConversationManager not initialized");try{const l=await this.api.post(`/api/chat-users/chats/${e}/block-user`,{userId:t});(s=this.config)!=null&&s.enableLogging&&console.log("🚫 ConversationManager: User blocked in chat",{chatId:e,userId:t}),(a=this.chatSDK.events)==null||a.emit("user.blocked",{chatId:e,userId:t})}catch(l){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(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Failed to block user in chat")}}async unblockUserInChat(e,t){var s,a,n,o,r,c;if(!this.api)throw new Error("ConversationManager not initialized");try{const l=await this.api.post(`/api/chat-users/chats/${e}/unblock-user`,{userId:t});(s=this.config)!=null&&s.enableLogging&&console.log("✅ ConversationManager: User unblocked in chat",{chatId:e,userId:t}),(a=this.chatSDK.events)==null||a.emit("user.unblocked",{chatId:e,userId:t})}catch(l){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(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Failed to unblock user in chat")}}async getBlockStatus(e){var t,s,a,n,o;if(!this.api)throw new Error("ConversationManager not initialized");try{const r=await this.api.get(`/api/chat-users/chats/${e}/block-status`);return(t=this.config)!=null&&t.enableLogging&&console.log("📊 ConversationManager: Block status fetched",{chatId:e}),r.data.data}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ ConversationManager: Get block status failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get block status")}}}class Te{constructor(e){this.api=null,this.config=null,this.chatSDK=e}async init(e){this.config=e,this.api=ce.create({baseURL:e.apiBaseUrl,headers:{"Content-Type":"application/json"},timeout:e.timeout||3e4}),this.api.interceptors.request.use(t=>{const s=localStorage.getItem("chatSDKToken");return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t))}async sendMessage(e,t,s){return this.sendMessageWithOptions({conversationId:e,content:t,type:"text",metadata:s})}async sendMessageWithOptions(e){var t;if(!this.api)throw new Error("MessageManager not initialized");if(this.chatSDK.socket&&this.chatSDK.socket.isConnected())try{return await this.sendMessageViaSocket(e)}catch(s){(t=this.config)!=null&&t.enableLogging&&console.warn("⚠️ Socket send failed, falling back to HTTP:",s)}return this.sendMessageViaHttp(e)}async sendMessageViaSocket(e){return new Promise((t,s)=>{var c,l,g;if(!this.chatSDK.socket||!this.chatSDK.socket.isConnected()){s(new Error("Socket not connected"));return}const a=this.chatSDK.getCurrentUser();if(!a){s(new Error("User not authenticated"));return}const n={conversationId:e.conversationId,content:e.content,messageType:e.type||"text",metadata:e.metadata,senderId:a.id,senderName:a.name,senderEmail:a.email},o=u=>{this.chatSDK.socket.off("message-sent",o),this.chatSDK.socket.off("message-error",r),t(u)},r=u=>{this.chatSDK.socket.off("message-sent",o),this.chatSDK.socket.off("message-error",r),s(new Error(u.message||"Socket send failed"))};this.chatSDK.socket.on("message-sent",o),this.chatSDK.socket.on("message-error",r),this.chatSDK.socket.emit("send_message",n),(c=this.config)!=null&&c.enableLogging&&console.log("📤 MessageManager: Message sent via socket",{conversationId:e.conversationId,content:((l=e.content)==null?void 0:l.substring(0,50))+(((g=e.content)==null?void 0:g.length)>50?"...":""),type:e.type||"text"}),setTimeout(()=>{this.chatSDK.socket.off("message-sent",o),this.chatSDK.socket.off("message-error",r),s(new Error("Socket send timeout"))},1e4)})}async sendMessageViaHttp(e){var t,s,a,n,o,r,c,l;if(!this.api)throw new Error("MessageManager not initialized");try{const g=await this.api.post("/api/chat-users/messages",{roomId:e.conversationId,content:e.content,messageType:e.type||"text",metadata:e.metadata,replyToMessageId:e.replyToMessageId}),u=g.data.data||g.data.message||g.data;return(t=this.config)!=null&&t.enableLogging&&console.log("📡 Message sent via HTTP:",{id:u.id,content:((s=u.content)==null?void 0:s.substring(0,50))+(((a=u.content)==null?void 0:a.length)>50?"...":""),type:u.type||"text"}),(n=this.chatSDK.events)==null||n.emit("message.sent",{message:u}),u}catch(g){throw(o=this.config)!=null&&o.enableLogging&&console.error("❌ MessageManager: HTTP send failed",((r=g.response)==null?void 0:r.data)||g.message),new Error(((l=(c=g.response)==null?void 0:c.data)==null?void 0:l.message)||"Failed to send message")}}async getMessages(e){var t,s,a,n,o;if(!this.api)throw new Error("MessageManager not initialized");try{const r=new URLSearchParams;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);const c=await this.api.get(`/api/chat-users/messages/${e.conversationId}?${r.toString()}`);console.log("📡 Get messages response:",c.data),console.log("📡 Raw server messages:",JSON.stringify(c.data,null,2));const l=c.data.data||c.data.messages||c.data||[];(t=this.config)!=null&&t.enableLogging&&console.log("📥 MessageManager: Messages fetched successfully",{conversationId:e.conversationId,count:l.length});const g=l.map(u=>({...u,type:u.messageType||u.type||"text",conversationId:u.roomId||u.conversationId,timestamp:u.createdAt||u.timestamp||new Date().toISOString()}));return console.log("📥 Final processed messages:",g),g}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ MessageManager: Get messages failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get messages")}}async getMessage(e){var t,s,a,n,o;if(!this.api)throw new Error("MessageManager not initialized");try{const r=await this.api.get(`/api/messages/${e}`);return(t=this.config)!=null&&t.enableLogging&&console.log("📄 MessageManager: Message fetched successfully",{messageId:e}),r.data.message}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ MessageManager: Get message failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get message")}}async updateMessage(e,t,s){var a,n,o,r,c,l;if(!this.api)throw new Error("MessageManager not initialized");try{const u=(await this.api.put(`/api/messages/${e}`,{content:t,metadata:s})).data.message;return(a=this.config)!=null&&a.enableLogging&&console.log("✏️ MessageManager: Message updated successfully",{messageId:e}),(n=this.chatSDK.events)==null||n.emit("message.updated",{message:u}),u}catch(g){throw(o=this.config)!=null&&o.enableLogging&&console.error("❌ MessageManager: Update message failed",((r=g.response)==null?void 0:r.data)||g.message),new Error(((l=(c=g.response)==null?void 0:c.data)==null?void 0:l.message)||"Failed to update message")}}async deleteMessage(e,t=!1){var s,a,n,o,r,c;if(!this.api)throw new Error("MessageManager not initialized");try{await this.api.delete(`/api/messages/${e}`,{data:{deleteForEveryone:t}}),(s=this.config)!=null&&s.enableLogging&&console.log("🗑️ MessageManager: Message deleted successfully",{messageId:e,deleteForEveryone:t}),(a=this.chatSDK.events)==null||a.emit("message.deleted",{messageId:e,deleteForEveryone:t})}catch(l){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(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Failed to delete message")}}async markAsRead(e,t){var s,a,n,o,r,c;if(!this.api)throw new Error("MessageManager not initialized");try{await this.api.put(`/api/conversations/${e}/messages/read`,{messageIds:t}),(s=this.config)!=null&&s.enableLogging&&console.log("👁️ MessageManager: Messages marked as read",{conversationId:e,messageCount:(t==null?void 0:t.length)||"all"}),(a=this.chatSDK.events)==null||a.emit("messages.read",{conversationId:e,messageIds:t})}catch(l){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(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Failed to mark messages as read")}}async searchMessages(e){var t,s,a,n,o;if(!this.api)throw new Error("MessageManager not initialized");try{const r=new URLSearchParams;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);const l=(await this.api.get(`/api/messages/search?${r.toString()}`)).data.messages||[];return(t=this.config)!=null&&t.enableLogging&&console.log("🔍 MessageManager: Messages searched successfully",{query:e.query,count:l.length}),l}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ MessageManager: Search messages failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to search messages")}}async sendTypingIndicator(e,t){var s,a,n,o;if(!this.api)throw new Error("MessageManager not initialized");try{await this.api.post(`/api/conversations/${e}/typing`,{isTyping:t}),(s=this.config)!=null&&s.enableLogging&&t&&console.log("⌨️ MessageManager: Typing indicator sent",{conversationId:e}),(a=this.chatSDK.events)==null||a.emit("typing.indicator",{conversationId:e,isTyping:t})}catch(r){(n=this.config)!=null&&n.enableLogging&&console.error("❌ MessageManager: Send typing indicator failed",((o=r.response)==null?void 0:o.data)||r.message)}}async reactToMessage(e,t){var s,a,n,o,r,c;if(!this.api)throw new Error("MessageManager not initialized");try{await this.api.post(`/api/messages/${e}/reactions`,{reaction:t}),(s=this.config)!=null&&s.enableLogging&&console.log("😊 MessageManager: Message reaction sent",{messageId:e,reaction:t}),(a=this.chatSDK.events)==null||a.emit("message.reaction",{messageId:e,reaction:t})}catch(l){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(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Failed to react to message")}}async removeReaction(e,t){var s,a,n,o,r,c;if(!this.api)throw new Error("MessageManager not initialized");try{await this.api.delete(`/api/messages/${e}/reactions/${t}`),(s=this.config)!=null&&s.enableLogging&&console.log("🗑️ MessageManager: Message reaction removed",{messageId:e,reaction:t}),(a=this.chatSDK.events)==null||a.emit("message.reaction.removed",{messageId:e,reaction:t})}catch(l){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(((c=(r=l.response)==null?void 0:r.data)==null?void 0:c.message)||"Failed to remove reaction")}}}class Ne{constructor(e){this.api=null,this.config=null,this.maxFileSize=50*1024*1024,this.allowedTypes=["image/jpeg","image/png","image/gif","image/webp","video/mp4","video/webm","video/quicktime","audio/mpeg","audio/wav","audio/ogg","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain"],this.chatSDK=e}async init(e){this.config=e,this.api=ce.create({baseURL:e.apiBaseUrl,headers:{"Content-Type":"application/json"},timeout:e.timeout||3e4}),this.api.interceptors.request.use(t=>{const s=localStorage.getItem("chatSDKToken");return s&&(t.headers.Authorization=`Bearer ${s}`),t},t=>Promise.reject(t))}async uploadMedia(e){var t,s,a,n,o,r;if(!this.api)throw new Error("MediaManager not initialized");this.validateFile(e.file);try{const c=new FormData;c.append("file",e.file),c.append("type",e.type),e.conversationId&&c.append("chatId",e.conversationId),e.caption&&c.append("caption",e.caption),e.metadata&&c.append("metadata",JSON.stringify(e.metadata));const g=(await this.api.post("/api/chat-users/upload",c,{headers:{"Content-Type":"multipart/form-data"},onUploadProgress:u=>{if(e.onProgress&&u.total){const m=Math.round(u.loaded*100/u.total);e.onProgress(m)}},timeout:300*1e3})).data.data;return(t=this.config)!=null&&t.enableLogging&&console.log("📎 MediaManager: File uploaded successfully",{url:g.fileUrl,fileName:g.fileName,fileSize:g.fileSize,mimeType:g.mimeType,type:e.type}),(s=this.chatSDK.events)==null||s.emit("media.uploaded",{media:g}),g}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ MediaManager: Upload failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to upload file")}}async sendImage(e,t,s){return this.uploadMedia({file:t,type:"image",conversationId:e,caption:s})}async sendVideo(e,t,s){return this.uploadMedia({file:t,type:"video",conversationId:e,caption:s})}async sendAudio(e,t,s){return this.uploadMedia({file:t,type:"audio",conversationId:e,caption:s})}async sendDocument(e,t,s){return this.uploadMedia({file:t,type:"document",conversationId:e,caption:s})}async getMedia(e){var t,s,a,n,o;if(!this.api)throw new Error("MediaManager not initialized");try{const r=await this.api.get(`/api/media/${e}`);return(t=this.config)!=null&&t.enableLogging&&console.log("📄 MediaManager: Media info fetched successfully",{mediaId:e}),r.data.media}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ MediaManager: Get media failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get media")}}async getDownloadUrl(e){var t,s,a,n,o;if(!this.api)throw new Error("MediaManager not initialized");try{const r=new URLSearchParams;e.quality&&r.append("quality",e.quality);const l=(await this.api.get(`/api/media/${e.mediaId}/download?${r.toString()}`)).data.url;return(t=this.config)!=null&&t.enableLogging&&console.log("🔗 MediaManager: Download URL generated",{mediaId:e.mediaId,quality:e.quality}),l}catch(r){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ MediaManager: Get download URL failed",((a=r.response)==null?void 0:a.data)||r.message),new Error(((o=(n=r.response)==null?void 0:n.data)==null?void 0:o.message)||"Failed to get download URL")}}async deleteMedia(e){var t,s,a,n,o,r;if(!this.api)throw new Error("MediaManager not initialized");try{await this.api.delete(`/api/media/${e}`),(t=this.config)!=null&&t.enableLogging&&console.log("🗑️ MediaManager: Media deleted successfully",{mediaId:e}),(s=this.chatSDK.events)==null||s.emit("media.deleted",{mediaId:e})}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ MediaManager: Delete media failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to delete media")}}async generateThumbnail(e,t="medium"){var s,a,n,o,r;if(!this.api)throw new Error("MediaManager not initialized");try{const l=(await this.api.post(`/api/media/${e}/thumbnail`,{size:t})).data.thumbnailUrl;return(s=this.config)!=null&&s.enableLogging&&console.log("🖼️ MediaManager: Thumbnail generated",{mediaId:e,size:t}),l}catch(c){throw(a=this.config)!=null&&a.enableLogging&&console.error("❌ MediaManager: Generate thumbnail failed",((n=c.response)==null?void 0:n.data)||c.message),new Error(((r=(o=c.response)==null?void 0:o.data)==null?void 0:r.message)||"Failed to generate thumbnail")}}setMaxFileSize(e){var t;this.maxFileSize=e,(t=this.config)!=null&&t.enableLogging&&console.log("📏 MediaManager: Max file size updated",{sizeInMB:Math.round(e/(1024*1024))})}setAllowedTypes(e){var t;this.allowedTypes=e,(t=this.config)!=null&&t.enableLogging&&console.log("📋 MediaManager: Allowed types updated",{types:e})}validateFile(e){if(e.size>this.maxFileSize)throw new Error(`File size exceeds maximum allowed size of ${Math.round(this.maxFileSize/(1024*1024))}MB`);if(!this.allowedTypes.includes(e.type))throw new Error(`File type ${e.type} is not allowed`);if(!e.name||e.name.trim().length===0)throw new Error("File must have a valid name")}isTypeSupported(e){return this.allowedTypes.includes(e)}getFileTypeCategory(e){return e.startsWith("image/")?"image":e.startsWith("video/")?"video":e.startsWith("audio/")?"audio":"document"}formatFileSize(e){if(e===0)return"0 Bytes";const t=1024,s=["Bytes","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,a)).toFixed(2))+" "+s[a]}}class Ke{constructor(e){this.config=null,this.socket=null,this.eventListeners=new Map,this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectDelay=1e3,this.heartbeatInterval=null,this.connectionTimeout=null,this.chatSDK=e}async init(e){var t;this.config=e,(t=this.config)!=null&&t.enableLogging&&console.log("📡 EventManager: Initialized")}async connect(){var e;if(!this.config)throw new Error("EventManager not initialized");return(e=this.config)!=null&&e.enableLogging&&console.log("📡 EventManager: Skipping native WebSocket connection (using Socket.io instead)"),this.isConnected=!0,Promise.resolve()}async disconnect(){var e;return(e=this.config)!=null&&e.enableLogging&&console.log("📡 EventManager: Skipping native WebSocket disconnection (using Socket.io instead)"),this.isConnected=!1,Promise.resolve()}on(e,t){var s;this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),(s=this.config)!=null&&s.enableLogging&&console.log("👂 EventManager: Event listener added",{event:e})}off(e,t){var a;if(!t){this.eventListeners.delete(e);return}const s=this.eventListeners.get(e);if(s){const n=s.indexOf(t);n>-1&&s.splice(n,1),s.length===0&&this.eventListeners.delete(e)}(a=this.config)!=null&&a.enableLogging&&console.log("🔇 EventManager: Event listener removed",{event:e})}emit(e,t){var a;const s=this.eventListeners.get(e);s&&s.forEach(n=>{var o;try{n(t)}catch(r){(o=this.config)!=null&&o.enableLogging&&console.error("❌ EventManager: Error in event callback",{event:e,error:r})}}),(a=this.config)!=null&&a.enableLogging&&console.log("📢 EventManager: Event emitted",{event:e,data:t})}send(e,t){var a,n,o;if(!this.isConnected||!this.socket){(a=this.config)!=null&&a.enableLogging&&console.warn("⚠️ EventManager: Cannot send message - not connected");return}const s={type:e,data:t,timestamp:Date.now()};try{this.socket.send(JSON.stringify(s)),(n=this.config)!=null&&n.enableLogging&&console.log("📤 EventManager: Message sent",{type:e,data:t})}catch(r){(o=this.config)!=null&&o.enableLogging&&console.error("❌ EventManager: Failed to send message",{type:e,error:r})}}isSocketConnected(){var e;return this.isConnected&&((e=this.socket)==null?void 0:e.readyState)===WebSocket.OPEN}getConnectionStatus(){if(!this.socket)return"disconnected";switch(this.socket.readyState){case WebSocket.CONNECTING:return"connecting";case WebSocket.OPEN:return"connected";case WebSocket.CLOSING:case WebSocket.CLOSED:return"disconnected";default:return"error"}}handleOpen(e){var t;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()})}handleMessage(e){var t,s;try{const a=JSON.parse(e.data);if((t=this.config)!=null&&t.enableLogging&&console.log("📥 EventManager: Message received",a),a.type==="heartbeat"){this.send("heartbeat",{timestamp:Date.now()});return}this.emit(a.type,a.data),this.emit("message.received",a)}catch(a){(s=this.config)!=null&&s.enableLogging&&console.error("❌ EventManager: Failed to parse message",{data:e.data,error:a})}}handleClose(e){var t;this.isConnected=!1,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),(t=this.config)!=null&&t.enableLogging&&console.log("🔌 EventManager: WebSocket closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}),this.emit("connection.close",{code:e.code,reason:e.reason,timestamp:Date.now()}),!e.wasClean&&this.reconnectAttempts<this.maxReconnectAttempts&&this.attemptReconnect()}handleError(e){var t;(t=this.config)!=null&&t.enableLogging&&console.error("❌ EventManager: WebSocket error",e),this.emit("connection.error",{error:e,timestamp:Date.now()})}startHeartbeat(){this.heartbeatInterval&&clearInterval(this.heartbeatInterval),this.heartbeatInterval=setInterval(()=>{this.isConnected&&this.send("ping",{timestamp:Date.now()})},3e4)}attemptReconnect(){var e,t;if(this.reconnectAttempts>=this.maxReconnectAttempts){(e=this.config)!=null&&e.enableLogging&&console.error("❌ EventManager: Max reconnection attempts reached"),this.emit("connection.failed",{attempts:this.reconnectAttempts,timestamp:Date.now()});return}this.reconnectAttempts++,(t=this.config)!=null&&t.enableLogging&&console.log(`🔄 EventManager: Attempting reconnection ${this.reconnectAttempts}/${this.maxReconnectAttempts}`),setTimeout(()=>{this.connect().catch(s=>{var a;(a=this.config)!=null&&a.enableLogging&&console.error("❌ EventManager: Reconnection failed",s),this.attemptReconnect()})},this.reconnectDelay),this.reconnectDelay=Math.min(this.reconnectDelay*2,3e4)}setMaxReconnectAttempts(e){this.maxReconnectAttempts=e}clearAllListeners(){var e;this.eventListeners.clear(),(e=this.config)!=null&&e.enableLogging&&console.log("🧹 EventManager: All event listeners cleared")}getActiveListeners(){return Array.from(this.eventListeners.keys())}}class ke{static parseUser(e){if(!e)throw new Error("User data is required");return{id:e.id,externalUserId:e.externalUserId,appId:e.appId,name:e.name,username:e.username,displayName:e.displayName,email:e.email,avatar:e.avatar,avatarUrl:e.avatarUrl,status:e.status||"offline",isOnline:e.isOnline||!1,isRegistered:e.isRegistered||!0,lastSeen:e.lastSeen,createdAt:e.createdAt,updatedAt:e.updatedAt,metadata:e.metadata||{},...e}}static parseMessage(e){var a,n,o;if(!e)throw new Error("Message data is required");let t=e.type||"text";if(t==="text"&&((a=e.metadata)!=null&&a.fileUrl)&&((n=e.metadata)!=null&&n.mimeType)){const r=e.metadata.mimeType;r.startsWith("image/")?t="image":r.startsWith("video/")?t="video":r.startsWith("audio/")?t="audio":t="file"}const s={id:e.id,content:e.content,senderId:e.senderId,roomId:e.roomId||e.conversationId,conversationId:e.conversationId||e.roomId,senderName:e.senderName,senderEmail:e.senderEmail,senderAvatar:e.senderAvatar,senderExternalUserId:e.senderExternalUserId,messageType:t,type:t,status:e.status||"sent",isRead:e.isRead||!1,isDelivered:e.isDelivered||!1,timestamp:e.timestamp,createdAt:e.createdAt,updatedAt:e.updatedAt,metadata:e.metadata||{}};return console.log("✅ ParseUtils: Parsed message:",{id:s.id,type:s.type,messageType:s.messageType,roomId:s.roomId,hasMetadata:!!s.metadata,metadataKeys:Object.keys(s.metadata||{}),fileUrl:(o=s.metadata)==null?void 0:o.fileUrl}),s}static parseConversation(e){if(!e)throw new Error("Conversation data is required");return{id:e.id,conversationId:e.conversationId||e.id,name:e.name,description:e.description,type:e.type||"direct",avatar:e.avatar,participants:Array.isArray(e.participants)?e.participants.map(t=>this.parseUser(t)):[],lastMessage:e.lastMessage?this.parseMessage(e.lastMessage):null,productContext:e.productContext?this.parseProductContext(e.productContext):void 0,metadata:e.metadata||{},createdAt:e.createdAt,updatedAt:e.updatedAt,...e}}static parseProductContext(e){if(e)return{productId:e.productId,productName:e.productName,productImage:e.productImage,price:e.price,currency:e.currency,category:e.category,productMetadata:e.productMetadata||{},...e}}static parseMessages(e){return Array.isArray(e)?e:[]}static parseConversations(e){return Array.isArray(e)?e:[]}static parseUsers(e){return Array.isArray(e)?e:[]}}class ze{constructor(e){this.socket=null,this.config=null,this.currentUserId=null,this.joinedRooms=new Set,this.chatSDK=e}async init(e){var t,s,a,n;this.config=e,(t=this.config)!=null&&t.enableLogging&&console.log("🔌 SocketManager: Starting initialization...",{apiBaseUrl:e.apiBaseUrl,enableLogging:e.enableLogging});try{let o=e.wsUrl;!o&&e.apiBaseUrl&&(o=e.apiBaseUrl.replace(/\/api\/?$/,"")),o||(o=e.environment==="production"?"https://chatsdk-mzad-admin.onrender.com":"http://localhost:5001"),(s=this.config)!=null&&s.enableLogging&&console.log("🔌 SocketManager: Creating socket connection to:",o,{wsUrl:e.wsUrl,apiBaseUrl:e.apiBaseUrl,environment:e.environment}),this.socket=rt.io(o,{transports:["websocket","polling"],autoConnect:!1,forceNew:!0,timeout:45e3,reconnection:!0,reconnectionAttempts:10,reconnectionDelay:2e3,reconnectionDelayMax:1e4,upgrade:!0,rememberUpgrade:!1}),this.setupEventListeners(),(a=this.config)!=null&&a.enableLogging&&console.log("✅ SocketManager: Initialized successfully with socket:",!!this.socket)}catch(o){throw(n=this.config)!=null&&n.enableLogging&&console.error("❌ SocketManager: Initialization failed",o),o}}async connect(e){var s,a,n,o,r,c,l;if(!this.socket)throw new Error("SocketManager not initialized");this.currentUserId=e;let t=(s=this.config)==null?void 0:s.wsUrl;return!t&&((a=this.config)!=null&&a.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...",{userId:e,socketUrl:t,wsUrl:(r=this.config)==null?void 0:r.wsUrl,apiBaseUrl:(c=this.config)==null?void 0:c.apiBaseUrl,environment:(l=this.config)==null?void 0:l.environment,hasSocket:!!this.socket}),new Promise((g,u)=>{const m=setTimeout(()=>{var p;(p=this.config)!=null&&p.enableLogging&&console.error("❌ SocketManager: Connection timeout after 10 seconds"),u(new Error("Connection timeout"))},1e4);this.socket.connect(),this.socket.on("connect",()=>{var p,x,B;clearTimeout(m),(p=this.config)!=null&&p.enableLogging&&console.log("✅ SocketManager: Connected to WebSocket server successfully!"),this.socket.emit("authenticate",{userId:e,appId:(x=this.config)==null?void 0:x.appId}),(B=this.config)!=null&&B.enableLogging&&console.log("🔐 SocketManager: Sent authentication for user:",e),g()}),this.socket.on("connect_error",p=>{var x;clearTimeout(m),(x=this.config)!=null&&x.enableLogging&&console.error("❌ SocketManager: Connection failed with error:",p),u(p)}),this.socket.on("disconnect",p=>{var x;(x=this.config)!=null&&x.enableLogging&&console.log("🔌 SocketManager: Disconnected from server, reason:",p)})})}disconnect(){var e;this.socket&&(this.socket.disconnect(),this.joinedRooms.clear(),(e=this.config)!=null&&e.enableLogging&&console.log("�� SocketManager: Disconnected from WebSocket server"))}joinConversation(e){var t,s,a;if(!this.socket||!this.socket.connected){(t=this.config)!=null&&t.enableLogging&&console.warn("SocketManager: Cannot join conversation - not connected");return}this.joinedRooms.has(e)||(this.socket.emit("join_conversation",{conversationId:e,appId:(s=this.config)==null?void 0:s.appId}),this.joinedRooms.add(e),(a=this.config)!=null&&a.enableLogging&&console.log(`🏠 SocketManager: Joined conversation ${e}`))}leaveConversation(e){var t;!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}`))}sendTypingIndicator(e,t){var s,a;if(!this.socket||!this.socket.connected){(s=this.config)!=null&&s.enableLogging&&console.warn("SocketManager: Cannot send typing indicator - not connected");return}this.socket.emit("typing_indicator",{conversationId:e,isTyping:t,userId:this.currentUserId}),(a=this.config)!=null&&a.enableLogging&&console.log(`⌨️ SocketManager: Typing indicator sent: ${t} for conversation ${e}`)}sendMessage(e){var s,a;if(!this.socket||!this.socket.connected){(s=this.config)!=null&&s.enableLogging&&console.warn("SocketManager: Cannot send message - not connected");return}const t={...e,timestamp:new Date().toISOString(),senderId:this.currentUserId||e.senderId};this.socket.emit("send-message",t),(a=this.config)!=null&&a.enableLogging&&console.log("📤 SocketManager: Message sent via WebSocket",t)}setupEventListeners(){this.socket&&(this.socket.on("message_received",e=>{var t,s,a;try{const n=ke.parseMessage(e);(t=this.chatSDK.events)==null||t.emit("message.received",{message:n})}catch(n){(s=this.config)!=null&&s.enableLogging&&console.error("❌ SocketManager: Failed to parse received message",n),(a=this.chatSDK.events)==null||a.emit("message.received",{message:e})}}),this.socket.on("typing_indicator",e=>{var t,s,a,n;try{const o={userId:e.userId||e.user_id,conversationId:e.conversationId||e.conversation_id||e.room_id,isTyping:e.isTyping||e.is_typing,timestamp:e.timestamp||e.created_at};(t=this.config)!=null&&t.enableLogging&&console.log("⌨️ SocketManager: Typing indicator received",o),(s=this.chatSDK.events)==null||s.emit("typing.indicator",o)}catch(o){(a=this.config)!=null&&a.enableLogging&&console.error("❌ SocketManager: Failed to process typing indicator",o),(n=this.chatSDK.events)==null||n.emit("typing.indicator",e)}}),this.socket.on("user_status_changed",e=>{var t,s,a,n;try{const o={userId:e.userId||e.user_id,status:e.status,timestamp:e.timestamp||e.updated_at||e.last_seen};(t=this.config)!=null&&t.enableLogging&&console.log("👤 SocketManager: User status update",o),(s=this.chatSDK.events)==null||s.emit("user.status.changed",o)}catch(o){(a=this.config)!=null&&a.enableLogging&&console.error("❌ SocketManager: Failed to process user status update",o),(n=this.chatSDK.events)==null||n.emit("user.status.changed",e)}}),this.socket.on("conversation_updated",e=>{var t,s,a,n;try{const o={conversationId:e.conversationId||e.conversation_id||e.room_id,lastMessage:e.lastMessage||e.last_message,unreadCount:e.unreadCount||e.unread_count,timestamp:e.timestamp||e.updated_at};(t=this.config)!=null&&t.enableLogging&&console.log("💬 SocketManager: Conversation update",o),(s=this.chatSDK.events)==null||s.emit("conversation.updated",o)}catch(o){(a=this.config)!=null&&a.enableLogging&&console.error("❌ SocketManager: Failed to process conversation update",o),(n=this.chatSDK.events)==null||n.emit("conversation.updated",e)}}),this.socket.on("user-joined-room",e=>{var t,s;(t=this.config)!=null&&t.enableLogging&&console.log("🏠 SocketManager: User joined room",e),(s=this.chatSDK.events)==null||s.emit("room.user.joined",e)}),this.socket.on("user-left-room",e=>{var t,s;(t=this.config)!=null&&t.enableLogging&&console.log("🚪 SocketManager: User left room",e),(s=this.chatSDK.events)==null||s.emit("room.user.left",e)}),this.socket.on("online-users",e=>{var t,s,a,n;try{const o=ke.parseUsers(e);(t=this.config)!=null&&t.enableLogging&&console.log("🌐 SocketManager: Online users update",{count:o.length}),(s=this.chatSDK.events)==null||s.emit("users.online",{users:o})}catch(o){(a=this.config)!=null&&a.enableLogging&&console.error("❌ SocketManager: Failed to parse online users",o),(n=this.chatSDK.events)==null||n.emit("users.online",{users:e})}}),this.socket.on("conversation_block_status",e=>{var t,s;(t=this.config)!=null&&t.enableLogging&&console.log("🚫 SocketManager: Conversation block status update",e),(s=this.chatSDK.events)==null||s.emit("conversation.block_status",e)}),this.socket.on("message_read_receipt",e=>{var t,s,a,n;try{(t=this.config)!=null&&t.enableLogging&&console.log("✅ SocketManager: Message read receipt received",e),(s=this.chatSDK.events)==null||s.emit("message.read.receipt",e)}catch(o){(a=this.config)!=null&&a.enableLogging&&console.error("❌ SocketManager: Failed to process read receipt",o),(n=this.chatSDK.events)==null||n.emit("message.read.receipt",e)}}),this.socket.on("messages_read_receipt",e=>{var t,s,a,n,o,r,c,l;try{(t=this.config)!=null&&t.enableLogging&&console.log("📥 SocketManager: messages_read_receipt received from server",{roomId:e.roomId,messageIds:e.messageIds,messageCount:(s=e.messageIds)==null?void 0:s.length,readBy:e.readBy,isRead:e.isRead}),(a=this.config)!=null&&a.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")}catch(g){(c=this.config)!=null&&c.enableLogging&&console.error("❌ SocketManager: Failed to process read receipts",g),(l=this.chatSDK.events)==null||l.emit("messages.read.receipt",e)}}))}isConnected(){var e;return((e=this.socket)==null?void 0:e.connected)||!1}getStatus(){return{connected:this.isConnected(),userId:this.currentUserId,rooms:Array.from(this.joinedRooms)}}joinRoom(e){this.joinConversation(e)}leaveRoom(e){this.leaveConversation(e)}emit(e,t){var s,a;this.socket&&this.socket.connected?(this.socket.emit(e,t),(s=this.config)!=null&&s.enableLogging&&console.log("📤 SocketManager: Emitted event:",e,t)):(a=this.config)!=null&&a.enableLogging&&console.warn("⚠️ SocketManager: Cannot emit event - not connected:",e)}on(e,t){var s,a;this.socket?(this.socket.on(e,t),(s=this.config)!=null&&s.enableLogging&&console.log("👂 SocketManager: Listening to event:",e)):(a=this.config)!=null&&a.enableLogging&&console.warn("⚠️ SocketManager: Cannot listen to event - socket not available:",e)}off(e,t){var s;this.socket&&(this.socket.off(e,t),(s=this.config)!=null&&s.enableLogging&&console.log("🔇 SocketManager: Stopped listening to event:",e))}}const re=class re{constructor(){this.config=null,this.isInitialized=!1,this.currentUser=null,this.auth=new Ie(this),this.chatUsers=new it(this),this.users=new je(this),this.conversations=new Ae(this),this.messages=new Te(this),this.media=new Ne(this),this.events=new Ke(this),this.socket=new ze(this)}static getInstance(){return re.instance||(re.instance=new re),re.instance}async init(e){try{this.config={enableLogging:!0,autoConnect:!0,timeout:3e4,...e},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()}catch(t){throw console.error("❌ ChatSDK: Initialization failed",t),new Error(`ChatSDK initialization failed: ${t}`)}}async connect(e){var t,s;this.ensureInitialized();try{let a;e?(console.log("🔌 ChatSDK: Using provided userId for connection:",e),a={id:e,externalUserId:e,appId:process.env.REACT_APP_APP_ID||"",name:"Chat User",email:`${e}@example.com`,status:"online",isOnline:!0,isRegistered:!0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},this.currentUser=a):(a=await this.auth.getCurrentUser(),this.currentUser=a),await this.events.connect();try{console.log("🔌 ChatSDK: Attempting WebSocket connection for user:",a.id),await this.socket.connect(a.id),console.log("✅ ChatSDK: WebSocket connected successfully")}catch(n){console.warn("⚠️ ChatSDK: WebSocket connection failed, continuing without real-time features:",n)}return(t=this.config)!=null&&t.enableLogging&&console.log("🔗 ChatSDK: Connected successfully",a),a}catch(a){throw(s=this.config)!=null&&s.enableLogging&&console.error("❌ ChatSDK: Connection failed",a),await this.auth.logout(),this.currentUser=null,a}}async disconnect(){var e;try{await this.events.disconnect(),this.socket.disconnect(),this.currentUser=null,(e=this.config)!=null&&e.enableLogging&&console.log("🔌 ChatSDK: Disconnected")}catch(t){throw console.error("❌ ChatSDK: Disconnect failed",t),t}}async login(e,t){return this.ensureInitialized(),await this.auth.login(e,t)}async register(e,t,s,a){return this.ensureInitialized(),await this.auth.register(e,t,s,a)}async logout(){this.ensureInitialized(),await this.auth.logout(),await this.disconnect()}getCurrentUser(){return this.currentUser}isSDKInitialized(){return this.isInitialized}getConfig(){return this.config}setLogging(e){this.config&&(this.config.enableLogging=e)}getVersion(){return"1.0.0"}ensureInitialized(){if(!this.isInitialized)throw new Error("ChatSDK not initialized. Call ChatSDK.init() first.")}};re.instance=null;let T=re;T.getInstance();const ct=Object.freeze(Object.defineProperty({__proto__:null,ChatSDK:T},Symbol.toStringTag,{value:"Module"}));let lt={data:""},dt=i=>typeof window=="object"?((i?i.querySelector("#_goober"):window._goober)||Object.assign((i||document.head).appendChild(document.createElement("style")),{innerHTML:" ",id:"_goober"})).firstChild:i||lt,gt=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,ht=/\/\*[^]*?\*\/| +/g,Ue=/\n+/g,te=(i,e)=>{let t="",s="",a="";for(let n in i){let o=i[n];n[0]=="@"?n[1]=="i"?t=n+" "+o+";":s+=n[1]=="f"?te(o,n):n+"{"+te(o,n[1]=="k"?"":e)+"}":typeof o=="object"?s+=te(o,e?e.replace(/([^,])+/g,r=>n.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,c=>/&/.test(c)?c.replace(/&/g,r):r?r+" "+c:c)):n):o!=null&&(n=/^--/.test(n)?n:n.replace(/[A-Z]/g,"-$&").toLowerCase(),a+=te.p?te.p(n,o):n+":"+o+";")}return t+(e&&a?e+"{"+a+"}":a)+s},Q={},Re=i=>{if(typeof i=="object"){let e="";for(let t in i)e+=t+Re(i[t]);return e}return i},ut=(i,e,t,s,a)=>{let n=Re(i),o=Q[n]||(Q[n]=(c=>{let l=0,g=11;for(;l<c.length;)g=101*g+c.charCodeAt(l++)>>>0;return"go"+g})(n));if(!Q[o]){let c=n!==i?i:(l=>{let g,u,m=[{}];for(;g=gt.exec(l.replace(ht,""));)g[4]?m.shift():g[3]?(u=g[3].replace(Ue," ").trim(),m.unshift(m[0][u]=m[0][u]||{})):m[0][g[1]]=g[2].replace(Ue," ").trim();return m[0]})(i);Q[o]=te(a?{["@keyframes "+o]:c}:c,t?"":"."+o)}let r=t&&Q.g?Q.g:null;return t&&(Q.g=Q[o]),((c,l,g,u)=>{u?l.data=l.data.replace(u,c):l.data.indexOf(c)===-1&&(l.data=g?c+l.data:l.data+c)})(Q[o],e,s,r),o},mt=(i,e,t)=>i.reduce((s,a,n)=>{let o=e[n];if(o&&o.call){let r=o(t),c=r&&r.props&&r.props.className||/^go/.test(r)&&r;o=c?"."+c:r&&typeof r=="object"?r.props?"":te(r,""):r===!1?"":r}return s+a+(o??"")},"");function me(i){let e=this||{},t=i.call?i(e.p):i;return ut(t.unshift?t.raw?mt(t,[].slice.call(arguments,1),e.p):t.reduce((s,a)=>Object.assign(s,a&&a.call?a(e.p):a),{}):t,dt(e.target),e.g,e.o,e.k)}let Be,ye,ve;me.bind({g:1});let Z=me.bind({k:1});function ft(i,e,t,s){te.p=e,Be=i,ye=t,ve=s}function se(i,e){let t=this||{};return function(){let s=arguments;function a(n,o){let r=Object.assign({},n),c=r.className||a.className;t.p=Object.assign({theme:ye&&ye()},r),t.o=/ *go\d+/.test(c),r.className=me.apply(t,s)+(c?" "+c:"");let l=i;return i[0]&&(l=r.as||i,delete r.as),ve&&l[0]&&ve(r),Be(l,r)}return a}}var pt=i=>typeof i=="function",be=(i,e)=>pt(i)?i(e):i,wt=(()=>{let i=0;return()=>(++i).toString()})(),kt=(()=>{let i;return()=>{if(i===void 0&&typeof window<"u"){let e=matchMedia("(prefers-reduced-motion: reduce)");i=!e||e.matches}return i}})(),yt=20,Pe=(i,e)=>{switch(e.type){case 0:return{...i,toasts:[e.toast,...i.toasts].slice(0,yt)};case 1:return{...i,toasts:i.toasts.map(n=>n.id===e.toast.id?{...n,...e.toast}:n)};case 2:let{toast:t}=e;return Pe(i,{type:i.toasts.find(n=>n.id===t.id)?1:0,toast:t});case 3:let{toastId:s}=e;return{...i,toasts:i.toasts.map(n=>n.id===s||s===void 0?{...n,dismissed:!0,visible:!1}:n)};case 4:return e.toastId===void 0?{...i,toasts:[]}:{...i,toasts:i.toasts.filter(n=>n.id!==e.toastId)};case 5:return{...i,pausedAt:e.time};case 6:let a=e.time-(i.pausedAt||0);return{...i,pausedAt:void 0,toasts:i.toasts.map(n=>({...n,pauseDuration:n.pauseDuration+a}))}}},vt=[],we={toasts:[],pausedAt:void 0},Me=i=>{we=Pe(we,i),vt.forEach(e=>{e(we)})},bt=(i,e="blank",t)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:e,ariaProps:{role:"status","aria-live":"polite"},message:i,pauseDuration:0,...t,id:(t==null?void 0:t.id)||wt()}),ge=i=>(e,t)=>{let s=bt(e,i,t);return Me({type:2,toast:s}),s.id},q=(i,e)=>ge("blank")(i,e);q.error=ge("error");q.success=ge("success");q.loading=ge("loading");q.custom=ge("custom");q.dismiss=i=>{Me({type:3,toastId:i})};q.remove=i=>Me({type:4,toastId:i});q.promise=(i,e,t)=>{let s=q.loading(e.loading,{...t,...t==null?void 0:t.loading});return typeof i=="function"&&(i=i()),i.then(a=>{let n=e.success?be(e.success,a):void 0;return n?q.success(n,{id:s,...t,...t==null?void 0:t.success}):q.dismiss(s),a}).catch(a=>{let n=e.error?be(e.error,a):void 0;n?q.error(n,{id:s,...t,...t==null?void 0:t.error}):q.dismiss(s)}),i};var Mt=Z`
2
2
  from {
3
3
  transform: scale(0) rotate(45deg);
4
4
  opacity: 0;
@@ -6,7 +6,7 @@ from {
6
6
  to {
7
7
  transform: scale(1) rotate(45deg);
8
8
  opacity: 1;
9
- }`,vt=Z`
9
+ }`,Ct=Z`
10
10
  from {
11
11
  transform: scale(0);
12
12
  opacity: 0;
@@ -14,7 +14,7 @@ from {
14
14
  to {
15
15
  transform: scale(1);
16
16
  opacity: 1;
17
- }`,yt=Z`
17
+ }`,St=Z`
18
18
  from {
19
19
  transform: scale(0) rotate(90deg);
20
20
  opacity: 0;
@@ -22,28 +22,28 @@ from {
22
22
  to {
23
23
  transform: scale(1) rotate(90deg);
24
24
  opacity: 1;
25
- }`,bt=se("div")`
25
+ }`,_t=se("div")`
26
26
  width: 20px;
27
27
  opacity: 0;
28
28
  height: 20px;
29
29
  border-radius: 10px;
30
- background: ${c=>c.primary||"#ff4b4b"};
30
+ background: ${i=>i.primary||"#ff4b4b"};
31
31
  position: relative;
32
32
  transform: rotate(45deg);
33
33
 
34
- animation: ${kt} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
34
+ animation: ${Mt} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
35
35
  forwards;
36
36
  animation-delay: 100ms;
37
37
 
38
38
  &:after,
39
39
  &:before {
40
40
  content: '';
41
- animation: ${vt} 0.15s ease-out forwards;
41
+ animation: ${Ct} 0.15s ease-out forwards;
42
42
  animation-delay: 150ms;
43
43
  position: absolute;
44
44
  border-radius: 3px;
45
45
  opacity: 0;
46
- background: ${c=>c.secondary||"#fff"};
46
+ background: ${i=>i.secondary||"#fff"};
47
47
  bottom: 9px;
48
48
  left: 4px;
49
49
  height: 2px;
@@ -51,27 +51,27 @@ to {
51
51
  }
52
52
 
53
53
  &:before {
54
- animation: ${yt} 0.15s ease-out forwards;
54
+ animation: ${St} 0.15s ease-out forwards;
55
55
  animation-delay: 180ms;
56
56
  transform: rotate(90deg);
57
57
  }
58
- `,Mt=Z`
58
+ `,Lt=Z`
59
59
  from {
60
60
  transform: rotate(0deg);
61
61
  }
62
62
  to {
63
63
  transform: rotate(360deg);
64
64
  }
65
- `,Ct=se("div")`
65
+ `,xt=se("div")`
66
66
  width: 12px;
67
67
  height: 12px;
68
68
  box-sizing: border-box;
69
69
  border: 2px solid;
70
70
  border-radius: 100%;
71
- border-color: ${c=>c.secondary||"#e0e0e0"};
72
- border-right-color: ${c=>c.primary||"#616161"};
73
- animation: ${Mt} 1s linear infinite;
74
- `,St=Z`
71
+ border-color: ${i=>i.secondary||"#e0e0e0"};
72
+ border-right-color: ${i=>i.primary||"#616161"};
73
+ animation: ${Lt} 1s linear infinite;
74
+ `,Et=Z`
75
75
  from {
76
76
  transform: scale(0) rotate(45deg);
77
77
  opacity: 0;
@@ -79,7 +79,7 @@ from {
79
79
  to {
80
80
  transform: scale(1) rotate(45deg);
81
81
  opacity: 1;
82
- }`,_t=Z`
82
+ }`,Dt=Z`
83
83
  0% {
84
84
  height: 0;
85
85
  width: 0;
@@ -93,43 +93,43 @@ to {
93
93
  100% {
94
94
  opacity: 1;
95
95
  height: 10px;
96
- }`,Lt=se("div")`
96
+ }`,Ut=se("div")`
97
97
  width: 20px;
98
98
  opacity: 0;
99
99
  height: 20px;
100
100
  border-radius: 10px;
101
- background: ${c=>c.primary||"#61d345"};
101
+ background: ${i=>i.primary||"#61d345"};
102
102
  position: relative;
103
103
  transform: rotate(45deg);
104
104
 
105
- animation: ${St} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
105
+ animation: ${Et} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
106
106
  forwards;
107
107
  animation-delay: 100ms;
108
108
  &:after {
109
109
  content: '';
110
110
  box-sizing: border-box;
111
- animation: ${_t} 0.2s ease-out forwards;
111
+ animation: ${Dt} 0.2s ease-out forwards;
112
112
  opacity: 0;
113
113
  animation-delay: 200ms;
114
114
  position: absolute;
115
115
  border-right: 2px solid;
116
116
  border-bottom: 2px solid;
117
- border-color: ${c=>c.secondary||"#fff"};
117
+ border-color: ${i=>i.secondary||"#fff"};
118
118
  bottom: 6px;
119
119
  left: 6px;
120
120
  height: 10px;
121
121
  width: 6px;
122
122
  }
123
- `,xt=se("div")`
123
+ `,Ft=se("div")`
124
124
  position: absolute;
125
- `,Et=se("div")`
125
+ `,It=se("div")`
126
126
  position: relative;
127
127
  display: flex;
128
128
  justify-content: center;
129
129
  align-items: center;
130
130
  min-width: 20px;
131
131
  min-height: 20px;
132
- `,Dt=Z`
132
+ `,jt=Z`
133
133
  from {
134
134
  transform: scale(0.6);
135
135
  opacity: 0.4;
@@ -137,20 +137,20 @@ from {
137
137
  to {
138
138
  transform: scale(1);
139
139
  opacity: 1;
140
- }`,Ut=se("div")`
140
+ }`,At=se("div")`
141
141
  position: relative;
142
142
  transform: scale(0.6);
143
143
  opacity: 0.4;
144
144
  min-width: 20px;
145
- animation: ${Dt} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275)
145
+ animation: ${jt} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275)
146
146
  forwards;
147
- `,Ft=({toast:c})=>{let{icon:e,type:t,iconTheme:s}=c;return e!==void 0?typeof e=="string"?W.createElement(Ut,null,e):e:t==="blank"?null:W.createElement(Et,null,W.createElement(Ct,{...s}),t!=="loading"&&W.createElement(xt,null,t==="error"?W.createElement(bt,{...s}):W.createElement(Lt,{...s})))},It=c=>`
148
- 0% {transform: translate3d(0,${c*-200}%,0) scale(.6); opacity:.5;}
147
+ `,Tt=({toast:i})=>{let{icon:e,type:t,iconTheme:s}=i;return e!==void 0?typeof e=="string"?W.createElement(At,null,e):e:t==="blank"?null:W.createElement(It,null,W.createElement(xt,{...s}),t!=="loading"&&W.createElement(Ft,null,t==="error"?W.createElement(_t,{...s}):W.createElement(Ut,{...s})))},Nt=i=>`
148
+ 0% {transform: translate3d(0,${i*-200}%,0) scale(.6); opacity:.5;}
149
149
  100% {transform: translate3d(0,0,0) scale(1); opacity:1;}
150
- `,jt=c=>`
150
+ `,Kt=i=>`
151
151
  0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;}
152
- 100% {transform: translate3d(0,${c*-150}%,-1px) scale(.6); opacity:0;}
153
- `,At="0%{opacity:0;} 100%{opacity:1;}",Tt="0%{opacity:1;} 100%{opacity:0;}",Nt=se("div")`
152
+ 100% {transform: translate3d(0,${i*-150}%,-1px) scale(.6); opacity:0;}
153
+ `,zt="0%{opacity:0;} 100%{opacity:1;}",Rt="0%{opacity:1;} 100%{opacity:0;}",Bt=se("div")`
154
154
  display: flex;
155
155
  align-items: center;
156
156
  background: #fff;
@@ -162,23 +162,23 @@ to {
162
162
  pointer-events: auto;
163
163
  padding: 8px 10px;
164
164
  border-radius: 8px;
165
- `,Kt=se("div")`
165
+ `,Pt=se("div")`
166
166
  display: flex;
167
167
  justify-content: center;
168
168
  margin: 4px 10px;
169
169
  color: inherit;
170
170
  flex: 1 1 auto;
171
171
  white-space: pre-line;
172
- `,zt=(c,e)=>{let t=c.includes("top")?1:-1,[s,a]=mt()?[At,Tt]:[It(t),jt(t)];return{animation:e?`${Z(s)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`:`${Z(a)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`}};W.memo(({toast:c,position:e,style:t,children:s})=>{let a=c.height?zt(c.position||e||"top-center",c.visible):{opacity:0},n=W.createElement(Ft,{toast:c}),o=W.createElement(Kt,{...c.ariaProps},ke(c.message,c));return W.createElement(Nt,{className:c.className,style:{...a,...t,...c.style}},typeof s=="function"?s({icon:n,message:o}):W.createElement(W.Fragment,null,n,o))});gt(W.createElement);ge`
172
+ `,$t=(i,e)=>{let t=i.includes("top")?1:-1,[s,a]=kt()?[zt,Rt]:[Nt(t),Kt(t)];return{animation:e?`${Z(s)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`:`${Z(a)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`}};W.memo(({toast:i,position:e,style:t,children:s})=>{let a=i.height?$t(i.position||e||"top-center",i.visible):{opacity:0},n=W.createElement(Tt,{toast:i}),o=W.createElement(Pt,{...i.ariaProps},be(i.message,i));return W.createElement(Bt,{className:i.className,style:{...a,...t,...i.style}},typeof s=="function"?s({icon:n,message:o}):W.createElement(W.Fragment,null,n,o))});ft(W.createElement);me`
173
173
  z-index: 9999;
174
174
  > * {
175
175
  pointer-events: auto;
176
176
  }
177
- `;var K=q;const Rt={send:"Send",conversations_title:"Chats",no_conversations_title:"No conversations yet",no_conversations_message:"Start chatting with product owners to see conversations here",loading_conversations:"Loading conversations...",error_load_conversations:"Failed to load conversations",select_conversation:"Select a conversation",select_conversation_message:"Choose a conversation from the list to start chatting",select_conversation_tip:"💡 Tip: Click on any conversation in the sidebar to open it here",message_hint:"Start typing a message",attach_file:"Attach file",loading_messages:"Loading messages...",file_sent_successfully:"File uploaded and sent!",uploading:"Uploading...",sent:"Sent",read:"Read",error_load_messages:"Failed to load messages",error_send_message:"Failed to send message",error_file_upload:"Failed to upload file",error_unknown:"Unknown error",error_user_blocked:"Your account has been blocked by administrator",error_registration_failed:"Registration failed. Please try again.",login_successful:"Login successful!",registration_successful:"Registration and login successful!",complete_profile_info:"Please complete your profile information.",block_user:"Block User",unblock_user:"Unblock",user_blocked:"User blocked",user_unblocked:"User unblocked",block_user_confirm:"Are you sure you want to block this user?",unblock_user_confirm:"Are you sure you want to unblock this user?",you_are_blocked:"You have been blocked in this chat",you_have_blocked:"You've blocked {{userName}}",you_have_blocked_submessage:"You can't message them in this chat, and you won't receive their messages.",blocked_by_user:"You have been blocked by {{userName}}",blocked_by_user_submessage:"You can't send messages in this chat.",user_is_blocked:"This user is blocked in this chat",failed_to_block:"Failed to block user",failed_to_unblock:"Failed to unblock user",user_not_found:"User not found",user_id_not_found:"User ID not found",cannot_block_self:"You cannot block yourself",loading:"Loading...",unknown_user:"Unknown User",image:"Image",file:"File",no_messages_yet:"No messages yet",yesterday:"Yesterday",unknown_size:"Unknown size",download:"Download",search:"Search",back:"Back",call:"Call",options:"Options",close:"Close",no_phone_number:"No phone number available",number_copied:"Phone number copied to clipboard",no_search_results:"No conversations found",demo_title:"ChatSDK Demo",welcome:"Welcome",logout:"Logout",products:"Products",all_products:"All Products",my_products:"My Products",conversations:"Conversations",sdk_tester:"SDK Tester",sdk_tester_desc:"SDK testing tools will be available here",loading_products:"Loading products...",no_products_listed:"You haven't listed any products yet.",realtime_active:"Real-time Chat Active",http_only:"HTTP Only",failed_to_load_products:"Failed to load products",failed_to_start_chat:"Failed to start chat",cannot_chat_self:"You cannot start a chat with yourself!",starting_chat:"Starting chat with product owner...",chat_opened:"Chat popup opened!",failed_init:"Failed to initialize app",login:"Login",login_as:"Login as",checking:"Checking...",registering:"Registering...",complete_registration:"Complete Registration",back_to_login:"Back to Login",quick_demo_login:"Quick Demo Login (with sample conversations):",external_user_id:"External User ID:",app_id_label:"App ID:",full_name:"Full Name:",email_label:"Email:",welcome_demo:"Welcome to the ChatSDK Demo Application",enter_user_id:"Enter your user ID (e.g., user1)",enter_app_id:"Enter app ID",enter_full_name:"Enter your full name",enter_email:"Enter your email",chat_with_owner:"Chat with Owner",your_product:"Your Product",owner_label:"Owner:"},Bt={send:"إرسال",conversations_title:"الدردشة",no_conversations_title:"لا توجد محادثات بعد",no_conversations_message:"ابدأ الدردشة مع مالكي المنتجات لمشاهدة محادثاتك هنا",loading_conversations:"جاري تحميل المحادثات...",error_load_conversations:"فشل تحميل المحادثات",select_conversation:"اختر محادثة",select_conversation_message:"اختر محادثة من القائمة لبدء الدردشة",select_conversation_tip:"💡 نصيحة: انقر على أي محادثة في الشريط الجانبي لفتحها هنا",message_hint:"اكتب رسالة هنا",attach_file:"إرفاق ملف",loading_messages:"جاري تحميل الرسائل...",file_sent_successfully:"تم إرسال الملف بنجاح!",uploading:"جاري الرفع...",sent:"تم الإرسال",read:"تم القراءة",error_load_messages:"فشل تحميل الرسائل",error_send_message:"فشل إرسال الرسالة",error_file_upload:"فشل رفع الملف",error_unknown:"خطأ غير معروف",error_user_blocked:"تم حظر حسابك من قبل المسؤول",error_registration_failed:"فشل التسجيل. يرجى المحاولة مرة أخرى.",login_successful:"تم تسجيل الدخول بنجاح!",registration_successful:"تم التسجيل وتسجيل الدخول بنجاح!",complete_profile_info:"يرجى إكمال معلومات ملفك الشخصي.",block_user:"حظر المستخدم",unblock_user:"إلغاء الحظر",user_blocked:"تم حظر المستخدم",user_unblocked:"تم إلغاء حظر المستخدم",block_user_confirm:"هل أنت متأكد أنك تريد حظر هذا المستخدم؟",unblock_user_confirm:"هل أنت متأكد أنك تريد إلغاء حظر هذا المستخدم؟",you_are_blocked:"تم حظرك في هذه المحادثة",you_have_blocked:"لقد قمت بحظر {{userName}}",you_have_blocked_submessage:"لا يمكنك مراسلتهم في هذه المحادثة، ولن تتلقى رسائلهم.",blocked_by_user:"تم حظرك من قبل {{userName}}",blocked_by_user_submessage:"لا يمكنك إرسال الرسائل في هذه المحادثة.",user_is_blocked:"هذا المستخدم محظور في هذه المحادثة",failed_to_block:"فشل حظر المستخدم",failed_to_unblock:"فشل إلغاء حظر المستخدم",user_not_found:"المستخدم غير موجود",user_id_not_found:"معرف المستخدم غير موجود",cannot_block_self:"لا يمكنك حظر نفسك",loading:"جاري التحميل...",unknown_user:"مستخدم غير معروف",image:"صورة",file:"ملف",no_messages_yet:"لا توجد رسائل بعد",yesterday:"أمس",unknown_size:"حجم غير معروف",download:"تنزيل",search:"بحث",back:"رجوع",call:"اتصال",options:"خيارات",close:"إغلاق",no_phone_number:"لا يوجد رقم هاتف متاح",number_copied:"تم نسخ رقم الهاتف",no_search_results:"لم يتم العثور على محادثات",demo_title:"عرض ChatSDK",welcome:"مرحبًا",logout:"تسجيل الخروج",products:"المنتجات",all_products:"كل المنتجات",my_products:"منتجاتي",conversations:"المحادثات",sdk_tester:"اختبار SDK",sdk_tester_desc:"ستتوفر أدوات اختبار SDK هنا",loading_products:"جاري تحميل المنتجات...",no_products_listed:"لم تقم بنشر أي منتجات بعد.",realtime_active:"الدردشة المباشرة نشطة",http_only:"HTTP فقط",failed_to_load_products:"فشل تحميل المنتجات",failed_to_start_chat:"فشل بدء الدردشة",cannot_chat_self:"لا يمكنك بدء محادثة مع نفسك!",starting_chat:"جاري بدء الدردشة مع مالك المنتج...",chat_opened:"تم فتح نافذة الدردشة!",failed_init:"فشل تهيئة التطبيق",login:"تسجيل الدخول",login_as:"تسجيل الدخول كـ",checking:"جاري التحقق...",registering:"جاري التسجيل...",complete_registration:"إكمال التسجيل",back_to_login:"العودة لتسجيل الدخول",quick_demo_login:"تسجيل دخول سريع (مع محادثات تجريبية):",external_user_id:"معرف المستخدم الخارجي:",app_id_label:"معرف التطبيق:",full_name:"الاسم الكامل:",email_label:"البريد الإلكتروني:",welcome_demo:"مرحبًا بك في تطبيق عرض ChatSDK",enter_user_id:"أدخل معرف المستخدم (مثل user1)",enter_app_id:"أدخل معرف التطبيق",enter_full_name:"أدخل اسمك الكامل",enter_email:"أدخل بريدك الإلكتروني",chat_with_owner:"الدردشة مع المالك",your_product:"منتجك",owner_label:"المالك:"},ve={en:Rt,ar:Bt};let le="en";const ye=c=>{ve[c]?(le=c,document.documentElement.lang=c,document.documentElement.dir=Re()?"rtl":"ltr",localStorage.setItem("chatSDK_language",c)):(console.warn(`Locale "${c}" not found, falling back to "en".`),le="en",document.documentElement.lang="en",document.documentElement.dir="ltr")},Pt=()=>le,Re=()=>le==="ar",w=(c,e)=>{let t=ve[le][c]||ve.en[c]||c;if(e)for(const s in e)t=t.replace(new RegExp(`{{${s}}}`,"g"),String(e[s]));return t},Ee=localStorage.getItem("chatSDK_language");ye(Ee||"en");const $t=({conversation:c,currentUser:e,onClose:t,onBack:s})=>{var Se;const[a,n]=M.useState([]),[o,r]=M.useState(""),[i,l]=M.useState(!1),[g,u]=M.useState(!1),[m,p]=M.useState({}),[x,B]=M.useState(!1),[Me,ce]=M.useState(!0),[v,C]=M.useState(1),[P,V]=M.useState(null),[z,H]=M.useState(!1),[E,U]=M.useState(!1),[A,j]=M.useState(!1),[N,$]=M.useState(null),[X,ee]=M.useState(!1),Y=M.useRef(null),oe=M.useRef(null),R=M.useRef(null),G=M.useRef(null),ae=20,ne=M.useCallback(()=>{if(!c||!e)return null;const h=c.participants||[];if(h.length===0)return null;const f=e.id||e.userId,b=e.externalUserId||e.external_user_id;return h.find(y=>{const _=y.id||y.userId,k=y.externalUserId||y.external_user_id;return!(f&&_&&_===f||b&&k&&k===b)&&(_||k)})||null},[c,e]),D=ne(),O=M.useCallback(()=>{if(!c)return{userName:w("conversations_title"),productName:null,productImage:null,productMetadata:null};const h=D&&(D.name||D.userName||D.displayName||D.externalUserId)||w("unknown_user"),f=c.productContext||c.product_context;return f?{userName:h,productName:f.productName||f.product_name,productImage:f.productImage||f.product_image,productId:f.productId||f.product_id,productMetadata:f.productMetadata||f.product_metadata}:{userName:h,productName:null,productImage:null,productMetadata:null}},[c,D])();M.useEffect(()=>(c&&(j(!1),Qe(1,!1),Oe(),T.getInstance().chatUsers.startViewingConversation(c.id)),()=>{c&&(We(),T.getInstance().chatUsers.stopViewingConversation(c.id))}),[c]),M.useEffect(()=>{const h=T.getInstance(),f=k=>{const S=k.message;S.roomId===(c==null?void 0:c.id)&&n(F=>F.some(L=>L.id===S.id)?F:(S.senderId!==e.id&&h.chatUsers.markMessageRead(S.id).catch(L=>{console.warn("ChatWindow: Failed to mark message as read:",L)}),[...F,{id:S.id,content:S.content,senderId:S.senderId,senderName:S.senderName,timestamp:S.createdAt||S.timestamp,conversationId:S.roomId,type:S.messageType||S.type||"text",metadata:S.metadata||void 0,isRead:S.isRead!==void 0?S.isRead:S.senderId!==e.id,isDelivered:S.isDelivered!==void 0?S.isDelivered:!0,status:S.status||"sent"}]))},b=k=>{!k.messageId||k.roomId!==(c==null?void 0:c.id)||n(S=>S.map(F=>F.id===k.messageId&&F.senderId===e.id?{...F,isRead:k.isRead}:F))},y=k=>{if(k.roomId!==(c==null?void 0:c.id))return;const S=e==null?void 0:e.id;if(!k.messageIds||k.messageIds.length===0){n(I=>I.map(L=>L.senderId===S&&!L.isRead?{...L,isRead:k.isRead}:L));return}const F=new Set(k.messageIds);n(I=>I.map(L=>F.has(L.id)&&L.senderId===S?{...L,isRead:k.isRead}:L))},_=k=>{if(!c||((k==null?void 0:k.conversationId)||(k==null?void 0:k.chatId)||(k==null?void 0:k.roomId))!==c.id)return;const F=(k==null?void 0:k.blockedUsers)||{};c.metadata={...c.metadata||{},blockedUsers:F};const I=e.id||e.userId,L=ne(),J=L?L.id||L.userId||L.externalUserId||L.external_user_id:null;H(F[I]===1),U(J?F[J]===1:!1)};return h.events.on("message.received",f),h.events.on("message.read.receipt",b),h.events.on("messages.read.receipt",y),h.events.on("conversation.block_status",_),()=>{h.events.off("message.received",f),h.events.off("message.read.receipt",b),h.events.off("messages.read.receipt",y),h.events.off("conversation.block_status",_)}},[c==null?void 0:c.id,e==null?void 0:e.id]),M.useEffect(()=>{if(!c||!e){H(!1),U(!1),V(null);return}const f=(c.metadata||{}).blockedUsers||{},b=e.id||e.userId,y=ne(),_=y?y.id||y.userId||y.externalUserId||y.external_user_id:null;H(f[b]===1),U(_?f[_]===1:!1),V({chatId:c.id,currentUserId:b,isBlockedByOther:f[b]===1,usersBlockedByMe:Object.keys(f).filter(k=>f[k]===1),blockedUsers:f})},[c==null?void 0:c.id,JSON.stringify(c==null?void 0:c.metadata),e==null?void 0:e.id]),M.useEffect(()=>{qe()},[a]),M.useEffect(()=>{const h=f=>{f.target.closest(".chat-options-wrapper")||j(!1)};return document.addEventListener("click",h),()=>{document.removeEventListener("click",h),G.current&&clearTimeout(G.current)}},[]);const Oe=()=>{c&&T.getInstance().socket.joinRoom(c.id)},We=()=>{c&&T.getInstance().socket.leaveRoom(c.id)},qe=()=>{var h;(h=Y.current)==null||h.scrollIntoView({behavior:"smooth"})},Ve=h=>new Date(h).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),ue=h=>{const f=new Date(h),b=new Date,y=new Date(b.getFullYear(),b.getMonth(),b.getDate()),_=new Date(f.getFullYear(),f.getMonth(),f.getDate()),k=Math.floor((y.getTime()-_.getTime())/(1e3*60*60*24));if(k===0)return"Today";if(k===1)return"Yesterday";const S=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],F=f.getDate().toString().padStart(2,"0"),I=(f.getMonth()+1).toString().padStart(2,"0");return k<7?`${S[f.getDay()]}, ${F}/${I}`:`${F}/${I}/${f.getFullYear()}`},Ge=(h,f)=>{if(f===0)return!0;const b=a[f-1],y=new Date(b.timestamp).toDateString(),_=new Date(h.timestamp).toDateString();return y!==_},He=h=>h?h.includes("pdf")?"📄":h.includes("word")?"📝":h.includes("excel")?"📊":h.includes("audio")?"🎵":h.includes("video")?"🎥":"📎":"📎",Ye=()=>{if(!R.current)return;const h=R.current,f=h.querySelectorAll(".date-divider[data-date]");if(f.length===0)return;let b=null;const y=h.getBoundingClientRect().top;for(let _=f.length-1;_>=0;_--){const k=f[_];if(k.getBoundingClientRect().top<=y+50){b=k.getAttribute("data-date");break}}!b&&a.length>0&&(b=ue(a[0].timestamp)),b&&($(b),ee(!0),G.current&&clearTimeout(G.current),G.current=setTimeout(()=>{ee(!1)},2e3))},Je=()=>{if(!D)return;const h=D,f=h.phone||h.phoneNumber||h.mobile||h.externalUserId||"";if(!f){K.error(w("no_phone_number")||"No phone number available");return}/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?window.location.href=`tel:${f}`:navigator.clipboard.writeText(f).then(()=>{K.success(w("number_copied")||`Phone number copied: ${f}`)}).catch(()=>{const y=document.createElement("textarea");y.value=f,document.body.appendChild(y),y.select(),document.execCommand("copy"),document.body.removeChild(y),K.success(w("number_copied")||`Phone number copied: ${f}`)})},Qe=async(h=1,f=!1)=>{if(c){h===1?(l(!0),n([]),C(1),ce(!0)):B(!0);try{const y=await T.getInstance().messages.getMessages({conversationId:c.id,limit:ae,offset:(h-1)*ae}),_=y.sort((k,S)=>new Date(k.timestamp).getTime()-new Date(S.timestamp).getTime());f&&h>1?n(k=>[..._,...k]):n(_),ce(y.length===ae),C(h)}catch{K.error(w("error_load_messages"))}finally{l(!1),B(!1)}}},Ze=async h=>{if(h.preventDefault(),!c||!o.trim()||z){z&&K.error(w("you_are_blocked"));return}const f=o.trim();r("");try{await T.getInstance().messages.sendMessage(c.id,f)}catch{r(f),K.error(w("error_send_message"))}},Xe=async h=>{if(!c)return;const f=`temp_${Date.now()}`,b={id:f,conversationId:c.id,senderId:e.id,senderName:e.name,content:`${h.name}`,type:h.type.startsWith("image/")?"image":"file",timestamp:new Date().toISOString(),status:"sending",isRead:!1,isDelivered:!1,isUploading:!0,uploadProgress:0,localFileUri:URL.createObjectURL(h),metadata:{fileName:h.name,fileSize:h.size,mimeType:h.type}};n(y=>[...y,b]),p(y=>({...y,[f]:0}));try{u(!0);const y=T.getInstance(),_=y.media.getFileTypeCategory(h.type),k=await y.media.uploadMedia({file:h,type:_,conversationId:c.id,onProgress:I=>{p(L=>({...L,[f]:I})),n(L=>L.map(J=>J.id===f?{...J,uploadProgress:I}:J))}});p(I=>({...I,[f]:100}));const S=_==="document"?"file":_==="image"?"image":"file",F={fileUrl:k.fileUrl,fileName:k.fileName,fileSize:k.fileSize,mimeType:k.mimeType||h.type};await y.messages.sendMessageWithOptions({conversationId:c.id,content:`${h.name}`,type:S,metadata:F}),setTimeout(()=>{n(I=>I.filter(L=>L.id!==f)),p(I=>{const L={...I};return delete L[f],L})},200),K.success(w("file_sent_successfully"))}catch(y){n(_=>_.filter(k=>k.id!==f)),p(_=>{const k={..._};return delete k[f],k}),K.error(w("error_file_upload")+": "+(y.message||w("error_unknown")))}finally{u(!1)}},et=async()=>{if(j(!1),!(!c||!e)&&window.confirm(w("block_user_confirm")))try{const h=T.getInstance();if(!D){K.error(w("user_not_found"));return}const f=e.id||e.userId,b=D.id||D.userId||D.externalUserId||D.external_user_id;if(!b){K.error(w("user_id_not_found"));return}if(b===f){K.error(w("cannot_block_self"));return}await h.conversations.blockUserInChat(c.id,b);const y=c.metadata||{},_=y.blockedUsers||{};_[b]=1,c&&(c.metadata={...y,blockedUsers:_}),U(!0),K.success(w("user_blocked"))}catch{K.error(w("failed_to_block"))}},Ce=async()=>{if(j(!1),!(!c||!e)&&window.confirm(w("unblock_user_confirm")))try{const h=T.getInstance();if(!D){K.error(w("user_not_found"));return}const f=D.id||D.userId||D.externalUserId||D.external_user_id;if(!f){K.error(w("user_id_not_found"));return}await h.conversations.unblockUserInChat(c.id,f);const b=c.metadata||{},y=b.blockedUsers||{};delete y[f],c&&(c.metadata={...b,blockedUsers:y}),U(!1),K.success(w("user_unblocked"))}catch{K.error(w("failed_to_unblock"))}};return i&&a.length===0?d.jsxs("div",{className:"chat-window",children:[d.jsxs("div",{className:"chat-header",children:[d.jsx("div",{className:"chat-header-left",children:d.jsx("h3",{style:{margin:0},children:w("loading")})}),d.jsx("div",{className:"chat-header-actions",children:t&&d.jsx("button",{onClick:t,className:"close-button",children:"×"})})]}),d.jsx("div",{className:"loading-messages",children:w("loading_messages")})]}):d.jsxs("div",{className:"chat-window",children:[d.jsxs("div",{className:"chat-header",children:[d.jsxs("div",{className:"chat-header-left",children:[s&&d.jsx("button",{className:"chat-back-btn",onClick:s,title:w("back")||"Back",children:d.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:d.jsx("polyline",{points:"15 18 9 12 15 6"})})}),d.jsx("div",{className:"chat-header-avatar",children:d.jsx("div",{className:"avatar-placeholder",children:O.userName?O.userName.charAt(0).toUpperCase():"?"})}),d.jsx("div",{className:"chat-header-info",children:d.jsx("h3",{className:"chat-participant-name",children:O.userName})})]}),d.jsxs("div",{className:"chat-header-actions",children:[D&&d.jsx("button",{onClick:Je,className:"chat-action-btn",title:w("call")||"Call",children:d.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:d.jsx("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"})})}),t&&d.jsx("button",{onClick:t,className:"chat-action-btn",title:w("close")||"Close",children:d.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:d.jsx("path",{d:"M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7"})})}),c&&D&&d.jsxs("div",{className:"chat-options-wrapper",children:[d.jsx("button",{onClick:()=>j(!A),className:"chat-action-btn",title:w("options")||"Options",children:d.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:[d.jsx("circle",{cx:"12",cy:"5",r:"2"}),d.jsx("circle",{cx:"12",cy:"12",r:"2"}),d.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}),A&&d.jsxs("div",{className:"chat-options-menu",children:[!z&&!E&&d.jsxs("button",{onClick:et,className:"danger",children:[d.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[d.jsx("circle",{cx:"12",cy:"12",r:"10"}),d.jsx("line",{x1:"4.93",y1:"4.93",x2:"19.07",y2:"19.07"})]}),w("block_user")]}),E&&d.jsxs("button",{onClick:Ce,children:[d.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[d.jsx("circle",{cx:"12",cy:"12",r:"10"}),d.jsx("path",{d:"M2 12h20"})]}),w("unblock_user")]})]})]})]})]}),O.productName&&d.jsxs("div",{className:"chat-product-bar",children:[O.productImage&&d.jsx("img",{src:O.productImage,alt:O.productName}),d.jsxs("div",{className:"chat-product-bar-info",children:[d.jsx("p",{className:"chat-product-bar-name",children:O.productName}),((Se=O.productMetadata)==null?void 0:Se.price)&&d.jsxs("p",{className:"chat-product-bar-price",children:[O.productMetadata.price," ",O.productMetadata.currency||"QAR"]})]})]}),d.jsxs("div",{className:"chat-messages",ref:R,onScroll:Ye,onClick:()=>j(!1),children:[N&&!i&&a.length>0&&d.jsx("div",{className:`sticky-date-header ${X?"sticky-date-visible":""}`,children:d.jsx("span",{className:"sticky-date-pill",children:N})}),i?d.jsx("div",{className:"loading-messages",children:w("loading_messages")}):d.jsxs(d.Fragment,{children:[a.map((h,f)=>{var b,y,_,k,S,F,I,L,J,_e;return d.jsxs(M.Fragment,{children:[Ge(h,f)&&d.jsxs("div",{className:"date-divider","data-date":ue(h.timestamp),children:[d.jsx("div",{className:"date-divider-line"}),d.jsx("span",{className:"date-divider-text",children:ue(h.timestamp)}),d.jsx("div",{className:"date-divider-line"})]}),d.jsx("div",{className:`message ${h.senderId===e.id?"sent":"received"}`,children:d.jsxs("div",{className:"message-content",children:[h.isUploading&&h.uploadProgress!==void 0&&d.jsx("div",{className:"upload-progress-bar",children:d.jsx("div",{className:"upload-progress-fill",style:{width:`${h.uploadProgress}%`}})}),h.type==="image"&&((b=h.metadata)!=null&&b.fileUrl||h.localFileUri)?d.jsxs("div",{className:"message-attachment image-attachment",children:[d.jsx("img",{src:h.isUploading?h.localFileUri:(y=h.metadata)==null?void 0:y.fileUrl,alt:((_=h.metadata)==null?void 0:_.fileName)||w("image"),className:h.isUploading?"uploading-image":"",onClick:()=>{var Le;return!h.isUploading&&((Le=h.metadata)==null?void 0:Le.fileUrl)&&window.open(h.metadata.fileUrl,"_blank")}}),d.jsxs("div",{className:"attachment-info",children:[((k=h.metadata)==null?void 0:k.fileName)||w("image"),((S=h.metadata)==null?void 0:S.fileSize)&&d.jsxs("span",{children:[" • ",Math.round(h.metadata.fileSize/1024)," KB"]})]})]}):h.type==="file"&&((F=h.metadata)!=null&&F.fileUrl)?d.jsxs("div",{className:"message-attachment file-attachment",children:[d.jsxs("div",{className:"file-info",children:[d.jsx("div",{className:"file-icon",children:He((I=h.metadata)==null?void 0:I.mimeType)}),d.jsxs("div",{className:"file-details",children:[d.jsx("div",{className:"file-name",children:((L=h.metadata)==null?void 0:L.fileName)||w("file")}),d.jsx("div",{className:"file-size",children:(J=h.metadata)!=null&&J.fileSize?`${Math.round(h.metadata.fileSize/1024)} KB`:w("unknown_size")})]})]}),d.jsx("a",{href:((_e=h.metadata)==null?void 0:_e.fileUrl)||"#",target:"_blank",rel:"noopener noreferrer",className:"download-btn",children:w("download")})]}):h.content,d.jsxs("div",{className:"message-footer",children:[d.jsx("span",{className:"message-time",children:Ve(h.timestamp)}),h.senderId===e.id&&d.jsx("span",{className:"message-status",children:d.jsx("span",{className:"read-status",children:h.isRead?d.jsxs("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:[d.jsx("polyline",{points:"1 13 5 17 11 9"}),d.jsx("polyline",{points:"7 13 11 17 17 9"})]}):d.jsx("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:d.jsx("polyline",{points:"4 13 8 17 16 9"})})})})]})]})})]},h.id)}),d.jsx("div",{ref:Y})]})]}),E&&d.jsxs("div",{className:"blocked-ui blocked-by-me",children:[d.jsx("div",{className:"blocked-title",children:w("you_have_blocked",{userName:O.userName||w("unknown_user")})}),d.jsx("div",{className:"blocked-message",children:w("you_have_blocked_submessage")}),d.jsx("button",{onClick:Ce,className:"unblock-btn",children:w("unblock_user")})]}),z&&!E&&d.jsxs("div",{className:"blocked-ui blocked-by-other",children:[d.jsx("div",{className:"blocked-title",children:w("blocked_by_user",{userName:O.userName||w("unknown_user")})}),d.jsx("div",{className:"blocked-message",children:w("blocked_by_user_submessage")})]}),!E&&!z&&d.jsxs("form",{onSubmit:Ze,className:"chat-input",children:[d.jsx("button",{type:"button",onClick:()=>{var h;return(h=oe.current)==null?void 0:h.click()},disabled:i||g||z,className:"attachment-btn",title:w("attach_file"),children:g?d.jsx("span",{children:"⌛"}):d.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:d.jsx("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"})})}),d.jsx("input",{ref:oe,type:"file",style:{display:"none"},accept:"image/*,video/*,audio/*,.pdf,.doc,.docx,.txt",onChange:h=>{var b;const f=(b=h.target.files)==null?void 0:b[0];f&&(Xe(f),h.target.value="")}}),d.jsx("input",{type:"text",value:o,onChange:h=>r(h.target.value),placeholder:w(z?"you_are_blocked":g?"uploading":"message_hint"),disabled:i||g||z}),d.jsx("button",{type:"submit",disabled:!o.trim()||i||g||z,className:"send-btn",children:w(g?"uploading":"send")})]})]})},Ot=({currentUser:c,onSelectConversation:e,selectedConversationId:t})=>{const[s,a]=M.useState([]),[n,o]=M.useState(!1),[r,i]=M.useState(""),l=M.useRef(t),g=M.useRef(c.id);M.useEffect(()=>{l.current=t},[t]),M.useEffect(()=>{g.current=c.id},[c.id]),M.useEffect(()=>{m()},[]),M.useEffect(()=>{c&&(a([]),m())},[c.id]),M.useEffect(()=>{var H;const v=T.getInstance(),C=E=>{const U=E.message,A=U.roomId||U.conversationId;a(j=>j.map(N=>{if(N.id===A){const $=U.senderId!==g.current,X=l.current!==A;return{...N,lastMessage:U,unreadCount:$&&X?N.unreadCount+1:N.unreadCount}}return N}).sort((N,$)=>{var Y,oe;const X=((Y=N.lastMessage)==null?void 0:Y.timestamp)||N.createdAt,ee=((oe=$.lastMessage)==null?void 0:oe.timestamp)||$.createdAt;return new Date(ee).getTime()-new Date(X).getTime()})),U.senderId!==g.current&&l.current===A&&T.getInstance().chatUsers.markMessageRead(U.id).then(()=>{a(N=>N.map($=>$.id===A?{...$,unreadCount:0}:$))}).catch(N=>{console.warn("Failed to auto-mark message as read:",N)})},P=E=>{var N,$,X,ee;const U=E.conversationId||((N=E.conversation)==null?void 0:N.id)||(($=E.conversation)==null?void 0:$.conversationId);if(!U)return;const A=E.lastMessage||((X=E.conversation)==null?void 0:X.lastMessage),j=(ee=E.conversation)==null?void 0:ee.unreadCount;a(Y=>Y.some(R=>R.id===U)?Y.map(R=>{if(R.id!==U)return R;const G=l.current===U,ae=g.current;if(typeof j=="number")return{...R,lastMessage:A||R.lastMessage,unreadCount:G?0:j};const ne=(A==null?void 0:A.senderId)&&A.senderId!==ae,D=!!A&&ne&&!G;return{...R,lastMessage:A||R.lastMessage,unreadCount:G?0:D?R.unreadCount+1:R.unreadCount}}).sort((R,G)=>{var D,he;const ae=((D=R.lastMessage)==null?void 0:D.timestamp)||R.createdAt,ne=((he=G.lastMessage)==null?void 0:he.timestamp)||G.createdAt;return new Date(ne).getTime()-new Date(ae).getTime()}):(m(),Y))},V=E=>{const U=E.conversationId||E.roomId;U&&a(A=>A.map(j=>j.id===U?{...j,unreadCount:0}:j))},z=E=>{const U=E.roomId||E.conversationId;U&&a(A=>A.map(j=>j.id===U?{...j,unreadCount:0}:j))};return v.events.on("message.received",C),v.events.on("conversation.updated",P),v.events.on("conversation.read",V),(H=v.socket)!=null&&H.isConnected()&&(v.socket.on("auto_marked_read",z),v.socket.on("room_marked_read",V)),()=>{var E;v.events.off("message.received",C),v.events.off("conversation.updated",P),v.events.off("conversation.read",V),(E=v.socket)!=null&&E.isConnected()&&(v.socket.off("auto_marked_read",z),v.socket.off("room_marked_read",V))}},[]);const u=async v=>{try{if(v.unreadCount>0){const C=T.getInstance();await C.chatUsers.markRoomMessagesRead(v.id),C.chatUsers.startViewingConversation(v.id)}e(v)}catch(C){console.error("Failed to mark conversation as read:",C),e(v)}},m=async()=>{o(!0);try{const C=await T.getInstance().chatUsers.getConversations();let P=C;C&&typeof C=="object"&&!Array.isArray(C)&&(P=C.conversations||C.data||[]),a(Array.isArray(P)?P:[])}catch{K.error(w("error_load_conversations"))}finally{o(!1)}},p=v=>v.participants.find(C=>C.id!==c.id),x=v=>{const C=p(v);return(C==null?void 0:C.name)||w("unknown_user")},B=v=>{var C;return((C=v.lastMessage)==null?void 0:C.content)||w("no_messages_yet")},Me=v=>{const C=new Date(v),V=(new Date().getTime()-C.getTime())/(1e3*60*60),z=V/24;return V<24?C.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):z<7?`${Math.floor(z)}d ago`:`${C.getDate()} ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][C.getMonth()]}`},ce=r.trim()?s.filter(v=>{var H,E;const C=r.toLowerCase().trim(),P=x(v).toLowerCase(),V=((E=(H=v.productContext)==null?void 0:H.productName)==null?void 0:E.toLowerCase())||"",z=B(v).toLowerCase();return P.includes(C)||V.includes(C)||z.includes(C)}):s;return n?d.jsx("div",{className:"conversation-list loading",children:d.jsx("div",{className:"loading-spinner",children:w("loading_conversations")})}):d.jsxs("div",{className:"conversation-list",children:[d.jsx("div",{className:"conversation-list-header",children:d.jsx("h3",{children:w("conversations_title")})}),d.jsx("div",{className:"conversation-search",children:d.jsxs("div",{className:"conversation-search-input",children:[d.jsx("span",{className:"search-icon",children:d.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx("circle",{cx:"11",cy:"11",r:"8"}),d.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}),d.jsx("input",{value:r,onChange:v=>i(v.target.value),type:"text",placeholder:w("search")||"Search"})]})}),d.jsx("div",{className:"conversations",children:ce.length===0?d.jsxs("div",{className:"empty-conversations",children:[d.jsx("p",{children:r?w("no_search_results")||"No results found":w("no_conversations_title")}),!r&&d.jsx("p",{children:w("no_conversations_message")})]}):ce.map(v=>{var P;const C=t===v.id;return d.jsxs("div",{className:`conversation-item ${C?"selected":""} ${v.unreadCount>0?"has-unread":""}`,onClick:()=>u(v),children:[d.jsx("div",{className:"conversation-avatar",children:(P=v.productContext)!=null&&P.productImage?d.jsx("img",{src:v.productContext.productImage,alt:v.productContext.productName,className:"product-image"}):d.jsx("div",{className:"avatar-placeholder",children:x(v).charAt(0).toUpperCase()})}),d.jsxs("div",{className:"conversation-content",children:[d.jsxs("div",{className:"conversation-header",children:[d.jsx("div",{className:"conversation-title-wrapper",children:d.jsx("h4",{className:"conversation-participant-name",children:x(v)})}),v.lastMessage&&d.jsx("span",{className:"conversation-time",children:Me(v.lastMessage.timestamp)})]}),d.jsxs("div",{className:"conversation-details",children:[d.jsx("p",{className:"conversation-last-message",children:B(v)}),v.unreadCount>0&&d.jsx("span",{className:"unread-badge",children:v.unreadCount})]})]})]},v.id)})})]})},Be=()=>{const[c,e]=M.useState(()=>typeof window<"u"&&localStorage.getItem("chatSDK-theme")||"auto"),[t,s]=M.useState(()=>typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),a=c==="auto"?t:c;M.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const r=window.matchMedia("(prefers-color-scheme: dark)"),i=l=>{s(l.matches?"dark":"light")};return r.addEventListener("change",i),()=>r.removeEventListener("change",i)},[]),M.useEffect(()=>{if(typeof window>"u")return;const r=document.documentElement;r.classList.remove("theme-light","theme-dark"),r.removeAttribute("data-theme"),r.classList.add(`theme-${a}`),r.setAttribute("data-theme",a)},[a]);const n=r=>{e(r),typeof window<"u"&&localStorage.setItem("chatSDK-theme",r)};return{theme:c,actualTheme:a,setTheme:n,toggleTheme:()=>{n(c==="auto"?t==="light"?"dark":"light":a==="light"?"dark":"light")}}},Pe=M.createContext(void 0),Wt=({children:c})=>{const e=Be();return d.jsx(Pe.Provider,{value:e,children:c})},$e=()=>{const c=M.useContext(Pe);if(!c)throw new Error("useThemeContext must be used within a ThemeProvider");return c},qt=({className:c="",showLabel:e=!1})=>{const{theme:t,actualTheme:s,setTheme:a}=$e(),n=()=>{switch(t){case"light":return d.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor",children:d.jsx("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"})});case"dark":return d.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor",children:d.jsx("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"})});case"auto":return d.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor",children:d.jsx("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"})});default:return null}},o=()=>{switch(t){case"light":return"Light";case"dark":return"Dark";case"auto":return`Auto (${s})`;default:return""}},r=()=>{switch(t){case"light":a("dark");break;case"dark":a("auto");break;case"auto":a("light");break}};return d.jsxs("button",{type:"button",onClick:r,className:`
177
+ `;var K=q;const Ot={send:"Send",conversations_title:"Chats",no_conversations_title:"No conversations yet",no_conversations_message:"Start chatting with product owners to see conversations here",loading_conversations:"Loading conversations...",error_load_conversations:"Failed to load conversations",select_conversation:"Select a conversation",select_conversation_message:"Choose a conversation from the list to start chatting",select_conversation_tip:"💡 Tip: Click on any conversation in the sidebar to open it here",message_hint:"Start typing a message",attach_file:"Attach file",loading_messages:"Loading messages...",file_sent_successfully:"File uploaded and sent!",uploading:"Uploading...",sent:"Sent",read:"Read",error_load_messages:"Failed to load messages",error_send_message:"Failed to send message",error_file_upload:"Failed to upload file",error_unknown:"Unknown error",error_user_blocked:"Your account has been blocked by administrator",error_registration_failed:"Registration failed. Please try again.",login_successful:"Login successful!",registration_successful:"Registration and login successful!",complete_profile_info:"Please complete your profile information.",block_user:"Block User",unblock_user:"Unblock",user_blocked:"User blocked",user_unblocked:"User unblocked",block_user_confirm:"Are you sure you want to block this user?",unblock_user_confirm:"Are you sure you want to unblock this user?",you_are_blocked:"You have been blocked in this chat",you_have_blocked:"You've blocked {{userName}}",you_have_blocked_submessage:"You can't message them in this chat, and you won't receive their messages.",blocked_by_user:"You have been blocked by {{userName}}",blocked_by_user_submessage:"You can't send messages in this chat.",user_is_blocked:"This user is blocked in this chat",failed_to_block:"Failed to block user",failed_to_unblock:"Failed to unblock user",user_not_found:"User not found",user_id_not_found:"User ID not found",cannot_block_self:"You cannot block yourself",loading:"Loading...",unknown_user:"Unknown User",image:"Image",file:"File",no_messages_yet:"No messages yet",yesterday:"Yesterday",unknown_size:"Unknown size",download:"Download",search:"Search",back:"Back",call:"Call",options:"Options",close:"Close",no_phone_number:"No phone number available",number_copied:"Phone number copied to clipboard",no_search_results:"No conversations found",demo_title:"ChatSDK Demo",welcome:"Welcome",logout:"Logout",products:"Products",all_products:"All Products",my_products:"My Products",conversations:"Conversations",sdk_tester:"SDK Tester",sdk_tester_desc:"SDK testing tools will be available here",loading_products:"Loading products...",no_products_listed:"You haven't listed any products yet.",realtime_active:"Real-time Chat Active",http_only:"HTTP Only",failed_to_load_products:"Failed to load products",failed_to_start_chat:"Failed to start chat",cannot_chat_self:"You cannot start a chat with yourself!",starting_chat:"Starting chat with product owner...",chat_opened:"Chat popup opened!",failed_init:"Failed to initialize app",login:"Login",login_as:"Login as",checking:"Checking...",registering:"Registering...",complete_registration:"Complete Registration",back_to_login:"Back to Login",quick_demo_login:"Quick Demo Login (with sample conversations):",external_user_id:"External User ID:",app_id_label:"App ID:",full_name:"Full Name:",email_label:"Email:",welcome_demo:"Welcome to the ChatSDK Demo Application",enter_user_id:"Enter your user ID (e.g., user1)",enter_app_id:"Enter app ID",enter_full_name:"Enter your full name",enter_email:"Enter your email",chat_with_owner:"Chat with Owner",your_product:"Your Product",owner_label:"Owner:"},Wt={send:"إرسال",conversations_title:"الدردشة",no_conversations_title:"لا توجد محادثات بعد",no_conversations_message:"ابدأ الدردشة مع مالكي المنتجات لمشاهدة محادثاتك هنا",loading_conversations:"جاري تحميل المحادثات...",error_load_conversations:"فشل تحميل المحادثات",select_conversation:"اختر محادثة",select_conversation_message:"اختر محادثة من القائمة لبدء الدردشة",select_conversation_tip:"💡 نصيحة: انقر على أي محادثة في الشريط الجانبي لفتحها هنا",message_hint:"اكتب رسالة هنا",attach_file:"إرفاق ملف",loading_messages:"جاري تحميل الرسائل...",file_sent_successfully:"تم إرسال الملف بنجاح!",uploading:"جاري الرفع...",sent:"تم الإرسال",read:"تم القراءة",error_load_messages:"فشل تحميل الرسائل",error_send_message:"فشل إرسال الرسالة",error_file_upload:"فشل رفع الملف",error_unknown:"خطأ غير معروف",error_user_blocked:"تم حظر حسابك من قبل المسؤول",error_registration_failed:"فشل التسجيل. يرجى المحاولة مرة أخرى.",login_successful:"تم تسجيل الدخول بنجاح!",registration_successful:"تم التسجيل وتسجيل الدخول بنجاح!",complete_profile_info:"يرجى إكمال معلومات ملفك الشخصي.",block_user:"حظر المستخدم",unblock_user:"إلغاء الحظر",user_blocked:"تم حظر المستخدم",user_unblocked:"تم إلغاء حظر المستخدم",block_user_confirm:"هل أنت متأكد أنك تريد حظر هذا المستخدم؟",unblock_user_confirm:"هل أنت متأكد أنك تريد إلغاء حظر هذا المستخدم؟",you_are_blocked:"تم حظرك في هذه المحادثة",you_have_blocked:"لقد قمت بحظر {{userName}}",you_have_blocked_submessage:"لا يمكنك مراسلتهم في هذه المحادثة، ولن تتلقى رسائلهم.",blocked_by_user:"تم حظرك من قبل {{userName}}",blocked_by_user_submessage:"لا يمكنك إرسال الرسائل في هذه المحادثة.",user_is_blocked:"هذا المستخدم محظور في هذه المحادثة",failed_to_block:"فشل حظر المستخدم",failed_to_unblock:"فشل إلغاء حظر المستخدم",user_not_found:"المستخدم غير موجود",user_id_not_found:"معرف المستخدم غير موجود",cannot_block_self:"لا يمكنك حظر نفسك",loading:"جاري التحميل...",unknown_user:"مستخدم غير معروف",image:"صورة",file:"ملف",no_messages_yet:"لا توجد رسائل بعد",yesterday:"أمس",unknown_size:"حجم غير معروف",download:"تنزيل",search:"بحث",back:"رجوع",call:"اتصال",options:"خيارات",close:"إغلاق",no_phone_number:"لا يوجد رقم هاتف متاح",number_copied:"تم نسخ رقم الهاتف",no_search_results:"لم يتم العثور على محادثات",demo_title:"عرض ChatSDK",welcome:"مرحبًا",logout:"تسجيل الخروج",products:"المنتجات",all_products:"كل المنتجات",my_products:"منتجاتي",conversations:"المحادثات",sdk_tester:"اختبار SDK",sdk_tester_desc:"ستتوفر أدوات اختبار SDK هنا",loading_products:"جاري تحميل المنتجات...",no_products_listed:"لم تقم بنشر أي منتجات بعد.",realtime_active:"الدردشة المباشرة نشطة",http_only:"HTTP فقط",failed_to_load_products:"فشل تحميل المنتجات",failed_to_start_chat:"فشل بدء الدردشة",cannot_chat_self:"لا يمكنك بدء محادثة مع نفسك!",starting_chat:"جاري بدء الدردشة مع مالك المنتج...",chat_opened:"تم فتح نافذة الدردشة!",failed_init:"فشل تهيئة التطبيق",login:"تسجيل الدخول",login_as:"تسجيل الدخول كـ",checking:"جاري التحقق...",registering:"جاري التسجيل...",complete_registration:"إكمال التسجيل",back_to_login:"العودة لتسجيل الدخول",quick_demo_login:"تسجيل دخول سريع (مع محادثات تجريبية):",external_user_id:"معرف المستخدم الخارجي:",app_id_label:"معرف التطبيق:",full_name:"الاسم الكامل:",email_label:"البريد الإلكتروني:",welcome_demo:"مرحبًا بك في تطبيق عرض ChatSDK",enter_user_id:"أدخل معرف المستخدم (مثل user1)",enter_app_id:"أدخل معرف التطبيق",enter_full_name:"أدخل اسمك الكامل",enter_email:"أدخل بريدك الإلكتروني",chat_with_owner:"الدردشة مع المالك",your_product:"منتجك",owner_label:"المالك:"},$e="chatsdk-root";let de=null;const qt=i=>{de=i},Vt=()=>{if(de&&de.isConnected)return de;const i=document.querySelector(`.${$e}`);return i?(de=i,i):null},Ce=i=>{document.querySelectorAll(`.${$e}`).forEach(i)},ue={en:Ot,ar:Wt};let oe="en",Fe=!1;const he=()=>{const i=oe,e=Oe()?"rtl":"ltr";Ce(t=>{t.setAttribute("lang",i),t.setAttribute("dir",e)})},Gt=i=>{ue[i]?(oe=i,localStorage.setItem("chatSDK_language",i)):(console.warn(`Locale "${i}" not found, falling back to "en".`),oe="en"),he()},Ht=()=>oe,Oe=()=>oe==="ar",w=(i,e)=>{let t=ue[oe][i]||ue.en[i]||i;if(e)for(const s in e)t=t.replace(new RegExp(`{{${s}}}`,"g"),String(e[s]));return t},Se=()=>{if(Fe)return;Fe=!0;const i=localStorage.getItem("chatSDK_language");i&&ue[i]&&(oe=i),he()},Yt=({conversation:i,currentUser:e,onClose:t,onBack:s})=>{var xe;const[a,n]=v.useState([]),[o,r]=v.useState(""),[c,l]=v.useState(!1),[g,u]=v.useState(!1),[m,p]=v.useState({}),[x,B]=v.useState(!1),[_e,le]=v.useState(!0),[y,C]=v.useState(1),[P,V]=v.useState(null),[z,H]=v.useState(!1),[E,U]=v.useState(!1),[A,j]=v.useState(!1),[N,$]=v.useState(null),[X,ee]=v.useState(!1),Y=v.useRef(null),ie=v.useRef(null),R=v.useRef(null),G=v.useRef(null),ae=20,ne=v.useCallback(()=>{if(!i||!e)return null;const h=i.participants||[];if(h.length===0)return null;const f=e.id||e.userId,M=e.externalUserId||e.external_user_id;return h.find(b=>{const _=b.id||b.userId,k=b.externalUserId||b.external_user_id;return!(f&&_&&_===f||M&&k&&k===M)&&(_||k)})||null},[i,e]),D=ne(),O=v.useCallback(()=>{if(!i)return{userName:w("conversations_title"),productName:null,productImage:null,productMetadata:null};const h=D&&(D.name||D.userName||D.displayName||D.externalUserId)||w("unknown_user"),f=i.productContext||i.product_context;return f?{userName:h,productName:f.productName||f.product_name,productImage:f.productImage||f.product_image,productId:f.productId||f.product_id,productMetadata:f.productMetadata||f.product_metadata}:{userName:h,productName:null,productImage:null,productMetadata:null}},[i,D])();v.useEffect(()=>(i&&(j(!1),tt(1,!1),Ge(),T.getInstance().chatUsers.startViewingConversation(i.id)),()=>{i&&(He(),T.getInstance().chatUsers.stopViewingConversation(i.id))}),[i]),v.useEffect(()=>{const h=T.getInstance(),f=k=>{const S=k.message;S.roomId===(i==null?void 0:i.id)&&n(F=>F.some(L=>L.id===S.id)?F:(S.senderId!==e.id&&h.chatUsers.markMessageRead(S.id).catch(L=>{console.warn("ChatWindow: Failed to mark message as read:",L)}),[...F,{id:S.id,content:S.content,senderId:S.senderId,senderName:S.senderName,timestamp:S.createdAt||S.timestamp,conversationId:S.roomId,type:S.messageType||S.type||"text",metadata:S.metadata||void 0,isRead:S.isRead!==void 0?S.isRead:S.senderId!==e.id,isDelivered:S.isDelivered!==void 0?S.isDelivered:!0,status:S.status||"sent"}]))},M=k=>{!k.messageId||k.roomId!==(i==null?void 0:i.id)||n(S=>S.map(F=>F.id===k.messageId&&F.senderId===e.id?{...F,isRead:k.isRead}:F))},b=k=>{if(k.roomId!==(i==null?void 0:i.id))return;const S=e==null?void 0:e.id;if(!k.messageIds||k.messageIds.length===0){n(I=>I.map(L=>L.senderId===S&&!L.isRead?{...L,isRead:k.isRead}:L));return}const F=new Set(k.messageIds);n(I=>I.map(L=>F.has(L.id)&&L.senderId===S?{...L,isRead:k.isRead}:L))},_=k=>{if(!i||((k==null?void 0:k.conversationId)||(k==null?void 0:k.chatId)||(k==null?void 0:k.roomId))!==i.id)return;const F=(k==null?void 0:k.blockedUsers)||{};i.metadata={...i.metadata||{},blockedUsers:F};const I=e.id||e.userId,L=ne(),J=L?L.id||L.userId||L.externalUserId||L.external_user_id:null;H(F[I]===1),U(J?F[J]===1:!1)};return h.events.on("message.received",f),h.events.on("message.read.receipt",M),h.events.on("messages.read.receipt",b),h.events.on("conversation.block_status",_),()=>{h.events.off("message.received",f),h.events.off("message.read.receipt",M),h.events.off("messages.read.receipt",b),h.events.off("conversation.block_status",_)}},[i==null?void 0:i.id,e==null?void 0:e.id]),v.useEffect(()=>{if(!i||!e){H(!1),U(!1),V(null);return}const f=(i.metadata||{}).blockedUsers||{},M=e.id||e.userId,b=ne(),_=b?b.id||b.userId||b.externalUserId||b.external_user_id:null;H(f[M]===1),U(_?f[_]===1:!1),V({chatId:i.id,currentUserId:M,isBlockedByOther:f[M]===1,usersBlockedByMe:Object.keys(f).filter(k=>f[k]===1),blockedUsers:f})},[i==null?void 0:i.id,JSON.stringify(i==null?void 0:i.metadata),e==null?void 0:e.id]),v.useEffect(()=>{Ye()},[a]),v.useEffect(()=>{const h=f=>{f.target.closest(".chat-options-wrapper")||j(!1)};return document.addEventListener("click",h),()=>{document.removeEventListener("click",h),G.current&&clearTimeout(G.current)}},[]);const Ge=()=>{i&&T.getInstance().socket.joinRoom(i.id)},He=()=>{i&&T.getInstance().socket.leaveRoom(i.id)},Ye=()=>{var h;(h=Y.current)==null||h.scrollIntoView({behavior:"smooth"})},Je=h=>new Date(h).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),pe=h=>{const f=new Date(h),M=new Date,b=new Date(M.getFullYear(),M.getMonth(),M.getDate()),_=new Date(f.getFullYear(),f.getMonth(),f.getDate()),k=Math.floor((b.getTime()-_.getTime())/(1e3*60*60*24));if(k===0)return"Today";if(k===1)return"Yesterday";const S=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],F=f.getDate().toString().padStart(2,"0"),I=(f.getMonth()+1).toString().padStart(2,"0");return k<7?`${S[f.getDay()]}, ${F}/${I}`:`${F}/${I}/${f.getFullYear()}`},Qe=(h,f)=>{if(f===0)return!0;const M=a[f-1],b=new Date(M.timestamp).toDateString(),_=new Date(h.timestamp).toDateString();return b!==_},Ze=h=>h?h.includes("pdf")?"📄":h.includes("word")?"📝":h.includes("excel")?"📊":h.includes("audio")?"🎵":h.includes("video")?"🎥":"📎":"📎",Xe=()=>{if(!R.current)return;const h=R.current,f=h.querySelectorAll(".date-divider[data-date]");if(f.length===0)return;let M=null;const b=h.getBoundingClientRect().top;for(let _=f.length-1;_>=0;_--){const k=f[_];if(k.getBoundingClientRect().top<=b+50){M=k.getAttribute("data-date");break}}!M&&a.length>0&&(M=pe(a[0].timestamp)),M&&($(M),ee(!0),G.current&&clearTimeout(G.current),G.current=setTimeout(()=>{ee(!1)},2e3))},et=()=>{if(!D)return;const h=D,f=h.phone||h.phoneNumber||h.mobile||h.externalUserId||"";if(!f){K.error(w("no_phone_number")||"No phone number available");return}/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?window.location.href=`tel:${f}`:navigator.clipboard.writeText(f).then(()=>{K.success(w("number_copied")||`Phone number copied: ${f}`)}).catch(()=>{const b=document.createElement("textarea");b.value=f,document.body.appendChild(b),b.select(),document.execCommand("copy"),document.body.removeChild(b),K.success(w("number_copied")||`Phone number copied: ${f}`)})},tt=async(h=1,f=!1)=>{if(i){h===1?(l(!0),n([]),C(1),le(!0)):B(!0);try{const b=await T.getInstance().messages.getMessages({conversationId:i.id,limit:ae,offset:(h-1)*ae}),_=b.sort((k,S)=>new Date(k.timestamp).getTime()-new Date(S.timestamp).getTime());f&&h>1?n(k=>[..._,...k]):n(_),le(b.length===ae),C(h)}catch{K.error(w("error_load_messages"))}finally{l(!1),B(!1)}}},st=async h=>{if(h.preventDefault(),!i||!o.trim()||z){z&&K.error(w("you_are_blocked"));return}const f=o.trim();r("");try{await T.getInstance().messages.sendMessage(i.id,f)}catch{r(f),K.error(w("error_send_message"))}},at=async h=>{if(!i)return;const f=`temp_${Date.now()}`,M={id:f,conversationId:i.id,senderId:e.id,senderName:e.name,content:`${h.name}`,type:h.type.startsWith("image/")?"image":"file",timestamp:new Date().toISOString(),status:"sending",isRead:!1,isDelivered:!1,isUploading:!0,uploadProgress:0,localFileUri:URL.createObjectURL(h),metadata:{fileName:h.name,fileSize:h.size,mimeType:h.type}};n(b=>[...b,M]),p(b=>({...b,[f]:0}));try{u(!0);const b=T.getInstance(),_=b.media.getFileTypeCategory(h.type),k=await b.media.uploadMedia({file:h,type:_,conversationId:i.id,onProgress:I=>{p(L=>({...L,[f]:I})),n(L=>L.map(J=>J.id===f?{...J,uploadProgress:I}:J))}});p(I=>({...I,[f]:100}));const S=_==="document"?"file":_==="image"?"image":"file",F={fileUrl:k.fileUrl,fileName:k.fileName,fileSize:k.fileSize,mimeType:k.mimeType||h.type};await b.messages.sendMessageWithOptions({conversationId:i.id,content:`${h.name}`,type:S,metadata:F}),setTimeout(()=>{n(I=>I.filter(L=>L.id!==f)),p(I=>{const L={...I};return delete L[f],L})},200),K.success(w("file_sent_successfully"))}catch(b){n(_=>_.filter(k=>k.id!==f)),p(_=>{const k={..._};return delete k[f],k}),K.error(w("error_file_upload")+": "+(b.message||w("error_unknown")))}finally{u(!1)}},nt=async()=>{if(j(!1),!(!i||!e)&&window.confirm(w("block_user_confirm")))try{const h=T.getInstance();if(!D){K.error(w("user_not_found"));return}const f=e.id||e.userId,M=D.id||D.userId||D.externalUserId||D.external_user_id;if(!M){K.error(w("user_id_not_found"));return}if(M===f){K.error(w("cannot_block_self"));return}await h.conversations.blockUserInChat(i.id,M);const b=i.metadata||{},_=b.blockedUsers||{};_[M]=1,i&&(i.metadata={...b,blockedUsers:_}),U(!0),K.success(w("user_blocked"))}catch{K.error(w("failed_to_block"))}},Le=async()=>{if(j(!1),!(!i||!e)&&window.confirm(w("unblock_user_confirm")))try{const h=T.getInstance();if(!D){K.error(w("user_not_found"));return}const f=D.id||D.userId||D.externalUserId||D.external_user_id;if(!f){K.error(w("user_id_not_found"));return}await h.conversations.unblockUserInChat(i.id,f);const M=i.metadata||{},b=M.blockedUsers||{};delete b[f],i&&(i.metadata={...M,blockedUsers:b}),U(!1),K.success(w("user_unblocked"))}catch{K.error(w("failed_to_unblock"))}};return c&&a.length===0?d.jsxs("div",{className:"chat-window",children:[d.jsxs("div",{className:"chat-header",children:[d.jsx("div",{className:"chat-header-left",children:d.jsx("h3",{style:{margin:0},children:w("loading")})}),d.jsx("div",{className:"chat-header-actions",children:t&&d.jsx("button",{onClick:t,className:"close-button",children:"×"})})]}),d.jsx("div",{className:"loading-messages",children:w("loading_messages")})]}):d.jsxs("div",{className:"chat-window",children:[d.jsxs("div",{className:"chat-header",children:[d.jsxs("div",{className:"chat-header-left",children:[s&&d.jsx("button",{className:"chat-back-btn",onClick:s,title:w("back")||"Back",children:d.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:d.jsx("polyline",{points:"15 18 9 12 15 6"})})}),d.jsx("div",{className:"chat-header-avatar",children:d.jsx("div",{className:"avatar-placeholder",children:O.userName?O.userName.charAt(0).toUpperCase():"?"})}),d.jsx("div",{className:"chat-header-info",children:d.jsx("h3",{className:"chat-participant-name",children:O.userName})})]}),d.jsxs("div",{className:"chat-header-actions",children:[D&&d.jsx("button",{onClick:et,className:"chat-action-btn",title:w("call")||"Call",children:d.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:d.jsx("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"})})}),t&&d.jsx("button",{onClick:t,className:"chat-action-btn",title:w("close")||"Close",children:d.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:d.jsx("path",{d:"M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7"})})}),i&&D&&d.jsxs("div",{className:"chat-options-wrapper",children:[d.jsx("button",{onClick:()=>j(!A),className:"chat-action-btn",title:w("options")||"Options",children:d.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:[d.jsx("circle",{cx:"12",cy:"5",r:"2"}),d.jsx("circle",{cx:"12",cy:"12",r:"2"}),d.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}),A&&d.jsxs("div",{className:"chat-options-menu",children:[!z&&!E&&d.jsxs("button",{onClick:nt,className:"danger",children:[d.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[d.jsx("circle",{cx:"12",cy:"12",r:"10"}),d.jsx("line",{x1:"4.93",y1:"4.93",x2:"19.07",y2:"19.07"})]}),w("block_user")]}),E&&d.jsxs("button",{onClick:Le,children:[d.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[d.jsx("circle",{cx:"12",cy:"12",r:"10"}),d.jsx("path",{d:"M2 12h20"})]}),w("unblock_user")]})]})]})]})]}),O.productName&&d.jsxs("div",{className:"chat-product-bar",children:[O.productImage&&d.jsx("img",{src:O.productImage,alt:O.productName}),d.jsxs("div",{className:"chat-product-bar-info",children:[d.jsx("p",{className:"chat-product-bar-name",children:O.productName}),((xe=O.productMetadata)==null?void 0:xe.price)&&d.jsxs("p",{className:"chat-product-bar-price",children:[O.productMetadata.price," ",O.productMetadata.currency||"QAR"]})]})]}),d.jsxs("div",{className:"chat-messages",ref:R,onScroll:Xe,onClick:()=>j(!1),children:[N&&!c&&a.length>0&&d.jsx("div",{className:`sticky-date-header ${X?"sticky-date-visible":""}`,children:d.jsx("span",{className:"sticky-date-pill",children:N})}),c?d.jsx("div",{className:"loading-messages",children:w("loading_messages")}):d.jsxs(d.Fragment,{children:[a.map((h,f)=>{var M,b,_,k,S,F,I,L,J,Ee;return d.jsxs(v.Fragment,{children:[Qe(h,f)&&d.jsxs("div",{className:"date-divider","data-date":pe(h.timestamp),children:[d.jsx("div",{className:"date-divider-line"}),d.jsx("span",{className:"date-divider-text",children:pe(h.timestamp)}),d.jsx("div",{className:"date-divider-line"})]}),d.jsx("div",{className:`message ${h.senderId===e.id?"sent":"received"}`,children:d.jsxs("div",{className:"message-content",children:[h.isUploading&&h.uploadProgress!==void 0&&d.jsx("div",{className:"upload-progress-bar",children:d.jsx("div",{className:"upload-progress-fill",style:{width:`${h.uploadProgress}%`}})}),h.type==="image"&&((M=h.metadata)!=null&&M.fileUrl||h.localFileUri)?d.jsxs("div",{className:"message-attachment image-attachment",children:[d.jsx("img",{src:h.isUploading?h.localFileUri:(b=h.metadata)==null?void 0:b.fileUrl,alt:((_=h.metadata)==null?void 0:_.fileName)||w("image"),className:h.isUploading?"uploading-image":"",onClick:()=>{var De;return!h.isUploading&&((De=h.metadata)==null?void 0:De.fileUrl)&&window.open(h.metadata.fileUrl,"_blank")}}),d.jsxs("div",{className:"attachment-info",children:[((k=h.metadata)==null?void 0:k.fileName)||w("image"),((S=h.metadata)==null?void 0:S.fileSize)&&d.jsxs("span",{children:[" • ",Math.round(h.metadata.fileSize/1024)," KB"]})]})]}):h.type==="file"&&((F=h.metadata)!=null&&F.fileUrl)?d.jsxs("div",{className:"message-attachment file-attachment",children:[d.jsxs("div",{className:"file-info",children:[d.jsx("div",{className:"file-icon",children:Ze((I=h.metadata)==null?void 0:I.mimeType)}),d.jsxs("div",{className:"file-details",children:[d.jsx("div",{className:"file-name",children:((L=h.metadata)==null?void 0:L.fileName)||w("file")}),d.jsx("div",{className:"file-size",children:(J=h.metadata)!=null&&J.fileSize?`${Math.round(h.metadata.fileSize/1024)} KB`:w("unknown_size")})]})]}),d.jsx("a",{href:((Ee=h.metadata)==null?void 0:Ee.fileUrl)||"#",target:"_blank",rel:"noopener noreferrer",className:"download-btn",children:w("download")})]}):h.content,d.jsxs("div",{className:"message-footer",children:[d.jsx("span",{className:"message-time",children:Je(h.timestamp)}),h.senderId===e.id&&d.jsx("span",{className:"message-status",children:d.jsx("span",{className:"read-status",children:h.isRead?d.jsxs("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:[d.jsx("polyline",{points:"1 13 5 17 11 9"}),d.jsx("polyline",{points:"7 13 11 17 17 9"})]}):d.jsx("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:d.jsx("polyline",{points:"4 13 8 17 16 9"})})})})]})]})})]},h.id)}),d.jsx("div",{ref:Y})]})]}),E&&d.jsxs("div",{className:"blocked-ui blocked-by-me",children:[d.jsx("div",{className:"blocked-title",children:w("you_have_blocked",{userName:O.userName||w("unknown_user")})}),d.jsx("div",{className:"blocked-message",children:w("you_have_blocked_submessage")}),d.jsx("button",{onClick:Le,className:"unblock-btn",children:w("unblock_user")})]}),z&&!E&&d.jsxs("div",{className:"blocked-ui blocked-by-other",children:[d.jsx("div",{className:"blocked-title",children:w("blocked_by_user",{userName:O.userName||w("unknown_user")})}),d.jsx("div",{className:"blocked-message",children:w("blocked_by_user_submessage")})]}),!E&&!z&&d.jsxs("form",{onSubmit:st,className:"chat-input",children:[d.jsx("button",{type:"button",onClick:()=>{var h;return(h=ie.current)==null?void 0:h.click()},disabled:c||g||z,className:"attachment-btn",title:w("attach_file"),children:g?d.jsx("span",{children:"⌛"}):d.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:d.jsx("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"})})}),d.jsx("input",{ref:ie,type:"file",style:{display:"none"},accept:"image/*,video/*,audio/*,.pdf,.doc,.docx,.txt",onChange:h=>{var M;const f=(M=h.target.files)==null?void 0:M[0];f&&(at(f),h.target.value="")}}),d.jsx("input",{type:"text",value:o,onChange:h=>r(h.target.value),placeholder:w(z?"you_are_blocked":g?"uploading":"message_hint"),disabled:c||g||z}),d.jsx("button",{type:"submit",disabled:!o.trim()||c||g||z,className:"send-btn",children:w(g?"uploading":"send")})]})]})},Jt=i=>{const e=v.useRef(null);return v.useEffect(()=>{Se(),he()},[]),d.jsx("div",{ref:e,className:"chatsdk-root",children:d.jsx(Yt,{...i})})},Qt=({currentUser:i,onSelectConversation:e,selectedConversationId:t})=>{const[s,a]=v.useState([]),[n,o]=v.useState(!1),[r,c]=v.useState(""),l=v.useRef(t),g=v.useRef(i.id);v.useEffect(()=>{l.current=t},[t]),v.useEffect(()=>{g.current=i.id},[i.id]),v.useEffect(()=>{m()},[]),v.useEffect(()=>{i&&(a([]),m())},[i.id]),v.useEffect(()=>{var H;const y=T.getInstance(),C=E=>{const U=E.message,A=U.roomId||U.conversationId;a(j=>j.map(N=>{if(N.id===A){const $=U.senderId!==g.current,X=l.current!==A;return{...N,lastMessage:U,unreadCount:$&&X?N.unreadCount+1:N.unreadCount}}return N}).sort((N,$)=>{var Y,ie;const X=((Y=N.lastMessage)==null?void 0:Y.timestamp)||N.createdAt,ee=((ie=$.lastMessage)==null?void 0:ie.timestamp)||$.createdAt;return new Date(ee).getTime()-new Date(X).getTime()})),U.senderId!==g.current&&l.current===A&&T.getInstance().chatUsers.markMessageRead(U.id).then(()=>{a(N=>N.map($=>$.id===A?{...$,unreadCount:0}:$))}).catch(N=>{console.warn("Failed to auto-mark message as read:",N)})},P=E=>{var N,$,X,ee;const U=E.conversationId||((N=E.conversation)==null?void 0:N.id)||(($=E.conversation)==null?void 0:$.conversationId);if(!U)return;const A=E.lastMessage||((X=E.conversation)==null?void 0:X.lastMessage),j=(ee=E.conversation)==null?void 0:ee.unreadCount;a(Y=>Y.some(R=>R.id===U)?Y.map(R=>{if(R.id!==U)return R;const G=l.current===U,ae=g.current;if(typeof j=="number")return{...R,lastMessage:A||R.lastMessage,unreadCount:G?0:j};const ne=(A==null?void 0:A.senderId)&&A.senderId!==ae,D=!!A&&ne&&!G;return{...R,lastMessage:A||R.lastMessage,unreadCount:G?0:D?R.unreadCount+1:R.unreadCount}}).sort((R,G)=>{var D,fe;const ae=((D=R.lastMessage)==null?void 0:D.timestamp)||R.createdAt,ne=((fe=G.lastMessage)==null?void 0:fe.timestamp)||G.createdAt;return new Date(ne).getTime()-new Date(ae).getTime()}):(m(),Y))},V=E=>{const U=E.conversationId||E.roomId;U&&a(A=>A.map(j=>j.id===U?{...j,unreadCount:0}:j))},z=E=>{const U=E.roomId||E.conversationId;U&&a(A=>A.map(j=>j.id===U?{...j,unreadCount:0}:j))};return y.events.on("message.received",C),y.events.on("conversation.updated",P),y.events.on("conversation.read",V),(H=y.socket)!=null&&H.isConnected()&&(y.socket.on("auto_marked_read",z),y.socket.on("room_marked_read",V)),()=>{var E;y.events.off("message.received",C),y.events.off("conversation.updated",P),y.events.off("conversation.read",V),(E=y.socket)!=null&&E.isConnected()&&(y.socket.off("auto_marked_read",z),y.socket.off("room_marked_read",V))}},[]);const u=async y=>{try{if(y.unreadCount>0){const C=T.getInstance();await C.chatUsers.markRoomMessagesRead(y.id),C.chatUsers.startViewingConversation(y.id)}e(y)}catch(C){console.error("Failed to mark conversation as read:",C),e(y)}},m=async()=>{o(!0);try{const C=await T.getInstance().chatUsers.getConversations();let P=C;C&&typeof C=="object"&&!Array.isArray(C)&&(P=C.conversations||C.data||[]),a(Array.isArray(P)?P:[])}catch{K.error(w("error_load_conversations"))}finally{o(!1)}},p=y=>y.participants.find(C=>C.id!==i.id),x=y=>{const C=p(y);return(C==null?void 0:C.name)||w("unknown_user")},B=y=>{var C;return((C=y.lastMessage)==null?void 0:C.content)||w("no_messages_yet")},_e=y=>{const C=new Date(y),V=(new Date().getTime()-C.getTime())/(1e3*60*60),z=V/24;return V<24?C.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):z<7?`${Math.floor(z)}d ago`:`${C.getDate()} ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][C.getMonth()]}`},le=r.trim()?s.filter(y=>{var H,E;const C=r.toLowerCase().trim(),P=x(y).toLowerCase(),V=((E=(H=y.productContext)==null?void 0:H.productName)==null?void 0:E.toLowerCase())||"",z=B(y).toLowerCase();return P.includes(C)||V.includes(C)||z.includes(C)}):s;return n?d.jsx("div",{className:"conversation-list loading",children:d.jsx("div",{className:"loading-spinner",children:w("loading_conversations")})}):d.jsxs("div",{className:"conversation-list",children:[d.jsx("div",{className:"conversation-list-header",children:d.jsx("h3",{children:w("conversations_title")})}),d.jsx("div",{className:"conversation-search",children:d.jsxs("div",{className:"conversation-search-input",children:[d.jsx("span",{className:"search-icon",children:d.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx("circle",{cx:"11",cy:"11",r:"8"}),d.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}),d.jsx("input",{value:r,onChange:y=>c(y.target.value),type:"text",placeholder:w("search")||"Search"})]})}),d.jsx("div",{className:"conversations",children:le.length===0?d.jsxs("div",{className:"empty-conversations",children:[d.jsx("p",{children:r?w("no_search_results")||"No results found":w("no_conversations_title")}),!r&&d.jsx("p",{children:w("no_conversations_message")})]}):le.map(y=>{var P;const C=t===y.id;return d.jsxs("div",{className:`conversation-item ${C?"selected":""} ${y.unreadCount>0?"has-unread":""}`,onClick:()=>u(y),children:[d.jsx("div",{className:"conversation-avatar",children:(P=y.productContext)!=null&&P.productImage?d.jsx("img",{src:y.productContext.productImage,alt:y.productContext.productName,className:"product-image"}):d.jsx("div",{className:"avatar-placeholder",children:x(y).charAt(0).toUpperCase()})}),d.jsxs("div",{className:"conversation-content",children:[d.jsxs("div",{className:"conversation-header",children:[d.jsx("div",{className:"conversation-title-wrapper",children:d.jsx("h4",{className:"conversation-participant-name",children:x(y)})}),y.lastMessage&&d.jsx("span",{className:"conversation-time",children:_e(y.lastMessage.timestamp)})]}),d.jsxs("div",{className:"conversation-details",children:[d.jsx("p",{className:"conversation-last-message",children:B(y)}),y.unreadCount>0&&d.jsx("span",{className:"unread-badge",children:y.unreadCount})]})]})]},y.id)})})]})},Zt=i=>{const e=v.useRef(null);return v.useEffect(()=>{Se(),he()},[]),d.jsx("div",{ref:e,className:"chatsdk-root",children:d.jsx(Qt,{...i})})},We=()=>{const[i,e]=v.useState(()=>typeof window<"u"&&localStorage.getItem("chatSDK-theme")||"auto"),[t,s]=v.useState(()=>typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),a=i==="auto"?t:i;v.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const r=window.matchMedia("(prefers-color-scheme: dark)"),c=l=>{s(l.matches?"dark":"light")};return r.addEventListener("change",c),()=>r.removeEventListener("change",c)},[]),v.useEffect(()=>{typeof window>"u"||Ce(r=>{r.classList.remove("theme-light","theme-dark"),r.removeAttribute("data-theme"),r.classList.add(`theme-${a}`),r.setAttribute("data-theme",a)})},[a]);const n=r=>{e(r),typeof window<"u"&&localStorage.setItem("chatSDK-theme",r)};return{theme:i,actualTheme:a,setTheme:n,toggleTheme:()=>{n(i==="auto"?t==="light"?"dark":"light":a==="light"?"dark":"light")}}},qe=v.createContext(void 0),Xt=({children:i})=>{const e=We();return d.jsx(qe.Provider,{value:e,children:i})},Ve=()=>{const i=v.useContext(qe);if(!i)throw new Error("useThemeContext must be used within a ThemeProvider");return i},es=({className:i="",showLabel:e=!1})=>{const{theme:t,actualTheme:s,setTheme:a}=Ve(),n=()=>{switch(t){case"light":return d.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor",children:d.jsx("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"})});case"dark":return d.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor",children:d.jsx("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"})});case"auto":return d.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor",children:d.jsx("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"})});default:return null}},o=()=>{switch(t){case"light":return"Light";case"dark":return"Dark";case"auto":return`Auto (${s})`;default:return""}},r=()=>{switch(t){case"light":a("dark");break;case"dark":a("auto");break;case"auto":a("light");break}};return d.jsxs("button",{type:"button",onClick:r,className:`
178
178
  inline-flex items-center gap-2 px-3 py-2 rounded-md
179
179
  text-on-surface bg-surface-variant hover:bg-primary hover:text-on-primary
180
180
  border border-figma-separator transition-colors duration-200
181
181
  focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2
182
- ${c}
183
- `,title:`Current theme: ${o()}. Click to cycle.`,"aria-label":`Switch theme. Current: ${o()}`,children:[n(),e&&d.jsx("span",{className:"text-sm font-medium",children:o()})]})},Vt=()=>{var a;const c=localStorage.getItem("chatSDK-theme"),e=(a=window.matchMedia)==null?void 0:a.call(window,"(prefers-color-scheme: dark)").matches,t=c||"auto",s=t==="auto"?e?"dark":"light":t;document.documentElement.classList.add(`theme-${s}`),document.documentElement.setAttribute("data-theme",s)},Gt={primary:{main:"#2196F3",onPrimary:"#FFFFFF",container:"#BBDEFB",onContainer:"#0D47A1",dark:"#1976D2"},secondary:{main:"#FF4081",onSecondary:"#FFFFFF",container:"#FCE4EC",onContainer:"#880E4F"},surface:{main:"#FFFFFF",onSurface:"#212121",variant:"#F5F5F5",onVariant:"#757575"},background:{main:"#FFFFFF",onBackground:"#212121"},error:{main:"#F44336",onError:"#FFFFFF",container:"#FFEBEE",onContainer:"#B71C1C"},status:{success:"#4CAF50",warning:"#FF9800",error:"#F44336",info:"#2196F3"},figma:{background:"#F0F0F0",textPrimary:"#1E1E1E",textProduct:"#95265B",textTimestamp:"#878787",separator:"#C4C4C4",onlineIndicator:"#4CAF50"},chat:{background:"#F4F4F4",productText:"#923060",messageReceived:"#FFFFFF",messageSent:"#C4C4C4",inputBackground:"#FBFBFB",inputPlaceholder:"#C4C4C4",timestamp:"#878787",primaryText:"#1E1E1E"},message:{sentBackground:"#2196F3",receivedBackground:"#F5F5F5"},avatar:{background:"#E0E0E0",border:"#BDBDBD"},input:{background:"#FAFAFA",border:"#E0E0E0"},badge:{unreadBackground:"#F44336"},common:{white:"#FFFFFF",black:"#000000",transparent:"transparent"}},Ht={primary:{main:"#90CAF9",onPrimary:"#0D47A1",container:"#1565C0",onContainer:"#E3F2FD",dark:"#42A5F5"},secondary:{main:"#F8BBD9",onSecondary:"#4A148C",container:"#7B1FA2",onContainer:"#FCE4EC"},surface:{main:"#121212",onSurface:"#FFFFFF",variant:"#1E1E1E",onVariant:"#BDBDBD"},background:{main:"#121212",onBackground:"#FFFFFF"},error:{main:"#CF6679",onError:"#000000",container:"#B00020",onContainer:"#FECDD3"},figma:{background:"#1E1E1E",textPrimary:"#FFFFFF",textProduct:"#F8BBD9",textTimestamp:"#BDBDBD",separator:"#424242",onlineIndicator:"#4CAF50"},chat:{background:"#121212",productText:"#F8BBD9",messageReceived:"#2C2C2C",messageSent:"#424242",inputBackground:"#1E1E1E",inputPlaceholder:"#757575",timestamp:"#BDBDBD",primaryText:"#FFFFFF"}},Yt={async init(c){const{ChatSDK:e}=await Promise.resolve().then(()=>nt);return e.getInstance().init(c)},formatFileSize(c){if(c===0)return"0 Bytes";const e=1024,t=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(c)/Math.log(e));return parseFloat((c/Math.pow(e,s)).toFixed(2))+" "+t[s]},formatTimeAgo(c){const e=new Date(c),s=new Date().getTime()-e.getTime(),a=Math.floor(s/6e4),n=Math.floor(s/36e5),o=Math.floor(s/864e5);return a<1?"now":a<60?`${a}m ago`:n<24?`${n}h ago`:o<7?`${o}d ago`:e.toLocaleDateString()}};exports.AuthManager=De;exports.ChatSDK=T;exports.ChatSDKHelpers=Yt;exports.ChatWindow=$t;exports.ConversationList=Ot;exports.ConversationManager=Fe;exports.EventManager=Ae;exports.MediaManager=je;exports.MessageManager=Ie;exports.ParseUtils=fe;exports.SocketManager=Te;exports.ThemeProvider=Wt;exports.ThemeToggle=qt;exports.UserManager=Ue;exports.changeLanguage=ye;exports.darkThemeConfig=Ht;exports.getCurrentLanguage=Pt;exports.initializeTheme=Vt;exports.isRTL=Re;exports.t=w;exports.themeConfig=Gt;exports.useTheme=Be;exports.useThemeContext=$e;
182
+ ${i}
183
+ `,title:`Current theme: ${o()}. Click to cycle.`,"aria-label":`Switch theme. Current: ${o()}`,children:[n(),e&&d.jsx("span",{className:"text-sm font-medium",children:o()})]})},ts=()=>{var a;const i=localStorage.getItem("chatSDK-theme"),e=(a=window.matchMedia)==null?void 0:a.call(window,"(prefers-color-scheme: dark)").matches,t=i||"auto",s=t==="auto"?e?"dark":"light":t;Ce(n=>{n.classList.add(`theme-${s}`),n.setAttribute("data-theme",s)})},ss={primary:{main:"#2196F3",onPrimary:"#FFFFFF",container:"#BBDEFB",onContainer:"#0D47A1",dark:"#1976D2"},secondary:{main:"#FF4081",onSecondary:"#FFFFFF",container:"#FCE4EC",onContainer:"#880E4F"},surface:{main:"#FFFFFF",onSurface:"#212121",variant:"#F5F5F5",onVariant:"#757575"},background:{main:"#FFFFFF",onBackground:"#212121"},error:{main:"#F44336",onError:"#FFFFFF",container:"#FFEBEE",onContainer:"#B71C1C"},status:{success:"#4CAF50",warning:"#FF9800",error:"#F44336",info:"#2196F3"},figma:{background:"#F0F0F0",textPrimary:"#1E1E1E",textProduct:"#95265B",textTimestamp:"#878787",separator:"#C4C4C4",onlineIndicator:"#4CAF50"},chat:{background:"#F4F4F4",productText:"#923060",messageReceived:"#FFFFFF",messageSent:"#C4C4C4",inputBackground:"#FBFBFB",inputPlaceholder:"#C4C4C4",timestamp:"#878787",primaryText:"#1E1E1E"},message:{sentBackground:"#2196F3",receivedBackground:"#F5F5F5"},avatar:{background:"#E0E0E0",border:"#BDBDBD"},input:{background:"#FAFAFA",border:"#E0E0E0"},badge:{unreadBackground:"#F44336"},common:{white:"#FFFFFF",black:"#000000",transparent:"transparent"}},as={primary:{main:"#90CAF9",onPrimary:"#0D47A1",container:"#1565C0",onContainer:"#E3F2FD",dark:"#42A5F5"},secondary:{main:"#F8BBD9",onSecondary:"#4A148C",container:"#7B1FA2",onContainer:"#FCE4EC"},surface:{main:"#121212",onSurface:"#FFFFFF",variant:"#1E1E1E",onVariant:"#BDBDBD"},background:{main:"#121212",onBackground:"#FFFFFF"},error:{main:"#CF6679",onError:"#000000",container:"#B00020",onContainer:"#FECDD3"},figma:{background:"#1E1E1E",textPrimary:"#FFFFFF",textProduct:"#F8BBD9",textTimestamp:"#BDBDBD",separator:"#424242",onlineIndicator:"#4CAF50"},chat:{background:"#121212",productText:"#F8BBD9",messageReceived:"#2C2C2C",messageSent:"#424242",inputBackground:"#1E1E1E",inputPlaceholder:"#757575",timestamp:"#BDBDBD",primaryText:"#FFFFFF"}},ns={async init(i){const{ChatSDK:e}=await Promise.resolve().then(()=>ct);return e.getInstance().init(i)},formatFileSize(i){if(i===0)return"0 Bytes";const e=1024,t=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(i)/Math.log(e));return parseFloat((i/Math.pow(e,s)).toFixed(2))+" "+t[s]},formatTimeAgo(i){const e=new Date(i),s=new Date().getTime()-e.getTime(),a=Math.floor(s/6e4),n=Math.floor(s/36e5),o=Math.floor(s/864e5);return a<1?"now":a<60?`${a}m ago`:n<24?`${n}h ago`:o<7?`${o}d ago`:e.toLocaleDateString()}};exports.AuthManager=Ie;exports.ChatSDK=T;exports.ChatSDKHelpers=ns;exports.ChatWindow=Jt;exports.ConversationList=Zt;exports.ConversationManager=Ae;exports.EventManager=Ke;exports.MediaManager=Ne;exports.MessageManager=Te;exports.ParseUtils=ke;exports.SocketManager=ze;exports.ThemeProvider=Xt;exports.ThemeToggle=es;exports.UserManager=je;exports.applyLanguageToDOM=he;exports.changeLanguage=Gt;exports.darkThemeConfig=as;exports.getCurrentLanguage=Ht;exports.getSDKRoot=Vt;exports.initializeI18n=Se;exports.initializeTheme=ts;exports.isRTL=Oe;exports.setSDKRoot=qt;exports.t=w;exports.themeConfig=ss;exports.useTheme=We;exports.useThemeContext=Ve;
184
184
  //# sourceMappingURL=chatsdk-react.cjs.map