Spaces:
Running

File size: 19,217 Bytes
cd61bf7
 
 
526e04d
c5525ab
 
f0e1c07
bdb1f39
cd61bf7
 
8c29deb
5b6905f
cd61bf7
526e04d
 
 
 
 
8ad0c07
8e132dd
526e04d
 
 
 
 
cd61bf7
 
 
 
0ca368e
 
 
cd61bf7
 
 
b470ffe
89c8da5
b470ffe
0ca368e
 
478e197
 
3612601
cd61bf7
 
526e04d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389e2f7
9589496
b470ffe
9589496
526e04d
 
 
3612601
526e04d
 
cd61bf7
 
 
526e04d
0ca368e
00a9ef7
5e6a8ea
 
 
 
 
 
 
 
 
 
8c29deb
f0e1c07
8ad0c07
8e132dd
 
 
 
 
f0e1c07
cd61bf7
526e04d
 
44051f4
 
 
 
2e1b596
b470ffe
00a9ef7
0efd976
 
00a9ef7
 
 
 
 
5e6a8ea
 
 
44051f4
 
5e6a8ea
44051f4
 
 
5e6a8ea
 
 
 
 
2e1b596
0efd976
526e04d
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
9d4625f
cd61bf7
526e04d
 
 
 
 
 
 
 
abb8c3e
 
 
 
 
 
526e04d
 
 
bdb1f39
5b6905f
 
 
 
d223b85
c70d9db
abb8c3e
 
 
 
 
 
 
d223b85
 
6a6deb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c70d9db
 
6a6deb3
5b6905f
 
6055af4
 
 
 
89c8da5
 
 
389e2f7
5b6905f
 
 
c5525ab
526e04d
 
 
0ca368e
cd61bf7
 
0ca368e
b470ffe
 
 
00a9ef7
 
b470ffe
 
0ca368e
b470ffe
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
0ca368e
b470ffe
 
 
cd61bf7
 
 
 
 
db2dc5e
 
 
 
abb8c3e
db2dc5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
615c63b
0ca368e
615c63b
 
 
 
 
cd61bf7
0ca368e
cd61bf7
0ca368e
cd61bf7
 
615c63b
cd61bf7
615c63b
 
 
 
cd61bf7
 
 
0ca368e
 
cd61bf7
 
615c63b
 
 
 
 
0ca368e
cd61bf7
0ca368e
 
 
cd61bf7
 
 
 
 
f0e1c07
 
 
 
 
 
8ad0c07
 
 
 
f0e1c07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ad0c07
f0e1c07
 
 
526e04d
 
 
9d4625f
0b42db9
76ab166
166119f
53900e6
cb528a9
 
53900e6
e727115
0b42db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dca4b49
0b42db9
ab96df2
0b42db9
d57223b
ab96df2
 
0b42db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e132dd
0b42db9
 
 
 
 
9121435
0b42db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
735c3a0
 
 
 
 
 
 
0b42db9
 
 
 
 
 
 
 
 
 
76ab166
cd61bf7
 
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
519
'use client'

import { useState, useRef, useEffect } from 'react'
import { Message, Lead, leadsApi } from '@/lib/api'
import { Bot, Loader2, X } from 'lucide-react'
import { AnimatePresence, motion } from 'framer-motion'
import { useToast } from '@/contexts/ToastContext'

import { ClientCard } from './ClientCard'
import { subscribeToMessages, isRealtimeEnabled } from '@/lib/supabaseClient'
import { BookingModal } from '@/components/bookings/BookingModal'
import { useChatWebSocket } from '@/hooks/useChatWebSocket'

// Import refactored sub-components
import { ChatHeader } from './ChatWindow/ChatHeader'
import { MessageBubble } from './ChatWindow/MessageBubble'
import { MessageInput } from './ChatWindow/MessageInput'
import { TypingIndicator } from './ChatWindow/TypingIndicator'
import { ConfirmModal } from '@/components/ui/ConfirmModal'
import { ImageViewer } from '@/components/ui/ImageViewer'

// ============================================================================
// Types
// ============================================================================

interface ChatWindowProps {
  messages: Message[]
  leadId?: string
  tenantId?: string
  conversationId?: string
  lead?: Lead
  conversation?: any
  isLoading?: boolean
  isAnalyzing?: boolean
  onRefresh?: () => void
  onLeadRefresh?: () => void
  onLeadUpdate?: (leadData: any) => void
  onConversationUpdate?: (data: any) => void // New prop for silent updates
  onTakeover?: () => void
  onBack?: () => void
  onToggleLeadsList?: () => void
  isLeadsListOpen?: boolean
  onOpenMobileDrawer?: () => void
}

// ============================================================================
// Helper Functions
// ============================================================================

function shouldShowDateSeparator(currentMsg: Message, prevMsg: Message | null): boolean {
  if (!prevMsg) return true
  const currentDate = new Date(currentMsg.created_at).toDateString()
  const prevDate = new Date(prevMsg.created_at).toDateString()
  return currentDate !== prevDate
}

function getDateLabel(dateString: string): string {
  const date = new Date(dateString)
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)

  if (date.toDateString() === today.toDateString()) return 'Сегодня'
  if (date.toDateString() === yesterday.toDateString()) return 'Вчера'
  return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' })
}

// ============================================================================
// Main Component
// ============================================================================

export function ChatWindow({
  messages,
  leadId,
  tenantId,
  conversationId,
  lead,
  conversation,
  isLoading,
  isAnalyzing,
  onRefresh,
  onLeadRefresh,
  onLeadUpdate,
  onConversationUpdate,
  onTakeover,
  onBack,
  onToggleLeadsList,
  isLeadsListOpen,
  onOpenMobileDrawer,
}: ChatWindowProps) {
  // State
  const [inputMessage, setInputMessage] = useState('')
  const [isSending, setIsSending] = useState(false)
  const [optimisticMessages, setOptimisticMessages] = useState<Message[]>([])
  const [realtimeMessages, setRealtimeMessages] = useState<Message[]>([])
  const [isTogglingAI, setIsTogglingAI] = useState(false)
  const lastInteractionTime = useRef<number>(0)
  const [localAIActive, setLocalAIActive] = useState<boolean>(() => {
    // Initial state priority: Lead has the latest mode status from the list
    if (lead && typeof lead.human_takeover === 'boolean') {
      return !lead.human_takeover
    }
    if (conversation && typeof conversation.human_takeover === 'boolean') {
      return !conversation.human_takeover
    }
    return true // Default to ON if no data yet
  })
  const [isBookingModalOpen, setIsBookingModalOpen] = useState(false)
  const [isTraining, setIsTraining] = useState(false)
  const [isTrainConfirmOpen, setIsTrainConfirmOpen] = useState(false)
  const [viewerData, setViewerData] = useState<{ src: string; alt: string; isOpen: boolean }>({
    src: '',
    alt: '',
    isOpen: false
  })
  const toast = useToast()

  const messagesEndRef = useRef<HTMLDivElement>(null)

  // Computed values
  const isConversationStale = conversation && conversation.lead_id !== leadId
  const isAIActive = localAIActive

  // Sync local state with props
  useEffect(() => {
    // GUARD 1: If we are currently toggling, ignore incoming prop updates
    if (isTogglingAI) return

    // GUARD 2: Temporal lockout. If the user interacted in the last 3s, 
    // ignore server updates to allow DB/Cache propagation to settle.
    // This solves the ON -> OFF -> ON -> OFF "ping-pong" effect.
    if (Date.now() - lastInteractionTime.current < 3000) return

    // Determine the next state based on available data
    let nextValue: boolean | undefined = undefined

    // 1. If we have a fresh conversation (matching current lead), it's the ultimate truth
    if (conversation && !isConversationStale && typeof conversation.human_takeover === 'boolean') {
      nextValue = !conversation.human_takeover
    }
    // 2. If no fresh conversation yet, use lead data (which we now pass from the list)
    else if (lead && typeof lead.human_takeover === 'boolean') {
      nextValue = !lead.human_takeover
    }

    if (nextValue !== undefined && nextValue !== localAIActive) {
      setLocalAIActive(nextValue)
    }
  }, [conversation?.human_takeover, lead?.human_takeover, isConversationStale, isTogglingAI])
  const allMessages = [...messages, ...optimisticMessages, ...realtimeMessages]
    .filter((msg, index, self) => index === self.findIndex((t) => t.id === msg.id))
    .sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime())

  // ============================================================================
  // Effects
  // ============================================================================

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages, optimisticMessages, realtimeMessages, isAnalyzing])

  useEffect(() => {
    if (!leadId || !tenantId || !isRealtimeEnabled()) return
    setRealtimeMessages([])
    const unsubscribe = subscribeToMessages(conversationId || '', (newMessage) => {
      setRealtimeMessages(prev => {
        if (prev.some(m => m.id === newMessage.id)) return prev
        return [...prev, newMessage]
      })
      // If we got a real message from us, clear optimistic state to avoid duplication
      if (newMessage.sender_type === 'human' || newMessage.sender_type === 'ai') {
        setOptimisticMessages(prev => prev.filter(m =>
          m.content !== newMessage.content || m.sender_type !== newMessage.sender_type
        ))
      }
    })
    return () => { unsubscribe() }
  }, [leadId, tenantId, conversationId])

  // WebSocket real-time updates (instant, doesn't require page refresh)
  const { isConnected: wsConnected } = useChatWebSocket({
    leadId,
    onNewMessage: (newMessage) => {
      console.log('🔔 WebSocket: New message received', newMessage.id, newMessage.content?.substring(0, 50))

      // Clear matching optimistic messages immediately to prevent duplication
      if (newMessage.sender_type === 'human' || newMessage.sender_type === 'ai') {
        setOptimisticMessages(prev => prev.filter(m =>
          m.content !== newMessage.content || m.sender_type !== newMessage.sender_type
        ))
      }

      setRealtimeMessages(prev => {
        // Check if message already exists
        const existingIndex = prev.findIndex(m => m.id === newMessage.id)

        if (existingIndex >= 0) {
          // UPDATE existing message (e.g., add media_url after voice upload)
          console.log('🔄 Updating existing message with new data', newMessage.id)
          const updated = [...prev]
          updated[existingIndex] = {
            ...prev[existingIndex],
            ...newMessage,
            // Merge media fields if new ones are provided
            media_url: newMessage.media_url || prev[existingIndex].media_url,
            media_type: newMessage.media_type || prev[existingIndex].media_type,
            media_name: newMessage.media_name || prev[existingIndex].media_name,
          }
          return updated
        }

        console.log('✅ Adding new message to realtimeMessages', newMessage.id)
        return [...prev, newMessage]
      })
    },
    // When lead data is updated (e.g., name extracted), refresh to update AI Summary
    onLeadUpdated: (updatedLead) => {
      console.log('📋 WebSocket: Lead updated', updatedLead?.name)
      // 1. Direct state update for instant UI response
      onLeadUpdate?.(updatedLead)
      // 2. Fallback to full refresh to ensure all related data (lists etc) are synced
      onLeadRefresh?.() || onRefresh?.()
    }
  })


  // ============================================================================
  // Handlers
  // ============================================================================

  const handleToggleAI = async () => {
    if (!leadId || isTogglingAI) return

    const prevValue = localAIActive
    const newValue = !prevValue

    // 1. Optimistic Update & Lockout
    lastInteractionTime.current = Date.now()
    setLocalAIActive(newValue)
    setIsTogglingAI(true)

    try {
      const result = await leadsApi.toggleAI(leadId, newValue)

      // 2. Silent refresh of lead data & conversation state
      if (onLeadRefresh) onLeadRefresh()
      if (onConversationUpdate) {
        // Update parent state with actual values from server
        onConversationUpdate({
          ...conversation,
          human_takeover: result.human_takeover
        })
      }
    } catch (error) {
      console.error('Error toggling AI:', error)
      // 3. Rollback on failure
      setLocalAIActive(prevValue)
      toast.error('Ошибка переключения режима AI')
    } finally {
      setIsTogglingAI(false)
    }
  }

  const handleDeleteMessage = async (messageId: string) => {
    if (!confirm('Удалить сообщение?')) return

    try {
      const token = localStorage.getItem('auth_token')
      if (!token) throw new Error('Не авторизован')

      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL}/api/v1/chats/messages/${messageId}`,
        {
          method: 'DELETE',
          headers: { 'Authorization': `Bearer ${token}` }
        }
      )

      if (!response.ok) {
        const err = await response.json().catch(() => ({}))
        throw new Error(err.detail || 'Failed to delete')
      }

      // Remove from local state
      setOptimisticMessages(prev => prev.filter(m => m.id !== messageId))
      setRealtimeMessages(prev => prev.filter(m => m.id !== messageId))

      // Refresh to get updated list
      if (onRefresh) onRefresh()
    } catch (error: any) {
      console.error('Error deleting message:', error)
      alert(error.message || 'Ошибка удаления сообщения')
    }
  }

  const handleSendMessage = async (e: React.FormEvent, file?: File | null, audioBlob?: Blob | null) => {
    e.preventDefault()

    const textToSend = inputMessage.trim() || (audioBlob ? '🎤 Голосовое сообщение' : (file ? `📎 Файл: ${file.name}` : ''))

    if (!textToSend && !file && !audioBlob) return
    if (!leadId || !conversationId) return

    const tempId = Date.now().toString()
    const optimisticMessage: Message = {
      id: tempId,
      conversation_id: conversationId,
      sender_type: 'human',
      content: textToSend,
      created_at: new Date().toISOString(),
      // Use createObjectURL for validation/preview, ideally revoking it later
      media_url: file ? URL.createObjectURL(file) : (audioBlob ? URL.createObjectURL(audioBlob) : undefined),
      media_type: file ? file.type : (audioBlob ? 'audio/webm' : undefined),
      media_name: file ? file.name : (audioBlob ? 'voice.webm' : undefined)
    }

    setOptimisticMessages(prev => [...prev, optimisticMessage])
    setInputMessage('')
    setIsSending(true)

    try {
      if (file || audioBlob) {
        await leadsApi.sendMessageWithMedia(leadId, conversationId, textToSend, file, audioBlob)
      } else {
        await leadsApi.sendMessage(leadId, conversationId, textToSend)
      }
      setOptimisticMessages(prev => prev.filter(m => m.id !== tempId))
    } catch (error) {
      console.error('Error sending message:', error)
      setOptimisticMessages(prev => prev.filter(m => m.id !== tempId))
      alert('Не удалось отправить сообщение')
    } finally {
      setIsSending(false)
    }
  }

  const handleTrainAI = async () => {
    if (!leadId || !conversationId || allMessages.length < 2) {
      toast.warning('Недостаточно сообщений для обучения')
      return
    }

    setIsTrainConfirmOpen(true)
  }

  const handleConfirmTrain = async () => {

    setIsTraining(true)
    try {
      const token = localStorage.getItem('auth_token')
      if (!token) throw new Error('Не авторизован')

      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL}/api/v1/ai-training/from-chat`,
        {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            conversation_id: conversationId,
            lead_id: leadId
          })
        }
      )

      if (!response.ok) {
        const err = await response.json().catch(() => ({}))
        throw new Error(err.detail || 'Failed to save training example')
      }

      toast.success('Диалог сохранён для обучения AI!')
    } catch (error: any) {
      console.error('Error training AI:', error)
      toast.error(error.message || 'Ошибка сохранения')
    } finally {
      setIsTraining(false)
      setIsTrainConfirmOpen(false)
    }
  }

  // ============================================================================
  // Render
  // ============================================================================

  return (
    <div
      className="flex flex-col h-full bg-transparent font-['Inter'] relative overflow-hidden"
      style={{
        // paddingTop: 'var(--header-height-mobile)', // REMOVED: layout.tsx already adds this
        // paddingBottom: 'var(--footer-height-mobile)' // REMOVED: layout.tsx already adds this
      }}
    >
      {/* Background Atmosphere - Synced with Main Layout */}
      <div className="absolute inset-0 pointer-events-none overflow-hidden -z-10">
        <div className="absolute top-0 right-0 w-[60%] h-[40%] bg-cyan-500/5 blur-[120px] rounded-full" />
        <div className="absolute bottom-0 left-0 w-[60%] h-[40%] bg-indigo-500/5 blur-[120px] rounded-full" />
      </div>

      {/* Header */}
      <ChatHeader
        lead={lead}
        isAnalyzing={isAnalyzing}
        isAIActive={isAIActive}
        isTogglingAI={isTogglingAI}
        isLeadsListOpen={isLeadsListOpen}
        onToggleLeadsList={onToggleLeadsList}
        onBack={onBack}
        onToggleAI={handleToggleAI}
        onOpenMobileDrawer={onOpenMobileDrawer}
        onOpenBookingModal={() => setIsBookingModalOpen(true)}
        onTrainAI={handleTrainAI}
      />

      {/* Messages Area */}
      <div
        className="flex-1 overflow-y-auto px-4 md:px-6 space-y-6 scrollbar-thin scrollbar-thumb-white/10 scroll-smooth"
        style={{
          WebkitOverflowScrolling: 'touch',
          willChange: 'scroll-position',
          transform: 'translateZ(0)'
        }}
      >
        {/* Top spacer to show content blurring behind header when scrolling */}
        <div className="h-4 shrink-0" />

        {isLoading ? (
          <div className="flex items-center justify-center h-full">
            <Loader2 className="w-8 h-8 animate-spin text-indigo-500" />
          </div>
        ) : allMessages.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-[calc(100%-2rem)] text-slate-500">
            <div className="w-16 h-16 bg-white/5 rounded-full flex items-center justify-center border border-white/10 mb-4">
              <Bot className="w-8 h-8 text-slate-600" />
            </div>
            <p className="text-sm font-medium text-slate-400">История сообщений пуста</p>
            <p className="text-xs mt-1 text-slate-500">Начните диалог первым</p>
          </div>
        ) : (
          <div className="py-4">
            {allMessages.map((msg, index) => {
              const isMe = msg.sender_type === 'human' || msg.sender_type === 'ai'
              const isAI = msg.sender_type === 'ai'
              const prevMsg = index > 0 ? allMessages[index - 1] : null
              const showDate = shouldShowDateSeparator(msg, prevMsg)

              const isSequence = prevMsg &&
                ((isMe && (prevMsg.sender_type === 'human' || prevMsg.sender_type === 'ai')) ||
                  (!isMe && (prevMsg.sender_type !== 'human' && prevMsg.sender_type !== 'ai'))) &&
                !showDate

              return (
                <MessageBubble
                  key={msg.id}
                  message={msg}
                  isMe={isMe}
                  isAI={isAI}
                  isSequence={!!isSequence}
                  showDate={showDate}
                  dateLabel={getDateLabel(msg.created_at)}
                  onDelete={handleDeleteMessage}
                  onImageClick={(src, alt) => setViewerData({ src, alt, isOpen: true })}
                />
              )
            })}

            <TypingIndicator isVisible={!!isAnalyzing} />
          </div>
        )}
        <div ref={messagesEndRef} className="h-4 shrink-0" />
      </div>

      {/* Input Area */}
      <MessageInput
        value={inputMessage}
        onChange={setInputMessage}
        onSubmit={handleSendMessage}
        isSending={isSending}
      />


      {/* Booking Modal */}
      <AnimatePresence>
        {isBookingModalOpen && leadId && (
          <BookingModal
            isOpen={isBookingModalOpen}
            onClose={() => setIsBookingModalOpen(false)}
            leadId={leadId}
            leadName={lead?.name || undefined}
          />
        )}
      </AnimatePresence>

      <ImageViewer
        src={viewerData.src}
        alt={viewerData.alt}
        isOpen={viewerData.isOpen}
        onClose={() => setViewerData(prev => ({ ...prev, isOpen: false }))}
      />

      {/* Train AI Confirmation Modal */}
      <ConfirmModal
        isOpen={isTrainConfirmOpen}
        onClose={() => setIsTrainConfirmOpen(false)}
        onConfirm={handleConfirmTrain}
        title="Обучение AI"
        message="Сохранить этот диалог как пример для обучения AI? Это поможет AI лучше понимать ваших клиентов."
        confirmText="Обучить AI"
        isLoading={isTraining}
      />
    </div>
  )
}