@traiyani/chatsdk-react 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -189,11 +189,23 @@ async function generateExternalGroupId(userId1, userId2, productId) {
189
189
  ? `${sorted[0]}_${sorted[1]}_product_${productId}`
190
190
  : `${sorted[0]}_${sorted[1]}`;
191
191
 
192
- const encoder = new TextEncoder();
193
- const data = encoder.encode(base);
194
- const hashBuffer = await crypto.subtle.digest('SHA-256', data);
195
- const hashArray = Array.from(new Uint8Array(hashBuffer));
196
- return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
192
+ return await hashString(base);
193
+ }
194
+
195
+ async function hashString(input) {
196
+ if (typeof crypto !== 'undefined' && crypto.subtle) {
197
+ const data = new TextEncoder().encode(input);
198
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
199
+ return Array.from(new Uint8Array(hashBuffer))
200
+ .map(b => b.toString(16).padStart(2, '0')).join('');
201
+ }
202
+ // Fallback for non-HTTPS environments (e.g. http://localhost)
203
+ let hash = 0x811c9dc5;
204
+ for (let i = 0; i < input.length; i++) {
205
+ hash ^= input.charCodeAt(i);
206
+ hash = (hash * 0x01000193) >>> 0;
207
+ }
208
+ return hash.toString(16).padStart(8, '0');
197
209
  }
198
210
  ```
199
211
 
@@ -174,11 +174,11 @@ to {
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 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=c=>d.jsx("div",{className:"chatsdk-root",children:d.jsx($t,{...c})}),Wt=({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)})})]})},qt=c=>d.jsx("div",{className:"chatsdk-root",children:d.jsx(Wt,{...c})}),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),Vt=({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},Gt=({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:`
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
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;
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()})]})},Ht=()=>{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)},Yt={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"}},Jt={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"}},Qt={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=Qt;exports.ChatWindow=Ot;exports.ConversationList=qt;exports.ConversationManager=Fe;exports.EventManager=Ae;exports.MediaManager=je;exports.MessageManager=Ie;exports.ParseUtils=fe;exports.SocketManager=Te;exports.ThemeProvider=Vt;exports.ThemeToggle=Gt;exports.UserManager=Ue;exports.changeLanguage=ye;exports.darkThemeConfig=Jt;exports.getCurrentLanguage=Pt;exports.initializeTheme=Ht;exports.isRTL=Re;exports.t=w;exports.themeConfig=Yt;exports.useTheme=Be;exports.useThemeContext=$e;
184
184
  //# sourceMappingURL=chatsdk-react.cjs.map