File size: 27,228 Bytes
fc3bf2a
 
 
 
 
 
 
 
 
 
 
0333b18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
 
 
 
 
 
 
 
 
 
 
 
 
0ee86b0
fc3bf2a
 
 
 
eee15b3
 
cd05629
0ee86b0
 
cd05629
eee15b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
 
 
 
 
 
 
 
 
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
 
 
 
 
0333b18
7a064ce
fc3bf2a
 
 
0ee86b0
fc3bf2a
 
0ee86b0
fc3bf2a
 
 
 
 
 
 
0ee86b0
fc3bf2a
 
 
0ee86b0
 
 
 
 
fc3bf2a
 
 
 
0ee86b0
fc3bf2a
0ee86b0
fc3bf2a
0ee86b0
fc3bf2a
 
0ee86b0
fc3bf2a
 
 
 
0333b18
 
 
 
 
 
fc3bf2a
 
 
 
 
0ee86b0
fc3bf2a
 
 
0ee86b0
fc3bf2a
 
0ee86b0
 
 
fc3bf2a
 
 
0ee86b0
 
 
 
 
 
 
 
 
fc3bf2a
0ee86b0
 
 
 
 
c9902dd
0ee86b0
fc3bf2a
0ee86b0
fc3bf2a
 
0ee86b0
 
 
 
 
 
 
 
 
fc3bf2a
0ee86b0
fc3bf2a
0ee86b0
fc3bf2a
0ee86b0
 
 
 
fc3bf2a
 
0ee86b0
 
 
 
f74bbfd
 
0ee86b0
 
f74bbfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
0ee86b0
fc3bf2a
 
 
 
 
 
0ee86b0
 
 
 
fc3bf2a
 
 
0ee86b0
fc3bf2a
 
0ee86b0
 
 
 
 
 
fc3bf2a
 
 
 
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
 
0ee86b0
 
 
 
 
 
 
 
 
fc3bf2a
0ee86b0
 
 
fc3bf2a
0ee86b0
 
fc3bf2a
0ee86b0
 
fc3bf2a
 
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
 
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
 
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
0ee86b0
 
 
 
 
 
 
 
 
 
 
fc3bf2a
0ee86b0
fc3bf2a
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
0ee86b0
 
 
36ad8fd
fc3bf2a
 
0ee86b0
36ad8fd
0ee86b0
 
 
36ad8fd
0ee86b0
 
 
 
 
 
 
 
 
 
 
fc3bf2a
 
36ad8fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
0ee86b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3bf2a
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <title>Chunks 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;align-items:center;gap:28px}
        .shell{width:100%;max-width:1400px;display:flex;flex-direction:column;gap:26px}
        .panel{background:#333;border-radius:20px;padding:26px 32px;box-shadow:0 18px 50px rgba(0,0,0,.5);display:flex;flex-direction:column;gap:20px}
        .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;margin:0}
        a{color:#87CEFA;text-decoration:none}a:hover{text-decoration:underline}
        form.query{display:flex;flex-wrap:wrap;gap:14px;align-items:flex-end}
        form.query>div{display:flex;flex-direction:column;gap:6px}
        label{font-size:.7rem;text-transform:uppercase;letter-spacing:1px;color:#ccc}
        input[type=number],input[type=text]{background:#222;border:2px solid #555;border-radius:10px;padding:10px 14px;color:#fff;font-family:inherit;min-width:140px}
        input:focus{outline:none;border-color:#7ec8ff;box-shadow:0 0 0 3px rgba(126,200,255,.15)}
        button{background:#7ec8ff;color:#001122;border:none;padding:10px 18px;border-radius:10px;font-weight:600;cursor:pointer;font-size:.85rem;letter-spacing:1px;transition:.25s;box-shadow:0 8px 18px rgba(126,200,255,.25)}
        button:hover{background:#6bb8ff;transform:translateY(-2px)}
        button:active{transform:translateY(0)}
        button.secondary{background:rgba(255,102,102,.45);color:#fff;box-shadow:none}
        button.secondary:hover{background:rgba(255,102,102,.6)}
        .status{font-size:.75rem;color:#ccc;min-height:18px}
        .results{display:flex;flex-direction:column;gap:22px}
        .summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px}
        .kv{background:#222;border:2px solid #555;border-radius:12px;padding:10px 12px;display:flex;flex-direction:column;gap:4px}
        .kv span.k{font-size:.6rem;text-transform:uppercase;letter-spacing:1px;color:#999}
        .kv span.v{font-size:.8rem;word-break:break-word}
    .table-wrapper{background:#222;border:2px solid #555;border-radius:16px;padding:14px 18px;max-height:60vh;overflow:auto;overflow-x:auto}
    table.data-table{width:auto;min-width:1900px;border-collapse:collapse;font-size:.65rem;table-layout:fixed}
    table.data-table th,table.data-table td{padding:6px 8px;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{max-width:unset;white-space:normal;word-break:break-word;overflow-wrap:anywhere}
    /* Wider, fixed column widths for better readability and horizontal scrolling */
    table.data-table th:nth-child(1),
    table.data-table td:nth-child(1){width:90px}
    table.data-table th:nth-child(2),
    table.data-table td:nth-child(2){width:90px}
    table.data-table th:nth-child(3),
    table.data-table td:nth-child(3){width:900px} /* text */
    table.data-table th:nth-child(4),
    table.data-table td:nth-child(4){width:120px}
    table.data-table th:nth-child(5),
    table.data-table td:nth-child(5){width:320px}
    table.data-table th:nth-child(6),
    table.data-table td:nth-child(6){width:180px}
    table.data-table th:nth-child(7),
    table.data-table td:nth-child(7){width:240px}
    table.data-table th:nth-child(8),
    table.data-table td:nth-child(8){width:140px}
        .toolbar{display:flex;flex-wrap:wrap;gap:10px}
        .toolbar input{background:#222;border:2px solid #555;border-radius:10px;padding:8px 10px;color:#fff;font-size:.75rem;min-width:220px}
        .toolbar input:focus{outline:none;border-color:#7ec8ff;box-shadow:0 0 0 3px rgba(126,200,255,.15)}
        .pagination{display:flex;align-items:center;gap:12px;font-size:.7rem;flex-wrap:wrap}
        .pagination button{padding:6px 12px;font-size:.65rem}
        .empty{text-align:center;font-style:italic;color:#ccc}
        .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}
        @keyframes spin{to{transform:rotate(360deg)}}
        @media (max-width:900px){.panel{padding:22px 20px}h1{font-size:1.7rem}}
        
        /* Edit mode styles */
        tr.editing { background:#283745 !important; }
        td.editable { cursor:text; }
        td.editable:hover { background:#203240; }
        .row-actions { display:flex; gap:6px; }
        .row-actions button { padding:4px 10px; font-size:.6rem; background:#355064; color:#cfe9ff; }
        .row-actions button.confirm { background:#4caf50; color:#fff; }
        .row-actions button.cancel { background:#d9534f; color:#fff; }
        th.sortable { cursor:pointer; user-select:none; }
        th.sortable:hover { background:#355064; }
        th.sortable .indicator { font-size:.55rem; margin-left:4px; opacity:.8; }
    </style>
</head>
<body>
    <div class="shell">
        <div class="panel">
            <h1 class="header-title">Chunks Explorer</h1>
            <p class="header-subtitle">Paginated table view of chunks data with inline editing capabilities. Chunk embeddings are stored in Neon using pgvector.</p>
            <form id="queryForm" class="query" autocomplete="off">
                <div>
                    <label for="docId">Document ID</label>
                    <input type="number" id="docId" min="1" placeholder="e.g., 12" />
                </div>
                <div>
                    <label for="filter">Text Filter</label>
                    <input type="text" id="filter" placeholder="filter text..." />
                </div>
                <div>
                    <label for="pageSize">Page Size</label>
                    <input type="number" id="pageSize" min="5" max="200" value="25" />
                </div>
                <div style="display:flex;gap:8px;">
                    <button type="submit" id="fetchBtn">Fetch by Doc ID</button>
                </div>
            </form>
            <div class="toolbar">
                <input type="text" id="sectionFilter" placeholder="filter by section title" />
                <input type="text" id="clauseFilter" placeholder="filter by clause type" />
                <div style="display:flex;gap:8px;">
                    <button type="button" class="secondary" id="clearBtn">Clear</button>
                </div>
            </div>
            <div class="status" id="status"></div>
        </div>

        <div class="panel results" id="resultsPanel">
            <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-bottom:6px;">
                <h2 style="font-size:1.2rem;margin:0;">Chunks Data</h2>
                <button type="button" id="globalMode" class="secondary" style="margin-left:auto;">Show All Chunks</button>
                <div style="font-size:.65rem;letter-spacing:1px;color:#ccc;">Total: <span id="rowCount">0</span></div>
            </div>
            <div class="summary" id="summary"></div>
            <div class="table-wrapper" id="tableWrapper"></div>
            <div class="pagination" id="pagination"></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>
        const form = document.getElementById('queryForm');
        const docIdInput = document.getElementById('docId');
        const filterInput = document.getElementById('filter');
        const sectionFilter = document.getElementById('sectionFilter');
        const clauseFilter = document.getElementById('clauseFilter');
        const pageSizeInput = document.getElementById('pageSize');
        const statusEl = document.getElementById('status');
        const summaryEl = document.getElementById('summary');
        const tableWrapper = document.getElementById('tableWrapper');
        const paginationEl = document.getElementById('pagination');
        const clearBtn = document.getElementById('clearBtn');
        const resultsPanel = document.getElementById('resultsPanel');
        const globalModeBtn = document.getElementById('globalMode');
        const rowCountEl = document.getElementById('rowCount');

        let rawChunks = [];
        let currentPage = 1;
        let sortCol = 'chunk_id';
        let sortDir = 'asc';
        let editing = { rowChunkId: null, col: null };

        const PAGE_SIZE = 25;

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

        function setStatus(msg, isErr=false) {
            statusEl.innerHTML = msg ? `<span style="${isErr ? 'color:#ff7b7b;font-weight:600;' : ''}">${esc(msg)}</span>` : '';
        }

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

        function fetchChunks(docId) {
            spinner();
            fetch(`/api/chunks?doc_id=${encodeURIComponent(docId)}`)
                .then(r => r.json())
                .then(data => {
                    if (data.error) {
                        setStatus(data.error, true);
                        resultsPanel.style.display = 'none';
                        return;
                    }
                    rawChunks = Array.isArray(data.chunks) ? data.chunks : [];
                    setStatus(rawChunks.length ? `Loaded ${rawChunks.length} chunk(s).` : 'No chunks.');
                    buildSummary(data);
                    currentPage = 1;
                    render();
                    resultsPanel.style.display = 'block';
                })
                .catch(err => {
                    setStatus('Failed to load chunks: ' + err.message, true);
                    resultsPanel.style.display = 'none';
                });
        }

        function fetchAllChunks() {
            setStatus('');
            summaryEl.innerHTML = '';
            spinner();
            // Prefer JSONL source so we can show all records
            fetch(`/api/chunks/jsonl`)
                .then(r => r.json())
                .then(data => {
                    if (data && data.chunks) {
                        rawChunks = Array.isArray(data.chunks) ? data.chunks : [];
                    } else if (Array.isArray(data)) {
                        rawChunks = data; // tolerate direct array response
                    } else {
                        rawChunks = [];
                    }
                    // If JSONL missing/empty, fall back to DB list with max limit
                    if (!rawChunks.length) {
                        return fetch(`/api/chunks/all?limit=500&offset=0`).then(r => r.json());
                    }
                    return { chunks: rawChunks };
                })
                .then(data => {
                    if (data && data.chunks && !rawChunks.length) {
                        rawChunks = Array.isArray(data.chunks) ? data.chunks : [];
                    }
                    setStatus(rawChunks.length ? `Loaded ${rawChunks.length} chunk(s).` : 'No chunks.');
                    currentPage = 1;
                    render();
                    resultsPanel.style.display = 'block';
                })
                .catch(err => {
                    setStatus('Failed to load global chunks: ' + err.message, true);
                });
        }

        function buildSummary(apiData) {
            summaryEl.innerHTML = '';
            if (!rawChunks.length) return;
            
            const last = rawChunks[rawChunks.length - 1];
            const meta = {
                doc_id: apiData.doc_id || 'Global',
                total_chunks: rawChunks.length,
                first_chunk_id: rawChunks[0]?.chunk_id,
                last_chunk_id: last?.chunk_id,
                token_version: last?.tok_ver,
                segment_version: last?.seg_ver
            };
            
            Object.entries(meta).forEach(([k, v]) => {
                summaryEl.insertAdjacentHTML('beforeend', 
                    `<div class="kv"><span class="k">${esc(k)}</span><span class="v">${esc(v)}</span></div>`);
            });
        }

        function applyFilters(list) {
            const t = filterInput.value.trim().toLowerCase();
            const s = sectionFilter.value.trim().toLowerCase();
            const c = clauseFilter.value.trim().toLowerCase();
            
            return list.filter(chunk => {
                if (t && !JSON.stringify(chunk).toLowerCase().includes(t)) return false;
                if (s && !(chunk.section_title || '').toLowerCase().includes(s)) return false;
                if (c && !(chunk.clause_type || '').toLowerCase().includes(c)) return false;
                return true;
            });
        }

        function compareValues(a, b) {
            const an = parseFloat(a); 
            const bn = parseFloat(b);
            const aNum = !isNaN(an) && String(an) === String(a).trim();
            const bNum = !isNaN(bn) && String(bn) === String(b).trim();
            
            if (aNum && bNum) {
                if (an < bn) return -1;
                if (an > bn) return 1;
                return 0;
            }
            
            const as = String(a).toLowerCase();
            const bs = String(b).toLowerCase();
            if (as < bs) return -1;
            if (as > bs) return 1;
            return 0;
        }

        function sortRows(rows) {
            if (!sortCol) return rows;
            return [...rows].sort((r1, r2) => {
                const v1 = r1[sortCol] ?? '';
                const v2 = r2[sortCol] ?? '';
                const cmp = compareValues(v1, v2);
                return sortDir === 'asc' ? cmp : -cmp;
            });
        }

        function setSort(col) {
            if (sortCol === col) {
                sortDir = sortDir === 'asc' ? 'desc' : 'asc';
            } else {
                sortCol = col;
                sortDir = 'asc';
            }
            currentPage = 1;
            render();
        }

        function buildHeader(cols) {
            return cols.map(c => {
                const active = c === sortCol;
                const indicator = active ? (sortDir === 'asc' ? '▲' : '▼') : '';
                return `<th class="sortable" data-col="${esc(c)}">${esc(c)}<span class="indicator">${indicator}</span></th>`;
            }).join('');
        }

        function paginate(rows) {
            const pageSize = parseInt(pageSizeInput.value, 10) || PAGE_SIZE;
            const pageCount = Math.max(1, Math.ceil(rows.length / pageSize));
            if (currentPage > pageCount) currentPage = pageCount;
            
            const start = (currentPage - 1) * pageSize;
            const slice = rows.slice(start, start + pageSize);
            
            updatePagination(currentPage, pageCount, slice.length, rows.length);
            return slice;
        }

        function updatePagination(current, total, visible, totalRows) {
            paginationEl.innerHTML = `
                <button id="firstPage" ${current === 1 ? 'disabled' : ''} title="First">⏮</button>
                <button id="prevPage" ${current === 1 ? 'disabled' : ''} title="Previous">◀</button>
                <span>Page ${current} / ${total}</span>
                <button id="nextPage" ${current === total ? 'disabled' : ''} title="Next">▶</button>
                <button id="lastPage" ${current === total ? 'disabled' : ''} title="Last">⏭</button>
                <span>| Rows: ${visible} / ${totalRows}</span>
            `;
            
            // Attach pagination event handlers
            const firstBtn = document.getElementById('firstPage');
            const prevBtn = document.getElementById('prevPage');
            const nextBtn = document.getElementById('nextPage');
            const lastBtn = document.getElementById('lastPage');
            
            firstBtn?.addEventListener('click', () => { currentPage = 1; render(); });
            prevBtn?.addEventListener('click', () => { if (currentPage > 1) { currentPage--; render(); } });
            nextBtn?.addEventListener('click', () => { currentPage++; render(); });
            lastBtn?.addEventListener('click', () => { currentPage = total; render(); });
            
            paginationEl.style.display = totalRows ? 'flex' : 'none';
        }

        function render() {
            const filtered = applyFilters(rawChunks);
            const rows = sortRows(filtered);
            rowCountEl.textContent = rows.length;
            
            if (!rows.length) {
                tableWrapper.innerHTML = '<div class="empty">No chunks match filters.</div>';
                paginationEl.style.display = 'none';
                return;
            }
            
            const pageRows = paginate(rows);
            renderTable(pageRows);
        }

        function renderTable(pageRows) {
            const cols = ["chunk_id", "doc_id", "text", "section_number", "section_title", "clause_type", "definition_terms", "embedding_count"];
            
            let html = '<table class="data-table"><thead><tr>' + buildHeader(cols) + '</tr></thead><tbody>';
            
            html += pageRows.map(r => {
                const rid = esc(r.chunk_id);
                let tds = cols.map(c => {
                    let val = r[c];
                    if (val == null) val = '';
                    let full = String(val);
                    let display = full;
                    
                    const nonEditable = (c === 'chunk_id' || c === 'doc_id' || c === 'embedding_count');
                    
                    if (c === 'text') {
                        // Truncate text to 350 characters unless editing
                        if (editing.rowChunkId === String(r.chunk_id) && editing.col === c) {
                            display = full; // Show full text when editing
                        } else {
                            display = full.length > 350 ? full.slice(0, 350) + '…' : full;
                        }
                    } else if (display.length > 160) {
                        display = display.slice(0, 160) + '…';
                    }
                    
                    const cls = [
                        display !== full ? 'truncate' : '', 
                        nonEditable ? '' : 'editable'
                    ].filter(Boolean).join(' ');
                    
                    let content = esc(display);
                    
                    if (editing.rowChunkId === String(r.chunk_id) && editing.col === c && !nonEditable) {
                        if (c === 'text') {
                            content = `<textarea style="width:100%;height:80px;background:#16232d;border:1px solid #4a6578;color:#fff;font-size:.65rem;padding:4px 6px;border-radius:4px;resize:vertical;" placeholder="Enter text...">${esc(full)}</textarea>`;
                        } else {
                            content = `<input type="text" style="width:100%;background:#16232d;border:1px solid #4a6578;color:#fff;font-size:.65rem;padding:4px 6px;border-radius:4px;" value="${esc(full)}" />`;
                        }
                    }
                    
                    return `<td data-col="${esc(c)}" data-chunk="${rid}" class="${cls}" title="${esc(full)}">${content}</td>`;
                }).join('');
                
                // Add action buttons if this row is being edited
                const actionTd = editing.rowChunkId === String(r.chunk_id) ? 
                    `<td class="row-actions"><button class="confirm">Save</button><button class="cancel">Cancel</button></td>` :
                    `<td></td>`;
                
                const rowClass = editing.rowChunkId === String(r.chunk_id) ? 'editing' : '';
                return `<tr data-chunk="${rid}" class="${rowClass}">${tds}${actionTd}</tr>`;
            }).join('');
            
            html += '</tbody></table>';
            tableWrapper.innerHTML = html;
            
            // Header sort handlers
            tableWrapper.querySelectorAll('th.sortable').forEach(th => {
                th.addEventListener('click', () => {
                    const col = th.getAttribute('data-col');
                    if (col) setSort(col);
                });
            });
            
            attachEditHandlers();
            focusEditingCell();
        }

        function attachEditHandlers() {
            // Attach direct click handlers to editable cells
            tableWrapper.querySelectorAll('td.editable').forEach(td => {
                td.addEventListener('click', () => beginCellEdit(td));
            });

            // Save/cancel handlers if visible
            tableWrapper.querySelectorAll('tr').forEach(tr => {
                const chunkId = tr.getAttribute('data-chunk');
                if (!chunkId) return;
                
                const confirmBtn = tr.querySelector('button.confirm');
                const cancelBtn = tr.querySelector('button.cancel');
                
                if (confirmBtn) confirmBtn.addEventListener('click', () => confirmCellEdit(chunkId));
                if (cancelBtn) cancelBtn.addEventListener('click', cancelCellEdit);
            });
        }

        function focusEditingCell() {
            if (!editing.rowChunkId || !editing.col) return;
            const row = tableWrapper.querySelector(`tr[data-chunk="${CSS.escape(editing.rowChunkId)}"]`);
            if (!row) return;
            const field = row.querySelector(`td[data-col="${CSS.escape(editing.col)}"] input, td[data-col="${CSS.escape(editing.col)}"] textarea`);
            if (field) {
                // Focus and place caret at the end
                field.focus();
                if (field.setSelectionRange && typeof field.value === 'string') {
                    const len = field.value.length;
                    try { field.setSelectionRange(len, len); } catch {}
                }
                // Keyboard shortcuts: Enter to save (except Shift+Enter for textarea), Esc to cancel
                field.addEventListener('keydown', (ev) => {
                    if (ev.key === 'Escape') { ev.preventDefault(); cancelCellEdit(); }
                    else if (ev.key === 'Enter') {
                        const isTextarea = field.tagName.toLowerCase() === 'textarea';
                        if (!isTextarea || (isTextarea && !ev.shiftKey)) {
                            ev.preventDefault();
                            confirmCellEdit(editing.rowChunkId);
                        }
                    }
                }, { once: true });
            }
        }

        function beginCellEdit(td) {
            const tr = td.closest('tr');
            const chunkId = tr.getAttribute('data-chunk');
            const col = td.getAttribute('data-col');
            
            if (!col || col === 'chunk_id' || col === 'doc_id' || col === 'embedding_count') return;
            
            // Only one cell at a time
            editing = { rowChunkId: String(chunkId), col };
            render();
        }

        function cancelCellEdit() {
            editing = { rowChunkId: null, col: null };
            render();
        }

        function confirmCellEdit(chunkId) {
            const row = tableWrapper.querySelector(`tr[data-chunk="${CSS.escape(chunkId)}"]`);
            if (!row) return;
            
            const cell = row.querySelector(`td[data-col="${CSS.escape(editing.col)}"] input, td[data-col="${CSS.escape(editing.col)}"] textarea`);
            if (!cell) {
                cancelCellEdit();
                return;
            }
            
            const newVal = cell.value.trim();
            const updates = { [editing.col]: newVal };
            
            setStatus('Saving…');
            
            fetch('/api/chunks', {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ chunk_id: parseInt(chunkId), updates })
            })
            .then(r => r.json().then(j => ({ ok: r.ok, data: j })))
            .then(res => {
                if (!res.ok) {
                    setStatus(res.data.error || 'Save failed', true);
                    return;
                }
                
                // Update local data
                const chunk = rawChunks.find(c => String(c.chunk_id) === String(chunkId));
                if (chunk) {
                    chunk[editing.col] = newVal;
                }
                
                setStatus('Saved.');
                cancelCellEdit();
            })
            .catch(err => setStatus('Save error: ' + err.message, true));
        }

        // Event listeners
        form.addEventListener('submit', e => {
            e.preventDefault();
            const id = docIdInput.value.trim();
            if (!id) {
                setStatus('Document ID required', true);
                return;
            }
            fetchChunks(id);
        });

        clearBtn.addEventListener('click', () => {
            docIdInput.value = '';
            filterInput.value = '';
            sectionFilter.value = '';
            clauseFilter.value = '';
            rawChunks = [];
            resultsPanel.style.display = 'none';
            setStatus('');
        });

        [filterInput, sectionFilter, clauseFilter, pageSizeInput].forEach(inp => 
            inp.addEventListener('input', () => { currentPage = 1; render(); })
        );

        globalModeBtn.addEventListener('click', () => {
            fetchAllChunks();
        });

        // Initial load
        const params = new URLSearchParams(window.location.search);
        const qsId = params.get('doc_id');
        if (qsId) {
            docIdInput.value = qsId;
            fetchChunks(qsId);
        } else {
            fetchAllChunks();
        }
    </script>
</body>
</html>