File size: 47,577 Bytes
fbb9eca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gemifish Chess</title>
    <link rel="stylesheet" href="https://unpkg.com/@chrisoakman/chessboardjs@1.0.0/dist/chessboard-1.0.0.min.css">
    <link href="https://fonts.googleapis.com/css?family=Inter:400,600&display=swap" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        html, body { height: 100%; overflow: hidden; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Inter', Arial, sans-serif;
            background-color: #2c2c2c; color: #ffffff; display: flex; flex-direction: column;
        }
        .container { display: flex; flex: 1; min-height: 0; }
        .left-panel {
            flex: 0 0 600px; background-color: #2c2c2c; display: flex; flex-direction: column;
            border-right: 1px solid #404040; min-height: 0; position: relative;
        }
        .header {
            display: flex; justify-content: space-between; align-items: center; padding: 12px 16px;
            background-color: #2c2c2c; border-bottom: 1px solid #404040; min-height: 56px; position: relative; z-index: 2;
        }
        .player-info { display: flex; align-items: center; gap: 12px; }
        .avatar {
            width: 32px; height: 32px; border-radius: 50%;
            background: linear-gradient(135deg, #ff6b35, #f7931e); display: flex;
            align-items: center; justify-content: center; flex-shrink: 0;
        }
        .avatar svg { width: 18px; height: 18px; fill: white; }
        .player-name { font-size: 16px; font-weight: 500; }
        .rating { color: #888; font-size: 14px; margin-left: 4px; }
        .header-actions { position: relative; display: flex; align-items: center; gap: 12px; }
        .settings-icon, .close-btn {
            width: 32px; height: 32px; color: #888; cursor: pointer; display: flex;
            align-items: center; justify-content: center; border-radius: 4px; flex-shrink: 0;
            transition: color 0.2s, background-color 0.2s;
        }
        .settings-icon:hover, .close-btn:hover { color: #fff; background-color: #404040; }
        .settings-icon.active-ai { color: #4a90e2; }
        .settings-icon.active-ai:hover { color: #6aaeff; }
        .settings-icon svg, .close-btn svg { width: 18px; height: 18px; }
        
        /* Perbaikan utama untuk container board catur */
        .chess-board-container {
            flex: 1; 
            display: flex; 
            align-items: center; 
            justify-content: center;
            background-color: #353535; 
            margin: 8px; /* Kurangi margin dari 16px menjadi 8px */
            border-radius: 8px; 
            border: 1px solid #404040;
            min-height: 0; 
            overflow: hidden; 
            padding: 8px; /* Kurangi padding dari 20px menjadi 8px */
            position: relative; 
            z-index: 0;
            contain: content;
        }
        
        #game-board { 
            width: 100%; 
            height: 100%;
            aspect-ratio: 1/1; /* Pertahankan rasio aspek */
        }
        
        .bottom-section {
            padding: 16px; border-top: 1px solid #404040; display: flex;
            align-items: center; gap: 12px; min-height: 56px; position: relative; z-index: 2;
        }
        .guest-avatar {
            width: 24px; height: 24px; background-color: #666; border-radius: 50%;
            display: flex; align-items: center; justify-content: center; color: #ccc; flex-shrink: 0;
        }
        .guest-avatar svg { width: 14px; height: 14px; fill: currentColor; }
        .guest-label { color: #ccc; font-size: 14px; }
        .action-icons { margin-left: auto; display: flex; gap: 8px; }
        .action-icon {
            width: 28px; height: 28px; color: #888; cursor: pointer; display: flex;
            align-items: center; justify-content: center; border-radius: 4px; flex-shrink: 0;
        }
        .action-icon:hover { color: #fff; background-color: #404040; }
        .action-icon svg { width: 16px; height: 16px; fill: currentColor; }
        .right-panel { flex: 1; background-color: #1e1e1e; display: flex; flex-direction: column; min-height: 0; }
        .right-header {
            padding: 12px 16px; border-bottom: 1px solid #404040; display: flex;
            align-items: center; justify-content: space-between; min-height: 56px; flex-shrink: 0;
        }
        .play-bots { display: flex; align-items: center; gap: 8px; font-size: 16px; font-weight: 500; }
        .bot-icon {
            width: 24px; height: 24px; background: linear-gradient(135deg, #4a90e2, #357abd);
            border-radius: 4px; display: flex; align-items: center; justify-content: center;
            color: white; flex-shrink: 0;
        }
        .bot-icon svg { width: 14px; height: 14px; fill: currentColor; }
        .moves-section { flex: 1; padding: 16px; overflow-y: auto; min-height: 0; }
        .moves-header { color: #888; font-size: 14px; margin-bottom: 16px; min-height: 20px; }
        .moves-list { display: flex; flex-direction: column; gap: 8px; }
        .move-row { display: flex; align-items: center; gap: 16px; font-size: 14px; }
        .move-number { color: #888; width: 20px; flex-shrink: 0; text-align: right; }
        .move { min-width: 60px; color: #fff; padding: 2px 4px; }
        .move.highlighted-move { background-color: #404040; border-radius: 3px; }

        .ai-reasoning-section {
            padding: 12px 16px; border-top: 1px solid #404040; background-color: #252525; flex-shrink: 0;
        }
        .ai-reasoning-header {
            font-size: 12px; font-weight: 600; color: #aaa; letter-spacing: 0.5px;
            text-transform: uppercase; margin-bottom: 8px; display: flex; align-items: center; gap: 6px;
        }
        #ai-reasoning-text { font-size: 14px; color: #ddd; min-height: 40px; font-style: italic; }

        .controls {
            padding: 16px; border-top: 1px solid #404040; display: flex;
            justify-content: space-between; align-items: center; gap: 12px; flex-shrink: 0;
        }
        .nav-controls { display: flex; gap: 8px; }
        .control-btn {
            width: 36px; height: 36px; background-color: #404040; border: none; border-radius: 4px;
            color: #ccc; cursor: pointer; display: flex; align-items: center; justify-content: center; flex-shrink: 0;
        }
        .control-btn:disabled { color: #666; cursor: not-allowed; }
        .control-btn:not(:disabled):hover { background-color: #505050; color: #fff; }
        .control-btn svg { width: 18px; height: 18px; fill: currentColor; }
        .resign-btn {
            background-color: #d32f2f; color: white; border: none; padding: 8px 16px; border-radius: 4px;
            cursor: pointer; font-size: 14px; display: flex; align-items: center; gap: 6px; flex-shrink: 0;
        }
        .resign-btn:hover { background-color: #b71c1c; }
        .resign-btn:disabled { background-color: #5a2e2e; color: #aaa; cursor: not-allowed; }
        .resign-btn svg { width: 16px; height: 16px; fill: currentColor; }
        
        .modal-overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0, 0, 0, 0.7); backdrop-filter: blur(4px); display: none;
            align-items: center; justify-content: center; z-index: 1000;
        }
        .modal {
          width: min(480px, 90vw); background: #2c2c2c; border-radius: 12px; border: 1px solid #404040;
          box-shadow: 0 8px 32px rgba(0,0,0,0.5); color: #fff; padding-bottom: 24px; position: relative;
        }
        .modal-header {
          padding: 16px 24px; font-size: 20px; font-weight: 600; border-bottom: 1px solid #404040;
          display: flex; justify-content: space-between; align-items: center;
        }
        .modal-close-btn {
          background: none; border: none; cursor: pointer; padding: 0; margin: 0; width: 28px;
          height: 28px; display: flex; align-items: center; justify-content: center;
        }
        .modal-content { padding: 0 24px; }
        .tabs { display: flex; border-bottom: 1.5px solid #404040; margin-bottom: 0; margin-top: 8px; }
        .tab {
          flex: 1; text-align: center; padding: 12px 0 8px 0; font-size: 16px; font-weight: 500;
          color: #fff; cursor: pointer; border: none; background: none; outline: none; border-bottom: 2.5px solid #fff;
        }
        .section-label {
          margin-top: 20px; margin-bottom: 8px; font-size: 14px; font-weight: 600;
          color: #aaa; letter-spacing: 0.5px;
        }
        .input-row { display: flex; align-items: center; position: relative; }
        .input-box {
          background: #404040; border: 1px solid #555; border-radius: 6px; color: #fff;
          font-size: 14px; padding: 10px 44px 10px 12px; width: 100%;
          font-family: 'Inter', 'Segoe UI', sans-serif; resize: none;
        }
        .pgn-area { min-height: 140px; max-height: 160px; }
        .copy-btn {
          position: absolute; right: 4px; top: 6px; background: none; border: none;
          cursor: pointer; padding: 4px; display: flex; align-items: center; justify-content: center;
          color: #aaa; border-radius: 4px;
        }
        .copy-btn:hover { background-color: #555; color: #fff; }
        .pgn-area + .copy-btn { top: 8px; right: 8px; }
        .modal-action-btn {
          width: 100%; color: #fff; font-size: 18px; font-weight: 600; border: none;
          border-radius: 8px; padding: 12px 0; margin-top: 18px; cursor: pointer;
          display: flex; align-items: center; justify-content: center; transition: background 0.2s;
        }
        .modal-action-btn.download{ background: #4a90e2; }
        .modal-action-btn.download:hover { background: #5a9ee6; }
        .modal-action-btn.save-ai { background: #3f9142; }
        .modal-action-btn.save-ai:hover { background: #4caf50; }
        .modal-action-btn svg { margin-right: 10px; }

        #settings-popover {
            display: none; position: absolute; top: 40px; right: 0; width: 220px; background: #2c2c2c;
            border: 1px solid #404040; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.4);
            z-index: 1100; padding: 8px;
        }
        .settings-section-header {
            font-size: 12px; color: #888; text-transform: uppercase; padding: 8px; font-weight: 600;
        }
        .theme-btn {
            width: 100%; background: none; border: none; color: #ddd; padding: 8px; text-align: left;
            display: flex; align-items: center; gap: 12px; border-radius: 4px; cursor: pointer;
        }
        .theme-btn:hover { background-color: #404040; }
        .theme-btn.active { color: #fff; background-color: #4a90e2; }
        .theme-swatch {
            width: 40px; height: 20px; border-radius: 4px; display: flex;
            overflow: hidden; border: 1px solid #555;
        }
        .theme-swatch-light { width: 50%; } .theme-swatch-dark { width: 50%; }

        .notification {
            position: fixed; top: -100px; left: 50%; transform: translateX(-50%);
            background-color: #ff6b35; color: white; padding: 12px 24px; border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3); z-index: 2000; font-size: 15px; font-weight: 500;
            transition: top 0.5s ease-in-out; display: flex; align-items: center; gap: 10px;
        }
        .notification.show { top: 20px; }
        
        /* Perbaikan responsif untuk mobile */
        @media (max-width: 768px) {
            .container { flex-direction: column; }
            .left-panel { 
                flex: 1; 
                width: 100%; 
                border-right: none; 
                border-bottom: 1px solid #404040; 
                min-height: auto;
            }
            .right-panel { flex: 1; }
            .chess-board-container { 
                margin: 4px; /* Kurangi margin di mobile */
                padding: 4px; /* Kurangi padding di mobile */
                height: auto; 
                overflow: hidden; 
            }
            .header, .bottom-section, .right-header, .controls { padding: 8px 12px; min-height: 48px; }
            .player-info { gap: 8px; }
            .avatar { width: 28px; height: 28px; }
            .player-name { font-size: 14px; }
            .rating { font-size: 12px; }
            #game-board { 
                width: 100%; 
                height: 100%;
                max-width: 100%; 
                max-height: none; 
                aspect-ratio: 1/1; 
            }
        }
        @media (max-width: 480px) {
            .nav-controls { gap: 4px; }
            .control-btn { width: 32px; height: 32px; }
            .resign-btn { padding: 6px 12px; font-size: 12px; }
            .chess-board-container { 
                margin: 2px; /* Kurangi margin lebih lanjut di layar kecil */
                padding: 2px; /* Kurangi padding lebih lanjut di layar kecil */
            }
        }
        
        /* API key input */
        #api-key-input { width: 100%; padding: 10px; background: #404040; border: 1px solid #555; color: #fff; }
        .credit { font-size: 12px; color: #888; margin-left: auto; }
        .credit a { color: #4a90e2; text-decoration: none; }
        .credit a:hover { text-decoration: underline; }
    </style>
</head>
<body>
    <div id="ai-notification" class="notification">
        <svg fill="currentColor" width="20" height="20" viewBox="0 0 24 24"><path d="M13,14H11V10H13M13,18H11V16H13M1,21H23L12,2L1,21Z"></path></svg>
        <span id="ai-notification-text"></span>
    </div>

    <div class="container">
        <div class="left-panel">
             <div class="header">
                <div class="player-info"><div class="avatar"><svg viewBox="0 0 24 24"><path d="M12,20A8,8 0 0,0 20,12A8,8 0 0,0 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22C6.47,22 2,17.5 2,12A10,10 0 0,1 12,2M15.5,8C16.3,8 17,8.7 17,9.5C17,10.3 16.3,11 15.5,11C14.7,11 14,10.3 14,9.5C14,8.7 14.7,8 15.5,8M10,9.5C10,10.3 9.3,11 8.5,11C7.7,11 7,10.3 7,9.5C7,8.7 7.7,8 8.5,8C9.3,8 10,8.7 10,9.5M12,17.23C10.25,17.23 8.71,16.5 7.81,15.42L9.07,14.34C9.69,15.12 10.8,15.23 12,15.23C13.2,15.23 14.31,15.12 14.93,14.34L16.19,15.42C15.29,16.5 13.75,17.23 12,17.23Z"/></svg></div><div><span class="player-name">Gemifish</span><span class="rating">(2000+)</span></div></div>
                <div class="header-actions">
                    <div id="ai-btn" class="settings-icon" title="AI Personality">
                        <svg fill="currentColor" viewBox="0 0 24 24"><path d="M12,2A2,2 0 0,1 14,4C14,4.74 13.6,5.39 13,5.73V7H14A7,7 0 0,1 21,14H22A1,1 0 0,1 23,15V18A1,1 0 0,1 22,19H21V20A2,2 0 0,1 19,22H5A2,2 0 0,1 3,20V19H2A1,1 0 0,1 1,18V15A1,1 0 0,1 2,14H3A7,7 0 0,1 10,7H11V5.73C10.4,5.39 10,4.74 10,4A2,2 0 0,1 12,2M7.5,13A2.5,2.5 0 0,0 5,15.5A2.5,2.5 0 0,0 7.5,18A2.5,2.5 0 0,0 10,15.5A2.5,2.5 0 0,0 7.5,13M16.5,13A2.5,2.5 0 0,0 14,15.5A2.5,2.5 0 0,0 16.5,18A2.5,2.5 0 0,0 19,15.5A2.5,2.5 0 0,0 16.5,13Z"/></svg>
                    </div>
                    <div id="settings-btn" class="settings-icon" title="Settings">
                        <svg fill="currentColor" viewBox="0 0 24 24"><path d="M12,15.5A3.5,3.5 0 0,1 8.5,12A3.5,3.5 0 0,1 12,8.5A3.5,3.5 0 0,1 15.5,12A3.5,3.5 0 0,1 12,15.5M19.43,12.97C19.47,12.65 19.5,12.33 19.5,12C19.5,11.67 19.47,11.34 19.43,11L21.54,9.37C21.73,9.22 21.78,8.95 21.66,8.73L19.66,5.27C19.54,5.05 19.27,4.96 19.05,5.05L16.56,6.05C16.04,5.66 15.5,5.32 14.87,5.07L14.5,2.42C14.46,2.18 14.25,2 14,2H10C9.75,2 9.54,2.18 9.5,2.42L9.13,5.07C8.5,5.32 7.96,5.66 7.44,6.05L4.95,5.05C4.73,4.96 4.46,5.05 4.34,5.27L2.34,8.73C2.22,8.95 2.27,9.22 2.46,9.37L4.57,11C4.53,11.34 4.5,11.67 4.5,12C4.5,12.33 4.53,12.65 4.57,12.97L2.46,14.63C2.27,14.78 2.22,15.05 2.34,15.27L4.34,18.73C4.46,18.95 4.73,19.03 4.95,18.95L7.44,17.94C7.96,18.34 8.5,18.68 9.13,18.93L9.5,21.58C9.54,21.82 9.75,22 10,22H14C14.25,22 14.46,21.82 14.5,21.58L14.87,18.93C15.5,18.68 16.04,18.34 16.56,17.94L19.05,18.95C19.27,19.03 19.54,18.95 19.66,18.73L21.66,15.27C21.78,15.05 21.73,14.78 21.54,14.63L19.43,12.97Z"/></svg>
                    </div>
                    <div id="settings-popover">
                        <div class="settings-section-header">Board Theme</div>
                        <button id="theme-brown-btn" class="theme-btn"><div class="theme-swatch"><div class="theme-swatch-light" style="background-color: #f0d9b5;"></div><div class="theme-swatch-dark" style="background-color: #b58863;"></div></div>Brown</button>
                        <button id="theme-blue-btn" class="theme-btn"><div class="theme-swatch"><div class="theme-swatch-light" style="background-color: #D8DEE9;"></div><div class="theme-swatch-dark" style="background-color: #819AAE;"></div></div>Blue</button>
                    </div>
                </div>
            </div>
            <div class="chess-board-container"><div id="game-board"></div></div>
            <div class="bottom-section">
                <div class="guest-avatar"><svg viewBox="0 0 24 24"><path d="M12,4A4,4 0 0,1 16,8A4,4 0 0,1 12,12A4,4 0 0,1 8,8A4,4 0 0,1 12,4M12,14C16.42,14 20,15.79 20,18V20H4V18C4,15.79 7.58,14 12,14Z"/></svg></div>
                <div class="guest-label">Guest</div>
                <div class="action-icons"><div id="share-btn" class="action-icon" title="Share"><svg viewBox="0 0 24 24"><path d="M21,12L14,5V9C7,10 4,15 3,20C5.5,16.5 9,14.9 14,14.9V19L21,12Z"/></svg></div></div>
                <div class="credit">Dibuat oleh <a href="https://reddit.com/u/DinnerUnlucky4661" target="_blank">/u/DinnerUnlucky4661</a> on Reddit</div>
            </div>
        </div>
        <div class="right-panel">
            <div class="right-header"><div class="play-bots"><div class="bot-icon"><svg viewBox="0 0 24 24"><path d="M12,2A2,2 0 0,1 14,4C14,4.74 13.6,5.39 13,5.73V7H14A7,7 0 0,1 21,14H22A1,1 0 0,1 23,15V18A1,1 0 0,1 22,19H21V20A2,2 0 0,1 19,22H5A2,2 0 0,1 3,20V19H2A1,1 0 0,1 1,18V15A1,1 0 0,1 2,14H3A7,7 0 0,1 10,7H11V5.73C10.4,5.39 10,4.74 10,4A2,2 0 0,1 12,2M7.5,13A2.5,2.5 0 0,0 5,15.5A2.5,2.5 0 0,0 7.5,18A2.5,2.5 0 0,0 10,15.5A2.5,2.5 0 0,0 7.5,13M16.5,13A2.5,2.5 0 0,0 14,15.5A2.5,2.5 0 0,0 16.5,18A2.5,2.5 0 0,0 19,15.5A2.5,2.5 0 0,0 16.5,13Z"/></svg></div><span>Play Bots</span></div></div>
            <div class="moves-section"><div class="moves-header" id="status-display">Loading Gemifish Engine...</div><div class="moves-list" id="moves-list"></div></div>
            <div class="ai-reasoning-section">
                <div class="ai-reasoning-header">
                   <svg fill="currentColor" width="16" height="16" viewBox="0 0 24 24"><path d="M12,2A2,2 0 0,1 14,4C14,4.74 13.6,5.39 13,5.73V7H14A7,7 0 0,1 21,14H22A1,1 0 0,1 23,15V18A1,1 0 0,1 22,19H21V20A2,2 0 0,1 19,22H5A2,2 0 0,1 3,20V19H2A1,1 0 0,1 1,18V15A1,1 0 0,1 2,14H3A7,7 0 0,1 10,7H11V5.73C10.4,5.39 10,4.74 10,4A2,2 0 0,1 12,2Z"/></svg>
                    AI Reasoning
                </div>
                <p id="ai-reasoning-text">Set a personality to see the AI's thoughts here.</p>
            </div>
            <div class="controls">
                <div class="nav-controls">
                    <button id="btn-first" class="control-btn"><svg viewBox="0 0 24 24"><path d="M18.41,16.59L13.82,12L18.41,7.41L17,6L11,12L17,18L18.41,16.59M6,6H8V18H6V6Z"/></svg></button>
                    <button id="btn-back" class="control-btn"><svg viewBox="0 0 24 24"><path d="M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z"/></svg></button>
                    <button id="btn-forward" class="control-btn"><svg viewBox="0 0 24 24"><path d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z"/></svg></button>
                    <button id="btn-last" class="control-btn"><svg viewBox="0 0 24 24"><path d="M5.59,7.41L10.18,12L5.59,16.59L7,18L13,12L7,6L5.59,7.41M16,6H18V18H16V6Z"/></svg></button>
                </div>
                <button id="resign-btn" class="resign-btn"><svg viewBox="0 0 24 24"><path d="M14.4,6L14,4H5V21H7V14H12.6L13,16H20V6H14.4Z"/></svg><span>Resign</span></button>
            </div>
        </div>
    </div>
    
    <div class="modal-overlay" id="pgn-modal-overlay">
      <div class="modal">
        <div class="modal-header">
          Share Game
          <button id="modal-close-btn" class="modal-close-btn"><svg width="22" height="22" viewBox="0 0 22 22"><line x1="6" y1="6" x2="16" y2="16" stroke="#bdbdbd" stroke-width="2" stroke-linecap="round"/><line x1="16" y1="6" x2="6" y2="16" stroke="#bdbdbd" stroke-width="2" stroke-linecap="round"/></svg></button>
        </div>
        <div class="modal-content">
          <div class="tabs"><button class="tab">PGN</button></div>
          <div>
            <div class="section-label">FEN</div>
            <div class="input-row"><input class="input-box" id="fenInput" readonly><button class="copy-btn" id="copy-fen-btn" title="Copy FEN"><svg width="22" height="22" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 4v4H4m12-4v4h4M8 20v-4H4m12 4v-4h4m-4-2h-4v4h4zM8 9H4V5h4zm12 0h-4V5h4zm-8 8H8v-4h4z"/></svg></button></div>
            <div class="section-label">PGN</div>
            <div class="input-row"><textarea class="input-box pgn-area" id="pgnText" readonly></textarea><button class="copy-btn" id="copy-pgn-btn" title="Copy PGN"><svg width="22" height="22" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 4v4H4m12-4v4h4M8 20v-4H4m12 4v-4h4m-4-2h-4v4h4zM8 9H4V5h4zm12 0h-4V5h4zm-8 8H8v-4h4z"/></svg></button></div>
            <button class="modal-action-btn download" id="download-pgn-btn"><svg width="24" height="24" viewBox="0 0 24 24"><path d="M12 4v12m0 0l-4-4m4 4l4-4m-4 8h8a2 2 0 002-2v-2" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>Download</button>
          </div>
        </div>
      </div>
    </div>
    
    <div class="modal-overlay" id="ai-modal-overlay">
      <div class="modal">
        <div class="modal-header">
          AI Personality
          <button id="ai-modal-close-btn" class="modal-close-btn"><svg width="22" height="22" viewBox="0 0 22 22"><line x1="6" y1="6" x2="16" y2="16" stroke="#bdbdbd" stroke-width="2" stroke-linecap="round"/><line x1="16" y1="6" x2="6" y2="16" stroke="#bdbdbd" stroke-width="2" stroke-linecap="round"/></svg></button>
        </div>
        <div class="modal-content">
          <div class="section-label" style="margin-top: 16px;">System Prompt</div>
          <p style="font-size: 13px; color: #aaa; margin-bottom: 12px;">Describe the personality for the AI opponent. If this is empty, the AI will play using the standard Stockfish engine.</p>
          <div class="input-row">
            <textarea class="input-box pgn-area" id="ai-personality-input" placeholder="e.g., An aggressive pirate who loves to attack and sacrifice pieces."></textarea>
          </div>
          <button class="modal-action-btn save-ai" id="save-ai-personality-btn"><svg fill="currentColor" width="24" height="24" viewBox="0 0 24 24"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>Apply Personality</button>
        </div>
      </div>
    </div>

    <!-- New Settings Modal with API Key Input -->
    <div class="modal-overlay" id="settings-modal-overlay">
      <div class="modal">
        <div class="modal-header">
          Settings
          <button id="settings-modal-close-btn" class="modal-close-btn"><svg width="22" height="22" viewBox="0 0 22 22"><line x1="6" y1="6" x2="16" y2="16" stroke="#bdbdbd" stroke-width="2" stroke-linecap="round"/><line x1="16" y1="6" x2="6" y2="16" stroke="#bdbdbd" stroke-width="2" stroke-linecap="round"/></svg></button>
        </div>
        <div class="modal-content">
          <div class="section-label">Gemini API Key (Optional)</div>
          <p style="font-size: 13px; color: #aaa; margin-bottom: 12px;">Masukkan API key-mu jika default error/limit. Kosongkan untuk pakai default.</p>
          <input type="text" id="api-key-input" class="input-box" placeholder="Your Gemini API Key">
          <button class="modal-action-btn save-ai" id="save-settings-btn"><svg fill="currentColor" width="24" height="24" viewBox="0 0 24 24"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>Save</button>
          
          <!-- Existing theme buttons moved here for better UX -->
          <div class="settings-section-header">Board Theme</div>
          <button id="theme-brown-btn" class="theme-btn"><div class="theme-swatch"><div class="theme-swatch-light" style="background-color: #f0d9b5;"></div><div class="theme-swatch-dark" style="background-color: #b58863;"></div></div>Brown</button>
          <button id="theme-blue-btn" class="theme-btn"><div class="theme-swatch"><div class="theme-swatch-light" style="background-color: #D8DEE9;"></div><div class="theme-swatch-dark" style="background-color: #819AAE;"></div></div>Blue</button>
        </div>
      </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://unpkg.com/@chrisoakman/chessboardjs@1.0.0/dist/chessboard-1.0.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.2/chess.min.js"></script>
    
    <script>
        var board = null, game = new Chess(), $status = $('#status-display');
        var playerColor = 'w', engine = null, isGameOver = false, viewingMoveIndex = -1;
        var boardThemeStyle = document.createElement('style');
        document.head.appendChild(boardThemeStyle);

        var aiPersonality = '';
        var geminiApiKey = ''; // <-- IMPORTANT: REPLACE WITH YOUR GEMINI API KEY
        var userApiKey = ''; // User-provided key
        var isEngineSearching = false;
        var topMovesWithEvals = [];
        const useLLM = () => aiPersonality && aiPersonality.trim() !== '';

        const THEMES = {
            brown: { light: '#f0d9b5', dark: '#b58863' },
            blue: { light: '#D8DEE9', dark: '#819AAE' }
        };
        const STOCKFISH_WORKER_URL = 'https://cdnjs.cloudflare.com/ajax/libs/stockfish.js/10.0.2/stockfish.js';
        const pieceImagePaths = {'wP': 'https://upload.wikimedia.org/wikipedia/commons/4/45/Chess_plt45.svg','wR': 'https://upload.wikimedia.org/wikipedia/commons/7/72/Chess_rlt45.svg','wN': 'https://upload.wikimedia.org/wikipedia/commons/7/70/Chess_nlt45.svg','wB': 'https://upload.wikimedia.org/wikipedia/commons/b/b1/Chess_blt45.svg','wQ': 'https://upload.wikimedia.org/wikipedia/commons/1/15/Chess_qlt45.svg','wK': 'https://upload.wikimedia.org/wikipedia/commons/4/42/Chess_klt45.svg','bP': 'https://upload.wikimedia.org/wikipedia/commons/c/c7/Chess_pdt45.svg','bR': 'https://upload.wikimedia.org/wikipedia/commons/f/ff/Chess_rdt45.svg','bN': 'https://upload.wikimedia.org/wikipedia/commons/e/ef/Chess_ndt45.svg','bB': 'https://upload.wikimedia.org/wikipedia/commons/9/98/Chess_bdt45.svg','bQ': 'https://upload.wikimedia.org/wikipedia/commons/4/47/Chess_qdt45.svg','bK': 'https://upload.wikimedia.org/wikipedia/commons/f/f0/Chess_kdt45.svg'};
        function pieceTheme(piece) { return pieceImagePaths[piece]; }

        function setBoardTheme(themeName) {
            const theme = THEMES[themeName];
            boardThemeStyle.innerHTML = `
                .square-55d63.white-1e1d7 { background-color: ${theme.light}; color: ${theme.dark}; }
                .square-55d63.black-3c85d { background-color: ${theme.dark}; color: ${theme.light}; }
            `;
            $('.theme-btn').removeClass('active');
            $(`#theme-${themeName}-btn`).addClass('active');
        }

        function onDragStart(source, piece) {
            const canMove = !isGameOver && !isEngineSearching && !game.game_over() && game.turn() === playerColor && viewingMoveIndex === game.history().length - 1;
            
            if (!canMove) {
                console.log("Move disallowed. Current state:", {
                    isGameOver,
                    isEngineSearching,
                    isGameTerminated: game.game_over(),
                    isPlayerTurn: game.turn() === playerColor,
                    isViewingLatestMove: viewingMoveIndex === game.history().length - 1
                });
            }
            return canMove;
        }
        
        function createEngineWorker() {
            return fetch(STOCKFISH_WORKER_URL).then(res => res.text()).then(scriptText => {
                const blob = new Blob([scriptText], { type: 'application/javascript' });
                return new Worker(URL.createObjectURL(blob));
            });
        }

        function initializeEngine() {
            createEngineWorker().then(worker => {
                engine = worker;
                engine.onmessage = handleEngineMessage;
                engine.postMessage('uci');
                engine.postMessage('setoption name MultiPV value 5');
                updateStatus();
            }).catch(err => {
                console.error("Failed to load engine:", err);
                updateStatus("Error: Could not load engine.");
            });
        }
        
        function showNotification(message, duration = 6000) {
            const notification = $('#ai-notification');
            $('#ai-notification-text').text(message);
            notification.addClass('show');
            setTimeout(() => { notification.removeClass('show'); }, duration);
        }
        
        function handleEngineMessage(event) {
            const message = event.data;
            if (useLLM()) {
                if (message.startsWith('info') && message.includes('score cp')) {
                    const scoreMatch = message.match(/score cp (-?\d+)/);
                    const moveMatch = message.match(/pv\s+([a-h][1-8][a-h][1-8][qrbn]?)/);
                    if (scoreMatch && moveMatch) {
                        const score = parseInt(scoreMatch[1], 10);
                        const move = moveMatch[1];
                        if (!topMovesWithEvals.some(item => item.move === move)) {
                            topMovesWithEvals.push({ move, score });
                        }
                    }
                }
                if (message.startsWith('bestmove')) {
                    const bestMoveFallback = message.split(' ')[1];
                    decideMoveWithLLM(bestMoveFallback);
                }
            } else {
                if (message.startsWith('bestmove')) {
                    isEngineSearching = false;
                    makeMoveOnBoard(message.split(' ')[1]);
                }
            }
        }

        async function decideMoveWithLLM(fallbackMove) {
            const apiKeyToUse = userApiKey || geminiApiKey; // Use user key if provided
            if (!apiKeyToUse) {
                showNotification('API key kosong. Gunakan Stockfish default.');
                makeMoveOnBoard(fallbackMove);
                return;
            }
            const maxRetries = 5;
            let retryCount = 0;

            while (retryCount < maxRetries) {
                try {
                    if (topMovesWithEvals.length === 0) {
                        console.warn("No top moves were analyzed. Using fallback move:", fallbackMove);
                        makeMoveOnBoard(fallbackMove);
                        return;
                    }

                    const fen = game.fen();
                    const turn = game.turn() === 'w' ? 'White' : 'Black';
                    const movesData = JSON.stringify(topMovesWithEvals);

                    const prompt = `You are a world-class chess engine and a master role-player. Your goal is to perfectly blend strong chess play with a defined personality. Your priority is 80% playing the best move and 20% fitting your character. You must select a move from the provided list.

        Current State:
        - Board (FEN): ${fen}
        - It is ${turn}'s turn to move.
        - Your designated personality is: "${aiPersonality}"

        Your Task:
        I have provided a JSON array of the top moves calculated by a strong chess engine. First, identify the strongest moves that don't lead to a disadvantage. From that small group of good moves, pick the one that best reflects your character. Then, explain your choice from your character's perspective.

        Input Moves Data:
        ${movesData}

        Output Format:
        You MUST respond in a VALID JSON FORMAT, with no other text. The JSON object must have three keys:
        - "bestMove": The chosen move from the list (e.g., "e2e4"). Required.
        - "reasoning": A brief, in-character explanation for your choice. DO NOT mention scores or technical analysis. This should be your character's internal monologue. Required.
        - "deviationWarning": If you were forced to deviate from your personality to avoid a blunder, provide a short message explaining why. If you did not deviate, this MUST be null.`;

                    updateStatus('Consulting AI personality...');
                    $('#ai-reasoning-text').text('Thinking...');

                    const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=${apiKeyToUse}`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ "contents": [{ "parts": [{ "text": prompt }] }] })
                    });
                    
                    if (response.status === 429) {
                        const delay = Math.pow(2, retryCount) * 1000 + Math.random() * 1000;
                        console.warn(`Rate limit hit. Retrying in ${delay.toFixed(2)}ms...`);
                        await new Promise(resolve => setTimeout(resolve, delay));
                        retryCount++;
                        continue; // Go to the next iteration of the while loop to retry
                    }

                    if (!response.ok) {
                        throw new Error(`API request failed with status ${response.status}`);
                    }

                    const data = await response.json();

                    if (!data.candidates || !data.candidates[0]?.content?.parts[0]?.text) {
                        const reason = data.candidates?.[0]?.finishReason || 'Unknown reason';
                        console.error("Invalid response structure from Gemini API. Content may be blocked or missing. Finish Reason:", reason, data);
                        throw new Error(`Invalid response structure from Gemini API. Finish Reason: ${reason}`);
                    }

                    let rawText = data.candidates[0].content.parts[0].text;
                    const jsonMatch = rawText.match(/```json\s*(\{[\s\S]*\})\s*```|(\{[\s\S]*\})/);
                    if (!jsonMatch) {
                        throw new Error("LLM did not return a parsable JSON object.");
                    }

                    const jsonString = jsonMatch[1] || jsonMatch[2];
                    const result = JSON.parse(jsonString);

                    if (!result.bestMove || typeof result.reasoning === 'undefined') {
                        throw new Error("Parsed JSON from LLM is missing required keys ('bestMove', 'reasoning').");
                    }

                    if (result.deviationWarning) {
                        showNotification(result.deviationWarning);
                    }
                    $('#ai-reasoning-text').text(result.reasoning || "I have made my move.");

                    if (topMovesWithEvals.some(item => item.move === result.bestMove)) {
                        makeMoveOnBoard(result.bestMove);
                    } else {
                        console.warn(`LLM chose a move (${result.bestMove}) not in the valid list. Defaulting to best Stockfish move.`);
                        makeMoveOnBoard(fallbackMove);
                    }
                    return; // Exit the function successfully

                } catch (error) {
                    console.error("An error occurred while getting the AI's move:", error);
                    // If we've exhausted retries, give up and use the fallback.
                    if (retryCount >= maxRetries - 1) {
                         $('#ai-reasoning-text').text("An error occurred. I will play the best move as a fallback.");
                         updateStatus('Error with AI. Using best move.');
                         makeMoveOnBoard(fallbackMove);
                         break; // Exit the while loop
                    }
                }
            }
             isEngineSearching = false; // Ensure searching is always set to false after attempting to get a move.
        }
        
        function makeEngineMove() {
            if (isGameOver || game.game_over() || !engine) return;
            isEngineSearching = true;
            updateStatus('Gemifish is thinking...');

            topMovesWithEvals = [];
            engine.postMessage('position fen ' + game.fen());
            engine.postMessage('go depth 15');
        }

        function makeMoveOnBoard(move) {
            game.move(move, { sloppy: true });
            board.position(game.fen());
            board.resize(); // Force resize after move to prevent cutting
            viewingMoveIndex = game.history().length - 1;
            updateStatus();
            updateMoveHistory();
            if (game.game_over()) updateStatus();
        }

        function onDrop(source, target) {
            var move = game.move({ from: source, to: target, promotion: 'q' });
            if (move === null) return 'snapback';
            
            viewingMoveIndex = game.history().length - 1;
            updateMoveHistory();
            
            if (game.game_over()) {
                updateStatus();
            } else {
                window.setTimeout(makeEngineMove, 250);
            }
        }

        function onSnapEnd() { 
            board.position(game.fen()); 
            // Tambahkan sedikit delay sebelum resize untuk memastikan DOM sudah diperbarui
            setTimeout(() => board.resize(), 10);
        }
        
        function updateMoveHistory() {
            const history = game.history({ verbose: false });
            const moveList = $('#moves-list');
            moveList.empty();
            let moveRow;
            for (let i = 0; i < history.length; i++) {
                if (i % 2 === 0) {
                    moveRow = $('<div class="move-row"></div>').append(`<span class="move-number">${(i / 2) + 1}.</span>`);
                    moveList.append(moveRow);
                }
                const san = history[i];
                const $moveSpan = $('<span class="move"></span>').text(san);
                moveRow.append($moveSpan);
            }
            $('.moves-section').scrollTop($('.moves-section')[0].scrollHeight);
            updateHighlighting();
        }

        function updateHighlighting() {
            $('.move').removeClass('highlighted-move');
            if (viewingMoveIndex > -1) $('.move').eq(viewingMoveIndex).addClass('highlighted-move');
        }
        
        function navigateToMove(index) {
            const history = game.history();
            if (index < -1 || index >= history.length) return;
            viewingMoveIndex = index;
            const tempGame = new Chess();
            for (let i = 0; i <= viewingMoveIndex; i++) tempGame.move(history[i]);
            board.position(tempGame.fen());
            // Tambahkan sedikit delay sebelum resize untuk memastikan DOM sudah diperbarui
            setTimeout(() => board.resize(), 10);
            updateHighlighting();
            updateNavButtons();
        }

        function updateStatus(customStatus) {
            var status = customStatus || '';
            if (!customStatus) {
                if (isGameOver) {
                    status = "You Resigned. Gemifish Wins.";
                } else {
                    var moveColor = game.turn() === 'b' ? 'Black' : 'White';
                    if (game.in_checkmate()) status = 'Game over: ' + moveColor + ' is in checkmate.';
                    else if (game.in_draw()) status = 'Game over: Drawn position';
                    else {
                        status = (game.turn() === playerColor ? 'Your' : "Gemifish's") + ' turn';
                        if (game.in_check()) status += ' (in check)';
                    }
                }
            }
            if (game.game_over() || isGameOver) {
                $('#resign-btn').prop('disabled', true);
            }
            $status.html(status);
            updateNavButtons();
        }
        
        function updateNavButtons() {
            const historyLength = game.history().length;
            const onLatestMove = viewingMoveIndex === historyLength - 1;
            $('#btn-first').prop('disabled', viewingMoveIndex <= -1);
            $('#btn-back').prop('disabled', viewingMoveIndex <= -1);
            $('#btn-forward').prop('disabled', onLatestMove);
            $('#btn-last').prop('disabled', onLatestMove);
        }

        function openShareModal() {
            $('#fenInput').val(game.fen());
            $('#pgnText').val(game.pgn());
            $('#pgn-modal-overlay').css('display', 'flex');
        }
        function closeShareModal() { $('#pgn-modal-overlay').css('display', 'none'); }
        function openAIPersonalityModal() {
            $('#ai-personality-input').val(aiPersonality);
            $('#ai-modal-overlay').css('display', 'flex');
        }
        function closeAIPersonalityModal() { $('#ai-modal-overlay').css('display', 'none'); }
        function saveAIPersonality() {
            aiPersonality = $('#ai-personality-input').val();
            if (useLLM()) {
                $('#ai-btn').addClass('active-ai');
                $('#ai-reasoning-text').text('Personality set. Make your move!');
            } else {
                $('#ai-btn').removeClass('active-ai');
                $('#ai-reasoning-text').text('Set a personality to see the AI\'s thoughts here.');
            }
            closeAIPersonalityModal();
        }

        function copyToClipboard(elementId, btnElem) {
            navigator.clipboard.writeText($(`#${elementId}`).val()).then(() => {
                const originalContent = $(btnElem).html();
                $(btnElem).html('Copied!');
                setTimeout(() => { $(btnElem).html(originalContent); }, 2000);
            }).catch(err => {
                console.error('Failed to copy text: ', err);
                const originalContent = $(btnElem).html();
                $(btnElem).html('Error!');
                 setTimeout(() => { $(btnElem).html(originalContent); }, 2000);
            });
        }

        function downloadPGN() {
            const text = $('#pgnText').val();
            const blob = new Blob([text], { type: 'application/vnd.chess-pgn' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a'); a.href = url;
            a.download = `Gemifish-vs-Guest-${new Date().toISOString().slice(0,10)}.pgn`;
            document.body.appendChild(a); a.click();
            document.body.removeChild(a); URL.revokeObjectURL(url);
        }

        // New functions for settings modal
        function openSettingsModal() {
            $('#api-key-input').val(userApiKey);
            $('#settings-modal-overlay').css('display', 'flex');
        }
        function closeSettingsModal() { $('#settings-modal-overlay').css('display', 'none'); }

        var config = { 
            draggable: true, 
            position: 'start', 
            onDragStart, 
            onDrop, 
            onSnapEnd, 
            pieceTheme,
            showNotation: true
        };
        board = Chessboard('game-board', config);
        
        // Fungsi untuk memastikan board menyesuaikan dengan container
        function ensureBoardFits() {
            const container = $('.chess-board-container');
            // Kurangi padding dari perhitungan ukuran
            const containerWidth = container.width() - 16; // Kurangi 2 * padding (8px)
            const containerHeight = container.height() - 16; // Kurangi 2 * padding (8px)
            
            // Tentukan ukuran maksimum berdasarkan container
            const maxSize = Math.min(containerWidth, containerHeight);
            
            // Atur ukuran board
            $('#game-board').css({
                'width': maxSize + 'px',
                'height': maxSize + 'px'
            });
            
            // Resize board
            board.resize();
        }
        
        // Panggil fungsi saat inisialisasi
        ensureBoardFits();
        
        // Panggil fungsi saat window di-resize
        $(window).on('resize', ensureBoardFits);

        // Event Handlers
        $('#resign-btn').on('click', () => { if (!isGameOver && !game.game_over()) { isGameOver = true; updateStatus(); }});
        $('#btn-back').on('click', () => navigateToMove(viewingMoveIndex - 1));
        $('#btn-forward').on('click', () => navigateToMove(viewingMoveIndex + 1));
        $('#btn-first').on('click', () => navigateToMove(-1));
        $('#btn-last').on('click', () => navigateToMove(game.history().length - 1));
        
        $('#share-btn').on('click', openShareModal);
        $('#modal-close-btn').on('click', function(e) { e.stopPropagation(); closeShareModal(); });
        $('#pgn-modal-overlay').on('click', function(e) { if (e.target === this || $(e.target).is('#modal-close-btn, #modal-close-btn *')) closeShareModal(); });
        
        $('#ai-btn').on('click', openAIPersonalityModal);
        $('#ai-modal-close-btn').on('click', function(e) { e.stopPropagation(); closeAIPersonalityModal(); });
        $('#ai-modal-overlay').on('click', function(e) { if (e.target === this || $(e.target).is('#ai-modal-close-btn, #ai-modal-close-btn *')) closeAIPersonalityModal(); });
        $('#save-ai-personality-btn').on('click', saveAIPersonality);

        $('.modal').on('click', e => e.stopPropagation());
        $('#copy-fen-btn').on('click', function() { copyToClipboard('fenInput', this); });
        $('#copy-pgn-btn').on('click', function() { copyToClipboard('pgnText', this); });
        $('#download-pgn-btn').on('click', downloadPGN);
        
        $('#settings-btn').on('click', openSettingsModal);
        $('#settings-modal-close-btn').on('click', function(e) { e.stopPropagation(); closeSettingsModal(); });
        $('#settings-modal-overlay').on('click', function(e) { if (e.target === this || $(e.target).is('#settings-modal-close-btn, #settings-modal-close-btn *')) closeSettingsModal(); });
        $('#save-settings-btn').on('click', () => {
            userApiKey = $('#api-key-input').val().trim();
            closeSettingsModal();
            showNotification('Settings disimpan!');
        });
        $('#theme-brown-btn').on('click', () => setBoardTheme('brown'));
        $('#theme-blue-btn').on('click', () => setBoardTheme('blue'));
        
        setBoardTheme('blue');
        initializeEngine();
    </script>
</body>
</html>