/**
 * WAHRB Wizard Validation
 * Frontend validation for vendor wizard fields
 * Validates: text-only fields (no numbers), number-only fields (no text), required fields
 */
(function ($) {
    'use strict';

    // Validation patterns
    const patterns = {
        textOnly: /^[a-zA-ZÀ-ÿ\s\-'.,;:!?]+$/,           // Letters, accents, punctuation
        numbersOnly: /^[\d.,\s]+$/,                       // Numbers, dots, commas
        email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,              // Email format
        phone: /^[\d\s\+\-\(\)]{8,20}$/,                  // Phone format
        positiveNumber: /^(?:0|[1-9]\d*)(?:[.,]\d+)?$/,   // Positive number
        alphanumeric: /^[a-zA-ZÀ-ÿ0-9\s\-'.,]+$/         // Text with numbers allowed
    };

    // Field configurations by input name/id patterns
    const fieldRules = {
        // Step 2: Product
        'product_name': { type: 'alphanumeric', required: true, minLength: 3, maxLength: 200 },
        'product_description': { type: 'any', required: false, maxLength: 5000 },
        'total_units': { type: 'positiveNumber', required: true, min: 1, max: 1000 },

        // Step 3: Availability
        'min_duration': { type: 'positiveNumber', required: true, min: 1, max: 365 },
        'max_duration': { type: 'positiveNumber', required: true, min: 1, max: 365 },
        'buffer_before': { type: 'positiveNumber', required: false, min: 0, max: 24 },
        'buffer_after': { type: 'positiveNumber', required: false, min: 0, max: 24 },
        'min_notice_hours': { type: 'positiveNumber', required: false, min: 0, max: 720 },
        'max_booking_days': { type: 'positiveNumber', required: false, min: 1, max: 365 },

        // Step 4: Pricing
        'base_price': { type: 'positiveNumber', required: true, min: 0 },
        'modifier_value': { type: 'numbersOnly', required: false },
        'rule_priority': { type: 'positiveNumber', required: false, min: 1, max: 100 },

        // Step 5: Payment
        'deposit_value': { type: 'positiveNumber', required: false, min: 0, max: 100 },
        'security_deposit_value': { type: 'positiveNumber', required: false, min: 0 },
        'balance_due_days': { type: 'positiveNumber', required: false, min: 1, max: 30 }
    };

    // Error messages
    const messages = {
        required: 'Ce champ est requis',
        textOnly: 'Ce champ ne doit contenir que des lettres',
        numbersOnly: 'Ce champ ne doit contenir que des chiffres',
        positiveNumber: 'Veuillez entrer un nombre positif valide',
        email: 'Format d\'email invalide',
        phone: 'Format de téléphone invalide',
        minLength: 'Minimum {min} caractères',
        maxLength: 'Maximum {max} caractères',
        min: 'Valeur minimum: {min}',
        max: 'Valeur maximum: {max}',
        alphanumeric: 'Caractères non autorisés détectés'
    };

    // Show error on field
    function showError($field, message) {
        clearError($field);
        $field.addClass('wahrb-validation-error');
        $field.after('<span class="wahrb-validation-message" style="color:#dc2626;font-size:12px;display:block;margin-top:4px;">⚠️ ' + message + '</span>');
    }

    // Clear error on field
    function clearError($field) {
        $field.removeClass('wahrb-validation-error');
        $field.siblings('.wahrb-validation-message').remove();
    }

    // Get field rule by checking name/id patterns
    function getFieldRule($field) {
        var name = $field.attr('name') || '';
        var id = $field.attr('id') || '';
        var identifier = name || id;

        // Check for matching patterns
        for (var pattern in fieldRules) {
            if (identifier.indexOf(pattern) !== -1 || identifier.toLowerCase().indexOf(pattern.replace('_', '')) !== -1) {
                return fieldRules[pattern];
            }
        }

        // Check by input type
        var type = $field.attr('type');
        if (type === 'number') {
            return { type: 'positiveNumber', required: false };
        }
        if (type === 'email') {
            return { type: 'email', required: false };
        }
        if (type === 'tel') {
            return { type: 'phone', required: false };
        }

        return null;
    }

    // Validate single field
    function validateField($field) {
        var rule = getFieldRule($field);
        if (!rule) return true;

        var value = $field.val();
        if (value) value = value.trim();

        // Required check
        if (rule.required && !value) {
            showError($field, messages.required);
            return false;
        }

        // Skip other checks if empty and not required
        if (!value) {
            clearError($field);
            return true;
        }

        // Type check
        if (rule.type && rule.type !== 'any') {
            var pattern = patterns[rule.type];
            if (pattern && !pattern.test(value)) {
                showError($field, messages[rule.type] || 'Format invalide');
                return false;
            }
        }

        // Min length check
        if (rule.minLength && value.length < rule.minLength) {
            showError($field, messages.minLength.replace('{min}', rule.minLength));
            return false;
        }

        // Max length check
        if (rule.maxLength && value.length > rule.maxLength) {
            showError($field, messages.maxLength.replace('{max}', rule.maxLength));
            return false;
        }

        // Numeric min/max checks
        if ((rule.type === 'positiveNumber' || rule.type === 'numbersOnly') && value) {
            var numValue = parseFloat(value.replace(',', '.'));
            if (!isNaN(numValue)) {
                if (rule.min !== undefined && numValue < rule.min) {
                    showError($field, messages.min.replace('{min}', rule.min));
                    return false;
                }
                if (rule.max !== undefined && numValue > rule.max) {
                    showError($field, messages.max.replace('{max}', rule.max));
                    return false;
                }
            }
        }

        // All valid
        clearError($field);
        return true;
    }

    // Validate all fields in a step/form
    function validateForm($container) {
        var isValid = true;
        $container.find('input, textarea, select').each(function () {
            if (!validateField($(this))) {
                isValid = false;
            }
        });
        return isValid;
    }

    // Prevent invalid characters on keypress for number fields
    function preventInvalidChars(e) {
        var $field = $(e.target);
        var rule = getFieldRule($field);

        if (!rule) return;

        var key = e.key;

        // Allow control keys
        if (e.ctrlKey || e.metaKey || key === 'Backspace' || key === 'Delete' ||
            key === 'ArrowLeft' || key === 'ArrowRight' || key === 'Tab') {
            return;
        }

        // For number-only fields, prevent letters
        if (rule.type === 'positiveNumber' || rule.type === 'numbersOnly') {
            if (!/[\d.,\s]/.test(key)) {
                e.preventDefault();
                // Flash the field to indicate rejection
                $field.addClass('wahrb-input-rejected');
                setTimeout(function () {
                    $field.removeClass('wahrb-input-rejected');
                }, 200);
            }
        }

        // For text-only fields, prevent numbers
        if (rule.type === 'textOnly') {
            if (/\d/.test(key)) {
                e.preventDefault();
                $field.addClass('wahrb-input-rejected');
                setTimeout(function () {
                    $field.removeClass('wahrb-input-rejected');
                }, 200);
            }
        }
    }

    // Initialize validation
    function init() {
        // Add CSS for validation styling
        if (!$('#wahrb-validation-styles').length) {
            $('head').append(
                '<style id="wahrb-validation-styles">' +
                '.wahrb-validation-error { border-color: #dc2626 !important; background-color: #fef2f2 !important; }' +
                '.wahrb-input-rejected { animation: wahrb-shake 0.2s ease-in-out; }' +
                '@keyframes wahrb-shake { 0%, 100% { transform: translateX(0); } 25% { transform: translateX(-4px); } 75% { transform: translateX(4px); } }' +
                '</style>'
            );
        }

        // Bind events using delegation for dynamic content
        $(document)
            .on('blur', 'input, textarea', function () {
                validateField($(this));
            })
            .on('keydown', 'input', preventInvalidChars)
            .on('input', 'input, textarea', function () {
                // Clear error on input (will re-validate on blur)
                var $field = $(this);
                if (!$field.hasClass('wahrb-validation-error')) return;
                clearError($field);
            });

        // Intercept form submissions and step transitions
        $(document).on('click', '.wahrb-wizard-next, .wahrb-btn-next, [data-action="next"]', function (e) {
            var $step = $(this).closest('.wahrb-wizard-step, .wahrb-step-content, [data-step]');
            if ($step.length && !validateForm($step)) {
                e.preventDefault();
                e.stopPropagation();
                // Scroll to first error
                var $firstError = $step.find('.wahrb-validation-error').first();
                if ($firstError.length) {
                    $firstError.focus();
                    $('html, body').animate({
                        scrollTop: $firstError.offset().top - 100
                    }, 300);
                }
                return false;
            }
        });
    }

    // Expose for external use
    window.WAHRBWizardValidation = {
        validateField: validateField,
        validateForm: validateForm,
        showError: showError,
        clearError: clearError
    };

    // Init on DOM ready
    $(document).ready(init);

})(jQuery);
