/**
 * AI Magic Metabox - Toolbar Interface
 *
 * Handles the toolbar interactions within the meta box
 *
 * @since 1.0.9
 */
(function ($) {
  "use strict";

  jQuery(document).ready(function ($) {
    const modal = $("#ai-magic-preview-modal");

    // Move modal to body to prevent z-index/overflow issues
    if (modal.parent().get(0) !== document.body) {
      modal.appendTo("body");
    }

    // UI Elements
    const promptInput = $("#ai-magic-prompt-input");
    const generateBtn = $("#ai-magic-generate-btn");
    const outputArea = $("#ai-magic-output");
    const outputContent = $("#ai-magic-output-content");
    const loadingArea = $("#ai-magic-loading");
    const optionsPanel = $("#ai-magic-options-panel");


    const autoInsertCheckbox = $("#ai-magic-auto-insert");

    // One-Click Full Article Elements
    const topicInput = $("#ai-magic-topic-input");
    const wordCountFull = $("#ai-magic-word-count-full");
    const generateFullBtn = $("#ai-magic-generate-full");
    const autoInsertAllCheckbox = $("#ai-magic-auto-insert-all");
    const progressBar = $("#ai-magic-progress");
    const progressFill = $("#ai-magic-progress-fill");

    // Inputs
    const providerSelect = $("#ai-magic-provider-select");
    const templateSelect = $("#ai-magic-template-select");
    const languageSelect = $("#ai-magic-language");
    const toneSelect = $("#ai-magic-tone");
    const styleSelect = $("#ai-magic-style");
    const wordCountSelect = $("#ai-magic-word-count");
    const keywordsInput = $("#ai-magic-keywords");
    const instructionsInput = $("#ai-magic-instructions");

    // Apply default settings from Settings page
    if (typeof aiMagicMetabox !== 'undefined') {
      if (aiMagicMetabox.defaultProvider && providerSelect.length) {
        providerSelect.val(aiMagicMetabox.defaultProvider);
      }
      if (aiMagicMetabox.defaultLanguage && languageSelect.length) {
        languageSelect.val(aiMagicMetabox.defaultLanguage);
      }
      if (aiMagicMetabox.defaultStyle && styleSelect.length) {
        styleSelect.val(aiMagicMetabox.defaultStyle);
      }
      if (aiMagicMetabox.defaultTone && toneSelect.length) {
        toneSelect.val(aiMagicMetabox.defaultTone);
      }
    }

    // Tabs Logic
    $(".ai-magic-tab-btn").on("click", function () {
      const tabId = $(this).data("tab");

      // Update buttons
      $(".ai-magic-tab-btn").removeClass("active");
      $(this).addClass("active");

      // Update content
      $(".ai-magic-tab-content").removeClass("active");
      $("#ai-magic-tab-" + tabId).addClass("active");
    });

    // State
    let isGenerating = false;

    // Initialize Autocomplete
    if ($.fn.autocomplete && aiMagicMetabox.promptHistory) {
      promptInput.autocomplete({
        source: aiMagicMetabox.promptHistory,
        minLength: 0,
        select: function (event, ui) {
          promptInput.val(ui.item.value);
        }
      }).focus(function () {
        // Show all items on focus
        $(this).autocomplete("search", "");
      });
    }

    // Initialize Autocomplete for Topic Input
    if ($.fn.autocomplete && aiMagicMetabox.topicHistory) {
      topicInput.autocomplete({
        source: aiMagicMetabox.topicHistory,
        minLength: 0,
        select: function (event, ui) {
          topicInput.val(ui.item.value);
          // Trigger auto-resize
          topicInput.css('height', 'auto').css('height', topicInput[0].scrollHeight + 'px');
        }
      }).focus(function () {
        // Show all items on focus
        $(this).autocomplete("search", "");
      });

      // Auto-resize textarea on input
      topicInput.on('input', function () {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
      });
    } else {
      // Fallback if autocomplete not available
      topicInput.on('input', function () {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
      });
    }

    /**
     * Show loading state
     */
    function showLoading() {
      loadingArea.addClass("active");
      outputArea.removeClass("active");
      generateBtn.prop("disabled", true);
    }

    /**
     * Hide loading state
     */
    function hideLoading() {
      loadingArea.removeClass("active");
      generateBtn.prop("disabled", false);
    }

    /**
     * Show output
     */
    function showOutput(content) {
      outputContent.html(content);
      outputArea.addClass("active");
    }

    /**
     * Generate Content
     */
    function generateContent() {
      const prompt = promptInput.val().trim();
      if (!prompt || isGenerating) return;

      isGenerating = true;
      showLoading();

      // Prepare data
      const data = {
        action: "generate_ai_magic_content",
        ai_magic_content: "toolbar", // Use 'toolbar' context
        ai_magic_try_text: prompt,
        provider: providerSelect.val(),
        template_id: templateSelect.val(),
        language: languageSelect.val(),
        tone: toneSelect.val(),
        style: styleSelect.val(),
        word_count: wordCountSelect.val(),
        keywords: keywordsInput.val(),
        instructions: instructionsInput.val(),
        nonce: aiMagicMetabox.nonce
      };

      // AJAX request
      $.ajax({
        type: "POST",
        url: ajaxurl,
        data: data,
        success: function (response) {
          hideLoading();
          isGenerating = false;

          if (response.success) {
            let content = "";
            let title = "";
            let tags = "";

            // 1. Try to get structured data
            if (response.data.data) {
              content = response.data.data.post_content || response.data.data.text || "";
              title = response.data.data.post_title || "";
              tags = response.data.data.post_tags || "";
            }

            // 2. Fallback to raw_text if content is empty or looks like a parsing artifact (e.g. just "#")
            // This fixes the issue where partial parsing results in empty content but raw_text has the goods
            if ((!content || content.trim() === "#" || content.trim() === "") && response.data.raw_text) {
              content = response.data.raw_text;
            }

            // 3. Final fallback to message text
            if (!content && response.data.text) {
              content = response.data.text;
            }

            if (!content) {
              content = "Received empty response.";
            }

            // Format content (basic markdown to HTML conversion if needed, or just nl2br)
            content = content.replace(/\n/g, "<br>");

            showOutput(content);

            // Update status with cost if available
            if (response.cost_formatted) {
              $("#ai-magic-status-text").html(
                `✓ Generated - Cost: ${response.cost_formatted} (${response.input_tokens} in + ${response.output_tokens} out tokens)`
              );
            } else {
              $("#ai-magic-status-text").text("✓ Generated successfully");
            }

            // Auto Insert if enabled
            if (autoInsertCheckbox.is(":checked")) {
              // Use the original content (before nl2br) for insertion
              autoInsertToEditor(title, response.data.data.post_content || response.data.raw_text || response.data.text, tags);
            }

          } else {
            showOutput("❌ Error: " + (response.data.message || response.data || "Unknown error"));
          }
        },
        error: function (xhr, status, error) {
          hideLoading();
          isGenerating = false;
          showOutput("❌ Network Error: " + error);
        }
      });
    }

    /**
     * Auto Insert to Editor (Title, Content, Tags, SEO)
     */
    function autoInsertToEditor(title, content, tags, articleData) {
      // Insert Title
      if (title) {
        if ($("#title").length) {
          $("#title").val(title).trigger("change"); // Classic
        } else if (wp.data && wp.data.dispatch("core/editor")) {
          wp.data.dispatch("core/editor").editPost({ title: title }); // Gutenberg
        }
      }

      // Insert Content
      if (content) {
        insertToEditor(content);
      }

      // Insert Tags
      if (tags) {
        insertTags(tags);
      }

      // Insert SEO Meta if available
      if (articleData) {
        updateSEOMeta(articleData);
      }

      // Insert Excerpt if available
      if (articleData && articleData.excerpt) {
        insertExcerpt(articleData.excerpt);
      }

      // Notify user
      const statusText = $("#ai-magic-status-text");
      const originalText = statusText.text();
      statusText.text("✅ Content inserted automatically!");
      setTimeout(() => statusText.text(originalText), 3000);
    }

    /**
     * Insert tags to WordPress
     */
    function insertTags(tags) {
      // Classic Editor tags
      if ($("#new-tag-post_tag").length) {
        $("#new-tag-post_tag").val(tags);
        $(".tagadd").click(); // Trigger add button
      } else if (wp.data && wp.data.dispatch("core/editor")) {
        // Gutenberg - create tags via AJAX and set them
        $.ajax({
          type: "POST",
          url: ajaxurl,
          data: {
            action: "ai_magic_create_tags",
            tags: tags,
            nonce: aiMagicMetabox.nonce
          },
          success: function (response) {
            if (response.success && response.data.tag_ids) {
              wp.data.dispatch("core/editor").editPost({
                tags: response.data.tag_ids
              });
            }
          }
        });
      }
    }

    /**
     * Insert excerpt
     */
    function insertExcerpt(excerpt) {
      // Classic Editor excerpt
      if ($("#excerpt").length) {
        $("#excerpt").val(excerpt).trigger("change");
      } else if (wp.data && wp.data.dispatch("core/editor")) {
        // Gutenberg
        wp.data.dispatch("core/editor").editPost({ excerpt: excerpt });
      }
    }

    /**
     * Update SEO Meta (Yoast, Rank Math, AIOSEO)
     */
    function updateSEOMeta(articleData) {
      // Yoast SEO
      if (typeof YoastSEO !== "undefined") {
        if (articleData.meta_description) {
          $("#yoast_wpseo_metadesc").val(articleData.meta_description).trigger("change");
        }
        if (articleData.focus_keyword) {
          $("#yoast_wpseo_focuskw").val(articleData.focus_keyword).trigger("change");
        }
        if (articleData.meta_title) {
          $("#yoast_wpseo_title").val(articleData.meta_title).trigger("change");
        }
        // Trigger Yoast refresh if available
        if (typeof YoastSEO.app !== "undefined" && YoastSEO.app.refresh) {
          YoastSEO.app.refresh();
        }
      }

      // Rank Math SEO
      if ($(".rank-math-editor").length || $("#rank_math_description").length) {
        if (articleData.meta_description) {
          $('textarea[name="rank_math_description"], #rank_math_description').val(articleData.meta_description).trigger("change");
        }
        if (articleData.focus_keyword) {
          $('input[name="rank_math_focus_keyword"], #rank_math_focus_keyword').val(articleData.focus_keyword).trigger("change");
        }
        if (articleData.meta_title) {
          $('input[name="rank_math_title"], #rank_math_title').val(articleData.meta_title).trigger("change");
        }
      }

      // All in One SEO (AIOSEO)
      if ($("#aioseo-post-settings").length || $(".aioseo-post-general").length) {
        if (articleData.meta_description) {
          $('textarea[name="aioseo-post-meta-description"]').val(articleData.meta_description).trigger("change");
        }
        if (articleData.focus_keyword) {
          $('input[name="aioseo-post-focus-keyphrase"]').val(articleData.focus_keyword).trigger("change");
        }
        if (articleData.meta_title) {
          $('input[name="aioseo-post-title"]').val(articleData.meta_title).trigger("change");
        }
      }
    }

    /**
     * Insert content to editor (Classic, Gutenberg, Elementor)
     */
    function insertToEditor(content) {
      // Check for Elementor first
      if (typeof elementor !== "undefined" && elementor.getPreviewContainer) {
        insertToElementor(content);
        return;
      }

      // Gutenberg
      if (wp.data && wp.data.dispatch("core/editor") && wp.blocks) {
        try {
          const blocks = wp.blocks.parse(content);
          const blockCount = wp.data.select("core/block-editor").getBlockCount();
          if (blocks.length > 0) {
            wp.data.dispatch("core/block-editor").insertBlocks(blocks, blockCount);
          } else {
            // If parsing fails, create a paragraph block
            const block = wp.blocks.createBlock("core/paragraph", {
              content: content
            });
            wp.data.dispatch("core/block-editor").insertBlocks([block], blockCount);
          }
        } catch (e) {
          // Fallback to raw HTML block
          const blockCount = wp.data.select("core/block-editor").getBlockCount();
          const block = wp.blocks.createBlock("core/html", {
            content: content
          });
          wp.data.dispatch("core/block-editor").insertBlocks([block], blockCount);
        }
        return;
      }

      // Classic Editor (TinyMCE)
      if (typeof tinyMCE !== "undefined" && tinyMCE.activeEditor) {
        tinyMCE.activeEditor.setContent(content);
        return;
      }

      // Textarea fallback
      const textarea = $("textarea#content");
      if (textarea.length) {
        if (textarea.val() === "") {
          textarea.val(content);
        } else {
          textarea.val(textarea.val() + "\n" + content);
        }
      }
    }

    /**
     * Insert content to Elementor
     */
    function insertToElementor(content) {
      // Check if content is JSON (Structure update)
      try {
        const jsonContent = JSON.parse(content);
        if (Array.isArray(jsonContent) || (typeof jsonContent === 'object' && jsonContent !== null)) {
          alert("Page structure updated successfully. Please reload the page to see the changes.");
          location.reload();
          return;
        }
      } catch (e) {
        // Not JSON, proceed with text insertion
      }

      if (typeof elementor !== "undefined" && typeof $e !== "undefined") {
        try {
          $e.run("document/elements/create", {
            model: {
              elType: "widget",
              widgetType: "text-editor",
              settings: {
                editor: content
              }
            },
            container: elementor.getPreviewContainer().children.first()
          });
        } catch (e) {
          console.log("Elementor insert failed:", e);
          // Fallback: try to find the main content area
          const editorFrame = $("#elementor-preview-iframe");
          if (editorFrame.length) {
            editorFrame.contents().find(".elementor-add-section").trigger("click");
          }
        }
      }
    }

    // Event Listeners

    // Generate button
    $(document).on("click", "#ai-magic-generate-btn", generateContent);

    // Enter key in prompt input
    promptInput.on("keydown", function (e) {
      if (e.key === "Enter") {
        e.preventDefault();
        generateContent();
      }
    });

    // Insert Button
    $(document).on("click", "#ai-magic-insert-btn", function () {
      const content = outputContent.html(); // Or text() depending on format
      insertToEditor(content);

      const btn = $(this);
      const originalText = btn.html();
      btn.html('<span class="dashicons dashicons-yes"></span> Inserted');
      setTimeout(() => btn.html(originalText), 2000);
    });

    // Copy Button
    $(document).on("click", "#ai-magic-copy-btn", function () {
      const content = outputContent.text();
      navigator.clipboard.writeText(content).then(() => {
        const btn = $(this);
        const originalText = btn.html();
        btn.html('<span class="dashicons dashicons-yes"></span> Copied');
        setTimeout(() => btn.html(originalText), 2000);
      });
    });

    // Regenerate Button
    $(document).on("click", "#ai-magic-regenerate-btn", generateContent);

    // Quick Actions
    $(".ai-magic-action-btn[data-action]").on("click", function () {
      const action = $(this).data("action");
      let prefix = "";

      // Define prefixes
      const prefixes = {
        "meta": "Write a meta description for: ",
        "keywords": "Generate keywords for: ",
        "image": "Create an image prompt for: ",
        "improve": "Improve this text: "
      };

      prefix = prefixes[action] || "";

      let currentVal = promptInput.val();

      // Remove any existing prefix
      for (const key in prefixes) {
        if (currentVal.startsWith(prefixes[key])) {
          currentVal = currentVal.replace(prefixes[key], "");
          break;
        }
      }

      // Set new value
      promptInput.val(prefix + currentVal);
      promptInput.focus();
    });

    // Preview Button
    $("#ai-magic-preview-btn").on("click", function () {
      const prompt = promptInput.val().trim();

      // Show modal immediately with loading state
      $("#ai-magic-preview-modal").fadeIn(200);
      $("#ai-magic-preview-prompt").html('<div class="ai-magic-spinner" style="margin: 20px auto;"></div>');
      $("#ai-magic-preview-settings").html('<li>Loading settings...</li>');

      const data = {
        action: "ai_magic_preview_prompt",
        prompt: prompt,
        provider: providerSelect.val(),
        language: languageSelect.val(),
        tone: toneSelect.val(),
        style: styleSelect.val(),
        word_count: wordCountSelect.val(),
        keywords: keywordsInput.val(),
        instructions: instructionsInput.val(),
        nonce: aiMagicMetabox.nonce
      };

      $.ajax({
        type: "POST",
        url: ajaxurl,
        data: data,
        success: function (response) {
          if (response.success) {
            // Show full prompt
            $("#ai-magic-preview-prompt").text(response.data.prompt);

            // Show settings list
            const settings = [];
            if (languageSelect.val()) settings.push("Language: " + languageSelect.find("option:selected").text());
            if (toneSelect.val()) settings.push("Tone: " + toneSelect.find("option:selected").text());
            if (styleSelect.val()) settings.push("Style: " + styleSelect.find("option:selected").text());
            if (wordCountSelect.val()) settings.push("Length: " + wordCountSelect.find("option:selected").text());
            if (keywordsInput.val()) settings.push("Keywords: " + keywordsInput.val());
            if (instructionsInput.val()) settings.push("Instructions: " + instructionsInput.val());

            const settingsList = $("#ai-magic-preview-settings");
            settingsList.empty();
            if (settings.length > 0) {
              settings.forEach(s => settingsList.append(`<li>${s}</li>`));
            } else {
              settingsList.append("<li>Default Settings</li>");
            }
          } else {
            $("#ai-magic-preview-prompt").html('<span style="color:red;">Error: ' + response.data + '</span>');
          }
        },
        error: function (xhr, status, error) {
          $("#ai-magic-preview-prompt").html('<span style="color:red;">Network Error: ' + error + '</span>');
        }
      });
    });

    // Close Modal
    // Close Modal
    $(".ai-magic-modal-close").on("click", function () {
      $(".ai-magic-modal").fadeOut(200);
    });

    // Generate from Modal
    $("#ai-magic-preview-generate").on("click", function () {
      $("#ai-magic-preview-modal").fadeOut(200);
      generateContent();
    });

    // Close modal on outside click
    $(window).on("click", function (e) {
      if ($(e.target).is("#ai-magic-preview-modal")) {
        $("#ai-magic-preview-modal").fadeOut(200);
      }
    });

    // Cost Estimation Logic
    function updateCostEstimate() {
      const model = $("#ai-magic-model").val() || "gpt-4o-mini"; // Default to mini if not found
      const promptText = promptInput.val() || "";
      const maxTokens = parseInt(wordCountSelect.val()) || 1000;

      // Approximate pricing per 1M tokens (Input / Output)
      // Prices are illustrative examples based on common OpenAI rates
      const pricing = {
        "gpt-4o": { input: 5.00, output: 15.00 },
        "gpt-4o-mini": { input: 0.15, output: 0.60 },
        "gpt-4-turbo": { input: 10.00, output: 30.00 },
        "gpt-3.5-turbo": { input: 0.50, output: 1.50 },
        "o1-preview": { input: 15.00, output: 60.00 },
        "o1-mini": { input: 3.00, output: 12.00 }
      };

      // Fallback for unknown models
      const rates = pricing[model] || pricing["gpt-4o-mini"];

      // Estimate input tokens (1 word ~= 0.75 tokens, so words / 0.75)
      // Simple char count approximation: 1 token ~= 4 chars
      const inputTokens = promptText.length / 4;

      // Output tokens is the max limit selected
      const outputTokens = maxTokens;

      const inputCost = (inputTokens / 1000000) * rates.input;
      const outputCost = (outputTokens / 1000000) * rates.output;
      const totalCost = inputCost + outputCost;

      // Format to 4 decimal places for small amounts, or less if larger
      let costString = totalCost < 0.01 ? totalCost.toFixed(5) : totalCost.toFixed(4);

      $("#ai-magic-cost-estimate").text("Est. Cost: $" + costString);
    }

    // Update cost on interactions
    promptInput.on("input", updateCostEstimate);
    $("#ai-magic-model, #ai-magic-word-count").on("change", updateCostEstimate);

    // Initial call
    updateCostEstimate();

    // ========================================
    // Builder Detection
    // ========================================

    function detectBuilder() {
      let builder = "classic";
      let builderName = "Classic Editor";

      // Elementor
      if ($("body").hasClass("elementor-editor-active") || typeof elementor !== "undefined" || $("#elementor-switch-mode").length > 0 || $(".elementor-switch-mode").length > 0) {
        builder = "elementor";
        builderName = "Elementor";
      }
      // Gutenberg
      else if ($("body").hasClass("block-editor-page") || (window.wp && wp.blocks)) {
        builder = "gutenberg";
        builderName = "Gutenberg";
      }
      // Divi (Basic detection)
      else if ($("body").hasClass("et_divi_builder")) {
        builder = "divi";
        builderName = "Divi Builder";
      }
      // WPBakery
      else if ($("body").hasClass("vc_editor")) {
        builder = "wpbakery";
        builderName = "WPBakery";
      }

      return { type: builder, name: builderName };
    }

    function updateBuilderBadge() {
      const detected = detectBuilder();
      const badge = $("#ai-magic-detected-builder");

      if (detected.type !== "classic") {
        badge.find(".builder-name").text(detected.name);
        badge.show();
      } else {
        badge.hide();
      }

      // Update status bar editor name
      $("#ai-magic-status-editor").text(detected.name);

      return detected;
    }

    // Run on load
    const currentBuilder = updateBuilderBadge();

    // ========================================
    // One-Click Full Article Generation
    // ========================================

    /**
     * Get current content from editor
     */
    function getCurrentContent() {
      // Gutenberg
      if (window.wp && wp.data && wp.data.select && wp.data.select("core/editor")) {
        try {
          return wp.data.select("core/editor").getEditedPostAttribute("content");
        } catch (e) {
          console.log("Gutenberg content retrieval failed", e);
        }
      }

      // Elementor (if active in editor)
      if (typeof elementor !== "undefined" && elementor.elements) {
        return JSON.stringify(elementor.elements.toJSON());
      }

      // Classic Editor (TinyMCE)
      if (typeof tinyMCE !== "undefined" && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
        return tinyMCE.activeEditor.getContent();
      }

      // Textarea fallback
      return $("#content").val() || "";
    }

    let isGeneratingFull = false;
    const languageFullSelect = $("#ai-magic-language-full");

    /**
     * Show progress indicator
     */
    function showProgress(step, percent) {
      progressBar.show();
      progressFill.css("width", percent + "%");

      // Update step indicators
      $(".ai-magic-progress-status .step").removeClass("active completed");
      $(".ai-magic-progress-status .step").each(function () {
        const stepNum = parseInt($(this).data("step"));
        if (stepNum < step) {
          $(this).addClass("completed");
        } else if (stepNum === step) {
          $(this).addClass("active");
        }
      });
    }

    /**
     * Hide progress indicator
     */
    function hideProgress() {
      progressBar.fadeOut(300);
      progressFill.css("width", "0%");
      $(".ai-magic-progress-status .step").removeClass("active completed");
    }

    /**
     * Generate full article with one click
     */
    function generateFullArticle() {
      const topic = topicInput.val().trim();

      if (!topic) {
        alert("Please enter a topic or title.");
        topicInput.focus();
        return;
      }

      if (isGeneratingFull) return;

      isGeneratingFull = true;
      generateFullBtn.prop("disabled", true).find("span:last").text("Generating...");
      showProgress(1, 10);

      const detected = detectBuilder();

      const data = {
        action: "ai_magic_generate_full_article",
        topic: topic,
        current_content: getCurrentContent(), // Send current content
        provider: providerSelect.val(),
        word_count: wordCountFull.val(),
        language: languageFullSelect.length ? languageFullSelect.val() : languageSelect.val(),
        style: styleSelect.val(),
        tone: toneSelect.val(),
        nonce: aiMagicMetabox.nonce,
        post_id: $("#post_ID").val(),
        auto_insert: autoInsertAllCheckbox.is(":checked") ? "1" : "0",
        builder: detected.type // Pass detected builder
      };

      $.ajax({
        type: "POST",
        url: ajaxurl,
        data: data,
        success: function (response) {
          isGeneratingFull = false;
          generateFullBtn.prop("disabled", false).find("span:last").text("Generate Article");

          if (response.success) {
            const articleData = response.data;

            // Update progress for each step
            showProgress(2, 40);

            setTimeout(() => {
              showProgress(3, 60);

              setTimeout(() => {
                showProgress(4, 80);

                setTimeout(() => {
                  showProgress(5, 100);

                  // Auto insert if enabled (Client-side fallback or notification)
                  if (autoInsertAllCheckbox.is(":checked")) {
                    if (response.data.auto_inserted) {
                      // Backend handled it
                      $("#ai-magic-status-text").text("✓ Content automatically inserted and updated!");
                      // Reload page after a delay to show changes (especially for Elementor)
                      setTimeout(() => {
                        window.location.reload();
                      }, 1500);
                    } else {
                      // Client-side fallback
                      console.log("Auto-inserting content (client-side)...");
                      autoInsertToEditor(
                        articleData.title,
                        articleData.content,
                        articleData.tags,
                        articleData
                      );
                      $("#ai-magic-status-text").text("✓ Full article generated successfully!");
                    }
                  } else {
                    $("#ai-magic-status-text").text("✓ Full article generated successfully!");
                  }

                  // Show in output area too
                  let displayContent = articleData.content || "";
                  displayContent = displayContent.replace(/\n/g, "<br>");
                  showOutput(displayContent);

                  setTimeout(hideProgress, 1000);
                }, 300);
              }, 300);
            }, 300);
          } else {
            hideProgress();
            showOutput("❌ Error: " + (response.data || "Unknown error"));
          }
        },
        error: function (xhr, status, error) {
          isGeneratingFull = false;
          generateFullBtn.prop("disabled", false).find("span:last").text("Generate Article");
          hideProgress();
          showOutput("❌ Network Error: " + error);
        }
      });
    }

    // Full article generate button
    $(document).on("click", "#ai-magic-generate-full", generateFullArticle);

    // Preview Full Article Button
    // Preview Full Article Button
    $(document).on("click", "#ai-magic-preview-full", function (e) {
      e.preventDefault();
      console.log("Preview button clicked");

      if (!topicInput || !topicInput.length) {
        console.error("Topic input not found");
        return;
      }

      const topicVal = topicInput.val();
      const topic = topicVal ? topicVal.trim() : "";

      if (!topic) {
        alert("Please enter a topic.");
        topicInput.focus();
        return;
      }

      // Show modal immediately with loading state
      const previewModal = $("#ai-magic-preview-modal");
      if (previewModal.length) {
        previewModal.fadeIn(200).css("display", "flex");
      } else {
        console.error("Preview modal not found");
        return;
      }

      $("#ai-magic-preview-prompt").html('<div class="ai-magic-spinner" style="margin: 20px auto;"></div>');
      $("#ai-magic-preview-settings").html('<li>Loading settings...</li>');

      const detected = detectBuilder();
      const langVal = languageFullSelect && languageFullSelect.length ? languageFullSelect.val() : (languageSelect && languageSelect.length ? languageSelect.val() : 'en');

      const data = {
        action: "ai_magic_preview_full_article_prompt",
        topic: topic,
        current_content: getCurrentContent(),
        word_count: wordCountFull.val(),
        language: langVal,
        style: styleSelect.val(),
        tone: toneSelect.val(),
        builder: detected.type,
        nonce: aiMagicMetabox.nonce
      };

      $.ajax({
        type: "POST",
        url: ajaxurl,
        data: data,
        success: function (response) {
          if (response.success) {
            // Show full prompt
            $("#ai-magic-preview-prompt").text(response.data.prompt);

            // Show settings list
            const settings = [];
            settings.push("Builder: " + detected.name);
            if (data.language) settings.push("Language: " + data.language);
            if (data.tone) settings.push("Tone: " + data.tone);
            if (data.style) settings.push("Style: " + data.style);
            if (data.word_count) settings.push("Length: " + data.word_count);

            const settingsList = $("#ai-magic-preview-settings");
            settingsList.empty();
            settings.forEach(s => settingsList.append(`<li>${s}</li>`));

            // Update generate button in modal to trigger full generation
            $("#ai-magic-preview-generate").off("click").on("click", function () {
              $("#ai-magic-preview-modal").fadeOut(200);
              generateFullArticle();
            });

          } else {
            $("#ai-magic-preview-prompt").html('<span style="color:red;">Error: ' + response.data + '</span>');
          }
        },
        error: function (xhr, status, error) {
          $("#ai-magic-preview-prompt").html('<span style="color:red;">Network Error: ' + error + '</span>');
        }
      });
    });

    // Enter key in topic input (Ctrl+Enter to submit)
    topicInput.on("keydown", function (e) {
      if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
        e.preventDefault();
        generateFullArticle();
      }
    });

    // ========================================
    // Quick Action Buttons
    // ========================================

    // Generate title suggestions
    $("#ai-magic-generate-titles").on("click", function () {
      const topic = topicInput.val().trim() || promptInput.val().trim();
      if (!topic) {
        alert("Please enter a topic.");
        return;
      }

      const btn = $(this);
      btn.prop("disabled", true).find("span:last").text("Loading...");

      $.ajax({
        type: "POST",
        url: ajaxurl,
        data: {
          action: "ai_magic_generate_titles",
          topic: topic,
          provider: providerSelect.val(),
          nonce: aiMagicMetabox.nonce
        },
        success: function (response) {
          btn.prop("disabled", false).find("span:last").text("Title Suggestions");

          if (response.success && response.data.titles) {
            let html = '<div class="ai-magic-titles-modal"><h4>📝 Title Suggestions</h4><ul class="ai-magic-titles-list">';
            response.data.titles.forEach((title, index) => {
              html += `<li data-title="${title.replace(/"/g, "&quot;")}">
                <span class="number">${index + 1}</span>
                <span class="title-text">${title}</span>
              </li>`;
            });
            html += '</ul><p style="font-size:12px;color:#666;margin-top:10px;">Click to select a title</p></div>';

            showOutput(html);

            // Handle title selection
            $(".ai-magic-titles-list li").on("click", function () {
              const selectedTitle = $(this).data("title");
              if ($("#title").length) {
                $("#title").val(selectedTitle).trigger("change");
              } else if (wp.data && wp.data.dispatch("core/editor")) {
                wp.data.dispatch("core/editor").editPost({ title: selectedTitle });
              }
              topicInput.val(selectedTitle);
              promptInput.val(selectedTitle);
              $("#ai-magic-status-text").text("✓ Title selected: " + selectedTitle);
            });
          } else {
            showOutput("❌ Could not get title suggestions: " + (response.data || "Unknown error"));
          }
        },
        error: function () {
          btn.prop("disabled", false).find("span:last").text("Title Suggestions");
          showOutput("❌ Connection error");
        }
      });
    });

    // Generate outline
    $("#ai-magic-generate-outline").on("click", function () {
      const topic = topicInput.val().trim() || promptInput.val().trim();
      if (!topic) {
        alert("Please enter a topic.");
        return;
      }

      const btn = $(this);
      btn.prop("disabled", true).find("span:last").text("Loading...");

      $.ajax({
        type: "POST",
        url: ajaxurl,
        data: {
          action: "ai_magic_generate_outline",
          topic: topic,
          provider: providerSelect.val(),
          nonce: aiMagicMetabox.nonce
        },
        success: function (response) {
          btn.prop("disabled", false).find("span:last").text("Generate Outline");

          if (response.success && response.data.outline) {
            const outline = response.data.outline.replace(/\n/g, "<br>");
            showOutput('<div class="ai-magic-outline-modal"><h4>📋 Content Outline</h4><div class="ai-magic-outline-preview">' + outline + '</div></div>');
          } else {
            showOutput("❌ Could not generate outline: " + (response.data || "Unknown error"));
          }
        },
        error: function () {
          btn.prop("disabled", false).find("span:last").text("Generate Outline");
          showOutput("❌ Connection error");
        }
      });
    });

    // ========================================
    // Help Modal Logic
    // ========================================

    // Open Help Modal
    $("#ai-magic-one-click-help").on("click", function (e) {
      e.preventDefault();
      e.stopPropagation();
      $("#ai-magic-help-modal").fadeIn(200);
    });

    // Close Help Modal (using existing close class)
    // Note: The generic close handler above handles .ai-magic-modal-close

    // Close Help Modal on outside click
    $(window).on("click", function (e) {
      if ($(e.target).is("#ai-magic-help-modal")) {
        $("#ai-magic-help-modal").fadeOut(200);
      }
    });

    // Improve content button
    $("#ai-magic-improve-content").on("click", function () {
      let content = "";

      // Get current content from editor
      if (wp.data && wp.data.select("core/editor")) {
        content = wp.data.select("core/editor").getEditedPostContent();
      } else if (typeof tinyMCE !== "undefined" && tinyMCE.activeEditor) {
        content = tinyMCE.activeEditor.getContent();
      } else if ($("textarea#content").length) {
        content = $("textarea#content").val();
      }

      if (!content || content.trim().length < 50) {
        alert("Please add content first to improve (at least 50 characters).");
        return;
      }

      // Set prompt input with improve action
      promptInput.val("Improve this text: " + content.substring(0, 500) + "...");
      $("#ai-magic-status-text").text("Content improvement mode active. Click Generate.");
    });

    // SEO Check button
    $("#ai-magic-check-seo").on("click", function () {
      let title = "";
      let content = "";

      // Get current title
      if ($("#title").length) {
        title = $("#title").val();
      } else if (wp.data && wp.data.select("core/editor")) {
        title = wp.data.select("core/editor").getEditedPostAttribute("title");
      }

      // Get current content
      if (wp.data && wp.data.select("core/editor")) {
        content = wp.data.select("core/editor").getEditedPostContent();
      } else if (typeof tinyMCE !== "undefined" && tinyMCE.activeEditor) {
        content = tinyMCE.activeEditor.getContent();
      } else if ($("textarea#content").length) {
        content = $("textarea#content").val();
      }

      if (!content || content.trim().length < 100) {
        alert("Please add content first for SEO check.");
        return;
      }

      // Simple SEO analysis
      const wordCount = content.split(/\s+/).length;
      const hasH1 = content.includes("<h1") || content.includes("# ");
      const hasH2 = content.includes("<h2") || content.includes("## ");
      const hasImages = content.includes("<img");
      const hasLinks = content.includes("<a ");
      const titleLength = title.length;

      let seoScore = 0;
      let suggestions = [];

      // Check word count
      if (wordCount >= 1000) {
        seoScore += 20;
      } else if (wordCount >= 500) {
        seoScore += 10;
        suggestions.push("📝 At least 1000 words recommended for ideal SEO.");
      } else {
        suggestions.push("⚠️ Content is too short. At least 500 words recommended.");
      }

      // Check headings
      if (hasH2) {
        seoScore += 20;
      } else {
        suggestions.push("📌 Add H2 headings.");
      }

      // Check title length
      if (titleLength >= 30 && titleLength <= 60) {
        seoScore += 20;
      } else if (titleLength > 0) {
        seoScore += 10;
        suggestions.push("📝 Title should be 30-60 characters.");
      } else {
        suggestions.push("⚠️ Add a title.");
      }

      // Check images
      if (hasImages) {
        seoScore += 20;
      } else {
        suggestions.push("🖼️ Consider adding images.");
      }

      // Check links
      if (hasLinks) {
        seoScore += 20;
      } else {
        suggestions.push("🔗 Add internal or external links.");
      }

      // Display results
      let resultHtml = `<div class="ai-magic-seo-check">
        <h4>🔍 SEO Analysis</h4>
        <div class="seo-score" style="text-align:center;margin:15px 0;">
          <div style="font-size:48px;font-weight:bold;color:${seoScore >= 70 ? '#10b981' : seoScore >= 40 ? '#f59e0b' : '#ef4444'};">${seoScore}/100</div>
          <div style="font-size:14px;color:#666;">${seoScore >= 70 ? 'Good' : seoScore >= 40 ? 'Medium' : 'Low'}</div>
        </div>
        <div class="seo-stats" style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin:15px 0;">
          <div style="text-align:center;padding:10px;background:#f8fafc;border-radius:6px;">
            <div style="font-size:20px;font-weight:bold;">${wordCount}</div>
            <div style="font-size:11px;color:#666;">Words</div>
          </div>
          <div style="text-align:center;padding:10px;background:#f8fafc;border-radius:6px;">
            <div style="font-size:20px;font-weight:bold;">${titleLength}</div>
            <div style="font-size:11px;color:#666;">Title Length</div>
          </div>
          <div style="text-align:center;padding:10px;background:#f8fafc;border-radius:6px;">
            <div style="font-size:20px;font-weight:bold;">${hasH2 ? '✓' : '✗'}</div>
            <div style="font-size:11px;color:#666;">H2 Headings</div>
          </div>
        </div>`;

      if (suggestions.length > 0) {
        resultHtml += '<div class="seo-suggestions" style="margin-top:15px;"><strong>Suggestions:</strong><ul style="margin:10px 0;padding-left:20px;">';
        suggestions.forEach(s => {
          resultHtml += `<li style="margin:5px 0;">${s}</li>`;
        });
        resultHtml += '</ul></div>';
      }

      resultHtml += '</div>';

      showOutput(resultHtml);
    });

    // ========================================
    // Title Suggestion Feature
    // ========================================

    /**
     * Initialize title suggestion button
     */
    function initTitleSuggestion() {
      // Check if button already exists
      if ($('#ai-magic-title-suggest-btn').length) {
        return;
      }

      // Create the suggestion button with SVG magic wand icon
      const suggestBtn = $(`
        <button type="button" id="ai-magic-title-suggest-btn" class="ai-magic-title-suggest-btn" title="AI Magic Title Suggestions">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M15 4V2"></path>
            <path d="M15 16v-2"></path>
            <path d="M8 9h2"></path>
            <path d="M20 9h2"></path>
            <path d="M17.8 11.8L19 13"></path>
            <path d="M15 9h0"></path>
            <path d="M17.8 6.2L19 5"></path>
            <path d="m3 21 9-9"></path>
            <path d="M12.2 6.2L11 5"></path>
          </svg>
          <span>AIM</span>
        </button>
      `);

      // Create dropdown container
      const dropdown = $(`
        <div id="ai-magic-title-dropdown" class="ai-magic-title-dropdown">
          <div class="ai-magic-title-dropdown-header">
            <h4>AI Magic Title Suggestions</h4>
            <button type="button" class="ai-magic-title-dropdown-close">&times;</button>
          </div>
          <div class="ai-magic-title-dropdown-content">
            <p style="font-size:12px;color:#666;margin:0;padding:8px 12px;">Enter a topic first, then click the AIM button to get suggestions.</p>
          </div>
        </div>
      `);

      // Classic Editor - Insert inside #titlewrap
      if ($('#title').length && !$('#ai-magic-title-suggest-btn').length) {
        const titleWrap = $('#titlewrap');
        if (titleWrap.length) {
          titleWrap.css('position', 'relative');
          suggestBtn.appendTo(titleWrap);
          dropdown.appendTo(titleWrap);
        }
      }

      // Gutenberg - Insert into the title area
      setTimeout(function () {
        if (wp && wp.data && wp.data.select('core/editor')) {
          const gutenbergTitle = $('.editor-post-title__input, .wp-block-post-title');
          if (gutenbergTitle.length && !$('#ai-magic-title-suggest-btn-gutenberg').length) {
            const wrapper = gutenbergTitle.parent();
            wrapper.css('position', 'relative');

            const gutenbergBtn = suggestBtn.clone().attr('id', 'ai-magic-title-suggest-btn-gutenberg');
            gutenbergBtn.css({
              'position': 'absolute',
              'right': '10px',
              'top': '50%',
              'transform': 'translateY(-50%)',
              'z-index': '100'
            });

            const gutenbergDropdown = dropdown.clone().attr('id', 'ai-magic-title-dropdown-gutenberg');

            wrapper.append(gutenbergBtn);
            wrapper.append(gutenbergDropdown);
          }
        }
      }, 1000);
    }

    /**
     * Generate title suggestions
     */
    function generateTitleSuggestions(topic, dropdownId, isMore = false) {
      const dropdown = $('#' + dropdownId);
      const content = dropdown.find('.ai-magic-title-dropdown-content');
      const existingList = dropdown.find('.ai-magic-title-dropdown-list');

      // Show loading - only replace content if no list exists
      if (!isMore || existingList.length === 0) {
        content.html(`
          <div class="ai-magic-title-dropdown-loading">
            <div class="ai-magic-spinner"></div>
            <span>Generating suggestions...</span>
          </div>
        `);
      }
      dropdown.addClass('active');

      $.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {
          action: 'ai_magic_generate_titles',
          topic: topic,
          content: getCurrentContent(),
          language: $('#ai-magic-language').val() || aiMagicMetabox.defaultLanguage || 'en',
          provider: $('#ai-magic-provider-select').val() || aiMagicMetabox.defaultProvider || 'openai',
          nonce: aiMagicMetabox.nonce
        },
        success: function (response) {
          if (response.success && response.data.titles) {
            // Get existing titles from dropdown
            const existingTitles = [];
            dropdown.find('.ai-magic-title-dropdown-list li').each(function () {
              existingTitles.push($(this).data('title'));
            });

            // Calculate starting index
            const startIndex = existingTitles.length;

            let html = dropdown.find('.ai-magic-title-dropdown-list').length ? '' : '<ul class="ai-magic-title-dropdown-list">';
            response.data.titles.forEach((title, index) => {
              // Strip HTML tags to get plain text
              const plainTitle = $('<div>').html(title).text().trim();
              html += `<li data-title="${plainTitle.replace(/"/g, '&quot;')}">
                <span class="number">${startIndex + index + 1}</span>
                <span class="title-text">${plainTitle}</span>
              </li>`;
            });

            if (dropdown.find('.ai-magic-title-dropdown-list').length) {
              // Append to existing list
              dropdown.find('.ai-magic-title-dropdown-list').append(html);
            } else {
              html += '</ul>';
              html += '<button type="button" class="ai-magic-title-more-btn">🔄 More Suggestions</button>';
              content.html(html);
            }

            // Handle title selection
            content.find('li').off('click').on('click', function () {
              const selectedTitle = $(this).data('title');

              // Classic Editor
              if ($('#title').length) {
                $('#title').val(selectedTitle).trigger('change');
              }

              // Gutenberg
              if (wp && wp.data && wp.data.dispatch('core/editor')) {
                wp.data.dispatch('core/editor').editPost({ title: selectedTitle });
              }

              // Update topic input in metabox too
              topicInput.val(selectedTitle);

              // Update status
              $('#ai-magic-status-text').text('✓ Title selected: ' + selectedTitle.substring(0, 40) + (selectedTitle.length > 40 ? '...' : ''));

              // Close dropdown
              dropdown.removeClass('active');
            });

            // Restore and handle More button click
            const moreBtn = content.find('.ai-magic-title-more-btn');
            moreBtn.html('🔄 More Suggestions').prop('disabled', false);
            moreBtn.off('click').on('click', function (e) {
              e.stopPropagation();
              $(this).html('<span class="ai-magic-spinner-inline"></span> Loading...').prop('disabled', true);
              generateTitleSuggestions(topic, dropdownId, true);
            });
          } else {
            // Restore More button on error too
            const moreBtn = content.find('.ai-magic-title-more-btn');
            if (moreBtn.length) {
              moreBtn.html('🔄 More Suggestions').prop('disabled', false);
            } else {
              content.html('<p style="color:#ef4444;padding:12px;">Failed to get suggestions. Please try again.</p>');
            }
          }
        },
        error: function () {
          const moreBtn = content.find('.ai-magic-title-more-btn');
          if (moreBtn.length) {
            moreBtn.html('🔄 More Suggestions').prop('disabled', false);
          } else {
            content.html('<p style="color:#ef4444;padding:12px;">Connection error. Please try again.</p>');
          }
        }
      });
    }

    // Initialize title suggestion button
    initTitleSuggestion();

    // Re-initialize for Gutenberg after DOM updates
    $(document).on('DOMNodeInserted', function (e) {
      if ($(e.target).hasClass('editor-post-title__input') || $(e.target).hasClass('wp-block-post-title')) {
        setTimeout(initTitleSuggestion, 500);
      }
    });

    // Handle title suggest button click (Classic Editor)
    $(document).on('click', '#ai-magic-title-suggest-btn', function (e) {
      e.preventDefault();
      e.stopPropagation();

      const dropdown = $('#ai-magic-title-dropdown');

      if (dropdown.hasClass('active')) {
        dropdown.removeClass('active');
        return;
      }

      // If titles already exist, just show the dropdown
      if (dropdown.find('.ai-magic-title-dropdown-list li').length > 0) {
        dropdown.addClass('active');
        return;
      }

      // Get current title or topic
      let topic = $('#title').val().trim();
      if (!topic) {
        topic = topicInput.val().trim();
      }
      if (!topic) {
        topic = promptInput.val().trim();
      }

      if (!topic) {
        dropdown.find('.ai-magic-title-dropdown-content').html('<p style="color:#f59e0b;padding:12px;">Please enter a title or topic first.</p>');
        dropdown.addClass('active');
        return;
      }

      generateTitleSuggestions(topic, 'ai-magic-title-dropdown');
    });

    // Handle title suggest button click (Gutenberg)
    $(document).on('click', '#ai-magic-title-suggest-btn-gutenberg', function (e) {
      e.preventDefault();
      e.stopPropagation();

      const dropdown = $('#ai-magic-title-dropdown-gutenberg');

      if (dropdown.hasClass('active')) {
        dropdown.removeClass('active');
        return;
      }

      // If titles already exist, just show the dropdown
      if (dropdown.find('.ai-magic-title-dropdown-list li').length > 0) {
        dropdown.addClass('active');
        return;
      }

      // Get current title from Gutenberg
      let topic = '';
      if (wp && wp.data && wp.data.select('core/editor')) {
        topic = wp.data.select('core/editor').getEditedPostAttribute('title') || '';
      }
      if (!topic) {
        topic = topicInput.val().trim();
      }

      if (!topic) {
        dropdown.find('.ai-magic-title-dropdown-content').html('<p style="color:#f59e0b;padding:12px;">Please enter a title or topic first.</p>');
        dropdown.addClass('active');
        return;
      }

      generateTitleSuggestions(topic, 'ai-magic-title-dropdown-gutenberg');
    });

    // Close dropdown on outside click
    $(document).on('click', function (e) {
      if (!$(e.target).closest('.ai-magic-title-dropdown, .ai-magic-title-suggest-btn').length) {
        $('.ai-magic-title-dropdown').removeClass('active');
      }
    });

    // Close dropdown on close button click
    $(document).on('click', '.ai-magic-title-dropdown-close', function () {
      $(this).closest('.ai-magic-title-dropdown').removeClass('active');
    });

  });
})(jQuery);

