File size: 27,954 Bytes
84e1dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
974b29f
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Deep Study - Data Vault</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>

    <style>

        :root {

            --bg-main: #0f172a;

            --bg-card: rgba(30, 41, 59, 0.7);

            --text-main: #f8fafc;

            --text-muted: #94a3b8;

            --primary: #3b82f6;

            --danger: #ef4444;

            --success: #10b981;

            --warning: #f59e0b;

            --border: rgba(255, 255, 255, 0.1);

        }



        @media (prefers-color-scheme: light) {

            :root {

                --bg-main: #f8fafc;

                --bg-card: rgba(255, 255, 255, 0.9);

                --text-main: #0f172a;

                --text-muted: #64748b;

                --border: rgba(0, 0, 0, 0.1);

            }

        }



        * { box-sizing: border-box; font-family: 'Poppins', sans-serif; }

        body { margin: 0; padding: 0; background: var(--bg-main); color: var(--text-main); overflow-x: hidden; }



        /* HEADER */

        .header { 

            position: sticky; top: 0; z-index: 100; backdrop-filter: blur(15px); -webkit-backdrop-filter: blur(15px);

            background: var(--bg-card); padding: 15px 20px; border-bottom: 1px solid var(--border);

            display: flex; justify-content: space-between; align-items: center; box-shadow: 0 4px 20px rgba(0,0,0,0.1);

        }

        .header h1 { margin: 0; font-size: 20px; font-weight: 800; display: flex; align-items: center; gap: 10px; }

        .back-btn { background: var(--border); border: none; color: var(--text-main); padding: 8px 12px; border-radius: 10px; cursor: pointer; font-weight: bold; }



        /* BUTTONS */

        .btn { padding: 10px 15px; border-radius: 12px; border: none; font-weight: 600; cursor: pointer; transition: 0.2s; display: inline-flex; align-items: center; gap: 8px; font-size: 13px; }

        .btn:hover { transform: translateY(-2px); }

        .btn-danger { background: var(--danger); color: white; box-shadow: 0 4px 15px rgba(239, 68, 68, 0.3); }

        .btn-primary { background: var(--primary); color: white; box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3); }

        .btn-warning { background: var(--warning); color: white; box-shadow: 0 4px 15px rgba(245, 158, 11, 0.3); }



        .top-controls { display: flex; gap: 10px; padding: 20px; flex-wrap: wrap; }



        /* STORAGE RING UI */

        .storage-overview { padding: 20px; margin: 20px; background: var(--bg-card); border-radius: 20px; border: 1px solid var(--border); box-shadow: 0 10px 30px rgba(0,0,0,0.05); }

        .storage-bar-bg { width: 100%; height: 24px; background: var(--border); border-radius: 12px; overflow: hidden; display: flex; margin-top: 15px; }

        .storage-chunk { height: 100%; transition: width 0.5s ease; }

        .chunk-media { background: var(--primary); }

        .chunk-chats { background: var(--success); }

        .chunk-system { background: var(--warning); }

        

        .legend { display: flex; gap: 15px; margin-top: 15px; font-size: 12px; font-weight: bold; flex-wrap: wrap; }

        .legend-item { display: flex; align-items: center; gap: 5px; }

        .legend-dot { width: 12px; height: 12px; border-radius: 4px; }



        /* ACCORDIONS */

        .section-container { padding: 0 20px 100px 20px; }

        .accordion { margin-bottom: 15px; background: var(--bg-card); border: 1px solid var(--border); border-radius: 16px; overflow: hidden; transition: 0.3s; }

        .acc-header { padding: 15px 20px; display: flex; justify-content: space-between; align-items: center; cursor: pointer; font-weight: 700; user-select: none; }

        .acc-header:hover { background: rgba(255,255,255,0.05); }

        .acc-title { display: flex; align-items: center; gap: 10px; font-size: 16px; }

        .acc-size { color: var(--text-muted); font-size: 14px; background: var(--border); padding: 4px 10px; border-radius: 20px; }

        

        .acc-content { display: none; padding: 0; border-top: 1px solid var(--border); }

        .acc-content.active { display: block; animation: slideDown 0.3s ease; }



        /* LIST ITEMS */

        .list-item { padding: 15px 20px; display: flex; align-items: center; gap: 15px; border-bottom: 1px solid var(--border); transition: 0.2s; }

        .list-item:hover { background: rgba(255,255,255,0.03); }

        .list-item:last-child { border-bottom: none; }

        

        .checkbox { width: 20px; height: 20px; cursor: pointer; accent-color: var(--primary); }

        .item-info { flex: 1; min-width: 0; }

        .item-name { font-weight: 600; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; gap: 8px; }

        .item-meta { font-size: 12px; color: var(--text-muted); margin-top: 4px; }

        

        /* MEDIA PREVIEWS */

        .media-preview { width: 50px; height: 50px; border-radius: 8px; object-fit: cover; background: var(--border); }



        /* STICKY ACTION BAR */

        .selection-bar {

            position: fixed; bottom: -100px; left: 50%; transform: translateX(-50%);

            background: var(--primary); color: white; padding: 15px 25px; border-radius: 30px;

            display: flex; align-items: center; gap: 20px; font-weight: bold; z-index: 1000;

            box-shadow: 0 10px 40px rgba(59, 130, 246, 0.5); transition: bottom 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);

        }

        .selection-bar.active { bottom: 30px; }



        /* RENAME MODAL */

        .modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.8); z-index: 9999; justify-content: center; align-items: center; backdrop-filter: blur(5px); }

        .modal-box { background: var(--bg-main); padding: 25px; border-radius: 20px; width: 90%; max-width: 400px; border: 1px solid var(--border); }

        .modal-box input { width: 100%; padding: 12px; border-radius: 10px; border: 1px solid var(--border); background: var(--bg-card); color: var(--text-main); margin: 15px 0; outline: none; }



        @keyframes slideDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }

    </style>
</head>
<body>

    <div class="header">
        <h1><button class="back-btn" onclick="apsToggleSidebar()" title="All pages">☰</button><span style="font-size:24px;">🗄️</span> Data Vault</h1>
        <button class="back-btn" onclick="window.history.back()">✖ Close</button>
    </div>

    <div class="top-controls">
        <button class="btn btn-warning" onclick="clearPwaCache()">🧹 Clear App Cache</button>
        <button class="btn btn-danger" onclick="logoutGoogle()">🚪 Logout Google</button>
        <button class="btn btn-primary" onclick="exportData()">💾 Backup Data (JSON)</button>
        <button class="btn btn-primary" style="background:#8b5cf6;" onclick="document.getElementById('importFile').click()">📂 Restore Backup</button>
        <input type="file" id="importFile" accept=".json" style="display:none;" onchange="importData(event)">
        <button class="btn btn-danger" style="background:#991b1b; width: 100%; justify-content: center;" onclick="nukeEverything()">☢️ NUKE ALL APP DATA</button>
    </div>

    <div class="storage-overview">
        <div style="display:flex; justify-content:space-between; align-items:flex-end;">
            <div>
                <div style="font-size:13px; color:var(--text-muted); font-weight:bold; text-transform:uppercase;">Hardware Storage Used</div>
                <div style="font-size:32px; font-weight:800;" id="totalUsedTxt">Calculating...</div>
            </div>
            <div style="font-size:13px; color:var(--text-muted); font-weight:bold; text-align:right;">
                App Usage: <span id="appUsedTxt" style="color:var(--text-main);">...</span><br>
                Device Free: <span id="freeSpaceTxt" style="color:var(--success);">...</span>
            </div>
        </div>

        <div class="storage-bar-bg">
            <div class="storage-chunk chunk-media" id="barMedia" style="width: 0%;" title="Media & Attachments"></div>
            <div class="storage-chunk chunk-chats" id="barChats" style="width: 0%;" title="AI Conversations"></div>
            <div class="storage-chunk chunk-system" id="barSystem" style="width: 0%;" title="System Cache & Settings"></div>
        </div>

        <div class="legend">
            <div class="legend-item"><div class="legend-dot chunk-media"></div> Media (<span id="legMedia">0 MB</span>)</div>
            <div class="legend-item"><div class="legend-dot chunk-chats"></div> Chats (<span id="legChats">0 MB</span>)</div>
            <div class="legend-item"><div class="legend-dot chunk-system"></div> System & Cache (<span id="legSystem">0 MB</span>)</div>
        </div>
    </div>

    <div class="section-container">
        <!-- AI CONVERSATIONS -->
        <div class="accordion">
            <div class="acc-header" onclick="toggleAcc('acc-chats')">
                <div class="acc-title">💬 AI Conversations</div>
                <div class="acc-size" id="size-chats">0 KB</div>
            </div>
            <div class="acc-content" id="acc-chats">
                <div style="padding: 10px 20px; background: rgba(0,0,0,0.2); display: flex; gap: 10px;">
                    <button class="btn" style="padding: 5px 10px; font-size: 11px;" onclick="selectAll('chat-cb')">Select All</button>
                    <button class="btn btn-danger" style="padding: 5px 10px; font-size: 11px;" onclick="clearCategory('chats')">Clear Category</button>
                </div>
                <div id="list-chats"></div>
            </div>
        </div>

        <!-- MEDIA & ATTACHMENTS -->
        <div class="accordion">
            <div class="acc-header" onclick="toggleAcc('acc-media')">
                <div class="acc-title">🖼️ Media & Extracts</div>
                <div class="acc-size" id="size-media">0 KB</div>
            </div>
            <div class="acc-content" id="acc-media">
                <div style="padding: 10px 20px; background: rgba(0,0,0,0.2); display: flex; gap: 10px;">
                    <button class="btn" style="padding: 5px 10px; font-size: 11px;" onclick="selectAll('media-cb')">Select All</button>
                    <button class="btn btn-danger" style="padding: 5px 10px; font-size: 11px;" onclick="clearCategory('media')">Clear Category</button>
                </div>
                <div id="list-media"></div>
            </div>
        </div>

        <!-- SYSTEM & SETTINGS -->
        <div class="accordion">
            <div class="acc-header" onclick="toggleAcc('acc-system')">
                <div class="acc-title">⚙️ System & Settings</div>
                <div class="acc-size" id="size-system">0 KB</div>
            </div>
            <div class="acc-content" id="acc-system">
                <div id="list-system"></div>
            </div>
        </div>
    </div>

    <!-- STICKY BOTTOM BAR -->
    <div class="selection-bar" id="selectionBar">
        <span id="selCount">0 Selected</span>
        <button class="btn btn-danger" style="box-shadow:none; border:2px solid white;" onclick="deleteSelected()">🗑️ Delete</button>
    </div>

    <!-- RENAME MODAL -->
    <div class="modal" id="renameModal">
        <div class="modal-box">
            <h3 style="margin-top:0; color:var(--primary);">Rename Storage Item</h3>
            <input type="text" id="renameInput" placeholder="Enter new name...">
            <div style="display:flex; gap:10px;">
                <button class="btn btn-primary" style="flex:1;" onclick="saveRename()">💾 Save</button>
                <button class="btn" style="flex:1; background:var(--border); color:var(--text-main);" onclick="document.getElementById('renameModal').style.display='none'">Cancel</button>
            </div>
        </div>
    </div>

    <script>

        localforage.config({ name: 'AI_Pro_Suite', storeName: 'massive_chat_history' });



        let appDataState = {

            chats: [],

            media: [],

            system: []

        };

        

        let renameTargetId = null;



        function formatBytes(bytes, decimals = 2) {

            if (!+bytes) return '0 Bytes';

            const k = 1024; const dm = decimals < 0 ? 0 : decimals;

            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];

            const i = Math.floor(Math.log(bytes) / Math.log(k));

            return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;

        }



        function getStrBytes(str) { return str ? str.length * 2 : 0; }



        function toggleAcc(id) {

            const el = document.getElementById(id);

            el.classList.toggle('active');

        }



        async function scanStorage() {

            appDataState = { chats: [], media: [], system: [] };

            let totalChatsBytes = 0; let totalMediaBytes = 0; let totalSystemBytes = 0;



            // 🧠 UPGRADED MEDIA EXTRACTOR: Catches all base64 images perfectly

            const extractMedia = (htmlStr, parentId, parentName) => {

                if (!htmlStr) return 0;

                let mediaCount = 0;

                let localMediaBytes = 0;

                const imgRegex = /<img[^>]+src=["'](data:image\/[^"']+)["']/gi;

                let match;

                while ((match = imgRegex.exec(htmlStr)) !== null) {

                    const b64String = match[1];

                    const imgBytes = getStrBytes(b64String);

                    localMediaBytes += imgBytes;

                    totalMediaBytes += imgBytes;

                    mediaCount++;

                    appDataState.media.push({

                        id: `media_${parentId}_${mediaCount}`,

                        parentId: parentId,

                        name: `Image from ${parentName}`,

                        src: b64String,

                        bytes: imgBytes

                    });

                }

                return localMediaBytes;

            };



            // 1. Scan LocalStorage for Chat Arrays & Settings

            for (let i = 0; i < localStorage.length; i++) {

                const key = localStorage.key(i);

                const val = localStorage.getItem(key);

                const bytes = getStrBytes(val);



                if (key === 'bookSessionsArray_VUltimateAI') {

                    try {

                        const sessions = JSON.parse(val);

                        sessions.forEach(sess => {

                            const sessBytes = getStrBytes(JSON.stringify(sess));

                            const mediaB = extractMedia(sess.html, sess.id, sess.title || "Saved Session");

                            totalChatsBytes += sessBytes;

                            appDataState.chats.push({

                                id: sess.id,

                                name: sess.title || "Saved Session",

                                date: new Date(Number(sess.id) > 10000 ? Number(sess.id) : Date.now()).toLocaleString(),

                                bytes: sessBytes - mediaB // Subtract media so it's not double-counted

                            });

                        });

                    } catch(e) {}

                } else if (key === 'bookChatHistory_VUltimateAI') {

                    // 🚨 FIXED: Your active chat is now properly categorized!

                    const mediaB = extractMedia(val, 'active_chat', 'Current Active Chat');

                    totalChatsBytes += bytes;

                    appDataState.chats.push({ 

                        id: key, 

                        name: `🟢 Current Active Chat`, 

                        date: 'Live Now', 

                        bytes: bytes - mediaB 

                    });

                } else if (key === 'bookSettings_VUltimateAI') {

                    totalSystemBytes += bytes;

                    appDataState.system.push({ id: key, name: `Active Book Settings`, bytes });

                } else if (key.includes('quota') || key.includes('gsi')) {

                    totalSystemBytes += bytes;

                    appDataState.system.push({ id: key, name: `Google/API Token: ${key}`, bytes });

                } else {

                    totalSystemBytes += bytes;

                    appDataState.system.push({ id: key, name: `Misc Key: ${key}`, bytes });

                }

            }



            // 2. Scan Service Worker Caches

            let cacheBytes = 0;

            if ('caches' in window) {

                const cacheNames = await caches.keys();

                for (let name of cacheNames) {

                    const cache = await caches.open(name);

                    const keys = await cache.keys();

                    cacheBytes += (keys.length * 50000); 

                }

                totalSystemBytes += cacheBytes;

                if(cacheBytes > 0) appDataState.system.push({ id: 'pwa_cache', name: 'PWA Offline Cache', bytes: cacheBytes });

            }



            // 3. Scan LocalForage (IndexedDB)

            try {

                const lfKeys = await localforage.keys();

                for (let k of lfKeys) {

                    const val = await localforage.getItem(k);

                    const bytes = getStrBytes(JSON.stringify(val));

                    

                    if (k === 'aiHistory') {

                        totalChatsBytes += bytes;

                        appDataState.chats.push({ id: `lf_${k}`, name: `Deep Vault Archive`, date: 'Offline DB', bytes });

                    } else {

                        totalSystemBytes += bytes;

                        appDataState.system.push({ id: `lf_${k}`, name: `IndexedDB: ${k}`, date: 'Offline', bytes });

                    }

                }

            } catch(e) {}



            // UPDATE UI TOTALS

            const totalAppBytes = totalChatsBytes + totalMediaBytes + totalSystemBytes;

            document.getElementById('appUsedTxt').innerText = formatBytes(totalAppBytes);

            

            document.getElementById('size-chats').innerText = formatBytes(totalChatsBytes);

            document.getElementById('size-media').innerText = formatBytes(totalMediaBytes);

            document.getElementById('size-system').innerText = formatBytes(totalSystemBytes);



            document.getElementById('legChats').innerText = formatBytes(totalChatsBytes);

            document.getElementById('legMedia').innerText = formatBytes(totalMediaBytes);

            document.getElementById('legSystem').innerText = formatBytes(totalSystemBytes);



            if(totalAppBytes > 0) {

                document.getElementById('barChats').style.width = `${(totalChatsBytes / totalAppBytes) * 100}%`;

                document.getElementById('barMedia').style.width = `${(totalMediaBytes / totalAppBytes) * 100}%`;

                document.getElementById('barSystem').style.width = `${(totalSystemBytes / totalAppBytes) * 100}%`;

            } else {

                document.getElementById('barChats').style.width = `0%`;

                document.getElementById('barMedia').style.width = `0%`;

                document.getElementById('barSystem').style.width = `0%`;

            }



            // GET HARDWARE QUOTA

            if (navigator.storage && navigator.storage.estimate) {

                const estimate = await navigator.storage.estimate();

                document.getElementById('totalUsedTxt').innerText = formatBytes(estimate.usage);

                

                // 🚨 FIXED: Clarified that this is the BROWSER limit, not phone storage.

                document.getElementById('freeSpaceTxt').innerText = `${formatBytes(estimate.quota - estimate.usage)} (Browser Sandbox Limit: ${formatBytes(estimate.quota)})`;

            }



            renderLists();

        }



        function renderLists() {

            const render = (arr, elId, cbClass, isSystem) => {

                const el = document.getElementById(elId);

                if (arr.length === 0) { el.innerHTML = `<div style="padding:20px; text-align:center; color:var(--text-muted);">Empty</div>`; return; }

                

                el.innerHTML = arr.map(item => `

                    <div class="list-item" id="item-${item.id}">

                        ${!isSystem ? `<input type="checkbox" class="checkbox ${cbClass}" value="${item.id}" onchange="updateSelection()">` : ''}

                        ${item.src ? `<img src="${item.src}" class="media-preview">` : `<div style="font-size:24px;">${elId.includes('chat') ? '📄' : '⚙️'}</div>`}

                        <div class="item-info">

                            <div class="item-name">${item.name} ${!isSystem && !item.src ? `<button style="background:none; border:none; cursor:pointer; font-size:12px;" onclick="openRename('${item.id}', '${item.name.replace(/'/g,"\\'")}')">✏️</button>` : ''}</div>

                            <div class="item-meta">${formatBytes(item.bytes)} • ${item.date || 'System Data'}</div>

                        </div>

                    </div>

                `).join('');

            };



            render(appDataState.chats, 'list-chats', 'chat-cb', false);

            render(appDataState.media, 'list-media', 'media-cb', false);

            render(appDataState.system, 'list-system', '', true);

        }



        function selectAll(cbClass) {

            const cbs = document.querySelectorAll(`.${cbClass}`);

            const allChecked = Array.from(cbs).every(cb => cb.checked);

            cbs.forEach(cb => cb.checked = !allChecked);

            updateSelection();

        }



        function updateSelection() {

            const checked = document.querySelectorAll('.checkbox:checked').length;

            const bar = document.getElementById('selectionBar');

            document.getElementById('selCount').innerText = `${checked} Selected`;

            if (checked > 0) bar.classList.add('active');

            else bar.classList.remove('active');

        }



        function clearCategory(type) {

            if(!confirm(`Delete ALL ${type}? This cannot be undone.`)) return;

            document.querySelectorAll(`.${type}-cb`).forEach(cb => cb.checked = true);

            deleteSelected();

        }



        function deleteSelected() {

            if(!confirm("Permanently delete selected items?")) return;

            const selected = Array.from(document.querySelectorAll('.checkbox:checked')).map(cb => cb.value);

            

            // Handle Chat Array Deletions

            let savedSessions = JSON.parse(localStorage.getItem('bookSessionsArray_VUltimateAI')) || [];

            

            selected.forEach(async id => {

                if (id === 'bookChatHistory_VUltimateAI') {

                    localStorage.removeItem('bookChatHistory_VUltimateAI');

                } else if (id.startsWith('lf_')) {

                    await localforage.removeItem(id.replace('lf_', ''));

                } else if (id.startsWith('media_')) {

                    alert("Media is embedded inside Chat logs. To delete this media, delete the parent Chat Session.");

                } else {

                    savedSessions = savedSessions.filter(s => s.id != id);

                }

            });



            localStorage.setItem('bookSessionsArray_VUltimateAI', JSON.stringify(savedSessions));

            

            document.getElementById('selectionBar').classList.remove('active');

            scanStorage();

        }



        function openRename(id, oldName) {

            renameTargetId = id;

            document.getElementById('renameInput').value = oldName;

            document.getElementById('renameModal').style.display = 'flex';

        }



        function saveRename() {

            const newName = document.getElementById('renameInput').value.trim();

            if(!newName || !renameTargetId) return;



            let savedSessions = JSON.parse(localStorage.getItem('bookSessionsArray_VUltimateAI')) || [];

            let session = savedSessions.find(s => s.id == renameTargetId);

            if(session) {

                session.title = newName;

                localStorage.setItem('bookSessionsArray_VUltimateAI', JSON.stringify(savedSessions));

            } else if (renameTargetId === 'bookChatHistory_VUltimateAI') {

                alert("Cannot rename the current active session from here. Save it first.");

            }

            

            document.getElementById('renameModal').style.display = 'none';

            scanStorage();

        }



        // --- GLOBAL ACTIONS ---



        async function clearPwaCache() {

            if(!confirm("Wipe PWA caches? App will need internet to reload assets.")) return;

            if ('caches' in window) {

                const keys = await caches.keys();

                await Promise.all(keys.map(k => caches.delete(k)));

            }

            alert("App cache cleared!");

            scanStorage();

        }



        function logoutGoogle() {

            if(!confirm("Wipe Google Auth Session?")) return;

            localStorage.removeItem("gsi_user_session");

            alert("Logged out of Google on this app layer.");

            scanStorage();

        }



        async function nukeEverything() {

            if(!confirm("☢️ WARNING: This deletes EVERYTHING. Chats, Settings, Caches, Logins. Proceed?")) return;

            if(!confirm("☢️ FINAL WARNING: There is no undo.")) return;

            

            localStorage.clear();

            sessionStorage.clear();

            await localforage.clear();

            if ('caches' in window) { const keys = await caches.keys(); await Promise.all(keys.map(k => caches.delete(k))); }

            

            alert("Data annihilated. Reloading system.");

            window.location.href = "index.html";

        }



        function exportData() {

            const dump = { local: {}, forage: {} };

            for(let i=0; i<localStorage.length; i++) {

                const k = localStorage.key(i); dump.local[k] = localStorage.getItem(k);

            }

            const blob = new Blob([JSON.stringify(dump)], {type: "application/json"});

            const url = URL.createObjectURL(blob);

            const a = document.createElement('a');

            a.href = url; a.download = `DeepStudy_Backup_${Date.now()}.json`;

            a.click(); URL.revokeObjectURL(url);

        }



        function importData(event) {

            const file = event.target.files[0];

            if(!file) return;

            const reader = new FileReader();

            reader.onload = function(e) {

                try {

                    const data = JSON.parse(e.target.result);

                    if(data.local) { Object.keys(data.local).forEach(k => localStorage.setItem(k, data.local[k])); }

                    alert("Backup restored! Reloading...");

                    window.location.reload();

                } catch(err) { alert("Invalid backup file."); }

            };

            reader.readAsText(file);

        }



        // INIT

        window.onload = scanStorage;

    </script>
<script src="nav-sidebar.js" data-pos="none"></script>
</body>
</html>