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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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
// Split Screen Document Viewer for Chainlit
(function() {
    'use strict';

    let documentViewer = null;
    let documents = [];
    let activeDocIndex = 0;
    let viewerActive = false;

    // Create the document viewer panel (hidden by default)
    function createDocumentViewer() {
        if (document.getElementById('document-viewer')) {
            return document.getElementById('document-viewer');
        }

        const viewer = document.createElement('div');
        viewer.id = 'document-viewer';
        viewer.className = '';  // Start without 'active' class

        // Create header
        const header = document.createElement('div');
        header.className = 'document-header';
        header.innerHTML = `

            <h3>Document Viewer</h3>

            <div style="display: flex; gap: 10px;">

                <button class="document-pin" title="Pin document">πŸ“Œ Pin</button>

                <button class="document-close-btn">Close</button>

            </div>

        `;
        viewer.appendChild(header);

        // Create tabs container
        const tabsContainer = document.createElement('div');
        tabsContainer.className = 'document-tabs';
        viewer.appendChild(tabsContainer);

        // Create content area
        const contentArea = document.createElement('div');
        contentArea.id = 'document-content';
        contentArea.innerHTML = `

            <div class="document-empty-state">

                <h4>No Document Selected</h4>

                <p>Click on any document, image, or file in the chat to view it here</p>

            </div>

        `;
        viewer.appendChild(contentArea);

        // Add close functionality
        header.querySelector('.document-close-btn').addEventListener('click', () => {
            hideDocumentViewer();
        });

        // Add pin functionality
        const pinBtn = header.querySelector('.document-pin');
        pinBtn.addEventListener('click', () => {
            pinBtn.classList.toggle('pinned');
            const isPinned = pinBtn.classList.contains('pinned');
            pinBtn.textContent = isPinned ? 'πŸ“ Pinned' : 'πŸ“Œ Pin';
        });

        return viewer;
    }

    // Show document viewer
    function showDocumentViewer() {
        if (!documentViewer) {
            documentViewer = createDocumentViewer();
            document.body.appendChild(documentViewer);
        }

        // Add active classes
        documentViewer.classList.add('active');
        document.body.classList.add('document-viewer-active');

        // Adjust main container
        const mainContainer = document.querySelector('#root > div');
        if (mainContainer) {
            mainContainer.classList.add('split-active');
        }

        viewerActive = true;
        console.log('Document viewer shown');
    }

    // Hide document viewer
    function hideDocumentViewer() {
        if (documentViewer) {
            documentViewer.classList.remove('active');
            document.body.classList.remove('document-viewer-active');

            const mainContainer = document.querySelector('#root > div');
            if (mainContainer) {
                mainContainer.classList.remove('split-active');
            }
        }
        viewerActive = false;
        console.log('Document viewer hidden');
    }

    // Display document in viewer
    function displayDocument(content, title = 'Document', type = 'text') {
        console.log('Displaying document:', title, type);

        // Show viewer if not visible
        if (!viewerActive) {
            showDocumentViewer();
        }

        const contentArea = document.getElementById('document-content');
        const tabsContainer = documentViewer.querySelector('.document-tabs');

        // Check if document already exists
        const existingIndex = documents.findIndex(doc => doc.title === title);
        if (existingIndex !== -1) {
            // Switch to existing tab
            activeDocIndex = existingIndex;
            updateTabs();
            displayContent(documents[existingIndex]);
            return;
        }

        // Add to documents array
        const docIndex = documents.length;
        documents.push({ content, title, type });

        // Create tab
        const tab = document.createElement('button');
        tab.className = 'document-tab';
        tab.textContent = title.length > 20 ? title.substring(0, 20) + '...' : title;
        tab.title = title;
        tab.dataset.docIndex = docIndex;

        tab.addEventListener('click', () => {
            activeDocIndex = parseInt(tab.dataset.docIndex);
            updateTabs();
            displayContent(documents[activeDocIndex]);
        });

        // Add close button to tab
        const closeTab = document.createElement('span');
        closeTab.innerHTML = ' Γ—';
        closeTab.style.cssText = 'margin-left: 8px; font-weight: bold; color: #888;';
        closeTab.onclick = (e) => {
            e.stopPropagation();
            removeDocument(docIndex);
        };
        tab.appendChild(closeTab);

        tabsContainer.appendChild(tab);

        // Display content
        activeDocIndex = docIndex;
        updateTabs();
        displayContent({ content, title, type });
    }

    // Update active tab styling
    function updateTabs() {
        const tabs = documentViewer.querySelectorAll('.document-tab');
        tabs.forEach((tab, index) => {
            if (parseInt(tab.dataset.docIndex) === activeDocIndex) {
                tab.classList.add('active');
            } else {
                tab.classList.remove('active');
            }
        });
    }

    // Remove document and tab
    function removeDocument(index) {
        documents.splice(index, 1);

        // Rebuild tabs
        const tabsContainer = documentViewer.querySelector('.document-tabs');
        tabsContainer.innerHTML = '';

        documents.forEach((doc, i) => {
            const tab = document.createElement('button');
            tab.className = 'document-tab';
            tab.textContent = doc.title.length > 20 ? doc.title.substring(0, 20) + '...' : doc.title;
            tab.title = doc.title;
            tab.dataset.docIndex = i;

            if (i === activeDocIndex) {
                tab.classList.add('active');
            }

            tab.addEventListener('click', () => {
                activeDocIndex = i;
                updateTabs();
                displayContent(documents[i]);
            });

            const closeTab = document.createElement('span');
            closeTab.innerHTML = ' Γ—';
            closeTab.style.cssText = 'margin-left: 8px; font-weight: bold; color: #888;';
            closeTab.onclick = (e) => {
                e.stopPropagation();
                removeDocument(i);
            };
            tab.appendChild(closeTab);

            tabsContainer.appendChild(tab);
        });

        // If no documents left, show empty state
        if (documents.length === 0) {
            const contentArea = document.getElementById('document-content');
            contentArea.innerHTML = `

                <div class="document-empty-state">

                    <h4>No Document Selected</h4>

                    <p>Click on any document, image, or file in the chat to view it here</p>

                </div>

            `;
            // Hide viewer if not pinned
            const pinBtn = documentViewer.querySelector('.document-pin');
            if (!pinBtn.classList.contains('pinned')) {
                hideDocumentViewer();
            }
        } else {
            // Adjust active index if needed
            if (activeDocIndex >= documents.length) {
                activeDocIndex = documents.length - 1;
            }
            displayContent(documents[activeDocIndex]);
        }
    }

    // Display content based on type
    function displayContent(doc) {
        const contentArea = document.getElementById('document-content');

        switch (doc.type) {
            case 'image':
                contentArea.innerHTML = `

                    <div class="document-content">

                        <img src="${doc.content}" alt="${doc.title}" class="document-image">

                    </div>

                `;
                break;
            case 'pdf':
                contentArea.innerHTML = `

                    <iframe src="${doc.content}" class="pdf-viewer"></iframe>

                `;
                break;
            case 'code':
                contentArea.innerHTML = `

                    <div class="document-code">

                        <pre><code>${escapeHtml(doc.content)}</code></pre>

                    </div>

                `;
                break;
            case 'html':
                contentArea.innerHTML = `

                    <div class="document-content">

                        ${doc.content}

                    </div>

                `;
                break;
            default:
                contentArea.innerHTML = `

                    <div class="document-content">

                        ${escapeHtml(doc.content)}

                    </div>

                `;
        }
    }

    // Escape HTML for safe display
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Add "View in Document Viewer" buttons to file elements
    function addViewerButtons() {
        console.log('Scanning for file elements to add viewer buttons...');

        // Enhanced file element selectors
        const fileSelectors = [
            '[data-testid*="element"]',
            '[data-testid*="file"]',
            '[data-testid*="pdf"]',
            '.cl-file',
            '.cl-pdf',
            '[class*="file"]',
            '[class*="pdf"]',
            'a[href$=".pdf"]',
            'a[download]',
            'div[class*="MuiPaper-root"]:has(a[download])',
            '.message-content a',
            '[title*=".pdf"]',
            '[title*="PDF"]'
        ];

        let foundElements = 0;

        fileSelectors.forEach(selector => {
            try {
                const elements = document.querySelectorAll(selector);
                elements.forEach(element => {
                    if (element.querySelector('.viewer-button') || element.closest('#document-viewer')) {
                        return; // Already has button or is in viewer
                    }

                    // Skip if element is too small or hidden
                    const rect = element.getBoundingClientRect();
                    if (rect.width < 10 || rect.height < 10) {
                        return;
                    }

                    // Check if element is actually visible
                    const style = window.getComputedStyle(element);
                    if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
                        return;
                    }

                    foundElements++;
                    console.log(`Adding viewer button to element:`, element, `(selector: ${selector})`);

                    // Create viewer button
                    const viewerBtn = document.createElement('button');
                    viewerBtn.className = 'viewer-button';
                    viewerBtn.innerHTML = 'πŸ‘οΈ View';
                    viewerBtn.title = 'Open in Document Viewer';

                    // Force button visibility with inline styles
                    viewerBtn.style.cssText = `

                        position: absolute !important;

                        top: 5px !important;

                        right: 5px !important;

                        padding: 6px 12px !important;

                        background: #ff4757 !important;

                        color: white !important;

                        border: none !important;

                        border-radius: 6px !important;

                        font-size: 12px !important;

                        font-weight: 500 !important;

                        cursor: pointer !important;

                        z-index: 9999 !important;

                        display: block !important;

                        visibility: visible !important;

                        opacity: 1 !important;

                        min-width: 60px !important;

                        text-align: center !important;

                        box-shadow: 0 2px 8px rgba(255, 71, 87, 0.3) !important;

                    `;

                    // Position the parent element if needed
                    const computedStyle = window.getComputedStyle(element);
                    if (computedStyle.position === 'static') {
                        element.style.position = 'relative';
                    }

                    viewerBtn.addEventListener('click', (e) => {
                        e.preventDefault();
                        e.stopPropagation();

                        console.log('Viewer button clicked for element:', element);

                        // Find download link or href
                        let link = element.href ||
                                  element.getAttribute('href') ||
                                  element.querySelector('a[href]')?.href ||
                                  element.querySelector('[href]')?.getAttribute('href');

                        let fileName = element.textContent?.trim() ||
                                      element.getAttribute('title') ||
                                      element.querySelector('[title]')?.title ||
                                      element.querySelector('a')?.textContent?.trim() ||
                                      `Document ${documents.length + 1}`;

                        console.log('Found link:', link, 'fileName:', fileName);

                        if (link) {
                            if (link.endsWith('.pdf') || link.includes('pdf') || fileName.toLowerCase().includes('pdf')) {
                                displayDocument(link, fileName, 'pdf');
                            } else if (link.match(/\.(jpg|jpeg|png|gif|webp)$/i)) {
                                displayDocument(link, fileName, 'image');
                            } else {
                                // Try to fetch content
                                fetch(link)
                                    .then(res => res.text())
                                    .then(content => {
                                        const type = link.endsWith('.html') ? 'html' : 'text';
                                        displayDocument(content, fileName, type);
                                    })
                                    .catch(err => {
                                        console.error('Error loading document:', err);
                                        displayDocument('Error loading document content', fileName, 'text');
                                    });
                            }
                        } else {
                            // If no link, display the element's content
                            const content = element.textContent || element.innerHTML;
                            displayDocument(content, fileName, 'html');
                        }
                    });

                    element.appendChild(viewerBtn);
                });
            } catch (error) {
                console.warn(`Error processing selector ${selector}:`, error);
            }
        });

        console.log(`Added viewer buttons to ${foundElements} elements`);
    }

    // Attach click handlers to documents
    function attachDocumentHandlers() {
        document.addEventListener('click', (e) => {
            const target = e.target;

            // Don't process clicks on viewer buttons
            if (target.classList.contains('viewer-button')) {
                return;
            }

            console.log('Click detected on:', target.tagName, target.className, target);

            // Enhanced detection for Chainlit file elements
            const fileSelectors = [
                '[data-testid*="element"]',
                '[data-testid*="file"]',
                '[data-testid*="pdf"]',
                '.cl-file',
                '.cl-pdf',
                '[class*="file"]',
                '[class*="pdf"]',
                'a[href$=".pdf"]',
                'a[download]'
            ];

            let fileElement = null;
            for (const selector of fileSelectors) {
                fileElement = target.closest(selector);
                if (fileElement && !fileElement.closest('#document-viewer')) {
                    break;
                }
            }

            if (fileElement) {
                console.log('File element detected:', fileElement);
                e.preventDefault();
                e.stopPropagation();

                // Try to find the download link within the element
                const downloadLink = fileElement.href ||
                                   fileElement.querySelector('a[href]')?.href ||
                                   fileElement.querySelector('[href]')?.getAttribute('href');

                if (downloadLink) {
                    const fileName = fileElement.textContent ||
                                   fileElement.querySelector('[title]')?.title ||
                                   fileElement.getAttribute('title') ||
                                   'Document ' + (documents.length + 1);

                    console.log('Opening document:', fileName, downloadLink);

                    if (downloadLink.endsWith('.pdf')) {
                        displayDocument(downloadLink, fileName, 'pdf');
                    } else {
                        // Try to fetch and display content
                        fetch(downloadLink)
                            .then(res => res.text())
                            .then(content => {
                                const type = downloadLink.endsWith('.html') ? 'html' : 'text';
                                displayDocument(content, fileName, type);
                            })
                            .catch(err => {
                                console.error('Error loading document:', err);
                                displayDocument('Error loading document content', fileName, 'text');
                            });
                    }
                }
                return;
            }

            // Check for images
            if (target.tagName === 'IMG' && target.src && !target.closest('#document-viewer')) {
                e.preventDefault();
                e.stopPropagation();
                const title = target.alt || 'Image ' + (documents.length + 1);
                displayDocument(target.src, title, 'image');
                return;
            }

            // Check for code blocks
            const codeBlock = target.closest('pre');
            if (codeBlock && !codeBlock.closest('#document-viewer')) {
                e.preventDefault();
                e.stopPropagation();
                const content = codeBlock.textContent;
                const title = 'Code Block ' + (documents.length + 1);
                displayDocument(content, title, 'code');
                return;
            }
        }, true);
    }

    // Periodically scan for new file elements and add viewer buttons
    function scanForNewElements() {
        addViewerButtons();
    }

    // Initialize when DOM is ready
    function initialize() {
        console.log('Initializing Chainlit Split Screen Document Viewer');

        // Add a global helper function to manually open documents
        window.openInDocumentViewer = function(url, title, type = 'pdf') {
            console.log('Manual document viewer open called:', url, title, type);
            displayDocument(url, title, type);
        };

        // Create viewer but keep it hidden
        documentViewer = createDocumentViewer();
        document.body.appendChild(documentViewer);

        // Attach handlers
        attachDocumentHandlers();

        // Add initial viewer buttons
        addViewerButtons();

        // Scan for new elements periodically (more frequently for better responsiveness)
        setInterval(scanForNewElements, 1000);

        // Also scan when new messages are added
        const observer = new MutationObserver((mutations) => {
            let shouldScan = false;
            mutations.forEach((mutation) => {
                if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                    mutation.addedNodes.forEach((node) => {
                        if (node.nodeType === Node.ELEMENT_NODE) {
                            // Check if new element contains file-like content
                            if (node.querySelector && (
                                node.querySelector('a[download]') ||
                                node.querySelector('[class*="file"]') ||
                                node.querySelector('[data-testid*="file"]') ||
                                node.textContent?.toLowerCase().includes('pdf')
                            )) {
                                shouldScan = true;
                            }
                        }
                    });
                }
            });
            if (shouldScan) {
                console.log('New content detected, scanning for file elements...');
                setTimeout(addViewerButtons, 500); // Small delay to let DOM settle
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });

        // Add mobile toggle button if needed
        if (window.innerWidth <= 768) {
            const toggleBtn = document.createElement('button');
            toggleBtn.className = 'mobile-doc-toggle';
            toggleBtn.innerHTML = 'πŸ“„';
            toggleBtn.style.display = viewerActive ? 'flex' : 'none';
            toggleBtn.addEventListener('click', () => {
                if (viewerActive) {
                    hideDocumentViewer();
                    toggleBtn.style.display = 'none';
                } else {
                    showDocumentViewer();
                }
            });
            document.body.appendChild(toggleBtn);
        }

        console.log('Document Viewer initialized (hidden by default)');
    }

    // Wait for DOM to be ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initialize);
    } else {
        // Delay initialization to ensure Chainlit is fully loaded
        setTimeout(initialize, 1000);

        // Additional initialization after a longer delay
        setTimeout(() => {
            console.log('Additional document viewer initialization...');
            addViewerButtons();

            // Force scan every few seconds in case elements are missed
            setInterval(() => {
                console.log('Force scanning for new elements...');
                addViewerButtons();
            }, 3000);
        }, 3000);
    }

    // Export functions for external use
    window.ChainlitDocumentViewer = {
        displayDocument,
        showDocumentViewer,
        hideDocumentViewer,
        addViewerButtons,
        openInDocumentViewer: function(url, title, type = 'pdf') {
            displayDocument(url, title, type);
        }
    };
})();