/**
 * @package Divine_Agreement_System
 * @author Aditya Singh
 */

(function($) {
    'use strict';

    var divineSignaturePad;

    $(document).ready(function() {
        divineInitSignaturePad();
        divineInitFormSubmission();
    });

    function divineInitSignaturePad() {
        var canvas = document.getElementById('divine-signature-pad');

        if (!canvas) {
            return;
        }

        divineSignaturePad = divineCreateSignaturePad(canvas);

        divineResizeCanvas(canvas);

        $('#divine-clear-signature').on('click', function(e) {
            e.preventDefault();
            divineSignaturePad.clear();
        });

        $(window).on('resize', function() {
            divineResizeCanvas(canvas);
        });
    }

    function divineResizeCanvas(canvas) {
        var ratio = Math.max(window.devicePixelRatio || 1, 1);
        var wrapper = canvas.parentElement;
        var imageData = null;

        if (canvas.width && canvas.height && divineSignaturePad && !divineSignaturePad.isEmpty()) {
            imageData = divineSignaturePad.toDataURL('image/png');
        }

        canvas.width = wrapper.offsetWidth * ratio;
        canvas.height = 200 * ratio;
        canvas.getContext('2d').scale(ratio, ratio);

        if (divineSignaturePad && imageData) {
            divineSignaturePad.fromDataURL(imageData);
        } else if (divineSignaturePad) {
            divineSignaturePad.clear();
        }
    }

    function divineCreateSignaturePad(canvas) {
        if (typeof SignaturePad === 'function') {
            return new SignaturePad(canvas, {
                backgroundColor: 'rgb(255, 255, 255)',
                penColor: 'rgb(0, 0, 0)',
                minWidth: 1,
                maxWidth: 3
            });
        }

        var context = canvas.getContext('2d');
        var drawing = false;
        var hasSignature = false;
        var lastX = 0;
        var lastY = 0;

        context.lineCap = 'round';
        context.lineJoin = 'round';
        context.strokeStyle = 'rgb(0, 0, 0)';
        context.lineWidth = 2;

        function getPoint(event) {
            var rect = canvas.getBoundingClientRect();
            var source = event.touches ? event.touches[0] : event;

            return {
                x: source.clientX - rect.left,
                y: source.clientY - rect.top
            };
        }

        function startDrawing(event) {
            event.preventDefault();

            var point = getPoint(event);

            drawing = true;
            lastX = point.x;
            lastY = point.y;
            context.beginPath();
            context.moveTo(lastX, lastY);
            context.lineTo(lastX, lastY);
            context.stroke();
            hasSignature = true;
        }

        function draw(event) {
            if (!drawing) {
                return;
            }

            event.preventDefault();

            var point = getPoint(event);

            context.beginPath();
            context.moveTo(lastX, lastY);
            context.lineTo(point.x, point.y);
            context.stroke();

            lastX = point.x;
            lastY = point.y;
            hasSignature = true;
        }

        function stopDrawing(event) {
            if (event) {
                event.preventDefault();
            }

            drawing = false;
        }

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

        return {
            clear: function() {
                context.clearRect(0, 0, canvas.width, canvas.height);
                hasSignature = false;
            },
            isEmpty: function() {
                return !hasSignature;
            },
            toDataURL: function() {
                return canvas.toDataURL('image/png');
            },
            fromDataURL: function(dataUrl) {
                var image = new Image();
                image.onload = function() {
                    context.clearRect(0, 0, canvas.width, canvas.height);
                    context.drawImage(image, 0, 0, canvas.width, canvas.height);
                    hasSignature = true;
                };
                image.src = dataUrl;
            }
        };
    }

    function divineInitFormSubmission() {
        $('#divine-signature-form').on('submit', function(e) {
            e.preventDefault();

            if (!divineSignaturePad) {
                divineShowMessage('Signature pad could not be loaded.', 'error');
                return false;
            }

            if (divineSignaturePad.isEmpty()) {
                divineShowMessage('Please provide your signature.', 'error');
                return false;
            }

            var nonceField = $('#divine_signature_nonce').val();

            var formData = {
                action: 'divine_submit_signature',
                nonce: nonceField || divineAgreementData.nonce,
                token: $('#divine_token').val(),
                name: $('#divine_name').val(),
                email: $('#divine_email').val(),
                address: $('#divine_address').val(),
                signature: divineSignaturePad.toDataURL('image/png'),
                acceptance: $('#divine_acceptance').is(':checked') ? 'yes' : 'no'
            };

            var $submitBtn = $('#divine-submit-btn');
            var originalText = $submitBtn.text();
            $submitBtn.prop('disabled', true).text('Processing...');
            $('#divine-loading').show();

            $.ajax({
                url: divineAgreementData.ajaxUrl,
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        divineShowMessage(response.data.message, 'success');

                        $('#divine-signature-form').fadeOut();

                        setTimeout(function() {
                            var successHtml = '<div class="divine-success-box">' +
                                '<h2>&#10003; Agreement Signed Successfully!</h2>' +
                                '<p>Thank you for signing the agreement. A copy has been sent to your email address.</p>' +
                                '<p>You may now close this page.</p>' +
                                '</div>';
                            $('.divine-signature-section').html(successHtml);
                        }, 1000);
                    } else {
                        divineShowMessage(response.data.message, 'error');
                        $submitBtn.prop('disabled', false).text(originalText);
                        $('#divine-loading').hide();
                    }
                },
                error: function() {
                    divineShowMessage('An error occurred. Please try again.', 'error');
                    $submitBtn.prop('disabled', false).text(originalText);
                    $('#divine-loading').hide();
                }
            });

            return false;
        });
    }

    function divineShowMessage(message, type) {
        var $messageDiv = $('#divine-message');
        var className = type === 'success' ? 'divine-message-success' : 'divine-message-error';

        $messageDiv
            .removeClass('divine-message-success divine-message-error')
            .addClass(className)
            .html(message)
            .fadeIn();

        $('html, body').animate({
            scrollTop: $messageDiv.offset().top - 100
        }, 500);

        if (type === 'success') {
            setTimeout(function() {
                $messageDiv.fadeOut();
            }, 5000);
        }
    }

})(jQuery);
