<?php
/**
 * AI Content Writer & Editor
 *
 * Handles content generation, link suggestions, and content editing
 * using AI powered by the WordChat backend
 *
 * @package WordChat
 * @since 0.2.0
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Render Content Writer tab
 */
function wordchat_render_content_writer_tab() {
    $site_id = get_option('wordchat_site_id');
    $api_key = get_option('wordchat_api_key');
    $is_paid = get_option('wordchat_is_paid') === '1';

    // Get usage stats
    $usage_stats = wordchat_get_content_writer_usage();

    ?>
    <div class="wordchat-content-writer-wrapper">
        <!-- Usage Stats Banner -->
        <div class="wordchat-usage-banner" style="background: #f0f6ff; border: 1px solid #3b82f6; border-radius: 8px; padding: 16px; margin-bottom: 24px;">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <h3 style="margin: 0 0 8px 0; color: #1e40af;">
                        <?php echo $is_paid ? '✨ Pro Plan' : '📝 Free Plan'; ?>
                    </h3>
                    <p style="margin: 0; color: #475569;">
                        <?php if ($is_paid): ?>
                            Unlimited content generation and link suggestions
                        <?php else: ?>
                            <?php echo esc_html($usage_stats['generations_remaining']); ?> generations,
                            <?php echo esc_html($usage_stats['links_remaining']); ?> link suggestions remaining this month
                        <?php endif; ?>
                    </p>
                </div>
                <?php if (!$is_paid): ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=wordchat-pro&tab=license')); ?>"
                       class="button button-primary">
                        Upgrade to Pro
                    </a>
                <?php endif; ?>
            </div>
        </div>

        <!-- Tabs Navigation -->
        <div class="wordchat-writer-tabs" style="margin-bottom: 24px;">
            <button class="wordchat-tab-button active" data-tab="generate">
                📝 Generate Content
            </button>
            <button class="wordchat-tab-button" data-tab="suggest-links">
                🔗 Suggest Links
            </button>
            <button class="wordchat-tab-button" data-tab="edit-content">
                ✏️ Edit Content
            </button>
        </div>

        <!-- Tab 1: Generate Content -->
        <div id="wordchat-tab-generate" class="wordchat-tab-content active">
            <?php wordchat_render_generate_content_tab(); ?>
        </div>

        <!-- Tab 2: Suggest Links -->
        <div id="wordchat-tab-suggest-links" class="wordchat-tab-content" style="display: none;">
            <?php wordchat_render_suggest_links_tab(); ?>
        </div>

        <!-- Tab 3: Edit Content -->
        <div id="wordchat-tab-edit-content" class="wordchat-tab-content" style="display: none;">
            <?php wordchat_render_edit_content_tab(); ?>
        </div>
    </div>

    <style>
        .wordchat-writer-tabs {
            display: flex;
            gap: 8px;
            border-bottom: 2px solid #e2e8f0;
        }
        .wordchat-tab-button {
            background: none;
            border: none;
            padding: 12px 24px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            color: #64748b;
            border-bottom: 3px solid transparent;
            transition: all 0.2s;
        }
        .wordchat-tab-button:hover {
            color: #1e40af;
            background: #f8fafc;
        }
        .wordchat-tab-button.active {
            color: #1e40af;
            border-bottom-color: #3b82f6;
        }
        .wordchat-card {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 24px;
            margin-bottom: 16px;
        }
        .wordchat-input-group {
            margin-bottom: 20px;
        }
        .wordchat-input-group label {
            display: block;
            font-weight: 600;
            margin-bottom: 8px;
            color: #1e293b;
        }
        .wordchat-input-group input[type="text"],
        .wordchat-input-group textarea,
        .wordchat-input-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #cbd5e1;
            border-radius: 6px;
            font-size: 14px;
        }
        .wordchat-input-group textarea {
            min-height: 120px;
            resize: vertical;
        }
        .wordchat-preview {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 20px;
            max-height: 600px;
            overflow-y: auto;
        }
        .wordchat-preview h1, .wordchat-preview h2, .wordchat-preview h3 {
            margin-top: 1.5em;
            margin-bottom: 0.5em;
        }
        .wordchat-preview p {
            line-height: 1.6;
            margin-bottom: 1em;
        }
        .wordchat-loading {
            text-align: center;
            padding: 40px;
            color: #64748b;
        }
        .wordchat-loading .spinner {
            display: inline-block;
            width: 40px;
            height: 40px;
            border: 4px solid #e2e8f0;
            border-top-color: #3b82f6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .wordchat-link-suggestion {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            padding: 16px;
            margin-bottom: 12px;
            transition: border-color 0.2s;
        }
        .wordchat-link-suggestion:hover {
            border-color: #3b82f6;
        }
        .wordchat-link-suggestion.accepted {
            background: #f0fdf4;
            border-color: #22c55e;
        }
        .wordchat-link-suggestion.rejected {
            background: #fef2f2;
            border-color: #ef4444;
            opacity: 0.6;
        }
    </style>
    <?php
}

/**
 * Render Generate Content tab
 */
function wordchat_render_generate_content_tab() {
    ?>
    <div class="wordchat-card">
        <h2 style="margin-top: 0;"><?php echo esc_html__('Generate New Content', 'wordchat-pro'); ?></h2>

        <form id="wordchat-generate-form">
            <div class="wordchat-input-group">
                <label for="wordchat-topic">
                    <?php echo esc_html__('Topic or Keyword', 'wordchat-pro'); ?> <span style="color: #ef4444;">*</span>
                </label>
                <input type="text"
                       id="wordchat-topic"
                       name="topic"
                       placeholder="e.g., WordPress Security Best Practices"
                       required>
                <p class="description">
                    <?php echo esc_html__('Enter the main topic or keyword for your blog post', 'wordchat-pro'); ?>
                </p>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                <div class="wordchat-input-group">
                    <label for="wordchat-tone">
                        <?php echo esc_html__('Writing Tone', 'wordchat-pro'); ?>
                    </label>
                    <select id="wordchat-tone" name="tone">
                        <option value="professional"><?php echo esc_html__('Professional', 'wordchat-pro'); ?></option>
                        <option value="casual"><?php echo esc_html__('Casual', 'wordchat-pro'); ?></option>
                        <option value="technical"><?php echo esc_html__('Technical', 'wordchat-pro'); ?></option>
                        <option value="friendly"><?php echo esc_html__('Friendly', 'wordchat-pro'); ?></option>
                    </select>
                </div>

                <div class="wordchat-input-group">
                    <label for="wordchat-word-count">
                        <?php echo esc_html__('Target Word Count', 'wordchat-pro'); ?>
                    </label>
                    <input type="number"
                           id="wordchat-word-count"
                           name="word_count"
                           value="1000"
                           min="300"
                           max="3000"
                           step="100">
                </div>
            </div>

            <div class="wordchat-input-group">
                <label for="wordchat-related-posts">
                    <?php echo esc_html__('Related Posts (Optional)', 'wordchat-pro'); ?>
                </label>
                <select id="wordchat-related-posts" name="related_posts[]" multiple style="height: 120px;">
                    <?php
                    $posts = get_posts([
                        'post_type' => ['post', 'page'],
                        'post_status' => 'publish',
                        'numberposts' => 50,
                        'orderby' => 'date',
                        'order' => 'DESC'
                    ]);
                    foreach ($posts as $post):
                    ?>
                        <option value="<?php echo esc_url(get_permalink($post)); ?>">
                            <?php echo esc_html($post->post_title); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <p class="description">
                    <?php echo esc_html__('Hold Ctrl/Cmd to select multiple posts. AI will reference these for context.', 'wordchat-pro'); ?>
                </p>
            </div>

            <div style="display: flex; gap: 12px; align-items: center;">
                <button type="submit" class="button button-primary button-large">
                    <span class="dashicons dashicons-edit" style="margin-top: 3px;"></span>
                    <?php echo esc_html__('Generate Content', 'wordchat-pro'); ?>
                </button>
                <div id="wordchat-generate-status" style="color: #64748b;"></div>
            </div>
        </form>
    </div>

    <!-- Preview Panel -->
    <div id="wordchat-preview-panel" style="display: none;">
        <div class="wordchat-card">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                <h2 style="margin: 0;"><?php echo esc_html__('Generated Content', 'wordchat-pro'); ?></h2>
                <div style="display: flex; gap: 8px;">
                    <button type="button" id="wordchat-copy-content" class="button">
                        <span class="dashicons dashicons-clipboard"></span>
                        <?php echo esc_html__('Copy to Clipboard', 'wordchat-pro'); ?>
                    </button>
                    <button type="button" id="wordchat-save-draft" class="button button-primary">
                        <span class="dashicons dashicons-yes-alt"></span>
                        <?php echo esc_html__('Save as Draft', 'wordchat-pro'); ?>
                    </button>
                </div>
            </div>

            <div id="wordchat-generation-meta" style="background: #f0f6ff; padding: 16px; border-radius: 6px; margin-bottom: 16px;">
                <!-- Generation metadata will be inserted here -->
            </div>

            <div id="wordchat-preview-content" class="wordchat-preview">
                <!-- Generated content will be inserted here -->
            </div>
        </div>
    </div>
    <?php
}

/**
 * Render Suggest Links tab
 */
function wordchat_render_suggest_links_tab() {
    ?>
    <div class="wordchat-card">
        <h2 style="margin-top: 0;"><?php echo esc_html__('Suggest Internal Links', 'wordchat-pro'); ?></h2>

        <form id="wordchat-suggest-links-form">
            <div class="wordchat-input-group">
                <label for="wordchat-select-post">
                    <?php echo esc_html__('Select Post/Page', 'wordchat-pro'); ?> <span style="color: #ef4444;">*</span>
                </label>
                <select id="wordchat-select-post" name="post_id" required style="max-width: 600px;">
                    <option value=""><?php echo esc_html__('-- Select a post --', 'wordchat-pro'); ?></option>
                    <?php
                    $posts = get_posts([
                        'post_type' => ['post', 'page'],
                        'post_status' => 'publish',
                        'numberposts' => 100,
                        'orderby' => 'date',
                        'order' => 'DESC'
                    ]);
                    foreach ($posts as $post):
                    ?>
                        <option value="<?php echo esc_attr($post->ID); ?>">
                            <?php echo esc_html($post->post_title); ?>
                            (<?php echo esc_html($post->post_type); ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div style="display: flex; gap: 12px; align-items: center;">
                <button type="submit" class="button button-primary button-large">
                    <span class="dashicons dashicons-admin-links" style="margin-top: 3px;"></span>
                    <?php echo esc_html__('Find Link Opportunities', 'wordchat-pro'); ?>
                </button>
                <div id="wordchat-suggest-status" style="color: #64748b;"></div>
            </div>
        </form>
    </div>

    <!-- Suggestions Panel -->
    <div id="wordchat-suggestions-panel" style="display: none;">
        <div class="wordchat-card">
            <h2><?php echo esc_html__('Link Suggestions', 'wordchat-pro'); ?></h2>
            <p class="description">
                <?php echo esc_html__('Review and accept/reject suggested internal links. Accepted links will be highlighted in context.', 'wordchat-pro'); ?>
            </p>

            <div id="wordchat-suggestions-list">
                <!-- Suggestions will be inserted here -->
            </div>

            <div style="margin-top: 24px; padding-top: 24px; border-top: 1px solid #e2e8f0;">
                <button type="button" id="wordchat-apply-links" class="button button-primary button-large" disabled>
                    <span class="dashicons dashicons-yes-alt" style="margin-top: 3px;"></span>
                    <?php echo esc_html__('Apply Selected Links', 'wordchat-pro'); ?>
                </button>
                <span id="wordchat-apply-status" style="margin-left: 12px; color: #64748b;"></span>
            </div>
        </div>
    </div>
    <?php
}

/**
 * Render Edit Content tab
 */
function wordchat_render_edit_content_tab() {
    ?>
    <div class="wordchat-card">
        <h2 style="margin-top: 0;"><?php echo esc_html__('AI Content Editor', 'wordchat-pro'); ?></h2>

        <p class="description" style="margin-bottom: 20px;">
            <?php echo esc_html__('Select a post and provide editing instructions. AI will improve the content while preserving your voice.', 'wordchat-pro'); ?>
        </p>

        <form id="wordchat-edit-form">
            <div class="wordchat-input-group">
                <label for="wordchat-edit-post">
                    <?php echo esc_html__('Select Post/Page', 'wordchat-pro'); ?> <span style="color: #ef4444;">*</span>
                </label>
                <select id="wordchat-edit-post" name="post_id" required style="max-width: 600px;">
                    <option value=""><?php echo esc_html__('-- Select a post --', 'wordchat-pro'); ?></option>
                    <?php
                    $posts = get_posts([
                        'post_type' => ['post', 'page'],
                        'post_status' => ['publish', 'draft'],
                        'numberposts' => 100,
                        'orderby' => 'date',
                        'order' => 'DESC'
                    ]);
                    foreach ($posts as $post):
                    ?>
                        <option value="<?php echo esc_attr($post->ID); ?>">
                            <?php echo esc_html($post->post_title); ?>
                            (<?php echo esc_html($post->post_status); ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="wordchat-input-group">
                <label for="wordchat-edit-instructions">
                    <?php echo esc_html__('Editing Instructions', 'wordchat-pro'); ?> <span style="color: #ef4444;">*</span>
                </label>
                <textarea id="wordchat-edit-instructions"
                          name="instructions"
                          placeholder="e.g., Improve readability, add internal links, fix grammar"
                          required></textarea>
                <p class="description">
                    <?php echo esc_html__('Be specific about what you want changed (e.g., "add internal links", "improve SEO", "make more conversational")', 'wordchat-pro'); ?>
                </p>
            </div>

            <div style="display: flex; gap: 12px; align-items: center;">
                <button type="submit" class="button button-primary button-large">
                    <span class="dashicons dashicons-edit" style="margin-top: 3px;"></span>
                    <?php echo esc_html__('Apply AI Edits', 'wordchat-pro'); ?>
                </button>
                <div id="wordchat-edit-status" style="color: #64748b;"></div>
            </div>
        </form>
    </div>

    <!-- Edit Results Panel -->
    <div id="wordchat-edit-results" style="display: none;">
        <div class="wordchat-card">
            <h2><?php echo esc_html__('Edited Content', 'wordchat-pro'); ?></h2>

            <div id="wordchat-changes-summary" style="background: #f0fdf4; border: 1px solid #22c55e; border-radius: 6px; padding: 16px; margin-bottom: 16px;">
                <!-- Changes summary will be inserted here -->
            </div>

            <div id="wordchat-edited-preview" class="wordchat-preview">
                <!-- Edited content will be inserted here -->
            </div>

            <div style="margin-top: 24px;">
                <button type="button" id="wordchat-update-post" class="button button-primary button-large">
                    <span class="dashicons dashicons-yes-alt" style="margin-top: 3px;"></span>
                    <?php echo esc_html__('Update Post', 'wordchat-pro'); ?>
                </button>
                <button type="button" id="wordchat-discard-edits" class="button">
                    <?php echo esc_html__('Discard Changes', 'wordchat-pro'); ?>
                </button>
            </div>
        </div>
    </div>
    <?php
}

/**
 * Get content writer usage stats
 */
function wordchat_get_content_writer_usage() {
    $site_id = get_option('wordchat_site_id');
    $is_paid = get_option('wordchat_is_paid') === '1';

    if ($is_paid) {
        return [
            'generations_used' => 0,
            'generations_limit' => -1, // Unlimited
            'generations_remaining' => 'Unlimited',
            'links_used' => 0,
            'links_limit' => -1,
            'links_remaining' => 'Unlimited'
        ];
    }

    // For free users, we'd query the backend, but for now return defaults
    // This would be populated via AJAX on page load
    return [
        'generations_used' => 0,
        'generations_limit' => 5,
        'generations_remaining' => 5,
        'links_used' => 0,
        'links_limit' => 10,
        'links_remaining' => 10
    ];
}
