File size: 26,278 Bytes
596f7cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
document.addEventListener('DOMContentLoaded', () => {
  const BASE_PUZZLE = '530070000600195000098000060800060003400803001700020006060000280000419005000080079';
  const TECHNIQUE_LABELS = {
    'naked-single': '단일 후보',
    'hidden-single-row': 'ν–‰ μˆ¨μ€ μ‹±κΈ€',
    'hidden-single-col': 'μ—΄ μˆ¨μ€ μ‹±κΈ€',
    'hidden-single-box': 'λ°•μŠ€ μˆ¨μ€ μ‹±κΈ€'
  };

  const dom = {
    board: document.getElementById('sudoku-board'),
    newGameBtn: document.getElementById('new-game-btn'),
    hintBtn: document.getElementById('hint-btn'),
    applyHintBtn: document.getElementById('apply-hint-btn'),
    checkBtn: document.getElementById('check-btn'),
    resetBtn: document.getElementById('reset-btn'),
    hintMessage: document.getElementById('hint-message'),
    gameStatus: document.getElementById('game-status'),
    puzzleMeta: document.getElementById('puzzle-meta'),
    difficultyBadge: document.getElementById('difficulty-badge'),
    filledCount: document.getElementById('filled-count'),
    remainingCount: document.getElementById('remaining-count'),
    nextTechnique: document.getElementById('next-technique'),
    analysisSummary: document.getElementById('analysis-summary'),
    logList: document.getElementById('log-list')
  };

  const state = {
    board: [],
    initial: [],
    solution: [],
    analysis: null,
    pendingHint: null,
    selected: null,
    showMistakes: false,
    hintMessage: '힌트 보기λ₯Ό λˆ„λ₯΄λ©΄ λ‹€μŒ 논리 단계λ₯Ό μ„€λͺ…ν•©λ‹ˆλ‹€.',
    gameCount: 0,
    learningLog: [],
    cells: []
  };

  createBoard();
  bindEvents();
  startNewGame();

  function bindEvents() {
    dom.newGameBtn.addEventListener('click', startNewGame);
    dom.hintBtn.addEventListener('click', requestHint);
    dom.applyHintBtn.addEventListener('click', applyHint);
    dom.checkBtn.addEventListener('click', toggleMistakes);
    dom.resetBtn.addEventListener('click', resetBoard);
  }

  function createBoard() {
    const fragment = document.createDocumentFragment();

    for (let row = 0; row < 9; row += 1) {
      const rowCells = [];
      for (let col = 0; col < 9; col += 1) {
        const input = document.createElement('input');
        input.type = 'text';
        input.className = 'cell';
        input.maxLength = 1;
        input.inputMode = 'numeric';
        input.autocomplete = 'off';
        input.pattern = '[1-9]';
        input.spellcheck = false;
        input.setAttribute('aria-describedby', 'sudoku-help');
        input.dataset.row = String(row);
        input.dataset.col = String(col);
        input.setAttribute('role', 'gridcell');
        input.setAttribute('aria-rowindex', String(row + 1));
        input.setAttribute('aria-colindex', String(col + 1));

        if (col === 2 || col === 5) {
          input.classList.add('edge-right');
        }
        if (row === 2 || row === 5) {
          input.classList.add('edge-bottom');
        }

        input.addEventListener('focus', onCellFocus);
        input.addEventListener('click', onCellFocus);
        input.addEventListener('input', onCellInput);
        input.addEventListener('keydown', onCellKeyDown);

        rowCells.push(input);
        fragment.appendChild(input);
      }
      state.cells.push(rowCells);
    }

    dom.board.appendChild(fragment);
  }

  function startNewGame() {
    const initial = generatePuzzle();
    const solution = solveBoard(initial);

    if (!solution) {
      setStatus('퍼즐 생성에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€. μƒˆλ‘œκ³ μΉ¨ ν›„ λ‹€μ‹œ μ‹œλ„ν•˜μ„Έμš”.');
      return;
    }

    state.initial = cloneBoard(initial);
    state.board = cloneBoard(initial);
    state.solution = solution;
    state.analysis = analyzePuzzle(initial);
    state.pendingHint = null;
    state.selected = findFirstEmpty(initial);
    state.showMistakes = false;
    state.hintMessage = '힌트 보기λ₯Ό λˆ„λ₯΄λ©΄ λ‹€μŒ 논리 단계λ₯Ό μ„€λͺ…ν•©λ‹ˆλ‹€.';
    state.gameCount += 1;
    state.learningLog = [
      {
        kind: '뢄석',
        message: describeAnalysis(state.analysis)
      }
    ];

    dom.checkBtn.textContent = 'μ˜€λ‹΅ 확인';
    setStatus('μƒˆ 퍼즐을 λΆˆλŸ¬μ™”μŠ΅λ‹ˆλ‹€.');
    render();
    focusSelectedCell();
  }

  function resetBoard() {
    state.board = cloneBoard(state.initial);
    state.pendingHint = null;
    state.showMistakes = false;
    state.selected = findFirstEmpty(state.initial);
    state.hintMessage = '퍼즐을 초기 μƒνƒœλ‘œ λ˜λŒλ ΈμŠ΅λ‹ˆλ‹€. λ‹€μ‹œ λ…Όλ¦¬λ‘œ ν’€μ–΄λ³΄μ„Έμš”.';
    state.learningLog.unshift({ kind: 'μ΄ˆκΈ°ν™”', message: 'μž…λ ₯ν•œ 값을 μ§€μš°κ³  μ‹œμž‘ μƒνƒœλ‘œ λŒμ•„κ°”μŠ΅λ‹ˆλ‹€.' });
    state.learningLog = state.learningLog.slice(0, 8);
    dom.checkBtn.textContent = 'μ˜€λ‹΅ 확인';
    setStatus('퍼즐을 μ΄ˆκΈ°ν™”ν–ˆμŠ΅λ‹ˆλ‹€.');
    render();
    focusSelectedCell();
  }

  function requestHint() {
    const conflicts = collectConflicts(state.board);
    const wrongCells = collectWrongCells(state.board, state.solution);

    if (conflicts.size > 0) {
      state.pendingHint = null;
      state.hintMessage = '같은 ν–‰, μ—΄ λ˜λŠ” λ°•μŠ€μ— μ€‘λ³΅λœ μˆ«μžκ°€ μžˆμŠ΅λ‹ˆλ‹€. μΆ©λŒμ„ λ¨Όμ € μ •λ¦¬ν•˜μ„Έμš”.';
      setStatus('κ·œμΉ™ 좩돌이 μžˆμ–΄ 힌트λ₯Ό μ€‘λ‹¨ν–ˆμŠ΅λ‹ˆλ‹€.');
      render();
      return;
    }

    if (wrongCells.length > 0) {
      state.pendingHint = null;
      state.showMistakes = true;
      dom.checkBtn.textContent = 'μ˜€λ‹΅ 숨기기';
      state.hintMessage = 'μ •λ‹΅κ³Ό λ‹€λ₯Έ 칸이 μžˆμ–΄ 힌트λ₯Ό λ©ˆμ·„μŠ΅λ‹ˆλ‹€. 뢉은 ν‘œμ‹œλ₯Ό λ¨Όμ € κ³ μ³λ³΄μ„Έμš”.';
      setStatus('μ˜€λ‹΅μ΄ μžˆμ–΄ 힌트λ₯Ό μ€‘λ‹¨ν–ˆμŠ΅λ‹ˆλ‹€.');
      render();
      return;
    }

    if (isSolved(state.board)) {
      state.pendingHint = null;
      state.hintMessage = '이미 퍼즐을 λͺ¨λ‘ ν•΄κ²°ν–ˆμŠ΅λ‹ˆλ‹€. μƒˆ 퍼즐을 μ‹œμž‘ν•  수 μžˆμŠ΅λ‹ˆλ‹€.';
      setStatus('퍼즐이 이미 μ™„μ„±λ˜μ–΄ μžˆμŠ΅λ‹ˆλ‹€.');
      render();
      return;
    }

    const step = findNextLogicalStep(state.board);

    if (!step) {
      state.pendingHint = null;
      state.hintMessage = 'ν˜„μž¬ MVP κ·œμΉ™(단일 후보, μˆ¨μ€ μ‹±κΈ€)λ‘œλŠ” λ‹€μŒ 단계λ₯Ό μ°Ύμ§€ λͺ»ν–ˆμŠ΅λ‹ˆλ‹€.';
      setStatus('μΆ”κ°€ κ·œμΉ™μ΄ ν•„μš”ν•œ κ΅¬κ°„μž…λ‹ˆλ‹€.');
      render();
      return;
    }

    state.pendingHint = step;
    state.selected = { row: step.row, col: step.col };
    state.hintMessage = `${TECHNIQUE_LABELS[step.type]}: ${step.detail}`;
    recordLog('힌트', `${cellRef(step.row, step.col)} = ${step.value} · ${TECHNIQUE_LABELS[step.type]}`);
    setStatus('λ‹€μŒ 논리 단계λ₯Ό μ°Ύμ•˜μŠ΅λ‹ˆλ‹€.');
    render();
    focusSelectedCell();
  }

  function applyHint() {
    if (!state.pendingHint) {
      requestHint();
      return;
    }

    const { row, col, value, type } = state.pendingHint;
    state.board[row][col] = value;
    state.selected = { row, col };
    state.hintMessage = `${cellRef(row, col)}에 ${value}λ₯Ό λ„£μ—ˆμŠ΅λ‹ˆλ‹€. λ‹€μŒ 단계가 ν•„μš”ν•˜λ©΄ λ‹€μ‹œ 힌트λ₯Ό μš”μ²­ν•˜μ„Έμš”.`;
    recordLog('적용', `${cellRef(row, col)} = ${value} · ${TECHNIQUE_LABELS[type]}`);
    state.pendingHint = null;

    if (boardsEqual(state.board, state.solution)) {
      state.hintMessage = '퍼즐을 ν•΄κ²°ν–ˆμŠ΅λ‹ˆλ‹€. μƒˆ 퍼즐둜 λ‹€μ‹œ μ‹œμž‘ν•  수 μžˆμŠ΅λ‹ˆλ‹€.';
      setStatus('μ™„μ„±ν–ˆμŠ΅λ‹ˆλ‹€. λͺ¨λ“  칸이 λ§žμŠ΅λ‹ˆλ‹€.');
      recordLog('μ™„λ£Œ', 'λͺ¨λ“  칸을 μ˜¬λ°”λ₯΄κ²Œ μ±„μ› μŠ΅λ‹ˆλ‹€.');
    } else {
      setStatus('힌트λ₯Ό μ μš©ν–ˆμŠ΅λ‹ˆλ‹€.');
    }

    render();
    focusSelectedCell();
  }

  function toggleMistakes() {
    state.showMistakes = !state.showMistakes;
    dom.checkBtn.textContent = state.showMistakes ? 'μ˜€λ‹΅ 숨기기' : 'μ˜€λ‹΅ 확인';
    setStatus(state.showMistakes ? 'μ˜€λ‹΅ ν‘œμ‹œλ₯Ό μΌ°μŠ΅λ‹ˆλ‹€.' : 'μ˜€λ‹΅ ν‘œμ‹œλ₯Ό κ»μŠ΅λ‹ˆλ‹€.');
    render();
  }

  function onCellFocus(event) {
    const row = Number(event.target.dataset.row);
    const col = Number(event.target.dataset.col);
    state.selected = { row, col };
    renderBoard();
  }

  function onCellInput(event) {
    const input = event.target;
    const row = Number(input.dataset.row);
    const col = Number(input.dataset.col);
    const previousValue = state.board[row][col];

    if (state.initial[row][col] !== 0) {
      input.value = String(state.initial[row][col]);
      return;
    }

    const raw = input.value.replace(/[^1-9]/g, '').slice(-1);
    input.value = raw;
    state.board[row][col] = raw ? Number(raw) : 0;
    state.pendingHint = null;
    state.selected = { row, col };
    const conflicts = collectConflicts(state.board);
    const wrongCells = collectWrongCells(state.board, state.solution);

    if (boardsEqual(state.board, state.solution)) {
      state.hintMessage = '퍼즐을 ν•΄κ²°ν–ˆμŠ΅λ‹ˆλ‹€. μƒˆ 퍼즐둜 λ‹€μ‹œ μ‹œμž‘ν•  수 μžˆμŠ΅λ‹ˆλ‹€.';
      setStatus('μ™„μ„±ν–ˆμŠ΅λ‹ˆλ‹€. λͺ¨λ“  칸이 λ§žμŠ΅λ‹ˆλ‹€.');
      recordLog('μ™„λ£Œ', 'λͺ¨λ“  칸을 μ˜¬λ°”λ₯΄κ²Œ μ±„μ› μŠ΅λ‹ˆλ‹€.');
    } else if (!raw && previousValue !== 0) {
      setStatus('칸을 λΉ„μ› μŠ΅λ‹ˆλ‹€.');
    } else if (!raw) {
      setStatus('1λΆ€ν„° 9κΉŒμ§€μ˜ 숫자만 μž…λ ₯ν•  수 μžˆμŠ΅λ‹ˆλ‹€.');
    } else if (conflicts.size > 0) {
      setStatus('κ·œμΉ™ 좩돌이 μžˆμŠ΅λ‹ˆλ‹€.');
    } else if (wrongCells.length > 0 && countFilled(state.board) === 81) {
      setStatus('μ˜€λ‹΅μ΄ μžˆμŠ΅λ‹ˆλ‹€. μ˜€λ‹΅ ν™•μΈμœΌλ‘œ μ κ²€ν•˜μ„Έμš”.');
    } else {
      const filled = countFilled(state.board);
      setStatus(`${filled}칸을 μ±„μ› μŠ΅λ‹ˆλ‹€.`);
    }

    render();
  }

  function onCellKeyDown(event) {
    const row = Number(event.target.dataset.row);
    const col = Number(event.target.dataset.col);
    let nextRow = row;
    let nextCol = col;

    if (event.key === 'ArrowUp') {
      nextRow = Math.max(0, row - 1);
    } else if (event.key === 'ArrowDown') {
      nextRow = Math.min(8, row + 1);
    } else if (event.key === 'ArrowLeft') {
      nextCol = Math.max(0, col - 1);
    } else if (event.key === 'ArrowRight') {
      nextCol = Math.min(8, col + 1);
    } else if (event.key === 'Backspace' || event.key === 'Delete' || event.key === 'Escape' || event.key === '0' || event.key === ' ') {
      if (state.initial[row][col] === 0) {
        state.board[row][col] = 0;
        state.pendingHint = null;
        state.selected = { row, col };
        setStatus('칸을 λΉ„μ› μŠ΅λ‹ˆλ‹€.');
        render();
      }
      event.preventDefault();
      return;
    } else {
      return;
    }

    event.preventDefault();
    state.selected = { row: nextRow, col: nextCol };
    focusSelectedCell();
    renderBoard();
  }

  function render() {
    renderBoard();
    renderSidebar();
    updateActionButtons();
  }

  function updateActionButtons() {
    const isComplete = boardsEqual(state.board, state.solution);

    dom.hintBtn.disabled = isComplete;
    dom.applyHintBtn.disabled = !state.pendingHint || isComplete;
    dom.resetBtn.disabled = boardsEqual(state.board, state.initial);
    dom.checkBtn.textContent = state.showMistakes ? 'μ˜€λ‹΅ 숨기기' : 'μ˜€λ‹΅ 확인';
    dom.checkBtn.setAttribute('aria-pressed', String(state.showMistakes));
  }

  function renderBoard() {
    const conflicts = collectConflicts(state.board);
    const wrongCells = state.showMistakes ? new Set(collectWrongCells(state.board, state.solution)) : new Set();

    for (let row = 0; row < 9; row += 1) {
      for (let col = 0; col < 9; col += 1) {
        const input = state.cells[row][col];
        const value = state.board[row][col];
        const key = toKey(row, col);
        const isGiven = state.initial[row][col] !== 0;
        const isSelected = Boolean(state.selected && state.selected.row === row && state.selected.col === col);
        const isHint = Boolean(state.pendingHint && state.pendingHint.row === row && state.pendingHint.col === col);
        const hasConflict = conflicts.has(key);
        const hasMistake = wrongCells.has(key);

        input.value = value === 0 ? '' : String(value);
        input.readOnly = isGiven;
        input.classList.toggle('is-given', isGiven);
        input.classList.toggle('is-selected', isSelected);
        input.classList.toggle('is-hint', isHint);
        input.classList.toggle('is-conflict', hasConflict);
        input.classList.toggle('is-mistake', hasMistake);
        input.setAttribute('aria-label', buildCellLabel(row, col, value, isGiven));
        input.setAttribute('aria-selected', String(isSelected));
        input.setAttribute('aria-invalid', String(hasConflict || hasMistake));
        input.setAttribute('aria-readonly', String(isGiven));
      }
    }
  }

  function renderSidebar() {
    const filled = countFilled(state.board);
    const conflicts = collectConflicts(state.board);
    const wrongCells = collectWrongCells(state.board, state.solution);
    const isComplete = boardsEqual(state.board, state.solution);
    let nextTechniqueLabel = 'λŒ€κΈ° 쀑';

    if (isComplete) {
      nextTechniqueLabel = 'μ™„λ£Œ';
    } else if (conflicts.size > 0) {
      nextTechniqueLabel = '좩돌 정리 ν•„μš”';
    } else if (wrongCells.length > 0) {
      nextTechniqueLabel = 'μ˜€λ‹΅ μˆ˜μ • ν•„μš”';
    } else {
      const nextStep = findNextLogicalStep(state.board);
      nextTechniqueLabel = nextStep ? TECHNIQUE_LABELS[nextStep.type] : 'ν˜„μž¬ κ·œμΉ™μœΌλ‘œ μ°Ύμ§€ λͺ»ν•¨';
    }

    dom.puzzleMeta.textContent = `${state.gameCount}번째 퍼즐 Β· 랜덀 λ³€ν˜• ν•™μŠ΅ 퍼즐`;
    dom.difficultyBadge.textContent = state.analysis.difficulty;
    dom.hintMessage.textContent = state.hintMessage;
    dom.filledCount.textContent = String(filled);
    dom.remainingCount.textContent = String(81 - filled);
    dom.nextTechnique.textContent = nextTechniqueLabel;
    dom.analysisSummary.textContent = describeAnalysis(state.analysis);

    dom.logList.innerHTML = '';
    const items = state.learningLog.length > 0 ? state.learningLog : [{ kind: 'μ•ˆλ‚΄', message: '힌트 λ‘œκ·Έκ°€ 여기에 ν‘œμ‹œλ©λ‹ˆλ‹€.' }];
    items.slice(0, 8).forEach((item) => {
      const li = document.createElement('li');
      li.textContent = `${item.kind} Β· ${item.message}`;
      dom.logList.appendChild(li);
    });
  }

  function setStatus(message) {
    dom.gameStatus.textContent = message;
  }

  function recordLog(kind, message) {
    const latest = `${kind}:${message}`;
    const exists = state.learningLog.some((entry) => `${entry.kind}:${entry.message}` === latest);
    if (!exists) {
      state.learningLog.unshift({ kind, message });
      state.learningLog = state.learningLog.slice(0, 8);
    }
  }

  function buildCellLabel(row, col, value, isGiven) {
    if (isGiven) {
      return `${row + 1}ν–‰ ${col + 1}μ—΄, κ³ μ • 숫자 ${value}`;
    }
    if (value === 0) {
      return `${row + 1}ν–‰ ${col + 1}μ—΄, 빈칸`;
    }
    return `${row + 1}ν–‰ ${col + 1}μ—΄, μž…λ ₯κ°’ ${value}`;
  }

  function focusSelectedCell() {
    if (!state.selected) {
      return;
    }
    const cell = state.cells[state.selected.row][state.selected.col];
    if (cell) {
      cell.focus();
    }
  }

  function analyzePuzzle(board) {
    const solverResult = buildSolverLog(board);
    const counts = solverResult.steps.reduce((acc, step) => {
      acc[step.type] = (acc[step.type] || 0) + 1;
      return acc;
    }, {});

    return {
      steps: solverResult.steps,
      solved: solverResult.solved,
      counts,
      difficulty: classifyDifficulty(solverResult.solved, counts)
    };
  }

  function describeAnalysis(analysis) {
    const countSummary = formatTechniqueCounts(analysis.counts);
    if (analysis.solved) {
      return `${analysis.steps.length}단계 논리 풀이 Β· ${countSummary}`;
    }
    return `μΌλΆ€λ§Œ 논리 풀이 κ°€λŠ₯ Β· ${countSummary}`;
  }

  function formatTechniqueCounts(counts) {
    const parts = [];
    if (counts['naked-single']) {
      parts.push(`단일 후보 ${counts['naked-single']}회`);
    }
    if (counts['hidden-single-row']) {
      parts.push(`ν–‰ μˆ¨μ€ μ‹±κΈ€ ${counts['hidden-single-row']}회`);
    }
    if (counts['hidden-single-col']) {
      parts.push(`μ—΄ μˆ¨μ€ μ‹±κΈ€ ${counts['hidden-single-col']}회`);
    }
    if (counts['hidden-single-box']) {
      parts.push(`λ°•μŠ€ μˆ¨μ€ μ‹±κΈ€ ${counts['hidden-single-box']}회`);
    }
    return parts.length > 0 ? parts.join(', ') : 'κΈ°λ³Έ κ·œμΉ™ 뢄석 μ—†μŒ';
  }

  function classifyDifficulty(solved, counts) {
    const hiddenCount = (counts['hidden-single-row'] || 0) + (counts['hidden-single-col'] || 0) + (counts['hidden-single-box'] || 0);
    if (!solved) {
      return 'μ—°μŠ΅';
    }
    if (hiddenCount === 0) {
      return 'μž…λ¬Έ';
    }
    if (hiddenCount <= 8) {
      return 'μ΄ˆκΈ‰';
    }
    return '쀑급';
  }

  function buildSolverLog(board) {
    const working = cloneBoard(board);
    const steps = [];
    let guard = 0;

    while (guard < 100) {
      if (isSolved(working)) {
        return { solved: true, steps };
      }

      const next = findNextLogicalStep(working);
      if (!next) {
        break;
      }

      working[next.row][next.col] = next.value;
      steps.push(next);
      guard += 1;
    }

    return { solved: isSolved(working), steps };
  }

  function findNextLogicalStep(board) {
    const candidates = [];

    for (let row = 0; row < 9; row += 1) {
      candidates[row] = [];
      for (let col = 0; col < 9; col += 1) {
        candidates[row][col] = board[row][col] === 0 ? getCandidates(board, row, col) : [];
      }
    }

    for (let row = 0; row < 9; row += 1) {
      for (let col = 0; col < 9; col += 1) {
        if (board[row][col] !== 0) {
          continue;
        }
        if (candidates[row][col].length === 1) {
          const value = candidates[row][col][0];
          return {
            type: 'naked-single',
            row,
            col,
            value,
            detail: `${cellRef(row, col)}의 ν›„λ³΄λŠ” ${value} ν•˜λ‚˜λΏμž…λ‹ˆλ‹€. ν–‰, μ—΄, λ°•μŠ€μ—μ„œ λ‹€λ₯Έ μˆ«μžκ°€ λͺ¨λ‘ μ œμ™Έλ©λ‹ˆλ‹€.`
          };
        }
      }
    }

    for (let row = 0; row < 9; row += 1) {
      for (let value = 1; value <= 9; value += 1) {
        const spots = [];
        for (let col = 0; col < 9; col += 1) {
          if (candidates[row][col].includes(value)) {
            spots.push({ row, col });
          }
        }
        if (spots.length === 1) {
          return {
            type: 'hidden-single-row',
            row: spots[0].row,
            col: spots[0].col,
            value,
            detail: `${row + 1}ν–‰μ—μ„œ 숫자 ${value}κ°€ λ“€μ–΄κ°ˆ 수 μžˆλŠ” 칸은 ${cellRef(spots[0].row, spots[0].col)} ν•˜λ‚˜λΏμž…λ‹ˆλ‹€.`
          };
        }
      }
    }

    for (let col = 0; col < 9; col += 1) {
      for (let value = 1; value <= 9; value += 1) {
        const spots = [];
        for (let row = 0; row < 9; row += 1) {
          if (candidates[row][col].includes(value)) {
            spots.push({ row, col });
          }
        }
        if (spots.length === 1) {
          return {
            type: 'hidden-single-col',
            row: spots[0].row,
            col: spots[0].col,
            value,
            detail: `${col + 1}μ—΄μ—μ„œ 숫자 ${value}κ°€ λ“€μ–΄κ°ˆ 수 μžˆλŠ” 칸은 ${cellRef(spots[0].row, spots[0].col)} ν•˜λ‚˜λΏμž…λ‹ˆλ‹€.`
          };
        }
      }
    }

    for (let box = 0; box < 9; box += 1) {
      const startRow = Math.floor(box / 3) * 3;
      const startCol = (box % 3) * 3;
      for (let value = 1; value <= 9; value += 1) {
        const spots = [];
        for (let row = startRow; row < startRow + 3; row += 1) {
          for (let col = startCol; col < startCol + 3; col += 1) {
            if (candidates[row][col].includes(value)) {
              spots.push({ row, col });
            }
          }
        }
        if (spots.length === 1) {
          return {
            type: 'hidden-single-box',
            row: spots[0].row,
            col: spots[0].col,
            value,
            detail: `${box + 1}번 λ°•μŠ€μ—μ„œ 숫자 ${value}κ°€ λ“€μ–΄κ°ˆ 수 μžˆλŠ” 칸은 ${cellRef(spots[0].row, spots[0].col)} ν•˜λ‚˜λΏμž…λ‹ˆλ‹€.`
          };
        }
      }
    }

    return null;
  }

  function generatePuzzle() {
    let board = parseBoard(BASE_PUZZLE);
    board = remapDigits(board);
    board = shuffleRows(board);
    board = shuffleCols(board);
    if (Math.random() > 0.5) {
      board = transpose(board);
    }
    return board;
  }

  function remapDigits(board) {
    const digits = shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9]);
    const map = new Map();
    for (let i = 1; i <= 9; i += 1) {
      map.set(i, digits[i - 1]);
    }
    return board.map((row) => row.map((value) => (value === 0 ? 0 : map.get(value))));
  }

  function shuffleRows(board) {
    const bands = shuffle([0, 1, 2]);
    const order = [];
    bands.forEach((band) => {
      shuffle([0, 1, 2]).forEach((offset) => order.push(band * 3 + offset));
    });
    return order.map((rowIndex) => board[rowIndex].slice());
  }

  function shuffleCols(board) {
    const stacks = shuffle([0, 1, 2]);
    const order = [];
    stacks.forEach((stack) => {
      shuffle([0, 1, 2]).forEach((offset) => order.push(stack * 3 + offset));
    });
    return board.map((row) => order.map((colIndex) => row[colIndex]));
  }

  function transpose(board) {
    return board[0].map((_, col) => board.map((row) => row[col]));
  }

  function shuffle(values) {
    const copy = values.slice();
    for (let i = copy.length - 1; i > 0; i -= 1) {
      const j = Math.floor(Math.random() * (i + 1));
      [copy[i], copy[j]] = [copy[j], copy[i]];
    }
    return copy;
  }

  function solveBoard(board) {
    const working = cloneBoard(board);
    return solveRecursive(working) ? working : null;
  }

  function solveRecursive(board) {
    let bestCell = null;
    let bestCandidates = null;

    for (let row = 0; row < 9; row += 1) {
      for (let col = 0; col < 9; col += 1) {
        if (board[row][col] !== 0) {
          continue;
        }
        const candidates = getCandidates(board, row, col);
        if (candidates.length === 0) {
          return false;
        }
        if (!bestCandidates || candidates.length < bestCandidates.length) {
          bestCell = { row, col };
          bestCandidates = candidates;
        }
      }
    }

    if (!bestCell) {
      return true;
    }

    for (const value of bestCandidates) {
      board[bestCell.row][bestCell.col] = value;
      if (solveRecursive(board)) {
        return true;
      }
    }

    board[bestCell.row][bestCell.col] = 0;
    return false;
  }

  function getCandidates(board, row, col) {
    if (board[row][col] !== 0) {
      return [];
    }
    const candidates = [];
    for (let value = 1; value <= 9; value += 1) {
      if (isValidPlacement(board, row, col, value)) {
        candidates.push(value);
      }
    }
    return candidates;
  }

  function isValidPlacement(board, row, col, value) {
    for (let index = 0; index < 9; index += 1) {
      if (board[row][index] === value) {
        return false;
      }
      if (board[index][col] === value) {
        return false;
      }
    }

    const startRow = Math.floor(row / 3) * 3;
    const startCol = Math.floor(col / 3) * 3;
    for (let r = startRow; r < startRow + 3; r += 1) {
      for (let c = startCol; c < startCol + 3; c += 1) {
        if (board[r][c] === value) {
          return false;
        }
      }
    }
    return true;
  }

  function collectConflicts(board) {
    const conflicts = new Set();

    for (let row = 0; row < 9; row += 1) {
      markHouseConflicts(conflicts, Array.from({ length: 9 }, (_, col) => ({ row, col, value: board[row][col] })));
    }
    for (let col = 0; col < 9; col += 1) {
      markHouseConflicts(conflicts, Array.from({ length: 9 }, (_, row) => ({ row, col, value: board[row][col] })));
    }
    for (let box = 0; box < 9; box += 1) {
      const startRow = Math.floor(box / 3) * 3;
      const startCol = (box % 3) * 3;
      const cells = [];
      for (let row = startRow; row < startRow + 3; row += 1) {
        for (let col = startCol; col < startCol + 3; col += 1) {
          cells.push({ row, col, value: board[row][col] });
        }
      }
      markHouseConflicts(conflicts, cells);
    }

    return conflicts;
  }

  function markHouseConflicts(conflicts, cells) {
    const buckets = new Map();
    cells.forEach((cell) => {
      if (cell.value === 0) {
        return;
      }
      if (!buckets.has(cell.value)) {
        buckets.set(cell.value, []);
      }
      buckets.get(cell.value).push(cell);
    });

    buckets.forEach((items) => {
      if (items.length > 1) {
        items.forEach((cell) => conflicts.add(toKey(cell.row, cell.col)));
      }
    });
  }

  function collectWrongCells(board, solution) {
    const wrong = [];
    for (let row = 0; row < 9; row += 1) {
      for (let col = 0; col < 9; col += 1) {
        if (board[row][col] !== 0 && board[row][col] !== solution[row][col]) {
          wrong.push(toKey(row, col));
        }
      }
    }
    return wrong;
  }

  function findFirstEmpty(board) {
    for (let row = 0; row < 9; row += 1) {
      for (let col = 0; col < 9; col += 1) {
        if (board[row][col] === 0) {
          return { row, col };
        }
      }
    }
    return { row: 0, col: 0 };
  }

  function isSolved(board) {
    return board.every((row) => row.every((value) => value !== 0));
  }

  function countFilled(board) {
    return board.flat().filter((value) => value !== 0).length;
  }

  function boardsEqual(a, b) {
    for (let row = 0; row < 9; row += 1) {
      for (let col = 0; col < 9; col += 1) {
        if (a[row][col] !== b[row][col]) {
          return false;
        }
      }
    }
    return true;
  }

  function cloneBoard(board) {
    return board.map((row) => row.slice());
  }

  function parseBoard(serialized) {
    const board = [];
    for (let row = 0; row < 9; row += 1) {
      const currentRow = [];
      for (let col = 0; col < 9; col += 1) {
        currentRow.push(Number(serialized[row * 9 + col]));
      }
      board.push(currentRow);
    }
    return board;
  }

  function toKey(row, col) {
    return `${row}-${col}`;
  }

  function cellRef(row, col) {
    return `${row + 1}ν–‰ ${col + 1}μ—΄`;
  }
});