@messenger-box/tailwind-ui-inbox 10.0.3-alpha.71 → 10.0.3-alpha.72

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.
Files changed (148) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/lib/components/AIAgent/AIAgent.d.ts +14 -0
  3. package/lib/components/AIAgent/AIAgent.d.ts.map +1 -0
  4. package/lib/components/AIAgent/AIAgent.js +1148 -0
  5. package/lib/components/AIAgent/AIAgent.js.map +1 -0
  6. package/lib/components/AIAgent/index.d.ts +2 -0
  7. package/lib/components/AIAgent/index.d.ts.map +1 -0
  8. package/lib/components/InboxMessage/InputComponent.d.ts +9 -0
  9. package/lib/components/InboxMessage/InputComponent.d.ts.map +1 -0
  10. package/lib/components/InboxMessage/InputComponent.js +210 -0
  11. package/lib/components/InboxMessage/InputComponent.js.map +1 -0
  12. package/lib/components/InboxMessage/MessageInput.d.ts.map +1 -1
  13. package/lib/components/InboxMessage/MessageInput.js +14 -10
  14. package/lib/components/InboxMessage/MessageInput.js.map +1 -1
  15. package/lib/components/InboxMessage/MessageInputComponent.d.ts +9 -0
  16. package/lib/components/InboxMessage/MessageInputComponent.d.ts.map +1 -0
  17. package/lib/components/InboxMessage/MessageInputComponent.js +173 -0
  18. package/lib/components/InboxMessage/MessageInputComponent.js.map +1 -0
  19. package/lib/components/InboxMessage/Messages.d.ts.map +1 -1
  20. package/lib/components/InboxMessage/Messages.js +4 -54
  21. package/lib/components/InboxMessage/Messages.js.map +1 -1
  22. package/lib/components/InboxMessage/MessagesBuilderUi.d.ts +17 -0
  23. package/lib/components/InboxMessage/MessagesBuilderUi.d.ts.map +1 -0
  24. package/lib/components/InboxMessage/MessagesBuilderUi.js +162 -0
  25. package/lib/components/InboxMessage/MessagesBuilderUi.js.map +1 -0
  26. package/lib/components/InboxMessage/UploadImageButton.d.ts +1 -0
  27. package/lib/components/InboxMessage/UploadImageButton.d.ts.map +1 -1
  28. package/lib/components/InboxMessage/UploadImageButton.js +3 -3
  29. package/lib/components/InboxMessage/UploadImageButton.js.map +1 -1
  30. package/lib/components/InboxMessage/index.d.ts +3 -0
  31. package/lib/components/InboxMessage/index.d.ts.map +1 -1
  32. package/lib/components/InboxMessage/message-widgets/CommonMessage.d.ts.map +1 -1
  33. package/lib/components/InboxMessage/message-widgets/CommonMessage.js +11 -6
  34. package/lib/components/InboxMessage/message-widgets/CommonMessage.js.map +1 -1
  35. package/lib/components/InboxMessage/message-widgets/ModernMessageGroup.d.ts +14 -0
  36. package/lib/components/InboxMessage/message-widgets/ModernMessageGroup.d.ts.map +1 -0
  37. package/lib/components/InboxMessage/message-widgets/ModernMessageGroup.js +1525 -0
  38. package/lib/components/InboxMessage/message-widgets/ModernMessageGroup.js.map +1 -0
  39. package/lib/components/InboxMessage/message-widgets/PlainMessage.d.ts.map +1 -1
  40. package/lib/components/InboxMessage/message-widgets/PlainMessage.js +6 -3
  41. package/lib/components/InboxMessage/message-widgets/PlainMessage.js.map +1 -1
  42. package/lib/components/InboxMessage/message-widgets/SlackLikeMessageGroup.d.ts.map +1 -1
  43. package/lib/components/InboxMessage/message-widgets/SlackLikeMessageGroup.js +207 -12
  44. package/lib/components/InboxMessage/message-widgets/SlackLikeMessageGroup.js.map +1 -1
  45. package/lib/components/InboxMessage/message-widgets/index.d.ts +1 -0
  46. package/lib/components/InboxMessage/message-widgets/index.d.ts.map +1 -1
  47. package/lib/components/index.d.ts +2 -1
  48. package/lib/components/index.d.ts.map +1 -1
  49. package/lib/compute.d.ts.map +1 -1
  50. package/lib/compute.js +79 -3
  51. package/lib/compute.js.map +1 -1
  52. package/lib/config/env-config.d.ts +6 -0
  53. package/lib/config/env-config.d.ts.map +1 -1
  54. package/lib/config/env-config.js +19 -1
  55. package/lib/config/env-config.js.map +1 -1
  56. package/lib/container/AiInbox.d.ts +15 -0
  57. package/lib/container/AiInbox.d.ts.map +1 -0
  58. package/lib/container/AiInbox.js +1520 -0
  59. package/lib/container/AiInbox.js.map +1 -0
  60. package/lib/container/AiInboxWithLoader.d.ts +36 -0
  61. package/lib/container/AiInboxWithLoader.d.ts.map +1 -0
  62. package/lib/container/AiInboxWithLoader.js +300 -0
  63. package/lib/container/AiInboxWithLoader.js.map +1 -0
  64. package/lib/container/AiLandingInput.d.ts +4 -0
  65. package/lib/container/AiLandingInput.d.ts.map +1 -0
  66. package/lib/container/AiLandingInput.js +164 -0
  67. package/lib/container/AiLandingInput.js.map +1 -0
  68. package/lib/container/Inbox.d.ts.map +1 -1
  69. package/lib/container/Inbox.js +6 -4
  70. package/lib/container/Inbox.js.map +1 -1
  71. package/lib/container/InboxAiMessagesLoader.d.ts +36 -0
  72. package/lib/container/InboxAiMessagesLoader.d.ts.map +1 -0
  73. package/lib/container/InboxAiMessagesLoader.js +47 -0
  74. package/lib/container/InboxAiMessagesLoader.js.map +1 -0
  75. package/lib/container/InboxContainer.d.ts +12 -0
  76. package/lib/container/InboxContainer.d.ts.map +1 -0
  77. package/lib/container/InboxContainer.js +31 -0
  78. package/lib/container/InboxContainer.js.map +1 -0
  79. package/lib/container/InboxTemplate1.d.ts +15 -0
  80. package/lib/container/InboxTemplate1.d.ts.map +1 -0
  81. package/lib/container/InboxTemplate1.js +1375 -0
  82. package/lib/container/InboxTemplate1.js.map +1 -0
  83. package/lib/container/InboxTemplate1WithLoader.d.ts +36 -0
  84. package/lib/container/InboxTemplate1WithLoader.d.ts.map +1 -0
  85. package/lib/container/InboxTemplate2.d.ts +15 -0
  86. package/lib/container/InboxTemplate2.d.ts.map +1 -0
  87. package/lib/container/InboxTemplate2.js +1426 -0
  88. package/lib/container/InboxTemplate2.js.map +1 -0
  89. package/lib/container/InboxWithAiLoader.d.ts +15 -0
  90. package/lib/container/InboxWithAiLoader.d.ts.map +1 -0
  91. package/lib/container/InboxWithAiLoader.js +56 -0
  92. package/lib/container/InboxWithAiLoader.js.map +1 -0
  93. package/lib/container/ServiceInbox.js +1 -1
  94. package/lib/container/ServiceInbox.js.map +1 -1
  95. package/lib/container/ThreadMessages.js +1 -1
  96. package/lib/container/ThreadMessages.js.map +1 -1
  97. package/lib/container/ThreadMessagesInbox.js +1 -1
  98. package/lib/container/ThreadMessagesInbox.js.map +1 -1
  99. package/lib/container/Threads.js +1 -1
  100. package/lib/container/Threads.js.map +1 -1
  101. package/lib/container/index.d.ts +4 -1
  102. package/lib/container/index.d.ts.map +1 -1
  103. package/lib/index.js +1 -1
  104. package/lib/machines/aiAgentMachine.d.ts +3 -0
  105. package/lib/machines/aiAgentMachine.d.ts.map +1 -0
  106. package/lib/machines/aiAgentMachine.js +1040 -0
  107. package/lib/machines/aiAgentMachine.js.map +1 -0
  108. package/lib/machines/types.d.ts +77 -0
  109. package/lib/machines/types.d.ts.map +1 -0
  110. package/lib/routes.json +40 -0
  111. package/lib/templates/InboxWithAi.d.ts +15 -0
  112. package/lib/templates/InboxWithAi.d.ts.map +1 -0
  113. package/lib/templates/InboxWithAi.js +405 -0
  114. package/lib/templates/InboxWithAi.js.map +1 -0
  115. package/lib/templates/InboxWithAi.tsx +502 -0
  116. package/package.json +7 -5
  117. package/src/components/AIAgent/AIAgent.tsx +1351 -0
  118. package/src/components/AIAgent/README.md +82 -0
  119. package/src/components/AIAgent/index.ts +1 -0
  120. package/src/components/InboxMessage/InputComponent.tsx +263 -0
  121. package/src/components/InboxMessage/MessageInput.tsx +73 -66
  122. package/src/components/InboxMessage/MessageInputComponent.tsx +245 -0
  123. package/src/components/InboxMessage/Messages.tsx +2 -56
  124. package/src/components/InboxMessage/MessagesBuilderUi.tsx +205 -0
  125. package/src/components/InboxMessage/UploadImageButton.tsx +3 -2
  126. package/src/components/InboxMessage/index.ts +3 -0
  127. package/src/components/InboxMessage/message-widgets/CommonMessage.tsx +39 -21
  128. package/src/components/InboxMessage/message-widgets/ModernMessageGroup.tsx +1968 -0
  129. package/src/components/InboxMessage/message-widgets/PlainMessage.tsx +6 -2
  130. package/src/components/InboxMessage/message-widgets/SlackLikeMessageGroup.tsx +306 -54
  131. package/src/components/InboxMessage/message-widgets/index.ts +1 -0
  132. package/src/components/index.ts +4 -0
  133. package/src/compute.ts +83 -2
  134. package/src/config/env-config.ts +6 -0
  135. package/src/container/AiInbox.tsx +1796 -0
  136. package/src/container/AiInboxWithLoader.tsx +356 -0
  137. package/src/container/AiLandingInput.tsx +168 -0
  138. package/src/container/Inbox.tsx +8 -5
  139. package/src/container/InboxAiMessagesLoader.tsx +68 -0
  140. package/src/container/InboxContainer.tsx +35 -0
  141. package/src/container/InboxTemplate1.tsx +1542 -0
  142. package/src/container/InboxTemplate1WithLoader.tsx +338 -0
  143. package/src/container/InboxTemplate2.tsx +1606 -0
  144. package/src/container/InboxWithAiLoader.tsx +76 -0
  145. package/src/container/index.ts +15 -1
  146. package/src/machines/aiAgentMachine.ts +1248 -0
  147. package/src/machines/types.ts +59 -0
  148. package/src/templates/InboxWithAi.tsx +502 -0
@@ -0,0 +1,1796 @@
1
+ import React, { ReactNode, useCallback, useEffect, useMemo, useReducer, useRef } from 'react';
2
+ import { orderBy, uniqBy } from 'lodash-es';
3
+ import {
4
+ OnChatMessageAddedDocument as CHAT_MESSAGE_ADDED,
5
+ useSendMessagesMutation,
6
+ GetChannelsByUserDocument,
7
+ MessagesDocument,
8
+ } from 'common/graphql';
9
+ import { useUploadFiles } from '@messenger-box/platform-client';
10
+ import { IFileInfo, RoomType, PostTypeEnum } from 'common';
11
+ import { useSelector, shallowEqual } from 'react-redux';
12
+ import { useNavigate, useParams } from '@remix-run/react';
13
+ import { LeftSidebar, Messages, RightSidebar, MessageInputComponent } from '../components';
14
+ import { Store, userSelector } from '@adminide-stack/user-auth0-client';
15
+ import { IUserState } from '@adminide-stack/core';
16
+ import { config } from '../config';
17
+ import { applyFooterStyles } from './apply-footer-styles';
18
+ import { objectId } from '@messenger-box/core';
19
+ import { ThreadsInbox } from './ThreadsInbox';
20
+ import { ThreadMessagesInbox } from './ThreadMessagesInbox';
21
+ import { useApolloClient } from '@apollo/client';
22
+ import { SubscriptionHandler } from '../components/InboxMessage/SubscriptionHandler';
23
+
24
+ const { MESSAGES_PER_PAGE } = config;
25
+
26
+ // Types
27
+ interface DrawerProps {
28
+ isOpen: boolean;
29
+ onClose: () => void;
30
+ children: ReactNode;
31
+ title?: string;
32
+ }
33
+
34
+ export interface InboxProps {
35
+ channelFilters?: Record<string, unknown>;
36
+ channelRole?: string;
37
+ supportServices?: boolean;
38
+ pathPrefix?: string;
39
+ data?: any;
40
+ orgName?: string;
41
+ }
42
+
43
+ interface MobilePreviewState {
44
+ mobilePreviewVisibility: boolean;
45
+ mobilePreviewText: string | ReactNode;
46
+ mobilePreviewCTAText: string | ReactNode;
47
+ }
48
+
49
+ // Static utility hooks and components
50
+ const useMediaQuery = (query: string) => {
51
+ const [matches, setMatches] = React.useState(false);
52
+
53
+ useEffect(() => {
54
+ if (typeof window === 'undefined') return;
55
+
56
+ const mediaQuery = window.matchMedia(query);
57
+ const updateMatches = () => setMatches(mediaQuery.matches);
58
+
59
+ updateMatches();
60
+ mediaQuery.addEventListener('change', updateMatches);
61
+ return () => mediaQuery.removeEventListener('change', updateMatches);
62
+ }, [query]);
63
+
64
+ return matches;
65
+ };
66
+
67
+ // Hook to get window dimensions
68
+ const useWindowDimensions = () => {
69
+ const [windowDimensions, setWindowDimensions] = React.useState({
70
+ width: typeof window !== 'undefined' ? window.innerWidth : 1024,
71
+ height: typeof window !== 'undefined' ? window.innerHeight : 768,
72
+ });
73
+
74
+ useEffect(() => {
75
+ if (typeof window === 'undefined') return;
76
+
77
+ const handleResize = () => {
78
+ setWindowDimensions({
79
+ width: window.innerWidth,
80
+ height: window.innerHeight,
81
+ });
82
+ };
83
+
84
+ window.addEventListener('resize', handleResize);
85
+ handleResize(); // Set initial dimensions
86
+
87
+ return () => window.removeEventListener('resize', handleResize);
88
+ }, []);
89
+
90
+ return windowDimensions;
91
+ };
92
+
93
+ // Static components
94
+ const Spinner = React.memo(({ className = '' }: { className?: string }) => (
95
+ <div className={`animate-spin rounded-full border-4 border-gray-200 border-t-blue-500 ${className}`}>
96
+ <span className="sr-only">Loading...</span>
97
+ </div>
98
+ ));
99
+
100
+ const Drawer = React.memo(({ isOpen, onClose, children, title }: DrawerProps) => {
101
+ if (!isOpen) return null;
102
+
103
+ return (
104
+ <div className="fixed inset-0 z-50 overflow-hidden">
105
+ <div className="absolute inset-0 bg-black bg-opacity-50" onClick={onClose} />
106
+ <div className="absolute bottom-0 left-0 right-0 bg-white rounded-t-lg shadow-lg max-h-[80vh] flex flex-col overflow-hidden">
107
+ <div className="flex items-center justify-between p-4 border-b border-gray-200 flex-shrink-0">
108
+ <h2 className="text-lg font-semibold truncate">{title}</h2>
109
+ <button
110
+ onClick={onClose}
111
+ className="p-1 hover:bg-gray-100 rounded-full transition-colors flex-shrink-0 ml-2"
112
+ >
113
+ <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
114
+ <path
115
+ strokeLinecap="round"
116
+ strokeLinejoin="round"
117
+ strokeWidth={2}
118
+ d="M6 18L18 6M6 6l12 12"
119
+ />
120
+ </svg>
121
+ </button>
122
+ </div>
123
+ <div className="flex-1 p-4 overflow-y-auto" style={{ minHeight: 0 }}>
124
+ {children}
125
+ </div>
126
+ </div>
127
+ </div>
128
+ );
129
+ });
130
+
131
+ const EmptyState = React.memo(() => (
132
+ <div className="h-full flex items-center justify-center bg-gray-100 p-4 sm:p-6 overflow-hidden">
133
+ <div className="text-center max-w-sm mx-auto">
134
+ <div className="text-3xl sm:text-4xl text-gray-400 mb-4">💬</div>
135
+ <h3 className="text-lg sm:text-xl font-semibold text-gray-600 mb-2">Welcome to Messenger</h3>
136
+ <p className="text-sm sm:text-base text-gray-500 leading-relaxed">
137
+ Select a conversation from the sidebar to start messaging
138
+ </p>
139
+ </div>
140
+ </div>
141
+ ));
142
+
143
+ // Mobile preview reducer
144
+ const mobilePreviewReducer = (
145
+ state: MobilePreviewState,
146
+ action: { payload: Partial<MobilePreviewState>; type: string },
147
+ ) => {
148
+ if (action.type === 'update') {
149
+ return { ...state, ...action.payload };
150
+ }
151
+ return state;
152
+ };
153
+
154
+ const Inbox = (props: InboxProps) => {
155
+ const { channelFilters: channelFilterProp, channelRole, supportServices, data, orgName, pathPrefix = null } = props;
156
+ const { id: pathChannelId, postId: pathPostId } = useParams();
157
+ const navigate = useNavigate();
158
+ const apolloClient = useApolloClient();
159
+
160
+ // Reduced state - only UI state remains, data comes from Apollo cache
161
+ const [isBottomDrawerOpen, setBottomDrawer] = React.useState(false);
162
+ const [mobilePreviewState, localDispatch] = useReducer(mobilePreviewReducer, {
163
+ mobilePreviewVisibility: false,
164
+ mobilePreviewText: false,
165
+ mobilePreviewCTAText: false,
166
+ });
167
+
168
+ // Hooks - improved responsive breakpoints with better granularity
169
+ const { width: windowWidth, height: windowHeight } = useWindowDimensions();
170
+ const isMobileView = useMediaQuery('(max-width: 640px)');
171
+ const isSmallTabletView = useMediaQuery('(min-width: 641px) and (max-width: 900px)');
172
+ const isTabletView = useMediaQuery('(min-width: 901px) and (max-width: 1024px)');
173
+ const isDesktopView = useMediaQuery('(min-width: 1025px)');
174
+ const isLargeDesktopView = useMediaQuery('(min-width: 1440px)');
175
+ const isSmallScreen = useMediaQuery('(max-width: 900px)');
176
+ // const auth = useSelector(userSelector);
177
+ const auth: any = useSelector<Store.Auth, IUserState>(userSelector, shallowEqual);
178
+ // const user = useSelector((state: any) => state.user, shallowEqual);
179
+
180
+ // Data destructuring from Apollo queries
181
+ const GetChannelsByUserQuery = data?.[0];
182
+ const {
183
+ data: userChannels,
184
+ loading: userChannelsLoading,
185
+ refetch: getChannelsRefetch,
186
+ } = GetChannelsByUserQuery || {};
187
+
188
+ // Get data directly from Apollo cache instead of local state
189
+ const channels = useMemo(() => {
190
+ if (!userChannels?.channelsByUser && !userChannels?.supportServiceChannels) return [];
191
+
192
+ return uniqBy([...(userChannels?.supportServiceChannels ?? []), ...(userChannels?.channelsByUser ?? [])], 'id');
193
+ }, [userChannels]);
194
+
195
+ // Memoize stable channel array to prevent unnecessary re-renders
196
+ const stableChannels = useMemo(() => {
197
+ return channels || [];
198
+ }, [channels]);
199
+
200
+ // Memoized values derived from Apollo cache data
201
+ const channelFilters = useMemo(() => {
202
+ const filters = { ...channelFilterProp };
203
+ const channelType = filters?.type ?? RoomType.Direct;
204
+ filters.type = supportServices ? [channelType, RoomType.Service] : channelType;
205
+ return filters;
206
+ }, [channelFilterProp, supportServices]);
207
+
208
+ const users = useMemo(() => {
209
+ return (
210
+ channels?.reduce((acc, curr) => {
211
+ const newMembers = curr.members?.filter(({ user }) => !acc.find(({ id }) => id === user.id)) || [];
212
+ return [...acc, ...newMembers.map(({ user }) => user)];
213
+ }, []) || []
214
+ );
215
+ }, [channels]);
216
+
217
+ // const currentUser = useMemo(
218
+ // () => users?.find((user) => user && user.alias?.includes(auth?.authUserId)),
219
+ // [users, auth?.authUserId],
220
+ // );
221
+ const currentUser = auth;
222
+
223
+ const channelName = useMemo(() => {
224
+ if (!channels || !pathChannelId) return '';
225
+
226
+ const currChannel = channels?.find((ch) => ch.id === pathChannelId);
227
+ if (!currChannel) return '';
228
+
229
+ const { members, title, type } = currChannel;
230
+
231
+ if (type === RoomType.Direct && members?.length >= 2) {
232
+ const otherUser = members.find((member) => member.user.id !== currentUser?.id);
233
+ if (otherUser?.user) {
234
+ const { givenName, familyName } = otherUser.user;
235
+ if (givenName && familyName) return `${givenName} ${familyName}`;
236
+ return givenName || familyName || title || 'Direct Message';
237
+ }
238
+ return title || 'Direct Message';
239
+ }
240
+
241
+ if (type === RoomType.Direct && members?.length === 1) {
242
+ if (members[0].user?.givenName && members[0]?.user?.familyName) {
243
+ return `${members[0].user?.givenName} ${members[0].user?.familyName}`;
244
+ }
245
+ return members[0].user?.givenName || members[0].user?.familyName || 'Direct Message';
246
+ }
247
+
248
+ return title || 'Channel';
249
+ }, [channels, pathChannelId, currentUser]);
250
+
251
+ // Effects
252
+ useEffect(() => {
253
+ applyFooterStyles();
254
+
255
+ // Optimistic refetch with cache update
256
+ const timeout = setTimeout(() => {
257
+ getChannelsRefetch?.({
258
+ role: channelRole,
259
+ criteria: orgName
260
+ ? { ...channelFilters, orgName: channelFilters?.orgName || orgName || '' }
261
+ : channelFilters,
262
+ supportServices: !!supportServices,
263
+ supportServiceCriteria: { type: RoomType.Service },
264
+ });
265
+ }, 0);
266
+ return () => clearTimeout(timeout);
267
+ }, [channelRole, channelFilters, supportServices, getChannelsRefetch]);
268
+
269
+ // Optimistic navigation with cache updates
270
+ const handleSelectChannel = useCallback(
271
+ async (channelId: string, pId: string | null = null) => {
272
+ // Optimistic UI update
273
+ const mainPath = orgName
274
+ ? pId
275
+ ? `/o/${orgName}/ai-messenger/${channelId}/${pId}`
276
+ : `/o/${orgName}/ai-messenger/${channelId}`
277
+ : pId
278
+ ? `/inbox/${channelId}/${pId}`
279
+ : `/inbox/${channelId}`;
280
+ const basePath = pathPrefix ? `${pathPrefix}${mainPath}` : mainPath;
281
+
282
+ const searchParams = new URLSearchParams();
283
+ // if (channelRole) searchParams.set('channelRole', channelRole);
284
+ // if (orgName) searchParams.set('orgName', orgName);
285
+
286
+ const newPath = searchParams.toString() ? `${basePath}?${searchParams.toString()}` : basePath;
287
+ navigate(newPath, { replace: true });
288
+
289
+ // Optimistically update Apollo cache for immediate UI feedback
290
+ try {
291
+ apolloClient.writeQuery({
292
+ query: MessagesDocument,
293
+ variables: {
294
+ channelId: channelId.toString(),
295
+ parentId: null,
296
+ limit: MESSAGES_PER_PAGE,
297
+ },
298
+ data: {
299
+ messages: {
300
+ __typename: 'Messages',
301
+ data: [],
302
+ totalCount: 0,
303
+ messagesRefId: channelId,
304
+ },
305
+ },
306
+ });
307
+ } catch (error) {
308
+ // Cache write might fail if query hasn't been executed yet, that's OK
309
+ console.debug('Cache write failed (expected on first load):', error);
310
+ }
311
+ },
312
+ [navigate, apolloClient, orgName, channelRole, pathPrefix],
313
+ );
314
+
315
+ const detailSidebarOptions = useMemo(
316
+ () => ({
317
+ isMobileView,
318
+ isSmallTabletView,
319
+ isTabletView,
320
+ isDesktopView,
321
+ isLargeDesktopView,
322
+ isSmallScreen,
323
+ setMobilePreviewCTAText: (v: string | ReactNode) =>
324
+ localDispatch({ payload: { mobilePreviewCTAText: v }, type: 'update' }),
325
+ setMobilePreviewText: (v: string | ReactNode) =>
326
+ localDispatch({ payload: { mobilePreviewText: v }, type: 'update' }),
327
+ setMobilePreviewVisibility: (v: boolean) =>
328
+ localDispatch({ payload: { mobilePreviewVisibility: v }, type: 'update' }),
329
+ }),
330
+ [isMobileView, isSmallTabletView, isTabletView, isDesktopView, isLargeDesktopView, isSmallScreen],
331
+ );
332
+
333
+ return (
334
+ <div
335
+ className="border-t border-gray-300 flex overflow-hidden"
336
+ style={{
337
+ height: `${windowHeight}px`,
338
+ maxHeight: '100vh',
339
+ }}
340
+ >
341
+ {/* Left Sidebar - Responsive Design */}
342
+ <div
343
+ className={`
344
+ flex-shrink-0 bg-gray-50 border-r border-gray-300 overflow-hidden transition-all duration-300 ease-in-out
345
+ ${isMobileView && pathChannelId ? 'hidden' : ''}
346
+ `}
347
+ style={{
348
+ width:
349
+ isMobileView && !pathChannelId
350
+ ? '100%'
351
+ : isMobileView && pathChannelId
352
+ ? '0px'
353
+ : isSmallTabletView
354
+ ? `${Math.min(288, windowWidth * 0.35)}px` // w-72 or 35% of window
355
+ : isTabletView
356
+ ? `${Math.min(320, windowWidth * 0.3)}px` // w-80 or 30% of window
357
+ : isLargeDesktopView
358
+ ? `${Math.min(384, windowWidth * 0.25)}px` // w-96 or 25% of window
359
+ : `${Math.min(320, windowWidth * 0.28)}px`, // w-80 or 28% of window
360
+ height: `${windowHeight}px`,
361
+ maxHeight: '100vh',
362
+ }}
363
+ >
364
+ <LeftSidebar
365
+ currentUser={currentUser}
366
+ userChannels={stableChannels}
367
+ userChannelsLoading={userChannelsLoading}
368
+ users={users}
369
+ handleSelectChannel={handleSelectChannel}
370
+ selectedChannelId={pathChannelId}
371
+ channelToTop={0}
372
+ getChannelsRefetch={getChannelsRefetch}
373
+ role={channelRole}
374
+ messagesQuery={data?.[1]}
375
+ windowHeight={windowHeight}
376
+ windowWidth={windowWidth}
377
+ />
378
+ </div>
379
+
380
+ {/* Main Content Area - Responsive */}
381
+ <div
382
+ className={`
383
+ flex-1 min-w-0 flex flex-col overflow-hidden transition-all duration-300 ease-in-out
384
+ ${isMobileView && !pathChannelId ? 'hidden' : 'flex'}
385
+ `}
386
+ style={{
387
+ minWidth: isSmallScreen ? '300px' : isDesktopView ? '500px' : '400px',
388
+ width: 'auto',
389
+ height: `${windowHeight}px`,
390
+ maxHeight: '100vh',
391
+ }}
392
+ >
393
+ {pathChannelId ? (
394
+ <ContentComponent
395
+ channelId={pathChannelId}
396
+ postId={pathPostId}
397
+ channelRole={channelRole}
398
+ pathPrefix={props.pathPrefix}
399
+ isMobileView={isMobileView}
400
+ isSmallTabletView={isSmallTabletView}
401
+ isTabletView={isTabletView}
402
+ isDesktopView={isDesktopView}
403
+ isLargeDesktopView={isLargeDesktopView}
404
+ isSmallScreen={isSmallScreen}
405
+ windowWidth={windowWidth}
406
+ windowHeight={windowHeight}
407
+ mobilePreviewState={mobilePreviewState}
408
+ detailSidebarOptions={detailSidebarOptions}
409
+ isBottomDrawerOpen={isBottomDrawerOpen}
410
+ setBottomDrawer={setBottomDrawer}
411
+ channelName={channelName}
412
+ loaderdata={data}
413
+ />
414
+ ) : (
415
+ <EmptyState />
416
+ )}
417
+ </div>
418
+
419
+ {/* Right Sidebar - Desktop Only */}
420
+ {pathChannelId && data?.[1] && isDesktopView && (
421
+ <div
422
+ className="border-l border-gray-200 bg-white flex-shrink-0 overflow-hidden"
423
+ style={{
424
+ width: `${windowWidth * 0.35}px`, // 40% of window width
425
+ height: `${windowHeight}px`,
426
+ maxHeight: '100vh',
427
+ }}
428
+ >
429
+ <RightSidebarWrapper
430
+ MessagesLoaderQuery={data?.[1]}
431
+ selectedPost={null}
432
+ detailSidebarOptions={detailSidebarOptions}
433
+ />
434
+ </div>
435
+ )}
436
+ </div>
437
+ );
438
+ };
439
+
440
+ const ContentComponent = React.memo((props: any) => {
441
+ const {
442
+ channelId,
443
+ channelRole,
444
+ pathPrefix,
445
+ postId,
446
+ isMobileView,
447
+ isSmallTabletView,
448
+ isTabletView,
449
+ isDesktopView,
450
+ isLargeDesktopView,
451
+ isSmallScreen,
452
+ windowWidth,
453
+ windowHeight,
454
+ mobilePreviewState,
455
+ detailSidebarOptions,
456
+ isBottomDrawerOpen,
457
+ setBottomDrawer,
458
+ channelName,
459
+ loaderdata,
460
+ } = props;
461
+
462
+ const ViewChannelDetailLoaderQuery = loaderdata?.[2];
463
+ const MessagesLoaderQuery = loaderdata?.[1];
464
+
465
+ const [selectedPost, setSelectedPost] = React.useState(null);
466
+ const { data: channelData, loading: channelLoading } = ViewChannelDetailLoaderQuery || {};
467
+
468
+ const onMessageClick = useCallback((msg: any) => {
469
+ setSelectedPost(msg);
470
+ }, []);
471
+
472
+ const channelsDetail = useMemo(() => {
473
+ return channelData?.viewChannelDetail || null;
474
+ }, [channelData]);
475
+
476
+ return (
477
+ <div className="flex overflow-hidden" style={{ height: `${windowHeight}px`, maxHeight: '100vh' }}>
478
+ {/* Main Chat Content */}
479
+ <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
480
+ {/* Channel Header */}
481
+ {channelId && (
482
+ <div
483
+ className={`border-b border-gray-200 bg-white flex-shrink-0 z-10 ${
484
+ isSmallScreen ? 'px-3 py-3' : 'px-4 sm:px-6 py-4'
485
+ }`}
486
+ >
487
+ <div className="flex items-center justify-between">
488
+ <div className="flex items-center space-x-2 min-w-0 flex-1">
489
+ {/* Mobile/Small Screen Back Button */}
490
+ {(isMobileView || isSmallTabletView) && (
491
+ <button
492
+ className="p-2 hover:bg-gray-100 rounded-full transition-colors flex-shrink-0"
493
+ onClick={() => window.history.back()}
494
+ aria-label="Go back"
495
+ >
496
+ <svg
497
+ className="w-5 h-5 text-gray-600"
498
+ fill="none"
499
+ stroke="currentColor"
500
+ viewBox="0 0 24 24"
501
+ >
502
+ <path
503
+ strokeLinecap="round"
504
+ strokeLinejoin="round"
505
+ strokeWidth={2}
506
+ d="M15 19l-7-7 7-7"
507
+ />
508
+ </svg>
509
+ </button>
510
+ )}
511
+ <h2
512
+ className={`font-semibold text-gray-800 truncate ${
513
+ isSmallScreen ? 'text-base' : 'text-lg'
514
+ }`}
515
+ >
516
+ {channelName}
517
+ </h2>
518
+ </div>
519
+ {(isMobileView || isSmallTabletView) && mobilePreviewState?.mobilePreviewVisibility && (
520
+ <button
521
+ className="text-sm px-3 py-1 bg-teal-500 hover:bg-teal-600 text-white rounded-md transition-colors flex-shrink-0"
522
+ onClick={() => setBottomDrawer(true)}
523
+ >
524
+ {mobilePreviewState?.mobilePreviewCTAText}
525
+ </button>
526
+ )}
527
+ </div>
528
+ </div>
529
+ )}
530
+
531
+ {/* Mobile Preview */}
532
+ {(isMobileView || isSmallTabletView) && channelId && mobilePreviewState?.mobilePreviewVisibility && (
533
+ <div className={`mt-4 ${isSmallScreen ? 'mx-3' : 'mx-4'}`}>
534
+ <div className="mb-2">
535
+ <div className="w-full flex justify-between items-center gap-2 mb-[5px]">
536
+ <span className="truncate flex-1 text-sm">{mobilePreviewState?.mobilePreviewText}</span>
537
+ <button
538
+ className="text-sm px-3 py-2 bg-teal-500 hover:bg-teal-600 text-white rounded-md transition-colors flex-shrink-0"
539
+ onClick={() => setBottomDrawer(true)}
540
+ >
541
+ {mobilePreviewState?.mobilePreviewCTAText}
542
+ </button>
543
+ </div>
544
+ </div>
545
+ <hr className="border-gray-200" />
546
+ </div>
547
+ )}
548
+
549
+ {/* Content based on postId */}
550
+ <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
551
+ {channelId && (
552
+ <>
553
+ {postId ? (
554
+ postId === '1' ? (
555
+ <ThreadsInbox
556
+ channelId={channelId}
557
+ role={channelRole}
558
+ pathPrefix={pathPrefix}
559
+ setChannelId={() => {}}
560
+ setPostId={() => {}}
561
+ setGoBack={() => {}}
562
+ />
563
+ ) : (
564
+ <ThreadMessagesInbox
565
+ channelId={channelId}
566
+ postId={postId}
567
+ role={channelRole}
568
+ goBack={false}
569
+ pathPrefix={pathPrefix}
570
+ setPostId={() => {}}
571
+ setChannelId={() => {}}
572
+ onMessageClick={onMessageClick}
573
+ />
574
+ )
575
+ ) : (
576
+ <MessagesComponent
577
+ channelId={channelId}
578
+ MessagesLoaderQuery={MessagesLoaderQuery}
579
+ channelsDetail={channelsDetail}
580
+ channelLoading={channelLoading}
581
+ onMessageClick={onMessageClick}
582
+ isSmallScreen={isSmallScreen}
583
+ isDesktopView={isDesktopView}
584
+ windowHeight={windowHeight}
585
+ windowWidth={windowWidth}
586
+ />
587
+ )}
588
+ </>
589
+ )}
590
+ </div>
591
+ </div>
592
+
593
+ {/* Mobile/Small Screen Drawer */}
594
+ {(isMobileView || isSmallTabletView) && (
595
+ <Drawer
596
+ isOpen={isBottomDrawerOpen}
597
+ onClose={() => setBottomDrawer(false)}
598
+ title={mobilePreviewState.mobilePreviewText as string}
599
+ >
600
+ <RightSidebarWrapper
601
+ MessagesLoaderQuery={MessagesLoaderQuery}
602
+ selectedPost={selectedPost}
603
+ detailSidebarOptions={detailSidebarOptions}
604
+ />
605
+ </Drawer>
606
+ )}
607
+ </div>
608
+ );
609
+ });
610
+
611
+ const RightSidebarWrapper = React.memo(({ MessagesLoaderQuery, selectedPost, detailSidebarOptions }: any) => {
612
+ const { data } = MessagesLoaderQuery || {};
613
+ const [activeTab, setActiveTab] = React.useState('preview');
614
+
615
+ const sortedMessages = useMemo(() => {
616
+ const messages = data?.messages?.data || [];
617
+ return orderBy(uniqBy(messages, 'id'), ['createdAt'], ['asc']);
618
+ }, [data?.messages?.data]);
619
+
620
+ const handleRefreshSandbox = useCallback(() => {
621
+ // Refresh sandbox functionality
622
+ console.log('Refreshing sandbox...');
623
+ // Add actual refresh logic here
624
+ }, []);
625
+
626
+ if (!sortedMessages.length) return null;
627
+
628
+ return (
629
+ <div className="h-full flex flex-col overflow-hidden bg-white">
630
+ {/* Header with tabs and refresh icon */}
631
+ <div className="flex-shrink-0 border-b border-gray-200">
632
+ <div className="flex items-center justify-between px-4 py-3">
633
+ <div className="flex items-center space-x-1">
634
+ <button
635
+ onClick={() => setActiveTab('preview')}
636
+ className={`flex items-center space-x-2 px-3 py-2 text-sm font-medium rounded-lg transition-colors ${
637
+ activeTab === 'preview'
638
+ ? 'bg-gray-100 text-gray-900'
639
+ : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
640
+ }`}
641
+ >
642
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
643
+ <path
644
+ strokeLinecap="round"
645
+ strokeLinejoin="round"
646
+ strokeWidth={2}
647
+ d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
648
+ />
649
+ <path
650
+ strokeLinecap="round"
651
+ strokeLinejoin="round"
652
+ strokeWidth={2}
653
+ d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
654
+ />
655
+ </svg>
656
+ <span>Preview</span>
657
+ </button>
658
+ <button
659
+ onClick={() => setActiveTab('code')}
660
+ className={`flex items-center space-x-2 px-3 py-2 text-sm font-medium rounded-lg transition-colors ${
661
+ activeTab === 'code'
662
+ ? 'bg-gray-100 text-gray-900'
663
+ : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
664
+ }`}
665
+ >
666
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
667
+ <path
668
+ strokeLinecap="round"
669
+ strokeLinejoin="round"
670
+ strokeWidth={2}
671
+ d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"
672
+ />
673
+ </svg>
674
+ <span>Code</span>
675
+ </button>
676
+ </div>
677
+
678
+ {/* Refresh icon on the right */}
679
+ <button
680
+ onClick={handleRefreshSandbox}
681
+ className="p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-50 rounded-lg transition-colors"
682
+ title="Refresh Sandbox"
683
+ >
684
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
685
+ <path
686
+ strokeLinecap="round"
687
+ strokeLinejoin="round"
688
+ strokeWidth={2}
689
+ d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
690
+ />
691
+ </svg>
692
+ </button>
693
+ </div>
694
+ <hr className="border-gray-300 my-6" />
695
+ {/* Refresh Sandbox Button - Below tabs, aligned right */}
696
+ <div className="px-4 pb-3 flex justify-end">
697
+ <button
698
+ onClick={handleRefreshSandbox}
699
+ className="flex items-center space-x-2 px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-900 hover:bg-gray-50 rounded-lg transition-colors border border-gray-200"
700
+ title="Refresh Sandbox"
701
+ >
702
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
703
+ <path
704
+ strokeLinecap="round"
705
+ strokeLinejoin="round"
706
+ strokeWidth={2}
707
+ d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
708
+ />
709
+ </svg>
710
+ <span>Refresh Sandbox</span>
711
+ </button>
712
+ </div>
713
+ </div>
714
+
715
+ {/* Content Area */}
716
+ <div className="flex-1 overflow-hidden">
717
+ {activeTab === 'preview' ? (
718
+ <div className="h-full flex items-center justify-center bg-gray-50">
719
+ <div className="text-center">
720
+ {/* Next.js Logo */}
721
+ <div className="mb-8">
722
+ <svg className="w-32 h-16 mx-auto text-black" viewBox="0 0 394 80" fill="currentColor">
723
+ <path d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.4zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.7h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z" />
724
+ <path d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.2 3.4 1 1.4 1.5 3 1.5 5h-5.8z" />
725
+ </svg>
726
+ </div>
727
+
728
+ <div className="space-y-4 text-gray-600">
729
+ <h3 className="text-lg font-semibold text-gray-900">Get started by editing</h3>
730
+ <p className="font-mono text-sm bg-gray-100 px-3 py-1 rounded">app/page.tsx</p>
731
+ <p>Save and see your changes instantly.</p>
732
+ </div>
733
+
734
+ <div className="mt-8 space-y-4">
735
+ <button className="bg-black text-white px-6 py-3 rounded-full hover:bg-gray-800 transition-colors flex items-center space-x-2 mx-auto">
736
+ <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
737
+ <path d="M12 2L2 7v10c0 5.55 3.84 9.739 9 11 5.16-1.261 9-5.45 9-11V7l-10-5z" />
738
+ </svg>
739
+ <span>Deploy now</span>
740
+ </button>
741
+ <p className="text-sm text-gray-500 underline cursor-pointer hover:text-gray-700">
742
+ Read our docs
743
+ </p>
744
+ </div>
745
+ </div>
746
+ </div>
747
+ ) : (
748
+ <div className="h-full bg-gray-900 text-gray-300 p-4 overflow-auto">
749
+ <div className="font-mono text-sm">
750
+ <div className="mb-4">
751
+ <div className="text-green-400">// app/page.tsx</div>
752
+ </div>
753
+ <div className="space-y-2">
754
+ <div>
755
+ <span className="text-purple-400">export</span>{' '}
756
+ <span className="text-purple-400">default</span>{' '}
757
+ <span className="text-blue-400">function</span>{' '}
758
+ <span className="text-yellow-400">Home</span>() {'{'}
759
+ </div>
760
+ <div className="ml-4">
761
+ <span className="text-purple-400">return</span> (
762
+ </div>
763
+ <div className="ml-8">
764
+ {'<'}
765
+ <span className="text-red-400">main</span>{' '}
766
+ <span className="text-green-400">className</span>=
767
+ <span className="text-yellow-400">
768
+ "flex min-h-screen flex-col items-center justify-between p-24"
769
+ </span>
770
+ {'>'}
771
+ </div>
772
+ <div className="ml-12">
773
+ {'<'}
774
+ <span className="text-red-400">div</span>{' '}
775
+ <span className="text-green-400">className</span>=
776
+ <span className="text-yellow-400">
777
+ "z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex"
778
+ </span>
779
+ {'>'}
780
+ </div>
781
+ <div className="ml-16">
782
+ {'<'}
783
+ <span className="text-red-400">p</span>{' '}
784
+ <span className="text-green-400">className</span>=
785
+ <span className="text-yellow-400">
786
+ "fixed left-0 top-0 flex w-full justify-center border-b border-gray-300
787
+ bg-gradient-to-b from-zinc-200 pb-6 pt-8 backdrop-blur-2xl
788
+ dark:border-neutral-800 dark:bg-zinc-800/30 dark:from-inherit lg:static
789
+ lg:w-auto lg:rounded-xl lg:border lg:bg-gray-200 lg:p-4 lg:dark:bg-zinc-800/30"
790
+ </span>
791
+ {'>'}
792
+ </div>
793
+ <div className="ml-20 text-gray-400">Get started by editing&nbsp;</div>
794
+ <div className="ml-20">
795
+ {'<'}
796
+ <span className="text-red-400">code</span>{' '}
797
+ <span className="text-green-400">className</span>=
798
+ <span className="text-yellow-400">"font-mono font-bold"</span>
799
+ {'>'}app/page.tsx{'</'}
800
+ <span className="text-red-400">code</span>
801
+ {'>'}
802
+ </div>
803
+ <div className="ml-16">
804
+ {'</'}
805
+ <span className="text-red-400">p</span>
806
+ {'>'}
807
+ </div>
808
+ <div className="ml-12">
809
+ {'</'}
810
+ <span className="text-red-400">div</span>
811
+ {'>'}
812
+ </div>
813
+ <div className="ml-8">
814
+ {'</'}
815
+ <span className="text-red-400">main</span>
816
+ {'>'}
817
+ </div>
818
+ <div className="ml-4">);</div>
819
+ <div>{'}'}</div>
820
+ </div>
821
+ </div>
822
+ </div>
823
+ )}
824
+ </div>
825
+ </div>
826
+ );
827
+ });
828
+
829
+ const MessagesComponent = React.memo((props: any) => {
830
+ const {
831
+ channelId,
832
+ MessagesLoaderQuery,
833
+ channelsDetail,
834
+ channelLoading,
835
+ onMessageClick,
836
+ isSmallScreen,
837
+ isDesktopView,
838
+ windowHeight = 768,
839
+ windowWidth = 1024,
840
+ } = props;
841
+
842
+ const messageRootListRef = useRef(null);
843
+ const messageListRef = useRef(null);
844
+ const apolloClient = useApolloClient();
845
+ const [isLoadingOlder, setIsLoadingOlder] = React.useState(false);
846
+ const isLoadingOlderRef = useRef(false);
847
+ const scrollTimeoutRef = useRef(null);
848
+
849
+ const auth = useSelector(userSelector);
850
+ const { startUpload } = useUploadFiles();
851
+ const [sendMsg] = useSendMessagesMutation();
852
+
853
+ const { data, loading: messageLoading, fetchMore: fetchMoreMessages, subscribeToMore } = MessagesLoaderQuery || {};
854
+
855
+ // Get messages directly from Apollo cache
856
+ const messages = useMemo(() => {
857
+ const messagesData = data?.messages?.data || [];
858
+ return orderBy(uniqBy(messagesData, 'id'), ['createdAt'], ['asc']);
859
+ }, [data?.messages?.data]);
860
+
861
+ const totalCount = data?.messages?.totalCount || 0;
862
+
863
+ const scrollToBottom = useCallback(() => {
864
+ if (messageRootListRef?.current) {
865
+ messageRootListRef.current.scrollTop = messageRootListRef.current.scrollHeight;
866
+ }
867
+ }, []);
868
+
869
+ // Auto-scroll on new messages (but not when loading older messages)
870
+ useEffect(() => {
871
+ if (!isLoadingOlderRef.current) {
872
+ const timer = setTimeout(() => scrollToBottom(), 100);
873
+ return () => clearTimeout(timer);
874
+ }
875
+ }, [messages.length, scrollToBottom]);
876
+
877
+ const onFetchOld = useCallback(
878
+ async (skip: number) => {
879
+ if (channelId && fetchMoreMessages && !isLoadingOlder) {
880
+ try {
881
+ setIsLoadingOlder(true);
882
+ isLoadingOlderRef.current = true;
883
+ // Capture current scroll height before fetching
884
+ const oldScrollHeight = messageRootListRef?.current?.scrollHeight || 0;
885
+
886
+ await fetchMoreMessages({
887
+ variables: {
888
+ channelId: channelId.toString(),
889
+ parentId: null,
890
+ skip,
891
+ },
892
+ updateQuery: (prev, { fetchMoreResult }) => {
893
+ if (!fetchMoreResult) return prev;
894
+
895
+ const newMessages = fetchMoreResult.messages.data;
896
+ const existingMessages = prev.messages?.data || [];
897
+
898
+ return {
899
+ ...prev,
900
+ messages: {
901
+ ...fetchMoreResult.messages,
902
+ data: uniqBy([...newMessages, ...existingMessages], 'id'),
903
+ },
904
+ };
905
+ },
906
+ });
907
+
908
+ // Maintain scroll position after loading older messages
909
+ setTimeout(() => {
910
+ if (messageRootListRef?.current) {
911
+ const newScrollHeight = messageRootListRef.current.scrollHeight;
912
+ const scrollDiff = newScrollHeight - oldScrollHeight;
913
+ // For normal flex layout, maintain position by adjusting scroll offset
914
+ messageRootListRef.current.scrollTop = scrollDiff;
915
+ }
916
+ // Reset the loading flag after position is maintained
917
+ setTimeout(() => {
918
+ isLoadingOlderRef.current = false;
919
+ }, 50);
920
+ }, 100);
921
+ } catch (error) {
922
+ console.error('Error fetching older messages:', error);
923
+ isLoadingOlderRef.current = false;
924
+ } finally {
925
+ setIsLoadingOlder(false);
926
+ }
927
+ }
928
+ },
929
+ [channelId, fetchMoreMessages, isLoadingOlder],
930
+ );
931
+
932
+ // Scroll to bottom when channel changes
933
+ useEffect(() => {
934
+ if (channelId && messages.length > 0) {
935
+ isLoadingOlderRef.current = false; // Reset flag on channel change
936
+ const timer = setTimeout(() => scrollToBottom(), 200);
937
+ return () => clearTimeout(timer);
938
+ }
939
+ }, [channelId, scrollToBottom]);
940
+
941
+ // Alternative scroll detection for Firefox
942
+ useEffect(() => {
943
+ const element = messageRootListRef.current;
944
+ if (!element) return;
945
+
946
+ // Firefox-specific scroll detection using passive listeners
947
+ const handleScrollEnd = () => {
948
+ if (!isLoadingOlder && element) {
949
+ const { scrollTop } = element;
950
+ const isAtTop = Math.round(scrollTop) <= 30;
951
+ const hasMoreMessages = totalCount > messages.length;
952
+
953
+ if (isAtTop && hasMoreMessages) {
954
+ console.log('ScrollEnd triggered load more (Firefox):', {
955
+ scrollTop: Math.round(scrollTop),
956
+ totalCount,
957
+ messagesLength: messages.length,
958
+ });
959
+ onFetchOld(messages.length);
960
+ }
961
+ }
962
+ };
963
+
964
+ // Use scrollend event if available (modern Firefox/Chrome)
965
+ if ('onscrollend' in element) {
966
+ element.addEventListener('scrollend', handleScrollEnd, { passive: true });
967
+ return () => {
968
+ element.removeEventListener('scrollend', handleScrollEnd);
969
+ };
970
+ }
971
+ }, [totalCount, messages.length, onFetchOld, isLoadingOlder]);
972
+
973
+ // Cleanup scroll timeout on unmount
974
+ useEffect(() => {
975
+ return () => {
976
+ if (scrollTimeoutRef.current) {
977
+ clearTimeout(scrollTimeoutRef.current);
978
+ }
979
+ };
980
+ }, []);
981
+
982
+ const onMessagesScroll = useCallback(
983
+ async (e: any) => {
984
+ // Throttle scroll events for better performance, especially in Firefox
985
+ if (scrollTimeoutRef.current) {
986
+ clearTimeout(scrollTimeoutRef.current);
987
+ }
988
+
989
+ scrollTimeoutRef.current = setTimeout(async () => {
990
+ if (messageRootListRef.current && !isLoadingOlder) {
991
+ const element = messageRootListRef.current;
992
+ const { clientHeight, scrollHeight, scrollTop } = element;
993
+
994
+ // Firefox-compatible scroll detection
995
+ // Use Math.ceil to handle Firefox's fractional scrollTop values
996
+ const isAtTop = Math.ceil(scrollTop) <= 25;
997
+ const hasMoreMessages = totalCount > messages.length;
998
+
999
+ // Additional Firefox-specific check
1000
+ const isFirefox = navigator.userAgent.includes('Firefox');
1001
+ const firefoxAdjustedTop = isFirefox ? Math.round(scrollTop) <= 30 : isAtTop;
1002
+
1003
+ if ((isAtTop || firefoxAdjustedTop) && hasMoreMessages) {
1004
+ console.log('Triggering load more:', {
1005
+ scrollTop: Math.ceil(scrollTop),
1006
+ originalScrollTop: scrollTop,
1007
+ totalCount,
1008
+ messagesLength: messages.length,
1009
+ scrollHeight,
1010
+ clientHeight,
1011
+ browser: isFirefox ? 'Firefox' : 'Other',
1012
+ isAtTop,
1013
+ firefoxAdjustedTop,
1014
+ });
1015
+ await onFetchOld(messages.length);
1016
+ }
1017
+ }
1018
+ }, 100);
1019
+ },
1020
+ [totalCount, messages.length, onFetchOld, isLoadingOlder],
1021
+ );
1022
+
1023
+ // Optimistic message sending with Apollo cache updates
1024
+ const handleSend = useCallback(
1025
+ async (message: string, files: any[] = []) => {
1026
+ // Allow sending if there's either a message or files
1027
+ if ((!message || !message.trim()) && (!files || files.length === 0)) return;
1028
+ if (!channelId) return;
1029
+
1030
+ try {
1031
+ const postId = objectId();
1032
+ const currentDate = new Date();
1033
+
1034
+ const createOptimisticMessage = (files?: any[]) => ({
1035
+ __typename: 'Post' as const,
1036
+ id: postId,
1037
+ message,
1038
+ createdAt: currentDate.toISOString(),
1039
+ updatedAt: currentDate.toISOString(),
1040
+ author: {
1041
+ __typename: 'UserAccount' as const,
1042
+ id: auth?.id,
1043
+ givenName: auth?.profile?.given_name || '',
1044
+ familyName: auth?.profile?.family_name || '',
1045
+ email: auth?.profile?.email || '',
1046
+ username: auth?.profile?.nickname || '',
1047
+ fullName: auth?.profile?.name || '',
1048
+ picture: auth?.profile?.picture || '',
1049
+ alias: [auth?.authUserId ?? ''],
1050
+ tokens: [],
1051
+ },
1052
+ isDelivered: false, // Will be true once confirmed by server
1053
+ isRead: false,
1054
+ type: 'TEXT' as PostTypeEnum,
1055
+ parentId: null,
1056
+ fromServer: false,
1057
+ channel: {
1058
+ __typename: 'Channel' as const,
1059
+ id: channelId,
1060
+ },
1061
+ propsConfiguration: {
1062
+ __typename: 'MachineConfiguration' as const,
1063
+ id: null,
1064
+ resource: '' as any,
1065
+ contents: null,
1066
+ keys: null,
1067
+ target: null,
1068
+ overrides: null,
1069
+ },
1070
+ props: {},
1071
+ files: {
1072
+ __typename: 'FilesInfo' as const,
1073
+ data: files || [],
1074
+ totalCount: files?.length || 0,
1075
+ },
1076
+ replies: {
1077
+ __typename: 'Messages' as const,
1078
+ data: [],
1079
+ totalCount: 0,
1080
+ },
1081
+ });
1082
+
1083
+ const optimisticMessage = createOptimisticMessage(files);
1084
+
1085
+ if (files?.length > 0) {
1086
+ const uploadResponse = await startUpload({
1087
+ file: files,
1088
+ saveUploadedFile: { variables: { postId } },
1089
+ createUploadLink: { variables: { postId } },
1090
+ });
1091
+
1092
+ const uploadedFiles = uploadResponse.data as unknown as IFileInfo[];
1093
+ if (uploadedFiles) {
1094
+ const fileIds = uploadedFiles.map((f: any) => f.id);
1095
+ await sendMsg({
1096
+ variables: { postId, channelId, content: message, files: fileIds },
1097
+ optimisticResponse: {
1098
+ __typename: 'Mutation',
1099
+ sendMessage: createOptimisticMessage(uploadedFiles),
1100
+ },
1101
+ update: (cache, { data: mutationData }) => {
1102
+ if (!mutationData?.sendMessage) return;
1103
+
1104
+ // Update messages cache optimistically
1105
+ const messagesQuery = {
1106
+ query: MessagesDocument,
1107
+ variables: {
1108
+ channelId: channelId.toString(),
1109
+ parentId: null,
1110
+ limit: MESSAGES_PER_PAGE,
1111
+ },
1112
+ };
1113
+
1114
+ try {
1115
+ const existingData = cache.readQuery(messagesQuery) as any;
1116
+ if (existingData?.messages) {
1117
+ cache.writeQuery({
1118
+ ...messagesQuery,
1119
+ data: {
1120
+ messages: {
1121
+ ...existingData.messages,
1122
+ data: [
1123
+ ...(existingData.messages.data || []),
1124
+ mutationData.sendMessage,
1125
+ ],
1126
+ totalCount: (existingData.messages.totalCount || 0) + 1,
1127
+ },
1128
+ },
1129
+ });
1130
+ }
1131
+ } catch (error) {
1132
+ console.debug('Cache update failed (expected on first message):', error);
1133
+ }
1134
+ },
1135
+ });
1136
+ }
1137
+ } else {
1138
+ await sendMsg({
1139
+ variables: { channelId, content: message },
1140
+ optimisticResponse: {
1141
+ __typename: 'Mutation',
1142
+ sendMessage: optimisticMessage,
1143
+ },
1144
+ update: (cache, { data: mutationData }) => {
1145
+ if (!mutationData?.sendMessage) return;
1146
+
1147
+ // Update messages cache optimistically
1148
+ const messagesQuery = {
1149
+ query: MessagesDocument,
1150
+ variables: {
1151
+ channelId: channelId.toString(),
1152
+ parentId: null,
1153
+ limit: MESSAGES_PER_PAGE,
1154
+ },
1155
+ };
1156
+
1157
+ try {
1158
+ const existingData = cache.readQuery(messagesQuery) as any;
1159
+ if (existingData?.messages) {
1160
+ cache.writeQuery({
1161
+ ...messagesQuery,
1162
+ data: {
1163
+ messages: {
1164
+ ...existingData.messages,
1165
+ data: [...(existingData.messages.data || []), mutationData.sendMessage],
1166
+ totalCount: (existingData.messages.totalCount || 0) + 1,
1167
+ },
1168
+ },
1169
+ });
1170
+ }
1171
+ } catch (error) {
1172
+ console.debug('Cache update failed (expected on first message):', error);
1173
+ }
1174
+ },
1175
+ });
1176
+ }
1177
+ } catch (error) {
1178
+ console.error('Error sending message:', error);
1179
+ }
1180
+ },
1181
+ [channelId, auth, startUpload, sendMsg],
1182
+ );
1183
+
1184
+ // Show loading spinner for initial load
1185
+ if ((messageLoading || channelLoading) && messages.length === 0) {
1186
+ return (
1187
+ <div className="flex-1 flex justify-center items-center">
1188
+ <Spinner className="w-12 h-12" />
1189
+ </div>
1190
+ );
1191
+ }
1192
+
1193
+ return (
1194
+ <>
1195
+ <div
1196
+ ref={messageRootListRef}
1197
+ className={`overflow-y-scroll bg-gray-50 ${
1198
+ isSmallScreen ? 'p-2 px-3' : isDesktopView ? 'p-6 px-8' : 'p-4 px-6'
1199
+ }`}
1200
+ onScroll={onMessagesScroll}
1201
+ style={{
1202
+ height: `${windowHeight - 140}px`, // Subtract header + input height
1203
+ maxHeight: '100vh',
1204
+ scrollbarWidth: 'thin',
1205
+ scrollbarColor: '#cbd5e0 #f7fafc',
1206
+ overflowY: 'scroll',
1207
+ WebkitOverflowScrolling: 'touch',
1208
+ }}
1209
+ >
1210
+ <div className="min-h-full">
1211
+ {messages.length > 0 ? (
1212
+ <>
1213
+ {/* Loading indicator for older messages at the top */}
1214
+ {isLoadingOlder && (
1215
+ <div className="flex justify-center py-4">
1216
+ <div className="flex items-center space-x-2 text-gray-500">
1217
+ <Spinner className="w-4 h-4" />
1218
+ <span className="text-sm">Loading older messages...</span>
1219
+ </div>
1220
+ </div>
1221
+ )}
1222
+ <Messages
1223
+ innerRef={messageListRef}
1224
+ channelId={channelId}
1225
+ currentUser={auth}
1226
+ channelMessages={messages}
1227
+ totalCount={totalCount}
1228
+ onMessageClick={onMessageClick}
1229
+ isDesktopView={isDesktopView || false}
1230
+ isSmallScreen={isSmallScreen || false}
1231
+ />
1232
+ <SubscriptionHandler
1233
+ subscribeToMore={subscribeToMore}
1234
+ document={CHAT_MESSAGE_ADDED}
1235
+ variables={{ channelId: channelId.toString() }}
1236
+ enabled={!!channelId && !!subscribeToMore}
1237
+ updateQuery={(prev: any, { subscriptionData }: any) => {
1238
+ console.log('Subscription updateQuery called:', { prev, subscriptionData });
1239
+ if (!subscriptionData.data) {
1240
+ console.log('No subscription data, returning prev');
1241
+ return prev;
1242
+ }
1243
+ const newMessage = subscriptionData.data.chatMessageAdded;
1244
+ console.log('New message received via subscription:', newMessage);
1245
+
1246
+ return {
1247
+ ...prev,
1248
+ messages: {
1249
+ ...prev?.messages,
1250
+ data: uniqBy([...(prev?.messages?.data || []), newMessage], 'id'),
1251
+ totalCount: (prev?.messages?.totalCount || 0) + 1,
1252
+ },
1253
+ };
1254
+ }}
1255
+ onError={(error) => {
1256
+ console.error('Subscription error:', error);
1257
+ }}
1258
+ />
1259
+ </>
1260
+ ) : (
1261
+ <div className="flex items-center justify-center text-gray-500 min-h-96">
1262
+ <div className="text-center max-w-sm mx-auto px-4">
1263
+ <div className="text-6xl mb-4 opacity-50">💬</div>
1264
+ <h3 className="text-lg font-semibold text-gray-600 mb-2">No messages yet</h3>
1265
+ <p className="text-sm text-gray-500">
1266
+ Start the conversation by sending a message below!
1267
+ </p>
1268
+ </div>
1269
+ </div>
1270
+ )}
1271
+ </div>
1272
+ </div>
1273
+ <div className="flex-shrink-0 border-t border-gray-200 bg-white">
1274
+ {/* Selection Options */}
1275
+ <div className="px-4 py-3 border-b border-gray-100">
1276
+ <div className="flex gap-3">
1277
+ {/* Framework Selection */}
1278
+ <div className="flex-1 relative">
1279
+ <button
1280
+ type="button"
1281
+ className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-left pr-10 flex items-center space-x-2"
1282
+ onClick={() => {
1283
+ const modal = document.getElementById('framework-modal');
1284
+ if (modal) {
1285
+ modal.classList.toggle('hidden');
1286
+ }
1287
+ }}
1288
+ >
1289
+ <div className="w-5 h-5 bg-purple-100 rounded flex items-center justify-center">⚛️</div>
1290
+ <span>Next.js</span>
1291
+ </button>
1292
+ <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
1293
+ <svg
1294
+ className="w-4 h-4 text-gray-400"
1295
+ fill="none"
1296
+ stroke="currentColor"
1297
+ viewBox="0 0 24 24"
1298
+ >
1299
+ <path
1300
+ strokeLinecap="round"
1301
+ strokeLinejoin="round"
1302
+ strokeWidth={2}
1303
+ d="M19 9l-7 7-7-7"
1304
+ />
1305
+ </svg>
1306
+ </div>
1307
+
1308
+ {/* Framework Modal */}
1309
+ <div
1310
+ id="framework-modal"
1311
+ className="hidden absolute bottom-full left-0 mb-1 w-80 bg-white border border-gray-200 rounded-lg shadow-lg z-50 p-4"
1312
+ >
1313
+ <div className="space-y-2">
1314
+ <div className="flex items-center justify-between p-3 hover:bg-gray-50 rounded cursor-pointer border border-blue-300 bg-blue-50">
1315
+ <div className="flex items-center space-x-3">
1316
+ <div className="w-8 h-8 bg-purple-100 rounded flex items-center justify-center">
1317
+ ⚛️
1318
+ </div>
1319
+ <div>
1320
+ <div className="text-sm font-medium">Next.js</div>
1321
+ <div className="text-xs text-gray-500">
1322
+ React + Next.js 15 with Shadcn UI
1323
+ </div>
1324
+ </div>
1325
+ </div>
1326
+ <svg className="w-4 h-4 text-blue-500" fill="currentColor" viewBox="0 0 20 20">
1327
+ <path
1328
+ fillRule="evenodd"
1329
+ d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
1330
+ clipRule="evenodd"
1331
+ />
1332
+ </svg>
1333
+ </div>
1334
+
1335
+ <div className="flex items-center p-3 hover:bg-gray-50 rounded cursor-pointer">
1336
+ <div className="flex items-center space-x-3">
1337
+ <div className="w-8 h-8 bg-green-100 rounded flex items-center justify-center">
1338
+ 💚
1339
+ </div>
1340
+ <div>
1341
+ <div className="text-sm font-medium">Vue.js</div>
1342
+ <div className="text-xs text-gray-500">
1343
+ Vue 3 + Nuxt 3 with Tailwind CSS
1344
+ </div>
1345
+ </div>
1346
+ </div>
1347
+ </div>
1348
+
1349
+ <div className="flex items-center p-3 hover:bg-gray-50 rounded cursor-pointer">
1350
+ <div className="flex items-center space-x-3">
1351
+ <div className="w-8 h-8 bg-blue-100 rounded flex items-center justify-center">
1352
+ ⚛️
1353
+ </div>
1354
+ <div>
1355
+ <div className="text-sm font-medium">React</div>
1356
+ <div className="text-xs text-gray-500">
1357
+ React 18 + Vite with TypeScript
1358
+ </div>
1359
+ </div>
1360
+ </div>
1361
+ </div>
1362
+
1363
+ <div className="flex items-center p-3 hover:bg-gray-50 rounded cursor-pointer">
1364
+ <div className="flex items-center space-x-3">
1365
+ <div className="w-8 h-8 bg-red-100 rounded flex items-center justify-center">
1366
+ 🅰️
1367
+ </div>
1368
+ <div>
1369
+ <div className="text-sm font-medium">Angular</div>
1370
+ <div className="text-xs text-gray-500">
1371
+ Angular 17 + Material Design
1372
+ </div>
1373
+ </div>
1374
+ </div>
1375
+ </div>
1376
+
1377
+ <div className="flex items-center p-3 hover:bg-gray-50 rounded cursor-pointer">
1378
+ <div className="flex items-center space-x-3">
1379
+ <div className="w-8 h-8 bg-orange-100 rounded flex items-center justify-center">
1380
+ 🔥
1381
+ </div>
1382
+ <div>
1383
+ <div className="text-sm font-medium">Svelte</div>
1384
+ <div className="text-xs text-gray-500">SvelteKit + TailwindCSS</div>
1385
+ </div>
1386
+ </div>
1387
+ </div>
1388
+ </div>
1389
+ </div>
1390
+ </div>
1391
+
1392
+ {/* AI Model Selection */}
1393
+ <div className="flex-1 relative">
1394
+ <button
1395
+ type="button"
1396
+ className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-left pr-10"
1397
+ onClick={() => {
1398
+ const modal = document.getElementById('ai-model-modal');
1399
+ if (modal) {
1400
+ modal.classList.toggle('hidden');
1401
+ }
1402
+ }}
1403
+ >
1404
+ 🧠 Claude 3.5 Sonnet
1405
+ </button>
1406
+ <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
1407
+ <svg
1408
+ className="w-4 h-4 text-gray-400"
1409
+ fill="none"
1410
+ stroke="currentColor"
1411
+ viewBox="0 0 24 24"
1412
+ >
1413
+ <path
1414
+ strokeLinecap="round"
1415
+ strokeLinejoin="round"
1416
+ strokeWidth={2}
1417
+ d="M19 9l-7 7-7-7"
1418
+ />
1419
+ </svg>
1420
+ </div>
1421
+
1422
+ {/* AI Model Modal */}
1423
+ <div
1424
+ id="ai-model-modal"
1425
+ className="hidden absolute bottom-full left-0 mb-1 w-72 bg-white border border-gray-200 rounded-lg shadow-lg z-50 p-4"
1426
+ >
1427
+ <div className="space-y-3">
1428
+ {/* Claude Models */}
1429
+ <div id="claude-models" className="space-y-2">
1430
+ <div className="flex items-center justify-between p-2 hover:bg-gray-50 rounded cursor-pointer">
1431
+ <div className="flex items-center space-x-3">
1432
+ <div className="w-6 h-6 bg-orange-100 rounded flex items-center justify-center">
1433
+ 🧠
1434
+ </div>
1435
+ <span className="text-sm font-medium">Claude 3.5 Sonnet</span>
1436
+ </div>
1437
+ <svg
1438
+ className="w-4 h-4 text-blue-500"
1439
+ fill="currentColor"
1440
+ viewBox="0 0 20 20"
1441
+ >
1442
+ <path
1443
+ fillRule="evenodd"
1444
+ d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
1445
+ clipRule="evenodd"
1446
+ />
1447
+ </svg>
1448
+ </div>
1449
+
1450
+ <div className="flex items-center p-2 hover:bg-gray-50 rounded cursor-pointer">
1451
+ <div className="flex items-center space-x-3">
1452
+ <div className="w-6 h-6 bg-orange-100 rounded flex items-center justify-center">
1453
+ 🧠
1454
+ </div>
1455
+ <span className="text-sm">Claude 3.5 Haiku</span>
1456
+ </div>
1457
+ </div>
1458
+
1459
+ <div className="flex items-center p-2 hover:bg-gray-50 rounded cursor-pointer">
1460
+ <div className="flex items-center space-x-3">
1461
+ <div className="w-6 h-6 bg-orange-100 rounded flex items-center justify-center">
1462
+ 🧠
1463
+ </div>
1464
+ <span className="text-sm">Claude 3 Opus</span>
1465
+ </div>
1466
+ </div>
1467
+
1468
+ <div className="flex items-center p-2 hover:bg-gray-50 rounded cursor-pointer">
1469
+ <div className="flex items-center space-x-3">
1470
+ <div className="w-6 h-6 bg-orange-100 rounded flex items-center justify-center">
1471
+ 🧠
1472
+ </div>
1473
+ <span className="text-sm">Claude 3 Sonnet</span>
1474
+ </div>
1475
+ </div>
1476
+
1477
+ <div className="flex items-center p-2 hover:bg-gray-50 rounded cursor-pointer">
1478
+ <div className="flex items-center space-x-3">
1479
+ <div className="w-6 h-6 bg-orange-100 rounded flex items-center justify-center">
1480
+ 🧠
1481
+ </div>
1482
+ <span className="text-sm">Claude 3 Haiku</span>
1483
+ </div>
1484
+ </div>
1485
+ </div>
1486
+
1487
+ {/* OpenAI Models */}
1488
+ <div id="openai-models" className="space-y-2 hidden">
1489
+ <div className="flex items-center justify-between p-2 hover:bg-gray-50 rounded cursor-pointer">
1490
+ <div className="flex items-center space-x-3">
1491
+ <div className="w-6 h-6 bg-green-100 rounded flex items-center justify-center">
1492
+ 🤖
1493
+ </div>
1494
+ <span className="text-sm font-medium">GPT-4o</span>
1495
+ </div>
1496
+ <svg
1497
+ className="w-4 h-4 text-blue-500"
1498
+ fill="currentColor"
1499
+ viewBox="0 0 20 20"
1500
+ >
1501
+ <path
1502
+ fillRule="evenodd"
1503
+ d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
1504
+ clipRule="evenodd"
1505
+ />
1506
+ </svg>
1507
+ </div>
1508
+
1509
+ <div className="flex items-center p-2 hover:bg-gray-50 rounded cursor-pointer">
1510
+ <div className="flex items-center space-x-3">
1511
+ <div className="w-6 h-6 bg-green-100 rounded flex items-center justify-center">
1512
+ 🤖
1513
+ </div>
1514
+ <span className="text-sm">GPT-4o mini</span>
1515
+ </div>
1516
+ </div>
1517
+
1518
+ <div className="flex items-center p-2 hover:bg-gray-50 rounded cursor-pointer">
1519
+ <div className="flex items-center space-x-3">
1520
+ <div className="w-6 h-6 bg-green-100 rounded flex items-center justify-center">
1521
+ 🤖
1522
+ </div>
1523
+ <span className="text-sm">GPT-4 Turbo</span>
1524
+ </div>
1525
+ </div>
1526
+
1527
+ <div className="flex items-center p-2 hover:bg-gray-50 rounded cursor-pointer">
1528
+ <div className="flex items-center space-x-3">
1529
+ <div className="w-6 h-6 bg-green-100 rounded flex items-center justify-center">
1530
+ 🤖
1531
+ </div>
1532
+ <span className="text-sm">GPT-4</span>
1533
+ </div>
1534
+ </div>
1535
+
1536
+ <div className="flex items-center p-2 hover:bg-gray-50 rounded cursor-pointer">
1537
+ <div className="flex items-center space-x-3">
1538
+ <div className="w-6 h-6 bg-green-100 rounded flex items-center justify-center">
1539
+ 🤖
1540
+ </div>
1541
+ <span className="text-sm">o1</span>
1542
+ </div>
1543
+ </div>
1544
+
1545
+ <div className="flex items-center p-2 hover:bg-gray-50 rounded cursor-pointer">
1546
+ <div className="flex items-center space-x-3">
1547
+ <div className="w-6 h-6 bg-green-100 rounded flex items-center justify-center">
1548
+ 🤖
1549
+ </div>
1550
+ <span className="text-sm">o1-mini</span>
1551
+ </div>
1552
+ </div>
1553
+ </div>
1554
+
1555
+ {/* Provider Buttons */}
1556
+ <div className="flex gap-2 pt-2 border-t border-gray-100">
1557
+ <button
1558
+ id="openai-btn"
1559
+ className="flex-1 px-3 py-2 border border-gray-300 text-gray-700 text-sm rounded-md hover:bg-gray-50 transition-colors"
1560
+ onClick={() => {
1561
+ document.getElementById('claude-models')?.classList.add('hidden');
1562
+ document.getElementById('openai-models')?.classList.remove('hidden');
1563
+ document
1564
+ .getElementById('openai-btn')
1565
+ ?.classList.add('bg-blue-500', 'text-white');
1566
+ document
1567
+ .getElementById('openai-btn')
1568
+ ?.classList.remove('border-gray-300', 'text-gray-700');
1569
+ document
1570
+ .getElementById('anthropic-btn')
1571
+ ?.classList.remove('bg-blue-500', 'text-white');
1572
+ document
1573
+ .getElementById('anthropic-btn')
1574
+ ?.classList.add('border-gray-300', 'text-gray-700');
1575
+ }}
1576
+ >
1577
+ OpenAI
1578
+ </button>
1579
+ <button
1580
+ id="anthropic-btn"
1581
+ className="flex-1 px-3 py-2 bg-blue-500 text-white text-sm rounded-md hover:bg-blue-600 transition-colors"
1582
+ onClick={() => {
1583
+ document.getElementById('openai-models')?.classList.add('hidden');
1584
+ document.getElementById('claude-models')?.classList.remove('hidden');
1585
+ document
1586
+ .getElementById('anthropic-btn')
1587
+ ?.classList.add('bg-blue-500', 'text-white');
1588
+ document
1589
+ .getElementById('anthropic-btn')
1590
+ ?.classList.remove('border-gray-300', 'text-gray-700');
1591
+ document
1592
+ .getElementById('openai-btn')
1593
+ ?.classList.remove('bg-blue-500', 'text-white');
1594
+ document
1595
+ .getElementById('openai-btn')
1596
+ ?.classList.add('border-gray-300', 'text-gray-700');
1597
+ }}
1598
+ >
1599
+ Anthropic
1600
+ </button>
1601
+ </div>
1602
+ </div>
1603
+ </div>
1604
+ </div>
1605
+
1606
+ {/* API Key Dropdown */}
1607
+ <div className="flex-1 relative">
1608
+ <button
1609
+ type="button"
1610
+ className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-left pr-10"
1611
+ onClick={() => {
1612
+ const modal = document.getElementById('api-key-modal');
1613
+ if (modal) {
1614
+ modal.classList.toggle('hidden');
1615
+ }
1616
+ }}
1617
+ >
1618
+ API Key ••••
1619
+ </button>
1620
+ <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
1621
+ <svg
1622
+ className="w-4 h-4 text-gray-400"
1623
+ fill="none"
1624
+ stroke="currentColor"
1625
+ viewBox="0 0 24 24"
1626
+ >
1627
+ <path
1628
+ strokeLinecap="round"
1629
+ strokeLinejoin="round"
1630
+ strokeWidth={2}
1631
+ d="M19 9l-7 7-7-7"
1632
+ />
1633
+ </svg>
1634
+ </div>
1635
+
1636
+ {/* API Key Modal */}
1637
+ <div id="api-key-modal" className="hidden">
1638
+ {/* Modal Backdrop */}
1639
+ <div
1640
+ className="fixed inset-0 bg-opacity-50 z-[9998]"
1641
+ onClick={() => {
1642
+ const modal = document.getElementById('api-key-modal');
1643
+ if (modal) {
1644
+ modal.classList.add('hidden');
1645
+ }
1646
+ }}
1647
+ ></div>
1648
+
1649
+ {/* Modal Content */}
1650
+ <div
1651
+ className="fixed w-80 bg-white border border-gray-200 rounded-lg shadow-lg z-[9999] p-4"
1652
+ style={{
1653
+ position: 'fixed',
1654
+ left: '50%',
1655
+ top: '50%',
1656
+ transform: 'translate(-50%, -50%)',
1657
+ zIndex: 9999,
1658
+ }}
1659
+ >
1660
+ {/* Close Button */}
1661
+ <div className="flex justify-between items-center mb-4">
1662
+ <h3 className="text-lg font-semibold text-gray-900">API Key Settings</h3>
1663
+ <button
1664
+ type="button"
1665
+ className="text-gray-400 hover:text-gray-600 transition-colors"
1666
+ onClick={() => {
1667
+ const modal = document.getElementById('api-key-modal');
1668
+ if (modal) {
1669
+ modal.classList.add('hidden');
1670
+ }
1671
+ }}
1672
+ >
1673
+ <svg
1674
+ className="w-5 h-5"
1675
+ fill="none"
1676
+ stroke="currentColor"
1677
+ viewBox="0 0 24 24"
1678
+ >
1679
+ <path
1680
+ strokeLinecap="round"
1681
+ strokeLinejoin="round"
1682
+ strokeWidth={2}
1683
+ d="M6 18L18 6M6 6l12 12"
1684
+ />
1685
+ </svg>
1686
+ </button>
1687
+ </div>
1688
+
1689
+ <div className="space-y-4">
1690
+ {/* API Key Input Section */}
1691
+ <div>
1692
+ <label className="block text-sm font-medium text-gray-700 mb-2">
1693
+ API Key
1694
+ </label>
1695
+ <div className="relative">
1696
+ <input
1697
+ type="password"
1698
+ placeholder="••••••••••••••••••••••••••••••••••••••••••••"
1699
+ className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent pr-10"
1700
+ />
1701
+ <button
1702
+ type="button"
1703
+ className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600"
1704
+ onClick={(e) => {
1705
+ const input = e.currentTarget
1706
+ .previousElementSibling as HTMLInputElement;
1707
+ if (input) {
1708
+ input.type =
1709
+ input.type === 'password' ? 'text' : 'password';
1710
+ }
1711
+ }}
1712
+ >
1713
+ <svg
1714
+ className="w-4 h-4"
1715
+ fill="none"
1716
+ stroke="currentColor"
1717
+ viewBox="0 0 24 24"
1718
+ >
1719
+ <path
1720
+ strokeLinecap="round"
1721
+ strokeLinejoin="round"
1722
+ strokeWidth={2}
1723
+ d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
1724
+ />
1725
+ <path
1726
+ strokeLinecap="round"
1727
+ strokeLinejoin="round"
1728
+ strokeWidth={2}
1729
+ d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
1730
+ />
1731
+ </svg>
1732
+ </button>
1733
+ </div>
1734
+ </div>
1735
+
1736
+ {/* Parameters Section */}
1737
+ <div>
1738
+ <h3 className="text-sm font-medium text-gray-700 mb-3">Parameters</h3>
1739
+ <div className="space-y-2">
1740
+ <div className="flex justify-between items-center">
1741
+ <span className="text-sm text-gray-600">Output tokens</span>
1742
+ <span className="text-sm text-gray-500 bg-gray-100 px-2 py-1 rounded">
1743
+ Auto
1744
+ </span>
1745
+ </div>
1746
+ <div className="flex justify-between items-center">
1747
+ <span className="text-sm text-gray-600">Temperature</span>
1748
+ <span className="text-sm text-gray-500 bg-gray-100 px-2 py-1 rounded">
1749
+ Auto
1750
+ </span>
1751
+ </div>
1752
+ <div className="flex justify-between items-center">
1753
+ <span className="text-sm text-gray-600">Top P</span>
1754
+ <span className="text-sm text-gray-500 bg-gray-100 px-2 py-1 rounded">
1755
+ Auto
1756
+ </span>
1757
+ </div>
1758
+ <div className="flex justify-between items-center">
1759
+ <span className="text-sm text-gray-600">Top K</span>
1760
+ <span className="text-sm text-gray-500 bg-gray-100 px-2 py-1 rounded">
1761
+ Auto
1762
+ </span>
1763
+ </div>
1764
+ <div className="flex justify-between items-center">
1765
+ <span className="text-sm text-gray-600">Frequence penalty</span>
1766
+ <span className="text-sm text-gray-500 bg-gray-100 px-2 py-1 rounded">
1767
+ Auto
1768
+ </span>
1769
+ </div>
1770
+ <div className="flex justify-between items-center">
1771
+ <span className="text-sm text-gray-600">Presence penalty</span>
1772
+ <span className="text-sm text-gray-500 bg-gray-100 px-2 py-1 rounded">
1773
+ Auto
1774
+ </span>
1775
+ </div>
1776
+ </div>
1777
+ </div>
1778
+ </div>
1779
+ </div>
1780
+ </div>
1781
+ </div>
1782
+ </div>
1783
+ </div>
1784
+ <MessageInputComponent channelId={channelId} handleSend={handleSend} placeholder="Message" />
1785
+ </div>
1786
+ </>
1787
+ );
1788
+ });
1789
+
1790
+ // Display names for debugging
1791
+ Inbox.displayName = 'Inbox';
1792
+ ContentComponent.displayName = 'ContentComponent';
1793
+ MessagesComponent.displayName = 'MessagesComponent';
1794
+ RightSidebarWrapper.displayName = 'RightSidebarWrapper';
1795
+
1796
+ export default React.memo(Inbox);