import { UI } from '../modules/ui.js';
import { Api } from '../modules/api.js';
import { CommonCanvas } from '../modules/canvas_utils.js';

document.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('nonogramCanvas');
    if (!canvas || !window.puzzleData) return;
    const p = window.puzzleData;
    const V = 800, CELL = 40, H = 220;
    const common = CommonCanvas.init(canvas, V, V+100);
    const { ctx, resize, getCoords, fillRoundRect, showSuccessOverlay } = common;

    let board = Array.from({length: p.rowClues.length}, () => Array(p.colClues.length).fill(0));
    let lives = 5, isWin = false, playMode = 'fill';

    // 배경 이미지 로드
    const revealImg = new Image();
    if (p.originalImageFile) revealImg.src = '/uploads/' + p.originalImageFile;
    revealImg.onload = () => draw();

    const ui = {
        fill: { x: 20, y: V+20, w: 100, h: 50, label: "■ 채우기" },
        mark: { x: 140, y: V+20, w: 100, h: 50, label: "X 표시" }
    };

    function draw() {
        ctx.clearRect(0,0,V,V+100); ctx.fillStyle = "#fff"; ctx.fillRect(0,0,V,V+100);

        // 배경 이미지 (투명도 조절)
        if (revealImg.complete && revealImg.naturalWidth) {
            ctx.globalAlpha = isWin ? 1.0 : 0.15;
            ctx.drawImage(revealImg, H, H, V-H, V-H);
            ctx.globalAlpha = 1.0;
        }

        // 힌트 및 그리드
        drawHints();
        drawBoard();

        // 하단 UI
        fillRoundRect(ui.fill.x, ui.fill.y, ui.fill.w, ui.fill.h, 10, playMode==='fill'?"#4a90e2":"#eee");
        fillRoundRect(ui.mark.x, ui.mark.y, ui.mark.w, ui.mark.h, 10, playMode==='mark'?"#4a90e2":"#eee");
        ctx.fillStyle = "#333"; ctx.font = "18px Arial"; ctx.textAlign = "center";
        ctx.fillText(ui.fill.label, ui.fill.x+50, ui.fill.y+32);
        ctx.fillText(ui.mark.label, ui.mark.x+50, ui.mark.y+32);

        ctx.textAlign = "right"; ctx.fillText(`LIFE: ${lives}`, V-30, V+50);
    }

    function drawHints() {
        ctx.fillStyle = "#333"; ctx.font = "bold 14px monospace"; ctx.textAlign = "right";
        p.rowClues.forEach((hints, r) => {
            hints.forEach((n, i) => ctx.fillText(n, H-10 - i*20, H + r*CELL + 25));
        });
        ctx.textAlign = "center";
        p.colClues.forEach((hints, c) => {
            hints.forEach((n, i) => ctx.fillText(n, H + c*CELL + 20, H - 10 - i*20));
        });
    }

    function drawBoard() {
        board.forEach((row, r) => row.forEach((val, c) => {
            const x = H + c*CELL, y = H + r*CELL;
            ctx.strokeStyle = "#bbb"; ctx.strokeRect(x, y, CELL, CELL);
            if (val === 1) { ctx.fillStyle = "#333"; ctx.fillRect(x+2, y+2, CELL-4, CELL-4); }
            else if (val === 2) {
                ctx.strokeStyle = "red"; ctx.lineWidth = 2;
                ctx.beginPath(); ctx.moveTo(x+5,y+5); ctx.lineTo(x+35,y+35); ctx.moveTo(x+35,y+5); ctx.lineTo(x+5,y+35); ctx.stroke();
            }
        }));
    }

    canvas.addEventListener('mousedown', (e) => {
        if (isWin) return;
        const pos = getCoords(e);

        // UI 클릭
        if (common.isInside(pos, ui.fill)) { playMode = 'fill'; draw(); return; }
        if (common.isInside(pos, ui.mark)) { playMode = 'mark'; draw(); return; }

        // 보드 클릭 (우클릭 마크 지원)
        const c = Math.floor((pos.x - H)/CELL), r = Math.floor((pos.y - H)/CELL);
        if (r >= 0 && c >= 0) {
            const mode = (e.button === 2) ? 'mark' : playMode;
            processMove(r, c, mode);
        }
        draw();
    });

    // 우클릭 메뉴 방지
    canvas.addEventListener('contextmenu', e => e.preventDefault());

    function processMove(r, c, mode) {
        if (board[r][c] !== 0) return;
        if (mode === 'fill') {
            if (p.solutionGrid[r][c] === 1) {
                board[r][c] = 1;
                if (checkClear()) {
                    isWin = true;
                    showSuccessOverlay({ title: "NONOGRAM CLEAR!", scoreValue: lives });
                    setTimeout(() => Api.request('/api/puzzle/clear', 'POST', { puzzleId: p.id }), 2500);
                }
            } else {
                board[r][c] = 2; lives--;
                if(lives <= 0) location.reload();
            }
        } else {
            board[r][c] = 2;
        }
    }

    function checkClear() {
        return p.solutionGrid.every((row, r) => row.every((val, c) => (val === 1 ? board[r][c] === 1 : true)));
    }

    resize(); draw();
});