/**
 * WordChat AI Content Writer
 * JavaScript for content generation, link suggestions, and editing
 */

(function($) {
    'use strict';

    // Tab switching
    $('.wordchat-tab-button').on('click', function() {
        const tabName = $(this).data('tab');

        // Update button states
        $('.wordchat-tab-button').removeClass('active');
        $(this).addClass('active');

        // Show/hide tab content
        $('.wordchat-tab-content').hide();
        $('#wordchat-tab-' + tabName).show();
    });

    // =====================================================
    // CONTENT GENERATION
    // =====================================================

    $('#wordchat-generate-form').on('submit', function(e) {
        e.preventDefault();

        const $form = $(this);
        const $submitBtn = $form.find('button[type="submit"]');
        const $status = $('#wordchat-generate-status');

        // Get form data
        const topic = $('#wordchat-topic').val().trim();
        const tone = $('#wordchat-tone').val();
        const wordCount = parseInt($('#wordchat-word-count').val());
        const relatedPosts = $('#wordchat-related-posts').val() || [];

        if (!topic) {
            alert('Please enter a topic');
            return;
        }

        // Disable form
        $submitBtn.prop('disabled', true);
        $status.html('<span class="wordchat-loading"><span class="spinner"></span> Generating content...</span>');
        $('#wordchat-preview-panel').hide();

        // Call backend API
        $.ajax({
            url: WordChatVars.ajax_url,
            type: 'POST',
            data: {
                action: 'wordchat_generate_content',
                nonce: WordChatVars.nonce,
                topic: topic,
                tone: tone,
                target_word_count: wordCount,
                related_post_urls: relatedPosts
            },
            success: function(response) {
                if (response.success) {
                    displayGeneratedContent(response.data);
                    $status.html('<span style="color: #22c55e;">✓ Content generated successfully!</span>');
                } else {
                    alert('Error: ' + (response.data || 'Failed to generate content'));
                    $status.html('<span style="color: #ef4444;">✗ Generation failed</span>');
                }
            },
            error: function(xhr) {
                console.error('Generation error:', xhr);
                alert('Network error. Please try again.');
                $status.html('<span style="color: #ef4444;">✗ Network error</span>');
            },
            complete: function() {
                $submitBtn.prop('disabled', false);
            }
        });
    });

    function displayGeneratedContent(data) {
        const generation = data.generation;

        // Build metadata display
        const meta = `
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px;">
                <div>
                    <strong>Word Count:</strong> ${generation.word_count}
                </div>
                <div>
                    <strong>Generation Time:</strong> ${(generation.generation_time_ms / 1000).toFixed(1)}s
                </div>
                <div>
                    <strong>Tokens Used:</strong> ${generation.tokens_used}
                </div>
            </div>
            <div style="margin-top: 12px;">
                <strong>Meta Description:</strong><br>
                <span style="color: #64748b;">${generation.meta_description}</span>
            </div>
            ${generation.title_variations && generation.title_variations.length > 0 ? `
                <div style="margin-top: 12px;">
                    <strong>Alternative Titles:</strong><br>
                    <ul style="margin: 8px 0 0 20px;">
                        ${generation.title_variations.map(title => `<li>${title}</li>`).join('')}
                    </ul>
                </div>
            ` : ''}
        `;

        $('#wordchat-generation-meta').html(meta);

        // Convert markdown to HTML (simple conversion)
        const contentHtml = markdownToHtml(generation.content);
        $('#wordchat-preview-content').html(contentHtml);

        // Store data for saving
        $('#wordchat-preview-panel').data('generation', generation);

        // Show preview
        $('#wordchat-preview-panel').fadeIn();

        // Scroll to preview
        $('html, body').animate({
            scrollTop: $('#wordchat-preview-panel').offset().top - 100
        }, 500);
    }

    // Copy content to clipboard
    $('#wordchat-copy-content').on('click', function() {
        const generation = $('#wordchat-preview-panel').data('generation');
        const textToCopy = `${generation.title}\n\n${generation.content}\n\nMeta Description: ${generation.meta_description}`;

        navigator.clipboard.writeText(textToCopy).then(function() {
            const $btn = $('#wordchat-copy-content');
            const originalText = $btn.html();
            $btn.html('<span class="dashicons dashicons-yes"></span> Copied!');
            setTimeout(function() {
                $btn.html(originalText);
            }, 2000);
        }).catch(function(err) {
            alert('Failed to copy to clipboard');
        });
    });

    // Save as draft
    $('#wordchat-save-draft').on('click', function() {
        const generation = $('#wordchat-preview-panel').data('generation');

        if (!confirm('Save this content as a WordPress draft post?')) {
            return;
        }

        const $btn = $(this);
        $btn.prop('disabled', true).text('Saving...');

        $.ajax({
            url: WordChatVars.ajax_url,
            type: 'POST',
            data: {
                action: 'wordchat_save_draft',
                nonce: WordChatVars.nonce,
                title: generation.title,
                content: generation.content,
                excerpt: generation.meta_description
            },
            success: function(response) {
                if (response.success) {
                    alert('Draft saved successfully! Post ID: ' + response.data.post_id);
                    // Optionally redirect to edit page
                    if (confirm('Open the draft post for editing?')) {
                        window.location.href = response.data.edit_url;
                    }
                } else {
                    alert('Error: ' + (response.data || 'Failed to save draft'));
                }
            },
            error: function() {
                alert('Network error. Please try again.');
            },
            complete: function() {
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt"></span> Save as Draft');
            }
        });
    });

    // =====================================================
    // LINK SUGGESTIONS
    // =====================================================

    $('#wordchat-suggest-links-form').on('submit', function(e) {
        e.preventDefault();

        const postId = $('#wordchat-select-post').val();
        if (!postId) {
            alert('Please select a post');
            return;
        }

        const $submitBtn = $(this).find('button[type="submit"]');
        const $status = $('#wordchat-suggest-status');

        $submitBtn.prop('disabled', true);
        $status.html('<span class="wordchat-loading"><span class="spinner"></span> Analyzing content...</span>');
        $('#wordchat-suggestions-panel').hide();

        $.ajax({
            url: WordChatVars.ajax_url,
            type: 'POST',
            data: {
                action: 'wordchat_suggest_links',
                nonce: WordChatVars.nonce,
                post_id: postId
            },
            success: function(response) {
                if (response.success) {
                    displayLinkSuggestions(response.data);
                    $status.html('<span style="color: #22c55e;">✓ Found ' + response.data.suggestions.length + ' suggestions</span>');
                } else {
                    alert('Error: ' + (response.data || 'Failed to get suggestions'));
                    $status.html('<span style="color: #ef4444;">✗ Failed</span>');
                }
            },
            error: function() {
                alert('Network error. Please try again.');
                $status.html('<span style="color: #ef4444;">✗ Network error</span>');
            },
            complete: function() {
                $submitBtn.prop('disabled', false);
            }
        });
    });

    function displayLinkSuggestions(data) {
        const suggestions = data.suggestions;

        if (suggestions.length === 0) {
            $('#wordchat-suggestions-list').html('<p style="color: #64748b;">No link suggestions found. Try syncing more content first.</p>');
            $('#wordchat-suggestions-panel').fadeIn();
            return;
        }

        let html = '';
        suggestions.forEach((suggestion, index) => {
            html += `
                <div class="wordchat-link-suggestion" data-index="${index}">
                    <div style="display: flex; justify-content: space-between; align-items: start;">
                        <div style="flex: 1;">
                            <div style="font-weight: 600; margin-bottom: 8px;">
                                Link: <span style="color: #3b82f6;">"${escapeHtml(suggestion.anchor)}"</span>
                                →
                                <a href="${escapeHtml(suggestion.target_url)}" target="_blank" style="color: #3b82f6;">
                                    ${escapeHtml(suggestion.target_title || suggestion.target_url)}
                                </a>
                            </div>
                            <div style="color: #64748b; font-size: 13px; margin-bottom: 8px;">
                                <strong>Context:</strong>
                                "${escapeHtml(suggestion.context_before)}
                                <span style="background: #fef08a; padding: 2px 4px;">${escapeHtml(suggestion.anchor)}</span>
                                ${escapeHtml(suggestion.context_after)}"
                            </div>
                            <div style="font-size: 12px; color: #64748b;">
                                Relevance: ${(suggestion.relevance_score * 100).toFixed(0)}%
                            </div>
                        </div>
                        <div style="display: flex; gap: 8px; margin-left: 16px;">
                            <button type="button" class="button wordchat-accept-link" data-index="${index}">
                                ✓ Accept
                            </button>
                            <button type="button" class="button wordchat-reject-link" data-index="${index}">
                                ✗ Reject
                            </button>
                        </div>
                    </div>
                </div>
            `;
        });

        $('#wordchat-suggestions-list').html(html);
        $('#wordchat-suggestions-panel').data('post-id', data.post_id);
        $('#wordchat-suggestions-panel').data('suggestions', suggestions);
        $('#wordchat-suggestions-panel').fadeIn();

        // Scroll to suggestions
        $('html, body').animate({
            scrollTop: $('#wordchat-suggestions-panel').offset().top - 100
        }, 500);
    }

    // Handle accept/reject link suggestions
    $(document).on('click', '.wordchat-accept-link', function() {
        const $suggestion = $(this).closest('.wordchat-link-suggestion');
        $suggestion.addClass('accepted').removeClass('rejected');
        $(this).prop('disabled', true);
        $suggestion.find('.wordchat-reject-link').prop('disabled', false);
        updateApplyButton();
    });

    $(document).on('click', '.wordchat-reject-link', function() {
        const $suggestion = $(this).closest('.wordchat-link-suggestion');
        $suggestion.addClass('rejected').removeClass('accepted');
        $(this).prop('disabled', true);
        $suggestion.find('.wordchat-accept-link').prop('disabled', false);
        updateApplyButton();
    });

    function updateApplyButton() {
        const acceptedCount = $('.wordchat-link-suggestion.accepted').length;
        const $applyBtn = $('#wordchat-apply-links');

        if (acceptedCount > 0) {
            $applyBtn.prop('disabled', false).html(
                `<span class="dashicons dashicons-yes-alt" style="margin-top: 3px;"></span> Apply ${acceptedCount} Selected Link${acceptedCount > 1 ? 's' : ''}`
            );
        } else {
            $applyBtn.prop('disabled', true).html(
                '<span class="dashicons dashicons-yes-alt" style="margin-top: 3px;"></span> Apply Selected Links'
            );
        }
    }

    // Apply selected links
    $('#wordchat-apply-links').on('click', function() {
        const postId = $('#wordchat-suggestions-panel').data('post-id');
        const allSuggestions = $('#wordchat-suggestions-panel').data('suggestions');
        const acceptedIndices = [];

        $('.wordchat-link-suggestion.accepted').each(function() {
            acceptedIndices.push($(this).data('index'));
        });

        if (acceptedIndices.length === 0) {
            return;
        }

        if (!confirm(`Apply ${acceptedIndices.length} internal link${acceptedIndices.length > 1 ? 's' : ''} to this post?`)) {
            return;
        }

        const $btn = $(this);
        const $status = $('#wordchat-apply-status');

        $btn.prop('disabled', true);
        $status.html('<span class="wordchat-loading"><span class="spinner"></span> Applying links...</span>');

        $.ajax({
            url: WordChatVars.ajax_url,
            type: 'POST',
            data: {
                action: 'wordchat_apply_links',
                nonce: WordChatVars.nonce,
                post_id: postId,
                accepted_indices: acceptedIndices
            },
            success: function(response) {
                if (response.success) {
                    $status.html('<span style="color: #22c55e;">✓ Links applied successfully!</span>');
                    alert('Links have been applied to the post. You can view the updated post now.');

                    // Optionally redirect to edit page
                    if (confirm('Open the post for review?')) {
                        window.location.href = response.data.edit_url;
                    } else {
                        // Reset form
                        $('#wordchat-suggestions-panel').hide();
                        $('#wordchat-select-post').val('');
                    }
                } else {
                    alert('Error: ' + (response.data || 'Failed to apply links'));
                    $status.html('<span style="color: #ef4444;">✗ Failed</span>');
                }
            },
            error: function() {
                alert('Network error. Please try again.');
                $status.html('<span style="color: #ef4444;">✗ Network error</span>');
            },
            complete: function() {
                $btn.prop('disabled', false);
            }
        });
    });

    // =====================================================
    // CONTENT EDITING
    // =====================================================

    $('#wordchat-edit-form').on('submit', function(e) {
        e.preventDefault();

        const postId = $('#wordchat-edit-post').val();
        const instructions = $('#wordchat-edit-instructions').val().trim();

        if (!postId || !instructions) {
            alert('Please select a post and provide editing instructions');
            return;
        }

        const $submitBtn = $(this).find('button[type="submit"]');
        const $status = $('#wordchat-edit-status');

        $submitBtn.prop('disabled', true);
        $status.html('<span class="wordchat-loading"><span class="spinner"></span> Editing content...</span>');
        $('#wordchat-edit-results').hide();

        $.ajax({
            url: WordChatVars.ajax_url,
            type: 'POST',
            data: {
                action: 'wordchat_edit_content',
                nonce: WordChatVars.nonce,
                post_id: postId,
                instructions: instructions
            },
            success: function(response) {
                if (response.success) {
                    displayEditedContent(response.data);
                    $status.html('<span style="color: #22c55e;">✓ Content edited successfully!</span>');
                } else {
                    alert('Error: ' + (response.data || 'Failed to edit content'));
                    $status.html('<span style="color: #ef4444;">✗ Edit failed</span>');
                }
            },
            error: function() {
                alert('Network error. Please try again.');
                $status.html('<span style="color: #ef4444;">✗ Network error</span>');
            },
            complete: function() {
                $submitBtn.prop('disabled', false);
            }
        });
    });

    function displayEditedContent(data) {
        $('#wordchat-changes-summary').html(`
            <strong>✨ Changes Applied:</strong><br>
            ${escapeHtml(data.changes_summary)}
        `);

        const contentHtml = markdownToHtml(data.edited_content);
        $('#wordchat-edited-preview').html(contentHtml);

        $('#wordchat-edit-results').data('post-id', data.post_id);
        $('#wordchat-edit-results').data('edited-content', data.edited_content);

        $('#wordchat-edit-results').fadeIn();

        // Scroll to results
        $('html, body').animate({
            scrollTop: $('#wordchat-edit-results').offset().top - 100
        }, 500);
    }

    // Update post with edited content
    $('#wordchat-update-post').on('click', function() {
        if (!confirm('Update this post with the edited content?')) {
            return;
        }

        const postId = $('#wordchat-edit-results').data('post-id');
        const editedContent = $('#wordchat-edit-results').data('edited-content');

        const $btn = $(this);
        $btn.prop('disabled', true).text('Updating...');

        $.ajax({
            url: WordChatVars.ajax_url,
            type: 'POST',
            data: {
                action: 'wordchat_update_post_content',
                nonce: WordChatVars.nonce,
                post_id: postId,
                content: editedContent
            },
            success: function(response) {
                if (response.success) {
                    alert('Post updated successfully!');
                    if (confirm('Open the post for review?')) {
                        window.location.href = response.data.edit_url;
                    } else {
                        $('#wordchat-edit-results').hide();
                        $('#wordchat-edit-post').val('');
                        $('#wordchat-edit-instructions').val('');
                    }
                } else {
                    alert('Error: ' + (response.data || 'Failed to update post'));
                }
            },
            error: function() {
                alert('Network error. Please try again.');
            },
            complete: function() {
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt" style="margin-top: 3px;"></span> Update Post');
            }
        });
    });

    // Discard edits
    $('#wordchat-discard-edits').on('click', function() {
        if (confirm('Discard these edits?')) {
            $('#wordchat-edit-results').hide();
        }
    });

    // =====================================================
    // HELPER FUNCTIONS
    // =====================================================

    function markdownToHtml(markdown) {
        // Simple markdown conversion (you may want to use a library like marked.js)
        let html = markdown;

        // Headers
        html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>');
        html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>');
        html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>');

        // Bold
        html = html.replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>');

        // Italic
        html = html.replace(/\*(.*?)\*/gim, '<em>$1</em>');

        // Links
        html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/gim, '<a href="$2">$1</a>');

        // Line breaks
        html = html.replace(/\n\n/g, '</p><p>');
        html = '<p>' + html + '</p>';

        return html;
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

})(jQuery);
