<?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\Logging\Logger;
use Wisewand\Utils\Wisewand_Payload_Builder;
use Wisewand\Calendar\Calendar_Entry_Manager;

// phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r -- error_log() and print_r() are only used within WP_DEBUG conditionals for debugging

class Editorial_Calendar {

	private $options;
	private $logger;
	private $payload_builder;
	private $entry_manager;

	/**
	 * Debug info for last error (used in exception handling)
	 *
	 * @var array|null
	 */
	private $_last_error_debug = null;

	public function __construct( Options $options, Logger $logger ) {
		$this->options = $options;
		$this->logger  = $logger;

		$this->payload_builder = new Wisewand_Payload_Builder( $options, $logger );

		if ( ! class_exists( 'Wisewand\\Calendar\\Calendar_Entry_Manager' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Calendar/Calendar_Entry_Manager.php';
		}

		if ( ! class_exists( 'Wisewand\\Repositories\\Calendar_Repository' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Repositories/Calendar_Repository.php';
		}

		$calendar_repository = new \Wisewand\Repositories\Calendar_Repository();
		$this->entry_manager = new \Wisewand\Calendar\Calendar_Entry_Manager( $options, $logger, $this->payload_builder, $calendar_repository );
	}

	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' ) );
		}

		$stats = $this->entry_manager->get_statistics();

		echo '<div class="wrap editorial-calendar-page">';

		$this->render_header( $stats );
		$this->render_calendar_container();
		$this->render_side_panel();
		$this->enqueue_assets();

		echo '</div>';
	}

	private function render_header( $stats ) {
		?>
		<div class="calendar-page-header">
			<div>
				<h1>📅 <?php esc_html_e( 'Editorial Calendar', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h1>
				<p><?php esc_html_e( 'Manage your automated content publication roadmap', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
			</div>
			<div class="header-stats">
				<div class="stat-item">
					<div class="stat-value"><?php echo esc_html( $stats['total_scheduled'] ?? 0 ); ?></div>
					<div class="stat-label"><?php esc_html_e( 'Total Scheduled', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
				</div>
				<div class="stat-item">
					<div class="stat-value"><?php echo esc_html( $stats['upcoming_7_days'] ?? 0 ); ?></div>
					<div class="stat-label"><?php esc_html_e( 'Next 7 Days', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
				</div>
				<div class="stat-item">
					<div class="stat-value"><?php echo esc_html( $stats['by_wisewand_status']['ready'] ?? 0 ); ?></div>
					<div class="stat-label"><?php esc_html_e( 'Ready to Publish', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
				</div>
			</div>
		</div>
		<?php
	}

	private function render_calendar_container() {
		?>
		<div class="calendar-main">
			<div class="calendar-toolbar">
				<div class="toolbar-left">
					<button type="button" id="clear-calendar-editorial" class="btn-clear-calendar" style="background: #EF4444; color: white;">
						🗑️ <?php esc_html_e( 'Clear All Scheduled', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</button>
					<select id="source-filter" class="source-filter-dropdown" style="margin-left: 12px; padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 14px; background: white; cursor: pointer;">
						<option value="all"><?php esc_html_e( '📋 All Sources', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<option value="manual"><?php esc_html_e( '✏️ Manual', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<option value="discovery"><?php esc_html_e( '🔍 Discovery', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						<option value="rss"><?php esc_html_e( '📡 RSS Feeds', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
					</select>
				</div>
				<div class="calendar-views">
					<button type="button" class="view-btn active" data-view="dayGridMonth">
						<?php esc_html_e( 'Month', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</button>
					<button type="button" class="view-btn" data-view="timeGridWeek">
						<?php esc_html_e( 'Week', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</button>
					<button type="button" class="view-btn" data-view="listMonth">
						<?php esc_html_e( 'List', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</button>
				</div>
			</div>

			<div id="editorial-calendar"></div>

			<div class="calendar-legend">
				<span class="legend-item"><span class="legend-color" style="background: #3b82f6;"></span> <?php esc_html_e( 'Scheduled', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
				<span class="legend-item"><span class="legend-color" style="background: #f59e0b;"></span> <?php esc_html_e( 'Generating', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
				<span class="legend-item"><span class="legend-color" style="background: #8b5cf6;"></span> <?php esc_html_e( 'Ready', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
				<span class="legend-item"><span class="legend-color" style="background: #10b981;"></span> <?php esc_html_e( 'Imported', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
				<span class="legend-item"><span class="legend-color" style="background: #ef4444;"></span> <?php esc_html_e( 'Failed', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
			</div>
		</div>
		<?php
	}

	private function render_side_panel() {
		?>
		<div id="entry-side-panel" class="side-panel" style="display: none;">
			<div class="panel-overlay"></div>
			<div class="panel-content">
				<div class="panel-header">
					<h2 id="panel-title">📝 <?php esc_html_e( 'Edit Publication', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
					<button type="button" class="close-panel">×</button>
				</div>
				<div class="panel-body" id="panel-body">
					<div class="loading-spinner">Loading...</div>
				</div>
			</div>
		</div>
		<?php
	}

	private function enqueue_assets() {
		// IMPORTANT: WordPress.org requires bundling external libraries locally
		// FullCalendar files are located in assets/vendor/fullcalendar/
		wp_enqueue_style(
			'fullcalendar',
			WISEWAND_PLUGIN_URL . 'assets/vendor/fullcalendar/fullcalendar.min.css',
			array(),
			'6.1.19'
		);

		wp_enqueue_script(
			'fullcalendar',
			WISEWAND_PLUGIN_URL . 'assets/vendor/fullcalendar/fullcalendar.min.js',
			array(),
			'6.1.19',
			true
		);

		$this->render_custom_assets();
	}

	private function render_custom_assets() {
		wp_enqueue_style(
			'wisewand-editorial-calendar-admin',
			WISEWAND_PLUGIN_URL . 'assets/css/admin/wisewand-editorial-calendar-admin.css',
			array(),
			WISEWAND_PLUGIN_VERSION
		);

		wp_enqueue_script(
			'wisewand-editorial-calendar-admin',
			WISEWAND_PLUGIN_URL . 'assets/js/admin/wisewand-editorial-calendar-admin.js',
			array( 'jquery', 'fullcalendar' ),
			WISEWAND_PLUGIN_VERSION,
			true
		);

		wp_localize_script(
			'wisewand-editorial-calendar-admin',
			'wisewandCalendar',
			array(
				'ajaxUrl'  => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'wisewand_calendar' ),
				'seoNonce' => wp_create_nonce( 'wisewand_seo_real' ),
			)
		);
	}

	// AJAX Handler - Get Calendar Events
	public function ajax_get_calendar_events() {
		check_ajax_referer( 'wisewand_calendar', 'nonce' );

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

		$start_date    = isset( $_POST['start_date'] ) ? sanitize_text_field( wp_unslash( $_POST['start_date'] ) ) : '';
		$end_date      = isset( $_POST['end_date'] ) ? sanitize_text_field( wp_unslash( $_POST['end_date'] ) ) : '';
		$source_filter = isset( $_POST['source_filter'] ) ? sanitize_text_field( wp_unslash( $_POST['source_filter'] ) ) : 'all';

		try {
			$filters = array(
				'publication_date_start' => $start_date,
				'publication_date_end'   => $end_date,
			);

			// Add keyword_source filter if not "all"
			if ( $source_filter !== 'all' ) {
				$filters['keyword_source'] = $source_filter;
			}

			$entries = $this->entry_manager->get_entries( $filters );

			$events = $this->transform_entries_to_fullcalendar_events( $entries );

			wp_send_json_success( array( 'events' => $events ) );

		} catch ( \Exception $e ) {
			$this->logger->error( 'Failed to load calendar events', array( 'error' => $e->getMessage() ) );
			wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
		}
	}

	private function transform_entries_to_fullcalendar_events( $entries ) {
		$events = array();

		foreach ( $entries as $entry ) {
			$color = $this->get_event_color( $entry );
			$title = $entry['keyword'];

			// Add status indicator
			if ( in_array( $entry['wordpress_status'], array( 'imported_draft', 'imported_published' ) ) ) {
				$title = '🟢 ' . $title; // Green for imported (success)
			} elseif ( $entry['wisewand_status'] === 'ready' ) {
				$title = '🟣 ' . $title; // Purple for ready
			} elseif ( $entry['wisewand_status'] === 'generating' ) {
				$title = '🟡 ' . $title; // Yellow for generating
			} elseif ( $entry['wisewand_status'] === 'failed' || $entry['wordpress_status'] === 'failed' ) {
				$title = '🔴 ' . $title; // Red for failed
			}

			/**
			 * Display publication time inline with article title
			 *
			 * Format: [emoji] [time] Article Title
			 * Time format respects WordPress Settings > General > Time Format.
			 * Time is displayed inline to save vertical space in calendar view.
			 *
			 * @since 1.0.0 Changed from multi-line to inline format, added wp_date() for timezone support
			 */
			// Add scheduled time info inline (for all entries, regardless of status)
			if ( ! empty( $entry['publication_time'] ) ) {
				// Show exact time - respects WordPress timezone and format settings
				$time_format    = get_option( 'time_format', 'g:i A' );
				$timestamp      = strtotime( $entry['publication_time'] );
				if ( false !== $timestamp ) {
					// v1.2.7: Use date() not wp_date() - publication_time already in local timezone
					// phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- Intentional: displaying already-local times from database
				$formatted_time = date( $time_format, $timestamp );
					if ( false !== $formatted_time ) {
						// Prepend time to beginning of title instead of appending
					$title = $formatted_time . ' ' . $title;
					}
				}
			}

		// Build class names for CSS targeting
		$class_names = array();
		if ( isset( $entry['keyword_source'] ) ) {
			$class_names[] = 'event-' . $entry['keyword_source'];
		}

		$events[] = array(
			'id'              => $entry['id'],
			'title'           => $title,
			'start'           => $entry['publication_date'],
			'backgroundColor' => $color,
			'borderColor'     => $color,
			'classNames'      => $class_names,
			'extendedProps'   => array(
				'keyword'                => $entry['keyword'],
				'wisewand_status'        => $entry['wisewand_status'],
				'wordpress_status'       => $entry['wordpress_status'],
				'search_volume'          => $entry['search_volume'],
				'current_position'       => $entry['current_position'],
				'publication_time'       => $entry['publication_time'] ?? null,
				'publication_time_range' => $entry['publication_time_range'] ?? 'random',
				'keyword_source'         => $entry['keyword_source'] ?? 'manual',
				'source_metadata'        => $entry['source_metadata'] ?? null,
				'rss_article_id'         => $entry['rss_article_id'] ?? null,
				'rss_feed_id'            => $entry['rss_feed_id'] ?? null,
			),
		);
		}

		return $events;
	}

	private function get_event_color( $entry ) {
		// RSS entries - use feed_color from source_metadata (green #10b981)
		if ( isset( $entry['keyword_source'] ) && $entry['keyword_source'] === 'rss' ) {
			if ( ! empty( $entry['source_metadata'] ) ) {
				$metadata = json_decode( $entry['source_metadata'], true );
				if ( isset( $metadata['feed_color'] ) ) {
					return $metadata['feed_color']; // Custom feed color (default: #10b981)
				}
			}
			return '#10b981'; // Default green for RSS entries
		}

		// Imported statuses (green - success state)
		if ( in_array( $entry['wordpress_status'], array( 'imported_draft', 'imported_published' ) ) ) {
			return '#10b981'; // Green
		}

		// Failed status (red)
		if ( $entry['wisewand_status'] === 'failed' || $entry['wordpress_status'] === 'failed' ) {
			return '#ef4444'; // Red
		}

		// Ready status (purple - distinct from generating)
		if ( $entry['wisewand_status'] === 'ready' ) {
			return '#8b5cf6'; // Purple
		}

		// Generating status (amber)
		if ( $entry['wisewand_status'] === 'generating' ) {
			return '#f59e0b'; // Amber
		}

		// Importing status (yellow)
		if ( $entry['wordpress_status'] === 'importing' ) {
			return '#eab308'; // Yellow
		}

		// Default: Scheduled (blue)
		return '#3b82f6'; // Blue
	}

	// AJAX Handler - Update Entry Date (from drag & drop)
	public function ajax_update_entry_gmdate() {
		check_ajax_referer( 'wisewand_calendar', 'nonce' );

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

		$entry_id = absint( $_POST['entry_id'] ?? 0 );
		$new_date = isset( $_POST['new_date'] ) ? sanitize_text_field( wp_unslash( $_POST['new_date'] ) ) : '';

		if ( ! $entry_id || ! $new_date ) {
			wp_send_json_error( array( 'message' => __( 'Invalid parameters', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		try {
			$result = $this->entry_manager->update_entry(
				$entry_id,
				array(
					'publication_date' => $new_date,
				)
			);

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			wp_send_json_success( array( 'message' => __( 'Date updated', 'wisewand-ai-content-writer-seo-content-generator' ) ) );

		} catch ( \Exception $e ) {
			wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
		}
	}

	// AJAX Handler - Get Entry Details for Side Panel
	public function ajax_get_entry_details() {
		check_ajax_referer( 'wisewand_calendar', 'nonce' );

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

		$entry_id = absint( $_POST['entry_id'] ?? 0 );

		if ( ! $entry_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid entry ID', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		try {
			$entry = $this->entry_manager->get_entry( $entry_id );

			if ( is_wp_error( $entry ) ) {
				throw new \Exception( $entry->get_error_message() );
			}

			$html = $this->render_entry_panel_form( $entry );

			wp_send_json_success(
				array(
					'html'  => $html,
					'entry' => $entry,
				)
			);

		} catch ( \Exception $e ) {
			wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
		}
	}

	private function render_entry_panel_form( $entry ) {
		$payload       = $entry['wisewand_payload_decoded'] ?? array();
		$related_pages = $this->find_related_pages( $entry['keyword'] );

		ob_start();
		?>
		<div class="panel-form">
			<input type="hidden" id="entry-id" value="<?php echo esc_attr( $entry['id'] ); ?>">

			<?php if ( isset( $entry['keyword_source'] ) && $entry['keyword_source'] === 'rss' ) : ?>
				<!-- RSS Entry Warning Banner -->
				<div style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); border: 2px solid #10b981; border-radius: 12px; padding: 16px; margin-bottom: 16px; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);">
					<div style="display: flex; align-items: center; gap: 12px; color: white;">
						<div style="font-size: 32px;">📡</div>
						<div style="flex: 1;">
							<div style="font-size: 14px; font-weight: 600; margin-bottom: 4px;">
								<?php esc_html_e( 'RSS Feed Entry', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</div>
							<div style="font-size: 12px; opacity: 0.9; margin-bottom: 4px;">
								<?php
								if ( ! empty( $entry['source_metadata'] ) ) {
									$metadata = json_decode( $entry['source_metadata'], true );
									if ( isset( $metadata['feed_name'] ) ) {
										/* translators: %s: RSS feed name */
										echo esc_html( sprintf( __( 'Source: %s', 'wisewand-ai-content-writer-seo-content-generator' ), $metadata['feed_name'] ) );
									}
								}
								?>
							</div>
							<div style="font-size: 11px; opacity: 0.8; background: rgba(255,255,255,0.15); padding: 6px 10px; border-radius: 6px; margin-top: 6px;">
								ℹ️ <?php esc_html_e( 'Limited editing: Only publication date/time and WordPress settings can be modified.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</div>
						</div>
					</div>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( $entry['wisewand_article_id'] ) ) : ?>
				<!-- Wisewand Article Link -->
				<div style="background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%); border: 2px solid #3b82f6; border-radius: 12px; padding: 16px; margin-bottom: 16px; box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);">
					<div style="display: flex; align-items: center; gap: 12px; color: white;">
						<div style="font-size: 32px;">
							<?php
							// Icon based on status
							if ( $entry['wisewand_status'] === 'ready' ) {
								echo esc_html( '✅' );
							} elseif ( in_array( $entry['wisewand_status'], array( 'creating', 'generating' ) ) ) {
								echo esc_html( '🔄' );
							} elseif ( $entry['wisewand_status'] === 'failed' ) {
								echo esc_html( '❌' );
							} else {
								echo esc_html( '🔗' );
							}
							?>
						</div>
						<div style="flex: 1;">
							<div style="font-size: 14px; font-weight: 600; margin-bottom: 4px;">
								Wisewand Article: <?php echo esc_html( $entry['wisewand_article_id'] ); ?>
							</div>
							<div style="font-size: 12px; opacity: 0.9; margin-bottom: 4px;">
								Status: <strong><?php echo esc_html( ucfirst( $entry['wisewand_status'] ) ); ?></strong>
							</div>
							<?php if ( $entry['wisewand_status'] === 'ready' ) : ?>
								<div style="font-size: 12px; opacity: 0.9; background: rgba(255,255,255,0.15); padding: 6px 10px; border-radius: 6px; margin-top: 6px;">
									<?php echo esc_html( '📅' ); ?> <strong>Scheduled Import:</strong><br>
									<?php echo esc_html( gmdate( 'F j, Y', strtotime( $entry['publication_date'] ) ) ); ?> at
									<?php
									$time_range  = $entry['publication_time_range'] ?? 'random';
									$time_labels = array(
										'random'    => '9 AM - 8 PM',
										'morning'   => '9 AM - 12 PM',
										'afternoon' => '12 PM - 5 PM',
										'evening'   => '5 PM - 8 PM',
									);
									echo esc_html( $time_labels[ $time_range ] ?? '9 AM - 8 PM' );
									?>
									<?php if ( ! empty( $entry['publication_time'] ) ) : ?>
										<?php // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- Intentional: displaying already-local times from database ?>
										<br><small>(Exact: <?php echo esc_html( date( 'g:i A', strtotime( $entry['publication_time'] ) ) ); ?>)</small>
									<?php endif; ?>
								</div>
							<?php endif; ?>
						</div>
						<a href="https://app.wisewand.ai/articles/<?php echo esc_attr( $entry['wisewand_article_id'] ); ?>" target="_blank" class="button" style="background: white; color: #3b82f6; border: none; font-weight: 600;">
							🔗 <?php esc_html_e( 'View on Wisewand', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</a>
					</div>
					<?php if ( $entry['wisewand_status'] === 'ready' && empty( $entry['wordpress_post_id'] ) ) : ?>
						<!-- Import Now Button -->
						<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(255,255,255,0.2);">
							<button type="button" id="import-now-btn" class="button" style="width: 100%; background: #10b981; color: white; border: none; font-weight: 600; padding: 10px; font-size: 14px; cursor: pointer;">
								📥 <?php esc_html_e( 'Import Now to WordPress', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</button>
						</div>
					<?php endif; ?>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( $entry['wordpress_post_id'] ) && in_array( $entry['wordpress_status'], array( 'imported_draft', 'imported_published' ) ) ) : ?>
				<!-- Article Imported - WordPress Post Links -->
				<?php
				// Get actual post to check status
				$post        = get_post( $entry['wordpress_post_id'] );
				$post_status = $post ? $post->post_status : 'unknown';
				$post_exists = $post && $post->post_status !== 'trash';

				// Display appropriate message based on status
				if ( $entry['wordpress_status'] === 'imported_published' ) :
					$status_label = __( 'Imported (Published)', 'wisewand-ai-content-writer-seo-content-generator' );
					$status_icon  = '🌐';
					$status_color = 'linear-gradient(135deg, #10b981 0%, #059669 100%)';
				else :
					$status_label = __( 'Imported (Draft)', 'wisewand-ai-content-writer-seo-content-generator' );
					$status_icon  = '📝';
					$status_color = 'linear-gradient(135deg, #10b981 0%, #059669 100%)';
				endif;
				?>

				<div style="background: <?php echo esc_attr( $status_color ); ?>; border: 2px solid #10b981; border-radius: 12px; padding: 20px; margin-bottom: 20px; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);">
					<?php if ( $post_exists ) : ?>
						<div style="display: flex; align-items: center; gap: 16px;">
							<div style="font-size: 48px;"><?php echo esc_html( $status_icon ); ?></div>
							<div style="flex: 1;">
								<div style="font-size: 18px; font-weight: 700; color: white; margin-bottom: 6px;">
									<?php esc_html_e( '✓ Imported to WordPress', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</div>
								<div style="font-size: 13px; color: rgba(255, 255, 255, 0.9); margin-bottom: 4px;">
									<?php
									/* translators: %s: WordPress post status (e.g., 'Published', 'Draft', 'Scheduled') */
									printf( esc_html__( 'Status: <strong>%s</strong>', 'wisewand-ai-content-writer-seo-content-generator' ), esc_html( $status_label ) );
									?>
								</div>
								<div style="font-size: 12px; color: rgba(255, 255, 255, 0.8); margin-bottom: 12px;">
									<?php if ( ! empty( $entry['published_at'] ) ) : ?>
										<?php esc_html_e( 'Imported:', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <strong><?php echo esc_html( gmdate( 'M j, Y g:i A', strtotime( $entry['published_at'] ) ) ); ?></strong>
									<?php endif; ?>
								</div>
								<div style="display: flex; gap: 8px; flex-wrap: wrap;">
									<?php if ( $post_status === 'publish' ) : ?>
										<a href="<?php echo esc_url( get_permalink( $entry['wordpress_post_id'] ) ); ?>" target="_blank" class="button button-primary" style="background: white; color: #10b981; border: none; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: transform 0.2s;">
											🌐 <?php esc_html_e( 'View Live Post', 'wisewand-ai-content-writer-seo-content-generator' ); ?> ↗
										</a>
									<?php endif; ?>
									<a href="<?php echo esc_url( get_edit_post_link( $entry['wordpress_post_id'] ) ); ?>" target="_blank" class="button button-secondary" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); font-weight: 600; transition: all 0.2s;">
										✏️ <?php esc_html_e( 'Edit in WordPress', 'wisewand-ai-content-writer-seo-content-generator' ); ?> →
									</a>
								</div>

								<!-- Post Metadata -->
								<div style="margin-top: 12px; padding: 10px; background: rgba(255, 255, 255, 0.15); border-left: 3px solid rgba(255, 255, 255, 0.4); border-radius: 4px;">
									<div style="font-size: 11px; color: rgba(255, 255, 255, 0.9); line-height: 1.6;">
										<strong><?php esc_html_e( 'Post ID:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php echo esc_html( $entry['wordpress_post_id'] ); ?><br>
										<strong><?php esc_html_e( 'WordPress Status:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php echo esc_html( ucfirst( $post_status ) ); ?>
									</div>
								</div>
							</div>
						</div>
					<?php else : ?>
						<!-- Post was deleted -->
						<div style="display: flex; align-items: center; gap: 16px;">
							<div style="font-size: 48px;">⚠️</div>
							<div style="flex: 1;">
								<div style="font-size: 18px; font-weight: 700; color: white; margin-bottom: 6px;">
									<?php esc_html_e( 'Post Not Found', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</div>
								<div style="font-size: 13px; color: rgba(255, 255, 255, 0.9);">
									<?php
									/* translators: %s: WordPress post ID (numeric identifier) */
									printf( esc_html__( 'The WordPress post (ID: %s) was deleted or moved.', 'wisewand-ai-content-writer-seo-content-generator' ), esc_html( $entry['wordpress_post_id'] ) );
									?>
								</div>
							</div>
						</div>
					<?php endif; ?>
				</div>
			<?php endif; ?>

			<!-- SEO Insights -->
			<div class="panel-section insights-section">
				<h3>📊 <?php esc_html_e( 'Keyword Insights', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<div class="insights-grid">
					<div class="metric-card-small">
						<div class="metric-label"><?php esc_html_e( 'Keyword', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
						<div class="metric-value-text"><?php echo esc_html( $entry['keyword'] ); ?></div>
					</div>
					<?php if ( $entry['search_volume'] ) : ?>
					<div class="metric-card-small">
						<div class="metric-label"><?php esc_html_e( 'Search Volume', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
						<div class="metric-value"><?php echo esc_html( number_format( $entry['search_volume'] ) ); ?></div>
						<div class="metric-sublabel">/month</div>
					</div>
					<?php endif; ?>
					<?php if ( $entry['current_position'] ) : ?>
					<div class="metric-card-small">
						<div class="metric-label"><?php esc_html_e( 'Position', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
						<div class="metric-value">#<?php echo esc_html( $entry['current_position'] ); ?></div>
					</div>
					<?php endif; ?>
					<div class="metric-card-small">
						<div class="metric-label"><?php esc_html_e( 'Intent', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
						<div class="intent-badge-small"><?php echo esc_html( ucfirst( $entry['search_intent'] ) ); ?></div>
					</div>
				</div>
			</div>

			<?php if ( ! empty( $related_pages ) ) : ?>
			<!-- Related WordPress Content -->
			<div class="panel-section">
				<h3>🔗 <?php esc_html_e( 'Related WordPress Content', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<p class="section-description"><?php esc_html_e( 'Existing posts related to this keyword. Select one to update instead of creating new content.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				<div class="related-pages">
					<?php foreach ( $related_pages as $page ) : ?>
					<label class="related-page-option">
						<input type="radio" name="existing_post_id" value="<?php echo esc_attr( $page->ID ); ?>" <?php checked( $entry['existing_post_id'], $page->ID ); ?>>
						<div class="page-info">
							<div class="page-title"><?php echo esc_html( $page->post_title ); ?></div>
							<div class="page-meta">
								<?php echo esc_html( $page->post_type ); ?> •
								Last updated: <?php echo esc_html( gmdate( 'M j, Y', strtotime( $page->post_modified ) ) ); ?>
							</div>
						</div>
					</label>
					<?php endforeach; ?>
					<label class="related-page-option">
						<input type="radio" name="existing_post_id" value="" <?php checked( empty( $entry['existing_post_id'] ) ); ?>>
						<div class="page-info">
							<div class="page-title">🆕 <?php esc_html_e( 'Create New Content', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
						</div>
					</label>
				</div>
			</div>
			<?php endif; ?>

			<!-- Article Configuration -->
			<div class="panel-section">
				<h3>✍️ <?php esc_html_e( 'Article Configuration', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>

				<div class="form-row-two">
					<div class="form-col">
						<label><?php esc_html_e( 'Content Type', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span style="color: #ef4444;">*</span></label>
						<select name="content_type_selector" id="content-type-selector" class="panel-input" style="font-weight: 600;">
							<?php
							// Determine current endpoint and type from payload
							$current_type     = $payload['type'] ?? 'blog';
							$current_endpoint = 'articles'; // Default

							// Map old values to new endpoint structure
							if ( $current_type === 'categorypage' ) {
								$current_endpoint = 'categorypages';
								$current_type     = '';
							} elseif ( $current_type === 'productpage' ) {
								$current_endpoint = 'productpages';
								$current_type     = '';
							}

							$current_value = $current_endpoint . '|' . $current_type;
							?>
							<optgroup label="📝 <?php esc_html_e( 'Articles & Blog Posts', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
								<option value="articles|blog" <?php selected( $current_value, 'articles|blog' ); ?>><?php esc_html_e( 'Blog Article', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="articles|news" <?php selected( $current_value, 'articles|news' ); ?>><?php esc_html_e( 'News Article', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							</optgroup>
							<optgroup label="🛍️ <?php esc_html_e( 'Affiliate & Reviews', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
								<option value="articles|affiliation-product-review" <?php selected( $current_value, 'articles|affiliation-product-review' ); ?>><?php esc_html_e( 'Product Review', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="articles|affiliation-compare-products" <?php selected( $current_value, 'articles|affiliation-compare-products' ); ?>><?php esc_html_e( 'Compare Products', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="articles|affiliation-top-product" <?php selected( $current_value, 'articles|affiliation-top-product' ); ?>><?php esc_html_e( 'Top Products List', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							</optgroup>
							<optgroup label="🏪 <?php esc_html_e( 'E-commerce Pages', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
								<option value="categorypages|" <?php selected( $current_value, 'categorypages|' ); ?>><?php esc_html_e( 'Category Page', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="productpages|" <?php selected( $current_value, 'productpages|' ); ?>><?php esc_html_e( 'Product Page', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							</optgroup>
							<optgroup label="📱 <?php esc_html_e( 'Special Formats', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
								<option value="discoverarticles|" <?php selected( $current_value, 'discoverarticles|' ); ?>><?php esc_html_e( 'Google Discover Article', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							</optgroup>
						</select>
						<p class="field-help"><?php esc_html_e( 'Different content types use different API endpoints and have different available fields.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>

						<!-- Hidden fields for backend processing -->
						<input type="hidden" name="api_endpoint" id="api-endpoint" value="<?php echo esc_attr( $current_endpoint ); ?>">
						<input type="hidden" name="article_type" id="article-type" value="<?php echo esc_attr( $current_type ); ?>">
					</div>

					<div class="form-col">
						<label><?php esc_html_e( 'Article Length', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<select name="article_length" class="panel-input">
							<option value="auto" <?php selected( $payload['length'] ?? 'auto', 'auto' ); ?>>Auto (Recommended)</option>
							<option value="800" <?php selected( $payload['length'] ?? '', '800' ); ?>>~800 words</option>
							<option value="1000" <?php selected( $payload['length'] ?? '', '1000' ); ?>>~1,000 words</option>
							<option value="1500" <?php selected( $payload['length'] ?? '', '1500' ); ?>>~1,500 words</option>
							<option value="2000" <?php selected( $payload['length'] ?? '', '2000' ); ?>>~2,000 words</option>
							<option value="3000" <?php selected( $payload['length'] ?? '', '3000' ); ?>>~3,000 words</option>
							<option value="5000" <?php selected( $payload['length'] ?? '', '5000' ); ?>>~5,000 words</option>
						</select>
					</div>
				</div>

				<div class="form-row-two">
					<div class="form-col">
						<label><?php esc_html_e( 'Language', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<select name="article_language" class="panel-input">
							<option value="en" <?php selected( $payload['lang'] ?? 'en', 'en' ); ?>>🇺🇸 English</option>
							<option value="fr" <?php selected( $payload['lang'] ?? '', 'fr' ); ?>>🇫🇷 Français</option>
							<option value="de" <?php selected( $payload['lang'] ?? '', 'de' ); ?>>🇩🇪 Deutsch</option>
							<option value="es" <?php selected( $payload['lang'] ?? '', 'es' ); ?>>🇪🇸 Español</option>
						</select>
					</div>

					<div class="form-col">
						<label><?php esc_html_e( 'Country', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<select name="article_country" class="panel-input">
							<option value="us" <?php selected( $payload['country'] ?? 'us', 'us' ); ?>>🇺🇸 United States</option>
							<option value="fr" <?php selected( $payload['country'] ?? '', 'fr' ); ?>>🇫🇷 France</option>
							<option value="de" <?php selected( $payload['country'] ?? '', 'de' ); ?>>🇩🇪 Germany</option>
							<option value="es" <?php selected( $payload['country'] ?? '', 'es' ); ?>>🇪🇸 Spain</option>
							<option value="gb" <?php selected( $payload['country'] ?? '', 'gb' ); ?>>🇬🇧 United Kingdom</option>
							<option value="ca" <?php selected( $payload['country'] ?? '', 'ca' ); ?>>🇨🇦 Canada</option>
						</select>
					</div>
				</div>

				<label><?php esc_html_e( 'Title', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
				<input type="text" name="article_title" value="<?php echo esc_attr( $payload['title'] ?? $entry['keyword'] ); ?>" class="panel-input" placeholder="<?php esc_html_e( 'Auto-generated if empty', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">

				<!-- Keep Title - Articles Only -->
				<div class="articles-only-fields" style="<?php echo in_array( $current_endpoint, array( 'categorypages', 'productpages', 'discoverarticles' ) ) ? 'display:none;' : ''; ?>">
					<div class="form-checkbox">
						<label>
							<input type="checkbox" name="keep_title" value="1" <?php checked( ! empty( $payload['keep_title'] ), true ); ?>>
							<?php esc_html_e( 'Keep this exact title (don\'t let Wisewand modify it)', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</label>
					</div>
				</div>

				<label><?php esc_html_e( 'Target Keyword', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
				<input type="text" name="target_keyword" value="<?php echo esc_attr( $payload['target_keyword'] ?? $entry['keyword'] ); ?>" class="panel-input">

				<!-- Secondary Keywords - Articles + Discover Only -->
				<div class="articles-discover-fields" style="<?php echo in_array( $current_endpoint, array( 'categorypages', 'productpages' ) ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Secondary Keywords', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
					<textarea name="keywords_secondary" rows="2" class="panel-input" placeholder="<?php esc_html_e( 'seo, référencement, erreurs seo courantes, positionnement web', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['keywords_secondary'] ?? '' ); ?></textarea>
				</div>

				<!-- Website URL - Category/Product/Discover Pages Only -->
				<div class="pages-only-fields" style="<?php echo ( $current_endpoint === 'articles' ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Website URL', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
					<input type="text" name="website" class="panel-input" value="<?php echo esc_url( $payload['website'] ?? home_url() ); ?>" placeholder="https://example.com">
					<p class="field-help"><?php esc_html_e( 'The website URL associated with this content.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				</div>

				<div class="form-row-two">
					<div class="form-col">
						<label><?php esc_html_e( 'Writing Style', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<select name="writing_style_mode" id="writing-style-mode" class="panel-input">
							<option value="auto" <?php selected( $payload['writing_style_mode'] ?? 'auto', 'auto' ); ?>>🤖 <?php esc_html_e( 'Auto (Analyze Website)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							<option value="persona" <?php selected( $payload['writing_style_mode'] ?? '', 'persona' ); ?>>👤 <?php esc_html_e( 'Use Persona', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						</select>
					</div>

					<div class="form-col" id="persona-select-container" style="<?php echo ( $payload['writing_style_mode'] ?? 'auto' ) !== 'persona' ? 'display:none;' : ''; ?>">
						<label><?php esc_html_e( 'Persona', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<select name="persona_id" id="persona-select" class="panel-input" data-current-value="<?php echo esc_attr( $payload['persona_id'] ?? '' ); ?>">
							<option value=""><?php esc_html_e( 'Loading personas...', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						</select>
					</div>
				</div>

				<label><?php esc_html_e( 'Project', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
				<select name="project_id" id="project-select" class="panel-input" data-current-value="<?php echo esc_attr( $payload['project_id'] ?? '' ); ?>">
					<option value=""><?php esc_html_e( 'Loading projects...', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				</select>
				<p class="field-help"><?php esc_html_e( 'Links website URL and project default settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>

				<!-- Writing Style Description - Category/Product/Discover Pages Only -->
				<div class="pages-only-fields-2" style="<?php echo ( $current_endpoint === 'articles' ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Custom Writing Style', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
					<textarea name="writing_style" rows="2" class="panel-input" placeholder="<?php esc_html_e( 'e.g., Professional, conversational tone with expert insights and practical examples', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['writing_style'] ?? '' ); ?></textarea>
					<p class="field-help"><?php esc_html_e( 'Custom writing style description. Leave empty to use persona or auto-detect from website.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				</div>
			</div>

			<!-- Content Features -->
			<div class="panel-section">
				<h3>🎨 <?php esc_html_e( 'Content Features', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>

				<div class="features-grid">
					<label class="feature-toggle">
						<input type="checkbox" name="use_toc" value="1" <?php checked( ! empty( $payload['use_toc'] ) || ! isset( $payload['use_toc'] ), true ); ?>>
						<span>📑 <?php esc_html_e( 'Table of Contents', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					</label>

					<label class="feature-toggle">
						<input type="checkbox" name="use_bulletlist" value="1" <?php checked( ! empty( $payload['use_bulletlist'] ) || ! isset( $payload['use_bulletlist'] ), true ); ?>>
						<span>📌 <?php esc_html_e( 'Bullet Lists', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					</label>

					<label class="feature-toggle">
						<input type="checkbox" name="use_infotable" value="1" <?php checked( ! empty( $payload['use_infotable'] ), true ); ?>>
						<span>📊 <?php esc_html_e( 'Info Tables', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					</label>

					<label class="feature-toggle">
						<input type="checkbox" name="use_boldkeywords" value="1" <?php checked( ! empty( $payload['use_boldkeywords'] ) || ! isset( $payload['use_boldkeywords'] ), true ); ?>>
						<span>🔤 <?php esc_html_e( 'Bold Keywords', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					</label>

					<label class="feature-toggle">
						<input type="checkbox" name="use_externalsources" value="1" <?php checked( ! empty( $payload['use_externalsources'] ) || ! isset( $payload['use_externalsources'] ), true ); ?>>
						<span>🔗 <?php esc_html_e( 'External Sources', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					</label>

					<!-- Summary & Blockquotes - Available for all types -->
					<label class="feature-toggle">
						<input type="checkbox" name="use_summary" value="1" <?php checked( ! empty( $payload['use_summary'] ) || ! isset( $payload['use_summary'] ), true ); ?>>
						<span>📝 <?php esc_html_e( 'Article Summary', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					</label>

					<label class="feature-toggle">
						<input type="checkbox" name="use_blockquotes" value="1" <?php checked( ! empty( $payload['use_blockquotes'] ) || ! isset( $payload['use_blockquotes'] ), true ); ?>>
						<span>💬 <?php esc_html_e( 'Blockquotes (2-5)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					</label>
				</div>
			</div>

			<!-- Affiliation Settings (Product Review, Compare, Top Products) -->
			<div class="panel-section affiliation-only-section" style="<?php echo ( ! in_array( $current_type, array( 'affiliation-product-review', 'affiliation-compare-products', 'affiliation-top-product' ) ) ) ? 'display:none;' : ''; ?>">
				<h3>🛍️ <?php esc_html_e( 'Affiliation Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<p class="section-description"><?php esc_html_e( 'Configure product-specific information for affiliate content.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>

				<!-- Product Review - Single Product -->
				<div class="affiliation-product-review-fields" style="<?php echo ( $current_type !== 'affiliation-product-review' ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Product Name', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
					<input type="text" name="affiliation_product_name" class="panel-input" value="<?php echo esc_attr( $payload['affiliation_product_name'] ?? '' ); ?>" placeholder="<?php esc_html_e( 'e.g., iPhone 15 Pro', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">

					<label><?php esc_html_e( 'Review URLs', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'optional - 1/3', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
					<div id="review-urls-container" class="repeater-container">
						<?php
						$review_urls = $payload['affiliation_product_review_urls'] ?? array( '' );
						foreach ( $review_urls as $index => $url ) :
							?>
						<div class="repeater-row">
							<input type="url" name="affiliation_product_review_urls[]" class="panel-input" value="<?php echo esc_url( $url ); ?>" placeholder="https://amazon.fr/product/reviews/...">
							<button type="button" class="btn-remove-repeater" <?php echo esc_attr( $index === 0 ? 'style="visibility:hidden;"' : '' ); ?>>🗑️</button>
						</div>
						<?php endforeach; ?>
					</div>
					<button type="button" class="btn-add-review-url btn-add-field"><?php esc_html_e( '+ Add Review URL', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>

					<label><?php esc_html_e( 'Affiliation Links', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( '1/5', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
					<div id="affiliation-links-container" class="affiliation-links-container">
						<?php
						$affiliation_links = $payload['affiliation_links'] ?? array(
							array(
								'url'    => '',
								'anchor' => '',
							),
						);
						foreach ( $affiliation_links as $index => $link ) :
							?>
						<div class="affiliation-link-row">
							<div class="affiliation-link-header">
								<span class="link-number"><?php esc_html_e( 'Link', 'wisewand-ai-content-writer-seo-content-generator' ); ?> #<?php echo esc_html( $index + 1 ); ?></span>
								<button type="button" class="btn-remove-affiliation-link" <?php echo esc_attr( $index === 0 ? 'style="visibility:hidden;"' : '' ); ?>>🗑️</button>
							</div>
							<div class="form-row-two">
								<div class="form-col">
									<label><?php esc_html_e( 'URL', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
									<input type="url" name="affiliation_link_url[]" class="panel-input affiliation-link-url" value="<?php echo esc_url( $link['url'] ?? '' ); ?>" placeholder="https://amazon.fr/product/...">
								</div>
								<div class="form-col">
									<label><?php esc_html_e( 'Anchor Text', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
									<input type="text" name="affiliation_link_anchor[]" class="panel-input affiliation-link-anchor" value="<?php echo esc_attr( $link['anchor'] ?? '' ); ?>" placeholder="<?php esc_html_e( 'Buy on Amazon', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
								</div>
							</div>
						</div>
						<?php endforeach; ?>
					</div>
					<button type="button" id="add-affiliation-link-btn" class="btn-add-field"><?php esc_html_e( '+ Add Affiliation Link', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>

					<div class="form-row-two">
						<div class="form-col">
							<label><?php esc_html_e( 'Promo Code', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
							<input type="text" name="affiliation_promo_code" class="panel-input" value="<?php echo esc_attr( $payload['affiliation_promo_code'] ?? '' ); ?>" placeholder="<?php esc_html_e( 'e.g., PROMO20', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
						</div>
						<div class="form-col">
							<label><?php esc_html_e( 'Discount Percentage', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
							<input type="text" name="affiliation_promo_percentage" class="panel-input" value="<?php echo esc_attr( $payload['affiliation_promo_percentage'] ?? '' ); ?>" placeholder="<?php esc_html_e( 'e.g., 20', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
						</div>
					</div>
				</div>

				<!-- Compare Products - 2 Products -->
				<div class="affiliation-compare-products-fields" style="<?php echo ( $current_type !== 'affiliation-compare-products' ) ? 'display:none;' : ''; ?>">
					<?php for ( $product_num = 1; $product_num <= 2; $product_num++ ) : ?>
					<div class="product-comparison-card">
						<h4 class="product-card-title">
							<?php if ( $product_num === 1 ) : ?>
								🥇 <?php esc_html_e( 'Product #1', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							<?php else : ?>
								🥈 <?php esc_html_e( 'Product #2', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							<?php endif; ?>
						</h4>

						<label><?php esc_html_e( 'Product Name', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<input type="text" name="affiliation_product_<?php echo esc_attr( $product_num ); ?>_name" class="panel-input" value="<?php echo esc_attr( $payload[ "affiliation_product_{$product_num}_name" ] ?? '' ); ?>" placeholder="<?php esc_html_e( 'e.g., iPhone 15 Pro', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">

						<label><?php esc_html_e( 'Review URLs', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
						<div class="review-urls-product-<?php echo esc_attr( $product_num ); ?> repeater-container">
							<?php
							$review_urls = $payload[ "affiliation_product_{$product_num}_review_urls" ] ?? array( '' );
							foreach ( $review_urls as $idx => $url ) :
								?>
							<div class="repeater-row">
								<input type="url" name="affiliation_product_<?php echo esc_attr( $product_num ); ?>_review_urls[]" class="panel-input" value="<?php echo esc_url( $url ); ?>" placeholder="https://...">
								<button type="button" class="btn-remove-repeater" <?php echo esc_attr( $idx === 0 ? 'style="visibility:hidden;"' : '' ); ?>>🗑️</button>
							</div>
							<?php endforeach; ?>
						</div>
						<button type="button" class="btn-add-review-url-<?php echo esc_attr( $product_num ); ?> btn-add-field-small" data-product="<?php echo esc_attr( $product_num ); ?>"><?php esc_html_e( '+ Add Review URL', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>

						<label><?php esc_html_e( 'Affiliation Links', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<div class="affiliation-links-product-<?php echo esc_attr( $product_num ); ?> affiliation-links-container-small">
							<?php
							$affiliation_links = $payload[ "affiliation_links_product_{$product_num}" ] ?? array(
								array(
									'url'    => '',
									'anchor' => '',
								),
							);
							foreach ( $affiliation_links as $idx => $link ) :
								?>
							<div class="affiliation-link-row-small">
								<div class="form-row-two">
									<div class="form-col">
										<input type="url" name="affiliation_links_product_<?php echo esc_attr( $product_num ); ?>_url[]" class="panel-input" value="<?php echo esc_url( $link['url'] ?? '' ); ?>" placeholder="URL">
									</div>
									<div class="form-col">
										<input type="text" name="affiliation_links_product_<?php echo esc_attr( $product_num ); ?>_anchor[]" class="panel-input" value="<?php echo esc_attr( $link['anchor'] ?? '' ); ?>" placeholder="<?php esc_html_e( 'Anchor', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
									</div>
								</div>
								<button type="button" class="btn-remove-affiliation-link-small" <?php echo $idx === 0 ? 'style="visibility:hidden;"' : ''; ?>>🗑️</button>
							</div>
							<?php endforeach; ?>
						</div>
						<button type="button" class="btn-add-affiliation-link-<?php echo esc_attr( $product_num ); ?> btn-add-field-small" data-product="<?php echo esc_attr( $product_num ); ?>"><?php esc_html_e( '+ Add Link', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>

						<div class="form-row-two">
							<div class="form-col">
								<label><?php esc_html_e( 'Promo Code', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
								<input type="text" name="affiliation_promo_code_<?php echo esc_attr( $product_num ); ?>" class="panel-input" value="<?php echo esc_attr( $payload[ "affiliation_promo_code_{$product_num}" ] ?? '' ); ?>" placeholder="PROMO20">
							</div>
							<div class="form-col">
								<label><?php esc_html_e( 'Discount %', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
								<input type="text" name="affiliation_promo_percentage_<?php echo esc_attr( $product_num ); ?>" class="panel-input" value="<?php echo esc_attr( $payload[ "affiliation_promo_percentage_{$product_num}" ] ?? '' ); ?>" placeholder="20">
							</div>
						</div>
					</div>
					<?php endfor; ?>
				</div>

				<!-- Top Products - Dynamic Repeater -->
				<div class="affiliation-top-products-fields" style="<?php echo ( $current_type !== 'affiliation-top-product' ) ? 'display:none;' : ''; ?>">
					<div id="top-products-container">
						<?php
						$top_products = $payload['affiliation_top_products'] ?? array(
							array(
								'name'              => '',
								'urls'              => array( '' ),
								'affiliation_links' => array(
									array(
										'url'    => '',
										'anchor' => '',
									),
								),
								'promo_code'        => '',
								'promo_percentage'  => '',
							),
						);

						foreach ( $top_products as $product_index => $product ) :
							?>
						<div class="top-product-card" data-product-index="<?php echo esc_attr( $product_index ); ?>">
							<div class="top-product-header">
								<span class="top-product-number">🥇 <?php esc_html_e( 'Product', 'wisewand-ai-content-writer-seo-content-generator' ); ?> #<?php echo esc_html( $product_index + 1 ); ?></span>
								<button type="button" class="btn-remove-top-product" <?php echo esc_attr( $product_index === 0 ? 'style="visibility:hidden;"' : '' ); ?>>🗑️</button>
							</div>

							<label><?php esc_html_e( 'Product Name', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<input type="text" class="panel-input top-product-name" value="<?php echo esc_attr( $product['name'] ?? '' ); ?>" placeholder="<?php esc_html_e( 'e.g., iPhone 15 Pro', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">

							<label><?php esc_html_e( 'Review URLs', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<div class="top-product-urls-container">
								<?php
								$urls = $product['urls'] ?? array( '' );
								foreach ( $urls as $url_idx => $url ) :
									?>
								<div class="repeater-row">
									<input type="url" class="panel-input top-product-url" value="<?php echo esc_url( $url ); ?>" placeholder="https://...">
									<button type="button" class="btn-remove-top-product-url" <?php echo esc_attr( $url_idx === 0 ? 'style="visibility:hidden;"' : '' ); ?>>🗑️</button>
								</div>
								<?php endforeach; ?>
							</div>
							<button type="button" class="btn-add-top-product-url btn-add-field-small"><?php esc_html_e( '+ Add URL', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>

							<label><?php esc_html_e( 'Affiliation Links', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<div class="top-product-affiliation-links-container">
								<?php
								$links = $product['affiliation_links'] ?? array(
									array(
										'url'    => '',
										'anchor' => '',
									),
								);
								foreach ( $links as $link_idx => $link ) :
									?>
								<div class="affiliation-link-row-small">
									<div class="form-row-two">
										<div class="form-col">
											<input type="url" class="panel-input top-product-link-url" value="<?php echo esc_url( $link['url'] ?? '' ); ?>" placeholder="URL">
										</div>
										<div class="form-col">
											<input type="text" class="panel-input top-product-link-anchor" value="<?php echo esc_attr( $link['anchor'] ?? '' ); ?>" placeholder="<?php esc_html_e( 'Anchor', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
										</div>
									</div>
									<button type="button" class="btn-remove-top-product-link" <?php echo esc_attr( $link_idx === 0 ? 'style="visibility:hidden;"' : '' ); ?>>🗑️</button>
								</div>
								<?php endforeach; ?>
							</div>
							<button type="button" class="btn-add-top-product-link btn-add-field-small"><?php esc_html_e( '+ Add Link', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>

							<div class="form-row-two">
								<div class="form-col">
									<label><?php esc_html_e( 'Promo Code', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
									<input type="text" class="panel-input top-product-promo-code" value="<?php echo esc_attr( $product['promo_code'] ?? '' ); ?>" placeholder="PROMO20">
								</div>
								<div class="form-col">
									<label><?php esc_html_e( 'Discount %', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
									<input type="text" class="panel-input top-product-promo-percentage" value="<?php echo esc_attr( $product['promo_percentage'] ?? '' ); ?>" placeholder="20">
								</div>
							</div>
						</div>
						<?php endforeach; ?>
					</div>
					<button type="button" id="add-top-product-btn" class="btn-add-field"><?php esc_html_e( '+ Add Another Product', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>
				</div>
			</div>

			<!-- FAQ Configuration -->
			<div class="panel-section">
				<h3>❓ <?php esc_html_e( 'FAQ Configuration', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>

				<div class="form-checkbox">
					<label>
						<input type="checkbox" name="use_faq" id="toggle-faq" value="1" <?php checked( ! empty( $payload['use_faq'] ) || ! isset( $payload['use_faq'] ), true ); ?>>
						<?php esc_html_e( 'Include FAQ Section', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</label>
				</div>

				<div id="faq-advanced" style="<?php echo empty( $payload['use_faq'] ) && ! ( $payload['use_faq'] ?? true ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Custom FAQ Questions', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'auto-generated if empty', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
					<textarea name="faq_questions" rows="4" class="panel-input" placeholder="<?php esc_html_e( 'What is WordPress?\nHow to install a plugin?\nWhy use SEO?\n\nOne question per line - AI will auto-generate if empty', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['faq_questions'] ?? '' ); ?></textarea>
					<p class="field-help"><?php esc_html_e( 'Leave empty for AI to automatically generate relevant FAQ questions based on the article content.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				</div>
			</div>

			<!-- CTAs & Conversion -->
			<div class="panel-section">
				<h3>📣 <?php esc_html_e( 'CTAs & Conversion', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>

				<div class="form-checkbox">
					<label>
						<input type="checkbox" name="use_cta" id="toggle-cta" value="1" <?php checked( ! empty( $payload['use_cta'] ), true ); ?>>
						<?php esc_html_e( 'Include Call-to-Actions in Article', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</label>
				</div>

				<div id="ctas-section" style="<?php echo empty( $payload['use_cta'] ) ? 'display:none;' : ''; ?>">
					<div id="ctas-container" class="ctas-container">
						<?php
						$existing_ctas = $payload['ctas'] ?? array();
						if ( empty( $existing_ctas ) ) {
							$existing_ctas = array(
								array(
									'anchor' => '',
									'url'    => '',
								),
							);
						}

						foreach ( $existing_ctas as $index => $cta ) :
							?>
						<div class="cta-row" data-index="<?php echo esc_attr( $index ); ?>">
							<div class="cta-row-header">
								<span class="cta-number">CTA #<?php echo esc_html( $index + 1 ); ?></span>
								<button type="button" class="btn-remove-cta" <?php echo esc_attr( $index === 0 ? 'style="visibility:hidden;"' : '' ); ?>>🗑️</button>
							</div>
							<div class="cta-row-fields">
								<div class="form-col">
									<label><?php esc_html_e( 'Anchor Text', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
									<input type="text" name="cta_anchor[]" class="panel-input cta-anchor" value="<?php echo esc_attr( $cta['anchor'] ?? '' ); ?>" placeholder="<?php esc_html_e( 'Click here to learn more', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
								</div>
								<div class="form-col">
									<label><?php esc_html_e( 'Target URL', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
									<input type="url" name="cta_url[]" class="panel-input cta-url" value="<?php echo esc_url( $cta['url'] ?? '' ); ?>" placeholder="https://example.com/product">
								</div>
							</div>
						</div>
						<?php endforeach; ?>
					</div>
					<button type="button" id="add-cta-btn" class="btn-add-field">
						➕ <?php esc_html_e( 'Add Another CTA', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</button>
				</div>
			</div>

			<!-- Social Media -->
			<div class="panel-section">
				<h3>📱 <?php esc_html_e( 'Social Media', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>

				<div class="form-checkbox">
					<label>
						<input type="checkbox" name="use_social" id="toggle-social" value="1" <?php checked( ! empty( $payload['use_social'] ), true ); ?>>
						<?php esc_html_e( 'Generate Social Media Posts', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="feature-cost">+0.5</span>
					</label>
				</div>

				<div id="social-networks-container" style="<?php echo empty( $payload['use_social'] ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Social Networks', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
					<div class="social-networks-grid">
						<?php
						$selected_networks  = $payload['social_networks'] ?? array( 'instagram', 'facebook', 'x', 'linkedin' );
						$available_networks = array(
							'instagram' => array(
								'label' => 'Instagram',
								'icon'  => '📸',
							),
							'facebook'  => array(
								'label' => 'Facebook',
								'icon'  => '📘',
							),
							'x'         => array(
								'label' => 'X (Twitter)',
								'icon'  => '🐦',
							),
							'linkedin'  => array(
								'label' => 'LinkedIn',
								'icon'  => '💼',
							),
						);

						foreach ( $available_networks as $network => $config ) :
							?>
						<label class="network-option">
							<input type="checkbox" name="social_networks[]" value="<?php echo esc_attr( $network ); ?>" <?php checked( in_array( $network, $selected_networks ) ); ?>>
							<span><?php echo esc_html( $config['icon'] ); ?> <?php echo esc_html( $config['label'] ); ?></span>
						</label>
						<?php endforeach; ?>
					</div>
				</div>
			</div>

			<!-- Media Settings -->
			<div class="panel-section">
				<div class="section-header-with-cost">
					<h3>🖼️ <?php esc_html_e( 'Media Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
					<div class="credit-calculator">
						💳 <strong id="total-credits">0.0</strong> <?php esc_html_e( 'credits', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</div>
				</div>
				<p class="section-description" style="margin-bottom: 16px;">
					<?php esc_html_e( 'Media generation costs:', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					<span class="cost-item">🖼️ <?php esc_html_e( 'Cover +0.5', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					<span class="cost-item">🎨 <?php esc_html_e( 'Inline +0.5 each (1-10)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					<span class="cost-item">📱 <?php esc_html_e( 'Social +0.5', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					<span class="cost-item">🎧 <?php esc_html_e( 'Audio +1.0', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
				</p>

				<!-- Featured Image -->
				<div class="media-subsection">
					<h4 class="subsection-title">🖼️ <?php esc_html_e( 'Featured Image', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h4>

					<div class="form-checkbox">
						<label>
							<input type="checkbox" name="use_image" id="toggle-featured-image" value="1" <?php checked( ! empty( $payload['use_image'] ) || ! isset( $payload['use_image'] ), true ); ?>>
							<?php esc_html_e( 'Generate Featured Image', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="feature-cost">+0.5</span>
						</label>
					</div>

					<div id="featured-image-config" style="<?php echo empty( $payload['use_image'] ) && ! ( $payload['use_image'] ?? true ) ? 'display:none;' : ''; ?>">
						<div class="form-row-two">
							<div class="form-col">
								<label><?php esc_html_e( 'Image Ratio', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
								<select name="image_ratio" class="panel-input">
									<option value="landscape" <?php selected( $payload['image_ratio'] ?? 'landscape', 'landscape' ); ?>>🖼️ Landscape (16:9)</option>
									<option value="portrait" <?php selected( $payload['image_ratio'] ?? '', 'portrait' ); ?>>📱 Portrait</option>
									<option value="1:1" <?php selected( $payload['image_ratio'] ?? '', '1:1' ); ?>>⬜ Square (1:1)</option>
									<option value="4:3" <?php selected( $payload['image_ratio'] ?? '', '4:3' ); ?>>🖥️ Standard (4:3)</option>
								</select>
							</div>

							<div class="form-col">
								<div class="form-checkbox" style="margin-top: 28px;">
									<label>
										<input type="checkbox" name="image_use_palette" id="toggle-image-palette" value="1" <?php checked( ! empty( $payload['image_use_palette'] ) || ! isset( $payload['image_use_palette'] ), true ); ?>>
										<?php esc_html_e( 'Use Brand Colors', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</label>
								</div>
							</div>
						</div>

						<div id="image-colors-config" style="<?php echo empty( $payload['image_use_palette'] ) && ! ( $payload['image_use_palette'] ?? true ) ? 'display:none;' : ''; ?>">
							<div class="form-row-two">
								<div class="form-col">
									<label><?php esc_html_e( 'Primary Color', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
									<input type="color" name="image_primary_color" value="<?php echo esc_attr( $payload['image_primary_color'] ?? '#ffffff' ); ?>" class="panel-input color-input">
								</div>
								<div class="form-col">
									<label><?php esc_html_e( 'Secondary Color', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
									<input type="color" name="image_secondary_color" value="<?php echo esc_attr( $payload['image_secondary_color'] ?? '#000000' ); ?>" class="panel-input color-input">
								</div>
							</div>
						</div>

						<details class="advanced-settings">
							<summary>🎨 <?php esc_html_e( 'Custom Image Prompt (Advanced)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></summary>
							<div class="advanced-content">
								<label><?php esc_html_e( 'Image Generation Prompt', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
								<textarea name="image_prompt" rows="3" class="panel-input" placeholder="<?php esc_html_e( 'e.g., Modern minimalist design with tech elements and blue gradient...', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['image_prompt'] ?? '' ); ?></textarea>
								<p class="field-help"><?php esc_html_e( 'Leave empty for AI to generate prompt based on article content.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
							</div>
						</details>
					</div>
				</div>

				<!-- Inline Images -->
				<div class="media-subsection">
					<h4 class="subsection-title">🎨 <?php esc_html_e( 'Inline Images', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h4>

					<div class="form-checkbox">
						<label>
							<input type="checkbox" name="use_inlineimages" id="toggle-inline-images" value="1" <?php checked( ! empty( $payload['use_inlineimages'] ), true ); ?>>
							<?php esc_html_e( 'Generate Inline Images', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							<span class="feature-cost" id="panel-inline-cost">+<?php echo number_format( ( $payload['inlineimages_count'] ?? 1 ) * 0.5, 1 ); ?></span>
						</label>
					</div>

					<div id="inline-images-config" style="<?php echo empty( $payload['use_inlineimages'] ) ? 'display:none;' : ''; ?>">
						<!-- Inline images count slider -->
						<div class="form-row" style="margin-bottom: 16px; padding: 12px; background: rgba(59, 130, 246, 0.05); border-left: 3px solid #3b82f6; border-radius: 4px;">
							<label style="font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 10px; display: block;">
								<?php esc_html_e( 'Number of Inline Images', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</label>
							<div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
								<input type="range" name="inlineimages_count" id="panel-inline-count-slider"
										min="1" max="10" step="1"
										value="<?php echo esc_attr( $payload['inlineimages_count'] ?? 1 ); ?>"
										class="panel-slider" style="flex: 1; max-width: 250px;">
								<span id="panel-inline-count-value" style="font-size: 15px; font-weight: 600; color: #3b82f6; min-width: 70px; text-align: center;">
									<?php echo esc_html( $payload['inlineimages_count'] ?? 1 ); ?> <?php esc_html_e( 'images', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</span>
							</div>
							<p style="font-size: 11px; color: #6b7280; margin: 0;">
								<span id="panel-inline-count-cost" style="color: #92400e; font-weight: 600; background: #fef3c7; padding: 2px 8px; border-radius: 8px; display: inline-block;">
									<?php
									$count = $payload['inlineimages_count'] ?? 1;
									echo esc_html( $count ) . ' × 0.5 = ' . esc_html( number_format( $count * 0.5, 1 ) ) . ' ' . esc_html__( 'credits', 'wisewand-ai-content-writer-seo-content-generator' );
									?>
								</span>
								<span style="margin-left: 8px; color: #9ca3af;">
									<?php esc_html_e( 'Each inline image costs 0.5 credits', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</span>
							</p>
						</div>

						<div class="form-row-two">
							<div class="form-col">
								<label><?php esc_html_e( 'Inline Images Ratio', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
								<select name="inline_images_ratio" class="panel-input">
									<option value="landscape" <?php selected( $payload['inline_images_ratio'] ?? 'landscape', 'landscape' ); ?>>🖼️ Landscape</option>
									<option value="portrait" <?php selected( $payload['inline_images_ratio'] ?? '', 'portrait' ); ?>>📱 Portrait</option>
								</select>
							</div>

							<div class="form-col">
								<div class="form-checkbox" style="margin-top: 28px;">
									<label>
										<input type="checkbox" name="inline_images_use_palette" id="toggle-inline-palette" value="1" <?php checked( ! empty( $payload['inline_images_use_palette'] ), true ); ?>>
										<?php esc_html_e( 'Use Brand Colors', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</label>
								</div>
							</div>
						</div>

						<div id="inline-colors-config" style="<?php echo empty( $payload['inline_images_use_palette'] ) ? 'display:none;' : ''; ?>">
							<div class="form-row-two">
								<div class="form-col">
									<label><?php esc_html_e( 'Primary Color', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
									<input type="color" name="inline_images_primary_color" value="<?php echo esc_attr( $payload['inline_images_primary_color'] ?? '#ffffff' ); ?>" class="panel-input color-input">
								</div>
								<div class="form-col">
									<label><?php esc_html_e( 'Secondary Color', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
									<input type="color" name="inline_images_secondary_color" value="<?php echo esc_attr( $payload['inline_images_secondary_color'] ?? '#000000' ); ?>" class="panel-input color-input">
								</div>
							</div>
						</div>
					</div>
				</div>

				<!-- Audio -->
				<div class="media-subsection">
					<h4 class="subsection-title">🎧 <?php esc_html_e( 'Audio Version', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h4>

					<div class="form-checkbox">
						<label>
							<input type="checkbox" name="use_audio" id="toggle-audio" value="1" <?php checked( ! empty( $payload['use_audio'] ), true ); ?>>
							<?php esc_html_e( 'Generate Audio Version', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="feature-cost" style="color: #f59e0b;">+1.0</span>
						</label>
					</div>

					<div id="audio-config" style="<?php echo empty( $payload['use_audio'] ) ? 'display:none;' : ''; ?>">
						<label><?php esc_html_e( 'Voice', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<select name="audio_voice_id" class="panel-input">
							<?php
							if ( ! class_exists( 'Wisewand\\Config\\Audio_Voices' ) ) {
								require_once WISEWAND_PLUGIN_DIR . 'includes/Config/Audio_Voices.php';
							}

							$current_lang  = $payload['lang'] ?? 'en';
							$all_voices    = \Wisewand\Config\Audio_Voices::get_all_voices();
							$current_voice = $payload['audio_voice_id'] ?? \Wisewand\Config\Audio_Voices::get_default_voice_id();

							// Group by language
							$voices_by_lang = array();
							foreach ( $all_voices as $voice ) {
								$voices_by_lang[ $voice['language'] ][] = $voice;
							}

							foreach ( $voices_by_lang as $lang => $voices ) :
								$lang_label = $lang === 'fr' ? '🇫🇷 French' : '🇬🇧 English';
								?>
								<optgroup label="<?php echo esc_attr( $lang_label ); ?>">
									<?php foreach ( $voices as $voice ) : ?>
										<option value="<?php echo esc_attr( $voice['id'] ); ?>" <?php selected( $current_voice, $voice['id'] ); ?>>
											<?php echo esc_html( \Wisewand\Config\Audio_Voices::format_voice_name( $voice ) ); ?>
										</option>
									<?php endforeach; ?>
								</optgroup>
							<?php endforeach; ?>
						</select>
						<p class="field-help"><?php esc_html_e( 'Select the voice for the audio narration. Voice selection affects tone and delivery of the audio content.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
					</div>
				</div>
			</div>

			<!-- Internal Links -->
			<div class="panel-section">
				<h3>🔗 <?php esc_html_e( 'Internal Links', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>

				<div class="features-grid">
					<label class="feature-toggle">
						<input type="checkbox" name="use_internallinks" value="1" <?php checked( ! empty( $payload['use_internallinks'] ) || ! isset( $payload['use_internallinks'] ), true ); ?>>
						<span><?php esc_html_e( 'Add Internal Links', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					</label>

					<label class="feature-toggle">
						<input type="checkbox" name="use_indexed_pages_internal_links" value="1" <?php checked( ! empty( $payload['use_indexed_pages_internal_links'] ) || ! isset( $payload['use_indexed_pages_internal_links'] ), true ); ?>>
						<span><?php esc_html_e( 'From Indexed Pages', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					</label>
				</div>

				<details class="advanced-settings">
					<summary>⚙️ <?php esc_html_e( 'Advanced Internal Links Configuration', 'wisewand-ai-content-writer-seo-content-generator' ); ?></summary>
					<div class="advanced-content">
						<div class="features-grid">
							<label class="feature-toggle">
								<input type="checkbox" name="use_wp_internal_links" value="1" <?php checked( ! empty( $payload['use_wp_internal_links'] ), true ); ?>>
								<span><?php esc_html_e( 'WordPress Internal Links', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
							</label>

							<label class="feature-toggle">
								<input type="checkbox" name="use_app_internal_links" value="1" <?php checked( ! empty( $payload['use_app_internal_links'] ), true ); ?>>
								<span><?php esc_html_e( 'App Internal Links', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
							</label>

							<label class="feature-toggle">
								<input type="checkbox" name="use_list_internal_links" id="toggle-manual-links" value="1" <?php checked( ! empty( $payload['use_list_internal_links'] ), true ); ?>>
								<span><?php esc_html_e( 'Use Manual Link List', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
							</label>
						</div>

						<div id="manual-links-config" style="<?php echo empty( $payload['use_list_internal_links'] ) ? 'display:none;' : ''; ?>">
							<label><?php esc_html_e( 'Manual Internal Links', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<textarea name="internal_links_list" rows="3" class="panel-input" placeholder="<?php esc_html_e( 'https://example.com/page1\nhttps://example.com/page2\n\nOne URL per line', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['internal_links_list'] ?? '' ); ?></textarea>
							<p class="field-help"><?php esc_html_e( 'One URL per line. These links will be intelligently inserted into the article content.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
						</div>

						<label><?php esc_html_e( 'WordPress Post Status Filter', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<div class="status-filter-grid">
							<?php
							$selected_statuses  = $payload['internal_links_wp_status'] ?? array( 'publish' );
							$available_statuses = array(
								'draft'   => '📝 Draft',
								'pending' => '⏳ Pending Review',
								'publish' => '✅ Published',
								'future'  => '📅 Scheduled',
							);

							foreach ( $available_statuses as $status => $label ) :
								?>
							<label class="status-option">
								<input type="checkbox" name="internal_links_wp_status[]" value="<?php echo esc_attr( $status ); ?>" <?php checked( in_array( $status, $selected_statuses ) ); ?>>
								<span><?php echo esc_html( $label ); ?></span>
							</label>
							<?php endforeach; ?>
						</div>
						<p class="field-help"><?php esc_html_e( 'Select which post statuses to include when finding internal link opportunities.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
					</div>
				</details>
			</div>

			<!-- AI Instructions -->
			<div class="panel-section">
				<h3>🤖 <?php esc_html_e( 'AI Instructions', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>

				<!-- Search Intention - Articles Only -->
				<div class="articles-only-fields-2" style="<?php echo ( $current_endpoint !== 'articles' ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Search Intention Answer', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
					<textarea name="search_intention_answer" rows="3" class="panel-input" placeholder="<?php esc_html_e( 'What should this article achieve for the reader?', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['search_intention_answer'] ?? '' ); ?></textarea>
				</div>

				<!-- Additional Instructions - All Types -->
				<label><?php esc_html_e( 'Additional Instructions', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
				<textarea name="additional_information" rows="3" class="panel-input" placeholder="<?php esc_html_e( 'Specific requirements, focus areas, or guidelines for the AI', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['additional_information'] ?? '' ); ?></textarea>

				<!-- Avoid Information - Articles Only -->
				<div class="articles-only-fields-3" style="<?php echo ( $current_endpoint !== 'articles' ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Avoid Information', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
					<textarea name="avoid_information" rows="2" class="panel-input" placeholder="<?php esc_html_e( 'Topics or information to exclude from the article', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['avoid_information'] ?? '' ); ?></textarea>
				</div>

				<!-- Generate Instructions Buttons -->
				<div style="display: flex; gap: 12px; margin-top: 16px; padding: 16px; background: rgba(59, 130, 246, 0.05); border-radius: 8px; border: 1px solid rgba(59, 130, 246, 0.2);">
					<button type="button" id="generate-instructions-template" class="button button-secondary" style="flex: 1;">
						📝 <?php esc_html_e( 'Quick Generate (Template)', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</button>
					<?php if ( \Wisewand\Utils\OpenAI_Client::is_configured() ) : ?>
						<button type="button" id="generate-instructions-ai" class="button button-primary" style="flex: 1; background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%); border: none;">
							✨ <?php esc_html_e( 'AI Generate (ChatGPT)', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span style="font-size: 10px; opacity: 0.8;">~$0.0001</span>
						</button>
					<?php else : ?>
						<button type="button" class="button button-secondary" style="flex: 1; opacity: 0.5;" disabled title="<?php esc_html_e( 'Configure OpenAI API key in Settings to enable', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
							✨ <?php esc_html_e( 'AI Generate (ChatGPT)', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span style="font-size: 10px;">⚠️ No API Key</span>
						</button>
					<?php endif; ?>
				</div>
				<p class="field-help" style="margin-top: 8px; font-size: 11px; color: #64748b;">
					💡 <strong><?php esc_html_e( 'Quick Generate:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'Uses smart templates (instant, free)', 'wisewand-ai-content-writer-seo-content-generator' ); ?><br>
					<strong><?php esc_html_e( 'AI Generate:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'Uses GPT-4o-mini for context-aware brief (better quality, small cost)', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</p>
			</div>

			<!-- WordPress Settings -->
			<div class="panel-section">
				<h3>📰 <?php esc_html_e( 'WordPress Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>

				<div class="form-row-two">
					<div class="form-col">
						<label><?php esc_html_e( 'Publication Date', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<input type="date" name="publication_date" value="<?php echo esc_attr( $entry['publication_date'] ); ?>" class="panel-input">
					</div>

					<div class="form-col">
					<?php // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- Intentional: displaying already-local times from database ?>
						<label><?php esc_html_e( 'Exact Publication Time', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<input type="time" name="publication_time"
								value="<?php echo ! empty( $entry['publication_time'] ) ? esc_attr( gmdate( 'H:i', strtotime( $entry['publication_time'] ) ) ) : ''; ?>"
								class="panel-input"
								placeholder="<?php esc_html_e( 'HH:MM', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
						<p class="field-help" style="font-size: 11px; margin-top: 4px;">
							<?php esc_html_e( 'CRON will import article at this exact time on publication date', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</p>
					</div>
				</div>

				<div class="form-row">
					<label><?php esc_html_e( 'Time Range (for reference)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
					<select name="publication_time_range" class="panel-input">
						<option value="random" <?php selected( $entry['publication_time_range'], 'random' ); ?>>🔀 Random (9 AM - 8 PM)</option>
						<option value="morning" <?php selected( $entry['publication_time_range'], 'morning' ); ?>>🌅 Morning (9-12 AM)</option>
						<option value="afternoon" <?php selected( $entry['publication_time_range'], 'afternoon' ); ?>>☀️ Afternoon (12-5 PM)</option>
						<option value="evening" <?php selected( $entry['publication_time_range'], 'evening' ); ?>>🌆 Evening (5-8 PM)</option>
					</select>
					<p class="field-help" style="font-size: 11px; margin-top: 4px;">
						<?php esc_html_e( 'Optional label - exact time above takes precedence', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</p>
				</div>

				<div class="form-row">
					<label><?php esc_html_e( 'Author', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'for WordPress import', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
					<?php
					// Get author from calendar entry (may come from AI matching or settings)
					$selected_author = $entry['target_author'] ?? get_current_user_id();

					// Get all authors (fixed: 'who' deprecated since WP 5.9)
					$all_authors = get_users(
						array(
							'capability' => 'edit_posts',
							'orderby'    => 'display_name',
							'order'      => 'ASC',
						)
					);
					?>
					<select name="target_author" class="panel-input">
						<?php foreach ( $all_authors as $author ) : ?>
							<option value="<?php echo esc_attr( $author->ID ); ?>" <?php selected( $selected_author, $author->ID ); ?>>
								<?php echo esc_html( $author->display_name ); ?>
							</option>
						<?php endforeach; ?>
					</select>
					<p class="field-help"><?php esc_html_e( 'This author will be set when importing to WordPress. If keyword was AI-matched to an author, that author is pre-selected.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				</div>

				<div class="form-row">
					<label><?php esc_html_e( 'Categories', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'for WordPress import', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
					<?php
					// Get selected categories from entry metadata
					$selected_categories = array();
					$has_ai_categories   = false;
					if ( ! empty( $entry['wordpress_categories'] ) ) {
						if ( is_array( $entry['wordpress_categories'] ) ) {
							$selected_categories = $entry['wordpress_categories'];
						} else {
							$decoded             = json_decode( $entry['wordpress_categories'], true );
							$selected_categories = $decoded ?: array();
						}
						$has_ai_categories = ! empty( $selected_categories );
					}

					// Get all categories from ALL languages (WPML fix)
					$all_categories_map = array();

					if ( isset( $GLOBALS['sitepress'] ) ) {
						// WPML active - load from all languages
						global $sitepress;
						$active_languages = $sitepress->get_active_languages();

						if ( ! empty( $active_languages ) ) {
							foreach ( $active_languages as $lang_code => $lang_data ) {
								$sitepress->switch_lang( $lang_code );
								$lang_cats = get_categories(
									array(
										'orderby'    => 'name',
										'order'      => 'ASC',
										'hide_empty' => false,
									)
								);
								foreach ( $lang_cats as $cat ) {
									$all_categories_map[ $cat->term_id ] = $cat; // Store by ID
								}
							}
							$sitepress->switch_lang( $sitepress->get_current_language() );
						} else {
							$cats = get_categories(
								array(
									'orderby'    => 'name',
									'order'      => 'ASC',
									'hide_empty' => false,
								)
							);
							foreach ( $cats as $cat ) {
								$all_categories_map[ $cat->term_id ] = $cat;
							}
						}
					} else {
						// No WPML
						$cats = get_categories(
							array(
								'orderby'    => 'name',
								'order'      => 'ASC',
								'hide_empty' => false,
							)
						);
						foreach ( $cats as $cat ) {
							$all_categories_map[ $cat->term_id ] = $cat;
						}
					}

					$all_categories = array_values( $all_categories_map );
					?>
					<?php
					// ALWAYS show category info for debugging (will remove after verification)
					$selected_count = count( $selected_categories );
					?>
					<?php if ( $selected_count > 0 ) : ?>
						<div style="background: rgba(16, 185, 129, 0.15); border: 2px solid #10b981; padding: 12px 16px; margin-bottom: 12px; border-radius: 8px; font-size: 13px; box-shadow: 0 2px 8px rgba(16, 185, 129, 0.2);">
							<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px;">
								<span style="font-size: 20px;">✅</span>
								<strong style="color: #10b981; font-size: 14px;">
									<?php echo esc_html( $selected_count ); ?> categor<?php echo esc_html( $selected_count > 1 ? 'ies' : 'y' ); ?> pre-selected
								</strong>
							</div>
							<div style="color: #64748b; font-size: 11px;">
								From AI matching • Category IDs: <?php echo esc_html( implode( ', ', array_slice( $selected_categories, 0, 5 ) ) ); ?><?php echo esc_html( count( $selected_categories ) > 5 ? '...' : '' ); ?>
							</div>
						</div>
					<?php else : ?>
						<div style="background: rgba(255, 193, 7, 0.1); border-left: 3px solid #ffc107; padding: 8px 12px; margin-bottom: 8px; border-radius: 4px; font-size: 12px;">
							ℹ️ <span style="color: #f59e0b;">No categories pre-selected.</span> Select categories below for WordPress import.
						</div>
					<?php endif; ?>
					<select name="wordpress_categories[]" multiple class="panel-input"
							style="height: 150px;
									font-size: 13px;
									<?php echo esc_attr( $selected_count > 0 ? 'border: 3px solid #10b981 !important; background: rgba(16, 185, 129, 0.08) !important; box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1) !important;' : 'border: 1px solid #d1d5db;' ); ?>">
						<?php foreach ( $all_categories as $category ) : ?>
							<option value="<?php echo esc_attr( $category->term_id ); ?>"
									<?php echo esc_attr( in_array( $category->term_id, $selected_categories ) ? 'selected' : '' ); ?>
									style="<?php echo esc_attr( in_array( $category->term_id, $selected_categories ) ? 'background: #10b981; color: white; font-weight: bold;' : '' ); ?>">
								<?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>
					<p class="field-help"><?php esc_html_e( 'Hold Ctrl/Cmd to select multiple. These categories will be applied when importing to WordPress.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				</div>

				<?php if ( $entry['publication_action'] === 'update' || ! empty( $entry['existing_post_id'] ) ) : ?>
				<label><?php esc_html_e( 'Content Update Strategy', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
				<select name="content_merge_strategy" class="panel-input">
					<option value="replace" <?php selected( $entry['content_merge_strategy'] ?? 'replace', 'replace' ); ?>>🔄 Replace Entire Content</option>
					<option value="append" <?php selected( $entry['content_merge_strategy'], 'append' ); ?>>➕ Append to End</option>
					<option value="prepend" <?php selected( $entry['content_merge_strategy'], 'prepend' ); ?>>⬆️ Prepend to Beginning</option>
				</select>
				<?php endif; ?>
			</div>

			<!-- Status & Progress -->
			<div class="panel-section status-section">
				<h3>🎯 <?php esc_html_e( 'Status & Progress', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<div class="status-timeline">
					<div class="status-step <?php echo esc_attr( $entry['wisewand_status'] === 'not_created' ? 'active' : 'completed' ); ?>">
						<div class="step-icon">📝</div>
						<div class="step-label"><?php esc_html_e( 'Scheduled', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
					<div class="status-step <?php echo esc_attr( in_array( $entry['wisewand_status'], array( 'creating', 'generating' ) ) ? 'active' : ( $entry['wisewand_status'] === 'ready' ? 'completed' : '' ) ); ?>">
						<div class="step-icon">⚙️</div>
						<div class="step-label"><?php esc_html_e( 'Generating', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
					<div class="status-step <?php echo esc_attr( $entry['wisewand_status'] === 'ready' ? 'active' : ( in_array( $entry['wordpress_status'], array( 'draft', 'pending', 'published' ) ) ? 'completed' : '' ) ); ?>">
						<div class="step-icon">✅</div>
						<div class="step-label"><?php esc_html_e( 'Ready', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
					<div class="status-step <?php echo esc_attr( in_array( $entry['wordpress_status'], array( 'draft', 'pending', 'published' ) ) ? 'active' : '' ); ?>">
						<div class="step-icon">🚀</div>
						<div class="step-label"><?php esc_html_e( 'Published', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
				</div>

				<?php if ( $entry['wisewand_error'] || $entry['wordpress_error'] ) : ?>
				<div class="error-box">
					<strong>⚠️ <?php esc_html_e( 'Error:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
					<p><?php echo esc_html( $entry['wisewand_error'] ?? $entry['wordpress_error'] ); ?></p>
					<?php if ( $entry['wisewand_retry_count'] > 0 ) : ?>
					<small>
						<?php
						/* translators: %d: Current retry attempt number (1-3) */
						printf( esc_html__( 'Retry attempt: %d of 3', 'wisewand-ai-content-writer-seo-content-generator' ), absint( $entry['wisewand_retry_count'] ) );
						?>
						</small>
					<?php endif; ?>
				</div>
				<?php endif; ?>
			</div>

			<!-- Notes -->
			<div class="panel-section">
				<label><?php esc_html_e( 'Private Notes', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
				<textarea name="notes" rows="3" class="panel-input" placeholder="<?php esc_html_e( 'Add private notes about this publication...', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $entry['notes'] ?? '' ); ?></textarea>
			</div>

			<!-- Actions -->
			<div class="panel-actions">
				<button type="button" class="btn-save-entry btn-primary">💾 <?php esc_html_e( 'Save Changes', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>
				<?php if ( $entry['wisewand_status'] === 'not_created' || $entry['wisewand_status'] === 'failed' ) : ?>
				<button type="button" class="btn-generate-now btn-secondary">⚡ <?php esc_html_e( 'Generate Now', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>
				<?php endif; ?>
				<button type="button" class="btn-delete-entry btn-danger">🗑️ <?php esc_html_e( 'Delete', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>
			</div>
		</div>

		<?php
		return ob_get_clean();
	}

	// AJAX Handler - Save Entry
	public function ajax_save_entry() {
		check_ajax_referer( 'wisewand_calendar', 'nonce' );

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

		$entry_id = absint( $_POST['entry_id'] ?? 0 );

		if ( ! $entry_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid entry ID', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		try {
			$existing_entry = $this->entry_manager->get_entry( $entry_id );

			if ( is_wp_error( $existing_entry ) ) {
				throw new \Exception( $existing_entry->get_error_message() );
			}

			// For RSS entries, only allow editing specific fields
			$is_rss_entry = isset( $existing_entry['keyword_source'] ) && $existing_entry['keyword_source'] === 'rss';

			$existing_payload = $existing_entry['wisewand_payload_decoded'] ?? array();

			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Payload is a complex JSON string, decoded and sanitized later
			// jQuery sends objects as arrays, not JSON strings - no need to json_decode
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Complex array sanitized by sanitize_payload_types()
			$raw_payload = isset( $_POST['wisewand_payload'] ) ? $this->sanitize_payload_types( wp_unslash( $_POST['wisewand_payload'] ) ) : array();

			// Process CTAs array
			$ctas = array();
			if ( ! empty( $raw_payload['cta_anchors'] ) && ! empty( $raw_payload['cta_urls'] ) ) {
				$anchors = $raw_payload['cta_anchors'];
				$urls    = $raw_payload['cta_urls'];

				for ( $i = 0; $i < count( $anchors ); $i++ ) {
					if ( ! empty( $anchors[ $i ] ) && ! empty( $urls[ $i ] ) ) {
						$ctas[] = array(
							'anchor' => sanitize_text_field( $anchors[ $i ] ),
							'url'    => esc_url_raw( $urls[ $i ] ),
						);
					}
				}
			}

			if ( ! empty( $ctas ) ) {
				$raw_payload['ctas']    = $ctas;
				$raw_payload['use_cta'] = true;
			} else {
				$raw_payload['ctas']    = array();
				$raw_payload['use_cta'] = false;
			}

			// Remove temporary arrays
			unset( $raw_payload['cta_anchors'] );
			unset( $raw_payload['cta_urls'] );

			// Process social networks array
			if ( isset( $raw_payload['social_networks'] ) && is_array( $raw_payload['social_networks'] ) ) {
				$raw_payload['social_networks'] = array_map( 'sanitize_text_field', $raw_payload['social_networks'] );
			} else {
				$raw_payload['social_networks'] = array();
			}

			// Process internal links WP status array
			if ( isset( $raw_payload['internal_links_wp_status'] ) && is_array( $raw_payload['internal_links_wp_status'] ) ) {
				$raw_payload['internal_links_wp_status'] = array_map( 'sanitize_text_field', $raw_payload['internal_links_wp_status'] );
			} else {
				$raw_payload['internal_links_wp_status'] = array( 'publish' );
			}

			// Process Affiliation Links - Product Review
			$affiliation_links = array();
			if ( ! empty( $raw_payload['affiliation_link_urls'] ) && ! empty( $raw_payload['affiliation_link_anchors'] ) ) {
				$urls    = $raw_payload['affiliation_link_urls'];
				$anchors = $raw_payload['affiliation_link_anchors'];

				for ( $i = 0; $i < count( $urls ); $i++ ) {
					if ( ! empty( $urls[ $i ] ) && ! empty( $anchors[ $i ] ) ) {
						$affiliation_links[] = array(
							'url'    => esc_url_raw( $urls[ $i ] ),
							'anchor' => sanitize_text_field( $anchors[ $i ] ),
						);
					}
				}
			}
			if ( ! empty( $affiliation_links ) ) {
				$raw_payload['affiliation_links'] = $affiliation_links;
			}
			unset( $raw_payload['affiliation_link_urls'] );
			unset( $raw_payload['affiliation_link_anchors'] );

			// Process Affiliation Links - Compare Products Product 1
			$affiliation_links_1 = array();
			if ( ! empty( $raw_payload['affiliation_product_1_link_urls'] ) && ! empty( $raw_payload['affiliation_product_1_link_anchors'] ) ) {
				$urls    = $raw_payload['affiliation_product_1_link_urls'];
				$anchors = $raw_payload['affiliation_product_1_link_anchors'];

				for ( $i = 0; $i < count( $urls ); $i++ ) {
					if ( ! empty( $urls[ $i ] ) && ! empty( $anchors[ $i ] ) ) {
						$affiliation_links_1[] = array(
							'url'    => esc_url_raw( $urls[ $i ] ),
							'anchor' => sanitize_text_field( $anchors[ $i ] ),
						);
					}
				}
			}
			if ( ! empty( $affiliation_links_1 ) ) {
				$raw_payload['affiliation_links_product_1'] = $affiliation_links_1;
			}
			unset( $raw_payload['affiliation_product_1_link_urls'] );
			unset( $raw_payload['affiliation_product_1_link_anchors'] );

			// Process Affiliation Links - Compare Products Product 2
			$affiliation_links_2 = array();
			if ( ! empty( $raw_payload['affiliation_product_2_link_urls'] ) && ! empty( $raw_payload['affiliation_product_2_link_anchors'] ) ) {
				$urls    = $raw_payload['affiliation_product_2_link_urls'];
				$anchors = $raw_payload['affiliation_product_2_link_anchors'];

				for ( $i = 0; $i < count( $urls ); $i++ ) {
					if ( ! empty( $urls[ $i ] ) && ! empty( $anchors[ $i ] ) ) {
						$affiliation_links_2[] = array(
							'url'    => esc_url_raw( $urls[ $i ] ),
							'anchor' => sanitize_text_field( $anchors[ $i ] ),
						);
					}
				}
			}
			if ( ! empty( $affiliation_links_2 ) ) {
				$raw_payload['affiliation_links_product_2'] = $affiliation_links_2;
			}
			unset( $raw_payload['affiliation_product_2_link_urls'] );
			unset( $raw_payload['affiliation_product_2_link_anchors'] );

			// Process Top Products - Rename from top_products_data to affiliation_top_products
			if ( isset( $raw_payload['top_products_data'] ) ) {
				$raw_payload['affiliation_top_products'] = $raw_payload['top_products_data'];
				unset( $raw_payload['top_products_data'] );
			}

			$updated_payload = array_merge( $existing_payload, $raw_payload );

			// Get API endpoint to determine which fields to keep
			$api_endpoint = isset( $_POST['api_endpoint'] ) ? sanitize_text_field( wp_unslash( $_POST['api_endpoint'] ) ) : 'articles';

			// Auto-set fields
			$updated_payload['subject']         = $existing_entry['keyword'];
			$updated_payload['use_webhook']     = false;
			$updated_payload['use_articles_v2'] = true;

			// Clean up legacy/deprecated fields
			unset( $updated_payload['use_inline_images'] ); // Wrong field name - API uses use_inlineimages (no underscore)

			// Clean up endpoint-specific fields
			if ( $api_endpoint === 'articles' ) {
				// Remove fields that don't exist for articles endpoint
				unset( $updated_payload['website'] ); // Set by user input, but articles use home_url()
				unset( $updated_payload['writing_style'] ); // Articles use writing_style_mode instead

				// Clean up affiliation fields if NOT an affiliation type
				$article_type = $updated_payload['type'] ?? 'blog';
				if ( ! in_array( $article_type, array( 'affiliation-product-review', 'affiliation-compare-products', 'affiliation-top-product' ) ) ) {
					// Remove all affiliation fields for non-affiliation article types
					unset( $updated_payload['affiliation_product_name'] );
					unset( $updated_payload['affiliation_product_review_urls'] );
					unset( $updated_payload['affiliation_links'] );
					unset( $updated_payload['affiliation_promo_code'] );
					unset( $updated_payload['affiliation_promo_percentage'] );
					unset( $updated_payload['affiliation_product_1_name'] );
					unset( $updated_payload['affiliation_product_1_review_urls'] );
					unset( $updated_payload['affiliation_links_product_1'] );
					unset( $updated_payload['affiliation_promo_code_1'] );
					unset( $updated_payload['affiliation_promo_percentage_1'] );
					unset( $updated_payload['affiliation_product_2_name'] );
					unset( $updated_payload['affiliation_product_2_review_urls'] );
					unset( $updated_payload['affiliation_links_product_2'] );
					unset( $updated_payload['affiliation_promo_code_2'] );
					unset( $updated_payload['affiliation_promo_percentage_2'] );
					unset( $updated_payload['affiliation_top_products'] );
				}

				// Clean up type-specific affiliation fields
				if ( $article_type !== 'affiliation-product-review' ) {
					unset( $updated_payload['affiliation_product_name'] );
					unset( $updated_payload['affiliation_product_review_urls'] );
					unset( $updated_payload['affiliation_links'] );
					unset( $updated_payload['affiliation_promo_code'] );
					unset( $updated_payload['affiliation_promo_percentage'] );
				}

				if ( $article_type !== 'affiliation-compare-products' ) {
					unset( $updated_payload['affiliation_product_1_name'] );
					unset( $updated_payload['affiliation_product_1_review_urls'] );
					unset( $updated_payload['affiliation_links_product_1'] );
					unset( $updated_payload['affiliation_promo_code_1'] );
					unset( $updated_payload['affiliation_promo_percentage_1'] );
					unset( $updated_payload['affiliation_product_2_name'] );
					unset( $updated_payload['affiliation_product_2_review_urls'] );
					unset( $updated_payload['affiliation_links_product_2'] );
					unset( $updated_payload['affiliation_promo_code_2'] );
					unset( $updated_payload['affiliation_promo_percentage_2'] );
				}

				if ( $article_type !== 'affiliation-top-product' ) {
					unset( $updated_payload['affiliation_top_products'] );
				}
			} else {
				// Category/Product/Discover pages
				// Remove fields that don't exist for these endpoints
				unset( $updated_payload['keep_title'] ); // Only for articles
				unset( $updated_payload['search_intention_answer'] ); // Only for articles
				unset( $updated_payload['avoid_information'] ); // Only for articles
				unset( $updated_payload['type'] ); // Only for articles

				// Remove ALL affiliation fields (only for articles endpoint)
				unset( $updated_payload['affiliation_product_name'] );
				unset( $updated_payload['affiliation_product_review_urls'] );
				unset( $updated_payload['affiliation_links'] );
				unset( $updated_payload['affiliation_promo_code'] );
				unset( $updated_payload['affiliation_promo_percentage'] );
				unset( $updated_payload['affiliation_product_1_name'] );
				unset( $updated_payload['affiliation_product_1_review_urls'] );
				unset( $updated_payload['affiliation_links_product_1'] );
				unset( $updated_payload['affiliation_promo_code_1'] );
				unset( $updated_payload['affiliation_promo_percentage_1'] );
				unset( $updated_payload['affiliation_product_2_name'] );
				unset( $updated_payload['affiliation_product_2_review_urls'] );
				unset( $updated_payload['affiliation_links_product_2'] );
				unset( $updated_payload['affiliation_promo_code_2'] );
				unset( $updated_payload['affiliation_promo_percentage_2'] );
				unset( $updated_payload['affiliation_top_products'] );

				// For categorypages and productpages (not discoverarticles)
				if ( $api_endpoint === 'categorypages' || $api_endpoint === 'productpages' ) {
					unset( $updated_payload['keywords_secondary'] ); // Only for articles + discover
				}
			}

			// Ensure website field for categorypages/productpages/discoverarticles
			if ( in_array( $api_endpoint, array( 'categorypages', 'productpages', 'discoverarticles' ) ) ) {
				if ( empty( $updated_payload['website'] ) ) {
					$updated_payload['website'] = home_url();
				}
			}

			$country_names                   = array(
				'us' => 'United States',
				'fr' => 'France',
				'de' => 'Germany',
				'es' => 'Spain',
				'gb' => 'United Kingdom',
				'ca' => 'Canada',
			);
			$updated_payload['country_name'] = $country_names[ $updated_payload['country'] ] ?? 'United States';

			// Process target_author (from form)
			$target_author = absint( $_POST['target_author'] ?? 0 );
			if ( ! $target_author ) {
				$target_author = get_current_user_id(); // Fallback to current user
			}

			// Process wordpress_categories (array of category IDs)
			$wordpress_categories = array();
			if ( ! empty( $_POST['wordpress_categories'] ) && is_array( $_POST['wordpress_categories'] ) ) {
				$wordpress_categories = array_map( 'absint', $_POST['wordpress_categories'] );
			}

			// Process publication_time - add :00 seconds if not present
			$publication_time = isset( $_POST['publication_time'] ) ? sanitize_text_field( wp_unslash( $_POST['publication_time'] ) ) : '';
			if ( ! empty( $publication_time ) && strlen( $publication_time ) === 5 ) {
				$publication_time .= ':00'; // Add seconds (HH:MM -> HH:MM:00)
			}

			$updates = array(
				'publication_date'       => isset( $_POST['publication_date'] ) ? sanitize_text_field( wp_unslash( $_POST['publication_date'] ) ) : '',
				'publication_time'       => $publication_time, // ✅ Save exact time
				'publication_time_range' => isset( $_POST['publication_time_range'] ) ? sanitize_text_field( wp_unslash( $_POST['publication_time_range'] ) ) : 'random',
				'content_merge_strategy' => isset( $_POST['content_merge_strategy'] ) ? sanitize_text_field( wp_unslash( $_POST['content_merge_strategy'] ) ) : 'replace',
				'existing_post_id'       => absint( $_POST['existing_post_id'] ?? 0 ) ?: null,
				'target_author'          => $target_author, // ✅ Save selected author
				'wordpress_categories'   => ! empty( $wordpress_categories ) ? wp_json_encode( $wordpress_categories ) : null,
				'notes'                  => isset( $_POST['notes'] ) ? sanitize_textarea_field( wp_unslash( $_POST['notes'] ) ) : '',
				'wisewand_payload'       => wp_json_encode( $updated_payload ),
				'wisewand_lang'          => $updated_payload['lang'],
				'wisewand_type'          => $updated_payload['type'] ?? $api_endpoint, // Store type or endpoint
				'wisewand_length'        => $updated_payload['length'],
			);

			if ( $updates['existing_post_id'] ) {
				$updates['publication_action'] = 'update';
			} else {
				$updates['publication_action'] = 'create';
			}

			// For RSS entries, filter update_data to only allowed fields
			if ( $is_rss_entry ) {
				$allowed_fields_for_rss = array(
					'publication_date',
					'publication_time',
					'publication_time_range',
					'target_author',
					'wordpress_categories',
					'notes',
					'content_merge_strategy',
					'existing_post_id',
				);

				$filtered_update_data = array();
				foreach ( $updates as $key => $value ) {
					if ( in_array( $key, $allowed_fields_for_rss, true ) ) {
						$filtered_update_data[ $key ] = $value;
					}
				}
				$updates = $filtered_update_data;
			}

			$result = $this->entry_manager->update_entry( $entry_id, $updates );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			wp_send_json_success( array( 'message' => __( 'Entry saved successfully', 'wisewand-ai-content-writer-seo-content-generator' ) ) );

		} catch ( \Exception $e ) {
			$this->logger->error( 'Failed to save entry', array( 'error' => $e->getMessage() ) );
			wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
		}
	}

	// AJAX Handler - Delete Entry
	public function ajax_delete_entry() {
		check_ajax_referer( 'wisewand_calendar', 'nonce' );

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

		$entry_id = absint( $_POST['entry_id'] ?? 0 );

		if ( ! $entry_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid entry ID', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		// Check if this is an RSS entry - RSS entries cannot be deleted from calendar
		$entry = $this->entry_manager->get_entry( $entry_id );
		if ( $entry && isset( $entry['keyword_source'] ) && $entry['keyword_source'] === 'rss' ) {
			wp_send_json_error(
				array(
					'message' => __( 'RSS entries cannot be deleted directly. These entries are synced from RSS feeds. To remove them, disable the RSS feed sync or edit the feed settings.', 'wisewand-ai-content-writer-seo-content-generator' ),
				)
			);
		}

		try {
			$result = $this->entry_manager->delete_entry( $entry_id );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			wp_send_json_success( array( 'message' => __( 'Entry deleted', 'wisewand-ai-content-writer-seo-content-generator' ) ) );

		} catch ( \Exception $e ) {
			wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
		}
	}

	// AJAX Handler - Generate AI Instructions (Template)
	public function ajax_generate_instructions_template() {
		check_ajax_referer( 'wisewand_calendar', 'nonce' );

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

		$entry_id = absint( $_POST['entry_id'] ?? 0 );

		if ( ! $entry_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid entry ID', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		try {
			// Get entry to extract keyword data
			$entry = $this->entry_manager->get_entry( $entry_id );

			if ( is_wp_error( $entry ) ) {
				throw new \Exception( $entry->get_error_message() );
			}

			// Build keyword data from entry
			$keyword_data = array(
				'keyword'          => $entry['keyword'],
				'search_intent'    => $entry['search_intent'] ?? 'informational',
				'search_volume'    => $entry['search_volume'] ?? 0,
				'difficulty'       => $entry['difficulty'] ?? 50,
				'current_position' => $entry['current_position'] ?? null,
			);

			// Use existing template methods
			if ( ! class_exists( 'Wisewand\\Utils\\Wisewand_Payload_Builder' ) ) {
				require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_Payload_Builder.php';
			}

			$payload_builder = new \Wisewand\Utils\Wisewand_Payload_Builder( $this->options, $this->logger );

			// Generate using templates
			$position = $keyword_data['current_position'];
			$keyword  = $keyword_data['keyword'];
			$intent   = $keyword_data['search_intent'];

			$instructions = array();

			if ( $position && $position <= 20 ) {
				$instructions['search_intention_answer'] = sprintf(
					'This article aims to improve our current ranking (position #%d) for "%s" by providing more comprehensive, up-to-date information and better user experience.',
					$position,
					$keyword
				);
				$instructions['additional_information']  = sprintf(
					'Focus on improving existing content for "%s" (currently ranked #%d). Add fresh insights, update statistics to %s, include practical examples, and ensure the content is more comprehensive than competing pages.',
					$keyword,
					$position,
					gmdate( 'Y' )
				);
			} else {
				$intent_descriptions = array(
					'informational' => 'provide comprehensive, factual information to educate readers about',
					'commercial'    => 'help readers make informed purchase decisions regarding',
					'transactional' => 'guide users through the process of',
				);
				$description         = $intent_descriptions[ $intent ] ?? $intent_descriptions['informational'];

				$instructions['search_intention_answer'] = sprintf( 'This article will %s "%s" with practical examples and actionable insights.', $description, $keyword );

				$intent_instructions = array(
					'informational' => 'Provide in-depth, well-researched information with clear structure, practical examples, and actionable takeaways.',
					'commercial'    => 'Include detailed comparisons, pros/cons, pricing information, and clear recommendations to help buyers make decisions.',
					'transactional' => 'Create step-by-step guides with clear instructions, tips for success, and common pitfalls to avoid.',
				);
				$base_instruction    = $intent_instructions[ $intent ] ?? $intent_instructions['informational'];

				$instructions['additional_information'] = sprintf(
					'Create content about "%s". %s Focus on %s best practices and current trends.',
					$keyword,
					$base_instruction,
					gmdate( 'Y' )
				);
			}

			$instructions['avoid_information'] = sprintf(
				'Avoid outdated information, unverified claims, and overly promotional content. Do not include generic filler content or information not directly relevant to "%s". Avoid speculation without factual basis.',
				$keyword
			);

			wp_send_json_success( array( 'instructions' => $instructions ) );

		} catch ( \Exception $e ) {
			wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
		}
	}

	// AJAX Handler - Generate AI Instructions (OpenAI)
	public function ajax_generate_instructions_ai() {
		check_ajax_referer( 'wisewand_calendar', 'nonce' );

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

		$entry_id = absint( $_POST['entry_id'] ?? 0 );

		if ( ! $entry_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid entry ID', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		try {
			// Get entry to extract keyword data
			$entry = $this->entry_manager->get_entry( $entry_id );

			if ( is_wp_error( $entry ) ) {
				throw new \Exception( $entry->get_error_message() );
			}

			// Build keyword data from entry
			$keyword_data = array(
				'keyword'          => $entry['keyword'],
				'search_intent'    => $entry['search_intent'] ?? 'informational',
				'search_volume'    => $entry['search_volume'] ?? 0,
				'difficulty'       => $entry['difficulty'] ?? 50,
				'current_position' => $entry['current_position'] ?? null,
				'language_code'    => $entry['wisewand_lang'] ?? 'en',
			);

			// Use AI generation
			if ( ! class_exists( 'Wisewand\\Utils\\Wisewand_Payload_Builder' ) ) {
				require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_Payload_Builder.php';
			}

			$payload_builder = new \Wisewand\Utils\Wisewand_Payload_Builder( $this->options, $this->logger );
			$result          = $payload_builder->generate_ai_instructions( $keyword_data );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			// Update calendar entry's payload with generated instructions
			$current_payload                            = $entry['wisewand_payload_decoded'] ?? array();
			$current_payload['search_intention_answer'] = $result['search_intention_answer'] ?? '';
			$current_payload['additional_information']  = $result['additional_information'] ?? '';
			$current_payload['avoid_information']       = $result['avoid_information'] ?? '';

			// Save updated payload to database
			$update_result = $this->entry_manager->update_entry(
				$entry_id,
				array(
					'wisewand_payload' => wp_json_encode( $current_payload ),
				)
			);

			if ( is_wp_error( $update_result ) ) {
				throw new \Exception( 'Failed to save instructions: ' . $update_result->get_error_message() );
			}

			$this->logger->info(
				'AI Instructions generated and saved',
				array(
					'entry_id' => $entry_id,
					'keyword'  => $entry['keyword'],
				)
			);

			wp_send_json_success(
				array(
					'instructions' => $result,
					'saved'        => true,
				)
			);

		} catch ( \Exception $e ) {
			wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
		}
	}

	/**
	 * Get whitelist of valid fields for Wisewand API endpoint
	 */
	private function get_valid_api_fields( $endpoint, $article_type = 'blog' ) {
		// Common fields for all content types (based on official API schema)
		$common_fields = array(
			'subject',
			'title',
			'length',
			'lang',
			'country',
			'target_keyword',
			'project_id',
			'persona_id',
			'writing_style_mode',
			'additional_information',
			'use_toc',
			'use_faq',
			'faq_questions',
			'use_bulletlist',
			'use_infotable',
			'use_boldkeywords',
			'use_externalsources',
			'use_cta',
			'ctas',
			'use_social',
			'social_networks',
			'use_image',
			'image_ratio',
			'image_prompt',
			'image_use_palette',
			'image_primary_color',
			'image_secondary_color',
			'use_inlineimages',
			'inlineimages_count',
			'inline_images_ratio',
			'inline_images_use_palette',
			'inline_images_primary_color',
			'inline_images_secondary_color',
			'use_summary',
			'use_blockquotes',
			'use_audio',
			'audio_voice_id',
			'use_internallinks',
			'use_indexed_pages_internal_links',
			'use_wp_internal_links',
			'use_app_internal_links',
			'use_list_internal_links',
			'internal_links_list',
			'internal_links_wp_status',
			'internal_links_wp_connection',
			'use_webhook',
			'webhook_connection_id',
		);

		if ( $endpoint === 'articles' ) {
			// Articles-specific fields
			$fields = array_merge(
				$common_fields,
				array(
					'type',
					'keep_title',
					'keywords_secondary',
					'search_intention_answer',
					'avoid_information',
				)
			);

			// Add affiliation fields if affiliation type
			if ( $article_type === 'affiliation-product-review' ) {
				$fields = array_merge(
					$fields,
					array(
						'affiliation_product_name',
						'affiliation_product_review_urls',
						'affiliation_links',
						'affiliation_promo_code',
						'affiliation_promo_percentage',
					)
				);
			} elseif ( $article_type === 'affiliation-compare-products' ) {
				$fields = array_merge(
					$fields,
					array(
						'affiliation_product_1_name',
						'affiliation_product_1_review_urls',
						'affiliation_links_product_1',
						'affiliation_promo_code_1',
						'affiliation_promo_percentage_1',
						'affiliation_product_2_name',
						'affiliation_product_2_review_urls',
						'affiliation_links_product_2',
						'affiliation_promo_code_2',
						'affiliation_promo_percentage_2',
					)
				);
			} elseif ( $article_type === 'affiliation-top-product' ) {
				$fields = array_merge( $fields, array( 'affiliation_top_products' ) );
			}
		} elseif ( in_array( $endpoint, array( 'categorypages', 'productpages', 'discoverarticles' ) ) ) {
			// Pages-specific fields
			$fields = array_merge(
				$common_fields,
				array(
					'website',
					'writing_style',
					'use_summary',
					'use_blockquotes',
				)
			);

			// Discover articles also have keywords_secondary
			if ( $endpoint === 'discoverarticles' ) {
				$fields[] = 'keywords_secondary';
			}
		} else {
			$fields = $common_fields;
		}

		return $fields;
	}

	/**
	 * Sanitize payload data with type-aware handling
	 *
	 * Handles type preservation for integer fields that get converted to strings
	 * by map_deep() sanitization.
	 *
	 * @since 1.4.3
	 *
	 * @param array $payload Raw payload data.
	 * @return array Sanitized payload with correct types.
	 */
	private function sanitize_payload_types( $payload ) {
		// Apply text sanitization to all fields first
		$sanitized = map_deep( wp_unslash( $payload ), 'sanitize_text_field' );

		// Integer fields needing type preservation
		$integer_fields = array( 'inlineimages_count' );

		foreach ( $integer_fields as $int_field ) {
			if ( isset( $sanitized[ $int_field ] ) && is_numeric( $sanitized[ $int_field ] ) ) {
				$sanitized[ $int_field ] = absint( $sanitized[ $int_field ] );
			}
		}

		return $sanitized;
	}

	/**
	 * Build clean API payload using whitelist approach
	 */
	private function build_clean_api_payload( $raw_payload, $endpoint, $article_type = 'blog' ) {
		$valid_fields  = $this->get_valid_api_fields( $endpoint, $article_type );
		$clean_payload = array();

		foreach ( $valid_fields as $field ) {
			if ( ! isset( $raw_payload[ $field ] ) ) {
				continue;
			}

			$value = $raw_payload[ $field ];

			// Skip empty strings and nulls for optional fields
			$required_fields = array( 'subject', 'title', 'target_keyword', 'lang', 'country' );
			if ( ( $value === '' || $value === null ) && ! in_array( $field, $required_fields ) ) {
				continue;
			}

			// Handle arrays - filter out empty values more thoroughly
			if ( is_array( $value ) ) {
				// Check if this is an array of objects (associative arrays)
				$is_array_of_objects = false;
				if ( ! empty( $value ) && isset( $value[0] ) && is_array( $value[0] ) ) {
					$is_array_of_objects = true;
				}

				if ( $is_array_of_objects ) {
					// Array of objects - keep only non-empty objects
					$value = array_filter(
						$value,
						function ( $item ) {
							if ( ! is_array( $item ) ) {
								return ! empty( $item ) && $item !== '';
							}
							// For objects, check if any property has a non-empty value
							foreach ( $item as $prop_value ) {
								if ( ! empty( $prop_value ) && $prop_value !== '' ) {
									return true;
								}
							}
							return false;
						}
					);
				} else {
					// Simple array - filter out empty strings, nulls, and false values
					$value = array_filter(
						$value,
						function ( $v ) {
							// Explicitly check for empty string, null, and false
							return $v !== '' && $v !== null && $v !== false;
						}
					);
				}

				// Skip if array is now empty (except for required array fields)
				$required_arrays = array( 'social_networks', 'internal_links_wp_status' );
				if ( empty( $value ) && ! in_array( $field, $required_arrays ) ) {
					continue;
				}

				// Reset array keys to be sequential
				$value = array_values( $value );
			}

			// Type conversions for specific fields
			if ( $field === 'length' ) {
				// Length must be either integer OR string "auto"
				if ( $value !== 'auto' && is_numeric( $value ) ) {
					$value = (int) $value;
				}
			}

			// Integer fields needing type preservation
			$integer_fields = array( 'inlineimages_count' );
			if ( in_array( $field, $integer_fields ) && is_numeric( $value ) ) {
				$value = absint( $value );
			}

			// Validate country matches language (API requirement)
			if ( $field === 'country' ) {
				$lang = $raw_payload['lang'] ?? 'fr';

				// For English, only: us, gb, ca
				if ( $lang === 'en' && ! in_array( $value, array( 'us', 'gb', 'ca' ) ) ) {
					if ( WP_DEBUG ) {
						error_log( "WISEWAND: Invalid country '$value' for lang '$lang'. Defaulting to 'us'" );
					}
					$value = 'us'; // Default to US for English
				}

				// For French, only: fr, be, ch, ca
				if ( $lang === 'fr' && ! in_array( $value, array( 'fr', 'be', 'ch', 'ca' ) ) ) {
					if ( WP_DEBUG ) {
						error_log( "WISEWAND: Invalid country '$value' for lang '$lang'. Defaulting to 'fr'" );
					}
					$value = 'fr'; // Default to France for French
				}
			}

			// Boolean fields - ensure they're actual booleans, not strings
			// jQuery sends false as string "false" which (bool) converts to TRUE! Use filter_var instead.
			$boolean_fields = array(
				'keep_title',
				'use_toc',
				'use_summary',
				'use_faq',
				'use_bulletlist',
				'use_blockquotes',
				'use_infotable',
				'use_boldkeywords',
				'use_externalsources',
				'use_cta',
				'use_social',
				'use_image',
				'image_use_palette',
				'use_inlineimages',
				'inline_images_use_palette',
				'use_audio',
				'use_internallinks',
				'use_indexed_pages_internal_links',
				'use_wp_internal_links',
				'use_app_internal_links',
				'use_list_internal_links',
				'use_webhook',
				'use_publishwordpress',
			);
			if ( in_array( $field, $boolean_fields ) ) {
				// filter_var properly handles: "true"→true, "false"→false, "1"→true, "0"→false, 1→true, 0→false
				$value = filter_var( $value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE );
				if ( $value === null ) {
					$value = false; // Default to false for invalid boolean values
				}
			}

			$clean_payload[ $field ] = $value;
		}

		return $clean_payload;
	}

	// AJAX Handler - Generate Now (COMPLETELY REWRITTEN - v3.1 - 2025-10-03 17:15 - PRODUCTION READY)
	public function ajax_generate_now() {
		// VERSION MARKER - This will appear in AJAX response if v3.1 is running
		$version_marker = 'WISEWAND_V3.1_2025-10-03_17:15_FINAL_PRODUCTION';
		if ( WP_DEBUG ) {
			error_log( "=== $version_marker - Function Called ===" );
		}

		check_ajax_referer( 'wisewand_calendar', 'nonce' );

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

		$entry_id = absint( $_POST['entry_id'] ?? 0 );

		if ( ! $entry_id ) {
			wp_send_json_error(
				array(
					'message' => __( 'Invalid entry ID', 'wisewand-ai-content-writer-seo-content-generator' ),
					'version' => $version_marker,
				)
			);
		}

		try {
			// Get entry
			$entry = $this->entry_manager->get_entry( $entry_id );
			if ( is_wp_error( $entry ) ) {
				throw new \Exception( $entry->get_error_message() );
			}

			// Get API key
			$api_key = $this->options->get( 'wisewand_api_key' );
			if ( empty( $api_key ) ) {
				throw new \Exception( __( 'Wisewand API key not configured', 'wisewand-ai-content-writer-seo-content-generator' ) );
			}

			// Process submitted form data (same as ajax_save_entry)
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Payload is a complex JSON string, decoded and sanitized later
			// jQuery sends objects as arrays, not JSON strings - no need to json_decode
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Complex array sanitized by sanitize_payload_types()
			$raw_payload  = isset( $_POST['wisewand_payload'] ) ? $this->sanitize_payload_types( wp_unslash( $_POST['wisewand_payload'] ) ) : array();
			$api_endpoint = isset( $_POST['api_endpoint'] ) ? sanitize_text_field( wp_unslash( $_POST['api_endpoint'] ) ) : 'articles';

			$existing_entry = $this->entry_manager->get_entry( $entry_id );
			if ( is_wp_error( $existing_entry ) ) {
				throw new \Exception( $existing_entry->get_error_message() );
			}

			// Process submitted payload (same logic as ajax_save_entry)
			$existing_payload = $existing_entry['wisewand_payload_decoded'] ?? array();
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Payload is a complex JSON string, decoded and sanitized later
			// jQuery sends objects as arrays, not JSON strings - no need to json_decode
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Complex array sanitized by sanitize_payload_types()
			$raw_payload      = isset( $_POST['wisewand_payload'] ) ? $this->sanitize_payload_types( wp_unslash( $_POST['wisewand_payload'] ) ) : array();

			// Process CTAs array
			$ctas = array();
			if ( ! empty( $raw_payload['cta_anchors'] ) && ! empty( $raw_payload['cta_urls'] ) ) {
				$anchors = $raw_payload['cta_anchors'];
				$urls    = $raw_payload['cta_urls'];
				for ( $i = 0; $i < count( $anchors ); $i++ ) {
					if ( ! empty( $anchors[ $i ] ) && ! empty( $urls[ $i ] ) ) {
						$ctas[] = array(
							'anchor' => sanitize_text_field( $anchors[ $i ] ),
							'url'    => esc_url_raw( $urls[ $i ] ),
						);
					}
				}
			}
			if ( ! empty( $ctas ) ) {
				$raw_payload['ctas']    = $ctas;
				$raw_payload['use_cta'] = true;
			}
			unset( $raw_payload['cta_anchors'] );
			unset( $raw_payload['cta_urls'] );

			// Process social networks
			if ( isset( $raw_payload['social_networks'] ) && is_array( $raw_payload['social_networks'] ) ) {
				$raw_payload['social_networks'] = array_map( 'sanitize_text_field', $raw_payload['social_networks'] );
			}

			// Process internal links WP status array
			if ( isset( $raw_payload['internal_links_wp_status'] ) && is_array( $raw_payload['internal_links_wp_status'] ) ) {
				$raw_payload['internal_links_wp_status'] = array_map( 'sanitize_text_field', $raw_payload['internal_links_wp_status'] );
			}

			// Process Affiliation Links - Product Review
			$affiliation_links = array();
			if ( ! empty( $raw_payload['affiliation_link_urls'] ) && ! empty( $raw_payload['affiliation_link_anchors'] ) ) {
				$urls    = $raw_payload['affiliation_link_urls'];
				$anchors = $raw_payload['affiliation_link_anchors'];

				for ( $i = 0; $i < count( $urls ); $i++ ) {
					if ( ! empty( $urls[ $i ] ) && ! empty( $anchors[ $i ] ) ) {
						$affiliation_links[] = array(
							'url'    => esc_url_raw( $urls[ $i ] ),
							'anchor' => sanitize_text_field( $anchors[ $i ] ),
						);
					}
				}
			}
			if ( ! empty( $affiliation_links ) ) {
				$raw_payload['affiliation_links'] = $affiliation_links;
			}
			unset( $raw_payload['affiliation_link_urls'] );
			unset( $raw_payload['affiliation_link_anchors'] );

			// Process Affiliation Links - Compare Products Product 1
			$affiliation_links_1 = array();
			if ( ! empty( $raw_payload['affiliation_product_1_link_urls'] ) && ! empty( $raw_payload['affiliation_product_1_link_anchors'] ) ) {
				$urls    = $raw_payload['affiliation_product_1_link_urls'];
				$anchors = $raw_payload['affiliation_product_1_link_anchors'];

				for ( $i = 0; $i < count( $urls ); $i++ ) {
					if ( ! empty( $urls[ $i ] ) && ! empty( $anchors[ $i ] ) ) {
						$affiliation_links_1[] = array(
							'url'    => esc_url_raw( $urls[ $i ] ),
							'anchor' => sanitize_text_field( $anchors[ $i ] ),
						);
					}
				}
			}
			if ( ! empty( $affiliation_links_1 ) ) {
				$raw_payload['affiliation_links_product_1'] = $affiliation_links_1;
			}
			unset( $raw_payload['affiliation_product_1_link_urls'] );
			unset( $raw_payload['affiliation_product_1_link_anchors'] );

			// Process Affiliation Links - Compare Products Product 2
			$affiliation_links_2 = array();
			if ( ! empty( $raw_payload['affiliation_product_2_link_urls'] ) && ! empty( $raw_payload['affiliation_product_2_link_anchors'] ) ) {
				$urls    = $raw_payload['affiliation_product_2_link_urls'];
				$anchors = $raw_payload['affiliation_product_2_link_anchors'];

				for ( $i = 0; $i < count( $urls ); $i++ ) {
					if ( ! empty( $urls[ $i ] ) && ! empty( $anchors[ $i ] ) ) {
						$affiliation_links_2[] = array(
							'url'    => esc_url_raw( $urls[ $i ] ),
							'anchor' => sanitize_text_field( $anchors[ $i ] ),
						);
					}
				}
			}
			if ( ! empty( $affiliation_links_2 ) ) {
				$raw_payload['affiliation_links_product_2'] = $affiliation_links_2;
			}
			unset( $raw_payload['affiliation_product_2_link_urls'] );
			unset( $raw_payload['affiliation_product_2_link_anchors'] );

			// Process Top Products
			if ( isset( $raw_payload['top_products_data'] ) ) {
				$raw_payload['affiliation_top_products'] = $raw_payload['top_products_data'];
				unset( $raw_payload['top_products_data'] );
			}

			$updated_payload = array_merge( $existing_payload, $raw_payload );
			$api_endpoint    = isset( $_POST['api_endpoint'] ) ? sanitize_text_field( wp_unslash( $_POST['api_endpoint'] ) ) : 'articles';

			// Clean up endpoint-specific fields (same as save handler)
			$updated_payload['subject']         = $existing_entry['keyword'];
			$updated_payload['use_webhook']     = false;
			$updated_payload['use_articles_v2'] = true;

			// Clean up legacy/deprecated fields
			unset( $updated_payload['use_inline_images'] ); // Wrong field name - API uses use_inlineimages (no underscore)

			// Field cleanup logic (COMPLETE - same as ajax_save_entry)
			if ( $api_endpoint === 'articles' ) {
				unset( $updated_payload['website'] );
				unset( $updated_payload['writing_style'] );

				// Clean up affiliation fields if NOT an affiliation type
				$article_type = $updated_payload['type'] ?? 'blog';
				if ( ! in_array( $article_type, array( 'affiliation-product-review', 'affiliation-compare-products', 'affiliation-top-product' ) ) ) {
					// Remove ALL affiliation fields for non-affiliation article types
					unset( $updated_payload['affiliation_product_name'] );
					unset( $updated_payload['affiliation_product_review_urls'] );
					unset( $updated_payload['affiliation_links'] );
					unset( $updated_payload['affiliation_promo_code'] );
					unset( $updated_payload['affiliation_promo_percentage'] );
					unset( $updated_payload['affiliation_product_1_name'] );
					unset( $updated_payload['affiliation_product_1_review_urls'] );
					unset( $updated_payload['affiliation_links_product_1'] );
					unset( $updated_payload['affiliation_promo_code_1'] );
					unset( $updated_payload['affiliation_promo_percentage_1'] );
					unset( $updated_payload['affiliation_product_2_name'] );
					unset( $updated_payload['affiliation_product_2_review_urls'] );
					unset( $updated_payload['affiliation_links_product_2'] );
					unset( $updated_payload['affiliation_promo_code_2'] );
					unset( $updated_payload['affiliation_promo_percentage_2'] );
					unset( $updated_payload['affiliation_top_products'] );
				}

				// Clean up type-specific affiliation fields
				if ( $article_type !== 'affiliation-product-review' ) {
					unset( $updated_payload['affiliation_product_name'] );
					unset( $updated_payload['affiliation_product_review_urls'] );
					unset( $updated_payload['affiliation_links'] );
					unset( $updated_payload['affiliation_promo_code'] );
					unset( $updated_payload['affiliation_promo_percentage'] );
				}
				if ( $article_type !== 'affiliation-compare-products' ) {
					unset( $updated_payload['affiliation_product_1_name'] );
					unset( $updated_payload['affiliation_product_1_review_urls'] );
					unset( $updated_payload['affiliation_links_product_1'] );
					unset( $updated_payload['affiliation_promo_code_1'] );
					unset( $updated_payload['affiliation_promo_percentage_1'] );
					unset( $updated_payload['affiliation_product_2_name'] );
					unset( $updated_payload['affiliation_product_2_review_urls'] );
					unset( $updated_payload['affiliation_links_product_2'] );
					unset( $updated_payload['affiliation_promo_code_2'] );
					unset( $updated_payload['affiliation_promo_percentage_2'] );
				}
				if ( $article_type !== 'affiliation-top-product' ) {
					unset( $updated_payload['affiliation_top_products'] );
				}
			} else {
				// Category/Product/Discover pages
				unset( $updated_payload['keep_title'] );
				unset( $updated_payload['search_intention_answer'] );
				unset( $updated_payload['avoid_information'] );
				unset( $updated_payload['type'] );

				// Remove ALL affiliation fields (only for articles endpoint)
				unset( $updated_payload['affiliation_product_name'] );
				unset( $updated_payload['affiliation_product_review_urls'] );
				unset( $updated_payload['affiliation_links'] );
				unset( $updated_payload['affiliation_promo_code'] );
				unset( $updated_payload['affiliation_promo_percentage'] );
				unset( $updated_payload['affiliation_product_1_name'] );
				unset( $updated_payload['affiliation_product_1_review_urls'] );
				unset( $updated_payload['affiliation_links_product_1'] );
				unset( $updated_payload['affiliation_promo_code_1'] );
				unset( $updated_payload['affiliation_promo_percentage_1'] );
				unset( $updated_payload['affiliation_product_2_name'] );
				unset( $updated_payload['affiliation_product_2_review_urls'] );
				unset( $updated_payload['affiliation_links_product_2'] );
				unset( $updated_payload['affiliation_promo_code_2'] );
				unset( $updated_payload['affiliation_promo_percentage_2'] );
				unset( $updated_payload['affiliation_top_products'] );

				if ( $api_endpoint === 'categorypages' || $api_endpoint === 'productpages' ) {
					unset( $updated_payload['keywords_secondary'] );
				}
			}

			$country_names                   = array(
				'us' => 'United States',
				'fr' => 'France',
				'de' => 'Germany',
				'es' => 'Spain',
				'gb' => 'United Kingdom',
				'ca' => 'Canada',
			);
			$updated_payload['country_name'] = $country_names[ $updated_payload['country'] ] ?? 'United States';

			// SAVE THE UPDATED ENTRY
			$updates = array(
				'wisewand_payload' => wp_json_encode( $updated_payload ),
				'wisewand_lang'    => $updated_payload['lang'],
				'wisewand_type'    => $updated_payload['type'] ?? $api_endpoint,
				'wisewand_length'  => $updated_payload['length'],
				'wisewand_status'  => 'creating', // Set to creating
				'wisewand_error'   => null,
			);

			$this->entry_manager->update_entry( $entry_id, $updates );

			// STEP 2: NOW GENERATE with the fresh payload
			$api_key = $this->options->get( 'wisewand_api_key' );
			if ( empty( $api_key ) ) {
				throw new \Exception( __( 'Wisewand API key not configured', 'wisewand-ai-content-writer-seo-content-generator' ) );
			}

			if ( ! class_exists( 'Wisewand\\Utils\\Wisewand_API_Client' ) ) {
				require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_API_Client.php';
			}

			$api_client = new \Wisewand\Utils\Wisewand_API_Client( $api_key, $this->logger );

			// Build clean payload using whitelist (CLEAN & RELIABLE)
			$article_type  = $updated_payload['type'] ?? 'blog';
			$clean_payload = $this->build_clean_api_payload( $updated_payload, $api_endpoint, $article_type );

			// DETAILED LOGGING: Log exact payload being sent to API
			if ( WP_DEBUG ) {
				error_log( '=== WISEWAND API REQUEST ===' );
				error_log( 'Entry ID: ' . $entry_id );
				error_log( 'Endpoint: ' . $api_endpoint );
				error_log( 'Article Type: ' . $article_type );
				error_log( 'Clean Payload Fields: ' . implode( ', ', array_keys( $clean_payload ) ) );
				error_log( 'Full Clean Payload JSON: ' . wp_json_encode( $clean_payload, JSON_PRETTY_PRINT ) );
				error_log( '===========================' );
			}

			$this->logger->info(
				'Generate Now: Sending to API',
				array(
					'entry_id'           => $entry_id,
					'endpoint'           => $api_endpoint,
					'article_type'       => $article_type,
					'clean_fields_count' => count( $clean_payload ),
					'clean_fields'       => array_keys( $clean_payload ),
				)
			);

			// Send payload directly (NO wrapper - API expects fields at root level)
			$article = $api_client->create_content( $api_endpoint, $clean_payload );

			if ( is_wp_error( $article ) ) {
				$error_message = esc_html( $article->get_error_message() );
				$error_data    = $article->get_error_data();

				// Enhanced error logging
				if ( WP_DEBUG ) {
					error_log( '=== GENERATE NOW ERROR ===' );
					error_log( 'Error Message: ' . $error_message );
					error_log( 'Error Data: ' . print_r( $error_data, true ) );
					error_log( '=========================' );
				}

				$this->logger->error(
					'Generate Now: API rejected payload',
					array(
						'error_message' => $error_message,
						'error_data'    => $error_data,
						'http_status'   => $error_data['status_code'] ?? 'unknown',
						'api_response'  => $error_data['response_data'] ?? 'none',
						'endpoint'      => $api_endpoint,
						'entry_id'      => $entry_id,
						'sent_payload'  => $clean_payload,
					)
				);

				// Build detailed error with payload info for debugging
				$payload_fields = array_keys( $clean_payload );
				sort( $payload_fields );

				$user_error = 'Generation failed: ' . $error_message;
				if ( ! empty( $error_data['status_code'] ) ) {
					$user_error .= ' (HTTP ' . $error_data['status_code'] . ')';
				}
				if ( ! empty( $error_data['response_data']['error'] ) ) {
					$user_error .= "\n\nAPI Error: " . $error_data['response_data']['error'];
				}
				if ( ! empty( $error_data['response_data']['message'] ) ) {
					$user_error .= "\n\nDetails: " . $error_data['response_data']['message'];
				}

				// Add payload info for debugging (will appear in error response)
				$user_error .= "\n\n[DEBUG] Sent " . count( $payload_fields ) . ' fields: ' . implode( ', ', $payload_fields );

				// Create detailed exception with payload data
				$exception = new \Exception( $user_error );

				// Store payload info to include in JSON response
				$this->_last_error_debug = array(
					'sent_fields'      => $payload_fields,
					'sent_field_count' => count( $payload_fields ),
					'clean_payload'    => $clean_payload,
				);

				throw $exception;
			}

			$article_id = $article['id'] ?? null;
			if ( ! $article_id ) {
				throw new \Exception( __( 'No content ID returned from Wisewand', 'wisewand-ai-content-writer-seo-content-generator' ) );
			}

			// Store article ID
			$this->entry_manager->update_entry(
				$entry_id,
				array(
					'wisewand_article_id' => $article_id,
				)
			);

			// Trigger generation
			$run_result = $api_client->run_content_generation( $api_endpoint, $article_id );

			if ( is_wp_error( $run_result ) ) {
				$error_msg = esc_html( $run_result->get_error_message() );

				// Special case: "already running or in queue" is not a real error
				// Article was created successfully, just can't run it right now
				if ( stripos( $error_msg, 'already running' ) !== false || stripos( $error_msg, 'in queue' ) !== false ) {
					// Update status to generating (it's already queued)
					$this->entry_manager->update_entry(
						$entry_id,
						array(
							'wisewand_status'         => 'generating',
							'generation_triggered_at' => current_time( 'mysql' ),
						)
					);

					$this->logger->info(
						'Generate Now: Article already in queue',
						array(
							'entry_id'   => $entry_id,
							'article_id' => $article_id,
						)
					);

					wp_send_json_success(
						array(
							'message'      => __( 'Article created and queued for generation!', 'wisewand-ai-content-writer-seo-content-generator' ),
							'article_id'   => $article_id,
							'wisewand_url' => 'https://app.wisewand.ai/articles/' . $article_id . '/result',
							'status'       => 'generating',
							'note'         => 'Generation already in progress',
							'version'      => $version_marker,
						)
					);
				}

				// Real error - throw it
				throw new \Exception( $error_msg );
			}

			// Update status to generating
			$this->entry_manager->update_entry(
				$entry_id,
				array(
					'wisewand_status'         => 'generating',
					'generation_triggered_at' => current_time( 'mysql' ),
				)
			);

			$this->logger->info(
				'Generate Now: Success',
				array(
					'entry_id'   => $entry_id,
					'article_id' => $article_id,
				)
			);

			wp_send_json_success(
				array(
					'message'      => __( 'Article generation started successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'article_id'   => $article_id,
					'wisewand_url' => 'https://app.wisewand.ai/articles/' . $article_id . '/result',
					'status'       => 'generating',
					'version'      => $version_marker, // Version confirmation
				)
			);

		} catch ( \Exception $e ) {
			$this->logger->error(
				'Generate Now failed',
				array(
					'entry_id' => $entry_id,
					'error'    => $e->getMessage(),
				)
			);

			$this->entry_manager->update_entry(
				$entry_id,
				array(
					'wisewand_status' => 'failed',
					'wisewand_error'  => $e->getMessage(),
				)
			);

			// Include debug info if available
			$error_response = array(
				'message' => $e->getMessage(),
				'version' => $version_marker, // Version confirmation
			);

			// Add payload debugging info if we have it
			if ( isset( $this->_last_error_debug ) ) {
				$error_response['debug'] = $this->_last_error_debug;
			}

			wp_send_json_error( $error_response );
		}
	}

	/**
	 * AJAX Handler - Import Now (manual immediate import)
	 */
	public function ajax_import_now() {
		check_ajax_referer( 'wisewand_calendar', 'nonce' );

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

		$entry_id = absint( $_POST['entry_id'] ?? 0 );

		if ( ! $entry_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid entry ID', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		try {
			// Get entry
			$entry = $this->entry_manager->get_entry( $entry_id );
			if ( is_wp_error( $entry ) ) {
				throw new \Exception( esc_html( $entry->get_error_message() ) );
			}

			// Check if already imported
			if ( ! empty( $entry['wordpress_post_id'] ) ) {
				throw new \Exception( __( 'This entry has already been imported', 'wisewand-ai-content-writer-seo-content-generator' ) );
			}

			// Check if content is ready
			if ( $entry['wisewand_status'] !== 'ready' ) {
				throw new \Exception( __( 'Content is not ready for import yet', 'wisewand-ai-content-writer-seo-content-generator' ) );
			}

			// Load Calendar_CRON
			if ( ! class_exists( 'Wisewand\\Automation\\Calendar_CRON' ) ) {
				require_once WISEWAND_PLUGIN_DIR . 'includes/Automation/Calendar_CRON.php';
			}

			// Load Content_Manager
			if ( ! class_exists( 'Wisewand\\Content\\Content_Manager' ) ) {
				require_once WISEWAND_PLUGIN_DIR . 'includes/Content/Content_Manager.php';
			}

			$content_manager = new \Wisewand\Content\Content_Manager( $this->options, $this->logger );
			$calendar_cron   = new \Wisewand\Automation\Calendar_CRON(
				$this->options,
				$this->logger,
				$content_manager
			);

			// Import using reflection to access private method
			$reflection = new \ReflectionClass( $calendar_cron );
			$method     = $reflection->getMethod( 'import_and_publish_entry' );
			$method->setAccessible( true );
			$result = $method->invoke( $calendar_cron, $entry );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( esc_html( $result->get_error_message() ) );
			}

			$this->logger->info(
				'Manual import successful',
				array(
					'entry_id' => $entry_id,
					'post_id'  => $result,
				)
			);

			wp_send_json_success(
				array(
					'message'  => __( 'Article imported successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'post_id'  => $result,
					'edit_url' => get_edit_post_link( $result, 'raw' ),
					'view_url' => get_permalink( $result ),
				)
			);

		} catch ( \Exception $e ) {
			$this->logger->error(
				'Manual import failed',
				array(
					'entry_id' => $entry_id,
					'error'    => $e->getMessage(),
				)
			);

			wp_send_json_error(
				array(
					'message' => $e->getMessage(),
				)
			);
		}
	}

	private function determine_endpoint_from_type( $wisewand_type ) {
		if ( $wisewand_type === 'categorypage' || $wisewand_type === 'categorypages' ) {
			return 'categorypages';
		}
		if ( $wisewand_type === 'productpage' || $wisewand_type === 'productpages' ) {
			return 'productpages';
		}
		if ( $wisewand_type === 'discoverarticles' ) {
			return 'discoverarticles';
		}
		return 'articles';
	}

	// AJAX Handler - Get Projects List
	public function ajax_get_projects() {
		$this->logger->info( 'AJAX: ajax_get_projects called' );

		check_ajax_referer( 'wisewand_calendar', 'nonce' );

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

		try {
			$api_key = $this->options->get( 'wisewand_api_key' );

			if ( empty( $api_key ) ) {
				$this->logger->error( 'AJAX: API key not configured' );
				wp_send_json_error( array( 'message' => __( 'Wisewand API key not configured', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
				return;
			}

			if ( ! class_exists( 'Wisewand\\Utils\\Wisewand_API_Client' ) ) {
				require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_API_Client.php';
			}

			$api_client = new \Wisewand\Utils\Wisewand_API_Client( $api_key, $this->logger );
			$this->logger->info( 'AJAX: Calling list_projects with force_refresh=true' );
			$result = $api_client->list_projects( array( 'take' => 100 ), true );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			$projects = array();
			foreach ( $result['items'] ?? array() as $project ) {
				$projects[] = array(
					'id'      => $project['id'] ?? '',
					'name'    => $project['name'] ?? 'Unnamed Project',
					'website' => $project['website'] ?? '',
				);
			}

			$this->logger->info( 'AJAX: Returning ' . count( $projects ) . ' projects' );
			wp_send_json_success( array( 'projects' => $projects ) );

		} catch ( \Exception $e ) {
			$this->logger->error( 'AJAX: Failed to fetch projects', array( 'error' => $e->getMessage() ) );
			wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
		}
	}

	// AJAX Handler - Get Single Project Details (including brief)
	public function ajax_get_project_details() {
		check_ajax_referer( 'wisewand_settings', 'nonce' );

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

		$project_id = isset( $_POST['project_id'] ) ? sanitize_text_field( wp_unslash( $_POST['project_id'] ) ) : '';

		if ( empty( $project_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Project ID required', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		try {
			$api_key = $this->options->get( 'wisewand_api_key' );

			if ( empty( $api_key ) ) {
				throw new \Exception( __( 'Wisewand API key not configured', 'wisewand-ai-content-writer-seo-content-generator' ) );
			}

			if ( ! class_exists( 'Wisewand\\Utils\\Wisewand_API_Client' ) ) {
				require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_API_Client.php';
			}

			$api_client = new \Wisewand\Utils\Wisewand_API_Client( $api_key, $this->logger );
			$result     = $api_client->get_project( $project_id );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			$project = array(
				'id'      => $result['id'] ?? $project_id,
				'name'    => $result['name'] ?? 'Unnamed Project',
				'brief'   => $result['brief'] ?? '',
				'website' => $result['website'] ?? '',
			);

			wp_send_json_success( array( 'project' => $project ) );

		} catch ( \Exception $e ) {
			$this->logger->error(
				'Failed to fetch project details',
				array(
					'project_id' => $project_id,
					'error'      => $e->getMessage(),
				)
			);
			wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
		}
	}

	// AJAX Handler - Get Personas List
	public function ajax_get_personas() {
		$this->logger->info( 'AJAX: ajax_get_personas called' );

		check_ajax_referer( 'wisewand_calendar', 'nonce' );

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

		try {
			$api_key = $this->options->get( 'wisewand_api_key' );

			if ( empty( $api_key ) ) {
				$this->logger->error( 'AJAX: API key not configured' );
				wp_send_json_error( array( 'message' => __( 'Wisewand API key not configured', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
				return;
			}

			if ( ! class_exists( 'Wisewand\\Utils\\Wisewand_API_Client' ) ) {
				require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_API_Client.php';
			}

			$api_client = new \Wisewand\Utils\Wisewand_API_Client( $api_key, $this->logger );
			$this->logger->info( 'AJAX: Calling list_personas with force_refresh=true' );
			$result = $api_client->list_personas( array( 'take' => 100 ), true );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			$personas = array();
			foreach ( $result['items'] ?? array() as $persona ) {
				$personas[] = array(
					'id'          => $persona['id'] ?? '',
					'name'        => $persona['name'] ?? 'Unnamed Persona',
					'description' => $persona['description'] ?? '',
				);
			}

			$this->logger->info( 'AJAX: Returning ' . count( $personas ) . ' personas' );
			wp_send_json_success( array( 'personas' => $personas ) );

		} catch ( \Exception $e ) {
			$this->logger->error( 'AJAX: Failed to fetch personas', array( 'error' => $e->getMessage() ) );
			wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
		}
	}

	private function find_related_pages( $keyword ) {
		global $wpdb;

		$like_keyword = '%' . $wpdb->esc_like( $keyword ) . '%';

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct query more efficient than WP_Query for content search with CASE ordering
		$related = $wpdb->get_results(
			$wpdb->prepare(
				"
            SELECT ID, post_title, post_type, post_modified, post_content
            FROM {$wpdb->posts}
            WHERE (post_title LIKE %s OR post_content LIKE %s)
            AND post_status IN ('publish', 'draft', 'pending')
            AND post_type IN ('post', 'page', 'product')
            ORDER BY
                CASE
                    WHEN post_title LIKE %s THEN 1
                    ELSE 2
                END,
                post_modified DESC
            LIMIT 5
        ",
				$like_keyword,
				$like_keyword,
				$like_keyword
			)
		);

		return $related;
	}

	// AJAX Handler - Manual CRON Trigger
	public function ajax_trigger_manual_cron() {
		check_ajax_referer( 'wisewand_calendar', 'nonce' );

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

		try {
			$this->logger->info( 'Manual CRON trigger started' );

			$start_time = microtime( true );

			if ( ! class_exists( 'Wisewand\\Automation\\Calendar_CRON' ) ) {
				require_once WISEWAND_PLUGIN_DIR . 'includes/Automation/Calendar_CRON.php';
			}

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

			if ( ! $content_manager ) {
				throw new \Exception( 'Content Manager not initialized' );
			}

			$calendar_cron = new \Wisewand\Automation\Calendar_CRON(
				$this->options,
				$this->logger,
				$content_manager
			);

			$calendar_cron->run();

			$elapsed = round( microtime( true ) - $start_time, 2 );

			$summary            = $calendar_cron->get_cron_summary();
			$summary['elapsed'] = $elapsed;

			wp_send_json_success(
				array(
					'summary' => $summary,
					'message' => __( 'Automation completed successfully', 'wisewand-ai-content-writer-seo-content-generator' ),
				)
			);

		} catch ( \Exception $e ) {
			$this->logger->error( 'Manual CRON failed', array( 'error' => $e->getMessage() ) );
			wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
		}
	}

}