<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @since 1.0.0
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Admin;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Wisewand\Utils\Options;
use Wisewand\Utils\Wisewand_API_Client;
use Wisewand\Logging\Logger;

// phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log -- error_log() is only used within WP_DEBUG conditionals for debugging

class Wisewand_Articles_Page {

	private $options;
	private $logger;
	private $api_client;
	private $repository;

	public function __construct( Options $options, Logger $logger ) {
		$this->options    = $options;
		$this->logger     = $logger;
		$this->repository = new \Wisewand\Repositories\Article_Repository();

		// Initialize API client immediately since all dependencies should be loaded by now
		$this->init_api_client();
	}

	public function init_api_client() {
		if ( class_exists( 'Wisewand\\Utils\\Wisewand_API_Client' ) ) {
			$api_key = Wisewand_API_Client::get_stored_api_key();
			if ( ! empty( $api_key ) ) {
				$this->api_client = new Wisewand_API_Client( $api_key, $this->logger );
			}
		}
	}

	/**
	 * Enqueue Articles page assets
	 */
	private function enqueue_assets() {
		wp_enqueue_style(
			'wisewand-articles-admin',
			WISEWAND_PLUGIN_URL . 'assets/css/admin/wisewand-articles-admin.css',
			array(),
			WISEWAND_PLUGIN_VERSION
		);

		// Add inline styles for imported article highlighting
		wp_add_inline_style(
			'wisewand-articles-admin',
			'.wp-list-table.wisewand-content-table tr.wisewand-imported .column-import,
			.wp-list-table.wisewand-content-table tr.import-success .column-import {
				color: #00a32a;
				font-weight: 600;
			}
			.wp-list-table.wisewand-content-table tr.wisewand-imported,
			.wp-list-table.wisewand-content-table tr.import-success {
				background-color: #f0f9f4;
			}
			.wp-list-table.wisewand-content-table tr.wisewand-imported:hover,
			.wp-list-table.wisewand-content-table tr.import-success:hover {
				background-color: #e6f4ea;
			}'
		);

		// Enqueue the articles admin JavaScript
		wp_enqueue_script(
			'wisewand-articles-admin',
			WISEWAND_PLUGIN_URL . 'assets/js/admin/wisewand-articles-admin.js',
			array( 'jquery' ),
			WISEWAND_PLUGIN_VERSION,
			true
		);

		// Localize script with i18n strings and nonces
		wp_localize_script(
			'wisewand-articles-admin',
			'wisewandArticles',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'i18n'    => array(
					'selectBulkAction'    => __( 'Please select a bulk action', 'wisewand-ai-content-writer-seo-content-generator' ),
					'selectOneArticle'    => __( 'Please select at least one article', 'wisewand-ai-content-writer-seo-content-generator' ),
					'confirmBulkAction'   => __( 'Are you sure you want to perform this action on', 'wisewand-ai-content-writer-seo-content-generator' ),
					'articles'            => __( 'articles?', 'wisewand-ai-content-writer-seo-content-generator' ),
					'processing'          => __( 'Processing...', 'wisewand-ai-content-writer-seo-content-generator' ),
					'bulkSuccess'         => __( 'Bulk action completed successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'bulkFailed'          => __( 'Bulk action failed:', 'wisewand-ai-content-writer-seo-content-generator' ),
					'bulkNetworkError'    => __( 'Network error occurred during bulk action.', 'wisewand-ai-content-writer-seo-content-generator' ),
					'importing'           => __( 'Importing...', 'wisewand-ai-content-writer-seo-content-generator' ),
					'imported'            => __( 'Imported', 'wisewand-ai-content-writer-seo-content-generator' ),
					'contentImported'     => __( 'Content imported successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'wooCommerceCategoryImported' => __( 'WooCommerce category imported successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'wordPressCategoryImported'   => __( 'WordPress category imported successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'postImported'        => __( 'Post imported successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'edit'                => __( 'Edit', 'wisewand-ai-content-writer-seo-content-generator' ),
					'importFailed'        => __( 'Import failed:', 'wisewand-ai-content-writer-seo-content-generator' ),
					'importNetworkError'  => __( 'Network error occurred during import.', 'wisewand-ai-content-writer-seo-content-generator' ),
					'selectPublishDate'   => __( 'Please select a publish date for scheduled posts.', 'wisewand-ai-content-writer-seo-content-generator' ),
					'starting'            => __( 'Starting...', 'wisewand-ai-content-writer-seo-content-generator' ),
					'generationStarted'   => __( 'Generation started!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'generationFailed'    => __( 'Generation failed:', 'wisewand-ai-content-writer-seo-content-generator' ),
					'generationNetworkError' => __( 'Network error occurred during generation.', 'wisewand-ai-content-writer-seo-content-generator' ),
					'unknownAction'       => __( 'Unknown bulk action.', 'wisewand-ai-content-writer-seo-content-generator' ),
				),
				'nonces'  => array(
					'bulk'       => wp_create_nonce( 'wisewand_bulk_action' ),
					'import'     => wp_create_nonce( 'wisewand_import_article' ),
					'generation' => wp_create_nonce( 'wisewand_run_generation' ),
				),
			)
		);
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'wisewand-ai-content-writer-seo-content-generator' ) );
		}

		$this->enqueue_assets();

		// Try to initialize API client again if it wasn't initialized during construction
		if ( ! $this->api_client ) {
			$this->init_api_client();
		}

		echo '<div class="wrap wisewand-articles">';
		$current_filters = $this->get_current_filters();
		$page_title      = $this->get_page_title( $current_filters['content_type'] );
		echo '<h1 class="wp-heading-inline">' . esc_html( $page_title ) . '</h1>';

		if ( ! $this->is_api_configured() ) {
			echo '<a href="' . esc_url( admin_url( 'admin.php?page=wisewand-settings' ) ) . '" class="page-title-action">' . esc_html__( 'Configure API', 'wisewand-ai-content-writer-seo-content-generator' ) . '</a>';
			echo '<hr class="wp-header-end">';
			$this->render_api_setup_notice();
			echo '</div>';
			return;
		}

		echo '<a href="' . esc_url( admin_url( 'admin.php?page=wisewand-settings' ) ) . '" class="page-title-action">' . esc_html__( 'Settings', 'wisewand-ai-content-writer-seo-content-generator' ) . '</a>';
		echo '<hr class="wp-header-end">';

		$this->render_articles_interface();
		echo '</div>';
	}

	private function is_api_configured() {
		return Wisewand_API_Client::is_api_key_configured();
	}

	private function render_api_setup_notice() {
		?>
		<div class="notice notice-warning">
			<p>
				<strong><?php esc_html_e( 'Wisewand API Key Required', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong><br>
				<?php esc_html_e( 'Please configure your Wisewand API key to browse and import articles.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-api-settings' ) ); ?>" class="button button-primary">
					<?php esc_html_e( 'Configure API Key', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
			</p>
		</div>
		<?php
	}

	private function render_articles_interface() {
		// Get current page and filters
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Pagination parameter, no action performed
		$current_page = max( 1, isset( $_GET['paged'] ) ? absint( wp_unslash( $_GET['paged'] ) ) : 1 );
		$per_page     = 20;
		$filters      = $this->get_current_filters();

		// Fetch articles from API
		$articles_data = $this->fetch_articles( $current_page, $per_page, $filters );

		if ( is_wp_error( $articles_data ) ) {
			$this->render_api_error( $articles_data );
			return;
		}

		?>
		<div class="wisewand-articles-wrapper">
			<?php $this->render_filters( $filters ); ?>
			<?php $this->render_articles_table( $articles_data ); ?>
			<?php $this->render_pagination( $articles_data ); ?>
		</div>
		<?php
	}

	private function render_filters( $current_filters ) {
		?>
		<div class="tablenav top">
			<div class="alignleft actions">
				<form method="get" action="" style="display: inline-flex; gap: 10px; align-items: center;">
                    <?php // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Form preserving $_GET parameters for filtering, no action performed ?>
					<input type="hidden" name="page" value="<?php echo esc_attr( isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '' ); ?>" />

					<input type="search" name="search" value="<?php echo esc_attr( $current_filters['search'] ); ?>" placeholder="<?php esc_html_e( 'Search content...', 'wisewand-ai-content-writer-seo-content-generator' ); ?>" />

					<select name="content_type">
						<option value="" <?php selected( $current_filters['content_type'], '' ); ?>><?php esc_html_e( 'All Content Types', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<option value="articles" <?php selected( $current_filters['content_type'], 'articles' ); ?>><?php esc_html_e( 'Articles', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<option value="categorypages" <?php selected( $current_filters['content_type'], 'categorypages' ); ?>><?php esc_html_e( 'Category Pages', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<option value="productpages" <?php selected( $current_filters['content_type'], 'productpages' ); ?>><?php esc_html_e( 'Product Pages', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<option value="discoverarticles" <?php selected( $current_filters['content_type'], 'discoverarticles' ); ?>><?php esc_html_e( 'Google Discover Articles', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
					</select>

					<select name="project_id">
						<option value="" <?php selected( $current_filters['project_id'], '' ); ?>><?php esc_html_e( 'All Projects', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<?php $this->render_projects_options( $current_filters['project_id'] ); ?>
					</select>

					<select name="status">
						<option value="" <?php selected( $current_filters['status'], '' ); ?>><?php esc_html_e( 'All Statuses', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<option value="success" <?php selected( $current_filters['status'], 'success' ); ?>><?php esc_html_e( 'Ready to Import', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<option value="running" <?php selected( $current_filters['status'], 'running' ); ?>><?php esc_html_e( 'Generating', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<option value="queued" <?php selected( $current_filters['status'], 'queued' ); ?>><?php esc_html_e( 'Queued', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<option value="error" <?php selected( $current_filters['status'], 'error' ); ?>><?php esc_html_e( 'Error', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
					</select>

					<?php submit_button( __( 'Filter', 'wisewand-ai-content-writer-seo-content-generator' ), 'secondary', 'submit', false, array( 'style' => 'margin: 0;' ) ); ?>

					<?php if ( $this->has_active_filters( $current_filters ) ) : ?>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-articles' ) ); ?>" class="button"><?php esc_html_e( 'Clear', 'wisewand-ai-content-writer-seo-content-generator' ); ?></a>
					<?php endif; ?>
				</form>
			</div>
		</div>
		<?php
	}

	private function render_articles_table( $articles_data ) {
		// FIX: Changed from 'items' to 'articles' to match API response structure.
		// API returns: { "articles": [...], "total": X, "page": Y }
		// Previously used 'items' key which didn't exist, causing empty table display.
		$articles = $articles_data['articles'] ?? array();
		$current_filters = $this->get_current_filters();
		?>
		<table class="wp-list-table widefat fixed striped wisewand-content-table">
			<thead>
				<tr>
					<td class="manage-column column-cb check-column">
						<input type="checkbox" id="cb-select-all" />
					</td>
					<th scope="col" class="column-title column-primary"><?php esc_html_e( 'Title', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<th scope="col" class="column-status"><?php esc_html_e( 'Status', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<?php if ( $this->has_multilingual_support() ) : ?>
					<th scope="col" class="column-language"><?php esc_html_e( 'Language', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<?php endif; ?>
					<th scope="col" class="column-author"><?php esc_html_e( 'Author', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<th scope="col" class="column-categories"><?php esc_html_e( 'Categories', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<th scope="col" class="column-post-type"><?php esc_html_e( 'Import As', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<th scope="col" class="column-publish-state"><?php esc_html_e( 'Publish As', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<th scope="col" class="column-publish-date"><?php esc_html_e( 'Publish Date', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<th scope="col" class="column-import"><?php esc_html_e( 'Import', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php if ( empty( $articles ) ) : ?>
				<tr>
					<td colspan="<?php echo esc_attr( $this->get_table_colspan() ); ?>" class="no-articles">
						<div style="text-align: center; padding: 40px;">
							<span class="dashicons dashicons-admin-post" style="font-size: 48px; color: #c3c4c7;"></span>
							<?php if ( $current_filters['status'] === 'success' ) : ?>
								<p><?php esc_html_e( 'No articles ready to import.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
								<p><?php esc_html_e( 'Generate some articles in Wisewand or check other statuses.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
								<a href="<?php echo esc_url( add_query_arg( 'status', '' ) ); ?>" class="button"><?php esc_html_e( 'View All Articles', 'wisewand-ai-content-writer-seo-content-generator' ); ?></a>
							<?php else : ?>
								<p><?php esc_html_e( 'No articles found.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
								<?php if ( ! empty( $current_filters['search'] ) || ( ! empty( $current_filters['status'] ) && $current_filters['status'] !== 'success' ) ) : ?>
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-articles' ) ); ?>" class="button"><?php esc_html_e( 'View Ready Articles', 'wisewand-ai-content-writer-seo-content-generator' ); ?></a>
								<?php endif; ?>
							<?php endif; ?>
						</div>
					</td>
				</tr>
				<?php else : ?>
					<?php foreach ( $articles as $article ) : ?>
				<tr class="<?php echo esc_attr( $this->get_row_class( $article ) ); ?>">
					<th scope="row" class="check-column">
						<input type="checkbox" name="article_ids[]" value="<?php echo esc_attr( $article['id'] ); ?>" />
					</th>
					<td class="column-title column-primary" data-colname="<?php esc_html_e( 'Title', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
						<strong class="row-title"><?php echo esc_html( $article['title'] ); ?></strong>

						<?php if ( ! empty( $article['target_keyword'] ) ) : ?>
						<div class="row-excerpt"><?php esc_html_e( 'Keyword:', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <em><?php echo esc_html( $article['target_keyword'] ); ?></em></div>
						<?php endif; ?>

						<div class="row-excerpt"><?php echo esc_html( wp_trim_words( $article['subject'], 12 ) ); ?></div>

						<div class="row-actions">
							<span class="view">
								<a href="<?php echo esc_url( $this->get_wisewand_url( $article ) ); ?>" target="_blank">
									<?php esc_html_e( 'View in Wisewand', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</a>
							</span>
							<?php if ( ! empty( $article['content_type'] ) && $article['content_type'] !== 'articles' ) : ?>
							| <span class="content-type"><?php echo esc_html( $this->get_content_type_label( $article['content_type'] ) ); ?></span>
							<?php endif; ?>
						</div>

						<button type="button" class="toggle-row"><span class="screen-reader-text"><?php esc_html_e( 'Show more details', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span></button>
					</td>
					<td class="column-status" data-colname="<?php esc_html_e( 'Status', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
						<?php $this->render_status_badge( $article['status'] ); ?>
					</td>
						<?php if ( $this->has_multilingual_support() ) : ?>
					<td class="column-language" data-colname="<?php esc_html_e( 'Language', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
							<?php $this->render_editable_language( $article ); ?>
					</td>
					<?php endif; ?>
					<td class="column-author" data-colname="<?php esc_html_e( 'Author', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
						<?php $this->render_author_selector( $article ); ?>
					</td>
					<td class="column-categories" data-colname="<?php esc_html_e( 'Categories', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
						<?php $this->render_categories_selector( $article ); ?>
					</td>
					<td class="column-post-type" data-colname="<?php esc_html_e( 'Import As', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
						<?php $this->render_post_type_selector( $article ); ?>
					</td>
					<td class="column-publish-state" data-colname="<?php esc_html_e( 'Publish As', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
						<?php $this->render_publish_state_selector( $article ); ?>
					</td>
					<td class="column-publish-date" data-colname="<?php esc_html_e( 'Publish Date', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
						<?php $this->render_publish_date_selector( $article ); ?>
					</td>
					<td class="column-import" data-colname="<?php esc_html_e( 'Import', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
						<?php $this->render_import_actions( $article ); ?>
					</td>
				</tr>
				<?php endforeach; ?>
				<?php endif; ?>
			</tbody>
			<tfoot>
				<tr>
					<td class="manage-column column-cb check-column">
						<input type="checkbox" id="cb-select-all-footer" />
					</td>
					<th scope="col" class="column-title column-primary"><?php esc_html_e( 'Title', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<th scope="col" class="column-status"><?php esc_html_e( 'Status', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<?php if ( $this->has_multilingual_support() ) : ?>
					<th scope="col" class="column-language"><?php esc_html_e( 'Language', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<?php endif; ?>
					<th scope="col" class="column-author"><?php esc_html_e( 'Author', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<th scope="col" class="column-categories"><?php esc_html_e( 'Categories', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<th scope="col" class="column-post-type"><?php esc_html_e( 'Import As', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<th scope="col" class="column-publish-state"><?php esc_html_e( 'Publish As', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<th scope="col" class="column-publish-date"><?php esc_html_e( 'Publish Date', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<th scope="col" class="column-import"><?php esc_html_e( 'Import', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
				</tr>
			</tfoot>
		</table>

		<div class="tablenav bottom">
			<div class="alignleft actions">
				<select id="bulk-action-selector-bottom">
					<option value=""><?php esc_html_e( 'Bulk Actions', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
					<option value="import_ready"><?php esc_html_e( 'Import Ready Articles', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
					<option value="run_generation"><?php esc_html_e( 'Start Generation', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				</select>
				<button type="button" class="button" id="bulk-action-submit"><?php esc_html_e( 'Apply', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>

				<span class="displaying-num">
					<?php
					/* translators: %s: Number of items in the list */
					echo esc_html( sprintf( _n( '%s item', '%s items', $articles_data['total'], 'wisewand-ai-content-writer-seo-content-generator' ), number_format_i18n( $articles_data['total'] ) ) );
					?>
				</span>
			</div>
		</div>

		<?php
	}

	private function render_article_actions( $article ) {
		$article_id = $article['id'];
		$status     = $article['status'];

		echo '<div class="wisewand-actions">';

		// Import action (for ready articles)
		if ( $status === 'success' ) {
			?>
			<button type="button"
					class="button button-primary button-small wisewand-import-article"
					data-article-id="<?php echo esc_attr( $article_id ); ?>">
				<?php esc_html_e( 'Import', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
			</button>
			<?php
		}

		// Run generation (for queued articles)
		if ( $status === 'queued' ) {
			?>
			<button type="button"
					class="button button-secondary button-small wisewand-run-generation"
					data-article-id="<?php echo esc_attr( $article_id ); ?>">
				<?php esc_html_e( 'Generate', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
			</button>
			<?php
		}

		// View details
		?>
		<button type="button"
				class="button button-small wisewand-view-details"
				data-article-id="<?php echo esc_attr( $article_id ); ?>">
			<?php esc_html_e( 'Details', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
		</button>
		<?php

		// Test import for debugging (only show for specific article or in debug mode)
		$debug_mode = get_option( 'wisewand_debug_mode', false );
		if ( $debug_mode || $article_id === 'a7285f6c-2918-4808-89fd-5e968692158b' ) {
			?>
			<button type="button"
					class="button button-small wisewand-test-import"
					data-article-id="<?php echo esc_attr( $article_id ); ?>">
				<?php esc_html_e( 'Test Import', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
			</button>
			<?php
		}

		// Error details (for failed articles)
		if ( $status === 'error' && $this->api_client ) {
			$error_message = $this->api_client->get_error_message( $article );
			if ( $error_message ) {
				?>
				<br><small class="wisewand-error-message"><?php echo esc_html( $error_message ); ?></small>
				<?php
			}
		}

		echo '</div>';
	}

	private function render_pagination( $articles_data ) {
		$total_pages  = $articles_data['total_pages'];
		$current_page = $articles_data['page'];

		if ( $total_pages <= 1 ) {
			return;
		}

		echo '<div class="wisewand-pagination">';
		echo wp_kses_post(
			paginate_links(
				array(
					'base'      => add_query_arg( 'paged', '%#%' ),
					'format'    => '',
					'prev_text' => __( '&laquo; Previous', 'wisewand-ai-content-writer-seo-content-generator' ),
					'next_text' => __( 'Next &raquo;', 'wisewand-ai-content-writer-seo-content-generator' ),
					'total'     => $total_pages,
					'current'   => $current_page,
				)
			)
		);
		echo '</div>';
	}

	private function render_api_error( $error ) {
		?>
		<div class="notice notice-error">
			<p>
				<strong><?php esc_html_e( 'Wisewand API Error', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong><br>
				<?php echo esc_html( $error->get_error_message() ); ?>
			</p>
			<p>
				<button type="button" class="button wisewand-refresh-articles">
					<?php esc_html_e( 'Retry', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</button>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-api-settings' ) ); ?>" class="button">
					<?php esc_html_e( 'Check API Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
			</p>
		</div>

		<?php
		// Show debug information if it's a client initialization error
		if ( $error->get_error_code() === 'wisewand_no_api_client' ) {
			// Load Debug Helper if not already loaded
			if ( ! class_exists( 'Wisewand\\Utils\\Debug_Helper' ) ) {
				$debug_file = WISEWAND_PLUGIN_DIR . 'includes/Utils/Debug_Helper.php';
				if ( file_exists( $debug_file ) ) {
					require_once $debug_file;
				}
			}

			if ( class_exists( 'Wisewand\\Utils\\Debug_Helper' ) ) {
				\Wisewand\Utils\Debug_Helper::render_debug_info();
			}
		}
		?>
		<?php
	}

	private function get_current_filters() {
		return array(
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading filter parameters from URL for display purposes, no action performed
			'search'       => isset( $_GET['search'] ) ? sanitize_text_field( wp_unslash( $_GET['search'] ) ) : '',
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading filter parameters from URL for display purposes, no action performed
			'status'       => isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : 'success', // Default to 'success' (Ready to Import)
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading filter parameters from URL for display purposes, no action performed
			'content_type' => isset( $_GET['content_type'] ) ? sanitize_text_field( wp_unslash( $_GET['content_type'] ) ) : 'articles', // Default to articles
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading filter parameters from URL for display purposes, no action performed
			'project_id'   => isset( $_GET['project_id'] ) ? sanitize_text_field( wp_unslash( $_GET['project_id'] ) ) : '',
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading filter parameters from URL for display purposes, no action performed
			'published'    => isset( $_GET['published'] ) ? sanitize_text_field( wp_unslash( $_GET['published'] ) ) : '',
		);
	}

	private function fetch_articles( $page, $per_page, $filters ) {
		// Try to initialize API client one more time if needed
		if ( ! $this->api_client ) {
			$this->init_api_client();
		}

		if ( ! $this->api_client ) {
			$api_key    = get_option( 'wisewand_api_key', '' );
			$debug_info = array(
				'api_key_exists' => ! empty( $api_key ),
				'api_key_length' => strlen( $api_key ),
				'class_exists'   => class_exists( 'Wisewand\\Utils\\Wisewand_API_Client' ),
				'is_configured'  => Wisewand_API_Client::is_api_key_configured(),
			);

			return new \WP_Error(
				'wisewand_no_api_client',
				sprintf(
					/* translators: %s: JSON-encoded debug information */
					__( 'API client not initialized. Debug info: %s', 'wisewand-ai-content-writer-seo-content-generator' ),
					wp_json_encode( $debug_info )
				)
			);
		}

		return $this->api_client->get_articles_for_admin( $page, $per_page, $filters );
	}

	private function render_projects_options( $selected_project_id ) {
		if ( ! $this->api_client ) {
			return;
		}

		// Fetch projects for dropdown
		$projects_result = $this->api_client->list_projects( array( 'take' => 100 ) );

		if ( is_wp_error( $projects_result ) || empty( $projects_result['items'] ) ) {
			echo '<option disabled>' . esc_html__( 'No projects available', 'wisewand-ai-content-writer-seo-content-generator' ) . '</option>';
			return;
		}

		foreach ( $projects_result['items'] as $project ) {
			$project_id = $project['id'] ?? '';

			// Try multiple possible name fields from Wisewand API
			$project_name = $project['name'] ??
							$project['title'] ??
							$project['project_name'] ??
							$project['display_name'] ??
							'Unnamed Project';

			// Debug log to see what data we're getting
			if ( $this->logger ) {
				$this->logger->debug(
					'Project data for dropdown',
					array(
						'project_id'   => $project_id,
						'project_keys' => array_keys( $project ),
						'name_field'   => $project['name'] ?? 'missing',
						'title_field'  => $project['title'] ?? 'missing',
					)
				);
			}

			echo '<option value="' . esc_attr( $project_id ) . '" ' . selected( $selected_project_id, $project_id, false ) . '>';
			echo esc_html( $project_name );
			echo '</option>';
		}
	}

	private function has_active_filters( $filters ) {
		return ! empty( $filters['search'] ) ||
				( ! empty( $filters['status'] ) && $filters['status'] !== 'success' ) ||
				( ! empty( $filters['content_type'] ) && $filters['content_type'] !== 'articles' ) ||
				! empty( $filters['project_id'] );
	}

	// Helper methods for clean table rendering

	private function get_row_class( $article ) {
		$classes = array( 'wisewand-article' );

		$article_id = $article['id'] ?? 'NO_ID';


		// Check if already imported
		// Check if already imported
		$existing_post_id = $this->repository->get_post_id_by_external_id( $article_id );



		if ( $existing_post_id ) {
			$post = get_post( $existing_post_id );


			if ( $post ) {
				$classes[] = 'wisewand-imported';  // Add imported class
				$classes[] = 'import-success';     // Also add success class

			}
		}

		switch ( $article['status'] ) {
			case 'success':
				$classes[] = 'status-ready';
				break;
			case 'running':
				$classes[] = 'status-generating';
				break;
			case 'error':
				$classes[] = 'status-error';
				break;
			case 'queued':
				$classes[] = 'status-queued';
				break;
		}

		$final_classes = implode( ' ', $classes );


		return $final_classes;
	}

	private function render_status_badge( $status ) {
		$status_info = $this->get_status_info( $status );
		?>
		<span class="status-badge status-<?php echo esc_attr( $status ); ?>" style="<?php echo esc_attr( $status_info['style'] ); ?>">
			<?php echo esc_html( $status_info['label'] ); ?>
		</span>
		<?php
	}

	private function get_status_info( $status ) {
		$statuses = array(
			'success' => array(
				'label' => __( 'Ready', 'wisewand-ai-content-writer-seo-content-generator' ),
				'style' => 'background: #00a32a; color: white; padding: 4px 8px; border-radius: 3px; font-size: 11px; font-weight: 600;',
			),
			'running' => array(
				'label' => __( 'Generating...', 'wisewand-ai-content-writer-seo-content-generator' ),
				'style' => 'background: #dba617; color: white; padding: 4px 8px; border-radius: 3px; font-size: 11px; font-weight: 600;',
			),
			'queued'  => array(
				'label' => __( 'Queued', 'wisewand-ai-content-writer-seo-content-generator' ),
				'style' => 'background: #72aee6; color: white; padding: 4px 8px; border-radius: 3px; font-size: 11px; font-weight: 600;',
			),
			'error'   => array(
				'label' => __( 'Error', 'wisewand-ai-content-writer-seo-content-generator' ),
				'style' => 'background: #d63638; color: white; padding: 4px 8px; border-radius: 3px; font-size: 11px; font-weight: 600;',
			),
		);

		return $statuses[ $status ] ?? array(
			'label' => ucfirst( $status ),
			'style' => 'background: #8c8f94; color: white; padding: 4px 8px; border-radius: 3px; font-size: 11px; font-weight: 600;',
		);
	}

	private function render_editable_language( $article ) {
		$article_id    = $article['id'];
		$detected_lang = $this->detect_article_language( $article );
		$wpml_target   = $this->get_wpml_language_for_article( $article );

		?>
		<div class="language-selector" data-article-id="<?php echo esc_attr( $article_id ); ?>">
			<?php if ( $this->options->is_wpml_active() ) : ?>
				<?php
				global $sitepress;
				if ( $sitepress ) {
					$active_languages = $sitepress->get_active_languages();
					?>
					<select class="language-override-select" data-article-id="<?php echo esc_attr( $article_id ); ?>">
						<option value=""><?php esc_html_e( 'Auto-detect', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<?php foreach ( $active_languages as $code => $lang_data ) : ?>
						<option value="<?php echo esc_attr( $code ); ?>" <?php selected( $wpml_target, $code ); ?>>
							<?php echo esc_html( $lang_data['display_name'] ?? strtoupper( $code ) ); ?>
						</option>
						<?php endforeach; ?>
					</select>
					<br>
					<small style="color: #646970;">
						<?php esc_html_e( 'Detected:', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						<strong><?php echo esc_html( $detected_lang ); ?></strong>
						<?php if ( $wpml_target && $wpml_target !== $detected_lang ) : ?>
						→ <strong><?php echo esc_html( strtoupper( $wpml_target ) ); ?></strong>
						<?php endif; ?>
					</small>
					<?php
				} else {
					echo '<span class="language-badge">' . esc_html( $detected_lang ) . '</span>';
				}
				?>
			<?php else : ?>
				<span class="language-badge"><?php echo esc_html( $detected_lang ); ?></span>
				<br><small style="color: #646970;"><?php esc_html_e( 'WPML not active', 'wisewand-ai-content-writer-seo-content-generator' ); ?></small>
			<?php endif; ?>
		</div>
		<?php
	}

	private function detect_article_language( $article ) {
		// Improved language detection logic
		$lang    = strtolower( $article['lang'] ?? 'fr' );
		$country = strtolower( $article['country'] ?? 'fr' );

		// Common language mappings for proper detection
		$language_map = array(
			'en' => 'EN',
			'fr' => 'FR',
			'de' => 'DE',
			'es' => 'ES',
			'it' => 'IT',
		);

		$base_lang = $language_map[ $lang ] ?? strtoupper( $lang );

		// Show country if different from language
		if ( $country !== $lang ) {
			return $base_lang . '-' . strtoupper( $country );
		}

		return $base_lang;
	}

	private function render_import_actions( $article ) {
		$article_id = $article['id'];
		$status     = $article['status'];



		// CRITICAL FIX: Check if article already imported
		// Search for existing WordPress post with this Wisewand external_id
		$existing_post_id = $this->repository->get_post_id_by_external_id( $article_id );



		$existing_post = $existing_post_id ? get_post( $existing_post_id ) : null;

		if ( $existing_post ) {

		}

		?>
		<div class="import-actions">
			<?php if ( $existing_post && $existing_post->post_status !== 'trash' ) : ?>
				<!-- ALREADY IMPORTED - Show Edit Post button -->
				<?php

				?>
				<a href="<?php echo esc_url( admin_url( 'post.php?post=' . $existing_post->ID . '&action=edit' ) ); ?>"
					class="button button-secondary"
					target="_blank"
					style="background: #f0f9f4; border-color: #00a32a; color: #00a32a;">
					<span class="dashicons dashicons-edit" style="margin-top: 3px;"></span>
					<?php esc_html_e( 'Edit Post', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
				<br>
				<small style="color: #00a32a; font-weight: 600;">
					✓ <?php esc_html_e( 'Imported', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					(ID: <?php echo esc_html( $existing_post->ID ); ?>)
				</small>
			<?php elseif ( $status === 'success' ) : ?>
				<?php

				?>
				<!-- NOT IMPORTED YET - Show Import Now button -->
				<button type="button"
						class="button button-primary wisewand-import-article"
						data-article-id="<?php echo esc_attr( $article_id ); ?>">
					<?php esc_html_e( 'Import Now', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</button>
			<?php elseif ( $status === 'queued' ) : ?>
				<button type="button"
						class="button button-secondary wisewand-run-generation"
						data-article-id="<?php echo esc_attr( $article_id ); ?>">
					<?php esc_html_e( 'Generate', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</button>
			<?php elseif ( $status === 'running' ) : ?>
				<span class="generating-indicator">
					<span class="spinner is-active" style="float: none; margin: 0;"></span>
					<?php esc_html_e( 'Generating...', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</span>
			<?php elseif ( $status === 'error' ) : ?>
				<button type="button"
						class="button button-secondary wisewand-run-generation"
						data-article-id="<?php echo esc_attr( $article_id ); ?>">
					<?php esc_html_e( 'Retry', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</button>
			<?php else : ?>
				<span style="color: #8c8f94;">—</span>
			<?php endif; ?>
		</div>
		<?php
	}

	private function render_post_type_selector( $article ) {
		$article_id        = $article['id'];
		$content_type      = $article['content_type'] ?? 'articles';
		$default_post_type = $this->get_default_post_type( $content_type );

		?>
		<div class="post-type-selector">
			<select class="post-type-select" data-article-id="<?php echo esc_attr( $article_id ); ?>" data-content-type="<?php echo esc_attr( $content_type ); ?>">
				<?php $this->render_post_type_options( $content_type, $default_post_type ); ?>
			</select>

			<div class="post-type-details" style="margin-top: 4px;">
				<?php $this->render_post_type_details( $content_type, $article_id ); ?>
			</div>
		</div>
		<?php
	}

	private function get_default_post_type( $content_type ) {
		switch ( $content_type ) {
			case 'articles':
				return 'post';
			case 'categorypages':
				return 'category'; // WordPress category
			case 'productpages':
				return $this->is_woocommerce_active() ? 'product' : 'post';
			default:
				return 'post';
		}
	}

	private function render_post_type_options( $content_type, $selected = '' ) {
		switch ( $content_type ) {
			case 'articles':
				?>
				<option value="post" <?php selected( $selected, 'post' ); ?>><?php esc_html_e( 'Blog Post', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				<option value="page" <?php selected( $selected, 'page' ); ?>><?php esc_html_e( 'Page', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				<?php
				break;

			case 'categorypages':
				?>
				<option value="category" <?php selected( $selected, 'category' ); ?>><?php esc_html_e( 'WordPress Category', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				<option value="page" <?php selected( $selected, 'page' ); ?>><?php esc_html_e( 'Page', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				<?php if ( $this->is_woocommerce_active() ) : ?>
				<option value="product_cat" <?php selected( $selected, 'product_cat' ); ?>><?php esc_html_e( 'WooCommerce Category', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				<?php endif; ?>
				<?php
				break;

			case 'productpages':
				if ( $this->is_woocommerce_active() ) {
					?>
					<option value="product" <?php selected( $selected, 'product' ); ?>><?php esc_html_e( 'WooCommerce Product', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
					<option value="post" <?php selected( $selected, 'post' ); ?>><?php esc_html_e( 'Blog Post', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
					<option value="page" <?php selected( $selected, 'page' ); ?>><?php esc_html_e( 'Page', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
					<?php
				} else {
					?>
					<option value="post" <?php selected( $selected, 'post' ); ?>><?php esc_html_e( 'Blog Post', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
					<option value="page" <?php selected( $selected, 'page' ); ?>><?php esc_html_e( 'Page', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
					<small style="color: #d63638;"><?php esc_html_e( 'WooCommerce not active', 'wisewand-ai-content-writer-seo-content-generator' ); ?></small>
					<?php
				}
				break;
		}
	}

	private function render_post_type_details( $content_type, $article_id ) {
		// Additional controls based on post type selection
		?>
		<div class="post-type-extra-controls" data-article-id="<?php echo esc_attr( $article_id ); ?>">
			<!-- Product selection dropdown (shown when product post type selected) -->
			<select class="existing-product-select" data-article-id="<?php echo esc_attr( $article_id ); ?>" style="display: none; width: 100%; font-size: 11px; margin-top: 4px;">
				<option value=""><?php esc_html_e( 'Create New Product', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				<?php $this->render_existing_products_options(); ?>
			</select>

			<!-- Category selection (shown when category post type selected) -->
			<select class="parent-category-select" data-article-id="<?php echo esc_attr( $article_id ); ?>" style="display: none; width: 100%; font-size: 11px; margin-top: 4px;">
				<option value=""><?php esc_html_e( 'Create New Category', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				<?php $this->render_existing_categories_options( $content_type ); ?>
			</select>
		</div>
		<?php
	}

	private function render_existing_products_options() {
		if ( ! $this->is_woocommerce_active() ) {
			return;
		}

		$products = get_posts(
			array(
				'post_type'      => 'product',
				'posts_per_page' => 100,
				'post_status'    => array( 'publish', 'draft', 'private' ),
				'orderby'        => 'title',
				'order'          => 'ASC',
			)
		);

		foreach ( $products as $product ) {
			echo '<option value="' . esc_attr( $product->ID ) . '">';
			echo esc_html( $product->post_title . ' (ID: ' . $product->ID . ')' );
			echo '</option>';
		}
	}

	private function render_existing_categories_options( $content_type ) {
		// This method will be called dynamically based on selected post type
		// We'll render both WordPress and WooCommerce categories and let JavaScript show the right ones

		// WordPress categories
		$wp_categories = get_terms(
			array(
				'taxonomy'   => 'category',
				'hide_empty' => false,
				'number'     => 100,
				'orderby'    => 'name',
				'order'      => 'ASC',
			)
		);

		if ( ! is_wp_error( $wp_categories ) ) {
			foreach ( $wp_categories as $category ) {
				echo '<option value="wp_cat_' . esc_attr( $category->term_id ) . '" data-taxonomy="category">';
				echo esc_html( $category->name . ' (' . $category->count . ' posts)' );
				echo '</option>';
			}
		}

		// WooCommerce product categories (if WooCommerce is active)
		if ( $this->is_woocommerce_active() ) {
			$product_categories = get_terms(
				array(
					'taxonomy'   => 'product_cat',
					'hide_empty' => false,
					'number'     => 100,
					'orderby'    => 'name',
					'order'      => 'ASC',
				)
			);

			if ( ! is_wp_error( $product_categories ) ) {
				foreach ( $product_categories as $category ) {
					echo '<option value="woo_cat_' . esc_attr( $category->term_id ) . '" data-taxonomy="product_cat">';
					echo esc_html( $category->name . ' (' . $category->count . ' products)' );
					echo '</option>';
				}
			}
		}
	}

	private function render_publish_state_selector( $article ) {
		$article_id     = $article['id'];
		$default_status = $this->options->get( 'wisewand_default_post_status', 'draft' );

		// Check if Wisewand has a specific status preference
		$wisewand_status = $article['original_input']['publishwordpress_status'] ?? $default_status;

		?>
		<div class="publish-state-selector">
			<select class="publish-state-select" data-article-id="<?php echo esc_attr( $article_id ); ?>">
				<option value="draft" <?php selected( $wisewand_status, 'draft' ); ?>><?php esc_html_e( 'Draft', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				<option value="pending" <?php selected( $wisewand_status, 'pending' ); ?>><?php esc_html_e( 'Pending Review', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				<option value="publish" <?php selected( $wisewand_status, 'publish' ); ?>><?php esc_html_e( 'Publish', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				<option value="future" <?php selected( $wisewand_status, 'future' ); ?>><?php esc_html_e( 'Schedule', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
			</select>

			<?php if ( $wisewand_status !== $default_status ) : ?>
			<br><small style="color: #646970;">
				<?php esc_html_e( 'Wisewand suggests:', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <strong><?php echo esc_html( ucfirst( $wisewand_status ) ); ?></strong>
			</small>
			<?php endif; ?>
		</div>
		<?php
	}

	private function render_publish_date_selector( $article ) {
		$article_id = $article['id'];

		// Get suggested date from Wisewand if available
		$suggested_date = $article['original_input']['publishwordpress_date'] ?? '';
		$default_date   = $suggested_date ? gmdate( 'Y-m-d\TH:i', strtotime( $suggested_date ) ) : '';

		?>
		<div class="publish-date-selector">
			<input type="datetime-local"
					class="publish-date-input"
					data-article-id="<?php echo esc_attr( $article_id ); ?>"
					value="<?php echo esc_attr( $default_date ); ?>"
					style="width: 100%; font-size: 12px;" />

			<div class="publish-date-actions" style="margin-top: 4px;">
				<button type="button" class="button-link set-now-btn" data-article-id="<?php echo esc_attr( $article_id ); ?>">
					<?php esc_html_e( 'Now', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</button>
				<button type="button" class="button-link clear-date-btn" data-article-id="<?php echo esc_attr( $article_id ); ?>">
					<?php esc_html_e( 'Clear', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</button>
			</div>

			<?php if ( $suggested_date ) : ?>
			<small style="color: #646970; display: block; margin-top: 2px;">
				<?php esc_html_e( 'Wisewand suggested:', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <?php echo esc_html( gmdate( 'M j, Y H:i', strtotime( $suggested_date ) ) ); ?>
			</small>
			<?php endif; ?>
		</div>
		<?php
	}

	private function render_author_selector( $article ) {
		$article_id = $article['id'];

		// Get current user as default
		$current_user_id = get_current_user_id();

		// Get all users who can edit posts (fixed: 'who' deprecated since WP 5.9)
		$users = get_users(
			array(
				'capability' => 'edit_posts',
				'orderby'    => 'display_name',
				'order'      => 'ASC',
			)
		);

		?>
		<div class="author-selector">
			<select class="author-select" data-article-id="<?php echo esc_attr( $article_id ); ?>" style="width: 100%; font-size: 12px;">
				<?php foreach ( $users as $user ) : ?>
					<option value="<?php echo esc_attr( $user->ID ); ?>" <?php selected( $user->ID, $current_user_id ); ?>>
						<?php echo esc_html( $user->display_name ); ?>
					</option>
				<?php endforeach; ?>
			</select>
		</div>
		<?php
	}

	private function render_categories_selector( $article ) {
		$article_id = $article['id'];

		// Get all categories
		$categories = get_categories(
			array(
				'orderby'    => 'name',
				'order'      => 'ASC',
				'hide_empty' => false,
			)
		);

		?>
		<div class="categories-selector">
			<select multiple
					class="categories-select"
					data-article-id="<?php echo esc_attr( $article_id ); ?>"
					style="width: 100%; height: 60px; font-size: 11px;">
				<?php foreach ( $categories as $category ) : ?>
					<option value="<?php echo esc_attr( $category->term_id ); ?>">
						<?php
						// Show parent > child hierarchy
						if ( $category->parent ) {
							$parent = get_category( $category->parent );
							if ( $parent ) {
								echo esc_html( $parent->name ) . ' > ';
							}
						}
						echo esc_html( $category->name );
						?>
					</option>
				<?php endforeach; ?>
			</select>
			<small style="color: #646970; display: block; margin-top: 2px;">
				<?php esc_html_e( 'Hold Ctrl/Cmd to select multiple', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
			</small>
		</div>
		<?php
	}

	private function get_wpml_language_for_article( $article ) {
		if ( ! $this->options->is_wpml_active() ) {
			return null;
		}

		$plugin       = \Wisewand\Core\Plugin::instance();
		$wpml_manager = $plugin->get_wpml_manager();

		if ( $wpml_manager ) {
			$input_data = array(
				'lang'    => $article['lang'],
				'country' => $article['country'],
			);
			return $wpml_manager->determine_wpml_language( $input_data );
		}

		return null;
	}

	private function render_row_actions( $article ) {
		$actions    = array();
		$article_id = $article['id'];
		$status     = $article['status'];

		// Primary action based on status
		if ( $status === 'success' ) {
			$actions['import'] = '<span class="import"><a href="#" class="wisewand-import-article" data-article-id="' . esc_attr( $article_id ) . '">' . esc_html__( 'Import', 'wisewand-ai-content-writer-seo-content-generator' ) . '</a></span>';
		} elseif ( $status === 'queued' ) {
			$actions['generate'] = '<span class="generate"><a href="#" class="wisewand-run-generation" data-article-id="' . esc_attr( $article_id ) . '">' . esc_html__( 'Start Generation', 'wisewand-ai-content-writer-seo-content-generator' ) . '</a></span>';
		}

		// Secondary actions
		$actions['view'] = '<span class="view"><a href="https://wisewand.ai/dashboard/articles/' . esc_attr( $article_id ) . '" target="_blank">' . esc_html__( 'View in Wisewand', 'wisewand-ai-content-writer-seo-content-generator' ) . '</a></span>';

		echo wp_kses_post( implode( ' | ', $actions ) );
	}

	// AJAX handlers
	public function ajax_import_article() {
		// CRITICAL DIAGNOSTIC: Log entry point immediately
		if ( WP_DEBUG ) {
			error_log( '🔵🔵🔵 AJAX_IMPORT_ARTICLES_PAGE: Handler called - timestamp: ' . current_time( 'mysql' ) );
			error_log( 'AJAX_IMPORT_ARTICLES_PAGE: POST data: ' . wp_json_encode( array_keys( $_POST ) ) );
		}

		check_ajax_referer( 'wisewand_import_article', 'nonce' );

		if ( ! current_user_can( 'edit_posts' ) ) {
			if ( WP_DEBUG ) {
				error_log( '❌ AJAX_IMPORT_ARTICLES_PAGE: Permission denied' );
			}
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$article_id = isset( $_POST['article_id'] ) ? sanitize_text_field( wp_unslash( $_POST['article_id'] ) ) : '';
		if ( empty( $article_id ) ) {
			if ( WP_DEBUG ) {
				error_log( '❌ AJAX_IMPORT_ARTICLES_PAGE: No article_id provided' );
			}
			wp_send_json_error( array( 'message' => __( 'Article ID required', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		if ( WP_DEBUG ) {
			error_log( 'AJAX_IMPORT_ARTICLES_PAGE: Processing article_id: ' . $article_id );
		}

		if ( ! $this->api_client ) {
			wp_send_json_error( array( 'message' => __( 'API client not configured', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		// CRITICAL: Check if article already imported (prevent duplicates)
		global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct query more efficient than get_posts() with meta_query for simple existence check
		$existing_post_id = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT post_id FROM {$wpdb->postmeta}
             WHERE meta_key = '_wisewand_external_id'
             AND meta_value = %s
             LIMIT 1",
				$article_id
			)
		);

		if ( $existing_post_id ) {
			$existing_post = get_post( $existing_post_id );
			if ( $existing_post && $existing_post->post_status !== 'trash' ) {
				// Already imported! Return existing post info instead of importing again
				if ( WP_DEBUG ) {
					error_log( 'IMPORT: Article ' . $article_id . ' already imported as post ' . $existing_post_id . ', returning existing' );
				}

				wp_send_json_success(
					array(
						'post_id'   => $existing_post->ID,
						'edit_url'  => admin_url( 'post.php?post=' . $existing_post->ID . '&action=edit' ),
						'operation' => 'already_imported',
						'message'   => __( 'This article was already imported. Showing existing post.', 'wisewand-ai-content-writer-seo-content-generator' ),
						'warnings'  => array(),
					)
				);
				return;
			}
		}

		if ( WP_DEBUG ) {
			error_log( 'IMPORT: Article ' . $article_id . ' not yet imported, proceeding...' );
		}

		// Get content type and fetch appropriate output
		$content_type   = isset( $_POST['content_type'] ) ? sanitize_text_field( wp_unslash( $_POST['content_type'] ) ) : 'articles';

		if ( WP_DEBUG ) {
			error_log( 'AJAX_IMPORT_ARTICLES_PAGE: Fetching content from API - article_id: ' . $article_id . ', type: ' . $content_type );
		}

		$content_output = $this->api_client->get_content_output( $article_id, $content_type );

		if ( is_wp_error( $content_output ) ) {
			if ( WP_DEBUG ) {
				error_log( '❌ AJAX_IMPORT_ARTICLES_PAGE: API fetch failed: ' . $content_output->get_error_message() );
			}
			wp_send_json_error( array( 'message' => esc_html( $content_output->get_error_message() ) ) );
		}

		if ( WP_DEBUG ) {
			error_log( '✅ AJAX_IMPORT_ARTICLES_PAGE: API fetch successful' );
		}

		// Import the article using existing content manager
		$plugin          = \Wisewand\Core\Plugin::instance();
		$content_manager = $plugin->get_content_manager();

		if ( ! $content_manager ) {
			wp_send_json_error( array( 'message' => __( 'Content manager not available', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		// Transform API data to internal format
		$import_data = $this->transform_api_data_for_import( $content_output, $content_type );

		// Apply user preferences from the interface
		$language_override = isset( $_POST['language_override'] ) ? sanitize_text_field( wp_unslash( $_POST['language_override'] ) ) : '';
		$target_post_type  = isset( $_POST['post_type'] ) ? sanitize_text_field( wp_unslash( $_POST['post_type'] ) ) : '';
		$publish_state     = isset( $_POST['publish_state'] ) ? sanitize_text_field( wp_unslash( $_POST['publish_state'] ) ) : '';
		$publish_date      = isset( $_POST['publish_date'] ) ? sanitize_text_field( wp_unslash( $_POST['publish_date'] ) ) : '';
		$existing_product  = isset( $_POST['existing_product'] ) ? absint( wp_unslash( $_POST['existing_product'] ) ) : 0;
		$existing_category = isset( $_POST['existing_category'] ) ? sanitize_text_field( wp_unslash( $_POST['existing_category'] ) ) : '';
		$post_author       = isset( $_POST['post_author'] ) ? absint( wp_unslash( $_POST['post_author'] ) ) : 0;
		$post_categories   = isset( $_POST['post_categories'] ) ? array_map( 'absint', map_deep( wp_unslash( $_POST['post_categories'] ), 'sanitize_text_field' ) ) : array();

		if ( ! empty( $language_override ) ) {
			$import_data['wpml_language_override'] = $language_override;
		}

		if ( ! empty( $target_post_type ) ) {
			$import_data['target_post_type'] = $target_post_type;
		}

		if ( ! empty( $publish_state ) ) {
			$import_data['post_status'] = $publish_state;
		}

		if ( ! empty( $publish_date ) && $publish_state === 'future' ) {
			$import_data['post_date'] = $publish_date;
		}

		// Handle existing content updates
		if ( $existing_product > 0 ) {
			$import_data['update_existing_product'] = $existing_product;
		}

		if ( ! empty( $existing_category ) ) {
			$import_data['update_existing_category'] = $existing_category;
		}

		// Set author - use 'author_id' key that Content_Manager expects
		if ( $post_author > 0 ) {
			$import_data['author_id'] = $post_author;
		}

		// Set categories - use 'categories' key that Content_Manager expects
		if ( ! empty( $post_categories ) ) {
			$import_data['categories'] = $post_categories;
		}

		$this->logger->info(
			'Importing with user preferences',
			array(
				'article_id'        => $article_id,
				'content_type'      => $content_type,
				'language_override' => $language_override,
				'target_post_type'  => $target_post_type,
				'publish_state'     => $publish_state,
				'publish_date'      => $publish_date,
				'existing_product'  => $existing_product,
				'existing_category' => $existing_category,
				'post_author'       => $post_author,
				'post_categories'   => $post_categories,
			)
		);

		// CRITICAL: Wrap in try/catch to prevent 500 errors from uncaught exceptions
		try {
			// Increase timeout for complex imports (multiple images, OpenAI metadata, etc.)
			// User requirement: Must upload ALL images without timeout
			// phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- Required for complex article imports with multiple images and metadata
			@set_time_limit( 300 ); // 5 minutes for complex imports

			$result = $content_manager->process_content( $import_data );

			if ( is_wp_error( $result ) ) {
				wp_send_json_error( array( 'message' => esc_html( $result->get_error_message() ) ) );
				return;
			}

			// Handle different result types (posts vs categories)
			$response_data = array(
				'operation' => $result['operation'],
				'warnings'  => $result['warnings'] ?? array(),
			);

			if ( isset( $result['post_id'] ) && $result['post_id'] ) {
				// Regular post/page/product
				$response_data['post_id']  = $result['post_id'];
				$response_data['edit_url'] = admin_url( 'post.php?post=' . $result['post_id'] . '&action=edit' );
			} elseif ( isset( $result['category_id'] ) && $result['category_id'] ) {
				// Category/taxonomy
				$response_data['category_id'] = $result['category_id'];
				$taxonomy                     = $result['taxonomy'] ?? 'category';
				$response_data['edit_url']    = admin_url( 'term.php?taxonomy=' . $taxonomy . '&tag_ID=' . $result['category_id'] );
				$response_data['taxonomy']    = $taxonomy;
			}

			wp_send_json_success( $response_data );

		} catch ( \Exception $e ) {
			// Catch exceptions and return proper JSON error (prevents 500 errors)
			$this->logger->error(
				'Import exception caught',
				array(
					'article_id' => $article_id,
					'error'      => $e->getMessage(),
					'file'       => $e->getFile(),
					'line'       => $e->getLine(),
					'trace'      => $e->getTraceAsString(),
				)
			);

			wp_send_json_error(
				array(
					'message'       => sprintf(
						/* translators: 1: Error message, 2: File basename, 3: Line number */
						__( 'Import failed: %1$s (in %2$s at line %3$d)', 'wisewand-ai-content-writer-seo-content-generator' ),
						$e->getMessage(),
						basename( $e->getFile() ),
						$e->getLine()
					),
					'error_type'    => 'exception',
					'error_details' => WP_DEBUG ? $e->getTraceAsString() : null,
				)
			);

		} catch ( \Error $e ) {
			// Catch PHP 7+ fatal errors (memory exhaustion, timeout, type errors, etc.)
			$this->logger->error(
				'Import fatal error caught',
				array(
					'article_id' => $article_id,
					'error'      => $e->getMessage(),
					'type'       => get_class( $e ),
				)
			);

			wp_send_json_error(
				array(
					'message'            => __( 'Import failed: Critical server error. This is typically caused by insufficient memory, execution timeout, or server misconfiguration. Please check PHP error logs or contact your hosting provider.', 'wisewand-ai-content-writer-seo-content-generator' ),
					'error_type'         => 'fatal_error',
					'error_class'        => get_class( $e ),
					'recommended_action' => __( 'Check Settings → Server Requirements for diagnostic information', 'wisewand-ai-content-writer-seo-content-generator' ),
				)
			);
		}
	}

	public function ajax_run_generation() {
		check_ajax_referer( 'wisewand_run_generation', 'nonce' );

		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$article_id = isset( $_POST['article_id'] ) ? sanitize_text_field( wp_unslash( $_POST['article_id'] ) ) : '';
		if ( empty( $article_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Article ID required', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		if ( ! $this->api_client ) {
			wp_send_json_error( array( 'message' => __( 'API client not configured', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		// Get content type (default to 'articles' for backwards compatibility)
		$content_type = isset( $_POST['content_type'] ) ? sanitize_text_field( wp_unslash( $_POST['content_type'] ) ) : 'articles';

		// Run generation using generic method that supports all content types
		$result = $this->api_client->run_content_generation( $content_type, $article_id );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => esc_html( $result->get_error_message() ) ) );
		}

		wp_send_json_success(
			array(
				'message'    => __( 'Content generation started successfully', 'wisewand-ai-content-writer-seo-content-generator' ),
				'article_id' => $article_id,
			)
		);
	}

	public function ajax_bulk_import() {
		check_ajax_referer( 'wisewand_bulk_action', 'nonce' );

		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$article_ids = isset( $_POST['article_ids'] ) ? array_map( 'sanitize_text_field', map_deep( wp_unslash( $_POST['article_ids'] ), 'sanitize_text_field' ) ) : array();
		if ( empty( $article_ids ) || ! is_array( $article_ids ) ) {
			wp_send_json_error( array( 'message' => __( 'No articles selected', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		if ( ! $this->api_client ) {
			wp_send_json_error( array( 'message' => __( 'API client not configured', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$imported = 0;
		$errors   = array();
		$warnings = array();

		// Increase timeout for bulk operations
		// phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- Required for bulk article import operations
		@set_time_limit( 600 ); // 10 minutes for bulk imports

		foreach ( $article_ids as $article_id ) {
			$article_id = sanitize_text_field( $article_id );

			// Wrap each import in try/catch to prevent one failure from breaking the batch
			try {
				// Get article output
				$article_output = $this->api_client->get_article_output( $article_id );

				if ( is_wp_error( $article_output ) ) {
					$errors[] = sprintf(
						/* translators: 1: Article ID, 2: Error message */
						__( 'Article %1$s: %2$s', 'wisewand-ai-content-writer-seo-content-generator' ),
						$article_id,
						$article_output->get_error_message()
					);
					continue;
				}

				// Check if article is ready
				if ( ! $this->api_client->is_article_ready( $article_output ) ) {
					$warnings[] = sprintf(
						/* translators: 1: Article ID, 2: Article status */
						__( 'Article %1$s is not ready for import (status: %2$s)', 'wisewand-ai-content-writer-seo-content-generator' ),
						$article_id,
						$article_output['status'] ?? 'unknown'
					);
					continue;
				}

				// Import the article
				$plugin          = \Wisewand\Core\Plugin::instance();
				$content_manager = $plugin->get_content_manager();

				if ( ! $content_manager ) {
					/* translators: %s: Article ID */
					$errors[] = sprintf( __( 'Content manager not available for article %s', 'wisewand-ai-content-writer-seo-content-generator' ), $article_id );
					continue;
				}

				$import_data = $this->transform_api_data_for_import( $article_output );

				// Apply stored user preferences for bulk import
				$import_data = $this->apply_stored_preferences( $import_data, $article_id );

				$result = $content_manager->process_content( $import_data );

				if ( is_wp_error( $result ) ) {
					$errors[] = sprintf(
						/* translators: 1: Article ID, 2: Error message */
						__( 'Article %1$s: %2$s', 'wisewand-ai-content-writer-seo-content-generator' ),
						$article_id,
						$result->get_error_message()
					);
					continue;
				}

				++$imported;

			} catch ( \Exception $e ) {
				$errors[] = sprintf(
					/* translators: 1: Article ID, 2: Error message */
					__( 'Article %1$s: Exception - %2$s', 'wisewand-ai-content-writer-seo-content-generator' ),
					$article_id,
					$e->getMessage()
				);

				$this->logger->error(
					'Bulk import exception',
					array(
						'article_id' => $article_id,
						'error'      => $e->getMessage(),
					)
				);

				continue; // Continue with next article

			} catch ( \Error $e ) {
				/* translators: 1: Article ID */
				$errors[] = sprintf( __( 'Article %1$s: Fatal error - server resource issue', 'wisewand-ai-content-writer-seo-content-generator' ), $article_id );

				$this->logger->error(
					'Bulk import fatal error',
					array(
						'article_id' => $article_id,
						'error'      => $e->getMessage(),
					)
				);

				continue; // Continue with next article
			}
		}

		$response_data = array(
			'imported'        => $imported,
			'total_requested' => count( $article_ids ),
			'errors'          => $errors,
			'warnings'        => $warnings,
			/* translators: 1: Number of articles imported, 2: Total number of articles */
			'message'         => sprintf( __( '%1$d of %2$d articles imported successfully', 'wisewand-ai-content-writer-seo-content-generator' ), $imported, count( $article_ids ) ),
		);

		if ( $imported > 0 ) {
			wp_send_json_success( $response_data );
		} else {
			wp_send_json_error(
				array_merge(
					$response_data,
					array(
						'message' => __( 'No articles were imported successfully', 'wisewand-ai-content-writer-seo-content-generator' ),
					)
				)
			);
		}
	}

	public function ajax_bulk_generate() {
		check_ajax_referer( 'wisewand_bulk_action', 'nonce' );

		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$article_ids = isset( $_POST['article_ids'] ) ? array_map( 'sanitize_text_field', map_deep( wp_unslash( $_POST['article_ids'] ), 'sanitize_text_field' ) ) : array();
		if ( empty( $article_ids ) || ! is_array( $article_ids ) ) {
			wp_send_json_error( array( 'message' => __( 'No articles selected', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		if ( ! $this->api_client ) {
			wp_send_json_error( array( 'message' => __( 'API client not configured', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$started = 0;
		$errors  = array();

		foreach ( $article_ids as $article_id ) {
			$article_id = sanitize_text_field( $article_id );

			$result = $this->api_client->run_article_generation( $article_id );

			if ( is_wp_error( $result ) ) {
				$errors[] = sprintf(
					/* translators: 1: Article ID, 2: Error message */
					__( 'Article %1$s: %2$s', 'wisewand-ai-content-writer-seo-content-generator' ),
					$article_id,
					$result->get_error_message()
				);
				continue;
			}

			++$started;
		}

		$response_data = array(
			'started'         => $started,
			'total_requested' => count( $article_ids ),
			'errors'          => $errors,
			/* translators: 1: Number of article generations started, 2: Total number of articles */
			'message'         => sprintf( __( '%1$d of %2$d article generations started successfully', 'wisewand-ai-content-writer-seo-content-generator' ), $started, count( $article_ids ) ),
		);

		if ( $started > 0 ) {
			wp_send_json_success( $response_data );
		} else {
			wp_send_json_error(
				array_merge(
					$response_data,
					array(
						'message' => __( 'No article generations started successfully', 'wisewand-ai-content-writer-seo-content-generator' ),
					)
				)
			);
		}
	}

	public function ajax_test_import_workflow() {
		check_ajax_referer( 'wisewand_test_import', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$article_id = isset( $_POST['article_id'] ) ? sanitize_text_field( wp_unslash( $_POST['article_id'] ) ) : '';
		if ( empty( $article_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Article ID required', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		// Load Import_Enhancer
		if ( ! class_exists( 'Wisewand\\Utils\\Import_Enhancer' ) ) {
			$enhancer_file = WISEWAND_PLUGIN_DIR . 'includes/Utils/Import_Enhancer.php';
			if ( file_exists( $enhancer_file ) ) {
				require_once $enhancer_file;
			}
		}

		if ( ! class_exists( 'Wisewand\\Utils\\Import_Enhancer' ) ) {
			wp_send_json_error( array( 'message' => 'Import_Enhancer class not available' ) );
		}

		try {
			$test_result = \Wisewand\Utils\Import_Enhancer::test_import_enhancement( $article_id );

			if ( is_wp_error( $test_result ) ) {
				wp_send_json_error( array( 'message' => $test_result->get_error_message() ) );
			}

			wp_send_json_success( $test_result );

		} catch ( Exception $e ) {
			wp_send_json_error( array( 'message' => esc_html( 'Test failed: ' . $e->getMessage() ) ) );
		}
	}

	private function transform_api_data_for_import( $api_data, $content_type = 'articles' ) {
		// Transform Wisewand API data to format expected by Content_Manager
		$import_data = array(
			'external_id'         => $api_data['id'] ?? uniqid( 'wisewand_' ),
			'content_type_source' => $content_type, // Track source type
		);

		// Set WordPress post type based on content type
		switch ( $content_type ) {
			case 'categorypages':
				$import_data['post_type'] = 'page'; // Category pages as WordPress pages
				break;
			case 'productpages':
				$import_data['post_type'] = 'product'; // Try product post type, fallback to page
				if ( ! post_type_exists( 'product' ) ) {
					$import_data['post_type'] = 'page';
				}
				break;
			case 'articles':
			default:
				$import_data['post_type'] = 'post'; // Articles as posts
				break;
		}

		// Input data - check both locations
		$input = null;
		if ( isset( $api_data['data']['input'] ) ) {
			$input = $api_data['data']['input'];
		} elseif ( isset( $api_data['input'] ) ) {
			$input = $api_data['input'];
		}

		if ( $input ) {
			$import_data['post_type'] = 'post'; // Default
			$import_data['lang']      = $input['lang'] ?? 'fr';
			$import_data['country']   = $input['country'] ?? 'fr';

			// Handle translation linking
			if ( ! empty( $input['translate_of_external_id'] ) ) {
				$import_data['translate_of_external_id'] = $input['translate_of_external_id'];
			}

			// Store original input for reference
			$import_data['input'] = $input;
		}

		// Output data - check both locations
		$output = null;
		if ( isset( $api_data['data']['output'] ) ) {
			$output = $api_data['data']['output'];
		} elseif ( isset( $api_data['output'] ) ) {
			$output = $api_data['output'];
		}

		if ( $output ) {
			$import_data['title']   = $output['h1'] ?? $output['title'] ?? '';
			$import_data['content'] = $output['content'] ?? '';
			$import_data['excerpt'] = $output['meta_description'] ?? '';

			// Clean SEO data mapping from Wisewand
			$import_data['seo'] = array(
				'title'               => $output['meta_title'] ?? '',
				'description'         => $output['meta_description'] ?? '',
				'canonical_url'       => $output['url'] ?? '',
				'focus_keyword'       => ! empty( $input['target_keyword'] ) ? trim( $input['target_keyword'] ) : '', // ONLY target keyword
				'og_title'            => $output['meta_title'] ?? '',
				'og_description'      => $output['meta_description'] ?? '',
				'twitter_title'       => $output['meta_title'] ?? '',
				'twitter_description' => $output['meta_description'] ?? '',
			);

			// Store secondary keywords separately (don't mix with focus)
			if ( ! empty( $input['keywords_secondary'] ) ) {
				$import_data['secondary_keywords'] = $input['keywords_secondary'];
			}

			// Media - comprehensive handling
			if ( ! empty( $output['cover_image'] ) ) {
				$import_data['featured_image_url'] = $output['cover_image'];
				// Also use for social sharing
				$import_data['seo']['og_image']      = $output['cover_image'];
				$import_data['seo']['twitter_image'] = $output['cover_image'];
			}

			if ( ! empty( $output['cover_images'] ) && is_array( $output['cover_images'] ) ) {
				$import_data['cover_images'] = $output['cover_images'];
			}

			if ( ! empty( $output['audio'] ) ) {
				$import_data['audio'] = $output['audio'];
			}

			// WordPress publishing data
			if ( isset( $output['publishwordpress_status'] ) ) {
				$import_data['post_status'] = $output['publishwordpress_status'];
			}

			if ( isset( $output['publishwordpress_category'] ) ) {
				if ( $output['publishwordpress_category'] > 0 ) {
					$import_data['categories'] = array( $output['publishwordpress_category'] );
				} elseif ( $output['publishwordpress_category'] === -2 ) {
					// Auto-category assignment - let WordPress handle it
					$import_data['auto_assign_category'] = true;
				}
			}

			if ( isset( $output['publishwordpress_author'] ) && $output['publishwordpress_author'] > 0 ) {
				$import_data['author_id'] = $output['publishwordpress_author'];
			}

			// Handle scheduled publishing
			if ( isset( $output['publishwordpress_date'] ) ) {
				$import_data['post_date'] = $output['publishwordpress_date'];
			}

			// Store full output for reference
			$import_data['output'] = $output;
		}

		// Additional top-level fields
		if ( isset( $api_data['cover_image'] ) ) {
			$import_data['featured_image_url'] = $api_data['cover_image'];
		}

		if ( isset( $api_data['title'] ) ) {
			$import_data['title'] = $import_data['title'] ?: $api_data['title'];
		}

		return $import_data;
	}

	/**
	 * Apply stored user preferences for language, publish state, and date
	 * Used for bulk imports to respect user interface selections
	 */
	private function apply_stored_preferences( $import_data, $article_id ) {
		// Note: For bulk operations, we can't access localStorage from PHP
		// Instead, we'll use the default settings or let the user override individual articles

		// Apply default publish state from settings
		$default_status = $this->options->get( 'wisewand_default_post_status', 'draft' );
		if ( empty( $import_data['post_status'] ) ) {
			$import_data['post_status'] = $default_status;
		}

		return $import_data;
	}

	private function get_wisewand_url( $article ) {
		$base_url     = 'https://app.wisewand.ai';
		$content_type = $article['content_type'] ?? 'articles';

		switch ( $content_type ) {
			case 'categorypages':
				return $base_url . '/categorypages/' . $article['id'];
			case 'productpages':
				return $base_url . '/productpages/' . $article['id'];
			case 'articles':
			default:
				return $base_url . '/articles/' . $article['id'];
		}
	}

	private function get_content_type_label( $content_type ) {
		$labels = array(
			'articles'         => __( 'Article', 'wisewand-ai-content-writer-seo-content-generator' ),
			'categorypages'    => __( 'Category Page', 'wisewand-ai-content-writer-seo-content-generator' ),
			'productpages'     => __( 'Product Page', 'wisewand-ai-content-writer-seo-content-generator' ),
			'discoverarticles' => __( 'Google Discover Article', 'wisewand-ai-content-writer-seo-content-generator' ),
		);

		return $labels[ $content_type ] ?? ucfirst( $content_type );
	}

	private function get_page_title( $content_type ) {
		$titles = array(
			'articles'         => __( 'Wisewand Articles', 'wisewand-ai-content-writer-seo-content-generator' ),
			'categorypages'    => __( 'Wisewand Category Pages', 'wisewand-ai-content-writer-seo-content-generator' ),
			'productpages'     => __( 'Wisewand Product Pages', 'wisewand-ai-content-writer-seo-content-generator' ),
			'discoverarticles' => __( 'Wisewand Google Discover Articles', 'wisewand-ai-content-writer-seo-content-generator' ),
		);

		return $titles[ $content_type ] ?? __( 'Wisewand Content', 'wisewand-ai-content-writer-seo-content-generator' );
	}

	private function has_multilingual_support() {
		// Load Plugin_Detector if not already loaded
		if ( ! class_exists( 'Wisewand\\Utils\\Plugin_Detector' ) ) {
			$detector_file = WISEWAND_PLUGIN_DIR . 'includes/Utils/Plugin_Detector.php';
			if ( file_exists( $detector_file ) ) {
				require_once $detector_file;
			}
		}

		if ( class_exists( 'Wisewand\\Utils\\Plugin_Detector' ) ) {
			return \Wisewand\Utils\Plugin_Detector::has_multilingual_support();
		}

		// Fallback to options method
		return $this->options->is_wpml_active() || $this->options->is_polylang_active();
	}

	private function has_seo_support() {
		// Load Plugin_Detector if not already loaded
		if ( ! class_exists( 'Wisewand\\Utils\\Plugin_Detector' ) ) {
			$detector_file = WISEWAND_PLUGIN_DIR . 'includes/Utils/Plugin_Detector.php';
			if ( file_exists( $detector_file ) ) {
				require_once $detector_file;
			}
		}

		if ( class_exists( 'Wisewand\\Utils\\Plugin_Detector' ) ) {
			return \Wisewand\Utils\Plugin_Detector::has_seo_support();
		}

		// Fallback to options method
		return $this->options->is_yoast_active() || $this->options->is_rankmath_active();
	}

	private function get_table_colspan() {
		$base_columns = 8; // Title, Status, Author, Categories, Post Type, Publish State, Publish Date, Import

		if ( $this->has_multilingual_support() ) {
			++$base_columns; // Add Language column
		}

		return $base_columns;
	}

	private function is_woocommerce_active() {
		// Load Plugin_Detector if not already loaded
		if ( ! class_exists( 'Wisewand\\Utils\\Plugin_Detector' ) ) {
			$detector_file = WISEWAND_PLUGIN_DIR . 'includes/Utils/Plugin_Detector.php';
			if ( file_exists( $detector_file ) ) {
				require_once $detector_file;
			}
		}

		if ( class_exists( 'Wisewand\\Utils\\Plugin_Detector' ) ) {
			$woo_info = \Wisewand\Utils\Plugin_Detector::detect_woocommerce();
			return $woo_info['active'];
		}

		return class_exists( 'WooCommerce' );
	}
}
