jQuery(document).ready(function ($) {

    function applyConditionalLogic() {
        $('.sincotechs-form-group[data-cond-field]').each(function () {
            var $group = $(this);
            var condField = $group.data('cond-field');
            var condValue = $group.data('cond-value');

            if (!condField || !condValue) {
                $group.show();
                return;
            }

            var $input = $('[name="' + condField + '"]');
            var currentVal = $input.val();

            if ($input.is('select')) {
                currentVal = $input.find('option:selected').val();
            }

            if (currentVal === condValue) {
                $group.show();
                $group.find('input, textarea, select').each(function () {
                    var required = $(this).data('original-required');
                    if (required) {
                        $(this).attr('required', 'required');
                    }
                });
            } else {
                $group.hide();
                $group.find('input, textarea, select').each(function () {
                    if ($(this).attr('required')) {
                        $(this).data('original-required', true);
                    }
                    $(this).removeAttr('required');
                });
            }
        });
    }

    // Initialize required flags
    $('.sincotechs-form-group').each(function () {
        var $group = $(this);
        $group.find('input[required], textarea[required], select[required]').each(function () {
            $(this).data('original-required', true);
        });
    });

    // Bind change events on all inputs to recompute logic
    $('.sincotechs-form').on('change keyup', 'input, select, textarea', function () {
        applyConditionalLogic();
    });

    // Initial run
    applyConditionalLogic();
});
