jQuery(document).ready(function($) {
    var postTypes = freshenupData.postTypes;
    var categories = freshenupData.categories;
    var tags = freshenupData.tags;
    var currentEditableElement = null;
    var initializedPrompt = 0;
    var totalEditables = 0;
    var clickableEditables = 0;

    // Show loading overlay
    $('#freshenup-loading-overlay').show();
        
    
    function freshenup_initializePrompt(promptElement) {
        var content = promptElement.find('.prompt-content');
        var html = content.html();
        var promptId = promptElement.data('id');
        
        // Remove old min_days format if it exists
        var oldMinDaysRegex = new RegExp(freshenupData.oldminDaysText + '.*?days\\.<br>', 'g');
        html = html.replace(oldMinDaysRegex, '');
        
        // Check if new fields exist in the content
        var hasMinDays = html.includes(freshenupData.minDaysText);
        var hasMultipleUpdates = html.includes(freshenupData.multipleUpdatesText);
        var hasMinDaysFreshenUp = html.includes(freshenupData.minDaysFreshenUpText);
        var hasMinDaysPublished = html.includes(freshenupData.minDaysPublishedText);
        var hasonlyDatebased = html.includes(freshenupData.onlyDatebased);
        
        var hasTags = html.includes('data-type="include_tags"');
        var hasExcludedTags = html.includes('data-type="exclude_tags"');
        var authorsSpanRegex = /<span[^>]*data-type="authors"[^>]*>.*?<\/span>[^<]*/;
        var excludecategoriesSpanRegex = /<span[^>]*data-type="exclude_categories"[^>]*>.*?<\/span>[^<]*/;
                
        // Insert tag fields *before* the authors field
        if (!hasTags || !hasExcludedTags) {
            var tagFields = '';
        
            if (!hasTags) {
                tagFields += '<br>' + freshenupData.youcanupdateText + ' <span id="editable-' + promptId + '-include_tags" class="editable" data-type="include_tags" data-value="' + freshenupData.alltagsText + '">' + freshenupData.alltagsText + '</span>.<br>';
            }
        
            
            if (!hasExcludedTags) {
                tagFields += freshenupData.excludeText + ' <span id="editable-' + promptId + '-exclude_tags" class="editable" data-type="exclude_tags" data-value="' + freshenupData.notagsText + '">' + freshenupData.notagsText + '</span>.';
            }
        
            // Inject tag fields before authors
            html = html.replace(excludecategoriesSpanRegex, '$&' + tagFields);
        }
        

        
        // If they don't exist, add them with proper spans
        if (!hasMinDays || !hasMinDaysFreshenUp || !hasMinDaysPublished || !hasMultipleUpdates || !hasonlyDatebased) {
            
            var newFields = '';
            
            if (!hasonlyDatebased) {
                newFields += '<br>' + freshenupData.onlyDatebased + ':<br>';
            }
            
            if (!hasMinDaysFreshenUp) {
                newFields += '- ' + freshenupData.minDaysFreshenUpText + ' <span id="editable-' + promptId + '-min_days_freshenup" class="editable" data-value="365" data-type="min_days_freshenup">365</span> ' + freshenupData.daysText + '.<br>';
            }
                
            if (!hasMinDays) {
                newFields += '- ' + freshenupData.minDaysText + ' <span id="editable-' + promptId + '-min_days" class="editable" data-value="365" data-type="min_days">365</span> ' + freshenupData.daysText + '.<br>';
            }
            if (!hasMinDaysPublished) {
                newFields += '- ' + freshenupData.minDaysPublishedText + ' <span id="editable-' + promptId + '-min_days_published" class="editable" data-value="365" data-type="min_days_published">365</span> ' + freshenupData.daysAgoText + '.<br>';
            }
            
            if (!hasMultipleUpdates) {
                newFields += '<br>' + freshenupData.multipleUpdatesText + ' <span id="editable-' + promptId + '-can_update_multiple" class="editable" data-value="' + freshenupData.canUpdateText + '" data-type="can_update_multiple">' + freshenupData.canUpdateText + '</span> ' + freshenupData.beUpdatedText + '.';
            }
            
            html = html.replace(authorsSpanRegex, '$&' + newFields);
            
        }
        
        var editableCount = 0;
        var newHtml = html.replace(/\*(.*?)\*/g, function(match, p1, offset) {
            var id = 'editable-' + promptElement.data('id') + '-' + editableCount;
            var type = getEditableType(editableCount);
            var value = p1;
            
            // If this is a post_types editable and contains "these post types: post"
            if (type === 'post_types' && p1.includes(freshenupData.theseposttypesText + ': post')) {
                value = 'post';
            }
            
            editableCount++;
            return '<span id="' + id + '" class="editable" data-value="' + value + '" data-type="' + type + '">' + p1 + '</span>';
        });
        
        content.html(newHtml);
        freshenup_updateHiddenInput(promptElement);
        
        initializedPrompt++;
        if (initializedPrompt >= $('.prompt-item').length) {
            startClickabilityCheck();
        }
    }
    
    function freshenup_updatePostsDaysText(promptElement) {
        var postsEditable = promptElement.find('.editable[data-type="posts"]');
        var daysEditable = promptElement.find('.editable[data-type="days"]');
        if (!postsEditable.length || !daysEditable.length) return;
    
        var count = parseInt(postsEditable.attr('data-value'));
        var isEveryDay = daysEditable.text() === freshenupData.everydayText;
    
        var postWord = (count === 1) ? freshenupData.postSingularText : freshenupData.postsText;
        var separator = isEveryDay ? ' ' : ' ' + freshenupData.onText + ' ';
    
        var textNode = postsEditable[0].nextSibling;
        if (textNode && textNode.nodeType === 3) {
            textNode.textContent = ' ' + postWord + separator;
        }
    }

    function startClickabilityCheck() {
        checkEditablesClickable();
    }

    function checkEditablesClickable() {
        $('.editable').each(function() {
            var $editable = $(this);
            if (!$editable.data('clickable-checked')) {
                testEditableClickable($editable);
            }
        });

        if (clickableEditables < totalEditables) {
            setTimeout(checkEditablesClickable, 100);
        } else {
            setTimeout(function() {
            $('#freshenup-loading-overlay').fadeOut(300);
        }, 400);
        }
    }

    function testEditableClickable($editable) {
        var wasClicked = false;
        $editable.one('click.test', function(e) {
            wasClicked = true;
            e.preventDefault();
            e.stopPropagation();
        });

        $editable.trigger('click.test');
        
        $editable.off('click.test');

        if (wasClicked) {
            clickableEditables++;
            $editable.data('clickable-checked', true);
        } else {
        }
    }


       
    function getEditableType(index) {
        var types = ['posts', 'days', 'percentage', 'post_types', 'include_categories', 'exclude_categories', 'include_tags', 'exclude_tags', 'authors', 'min_days_freshenup', 'min_days', 'min_days_published', 'can_update_multiple', 'moderation'];
        return types[index] || 'unknown';
    }

   
    function freshenup_createDropdown(min, max, current) {
        var select = $('<select>');
        for (var i = min; i <= max; i++) {
            select.append($('<option>', {value: i, text: i, selected: i == current}));
        }
        return select;
    }
    
    function freshenup_createDayRadio(currentValue) {
        var container = $('<div>');
        var days = [
            freshenupData.mondayText, freshenupData.tuesdayText,
            freshenupData.wednesdayText, freshenupData.thursdayText,
            freshenupData.fridayText, freshenupData.saturdayText,
            freshenupData.sundayText
        ];
        days.forEach(function(day) {
            container.append(
                $('<label>').append(
                    $('<input>', {
                        type: 'radio',
                        name: 'freshenup_day_select',
                        value: day,
                        checked: day === currentValue
                    })
                ).append(day)
            );
        });
        return container;
    }

    function freshenup_createCheckboxes(options, selected, includeDefault) {
        includeDefault = includeDefault || false;
        var container = $('<div>');
        if (includeDefault) {
            var defaultOption = options[0];
            var defaultCheckbox = $('<label>').append(
                $('<input>', {type: 'checkbox', value: defaultOption, checked: selected.includes(defaultOption) || selected[0] === defaultOption})
            ).append(defaultOption);
            container.append(defaultCheckbox);
            options = options.slice(1);
        }

        options.forEach(function(option) {
            var isChecked = selected.includes(option);
            container.append(
                $('<label>').append(
                    $('<input>', {type: 'checkbox', value: option, checked: isChecked, disabled: selected[0] === freshenupData.everydayText})
                ).append(option)
            );
        });

        if (includeDefault) {
            defaultCheckbox.find('input').on('change', function() {
                var isChecked = $(this).is(':checked');
                container.find('input').not(this).prop('disabled', isChecked).prop('checked', false);
            });
        }

        return container;
    }
    
    
    function freshenup_createAuthorsCheckboxes(currentValue) {
    var container = $('<div>');
    
    var allCheckbox = $('<label>').append(
        $('<input>', {
            type: 'checkbox', 
            value: freshenupData.allText, 
            checked: currentValue === freshenupData.allauthorsText
        })
    ).append(freshenupData.allauthorsText);
    container.append(allCheckbox);

    var selectedAuthors = currentValue.includes(freshenupData.theseauthorsText + ':') 
        ? currentValue.split(': ')[1].split(', ')
        : [];

    freshenupData.authors.forEach(function(author) {
        var isChecked = selectedAuthors.includes(author.name);
        container.append(
            $('<label>').append(
                $('<input>', {
                    type: 'checkbox', 
                    value: author.id.toString(),
                    'data-name': author.name,
                    checked: isChecked, 
                    disabled: currentValue === freshenupData.allauthorsText
                })
            ).append(author.name + ' (' + author.count + ')')
        );
    });

    container.find('input[value="' + freshenupData.allText + '"]').on('change', function() {
        var isChecked = $(this).is(':checked');
        container.find('input').not(this).prop('disabled', isChecked).prop('checked', false);
    });

    return container;
}

    
    function freshenup_createModerationOptions(currentValue) {
        var container = $('<div>');
        var options = [freshenupData.ModerateText, freshenupData.donotModerateText];
        options.forEach(function(option) {
            container.append(
                $('<label>').append(
                    $('<input>', {
                        type: 'radio',
                        name: 'moderation',
                        value: option,
                        checked: option === currentValue
                    })
                ).append(option)
            );
        });
        return container;
    }

function freshenup_createPostTypesCheckboxes(currentValue) {
    var container = $('<div>');
    var allCheckbox = $('<label>').append(
        $('<input>', {
            type: 'checkbox',
            value: freshenupData.allText,
            checked: currentValue === freshenupData.allposttypesText
        })
    ).append(freshenupData.allposttypesText);
    container.append(allCheckbox);

    var selectedPostTypes = currentValue.includes(freshenupData.theseposttypesText + ':') 
        ? currentValue.split(': ')[1].split(', ')
        : [];

    postTypes.forEach(function(postType) {
        var isChecked = selectedPostTypes.includes(postType.name);
        container.append(
            $('<label>').append(
                $('<input>', {
                    type: 'checkbox',
                    value: postType.slug,
                    'data-name': postType.name,
                    checked: isChecked,
                    disabled: currentValue === freshenupData.allposttypesText
                })
            ).append(postType.name)
        );
    });

    allCheckbox.find('input').on('change', function() {
        var isChecked = $(this).is(':checked');
        container.find('input').not(this).prop('disabled', isChecked).prop('checked', false);
    });

    return container;
}

function freshenup_createCategoriesCheckboxes(currentValue, type) {
    var container = $('<div>');
    
    if (type === 'include') {
        var allCheckbox = $('<label>').append(
            $('<input>', {
                type: 'checkbox', 
                value: freshenupData.allText, 
                checked: currentValue === freshenupData.allcategoriesText
            })
        ).append(freshenupData.allcategoriesText);
        container.append(allCheckbox);
    } else {
        var noneCheckbox = $('<label>').append(
            $('<input>', {
                type: 'checkbox', 
                value: freshenupData.nocategoriesText, 
                checked: currentValue === freshenupData.nocategoriesText
            })
        ).append(freshenupData.nocategoriesText);
        container.append(noneCheckbox);
    }

    var selectedCategories = currentValue.includes(freshenupData.thesecategoriesText + ':') 
        ? currentValue.split(': ')[1].split(', ')
        : (type === 'exclude' && currentValue !== freshenupData.nocategoriesText ? [currentValue] : []);

    categories.forEach(function(category) {
        var isChecked = selectedCategories.includes(category.name);
        container.append(
            $('<label>').append(
                $('<input>', {
                    type: 'checkbox', 
                    value: category.id.toString(),
                    'data-name': category.name,
                    checked: isChecked, 
                    disabled: currentValue === freshenupData.allcategoriesText || currentValue === freshenupData.nocategoriesText
                })
            ).append(category.name + ' (' + category.count + ')')
        );
    });

    container.find('input[value="' + freshenupData.allText + '"], input[value="' + freshenupData.nocategoriesText + '"]').on('change', function() {
        var isChecked = $(this).is(':checked');
        container.find('input').not(this).prop('disabled', isChecked).prop('checked', false);
    });

    return container;
}

function freshenup_createTagsCheckboxes(currentValue, type) {
    var container = $('<div>');
    
    if (type === 'include') {
        var allCheckbox = $('<label>').append(
            $('<input>', {
                type: 'checkbox', 
                value: freshenupData.allText, 
                checked: currentValue === freshenupData.alltagsText
            })
        ).append(freshenupData.alltagsText);
        container.append(allCheckbox);
    } else {
        var noneCheckbox = $('<label>').append(
            $('<input>', {
                type: 'checkbox', 
                value: freshenupData.notagsText, 
                checked: currentValue === freshenupData.notagsText
            })
        ).append(freshenupData.notagsText);
        container.append(noneCheckbox);
    }

    var selectedTags = currentValue.includes(freshenupData.thesetagsText + ':') 
        ? currentValue.split(': ')[1].split(', ')
        : (type === 'exclude' && currentValue !== freshenupData.notagsText ? [currentValue] : []);

    freshenupData.tags.forEach(function(tag) {
        var isChecked = selectedTags.includes(tag.name);
        container.append(
            $('<label>').append(
                $('<input>', {
                    type: 'checkbox', 
                    value: tag.id.toString(),
                    'data-name': tag.name,
                    checked: isChecked,
                    disabled: currentValue === freshenupData.alltagsText || currentValue === freshenupData.notagsText
                })
            ).append(tag.name + ' (' + tag.count + ')')
        );
    });

    container.find('input[value="' + freshenupData.allText + '"], input[value="' + freshenupData.notagsText + '"]').on('change', function() {
        var isChecked = $(this).is(':checked');
        container.find('input').not(this).prop('disabled', isChecked).prop('checked', false);
    });

    return container;
}


    function freshenup_createSlider(min, max, step, current) {
        var slider = $('<input>', {type: 'range', min: min, max: max, step: step, value: current});
        var valueDisplay = $('<span>').text(current + '%');
        slider.on('input', function() {
            valueDisplay.text(this.value + '%');
        });
        return $('<div>').append(slider).append(valueDisplay);
    }
    
    function freshenup_createMinDaysInput(currentValue) {
        var input = $('<input>', {
            type: 'number',
            min: 0,
            value: currentValue || 365,
            style: 'width: 100px'
        });
        return $('<div>').append(input);
    }
    
    function freshenup_createDaysFreshenUpInput(currentValue) {
        var input = $('<input>', {
            type: 'number',
            min: 0,
            value: currentValue || 365,
            style: 'width: 100px'
        });
        return $('<div>').append(input);
    }
    
    function freshenup_createDaysPublishedInput(currentValue) {
        var input = $('<input>', {
            type: 'number',
            min: 0,
            value: currentValue || 365,
            style: 'width: 100px'
        });
        return $('<div>').append(input);
    }
    
    function freshenup_createUpdateMultipleOptions(currentValue) {
        var container = $('<div>');
        var options = [freshenupData.canUpdateText, freshenupData.cannotUpdateText];
        options.forEach(function(option) {
            container.append(
                $('<label>').append(
                    $('<input>', {
                        type: 'radio',
                        name: 'can_update_multiple',
                        value: option,
                        checked: option === currentValue
                    })
                ).append(option)
            );
        });
        return container;
    }
    
    
    
        function freshenup_updateHiddenInput(promptElement) {
        var content = promptElement.find('.prompt-content');
        var hiddenInput = promptElement.find('input[name$="[content]"]');
        var titleInput = promptElement.find('input[name$="[name]"]');
        
        if (titleInput.val().trim() === '') {
            var promptNumber = promptElement.index();
            titleInput.val(freshenupData.promptidentifierText + ' #' + promptNumber);
        }
        
        hiddenInput.val(content.html());
    }


    $(document).on('click', '.prompt-content .editable', function(e) {
        e.preventDefault();
        e.stopPropagation();
        currentEditableElement = $(this);
        var currentValue = currentEditableElement.text();
        var editableType = currentEditableElement.data('type');
        var input;

        try {
            switch (editableType) {
                case 'posts':
                    input = freshenup_createDropdown(1, 1, 1);
                    break;
                case 'days':
                    input = freshenup_createDayRadio(currentValue);
                    break;
                case 'percentage':
                    input = freshenup_createSlider(20, 50, 5, parseInt(currentValue));
                    break;
                case 'post_types':
                    input = freshenup_createPostTypesCheckboxes(currentValue);
                    break;
                case 'include_categories':
                    input = freshenup_createCategoriesCheckboxes(currentValue, 'include');
                    break;
                case 'exclude_categories':
                    input = freshenup_createCategoriesCheckboxes(currentValue, 'exclude');
                    break;
                case 'include_tags':
                    input = freshenup_createTagsCheckboxes(currentValue, 'include');
                    break;
                case 'exclude_tags':
                    input = freshenup_createTagsCheckboxes(currentValue, 'exclude');
                    break;
                case 'authors':
                    input = freshenup_createAuthorsCheckboxes(currentValue);
                    break;
                case 'min_days':
                    input = freshenup_createMinDaysInput(parseInt(currentValue));
                    break;
                case 'min_days_freshenup':
                    input = freshenup_createDaysFreshenUpInput(parseInt(currentValue));
                    break;
                case 'min_days_published':
                    input = freshenup_createDaysPublishedInput(parseInt(currentValue));
                    break;
                case 'can_update_multiple':
                    input = freshenup_createUpdateMultipleOptions(currentValue);
                    break;
                case 'moderation':
                    input = freshenup_createModerationOptions(currentValue);
                    break;
                default:
                    return;
            }

            if (input) {
                $('#modal-input-container').empty().append(input);
                $('#edit-modal').fadeIn(300);
            }
        } catch (error) {
        }
    });
    
    $('#save-modal').on('click', function(e) {
        e.preventDefault();
        var newValue = freshenup_getInputValue($('#modal-input-container'));
        currentEditableElement.attr('data-value', newValue.value);
        currentEditableElement.text(newValue.display);
        
        // Update "posts" / "post" text after the number
        if (currentEditableElement.data('type') === 'posts' || currentEditableElement.data('type') === 'days') {
            freshenup_updatePostsDaysText(currentEditableElement.closest('.prompt-item'));
        }
        
        freshenup_updateHiddenInput(currentEditableElement.closest('.prompt-item'));
        $('#edit-modal').fadeOut(300);
    });


    $('.close').on('click', function(e) {
        e.preventDefault();
        $('#edit-modal').fadeOut(300);
    });

    $(window).on('click', function(event) {
        if ($(event.target).is('#edit-modal')) {
            $('#edit-modal').fadeOut(300);
        }
    });


    function freshenup_getInputValue(container) {
        var inputs = container.find('input');
        
        if (inputs.attr('type') === 'range') {
            return {
                value: inputs.val(),
                display: inputs.val() + '%'
            };
        } else if (inputs.attr('type') === 'number') {
            return {
                value: inputs.val(),
                display: inputs.val()
            };
        } else if (inputs.attr('type') === 'radio') {
            var selectedValue = inputs.filter(':checked').val();
            return {
                value: selectedValue,
                display: selectedValue
            };
        } else if (inputs.attr('type') === 'checkbox') {
            var defaultOption = container.find('input').first();
            var defaultVal = defaultOption.val();
            var firstLabelText = container.find('label:first').text();
        
            if (defaultOption.is(':checked')) {
                if (defaultVal === freshenupData.allText) {
                    if (firstLabelText.includes(freshenupData.posttypesText)) {
                        return {
                            value: freshenupData.allText,
                            display: freshenupData.allposttypesText
                        };
                    } else if (firstLabelText.includes(freshenupData.allauthorsText)) {
                        return {
                            value: freshenupData.allText,
                            display: freshenupData.allauthorsText
                        };
                    } else if (firstLabelText.includes(freshenupData.alltagsText)) {
                        return {
                            value: freshenupData.allText,
                            display: freshenupData.alltagsText
                        };
                    } else {
                        return {
                            value: freshenupData.allText,
                            display: freshenupData.allcategoriesText
                        };
                    }
                }
        
                if (
                    defaultVal === freshenupData.nocategoriesText ||
                    defaultVal === freshenupData.notagsText
                ) {
                    return {
                        value: defaultVal,
                        display: defaultVal
                    };
                }
        
                return {
                    value: defaultVal,
                    display: freshenupData.everydayText
                };
            }
        
            var checked = inputs.filter(':checked').not(defaultOption);
            if (checked.length === 0) {
                if (firstLabelText.includes(freshenupData.notagsText)) {
                    return {
                        value: freshenupData.notagsText,
                        display: freshenupData.notagsText
                    };
                }
        
                return {
                    value: freshenupData.nocategoriesText,
                    display: freshenupData.nocategoriesText
                };
            }
        
            if (container.find('input[value="' + freshenupData.mondayText + '"]').length) {
                return {
                    value: checked.map(function () {
                        return this.value;
                    }).get().join('-'),
                    display: checked.map(function () {
                        return $(this).parent().text().trim();
                    }).get().join(', ')
                };
            } else {
                var values = checked.map(function () {
                    return this.value;
                }).get();
        
                var displayNames = checked.map(function () {
                    var text = $(this).parent().text().trim();
                    return text.replace(/\s*\(\d+\)$/, ''); // remove trailing (count)
                }).get();
        
                if (firstLabelText.includes(freshenupData.posttypesText)) {
                    return {
                        value: values.join('-'),
                        display: freshenupData.theseposttypesText + ': ' + displayNames.join(', ')
                    };
                } else if (firstLabelText.includes(freshenupData.allauthorsText)) {
                    return {
                        value: values.join('-'),
                        display: freshenupData.theseauthorsText + ': ' + displayNames.join(', ')
                    };
                } else if (firstLabelText.includes(freshenupData.tagsText)) {
                    return {
                        value: values.join('-'),
                        display: freshenupData.thesetagsText + ': ' + displayNames.join(', ')
                    };
                } else {
                    return {
                        value: values.join('-'),
                        display: freshenupData.thesecategoriesText + ': ' + displayNames.join(', ')
                    };
                }
            }
        }
        else {
            var value = container.find('select').val();
            return {
                value: value,
                display: value
            };
        }
    }



    // Initialize existing prompt
    $('.prompt-item').each(function() {
        freshenup_initializePrompt($(this));
    });

    // If there is no prompt, hide the loading overlay
    if ($('.prompt-item').length === 0) {
        setTimeout(function() {
            $('#freshenup-loading-overlay').fadeOut(300);
        }, 500);
    }

    // Handle adding a new prompt (only allowed when none exist)
    $('#add-new-prompt').on('click', function(e) {
        e.preventDefault();
        var newPromptId = Date.now();
        var newPrompt = $('<div class="prompt-item" data-id="' + newPromptId + '">' +
            '<input type="text" name="freshenup_prompts[' + newPromptId + '][name]" placeholder="' + freshenupData.promptidentifierText + ' #0">' +
            '<div class="prompt-content">' + freshenupData.UpdateText + ' *1* ' + freshenupData.postSingularText + ' ' + freshenupData.onText + ' *' + freshenupData.mondayText + '* ' + freshenupData.addingaroundText + ' *25%* ' + freshenupData.ofnewcontentText + '.<br>' +
            freshenupData.includeText + ' *' + freshenupData.theseposttypesText + ': ' + 'post*.<br>' +            
            freshenupData.youcanupdateText + ' *' + freshenupData.allcategoriesText + '*.<br>' + 
            freshenupData.excludeText + ' *' + freshenupData.nocategoriesText + '*.<br>' +
            freshenupData.youcanupdateText + ' *' + freshenupData.alltagsText + '*.<br>' + 
            freshenupData.excludeText + ' *' + freshenupData.notagsText + '*.<br>' +
            freshenupData.includeText + ' *' + freshenupData.allauthorsText + '*.<br>' +
            
            freshenupData.onlyDatebased + ':<br>' +
            '- ' + freshenupData.minDaysFreshenUpText + ' *365* ' + freshenupData.daysText + '.<br>' +
            '- ' + freshenupData.minDaysText + ' *365* ' + freshenupData.daysText + '.<br>' +
            '- ' + freshenupData.minDaysPublishedText + ' *365* ' + freshenupData.daysAgoText + '.<br>' +
            
            freshenupData.multipleUpdatesText + ' *' + freshenupData.canUpdateText + '* ' + freshenupData.beUpdatedText + '.<br>' +
            '*' + freshenupData.ModerateText + '* ' + freshenupData.modbeforeliveText + '.</div>' +
            '<input type="hidden" name="freshenup_prompts[' + newPromptId + '][content]" value="">' +
            '<input type="hidden" name="freshenup_prompts[' + newPromptId + '][id]" value="' + newPromptId + '">' +
            '<div class="freshenup_remove_button_container">' +
            '<button class="remove-prompt button">' + freshenupData.removeButtonText + '</button>' +
            '</div>' +
            '</div>');
        $(this).before(newPrompt);
        freshenup_initializePrompt(newPrompt);
        // Hide the button after adding one prompt
        $(this).hide();
    });
    
    // Handle removing a prompt
    $(document).on('click', '.remove-prompt', function(e) {
        e.preventDefault();
        $(this).closest('.prompt-item').remove();
        // Show the add button again since we now have 0 prompts
        $('#add-new-prompt').show();
    });

    // Add this to ensure prompt is saved with title
    $('#form_prompt').on('submit', function(e) {
        $('.prompt-item').each(function() {
            freshenup_updateHiddenInput($(this));
        });
    });
});