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
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
import { useCallback, useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  createChat,
  fetchChatPage,
  listChats,
  removeChat,
  sendMessage,
} from '../api/chat'
import { clearSession, getStoredUser } from '../auth/storage'
import ChatMain from '../components/chat/ChatMain'
import CollapsedSidebarRail from '../components/chat/CollapsedSidebarRail'
import ChatSidebar from '../components/chat/ChatSidebar'
import ProfileModal from '../components/chat/ProfileModal'

const THREAD_LIMIT = 20
const SIDEBAR_LIMIT = 25
const SUGGESTIONS_PREF_KEY = 'comsats_suggestions_enabled'
const WEB_SEARCH_PREF_KEY = 'comsats_use_web_search'

function readSuggestionsPref() {
  try {
    return localStorage.getItem(SUGGESTIONS_PREF_KEY) !== 'false'
  } catch {
    return true
  }
}

function readWebSearchPref() {
  try {
    const raw = localStorage.getItem(WEB_SEARCH_PREF_KEY)
    if (raw === null) {
      localStorage.setItem(WEB_SEARCH_PREF_KEY, 'false')
      return false
    }
    return raw === 'true'
  } catch {
    return false
  }
}

function enrichSlice(slice, rangeStart) {
  return slice.map((pair, i) => ({
    question: pair.question,
    answer: pair.answer,
    pairIndex: rangeStart + i,
    pending: false,
  }))
}

export default function ChatPage() {
  const navigate = useNavigate()
  const user = getStoredUser()
  const scrollRef = useRef(null)

  const [chats, setChats] = useState([])
  const [chatListTotal, setChatListTotal] = useState(0)
  const [chatListHasMore, setChatListHasMore] = useState(false)
  const [loadingMoreChats, setLoadingMoreChats] = useState(false)

  const [selectedId, setSelectedId] = useState(null)
  const [turns, setTurns] = useState([])
  const [nextBeforeIndex, setNextBeforeIndex] = useState(null)
  const [hasOlder, setHasOlder] = useState(false)
  const [totalPairs, setTotalPairs] = useState(0)

  const [question, setQuestion] = useState('')
  const [loadingList, setLoadingList] = useState(true)
  const [loadingChat, setLoadingChat] = useState(false)
  const [loadingOlder, setLoadingOlder] = useState(false)
  const [sending, setSending] = useState(false)
  const [sendError, setSendError] = useState('')
  const [profileOpen, setProfileOpen] = useState(false)
  const [tailBump, setTailBump] = useState(0)
  const [followUpSuggestions, setFollowUpSuggestions] = useState([])
  const [suggestionsEnabled, setSuggestionsEnabled] = useState(readSuggestionsPref)
  const [webSearchEnabled, setWebSearchEnabled] = useState(() =>
    readWebSearchPref(),
  )
  const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false)
  const [desktopSidebarOpen, setDesktopSidebarOpen] = useState(true)
  const [viewportMd, setViewportMd] = useState(() =>
    typeof window !== 'undefined' ? window.matchMedia('(min-width: 768px)').matches : true,
  )

  const emptyListBootstrapRef = useRef(false)
  const chatsRef = useRef([])
  chatsRef.current = chats

  const loadSidebarFirstPage = useCallback(async () => {
    setLoadingList(true)
    try {
      const data = await listChats({ skip: 0, limit: SIDEBAR_LIMIT })
      setChats(data.chats || [])
      setChatListTotal(data.total ?? 0)
      setChatListHasMore(!!data.has_more)
    } catch {
      setChats([])
      setChatListTotal(0)
      setChatListHasMore(false)
    } finally {
      setLoadingList(false)
    }
  }, [])

  const loadMoreSidebarChats = useCallback(async () => {
    setLoadingMoreChats(true)
    try {
      const data = await listChats({
        skip: chatsRef.current.length,
        limit: SIDEBAR_LIMIT,
      })
      const batch = data.chats || []
      setChats((prev) => {
        const seen = new Set(prev.map((c) => c.chat_id))
        const merged = [...prev]
        for (const c of batch) {
          if (!seen.has(c.chat_id)) merged.push(c)
        }
        return merged
      })
      setChatListTotal(data.total ?? 0)
      setChatListHasMore(!!data.has_more)
    } catch {
      /* keep existing */
    } finally {
      setLoadingMoreChats(false)
    }
  }, [])

  useEffect(() => {
    loadSidebarFirstPage()
  }, [loadSidebarFirstPage])

  useEffect(() => {
    const mq = window.matchMedia('(min-width: 768px)')
    function onViewportChange() {
      const md = mq.matches
      setViewportMd(md)
      if (md) setMobileSidebarOpen(false)
    }
    onViewportChange()
    mq.addEventListener('change', onViewportChange)
    return () => mq.removeEventListener('change', onViewportChange)
  }, [])

  useEffect(() => {
    try {
      localStorage.setItem(SUGGESTIONS_PREF_KEY, String(suggestionsEnabled))
    } catch {
      /* ignore */
    }
    if (!suggestionsEnabled) setFollowUpSuggestions([])
  }, [suggestionsEnabled])

  useEffect(() => {
    try {
      localStorage.setItem(WEB_SEARCH_PREF_KEY, String(webSearchEnabled))
    } catch {
      /* ignore */
    }
  }, [webSearchEnabled])

  const selectChat = useCallback(async (chatId) => {
    setSelectedId(chatId)
    setLoadingChat(true)
    setSendError('')
    setFollowUpSuggestions([])
    setTurns([])
    setHasOlder(false)
    setNextBeforeIndex(null)
    setTotalPairs(0)
    try {
      const data = await fetchChatPage(chatId, { limit: THREAD_LIMIT })
      const slice = data.history || []
      const rangeStart = data.range_start ?? 0
      setTurns(enrichSlice(slice, rangeStart))
      setTotalPairs(data.total_pairs ?? slice.length)
      setHasOlder(!!data.has_older)
      setNextBeforeIndex(
        data.next_before_index != null ? data.next_before_index : rangeStart,
      )
    } catch {
      setTurns([])
      setSendError('Could not load this chat.')
    } finally {
      setLoadingChat(false)
    }
  }, [])

  useEffect(() => {
    if (loadingList) return

    if (chats.length === 0) {
      if (emptyListBootstrapRef.current) return
      emptyListBootstrapRef.current = true
      ;(async () => {
        try {
          const created = await createChat()
          const id = created.chat_id
          setChats([
            {
              chat_id: id,
              preview: 'New conversation',
              updated_at: null,
              message_count: 0,
            },
          ])
          setChatListTotal(1)
          setChatListHasMore(false)
          setSelectedId(id)
          setFollowUpSuggestions([])
          setTurns([])
          setHasOlder(false)
          setNextBeforeIndex(null)
          setTotalPairs(0)
        } catch {
          setSendError('Could not start a chat. Is the API running on port 8000?')
        }
      })()
      return
    }

    if (!selectedId && chats[0]) {
      selectChat(chats[0].chat_id)
    }
  }, [loadingList, chats, selectedId, selectChat])

  async function handleLoadOlderMessages() {
    if (!selectedId || !hasOlder || loadingOlder) return
    const beforeIdx =
      nextBeforeIndex != null ? nextBeforeIndex : turns[0]?.pairIndex ?? 0
    const el = scrollRef.current
    const prevScrollHeight = el?.scrollHeight ?? 0
    const prevScrollTop = el?.scrollTop ?? 0

    setLoadingOlder(true)
    try {
      const data = await fetchChatPage(selectedId, {
        beforeIndex: beforeIdx,
        limit: THREAD_LIMIT,
      })
      const slice = data.history || []
      const rangeStart = data.range_start ?? 0
      const older = enrichSlice(slice, rangeStart)
      setTurns((prev) => [...older, ...prev])
      setHasOlder(!!data.has_older)
      setNextBeforeIndex(data.next_before_index ?? 0)

      requestAnimationFrame(() => {
        const el2 = scrollRef.current
        if (el2) {
          el2.scrollTop = el2.scrollHeight - prevScrollHeight + prevScrollTop
        }
      })
    } catch (e) {
      setSendError(e.message || 'Could not load older messages')
    } finally {
      setLoadingOlder(false)
    }
  }

  async function handleNewChat() {
    setSendError('')
    try {
      const created = await createChat()
      const id = created.chat_id
      const entry = {
        chat_id: id,
        preview: 'New conversation',
        updated_at: null,
        message_count: 0,
      }
      setChats((prev) => [entry, ...prev.filter((c) => c.chat_id !== id)])
      setChatListTotal((t) => t + 1)
      setSelectedId(id)
      setFollowUpSuggestions([])
      setTurns([])
      setHasOlder(false)
      setNextBeforeIndex(null)
      setTotalPairs(0)
      setTailBump((x) => x + 1)
    } catch (e) {
      setSendError(e.message || 'Could not create chat')
    }
  }

  async function handleDeleteChat(chatId) {
    if (!window.confirm('Delete this conversation?')) return
    try {
      await removeChat(chatId)
      const remaining = chats.filter((c) => c.chat_id !== chatId)
      setChats(remaining)
      setChatListTotal((t) => Math.max(0, t - 1))
      if (selectedId === chatId) {
        if (remaining.length > 0) {
          await selectChat(remaining[0].chat_id)
        } else {
          emptyListBootstrapRef.current = false
          const created = await createChat()
          const id = created.chat_id
          setChats([
            {
              chat_id: id,
              preview: 'New conversation',
              updated_at: null,
              message_count: 0,
            },
          ])
          setChatListTotal(1)
          setChatListHasMore(false)
          setSelectedId(id)
          setFollowUpSuggestions([])
          setTurns([])
          setHasOlder(false)
          setNextBeforeIndex(null)
          setTotalPairs(0)
          emptyListBootstrapRef.current = true
        }
      }
    } catch (e) {
      setSendError(e.message || 'Could not delete chat')
    }
  }

  async function handleSend(overrideText) {
    const raw =
      overrideText !== undefined && overrideText !== null
        ? String(overrideText)
        : question
    const q = raw.trim()
    if (!selectedId || !q || sending) return

    const clientKey = crypto.randomUUID()
    const pairIdx = totalPairs

    setSendError('')
    setSending(true)
    setQuestion('')
    setTurns((prev) => [
      ...prev,
      {
        question: q,
        answer: null,
        pending: true,
        clientKey,
      },
    ])
    setTailBump((x) => x + 1)

    try {
      const res = await sendMessage(selectedId, q, {
        allowAugmentation: suggestionsEnabled,
        useWebSearch: webSearchEnabled,
      })
      const answer = res.answer
      if (suggestionsEnabled) {
        setFollowUpSuggestions(
          Array.isArray(res.suggested_questions) ? res.suggested_questions : [],
        )
      } else {
        setFollowUpSuggestions([])
      }
      setTurns((prev) =>
        prev.map((t) =>
          t.clientKey === clientKey
            ? {
                question: q,
                answer,
                pending: false,
                pairIndex: pairIdx,
              }
            : t,
        ),
      )
      setTotalPairs((n) => n + 1)
      setTailBump((x) => x + 1)

      setChats((prev) =>
        prev.map((c) =>
          c.chat_id === selectedId
            ? {
                ...c,
                preview: q.slice(0, 100),
                message_count: (c.message_count || 0) + 1,
              }
            : c,
        ),
      )
    } catch (e) {
      setFollowUpSuggestions([])
      setTurns((prev) => prev.filter((t) => t.clientKey !== clientKey))
      setQuestion(q)
      setSendError(e.message || 'Failed to send')
    } finally {
      setSending(false)
    }
  }

  function logout() {
    clearSession()
    navigate('/login', { replace: true })
  }

  const selectedChat = selectedId
    ? chats.find((c) => c.chat_id === selectedId)
    : null
  const chatTitle = selectedChat?.preview?.trim() || 'New conversation'

  function closeMobileSidebar() {
    setMobileSidebarOpen(false)
  }

  function handleCloseSidebar() {
    if (viewportMd) setDesktopSidebarOpen(false)
    else closeMobileSidebar()
  }

  function handleOpenSidebar() {
    if (viewportMd) setDesktopSidebarOpen(true)
    else setMobileSidebarOpen(true)
  }

  const sidebarExpanded = viewportMd ? desktopSidebarOpen : mobileSidebarOpen
  const collapsedSidebarRail = viewportMd && !desktopSidebarOpen

  return (
    <div className="relative flex h-dvh min-h-0 w-full overflow-hidden bg-chat-canvas md:bg-white">
      {mobileSidebarOpen ? (
        <button
          type="button"
          aria-label="Close sidebar"
          className="fixed inset-0 z-30 bg-slate-900/35 backdrop-blur-[1px] md:hidden"
          onClick={closeMobileSidebar}
        />
      ) : null}

      <div
        className={`fixed inset-y-0 left-0 z-40 flex h-dvh shrink-0 flex-col overflow-hidden border-r border-slate-200/70 bg-chat-sidebar shadow-[4px_0_24px_rgba(0,0,0,0.08)] transition-[transform,width,min-width,max-width] duration-200 ease-out md:z-0 md:shadow-none ${
          mobileSidebarOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'
        } ${
          desktopSidebarOpen
            ? 'w-[min(92vw,360px)] md:relative md:w-[320px] md:min-w-[320px] lg:w-[360px] lg:min-w-[360px]'
            : 'w-[min(92vw,360px)] md:relative md:w-0 md:min-w-0 md:max-w-0 md:border-r-0 md:opacity-0 md:pointer-events-none'
        }`}
      >
        <ChatSidebar
          user={user}
          chats={chats}
          selectedId={selectedId}
          onCloseSidebar={handleCloseSidebar}
          onSelectChat={(id) => {
            selectChat(id)
            closeMobileSidebar()
          }}
          onNewChat={() => {
            handleNewChat()
            closeMobileSidebar()
          }}
          onDeleteChat={handleDeleteChat}
          onEditProfile={() => {
            setProfileOpen(true)
            closeMobileSidebar()
          }}
          onLogout={() => {
            logout()
            closeMobileSidebar()
          }}
          loadingList={loadingList}
          hasMoreChats={chatListHasMore}
          loadingMoreChats={loadingMoreChats}
          onLoadMoreChats={loadMoreSidebarChats}
          chatListTotal={chatListTotal}
        />
      </div>

      <div className="flex min-h-0 min-w-0 flex-1 md:bg-chat-canvas">
        {collapsedSidebarRail ? (
          <CollapsedSidebarRail
            onOpenSidebar={handleOpenSidebar}
            onEditProfile={() => setProfileOpen(true)}
            onLogout={logout}
          />
        ) : null}

        <div className="flex min-h-0 min-w-0 flex-1 flex-col">
        <ChatMain
          ref={scrollRef}
          chatId={selectedId}
          chatTitle={chatTitle}
          turns={turns}
          loadingChat={loadingChat}
          loadingOlder={loadingOlder}
          hasOlder={hasOlder}
          onLoadOlder={handleLoadOlderMessages}
          sending={sending}
          tailBump={tailBump}
          error={sendError}
          question={question}
          setQuestion={setQuestion}
          onSend={handleSend}
          followUpSuggestions={followUpSuggestions}
          suggestionsEnabled={suggestionsEnabled}
          onSuggestionsEnabledChange={setSuggestionsEnabled}
          webSearchEnabled={webSearchEnabled}
          onWebSearchEnabledChange={setWebSearchEnabled}
          onPickFollowUp={(text) => handleSend(text)}
          sidebarExpanded={sidebarExpanded}
          collapsedSidebarRail={collapsedSidebarRail}
          onOpenSidebar={handleOpenSidebar}
        />
        </div>
      </div>
      <ProfileModal open={profileOpen} onClose={() => setProfileOpen(false)} />
    </div>
  )
}