File size: 30,456 Bytes
ca4eb2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modern Dataset Builder</title>
    
    <!-- Marked.js -->
    <script src="https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js"></script>
    <!-- Phosphor Icons (para ícones mais bonitos) -->
    <script src="https://unpkg.com/@phosphor-icons/web"></script>

    <style>
        :root {
            /* Palette: Indigo & Slate */
            --primary: #4f46e5;
            --primary-hover: #4338ca;
            --secondary: #64748b;
            --danger: #ef4444;
            --danger-hover: #dc2626;
            --success: #22c55e;
            --bg: #f1f5f9;
            --surface: #ffffff;
            --border: #e2e8f0;
            --text-main: #1e293b;
            --text-muted: #64748b;
            --shadow-sm: 0 1px 3px rgba(0,0,0,0.1);
            --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.1);
            --radius: 12px;
        }

        * { box-sizing: border-box; }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background-color: var(--bg);
            color: var(--text-main);
            margin: 0;
            padding: 40px 20px;
            line-height: 1.5;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
        }

        h1 {
            text-align: center;
            color: var(--text-main);
            margin-bottom: 40px;
            font-weight: 800;
            letter-spacing: -0.025em;
        }

        /* --- Card Styles --- */
        .card {
            background: var(--surface);
            padding: 30px;
            border-radius: var(--radius);
            box-shadow: var(--shadow-md);
            margin-bottom: 30px;
            border: 1px solid var(--border);
        }

        /* --- Form --- */
        .form-title {
            margin-top: 0;
            display: flex;
            align-items: center;
            gap: 10px;
            color: var(--primary);
        }

        .form-group { margin-bottom: 20px; }
        
        label {
            display: block;
            font-weight: 600;
            margin-bottom: 8px;
            color: var(--text-main);
            font-size: 0.95rem;
        }

        textarea {
            width: 100%;
            padding: 15px;
            border: 1px solid var(--border);
            border-radius: 8px;
            font-family: monospace;
            font-size: 14px;
            resize: vertical;
            transition: border-color 0.2s, box-shadow 0.2s;
            background: #f8fafc;
        }

        textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
            background: #fff;
        }

        /* --- Buttons --- */
        .btn-group { display: flex; gap: 12px; flex-wrap: wrap; }
        
        button {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            font-size: 0.95rem;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        button:active { transform: translateY(1px); }

        .btn-primary { background-color: var(--primary); color: white; }
        .btn-primary:hover { background-color: var(--primary-hover); }
        
        .btn-danger { background-color: var(--danger); color: white; }
        .btn-danger:hover { background-color: var(--danger-hover); }
        
        .btn-success { background-color: var(--success); color: white; }
        .btn-success:hover { filter: brightness(90%); }
        
        .btn-secondary { background-color: var(--surface); border: 1px solid var(--border); color: var(--text-main); }
        .btn-secondary:hover { background-color: #f8fafc; border-color: #cbd5e1; }

        .btn-icon { padding: 8px; border-radius: 6px; }

        /* --- Toolbar (Search & Global Actions) --- */
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 20px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .search-box {
            flex: 1;
            position: relative;
            min-width: 250px;
        }
        .search-box input {
            width: 100%;
            padding: 10px 15px 10px 40px;
            border-radius: 8px;
            border: 1px solid var(--border);
            font-size: 1rem;
        }
        .search-box i {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-muted);
        }

        /* --- List --- */
        .list-header-info {
            font-weight: 700; color: var(--text-muted); margin-bottom: 10px;
            display: flex; justify-content: space-between; align-items: center;
        }

        .accordion-item {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: 8px;
            margin-bottom: 12px;
            overflow: hidden;
            transition: box-shadow 0.2s;
        }
        .accordion-item:hover { box-shadow: var(--shadow-sm); }

        .accordion-header {
            padding: 15px 20px;
            cursor: pointer;
            display: flex; justify-content: space-between; align-items: center;
            user-select: none;
            background: #fff;
        }
        .accordion-header:hover { background-color: #f8fafc; }

        .header-content {
            display: flex; align-items: center; gap: 15px; flex: 1; overflow: hidden;
        }
        
        .id-badge {
            background: #e0e7ff; color: var(--primary);
            padding: 4px 8px; border-radius: 6px; font-size: 0.8em; font-weight: 700;
        }
        
        .preview-text {
            color: var(--text-main);
            white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
            font-weight: 500;
        }

        .header-actions {
            display: flex; gap: 8px; align-items: center; margin-left: 15px;
        }

        .accordion-content {
            display: none; border-top: 1px solid var(--border);
            background-color: #fafafa; padding: 25px;
        }
        .accordion-item.active .accordion-content { display: block; animation: slideDown 0.2s ease-out; }
        .accordion-item.active .caret-icon { transform: rotate(180deg); }
        .caret-icon { transition: transform 0.2s; color: var(--text-muted); }

        /* --- Tabs in Item --- */
        .item-tabs { display: flex; gap: 2px; margin-bottom: 20px; border-bottom: 2px solid var(--border); }
        .tab-btn {
            background: transparent; border: none; padding: 10px 20px; cursor: pointer;
            color: var(--text-muted); border-bottom: 2px solid transparent; margin-bottom: -2px;
            border-radius: 6px 6px 0 0;
        }
        .tab-btn:hover { color: var(--primary); background: rgba(79, 70, 229, 0.05); }
        .tab-btn.active { color: var(--primary); border-bottom-color: var(--primary); font-weight: 700; background: #fff; border: 1px solid var(--border); border-bottom-color: #fff; }
        
        .tab-content { display: none; }
        .tab-content.active { display: block; }

        .field-label { font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted); font-weight: 700; margin: 15px 0 5px; display: flex; justify-content: space-between;}
        .data-box { background: #fff; border: 1px solid var(--border); padding: 15px; border-radius: 6px; white-space: pre-wrap; word-break: break-all; color: var(--text-main); font-family: monospace; font-size: 0.9em; }

        /* --- Pagination --- */
        .pagination { display: flex; justify-content: center; align-items: center; gap: 10px; margin-top: 30px; }
        .page-info { color: var(--text-muted); font-size: 0.9em; }

        /* --- Modal Custom --- */
        .modal-overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.5); backdrop-filter: blur(2px);
            display: flex; justify-content: center; align-items: center;
            z-index: 1000; opacity: 0; pointer-events: none;
            transition: opacity 0.2s;
        }
        .modal-overlay.open { opacity: 1; pointer-events: auto; }
        
        .modal {
            background: white; width: 90%; max-width: 450px;
            border-radius: 16px; padding: 25px;
            box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1);
            transform: scale(0.95); transition: transform 0.2s;
        }
        .modal-overlay.open .modal { transform: scale(1); }
        
        .modal h3 { margin-top: 0; color: var(--text-main); }
        .modal p { color: var(--text-muted); margin-bottom: 25px; }
        .modal-actions { display: flex; justify-content: flex-end; gap: 10px; }

        /* File input hidden */
        #fileInput { display: none; }

        @keyframes slideDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
    </style>
</head>
<body>

    <div class="container">
        <h1>Dataset Builder</h1>

        <!-- Editor Card -->
        <div class="card">
            <h3 id="formTitle" class="form-title"><i class="ph ph-pencil-simple"></i> New Record</h3>
            <form id="datasetForm">
                <div class="form-group">
                    <label for="input">Input</label>
                    <textarea id="input" name="input" rows="10" placeholder="Type the input text here..."></textarea>
                </div>
                <div class="form-group">
                    <label for="output">Output</label>
                    <textarea id="output" name="output" rows="10" placeholder="Type the expected output here..."></textarea>
                </div>
                <div class="btn-group">
                    <button type="submit" class="btn-primary" id="saveBtn"><i class="ph ph-floppy-disk"></i> Save Record</button>
                    <button type="button" class="btn-secondary" id="cancelBtn" style="display: none;"><i class="ph ph-x"></i> Cancel</button>
                </div>
            </form>
        </div>

        <!-- Toolbar -->
        <div class="toolbar">
            <div class="search-box">
                <i class="ph ph-magnifying-glass"></i>
                <input type="text" id="searchInput" placeholder="Search inputs..." onkeyup="handleSearch()" autocomplete="off">
            </div>
            <div class="btn-group">
                <input type="file" id="fileInput" accept=".json" onchange="processFile(this)">
                <button onclick="document.getElementById('fileInput').click()" class="btn-secondary">
                    <i class="ph ph-upload-simple"></i> Import JSON
                </button>
                <button onclick="downloadJSON()" class="btn-success">
                    <i class="ph ph-download-simple"></i> Export JSON
                </button>
                <button onclick="confirmDeleteAll()" class="btn-danger">
                    <i class="ph ph-trash"></i> Delete All
                </button>
            </div>
        </div>

        <!-- List Stats -->
        <div class="list-header-info">
            <span>Total Records: <span id="totalCount">0</span></span>
            <span>Showing: <span id="showingCount">0</span></span>
        </div>

        <!-- List Container -->
        <div id="listContainer"></div>

        <!-- Pagination -->
        <div class="pagination" id="paginationControls">
            <button class="btn-secondary btn-icon" id="prevPageBtn" onclick="changePage(-1)"><i class="ph ph-caret-left"></i></button>
            <span class="page-info">Page <span id="currPageDisplay">1</span> of <span id="totalPageDisplay">1</span></span>
            <button class="btn-secondary btn-icon" id="nextPageBtn" onclick="changePage(1)"><i class="ph ph-caret-right"></i></button>
        </div>
    </div>

    <!-- Custom Modal -->
    <div class="modal-overlay" id="customModal">
        <div class="modal">
            <h3 id="modalTitle">Title</h3>
            <p id="modalMessage">Message goes here</p>
            <div class="modal-actions">
                <button class="btn-secondary" id="modalCancelBtn">Cancel</button>
                <button class="btn-primary" id="modalConfirmBtn">Confirm</button>
            </div>
        </div>
    </div>

    <script>
        // State
        let dataset = [];
        let filteredDataset = [];
        let editingIndex = -1; // Index in the original dataset
        let currentPage = 1;
        const itemsPerPage = 10;
        let searchTerm = "";

        // Elements
        const form = document.getElementById('datasetForm');
        const inputField = document.getElementById('input');
        const outputField = document.getElementById('output');
        const listContainer = document.getElementById('listContainer');
        const saveBtn = document.getElementById('saveBtn');
        const cancelBtn = document.getElementById('cancelBtn');
        const formTitle = document.getElementById('formTitle');
        const modalOverlay = document.getElementById('customModal');

        // Init
        document.addEventListener('DOMContentLoaded', () => {
            if (typeof marked !== 'undefined') marked.setOptions({ breaks: true, gfm: true });
            loadFromStorage();
            filterAndRender();
        });

        // --- Core Functions ---

        form.addEventListener('submit', (e) => {
            e.preventDefault();
            const inputVal = inputField.value;
            const outputVal = outputField.value;

            if (!inputVal.trim() && !outputVal.trim()) {
                showAlert("Validation", "Please fill in at least one field.");
                return;
            }

            const record = { input: inputVal, output: outputVal };

            if (editingIndex >= 0) {
                dataset[editingIndex] = record;
                showAlert("Success", "Record updated successfully!", "success");
                editingIndex = -1;
            } else {
                dataset.push(record);
                showAlert("Success", "New record added!", "success");
            }

            saveToStorage();
            resetForm();
            filterAndRender(); // Re-filters and goes to page 1 or current
        });

        function handleSearch() {
            searchTerm = document.getElementById('searchInput').value.toLowerCase();
            currentPage = 1; // Reset to page 1 on search
            filterAndRender();
        }

        function filterAndRender() {
            // 1. Filter
            if (!searchTerm) {
                filteredDataset = dataset.map((item, index) => ({...item, originalIndex: index}));
            } else {
                filteredDataset = dataset
                    .map((item, index) => ({...item, originalIndex: index}))
                    .filter(item => item.input.toLowerCase().includes(searchTerm));
            }

            // 2. Update Stats
            document.getElementById('totalCount').innerText = dataset.length;
            document.getElementById('showingCount').innerText = filteredDataset.length;

            // 3. Pagination Logic
            const totalPages = Math.ceil(filteredDataset.length / itemsPerPage) || 1;
            if (currentPage > totalPages) currentPage = totalPages;
            if (currentPage < 1) currentPage = 1;

            const start = (currentPage - 1) * itemsPerPage;
            const end = start + itemsPerPage;
            const pageData = filteredDataset.slice(start, end);

            // 4. Render
            renderList(pageData);
            updatePaginationControls(totalPages);
        }

        function renderList(pageData) {
            listContainer.innerHTML = '';

            if (pageData.length === 0) {
                listContainer.innerHTML = `
                    <div style="text-align:center; padding:60px; color:var(--text-muted);">
                        <i class="ph ph-tray" style="font-size: 3em; margin-bottom:10px;"></i><br>
                        No records found.
                    </div>`;
                return;
            }

            pageData.forEach((item) => {
                const div = document.createElement('div');
                div.className = 'accordion-item';
                div.id = `item-${item.originalIndex}`;

                const previewText = item.input.length > 80 
                    ? item.input.substring(0, 80).replace(/\n/g, ' ') + '...' 
                    : item.input.replace(/\n/g, ' ');

                // Markdown rendering
                let mdRendered = "<i>Markdown library not loaded.</i>";
                let mdRaw = `### Record\n\n**Input:**\n${safeForMarkdown(item.input)}\n\n**Output:**\n${safeForMarkdown(item.output)}`;
                if (typeof marked !== 'undefined') {
                    mdRendered = marked.parse(mdRaw);
                }

                div.innerHTML = `
                    <div class="accordion-header" onclick="toggleAccordion(${item.originalIndex})">
                        <div class="header-content">
                            <span class="id-badge">#${item.originalIndex + 1}</span>
                            <span class="preview-text">${escapeHtml(previewText)}</span>
                        </div>
                        
                        <div class="header-actions">
                            <!-- Side Buttons (Stop Propagation) -->
                            <button onclick="editItem(event, ${item.originalIndex})" class="btn-secondary btn-icon" title="Edit">
                                <i class="ph ph-pencil-simple"></i>
                            </button>
                            <button onclick="confirmDeleteItem(event, ${item.originalIndex})" class="btn-danger btn-icon" title="Delete">
                                <i class="ph ph-trash"></i>
                            </button>
                            <i class="ph ph-caret-down caret-icon" style="margin-left:10px;"></i>
                        </div>
                    </div>
                    
                    <div class="accordion-content">
                        <div class="item-tabs">
                            <button class="tab-btn active" onclick="switchTab(event, 'view-data-${item.originalIndex}')">Raw Data</button>
                            <button class="tab-btn" onclick="switchTab(event, 'view-md-${item.originalIndex}')">Rendered Markdown</button>
                        </div>

                        <div id="view-data-${item.originalIndex}" class="tab-content active">
                            <div class="field-label">Input</div>
                            <div class="data-box">${escapeHtml(item.input)}</div>
                            
                            <div class="field-label">
                                <span>Output</span>
                                <button onclick="copyOutput(${item.originalIndex})" style="padding:2px 8px; font-size:0.75rem;" class="btn-secondary">
                                    <i class="ph ph-copy"></i> Copy
                                </button>
                            </div>
                            <div class="data-box">${escapeHtml(item.output)}</div>
                        </div>

                        <div id="view-md-${item.originalIndex}" class="tab-content">
                            <div style="background:#fff; padding:20px; border:1px solid var(--border); border-radius:8px;">
                                ${mdRendered}
                            </div>
                        </div>
                    </div>
                `;
                listContainer.appendChild(div);
            });
        }

        // --- Actions ---

        function editItem(e, index) {
            e.stopPropagation(); // Don't open accordion
            const item = dataset[index];
            inputField.value = item.input;
            outputField.value = item.output;
            editingIndex = index;

            saveBtn.innerHTML = '<i class="ph ph-arrows-clockwise"></i> Update Record';
            saveBtn.classList.remove('btn-primary');
            saveBtn.classList.add('btn-success');
            
            cancelBtn.style.display = 'inline-flex';
            formTitle.innerHTML = `<i class="ph ph-pencil-simple"></i> Editing Record #${index + 1}`;
            
            window.scrollTo({ top: 0, behavior: 'smooth' });
            inputField.focus();
        }

        function confirmDeleteItem(e, index) {
            e.stopPropagation();
            showConfirm(
                "Delete Record", 
                "Are you sure you want to delete this record? This cannot be undone.",
                () => deleteItem(index),
                "Delete",
                "danger"
            );
        }

        function deleteItem(index) {
            dataset.splice(index, 1);
            if (editingIndex === index) resetForm();
            saveToStorage();
            filterAndRender();
        }

        function confirmDeleteAll() {
            if (dataset.length === 0) return showAlert("Info", "No records to delete.");
            showConfirm(
                "Delete All Records",
                "⚠️ Are you sure you want to delete ALL records? This action is irreversible.",
                () => {
                    dataset = [];
                    resetForm();
                    saveToStorage();
                    filterAndRender();
                },
                "Delete All",
                "danger"
            );
        }

        function resetForm() {
            form.reset();
            editingIndex = -1;
            saveBtn.innerHTML = '<i class="ph ph-floppy-disk"></i> Save Record';
            saveBtn.classList.add('btn-primary');
            saveBtn.classList.remove('btn-success');
            cancelBtn.style.display = 'none';
            formTitle.innerHTML = '<i class="ph ph-pencil-simple"></i> New Record';
        }

        cancelBtn.addEventListener('click', resetForm);

        // --- JSON Import/Export ---

        function downloadJSON() {
            if (dataset.length === 0) return showAlert("Info", "Nothing to download.");
            const dataStr = JSON.stringify(dataset, null, 4); 
            const blob = new Blob([dataStr], { type: "application/json;charset=utf-8" });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `dataset_${new Date().toISOString().slice(0,10)}.json`;
            a.click();
            URL.revokeObjectURL(url);
        }

        function processFile(input) {
            const file = input.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    let importedData = JSON.parse(e.target.result);
                    
                    // Handle wrapped data { data: [...] } or raw array [...]
                    if (!Array.isArray(importedData) && importedData.data && Array.isArray(importedData.data)) {
                        importedData = importedData.data;
                    } else if (!Array.isArray(importedData)) {
                        throw new Error("Invalid JSON format. Expected an array.");
                    }

                    let addedCount = 0;
                    
                    // Deduplication Logic
                    importedData.forEach(newItem => {
                        if (!newItem.input && !newItem.output) return; // Skip empty
                        
                        // Check if exists
                        const exists = dataset.some(existing => 
                            existing.input === newItem.input && existing.output === newItem.output
                        );

                        if (!exists) {
                            dataset.push({ input: newItem.input, output: newItem.output });
                            addedCount++;
                        }
                    });

                    saveToStorage();
                    filterAndRender();
                    input.value = ''; // Reset file input
                    
                    if (addedCount > 0) {
                        showAlert("Import Successful", `Successfully imported ${addedCount} new records. Duplicates were skipped.`, "success");
                    } else {
                        showAlert("Import Info", "No new records were added. All records already existed.", "normal");
                    }

                } catch (err) {
                    showAlert("Import Error", "Failed to parse JSON file. Make sure format is correct.", "danger");
                    console.error(err);
                }
            };
            reader.readAsText(file);
        }

        // --- UI Helpers ---

        function changePage(delta) {
            const totalPages = Math.ceil(filteredDataset.length / itemsPerPage) || 1;
            const newPage = currentPage + delta;
            if (newPage >= 1 && newPage <= totalPages) {
                currentPage = newPage;
                filterAndRender();
                window.scrollTo({ top: document.querySelector('.list-header-info').offsetTop - 20, behavior: 'smooth' });
            }
        }

        function updatePaginationControls(totalPages) {
            document.getElementById('currPageDisplay').innerText = currentPage;
            document.getElementById('totalPageDisplay').innerText = totalPages;
            document.getElementById('prevPageBtn').disabled = currentPage === 1;
            document.getElementById('nextPageBtn').disabled = currentPage === totalPages;
            
            // Visual disable style
            document.getElementById('prevPageBtn').style.opacity = currentPage === 1 ? '0.5' : '1';
            document.getElementById('nextPageBtn').style.opacity = currentPage === totalPages ? '0.5' : '1';
        }

        function toggleAccordion(originalIndex) {
            const item = document.getElementById(`item-${originalIndex}`);
            item.classList.toggle('active');
        }

        function switchTab(event, tabId) {
            event.stopPropagation();
            const contentDiv = event.target.closest('.accordion-content');
            contentDiv.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            contentDiv.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
            event.target.classList.add('active');
            document.getElementById(tabId).classList.add('active');
        }

        function copyOutput(index) {
            const item = dataset[index];
            if(!item.output) return showAlert("Info", "Output is empty.");
            copyToClipboard(item.output, "Output copied to clipboard!");
        }

        function copyToClipboard(text, successMsg) {
            navigator.clipboard.writeText(text).then(() => {
                showAlert("Success", successMsg, "success");
            }).catch(err => {
                // Fallback
                const txt = document.createElement("textarea");
                txt.value = text;
                document.body.appendChild(txt);
                txt.select();
                document.execCommand("copy");
                document.body.removeChild(txt);
                showAlert("Success", successMsg, "success");
            });
        }

        // --- Custom Modal System ---

        function showModal(title, message, onConfirm, showCancel = false, confirmText = "OK", type = "primary") {
            const titleEl = document.getElementById('modalTitle');
            const msgEl = document.getElementById('modalMessage');
            const confirmBtn = document.getElementById('modalConfirmBtn');
            const cancelBtn = document.getElementById('modalCancelBtn');

            titleEl.textContent = title;
            msgEl.textContent = message;
            
            confirmBtn.textContent = confirmText;
            confirmBtn.className = type === 'danger' ? 'btn-danger' : 'btn-primary';
            
            cancelBtn.style.display = showCancel ? 'block' : 'none';

            // Clone buttons to remove old event listeners
            const newConfirm = confirmBtn.cloneNode(true);
            const newCancel = cancelBtn.cloneNode(true);
            confirmBtn.parentNode.replaceChild(newConfirm, confirmBtn);
            cancelBtn.parentNode.replaceChild(newCancel, cancelBtn);

            newConfirm.addEventListener('click', () => {
                if (onConfirm) onConfirm();
                closeModal();
            });

            newCancel.addEventListener('click', closeModal);

            modalOverlay.classList.add('open');
        }

        function closeModal() {
            modalOverlay.classList.remove('open');
        }

        function showAlert(title, message, type="primary") {
            showModal(title, message, null, false, "OK", type);
        }

        function showConfirm(title, message, onConfirm, confirmText="Confirm", type="primary") {
            showModal(title, message, onConfirm, true, confirmText, type);
        }

        // --- Utilities ---
        function safeForMarkdown(text) { return text ? text.replace(/</g, "&lt;").replace(/>/g, "&gt;") : ""; }
        function escapeHtml(text) {
            if (!text) return "";
            return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
        }
        
        // --- Storage (Mantido 'jsonDatasetRender' para compatibilidade) ---
        function saveToStorage() { localStorage.setItem('jsonDatasetRender', JSON.stringify(dataset)); }
        function loadFromStorage() {
            const saved = localStorage.getItem('jsonDatasetRender');
            if (saved) dataset = JSON.parse(saved);
        }
    </script>
</body>
</html>