File size: 24,136 Bytes
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
0333b18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ee86b0
 
 
 
 
 
 
 
 
4135ac0
 
eee15b3
0ee86b0
 
eee15b3
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7645832
0ee86b0
 
 
 
 
f734117
 
 
 
 
 
7645832
0ee86b0
 
 
 
 
0333b18
7a064ce
4e10575
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734117
 
 
 
 
 
 
0ee86b0
 
 
 
 
 
 
 
 
c9902dd
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734117
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734117
 
 
 
 
 
 
 
 
0ee86b0
f734117
 
 
 
 
0ee86b0
 
f734117
0ee86b0
 
 
 
 
 
 
 
 
7a064ce
 
 
 
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734117
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734117
 
 
 
 
 
 
 
 
0ee86b0
f734117
 
 
 
 
0ee86b0
 
f734117
0ee86b0
 
 
 
7645832
 
 
 
 
 
 
 
 
 
0ee86b0
 
 
 
 
 
 
 
 
 
 
f734117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734117
 
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734117
 
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <title>Database Viewer</title>
    <style>
        * { margin:0; padding:0; box-sizing:border-box; }
        body {
            font-family:-apple-system,BlinkMacSystemFont,'SF Pro Rounded','SF Pro Display',Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;
            background:#001122; color:#fff; min-height:100vh; padding:28px; display:flex; flex-direction:column; gap:28px; align-items:center;
        }
        .shell { width:100%; max-width:1200px; display:flex; flex-direction:column; gap:26px; }
        .panel { background:#333; border-radius:20px; padding:28px 32px; box-shadow:0 18px 50px rgba(0,0,0,.5); }
        .header-title {
            color: #fff;
            font-size: 2.5rem;
            font-weight: 500;
            text-decoration: underline;
            text-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
            text-align: center;
            margin: 10px;
        }

        .header-subtitle {
            color: #ccc;
            font-size: 0.85rem;
            font-weight: 400;
            font-style: italic;
            margin: 5px;
        }
        p.sub { font-size:.8rem; color:#ccc; font-style:italic; line-height:1.5; }
        a { color:#87CEFA; text-decoration:none; }
        a:hover { text-decoration:underline; }
        .status { font-size:.75rem; color:#ccc; margin-top:6px; min-height:18px; }
        .view-toggles { display:flex; gap:10px; flex-wrap:wrap; margin-bottom:20px; }
        .view-toggles button { background:#2d3f4d; color:#cfe9ff; box-shadow:none; padding:12px 20px; font-size:.8rem; border:none; border-radius:10px; cursor:pointer; transition:.25s; font-weight:600; }
        .view-toggles button.active { background:#7ec8ff; color:#001122; }
        .view-toggles button:hover { background:#355064; }
        .view-toggles button.active:hover { background:#6bb8ff; }
    .table-wrapper { background:#222; border:2px solid #555; border-radius:16px; padding:14px 18px; max-height:60vh; overflow-x:auto; overflow-y:auto; }
    table.data-table { width:100%; min-width:1800px; border-collapse:collapse; font-size:.7rem; }
    table.data-table th, table.data-table td { padding:8px 10px; text-align:left; border:1px solid #444; vertical-align:top; white-space:normal; word-break:break-word; overflow-wrap:anywhere; }
        table.data-table th { position:sticky; top:0; background:#2d3f4d; z-index:2; font-weight:600; letter-spacing:.5px; }
        table.data-table tbody tr:nth-child(even){ background:#1e2a33; }
    .truncate { white-space:normal; word-break:break-word; overflow-wrap:anywhere; cursor:pointer; }
        .truncate:hover { background:#203240; }
        .empty { text-align:center; font-style:italic; color:#ccc; padding:40px; }
        .error { color:#ff7b7b; font-weight:600; }
        .spinner { width:18px; height:18px; border:3px solid rgba(255,255,255,.2); border-top-color:#7ec8ff; border-radius:50%; animation:spin 1s linear infinite; }
        .inline { display:inline-flex; align-items:center; gap:10px; }
        @keyframes spin { to { transform:rotate(360deg);} }
        .pagination { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin-top:16px; font-size:.7rem; }
        .pagination button { padding:8px 12px; font-size:.7rem; background:#2d3f4d; color:#cfe9ff; box-shadow:none; border:none; border-radius:8px; cursor:pointer; transition:.25s; }
        .pagination button:disabled { opacity:.35; cursor:not-allowed; }
        .pagination button:hover:not(:disabled) { background:#355064; }
        .pagination .current { color:#7ec8ff; font-weight:600; }
        @media (max-width:800px){ .panel { padding:22px 20px; } h1 { font-size:1.7rem; } }
        
        /* Modal styles for full content view */
        .modal { display:none; position:fixed; z-index:1000; left:0; top:0; width:100%; height:100%; background:rgba(0,0,0,.8); }
        .modal-content { background:#333; margin:5% auto; padding:20px; border-radius:15px; width:90%; max-width:800px; max-height:80vh; overflow:auto; }
        .modal-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:15px; }
        .modal-title { font-size:1.2rem; color:#7ec8ff; }
        .close { color:#ccc; font-size:28px; font-weight:bold; cursor:pointer; }
        .close:hover { color:#fff; }
    .modal-body { background:#222; border:1px solid #555; border-radius:8px; padding:15px; font-family:monospace; font-size:.8rem; white-space:pre-wrap; overflow-wrap:anywhere; word-break:break-word; }
        
        .tab-content { display:none; }
        .tab-content.active { display:block; }
        .tab-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:15px; gap:10px; flex-wrap:wrap; }
        .tab-info { font-size:.65rem; letter-spacing:1px; color:#ccc; }

        /* Sorting styles */
        th.sortable { cursor:pointer; user-select:none; }
        th.sortable:hover { background:#355064; }
        th.sortable.active { color:#7ec8ff; }
        .sort-indicator { opacity:.85; font-size:.7rem; margin-left:6px; }
    .clickable { cursor:pointer; }
    </style>
</head>
<body>
    <div class="shell">
        <div class="panel">
            <h1 class="header-title">Database Viewer</h1>
            <p class="header-subtitle">Browse documents and chunks stored in Neon Postgres. Values are truncated - click to view the complete content.</p>
            <br />
            <div class="view-toggles">
                <button id="documentsTab" class="active" data-tab="documents">Documents</button>
                <button id="chunksTab" data-tab="chunks">Chunks</button>
            </div>
            
            <div class="status" id="status"></div>
        </div>

        <!-- Documents Tab -->
        <div class="panel tab-content active" id="documentsContent">
            <div class="tab-header">
                <h2 style="font-size:1.2rem;margin:0;">Documents Table</h2>
                <div class="tab-info">
                    Page <span id="documentsPage">1</span> | 
                    <span id="documentsCount">0</span> records
                </div>
            </div>
            <div class="table-wrapper" id="documentsTableWrapper">
                <div class="empty">Loading documents...</div>
            </div>
            <div class="pagination" id="documentsPagination" style="display:none;"></div>
        </div>

        <!-- Chunks Tab -->
        <div class="panel tab-content" id="chunksContent">
            <div class="tab-header">
                <h2 style="font-size:1.2rem;margin:0;">Chunks Table</h2>
                <div class="tab-info">
                    Page <span id="chunksPage">1</span> | 
                    <span id="chunksCount">0</span> records
                </div>
            </div>
            <div class="table-wrapper" id="chunksTableWrapper">
                <div class="empty">Loading chunks...</div>
            </div>
            <div class="pagination" id="chunksPagination" style="display:none;"></div>
        </div>
    </div>

    <!-- Modal for full content display -->
    <div id="contentModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <span class="modal-title" id="modalTitle">Content</span>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body" id="modalBody"></div>
        </div>
    </div>

    <div style="text-align: center; margin-top: 20px;">
        <a href="/" style="color: #87CEFA; text-decoration: none; font-size: 1rem; padding: 10px 20px; border: 1px solid #87CEFA; border-radius: 10px; transition: all 0.3s ease;" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'">
            ← Back to Home
        </a>
    </div>

    <script>
        // Global state
        let currentTab = 'documents';
        let documentsPage = 1;
        let chunksPage = 1;
        const PAGE_SIZE = 25;

        // Elements
        const statusEl = document.getElementById('status');
        const modal = document.getElementById('contentModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalBody = document.getElementById('modalBody');
        const closeModal = document.querySelector('.close');

        // Tab elements
        const documentsTab = document.getElementById('documentsTab');
        const chunksTab = document.getElementById('chunksTab');
        const documentsContent = document.getElementById('documentsContent');
        const chunksContent = document.getElementById('chunksContent');

        // Table elements
        const documentsTableWrapper = document.getElementById('documentsTableWrapper');
        const chunksTableWrapper = document.getElementById('chunksTableWrapper');
        const documentsPagination = document.getElementById('documentsPagination');
        const chunksPagination = document.getElementById('chunksPagination');

        // Status elements
        const documentsPageEl = document.getElementById('documentsPage');
        const documentsCountEl = document.getElementById('documentsCount');
        const chunksPageEl = document.getElementById('chunksPage');
        const chunksCountEl = document.getElementById('chunksCount');

    // Sorting state (default: doc_id ascending)
    let documentsSort = { key: 'doc_id', dir: 'asc' };
    let chunksSort = { key: 'doc_id', dir: 'asc' };
    // Cache last-loaded page data for re-render on sort without refetch
    let lastDocumentsData = null;
    let lastChunksData = null;

        function esc(v) {
            return String(v ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
        }

        function setStatus(msg, isError = false) {
            statusEl.innerHTML = msg ? `<span class="${isError ? 'error' : ''}">${esc(msg)}</span>` : '';
        }

        function spinner() {
            setStatus(`Loading...`);
        }

        function truncateValue(value, maxLength = 100) {
            const str = String(value ?? '');
            if (str.length <= maxLength) {
                return { display: str, truncated: false, full: str };
            }
            return {
                display: str.slice(0, maxLength) + '…',
                truncated: true,
                full: str
            };
        }

        function showModal(title, content) {
            modalTitle.textContent = title;
            modalBody.textContent = content;
            modal.style.display = 'block';
        }

        function hideModal() {
            modal.style.display = 'none';
        }

        // Modal event listeners
        closeModal.addEventListener('click', hideModal);
        window.addEventListener('click', (e) => {
            if (e.target === modal) {
                hideModal();
            }
        });

        // Tab switching
        function switchTab(tabName) {
            currentTab = tabName;
            
            // Update tab buttons
            document.querySelectorAll('.view-toggles button').forEach(btn => {
                btn.classList.remove('active');
            });
            document.getElementById(tabName + 'Tab').classList.add('active');
            
            // Update tab content
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            document.getElementById(tabName + 'Content').classList.add('active');
            
            // Load data if needed
            if (tabName === 'documents') {
                loadDocuments();
            } else if (tabName === 'chunks') {
                loadChunks();
            }
        }

        documentsTab.addEventListener('click', () => switchTab('documents'));
        chunksTab.addEventListener('click', () => switchTab('chunks'));

        function renderDocumentsTable(data) {
            if (!data) return;
            const { documents, page, count } = data;
            
            documentsPageEl.textContent = page;
            documentsCountEl.textContent = count;
            
            if (!documents || documents.length === 0) {
                documentsTableWrapper.innerHTML = '<div class="empty">No documents found.</div>';
                documentsPagination.style.display = 'none';
                return;
            }

            const columns = [
                'doc_id', 'title', 'source_path', 'doc_type', 'jurisdiction', 
                'governing_law', 'party_roles', 'industry', 'effective_date', 
                'created_at', 'chunk_count', 'sha256'
            ];

            // Sort rows client-side by current sort state
            const sortedDocs = [...documents].sort((a, b) => {
                const key = documentsSort.key;
                const cmp = compareValues(a[key], b[key], key);
                if (cmp !== 0) return documentsSort.dir === 'asc' ? cmp : -cmp;
                // stable tie-breaker by doc_id
                return compareValues(a['doc_id'], b['doc_id'], 'doc_id');
            });

            let html = '<table class="data-table"><thead><tr>';
            html += columns.map(col => {
                const active = documentsSort.key === col;
                const arrow = active ? (documentsSort.dir === 'asc' ? '▲' : '▼') : '';
                return `<th class="sortable ${active ? 'active' : ''}" onclick="setSort('documents','${col}')">${esc(col)}${arrow ? ` <span class='sort-indicator'>${arrow}</span>` : ''}</th>`;
            }).join('');
            html += '</tr></thead><tbody>';

            sortedDocs.forEach(doc => {
                html += '<tr>';
                columns.forEach(col => {
                    const value = doc[col];
                    const { display, truncated, full } = truncateValue(value);
                    const cls = truncated ? 'truncate' : '';
                    const onClick = truncated ? `onclick="showModal('${esc(col)}', ${JSON.stringify(full).replace(/"/g, '&quot;')})"` : '';
                    
                    if (col === 'source_path' && value) {
                        // Make source path clickable
                        if (value.startsWith('/api/raw/')) {
                            html += `<td class="${cls}"><a href="${encodeURI(value)}" target="_blank" rel="noopener noreferrer">${esc(display)}</a></td>`;
                            return;
                        }
                        const rawPrefix = '/data/corpus_raw/';
                        let rel = '';
                        if (value.startsWith(rawPrefix)) {
                            rel = value.substring(rawPrefix.length);
                        } else {
                            try {
                                const parts = value.split('/');
                                rel = parts.slice(parts.indexOf('corpus_raw') + 1).join('/');
                            } catch {
                                rel = value.split('/').pop() || '';
                            }
                        }
                        const href = '/api/raw/' + encodeURI(rel);
                        html += `<td class="${cls}"><a href="${href}" target="_blank" rel="noopener noreferrer">${esc(display)}</a></td>`;
                    } else {
                        html += `<td class="${cls}" ${onClick}>${esc(display)}</td>`;
                    }
                });
                html += '</tr>';
            });

            html += '</tbody></table>';
            documentsTableWrapper.innerHTML = html;

            // Render pagination
            renderPagination('documents', data);
        }

        function renderChunksTable(data) {
            if (!data) return;
            const { chunks, page, count } = data;
            
            chunksPageEl.textContent = page;
            chunksCountEl.textContent = count;
            
            if (!chunks || chunks.length === 0) {
                chunksTableWrapper.innerHTML = '<div class="empty">No chunks found.</div>';
                chunksPagination.style.display = 'none';
                return;
            }

            const columns = [
                'chunk_id', 'doc_id', 'chunk_index', 'text', 'token_count', 
                'page_start', 'page_end', 'section_number', 'section_title', 
                'clause_type', 'path', 'numbers_present', 'definition_terms',
                'tok_ver', 'seg_ver', 'embedding_count'
            ];

            // Sort rows client-side by current sort state
            const sortedChunks = [...chunks].sort((a, b) => {
                const key = chunksSort.key;
                const cmp = compareValues(a[key], b[key], key);
                if (cmp !== 0) return chunksSort.dir === 'asc' ? cmp : -cmp;
                // stable tie-breaker by chunk_id
                return compareValues(a['chunk_id'], b['chunk_id'], 'chunk_id');
            });

            let html = '<table class="data-table"><thead><tr>';
            html += columns.map(col => {
                const active = chunksSort.key === col;
                const arrow = active ? (chunksSort.dir === 'asc' ? '▲' : '▼') : '';
                return `<th class="sortable ${active ? 'active' : ''}" onclick="setSort('chunks','${col}')">${esc(col)}${arrow ? ` <span class='sort-indicator'>${arrow}</span>` : ''}</th>`;
            }).join('');
            html += '</tr></thead><tbody>';

            sortedChunks.forEach(chunk => {
                html += '<tr>';
                columns.forEach(col => {
                    const value = chunk[col];
                    const { display, truncated, full } = truncateValue(value);
                    let cls = truncated ? 'truncate' : '';
                    let onClick = '';
                    if (col === 'text') {
                        // Always clickable for chunk text; show full content in modal, wrapped
                        onClick = `onclick=\"showModal('text', ${JSON.stringify(full).replace(/\"/g, '&quot;')})\"`;
                        cls = (cls ? cls + ' ' : '') + 'clickable';
                    } else {
                        onClick = truncated ? `onclick=\"showModal('${esc(col)}', ${JSON.stringify(full).replace(/\"/g, '&quot;')})\"` : '';
                    }
                    html += `<td class=\"${cls}\" ${onClick}>${esc(display)}</td>`;
                });
                html += '</tr>';
            });

            html += '</tbody></table>';
            chunksTableWrapper.innerHTML = html;

            // Render pagination
            renderPagination('chunks', data);
        }

        // Change sort key/direction and re-render current table
        function setSort(type, key) {
            if (type === 'documents') {
                if (documentsSort.key === key) {
                    documentsSort.dir = documentsSort.dir === 'asc' ? 'desc' : 'asc';
                } else {
                    documentsSort = { key, dir: 'asc' };
                }
                renderDocumentsTable(lastDocumentsData);
            } else if (type === 'chunks') {
                if (chunksSort.key === key) {
                    chunksSort.dir = chunksSort.dir === 'asc' ? 'desc' : 'asc';
                } else {
                    chunksSort = { key, dir: 'asc' };
                }
                renderChunksTable(lastChunksData);
            }
        }

        // Generic value comparator supporting numbers, dates, booleans, and strings
        function compareValues(a, b, key) {
            const isNullish = (v) => v === null || v === undefined || v === '';
            const aN = isNullish(a);
            const bN = isNullish(b);
            if (aN && bN) return 0;
            if (aN) return 1; // nullish last
            if (bN) return -1;

            // Date-aware for common date fields
            if (key === 'created_at' || key === 'effective_date') {
                const ta = Date.parse(a);
                const tb = Date.parse(b);
                const aValid = !Number.isNaN(ta);
                const bValid = !Number.isNaN(tb);
                if (aValid && bValid) return ta - tb;
            }

            const aNum = typeof a === 'number' || (typeof a === 'string' && a.trim() !== '' && !isNaN(a));
            const bNum = typeof b === 'number' || (typeof b === 'string' && b.trim() !== '' && !isNaN(b));
            if (aNum && bNum) return Number(a) - Number(b);

            if (typeof a === 'boolean' && typeof b === 'boolean') {
                return (a === b) ? 0 : (a ? 1 : -1);
            }

            return String(a).toLowerCase().localeCompare(String(b).toLowerCase());
        }

        function renderPagination(type, data) {
            const { page, has_more } = data;
            const paginationEl = type === 'documents' ? documentsPagination : chunksPagination;
            
            let html = '';
            
            // Previous button
            if (page > 1) {
                html += `<button onclick="changePage('${type}', ${page - 1})">← Previous</button>`;
            } else {
                html += `<button disabled>← Previous</button>`;
            }
            
            // Current page
            html += `<span class="current">Page ${page}</span>`;
            
            // Next button
            if (has_more) {
                html += `<button onclick="changePage('${type}', ${page + 1})">Next →</button>`;
            } else {
                html += `<button disabled>Next →</button>`;
            }
            
            paginationEl.innerHTML = html;
            paginationEl.style.display = 'flex';
        }

        function changePage(type, page) {
            if (type === 'documents') {
                documentsPage = page;
                loadDocuments();
            } else if (type === 'chunks') {
                chunksPage = page;
                loadChunks();
            }
        }

        function loadDocuments() {
            spinner();
            fetch(`/api/dbviewer/documents?page=${documentsPage}&limit=${PAGE_SIZE}`)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        setStatus(`Error loading documents: ${data.error}`, true);
                        documentsTableWrapper.innerHTML = '<div class="empty">Error loading documents.</div>';
                        return;
                    }
                    lastDocumentsData = data;
                    renderDocumentsTable(lastDocumentsData);
                    setStatus(data.count ? `Loaded ${data.count} documents.` : 'No documents found.');
                })
                .catch(error => {
                    setStatus(`Failed to load documents: ${error.message}`, true);
                    documentsTableWrapper.innerHTML = '<div class="empty">Failed to load documents.</div>';
                });
        }

        function loadChunks() {
            spinner();
            fetch(`/api/dbviewer/chunks?page=${chunksPage}&limit=${PAGE_SIZE}`)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        setStatus(`Error loading chunks: ${data.error}`, true);
                        chunksTableWrapper.innerHTML = '<div class="empty">Error loading chunks.</div>';
                        return;
                    }
                    lastChunksData = data;
                    renderChunksTable(lastChunksData);
                    setStatus(data.count ? `Loaded ${data.count} chunks.` : 'No chunks found.');
                })
                .catch(error => {
                    setStatus(`Failed to load chunks: ${error.message}`, true);
                    chunksTableWrapper.innerHTML = '<div class="empty">Failed to load chunks.</div>';
                });
        }

        // Initialize
        loadDocuments();
    </script>
</body>
</html>