/**
 * CommonCanvas.js
 * - 고해상도(DPR) 대응, 모바일 터치 최적화
 * - 성공 오버레이 & 폭죽(Particles) 효과 통합
 */
export const CommonCanvas = {
    init(canvas, logicalWidth, logicalHeight) {
        if (!canvas) return null;
        const ctx = canvas.getContext('2d');
        const container = canvas.parentElement;
        const dpr = window.devicePixelRatio || 1;

        let particles = [];
        let animationId = null;

        // 모바일 스크롤 방지
        canvas.style.touchAction = 'none';

        // 1. 리사이징 함수
        const resize = () => {
            const style = getComputedStyle(container);
            const availableWidth = container.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);

            // 비율 유지 계산
            const scale = availableWidth / logicalWidth;
            const displayHeight = logicalHeight * scale;

            canvas.style.width = `${availableWidth}px`;
            canvas.style.height = `${displayHeight}px`;

            // 실제 픽셀 해상도 (선명하게)
            canvas.width = availableWidth * dpr;
            canvas.height = displayHeight * dpr;

            // 컨텍스트 스케일링
            ctx.setTransform(1, 0, 0, 1, 0, 0); // 초기화
            ctx.scale(dpr * scale, dpr * scale);

            return { scale };
        };

        // 2. 좌표 계산 (마우스/터치 통합)
        const getCoords = (e) => {
            const rect = canvas.getBoundingClientRect();
            const clientX = e.touches ? e.touches[0].clientX : e.clientX;
            const clientY = e.touches ? e.touches[0].clientY : e.clientY;

            // 현재 스케일 역산
            const scaleX = logicalWidth / rect.width;
            const scaleY = logicalHeight / rect.height;

            return {
                x: (clientX - rect.left) * scaleX,
                y: (clientY - rect.top) * scaleY
            };
        };

        // 3. UI 유틸리티
        const isInside = (pos, rect) => {
            return pos.x >= rect.x && pos.x <= rect.x + rect.w &&
                pos.y >= rect.y && pos.y <= rect.y + rect.h;
        };

        const fillRoundRect = (x, y, w, h, r, color) => {
            ctx.save();
            ctx.fillStyle = color;
            if (ctx.roundRect) {
                ctx.beginPath(); ctx.roundRect(x, y, w, h, r); ctx.fill();
            } else {
                // 구형 브라우저 호환
                ctx.fillRect(x, y, w, h);
            }
            ctx.restore();
        };

        // 4. 폭죽(Particles) 효과 로직
        const createParticles = () => {
            for (let i = 0; i < 80; i++) {
                particles.push({
                    x: logicalWidth / 2,
                    y: logicalHeight / 2,
                    vx: (Math.random() - 0.5) * 15,
                    vy: (Math.random() - 0.5) * 15 - 5,
                    size: Math.random() * 5 + 3,
                    color: `hsl(${Math.random() * 360}, 80%, 60%)`,
                    life: 1.0,
                    decay: 0.01 + Math.random() * 0.02
                });
            }
        };

        const showSuccessOverlay = (data) => {
            const { title = "SUCCESS!", scoreLabel = "SCORE", scoreValue, timeValue } = data;
            createParticles();

            const renderFrame = () => {
                // 배경 (약간 투명한 검정)
                ctx.fillStyle = "rgba(0, 0, 0, 0.6)";
                ctx.fillRect(0, 0, logicalWidth, logicalHeight);

                // 폭죽 그리기
                particles.forEach((p, i) => {
                    p.x += p.vx;
                    p.y += p.vy;
                    p.vy += 0.2; // 중력
                    p.life -= p.decay;

                    if (p.life <= 0) particles.splice(i, 1);

                    ctx.save();
                    ctx.globalAlpha = p.life;
                    ctx.fillStyle = p.color;
                    ctx.beginPath();
                    ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
                    ctx.fill();
                    ctx.restore();
                });

                // 메시지 박스
                const boxW = Math.min(logicalWidth * 0.8, 500);
                const boxH = 300;
                const boxX = (logicalWidth - boxW) / 2;
                const boxY = (logicalHeight - boxH) / 2;

                fillRoundRect(boxX, boxY, boxW, boxH, 20, "#ffffff");

                // 텍스트
                ctx.fillStyle = "#4CAF50";
                ctx.font = "bold 50px Arial";
                ctx.textAlign = "center";
                ctx.fillText(title, logicalWidth / 2, boxY + 80);

                ctx.fillStyle = "#333";
                ctx.font = "bold 24px Arial";
                let textY = boxY + 150;

                if (timeValue !== undefined) {
                    const m = String(Math.floor(timeValue / 60)).padStart(2, '0');
                    const s = String(timeValue % 60).padStart(2, '0');
                    ctx.fillText(`TIME: ${m}:${s}`, logicalWidth / 2, textY);
                    textY += 40;
                }

                if (scoreValue !== undefined) {
                    ctx.fillText(`${scoreLabel}: ${scoreValue}`, logicalWidth / 2, textY);
                    textY += 40;
                }

                ctx.fillStyle = "#666";
                ctx.font = "16px Arial";
                ctx.fillText("잠시 후 결과가 저장됩니다...", logicalWidth / 2, boxY + 260);

                if (particles.length > 0) {
                    animationId = requestAnimationFrame(renderFrame);
                }
            };

            if (animationId) cancelAnimationFrame(animationId);
            renderFrame();
        };

        return { ctx, resize, getCoords, isInside, fillRoundRect, showSuccessOverlay };
    }
};