/**
 * Signature Field Frontend JavaScript
 *
 * Initializes the signature pad for signature fields on registration forms
 *
 * @since 4.3.0
 */
(function($) {
    'use strict';

    var WPUF_Signature_Field = {

        // Store signature pad instances
        signaturePads: {},

        // Initialize signature fields
        init: function() {
            var self = this;

            // Initialize each signature container
            $('.wpuf-signature-container').each(function() {
                self.initSignatureField($(this));
            });

            // Handle clear button clicks
            $(document).on('click', '.wpuf-clear-signature', function(e) {
                e.preventDefault();
                var fieldId = $(this).data('target');
                self.clearSignature(fieldId);
            });

            // Handle form submission to capture signature data
            $('form').on('submit', function() {
                self.captureSignatures();
            });
        },

        // Initialize a single signature field
        initSignatureField: function($container) {
            var self = this;
            var $canvas = $container.find('.signature-canvas');
            var $hiddenInput = $container.find('.signature-data');
            var fieldId = $container.data('field-id');
            var width = parseInt($container.data('width')) || 450;
            var height = parseInt($container.data('height')) || 150;

            // Ensure the signature pad library is loaded
            if (typeof SignaturePad === 'undefined') {
                console.error('SignaturePad library not loaded');
                return;
            }

            // Set canvas dimensions
            $canvas.attr('width', width);
            $canvas.attr('height', height);

            // Get canvas context
            var canvas = $canvas[0];
            var context = canvas.getContext('2d');

            // Create signature data object to track placeholder state
            var signatureData = {
                $container: $container,
                $canvas: $canvas,
                $hiddenInput: $hiddenInput,
                width: width,
                height: height,
                hasPlaceholder: true // Track if placeholder is currently visible
            };

            // Initialize SignaturePad
            var signaturePad = new SignaturePad(canvas, {
                minWidth: 0.5,
                maxWidth: 2.5,
                penColor: 'rgb(0, 0, 0)',
                backgroundColor: 'rgb(255, 255, 255)'
            });

            // Store the pad instance in signature data
            signatureData.pad = signaturePad;

            // Use proper SignaturePad events (beginStroke and endStroke)
            signaturePad.addEventListener('beginStroke', function() {
                // Clear placeholder when user starts drawing
                if (signatureData.hasPlaceholder) {
                    context.clearRect(0, 0, width, height);
                    signatureData.hasPlaceholder = false;
                }
            });

            signaturePad.addEventListener('endStroke', function() {
                // Store signature data when finished - use toSVG() to get SVG string without background
                var svgString = signaturePad.toSVG();
                self.updateSignatureData(fieldId, svgString);
            });

            // Draw placeholder initially (canvas is empty on initialization)
            self.drawPlaceholder(context, width, height);

            // Store the instance
            self.signaturePads[fieldId] = signatureData;

            // Handle touch events for mobile
            self.setupTouchEvents(canvas);
        },

        // Draw dotted line placeholder
        drawPlaceholder: function(context, width, height) {
            context.strokeStyle = '#ddd';
            context.lineWidth = 1;
            context.setLineDash([5, 5]);

            // Draw line in the middle
            context.beginPath();
            context.moveTo(20, height / 2);
            context.lineTo(width - 20, height / 2);
            context.stroke();

            // Reset line dash
            context.setLineDash([]);

            // Add text "Sign here"
            context.font = '14px Arial';
            context.fillStyle = '#ccc';
            context.textAlign = 'center';
            context.fillText('Sign here', width / 2, height / 2 - 10);
        },

        // Setup touch events for mobile
        setupTouchEvents: function(canvas) {
            // Prevent scrolling when touching the canvas
            canvas.addEventListener('touchstart', function(e) {
                e.preventDefault();
            }, { passive: false });

            canvas.addEventListener('touchmove', function(e) {
                e.preventDefault();
            }, { passive: false });
        },

        // Clear signature
        clearSignature: function(fieldId) {
            var signatureData = this.signaturePads[fieldId];

            if (signatureData) {
                // Clear the signature pad
                signatureData.pad.clear();
                
                // Get fresh context and redraw placeholder
                var canvas = signatureData.$canvas[0];
                var context = canvas.getContext('2d');
                
                this.drawPlaceholder(context, signatureData.width, signatureData.height);
                
                // Mark placeholder as visible
                signatureData.hasPlaceholder = true;
                
                // Update hidden input
                this.updateSignatureData(fieldId, '');
            }
        },

        // Update signature data in hidden field
        updateSignatureData: function(fieldId, data) {
            var signatureData = this.signaturePads[fieldId];
            // Check if SVG string is not empty (SVG should start with <svg)
            var hasData = data && data !== '' && data.trim() !== '' && data.indexOf('<svg') !== -1;

            if (signatureData) {
                signatureData.$hiddenInput.val(data);

                // Trigger change event
                signatureData.$hiddenInput.trigger('change');

                // Remove or add required validation class
                if (hasData) {
                    signatureData.$container.removeClass('wpuf-signature-empty');
                } else {
                    signatureData.$container.addClass('wpuf-signature-empty');
                }
            }
        },

        // Capture all signatures before form submission
        captureSignatures: function() {
            var self = this;

            Object.keys(this.signaturePads).forEach(function(fieldId) {
                var signatureData = self.signaturePads[fieldId];

                if (signatureData && !signatureData.pad.isEmpty()) {
                    // Use toSVG() to get SVG string without background
                    var svgString = signatureData.pad.toSVG();
                    if (svgString && svgString.trim() !== '' && svgString.indexOf('<svg') !== -1) {
                        self.updateSignatureData(fieldId, svgString);
                    }
                }
            });
        },

        // Validate required signature fields
        validateSignatures: function() {
            var isValid = true;
            var self = this;

            $('.wpuf-signature-container').each(function() {
                var $container = $(this);
                var fieldId = $container.data('field-id');
                var signatureData = self.signaturePads[fieldId];
                var isRequired = $container.data('required') === '1';

                if (isRequired && signatureData) {
                    var inputValue = signatureData.$hiddenInput.val() || '';
                    var isEmpty = !inputValue || 
                                 inputValue.trim() === '' || 
                                 inputValue.indexOf('<svg') === -1 ||
                                 signatureData.pad.isEmpty();

                    if (isEmpty) {
                        isValid = false;
                        $container.addClass('wpuf-signature-error');

                        // Remove error after user starts drawing
                        signatureData.$canvas.on('beginSign', function() {
                            $container.removeClass('wpuf-signature-error');
                        });
                    } else {
                        $container.removeClass('wpuf-signature-error');
                    }
                }
            });

            return isValid;
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        WPUF_Signature_Field.init();

        // Expose validation method for WPUF form validation
        window.WPUF_Signature_Validate = WPUF_Signature_Field.validateSignatures;
        
        // Expose the main object for validation access
        window.WPUF_Signature_Field = WPUF_Signature_Field;
    });

})(jQuery);