File size: 24,899 Bytes
5e5a495
 
 
 
 
 
 
 
 
29aaf91
5e5a495
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29aaf91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e5a495
 
29aaf91
5e5a495
29aaf91
 
 
 
 
 
 
 
5e5a495
29aaf91
 
 
 
 
 
 
 
5e5a495
 
 
29aaf91
5e5a495
29aaf91
5e5a495
29aaf91
5e5a495
 
 
 
 
29aaf91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e5a495
29aaf91
 
 
 
 
 
 
5e5a495
 
29aaf91
 
 
 
 
 
 
 
 
 
5e5a495
 
 
29aaf91
 
 
 
 
5e5a495
29aaf91
5e5a495
29aaf91
5e5a495
 
29aaf91
5e5a495
 
 
 
 
 
 
 
 
 
29aaf91
 
9a64f23
5e5a495
 
29aaf91
 
 
 
 
5e5a495
 
 
29aaf91
5e5a495
 
29aaf91
 
 
5e5a495
 
 
 
 
29aaf91
 
 
 
 
 
 
 
 
5e5a495
29aaf91
 
 
5e5a495
 
29aaf91
 
 
 
 
 
 
 
 
5e5a495
 
29aaf91
 
5e5a495
 
 
 
 
29aaf91
5e5a495
 
 
 
 
 
 
 
 
 
 
 
 
29aaf91
5e5a495
 
 
 
 
 
 
 
 
 
 
 
 
5d22ea0
 
5e5a495
 
 
 
29aaf91
 
 
 
 
 
 
5e5a495
 
 
5d22ea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29aaf91
5e5a495
 
 
29aaf91
5e5a495
 
 
 
 
 
 
 
 
 
 
29aaf91
5e5a495
 
29aaf91
5e5a495
 
 
 
 
 
 
 
29aaf91
5e5a495
29aaf91
5e5a495
 
 
 
 
 
 
 
29aaf91
 
 
 
 
 
 
 
 
5e5a495
 
29aaf91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e5a495
29aaf91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e5a495
29aaf91
 
 
 
5e5a495
29aaf91
 
 
5e5a495
29aaf91
 
 
 
 
 
 
 
 
 
5e5a495
29aaf91
5e5a495
29aaf91
5e5a495
29aaf91
 
5e5a495
 
 
29aaf91
5e5a495
 
29aaf91
5e5a495
 
 
5d22ea0
 
29aaf91
5e5a495
 
 
 
29aaf91
5e5a495
 
 
 
 
5d22ea0
 
29aaf91
5e5a495
 
29aaf91
5e5a495
 
 
 
29aaf91
5e5a495
 
 
 
29aaf91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e5a495
 
 
29aaf91
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>just-mtg-scan - MTG Card Scanner</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #1e1b4b 0%, #0f172a 50%, #134e4a 100%);
        }
        
        .mtg-gradient {
            background: linear-gradient(135deg, #8b5cf6, #3b82f6, #10b981);
        }
        
        .card-shadow {
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.3), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        
        #fileInput {
            display: none;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .slide-in {
            animation: slideIn 0.5s ease-out;
        }
        
        #messageBox {
            transition: all 0.3s ease-in-out;
        }
        
        .scanning-line {
            position: absolute;
            width: 100%;
            height: 2px;
            background: linear-gradient(90deg, transparent, #10b981, transparent);
            animation: scan 2s linear infinite;
        }
        
        @keyframes scan {
            0% { top: 0%; }
            100% { top: 100%; }
        }
        
        .spinner {
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top: 3px solid white;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .card-item {
            transition: all 0.3s ease;
        }

        .card-item:hover {
            transform: translateX(4px);
        }

        .card-expanded {
            max-height: 2000px;
            transition: max-height 0.5s ease-in-out;
        }

        .card-collapsed {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease-in-out;
        }
    </style>
</head>
<body class="min-h-screen p-4">

    <div class="max-w-2xl mx-auto space-y-6">
        
        <!-- Header -->
        <div class="text-center space-y-2 slide-in">
            <div class="inline-flex items-center justify-center w-16 h-16 rounded-full mtg-gradient mb-2">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
                </svg>
            </div>
            <h1 class="text-4xl font-black bg-gradient-to-r from-violet-400 via-blue-400 to-emerald-400 bg-clip-text text-transparent">just-mtg-scan</h1>
            <p class="text-gray-400 text-sm">Instant MTG card recognition</p>
        </div>

        <!-- Scan Mode Toggle -->
        <div class="bg-gray-900 text-gray-100 rounded-2xl card-shadow p-6 border border-gray-800 slide-in">
            <div class="flex gap-3 mb-4">
                <button id="liveScanModeBtn" class="flex-1 bg-gradient-to-r from-violet-600 to-blue-600 text-white font-semibold py-3 px-4 rounded-xl shadow-lg transition-all duration-300 flex items-center justify-center space-x-2">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
                    </svg>
                    <span>Live Camera</span>
                </button>
                <button id="uploadModeBtn" class="flex-1 bg-gray-800 hover:bg-gray-700 text-white font-semibold py-3 px-4 rounded-xl shadow-lg transition-all duration-300 flex items-center justify-center space-x-2 border border-gray-700">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                    <span>Upload Photo</span>
                </button>
            </div>

            <!-- Live Camera Mode -->
            <div id="liveScanArea" class="space-y-4">
                <div class="relative w-full aspect-square bg-black rounded-2xl overflow-hidden shadow-2xl border border-gray-700">
                    <video id="videoFeed" class="w-full h-full object-cover" autoplay playsinline muted></video>
                    <div class="scanning-line"></div>
                    
                    <!-- Corner markers -->
                    <div class="absolute top-4 left-4 w-8 h-8 border-t-2 border-l-2 border-emerald-400"></div>
                    <div class="absolute top-4 right-4 w-8 h-8 border-t-2 border-r-2 border-emerald-400"></div>
                    <div class="absolute bottom-4 left-4 w-8 h-8 border-b-2 border-l-2 border-emerald-400"></div>
                    <div class="absolute bottom-4 right-4 w-8 h-8 border-b-2 border-r-2 border-emerald-400"></div>

                    <!-- Processing overlay -->
                    <div id="processingOverlay" class="hidden absolute inset-0 bg-black/70 flex items-center justify-center">
                        <div class="flex flex-col items-center space-y-3">
                            <div class="spinner"></div>
                            <p class="text-white text-sm">Processing...</p>
                        </div>
                    </div>
                </div>
                
                <button id="captureButton" class="w-full bg-gradient-to-r from-emerald-600 to-teal-600 text-white font-semibold py-4 px-6 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-0.5 flex items-center justify-center space-x-2">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                    <span>Scan Card</span>
                </button>
            </div>

            <!-- Upload Mode -->
            <div id="uploadArea" class="hidden">
                <label for="fileInput" class="w-full h-96 border-2 border-dashed border-gray-700 rounded-2xl flex flex-col items-center justify-center text-gray-400 hover:bg-gray-800/50 hover:border-violet-500 cursor-pointer transition-all duration-200 group">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-16 h-16 mb-4 group-hover:text-violet-400 transition-colors" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                    <span class="font-medium group-hover:text-violet-400 transition-colors text-lg">Click to upload</span>
                    <span class="text-sm mt-2">PNG, JPG, or WEBP</span>
                </label>
                <input type="file" id="fileInput" accept="image/png, image/jpeg, image/webp">
            </div>
        </div>

        <!-- Scanned Cards List -->
        <div id="cardsListContainer" class="bg-gray-900 text-gray-100 rounded-2xl card-shadow p-6 border border-gray-800 hidden">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-bold">Scanned Cards</h2>
                <button id="clearAllBtn" class="text-sm text-red-400 hover:text-red-300 font-medium transition-colors">Clear All</button>
            </div>
            <div id="cardsList" class="space-y-2"></div>
        </div>

    </div>

    <!-- Message Box -->
    <div id="messageBox" class="fixed top-5 right-5 bg-red-900/90 backdrop-blur text-white p-4 rounded-xl shadow-2xl z-50 opacity-0 transform translate-x-full pointer-events-none max-w-sm border border-red-700">
        <div class="flex items-start space-x-3">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span id="messageText" class="flex-1"></span>
            <button id="closeMessageButton" class="text-red-400 hover:text-red-300 font-bold"></button>
        </div>
    </div>

    <!-- Hidden canvases -->
    <canvas id="processingCanvas" class="hidden" width="256" height="256"></canvas>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // Elements
            const liveScanModeBtn = document.getElementById('liveScanModeBtn');
            const uploadModeBtn = document.getElementById('uploadModeBtn');
            const liveScanArea = document.getElementById('liveScanArea');
            const uploadArea = document.getElementById('uploadArea');
            const captureButton = document.getElementById('captureButton');
            const fileInput = document.getElementById('fileInput');
            const video = document.getElementById('videoFeed');
            const processingOverlay = document.getElementById('processingOverlay');
            const processingCanvas = document.getElementById('processingCanvas');
            const processingCtx = processingCanvas.getContext('2d');
            const cardsListContainer = document.getElementById('cardsListContainer');
            const cardsList = document.getElementById('cardsList');
            const clearAllBtn = document.getElementById('clearAllBtn');
            const messageBox = document.getElementById('messageBox');
            const messageText = document.getElementById('messageText');
            const closeMessageButton = document.getElementById('closeMessageButton');

            let currentStream = null;
            let scannedCards = [];
            const FINAL_SIZE = 256;

            // --- Mode Switching ---
            function switchToLiveMode() {
                liveScanModeBtn.classList.remove('bg-gray-800', 'hover:bg-gray-700', 'border', 'border-gray-700');
                liveScanModeBtn.classList.add('bg-gradient-to-r', 'from-violet-600', 'to-blue-600');
                uploadModeBtn.classList.remove('bg-gradient-to-r', 'from-violet-600', 'to-blue-600');
                uploadModeBtn.classList.add('bg-gray-800', 'hover:bg-gray-700', 'border', 'border-gray-700');
                
                liveScanArea.classList.remove('hidden');
                uploadArea.classList.add('hidden');
                startCamera();
            }

            function switchToUploadMode() {
                uploadModeBtn.classList.remove('bg-gray-800', 'hover:bg-gray-700', 'border', 'border-gray-700');
                uploadModeBtn.classList.add('bg-gradient-to-r', 'from-violet-600', 'to-blue-600');
                liveScanModeBtn.classList.remove('bg-gradient-to-r', 'from-violet-600', 'to-blue-600');
                liveScanModeBtn.classList.add('bg-gray-800', 'hover:bg-gray-700', 'border', 'border-gray-700');
                
                uploadArea.classList.remove('hidden');
                liveScanArea.classList.add('hidden');
                stopCamera();
            }

            liveScanModeBtn.addEventListener('click', switchToLiveMode);
            uploadModeBtn.addEventListener('click', switchToUploadMode);

            // --- Camera Logic ---
            async function startCamera() {
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({ 
                        video: { facingMode: 'environment' }
                    });
                    video.srcObject = stream;
                    currentStream = stream;
                    video.play();
                } catch (err) {
                    console.error("Error accessing camera:", err);
                    try {
                        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
                        video.srcObject = stream;
                        currentStream = stream;
                        video.play();
                    } catch (err2) {
                        console.error("Error accessing any camera:", err2);
                        showMessage('Unable to access camera. Please check permissions.');
                    }
                }
            }

            function stopCamera() {
                if (currentStream) {
                    currentStream.getTracks().forEach(track => track.stop());
                    currentStream = null;
                    video.srcObject = null;
                }
            }

            // --- Image Processing ---
            function processImageCenterCrop(source, sourceWidth, sourceHeight) {
                // Center crop to square for live camera
                const size = Math.min(sourceWidth, sourceHeight);
                const sx = (sourceWidth - size) / 2;
                const sy = (sourceHeight - size) / 2;

                processingCtx.clearRect(0, 0, FINAL_SIZE, FINAL_SIZE);
                processingCtx.drawImage(
                    source,
                    sx, sy,
                    size, size,
                    0, 0,
                    FINAL_SIZE, FINAL_SIZE
                );
            }

            function processImageResizePad(source, sourceWidth, sourceHeight) {
                // Resize longest dimension to 256 and zero-pad for uploads
                const scale = FINAL_SIZE / Math.max(sourceWidth, sourceHeight);
                const scaledWidth = sourceWidth * scale;
                const scaledHeight = sourceHeight * scale;
                
                // Calculate padding to center the image
                const offsetX = (FINAL_SIZE - scaledWidth) / 2;
                const offsetY = (FINAL_SIZE - scaledHeight) / 2;

                // Clear canvas (black background = zero padding)
                processingCtx.fillStyle = 'black';
                processingCtx.fillRect(0, 0, FINAL_SIZE, FINAL_SIZE);
                
                // Draw scaled image centered with padding
                processingCtx.drawImage(
                    source,
                    0, 0,
                    sourceWidth, sourceHeight,
                    offsetX, offsetY,
                    scaledWidth, scaledHeight
                );
            }

            // --- API Call ---
            async function callPredictAPI() {
                try {
                    const blob = await new Promise(resolve => {
                        processingCanvas.toBlob(resolve, 'image/png');
                    });
                    
                    const formData = new FormData();
                    formData.append('file', blob, 'image.png');
                    
                    const response = await fetch('/predict', {
                        method: 'POST',
                        body: formData
                    });
                    
                    if (!response.ok) {
                        throw new Error(`API error: ${response.status}`);
                    }
                    
                    return await response.json();
                    
                } catch (error) {
                    console.error('API Error:', error);
                    showMessage('Error calling prediction API: ' + error.message);
                    return null;
                }
            }

            // --- Card List Management ---
            function getRarityColor(rarity) {
                switch(rarity.toLowerCase()) {
                    case 'common': return 'bg-gray-600';
                    case 'uncommon': return 'bg-gray-500';
                    case 'rare': return 'bg-yellow-600';
                    case 'mythic': return 'bg-orange-600';
                    default: return 'bg-purple-600';
                }
            }

            function addCardToList(cardData) {
                scannedCards.unshift(cardData); // Add to beginning
                renderCardsList();
                cardsListContainer.classList.remove('hidden');
            }

            function renderCardsList() {
                if (scannedCards.length === 0) {
                    cardsListContainer.classList.add('hidden');
                    return;
                }

                cardsList.innerHTML = scannedCards.map((card, index) => `
                    <div class="card-item bg-gray-800/50 rounded-xl border border-gray-700 overflow-hidden">
                        <!-- Collapsed Header -->
                        <div class="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-800/70 transition-colors" onclick="toggleCard(${index})">
                            <div class="flex-1">
                                <div class="flex items-center gap-2">
                                    <h3 class="font-bold text-white">${card.name}</h3>
                                    <span class="${getRarityColor(card.rarity)} px-2 py-0.5 rounded text-xs font-bold uppercase text-white">${card.rarity}</span>
                                </div>
                                <p class="text-sm text-gray-400 mt-1">${card.set_name}${card.set.toUpperCase()}</p>
                                <p class="text-xs text-emerald-400 mt-1">⚡ Prediction time: ${card.prediction_time}ms</p>
                            </div>
                            <svg id="chevron-${index}" xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-gray-400 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                            </svg>
                        </div>

                        <!-- Expanded Content -->
                        <div id="card-details-${index}" class="card-collapsed">
                            <div class="p-4 pt-0 space-y-4">
                                <!-- Card Image -->
                                <div class="flex justify-center">
                                    <img data-src="${card.image_url}" alt="${card.name}" class="lazy-load rounded-lg shadow-xl max-w-full" style="max-height: 350px;">
                                </div>

                                <!-- Links -->
                                <div class="space-y-2">
                                    <a href="${card.scryfall_uri}" target="_blank" class="w-full bg-gradient-to-r from-orange-600 to-red-600 text-white font-semibold py-3 px-4 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-0.5 flex items-center justify-center space-x-2">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                                        </svg>
                                        <span>View on Scryfall</span>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                `).join('');
            }

            // Toggle card expansion
            window.toggleCard = function(index) {
                const detailsEl = document.getElementById(`card-details-${index}`);
                const chevronEl = document.getElementById(`chevron-${index}`);
                
                if (detailsEl.classList.contains('card-collapsed')) {
                    // Load image if not already loaded
                    const img = detailsEl.querySelector('img.lazy-load');
                    if (img && img.dataset.src && !img.src) {
                        img.src = img.dataset.src;
                        img.classList.remove('lazy-load');
                    }
                    
                    detailsEl.classList.remove('card-collapsed');
                    detailsEl.classList.add('card-expanded');
                    chevronEl.style.transform = 'rotate(180deg)';
                } else {
                    detailsEl.classList.remove('card-expanded');
                    detailsEl.classList.add('card-collapsed');
                    chevronEl.style.transform = 'rotate(0deg)';
                }
            };

            clearAllBtn.addEventListener('click', () => {
                scannedCards = [];
                renderCardsList();
            });

            // --- Process and Add Card ---
            async function processCaptureOrUpload() {
                processingOverlay.classList.remove('hidden');
                
                const result = await callPredictAPI();
                
                processingOverlay.classList.add('hidden');
                
                if (result) {
                    addCardToList(result);
                }
            }

            // --- Event Listeners ---
            captureButton.addEventListener('click', () => {
                if (!currentStream) {
                    showMessage('Camera not available');
                    return;
                }
                
                // Use center crop for live camera
                processImageCenterCrop(video, video.videoWidth, video.videoHeight);
                processCaptureOrUpload();
            });

            fileInput.addEventListener('change', (event) => {
                const file = event.target.files[0];
                if (!file) return;

                const reader = new FileReader();
                reader.onload = (e) => {
                    const img = new Image();
                    img.onload = () => {
                        // Use resize+pad for uploads
                        processImageResizePad(img, img.width, img.height);
                        processCaptureOrUpload();
                    };
                    img.onerror = () => {
                        showMessage('Failed to load image');
                    };
                    img.src = e.target.result;
                };
                reader.onerror = () => {
                    showMessage('Failed to read file');
                };
                reader.readAsDataURL(file);
            });

            // --- Error Messages ---
            function showMessage(message) {
                messageText.textContent = message;
                messageBox.classList.remove('opacity-0', 'translate-x-full', 'pointer-events-none');
                messageBox.classList.add('opacity-100', 'translate-x-0');
                setTimeout(hideMessage, 5000);
            }

            function hideMessage() {
                messageBox.classList.add('opacity-0', 'translate-x-full', 'pointer-events-none');
                messageBox.classList.remove('opacity-100', 'translate-x-0');
            }

            closeMessageButton.addEventListener('click', hideMessage);

            // --- Initialize ---
            switchToLiveMode();
        });
    </script>
</body>
</html>