/**
 * SalonPro X - Client-side Form Validation
 * Real-time validation with Bootstrap 5 integration
 */

$(function() {
    'use strict';

    // Initialize validation on all forms with .needs-validation
    initFormValidation();

    // Auto-capitalize name fields
    initNameFields();
});

/**
 * Initialize Bootstrap 5 form validation
 */
function initFormValidation() {
    const forms = document.querySelectorAll('.needs-validation');

    Array.from(forms).forEach(function(form) {
        form.addEventListener('submit', function(event) {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
                // Focus first invalid field
                const firstInvalid = form.querySelector(':invalid');
                if (firstInvalid) {
                    firstInvalid.focus();
                    firstInvalid.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
            }
            form.classList.add('was-validated');
        }, false);
    });
}

/**
 * Auto-capitalize first letter of name fields
 */
function initNameFields() {
    $(document).on('input', '.input-name', function() {
        const $el = $(this);
        const val = $el.val();
        if (val.length > 0) {
            // Capitalize first letter of each word
            $el.val(val.replace(/\b\w/g, function(c) {
                return c.toUpperCase();
            }));
        }
    });
}

/**
 * Show password toggle
 */
$(document).on('click', '.toggle-password', function() {
    const $btn = $(this);
    const $input = $btn.closest('.input-group').find('input');
    const type = $input.attr('type') === 'password' ? 'text' : 'password';
    $input.attr('type', type);
    $btn.find('i').toggleClass('fa-eye fa-eye-slash');
});

/**
 * Initialize phone number formatting
 */
$(document).on('input', '.input-phone', function() {
    const $el = $(this);
    let val = $el.val().replace(/[^0-9+\-() ]/g, '');
    $el.val(val);
});
