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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
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
class Match3Game {
    constructor() {
        this.boardRows = 7;
        this.boardCols = 8;
        this.numGemTypes = 6;
        this.board = [];
        this.selectedCell = null;
        this.score = 0;
        this.totalScore = 0;
        this.moves = 30;
        this.level = 1;
        this.levelTargetScore = 1000;
        this.isProcessing = false;
        this.dragStartCell = null;
        this.isDragging = false;
        this.visualSwapActive = false;
        this.visualSwapTarget = null;
        this.mouseX = 0;
        this.mouseY = 0;
        this.dragOffsetX = 0;
        this.dragOffsetY = 0;
        this.targetOffsetX = 0;
        this.targetOffsetY = 0;
        this.currentOffsetX = 0;
        this.currentOffsetY = 0;
        this.animationFrameId = null;
        this.buttonClickCooldown = false;
        this.renderPending = false;
        this.lastBoardState = null;
        
        // Load best stats from localStorage
        this.bestLevel = parseInt(localStorage.getItem('bestLevel') || '1');
        this.bestScore = parseInt(localStorage.getItem('bestScore') || '0');
        
        // Initialize sound system
        this.soundManager = new SoundManager();
        
        this.init();
    }
    
    init() {
        this.setupEventListeners();
        this.setupTheme();
        this.showHome();
    }
    
    setupTheme() {
        // Load saved theme or default to light
        const savedTheme = localStorage.getItem('gameTheme') || 'light';
        this.applyTheme(savedTheme);
        
        // Setup theme selector
        const themeSelect = document.getElementById('theme-select');
        if (themeSelect) {
            themeSelect.value = savedTheme;
            themeSelect.addEventListener('change', (e) => {
                this.applyTheme(e.target.value);
            });
        }
    }
    
    applyTheme(theme) {
        const body = document.body;
        if (theme === 'dark') {
            body.classList.add('dark-theme');
            body.classList.remove('light-theme');
        } else {
            body.classList.add('light-theme');
            body.classList.remove('dark-theme');
        }
        localStorage.setItem('gameTheme', theme);
    }
    
    showHome() {
        document.getElementById('home-page').classList.remove('hidden');
        const gameHeader = document.querySelector('.game-header');
        const gameBoard = document.getElementById('game-board');
        const gameControls = document.querySelector('.game-controls');
        
        if (gameHeader) gameHeader.classList.add('hidden');
        if (gameBoard) gameBoard.classList.add('hidden');
        if (gameControls) {
            gameControls.classList.add('hidden');
            gameControls.style.visibility = 'hidden';
        }
        
        // Stop background music when going home
        if (this.soundManager) {
            this.soundManager.stopBackgroundMusic();
        }
        
        this.updateHomeStats();
    }
    
    showGame() {
        document.getElementById('home-page').classList.add('hidden');
        const gameHeader = document.querySelector('.game-header');
        const gameBoard = document.getElementById('game-board');
        const gameControls = document.querySelector('.game-controls');
        
        if (gameHeader) gameHeader.classList.remove('hidden');
        if (gameBoard) gameBoard.classList.remove('hidden');
        if (gameControls) {
            gameControls.classList.remove('hidden');
            gameControls.style.visibility = 'visible';
            gameControls.style.display = 'flex';
            gameControls.style.opacity = '1';
        }
        this.createBoard();
        this.renderBoard();
        this.updateUI();
        
        // Start background music
        if (this.soundManager) {
            this.soundManager.startBackgroundMusic();
            this.soundManager.updateMusicButton();
        }
    }
    
    updateHomeStats() {
        document.getElementById('best-level').textContent = this.bestLevel;
        document.getElementById('best-score').textContent = this.bestScore.toLocaleString();
    }
    
    saveBestStats() {
        let updated = false;
        if (this.level > this.bestLevel) {
            this.bestLevel = this.level;
            localStorage.setItem('bestLevel', this.bestLevel.toString());
            updated = true;
        }
        if (this.totalScore > this.bestScore) {
            this.bestScore = this.totalScore;
            localStorage.setItem('bestScore', this.bestScore.toString());
            updated = true;
        }
        // Update home stats display if we're on home page
        if (updated && !document.querySelector('.game-header').classList.contains('hidden')) {
            // Will update when going to home
        }
    }
    
    createBoard() {
        // Initialize empty board
        this.board = [];
        for (let row = 0; row < this.boardRows; row++) {
            this.board[row] = [];
            for (let col = 0; col < this.boardCols; col++) {
                this.board[row][col] = this.getRandomGem();
            }
        }
        
        // Remove initial matches
        while (this.findMatches().length > 0) {
            for (let row = 0; row < this.boardRows; row++) {
                for (let col = 0; col < this.boardCols; col++) {
                    if (this.isPartOfMatch(row, col)) {
                        this.board[row][col] = this.getRandomGem();
                    }
                }
            }
        }
    }
    
    getRandomGem() {
        return Math.floor(Math.random() * this.numGemTypes);
    }
    
    isPartOfMatch(row, col) {
        const gem = this.board[row][col];
        
        // Check horizontal match
        let horizontalCount = 1;
        for (let c = col - 1; c >= 0 && this.board[row][c] === gem; c--) horizontalCount++;
        for (let c = col + 1; c < this.boardCols && this.board[row][c] === gem; c++) horizontalCount++;
        if (horizontalCount >= 3) return true;
        
        // Check vertical match
        let verticalCount = 1;
        for (let r = row - 1; r >= 0 && this.board[r][col] === gem; r--) verticalCount++;
        for (let r = row + 1; r < this.boardRows && this.board[r][col] === gem; r++) verticalCount++;
        if (verticalCount >= 3) return true;
        
        return false;
    }
    
    renderBoard(forceUpdate = false) {
        // Allow rendering during processing only if forceUpdate is true (for final render after matches)
        if (this.isProcessing && !forceUpdate) {
            this.renderPending = true;
            return;
        }
        
        // Don't render during active drag unless forced
        if (this.isDragging && !forceUpdate) {
            this.renderPending = true;
            return;
        }
        
        const boardElement = document.getElementById('game-board');
        if (!boardElement) return;
        
        // Check if board already exists - update instead of recreate
        const existingCells = boardElement.querySelectorAll('.cell');
        const needsFullRender = existingCells.length !== this.boardRows * this.boardCols;
        
        if (needsFullRender) {
            boardElement.innerHTML = '';
        }
        
        // Create board state string for comparison
        const currentState = JSON.stringify(this.board);
        const stateChanged = currentState !== this.lastBoardState;
        
        // If state hasn't changed and we don't need full render, skip update completely
        if (!needsFullRender && !stateChanged && !forceUpdate) {
            return;
        }
        
        this.lastBoardState = currentState;
        
        // Update cells directly without requestAnimationFrame to prevent flickering
        for (let row = 0; row < this.boardRows; row++) {
            for (let col = 0; col < this.boardCols; col++) {
                    let cell = existingCells[row * this.boardCols + col];
                    
                    if (!cell || needsFullRender) {
                        cell = document.createElement('div');
                        cell.dataset.row = row;
                        cell.dataset.col = col;
                        
                        // Click handler (fallback)
                        cell.addEventListener('click', () => this.handleCellClick(row, col));
                        
                        // Drag handlers
                        cell.addEventListener('mousedown', (e) => this.handleDragStart(e, row, col));
                        cell.addEventListener('mouseenter', (e) => this.handleDragOver(e, row, col));
                        
                        // Prevent text selection during drag
                        cell.addEventListener('selectstart', (e) => e.preventDefault());
                        cell.addEventListener('dragstart', (e) => e.preventDefault());
                        
                        boardElement.appendChild(cell);
                    }
                    
                    // Only update if gem type changed
                    const gemType = this.board[row][col];
                    const expectedClass = `cell gem-${gemType}`;
                    const expectedEmoji = this.getGemEmoji(gemType);
                    
                    // Handle empty cells first
                    if (gemType === -1) {
                        // Hide empty cells
                        if (!cell.classList.contains('empty-cell')) {
                            cell.classList.add('empty-cell');
                            cell.style.display = 'none';
                        }
                        continue;
                    }
                    
                    // Remove empty-cell class and ensure visibility for non-empty cells
                    if (cell.classList.contains('empty-cell')) {
                        cell.classList.remove('empty-cell');
                        cell.style.display = '';
                        cell.style.opacity = '';
                        cell.style.visibility = '';
                    }
                    
                    // Check if cell needs update
                    const currentGemClass = Array.from(cell.classList).find(c => c.startsWith('gem-'));
                    const needsUpdate = needsFullRender || 
                                       currentGemClass !== `gem-${gemType}` || 
                                       cell.textContent !== expectedEmoji;
                    
                    if (needsUpdate) {
                        // NEVER update cells that are in animation states
                        const isMatched = cell.classList.contains('matched');
                        const isMatchEnlarge = cell.classList.contains('match-enlarge');
                        const hasActiveAnimation = isMatched || isMatchEnlarge;
                        
                        // Only update if not animating
                        if (!hasActiveAnimation) {
                            // Always ensure cell is visible for non-empty cells
                            cell.style.display = '';
                            cell.style.opacity = '';
                            cell.style.visibility = '';
                            
                            cell.className = expectedClass;
                            cell.textContent = expectedEmoji;
                            
                            // Only reset transform if cell is idle
                            if (!cell.style.transform || cell.style.transform === '') {
                                cell.style.transform = '';
                                cell.style.transition = '';
                            }
                        }
                    }
                }
            }
        
        // Add board-level mousemove for better drag tracking
        boardElement.addEventListener('mousemove', (e) => {
            if (this.isDragging && this.dragStartCell) {
                // Update mouse position for smooth tracking
                this.mouseX = e.clientX;
                this.mouseY = e.clientY;
                
                const startCell = document.querySelector(
                    `[data-row="${this.dragStartCell.row}"][data-col="${this.dragStartCell.col}"]`
                );
                if (startCell) {
                    const rect = startCell.getBoundingClientRect();
                    // Calculate target offset (where we want to go)
                    this.targetOffsetX = (e.clientX - (rect.left + rect.width / 2)) * 0.6;
                    this.targetOffsetY = (e.clientY - (rect.top + rect.height / 2)) * 0.6;
                    this.dragOffsetX = this.targetOffsetX;
                    this.dragOffsetY = this.targetOffsetY;
                }
                
                const cell = e.target.closest('.cell');
                if (cell && cell.dataset.row && cell.dataset.col) {
                    const row = parseInt(cell.dataset.row);
                    const col = parseInt(cell.dataset.col);
                    this.handleDragOver(e, row, col);
                }
            }
        });
        
        // Add global mouse up handler to handle drag end
        document.addEventListener('mouseup', () => this.handleDragEnd());
    }
    
    getGemEmoji(gemType) {
        if (gemType === -1) return ''; // Empty cell
        const emojis = ['🔴', '🔵', '🟡', '🟢', '🟠', '🟣'];
        return emojis[gemType] || '⚪';
    }
    
    handleDragStart(e, row, col) {
        if (this.isProcessing) return;
        if (this.moves <= 0) return; // No moves left
        
        e.preventDefault();
        this.dragStartCell = { row, col };
        this.isDragging = true;
        
        // Play swipe sound
        if (this.soundManager) {
            this.soundManager.playSwipeSound();
        }
        
        const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
        if (cell) {
            const rect = cell.getBoundingClientRect();
            const boardRect = document.getElementById('game-board').getBoundingClientRect();
            
            // Store initial mouse position relative to cell center
            this.mouseX = e.clientX;
            this.mouseY = e.clientY;
            this.dragOffsetX = 0;
            this.dragOffsetY = 0;
            this.targetOffsetX = 0;
            this.targetOffsetY = 0;
            this.currentOffsetX = 0;
            this.currentOffsetY = 0;
            
            cell.classList.add('selected', 'dragging');
            cell.style.cursor = 'grabbing';
            cell.style.transition = 'none'; // Disable transition during drag for smooth following
            cell.style.willChange = 'transform';
            
            // Start smooth position tracking
            this.startDragTracking();
        }
        
        // Add dragging class to board for visual feedback
        document.getElementById('game-board').classList.add('is-dragging');
    }
    
    startDragTracking() {
        if (this.animationFrameId) {
            cancelAnimationFrame(this.animationFrameId);
        }
        
        const updateDragPosition = () => {
            if (!this.isDragging || !this.dragStartCell) return;
            
            const cell = document.querySelector(
                `[data-row="${this.dragStartCell.row}"][data-col="${this.dragStartCell.col}"]`
            );
            
            if (cell) {
                // Smooth interpolation using easing (ease-out cubic for fluid motion)
                const smoothingFactor = 0.15; // Lower = smoother but slower response
                this.currentOffsetX += (this.targetOffsetX - this.currentOffsetX) * smoothingFactor;
                this.currentOffsetY += (this.targetOffsetY - this.currentOffsetY) * smoothingFactor;
                
                // Apply smooth transform with fluid motion
                const scale = 1.12 + Math.min(Math.abs(this.currentOffsetX) + Math.abs(this.currentOffsetY), 30) / 200;
                const rotationX = this.currentOffsetY * 0.1;
                const rotationY = this.currentOffsetX * 0.1;
                
                cell.style.transform = `translate(${this.currentOffsetX}px, ${this.currentOffsetY}px) scale(${scale}) translateZ(20px) rotateX(${rotationX}deg) rotateY(${rotationY}deg)`;
            }
            
            this.animationFrameId = requestAnimationFrame(updateDragPosition);
        };
        
        this.animationFrameId = requestAnimationFrame(updateDragPosition);
    }
    
    handleDragOver(e, row, col) {
        if (!this.isDragging || !this.dragStartCell) return;
        if (this.isProcessing) return;
        
        e.preventDefault();
        
        // Don't update if hovering over the same cell
        if (row === this.dragStartCell.row && col === this.dragStartCell.col) return;
        
        // Check if target is adjacent
        const isAdjacent = 
            (Math.abs(this.dragStartCell.row - row) === 1 && this.dragStartCell.col === col) ||
            (Math.abs(this.dragStartCell.col - col) === 1 && this.dragStartCell.row === row);
        
        const startCell = document.querySelector(
            `[data-row="${this.dragStartCell.row}"][data-col="${this.dragStartCell.col}"]`
        );
        
        // If we have a visual swap active but target changed, revert it
        if (this.visualSwapActive && this.visualSwapTarget) {
            if (this.visualSwapTarget.row !== row || this.visualSwapTarget.col !== col) {
                this.revertVisualSwap();
            }
        }
        
        if (isAdjacent) {
            const targetCell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
            
            // If this is a new target or we don't have a visual swap, create one
            if (!this.visualSwapActive || 
                !this.visualSwapTarget || 
                this.visualSwapTarget.row !== row || 
                this.visualSwapTarget.col !== col) {
                
                // Revert any existing swap first
                if (this.visualSwapActive) {
                    this.revertVisualSwap();
                }
                
                // Perform visual swap
                this.performVisualSwap(this.dragStartCell.row, this.dragStartCell.col, row, col);
                this.visualSwapTarget = { row, col };
            }
            
            if (targetCell) {
                targetCell.classList.add('drag-target');
                if (startCell) {
                    this.drawConnectionLine(startCell, targetCell);
                }
            }
        } else {
            // Not adjacent - revert visual swap if active
            if (this.visualSwapActive) {
                this.revertVisualSwap();
            }
            
            // Remove target from all cells
            document.querySelectorAll('.cell').forEach(c => {
                c.classList.remove('drag-target');
            });
            
            // Remove connection line if not adjacent
            this.removeConnectionLine();
        }
    }
    
    performVisualSwap(row1, col1, row2, col2) {
        const cell1 = document.querySelector(`[data-row="${row1}"][data-col="${col1}"]`);
        const cell2 = document.querySelector(`[data-row="${row2}"][data-col="${col2}"]`);
        
        if (!cell1 || !cell2) return;
        
        // Get cell positions for smooth swap animation
        const rect1 = cell1.getBoundingClientRect();
        const rect2 = cell2.getBoundingClientRect();
        
        // Calculate relative positions in pixels for smoother animation
        const deltaX = rect2.left - rect1.left;
        const deltaY = rect2.top - rect1.top;
        
        // Actually swap in the board array so match checking works correctly
        [this.board[row1][col1], this.board[row2][col2]] = 
        [this.board[row2][col2], this.board[row1][col1]];
        
        // Get the gem types (now swapped)
        const gem1 = this.board[row1][col1];
        const gem2 = this.board[row2][col2];
        
        // Enable ultra-smooth transitions for swap animation
        cell1.style.transition = 'transform 0.35s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
        cell2.style.transition = 'transform 0.35s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
        
        // Animate swap with fluid position interpolation
        cell1.style.transform = `translate(${deltaX}px, ${deltaY}px) scale(1.08) translateZ(15px)`;
        cell2.style.transform = `translate(${-deltaX}px, ${-deltaY}px) scale(1.08) translateZ(15px)`;
        
        // Update the visual appearance mid-animation for seamless transition
        setTimeout(() => {
            cell1.className = `cell gem-${gem1}`;
            cell1.textContent = this.getGemEmoji(gem1);
            cell1.classList.add('selected', 'dragging');
            
            cell2.className = `cell gem-${gem2}`;
            cell2.textContent = this.getGemEmoji(gem2);
            cell2.classList.add('drag-target');
        }, 175); // Halfway through animation for smooth visual swap
        
        // Reset transforms after animation completes
        setTimeout(() => {
            cell1.style.transform = '';
            cell2.style.transform = '';
        }, 350);
        
        this.visualSwapActive = true;
    }
    
    revertVisualSwap() {
        if (!this.visualSwapActive || !this.dragStartCell || !this.visualSwapTarget) return;
        
        const cell1 = document.querySelector(
            `[data-row="${this.dragStartCell.row}"][data-col="${this.dragStartCell.col}"]`
        );
        const cell2 = document.querySelector(
            `[data-row="${this.visualSwapTarget.row}"][data-col="${this.visualSwapTarget.col}"]`
        );
        
        if (cell1 && cell2) {
            // Smooth revert animation
            cell1.style.transition = 'transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)';
            cell2.style.transition = 'transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)';
            
            // Animate back to original positions
            cell1.style.transform = 'translate(0, 0) scale(1.1) translateZ(15px)';
            cell2.style.transform = 'translate(0, 0) scale(1.1) translateZ(15px)';
            
            // Revert the board array swap after animation
            setTimeout(() => {
                [this.board[this.dragStartCell.row][this.dragStartCell.col], 
                 this.board[this.visualSwapTarget.row][this.visualSwapTarget.col]] = 
                [this.board[this.visualSwapTarget.row][this.visualSwapTarget.col], 
                 this.board[this.dragStartCell.row][this.dragStartCell.col]];
                
                // Restore original appearance
                const gem1 = this.board[this.dragStartCell.row][this.dragStartCell.col];
                const gem2 = this.board[this.visualSwapTarget.row][this.visualSwapTarget.col];
                
                cell1.className = `cell gem-${gem1}`;
                cell1.textContent = this.getGemEmoji(gem1);
                cell1.classList.add('selected', 'dragging');
                cell1.style.transform = '';
                
                cell2.className = `cell gem-${gem2}`;
                cell2.textContent = this.getGemEmoji(gem2);
                cell2.style.transform = '';
                
                // Render board after revert animation completes
                requestAnimationFrame(() => {
                    this.renderBoard();
                });
            }, 300);
        }
        
        this.visualSwapActive = false;
        this.visualSwapTarget = null;
    }
    
    drawConnectionLine(startCell, targetCell) {
        // Remove existing line
        this.removeConnectionLine();
        
        const board = document.getElementById('game-board');
        const startRect = startCell.getBoundingClientRect();
        const targetRect = targetCell.getBoundingClientRect();
        const boardRect = board.getBoundingClientRect();
        
        // Calculate positions relative to board
        const startX = startRect.left + startRect.width / 2 - boardRect.left;
        const startY = startRect.top + startRect.height / 2 - boardRect.top;
        const targetX = targetRect.left + targetRect.width / 2 - boardRect.left;
        const targetY = targetRect.top + targetRect.height / 2 - boardRect.top;
        
        // Create SVG line
        const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svg.setAttribute('class', 'drag-connection');
        svg.style.position = 'absolute';
        svg.style.left = '0';
        svg.style.top = '0';
        svg.style.width = '100%';
        svg.style.height = '100%';
        svg.style.pointerEvents = 'none';
        
        const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
        line.setAttribute('x1', startX);
        line.setAttribute('y1', startY);
        line.setAttribute('x2', targetX);
        line.setAttribute('y2', targetY);
        line.setAttribute('stroke', 'rgba(100, 150, 255, 0.9)');
        line.setAttribute('stroke-width', '5');
        line.setAttribute('stroke-dasharray', '8, 4');
        line.setAttribute('marker-end', 'url(#arrowhead)');
        
        // Add arrow marker
        const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
        const marker = document.createElementNS('http://www.w3.org/2000/svg', 'marker');
        marker.setAttribute('id', 'arrowhead');
        marker.setAttribute('markerWidth', '10');
        marker.setAttribute('markerHeight', '10');
        marker.setAttribute('refX', '9');
        marker.setAttribute('refY', '3');
        marker.setAttribute('orient', 'auto');
        
        const polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
        polygon.setAttribute('points', '0 0, 10 3, 0 6');
        polygon.setAttribute('fill', 'rgba(100, 150, 255, 0.9)');
        
        marker.appendChild(polygon);
        defs.appendChild(marker);
        svg.appendChild(defs);
        svg.appendChild(line);
        
        board.style.position = 'relative';
        board.appendChild(svg);
    }
    
    removeConnectionLine() {
        const existingLine = document.querySelector('.drag-connection');
        if (existingLine) {
            existingLine.remove();
        }
    }
    
    handleDragEnd() {
        if (!this.isDragging || !this.dragStartCell) return;
        
        // If we have a visual swap active, commit it to the game logic
        if (this.visualSwapActive && this.visualSwapTarget) {
            // The board array is already swapped from performVisualSwap
            // Just check for matches and process
            const matches = this.findMatches();
            
            if (matches.length > 0) {
                // Valid swap
                this.selectedCell = null;
                this.updateCellSelection();
                if (this.moves > 0) this.moves--;
                
                // Animate matched cells by enlarging them
                this.animateMatchedCells(matches).then(() => {
                    this.processMatches();
                });
            } else {
                // Invalid swap - revert
                this.revertVisualSwap();
                // Don't call renderBoard here - revertVisualSwap handles it
            }
            
            // Clear visual swap state
            this.visualSwapActive = false;
            this.visualSwapTarget = null;
        } else {
            // No visual swap was active, check if there's a target cell
            const targetCell = document.querySelector('.drag-target');
            if (targetCell) {
                const targetRow = parseInt(targetCell.dataset.row);
                const targetCol = parseInt(targetCell.dataset.col);
                
                this.swapCells(
                    this.dragStartCell.row,
                    this.dragStartCell.col,
                    targetRow,
                    targetCol
                );
            } else {
                // No valid target - just clean up
                if (this.visualSwapActive) {
                    this.revertVisualSwap();
                }
            }
        }
        
        // Remove connection line
        this.removeConnectionLine();
        
        // Reset drag state first
        this.isDragging = false;
        const dragStart = this.dragStartCell;
        this.dragStartCell = null;
        
        // Cancel animation frame
        if (this.animationFrameId) {
            cancelAnimationFrame(this.animationFrameId);
            this.animationFrameId = null;
        }
        
        // Smoothly reset all drag-related styles using requestAnimationFrame for smoothness
        requestAnimationFrame(() => {
            document.querySelectorAll('.cell').forEach(c => {
                // Only reset if not in an animation state
                if (!c.classList.contains('matched') && !c.classList.contains('match-enlarge')) {
                    c.style.transition = 'transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94), opacity 0.2s ease';
                    c.style.transform = '';
                    c.style.willChange = '';
                    c.classList.remove('selected', 'drag-target', 'dragging');
                    c.style.cursor = '';
                    
                    // Remove inline styles after transition
                    setTimeout(() => {
                        if (!c.classList.contains('matched')) {
                            c.style.transition = '';
                        }
                    }, 300);
                }
            });
        });
        
        // Reset offsets
        this.currentOffsetX = 0;
        this.currentOffsetY = 0;
        this.targetOffsetX = 0;
        this.targetOffsetY = 0;
        
        // Remove board dragging class
        document.getElementById('game-board').classList.remove('is-dragging');
    }
    
    handleCellClick(row, col) {
        // Clicking only allows visual selection, no matching allowed
        // Matching is only allowed through drag and drop
        if (this.isProcessing) return;
        if (this.isDragging) return; // Ignore clicks during drag
        
        // Just allow visual selection for feedback, but don't perform swaps
        this.selectedCell = { row, col };
        this.updateCellSelection();
    }
    
    updateCellSelection() {
        const cells = document.querySelectorAll('.cell');
        cells.forEach(cell => cell.classList.remove('selected'));
        
        if (this.selectedCell) {
            const cell = document.querySelector(
                `[data-row="${this.selectedCell.row}"][data-col="${this.selectedCell.col}"]`
            );
            if (cell) cell.classList.add('selected');
        }
    }
    
    swapCells(row1, col1, row2, col2) {
        // If visual swap is already active, the board array is already swapped
        // Otherwise, swap it now
        if (!this.visualSwapActive) {
            // Swap in board
            [this.board[row1][col1], this.board[row2][col2]] = 
            [this.board[row2][col2], this.board[row1][col1]];
        }
        
        // Check if swap creates a match
        const matches = this.findMatches();
        
        if (matches.length > 0) {
            // Valid swap - visual swap already shows the correct state (or we just swapped)
            this.selectedCell = null;
            this.updateCellSelection();
            if (this.moves > 0) this.moves--;
            
            // Play match sound
            if (this.soundManager) {
                this.soundManager.playMatchSound(matches.length);
            }
            
            // Animate matched cells by enlarging them
            this.animateMatchedCells(matches).then(() => {
                this.processMatches();
            });
            } else {
                // Invalid swap - revert both visual and logical
                if (this.visualSwapActive) {
                    // Visual swap will be reverted by revertVisualSwap, but we need to revert the array
                    [this.board[row1][col1], this.board[row2][col2]] = 
                    [this.board[row2][col2], this.board[row1][col1]];
                } else {
                    // Revert the swap we just made
                    [this.board[row1][col1], this.board[row2][col2]] = 
                    [this.board[row2][col2], this.board[row1][col1]];
                }
                // Don't call renderBoard here - revertVisualSwap handles visual update
                // renderBoard will be called after revert completes
        }
    }
    
    async animateMatchedCells(matches) {
        // No animation - skip immediately
        // This function is kept for compatibility but does nothing now
        await this.sleep(0);
    }
    
    updateCellsAfterMatch() {
        // This function is no longer needed - we use renderBoard(true) instead
        // Keeping it for backwards compatibility but it's essentially a no-op now
    }
    
    findMatches() {
        const matches = [];
        const visited = new Set();
        
        // Check horizontal matches
        for (let row = 0; row < this.boardRows; row++) {
            let count = 1;
            let currentGem = this.board[row][0];
            
            for (let col = 1; col < this.boardCols; col++) {
                if (this.board[row][col] === currentGem) {
                    count++;
                } else {
                    if (count >= 3) {
                        for (let c = col - count; c < col; c++) {
                            const key = `${row},${c}`;
                            if (!visited.has(key)) {
                                matches.push({ row, col: c });
                                visited.add(key);
                            }
                        }
                    }
                    count = 1;
                    currentGem = this.board[row][col];
                }
            }
            
            // Check end of row
            if (count >= 3) {
                for (let c = this.boardCols - count; c < this.boardCols; c++) {
                    const key = `${row},${c}`;
                    if (!visited.has(key)) {
                        matches.push({ row, col: c });
                        visited.add(key);
                    }
                }
            }
        }
        
        // Check vertical matches
        for (let col = 0; col < this.boardCols; col++) {
            let count = 1;
            let currentGem = this.board[0][col];
            
            for (let row = 1; row < this.boardRows; row++) {
                if (this.board[row][col] === currentGem) {
                    count++;
                } else {
                    if (count >= 3) {
                        for (let r = row - count; r < row; r++) {
                            const key = `${r},${col}`;
                            if (!visited.has(key)) {
                                matches.push({ row: r, col });
                                visited.add(key);
                            }
                        }
                    }
                    count = 1;
                    currentGem = this.board[row][col];
                }
            }
            
            // Check end of column
            if (count >= 3) {
                for (let r = this.boardRows - count; r < this.boardRows; r++) {
                    const key = `${r},${col}`;
                    if (!visited.has(key)) {
                        matches.push({ row: r, col });
                        visited.add(key);
                    }
                }
            }
        }
        
        return matches;
    }
    
    async processMatches() {
        this.isProcessing = true;
        
        while (true) {
            const matches = this.findMatches();
            
            if (matches.length === 0) {
                break;
            }
            
            // Update score
            this.score += matches.length * 10;
            this.updateUI();
            
            // Animate matched cells - add matched class to trigger fade-out
            matches.forEach(match => {
                const cell = document.querySelector(
                    `[data-row="${match.row}"][data-col="${match.col}"]`
                );
                if (cell) {
                    cell.classList.add('matched');
                    // Create random particles for each matched cell
                    this.createExplosionParticles(cell);
                }
            });
            
            // No animation wait - tiles disappear immediately
            await this.sleep(50);
            
            // Clean up particles
            document.querySelectorAll('.explosion-particle').forEach(particle => {
                particle.remove();
            });
            
            // Remove matched cells from board and DOM
            matches.forEach(match => {
                this.board[match.row][match.col] = -1; // Mark as empty
                
                // Mark cell as empty - renderBoard will handle hiding it
                // Don't manipulate DOM directly here to prevent flickering
            });
            
            // Make pieces fall
            await this.applyGravity();
            
            // Fill empty spaces with new random gems
            this.fillEmptySpaces();
            
            // Re-render board to show new tiles - force update even during processing
            this.renderBoard(true);
            
            // Small delay to let the new tiles appear before checking for new matches
            await this.sleep(100);
        }
        
        this.isProcessing = false;
        
        // Render any pending updates after processing completes - do it synchronously
        if (this.renderPending) {
            this.renderPending = false;
            this.renderBoard(true);
        }
        
        this.checkGameOver();
    }
    
    async applyGravity() {
        for (let col = 0; col < this.boardCols; col++) {
            let writeIndex = this.boardRows - 1;
            
            for (let row = this.boardRows - 1; row >= 0; row--) {
                if (this.board[row][col] !== -1) {
                    if (writeIndex !== row) {
                        this.board[writeIndex][col] = this.board[row][col];
                        this.board[row][col] = -1;
                    }
                    writeIndex--;
                }
            }
        }
    }
    
    fillEmptySpaces() {
        for (let row = 0; row < this.boardRows; row++) {
            for (let col = 0; col < this.boardCols; col++) {
                if (this.board[row][col] === -1) {
                    this.board[row][col] = this.getRandomGem();
                }
            }
        }
    }
    
    checkGameOver() {
        // Check if level is complete (reached target score)
        if (this.score >= this.levelTargetScore) {
            this.completeLevel();
            return;
        }
        
        // Check if moves are exhausted and target not reached - game over
        if (this.moves <= 0 && this.score < this.levelTargetScore) {
            this.gameOver();
        }
    }
    
    gameOver() {
        // Pause the game
        this.isProcessing = true;
        
        // Save best stats
        this.saveBestStats();
        
        // Play game over sound
        if (this.soundManager) {
            this.soundManager.playGameOverSound();
        }
        
        // Show game over modal
        document.getElementById('final-level').textContent = this.level;
        document.getElementById('final-score').textContent = this.totalScore.toLocaleString();
        document.getElementById('game-over').classList.remove('hidden');
    }
    
    retryLevel() {
        // Hide game over modal
        document.getElementById('game-over').classList.add('hidden');
        
        // Reset level score (keep total score and level)
        this.score = 0;
        
        // Reset moves for current level
        this.moves = this.getLevelMoves(this.level);
        
        // Reset game state
        this.selectedCell = null;
        this.isProcessing = false;
        
        // Create new board
        this.createBoard();
        this.renderBoard();
        this.updateUI();
    }
    
    completeLevel() {
        // Pause the game
        this.isProcessing = true;
        
        // Update total score
        this.totalScore += this.score;
        
        // Play level complete sound
        if (this.soundManager) {
            this.soundManager.playLevelCompleteSound();
        }
        
        // Show level complete modal
        document.getElementById('completed-level').textContent = this.level;
        document.getElementById('level-score').textContent = this.score;
        document.getElementById('total-score').textContent = this.totalScore;
        document.getElementById('level-complete').classList.remove('hidden');
    }
    
    continueToNextLevel() {
        // Hide level complete modal
        document.getElementById('level-complete').classList.add('hidden');
        
        // Increment level
        this.level++;
        
        // Save best stats
        this.saveBestStats();
        
        // Increase difficulty: more score needed, but also more moves
        this.levelTargetScore = this.level * 1000;
        this.moves = this.getLevelMoves(this.level); // Use correct calculation
        
        // Reset level score (keep total score)
        this.score = 0;
        
        // Create new board
        this.createBoard();
        this.renderBoard();
        this.updateUI();
        
        // Resume game
        this.isProcessing = false;
    }
    
    goToHome() {
        // Save best stats before going home
        this.saveBestStats();
        
        // Hide all modals
        document.getElementById('level-complete').classList.add('hidden');
        document.getElementById('game-over').classList.add('hidden');
        
        // Show home page
        this.showHome();
    }
    
    endGame() {
        // Go to home from game over screen
        this.goToHome();
    }
    
    getLevelMoves(level) {
        // Level 1: 30 moves, Level 2+: 25 + (level * 2)
        return level === 1 ? 30 : 25 + (level * 2);
    }
    
    updateUI() {
        document.getElementById('score').textContent = this.score;
        document.getElementById('moves').textContent = Math.max(0, this.moves);
        document.getElementById('level').textContent = this.level;
        document.getElementById('target-score').textContent = this.levelTargetScore.toLocaleString();
        
        // Calculate and display the correct level moves
        const levelMoves = this.getLevelMoves(this.level);
        document.getElementById('level-moves').textContent = levelMoves;
        
        // Show progress to next level (optional visual indicator)
        const progress = Math.min(100, (this.score / this.levelTargetScore) * 100);
        // Could add a progress bar here if desired
    }
    
    setupEventListeners() {
        // Helper function to prevent rapid clicks
        const preventRapidClicks = (callback) => {
            return (e) => {
                if (this.buttonClickCooldown) {
                    e.preventDefault();
                    e.stopPropagation();
                    return;
                }
                
                this.buttonClickCooldown = true;
                const button = e.currentTarget;
                
                // Play click sound
                if (this.soundManager) {
                    this.soundManager.playClickSound();
                }
                
                // Add visual feedback
                button.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    button.style.transform = '';
                }, 150);
                
                // Execute callback
                callback();
                
                // Reset cooldown after a short delay
                setTimeout(() => {
                    this.buttonClickCooldown = false;
                }, 300);
            };
        };
        
        document.getElementById('start-game-btn').addEventListener('click', preventRapidClicks(() => {
            this.startNewGame();
        }));
        
        document.getElementById('home-btn').addEventListener('click', preventRapidClicks(() => {
            this.goToHome();
        }));
        
        document.getElementById('reset-btn').addEventListener('click', preventRapidClicks(() => {
            this.resetGame();
        }));
        
        document.getElementById('retry-btn').addEventListener('click', preventRapidClicks(() => {
            this.retryLevel();
        }));
        
        document.getElementById('quit-game-btn').addEventListener('click', preventRapidClicks(() => {
            this.goToHome();
        }));
        
        document.getElementById('hint-btn').addEventListener('click', preventRapidClicks(() => {
            this.showHint();
        }));
        
        document.getElementById('continue-btn').addEventListener('click', preventRapidClicks(() => {
            this.continueToNextLevel();
        }));
        
        document.getElementById('quit-btn').addEventListener('click', preventRapidClicks(() => {
            this.goToHome();
        }));
        
        // Music toggle button
        const musicToggleBtn = document.getElementById('music-toggle-btn');
        if (musicToggleBtn) {
            musicToggleBtn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                if (this.soundManager) {
                    this.soundManager.toggleMusic();
                    this.soundManager.playClickSound();
                }
            });
        }
    }
    
    startNewGame() {
        this.score = 0;
        this.totalScore = 0;
        this.moves = 30;
        this.level = 1;
        this.levelTargetScore = 1000;
        this.selectedCell = null;
        this.isProcessing = false;
        this.showGame();
    }
    
    resetGame() {
        // Reset current game but stay on game screen
        this.score = 0;
        this.totalScore = 0;
        this.moves = 30;
        this.level = 1;
        this.levelTargetScore = 1000;
        this.selectedCell = null;
        this.isProcessing = false;
        document.getElementById('game-over').classList.add('hidden');
        document.getElementById('level-complete').classList.add('hidden');
        this.createBoard();
        this.renderBoard();
        this.updateUI();
    }
    
    showHint() {
        // Find a valid move
        for (let row = 0; row < this.boardRows - 1; row++) {
            for (let col = 0; col < this.boardCols; col++) {
                // Try swapping down
                [this.board[row][col], this.board[row + 1][col]] = 
                [this.board[row + 1][col], this.board[row][col]];
                
                if (this.findMatches().length > 0) {
                    // Valid move found - highlight it
                    [this.board[row][col], this.board[row + 1][col]] = 
                    [this.board[row + 1][col], this.board[row][col]];
                    
                    const cell1 = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                    const cell2 = document.querySelector(`[data-row="${row + 1}"][data-col="${col}"]`);
                    
                    if (cell1 && cell2) {
                        cell1.style.boxShadow = '0 0 0 4px #00ff00';
                        cell2.style.boxShadow = '0 0 0 4px #00ff00';
                        
                        setTimeout(() => {
                            cell1.style.boxShadow = '';
                            cell2.style.boxShadow = '';
                        }, 2000);
                    }
                    return;
                }
                
                [this.board[row][col], this.board[row + 1][col]] = 
                [this.board[row + 1][col], this.board[row][col]];
            }
        }
        
        for (let row = 0; row < this.boardRows; row++) {
            for (let col = 0; col < this.boardCols - 1; col++) {
                // Try swapping right
                [this.board[row][col], this.board[row][col + 1]] = 
                [this.board[row][col + 1], this.board[row][col]];
                
                if (this.findMatches().length > 0) {
                    // Valid move found
                    [this.board[row][col], this.board[row][col + 1]] = 
                    [this.board[row][col + 1], this.board[row][col]];
                    
                    const cell1 = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                    const cell2 = document.querySelector(`[data-row="${row}"][data-col="${col + 1}"]`);
                    
                    if (cell1 && cell2) {
                        cell1.style.boxShadow = '0 0 0 4px #00ff00';
                        cell2.style.boxShadow = '0 0 0 4px #00ff00';
                        
                        setTimeout(() => {
                            cell1.style.boxShadow = '';
                            cell2.style.boxShadow = '';
                        }, 2000);
                    }
                    return;
                }
                
                [this.board[row][col], this.board[row][col + 1]] = 
                [this.board[row][col + 1], this.board[row][col]];
            }
        }
        
        alert('No valid moves found! Shuffling board...');
        this.createBoard();
        this.renderBoard();
    }
    
    createExplosionParticles(cell) {
        const particleEmojis = ['✨', '⭐', '💫', '🌟', '⚡', '💥'];
        const numParticles = 4 + Math.floor(Math.random() * 3); // 4-6 particles per cell
        
        for (let i = 0; i < numParticles; i++) {
            const particle = document.createElement('div');
            particle.className = 'explosion-particle';
            particle.textContent = particleEmojis[Math.floor(Math.random() * particleEmojis.length)];
            
            // Generate random nonlinear path
            const angle = (Math.PI * 2 * i) / numParticles + (Math.random() - 0.5) * 0.8; // Spread around circle with randomness
            const distance = 20 + Math.random() * 15; // 20-35px distance (scaled down)
            const curveAmount = 7 + Math.random() * 10; // Curve variation (scaled down)
            
            // Create curved path with 3 control points
            const x1 = Math.cos(angle) * (distance * 0.3) + (Math.random() - 0.5) * curveAmount;
            const y1 = Math.sin(angle) * (distance * 0.3) + (Math.random() - 0.5) * curveAmount;
            
            const x2 = Math.cos(angle) * (distance * 0.6) + (Math.random() - 0.5) * curveAmount * 1.5;
            const y2 = Math.sin(angle) * (distance * 0.6) + (Math.random() - 0.5) * curveAmount * 1.5;
            
            const x3 = Math.cos(angle) * distance + (Math.random() - 0.5) * curveAmount * 2;
            const y3 = Math.sin(angle) * distance + (Math.random() - 0.5) * curveAmount * 2;
            
            // Random rotation
            const rotation = (Math.random() > 0.5 ? 1 : -1) * (720 + Math.random() * 720); // 720-1440 degrees
            
            // Random scale variation
            const scale = 0.05 + Math.random() * 0.03; // 0.05-0.08
            
            // Set CSS custom properties for animation
            particle.style.setProperty('--particle-x1', `${x1}px`);
            particle.style.setProperty('--particle-y1', `${y1}px`);
            particle.style.setProperty('--particle-x2', `${x2}px`);
            particle.style.setProperty('--particle-y2', `${y2}px`);
            particle.style.setProperty('--particle-x3', `${x3}px`);
            particle.style.setProperty('--particle-y3', `${y3}px`);
            particle.style.setProperty('--particle-rotate', `${rotation}deg`);
            particle.style.setProperty('--particle-scale', scale.toString());
            
            // Random delay for staggered effect
            particle.style.animationDelay = `${Math.random() * 0.2}s`;
            
            cell.appendChild(particle);
        }
    }
    
    sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// Sound Manager Class
class SoundManager {
    constructor() {
        this.audioContext = null;
        this.musicEnabled = localStorage.getItem('musicEnabled') !== 'false';
        this.soundsEnabled = localStorage.getItem('soundsEnabled') !== 'false';
        this.musicVolume = parseFloat(localStorage.getItem('musicVolume') || '0.5');
        this.sfxVolume = parseFloat(localStorage.getItem('sfxVolume') || '0.7');
        this.musicOscillator = null;
        this.musicGainNode = null;
        this.isMusicPlaying = false;
        this.initAudioContext();
        this.setupVolumeControls();
    }
    
    setupVolumeControls() {
        // Setup music volume control
        const musicVolumeSlider = document.getElementById('music-volume');
        if (musicVolumeSlider) {
            musicVolumeSlider.value = this.musicVolume * 100;
            musicVolumeSlider.addEventListener('input', (e) => {
                this.musicVolume = e.target.value / 100;
                localStorage.setItem('musicVolume', this.musicVolume);
            });
        }
        
        // Setup SFX volume control
        const sfxVolumeSlider = document.getElementById('sfx-volume');
        if (sfxVolumeSlider) {
            sfxVolumeSlider.value = this.sfxVolume * 100;
            sfxVolumeSlider.addEventListener('input', (e) => {
                this.sfxVolume = e.target.value / 100;
                localStorage.setItem('sfxVolume', this.sfxVolume);
            });
        }
    }
    
    initAudioContext() {
        try {
            this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
        } catch (e) {
            console.warn('Web Audio API not supported');
        }
    }
    
    // Start background music (looping, fun upbeat melody)
    startBackgroundMusic() {
        if (!this.audioContext || !this.musicEnabled || this.isMusicPlaying) return;
        
        try {
            this.isMusicPlaying = true;
            this.playMusicLoop();
        } catch (e) {
            console.warn('Could not start music:', e);
        }
    }
    
    playMusicLoop() {
        if (!this.audioContext || !this.musicEnabled) return;
        
        const notes = [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]; // C major scale
        let noteIndex = 0;
        
        const playNote = () => {
            if (!this.musicEnabled || !this.isMusicPlaying) return;
            
            const frequency = notes[noteIndex % notes.length];
            const oscillator = this.audioContext.createOscillator();
            const gainNode = this.audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(this.audioContext.destination);
            
            oscillator.type = 'sine';
            oscillator.frequency.value = frequency;
            
            const baseGain = this.musicVolume * 0.1;
            gainNode.gain.setValueAtTime(baseGain, this.audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(baseGain * 0.5, this.audioContext.currentTime + 0.3);
            gainNode.gain.exponentialRampToValueAtTime(baseGain * 0.1, this.audioContext.currentTime + 0.6);
            
            oscillator.start(this.audioContext.currentTime);
            oscillator.stop(this.audioContext.currentTime + 0.6);
            
            noteIndex++;
            
            setTimeout(() => {
                if (this.musicEnabled && this.isMusicPlaying) {
                    playNote();
                }
            }, 300);
        };
        
        playNote();
    }
    
    stopBackgroundMusic() {
        this.isMusicPlaying = false;
        if (this.musicOscillator) {
            this.musicOscillator.stop();
            this.musicOscillator = null;
        }
    }
    
    toggleMusic() {
        this.musicEnabled = !this.musicEnabled;
        localStorage.setItem('musicEnabled', this.musicEnabled);
        
        if (this.musicEnabled) {
            this.startBackgroundMusic();
        } else {
            this.stopBackgroundMusic();
        }
        
        this.updateMusicButton();
    }
    
    updateMusicButton() {
        const btn = document.getElementById('music-toggle-btn');
        if (btn) {
            btn.textContent = this.musicEnabled ? '🔊' : '🔇';
        }
    }
    
    // Play swipe sound (whoosh)
    playSwipeSound() {
        if (!this.audioContext || !this.soundsEnabled) return;
        
        const oscillator = this.audioContext.createOscillator();
        const gainNode = this.audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(this.audioContext.destination);
        
        oscillator.type = 'sine';
        oscillator.frequency.setValueAtTime(400, this.audioContext.currentTime);
        oscillator.frequency.exponentialRampToValueAtTime(200, this.audioContext.currentTime + 0.1);
        
        const volume = this.sfxVolume * 0.2;
        gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(volume * 0.05, this.audioContext.currentTime + 0.1);
        
        oscillator.start(this.audioContext.currentTime);
        oscillator.stop(this.audioContext.currentTime + 0.1);
    }
    
    // Play match sound (successful match - cheerful chime)
    playMatchSound(count = 1) {
        if (!this.audioContext || !this.soundsEnabled) return;
        
        const frequencies = [523.25, 659.25, 783.99]; // C, E, G chord
        const delay = 0.05;
        
        frequencies.forEach((freq, index) => {
            setTimeout(() => {
                const oscillator = this.audioContext.createOscillator();
                const gainNode = this.audioContext.createGain();
                
                oscillator.connect(gainNode);
                gainNode.connect(this.audioContext.destination);
                
                oscillator.type = 'sine';
                oscillator.frequency.value = freq * (1 + count * 0.1);
                
                const volume = this.sfxVolume * 0.15;
                gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
                gainNode.gain.exponentialRampToValueAtTime(volume * 0.07, this.audioContext.currentTime + 0.3);
                
                oscillator.start(this.audioContext.currentTime);
                oscillator.stop(this.audioContext.currentTime + 0.3);
            }, index * delay);
        });
    }
    
    // Play level complete sound (victory fanfare)
    playLevelCompleteSound() {
        if (!this.audioContext || !this.soundsEnabled) return;
        
        const melody = [523.25, 659.25, 783.99, 1046.50, 783.99, 1046.50];
        melody.forEach((freq, index) => {
            setTimeout(() => {
                const oscillator = this.audioContext.createOscillator();
                const gainNode = this.audioContext.createGain();
                
                oscillator.connect(gainNode);
                gainNode.connect(this.audioContext.destination);
                
                oscillator.type = 'sine';
                oscillator.frequency.value = freq;
                
                const volume = this.sfxVolume * 0.2;
                gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
                gainNode.gain.exponentialRampToValueAtTime(volume * 0.05, this.audioContext.currentTime + 0.4);
                
                oscillator.start(this.audioContext.currentTime);
                oscillator.stop(this.audioContext.currentTime + 0.4);
            }, index * 150);
        });
    }
    
    // Play game over sound (sad tone)
    playGameOverSound() {
        if (!this.audioContext || !this.soundsEnabled) return;
        
        const frequencies = [392.00, 349.23, 293.66, 261.63];
        frequencies.forEach((freq, index) => {
            setTimeout(() => {
                const oscillator = this.audioContext.createOscillator();
                const gainNode = this.audioContext.createGain();
                
                oscillator.connect(gainNode);
                gainNode.connect(this.audioContext.destination);
                
                oscillator.type = 'sine';
                oscillator.frequency.value = freq;
                
                const volume = this.sfxVolume * 0.15;
                gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
                gainNode.gain.exponentialRampToValueAtTime(volume * 0.07, this.audioContext.currentTime + 0.5);
                
                oscillator.start(this.audioContext.currentTime);
                oscillator.stop(this.audioContext.currentTime + 0.5);
            }, index * 200);
        });
    }
    
    // Play button click sound
    playClickSound() {
        if (!this.audioContext || !this.soundsEnabled) return;
        
        const oscillator = this.audioContext.createOscillator();
        const gainNode = this.audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(this.audioContext.destination);
        
        oscillator.type = 'sine';
        oscillator.frequency.value = 800;
        
        const volume = this.sfxVolume * 0.1;
        gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(volume * 0.1, this.audioContext.currentTime + 0.05);
        
        oscillator.start(this.audioContext.currentTime);
        oscillator.stop(this.audioContext.currentTime + 0.05);
    }
}

// Initialize game when page loads
let game;
window.addEventListener('DOMContentLoaded', () => {
    game = new Match3Game();
});