File size: 14,281 Bytes
3b978bc
 
b2b182f
 
 
 
 
 
625853d
 
 
3b978bc
 
 
 
 
 
 
b2b182f
 
 
 
 
3b978bc
 
 
 
b2b182f
3b978bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2b182f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b978bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2b182f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b978bc
b2b182f
ddd6f63
 
625853d
 
b2b182f
3b978bc
b2b182f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b978bc
b2b182f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b978bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2b182f
 
3b978bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2b182f
 
 
 
 
 
3b978bc
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
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { Send, Paperclip, FileText, X, Trash2, Download, Mic, MicOff, MessageCircle, ClipboardList, Loader2, Columns3, FileOutput } from 'lucide-react';
import FileUpload from './FileUpload';

const EnhancedChatInput = ({ 
  onSendMessage, 
  onFileUploaded,
  uploadedDocuments = [],
  isLoading,
  currentChatSessionId,
  authToken, 
  placeholder = "Ask your advisors anything...",
  showProfileButtons = false,
  onOpenOnboarding,
  onOpenProfileForm,
  synthesizedMode = false,
  onToggleSynthesized,
  ensureSessionId,
}) => {
  const [inputMessage, setInputMessage] = useState('');
  const [showUpload, setShowUpload] = useState(false);
  const [showDocuments, setShowDocuments] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const [isTranscribing, setIsTranscribing] = useState(false);
  const mediaRecorderRef = useRef(null);
  const audioChunksRef = useRef([]);
  const textareaRef = useRef(null);
  const uploadRef = useRef(null);
  const uploadBtnRef = useRef(null);

  const sendForTranscription = useCallback(async (blob) => {
    if (!blob || blob.size < 100) {
      console.warn('STT: blob too small, skipping', blob?.size);
      return;
    }
    setIsTranscribing(true);
    try {
      const form = new FormData();
      form.append('audio', blob, 'recording.webm');
      const token = authToken || localStorage.getItem('authToken');
      const resp = await fetch(`${process.env.REACT_APP_API_URL}/voice/transcribe`, {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${token}` },
        body: form,
      });
      if (resp.ok) {
        const data = await resp.json();
        const text = data?.text?.trim();
        if (text) {
          setInputMessage(prev => prev ? `${prev} ${text}` : text);
        }
      } else {
        console.error('STT response not ok:', resp.status, await resp.text().catch(() => ''));
      }
    } catch (err) {
      console.error('Transcription failed:', err);
    } finally {
      setIsTranscribing(false);
    }
  }, [authToken]);

  const toggleRecording = useCallback(async () => {
    if (isRecording) {
      mediaRecorderRef.current?.stop();
      setIsRecording(false);
      return;
    }
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });

      // Pick a supported mimeType
      const mimeType = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', '']
        .find(mt => mt === '' || MediaRecorder.isTypeSupported(mt));
      const options = mimeType ? { mimeType } : undefined;
      const mediaRecorder = new MediaRecorder(stream, options);

      audioChunksRef.current = [];
      mediaRecorder.ondataavailable = (e) => {
        if (e.data && e.data.size > 0) audioChunksRef.current.push(e.data);
      };
      mediaRecorder.onstop = () => {
        stream.getTracks().forEach(t => t.stop());
        const blobType = mediaRecorder.mimeType || 'audio/webm';
        const blob = new Blob(audioChunksRef.current, { type: blobType });
        sendForTranscription(blob);
      };
      mediaRecorderRef.current = mediaRecorder;
      // Request data every 500ms so chunks are available when stop() fires
      mediaRecorder.start(500);
      setIsRecording(true);
    } catch (err) {
      console.error('Microphone access error:', err);
    }
  }, [isRecording, sendForTranscription]);

  const handleSend = () => {
    if (!inputMessage.trim() || isLoading || isUploading) return;
    
    onSendMessage(inputMessage);
    setInputMessage('');
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const handleFileUploaded = (file, response) => {
    setIsUploading(false);
    setShowUpload(false);
    
    if (onFileUploaded) {
      onFileUploaded(file, response);
    }
  };

  const handleUploadStart = () => {
    setIsUploading(true);
  };

  const toggleUpload = () => {
    if (!isUploading) {
      setShowUpload(!showUpload);
      setShowDocuments(false); // Close documents panel when opening upload
    }
  };

  const toggleDocuments = () => {
    setShowDocuments(!showDocuments);
    setShowUpload(false); // Close upload panel when opening documents
  };

  // Auto-resize textarea
  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
      textareaRef.current.style.height = textareaRef.current.scrollHeight + 'px';
    }
  }, [inputMessage]);

  // Close upload panel when clicking outside
  useEffect(() => {
    if (!showUpload) return;
    const handleClickOutside = (e) => {
      if (
        uploadRef.current && !uploadRef.current.contains(e.target) &&
        uploadBtnRef.current && !uploadBtnRef.current.contains(e.target)
      ) {
        setShowUpload(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [showUpload]);

  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const getFileIcon = (type) => {
    if (type.includes('pdf')) return '📄';
    if (type.includes('word') || type.includes('document')) return '📝';
    if (type.includes('text')) return '📃';
    return '📄';
  };

  const formatUploadTime = (date) => {
    return new Date(date).toLocaleString([], {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const isDisabled = isLoading || isUploading;
  const canSend = inputMessage.trim() && !isDisabled;

  return (
    <div className="enhanced-chat-input-container">
      {/* File Upload Area */}
      {showUpload && (
        <div className="floating-upload-section" ref={uploadRef}>
          <FileUpload 
            onFileUploaded={handleFileUploaded}
            isUploading={isUploading}
            currentChatSessionId={currentChatSessionId}  
            authToken={authToken}
            onUploadStart={handleUploadStart}
            ensureSessionId={ensureSessionId}
          />
        </div>
      )}

      {/* Documents Viewer Panel */}
      {showDocuments && (
        <div className="floating-documents-section">
          <div className="documents-header">
            <div className="documents-title">
              <FileText size={16} />
              <span>Uploaded Documents ({uploadedDocuments.length})</span>
            </div>
            <button 
              onClick={() => setShowDocuments(false)}
              className="close-documents-btn"
            >
              <X size={16} />
            </button>
          </div>
          
          <div className="documents-list">
            {uploadedDocuments.length === 0 ? (
              <div className="no-documents">
                <FileText size={24} />
                <p>No documents uploaded yet</p>
                <span>Upload documents to reference them in your conversations</span>
              </div>
            ) : (
              uploadedDocuments.map((doc) => (
                <div key={doc.id} className="document-item">
                  <div className="document-icon">
                    {getFileIcon(doc.type)}
                  </div>
                  <div className="document-info">
                    <div className="document-name">{doc.name}</div>
                    <div className="document-details">
                      {formatFileSize(doc.size)} • {formatUploadTime(doc.uploadTime)}
                    </div>
                  </div>
                  <div className="document-actions">
                    <button 
                      className="document-action-btn"
                      title="Remove document"
                      onClick={() => {
                        // TODO: Implement remove functionality
                        console.log('Remove document:', doc.id);
                      }}
                    >
                      <Trash2 size={14} />
                    </button>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      )}

      {/* Main Input Box */}
      <div className="floating-input-box">
        {/* Text Input Row */}
        <div className="text-input-row">
          <textarea
            ref={textareaRef}
            value={inputMessage}
            onChange={(e) => setInputMessage(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder={placeholder}
            className="main-textarea"
            disabled={isDisabled}
            rows={1}
          />
        </div>

        {/* Controls Row */}
        <div className="controls-row">
          {/* Left - File Controls */}
          <div className="file-controls">
            <button
              ref={uploadBtnRef}
              onClick={toggleUpload}
              className={`add-docs-btn ${showUpload ? 'active' : ''}`}
              disabled={isUploading}
              type="button"
            >
              <Paperclip size={16} />
              <span>Add documents</span>
            </button>
            
            {uploadedDocuments.length > 0 && (
              <button
                onClick={toggleDocuments}
                className={`view-docs-btn ${showDocuments ? 'active' : ''}`}
                type="button"
                title={`View ${uploadedDocuments.length} uploaded document${uploadedDocuments.length !== 1 ? 's' : ''}`}
              >
                <FileText size={16} />
                <span className="docs-count">{uploadedDocuments.length}</span>
              </button>
            )}
            {showProfileButtons && (
              <>
                <button
                  onClick={onOpenOnboarding}
                  className="add-docs-btn"
                  type="button"
                >
                  <MessageCircle size={16} />
                  <span>Tell us about yourself</span>
                </button>
                <button
                  onClick={onOpenProfileForm}
                  className="add-docs-btn"
                  type="button"
                >
                  <ClipboardList size={16} />
                  <span>Fill out profile form</span>
                </button>
              </>
            )}
          </div>

          {/* Right - Mode Toggle + Mic + Send */}
          <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
            {onToggleSynthesized && (
              <div style={{
                display: 'flex', borderRadius: '18px', overflow: 'hidden',
                border: '1px solid #3b82f6', flexShrink: 0,
              }}>
                <button
                  onClick={synthesizedMode ? onToggleSynthesized : undefined}
                  type="button"
                  title="Panel Response (3 advisors)"
                  style={{
                    display: 'flex', alignItems: 'center', gap: '4px',
                    padding: '5px 10px', fontSize: '12px', fontWeight: 600,
                    cursor: synthesizedMode ? 'pointer' : 'default',
                    border: 'none', transition: 'all 0.2s', whiteSpace: 'nowrap',
                    background: !synthesizedMode ? '#3b82f6' : 'transparent',
                    color: !synthesizedMode ? '#fff' : '#3b82f6',
                  }}
                >
                  <Columns3 size={13} />
                  Panel
                </button>
                <div style={{ width: 1, background: '#3b82f6', alignSelf: 'stretch' }} />
                <button
                  onClick={!synthesizedMode ? onToggleSynthesized : undefined}
                  type="button"
                  title="Aggregate synthesized answer"
                  style={{
                    display: 'flex', alignItems: 'center', gap: '4px',
                    padding: '5px 10px', fontSize: '12px', fontWeight: 600,
                    cursor: !synthesizedMode ? 'pointer' : 'default',
                    border: 'none', transition: 'all 0.2s', whiteSpace: 'nowrap',
                    background: synthesizedMode ? '#3b82f6' : 'transparent',
                    color: synthesizedMode ? '#fff' : '#3b82f6',
                  }}
                >
                  <FileOutput size={13} />
                  Aggregate
                </button>
              </div>
            )}
            <button
              onClick={toggleRecording}
              disabled={isTranscribing}
              className={`mic-button ${isRecording ? 'listening' : ''}`}
              type="button"
              title={isTranscribing ? 'Transcribing...' : isRecording ? 'Stop recording' : 'Voice input'}
              style={{
                background: isRecording ? '#EF4444' : 'transparent',
                border: isRecording ? '1px solid #EF4444' : '1px solid var(--border-primary)',
                color: isRecording ? '#fff' : 'var(--text-secondary)',
                borderRadius: '50%', width: 36, height: 36,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                cursor: isTranscribing ? 'wait' : 'pointer', transition: 'all 0.2s',
                animation: isRecording ? 'mic-pulse 1.5s ease-in-out infinite' : 'none',
                opacity: isTranscribing ? 0.6 : 1,
              }}
            >
              {isTranscribing ? <Loader2 size={16} className="spinning" /> : isRecording ? <MicOff size={16} /> : <Mic size={16} />}
            </button>
            <button
              onClick={handleSend}
              disabled={!canSend}
              className={`send-button ${canSend ? 'enabled' : 'disabled'}`}
              type="button"
            >
              <Send size={16} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default EnhancedChatInput;