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
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
// File upload and management functionality

// Initialize file upload functionality
document.addEventListener('DOMContentLoaded', () => {
    if (document.body.classList.contains('chat-page')) {
        initializeFileUpload();
    }
});

function initializeFileUpload() {
    const fileInput = document.getElementById('fileInput');
    const imageInput = document.getElementById('imageInput');
    
    if (fileInput) {
        fileInput.addEventListener('change', handleFileSelect);
    }
    
    if (imageInput) {
        imageInput.addEventListener('change', handleFileSelect);
    }
    
    // Handle drag and drop
    const chatMessages = document.getElementById('chatMessages');
    if (chatMessages) {
        chatMessages.addEventListener('dragover', handleDragOver);
        chatMessages.addEventListener('drop', handleFileDrop);
        chatMessages.addEventListener('dragenter', handleDragEnter);
        chatMessages.addEventListener('dragleave', handleDragLeave);
    }
    
    console.log('File upload initialized');
}

function openFileUpload() {
    if (!window.currentConversation) {
        MainJS.showError('Please select a conversation first');
        return;
    }
    
    const fileInput = document.getElementById('fileInput');
    if (fileInput) {
        fileInput.click();
    }
}

function openImageUpload() {
    if (!window.currentConversation) {
        MainJS.showError('Please select a conversation first');
        return;
    }
    
    const imageInput = document.getElementById('imageInput');
    if (imageInput) {
        imageInput.click();
    }
}

function handleFileSelect(event) {
    const files = Array.from(event.target.files);
    if (files.length === 0) return;
    
    // Reset input value to allow selecting the same file again
    event.target.value = '';
    
    files.forEach(file => {
        uploadFile(file);
    });
}

function handleDragOver(event) {
    event.preventDefault();
    event.dataTransfer.dropEffect = 'copy';
}

function handleDragEnter(event) {
    event.preventDefault();
    const chatMessages = document.getElementById('chatMessages');
    if (chatMessages) {
        chatMessages.classList.add('drag-over');
    }
}

function handleDragLeave(event) {
    event.preventDefault();
    // Only remove class if we're leaving the chat messages area entirely
    if (!event.currentTarget.contains(event.relatedTarget)) {
        const chatMessages = document.getElementById('chatMessages');
        if (chatMessages) {
            chatMessages.classList.remove('drag-over');
        }
    }
}

function handleFileDrop(event) {
    event.preventDefault();
    
    const chatMessages = document.getElementById('chatMessages');
    if (chatMessages) {
        chatMessages.classList.remove('drag-over');
    }
    
    if (!window.currentConversation) {
        MainJS.showError('Please select a conversation first');
        return;
    }
    
    const files = Array.from(event.dataTransfer.files);
    files.forEach(file => {
        uploadFile(file);
    });
}

async function uploadFile(file) {
    if (!window.currentConversation) {
        MainJS.showError('Please select a conversation first');
        return;
    }
    
    // Validate file size (100MB limit)
    const maxSize = 100 * 1024 * 1024; // 100MB
    if (file.size > maxSize) {
        MainJS.showError(`File "${file.name}" is too large. Maximum size is 100MB.`);
        return;
    }
    
    // Validate file type
    const allowedExtensions = [
        'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'mp3', 'wav', 'ogg', 'm4a',
        'mp4', 'avi', 'mov', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 
        'zip', 'rar', '7z', 'apk', 'exe', 'dmg', 'deb', 'rpm'
    ];
    
    const fileExtension = file.name.split('.').pop().toLowerCase();
    if (!allowedExtensions.includes(fileExtension)) {
        MainJS.showError(`File type "${fileExtension}" is not allowed.`);
        return;
    }
    
    // Create progress UI
    const progressId = createProgressUI(file);
    
    try {
        // Create form data
        const formData = new FormData();
        formData.append('file', file);
        formData.append('conversation_id', window.currentConversation);
        
        // Upload with progress tracking
        const response = await uploadWithProgress(formData, progressId);
        
        if (response.success) {
            updateProgressUI(progressId, 100, 'Upload complete');
            MainJS.showSuccess(`File "${file.name}" uploaded successfully!`);
            
            // Remove progress UI after a delay
            setTimeout(() => {
                removeProgressUI(progressId);
            }, 2000);
            
            // Reload messages and conversations
            await loadMessages(window.currentConversation);
            await loadConversations();
            
        } else {
            updateProgressUI(progressId, 0, 'Upload failed: ' + response.message);
            MainJS.showError('Failed to upload file: ' + response.message);
            
            // Remove progress UI after delay
            setTimeout(() => {
                removeProgressUI(progressId);
            }, 3000);
        }
        
    } catch (error) {
        console.error('Error uploading file:', error);
        updateProgressUI(progressId, 0, 'Upload failed');
        MainJS.showError('Failed to upload file: ' + error.message);
        
        // Remove progress UI after delay
        setTimeout(() => {
            removeProgressUI(progressId);
        }, 3000);
    }
}

function uploadWithProgress(formData, progressId) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        
        // Track upload progress
        xhr.upload.addEventListener('progress', (event) => {
            if (event.lengthComputable) {
                const percentComplete = (event.loaded / event.total) * 100;
                updateProgressUI(progressId, percentComplete, 'Uploading...');
            }
        });
        
        // Handle completion
        xhr.addEventListener('load', () => {
            try {
                const response = JSON.parse(xhr.responseText);
                resolve(response);
            } catch (error) {
                reject(new Error('Invalid response format'));
            }
        });
        
        // Handle errors
        xhr.addEventListener('error', () => {
            reject(new Error('Network error during upload'));
        });
        
        xhr.addEventListener('abort', () => {
            reject(new Error('Upload cancelled'));
        });
        
        // Start upload
        xhr.open('POST', '/api/upload_file');
        xhr.send(formData);
    });
}

function createProgressUI(file) {
    const progressId = 'progress_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    const chatMessages = document.getElementById('chatMessages');
    
    if (!chatMessages) return progressId;
    
    const progressElement = document.createElement('div');
    progressElement.id = progressId;
    progressElement.className = 'upload-progress';
    
    const iconClass = MainJS.getFileIconClass(file.type);
    const iconColor = MainJS.getFileIconColor(file.type);
    
    progressElement.innerHTML = `
        <div class="d-flex align-items-center mb-2">
            <div class="file-icon ${iconColor} me-3">
                <i class="${iconClass}"></i>
            </div>
            <div class="flex-grow-1">
                <div class="fw-bold text-truncate">${MainJS.escapeHtml(file.name)}</div>
                <small class="text-muted">${MainJS.formatFileSize(file.size)}</small>
            </div>
        </div>
        <div class="progress mb-2" style="height: 4px;">
            <div class="progress-bar bg-success" role="progressbar" style="width: 0%"></div>
        </div>
        <div class="progress-status small text-muted">Preparing upload...</div>
    `;
    
    chatMessages.appendChild(progressElement);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    
    return progressId;
}

function updateProgressUI(progressId, percent, status) {
    const progressElement = document.getElementById(progressId);
    if (!progressElement) return;
    
    const progressBar = progressElement.querySelector('.progress-bar');
    const statusElement = progressElement.querySelector('.progress-status');
    
    if (progressBar) {
        progressBar.style.width = percent + '%';
        progressBar.setAttribute('aria-valuenow', percent);
    }
    
    if (statusElement) {
        statusElement.textContent = status;
    }
    
    // Change color based on status
    if (status.includes('failed') || status.includes('error')) {
        if (progressBar) {
            progressBar.classList.remove('bg-success');
            progressBar.classList.add('bg-danger');
        }
        if (statusElement) {
            statusElement.classList.add('text-danger');
        }
    } else if (status.includes('complete')) {
        if (progressBar) {
            progressBar.classList.remove('bg-success');
            progressBar.classList.add('bg-success');
        }
        if (statusElement) {
            statusElement.classList.add('text-success');
        }
    }
}

function removeProgressUI(progressId) {
    const progressElement = document.getElementById(progressId);
    if (progressElement) {
        progressElement.remove();
    }
}

// File preview functionality
function previewFile(fileUrl, fileName, fileType) {
    if (fileType.startsWith('image/')) {
        showImagePreview(fileUrl, fileName);
    } else if (fileType.startsWith('text/') || fileType.includes('pdf')) {
        window.open(fileUrl, '_blank');
    } else {
        // For other file types, just download
        downloadFileFromUrl(fileUrl, fileName);
    }
}

function showImagePreview(imageUrl, fileName) {
    // Create modal for image preview
    const modal = document.createElement('div');
    modal.className = 'modal fade';
    modal.setAttribute('tabindex', '-1');
    
    modal.innerHTML = `
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">${MainJS.escapeHtml(fileName)}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <img src="${imageUrl}" alt="${MainJS.escapeHtml(fileName)}" class="img-fluid" style="max-height: 70vh;">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-success" onclick="downloadFileFromUrl('${imageUrl}', '${fileName}')">
                        <i class="fas fa-download me-2"></i>Download
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Show modal
    const bsModal = new bootstrap.Modal(modal);
    bsModal.show();
    
    // Remove modal from DOM when hidden
    modal.addEventListener('hidden.bs.modal', () => {
        modal.remove();
    });
}

function downloadFileFromUrl(url, fileName) {
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// File type validation
function validateFileType(file) {
    const allowedTypes = [
        // Images
        'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp',
        // Audio
        'audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/ogg', 'audio/m4a',
        // Video
        'video/mp4', 'video/avi', 'video/quicktime', 'video/webm',
        // Documents
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-powerpoint',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        // Archives
        'application/zip',
        'application/x-rar-compressed',
        'application/x-7z-compressed',
        // Text
        'text/plain',
        // Applications
        'application/vnd.android.package-archive'
    ];
    
    return allowedTypes.includes(file.type) || file.type === '';
}

// File size formatting (already available in main.js, but keeping for reference)
function 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];
}

// Add CSS for drag and drop visual feedback
const dragDropStyles = document.createElement('style');
dragDropStyles.textContent = `
    .chat-messages.drag-over {
        border: 2px dashed #25d366;
        background-color: rgba(37, 211, 102, 0.1);
    }
    
    .chat-messages.drag-over::after {
        content: "Drop files here to upload";
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(37, 211, 102, 0.9);
        color: white;
        padding: 1rem 2rem;
        border-radius: 8px;
        font-weight: bold;
        z-index: 1000;
        pointer-events: none;
    }
`;
document.head.appendChild(dragDropStyles);

// Export functions for global access
window.FileJS = {
    openFileUpload,
    openImageUpload,
    uploadFile,
    previewFile,
    validateFileType,
    formatFileSize
};