File size: 38,994 Bytes
c511686
 
 
 
 
57b392b
c511686
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7e707a
c511686
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dataset Caption Tag Manager - Local only, NO uploads</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- JSZip for Firefox/Fallback Export -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        dark: { 900: '#11111b', 800: '#1e1e2e', 700: '#313244', 600: '#45475a', 500: '#585b70' },
                        accent: { primary: '#89b4fa', secondary: '#cba6f7', danger: '#f38ba8', success: '#a6e3a1' }
                    }
                }
            }
        }
    </script>
    <style>
        /* Custom Scrollbar */
        ::-webkit-scrollbar { width: 8px; height: 8px; }
        ::-webkit-scrollbar-track { background: #1e1e2e; }
        ::-webkit-scrollbar-thumb { background: #45475a; border-radius: 4px; }
        ::-webkit-scrollbar-thumb:hover { background: #585b70; }

        body { font-family: system-ui, -apple-system, sans-serif; background-color: #11111b; color: #cdd6f4; overflow: hidden; }
        
        .img-card { transition: transform 0.1s, box-shadow 0.1s; }
        .img-card.selected { box-shadow: 0 0 0 4px #89b4fa; transform: scale(0.98); }
        
        .tag-pill { display: inline-flex; align-items: center; background: #313244; padding: 2px 8px; border-radius: 12px; font-size: 0.85rem; margin: 2px; border: 1px solid #cba6f7; cursor: pointer; transition: background 0.2s;}
        .tag-pill:hover { background: #45475a; }
        
        #lightbox { display: none; background: rgba(0,0,0,0.85); backdrop-filter: blur(4px); z-index: 50; }
        #lightbox.active { display: flex; }
        #lightbox img { max-height: 90vh; max-width: 90vw; object-fit: contain; }

        #custom-modal { display: none; background: rgba(0,0,0,0.6); backdrop-filter: blur(2px); z-index: 60; }
        #custom-modal.active { display: flex; }

        .drop-zone-overlay { display: none; background: rgba(137, 180, 250, 0.2); border: 4px dashed #89b4fa; z-index: 40;}
        body.dragover .drop-zone-overlay { display: flex; }
    </style>
</head>
<body class="h-screen flex flex-col">

    <!-- Top Navigation Bar -->
    <header class="bg-dark-800 border-b border-dark-700 p-3 flex flex-wrap items-center justify-between gap-4 shrink-0">
        <div class="flex items-center gap-2">
            <h1 class="text-xl font-bold text-accent-primary mr-4">TagManager</h1>
            
            <button id="btn-load-folder" class="bg-dark-700 hover:bg-dark-600 text-white px-3 py-1.5 rounded text-sm flex items-center gap-2 transition" title="Requires Chromium">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"></path></svg>
                Load Folder
            </button>
            <span class="text-dark-500 text-xs">-or-</span>
            <input type="file" id="btn-load-files" multiple accept="image/*,.txt" class="text-sm text-gray-400 file:mr-2 file:py-1 file:px-2 file:rounded file:border-0 file:text-sm file:bg-dark-700 file:text-white hover:file:bg-dark-600 cursor-pointer" title="Fallback for Firefox or specific files">

            <div class="w-px h-6 bg-dark-600 mx-2"></div>

            <button id="btn-undo" class="bg-dark-700 hover:bg-dark-600 text-white px-3 py-1.5 rounded text-sm flex items-center gap-2 transition disabled:opacity-50 disabled:cursor-not-allowed">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"></path></svg>
                Undo (<span id="undo-count">0</span>)
            </button>

            <!-- New Sort Lines Button -->
            <button id="btn-sort-lines" class="bg-dark-700 hover:bg-dark-600 text-white border border-transparent px-3 py-1.5 rounded text-sm flex items-center gap-2 transition" title="Toggle sorting order of the master list">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12"></path></svg>
                <span id="sort-label">Sort: Time</span>
            </button>
        </div>

        <div class="flex items-center gap-3">
            <div class="flex items-center gap-1">
                <label class="text-xs text-dark-400">Prefix:</label>
                <input type="text" id="global-prefix" class="bg-dark-900 border border-dark-600 rounded px-2 py-1 text-sm w-32 focus:border-accent-primary outline-none" placeholder="e.g. triggerword,">
            </div>
            <div class="flex items-center gap-1">
                <label class="text-xs text-dark-400">Suffix:</label>
                <input type="text" id="global-suffix" class="bg-dark-900 border border-dark-600 rounded px-2 py-1 text-sm w-32 focus:border-accent-primary outline-none" placeholder="e.g. masterpiece">
            </div>
            
            <label class="flex items-center gap-2 text-sm cursor-pointer ml-2">
                <input type="checkbox" id="toggle-uncaptioned" class="rounded bg-dark-900 border-dark-600 text-accent-primary focus:ring-accent-primary">
                Uncaptioned Only
            </label>

            <!-- Select/Deselect All Buttons -->
            <div class="flex items-center gap-1 ml-1">
                <button id="btn-select-all" class="text-xs bg-dark-700 hover:bg-dark-600 px-2 py-1.5 rounded text-dark-300 hover:text-white transition" title="Select all currently visible images">Select All</button>
                <button id="btn-deselect-all" class="text-xs bg-dark-700 hover:bg-dark-600 px-2 py-1.5 rounded text-dark-300 hover:text-white transition" title="Deselect all images">Deselect</button>
            </div>

            <div class="w-px h-6 bg-dark-600 mx-2"></div>
            
            <button id="btn-export-folder" class="bg-accent-primary hover:bg-blue-400 text-dark-900 font-medium px-3 py-1.5 rounded text-sm flex items-center gap-2 transition" title="Overwrites/Saves .txt directly (Chromium Only)">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"></path></svg>
                Save to Folder
            </button>
            <button id="btn-export-zip" class="bg-dark-700 hover:bg-dark-600 text-white border border-dark-500 px-3 py-1.5 rounded text-sm flex items-center gap-2 transition" title="Downloads a .zip of all .txt files (All Browsers)">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"></path></svg>
                Export ZIP
            </button>
        </div>
    </header>

    <!-- Main Layout -->
    <main class="flex-1 flex overflow-hidden">
        <!-- Image Grid -->
        <div id="grid-container" class="flex-1 overflow-y-auto p-4 relative">
            <div class="flex justify-between items-center mb-4 text-sm text-dark-400">
                <span id="status-text">0 Images Loaded</span>
                <span class="italic text-xs"> LOCAL browser storage Only, no Uploads, no cookies, no nothing.   -----------  SHIFT+CLICK to MULTI-SELECT - - CTRL+CLICK to TOGGLE.</span>
            </div>
            <div id="image-grid" class="grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-4">
                <!-- Images will be injected here -->
            </div>
        </div>

        <!-- Right Sidebar (Master List) -->
        <div class="w-80 bg-dark-800 border-l border-dark-700 flex flex-col shrink-0">
            <!-- Lines Section -->
            <div class="flex-1 flex flex-col min-h-0">
                <div class="p-3 bg-dark-700 font-semibold text-sm flex justify-between items-center">
                    <span>Sentences / Lines</span>
                    <span class="text-xs text-dark-400 font-normal">Click to apply selected</span>
                </div>
                <div class="p-2 border-b border-dark-600 flex gap-2">
                    <input type="text" id="input-new-line" class="flex-1 bg-dark-900 border border-dark-600 rounded px-2 py-1 text-sm focus:border-accent-secondary outline-none" placeholder="New line (Enter)">
                    <button id="btn-add-line" class="bg-dark-600 hover:bg-dark-500 px-2 rounded">+</button>
                </div>
                <div id="list-lines" class="flex-1 overflow-y-auto p-2 flex flex-col gap-1">
                    <!-- Lines will be injected here -->
                </div>
            </div>
        </div>
    </main>

    <!-- Overlay UI -->
    <div class="drop-zone-overlay absolute inset-0 items-center justify-center pointer-events-none">
        <div class="bg-dark-800 p-8 rounded-xl border border-accent-primary shadow-2xl flex flex-col items-center">
            <svg class="w-16 h-16 text-accent-primary mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path></svg>
            <h2 class="text-2xl font-bold">Drop Images/Folders Here</h2>
        </div>
    </div>

    <div id="lightbox" class="fixed inset-0 items-center justify-center">
        <img id="lightbox-img" src="" alt="High-res preview">
    </div>

    <!-- Custom Modal -->
    <div id="custom-modal" class="fixed inset-0 items-center justify-center">
        <div class="bg-dark-800 border border-dark-600 rounded-lg shadow-xl w-96 p-5 flex flex-col gap-4">
            <h3 id="modal-title" class="text-lg font-bold">Title</h3>
            <p id="modal-desc" class="text-sm text-dark-400">Description</p>
            <input type="text" id="modal-input" class="bg-dark-900 border border-dark-600 rounded px-3 py-2 text-sm focus:border-accent-primary outline-none">
            <div class="flex justify-end gap-2 mt-2">
                <button id="modal-cancel" class="px-4 py-2 rounded text-sm bg-dark-700 hover:bg-dark-600 transition">Cancel</button>
                <button id="modal-confirm" class="px-4 py-2 rounded text-sm bg-accent-primary text-dark-900 font-bold hover:bg-blue-400 transition">Confirm</button>
            </div>
        </div>
    </div>

    <script>
        // --- State Management ---
        const imageStore = {}; // { id: { file, url, name, hash } }
        let directoryHandle = null; // For File System API saving
        
        let state = {
            imageOrder: [], // [id1, id2]
            imageTags: {}, // { id: [tagId1, tagId2] }
            tags: {}, // { tagId: { text: "cat" } }
            selected: [], // [id1, id2]
            globalPrefix: "",
            globalSuffix: "",
            showUncaptioned: false
        };

        const history = []; // Stack of cloned states (max 3)
        let lastSelectedIdx = -1;
        
        let isSortedAlphabetically = false; // View state for sidebar sorting

        // --- Core Functions ---
        const generateId = () => Math.random().toString(36).substr(2, 9);
        
        const pushState = () => {
            history.push(JSON.parse(JSON.stringify(state)));
            if (history.length > 3) history.shift();
            updateUndoUI();
        };

        const popState = () => {
            if (history.length === 0) return;
            state = history.pop();
            lastSelectedIdx = -1;
            updateUndoUI();
            renderAll();
        };

        const updateUndoUI = () => {
            const btn = document.getElementById('btn-undo');
            const count = document.getElementById('undo-count');
            count.textContent = history.length;
            btn.disabled = history.length === 0;
        };

        const createTag = (text) => {
            text = text.trim();
            if (!text) return null;
            // Check if exists
            for (const [id, tag] of Object.entries(state.tags)) {
                if (tag.text.toLowerCase() === text.toLowerCase()) return id;
            }
            const id = generateId();
            state.tags[id] = { text };
            return id;
        };

        // --- UI & Rendering ---
        const renderAll = () => {
            renderGrid();
            renderSidebar();
            updateStatus();
            document.getElementById('global-prefix').value = state.globalPrefix;
            document.getElementById('global-suffix').value = state.globalSuffix;
            document.getElementById('toggle-uncaptioned').checked = state.showUncaptioned;
        };

        const updateStatus = () => {
            document.getElementById('status-text').textContent = 
                `${state.imageOrder.length} Images Loaded | ${state.selected.length} Selected`;
        };

        const renderSidebar = () => {
            const listLines = document.getElementById('list-lines');
            listLines.innerHTML = '';

            const lines = [];
            for (const [id, tag] of Object.entries(state.tags)) {
                lines.push({id, ...tag});
            }

            // Apply Sort filter if enabled
            if (isSortedAlphabetically) {
                lines.sort((a, b) => a.text.localeCompare(b.text));
            }

            lines.forEach(l => {
                const el = document.createElement('div');
                el.className = 'bg-dark-900 border border-dark-600 rounded p-2 text-sm text-dark-300 hover:border-accent-secondary cursor-pointer group relative flex items-center min-h-[40px]';
                el.innerHTML = `
                    <p class="pr-12 break-words whitespace-normal">${l.text}</p>
                    <div class="absolute right-2 top-1/2 -translate-y-1/2 hidden group-hover:flex gap-2">
                        <button class="hover:text-accent-primary" onclick="editTag(event, '${l.id}')"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg></button>
                        <button class="text-accent-danger hover:text-red-400" onclick="deleteMasterTag(event, '${l.id}')"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg></button>
                    </div>
                `;
                el.onclick = () => applyTagToSelected(l.id);
                listLines.appendChild(el);
            });
        };

        const renderGrid = () => {
            const grid = document.getElementById('image-grid');
            grid.innerHTML = '';

            let visibleOrder = state.imageOrder;
            if (state.showUncaptioned) {
                visibleOrder = visibleOrder.filter(id => state.imageTags[id].length === 0);
            }

            visibleOrder.forEach((id, displayIdx) => {
                const imgData = imageStore[id];
                const isSelected = state.selected.includes(id);
                const tagIds = state.imageTags[id];

                const card = document.createElement('div');
                card.className = `img-card bg-dark-800 rounded-lg overflow-hidden border border-dark-700 flex flex-col ${isSelected ? 'selected' : ''}`;
                card.dataset.id = id;
                card.dataset.idx = state.imageOrder.indexOf(id);

                // Thumbnail area
                const imgWrap = document.createElement('div');
                imgWrap.className = 'relative h-48 w-full cursor-pointer bg-dark-900 group';
                imgWrap.innerHTML = `
                    <img src="${imgData.url}" loading="lazy" class="w-full h-full object-contain">
                    <div class="absolute inset-0 bg-black/50 hidden group-hover:flex items-center justify-center pointer-events-none">
                        <span class="text-white text-xs bg-dark-900/80 px-2 py-1 rounded border border-dark-600">Select</span>
                    </div>
                    <button class="absolute top-2 right-2 bg-dark-900/80 p-1 rounded hidden group-hover:block hover:bg-accent-primary text-white hover:text-dark-900 transition z-10" onclick="openLightbox(event, '${imgData.url}')" title="Zoom">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"></path></svg>
                    </button>
                    <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-2 text-xs truncate pointer-events-none">${imgData.name}</div>
                `;
                imgWrap.onclick = (e) => handleImageSelect(e, id, state.imageOrder.indexOf(id));

                // Tags area
                const tagsWrap = document.createElement('div');
                tagsWrap.className = 'p-2 flex-1 flex flex-col gap-2 min-h-[80px] bg-dark-800';
                
                const pillsContainer = document.createElement('div');
                pillsContainer.className = 'flex flex-wrap gap-1 flex-1 content-start';
                
                tagIds.forEach(tagId => {
                    const tagDef = state.tags[tagId];
                    if (!tagDef) return; // safety
                    const pill = document.createElement('span');
                    pill.className = `tag-pill group flex items-start text-left`;
                    
                    const textDisplay = `<span class="break-words whitespace-normal leading-tight py-0.5">${tagDef.text}</span>`;
                        
                    pill.innerHTML = `${textDisplay} <button class="ml-1 text-dark-400 group-hover:text-accent-danger flex-shrink-0" onclick="removeTagFromImage(event, '${id}', '${tagId}')">&times;</button>`;
                    pillsContainer.appendChild(pill);
                });

                // Input to add tag to specific image
                const inputWrap = document.createElement('div');
                inputWrap.innerHTML = `<input type="text" class="w-full bg-dark-900 border border-dark-600 rounded px-2 py-1 text-xs outline-none focus:border-accent-primary" placeholder="Add sentence/line to this image (Enter)" onkeydown="handleImageInputKey(event, '${id}')">`;

                tagsWrap.appendChild(pillsContainer);
                tagsWrap.appendChild(inputWrap);

                card.appendChild(imgWrap);
                card.appendChild(tagsWrap);
                grid.appendChild(card);
            });
        };

        // --- Interaction Logic ---
        const handleImageSelect = (e, id, idx) => {
            pushState();
            if (e.shiftKey && lastSelectedIdx !== -1) {
                // Range select
                const start = Math.min(lastSelectedIdx, idx);
                const end = Math.max(lastSelectedIdx, idx);
                for (let i = start; i <= end; i++) {
                    const currId = state.imageOrder[i];
                    if (!state.selected.includes(currId)) state.selected.push(currId);
                }
            } else if (e.ctrlKey || e.metaKey) {
                // Toggle
                const sIdx = state.selected.indexOf(id);
                if (sIdx > -1) state.selected.splice(sIdx, 1);
                else state.selected.push(id);
                lastSelectedIdx = idx;
            } else {
                // Single select (or deselect all if clicking already selected)
                if (state.selected.length === 1 && state.selected[0] === id) {
                    state.selected = [];
                    lastSelectedIdx = -1;
                } else {
                    state.selected = [id];
                    lastSelectedIdx = idx;
                }
            }
            renderGridClasses();
            updateStatus();
        };

        const renderGridClasses = () => {
            document.querySelectorAll('.img-card').forEach(card => {
                if (state.selected.includes(card.dataset.id)) card.classList.add('selected');
                else card.classList.remove('selected');
            });
        }

        const applyTagToSelected = (tagId) => {
            if (state.selected.length === 0) {
                showModal("Info", "Select one or more images first to apply this line.", null, false);
                return;
            }
            pushState();
            let applied = 0;
            state.selected.forEach(imgId => {
                if (!state.imageTags[imgId].includes(tagId)) {
                    state.imageTags[imgId].push(tagId);
                    applied++;
                }
            });
            if (applied > 0) renderGrid();
        };

        const removeTagFromImage = (e, imgId, tagId) => {
            e.stopPropagation();
            pushState();
            state.imageTags[imgId] = state.imageTags[imgId].filter(t => t !== tagId);
            renderGrid();
        };

        const handleImageInputKey = (e, imgId) => {
            if (e.key === 'Enter' && e.target.value.trim()) {
                pushState();
                const text = e.target.value.trim();
                const tagId = createTag(text);
                if (!state.imageTags[imgId].includes(tagId)) {
                    state.imageTags[imgId].push(tagId);
                }
                e.target.value = '';
                renderAll();
            }
        };

        const deleteMasterTag = (e, tagId) => {
            e.stopPropagation();
            pushState();
            // Remove from master list
            delete state.tags[tagId];
            // Remove from all images
            for (const imgId of state.imageOrder) {
                state.imageTags[imgId] = state.imageTags[imgId].filter(t => t !== tagId);
            }
            renderAll();
        };

        const editTag = (e, tagId) => {
            e.stopPropagation();
            const tag = state.tags[tagId];
            showModal("Edit Line", "Modify the text. Changes will reflect on all linked images.", (newVal) => {
                if (newVal) {
                    pushState();
                    state.tags[tagId].text = newVal;
                    renderAll();
                }
            }, true, tag.text);
        };

        // --- File Handling & Importing ---
        const processFiles = async (filesArray) => {
            const images = [];
            const texts = {}; // lowercase basename -> content

            for (const file of filesArray) {
                if (!file || !file.name) continue;
                const name = file.name;
                const ext = name.slice((name.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
                if (['jpg', 'jpeg', 'png', 'webp'].includes(ext)) {
                    images.push(file);
                } else if (ext === 'txt') {
                    const baseName = name.replace(/\.[^/.]+$/, "").toLowerCase();
                    const text = await file.text();
                    texts[baseName] = text;
                }
            }

            if (images.length === 0) return;
            pushState();

            images.forEach(imgFile => {
                const baseName = imgFile.name.replace(/\.[^/.]+$/, "");
                const hash = imgFile.name + imgFile.size; // Basic dup check
                
                // Skip duplicates
                let isDup = false;
                for (const existingId of state.imageOrder) {
                    if (imageStore[existingId].hash === hash) { isDup = true; break; }
                }
                if (isDup) return;

                const id = generateId();
                imageStore[id] = {
                    file: imgFile,
                    url: URL.createObjectURL(imgFile),
                    name: imgFile.name,
                    hash: hash,
                    baseName: baseName
                };
                state.imageOrder.push(id);
                state.imageTags[id] = [];

                // Import logic: Check if matching txt exists
                if (texts[baseName.toLowerCase()]) {
                    const content = texts[baseName.toLowerCase()];
                    // Split by comma for tags
                    const parts = content.split(',').map(s => s.trim()).filter(s => s);
                    parts.forEach(part => {
                        const tagId = createTag(part);
                        if (!state.imageTags[id].includes(tagId)) {
                            state.imageTags[id].push(tagId);
                        }
                    });
                }
            });

            renderAll();
        };

        // --- Event Listeners ---
        
        // Add Master Lines
        document.getElementById('input-new-line').addEventListener('keydown', (e) => {
            if (e.key === 'Enter') document.getElementById('btn-add-line').click();
        });
        document.getElementById('btn-add-line').addEventListener('click', () => {
            const inp = document.getElementById('input-new-line');
            if(inp.value.trim()) { pushState(); createTag(inp.value); inp.value = ''; renderSidebar(); }
        });

        // Toggle Sorting Logic
        document.getElementById('btn-sort-lines').addEventListener('click', (e) => {
            isSortedAlphabetically = !isSortedAlphabetically;
            const btn = e.currentTarget;
            const label = document.getElementById('sort-label');
            
            if (isSortedAlphabetically) {
                label.textContent = 'Sort: A-Z';
                btn.classList.replace('text-white', 'text-accent-primary');
                btn.classList.replace('border-transparent', 'border-accent-primary');
            } else {
                label.textContent = 'Sort: Time';
                btn.classList.replace('text-accent-primary', 'text-white');
                btn.classList.replace('border-accent-primary', 'border-transparent');
            }
            renderSidebar();
        });

        // Top Bar inputs & Toggles
        document.getElementById('global-prefix').addEventListener('input', e => state.globalPrefix = e.target.value);
        document.getElementById('global-suffix').addEventListener('input', e => state.globalSuffix = e.target.value);
        
        document.getElementById('toggle-uncaptioned').addEventListener('change', e => {
            state.showUncaptioned = e.target.checked;
            renderGrid();
        });

        document.getElementById('btn-select-all').addEventListener('click', () => {
            if (state.imageOrder.length === 0) return;
            pushState();
            let visibleOrder = state.imageOrder;
            if (state.showUncaptioned) {
                visibleOrder = visibleOrder.filter(id => state.imageTags[id].length === 0);
            }
            state.selected = [...visibleOrder];
            renderGridClasses();
            updateStatus();
        });

        document.getElementById('btn-deselect-all').addEventListener('click', () => {
            if (state.selected.length === 0) return;
            pushState();
            state.selected = [];
            lastSelectedIdx = -1;
            renderGridClasses();
            updateStatus();
        });

        document.getElementById('btn-undo').addEventListener('click', popState);

        // Lightbox
        const lightbox = document.getElementById('lightbox');
        const openLightbox = (e, url) => {
            e.stopPropagation();
            document.getElementById('lightbox-img').src = url;
            lightbox.classList.add('active');
        };
        lightbox.addEventListener('click', () => lightbox.classList.remove('active'));

        // Load folder via standard input fallback
        document.getElementById('btn-load-files').addEventListener('change', (e) => {
            processFiles(Array.from(e.target.files));
            e.target.value = ''; // reset
        });

        // Load folder via API (Chromium)
        document.getElementById('btn-load-folder').addEventListener('click', async () => {
            if (!window.showDirectoryPicker) {
                showModal("Browser Unsupported", "Direct folder access is only available in Chromium browsers (Chrome, Edge, Brave). Please use the 'Load Files' fallback button next to it.", null, false);
                return;
            }
            try {
                directoryHandle = await window.showDirectoryPicker({ mode: 'readwrite' });
                const files = [];
                for await (const entry of directoryHandle.values()) {
                    if (entry.kind === 'file') {
                        files.push(await entry.getFile());
                    }
                }
                processFiles(files);
            } catch (err) {
                console.warn(err);
            }
        });

        // --- Chromium-Proof Drag and Drop ---
        document.body.addEventListener('dragover', e => { e.preventDefault(); document.body.classList.add('dragover'); });
        document.body.addEventListener('dragleave', e => { if (e.target === document.body || e.relatedTarget === null) document.body.classList.remove('dragover'); });
        document.body.addEventListener('drop', e => {
            e.preventDefault();
            document.body.classList.remove('dragover');
            
            const files = [];
            const dirEntries = [];

            if (e.dataTransfer.items) {
                // Parse synchronously! Chromium will clear e.dataTransfer.items if we yield/await here.
                for (let i = 0; i < e.dataTransfer.items.length; i++) {
                    const item = e.dataTransfer.items[i];
                    if (item.kind === 'file') {
                        const entry = item.webkitGetAsEntry ? item.webkitGetAsEntry() : null;
                        if (entry && entry.isDirectory) {
                            dirEntries.push(entry);
                        } else {
                            const file = item.getAsFile();
                            if (file) files.push(file);
                        }
                    }
                }
            } else if (e.dataTransfer.files) {
                for (let i = 0; i < e.dataTransfer.files.length; i++) {
                    files.push(e.dataTransfer.files[i]);
                }
            }

            // Fast path for normal file drops
            if (dirEntries.length === 0) {
                if (files.length > 0) processFiles(files);
                return;
            }

            // Complex path for dropped folders (Recursive reading)
            const readDir = (dirEntry) => {
                return new Promise(resolve => {
                    const dirReader = dirEntry.createReader();
                    const allEntries = [];
                    
                    const readBatch = () => {
                        dirReader.readEntries(async (entries) => {
                            if (entries.length === 0) {
                                // Batch finished, now process the collected entries
                                const filePromises = allEntries.map(ent => {
                                    return new Promise(res => {
                                        if (ent.isFile) {
                                            ent.file(f => res(f), () => res(null));
                                        } else if (ent.isDirectory) {
                                            readDir(ent).then(res); // Recurse inside
                                        } else {
                                            res(null);
                                        }
                                    });
                                });
                                const nestedFiles = await Promise.all(filePromises);
                                resolve(nestedFiles.flat().filter(f => f !== null));
                            } else {
                                allEntries.push(...entries);
                                readBatch(); // Fetch next batch of 100 entries
                            }
                        }, () => resolve([])); // Error fallback
                    };
                    readBatch();
                });
            };

            // Process all dropped directory entries
            Promise.all(dirEntries.map(readDir)).then(results => {
                files.push(...results.flat());
                if (files.length > 0) processFiles(files);
            });
        });

        // Get Caption String for an Image
        const getCaptionString = (id) => {
            const tagIds = state.imageTags[id];
            let elements = [];
            if (state.globalPrefix) elements.push(state.globalPrefix.trim());
            
            tagIds.forEach(tid => {
                if(state.tags[tid]) elements.push(state.tags[tid].text);
            });

            if (state.globalSuffix) elements.push(state.globalSuffix.trim());
            
            // Join properly avoiding double commas
            return elements.join(', ').replace(/,\s*,/g, ',').trim();
        };

        // Export ZIP
        document.getElementById('btn-export-zip').addEventListener('click', async () => {
            if (state.imageOrder.length === 0) return showModal("Info", "No images loaded.", null, false);
            
            const zip = new JSZip();
            let count = 0;
            state.imageOrder.forEach(id => {
                const text = getCaptionString(id);
                if (text) {
                    const baseName = imageStore[id].baseName;
                    zip.file(`${baseName}.txt`, text);
                    count++;
                }
            });

            if (count === 0) return showModal("Info", "No captions to export.", null, false);

            const btn = document.getElementById('btn-export-zip');
            const originalText = btn.innerHTML;
            btn.innerHTML = 'Generating...';
            
            zip.generateAsync({type:"blob"}).then(function(content) {
                const a = document.createElement("a");
                a.href = URL.createObjectURL(content);
                a.download = "captions_export.zip";
                a.click();
                btn.innerHTML = originalText;
            });
        });

        // Export to Folder (Direct API)
        document.getElementById('btn-export-folder').addEventListener('click', async () => {
            if (!window.showDirectoryPicker) {
                showModal("Browser Unsupported", "Saving directly to a folder requires a Chromium browser. Please use 'Export ZIP' instead.", null, false);
                return;
            }
            if (state.imageOrder.length === 0) return showModal("Info", "No images loaded.", null, false);

            let handleToUse = directoryHandle;
            if (!handleToUse) {
                try {
                    handleToUse = await window.showDirectoryPicker({ mode: 'readwrite' });
                } catch(e) { return; } // User cancelled
            }

            const btn = document.getElementById('btn-export-folder');
            const originalText = btn.innerHTML;
            btn.innerHTML = 'Saving...';

            let count = 0;
            try {
                for (const id of state.imageOrder) {
                    const text = getCaptionString(id);
                    if (text) {
                        const baseName = imageStore[id].baseName;
                        const fileHandle = await handleToUse.getFileHandle(`${baseName}.txt`, { create: true });
                        const writable = await fileHandle.createWritable();
                        // Flux standard dictates utf-8
                        await writable.write(new Blob([text], {type: 'text/plain;charset=utf-8'}));
                        await writable.close();
                        count++;
                    }
                }
                showModal("Success", `Saved ${count} caption files directly to folder.`, null, false);
            } catch (err) {
                showModal("Error", "Permission to write denied or folder access lost. " + err.message, null, false);
            } finally {
                btn.innerHTML = originalText;
            }
        });

        // --- Custom Modal UI ---
        const modal = document.getElementById('custom-modal');
        const modalTitle = document.getElementById('modal-title');
        const modalDesc = document.getElementById('modal-desc');
        const modalInput = document.getElementById('modal-input');
        const btnCancel = document.getElementById('modal-cancel');
        const btnConfirm = document.getElementById('modal-confirm');
        let modalConfirmCallback = null;

        const showModal = (title, desc, onConfirm, showInput = false, defaultVal = "") => {
            modalTitle.textContent = title;
            modalDesc.textContent = desc;
            
            if (showInput) {
                modalInput.style.display = 'block';
                modalInput.value = defaultVal;
            } else {
                modalInput.style.display = 'none';
            }

            btnCancel.style.display = onConfirm ? 'block' : 'none';
            modalConfirmCallback = onConfirm;
            
            modal.classList.add('active');
            if (showInput) modalInput.focus();
        };

        const closeModal = () => {
            modal.classList.remove('active');
            modalConfirmCallback = null;
        };

        btnCancel.addEventListener('click', closeModal);
        btnConfirm.addEventListener('click', () => {
            const val = modalInput.value.trim();
            if (modalConfirmCallback) modalConfirmCallback(val);
            closeModal();
        });
        modalInput.addEventListener('keydown', e => {
            if (e.key === 'Enter') btnConfirm.click();
        });
        
    </script>
</body>
</html>