<?php
/**
 * Editor Chat Functionality
 *
 * This file contains functionality for the chat component in the WordPress Block Editor.
 *
 * @package Simple_Ai_Auto_Post
 * @since 1.1.3
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

// Make sure this file is being included by a parent file.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Get basic site context for the editor chat
 *
 * Returns a brief summary of the site to help the AI understand the context.
 *
 * @return string The site context string
 */
function saiap_get_editor_chat_site_context() {
	$context_parts = array();

	// Basic WordPress site info
	$site_name        = get_bloginfo( 'name' );
	$site_description = get_bloginfo( 'description' );
	$site_url         = wp_parse_url( home_url(), PHP_URL_HOST );

	if ( ! empty( $site_name ) ) {
		$context_parts[] = 'Site name: ' . $site_name;
	}
	if ( ! empty( $site_url ) ) {
		$context_parts[] = 'Domain: ' . $site_url;
	}
	if ( ! empty( $site_description ) ) {
		$context_parts[] = 'Site tagline: ' . $site_description;
	}

	// Get cached site context if available (from Site Context feature)
	$cached_context = get_option( 'saiap_context_cache', null );
	if ( is_array( $cached_context ) && ! empty( $cached_context ) ) {
		if ( ! empty( $cached_context['summary'] ) ) {
			// Truncate summary to keep it concise (first 500 chars)
			$summary = wp_strip_all_tags( $cached_context['summary'] );
			if ( strlen( $summary ) > 500 ) {
				$summary = substr( $summary, 0, 500 ) . '...';
			}
			$context_parts[] = 'Site summary: ' . $summary;
		}
		if ( ! empty( $cached_context['topics'] ) && is_array( $cached_context['topics'] ) ) {
			// Limit to first 10 topics
			$topics          = array_slice( $cached_context['topics'], 0, 10 );
			$context_parts[] = 'Key topics: ' . implode( ', ', $topics );
		}
		if ( ! empty( $cached_context['style_guide'] ) ) {
			// Truncate style guide to keep it concise (first 300 chars)
			$style = wp_strip_all_tags( $cached_context['style_guide'] );
			if ( strlen( $style ) > 300 ) {
				$style = substr( $style, 0, 300 ) . '...';
			}
			$context_parts[] = 'Writing style: ' . $style;
		}
	}

	if ( empty( $context_parts ) ) {
		return '';
	}

	return implode( "\n", $context_parts );
}

/**
 * Get model for the specified provider
 *
 * @param string $provider The AI provider ('openai', 'anthropic', 'gemini')
 * @return string The model name
 */
function saiap_get_model_for_provider( $provider = '' ) {
	if ( empty( $provider ) ) {
		$provider = get_option( 'saiap_default_provider', 'openai' );
	}

	switch ( $provider ) {
		case 'anthropic':
			return get_option( 'saiap_anthropic_model', 'claude-opus-4-5' );
		case 'gemini':
			return get_option( 'saiap_gemini_model', 'gemini-3-pro-preview' );
		case 'openai':
		default:
			return get_option( 'saiap_openai_model', 'gpt-5.4' );
	}
}

/**
 * Edit post content using AI
 *
 * @param string $message The user's editing request
 * @param string $current_content The current post content
 * @param string $model The AI model to use
 * @param string $provider The AI provider
 * @param array  $history Optional conversation history array of {role, content} objects
 * @return array|WP_Error The AI response or error
 */
function saiap_edit_post_content( $message, $current_content, $model = '', $provider = '', $history = array() ) {
	// Validate input
	if ( empty( $message ) ) {
		return new WP_Error( 'empty_message', 'Message cannot be empty.' );
	}

	// Set defaults
	if ( empty( $provider ) ) {
		$provider = get_option( 'saiap_default_provider', 'openai' );
	}
	if ( empty( $model ) ) {
		$model = saiap_get_model_for_provider( $provider );
	}

    // Premium-first: If license key exists, try premium chat endpoint before local provider
    // Check both regular license and trial license key
    $license_key = get_option( 'saiap_license_key', '' );
    if ( empty( $license_key ) ) {
        $license_key = get_option( 'saiap_trial_license_key', '' );
    }

    // Get site context for better AI understanding
	$site_context = saiap_get_editor_chat_site_context();

    // Create editing-specific system prompt
	$editing_system_prompt = "You are a friendly and helpful AI assistant and content editor for WordPress. Your goal is to help the user write and improve their blog post. You can perform edits, answer questions about the content, or just chat about the post.

**Interaction Flow:**

1.  **Analyze the User's Request:** Carefully determine the user's intent. Are they asking for a specific edit, asking a question, or making a general comment?

2.  **Handling Edits:**
    *   If the user asks for an edit, apply it precisely to the provided content.
    *   Maintain the original Gutenberg formatting, links, and media references.
    *   If an edit is made, set `has_edit` to `true` and include the full, modified content in `edited_content`. Your `chat_message` should explain the change.

3.  **Handling Questions & Conversation:**
    *   If the user asks a question about the content (e.g., \"What's a good title for this?\", \"Is the tone right?\"), provide a thoughtful and helpful answer in `chat_message`.
    *   If the user makes a general comment or starts a conversation (e.g., \"hey there\", \"what do you think of this so far?\"), respond conversationally in `chat_message`.
    *   For non-edit interactions, set `has_edit` to `false` and return an empty string for `edited_content`.

4.  **Clarification:**
    *   If a request is ambiguous, ask for clarification. For example, if a user says \"make it better\", you can ask \"What specific aspects would you like to improve? For example, the tone, clarity, or maybe adding a conclusion?\"

**Response Format:**

You must respond in this EXACT JSON format.

*Example for an edit:*
{
	\"chat_message\": \"I've updated the first paragraph to be more engaging.\",
	\"has_edit\": true,
	\"edited_content\": \"The complete edited content with changes applied\"
}

*Example for a conversation (no edit):*
{
	\"chat_message\": \"That's a great start! The introduction is strong. What would you like to work on next?\",
	\"has_edit\": false,
	\"edited_content\": \"\"
}


**Important Guidelines:**
-   Always be friendly and collaborative.
-   When editing, preserve the tone unless asked to change it.
-   When `has_edit` is `true`, `edited_content` must contain the ENTIRE post content with the changes, not just the changed parts.
-   If no edit is made, `edited_content` MUST be an empty string.

**Internal Linking (when tools available):**
-   You may have access to tools to search for existing posts on this site.
-   If asked to add internal links, use those tools to find relevant posts.
-   Add 2-4 contextually relevant internal links where appropriate.
-   Only use permalinks returned by the tools - never invent URLs.
-   If no relevant posts are found, proceed without internal links.
" . ( ! empty( $site_context ) ? "
**About this site:**
" . $site_context . "
" : '' ) . "
Current content to work with:
" . $current_content;

    // Prepare the user message
	$user_message = "My request is: " . $message;

	// Build messages array with history (cap at 20 turns to avoid token limits)
	$max_history_items = 40; // 20 turns = 40 messages (user + assistant each)
	$trimmed_history   = array_slice( $history, -$max_history_items );

    // Attempt premium call if license is present (uses async endpoint, returns job_id)
    if ( ! empty( $license_key ) ) {
        $domain   = function_exists( 'saiap_get_server_host' ) ? saiap_get_server_host() : wp_parse_url( home_url(), PHP_URL_HOST );
        $messages = array(
            array( 'role' => 'system', 'content' => $editing_system_prompt ),
        );
        // Add conversation history
        foreach ( $trimmed_history as $hist_msg ) {
            $messages[] = array( 'role' => $hist_msg['role'], 'content' => $hist_msg['content'] );
        }
        // Add current user message
        $messages[] = array( 'role' => 'user', 'content' => $user_message );

        // Use async endpoint - returns job_id immediately
        $premium_response = wp_remote_post(
            SAIAP_PREMIUM_API_URL . '/api/chat/edit/async',
            array(
                'headers' => array(
                    'Content-Type' => 'application/json',
                ),
                'body'    => wp_json_encode(
                    array(
                        'license_key' => $license_key,
                        'domain'      => $domain,
                        'provider'    => $provider,
                        'model'       => $model,
                        'messages'    => $messages,
                        'post_id'     => $post_id,
                    )
                ),
                'timeout' => 10, // Short timeout - just starting the job
            )
        );

        if ( is_wp_error( $premium_response ) ) {
            // Network or request error — surface as request failure (no fallback)
            return new WP_Error( 'api_request_failed', esc_html( $premium_response->get_error_message() ) );
        }

        $status_code = wp_remote_retrieve_response_code( $premium_response );
        $body        = wp_remote_retrieve_body( $premium_response );

        if ( $status_code === 401 || $status_code === 403 ) {
            // Auth error — fall back to local provider if possible
        } elseif ( $status_code === 202 ) {
            // 202 Accepted — job started, return job_id to frontend for polling
            $data = json_decode( $body, true );
            if ( isset( $data['job_id'] ) ) {
                return array(
                    'async'  => true,
                    'job_id' => sanitize_text_field( $data['job_id'] ),
                );
            }
            return new WP_Error( 'invalid_response', 'Missing job_id from async response' );
        } elseif ( $status_code !== 200 ) {
            // Other server/provider error — surface without fallback
            $data = json_decode( $body, true );
            $msg  = isset( $data['error'] ) ? sanitize_text_field( $data['error'] ) : 'Premium service error';
            return new WP_Error( 'api_error', $msg );
        } else {
            // 200 OK — parse structured response (shouldn't happen with async, but handle it)
            $data = json_decode( $body, true );
            if ( isset( $data['chat_message'] ) && isset( $data['edited_content'] ) && isset( $data['has_edit'] ) ) {
                return array(
                    'chat_message'   => sanitize_textarea_field( $data['chat_message'] ),
                    'has_edit'       => (bool) $data['has_edit'],
                    'edited_content' => wp_kses_post( $data['edited_content'] ),
                );
            }

            // Invalid structured response
            return new WP_Error( 'invalid_response', 'Invalid response from premium chat API' );
        }
    }

    // Fallback to local provider flow (or primary when no license)
    // Get API key for the provider
    $api_key_option = 'saiap_' . $provider . '_api_key';
    $api_key = get_option( $api_key_option );

    if ( empty( $api_key ) ) {
        return new WP_Error( 'missing_api_key', 'API key not configured for ' . $provider );
    }

    // Build user message with conversation history for local provider
    $local_user_message = $user_message;
    if ( ! empty( $trimmed_history ) ) {
        $history_text = "Previous conversation:\n";
        foreach ( $trimmed_history as $hist_msg ) {
            $role_label    = $hist_msg['role'] === 'user' ? 'User' : 'Assistant';
            $history_text .= $role_label . ': ' . $hist_msg['content'] . "\n";
        }
        $local_user_message = $history_text . "\nCurrent request:\n" . $user_message;
    }

    // Make AI request based on provider
    try {
        $result = saiap_make_ai_request( $local_user_message, $provider, $model, $editing_system_prompt );

        if ( is_wp_error( $result ) ) {
            return $result;
        }

        // Parse the JSON response
        $parsed_response = json_decode( $result, true );

        // Check if the response is valid and contains the required fields
        if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $parsed_response ) || ! isset( $parsed_response['chat_message'] ) || ! isset( $parsed_response['edited_content'] ) ) {
            // If not, treat the entire response as a chat message and assume no edit was made.
            // This prevents overwriting content with an error or non-content response.
            return array(
                'chat_message'   => $result, // The raw response from the AI.
                'has_edit'       => false,
                'edited_content' => '', // No changes to the content.
            );
        }

        // Sanitize the response
        $response = array(
            'chat_message' => sanitize_textarea_field( $parsed_response['chat_message'] ),
            'has_edit'     => isset( $parsed_response['has_edit'] ) ? (bool) $parsed_response['has_edit'] : true,
            'edited_content' => wp_kses_post( $parsed_response['edited_content'] ),
        );

        return $response;

    } catch ( Exception $e ) {
        return new WP_Error( 'api_request_failed', 'Failed to communicate with AI service: ' . $e->getMessage() );
    }
}

/**
 * Enqueue editor chat assets
 */
function saiap_enqueue_editor_chat_assets() {
	global $pagenow;

	// Only load in the block editor
	if ( ! ( $pagenow === 'post.php' || $pagenow === 'post-new.php' ) ) {
		return;
	}

	// Check if we're in the block editor
	if ( ! function_exists( 'use_block_editor_for_post' ) ) {
		return;
	}

	$post_id = 0;
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only access to current editor screen context
	if ( isset( $_GET['post'] ) ) {
		$post_id = intval( $_GET['post'] );
	}

	// For new posts, use_block_editor_for_post needs a post type
	$post_type = 'post';
	if ( $post_id > 0 ) {
		$post = get_post( $post_id );
		if ( $post ) {
			$post_type = $post->post_type;
		}
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only post_type detection in editor context
	} elseif ( isset( $_GET['post_type'] ) ) {
		$post_type = sanitize_text_field( wp_unslash( $_GET['post_type'] ) );
	}

	// Only load for block editor
	if ( ! use_block_editor_for_post_type( $post_type ) ) {
		return;
	}

	// Enqueue the bundled React component
	$bundle_version = file_exists( plugin_dir_path( __FILE__ ) . '../assets/js/dist/editor-chat.bundle.js' ) ?
		filemtime( plugin_dir_path( __FILE__ ) . '../assets/js/dist/editor-chat.bundle.js' ) . '-' . wp_rand() : SAIAP_VERSION;

	wp_enqueue_script(
		'saiap-editor-chat',
		plugin_dir_url( __FILE__ ) . '../assets/js/dist/editor-chat.bundle.js',
		array( 'wp-element', 'wp-data', 'wp-editor', 'wp-plugins', 'wp-components', 'jquery' ),
		$bundle_version,
		true
	);

	// Enqueue styles
	$css_version = file_exists( plugin_dir_path( __FILE__ ) . '../assets/css/editor-chat.css' ) ?
		filemtime( plugin_dir_path( __FILE__ ) . '../assets/css/editor-chat.css' ) . '-' . wp_rand() : SAIAP_VERSION;

	wp_enqueue_style(
		'saiap-editor-chat',
		plugin_dir_url( __FILE__ ) . '../assets/css/editor-chat.css',
		array( 'wp-edit-blocks' ),
		$css_version
	);

	// Get mock chat history for screenshots/demos if available
	$chat_history     = get_option( 'saiap_editor_chat_history', array() );
	$initial_messages = array();
	if ( isset( $chat_history[ $post_id ] ) && is_array( $chat_history[ $post_id ] ) ) {
		// Convert stored format to UI format
		foreach ( $chat_history[ $post_id ] as $msg ) {
			$initial_messages[] = array(
				'message'   => $msg['content'],
				'sentTime'  => 'just now',
				'sender'    => 'user' === $msg['role'] ? 'You' : 'AI Assistant',
				'direction' => 'user' === $msg['role'] ? 'outgoing' : 'incoming',
			);
		}
	}

	// Localize script with AJAX data
	wp_localize_script(
		'saiap-editor-chat',
		'saiapEditorChat',
		array(
			'ajaxurl'           => admin_url( 'admin-ajax.php' ),
			'nonce'             => wp_create_nonce( 'saiap_editor_chat' ),
			'restUrl'           => esc_url_raw( get_rest_url( null, 'simple-ai-auto-post/v1' ) ),
			'restNonce'         => wp_create_nonce( 'wp_rest' ),
			'currentProvider'   => get_option( 'saiap_default_provider', 'openai' ),
			'currentModel'      => saiap_get_model_for_provider(),
			'availableModels'   => saiap_get_ai_models(),
			'postId'            => $post_id,
			'initialMessages'   => $initial_messages,
			'i18n'              => array(
				'chatTitle'          => __( 'AI Editor Assistant', 'clearpost-simple-ai-auto-post' ),
				'placeholder'        => __( 'Ask me to edit your content...', 'clearpost-simple-ai-auto-post' ),
				'sendButton'         => __( 'Send', 'clearpost-simple-ai-auto-post' ),
				'errorConnection'    => __( 'Unable to connect to AI service. Please check your internet connection.', 'clearpost-simple-ai-auto-post' ),
				'errorService'       => __( 'AI service is temporarily unavailable. Please try again.', 'clearpost-simple-ai-auto-post' ),
				'errorApiKey'        => __( 'Your API key appears to be invalid. Please check your settings.', 'clearpost-simple-ai-auto-post' ),
				'errorIncomplete'    => __( 'The response was incomplete. Please try your request again.', 'clearpost-simple-ai-auto-post' ),
				'errorEmpty'         => __( 'Please enter a message.', 'clearpost-simple-ai-auto-post' ),
				'errorGeneral'       => __( 'Something went wrong. Please try again.', 'clearpost-simple-ai-auto-post' ),
				'thinking'           => __( 'Thinking...', 'clearpost-simple-ai-auto-post' ),
				'updatingContent'    => __( 'Updating content...', 'clearpost-simple-ai-auto-post' ),
				'contentUpdated'     => __( 'Content updated successfully!', 'clearpost-simple-ai-auto-post' ),
				'toggleChat'         => __( 'Toggle AI Chat', 'clearpost-simple-ai-auto-post' ),
				'findImages'         => __( 'Find Featured Image', 'clearpost-simple-ai-auto-post' ),
				'selectImage'        => __( 'Select an image', 'clearpost-simple-ai-auto-post' ),
				'useAsFeatured'      => __( 'Use as Featured Image', 'clearpost-simple-ai-auto-post' ),
				'imageSearchError'   => __( 'Image search failed. Please try again.', 'clearpost-simple-ai-auto-post' ),
				'imageSetSuccess'    => __( 'Featured image set!', 'clearpost-simple-ai-auto-post' ),
			),
		)
	);
}
add_action( 'enqueue_block_editor_assets', 'saiap_enqueue_editor_chat_assets' );

/**
 * Handle chat message AJAX request
 */
function saiap_handle_chat_message() {
	// Verify nonce
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'saiap_editor_chat' ) ) {
		wp_send_json_error( array( 'message' => 'Security check failed.' ) );
		return;
	}

	// Check user capabilities
	if ( ! current_user_can( 'edit_posts' ) ) {
		wp_send_json_error( array( 'message' => 'Insufficient permissions.' ) );
		return;
	}

	try {
		// Get and sanitize input
		$message = isset( $_POST['message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : '';
		$content = isset( $_POST['content'] ) ? wp_kses_post( wp_unslash( $_POST['content'] ) ) : '';
		$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;

		// Validate input
		if ( empty( $message ) ) {
			wp_send_json_error( array( 'message' => 'Please enter a message.' ) );
			return;
		}

		// Get AI provider and model (use passed parameters or defaults)
		$provider = isset( $_POST['provider'] ) ? sanitize_text_field( wp_unslash( $_POST['provider'] ) ) : get_option( 'saiap_default_provider', 'openai' );
		$model = isset( $_POST['model'] ) ? sanitize_text_field( wp_unslash( $_POST['model'] ) ) : saiap_get_model_for_provider( $provider );

		// Parse conversation history from frontend
		$history = array();
		if ( isset( $_POST['history'] ) ) {
			$raw_history = json_decode( sanitize_text_field( wp_unslash( $_POST['history'] ) ), true );
			if ( is_array( $raw_history ) ) {
				foreach ( $raw_history as $item ) {
					if ( isset( $item['role'] ) && isset( $item['content'] ) ) {
						$history[] = array(
							'role'    => in_array( $item['role'], array( 'user', 'assistant' ), true ) ? $item['role'] : 'user',
							'content' => sanitize_textarea_field( $item['content'] ),
						);
					}
				}
			}
		}

		// Call the AI chat function
		$ai_response = saiap_edit_post_content( $message, $content, $model, $provider, $history );

		// Check for errors
		if ( is_wp_error( $ai_response ) ) {
			$error_code = $ai_response->get_error_code();
			$error_message = $ai_response->get_error_message();

			// Map error codes to user-friendly messages
			switch ( $error_code ) {
				case 'missing_api_key':
					$user_message = 'Your API key appears to be invalid. Please check your settings.';
					break;
				case 'api_request_failed':
					$user_message = 'Unable to connect to AI service. Please check your internet connection.';
					break;
				case 'api_error':
					$user_message = $error_message; // Use the detailed error message from the API.
					break;
				case 'invalid_response':
				case 'empty_response':
					$user_message = 'The response was incomplete. Please try your request again.';
					break;
				default:
					$user_message = 'Something went wrong. Please try again.';
					break;
			}

			wp_send_json_error( array( 
				'message' => $user_message,
				'debug' => $error_message // Include technical details for debugging
			) );
			return;
		}

		// Check if this is an async response with job_id
		if ( isset( $ai_response['async'] ) && $ai_response['async'] && isset( $ai_response['job_id'] ) ) {
			wp_send_json_success( array(
				'async'  => true,
				'job_id' => $ai_response['job_id'],
			) );
			return;
		}

		// Return success with the structured response
		wp_send_json_success( array(
			'chat_message' => $ai_response['chat_message'],
			'has_edit' => $ai_response['has_edit'],
			'edited_content' => $ai_response['edited_content']
		) );

	} catch ( Exception $e ) {
		wp_send_json_error( array( 'message' => 'Something went wrong. Please try again.' ) );
	}
}
add_action( 'wp_ajax_saiap_chat_message', 'saiap_handle_chat_message' );

/**
 * Check status of an async chat job
 */
function saiap_check_chat_status() {
	// Verify nonce
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'saiap_editor_chat' ) ) {
		wp_send_json_error( array( 'message' => 'Security check failed.' ) );
		return;
	}

	// Check user capabilities
	if ( ! current_user_can( 'edit_posts' ) ) {
		wp_send_json_error( array( 'message' => 'Insufficient permissions.' ) );
		return;
	}

	// Get job_id
	$job_id = isset( $_POST['job_id'] ) ? sanitize_text_field( wp_unslash( $_POST['job_id'] ) ) : '';
	if ( empty( $job_id ) ) {
		wp_send_json_error( array( 'message' => 'Missing job_id.' ) );
		return;
	}

	// Call the status endpoint
	$response = wp_remote_get(
		SAIAP_PREMIUM_API_URL . '/api/chat/edit/status/' . $job_id,
		array(
			'timeout' => 10,
		)
	);

	if ( is_wp_error( $response ) ) {
		wp_send_json_error( array( 'message' => 'Failed to check job status.' ) );
		return;
	}

	$status_code = wp_remote_retrieve_response_code( $response );
	$body        = wp_remote_retrieve_body( $response );
	$data        = json_decode( $body, true );

	if ( $status_code === 404 ) {
		wp_send_json_error( array( 'message' => 'Job not found or expired.' ) );
		return;
	}

	if ( ! is_array( $data ) || ! isset( $data['status'] ) ) {
		wp_send_json_error( array( 'message' => 'Invalid response from server.' ) );
		return;
	}

	// Return the status
	if ( $data['status'] === 'completed' && isset( $data['result'] ) ) {
		$chat_message   = isset( $data['result']['chat_message'] ) ? sanitize_textarea_field( $data['result']['chat_message'] ) : '';
		$has_edit        = isset( $data['result']['has_edit'] ) ? (bool) $data['result']['has_edit'] : false;
		$edited_content  = isset( $data['result']['edited_content'] ) ? wp_kses_post( $data['result']['edited_content'] ) : '';
		$featured_media  = 0;

		// Process image actions locally if present.
		$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
		if ( $post_id > 0 && ! empty( $data['result']['image_actions'] ) && is_array( $data['result']['image_actions'] ) ) {
			$post = get_post( $post_id );
			if ( $post ) {
				// Start with AI-edited content or current post content.
				$working_content = ( $has_edit && '' !== $edited_content ) ? $edited_content : $post->post_content;

				foreach ( $data['result']['image_actions'] as $action ) {
					$type      = isset( $action['type'] ) ? sanitize_text_field( $action['type'] ) : '';
					$image_url = isset( $action['image_url'] ) ? esc_url_raw( $action['image_url'] ) : '';
					$alt_text  = isset( $action['alt_text'] ) ? sanitize_text_field( $action['alt_text'] ) : '';

					if ( empty( $image_url ) ) {
						continue;
					}

					if ( 'set_feature_image' === $type ) {
						$attach_id = saiap_set_featured_image_from_url( $post_id, $image_url, $alt_text );
						if ( ! is_wp_error( $attach_id ) ) {
							$featured_media = (int) $attach_id;
						}
					} elseif ( 'insert_inline_image' === $type && ! empty( $action['after_heading'] ) ) {
						$selector = array(
							'level'      => isset( $action['after_heading']['level'] ) ? (int) $action['after_heading']['level'] : 2,
							'occurrence' => isset( $action['after_heading']['occurrence'] ) ? (int) $action['after_heading']['occurrence'] : 1,
						);
						$position = ( isset( $action['position'] ) && 'after_first_paragraph' === $action['position'] )
							? 'after_first_paragraph_in_section'
							: 'after_heading';

						$attach_id = saiap_create_image_attachment_from_url( $post_id, $image_url, $alt_text );
						if ( ! is_wp_error( $attach_id ) ) {
							$block_html = saiap_build_core_image_block_html( $attach_id, $alt_text, 'large' );
							if ( '' !== $block_html ) {
								$new_content = saiap_insert_block_by_selector( $working_content, $selector, $position, $block_html, 1 );
								if ( ! is_wp_error( $new_content ) && $new_content !== $working_content ) {
									$working_content = $new_content;
								}
							}
						}
					}
				}

				// If inline images were inserted, update the content to return.
				if ( $working_content !== ( ( $has_edit && '' !== $edited_content ) ? $edited_content : $post->post_content ) ) {
					$has_edit       = true;
					$edited_content = wp_kses_post( $working_content );
				}
			}
		}

		// The model can write <img> markup with an external src straight into the
		// edited content, which bypasses the sideloading that image_actions do.
		// Pull those into the media library so images serve from this site.
		if ( $post_id > 0 && $has_edit && '' !== $edited_content
			&& function_exists( 'saiap_sideload_external_images_in_content' ) ) {
			$edited_content = saiap_sideload_external_images_in_content( $post_id, $edited_content );
		}

		$response_data = array(
			'status'         => 'completed',
			'chat_message'   => $chat_message,
			'has_edit'       => $has_edit,
			'edited_content' => $edited_content,
		);
		if ( $featured_media > 0 ) {
			$response_data['featured_media'] = $featured_media;
		}
		wp_send_json_success( $response_data );
	} elseif ( $data['status'] === 'error' ) {
		wp_send_json_error( array(
			'status'  => 'error',
			'message' => isset( $data['error'] ) ? sanitize_text_field( $data['error'] ) : 'Unknown error',
		) );
	} else {
		// Still pending
		wp_send_json_success( array(
			'status' => 'pending',
		) );
	}
}
add_action( 'wp_ajax_saiap_chat_status', 'saiap_check_chat_status' );

/**
 * Render the Edit with AI tab
 */
function saiap_render_edit_with_ai_tab() {
	// Render trial CTA for non-trial/non-paid users.
	$scenario = saiap_get_user_scenario();
	if ( in_array( $scenario, array( 'no_trial_no_keys', 'no_trial_has_keys', 'expired_trial' ), true ) ) {
		saiap_render_trial_cta_card( 'editor', true );
	}
	?>
	<div class="container">
		<div class="row">
			<div class="col col-12">
				<div class="card spacing-24">
					<h2><?php esc_html_e( 'Edit with AI in the Editor', 'clearpost-simple-ai-auto-post' ); ?></h2>
					<p class="body-text" style="margin-bottom: 12px;">
						<?php esc_html_e( 'Open any post, click the AI chat icon in the sidebar, and ask it to improve, rewrite, expand, or fix your content.', 'clearpost-simple-ai-auto-post' ); ?>
					</p>
					<button type="button" class="primary-button" onclick="window.open('<?php echo esc_url( admin_url( 'post-new.php' ) ); ?>', '_blank');">
						<?php esc_html_e( 'Try It Now', 'clearpost-simple-ai-auto-post' ); ?>
					</button>
				</div>
			</div>
		</div>
		<div class="row">
			<div class="col col-12">
				<?php
				if ( function_exists( 'saiap_render_mcp_card' ) ) {
					saiap_render_mcp_card();
				}
				?>
			</div>
		</div>
	</div>
	<?php
}