/**
 * Rank Booster — Editor Injection
 *
 * When the post editor loads with ?rank_booster_inject=JOB_ID,
 * this script injects AI-generated content into the editor state.
 * Nothing is saved until the user clicks Update/Publish.
 *
 * Supports: Gutenberg (block editor) and Classic Editor (TinyMCE).
 *
 * Data comes from window.rankBoosterInject (set by inline PHP script):
 *   { title: '', content: '', meta: { key: val, ... } }
 */
(function($) {
    'use strict';

    var data = window.rankBoosterInject;
    if (!data) return;

    var editorType = window.rankBoosterEditorType || 'classic';

    /**
     * Gutenberg injection via wp.data.dispatch('core/editor').editPost()
     */
    function injectGutenberg() {
        // Wait for the editor store to be ready
        var attempts = 0;
        var maxAttempts = 50; // 5 seconds max

        var interval = setInterval(function() {
            attempts++;

            if (typeof wp === 'undefined' || !wp.data || !wp.data.select || !wp.data.dispatch) {
                if (attempts >= maxAttempts) {
                    clearInterval(interval);
                    console.warn('Rank Booster: Gutenberg editor not available, falling back to Classic.');
                    injectClassic();
                }
                return;
            }

            // Check if editor is ready (has a post loaded)
            var editor = wp.data.select('core/editor');
            if (!editor || !editor.getCurrentPostId || !editor.getCurrentPostId()) {
                if (attempts >= maxAttempts) {
                    clearInterval(interval);
                    console.warn('Rank Booster: Editor post not loaded in time.');
                }
                return;
            }

            clearInterval(interval);

            var payload = {};

            if (data.title) {
                payload.title = data.title;
            }
            if (data.content) {
                payload.content = data.content;
            }
            if (data.meta && Object.keys(data.meta).length > 0) {
                payload.meta = data.meta;
            }

            wp.data.dispatch('core/editor').editPost(payload);

            // Show a notice so the user knows AI content was injected
            if (wp.data.dispatch('core/notices')) {
                wp.data.dispatch('core/notices').createNotice(
                    'info',
                    'Page Booster: AI draft loaded. Review changes and click Update to save.',
                    { isDismissible: true, id: 'rank-booster-inject-notice' }
                );
            }

            console.log('Rank Booster: AI draft injected into Gutenberg editor.');
        }, 100);
    }

    /**
     * Classic Editor injection via TinyMCE + jQuery
     */
    function injectClassic() {
        var attempts = 0;
        var maxAttempts = 50;

        var interval = setInterval(function() {
            attempts++;

            // Wait for title field and TinyMCE to be available
            var $title = $('#title');
            var mceReady = (typeof tinymce !== 'undefined' && tinymce.get('content'));

            if (!$title.length || !mceReady) {
                if (attempts >= maxAttempts) {
                    clearInterval(interval);
                    console.warn('Rank Booster: Classic Editor not ready in time.');
                }
                return;
            }

            clearInterval(interval);

            if (data.title) {
                $title.val(data.title).trigger('change');
            }

            if (data.content) {
                tinymce.get('content').setContent(data.content);
                // Also update the text-mode textarea
                $('#content').val(data.content);
            }

            // Show a notice banner
            var $notice = $('<div class="notice notice-info is-dismissible"><p>' +
                '<strong>Page Booster:</strong> AI draft loaded. Review changes and click Update to save.' +
                '</p></div>');
            $('#wpbody-content .wrap').first().prepend($notice);

            console.log('Rank Booster: AI draft injected into Classic Editor.');
        }, 100);
    }

    // Detect which editor is active and inject
    if (editorType === 'gutenberg' || document.body.classList.contains('block-editor-page')) {
        injectGutenberg();
    } else {
        injectClassic();
    }

})(jQuery);
