jQuery(document).ready(function($) {
    $(document).on('mouseenter', '.coolform-rating .rating-icon', function() {
        var $icon = $(this);
        var $field = $icon.closest('.coolform-rating');
        var value = parseFloat($icon.data('value'));

        $field.find('.rating-icon').each(function() {
            var iconValue = parseFloat($(this).data('value'));
            if (iconValue <= value) {
                $(this).addClass('hover');
            } else {
                $(this).removeClass('hover');
            }
        });

        if ($field.data('show-rating-value')) {
            $field.find('.coolform-rating-value').text('(' + value + '/' + $field.data('rating-scale') + ')');
        }
    });

    $(document).on('mouseleave', '.coolform-rating', function() {
        var $field = $(this);
        $(this).find('.rating-icon').removeClass('hover');
        var value = $field.find('.coolform-rating-input').val();
        if ($field.data('show-rating-value')) {
            $field.find('.coolform-rating-value').text('(' + value + '/' + $field.data('rating-scale') + ')');
        }
    });

    $(document).on('click', '.coolform-rating .rating-icon', function() {
        var $icon = $(this);
        var $field = $icon.closest('.coolform-rating');
        var value = parseFloat($icon.data('value'));

        $field.find('.rating-icon').removeClass('marked');
        $field.find('.rating-icon').each(function() {
            var iconValue = parseFloat($(this).data('value'));
            if (iconValue <= value) {
                $(this).addClass('marked');
            }
        });
        $field.find('.coolform-rating-input').val(value);
        $field.find('.coolform-rating-input').trigger('change');
        $field.find('.coolform-rating-input').trigger('input');

        if ($field.data('show-rating-value')) {
            $field.find('.coolform-rating-value').text('(' + value + '/' + $field.data('rating-scale') + ')');
        }
    });

    $('form button[type="submit"]').on('click', function(event) {
        var form = $(this).closest('form');
        var isValid = true;      
        
        form.find('.coolform-rating[data-required="true"]').each(function() {
            if ($(this).find('.coolform-rating-input').val() === '0') {
                isValid = false;
                $(this).parent().find('.error-rating-message').remove();
                $(this).parent().append('<div class="error-rating-message">This field is required and cannot be left blank.</div>'); 
            } else {
                $(this).parent().find('.error-rating-message').remove();
            }
        });
        
        if (!isValid) {
            event.preventDefault(); 
        }
    });

    $(document).find('.rating-icon-wrapper').on('click', function(event) {
        var parentFieldGroup = $(this).closest('.is-field-type-rating');
        parentFieldGroup.find('.error-rating-message').remove();
    });
    
});
