/**
 * Forumax Inline Edit - Topic
 *
 * Intercepts the Edit link in the admin dropdown,
 * swaps the topic title and content with a visual TinyMCE editor,
 * and saves changes via AJAX without page reload.
 *
 * @package Forumax
 */
; (function ($) {

    'use strict';

    /**
     * TinyMCE editor ID used for the inline editor instance.
     *
     * @type {string}
     */
    var EDITOR_ID = 'frmx-edit-content';

    /**
     * Inline edit state management.
     */
    var FrmxInlineEdit = {

        isEditing: false,

        /**
         * Initialize inline edit functionality.
         */
        init: function () {
            this.bindEvents();
        },

        /**
         * Bind event listeners.
         */
        bindEvents: function () {
            var self = this;

            // Intercept the Edit option in the topic admin dropdown (nice-select).
            // nice-select does NOT copy data-action attributes, so we find the
            // corresponding <option> by index from the original <select>.
            $(document).on('click', '.topic-content-wrapper .bbp-admin-links-dropdown .nice-select .list .option', function (e) {
                var $option   = $(this);
                var optIndex  = $option.index();
                var $dropdown = $option.closest('.bbp-admin-links-dropdown');
                var $origOpt  = $dropdown.find('select option').eq(optIndex);
                var action    = $origOpt.data('action');

                if (action === 'edit') {
                    e.preventDefault();
                    e.stopPropagation();

                    var $wrapper = $dropdown.closest('.topic-content-wrapper');

                    // Close the nice-select dropdown
                    $dropdown.find('.nice-select').removeClass('open');

                    if (!self.isEditing) {
                        self.startEditing($wrapper);
                    }

                    return false;
                }
            });

            // Intercept changes on the original <select> (fallback for non-nice-select).
            // Scoped to topic-content-wrapper so it does not catch reply dropdowns.
            $(document).on('change', '.topic-content-wrapper .bbp-admin-dropdown-menu', function () {
                var $selected = $(this).find('option:selected');
                var action    = $selected.data('action');

                if (action === 'edit') {
                    $(this).val('');

                    var $dropdown = $(this).closest('.bbp-admin-links-dropdown');
                    var $wrapper  = $dropdown.closest('.topic-content-wrapper');

                    if (!self.isEditing) {
                        self.startEditing($wrapper);
                    }

                    return false;
                }
            });
        },

        /**
         * Start inline editing mode.
         *
         * @param {jQuery} $wrapper - The .topic-content-wrapper element.
         */
        startEditing: function ($wrapper) {
            var self    = this;
            var topicId = frmxInlineEdit.topic_id;

            if (!topicId) {
                return;
            }

            self.isEditing = true;

            // Show loading state
            var $titleEl   = $wrapper.find('.q-title h1');
            var $contentEl = $wrapper.find('.content.editor-content');

            // $titleEl.css('opacity', '0.5');
            $contentEl.css('opacity', '0.5');

            // Fetch raw content via AJAX
            $.ajax({
                url: frmxInlineEdit.ajaxurl,
                type: 'POST',
                data: {
                    action: 'forumax_get_topic_content',
                    nonce: frmxInlineEdit.nonce,
                    topic_id: topicId
                },
                success: function (response) {
                    if (response.success) {
                        self.renderEditor($wrapper, response.data);
                    } else {
                        self.showNotice($wrapper, response.data.message, 'error');
                        self.isEditing = false;
                    }

                    $titleEl.css('opacity', '');
                    $contentEl.css('opacity', '');
                },
                error: function () {
                    self.showNotice($wrapper, frmxInlineEdit.i18n.error, 'error');
                    self.isEditing = false;
                    $titleEl.css('opacity', '');
                    $contentEl.css('opacity', '');
                }
            });
        },

        /**
         * Render the inline editor form with TinyMCE visual editor.
         *
         * @param {jQuery} $wrapper - The .topic-content-wrapper element.
         * @param {Object} data     - { title, content } from the server.
         */
        renderEditor: function ($wrapper, data) {
            var self = this;

            var $qTitle    = $wrapper.find('.q-title');
            var $contentEl = $wrapper.find('.content.editor-content');

            // Store original HTML for cancel
            self.originalTitleHtml   = $qTitle.html();
            self.originalContentHtml = $contentEl.html();

            // Replace title with input
            var titleInput = '<div class="frmx-inline-edit-title">' +
                '<label for="frmx-edit-title" class="screen-reader-text">' + frmxInlineEdit.i18n.title_label + '</label>' +
                '<input type="text" id="frmx-edit-title" class="frmx-edit-title-input" value="' + self.escapeAttr(data.title) + '" />' +
                '</div>';
            $qTitle.html(titleInput);

            // Replace content with a textarea that TinyMCE will enhance
            var editorHtml = '<div class="frmx-inline-edit-content">' +
                '<label for="' + EDITOR_ID + '" class="screen-reader-text">' + frmxInlineEdit.i18n.content_label + '</label>' +
                '<textarea id="' + EDITOR_ID + '" class="frmx-edit-content-textarea" rows="12">' + data.content + '</textarea>' +
                '<div class="frmx-inline-edit-actions">' +
                    '<button type="button" class="frmx-edit-save">' + frmxInlineEdit.i18n.save + '</button>' +
                    '<button type="button" class="frmx-edit-cancel">' + frmxInlineEdit.i18n.cancel + '</button>' +
                '</div>' +
                '</div>';
            $contentEl.html(editorHtml);

            // Add editing class for styling
            $wrapper.addClass('frmx-is-editing');

            // Initialize TinyMCE visual editor on the textarea
            self.initTinyMCE();

            // Focus the title input
            $wrapper.find('.frmx-edit-title-input').focus();

            // Bind save/cancel
            $contentEl.find('.frmx-edit-save').on('click', function () {
                self.saveEdit($wrapper);
            });

            $contentEl.find('.frmx-edit-cancel').on('click', function () {
                self.cancelEdit($wrapper);
            });

            // Keyboard shortcuts on the title input
            $wrapper.find('.frmx-edit-title-input').on('keydown', function (e) {
                // Ctrl+Enter / Cmd+Enter to save
                if ((e.ctrlKey || e.metaKey) && e.keyCode === 13) {
                    e.preventDefault();
                    self.saveEdit($wrapper);
                }
                // Escape to cancel
                if (e.keyCode === 27) {
                    e.preventDefault();
                    self.cancelEdit($wrapper);
                }
            });
        },

        /**
         * Initialize TinyMCE on the editor textarea.
         *
         * Uses the WordPress wp.editor API for consistent behavior.
         */
        initTinyMCE: function () {
            var self = this;

            // Remove any existing editor instance first
            if (typeof wp !== 'undefined' && wp.editor) {
                wp.editor.remove(EDITOR_ID);
            }

            // Use wp.editor.initialize for proper TinyMCE setup
            if (typeof wp !== 'undefined' && wp.editor && wp.editor.initialize) {
                wp.editor.initialize(EDITOR_ID, {
                    tinymce: {
                        wpautop: true,
                        toolbar1: 'bold,italic,underline,strikethrough,|,bullist,numlist,|,blockquote,|,link,unlink,|,undo,redo',
                        toolbar2: '',
                        height: 250,
                        statusbar: false,
                        resize: true,
                        setup: function (editor) {
                            // Ctrl+Enter / Cmd+Enter to save from inside the editor
                            editor.on('keydown', function (e) {
                                if ((e.ctrlKey || e.metaKey) && e.keyCode === 13) {
                                    e.preventDefault();
                                    var $wrapper = $('#' + EDITOR_ID).closest('.topic-content-wrapper');
                                    self.saveEdit($wrapper);
                                }
                                if (e.keyCode === 27) {
                                    e.preventDefault();
                                    var $wrapper = $('#' + EDITOR_ID).closest('.topic-content-wrapper');
                                    self.cancelEdit($wrapper);
                                }
                            });
                        }
                    },
                    quicktags: true,
                    mediaButtons: false
                });
            }
        },

        /**
         * Get the content from TinyMCE or fallback textarea.
         *
         * @return {string} The editor content.
         */
        getEditorContent: function () {
            // Try TinyMCE first
            if (typeof tinyMCE !== 'undefined') {
                var editor = tinyMCE.get(EDITOR_ID);
                if (editor && !editor.isHidden()) {
                    return editor.getContent();
                }
            }

            // Fallback to textarea value (text mode)
            return $('#' + EDITOR_ID).val();
        },

        /**
         * Destroy the TinyMCE editor instance.
         */
        destroyEditor: function () {
            if (typeof wp !== 'undefined' && wp.editor) {
                wp.editor.remove(EDITOR_ID);
            }
        },

        /**
         * Save the inline edit via AJAX.
         *
         * @param {jQuery} $wrapper - The .topic-content-wrapper element.
         */
        saveEdit: function ($wrapper) {
            var self       = this;
            var topicId    = frmxInlineEdit.topic_id;
            var newTitle   = $wrapper.find('.frmx-edit-title-input').val().trim();
            var newContent = self.getEditorContent().trim();

            if (!newTitle) {
                self.showNotice($wrapper, frmxInlineEdit.i18n.title_required, 'error');
                $wrapper.find('.frmx-edit-title-input').focus();
                return;
            }

            if (!newContent) {
                self.showNotice($wrapper, frmxInlineEdit.i18n.content_required, 'error');
                return;
            }

            // Disable buttons and show saving state
            var $saveBtn = $wrapper.find('.frmx-edit-save');
            var $cancelBtn = $wrapper.find('.frmx-edit-cancel');
            $saveBtn.prop('disabled', true).text(frmxInlineEdit.i18n.saving);
            $cancelBtn.prop('disabled', true);

            $.ajax({
                url: frmxInlineEdit.ajaxurl,
                type: 'POST',
                data: {
                    action: 'forumax_save_topic_edit',
                    nonce: frmxInlineEdit.nonce,
                    topic_id: topicId,
                    title: newTitle,
                    content: newContent
                },
                success: function (response) {
                    if (response.success) {
                        // Destroy TinyMCE before replacing HTML
                        self.destroyEditor();

                        // Update the displayed content
                        var $qTitle    = $wrapper.find('.q-title');
                        var $contentEl = $wrapper.find('.content.editor-content');

                        // Restore title area with new title
                        $qTitle.html(self.originalTitleHtml);
                        $qTitle.find('h1').contents().first().replaceWith(response.data.title);

                        // Restore content area with new rendered content
                        $contentEl.html(response.data.content);

                        $wrapper.removeClass('frmx-is-editing');
                        self.isEditing = false;

                        self.showNotice($wrapper, response.data.message, 'success');

                        // Re-initialize nice-select on admin dropdown if it exists
                        if (typeof $.fn.frmxNiceSelect === 'function') {
                            $wrapper.find('select.bbp-admin-dropdown-menu').each(function () {
                                var $select = $(this);
                                $select.nextAll('.nice-select, .frmx-nice-select').remove();
                                $select.frmxNiceSelect();
                                $select.next('.frmx-nice-select').removeClass('nice-select');
                            });
                        }
                    } else {
                        self.showNotice($wrapper, response.data.message, 'error');
                        $saveBtn.prop('disabled', false).text(frmxInlineEdit.i18n.save);
                        $cancelBtn.prop('disabled', false);
                    }
                },
                error: function () {
                    self.showNotice($wrapper, frmxInlineEdit.i18n.error, 'error');
                    $saveBtn.prop('disabled', false).text(frmxInlineEdit.i18n.save);
                    $cancelBtn.prop('disabled', false);
                }
            });
        },

        /**
         * Cancel inline editing and restore original content.
         *
         * @param {jQuery} $wrapper - The .topic-content-wrapper element.
         */
        cancelEdit: function ($wrapper) {
            // Destroy TinyMCE before replacing HTML
            this.destroyEditor();

            var $qTitle    = $wrapper.find('.q-title');
            var $contentEl = $wrapper.find('.content.editor-content');

            $qTitle.html(this.originalTitleHtml);
            $contentEl.html(this.originalContentHtml);

            $wrapper.removeClass('frmx-is-editing');
            this.isEditing = false;
        },

        /**
         * Show a temporary notice message.
         *
         * @param {jQuery} $wrapper - The wrapper element.
         * @param {string} message  - The message text.
         * @param {string} type     - 'success' or 'error'.
         */
        showNotice: function ($wrapper, message, type) {
            // Remove any existing notices
            $wrapper.find('.frmx-inline-edit-notice').remove();

            var noticeClass = 'frmx-inline-edit-notice frmx-notice-' + type;
            var $notice = $('<div class="' + noticeClass + '">' + message + '</div>');

            $wrapper.find('.q-title').after($notice);

            // Auto-dismiss after 4 seconds
            setTimeout(function () {
                $notice.fadeOut(300, function () {
                    $(this).remove();
                });
            }, 4000);
        },

        /**
         * Escape HTML entities for safe attribute insertion.
         *
         * @param {string} str - The string to escape.
         * @return {string} Escaped string.
         */
        escapeAttr: function (str) {
            return str
                .replace(/&/g, '&amp;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;');
        }
    };

    $(document).ready(function () {
        // Only initialize on single topic pages
        if (typeof frmxInlineEdit !== 'undefined') {
            if ($('.topic-content-wrapper').length) {
                FrmxInlineEdit.init();
            }
            if ($('.forum-comment').length) {
                FrmxReplyInlineEdit.init();
            }
        }
    });

    /**
     * Reply inline edit state management.
     *
     * Intercepts the Edit link in reply admin dropdowns,
     * swaps the reply content with a visual TinyMCE editor,
     * and saves changes via AJAX without page reload.
     */
    var FrmxReplyInlineEdit = {

        /**
         * Track which reply is currently being edited (reply ID or false).
         *
         * @type {number|boolean}
         */
        editingReplyId: false,

        /**
         * Initialize reply inline edit functionality.
         */
        init: function () {
            this.bindEvents();
        },

        /**
         * Bind event listeners for reply edit interception.
         */
        bindEvents: function () {
            var self = this;

            // Intercept the Edit option in reply admin dropdown (nice-select).
            // nice-select does NOT copy data-action attributes, so we find the
            // corresponding <option> by index from the original <select>.
            $(document).on('click', '.reply-admin-links .bbp-admin-links-dropdown .nice-select .list .option, .reply-admin-links .bbp-admin-links-dropdown .frmx-nice-select .list .option', function (e) {
                var $option   = $(this);
                var optIndex  = $option.index();
                var $dropdown = $option.closest('.bbp-admin-links-dropdown');
                var $origOpt  = $dropdown.find('select option').eq(optIndex);
                var action    = $origOpt.data('action');

                if (action === 'edit') {
                    e.preventDefault();
                    e.stopPropagation();

                    var $reply = $dropdown.closest('.forum-comment');

                    // Close the nice-select dropdown
                    $dropdown.find('.nice-select, .frmx-nice-select').removeClass('open');

                    if (!self.editingReplyId) {
                        self.startEditing($reply);
                    }

                    return false;
                }
            });

            // Intercept changes on the original <select> (fallback for non-nice-select).
            $(document).on('change', '.reply-admin-links .bbp-admin-dropdown-menu', function () {
                var $selected = $(this).find('option:selected');
                var action    = $selected.data('action');

                if (action === 'edit') {
                    $(this).val('');

                    var $dropdown = $(this).closest('.bbp-admin-links-dropdown');
                    var $reply    = $dropdown.closest('.forum-comment');

                    if (!self.editingReplyId) {
                        self.startEditing($reply);
                    }

                    return false;
                }
            });
        },

        /**
         * Get the reply ID from a .forum-comment element.
         *
         * @param {jQuery} $reply - The .forum-comment element.
         * @return {number} The reply ID.
         */
        getReplyId: function ($reply) {
            // The reply container has id="post-{id}"
            var postId = $reply.attr('id');
            if (postId) {
                return parseInt(postId.replace('post-', ''), 10);
            }
            return 0;
        },

        /**
         * Get the TinyMCE editor ID for a specific reply.
         *
         * @param {number} replyId - The reply ID.
         * @return {string} The editor textarea ID.
         */
        getEditorId: function (replyId) {
            return 'frmx-reply-edit-content-' + replyId;
        },

        /**
         * Start inline editing mode for a reply.
         *
         * @param {jQuery} $reply - The .forum-comment element.
         */
        startEditing: function ($reply) {
            var self    = this;
            var replyId = self.getReplyId($reply);

            if (!replyId) {
                return;
            }

            self.editingReplyId = replyId;

            // Show loading state
            var $contentEl = $reply.find('.comment-content').first();
            $contentEl.css('opacity', '0.5');

            // Fetch raw content via AJAX
            $.ajax({
                url: frmxInlineEdit.ajaxurl,
                type: 'POST',
                data: {
                    action: 'forumax_get_reply_content',
                    nonce: frmxInlineEdit.nonce,
                    reply_id: replyId
                },
                success: function (response) {
                    if (response.success) {
                        self.renderEditor($reply, response.data);
                    } else {
                        self.showNotice($reply, response.data.message, 'error');
                        self.editingReplyId = false;
                    }

                    $contentEl.css('opacity', '');
                },
                error: function () {
                    self.showNotice($reply, frmxInlineEdit.i18n.error, 'error');
                    self.editingReplyId = false;
                    $contentEl.css('opacity', '');
                }
            });
        },

        /**
         * Render the inline editor form for a reply with TinyMCE visual editor.
         *
         * @param {jQuery} $reply - The .forum-comment element.
         * @param {Object} data   - { content } from the server.
         */
        renderEditor: function ($reply, data) {
            var self     = this;
            var replyId  = self.getReplyId($reply);
            var editorId = self.getEditorId(replyId);

            var $contentEl = $reply.find('.comment-content').first();

            // Store original HTML for cancel
            self.originalContentHtml = $contentEl.html();

            // Replace content with a textarea that TinyMCE will enhance
            var editorHtml = '<div class="frmx-inline-edit-content frmx-reply-inline-edit">' +
                '<label for="' + editorId + '" class="screen-reader-text">' + frmxInlineEdit.i18n.content_label + '</label>' +
                '<textarea id="' + editorId + '" class="frmx-edit-content-textarea" rows="10">' + data.content + '</textarea>' +
                '<div class="frmx-inline-edit-actions">' +
                    '<button type="button" class="frmx-edit-save">' + frmxInlineEdit.i18n.save + '</button>' +
                    '<button type="button" class="frmx-edit-cancel">' + frmxInlineEdit.i18n.cancel + '</button>' +
                '</div>' +
                '</div>';
            $contentEl.html(editorHtml);

            // Add editing class for styling
            $reply.addClass('frmx-is-editing');

            // Initialize TinyMCE visual editor on the textarea
            self.initTinyMCE(editorId);

            // Bind save/cancel
            $contentEl.find('.frmx-edit-save').on('click', function () {
                self.saveEdit($reply);
            });

            $contentEl.find('.frmx-edit-cancel').on('click', function () {
                self.cancelEdit($reply);
            });
        },

        /**
         * Initialize TinyMCE on the reply editor textarea.
         *
         * @param {string} editorId - The textarea element ID.
         */
        initTinyMCE: function (editorId) {
            var self = this;

            // Remove any existing editor instance first
            if (typeof wp !== 'undefined' && wp.editor) {
                wp.editor.remove(editorId);
            }

            // Use wp.editor.initialize for proper TinyMCE setup
            if (typeof wp !== 'undefined' && wp.editor && wp.editor.initialize) {
                wp.editor.initialize(editorId, {
                    tinymce: {
                        wpautop: true,
                        toolbar1: 'bold,italic,underline,strikethrough,|,bullist,numlist,|,blockquote,|,link,unlink,|,undo,redo',
                        toolbar2: '',
                        height: 200,
                        statusbar: false,
                        resize: true,
                        setup: function (editor) {
                            // Ctrl+Enter / Cmd+Enter to save from inside the editor
                            editor.on('keydown', function (e) {
                                if ((e.ctrlKey || e.metaKey) && e.keyCode === 13) {
                                    e.preventDefault();
                                    var $reply = $('#' + editorId).closest('.forum-comment');
                                    self.saveEdit($reply);
                                }
                                if (e.keyCode === 27) {
                                    e.preventDefault();
                                    var $reply = $('#' + editorId).closest('.forum-comment');
                                    self.cancelEdit($reply);
                                }
                            });
                        }
                    },
                    quicktags: true,
                    mediaButtons: false
                });
            }
        },

        /**
         * Get the content from TinyMCE or fallback textarea for a reply.
         *
         * @param {string} editorId - The editor textarea ID.
         * @return {string} The editor content.
         */
        getEditorContent: function (editorId) {
            // Try TinyMCE first
            if (typeof tinyMCE !== 'undefined') {
                var editor = tinyMCE.get(editorId);
                if (editor && !editor.isHidden()) {
                    return editor.getContent();
                }
            }

            // Fallback to textarea value (text mode)
            return $('#' + editorId).val();
        },

        /**
         * Destroy the TinyMCE editor instance for a reply.
         *
         * @param {string} editorId - The editor textarea ID.
         */
        destroyEditor: function (editorId) {
            if (typeof wp !== 'undefined' && wp.editor) {
                wp.editor.remove(editorId);
            }
        },

        /**
         * Save the inline reply edit via AJAX.
         *
         * @param {jQuery} $reply - The .forum-comment element.
         */
        saveEdit: function ($reply) {
            var self       = this;
            var replyId    = self.getReplyId($reply);
            var editorId   = self.getEditorId(replyId);
            var newContent = self.getEditorContent(editorId).trim();

            if (!newContent) {
                self.showNotice($reply, frmxInlineEdit.i18n.content_required, 'error');
                return;
            }

            // Disable buttons and show saving state
            var $saveBtn   = $reply.find('.frmx-edit-save');
            var $cancelBtn = $reply.find('.frmx-edit-cancel');
            $saveBtn.prop('disabled', true).text(frmxInlineEdit.i18n.saving);
            $cancelBtn.prop('disabled', true);

            $.ajax({
                url: frmxInlineEdit.ajaxurl,
                type: 'POST',
                data: {
                    action: 'forumax_save_reply_edit',
                    nonce: frmxInlineEdit.nonce,
                    reply_id: replyId,
                    content: newContent
                },
                success: function (response) {
                    if (response.success) {
                        // Destroy TinyMCE before replacing HTML
                        self.destroyEditor(editorId);

                        // Restore content area with new rendered content
                        var $contentEl = $reply.find('.comment-content').first();
                        $contentEl.html(response.data.content);

                        $reply.removeClass('frmx-is-editing');
                        self.editingReplyId = false;

                        self.showNotice($reply, response.data.message, 'success');

                        // Re-initialize nice-select on admin dropdown if it exists
                        if (typeof $.fn.frmxNiceSelect === 'function') {
                            $reply.find('select.bbp-admin-dropdown-menu').each(function () {
                                var $select = $(this);
                                $select.nextAll('.nice-select, .frmx-nice-select').remove();
                                $select.frmxNiceSelect();
                                $select.next('.frmx-nice-select').removeClass('nice-select');
                            });
                        }

                        // Re-initialize nested reply buttons if they exist
                        self.reinitNestedReplyButtons($reply);
                    } else {
                        self.showNotice($reply, response.data.message, 'error');
                        $saveBtn.prop('disabled', false).text(frmxInlineEdit.i18n.save);
                        $cancelBtn.prop('disabled', false);
                    }
                },
                error: function () {
                    self.showNotice($reply, frmxInlineEdit.i18n.error, 'error');
                    $saveBtn.prop('disabled', false).text(frmxInlineEdit.i18n.save);
                    $cancelBtn.prop('disabled', false);
                }
            });
        },

        /**
         * Cancel inline editing and restore original reply content.
         *
         * @param {jQuery} $reply - The .forum-comment element.
         */
        cancelEdit: function ($reply) {
            var editorId = this.getEditorId(this.getReplyId($reply));

            // Destroy TinyMCE before replacing HTML
            this.destroyEditor(editorId);

            var $contentEl = $reply.find('.comment-content').first();
            $contentEl.html(this.originalContentHtml);

            $reply.removeClass('frmx-is-editing');
            this.editingReplyId = false;
        },

        /**
         * Show a temporary notice message for a reply.
         *
         * @param {jQuery} $reply  - The .forum-comment element.
         * @param {string} message - The message text.
         * @param {string} type    - 'success' or 'error'.
         */
        showNotice: function ($reply, message, type) {
            // Remove any existing notices
            $reply.find('.frmx-inline-edit-notice').remove();

            var noticeClass = 'frmx-inline-edit-notice frmx-notice-' + type;
            var $notice = $('<div class="' + noticeClass + '">' + message + '</div>');

            $reply.find('.comment-content').first().before($notice);

            // Auto-dismiss after 4 seconds
            setTimeout(function () {
                $notice.fadeOut(300, function () {
                    $(this).remove();
                });
            }, 4000);
        },

        /**
         * Re-initialize nested reply buttons after content update.
         *
         * This ensures the "Reply" button works correctly after inline editing.
         *
         * @param {jQuery} $reply - The .forum-comment element.
         */
        reinitNestedReplyButtons: function ($reply) {
            // Only proceed if bbPress reply system is loaded and nested replies is enabled.
            if (typeof addReply === 'undefined' || ! addReply.moveForm) {
                return;
            }

            // Find all reply-to links in the reply.
            $reply.find('a.bbp-reply-to-link').each(function () {
                var $link = $(this);

                // Extract the reply ID from the link's onclick or data attributes.
                var replyId = $link.data('reply-id');

                // If no data attribute, try to extract from onclick attribute.
                if (!replyId) {
                    var onclick = $link.attr('onclick');
                    if (onclick) {
                        var match = onclick.match(/addReply\.moveForm\([^,]+,\s*['"](\d+)['"]/);
                        if (match) {
                            replyId = match[1];
                        }
                    }
                }

                // If we still don't have a reply ID, try to get it from the parent post ID.
                if (!replyId) {
                    var $post = $link.closest('[id^="post-"]');
                    if ($post.length) {
                        replyId = $post.attr('id').replace('post-', '');
                    }
                }

                if (replyId) {
                    // Remove any existing onclick to avoid duplicates.
                    $link.removeAttr('onclick');

                    // Attach the click handler.
                    $link.on('click', function (e) {
                        e.preventDefault();

                        // Get topic ID from localized script if available.
                        var topicId = (typeof frmxInlineEdit !== 'undefined' && frmxInlineEdit.topic_id)
                            ? frmxInlineEdit.topic_id
                            : 0;

                        // Use bbPress's addReply.moveForm to move the reply form.
                        // Parameters: anchor, replyId, respondId, postId
                        addReply.moveForm(
                            'bbp-reply-to-link-' + replyId,
                            replyId,
                            'new-post',
                            topicId
                        );

                        return false;
                    });
                }
            });
        }
    };

})(jQuery);
