jQuery(window).on('elementor/frontend/init', function() {
    elementorFrontend.hooks.addAction('frontend/element_ready/form.default', function($scope) {
        var configStr = $scope.attr('data-dce-field-description');
        if (!configStr) {
            return;
        }

        var config = JSON.parse(configStr);
        if (!config.fields || config.fields.length === 0) {
            return;
        }

        var widgetId = $scope.data('id');

        config.fields.forEach(function(field) {
            if (field.position === 'elementor-field-label') {
                if (field.tooltip) {
                    // Add tooltip to label
                    var $label = jQuery('.elementor-element-' + widgetId + ' .elementor-field-group-' + field.custom_id + ' .elementor-field-label');
                    $label.addClass('dce-tooltip').addClass('elementor-field-label-description');
                    var tooltipPos = field.tooltip_position || 'top';
                    var $tooltip = jQuery('<span class="dce-tooltiptext dce-tooltip-' + tooltipPos + '"></span>');
                    $tooltip.html(field.description);
                    $label.append($tooltip);
                } else {
                    // Add abbr with title
                    var $label = jQuery('.elementor-element-' + widgetId + ' .elementor-field-group-' + field.custom_id + ' .elementor-field-label');
                    var $abbr = jQuery('<abbr class="elementor-field-label-description elementor-field-label-description-' + field.custom_id + '"></abbr>');
                    $abbr.attr('title', field.description_text);
                    $label.wrap($abbr);
                }
            } else if (field.position === 'elementor-field') {
                // Add description below input
                var $fieldGroup = jQuery('.elementor-element-' + widgetId + ' .elementor-field-group-' + field.custom_id);
                var $desc = jQuery('<div class="elementor-field-input-description elementor-field-input-description-' + field.custom_id + '"></div>');
                $desc.html(field.description);
                $fieldGroup.append($desc);
            }
        });
    });
});
