File size: 24,107 Bytes
d7318a6
fef03db
d7318a6
fef03db
 
 
 
 
 
5b6c2a2
fef03db
 
 
 
 
 
5b6c2a2
fef03db
d7318a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fef03db
 
d7318a6
 
 
fef03db
 
 
 
 
 
 
 
 
 
d7318a6
 
985683f
 
d7318a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fef03db
 
d7318a6
 
 
 
 
 
 
fef03db
 
d7318a6
 
 
fef03db
d7318a6
 
 
 
 
 
 
 
 
 
 
 
 
 
fef03db
 
 
 
 
 
 
 
 
 
 
5b6c2a2
 
fef03db
 
 
 
 
 
 
 
 
 
 
 
 
d7318a6
fef03db
 
 
d7318a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fef03db
 
d7318a6
 
 
fef03db
 
 
 
 
 
 
4f2b55e
 
 
fef03db
d7318a6
 
 
fef03db
 
 
d7318a6
 
4f2b55e
 
 
 
 
d7318a6
 
 
 
 
 
 
 
4f2b55e
d7318a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fef03db
 
 
 
 
0724296
5b6c2a2
0724296
5b6c2a2
0724296
d7318a6
5b6c2a2
fef03db
 
 
 
 
 
 
 
 
d7318a6
 
 
 
fef03db
d7318a6
0724296
fef03db
 
 
d7318a6
fef03db
 
d7318a6
fef03db
 
 
 
 
 
 
d7318a6
fef03db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7318a6
fef03db
 
 
 
 
 
 
5b6c2a2
 
 
fef03db
d7318a6
fef03db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7318a6
 
0724296
 
 
 
 
d7318a6
 
 
0724296
d7318a6
0724296
 
d7318a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0724296
 
d7318a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// ----------------------------
// Sample Email Data
// ----------------------------
const emails = [
    {
        id: 1,
        sender: "Interview Kicks",
        subject: "Can I Become an ML Engineer? Why Not, We Ask!",
        snippet: "It's time to banish that doubt forever. Attend our masterclass to unlock your potential.",
        timestamp: "1:31 PM"
    },
    {
        id: 2,
        sender: "Career Brew",
        subject: "7th Sep Jobs, 87 Hottest Jobs and Early Career Jobs - Do Not Miss",
        snippet: "Top companies are hiring right now β€” don't miss your shot at these exclusive opportunities!",
        timestamp: "12:35 PM"
    },
    {
        id: 3,
        sender: "Professor Smith",
        subject: "Research Collaboration Proposal",
        snippet: "I've reviewed your proposal draft. Let's schedule a call next week to discuss next steps.",
        timestamp: "10:22 AM"
    },
    {
        id: 4,
        sender: "Friend",
        subject: "Weekend Plans",
        snippet: "Are we still on for the hiking trip this weekend? Let me know so I can book the gear.",
        timestamp: "Yesterday"
    },
    {
        id: 5,
        sender: "Bank Support",
        subject: "Monthly Statement",
        snippet: "Your statement is ready. Minimum due: $120. Avoid penalties by paying before the 15th.",
        timestamp: "Sep 5"
    },
    {
        id: 6,
        sender: "Netflix",
        subject: "New Releases This Week!",
        snippet: "Check out the hottest new shows and movies added to your watchlist this week.",
        timestamp: "Sep 4"
    },
    {
        id: 7,
        sender: "Amazon",
        subject: "Your Order #12345 Has Shipped",
        snippet: "Your package is on the way! Track your delivery using the link below.",
        timestamp: "Sep 3"
    },
    {
        id: 8,
        sender: "LinkedIn",
        subject: "You have 5 new notifications",
        snippet: "See who viewed your profile and new job recommendations.",
        timestamp: "Sep 2"
    },
    {
        id: 9,
        sender: "Microsoft",
        subject: "Your Office 365 Subscription Renewal",
        snippet: "Your Office 365 subscription will expire in 7 days. Renew now to avoid service interruption.",
        timestamp: "Sep 1"
    },
    {
        id: 10,
        sender: "TripAdvisor",
        subject: "Your upcoming trip to Paris",
        snippet: "Don't forget to check-in for your flight tomorrow. Here's your itinerary and hotel information.",
        timestamp: "Aug 30"
    }
];

// ----------------------------
// Debug Utilities
// ----------------------------
class DebugManager {
    constructor() {
        this.statusEl = document.getElementById('debugStatus');
        this.selectedEmailEl = document.getElementById('debugSelectedEmail');
        this.gestureTypeEl = document.getElementById('debugGestureType');
        this.bufferCountEl = document.getElementById('debugBufferCount');
        this.circleCountEl = document.getElementById('debugCircleCount');
        this.cameraStatusEl = document.getElementById('debugCameraStatus');
        this.lastErrorEl = document.getElementById('debugLastError');
        this.statusIndicator = document.getElementById('statusIndicator');
        
        // Get debug toggle button
        this.toggleButton = document.getElementById('debugToggle');
        this.debugPanel = document.getElementById('debugPanel');
        
        // Add click event listener
        this.toggleButton.addEventListener('click', () => {
            this.toggleDebugPanel();
        });
    }
    
    updateStatus(status) {
        this.statusEl.textContent = status;
    }
    
    updateSelectedEmail(emailId) {
        if (emailId) {
            const email = emails.find(e => e.id === emailId);
            this.selectedEmailEl.textContent = email ? email.subject.substring(0, 20) + '...' : 'Unknown';
        } else {
            this.selectedEmailEl.textContent = 'None';
        }
    }
    
    updateGestureType(gestureType) {
        this.gestureTypeEl.textContent = gestureType;
    }
    
    updateBufferCount(count) {
        this.bufferCountEl.textContent = `${count} points`;
    }
    
    updateCircleCount(count) {
        this.circleCountEl.textContent = `${count} points`;
    }
    
    updateCameraStatus(status) {
        this.cameraStatusEl.textContent = status;
    }
    
    logError(error) {
        console.error("Gesture Detection Error:", error);
        this.lastErrorEl.textContent = error.message.substring(0, 50) + (error.message.length > 50 ? '...' : '');
        
        // Update status indicator to red
        this.statusIndicator.className = 'status-indicator error';
    }
    
    setReady() {
        this.updateStatus('Ready');
        this.statusIndicator.className = 'status-indicator ready';
    }
    
    setProcessing() {
        this.updateStatus('Processing...');
        this.statusIndicator.className = 'status-indicator processing';
    }
    
    toggleDebugPanel() {
        if (this.debugPanel.classList.contains('visible')) {
            this.debugPanel.classList.remove('visible');
        } else {
            this.debugPanel.classList.add('visible');
        }
    }
}

// ----------------------------
// UI Management
// ----------------------------
class UIManager {
    constructor() {
        this.emailList = document.getElementById('emailList');
        this.actionFeedback = document.getElementById('actionFeedback');
        this.selectionHighlight = document.getElementById('selectionHighlight');
        this.handLandmarks = document.getElementById('handLandmarks');
        this.gesturePath = document.getElementById('gesturePath');
        
        this.selectedEmail = null;
        this.emailElements = [];
        
        this.renderEmails();
        this.setupEventListeners();
    }
    
    renderEmails() {
        this.emailList.innerHTML = '';
        this.emailElements = [];
        
        emails.forEach(email => {
            const emailElement = document.createElement('div');
            emailElement.className = 'email-item';
            emailElement.dataset.id = email.id;
            
            emailElement.innerHTML = `
                <div class="email-header">
                    <div class="email-sender">${email.sender}</div>
                    <div class="email-time">${email.timestamp}</div>
                </div>
                <div class="email-subject">${email.subject}</div>
                <div class="email-snippet">${email.snippet}</div>
            `;
            
            this.emailList.appendChild(emailElement);
            this.emailElements.push({
                id: email.id,
                element: emailElement,
                rect: null
            });
        });
        
        // Update email positions
        this.updateEmailPositions();
    }
    
    updateEmailPositions() {
        this.emailElements.forEach(item => {
            const rect = item.element.getBoundingClientRect();
            item.rect = {
                left: rect.left,
                top: rect.top,
                right: rect.right,
                bottom: rect.bottom,
                width: rect.width,
                height: rect.height
            };
        });
    }
    
    selectEmail(emailId) {
        // Remove previous selection
        if (this.selectedEmail) {
            const prevElement = this.emailElements.find(e => e.id === this.selectedEmail);
            if (prevElement) {
                prevElement.element.classList.remove('selected');
            }
        }
        
        // Set new selection
        this.selectedEmail = emailId;
        const newElement = this.emailElements.find(e => e.id === emailId);
        
        if (newElement) {
            newElement.element.classList.add('selected');
            this.showSelectionHighlight(newElement.rect);
        }
        
        return newElement ? newElement.rect : null;
    }
    
    showSelectionHighlight(rect) {
        this.selectionHighlight.style.display = 'block';
        this.selectionHighlight.style.left = `${rect.left}px`;
        this.selectionHighlight.style.top = `${rect.top}px`;
        this.selectionHighlight.style.width = `${rect.width}px`;
        this.selectionHighlight.style.height = `${rect.height}px`;
    }
    
    hideSelectionHighlight() {
        this.selectionHighlight.style.display = 'none';
    }
    
    showActionFeedback(message, type) {
        this.actionFeedback.textContent = message;
        this.actionFeedback.className = 'action-feedback';
        
        if (type === 'delete') {
            this.actionFeedback.classList.add('delete');
        } else if (type === 'archive') {
            this.actionFeedback.classList.add('archive');
        } else {
            this.actionFeedback.classList.add('summary');
        }
        
        this.actionFeedback.classList.add('show');
        
        setTimeout(() => {
            this.actionFeedback.classList.remove('show');
        }, 2000);
    }
    
    clearSelection() {
        if (this.selectedEmail) {
            const element = this.emailElements.find(e => e.id === this.selectedEmail);
            if (element) {
                element.element.classList.remove('selected');
            }
            this.selectedEmail = null;
            this.hideSelectionHighlight();
        }
    }
    
    setupEventListeners() {
        window.addEventListener('resize', () => {
            this.updateEmailPositions();
            if (this.selectedEmail) {
                const element = this.emailElements.find(e => e.id === this.selectedEmail);
                if (element) {
                    this.showSelectionHighlight(element.rect);
                }
            }
        });
    }
    
    // For gesture visualization
    updateHandLandmarks(landmarks) {
        this.handLandmarks.innerHTML = '';
        
        if (!landmarks || landmarks.length === 0) return;
        
        landmarks.forEach((landmark, i) => {
            const landmarkEl = document.createElement('div');
            landmarkEl.className = 'landmark';
            if (i === 8) { // Index finger tip
                landmarkEl.classList.add('index-tip');
            }
            
            landmarkEl.style.left = `${landmark.x * 100}%`;
            landmarkEl.style.top = `${landmark.y * 100}%`;
            
            this.handLandmarks.appendChild(landmarkEl);
        });
    }
    
    updateGesturePath(points) {
        this.gesturePath.innerHTML = '';
        
        if (!points || points.length === 0) return;
        
        points.forEach(point => {
            const pointEl = document.createElement('div');
            pointEl.className = 'point';
            pointEl.style.left = `${point.x * 100}%`;
            pointEl.style.top = `${point.y * 100}%`;
            this.gesturePath.appendChild(pointEl);
        });
    }
}

// ----------------------------
// Gesture Detection
// ----------------------------
class GestureDetector {
    constructor(uiManager, debugManager) {
        this.uiManager = uiManager;
        this.debugManager = debugManager;
        this.selectedEmailId = null;
        this.gestureBuffer = [];
        this.circlePoints = [];
        this.circleThreshold = 8;
        this.swipeThreshold = 30;
        this.gestureCooldown = 1500;
        this.lastGestureTime = 0;
        this.camera = null;
        
        this.debugManager.updateStatus('Setting up MediaPipe...');
        this.setupMediaPipe();
    }
    
    setupMediaPipe() {
        try {
            const hands = new Hands({
                locateFile: (file) => {
                    return `https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/${file}`;
                }
            });
            
            hands.setOptions({
                maxNumHands: 1,
                modelComplexity: 1,
                minDetectionConfidence: 0.7,
                minTrackingConfidence: 0.7
            });
            
            hands.onResults((results) => {
                this.processResults(results);
            });
            
            const videoElement = document.getElementById('webcam');
            
            // Check if Camera is available
            if (typeof Camera === 'undefined') {
                this.debugManager.logError(new Error("Camera utils not loaded. Make sure camera_utils.js is included."));
                return;
            }
            
            this.camera = new Camera(videoElement, {
                onFrame: async () => {
                    try {
                        this.debugManager.setProcessing();
                        await hands.send({image: videoElement});
                    } catch (error) {
                        this.debugManager.logError(error);
                    }
                },
                width: 320,
                height: 240
            });
            
            this.startCamera();
        } catch (error) {
            this.debugManager.logError(error);
            console.error("MediaPipe setup error:", error);
        }
    }
    
    async startCamera() {
        try {
            this.debugManager.updateCameraStatus('Starting...');
            await this.camera.start();
            this.debugManager.updateCameraStatus('Active');
            this.debugManager.setReady();
            console.log("Camera initialized successfully");
        } catch (error) {
            this.debugManager.updateCameraStatus('Error');
            this.debugManager.logError(error);
            
            // Try to get more specific error information
            if (error.name === 'NotAllowedError') {
                alert("Camera access denied. Please allow camera access in your browser settings.");
            } else if (error.name === 'NotFoundError') {
                alert("No camera found. Please connect a camera device.");
            } else {
                alert("Failed to start camera: " + error.message);
            }
        }
    }
    
    processResults(results) {
        try {
            // Update hand landmarks visualization
            if (results.multiHandLandmarks && results.multiHandLandmarks.length > 0) {
                this.uiManager.updateHandLandmarks(results.multiHandLandmarks[0]);
                
                // Update gesture path for debugging
                if (this.gestureBuffer.length > 0) {
                    this.uiManager.updateGesturePath(this.gestureBuffer);
                }
                
                this.detectGesture(results.multiHandLandmarks[0]);
            } else {
                this.uiManager.clearSelection();
                this.gestureBuffer = [];
                this.circlePoints = [];
                this.debugManager.updateGestureType('None');
                this.debugManager.updateBufferCount(0);
                this.debugManager.updateCircleCount(0);
            }
        } catch (error) {
            this.debugManager.logError(error);
        }
    }
    
    detectGesture(landmarks) {
        try {
            const indexTip = landmarks[8];
            const middleTip = landmarks[12];
            
            // πŸ”₯ CRITICAL FIX: Account for 60px header height!
            const screenX = indexTip.x * window.innerWidth;
            const screenY = (1 - indexTip.y) * (window.innerHeight - 60); // Subtract header height
            
            // Pointing detection (index finger higher than middle)
            if (indexTip.y < middleTip.y) {
                this.checkEmailSelection(screenX, screenY);
            } else {
                this.uiManager.clearSelection();
                this.gestureBuffer = [];
                this.circlePoints = [];
                this.debugManager.updateGestureType('None');
                this.debugManager.updateBufferCount(0);
                this.debugManager.updateCircleCount(0);
            }
            
            // Only process gestures if an email is selected
            if (this.selectedEmailId === null) {
                return;
            }
            
            // Get palm center for gesture detection
            const wrist = landmarks[0];
            const palmCenterX = (wrist.x + landmarks[9].x) / 2;
            const palmCenterY = (wrist.y + landmarks[9].y) / 2;
            
            // Add to gesture buffer
            this.gestureBuffer.push({x: palmCenterX, y: palmCenterY});
            
            // Check for swipe
            if (this.gestureBuffer.length > 2) {
                const prev = this.gestureBuffer[this.gestureBuffer.length - 2];
                const current = this.gestureBuffer[this.gestureBuffer.length - 1];
                
                const dx = (current.x - prev.x) * window.innerWidth;
                const dy = (current.y - prev.y) * window.innerHeight;
                
                // Check if it's a horizontal swipe
                if (Math.abs(dx) > this.swipeThreshold && Math.abs(dx) > Math.abs(dy) * 2) {
                    if (Date.now() - this.lastGestureTime > this.gestureCooldown) {
                        this.lastGestureTime = Date.now();
                        
                        if (dx > 0) {
                            this.debugManager.updateGestureType('Swipe Right');
                            this.handleGesture('swipe_right');
                        } else {
                            this.debugManager.updateGestureType('Swipe Left');
                            this.handleGesture('swipe_left');
                        }
                        
                        this.gestureBuffer = [];
                        this.debugManager.updateBufferCount(0);
                    }
                }
            }
            
            // Check for circle
            this.circlePoints.push({x: palmCenterX, y: palmCenterY});
            this.debugManager.updateCircleCount(this.circlePoints.length);
            
            if (this.circlePoints.length > this.circleThreshold) {
                const startPoint = this.circlePoints[0];
                const endPoint = this.circlePoints[this.circlePoints.length - 1];
                
                const dx = endPoint.x - startPoint.x;
                const dy = endPoint.y - startPoint.y;
                const distance = Math.sqrt(dx*dx + dy*dy) * window.innerWidth;
                
                // Fix: Better circle detection with radius check
                if (distance < 40 && Date.now() - this.lastGestureTime > this.gestureCooldown) {
                    this.lastGestureTime = Date.now();
                    this.debugManager.updateGestureType('Circle');
                    this.handleGesture('circle');
                    this.circlePoints = [];
                    this.debugManager.updateCircleCount(0);
                }
            }
            
            this.debugManager.updateBufferCount(this.gestureBuffer.length);
        } catch (error) {
            this.debugManager.logError(error);
        }
    }
    
    checkEmailSelection(x, y) {
        try {
            // Convert to page-relative coordinates (accounting for scroll)
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            const adjustedY = y + scrollTop;
            
            // Find the email under the finger
            for (let i = this.uiManager.emailElements.length - 1; i >= 0; i--) {
                const email = this.uiManager.emailElements[i];
                if (email.rect && 
                    x >= email.rect.left &&
                    x <= email.rect.right &&
                    adjustedY >= email.rect.top &&
                    adjustedY <= email.rect.bottom) {
                    
                    // Only select if it's a different email
                    if (this.selectedEmailId !== email.id) {
                        this.selectedEmailId = email.id;
                        this.uiManager.selectEmail(email.id);
                        this.debugManager.updateSelectedEmail(email.id);
                    }
                    return;
                }
            }
            
            // If no email is selected, clear selection
            if (!this.uiManager.emailElements.some(email => 
                email.rect && 
                x >= email.rect.left && 
                x <= email.rect.right &&
                adjustedY >= email.rect.top && 
                adjustedY <= email.rect.bottom)) {
                this.uiManager.clearSelection();
                this.selectedEmailId = null;
                this.debugManager.updateSelectedEmail(null);
            }
        } catch (error) {
            this.debugManager.logError(error);
        }
    }
    
    handleGesture(gesture) {
        try {
            if (!this.selectedEmailId) return;
            
            const email = emails.find(e => e.id === this.selectedEmailId);
            if (!email) return;
            
            switch (gesture) {
                case 'swipe_left':
                    this.uiManager.showActionFeedback(`πŸ—‘οΈ Deleted: ${email.subject}`, 'delete');
                    const index = emails.findIndex(e => e.id === this.selectedEmailId);
                    if (index !== -1) emails.splice(index, 1);
                    this.uiManager.renderEmails();
                    this.selectedEmailId = null;
                    this.debugManager.updateSelectedEmail(null);
                    break;
                    
                case 'swipe_right':
                    this.uiManager.showActionFeedback(`βœ… Archived: ${email.subject}`, 'archive');
                    const archiveIndex = emails.findIndex(e => e.id === this.selectedEmailId);
                    if (archiveIndex !== -1) emails.splice(archiveIndex, 1);
                    this.uiManager.renderEmails();
                    this.selectedEmailId = null;
                    this.debugManager.updateSelectedEmail(null);
                    break;
                    
                case 'circle':
                    const summary = `This email discusses ${email.subject.toLowerCase()}.`;
                    this.uiManager.showActionFeedback(`πŸ“ Summary: ${summary}`, 'summary');
                    break;
            }
        } catch (error) {
            this.debugManager.logError(error);
        }
    }
}

// ----------------------------
// Initialize App
// ----------------------------
document.addEventListener('DOMContentLoaded', () => {
    // Initialize debug manager first
    const debugManager = new DebugManager();
    debugManager.updateStatus('Initializing UI...');
    
    // Initialize UI
    const uiManager = new UIManager();
    debugManager.setReady();
    
    // Request camera access
    const videoElement = document.getElementById('webcam');
    
    navigator.mediaDevices.getUserMedia({ video: true })
        .then(stream => {
            videoElement.srcObject = stream;
            debugManager.updateCameraStatus('Initializing...');
            
            // Initialize gesture detection after a short delay to ensure UI is ready
            setTimeout(() => {
                debugManager.updateStatus('Setting up gesture detection...');
                try {
                    new GestureDetector(uiManager, debugManager);
                } catch (error) {
                    debugManager.logError(error);
                }
            }, 1500);
        })
        .catch(err => {
            debugManager.updateCameraStatus('Denied');
            debugManager.logError(err);
            console.error("Error accessing camera:", err);
            
            // More specific error handling
            if (err.name === 'NotAllowedError') {
                alert("Camera access denied. Please allow camera access in your browser settings.");
            } else if (err.name === 'NotFoundError') {
                alert("No camera found. Please connect a camera device.");
            } else {
                alert("Camera error: " + err.message);
            }
        });
});