File size: 46,584 Bytes
df9973f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633f37b
df9973f
 
 
 
 
 
 
 
 
633f37b
df9973f
 
84e1dd3
df9973f
 
 
 
 
 
84e1dd3
df9973f
84e1dd3
df9973f
 
84e1dd3
 
df9973f
 
 
84e1dd3
df9973f
 
 
 
 
 
84e1dd3
 
 
633f37b
 
df9973f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Pro Suite - Chess AI</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
/* =========================================================
   1. CORE STYLES & LAYOUT
   ========================================================= */
body { min-height: 100vh; background: radial-gradient(circle at top,#1e3a8a 0,#0f172a 45%,#020617 100%); color: #f8fafc; font-family: Poppins,sans-serif; overflow-y: auto !important; overflow-x: hidden; margin: 0; padding-bottom: 50px; }
.chess-wrap { max-width: 1100px; margin: 85px auto 30px; padding: 20px; box-sizing: border-box; }
.hero { background: rgba(15,23,42,.78); border: 1px solid rgba(255,255,255,.12); border-radius: 28px; padding: 30px; box-shadow: 0 25px 80px rgba(0,0,0,.4); text-align: center; }
.hero h1 { font-size: clamp(30px,6vw,58px); margin: 0; background: linear-gradient(90deg,#60a5fa,#c084fc,#facc15); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
.menu-grid { display: grid; grid-template-columns: repeat(auto-fit,minmax(250px,1fr)); gap: 18px; margin-top: 24px; }
.panel { background: rgba(2,6,23,.55); border: 1px solid rgba(255,255,255,.12); border-radius: 22px; padding: 20px; }
.big-btn, .small-btn { border: 0; border-radius: 999px; padding: 14px 22px; font-weight: 800; cursor: pointer; color: white; background: linear-gradient(135deg,#2563eb,#9333ea); box-shadow: 0 10px 28px rgba(37,99,235,.35); transition: 0.2s; }
.big-btn:hover, .small-btn:hover { transform: scale(1.05); }
.small-btn { padding: 9px 14px; font-size: 13px; }
.danger { background: #ef4444; box-shadow: 0 5px 15px rgba(239,68,68,0.4); }
.green { background: #16a34a; box-shadow: 0 5px 15px rgba(22,163,74,0.4); }
.gold { background: #eab308; color: #000; box-shadow: 0 5px 15px rgba(234,179,8,0.4); }

/* =========================================================
   2. PERFECT RESPONSIVE BOARD SIZING
   ========================================================= */
.game { display: none; grid-template-columns: minmax(320px, 600px) 1fr; gap: 25px; align-items: start; }
.board-container { width: 100%; display: flex; flex-direction: column; align-items: center; }
.board-wrapper { 
    position: relative; padding: 15px; background: #2a2015; border-radius: 12px; 
    box-shadow: 0 30px 70px rgba(0,0,0,.6); width: 100%; max-width: 600px;
    box-sizing: border-box; 
}
/* Fixed aspect ratio square */
.board { 
    display: grid; grid-template-columns: repeat(8, 1fr); grid-template-rows: repeat(8, 1fr); 
    width: 100%; aspect-ratio: 1; border: 4px solid #1a140d; border-radius: 4px; 
    overflow: hidden; transition: transform 0.6s ease; background: #b58863;
}
.flipped { transform: rotate(180deg); }
.flipped .sq span { transform: rotate(180deg); display: inline-block; }

/* Fixed piece sizing */
.sq { display: flex; align-items: center; justify-content: center; cursor: pointer; user-select: none; position: relative; }
.light { background: #f0d9b5; }
.dark { background: #b58863; }
.sq span { 
    font-size: min(10vw, 42px); /* Relative to screen size, caps at 42px */
    line-height: 1; 
    transition: all 0.2s ease;
}

/* =========================================================
   3. HIGH-CONTRAST PIECES & HUD
   ========================================================= */
.piece-w { color: #ffffff !important; text-shadow: 0 4px 6px rgba(0,0,0,0.9), 0 -1px 2px #000, 1px 0 2px #000, -1px 0 2px #000 !important; }
.piece-b { color: #000000 !important; text-shadow: 0 3px 6px rgba(255,255,255,0.7), 0 -1px 2px #fff, 1px 0 2px #fff, -1px 0 2px #fff !important; }
.blindfold { opacity: 0 !important; }

.selected { outline: 5px solid #38bdf8; outline-offset: -5px; z-index: 2;}
.hint:after { content: ""; width: 28%; height: 28%; border-radius: 50%; background: rgba(34,197,94,.75); position: absolute; }
.capture:after { content: ""; inset: 8%; border: 6px solid rgba(239,68,68,.85); border-radius: 50%; position: absolute; }
.last-move { background: rgba(250, 204, 21, 0.5) !important; }
.best-hint { outline: 5px solid #22c55e; outline-offset: -5px; z-index: 3; background: rgba(34,197,94,0.4) !important; }
.in-check { background: radial-gradient(circle, rgba(239, 68, 68, 0.9) 0%, transparent 70%) !important; }
.status { font-weight: 800; color: #facc15; margin-bottom: 10px; font-size: 18px; text-transform: uppercase; letter-spacing: 1px;}
.piece-tray { display: grid; grid-template-columns: repeat(6,1fr); gap: 8px; margin-bottom: 15px;}
.tray-piece { background: rgba(255,255,255,.08); border: 1px solid rgba(255,255,255,.12); border-radius: 12px; font-size: 30px; padding: 8px; cursor: pointer; transition: 0.2s; text-align:center; }
.tray-piece.active { background: #2563eb; transform: scale(1.1); border-color:#60a5fa;}
.hidden { display: none !important; }

/* Move History & Dashboard */
.history-box { height: 130px; overflow-y: auto; background: rgba(0,0,0,0.5); border: 1px solid rgba(255,255,255,0.1); border-radius: 10px; padding: 10px; font-family: monospace; font-size: 13px; color: #94a3b8; display: grid; grid-template-columns: 30px 1fr 1fr; gap: 5px; align-content: start; margin-bottom: 15px; }
.history-row { display: contents; }
.history-num { color: #475569; font-weight: bold; }
.history-move { color: #cbd5e1; }
.graveyard { min-height: 35px; background: rgba(0,0,0,0.3); border-radius: 8px; padding: 5px 10px; display: flex; flex-wrap: wrap; gap: 5px; align-items: center; font-size: 22px; width: 100%; box-sizing: border-box; margin-bottom: 10px;}

.dash-table { width: 100%; border-collapse: collapse; margin-top: 15px; font-size: 14px; text-align: left; }
.dash-table th, .dash-table td { border-bottom: 1px solid rgba(255,255,255,0.1); padding: 10px; }
.dash-table th { color: #94a3b8; font-weight: bold; }

/* GUI Modals */
.modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.85); z-index: 9999; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(5px); }
.modal-box { background: #0f172a; border: 2px solid #3b82f6; border-radius: 20px; padding: 30px; text-align: center; max-width: 400px; width: 90%; box-shadow: 0 20px 60px rgba(0,0,0,0.8); }
.modal-box h2 { margin-top: 0; font-size: 24px; background: linear-gradient(90deg,#60a5fa,#c084fc); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }

.coords-x { display: flex; width: 100%; justify-content: space-around; font-size: 12px; color: #a3a3a3; font-weight: bold; margin-top: 5px;}
.coords-y { position: absolute; left: 2px; top: 15px; height: calc(100% - 30px); display: flex; flex-direction: column; justify-content: space-around; font-size: 12px; color: #a3a3a3; font-weight: bold; }

@media(max-width:800px) { .game { grid-template-columns: 1fr; } .chess-wrap { padding: 10px; margin-top: 20px;} }
</style>
</head>
<body>
<style>
/* === UNIVERSAL SIDEBAR (injected — this page had no navigation drawer before) === */
#globalMenuBtn { position: fixed; top: 14px; left: 14px; z-index: 999997; width: 42px; height: 42px; border-radius: 50%; border: none; background: var(--primary, #8b5cf6); color: #fff; font-size: 18px; display: flex; align-items: center; justify-content: center; cursor: pointer; box-shadow: 0 4px 14px rgba(0,0,0,0.25); }
#overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999998; display: none; opacity: 0; transition: 0.3s; }
#overlay.active { display: block; opacity: 1; }
.sidebar { position: fixed; top: 0; left: -300px; width: 280px; height: 100%; background: var(--bg-surface, #ffffff); z-index: 999999; transition: left 0.3s ease; box-shadow: 4px 0 25px rgba(0,0,0,0.3); padding: 20px 14px; box-sizing: border-box; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; }
.sidebar.active { left: 0; }
.sidebar button { display: block; width: 100%; text-align: left; padding: 12px 14px; border-radius: 10px; border: none; background: transparent; color: var(--text-main, #1e293b); font-size: 14.5px; font-weight: 600; cursor: pointer; }
.sidebar button:hover { background: var(--border-light, rgba(139,92,246,0.1)); }
.sidebar-close-btn { color: #ef4444 !important; font-weight: 800 !important; margin-bottom: 10px; border: 1px solid rgba(239,68,68,0.3) !important; }
</style>
<button id="globalMenuBtn" onclick="toggleSidebar()">☰</button>
<div class="overlay" id="overlay" onclick="toggleSidebar()"></div>
<div class="sidebar" id="sidebar" style="overflow-y:auto;">
  <button class="sidebar-close-btn" onclick="toggleSidebar()">✖ Close Menu</button>
  <button onclick="window.location.href='index.html'">🏠 Dashboard</button>
  <button onclick="window.location.href='lens.html'">✨ Lens Studio</button>
  <button onclick="window.location.href='books.html'">📚 Book Deep Study</button>
  <button onclick="window.location.href='maths.html'">🧮 Math Solver</button>
  <button onclick="window.location.href='search.html'">🔎 Deep Search</button>
  <button onclick="window.location.href='downloader.html'">📥 Video Downloader</button>
  <button onclick="window.location.href='board.html'">📋 Whiteboard</button>
  <button onclick="window.location.href='clone.html'">📑 Website Cloner</button>
  <button onclick="window.location.href='runhtml.html'">🌐 Write HTML</button>
  <button onclick="window.location.href='youtube.html'">▶️ YouTube Search</button>
  <button onclick="window.location.href='managequiz.html'">⚙️ Manage Quiz</button>
  <button onclick="window.location.href='tutor.html'">👨‍🏫 AI Tutor</button>
  <button onclick="window.location.href='quiz.html'">📝 Take a Quiz!</button>
  <button onclick="window.location.href='book_quiz.html'">📝 Take a Book Quiz!</button>
  <button onclick="window.location.href='tables.html'">🔢 Maths Table</button>
  <button onclick="window.location.href='coding.html'">💻 AI Coding</button>
  <button onclick="window.location.href='chess.html'" style="border-left: 4px solid var(--primary); color: var(--primary); background: var(--border-light);">♟️ Chess AI</button>
  <button onclick="window.location.href='translator.html'">🎙️ Text Translator</button>
  <button onclick="window.location.href='image.html'">🖼️ Image Translator</button>
  <button onclick="window.location.href='create.html'">🎨 Image Creator</button>
  <button onclick="window.location.href='qa.html'">📚 Document Q&A</button>
  <button onclick="window.location.href='history.html'">🕒 History & Downloads</button>
  <button onclick="window.location.href='storage.html'">📂 Storage</button>
  <button onclick="window.location.href='hub.html'">🛰️ HF Command Center</button>
  <button onclick="window.location.href='live.html'">🗣️ Gemini Live</button>
</div>
<script>
function toggleSidebar() { const s = document.getElementById("sidebar"), o = document.getElementById("overlay"); const a = !s.classList.contains("active"); s.classList.toggle("active", a); o.classList.toggle("active", a); }
</script>


<main class="chess-wrap">
    <section id="home" class="hero">
        <h1>♟️ Chess AI Pro</h1>
        <p style="color:#cbd5e1; font-size: 15px;">Alpha-Beta Engine, Smart Scaling, FEN Support, and Match History!</p>
        
        <!-- MAIN DASHBOARD -->
        <div class="menu-grid">
            <div class="panel">
                <h2>Standard Match</h2>
                <div style="display:flex; gap:10px; margin-bottom:15px;">
                    <select id="playerColor" style="width:100%; padding:10px; border-radius:8px; background:rgba(0,0,0,0.4); color:white; border:1px solid #3b82f6; font-weight:bold; font-size:14px;">
                        <option value="w">⬜ Play as White</option>
                        <option value="b">⬛ Play as Black</option>
                    </select>
                </div>
                <label style="display:flex; justify-content:space-between;">
                    <span>AI Level: <b id="lvlValue" style="color:#facc15;">35</b></span>
                    <span id="lvlTitle" style="color:#38bdf8; font-weight:bold;">PRO</span>
                </label>
                <input id="level" type="range" min="1" max="100" value="35" oninput="updateLevelUI(this.value)" style="width:100%;accent-color:#a855f7; margin: 15px 0;">
                <button class="big-btn" style="width:100%; margin-bottom:10px;" onclick="startGame(false)">▶ Start Game</button>
                <button class="small-btn gold" style="width:100%;" onclick="loadSavedGame()">💾 Load Saved Game</button>
            </div>
            
            <div class="panel">
                <h2>Custom Organizer</h2>
                <p style="font-size: 13px; color: #94a3b8; margin-bottom: 10px;">Place pieces yourself or import FEN!</p>
                <button class="big-btn green" style="width:100%; margin-bottom:10px;" onclick="openBuilder()">🛠️ Build Board</button>
                <button class="small-btn" style="width:100%; background:#8b5cf6;" onclick="importFEN()">📥 Import FEN String</button>
            </div>
            
            <div class="panel" style="grid-column: 1 / -1;">
                <h2 style="color:#38bdf8; margin-bottom: 5px;">📜 Match History Dashboard</h2>
                <div style="display:flex; justify-content:space-between; margin-bottom: 10px;">
                    <p style="font-size: 12px; color: #94a3b8;">Your recent games against the AI.</p>
                    <button class="small-btn" style="background:#475569;" onclick="downloadPGN()">📥 Download PGN</button>
                </div>
                <div style="overflow-x:auto;">
                    <table class="dash-table">
                        <thead><tr><th>Result</th><th>AI Level</th><th>Turns</th><th>Type</th><th>Action</th></tr></thead>
                        <tbody id="historyTableBody">
                            <tr><td colspan="5" style="text-align:center; color:#64748b;">No matches played yet.</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </section>

    <!-- GAME BOARD -->
    <section id="game" class="game">
        <div class="board-container">
            <div style="display:flex; justify-content:space-between; width:100%; margin-bottom:5px;">
                <span id="materialAdvantage" style="font-weight:bold; color:#cbd5e1; font-size:14px;">Material: Even</span>
            </div>
            
            <div id="aiGraveyard" class="graveyard" title="Pieces AI has lost"></div>
            
            <div class="board-wrapper">
                <div class="coords-y" id="coordY"><span>8</span><span>7</span><span>6</span><span>5</span><span>4</span><span>3</span><span>2</span><span>1</span></div>
                <div id="board" class="board"></div>
                <div class="coords-x" id="coordX"><span>a</span><span>b</span><span>c</span><span>d</span><span>e</span><span>f</span><span>g</span><span>h</span></div>
            </div>
            
            <div id="playerGraveyard" class="graveyard" style="margin-top:10px; margin-bottom:0;"></div>
        </div>

        <aside class="panel" style="display:flex; flex-direction:column; gap:12px;">
            <div style="display:flex; justify-content:space-between; align-items:center;">
                <div id="status" class="status">Your move</div>
                <button id="muteBtn" onclick="toggleMute()" style="background:transparent; border:none; font-size:20px; cursor:pointer;">🔊</button>
            </div>
            
            <div style="font-size:12px; color:#cbd5e1; display:flex; justify-content:space-between;">
                <span>Turns: <b id="turnCounter" style="color:white;">0</b></span>
                <span id="aiThinkingStatus" style="color:#f97316; font-weight:bold; display:none;">🤖 AI is thinking...</span>
            </div>

            <div id="moveLog" class="history-box"></div>
            
            <div id="builderTools" class="hidden" style="background:rgba(0,0,0,0.3); padding:15px; border-radius:15px;">
                <h3 style="margin-top:0; color:#38bdf8;">Custom Organizer</h3>
                <div class="piece-tray" id="tray"></div>
                <button class="small-btn green" style="width:100%; margin-top: 10px;" onclick="validateCustomBoard()">▶ Start Match With AI</button>
            </div>

            <div style="display:grid; grid-template-columns:1fr 1fr; gap:10px;">
                <button class="small-btn" id="undoBtn" onclick="undoMove()">⏪ Undo Move</button>
                <button class="small-btn gold" id="hintBtn" onclick="showHint()">💡 Hint</button>
            </div>
            
            <!-- MEGA BUTTON ROW -->
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-top: 10px;">
                <button class="small-btn blue" onclick="copyFEN()">📋 Copy FEN</button>
                <button class="small-btn green" onclick="document.getElementById('board').classList.toggle('flipped')">🔄 Flip Board</button>
                <button class="small-btn danger" onclick="confirmResign()">🏳️ Resign</button>
                <button class="small-btn gold" onclick="offerDraw()">🤝 Offer Draw</button>
                <button class="small-btn" style="background:#8b5cf6;" onclick="document.querySelectorAll('.sq span').forEach(s => s.classList.toggle('blindfold'))">👁️ Blindfold</button>
                <button class="small-btn blue" onclick="saveGame()">💾 Save Game</button>
            </div>

            <button class="small-btn danger" onclick="confirmResetPrompt()" style="margin-top: 10px;">🔄 Restart Match</button>
            <button class="small-btn" style="background:#475569;" onclick="confirmHomePrompt()">🏠 Home Screen</button>
        </aside>
    </section>
</main>

<!-- CUSTOM GUI MODALS (NO BROWSER POPUPS ALLOWED) -->
<div id="guiModal" class="modal-overlay hidden">
    <div class="modal-box">
        <h2 id="guiTitle">Alert</h2>
        <p id="guiDesc" style="color:#cbd5e1; font-size:14px; margin-bottom:20px;"></p>
        <input type="text" id="guiInput" class="hidden" style="width:90%; padding:10px; margin-bottom:20px; border-radius:8px; background:rgba(0,0,0,0.4); color:white; border:1px solid #3b82f6;">
        <div style="display:flex; gap:10px; justify-content:center;">
            <button class="big-btn" id="guiCancelBtn" style="flex:1; background:#475569;">Cancel</button>
            <button class="big-btn green" id="guiConfirmBtn" style="flex:1;">OK</button>
        </div>
    </div>
</div>

<div id="botLevelModal" class="modal-overlay hidden">
    <div class="modal-box">
        <h2>Set AI Difficulty</h2>
        <input type="range" min="1" max="100" value="50" id="customLvl" oninput="document.getElementById('cLvlTxt').textContent=this.value" style="width:100%;accent-color:#a855f7;">
        <p style="font-size: 18px; font-weight:bold;">Level: <span id="cLvlTxt" style="color:#facc15;">50</span> / 100</p>
        <div style="display:flex; gap:10px; margin-top:20px;">
            <button class="big-btn" style="flex:1; background:#475569;" onclick="document.getElementById('botLevelModal').classList.add('hidden')">Cancel</button>
            <button class="big-btn green" style="flex:1;" onclick="startCustomPlay()">▶ Start</button>
        </div>
    </div>
</div>

<div id="gameOverModal" class="modal-overlay hidden">
    <div class="modal-box">
        <h2 id="goTitle" style="font-size: 35px;">You Win!</h2>
        <p id="goDesc" style="color:#cbd5e1; font-size:16px; margin-bottom:25px;">Checkmate delivered.</p>
        <div style="display:flex; flex-direction:column; gap:10px;">
            <button class="big-btn green" onclick="document.getElementById('gameOverModal').classList.add('hidden'); confirmResetPrompt(true);">🔄 Play Again</button>
            <button class="big-btn" onclick="document.getElementById('gameOverModal').classList.add('hidden'); confirmHomePrompt(true);">🏠 Home Screen</button>
            <button class="small-btn danger" onclick="document.getElementById('gameOverModal').classList.add('hidden')">✖ View Board</button>
        </div>
    </div>
</div>

<script>

// =========================================================

// CUSTOM GUI HANDLER

// =========================================================

let guiCallback = null;

function showGUI(title, desc, type, callback) {

    document.getElementById('guiTitle').textContent = title;

    document.getElementById('guiDesc').textContent = desc;

    const input = document.getElementById('guiInput');

    const cancelBtn = document.getElementById('guiCancelBtn');

    const confirmBtn = document.getElementById('guiConfirmBtn');

    

    input.classList.add('hidden');

    cancelBtn.classList.add('hidden');

    input.value = '';



    if (type === 'prompt') {

        input.classList.remove('hidden');

        cancelBtn.classList.remove('hidden');

        input.focus();

    } else if (type === 'confirm') {

        cancelBtn.classList.remove('hidden');

    }



    document.getElementById('guiModal').classList.remove('hidden');

    guiCallback = callback;

}



document.getElementById('guiCancelBtn').onclick = () => {

    document.getElementById('guiModal').classList.add('hidden');

    if (guiCallback) guiCallback(null);

};



document.getElementById('guiConfirmBtn').onclick = () => {

    document.getElementById('guiModal').classList.add('hidden');

    let val = document.getElementById('guiInput').classList.contains('hidden') ? true : document.getElementById('guiInput').value;

    if (guiCallback) guiCallback(val);

};



// =========================================================

// AUDIO ENGINE

// =========================================================

const AudioCtx = window.AudioContext || window.webkitAudioContext;

let aCtx = null, isMuted = false;



function toggleMute() { isMuted = !isMuted; document.getElementById('muteBtn').textContent = isMuted ? '🔇' : '🔊'; }



function playTone(f1, f2, type, dur, vol=0.1) {

    if(isMuted) return;

    if(!aCtx) aCtx = new AudioCtx();

    if(aCtx.state === 'suspended') aCtx.resume();

    let osc = aCtx.createOscillator(), gain = aCtx.createGain();

    osc.type = type; osc.frequency.setValueAtTime(f1, aCtx.currentTime);

    if(f2) osc.frequency.exponentialRampToValueAtTime(f2, aCtx.currentTime + dur);

    gain.gain.setValueAtTime(vol, aCtx.currentTime); gain.gain.exponentialRampToValueAtTime(0.01, aCtx.currentTime + dur);

    osc.connect(gain); gain.connect(aCtx.destination); osc.start(); osc.stop(aCtx.currentTime + dur);

}

function playSound(event) {

    if(event==='move') playTone(300, 400, 'sine', 0.15, 0.2);

    if(event==='capture') playTone(150, 50, 'square', 0.2, 0.3);

    if(event==='check') playTone(600, 400, 'sawtooth', 0.3, 0.2);

    if(event==='castle') playTone(350, 450, 'triangle', 0.2, 0.2);

    if(event==='win') { playTone(400, 600, 'sine', 0.2, 0.2); setTimeout(()=>playTone(600, 800, 'sine', 0.4, 0.2), 200); }

    if(event==='lose') { playTone(300, 150, 'sawtooth', 0.3, 0.2); setTimeout(()=>playTone(150, 50, 'sawtooth', 0.5, 0.2), 300); }

}



// =========================================================

// CORE CHESS LOGIC

// =========================================================

const U={P:'♙',N:'♘',B:'♗',R:'♖',Q:'♕',K:'♔',p:'♟',n:'♞',b:'♝',r:'♜',q:'♛',k:'♚'};

const Vals={P:1,N:3,B:3,R:5,Q:9,p:-1,n:-3,b:-3,r:-5,q:-9,K:0,k:0};

let B=[], turn='w', sel=null, hints=[], bestHint=null, aiLevel=35, builder=false, chosen='P', gameOver=false;

let lastMove = null, historyStack = [], moveLogArray = [], pColor = 'w', moveCounter = 0;

let wCaptured = [], bCaptured = [];

let rights = {wK:true, wQ:true, bK:true, bQ:true};

let matchDash = JSON.parse(localStorage.getItem('chessDashHistory')) || [];



function updateLevelUI(val) {

    document.getElementById('lvlValue').textContent = val;

    let title = val < 34 ? "NOOB" : (val < 67 ? "PRO" : "GOD");

    document.getElementById('lvlTitle').textContent = title;

    document.getElementById('lvlTitle').style.color = val < 34 ? "#4ade80" : (val < 67 ? "#38bdf8" : "#f43f5e");

}



function init() { B='rnbqkbnrpppppppp................................PPPPPPPPRNBQKBNR'.split(''); rights={wK:true,wQ:true,bK:true,bQ:true}; }

function xy(i) { return[i%8,Math.floor(i/8)]; }

function idx(x,y) { return y*8+x; }

function color(p) { return p=='.'?null:p===p.toUpperCase()?'w':'b'; }

function enemy(p,c) { return p!=='.'&&color(p)!==c; }



function isAttacked(index, defenderColor, br=B) {

    let attackerColor = defenderColor === 'w' ? 'b' : 'w';

    for(let i=0; i<64; i++) {

        if(color(br[i]) === attackerColor) {

            let m = rawMoves(i, br); 

            if(m.includes(index)) return true;

        }

    }

    return false;

}



function filterLegal(rawMovesList, fromIdx, br) {

    let myColor = color(br[fromIdx]);

    return rawMovesList.filter(toIdx => {

        let tempB = simMake(br, fromIdx, toIdx);

        let kChar = myColor === 'w' ? 'K' : 'k';

        let kIdx = tempB.indexOf(kChar);

        if(kIdx === -1) return false; 

        return !isAttacked(kIdx, myColor, tempB); 

    });

}



function calculateMaterial() {

    let score = 0;

    B.forEach(p => { if(p !== '.') score += Vals[p]; });

    let text = score === 0 ? "Material: Even" : (score > 0 ? `White +${score}` : `Black +${Math.abs(score)}`);

    document.getElementById('materialAdvantage').textContent = text;

}



function updateHUD() {

    document.getElementById('turnCounter').textContent = moveCounter;

    calculateMaterial();

    

    let aiGrave = pColor === 'w' ? wCaptured : bCaptured;

    let plyGrave = pColor === 'w' ? bCaptured : wCaptured;

    document.getElementById('aiGraveyard').innerHTML = aiGrave.map(p => `<span class="${p===p.toUpperCase()?'piece-w':'piece-b'}">${U[p]}</span>`).join('');

    document.getElementById('playerGraveyard').innerHTML = plyGrave.map(p => `<span class="${p===p.toUpperCase()?'piece-w':'piece-b'}">${U[p]}</span>`).join('');

    

    let logHtml = '';

    for(let i=0; i<moveLogArray.length; i+=2) {

        logHtml += `<div class="history-row"><span class="history-num">${Math.floor(i/2)+1}.</span><span class="history-move">${moveLogArray[i]||''}</span><span class="history-move">${moveLogArray[i+1]||''}</span></div>`;

    }

    const ml = document.getElementById('moveLog'); ml.innerHTML = logHtml; ml.scrollTop = ml.scrollHeight;

}



function getNotation(from, to, p, captured, isCastle) {

    if(isCastle === 'K') return "O-O"; if(isCastle === 'Q') return "O-O-O";

    const f="abcdefgh", r="87654321";

    let pStr = p.toUpperCase()==='P' ? (captured?f[from%8]:'') : p.toUpperCase();

    return `${pStr}${captured?'x':''}${f[to%8]}${r[Math.floor(to/8)]}`;

}



function render() {

    board.innerHTML='';

    let bKIdx = B.indexOf('k'), wKIdx = B.indexOf('K');

    let bCheck = bKIdx !== -1 && isAttacked(bKIdx, 'b');

    let wCheck = wKIdx !== -1 && isAttacked(wKIdx, 'w');



    for(let i=0; i<64; i++) {

        let s = document.createElement('div');

        s.className = 'sq ' + ((xy(i)[0]+xy(i)[1])%2 ? 'dark' : 'light');

        if(lastMove && (i === lastMove.from || i === lastMove.to)) s.classList.add('last-move');

        if(bestHint && (i === bestHint.from || i === bestHint.to)) s.classList.add('best-hint');

        if(sel === i) s.classList.add('selected');

        if(hints.includes(i)) s.classList.add(B[i]==='.' ? 'hint' : 'capture');

        if(bCheck && i === bKIdx) s.classList.add('in-check');

        if(wCheck && i === wKIdx) s.classList.add('in-check');



        if(B[i] !== '.') s.innerHTML = `<span class="${B[i]===B[i].toUpperCase()?'piece-w':'piece-b'}">${U[B[i]]}</span>`;

        s.onclick = () => clickSq(i);

        board.appendChild(s);

    }

    updateHUD();

}



function rawMoves(i, br=B) {

    let p=br[i], c=color(p);

    if(!c) return [];

    let [x,y]=xy(i), m=[], add=(a,b)=>{if(a>=0&&a<8&&b>=0&&b<8){let t=idx(a,b);if(br[t]==='.'||enemy(br[t],c))m.push(t)}};

    let low=p.toLowerCase();

    

    if(low==='p'){let d=c==='w'?-1:1,st=c==='w'?6:1;if(br[idx(x,y+d)]==='.') {add(x,y+d); if(y===st&&br[idx(x,y+2*d)]==='.') add(x,y+2*d)};for(let dx of[-1,1])if(x+dx>=0&&x+dx<8&&enemy(br[idx(x+dx,y+d)],c))m.push(idx(x+dx,y+d))}

    if(low==='n')[[1,2],[2,1],[-1,2],[-2,1],[1,-2],[2,-1],[-1,-2],[-2,-1]].forEach(d=>add(x+d[0],y+d[1]));

    if('brq'.includes(low)){let dirs=[];if('rq'.includes(low))dirs.push([1,0],[-1,0],[0,1],[0,-1]);if('bq'.includes(low))dirs.push([1,1],[-1,1],[1,-1],[-1,-1]);dirs.forEach(d=>{let a=x+d[0],b=y+d[1];while(a>=0&&a<8&&b>=0&&b<8){let t=idx(a,b);if(br[t]==='.')m.push(t);else{if(enemy(br[t],c))m.push(t);break;}a+=d[0];b+=d[1]}})}

    

    if(low==='k') {

        for(let a=-1;a<=1;a++)for(let b=-1;b<=1;b++)if(a||b)add(x+a,y+b);

        if(c==='w' && i===60 && !builder) {

            if(rights.wK && br[61]==='.' && br[62]==='.' && !isAttacked(60,'w',br) && !isAttacked(61,'w',br) && !isAttacked(62,'w',br)) m.push(62);

            if(rights.wQ && br[59]==='.' && br[58]==='.' && br[57]==='.' && !isAttacked(60,'w',br) && !isAttacked(59,'w',br) && !isAttacked(58,'w',br)) m.push(58);

        }

        if(c==='b' && i===4 && !builder) {

            if(rights.bK && br[5]==='.' && br[6]==='.' && !isAttacked(4,'b',br) && !isAttacked(5,'b',br) && !isAttacked(6,'b',br)) m.push(6);

            if(rights.bQ && br[3]==='.' && br[2]==='.' && br[1]==='.' && !isAttacked(4,'b',br) && !isAttacked(3,'b',br) && !isAttacked(2,'b',br)) m.push(2);

        }

    }

    return m;

}



function allLegal(c, br=B) {

    let r=[];

    br.forEach((p,i)=>{ if(color(p)===c) filterLegal(rawMoves(i,br), i, br).forEach(to=>r.push([i,to])) });

    return r;

}



function simMake(br, f, t) {

    let nb = [...br]; nb[t] = nb[f]; nb[f] = '.';

    if(nb[t]==='P'&&t<8) nb[t]='Q'; if(nb[t]==='p'&&t>55) nb[t]='q';

    if(nb[t]==='K'&&f===60&&t===62) { nb[61]='R'; nb[63]='.'; } 

    if(nb[t]==='K'&&f===60&&t===58) { nb[59]='R'; nb[56]='.'; } 

    if(nb[t]==='k'&&f===4&&t===6) { nb[5]='r'; nb[7]='.'; } 

    if(nb[t]==='k'&&f===4&&t===2) { nb[3]='r'; nb[0]='.'; } 

    return nb;

}



function make(a) {

    bestHint = null;

    let pMoved = B[a[0]], pCaptured = B[a[1]], captured = pCaptured !== '.';

    let isCastle = false;



    if(captured) { color(pCaptured)==='w' ? bCaptured.push(pCaptured) : wCaptured.push(pCaptured); }



    B = simMake(B, a[0], a[1]);

    

    if(pMoved.toLowerCase()==='k' && Math.abs(a[0]-a[1])===2) isCastle = a[1]>a[0] ? 'K' : 'Q';



    if(pMoved==='K') { rights.wK=false; rights.wQ=false; }

    if(pMoved==='k') { rights.bK=false; rights.bQ=false; }

    if(a[0]===63||a[1]===63) rights.wK=false; if(a[0]===56||a[1]===56) rights.wQ=false;

    if(a[0]===7||a[1]===7) rights.bK=false; if(a[0]===0||a[1]===0) rights.bQ=false;



    moveLogArray.push(getNotation(a[0], a[1], pMoved, captured, isCastle));

    lastMove = {from: a[0], to: a[1]};

    if(turn === 'w') moveCounter++;

    

    if(isCastle) playSound('castle');

    else if(captured) playSound('capture');

    else playSound('move');

}



// =========================================================

// 3. GAME PLAY & AI ENGINE (NOOB AVOIDS CAPTURING)

// =========================================================

function clickSq(i) {

    if(gameOver || builder || turn !== pColor) {

        if(builder) { B[i] = chosen; render(); }

        return;

    }

    if(sel === null) {

        if(color(B[i]) === pColor) { sel = i; hints = filterLegal(rawMoves(i), i, B); render(); }

    } else if (hints.includes(i)) {

        historyStack.push({ b: [...B], turn: pColor, last: lastMove ? {...lastMove} : null, log: [...moveLogArray], wCap: [...wCaptured], bCap: [...bCaptured], moves: moveCounter, r: {...rights} });

        make([sel,i]); sel = null; hints = []; turn = pColor === 'w' ? 'b' : 'w'; 

        

        if(isAttacked(B.indexOf(turn==='w'?'K':'k'), turn)) { playSound('check'); moveLogArray[moveLogArray.length-1] += '+'; }

        render();

        

        document.getElementById('aiThinkingStatus').style.display = 'block'; 

        

        // STRICT TIMINGS based on requested rules

        let thinkDelay = 1000;

        if (aiLevel < 34) {

            thinkDelay = Math.floor(Math.random() * 1000) + 3000; // NOOB: 3-4s

        } else if (aiLevel < 67) {

            thinkDelay = Math.floor(Math.random() * 1000) + 2000; // PRO: 2-3s

        } else {

            thinkDelay = Math.floor(Math.random() * 1000) + 1000; // GOD: 1-2s

        }

        

        setTimeout(aiMove, thinkDelay); 

        

    } else { sel = null; hints = []; render(); }

}



function undoMove() {

    if(historyStack.length === 0 || builder || gameOver) return;

    let s = historyStack.pop();

    B = s.b; turn = s.turn; lastMove = s.last; moveLogArray = s.log; wCaptured = s.wCap; bCaptured = s.bCap; moveCounter = s.moves; rights = s.r;

    bestHint = null; gameOver = false; document.getElementById('gameOverModal').classList.add('hidden');

    status.textContent = 'Your move'; render();

}



function evaluateBoard(br, c) {

    let v={P:10,N:30,B:30,R:50,Q:90,K:900,p:-10,n:-30,b:-30,r:-50,q:-90,k:-900};

    let center = [27,28,35,36]; let s = 0;

    for(let i=0; i<64; i++) {

        if(br[i]==='.') continue;

        let val = v[br[i]];

        if(br[i].toLowerCase()!=='k' && br[i].toLowerCase()!=='r' && center.includes(i)) val += (val>0?1:-1); 

        s += val;

    }

    return c==='w' ? s : -s;

}



function getBestMove(br, evalColor, lvl) {

    let myMoves = allLegal(evalColor, br);

    if(!myMoves.length) return null;

    

    // Level 1-33 NOOB MODE: Play randomly, actively avoid capturing if level is very low

    if(lvl < 34) {

        if(lvl < 15) {

            let nonCaptures = myMoves.filter(m => br[m[1]] === '.');

            if (nonCaptures.length > 0) return nonCaptures[Math.floor(Math.random() * nonCaptures.length)];

        }

        return myMoves[Math.floor(Math.random()*myMoves.length)];

    }



    let bestScore = -Infinity; let bestChoices = [];

    myMoves.sort((a, b) => (br[b[1]] !== '.' ? 1 : 0) - (br[a[1]] !== '.' ? 1 : 0));



    for(let m of myMoves) {

        let sim1 = simMake(br, m[0], m[1]);

        let score = evaluateBoard(sim1, evalColor);



        // Alpha-Beta Pruning implementation to stop freezing on GOD levels

        if(lvl > 66) {

            let oppColor = evalColor==='w'?'b':'w';

            let oppMoves = allLegal(oppColor, sim1);

            let worstOppScore = Infinity;

            

            if(oppMoves.length === 0) { 

                score = 99999; 

            } else {

                let maxOpponentChecks = lvl === 100 ? 5 : oppMoves.length; 

                oppMoves.sort((a, b) => (sim1[b[1]] !== '.' ? 1 : 0) - (sim1[a[1]] !== '.' ? 1 : 0));



                for(let i = 0; i < Math.min(maxOpponentChecks, oppMoves.length); i++) {

                    let om = oppMoves[i];

                    let sim2 = simMake(sim1, om[0], om[1]);

                    let oppS = evaluateBoard(sim2, evalColor); 

                    if(oppS < worstOppScore) worstOppScore = oppS;

                }

                score = worstOppScore;

            }

        }



        if(score > bestScore) { bestScore = score; bestChoices = [m]; }

        else if(score === bestScore) { bestChoices.push(m); }

    }

    return bestChoices[Math.floor(Math.random()*bestChoices.length)];

}



function showHint() {

    if(gameOver || turn !== pColor || builder) return;

    let m = getBestMove(B, pColor, 100); 

    if(m) { bestHint = {from: m[0], to: m[1]}; render(); }

}



function aiMove() {

    document.getElementById('aiThinkingStatus').style.display = 'none';

    let aiColor = pColor === 'w' ? 'b' : 'w';

    let m = getBestMove(B, aiColor, aiLevel);

    

    if(!m) {

        if(isAttacked(B.indexOf(aiColor === 'w'?'K':'k'), aiColor)) return end('CHECKMATE! You Win!', true);

        else return end('Stalemate! Game is a Draw.', true); 

    }

    

    make(m); turn = pColor;

    

    let isCheck = isAttacked(B.indexOf(pColor==='w'?'K':'k'), pColor);

    if(isCheck) { playSound('check'); moveLogArray[moveLogArray.length-1] += '+'; }

    render();

    

    if(!allLegal(pColor).length) {

        if(isCheck) return end('CHECKMATE! The AI Wins!', false);

        else return end('Stalemate! Game is a Draw.', true);

    }

    status.textContent = isCheck ? '⚠️ CHECK! Defend your King!' : 'Your move';

}



function end(msg, isWin) {

    gameOver = true; status.textContent = msg; playSound(isWin ? 'win' : 'lose');

    document.getElementById('goTitle').textContent = isWin ? "Victory!" : (msg.includes('Draw') ? "Draw!" : "Defeat!");

    document.getElementById('goTitle').style.color = isWin ? "#10b981" : (msg.includes('Draw') ? "#facc15" : "#ef4444");

    document.getElementById('goDesc').textContent = msg;

    document.getElementById('gameOverModal').classList.remove('hidden');

    saveMatchToDashboard(isWin ? "Win" : (msg.includes('Draw') ? "Draw" : "Loss"));

}



// =========================================================

// 4. SAVE/LOAD, DASHBOARD & FEN

// =========================================================

function saveGame() {

    const gameState = { B, turn, pColor, lastMove, moveLogArray, wCaptured, bCaptured, moveCounter, rights, aiLevel };

    localStorage.setItem('chessSaveGame', JSON.stringify(gameState));

    showGUI('Success', 'Game Saved Successfully!', 'alert');

}



function loadSavedGame() {

    const saved = JSON.parse(localStorage.getItem('chessSaveGame'));

    if(!saved) return showGUI('Error', 'No saved game found!', 'alert');

    B = saved.B; turn = saved.turn; pColor = saved.pColor; lastMove = saved.lastMove; moveLogArray = saved.moveLogArray; wCaptured = saved.wCaptured; bCaptured = saved.bCaptured; moveCounter = saved.moveCounter; rights = saved.rights; aiLevel = saved.aiLevel;

    builder = false; gameOver = false;

    document.getElementById('home').style.display = 'none'; document.getElementById('game').style.display = 'grid';

    render();

    if(turn !== pColor) { document.getElementById('aiThinkingStatus').style.display = 'block'; setTimeout(aiMove, 1000); }

}



function copyFEN() {

    let fen = ""; let empty = 0;

    for(let r=0; r<8; r++) {

        for(let c=0; c<8; c++) {

            let p = B[r*8+c];

            if(p === '.') { empty++; }

            else { if(empty>0) { fen+=empty; empty=0; } fen+=p; }

        }

        if(empty>0) { fen+=empty; empty=0; }

        if(r<7) fen+='/';

    }

    navigator.clipboard.writeText(fen); 

    showGUI('Success', 'FEN Copied to Clipboard!', 'alert');

}



function importFEN() {

    showGUI('Import Board', 'Paste FEN string below:', 'prompt', (fen) => {

        if(!fen) return;

        B = []; let rows = fen.split(' ')[0].split('/');

        if(rows.length !== 8) return showGUI('Error', 'Invalid FEN', 'alert');

        rows.forEach(r => { for(let char of r) { if(!isNaN(char)) { for(let i=0;i<parseInt(char);i++) B.push('.'); } else { B.push(char); } } });

        builder = true; gameOver = false;

        document.getElementById('home').style.display = 'none'; document.getElementById('game').style.display = 'grid';

        document.getElementById('builderTools').classList.remove('hidden');

        render();

    });

}



function downloadPGN() {

    if(!moveLogArray.length) return showGUI('Error', 'No moves to download.', 'alert');

    let pgn = "";

    for(let i=0; i<moveLogArray.length; i+=2) pgn += `${Math.floor(i/2)+1}. ${moveLogArray[i]} ${moveLogArray[i+1]||''}\n`;

    let blob = new Blob([pgn], { type: "text/plain" });

    let a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = "ChessAI_Pro_Match.pgn"; a.click();

}



function saveMatchToDashboard(res) {

    if(moveCounter < 2 && !builder) return; 

    let type = builder ? "Custom" : "Standard";

    matchDash.unshift({res, lvl: aiLevel, turns: moveCounter, type, date: new Date().toLocaleDateString()});

    if(matchDash.length > 10) matchDash.pop();

    localStorage.setItem('chessDashHistory', JSON.stringify(matchDash));

    loadDashboard();

}



function loadDashboard() {

    let html = '';

    if(!matchDash.length) { html = `<tr><td colspan="5" style="text-align:center; color:#64748b;">No matches played yet.</td></tr>`; }

    else {

        matchDash.forEach((m, i) => {

            let color = m.res==='Win' ? '#4ade80' : (m.res==='Loss' ? '#f43f5e' : '#facc15');

            html += `<tr><td style="color:${color};font-weight:bold;">${m.res}</td><td>${m.lvl}</td><td>${m.turns}</td><td>${m.type}</td>

            <td><button style="background:#ef4444;border:none;border-radius:5px;color:white;cursor:pointer;padding:4px 8px;" onclick="delDash(${i})">X</button></td></tr>`;

        });

    }

    document.getElementById('historyTableBody').innerHTML = html;

}

function delDash(i) { matchDash.splice(i,1); localStorage.setItem('chessDashHistory', JSON.stringify(matchDash)); loadDashboard(); }



function startGame(custom) {

    aiLevel = custom ? +document.getElementById('customLvl').value : +document.getElementById('level').value;

    builder = false; gameOver = false; sel = null; hints = []; bestHint = null; lastMove = null; historyStack = []; moveLogArray = []; moveCounter = 0; wCaptured = []; bCaptured = [];

    if(!custom) { init(); pColor = document.getElementById('playerColor').value; } else { pColor = 'w'; }

    turn = 'w'; 

    

    const brd = document.getElementById('board');

    if(pColor === 'b') {

        brd.classList.add('flipped');

        document.getElementById('coordY').innerHTML = `<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span>`;

        document.getElementById('coordX').innerHTML = `<span>h</span><span>g</span><span>f</span><span>e</span><span>d</span><span>c</span><span>b</span><span>a</span>`;

    } else {

        brd.classList.remove('flipped');

        document.getElementById('coordY').innerHTML = `<span>8</span><span>7</span><span>6</span><span>5</span><span>4</span><span>3</span><span>2</span><span>1</span>`;

        document.getElementById('coordX').innerHTML = `<span>a</span><span>b</span><span>c</span><span>d</span><span>e</span><span>f</span><span>g</span><span>h</span>`;

    }



    document.getElementById('home').style.display = 'none'; document.getElementById('game').style.display = 'grid';

    document.getElementById('builderTools').classList.add('hidden'); document.getElementById('undoBtn').classList.remove('hidden'); document.getElementById('hintBtn').classList.remove('hidden');

    render();



    if(pColor === 'b' && !custom) { status.textContent = 'AI is playing White...'; document.getElementById('aiThinkingStatus').style.display = 'block'; setTimeout(aiMove, 600); } 

    else { status.textContent = 'Your move'; }

}



function confirmHomePrompt(force=false) {

    if(!force && !gameOver && !builder && historyStack.length > 0) { 

        showGUI('Warning', 'Exit to Home? Current game will be lost.', 'confirm', (res) => {

            if(res) { document.getElementById('game').style.display = 'none'; document.getElementById('home').style.display = 'block'; loadDashboard(); }

        });

    } else {

        document.getElementById('game').style.display = 'none'; document.getElementById('home').style.display = 'block'; loadDashboard();

    }

}



function confirmResetPrompt(force=false) {

    if(!force && !gameOver && !builder && historyStack.length > 0) { 

        showGUI('Restart', 'Restart the match?', 'confirm', (res) => {

            if(res) { askLevelAndStart(); }

        });

    } else {

        askLevelAndStart();

    }

}



function askLevelAndStart() {

    showGUI('Restart', 'Enter new AI Level (1-100) to make it MORE PRO:', 'prompt', (newLevel) => {

        if(newLevel && !isNaN(newLevel)) {

            aiLevel = Math.max(1, Math.min(100, parseInt(newLevel)));

            document.getElementById('level').value = aiLevel;

            updateLevelUI(aiLevel);

        }

        startGame(builder);

    });

}



function offerDraw() {

    showGUI('Offer Draw', 'AI Refuses your Draw Offer! 🤖 Keep playing.', 'alert');

}



function confirmResign() {

    showGUI('Resign', 'Are you sure you want to resign?', 'confirm', (res) => {

        if(res) { end('You Resigned! AI Wins.', false); }

    });

}



function openBuilder() {

    builder = true; gameOver = false; B = '................................................................'.split('');

    document.getElementById('home').style.display = 'none'; document.getElementById('game').style.display = 'grid';

    document.getElementById('builderTools').classList.remove('hidden'); document.getElementById('undoBtn').classList.add('hidden'); document.getElementById('hintBtn').classList.add('hidden');

    status.textContent = 'Build custom board'; document.getElementById('board').classList.remove('flipped'); renderTray(); render();

}



function validateCustomBoard() {

    if(B.filter(p=>p==='K').length !== 1 || B.filter(p=>p==='k').length !== 1) return showGUI('Error', '⚠️ You MUST place exactly ONE White King (♔) and ONE Black King (♚)!', 'alert');

    document.getElementById('botLevelModal').classList.remove('hidden');

}



function startCustomPlay() { document.getElementById('botLevelModal').classList.add('hidden'); startGame(true); }

function renderTray() { document.getElementById('tray').innerHTML = ['P','N','B','R','Q','K','p','n','b','r','q','k','.'].map(p=>`<button class="tray-piece ${chosen===p?'active':''}" onclick="chosen='${p}';renderTray()"><span class="${p==='.'?'':(p===p.toUpperCase()?'piece-w':'piece-b')}">${p==='.'?'🧽':U[p]}</span></button>`).join(''); }



loadDashboard();

</script></body></html>