(function ($) {
    "use strict";

    jQuery(document).ready(function ($) {

        const panel = $("#ai-magic-slide-panel");
        const messagesContainer = $("#ai-magic-messages");
        const chatInput = $("#ai-magic-chat-input");
        const sendBtn = $("#ai-magic-send-btn");
        const templateSelect = $("#ai-magic-template");

        // Open panel when admin bar item clicked
        $("#wp-admin-bar-ai-magic-chat").on("click", function (e) {
            e.preventDefault();
            panel.addClass("active");
            chatInput.focus();
        });

        // Close panel
        $(".ai-magic-panel-close, .ai-magic-panel-overlay").on("click", function () {
            panel.removeClass("active");
        });

        // Close on ESC key
        $(document).on("keydown", function (e) {
            if (e.key === "Escape" && panel.hasClass("active")) {
                panel.removeClass("active");
            }
        });

        // Auto-resize textarea
        chatInput.on('input', function () {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });

        // Add message to chat
        function addMessage(text, isAI = false, time = 'Now') {
            const avatarIcon = isAI ?
                '<span class="dashicons dashicons-admin-comments"></span>' :
                '<span class="dashicons dashicons-admin-users"></span>';

            const messageHTML = `
        <div class="ai-magic-message ${isAI ? 'ai' : 'user'}">
          <div class="ai-magic-message-avatar">${avatarIcon}</div>
          <div class="ai-magic-message-content">
            <div class="ai-magic-message-text">${text}</div>
            <div class="ai-magic-message-time">${time}</div>
          </div>
        </div>
      `;

            messagesContainer.append(messageHTML);
            scrollToBottom();
        }

        // Scroll to bottom
        function scrollToBottom() {
            messagesContainer.animate({
                scrollTop: messagesContainer[0].scrollHeight
            }, 300);
        }

        // Show typing indicator
        function showTyping() {
            const typingHTML = `
        <div class="ai-magic-message ai ai-magic-typing-message">
          <div class="ai-magic-message-avatar">
            <span class="dashicons dashicons-admin-comments"></span>
          </div>
          <div class="ai-magic-message-content">
            <div class="ai-magic-typing" style="display: block;">
              <div class="ai-magic-typing-dots">
                <div class="ai-magic-typing-dot"></div>
                <div class="ai-magic-typing-dot"></div>
                <div class="ai-magic-typing-dot"></div>
              </div>
            </div>
          </div>
        </div>
      `;

            messagesContainer.append(typingHTML);
            scrollToBottom();
        }

        // Hide typing indicator
        function hideTyping() {
            $(".ai-magic-typing-message").remove();
        }

        // Quick action buttons
        $(".ai-magic-action-btn").on("click", function () {
            const action = $(this).data("action");

            switch (action) {
                case 'blog-post':
                    chatInput.val("Write a comprehensive blog post about WordPress SEO");
                    templateSelect.val("1");
                    break;
                case 'meta-description':
                    generateMetaDescription();
                    return;
                case 'keywords':
                    extractKeywords();
                    return;
                case 'how-to':
                    chatInput.val("Create a how-to guide");
                    templateSelect.val("2");
                    break;
                case 'product':
                    chatInput.val("Write a product description");
                    templateSelect.val("6");
                    break;
                case 'history':
                    window.location.href = "admin.php?page=ai-magic-history";
                    return;
            }

            chatInput.focus();
        });

        // Send message
        function sendMessage() {
            const message = chatInput.val().trim();
            const template_id = templateSelect.val();
            const provider = $("#ai-magic-chat-provider").val();

            if (!message) {
                addMessage("❌ Please type a message!", true);
                return;
            }

            // Add user message
            addMessage(message, false);

            // Clear input
            chatInput.val('');
            chatInput.css('height', 'auto');

            // Disable send button
            sendBtn.prop("disabled", true);

            // Show typing
            showTyping();

            // Send AJAX request
            $.ajax({
                type: "POST",
                url: aiMagicPanel.ajaxurl,
                data: {
                    action: "ai_magic_chat_message",
                    message: message,
                    template_id: template_id,
                    provider: provider,
                    nonce: aiMagicPanel.nonce
                },
                success: function (response) {
                    hideTyping();

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

                        // Add success message
                        addMessage(`✅ <strong>Content created successfully!</strong><br><br>
              📝 <strong>Title:</strong> ${data.post_title}<br>
              📊 <strong>Word Count:</strong> ~${Math.round(data.post_content.length / 6)} words<br><br>
              Content has been added to the editor!`, true);

                        // Update Gutenberg editor if available
                        if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch("core/editor")) {
                            wp.data.dispatch("core/editor").editPost({ title: data.post_title });
                            wp.data.dispatch("core/editor").editPost({ excerpt: data.post_excerpt });
                            wp.data.dispatch("core/editor").editPost({ content: data.post_content });
                        }
                    } else {
                        addMessage(`❌ <strong>Error:</strong> ${response.data}`, true);
                    }

                    sendBtn.prop("disabled", false);
                },
                error: function () {
                    hideTyping();
                    addMessage("❌ <strong>An error occurred.</strong> Please try again.", true);
                    sendBtn.prop("disabled", false);
                }
            });
        }

        // Generate meta description
        function generateMetaDescription() {
            let post_id = 0;
            let title = "";
            let content = "";

            // Try to get post data
            if (typeof wp !== 'undefined' && wp.data && wp.data.select("core/editor")) {
                const currentPost = wp.data.select("core/editor").getCurrentPost();
                post_id = currentPost.id || 0;
                title = currentPost.title || "";
                content = wp.data.select("core/editor").getEditedPostContent();
            } else {
                // Fallback for classic editor
                title = $("#title").val() || "";
                content = $("#content").val() || "";
            }

            if (!title) {
                addMessage("❌ Please enter a post title first!", true);
                return;
            }

            addMessage("Generate meta description", false);
            showTyping();

            $.ajax({
                type: "POST",
                url: aiMagicPanel.ajaxurl,
                data: {
                    action: "ai_magic_generate_meta",
                    post_id: post_id,
                    title: title,
                    content: content,
                    nonce: aiMagicPanel.nonce
                },
                success: function (response) {
                    hideTyping();

                    if (response.type === 'success') {
                        addMessage(`✅ <strong>Meta description generated!</strong><br><br>
              "${response.data}"<br><br>
              📏 Length: ${response.length} characters`, true);
                    } else {
                        addMessage(`❌ ${response.message}`, true);
                    }
                },
                error: function () {
                    hideTyping();
                    addMessage("❌ An error occurred.", true);
                }
            });
        }

        // Extract keywords
        function extractKeywords() {
            let content = "";

            // Try to get content
            if (typeof wp !== 'undefined' && wp.data && wp.data.select("core/editor")) {
                content = wp.data.select("core/editor").getEditedPostContent();
            } else {
                content = $("#content").val() || "";
            }

            if (!content) {
                addMessage("❌ Please add some content first!", true);
                return;
            }

            addMessage("Extract keywords", false);
            showTyping();

            $.ajax({
                type: "POST",
                url: aiMagicPanel.ajaxurl,
                data: {
                    action: "ai_magic_extract_keywords",
                    content: content,
                    nonce: aiMagicPanel.nonce
                },
                success: function (response) {
                    hideTyping();

                    if (response.type === 'success') {
                        const keywords = response.data.join(", ");
                        addMessage(`🔑 <strong>Keywords:</strong><br><br>${keywords}`, true);
                    } else {
                        addMessage(`❌ ${response.message}`, true);
                    }
                },
                error: function () {
                    hideTyping();
                    addMessage("❌ An error occurred.", true);
                }
            });
        }

        // Send button click
        sendBtn.on("click", sendMessage);

        // Enter key to send (Shift+Enter for new line)
        chatInput.on("keydown", function (e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

    });
})(jQuery);
