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
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
document.addEventListener('DOMContentLoaded', () => {
    // DOM elements
    const imageUpload = document.getElementById('imageUpload');
    const preview = document.getElementById('preview');
    const scanCanvas = document.getElementById('scanCanvas');
    const status = document.getElementById('status');
    const result = document.getElementById('result');
    
    // Camera elements - will be created dynamically
    let videoElement;
    let cameraContainer;
    let cameraControls;
    let startCameraButton;
    let stopCameraButton;
    let switchCameraButton;
    let enhancementToggle;
    let debugModeToggle;
    let cameraStream = null;
    let activeCameraId = null;
    let availableCameras = [];
    let isScanning = false;
    let scanInterval = null;
    let useImageEnhancement = true; // Default to true
    let debugMode = false; // Default to false
    let focusModeActive = false;

    // Check if ZXing library is loaded
    if (typeof ZXing === 'undefined') {
        status.textContent = 'Error: ZXing library not loaded';
        result.textContent = 'Please check your internet connection and reload the page.';
        console.error('ZXing library not loaded');
        return;
    }

    // Initialize ZXing code reader and hints
    const codeReader = new ZXing.BrowserMultiFormatReader();
    const hints = new Map();
    const formats = [
        ZXing.BarcodeFormat.QR_CODE,
        ZXing.BarcodeFormat.DATA_MATRIX,
        ZXing.BarcodeFormat.AZTEC,
        ZXing.BarcodeFormat.PDF_417,
        ZXing.BarcodeFormat.EAN_13,
        ZXing.BarcodeFormat.EAN_8,
        ZXing.BarcodeFormat.UPC_A,
        ZXing.BarcodeFormat.UPC_E,
        ZXing.BarcodeFormat.CODE_128,
        ZXing.BarcodeFormat.CODE_39,
        ZXing.BarcodeFormat.CODE_93,
        ZXing.BarcodeFormat.ITF,
        ZXing.BarcodeFormat.CODABAR
    ];
    hints.set(ZXing.DecodeHintType.POSSIBLE_FORMATS, formats);
    hints.set(ZXing.DecodeHintType.TRY_HARDER, true);

    // Initialize the app
    function init() {
        status.textContent = 'Ready to scan barcodes. Upload an image or use camera.';
        createCameraElements();
        
        // Check if we're in a secure context (HTTPS or localhost)
        if (!isSecureContext()) {
            status.textContent = 'Camera access requires HTTPS. Current connection is not secure.';
            const warningDiv = document.createElement('div');
            warningDiv.className = 'security-warning';
            warningDiv.innerHTML = '<strong>Security Warning:</strong> Camera access requires a secure connection (HTTPS). ' +
                'You are currently on an insecure connection, which may prevent camera access. ' +
                'Please access this page via HTTPS or use localhost for testing.';
            document.querySelector('.container').insertBefore(warningDiv, document.querySelector('.upload-section'));
        }
        
        checkCameraSupport();
    }
    
    // Check if we're in a secure context (HTTPS or localhost)
    function isSecureContext() {
        // Check if the context is secure using the SecureContext API
        if (window.isSecureContext === true) {
            return true;
        }
        
        // Fallback check for older browsers
        return location.protocol === 'https:' || 
               location.hostname === 'localhost' || 
               location.hostname === '127.0.0.1';
    }

    // Create camera UI elements
    function createCameraElements() {
        // Create camera container
        cameraContainer = document.createElement('div');
        cameraContainer.id = 'camera-container';
        cameraContainer.className = 'camera-container';
        cameraContainer.style.display = 'none';
        
        // Create video element
        videoElement = document.createElement('video');
        videoElement.id = 'camera-feed';
        videoElement.autoplay = true;
        videoElement.playsInline = true;
        
        // Create camera controls
        cameraControls = document.createElement('div');
        cameraControls.className = 'camera-controls';
        
        // Create camera buttons
        startCameraButton = document.createElement('button');
        startCameraButton.id = 'start-camera';
        startCameraButton.textContent = 'Start Camera';
        startCameraButton.addEventListener('click', startCamera);
        
        stopCameraButton = document.createElement('button');
        stopCameraButton.id = 'stop-camera';
        stopCameraButton.textContent = 'Stop Camera';
        stopCameraButton.style.display = 'none';
        stopCameraButton.addEventListener('click', stopCamera);
        
        switchCameraButton = document.createElement('button');
        switchCameraButton.id = 'switch-camera';
        switchCameraButton.textContent = 'Switch Camera';
        switchCameraButton.style.display = 'none';
        switchCameraButton.addEventListener('click', switchCamera);
        
        // Create capture image button
        const captureImageButton = document.createElement('button');
        captureImageButton.id = 'capture-image';
        captureImageButton.textContent = 'Capture Image';
        captureImageButton.style.display = 'none';
        captureImageButton.addEventListener('click', captureImage);
        
        // Create focus mode button
        const focusModeButton = document.createElement('button');
        focusModeButton.id = 'focus-mode';
        focusModeButton.textContent = 'Focus Mode';
        focusModeButton.style.display = 'none';
        focusModeButton.addEventListener('click', toggleFocusMode);
        
        // Create retry button for permission issues
        const retryPermissionButton = document.createElement('button');
        retryPermissionButton.id = 'retry-permission';
        retryPermissionButton.textContent = 'Retry Camera Permission';
        retryPermissionButton.style.display = 'none';
        retryPermissionButton.addEventListener('click', () => {
            retryPermissionButton.style.display = 'none';
            status.textContent = 'Requesting camera permission...';
            checkCameraSupport();
        });
        
        // Create enhancement toggle
        const enhancementContainer = document.createElement('div');
        enhancementContainer.className = 'enhancement-toggle-container';
        
        enhancementToggle = document.createElement('input');
        enhancementToggle.type = 'checkbox';
        enhancementToggle.id = 'enhancement-toggle';
        enhancementToggle.checked = useImageEnhancement;
        enhancementToggle.addEventListener('change', (e) => {
            useImageEnhancement = e.target.checked;
            status.textContent = useImageEnhancement ? 
                'Image enhancement enabled. This may help detect barcodes in difficult lighting.' : 
                'Image enhancement disabled. Use this if barcodes are not being detected correctly.';
        });
        
        const enhancementLabel = document.createElement('label');
        enhancementLabel.htmlFor = 'enhancement-toggle';
        enhancementLabel.textContent = 'Enable image enhancement';
        
        enhancementContainer.appendChild(enhancementToggle);
        enhancementContainer.appendChild(enhancementLabel);
        
        // Create debug mode toggle
        const debugContainer = document.createElement('div');
        debugContainer.className = 'enhancement-toggle-container debug-toggle-container';
        
        debugModeToggle = document.createElement('input');
        debugModeToggle.type = 'checkbox';
        debugModeToggle.id = 'debug-toggle';
        debugModeToggle.checked = debugMode;
        debugModeToggle.addEventListener('change', (e) => {
            debugMode = e.target.checked;
            status.textContent = debugMode ? 
                'Debug mode enabled. Processing details will be shown.' : 
                'Debug mode disabled.';
                
            // Create or remove debug info element
            let debugInfo = document.getElementById('debug-info');
            if (debugMode) {
                if (!debugInfo) {
                    debugInfo = document.createElement('div');
                    debugInfo.id = 'debug-info';
                    debugInfo.className = 'debug-info';
                    result.parentNode.appendChild(debugInfo);
                }
            } else {
                if (debugInfo) {
                    debugInfo.remove();
                }
            }
        });
        
        const debugLabel = document.createElement('label');
        debugLabel.htmlFor = 'debug-toggle';
        debugLabel.textContent = 'Debug mode';
        
        debugContainer.appendChild(debugModeToggle);
        debugContainer.appendChild(debugLabel);
        
        // Append elements
        cameraControls.appendChild(startCameraButton);
        cameraControls.appendChild(stopCameraButton);
        cameraControls.appendChild(switchCameraButton);
        cameraControls.appendChild(captureImageButton);
        cameraControls.appendChild(focusModeButton);
        cameraControls.appendChild(retryPermissionButton);
        cameraControls.appendChild(enhancementContainer);
        cameraControls.appendChild(debugContainer);
        cameraContainer.appendChild(videoElement);
        
        // Insert camera elements into the DOM
        const uploadSection = document.querySelector('.upload-section');
        uploadSection.parentNode.insertBefore(cameraContainer, uploadSection.nextSibling);
        uploadSection.parentNode.insertBefore(cameraControls, uploadSection.nextSibling);
    }

    // Check if camera is supported
    function checkCameraSupport() {
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            console.warn('Camera access not supported in this browser');
            startCameraButton.disabled = true;
            startCameraButton.title = 'Camera not supported in this browser';
            status.textContent = 'Camera not supported in this browser. Try using a modern browser like Chrome, Firefox, or Edge.';
            return false;
        }
        
        // First try to access the camera to trigger permission prompt
        navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
                // Stop the stream immediately after getting permission
                stream.getTracks().forEach(track => track.stop());
                
                // Now enumerate devices after permission is granted
                return navigator.mediaDevices.enumerateDevices();
            })
            .then(devices => {
                availableCameras = devices.filter(device => device.kind === 'videoinput');
                console.log('Available cameras:', availableCameras);
                
                if (availableCameras.length === 0) {
                    startCameraButton.disabled = true;
                    startCameraButton.title = 'No cameras detected';
                    status.textContent = 'No cameras detected on your device';
                    return;
                }
                
                // Enable camera button
                startCameraButton.disabled = false;
                startCameraButton.title = 'Start camera for barcode scanning';
                status.textContent = 'Camera permission granted. Click "Start Camera" to begin scanning.';
                
                // Show switch camera button if multiple cameras available
                if (availableCameras.length > 1) {
                    switchCameraButton.style.display = 'inline-block';
                }
            })
            .catch(error => {
                console.error('Error accessing camera:', error);
                if (error.name === 'NotAllowedError' || error.name === 'PermissionDeniedError') {
                    status.textContent = 'Camera permission denied. Please click "Retry Camera Permission" and allow camera access when prompted.';
                    startCameraButton.disabled = true;
                    startCameraButton.title = 'Camera permission denied';
                    
                    // Show retry permission button
                    const retryButton = document.getElementById('retry-permission');
                    if (retryButton) {
                        retryButton.style.display = 'inline-block';
                    }
                } else {
                    // Try to enumerate devices anyway, in case permissions were granted before
                    navigator.mediaDevices.enumerateDevices()
                        .then(devices => {
                            availableCameras = devices.filter(device => device.kind === 'videoinput');
                            console.log('Available cameras (without permission):', availableCameras);
                            
                            if (availableCameras.length === 0) {
                                startCameraButton.disabled = true;
                                startCameraButton.title = 'No cameras detected';
                                status.textContent = 'No cameras detected on your device';
                            } else {
                                startCameraButton.disabled = false;
                                startCameraButton.title = 'Start camera for barcode scanning';
                                
                                if (availableCameras.length > 1) {
                                    switchCameraButton.style.display = 'inline-block';
                                }
                            }
                        })
                        .catch(enumError => {
                            console.error('Error enumerating devices:', enumError);
                            startCameraButton.disabled = true;
                            startCameraButton.title = 'Error accessing camera information';
                            status.textContent = 'Error accessing camera. Please check if your camera is connected and working properly.';
                        });
                }
            });
        
        return true;
    }

    // Start camera
    function startCamera() {
        // Hide image preview and show camera
        preview.style.display = 'none';
        cameraContainer.style.display = 'block';
        
        // Update buttons
        startCameraButton.style.display = 'none';
        stopCameraButton.style.display = 'inline-block';
        
        // Show focus mode and capture image buttons
        const focusModeButton = document.getElementById('focus-mode');
        const captureImageButton = document.getElementById('capture-image');
        if (focusModeButton) {
            focusModeButton.style.display = 'inline-block';
        }
        if (captureImageButton) {
            captureImageButton.style.display = 'inline-block';
        }
        
        // Clear previous results
        status.textContent = 'Starting camera...';
        result.textContent = '';
        
        // Try to get cameras again if none were detected initially
        if (availableCameras.length === 0) {
            navigator.mediaDevices.enumerateDevices()
                .then(devices => {
                    availableCameras = devices.filter(device => device.kind === 'videoinput');
                    console.log('Re-checking available cameras:', availableCameras);
                    continueStartCamera();
                })
                .catch(error => {
                    console.error('Error re-enumerating devices:', error);
                    continueStartCamera();
                });
        } else {
            continueStartCamera();
        }
    }
    
    // Continue camera startup after checking for cameras
    function continueStartCamera() {
        // Select camera (use first camera by default or previously selected)
        const cameraId = activeCameraId || (availableCameras.length > 0 ? availableCameras[0].deviceId : null);
        
        if (!cameraId) {
            // Try a more generic approach if no specific camera ID is available
            const constraints = {
                video: {
                    facingMode: 'environment' // Prefer back camera
                }
            };
            
            startCameraWithConstraints(constraints);
        } else {
            // Use specific camera ID
            const constraints = {
                video: {
                    deviceId: { exact: cameraId },
                    width: { ideal: 1280 },
                    height: { ideal: 720 }
                }
            };
            
            startCameraWithConstraints(constraints);
        }
    }
    
    // Start camera with specific constraints
    function startCameraWithConstraints(constraints) {
        navigator.mediaDevices.getUserMedia(constraints)
            .then(stream => {
                cameraStream = stream;
                videoElement.srcObject = stream;
                
                // Get the actual device ID from the stream
                const videoTrack = stream.getVideoTracks()[0];
                if (videoTrack) {
                    const settings = videoTrack.getSettings();
                    activeCameraId = settings.deviceId;
                    console.log('Active camera ID:', activeCameraId);
                    console.log('Camera settings:', settings);
                }
                
                // Wait for video to be ready
                videoElement.onloadedmetadata = () => {
                    status.textContent = 'Camera active. Point at a barcode to scan.';
                    startBarcodeScanning();
                };
            })
            .catch(error => {
                console.error('Error starting camera with constraints:', error, constraints);
                
                // If failed with specific constraints, try generic constraints
                if (constraints.video.deviceId) {
                    console.log('Trying generic camera constraints...');
                    startCameraWithConstraints({
                        video: {
                            facingMode: 'environment'
                        }
                    });
                } else {
                    status.textContent = 'Error starting camera: ' + (error.message || 'Unknown error');
                    stopCamera();
                }
            });
    }

    // Stop camera
    function stopCamera() {
        // Stop scanning
        stopBarcodeScanning();
        
        // Stop camera stream
        if (cameraStream) {
            cameraStream.getTracks().forEach(track => track.stop());
            cameraStream = null;
        }
        
        // Update UI
        videoElement.srcObject = null;
        cameraContainer.style.display = 'none';
        startCameraButton.style.display = 'inline-block';
        stopCameraButton.style.display = 'none';
        
        // Hide focus mode and capture image buttons
        const focusModeButton = document.getElementById('focus-mode');
        const captureImageButton = document.getElementById('capture-image');
        if (focusModeButton) {
            focusModeButton.style.display = 'none';
        }
        if (captureImageButton) {
            captureImageButton.style.display = 'none';
        }
        
        // Remove focus mode if active
        document.body.classList.remove('focus-mode-active');
        
        status.textContent = 'Camera stopped. Upload an image or restart camera.';
    }

    // Switch between available cameras
    function switchCamera() {
        if (availableCameras.length <= 1) return;
        
        // Find next camera in the list
        const currentIndex = availableCameras.findIndex(camera => camera.deviceId === activeCameraId);
        const nextIndex = (currentIndex + 1) % availableCameras.length;
        activeCameraId = availableCameras[nextIndex].deviceId;
        
        // Restart camera with new device
        if (cameraStream) {
            stopCamera();
            startCamera();
        }
    }

    // Start continuous barcode scanning
    function startBarcodeScanning() {
        if (isScanning) return;
        isScanning = true;
        
        // Add scanning indicator
        const scanIndicator = document.createElement('div');
        scanIndicator.id = 'scan-indicator';
        scanIndicator.className = 'scan-indicator';
        cameraContainer.appendChild(scanIndicator);
        
        // Process frames at regular intervals
        scanInterval = setInterval(() => {
            if (!videoElement || !cameraStream) return;
            
            // Capture current frame
            const width = videoElement.videoWidth;
            const height = videoElement.videoHeight;
            
            if (width === 0 || height === 0) return; // Skip if video dimensions aren't available yet
            
            // Set canvas dimensions to match video
            scanCanvas.width = width;
            scanCanvas.height = height;
            
            // Draw video frame on canvas
            const ctx = scanCanvas.getContext('2d');
            ctx.drawImage(videoElement, 0, 0, width, height);
            
            // Add scanning guide overlay
            drawScanningGuide(ctx, width, height);
            
            // Process the frame
            processVideoFrame(ctx, width, height);
        }, 100); // Scan more frequently (every 100ms instead of 200ms)
    }

    // Stop barcode scanning
    function stopBarcodeScanning() {
        isScanning = false;
        if (scanInterval) {
            clearInterval(scanInterval);
            scanInterval = null;
        }
        
        // Remove scanning indicator if it exists
        const scanIndicator = document.getElementById('scan-indicator');
        if (scanIndicator) {
            scanIndicator.remove();
        }
    }
    
    // Draw scanning guide overlay
    function drawScanningGuide(ctx, width, height) {
        // Draw a semi-transparent guide rectangle in the center
        const guideSize = Math.min(width, height) * (focusModeActive ? 0.5 : 0.7); // Smaller guide in focus mode
        const x = (width - guideSize) / 2;
        const y = (height - guideSize) / 2;
        
        // Draw outer darkened area
        ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
        ctx.fillRect(0, 0, width, height);
        
        // Draw transparent center
        ctx.clearRect(x, y, guideSize, guideSize);
        
        // Draw guide border
        ctx.strokeStyle = focusModeActive ? 'rgba(231, 76, 60, 0.8)' : 'rgba(52, 152, 219, 0.8)';
        ctx.lineWidth = focusModeActive ? 6 : 4;
        ctx.strokeRect(x, y, guideSize, guideSize);
        
        // Draw corner markers
        const markerLength = guideSize * 0.1;
        ctx.lineWidth = focusModeActive ? 8 : 6;
        
        // Top-left corner
        ctx.beginPath();
        ctx.moveTo(x, y + markerLength);
        ctx.lineTo(x, y);
        ctx.lineTo(x + markerLength, y);
        ctx.stroke();
        
        // Top-right corner
        ctx.beginPath();
        ctx.moveTo(x + guideSize - markerLength, y);
        ctx.lineTo(x + guideSize, y);
        ctx.lineTo(x + guideSize, y + markerLength);
        ctx.stroke();
        
        // Bottom-right corner
        ctx.beginPath();
        ctx.moveTo(x + guideSize, y + guideSize - markerLength);
        ctx.lineTo(x + guideSize, y + guideSize);
        ctx.lineTo(x + guideSize - markerLength, y + guideSize);
        ctx.stroke();
        
        // Bottom-left corner
        ctx.beginPath();
        ctx.moveTo(x + markerLength, y + guideSize);
        ctx.lineTo(x, y + guideSize);
        ctx.lineTo(x, y + guideSize - markerLength);
        ctx.stroke();
        
        // Add text instruction
        ctx.font = '16px Arial';
        ctx.fillStyle = 'white';
        ctx.textAlign = 'center';
        
        if (focusModeActive) {
            ctx.fillText('FOCUS MODE: Position barcode in the red box', width / 2, y + guideSize + 30);
            
            // Add crosshair in focus mode
            const centerX = x + guideSize / 2;
            const centerY = y + guideSize / 2;
            const crosshairSize = guideSize * 0.1;
            
            ctx.strokeStyle = 'rgba(231, 76, 60, 0.8)';
            ctx.lineWidth = 2;
            
            // Horizontal line
            ctx.beginPath();
            ctx.moveTo(centerX - crosshairSize, centerY);
            ctx.lineTo(centerX + crosshairSize, centerY);
            ctx.stroke();
            
            // Vertical line
            ctx.beginPath();
            ctx.moveTo(centerX, centerY - crosshairSize);
            ctx.lineTo(centerX, centerY + crosshairSize);
            ctx.stroke();
        } else {
            ctx.fillText('Position barcode within the box', width / 2, y + guideSize + 30);
        }
    }

    // Process video frame for barcode detection
    function processVideoFrame(ctx, width, height) {
        try {
            // Pulse the scan indicator to show active scanning
            const scanIndicator = document.getElementById('scan-indicator');
            if (scanIndicator) {
                scanIndicator.classList.add('pulse');
                setTimeout(() => {
                    scanIndicator.classList.remove('pulse');
                }, 50);
            }
            
            // Update debug info
            if (debugMode) {
                updateDebugInfo('Processing frame', { width, height });
            }
            
            // Store original image data for fallback
            const originalImageData = ctx.getImageData(0, 0, width, height);
            
            // Apply image enhancements to improve detection if enabled
            if (useImageEnhancement) {
                enhanceImage(ctx, width, height);
                if (debugMode) {
                    updateDebugInfo('Image enhancement applied');
                }
            }
            
            // Create a data URL from the canvas for the BrowserMultiFormatReader
            const dataUrl = scanCanvas.toDataURL('image/png');
            
            // Try direct MultiFormatReader approach first (more reliable for video)
            try {
                // Create a ZXing HTMLCanvasElementLuminanceSource
                const luminanceSource = new ZXing.HTMLCanvasElementLuminanceSource(scanCanvas);
                
                // Create a MultiFormatReader with hints
                const reader = new ZXing.MultiFormatReader();
                
                // Set up hints with all supported formats and try harder flag
                const newHints = new Map();
                newHints.set(ZXing.DecodeHintType.POSSIBLE_FORMATS, formats);
                newHints.set(ZXing.DecodeHintType.TRY_HARDER, true);
                // Add these additional hints for better video frame detection
                newHints.set(ZXing.DecodeHintType.PURE_BARCODE, false);
                newHints.set(ZXing.DecodeHintType.CHARACTER_SET, "UTF-8");
                newHints.set(ZXing.DecodeHintType.ASSUME_GS1, false);
                reader.setHints(newHints);
                
                // Try different binarizers for better detection
                const binarizers = [
                    new ZXing.HybridBinarizer(luminanceSource),
                    new ZXing.GlobalHistogramBinarizer(luminanceSource)
                ];
                
                let decodedResult = null;
                let usedBinarizer = '';
                let errorMessages = [];
                
                // Try each binarizer
                for (const binarizer of binarizers) {
                    if (decodedResult) break; // Stop if we already found a result
                    
                    const binaryBitmap = new ZXing.BinaryBitmap(binarizer);
                    usedBinarizer = binarizer instanceof ZXing.HybridBinarizer ? 'HybridBinarizer' : 'GlobalHistogramBinarizer';
                    
                    if (debugMode) {
                        updateDebugInfo(`Trying ${usedBinarizer}`);
                    }
                    
                    try {
                        // Try to decode the image using the binary bitmap
                        const result = reader.decode(binaryBitmap);
                        
                        decodedResult = {
                            text: result.getText(),
                            format: result.getBarcodeFormat(),
                            resultPoints: result.getResultPoints()
                        };
                        
                        if (debugMode) {
                            updateDebugInfo(`Success with ${usedBinarizer}`, decodedResult);
                        }
                        
                    } catch (error) {
                        // Store error for debugging
                        errorMessages.push(`${usedBinarizer}: ${error.message || 'Unknown error'}`);
                        
                        if (debugMode) {
                            updateDebugInfo(`Failed with ${usedBinarizer}`, { error: error.message || 'Unknown error' });
                        }
                    }
                }
                
                // If we got a result from the direct approach
                if (decodedResult) {
                    // Barcode detected successfully
                    status.textContent = 'Barcode recognized successfully!';
                    
                    // Format the result
                    const resultText = `Code: ${decodedResult.text}\nFormat: ${decodedResult.format}`;
                    document.getElementById('result').textContent = resultText;
                    
                    // Draw the barcode location on the canvas
                    if (decodedResult.resultPoints && decodedResult.resultPoints.length > 0) {
                        drawBarcodeLocation(ctx, decodedResult.resultPoints);
                    }
                    
                    // Play success sound
                    playSuccessBeep();
                    
                    // Pause scanning briefly after successful detection
                    stopBarcodeScanning();
                    setTimeout(startBarcodeScanning, 2000);
                    return;
                }
                
                // If direct approach failed, try with original image if we enhanced it
                if (useImageEnhancement) {
                    // Restore original image
                    ctx.putImageData(originalImageData, 0, 0);
                    
                    if (debugMode) {
                        updateDebugInfo('Trying with original (non-enhanced) image');
                    }
                    
                    // Try again with original image
                    for (const binarizer of binarizers) {
                        if (decodedResult) break; // Stop if we already found a result
                        
                        const luminanceSource = new ZXing.HTMLCanvasElementLuminanceSource(scanCanvas);
                        const binaryBitmap = new ZXing.BinaryBitmap(binarizer);
                        usedBinarizer = binarizer instanceof ZXing.HybridBinarizer ? 'HybridBinarizer (original)' : 'GlobalHistogramBinarizer (original)';
                        
                        try {
                            // Try to decode the image using the binary bitmap
                            const result = reader.decode(binaryBitmap);
                            
                            decodedResult = {
                                text: result.getText(),
                                format: result.getBarcodeFormat(),
                                resultPoints: result.getResultPoints()
                            };
                            
                            if (debugMode) {
                                updateDebugInfo(`Success with ${usedBinarizer}`, decodedResult);
                            }
                            
                        } catch (error) {
                            // Store error for debugging
                            errorMessages.push(`${usedBinarizer}: ${error.message || 'Unknown error'}`);
                            
                            if (debugMode) {
                                updateDebugInfo(`Failed with ${usedBinarizer}`, { error: error.message || 'Unknown error' });
                            }
                        }
                    }
                    
                    // If we got a result from the original image
                    if (decodedResult) {
                        // Barcode detected successfully
                        status.textContent = 'Barcode recognized successfully!';
                        
                        // Format the result
                        const resultText = `Code: ${decodedResult.text}\nFormat: ${decodedResult.format}`;
                        document.getElementById('result').textContent = resultText;
                        
                        // Draw the barcode location on the canvas
                        if (decodedResult.resultPoints && decodedResult.resultPoints.length > 0) {
                            drawBarcodeLocation(ctx, decodedResult.resultPoints);
                        }
                        
                        // Play success sound
                        playSuccessBeep();
                        
                        // Pause scanning briefly after successful detection
                        stopBarcodeScanning();
                        setTimeout(startBarcodeScanning, 2000);
                        return;
                    }
                }
                
                // If all direct methods failed, fall back to BrowserMultiFormatReader
                if (debugMode) {
                    updateDebugInfo('Trying BrowserMultiFormatReader fallback');
                }
                
                // Use the BrowserMultiFormatReader to decode the image
                codeReader.decodeFromImageUrl(dataUrl)
                    .then(result => {
                        if (result) {
                            // Barcode detected successfully
                            status.textContent = 'Barcode recognized successfully!';
                            
                            // Format the result
                            const resultText = `Code: ${result.text}\nFormat: ${result.format}`;
                            document.getElementById('result').textContent = resultText;
                            
                            if (debugMode) {
                                updateDebugInfo('Success with BrowserMultiFormatReader', { 
                                    text: result.text, 
                                    format: result.format 
                                });
                            }
                            
                            // Draw the barcode location on the canvas if available
                            if (result.resultPoints && result.resultPoints.length > 0) {
                                drawBarcodeLocation(ctx, result.resultPoints);
                            }
                            
                            // Play success sound
                            playSuccessBeep();
                            
                            // Pause scanning briefly after successful detection
                            stopBarcodeScanning();
                            setTimeout(startBarcodeScanning, 2000);
                        }
                    })
                    .catch((error) => {
                        // No barcode detected with any method
                        if (debugMode) {
                            updateDebugInfo('Failed with all methods', { 
                                error: error.message || 'Unknown error',
                                allErrors: errorMessages.join(', ')
                            });
                        }
                    });
                
            } catch (directError) {
                // If direct MultiFormatReader approach fails completely, fall back to BrowserMultiFormatReader
                if (debugMode) {
                    updateDebugInfo('Direct MultiFormatReader failed, trying BrowserMultiFormatReader', { 
                        error: directError.message || 'Unknown error' 
                    });
                }
                
                // Use the BrowserMultiFormatReader to decode the image
                codeReader.decodeFromImageUrl(dataUrl)
                    .then(result => {
                        if (result) {
                            // Barcode detected successfully
                            status.textContent = 'Barcode recognized successfully!';
                            
                            // Format the result
                            const resultText = `Code: ${result.text}\nFormat: ${result.format}`;
                            document.getElementById('result').textContent = resultText;
                            
                            if (debugMode) {
                                updateDebugInfo('Success with BrowserMultiFormatReader', { 
                                    text: result.text, 
                                    format: result.format 
                                });
                            }
                            
                            // Draw the barcode location on the canvas if available
                            if (result.resultPoints && result.resultPoints.length > 0) {
                                drawBarcodeLocation(ctx, result.resultPoints);
                            }
                            
                            // Play success sound
                            playSuccessBeep();
                            
                            // Pause scanning briefly after successful detection
                            stopBarcodeScanning();
                            setTimeout(startBarcodeScanning, 2000);
                        }
                    })
                    .catch((error) => {
                        // No barcode detected with any method
                        if (debugMode) {
                            updateDebugInfo('Failed with all methods', { 
                                error: error.message || 'Unknown error' 
                            });
                        }
                    });
            }
            
        } catch (error) {
            console.error('Error processing video frame:', error);
            if (debugMode) {
                updateDebugInfo('Error processing frame', { error: error.message || 'Unknown error' });
            }
        }
    }
    
    // Update debug information
    function updateDebugInfo(action, data = {}) {
        if (!debugMode) return;
        
        const debugInfo = document.getElementById('debug-info');
        if (!debugInfo) return;
        
        const timestamp = new Date().toLocaleTimeString();
        const entry = document.createElement('div');
        entry.className = 'debug-entry';
        
        let content = `<strong>${timestamp}</strong>: ${action}`;
        
        if (Object.keys(data).length > 0) {
            content += '<ul>';
            for (const [key, value] of Object.entries(data)) {
                content += `<li><strong>${key}:</strong> ${value}</li>`;
            }
            content += '</ul>';
        }
        
        entry.innerHTML = content;
        
        // Add to the top
        if (debugInfo.firstChild) {
            debugInfo.insertBefore(entry, debugInfo.firstChild);
        } else {
            debugInfo.appendChild(entry);
        }
        
        // Limit entries to 10
        while (debugInfo.children.length > 10) {
            debugInfo.removeChild(debugInfo.lastChild);
        }
    }

    // Enhance image to improve barcode detection
    function enhanceImage(ctx, width, height) {
        try {
            // Get image data
            const imageData = ctx.getImageData(0, 0, width, height);
            const data = imageData.data;
            
            // Try different enhancement approaches
            // First, store the original image data
            const originalData = new Uint8ClampedArray(data);
            
            // Image enhancement parameters - adjust based on focus mode
            const brightness = focusModeActive ? 20 : 15; // -255 to 255
            const contrast = focusModeActive ? 1.4 : 1.3;  // 0 to 2+
            const threshold = focusModeActive ? 135 : 128; // 0 to 255 (middle value for better results)
            
            // Apply brightness, contrast, and threshold
            for (let i = 0; i < data.length; i += 4) {
                // Apply brightness
                data[i] += brightness;     // R
                data[i + 1] += brightness; // G
                data[i + 2] += brightness; // B
                
                // Apply contrast
                data[i] = Math.min(255, Math.max(0, ((data[i] - 128) * contrast) + 128));     // R
                data[i + 1] = Math.min(255, Math.max(0, ((data[i + 1] - 128) * contrast) + 128)); // G
                data[i + 2] = Math.min(255, Math.max(0, ((data[i + 2] - 128) * contrast) + 128)); // B
                
                // Calculate grayscale value
                const gray = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
                
                // Apply threshold for better barcode detection
                // This creates higher contrast between dark and light areas
                if (gray < threshold) {
                    data[i] = 0;     // R
                    data[i + 1] = 0; // G
                    data[i + 2] = 0; // B
                } else {
                    data[i] = 255;     // R
                    data[i + 1] = 255; // G
                    data[i + 2] = 255; // B
                }
            }
            
            // Put the modified image data back on the canvas
            ctx.putImageData(imageData, 0, 0);
            
            // Apply sharpening filter
            applySharpening(ctx, width, height);
            
            // Store this enhanced version for potential fallback
            const enhancedImageData = ctx.getImageData(0, 0, width, height);
            
            // If debug mode is on, we'll keep the enhanced image visible
            if (!debugMode) {
                // For non-debug mode, we'll try a less aggressive approach as a fallback
                // This will be used in the next scan cycle if the current one fails
                window.lastEnhancedImageData = enhancedImageData;
                window.originalImageData = originalData;
                window.lastImageDimensions = { width, height };
            }
            
        } catch (error) {
            console.error('Error enhancing image:', error);
        }
    }
    
    // Apply sharpening filter to the image
    function applySharpening(ctx, width, height) {
        try {
            // Get image data
            const imageData = ctx.getImageData(0, 0, width, height);
            const data = imageData.data;
            const dataBackup = new Uint8ClampedArray(data);
            
            // Sharpening kernel - less aggressive
            const kernel = [
                0, -0.5, 0,
                -0.5, 3, -0.5,
                0, -0.5, 0
            ];
            
            // Apply convolution
            for (let y = 1; y < height - 1; y++) {
                for (let x = 1; x < width - 1; x++) {
                    const offset = (y * width + x) * 4;
                    
                    // For each color channel
                    for (let c = 0; c < 3; c++) {
                        let val = 0;
                        
                        // Apply kernel
                        for (let ky = -1; ky <= 1; ky++) {
                            for (let kx = -1; kx <= 1; kx++) {
                                const idx = ((y + ky) * width + (x + kx)) * 4 + c;
                                val += dataBackup[idx] * kernel[(ky + 1) * 3 + (kx + 1)];
                            }
                        }
                        
                        // Set the new value
                        data[offset + c] = Math.min(255, Math.max(0, val));
                    }
                }
            }
            
            // Put the modified image data back on the canvas
            ctx.putImageData(imageData, 0, 0);
            
        } catch (error) {
            console.error('Error applying sharpening:', error);
        }
    }

    // Play a success beep sound
    function playSuccessBeep() {
        try {
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.type = 'sine';
            oscillator.frequency.setValueAtTime(1800, audioContext.currentTime);
            oscillator.frequency.setValueAtTime(1200, audioContext.currentTime + 0.1);
            
            gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            oscillator.start();
            oscillator.stop(audioContext.currentTime + 0.3);
        } catch (error) {
            console.error('Error playing success beep:', error);
        }
    }

    // Handle image upload
    imageUpload.addEventListener('change', async (e) => {
        const file = e.target.files[0];
        if (!file) return;

        // Stop camera if running
        stopCamera();

        // Check if file is an image
        if (!file.type.match('image.*')) {
            status.textContent = 'Error: Not an image file';
            result.textContent = 'Please upload an image file (JPEG, PNG, etc.)';
            return;
        }

        // Display image preview
        const reader = new FileReader();
        reader.onload = (event) => {
            preview.src = event.target.result;
            preview.style.display = 'block';
            
            // Process the image with ZXing after it's loaded
            preview.onload = () => {
                processImage(preview);
            };
        };
        reader.onerror = () => {
            status.textContent = 'Error: Failed to read file';
            result.textContent = 'There was an error reading the file. Please try again.';
        };
        reader.readAsDataURL(file);
    });

    // Process image with ZXing
    async function processImage(imageElement) {
        status.textContent = 'Processing image...';
        result.textContent = '';

        try {
            // Get image dimensions
            const width = imageElement.naturalWidth;
            const height = imageElement.naturalHeight;

            // Set canvas dimensions to match image
            scanCanvas.width = width;
            scanCanvas.height = height;
            
            // Draw image on canvas
            const ctx = scanCanvas.getContext('2d');
            ctx.drawImage(imageElement, 0, 0, width, height);

            // Create a ZXing HTMLCanvasElementLuminanceSource
            const luminanceSource = new ZXing.HTMLCanvasElementLuminanceSource(scanCanvas);
            const binaryBitmap = new ZXing.BinaryBitmap(new ZXing.HybridBinarizer(luminanceSource));
            
            try {
                // Create a multi-format reader
                const reader = new ZXing.MultiFormatReader();
                reader.setHints(hints);
                
                // Try to decode the image using the binary bitmap
                const decodedResult = reader.decode(binaryBitmap);
                
                // Barcode detected successfully
                status.textContent = 'Barcode recognized successfully!';
                
                // Format the result
                const resultText = `Code: ${decodedResult.getText()}\nFormat: ${decodedResult.getBarcodeFormat()}`;
                document.getElementById('result').textContent = resultText;
                
                // Draw the barcode location on the canvas
                drawBarcodeLocation(ctx, decodedResult.getResultPoints());
                
            } catch (error) {
                // Try alternative method if the first one fails
                try {
                    // Use the BrowserMultiFormatReader as a fallback
                    const result = await codeReader.decodeFromImageUrl(imageElement.src);
                    
                    // Barcode detected successfully
                    status.textContent = 'Barcode recognized successfully!';
                    
                    // Format the result
                    const resultText = `Code: ${result.text}\nFormat: ${result.format}`;
                    document.getElementById('result').textContent = resultText;
                    
                    // Draw the barcode location on the canvas if available
                    if (result.resultPoints && result.resultPoints.length > 0) {
                        drawBarcodeLocation(ctx, result.resultPoints);
                    }
                    
                } catch (secondError) {
                    // Try one more approach with different binarizer
                    try {
                        const globalHistogramBinarizer = new ZXing.GlobalHistogramBinarizer(luminanceSource);
                        const secondBinaryBitmap = new ZXing.BinaryBitmap(globalHistogramBinarizer);
                        
                        const reader = new ZXing.MultiFormatReader();
                        reader.setHints(hints);
                        const thirdResult = reader.decode(secondBinaryBitmap);
                        
                        status.textContent = 'Barcode recognized successfully!';
                        const resultText = `Code: ${thirdResult.getText()}\nFormat: ${thirdResult.getBarcodeFormat()}`;
                        document.getElementById('result').textContent = resultText;
                        
                        drawBarcodeLocation(ctx, thirdResult.getResultPoints());
                    } catch (thirdError) {
                        // No barcode detected after all attempts
                        status.textContent = 'No barcode detected';
                        result.textContent = 'Could not detect a valid barcode in the image. Please try another image with a clearer barcode.';
                        console.error('ZXing errors:', error, secondError, thirdError);
                    }
                }
            }
        } catch (error) {
            // Handle any exceptions during processing
            status.textContent = 'Error processing image';
            result.textContent = error.message || 'An unexpected error occurred';
            console.error('Error in processImage:', error);
        }
    }

    // Draw barcode location on canvas
    function drawBarcodeLocation(ctx, points) {
        if (!points || points.length === 0) return;
        
        ctx.strokeStyle = 'rgba(255, 0, 0, 0.8)'; // Red color for detected barcodes
        ctx.lineWidth = 5;
        
        ctx.beginPath();
        
        // For QR codes and other 2D barcodes (usually 4 points)
        if (points.length >= 4) {
            ctx.moveTo(points[0].x, points[0].y);
            ctx.lineTo(points[1].x, points[1].y);
            ctx.lineTo(points[2].x, points[2].y);
            ctx.lineTo(points[3].x, points[3].y);
            ctx.lineTo(points[0].x, points[0].y);
        } 
        // For 1D barcodes (usually 2 points)
        else if (points.length >= 2) {
            // Calculate the corners of a rectangle for the barcode
            const p1 = points[0];
            const p2 = points[points.length - 1];
            
            // Calculate the width of the barcode (perpendicular to the line)
            const angle = Math.atan2(p2.y - p1.y, p2.x - p1.x);
            const perpAngle = angle + Math.PI / 2;
            const width = 20; // Width of the barcode rectangle
            
            // Calculate the four corners of the rectangle
            const corners = [
                { x: p1.x - width * Math.cos(perpAngle), y: p1.y - width * Math.sin(perpAngle) },
                { x: p1.x + width * Math.cos(perpAngle), y: p1.y + width * Math.sin(perpAngle) },
                { x: p2.x + width * Math.cos(perpAngle), y: p2.y + width * Math.sin(perpAngle) },
                { x: p2.x - width * Math.cos(perpAngle), y: p2.y - width * Math.sin(perpAngle) }
            ];
            
            // Draw the rectangle
            ctx.moveTo(corners[0].x, corners[0].y);
            ctx.lineTo(corners[1].x, corners[1].y);
            ctx.lineTo(corners[2].x, corners[2].y);
            ctx.lineTo(corners[3].x, corners[3].y);
            ctx.lineTo(corners[0].x, corners[0].y);
        }
        
        ctx.stroke();
    }

    // Handle page visibility changes
    document.addEventListener('visibilitychange', () => {
        if (document.hidden && cameraStream) {
            // Pause scanning when page is not visible
            stopBarcodeScanning();
        } else if (!document.hidden && cameraStream && !isScanning) {
            // Resume scanning when page becomes visible again
            startBarcodeScanning();
        }
    });

    // Toggle focus mode for better barcode scanning
    function toggleFocusMode() {
        focusModeActive = !focusModeActive;
        
        const focusModeButton = document.getElementById('focus-mode');
        if (focusModeButton) {
            focusModeButton.textContent = focusModeActive ? 'Exit Focus Mode' : 'Focus Mode';
            focusModeButton.classList.toggle('active', focusModeActive);
        }
        
        document.body.classList.toggle('focus-mode-active', focusModeActive);
        
        if (focusModeActive) {
            status.textContent = 'Focus Mode active. Hold barcode steady in the center of the screen.';
            
            // Pause and restart scanning to apply new settings
            if (isScanning) {
                stopBarcodeScanning();
                startBarcodeScanning();
            }
        } else {
            status.textContent = 'Focus Mode disabled. Camera active.';
            
            // Pause and restart scanning to apply new settings
            if (isScanning) {
                stopBarcodeScanning();
                startBarcodeScanning();
            }
        }
    }

    // Capture a still image from the camera feed
    function captureImage() {
        if (!videoElement || !cameraStream) {
            status.textContent = 'Camera not active. Cannot capture image.';
            return;
        }
        
        try {
            // Temporarily pause scanning
            const wasScanning = isScanning;
            if (isScanning) {
                stopBarcodeScanning();
            }
            
            // Get video dimensions
            const width = videoElement.videoWidth;
            const height = videoElement.videoHeight;
            
            if (width === 0 || height === 0) {
                status.textContent = 'Cannot capture image. Video feed not ready.';
                if (wasScanning) {
                    startBarcodeScanning();
                }
                return;
            }
            
            // Create a temporary canvas for the capture
            const captureCanvas = document.createElement('canvas');
            captureCanvas.width = width;
            captureCanvas.height = height;
            
            // Draw the current video frame to the canvas
            const ctx = captureCanvas.getContext('2d');
            ctx.drawImage(videoElement, 0, 0, width, height);
            
            // Create an image element from the canvas
            const capturedImage = new Image();
            capturedImage.onload = () => {
                // Display the captured image
                preview.src = capturedImage.src;
                preview.style.display = 'block';
                
                // Hide camera feed temporarily
                cameraContainer.style.display = 'none';
                
                // Process the captured image
                status.textContent = 'Processing captured image...';
                processImage(capturedImage, true);
            };
            
            // Convert canvas to data URL and set as image source
            capturedImage.src = captureCanvas.toDataURL('image/png');
            
            // Show a notification
            status.textContent = 'Image captured from camera. Processing...';
            
        } catch (error) {
            console.error('Error capturing image:', error);
            status.textContent = 'Error capturing image: ' + (error.message || 'Unknown error');
            
            // Resume scanning if it was active
            if (wasScanning) {
                startBarcodeScanning();
            }
        }
    }

    // Process image with ZXing
    async function processImage(imageElement, fromCamera = false) {
        status.textContent = 'Processing image...';
        result.textContent = '';

        try {
            // Get image dimensions
            const width = imageElement.naturalWidth;
            const height = imageElement.naturalHeight;

            // Set canvas dimensions to match image
            scanCanvas.width = width;
            scanCanvas.height = height;
            
            // Draw image on canvas
            const ctx = scanCanvas.getContext('2d');
            ctx.drawImage(imageElement, 0, 0, width, height);
            
            // Apply image enhancement if enabled
            if (useImageEnhancement) {
                enhanceImage(ctx, width, height);
                if (debugMode) {
                    updateDebugInfo('Image enhancement applied to captured image');
                }
            }

            // Create a ZXing HTMLCanvasElementLuminanceSource
            const luminanceSource = new ZXing.HTMLCanvasElementLuminanceSource(scanCanvas);
            
            // Try different binarizers for better detection
            const binarizers = [
                new ZXing.HybridBinarizer(luminanceSource),
                new ZXing.GlobalHistogramBinarizer(luminanceSource)
            ];
            
            let decodedResult = null;
            let usedBinarizer = '';
            let errorMessages = [];
            
            // Try each binarizer
            for (const binarizer of binarizers) {
                if (decodedResult) break; // Stop if we already found a result
                
                const binaryBitmap = new ZXing.BinaryBitmap(binarizer);
                usedBinarizer = binarizer instanceof ZXing.HybridBinarizer ? 'HybridBinarizer' : 'GlobalHistogramBinarizer';
                
                if (debugMode) {
                    updateDebugInfo(`Trying ${usedBinarizer} on captured image`);
                }
                
                try {
                    // Create a multi-format reader with hints
                    const reader = new ZXing.MultiFormatReader();
                    
                    // Set up hints with all supported formats and try harder flag
                    const newHints = new Map();
                    newHints.set(ZXing.DecodeHintType.POSSIBLE_FORMATS, formats);
                    newHints.set(ZXing.DecodeHintType.TRY_HARDER, true);
                    newHints.set(ZXing.DecodeHintType.PURE_BARCODE, false);
                    newHints.set(ZXing.DecodeHintType.CHARACTER_SET, "UTF-8");
                    reader.setHints(newHints);
                    
                    // Try to decode the image using the binary bitmap
                    const result = reader.decode(binaryBitmap);
                    
                    decodedResult = {
                        text: result.getText(),
                        format: result.getBarcodeFormat(),
                        resultPoints: result.getResultPoints()
                    };
                    
                    if (debugMode) {
                        updateDebugInfo(`Success with ${usedBinarizer} on captured image`, decodedResult);
                    }
                    
                } catch (error) {
                    // Store error for debugging
                    errorMessages.push(`${usedBinarizer}: ${error.message || 'Unknown error'}`);
                    
                    if (debugMode) {
                        updateDebugInfo(`Failed with ${usedBinarizer} on captured image`, { error: error.message || 'Unknown error' });
                    }
                }
            }
            
            // If we got a result from the direct approach
            if (decodedResult) {
                // Barcode detected successfully
                status.textContent = 'Barcode recognized successfully!';
                
                // Format the result
                const resultText = `Code: ${decodedResult.text}\nFormat: ${decodedResult.format}`;
                document.getElementById('result').textContent = resultText;
                
                // Draw the barcode location on the canvas
                if (decodedResult.resultPoints && decodedResult.resultPoints.length > 0) {
                    drawBarcodeLocation(ctx, decodedResult.resultPoints);
                }
                
                // Play success sound
                playSuccessBeep();
                
                // If this was from a camera capture, show a button to return to camera
                if (fromCamera) {
                    showReturnToCameraButton();
                }
                
                return;
            }
            
            // If direct approach failed, try BrowserMultiFormatReader as fallback
            try {
                // Use the BrowserMultiFormatReader as a fallback
                const dataUrl = scanCanvas.toDataURL('image/png');
                const result = await codeReader.decodeFromImageUrl(dataUrl);
                
                // Barcode detected successfully
                status.textContent = 'Barcode recognized successfully!';
                
                // Format the result
                const resultText = `Code: ${result.text}\nFormat: ${result.format}`;
                document.getElementById('result').textContent = resultText;
                
                // Draw the barcode location on the canvas if available
                if (result.resultPoints && result.resultPoints.length > 0) {
                    drawBarcodeLocation(ctx, result.resultPoints);
                }
                
                // Play success sound
                playSuccessBeep();
                
                // If this was from a camera capture, show a button to return to camera
                if (fromCamera) {
                    showReturnToCameraButton();
                }
                
            } catch (error) {
                // No barcode detected after all attempts
                status.textContent = 'No barcode detected';
                result.textContent = 'Could not detect a valid barcode in the image. Please try again with a clearer image.';
                
                if (debugMode) {
                    updateDebugInfo('Failed with all methods on captured image', { 
                        error: error.message || 'Unknown error',
                        allErrors: errorMessages.join(', ')
                    });
                }
                
                // If this was from a camera capture, show a button to return to camera
                if (fromCamera) {
                    showReturnToCameraButton();
                }
            }
            
        } catch (error) {
            // Handle any exceptions during processing
            status.textContent = 'Error processing image';
            result.textContent = error.message || 'An unexpected error occurred';
            console.error('Error in processImage:', error);
            
            // If this was from a camera capture, show a button to return to camera
            if (fromCamera) {
                showReturnToCameraButton();
            }
        }
    }
    
    // Show a button to return to camera view after processing a captured image
    function showReturnToCameraButton() {
        // Check if button already exists
        let returnButton = document.getElementById('return-to-camera');
        if (returnButton) {
            returnButton.style.display = 'inline-block';
            return;
        }
        
        // Create return to camera button
        returnButton = document.createElement('button');
        returnButton.id = 'return-to-camera';
        returnButton.className = 'return-to-camera-btn';
        returnButton.textContent = 'Return to Camera';
        returnButton.addEventListener('click', () => {
            // Hide the preview and show the camera
            preview.style.display = 'none';
            cameraContainer.style.display = 'block';
            
            // Hide the return button
            returnButton.style.display = 'none';
            
            // Restart scanning
            startBarcodeScanning();
            
            status.textContent = 'Returned to camera. Point at a barcode to scan.';
        });
        
        // Add to the DOM
        const resultSection = document.getElementById('result').parentNode;
        resultSection.appendChild(returnButton);
    }

    // Initialize the app
    init();
});