/**
 * Signature Field Frontend Validation
 *
 * @since 4.2.9
 */
(function ($) {
    "use strict";

    // Store signature validation errors
    var signatureErrors = [];

    // Bind directly to forms to ensure we run before delegated handlers
    function bindSignatureValidation() {
        $('form.wpuf-form-add').off('submit.signature-validation').on('submit.signature-validation', function (e) {
            var $form = $(this);
            var hasErrors = false;
            var firstErrorField = null;
            signatureErrors = []; // Reset errors array

            // Remove any previous signature validation flags
            $form.removeData('wpuf-signature-validation-failed');

            // Validate each signature field
            $form.find('.wpuf-signature-container').each(function () {
                var $container = $(this);
                var fieldId = $container.data('field-id');
                var isRequired = $container.data('required');
                var $hiddenInput = $container.find('.signature-data');
                var $wrapper = $container.closest('.wpuf-fields');

                // Only validate if field is required
                if (isRequired === 'yes' || isRequired === '1' || isRequired === true || isRequired === 1) {
                    var isEmpty = false;

                    // Check SignaturePad instance to determine if signature is actually empty
                    // This is important because the placeholder creates a base64 image
                    if (typeof window.WPUF_Signature_Field !== 'undefined' &&
                        window.WPUF_Signature_Field.signaturePads &&
                        window.WPUF_Signature_Field.signaturePads[fieldId]) {
                        var signatureData = window.WPUF_Signature_Field.signaturePads[fieldId];

                        // Check if placeholder is still visible (meaning user hasn't drawn anything)
                        if (signatureData.hasPlaceholder === true) {
                            isEmpty = true;
                        } else if (signatureData.pad) {
                            // Also check SignaturePad's isEmpty() method as backup
                            if (signatureData.pad.isEmpty()) {
                                isEmpty = true;
                            }
                        }
                    } else {
                        // Fallback: Check if hidden input is empty or not a valid SVG string
                        var signatureValue = $hiddenInput.val() || '';
                        if (!signatureValue ||
                            signatureValue.trim() === '' ||
                            signatureValue.indexOf('<svg') === -1) {
                            isEmpty = true;
                        }
                    }

                    if (isEmpty) {
                        hasErrors = true;

                        // Store error in array (similar to main validation's errors array)
                        signatureErrors.push({
                            type: 'required',
                            container: $hiddenInput[0]
                        });

                        // Use WPUF's markError function to show error
                        if (typeof window.WP_User_Frontend !== 'undefined' &&
                            typeof window.WP_User_Frontend.markError === 'function') {
                            // Use the hidden input as the item for markError
                            window.WP_User_Frontend.markError($hiddenInput[0], 'required');
                        }

                        // Track first error for focusing
                        if (!firstErrorField) {
                            firstErrorField = $hiddenInput[0];
                        }
                    }
                }
            });

            // If validation failed, prevent form submission and show error notice
            if (hasErrors) {
                // Mark form as having signature validation errors
                $form.data('wpuf-signature-validation-failed', true);

                // Prevent form submission
                e.preventDefault();
                e.stopImmediatePropagation();
                e.stopPropagation();

                // Use WPUF's addErrorNotice function to show general error message
                if (typeof window.WP_User_Frontend !== 'undefined' &&
                    typeof window.WP_User_Frontend.addErrorNotice === 'function') {
                    window.WP_User_Frontend.addErrorNotice($form, 'end');
                }

                // Focus on first error field
                if (firstErrorField) {
                    $(firstErrorField).focus();

                    // Scroll to first error
                    $('html, body').animate({
                        scrollTop: $(firstErrorField).closest('.wpuf-fields').offset().top - 100
                    }, 500);
                }

                // Return false to ensure event is stopped
                return false;
            } else {
                // Clear any previous signature validation flags
                $form.removeData('wpuf-signature-validation-failed');
            }
        });
    }

    // Bind validation immediately when DOM is ready (before other handlers)
    $(function() {
        // Bind validation to existing forms immediately
        bindSignatureValidation();

        // Also bind to dynamically added forms using MutationObserver (more reliable than DOMNodeInserted)
        if (typeof MutationObserver !== 'undefined') {
            var observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    $(mutation.addedNodes).find('form.wpuf-form-add').each(function() {
                        bindSignatureValidation();
                    });
                });
            });

            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        }

        // Clear error when signature is updated (user draws or clears)
        $(document).on('change', '.signature-data', function () {
            var $hiddenInput = $(this);
            var $wrapper = $hiddenInput.closest('.wpuf-fields');
            var signatureValue = $hiddenInput.val() || '';

            // Check if signature has actual data (not just placeholder)
            var hasData = false;
            var fieldId = $hiddenInput.closest('.wpuf-signature-container').data('field-id');

            if (typeof window.WPUF_Signature_Field !== 'undefined' &&
                window.WPUF_Signature_Field.signaturePads &&
                window.WPUF_Signature_Field.signaturePads[fieldId]) {
                var signatureData = window.WPUF_Signature_Field.signaturePads[fieldId];
                // If placeholder is not visible, user has drawn something
                hasData = signatureData.hasPlaceholder === false;
            } else {
                // Fallback: check if value exists and is a valid SVG string
                hasData = signatureValue &&
                    signatureValue !== '' &&
                    signatureValue.trim() !== '' &&
                    signatureValue.indexOf('<svg') !== -1;
            }

            // Only clear error if signature has actual data
            if (hasData) {
                // Use WPUF's removeErrors function to clear errors
                if (typeof window.WP_User_Frontend !== 'undefined' &&
                    typeof window.WP_User_Frontend.removeErrors === 'function') {
                    window.WP_User_Frontend.removeErrors($wrapper[0]);
                }
            }
        });
    });

    // Add error message if not already defined
    if (typeof wpuf_frontend === 'undefined') {
        window.wpuf_frontend = {};
    }

    if (typeof wpuf_frontend.error_message === 'undefined') {
        wpuf_frontend.error_message = {};
    }

    wpuf_frontend.error_message.signature_required =
        wpuf_frontend.error_message.signature_required ||
        'This field is required. Please provide your signature.';
})(jQuery);

