(function () {
    'use strict';

    const canvas = document.getElementById('signatureCanvas');
    if (!canvas) {
        return;
    }

    const ctx = canvas.getContext('2d');
    let drawing = false;
    let hasSignature = false;

    const drawScreen = document.getElementById('drawPanel');
    const drawStage = document.getElementById('regDrawStage');
    const uploadInput = document.getElementById('signatureUpload');
    const uploadPreview = document.getElementById('uploadPreview');
    const uploadSimple = document.querySelector('.reg-sign-upload-simple');
    const drawHint = document.querySelector('.reg-sign-draw-hint');

    function hideDrawHint() {
        if (drawHint) {
            drawHint.classList.add('hidden');
        }
    }

    function showDrawHint() {
        if (drawHint && !hasSignature) {
            drawHint.classList.remove('hidden');
        }
    }

    function isDrawScreenOpen() {
        return drawScreen && !drawScreen.classList.contains('hidden');
    }

    function resizeCanvas() {
        const wrap = drawStage ? drawStage.querySelector('.reg-sign-draw-frame') : canvas.parentElement;
        const rect = wrap ? wrap.getBoundingClientRect() : canvas.getBoundingClientRect();
        canvas.width = rect.width * window.devicePixelRatio;
        canvas.height = rect.height * window.devicePixelRatio;
        ctx.setTransform(1, 0, 0, 1, 0, 0);
        ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
        ctx.strokeStyle = '#0a0a0a';
        ctx.lineWidth = 2.5;
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
    }

    function resizeCanvasIfVisible() {
        if (!isDrawScreenOpen()) {
            return;
        }

        const imageData = hasSignature ? canvas.toDataURL() : null;
        resizeCanvas();

        if (imageData) {
            const img = new Image();
            img.onload = function () {
                const rect = canvas.getBoundingClientRect();
                ctx.drawImage(img, 0, 0, rect.width, rect.height);
            };
            img.src = imageData;
        }
    }

    function getPos(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;
        return { x: clientX - rect.left, y: clientY - rect.top };
    }

    function startDraw(e) {
        if (!isDrawScreenOpen()) {
            return;
        }
        e.preventDefault();
        drawing = true;
        hideDrawHint();
        const pos = getPos(e);
        ctx.beginPath();
        ctx.moveTo(pos.x, pos.y);
    }

    function draw(e) {
        if (!drawing) {
            return;
        }
        e.preventDefault();
        const pos = getPos(e);
        ctx.lineTo(pos.x, pos.y);
        ctx.stroke();
        hasSignature = true;
        window.dispatchEvent(new CustomEvent('reg-draw-changed'));
    }

    function stopDraw() {
        drawing = false;
    }

    function clearCanvas() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        hasSignature = false;
        showDrawHint();
        window.dispatchEvent(new CustomEvent('reg-draw-changed'));
    }

    const clearBtn = document.getElementById('clearSignature');
    if (clearBtn) {
        clearBtn.addEventListener('click', clearCanvas);
    }

    if (uploadInput) {
        uploadInput.addEventListener('change', function (e) {
            const file = e.target.files[0];
            if (!file) {
                return;
            }
            const reader = new FileReader();
            reader.onload = function (ev) {
                if (uploadPreview) {
                    uploadPreview.src = ev.target.result;
                    uploadPreview.classList.remove('hidden');
                }
                if (uploadSimple) {
                    uploadSimple.classList.add('hidden');
                }
                window.dispatchEvent(new CustomEvent('reg-upload-changed'));
            };
            reader.readAsDataURL(file);
        });
    }

    window.addEventListener('resize', resizeCanvasIfVisible);
    window.addEventListener('reg-draw-opened', resizeCanvasIfVisible);
    window.addEventListener('orientationchange', function () {
        window.setTimeout(resizeCanvasIfVisible, 150);
    });

    if (drawStage && typeof ResizeObserver !== 'undefined') {
        const drawFrame = drawStage.querySelector('.reg-sign-draw-frame');
        if (drawFrame) {
            new ResizeObserver(function () {
                resizeCanvasIfVisible();
            }).observe(drawFrame);
        }
    }

    canvas.addEventListener('mousedown', startDraw);
    canvas.addEventListener('mousemove', draw);
    canvas.addEventListener('mouseup', stopDraw);
    canvas.addEventListener('mouseleave', stopDraw);
    canvas.addEventListener('touchstart', startDraw, { passive: false });
    canvas.addEventListener('touchmove', draw, { passive: false });
    canvas.addEventListener('touchend', stopDraw);

    function trimCanvasToSignature() {
        const padding = Math.max(8, Math.round(10 * window.devicePixelRatio));
        const width = canvas.width;
        const height = canvas.height;
        const imageData = ctx.getImageData(0, 0, width, height);
        const pixels = imageData.data;
        let minX = width;
        let minY = height;
        let maxX = 0;
        let maxY = 0;
        let found = false;

        for (let y = 0; y < height; y++) {
            for (let x = 0; x < width; x++) {
                const index = (y * width + x) * 4;
                const alpha = pixels[index + 3];
                if (alpha <= 0) {
                    continue;
                }
                found = true;
                if (x < minX) {
                    minX = x;
                }
                if (y < minY) {
                    minY = y;
                }
                if (x > maxX) {
                    maxX = x;
                }
                if (y > maxY) {
                    maxY = y;
                }
            }
        }

        if (!found) {
            return canvas.toDataURL('image/png');
        }

        minX = Math.max(0, minX - padding);
        minY = Math.max(0, minY - padding);
        maxX = Math.min(width - 1, maxX + padding);
        maxY = Math.min(height - 1, maxY + padding);

        const trimmedWidth = maxX - minX + 1;
        const trimmedHeight = maxY - minY + 1;
        const trimmedCanvas = document.createElement('canvas');
        trimmedCanvas.width = trimmedWidth;
        trimmedCanvas.height = trimmedHeight;
        trimmedCanvas.getContext('2d').drawImage(
            canvas,
            minX,
            minY,
            trimmedWidth,
            trimmedHeight,
            0,
            0,
            trimmedWidth,
            trimmedHeight
        );

        return trimmedCanvas.toDataURL('image/png');
    }

    window.KarviSignature = {
        hasSignature: function () {
            return hasSignature;
        },
        toDataUrl: function () {
            return trimCanvasToSignature();
        },
        reset: function () {
            clearCanvas();
            showDrawHint();
            if (uploadPreview) {
                uploadPreview.classList.add('hidden');
                uploadPreview.src = '';
            }
            if (uploadInput) {
                uploadInput.value = '';
            }
            if (uploadSimple) {
                uploadSimple.classList.remove('hidden');
            }
        },
    };
})();
