File size: 30,441 Bytes
95d95a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Memories</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.js"></script>
    <style>
        .memory-card {
            transition: all 0.3s ease;
            border: 1px solid #e5e7eb;
        }
        .memory-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }
        .loading-shimmer {
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: shimmer 1.5s infinite;
        }
        @keyframes shimmer {
            0% { background-position: 200% 0; }
            100% { background-position: -200% 0; }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-50 to-blue-50 min-h-screen">
    <div class="max-w-6xl mx-auto px-4 py-8">
        <!-- Header -->
        <header class="text-center mb-12">
            <h1 class="text-5xl font-bold text-gray-800 mb-4">
                <i data-lucide="brain" class="inline-block mr-3 text-blue-600"></i>
                My Memories
            </h1>
            <p class="text-gray-600 text-lg">Capture and organize your thoughts with AI-powered memory management</p>
        </header>

        <div class="grid lg:grid-cols-3 gap-8">
            <!-- Add Memory Section -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h2 class="text-2xl font-semibold text-gray-800 mb-4 flex items-center">
                        <i data-lucide="plus-circle" class="mr-2 text-green-500"></i>
                        Add New Memory
                    </h2>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Content</label>
                            <textarea 
                                id="content" 
                                rows="4" 
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                                placeholder="Share your thoughts, ideas, or memories..."
                            ></textarea>
                            <p class="text-xs text-gray-500 mt-1">Supports up to 5000 characters</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Tag</label>
                            <input 
                                type="text" 
                                id="memoryTag" 
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                                placeholder="e.g., work, personal, idea"
                            >
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Source</label>
                            <input 
                                type="text" 
                                id="memorySource" 
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                                placeholder="e.g., book, article, thought"
                            >
                        </div>
                        
                        <button 
                            onclick="addMemory()" 
                            class="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-4 rounded-lg transition-all duration-200 flex items-center justify-center"
                        >
                            <i data-lucide="save" class="mr-2"></i>
                            Add Memory
                        </button>
                        
                        <div id="addStatus" class="text-sm"></div>
                    </div>
                </div>

                <!-- Advanced Controls -->
                <div class="bg-white rounded-xl shadow-lg p-6 mt-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-3 flex items-center">
                        <i data-lucide="sliders" class="mr-2 text-purple-500"></i>
                        Advanced
                    </h3>
                    <div class="space-y-3">
                        <button onclick="groupMemories()" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-2 px-4 rounded-lg">
                            Group Memories
                        </button>
                        <button onclick="exportMemories()" class="w-full bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-lg">
                            Export Memories
                        </button>
                        <button onclick="importMemories()" class="w-full bg-orange-600 hover:bg-orange-700 text-white font-medium py-2 px-4 rounded-lg">
                            Import Memories
                        </button>
                    </div>
                </div>

                <!-- API Key Section -->
                <div class="bg-white rounded-xl shadow-lg p-6 mt-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-3 flex items-center">
                        <i data-lucide="key" class="mr-2 text-purple-500"></i>
                        Configuration
                    </h3>
                    <button 
                        onclick="updateAPIKey()" 
                        class="w-full bg-gray-600 hover:bg-gray-700 text-white font-medium py-2 px-4 rounded-lg transition-colors"
                    >
                        Update API Key
                    </button>
                </div>
            </div>

            <!-- Memories List Section -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-2xl font-semibold text-gray-800 flex items-center">
                            <i data-lucide="list" class="mr-2 text-indigo-500"></i>
                            My Memories
                        </h2>
                        <button 
                            onclick="listMemories()" 
                            class="bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200 flex items-center"
                        >
                            <i data-lucide="refresh-cw" class="mr-2"></i>
                            Refresh
                        </button>
                    </div>
                    
                    <!-- Search and Filter -->
                    <div class="mb-4 space-y-3">
                        <div class="flex gap-2">
                            <input 
                                type="text" 
                                id="searchQuery" 
                                placeholder="Search memories..." 
                                class="flex-1 px-3 py-2 border border-gray-300 rounded-lg"
                                onkeypress="if(event.key === 'Enter') searchMemories()"
                            >
                            <button onclick="searchMemories()" class="px-4 py-2 bg-blue-600 text-white rounded-lg">
                                <i data-lucide="search" class="h-4 w-4"></i>
                            </button>
                        </div>
                        
                        <div class="flex gap-2 items-center">
                            <label class="text-sm text-gray-600">Group by:</label>
                            <select id="groupBySelect" class="px-3 py-1 border border-gray-300 rounded">
                                <option value="date">Date</option>
                                <option value="week">Week</option>
                                <option value="month">Month</option>
                                <option value="tag">Tag</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="space-y-4">
                        <div id="memoriesList"></div>
                    </div>
                    
                    <div id="listStatus" class="text-sm mt-4"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal for API Key -->
    <div id="apiKeyModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4">
            <h3 class="text-xl font-semibold mb-4">Enter SuperMemory API Key</h3>
            <input 
                type="password" 
                id="apiKeyInput" 
                class="w-full px-3 py-2 border border-gray-300 rounded-lg mb-4"
                placeholder="Your API key..."
            >
            <div class="flex gap-2">
                <button onclick="saveAPIKey()" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-2 rounded">Save</button>
                <button onclick="closeModal()" class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-800 py-2 rounded">Cancel</button>
            </div>
        </div> 
    </div>

    <!-- Edit Memory Modal -->
    <div id="editModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-white rounded-xl p-6 max-w-2xl w-full mx-4">
            <h3 class="text-xl font-semibold mb-4">Edit Memory</h3>
            <textarea 
                id="editContent" 
                rows="6" 
                class="w-full px-3 py-2 border border-gray-300 rounded-lg mb-4"
            ></textarea>
            <input type="hidden" id="editId">
            <div class="flex gap-2">
                <button onclick="saveEdit()" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-2 rounded">Save</button>
                <button onclick="closeEditModal()" class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-800 py-2 rounded">Cancel</button>
            </div>
        </div>
    </div>

    <script>
        // Configuration
        const CONFIG = {
            API_BASE: 'https://v2.api.supermemory.ai',
            CORS_PROXY: 'https://cors.trigox.workers.dev?url=',
            get BASE_URL() {
                return `${this.CORS_PROXY}${encodeURIComponent(this.API_BASE)}`;
            }
        };

        // Global state
        let currentMemories = [];
        let currentFilters = {};
        let currentPage = 1;
        const ITEMS_PER_PAGE = 20;

        // Initialize Lucide icons
        lucide.createIcons();

        // CRUD Operations Implementation
        class MemoryManager {
            constructor() {
                this.apiKey = localStorage.getItem('sm_api_key');
            }

            async createMemory(content, metadata = {}) {
                if (!this.apiKey) throw new Error('API key required');
                
                const response = await fetch(`${CONFIG.CORS_PROXY}${encodeURIComponent(CONFIG.API_BASE)}/add`, {
                    method: 'POST',
                    headers: {
                        'x-api-key': this.apiKey,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ content, metadata })
                });
                
                return response.json();
            }

            async readMemory(id) {
                if (!this.apiKey) throw new Error('API key required');
                
                const response = await fetch(`${CONFIG.CORS_PROXY}${encodeURIComponent(CONFIG.API_BASE)}/memories/${id}`, {
                    headers: { 'x-api-key': this.apiKey }
                });
                
                return response.json();
            }

            async updateMemory(id, content, metadata = {}) {
                if (!this.apiKey) throw new Error('API key required');
                
                const response = await fetch(`${CONFIG.CORS_PROXY}${encodeURIComponent(CONFIG.API_BASE)}/memories/${id}`, {
                    method: 'PUT',
                    headers: {
                        'x-api-key': this.apiKey,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ content, metadata })
                });
                
                return response.json();
            }

            async deleteMemory(id) {
                if (!this.apiKey) throw new Error('API key required');
                
                const response = await fetch(`${CONFIG.CORS_PROXY}${encodeURIComponent(CONFIG.API_BASE)}/memories/${id}`, {
                    method: 'DELETE',
                    headers: { 'x-api-key': this.apiKey }
                });
                
                return response.json();
            }

            async listMemories(limit = 20, offset = 0) {
                if (!this.apiKey) throw new Error('API key required');
                
                const response = await fetch(`${CONFIG.CORS_PROXY}${encodeURIComponent(CONFIG.API_BASE)}/memories/list`, {
                    method: 'POST',
                    headers: {
                        'x-api-key': this.apiKey,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ limit, offset })
                });
                
                const data = await response.json();
                return data.memories || [];
            }

            async searchMemories(query, filters = {}, limit = 10) {
                if (!this.apiKey) throw new Error('API key required');
                
                const response = await fetch(`${CONFIG.CORS_PROXY}${encodeURIComponent(CONFIG.API_BASE)}/search`, {
                    method: 'POST',
                    headers: {
                        'x-api-key': this.apiKey,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ q: query, limit, filters })
                });
                
                const data = await response.json();
                return data.results || [];
            }

            async groupMemories(groupBy = 'date') {
                if (!currentMemories.length) return {};
                
                const groups = {};
                
                currentMemories.forEach(memory => {
                    let key;
                    switch(groupBy) {
                        case 'date':
                            key = new Date(memory.createdAt).toDateString();
                            break;
                        case 'week':
                            const weekStart = new Date(memory.createdAt);
                            weekStart.setDate(weekStart.getDate() - weekStart.getDay());
                            key = weekStart.toDateString();
                            break;
                        case 'month':
                            key = new Date(memory.createdAt).toLocaleDateString('en-US', { year: 'numeric', month: 'long' });
                            break;
                        case 'tag':
                            key = memory.metadata?.tag || 'untagged';
                            break;
                        default:
                            key = 'ungrouped';
                    }
                    
                    if (!groups[key]) groups[key] = [];
                    groups[key].push(memory);
                });
                
                return groups;
            }

            async getRelatedMemories(memoryId) {
                const memory = await this.readMemory(memoryId);
                if (!memory?.content) return [];
                
                const related = await this.searchMemories(memory.content, {}, 10);
                return related.filter(m => m.id !== memoryId);
            }

            async bulkDelete(memoryIds) {
                const results = await Promise.all(
                    memoryIds.map(id => this.deleteMemory(id).catch(e => ({ error: e.message, id })))
                );
                return results;
            }

            async exportMemories(format = 'json') {
                const memories = await this.listMemories(1000);
                
                switch(format) {
                    case 'json':
                        return JSON.stringify(memories, null, 2);
                    case 'csv':
                        const csv = memories.map(m => 
                            `"${m.id}","${m.content.replace(/"/g, '""')}","${m.createdAt}"`
                        ).join('\n');
                        return 'id,content,createdAt\n' + csv;
                    default:
                        return memories;
                }
            }

            async importMemories(memories) {
                const results = await Promise.all(
                    memories.map(memory => this.createMemory(memory.content, memory.metadata))
                );
                return results;
            }

            async getStats() {
                const memories = await this.listMemories(1000);
                return {
                    total: memories.length,
                    oldest: memories[memories.length - 1],
                    newest: memories[0],
                    averageLength: memories.reduce((sum, m) => sum + (m.content?.length || 0), 0) / memories.length
                };
            }
        }

        const memoryManager = new MemoryManager();

        // Main functions
        async function addMemory() {
            const content = document.getElementById('content').value;
            const metadata = collectMetadata();
            const statusDiv = document.getElementById('addStatus');

            if (!content.trim()) {
                showStatus(statusDiv, 'Please enter some content', 'error');
                return;
            }

            try {
                const button = event.target;
                button.disabled = true;
                button.innerHTML = '<i data-lucide="loader" class="mr-2 animate-spin"></i>Adding...';
                
                await memoryManager.createMemory(content, metadata);
                showStatus(statusDiv, 'Memory added successfully!', 'success');
                document.getElementById('content').value = '';
                listMemories();
            } catch (error) {
                console.error('Error adding memory:', error);
                showStatus(statusDiv, `Error: ${error.message}`, 'error');
            } finally {
                const button = event.target;
                button.disabled = false;
                button.innerHTML = '<i data-lucide="save" class="mr-2"></i>Add Memory';
                lucide.createIcons();
            }
        }

        async function listMemories(page = 1) {
            const listDiv = document.getElementById('memoriesList');
            const apiKey = localStorage.getItem('sm_api_key');

            if (!apiKey) {
                updateAPIKey();
                return;
            }

            showLoading(listDiv);
            
            try {
                memoryManager.apiKey = apiKey;
                const offset = (page - 1) * ITEMS_PER_PAGE;
                const memories = await memoryManager.listMemories(ITEMS_PER_PAGE, offset);
                currentMemories = memories;
                displayMemories(memories);
                currentPage = page;
            } catch (error) {
                console.error('Error loading memories:', error);
                listDiv.innerHTML = `<p class="text-red-500">Error: ${error.message}</p>`;
            }
        }

        async function searchMemories() {
            const query = document.getElementById('searchQuery').value;
            const listDiv = document.getElementById('memoriesList');
            
            if (!query.trim()) {
                listMemories();
                return;
            }

            showLoading(listDiv);
            
            try {
                const results = await memoryManager.searchMemories(query, currentFilters);
                currentMemories = results;
                displayMemories(results);
            } catch (error) {
                console.error('Error searching:', error);
                listDiv.innerHTML = `<p class="text-red-500">Search error: ${error.message}</p>`;
            }
        }

        async function groupMemories() {
            const groupBy = document.getElementById('groupBySelect').value;
            const groups = await memoryManager.groupMemories(groupBy);
            displayGroupedMemories(groups);
        }

        async function deleteMemory(id) {
            if (!confirm('Are you sure you want to delete this memory?')) return;
            
            try {
                await memoryManager.deleteMemory(id);
                showStatus(document.getElementById('listStatus'), 'Memory deleted', 'success');
                listMemories();
            } catch (error) {
                showStatus(document.getElementById('listStatus'), `Delete error: ${error.message}`, 'error');
            }
        }

        async function editMemory(id) {
            const memory = await memoryManager.readMemory(id);
            if (!memory) return;

            document.getElementById('editModal').classList.remove('hidden');
            document.getElementById('editContent').value = memory.content || '';
            document.getElementById('editId').value = id;
        }

        async function saveEdit() {
            const id = document.getElementById('editId').value;
            const content = document.getElementById('editContent').value;
            
            try {
                await memoryManager.updateMemory(id, content);
                closeEditModal();
                listMemories();
            } catch (error) {
                alert(`Edit error: ${error.message}`);
            }
        }

        function closeEditModal() {
            document.getElementById('editModal').classList.add('hidden');
        }

        function displayMemories(memories) {
            const listDiv = document.getElementById('memoriesList');
            
            if (memories.length === 0) {
                listDiv.innerHTML = `
                    <div class="text-center py-8">
                        <i data-lucide="inbox" class="mx-auto h-12 w-12 text-gray-400 mb-3"></i>
                        <p class="text-gray-500">No memories found</p>
                        <p class="text-sm text-gray-400 mt-1">Try adjusting your search or filters</p>
                    </div>
                `;
                lucide.createIcons();
                return;
            }

            listDiv.innerHTML = `
                <div class="space-y-4">
                    ${memories.map(memory => `
                        <div class="memory-card bg-white rounded-lg p-5">
                            <div class="flex justify-between items-start mb-3">
                                <div>
                                    <span class="text-xs text-gray-500">${new Date(memory.createdAt).toLocaleString()}</span>
                                    ${memory.metadata?.tag ? `<span class="ml-2 px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded">${memory.metadata.tag}</span>` : ''}
                                </div>
                                <div class="flex gap-2">
                                    <button onclick="editMemory('${memory.id}')" class="text-blue-600 hover:text-blue-800">
                                        <i data-lucide="edit-3" class="h-4 w-4"></i>
                                    </button>
                                    <button onclick="deleteMemory('${memory.id}')" class="text-red-600 hover:text-red-800">
                                        <i data-lucide="trash-2" class="h-4 w-4"></i>
                                    </button>
                                </div>
                            </div>
                            <p class="text-gray-800 leading-relaxed">${memory.content || 'No content'}</p>
                            ${memory.metadata?.source ? `<p class="text-xs text-gray-500 mt-2">Source: ${memory.metadata.source}</p>` : ''}
                        </div>
                    `).join('')}
                </div>
                <div class="mt-6 flex justify-between items-center">
                    <button onclick="listMemories(${currentPage - 1})" ${currentPage <= 1 ? 'disabled' : ''} 
                            class="px-4 py-2 bg-gray-200 rounded disabled:opacity-50">
                        Previous
                    </button>
                    <span class="text-gray-600">Page ${currentPage}</span>
                    <button onclick="listMemories(${currentPage + 1})" 
                            class="px-4 py-2 bg-gray-200 rounded">
                        Next
                    </button>
                </div>
            `;
            lucide.createIcons();
        }

        function displayGroupedMemories(groups) {
            const listDiv = document.getElementById('memoriesList');
            let html = '<div class="space-y-6">';
            
            Object.entries(groups).forEach(([group, memories]) => {
                html += `
                    <div class="border rounded-lg p-4">
                        <h4 class="font-semibold text-lg mb-3">${group} (${memories.length})</h4>
                    </div>
                `;
            });
            
            html += '</div>';
            listDiv.innerHTML = html;
        }

        function collectMetadata() {
            const metadata = {};
            const tag = document.getElementById('memoryTag').value;
            const source = document.getElementById('memorySource').value;
            
            if (tag) metadata.tag = tag;
            if (source) metadata.source = source;
            
            return metadata;
        }

        function showStatus(element, message, type) {
            element.innerHTML = `<p class="${type === 'error' ? 'text-red-600' : 'text-green-600'}">${message}</p>`;
            setTimeout(() => element.innerHTML = '', 3000);
        }

        function showLoading(element) {
            element.innerHTML = `
                <div class="space-y-3">
                    ${Array(3).fill(0).map(() => `
                        <div class="memory-card bg-white rounded-lg p-5">
                            <div class="loading-shimmer h-4 w-1/3 rounded mb-3"></div>
                            <div class="loading-shimmer h-4 w-full rounded mb-2"></div>
                            <div class="loading-shimmer h-4 w-3/4 rounded"></div>
                        </div>
                    `).join('')}
                </div>
            `;
        }

        function updateAPIKey() {
            document.getElementById('apiKeyModal').classList.remove('hidden');
            document.getElementById('apiKeyInput').value = localStorage.getItem('sm_api_key') || '';
        }

        function saveAPIKey() {
            const key = document.getElementById('apiKeyInput').value.trim();
            if (key) {
                localStorage.setItem('sm_api_key', key);
                memoryManager.apiKey = key;
                closeModal();
                listMemories();
            }
        }

        function closeModal() {
            document.getElementById('apiKeyModal').classList.add('hidden');
        }

        async function exportMemories() {
            try {
                const data = await memoryManager.exportMemories('json');
                const blob = new Blob([data], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'memories.json';
                a.click();
            } catch (error) {
                alert(`Export error: ${error.message}`);
            }
        }

        async function importMemories() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.json';
            input.onchange = async (e) => {
                const file = e.target.files[0];
                if (!file) return;
                
                try {
                    const text = await file.text();
                    const memories = JSON.parse(text);
                    await memoryManager.importMemories(memories);
                    listMemories();
                } catch (error) {
                    alert(`Import error: ${error.message}`);
                }
            };
            input.click();
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', () => {
            if (!localStorage.getItem('sm_api_key')) {
                setTimeout(updateAPIKey, 500);
            } else {
                memoryManager.apiKey = localStorage.getItem('sm_api_key');
                listMemories();
            }
        });
    </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=samihalawa/supermemory" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>