<?php
/**
 * WordAI Agent Indexing Page — refined button & layout alignment
 */
if ( ! defined( 'ABSPATH' ) ) exit;
$is_basic_tier          = class_exists( 'SftcyWordaiFeatures' ) && SftcyWordaiFeatures::wordai_is_basic_tier();
$embedding_limits       = class_exists( 'SftcyWordaiFeatures' ) ? SftcyWordaiFeatures::wordai_get_feature_limits( 'contents_embedding' ) : array();
$embedding_item_limit   = ! empty( $embedding_limits['maxItems'] ) ? max( 1, (int) $embedding_limits['maxItems'] ) : 5;
$embedding_limit_label  = ! empty( $embedding_limits['label'] ) ? $embedding_limits['label'] : sprintf( __( 'Embed up to %d posts, pages, products, or CPT items', 'wordai' ), $embedding_item_limit );
$upgrade_url            = class_exists( 'SftcyWordaiFeatures' ) ? SftcyWordaiFeatures::wordai_get_upgrade_url() : 'https://softcoy.com/products/wordai-pro/checkout';
$embedding_product_url  = 'https://softcoy.com/products/wordai-pro';
$embedded_item_count    = class_exists( 'SftcyWordaiOpenaiAgentAjax' ) && method_exists( 'SftcyWordaiOpenaiAgentAjax', 'get_embedded_item_count' )
	? SftcyWordaiOpenaiAgentAjax::get_embedded_item_count()
	: 0;
$is_embedding_limit_reached = $is_basic_tier && $embedding_item_limit > 0 && $embedded_item_count >= $embedding_item_limit;
$current_provider       = SftcyWordaiBase::sc_wordai_get_current_ai_provider();
$openai_models          = class_exists( 'SftcyWordaiAgentOpenai' ) ? SftcyWordaiAgentOpenai::embedding_models() : [
	'text-embedding-3-small' => 'text-embedding-3-small',
	'text-embedding-3-large' => 'text-embedding-3-large',
];
$gemini_models          = [
	'gemini-embedding-001' => 'gemini-embedding-001 (Recommended)',
];
$xai_models             = class_exists( 'SftcyWordaiAgentXai' ) ? SftcyWordaiAgentXai::embedding_models() : [
	'grok-embedding-small' => 'grok-embedding-small (Recommended)',
];
$last_model             = get_option( 'sc_wordai_agent_last_embedding_model_' . $current_provider, '' );

if ( $current_provider === 'google' && in_array( $last_model, [ '', 'text-embedding-004', 'multimodalembedding-001' ], true ) ) {
	$last_model = 'gemini-embedding-001';
}

if ( $current_provider === 'openai' && class_exists( 'SftcyWordaiAgentOpenai' ) ) {
	$last_model = SftcyWordaiAgentOpenai::normalize_embedding_model( $last_model );
}

$anthropic_models = class_exists( 'SftcyWordaiAgentAnthropic' )
	? SftcyWordaiAgentAnthropic::voyage_models()
	: [];

if ( $current_provider === 'anthropic' && $last_model === '' && class_exists( 'SftcyWordaiAgentAnthropic' ) ) {
	$last_model = SftcyWordaiAgentAnthropic::DEFAULT_EMBEDDING_MODEL;
}

if ( $current_provider === 'xai' && class_exists( 'SftcyWordaiAgentXai' ) ) {
	$last_model = SftcyWordaiAgentXai::normalize_embedding_model( $last_model );
}
include_once SFTCY_WORDAI_PLUGIN_DIR . 'admin/views/settings-pages-header-template.php';
?>

<div id="openai-agent-settings-wrapper" class="">
	<h3 style="padding: 15px;">
		<span class="sc-wordai-settings-icon dashicons dashicons-database-add"></span>
		<?php esc_html_e('Contents Embedding & Indexing', 'wordai-pro'); ?>
	</h3>

	<div class="sc-wordai-compact-toggle">
		<label><input type="checkbox" id="scWordaiCompactToggle" /> <span>💎 Minimal Mode</span></label>
	</div>

	<?php if ( $is_basic_tier ) : ?>
		<div class="notice notice-info inline wordai-tier-inline-notice wordai-tier-inline-notice-agent">
			<p>
				<strong><?php esc_html_e( 'WordAI Free includes the full AI Agent workflow for a small live sample.', 'wordai' ); ?></strong>
				<?php echo esc_html( $embedding_limit_label ); ?>.
				<?php esc_html_e( 'Use this to test embedding, retrieval, and chat behavior before upgrading the knowledge base capacity.', 'wordai' ); ?>
				<a class="button button-small wordai-tier-inline-cta" href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Get Pro', 'wordai' ); ?></a>
			</p>
		</div>
	<?php endif; ?>

	<?php if ( $is_embedding_limit_reached ) : ?>
		<div class="notice notice-warning inline wordai-tier-inline-notice wordai-tier-inline-notice-agent">
			<p>
				<strong>
					<?php
					printf(
						esc_html__( 'You have embedded your allowed %d content items already.', 'wordai' ),
						(int) $embedding_item_limit
					);
					?>
				</strong>
				<?php esc_html_e( 'To embed more or unlimited posts, pages, products, or CPT contents, upgrade to WordAI Pro.', 'wordai' ); ?>
				<a class="button button-small wordai-tier-inline-cta" href="<?php echo esc_url( $embedding_product_url ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Upgrade to WordAI Pro', 'wordai' ); ?></a>
			</p>
		</div>
	<?php endif; ?>

	<div class="wordai-agent-global-controls">
		<div class="wordai-agent-embedding-options-panel <?php echo ( $current_provider === 'anthropic' && class_exists( 'SftcyWordaiAgentAnthropic' ) ) ? 'has-embedding-key-card' : ''; ?>">
			<div class="wordai-agent-embedding-option-card wordai-agent-embedding-option-card-model">
				<div class="wordai-agent-embedding-option-heading">
					<span class="dashicons dashicons-networking"></span>
					<strong><?php esc_html_e( 'Embedding Model', 'wordai-pro' ); ?></strong>
				</div>
				<p><?php esc_html_e( 'Choose the embedding model WordAI will use when indexing the selected content types for website AI Chat answers.', 'wordai-pro' ); ?></p>
				<select id="wa-embed-model" class="sc-wordai-embed-model-select">
					<?php if ( $current_provider === 'google' ) : ?>
						<?php foreach ( $gemini_models as $value => $label ) : ?>
							<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $last_model, $value ); ?>>
								<?php echo esc_html( $label ); ?>
							</option>
						<?php endforeach; ?>
					<?php elseif ( $current_provider === 'anthropic' ) : ?>
						<?php foreach ( $anthropic_models as $group_label => $group_models ) : ?>
							<optgroup label="<?php echo esc_attr( $group_label ); ?>">
								<?php foreach ( $group_models as $value => $label ) : ?>
									<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $last_model, $value ); ?>>
										<?php echo esc_html( $label ); ?>
									</option>
								<?php endforeach; ?>
							</optgroup>
						<?php endforeach; ?>
					<?php elseif ( $current_provider === 'xai' ) : ?>
						<?php foreach ( $xai_models as $value => $label ) : ?>
							<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $last_model, $value ); ?>>
								<?php echo esc_html( $label ); ?>
							</option>
						<?php endforeach; ?>
					<?php else : ?>
						<?php foreach ( $openai_models as $value => $label ) : ?>
							<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $last_model, $value ); ?>>
								<?php echo esc_html( $label ); ?>
							</option>
						<?php endforeach; ?>
					<?php endif; ?>
				</select>
				<div class="sc-wordai-hint-box wordai-agent-embedding-model-hint">
					<?php if ( $current_provider === 'google' ) : ?>
						💡 <strong>Gemini Embedding tips:</strong><br>
						<strong>gemini-embedding-001</strong> — Current supported Gemini embedding model for WordPress content search and AI chat retrieval.<br><br>
						If your site was indexed earlier with older Gemini embedding models, run indexing again so the chat agent uses the new supported vectors.
					<?php elseif ( $current_provider === 'anthropic' ) : ?>
						💡 <strong>Voyage Embedding tips for Anthropic:</strong><br>
						<strong>voyage-4-lite</strong> — Recommended default for faster indexing and lower cost while keeping retrieval quality strong.<br><br>
						<strong>voyage-4 / voyage-4-large</strong> — Use for larger or more technical knowledge bases when you want stronger semantic retrieval accuracy.
					<?php elseif ( $current_provider === 'xai' ) : ?>
						💡 <strong>xAI Grok Embedding tips:</strong><br>
						<strong>grok-embedding-small</strong> — Recommended for indexing WordPress content for Grok-powered AI chat retrieval. After changing providers, re-run indexing so stored vectors match the selected provider.
					<?php else : ?>
						💡 <strong>Model selection tips (OpenAI):</strong><br>
						<strong>text-embedding-3-small</strong> — Fast and cost-efficient, ideal for most WordPress sites with hundreds or thousands of posts.<br><br>
						<strong>text-embedding-3-large</strong> — Use for high-value knowledge bases or technical content that needs deeper semantic precision.
					<?php endif; ?>
				</div>
			</div>

			<?php if ( $current_provider === 'anthropic' && class_exists( 'SftcyWordaiAgentAnthropic' ) ) : ?>
				<?php
				$anthropic_embed_settings = SftcyWordaiAgentAnthropic::get_settings();
				$voyage_real_key         = $anthropic_embed_settings['voyage_api_key'] ?? '';
				$voyage_mask             = SftcyWordaiAgentAnthropic::get_voyage_api_key_mask();
				$voyage_configured       = ! empty( $voyage_real_key );
				?>
				<div class="wordai-agent-embedding-option-card wordai-agent-embedding-option-card-key">
					<div class="wordai-agent-embedding-option-heading">
						<span class="dashicons dashicons-admin-network"></span>
						<strong><?php esc_html_e( 'Voyage API Key', 'wordai-pro' ); ?></strong>
					</div>
					<p><?php esc_html_e( 'Anthropic website embeddings use Voyage AI for vectors while Claude remains the chat provider.', 'wordai-pro' ); ?></p>
					<div class="wrap anthropic-api-key-save-div-wrapper sc-wordai-embed-key-stack">
						<div class="sc-wordai-embed-key-label <?php echo $voyage_configured ? esc_attr( 'success-msg' ) : ''; ?>">
							<i class="fa-solid fa-key"></i> <?php esc_html_e( 'Voyage API Key', 'wordai-pro' ); ?>
						</div>
						<div class="sc-wordai-embed-key-input-row">
							<input type="text" id="wa-anthropic-voyage-api-key" class="wordai-anthropic-api-key-data" data-real="<?php echo esc_attr( $voyage_real_key ); ?>" data-mask="<?php echo esc_attr( $voyage_mask ); ?>" <?php echo $voyage_configured ? 'value="' . esc_attr( $voyage_mask ) . '"' : 'placeholder="' . esc_attr( $voyage_mask ) . '" value=""'; ?> autocomplete="off" />
						</div>
						<div class="sc-wordai-embed-key-actions">
							<label for="wa-anthropic-voyage-show-key" class="sc-wordai-embed-key-toggle">
								<input type="checkbox" id="wa-anthropic-voyage-show-key" />
								<i class="fa-solid fa-eye" title="<?php esc_attr_e( 'Show/Hide API Key', 'wordai-pro' ); ?>"></i>
								<span><?php esc_html_e( 'Show / Hide API Key', 'wordai-pro' ); ?></span>
							</label>
							<button type="button" class="button button-primary sc-wordai-save-apikey-submit-btn" id="wa-anthropic-voyage-save-btn">
								<i class="fa-solid fa-hard-drive"></i> <?php esc_html_e( 'Save', 'wordai-pro' ); ?>
							</button>
						</div>
					</div>
					<p class="description">
						<?php esc_html_e( 'Save your Voyage API key to enable Anthropic content embedding and RAG search. Leave it empty if you do not want to replace the currently saved key.', 'wordai-pro' ); ?>
						<a href="https://dashboard.voyageai.com/organization/api-keys" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Create or manage your Voyage API key', 'wordai-pro' ); ?></a>.
					</p>
					<p class="description" id="wa-anthropic-voyage-status" style="<?php echo $voyage_configured ? 'color:#00a32a;' : 'color:#b32d2e;'; ?>">
						<?php echo esc_html( $voyage_configured ? __( 'Voyage API key is configured.', 'wordai-pro' ) : __( 'Voyage API key is not configured yet.', 'wordai-pro' ) ); ?>
					</p>
				</div>
			<?php endif; ?>
		</div>
	</div>

	<div class="wordai-options-grid wordai-agent-embedding-grid" <?php echo $is_basic_tier ? 'data-wordai-free-embedding-limit="' . esc_attr( $embedding_item_limit ) . '"' : ''; ?>>

		<!-- 🔹 CARD 1: Scan & Estimate -->
		<div class="wordai-card wordai-agent-scan-estimate-card" hidden aria-hidden="true">
			<div class="wordai-card-header">🔍 <?php esc_html_e('Scan & Estimate', 'wordai-pro'); ?></div>

			<p class="sc-wordai-settings-text-hints">
				<?php esc_html_e('Select which post types should be scanned and estimated for token & cost before indexing.', 'wordai-pro'); ?>
			</p>

			<?php if ( false ) : // Moved to the visible global controls above while keeping the hidden estimate card available for later review. ?>
			<!-- Model -->
			<div style="margin-bottom:15px;">
				<strong><?php esc_html_e('Embedding Model', 'wordai-pro'); ?></strong><br>

				<?php
				$openai_models = class_exists( 'SftcyWordaiAgentOpenai' ) ? SftcyWordaiAgentOpenai::embedding_models() : [
					'text-embedding-3-small' => 'text-embedding-3-small',
					'text-embedding-3-large' => 'text-embedding-3-large',
				];

				$gemini_models = [
					'gemini-embedding-001' => 'gemini-embedding-001 (Recommended)',
				];

				$last_model = get_option( 'sc_wordai_agent_last_embedding_model_' . $current_provider, '' );

				if ( $current_provider === 'google' && in_array( $last_model, [ '', 'text-embedding-004', 'multimodalembedding-001' ], true ) ) {
					$last_model = 'gemini-embedding-001';
				}

				$anthropic_models = class_exists( 'SftcyWordaiAgentAnthropic' )
					? SftcyWordaiAgentAnthropic::voyage_models()
					: [];

				if ( $current_provider === 'anthropic' && $last_model === '' && class_exists( 'SftcyWordaiAgentAnthropic' ) ) {
					$last_model = SftcyWordaiAgentAnthropic::DEFAULT_EMBEDDING_MODEL;
				}
				?>

				<?php if ( $current_provider === 'anthropic' && class_exists( 'SftcyWordaiAgentAnthropic' ) ) : ?>
					<?php
					$anthropic_embed_settings = SftcyWordaiAgentAnthropic::get_settings();
					$voyage_real_key         = $anthropic_embed_settings['voyage_api_key'] ?? '';
					$voyage_mask             = SftcyWordaiAgentAnthropic::get_voyage_api_key_mask();
					$voyage_configured       = ! empty( $voyage_real_key );
					?>
					<div class="notice notice-info inline" style="margin: 0 0 15px;">
						<p><?php esc_html_e( 'Anthropic website embeddings use Voyage AI. Claude remains the chat provider, while Voyage generates the embedding vectors stored under the Anthropic provider in WordAI.', 'wordai-pro' ); ?></p>
					</div>

					<div style="margin-bottom:15px;">
						<div class="wrap anthropic-api-key-save-div-wrapper sc-wordai-embed-key-stack" style="margin-top:8px;">
							<div class="sc-wordai-embed-key-label <?php echo $voyage_configured ? esc_attr( 'success-msg' ) : ''; ?>">
								<i class="fa-solid fa-key"></i> <?php esc_html_e('Voyage API Key', 'wordai-pro'); ?>
							</div>
							<div class="sc-wordai-embed-key-input-row">
								<input
									type="text"
									id="wa-anthropic-voyage-api-key"
									class="wordai-anthropic-api-key-data"
									data-real="<?php echo esc_attr( $voyage_real_key ); ?>"
									data-mask="<?php echo esc_attr( $voyage_mask ); ?>"
									<?php if ( $voyage_configured ) : ?>
										value="<?php echo esc_attr( $voyage_mask ); ?>"
									<?php else : ?>
										placeholder="<?php echo esc_attr( $voyage_mask ); ?>"
										value=""
									<?php endif; ?>
									autocomplete="off"
								/>
							</div>
							<div class="sc-wordai-embed-key-actions">
								<label for="wa-anthropic-voyage-show-key" class="sc-wordai-embed-key-toggle">
									<input type="checkbox" id="wa-anthropic-voyage-show-key" />
									<i class="fa-solid fa-eye" title="<?php esc_attr_e( 'Show/Hide API Key', 'wordai-pro' ); ?>"></i>
									<span><?php esc_html_e('Show / Hide API Key', 'wordai-pro'); ?></span>
								</label>
								<button type="button" class="button button-primary sc-wordai-save-apikey-submit-btn" id="wa-anthropic-voyage-save-btn">
									<i class="fa-solid fa-hard-drive"></i> <?php esc_html_e('Save', 'wordai-pro'); ?>
								</button>
							</div>
						</div>
						<p class="description">
							<?php esc_html_e( 'Save your Voyage API key here to enable Anthropic content embedding and RAG search. Leave the field empty if you do not want to replace the currently saved key.', 'wordai-pro' ); ?>
							<a href="https://dashboard.voyageai.com/organization/api-keys" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Create or manage your Voyage API key', 'wordai-pro' ); ?></a>.
						</p>
						<p class="description" id="wa-anthropic-voyage-status" style="<?php echo $voyage_configured ? 'color:#00a32a;' : 'color:#b32d2e;'; ?>">
							<?php echo esc_html( $voyage_configured ? __( 'Voyage API key is configured.', 'wordai-pro' ) : __( 'Voyage API key is not configured yet.', 'wordai-pro' ) ); ?>
						</p>
					</div>
				<?php endif; ?>

				<div class="sc-wordai-embed-model-select-wrap">
					<select id="wa-embed-model" class="sc-wordai-embed-model-select">
						<?php if ( $current_provider === 'google' ) : ?>
							<?php foreach ( $gemini_models as $value => $label ) : ?>
								<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $last_model, $value ); ?>>	
									<?php echo esc_html( $label ); ?>
								</option>
							<?php endforeach; ?>
						<?php elseif ( $current_provider === 'anthropic' ) : ?>
							<?php foreach ( $anthropic_models as $group_label => $group_models ) : ?>
								<optgroup label="<?php echo esc_attr( $group_label ); ?>">
									<?php foreach ( $group_models as $value => $label ) : ?>
										<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $last_model, $value ); ?>>
											<?php echo esc_html( $label ); ?>
										</option>
									<?php endforeach; ?>
								</optgroup>
							<?php endforeach; ?>
						<?php else : ?>
							<?php foreach ( $openai_models as $value => $label ) : ?>
								<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $last_model, $value ); ?>>
									<?php echo esc_html( $label ); ?>
								</option>
							<?php endforeach; ?>
						<?php endif; ?>
					</select>
				</div>

				<div class="sc-wordai-hint-box">
					<?php if ( $current_provider === 'google' ) : ?>
						💡 <strong>Gemini Embedding tips:</strong><br>
						<strong>gemini-embedding-001</strong> — Current supported Gemini embedding model for WordPress content search and AI chat retrieval.<br><br>
						If your site was indexed earlier with older Gemini embedding models, run indexing again so the chat agent uses the new supported vectors.
					<?php elseif ( $current_provider === 'anthropic' ) : ?>
						💡 <strong>Voyage Embedding tips for Anthropic:</strong><br>
						<strong>voyage-4-lite</strong> — Recommended default for faster indexing and lower cost while keeping retrieval quality strong.<br><br>
						<strong>voyage-4 / voyage-4-large</strong> — Use for larger or more technical knowledge bases when you want stronger semantic retrieval accuracy.
					<?php else : ?>
						💡 <strong>Model selection tips (OpenAI):</strong><br>
						<strong>text-embedding-3-small</strong> — Fast and cost-efficient, ideal for most WordPress sites with hundreds or thousands of posts.
						It performs at nearly the same quality as <code>3-large</code> while being cheaper.<br><br>
						<strong>text-embedding-3-large</strong> — Offers deeper semantic understanding and slightly higher precision.
						Recommended for high-value knowledge bases or technical content.
					<?php endif; ?>
				</div>
			</div>

			<?php endif; ?>

			<!-- Chunk Size -->
			<div style="margin-bottom:15px;">
				<strong><?php esc_html_e('Chunk Size (tokens per chunk)', 'wordai-pro'); ?></strong><br>
				<input type="number" id="wa-chunk-size" value="800" min="100" max="2000" step="100" style="margin-top:6px; width:150px;" />
			</div>

			<!-- Result Messages -->
			<div id="wa-estimate-result" class="sc-wordai-estimate-notice" style="display:none;"></div>

			<!-- Action Button -->
			<div class="card-actions">
				<button id="wa-estimate" class="button button-primary">
					<i class="fa-solid fa-calculator"></i>
					<span><?php esc_html_e('Estimate Cost', 'wordai-pro'); ?></span>
				</button>
			</div>
		</div>

		<!-- 🔹 CARD 2: Indexing Process -->
		<div class="wordai-card">
			<div class="wordai-card-header">⚙️ <?php esc_html_e('Start Indexing', 'wordai-pro'); ?></div>

			<div class="wordai-agent-start-indexing-controls">
				<div class="wordai-agent-global-control-header">
					<div>
						<h4><?php esc_html_e( 'Content Types to Embed', 'wordai-pro' ); ?></h4>
						<p><?php esc_html_e( 'Choose which published WordPress content types should be added to the AI Agent knowledge base before indexing.', 'wordai-pro' ); ?></p>
					</div>
					<?php if ( $is_basic_tier ) : ?>
						<span class="wordai-agent-limit-badge"><?php echo esc_html( $embedding_limit_label ); ?></span>
					<?php endif; ?>
				</div>
				<details class="wordai-agent-post-type-dropdown">
					<summary>
						<span class="wordai-agent-post-type-summary-text"><?php esc_html_e( 'Posts and Pages selected', 'wordai-pro' ); ?></span>
						<span class="dashicons dashicons-arrow-down-alt2"></span>
					</summary>
					<div class="wordai-agent-post-type-menu">
						<div class="wordai-agent-post-type-actions">
							<button type="button" class="button button-small wordai-agent-select-all-post-types"><?php esc_html_e( 'Select All', 'wordai-pro' ); ?></button>
							<button type="button" class="button button-small wordai-agent-clear-post-types"><?php esc_html_e( 'Clear', 'wordai-pro' ); ?></button>
						</div>
						<div class="wordai-checkbox-group wordai-agent-post-type-options">
							<?php
							$post_types = get_post_types( array( 'public' => true ), 'objects' );
							foreach ( $post_types as $pt ) {
								$name    = $pt->labels->singular_name;
								$slug    = $pt->name;
								$checked = in_array( $slug, array( 'post', 'page' ), true ) ? 'checked' : '';
								printf(
									'<label>
										<input type="checkbox" class="wa-cpt" value="%1$s" data-label="%2$s" %3$s>
										<span>%2$s</span>
										<small>%1$s</small>
									</label>',
									esc_attr( $slug ),
									esc_html( $name ),
									$checked
								);
							}
							?>
						</div>
					</div>
				</details>
			</div>

			<p class="sc-wordai-settings-text-hints" style="margin-bottom:18px;">
				<?php esc_html_e('Begin embedding selected contents into the local AI Agent database. You can safely stay on this page while progress updates automatically.', 'wordai-pro'); ?>
			</p>
			<p class="sc-wordai-settings-text-hints alert-info" style="margin-bottom:18px;">
				<?php esc_html_e('Tip: indexed content becomes the knowledge base for the frontend AI Chat agent. After indexing, visitor questions can be matched with your pages, posts, products, or CPT content before WordAI prepares the reply.', 'wordai-pro'); ?>
			</p>

			<div id="wa-progress" style="display:none; margin-top:10px; margin-bottom:20px;">
				<div class="wa-progress-bar"
					style="width:0%; height:20px; background:linear-gradient(90deg,#0073aa,#2296e3);
						   border-radius:5px; transition:width 0.4s ease;"></div>
				<p class="wa-progress-label" style="margin-top:8px; text-align:center; font-weight:600;">0%</p>
			</div>
			<p class="wa-progress-eta" style="text-align:center; font-style:italic; color:#666; display:none;">~Calculating time remaining…</p>

			<div class="card-actions">
				<button id="wa-start-indexing" class="button button-primary">
					<i class="fa-solid fa-play"></i>
					<span><?php esc_html_e('Start Indexing', 'wordai-pro'); ?></span>
				</button>
				<button id="wa-cancel-indexing" class="button button-secondary" style="display:none; margin-left:8px;">
					<i class="fa-solid fa-stop"></i>
					<span><?php esc_html_e('Cancel', 'wordai-pro'); ?></span>
				</button>
			</div>

		</div>

		<!-- 🔹 CARD 3: Summary Status / Logs -->
		<div class="wordai-card">
			<div class="wordai-card-header">📊 <?php esc_html_e('Indexing Summary', 'wordai-pro'); ?></div>

			<p class="sc-wordai-settings-text-hints" style="margin-bottom:18px;">
				<?php esc_html_e('Check the latest summary of your indexed content and track when the last indexing job ran.', 'wordai-pro'); ?>
			</p>

			<table class="widefat striped" style="margin-top:10px;">
				<tbody>
					<tr><td><strong>✅ <?php esc_html_e('Indexed', 'wordai-pro'); ?></strong></td><td id="wa-total-indexed">0</td></tr>
					<tr><td><strong>❌ <?php esc_html_e('Failed', 'wordai-pro'); ?></strong></td><td id="wa-total-failed">0</td></tr>
					<tr><td><strong>🟠 <?php esc_html_e('Cancelled', 'wordai-pro'); ?></strong></td><td id="wa-total-cancelled">0</td></tr>
					<tr>
						<td><strong>🕒 <?php esc_html_e('Last Run', 'wordai-pro'); ?></strong></td><?php
						$provider_last_run = get_option( 'sc_wordai_agent_last_run_' . $current_provider, '' );
						if ( $provider_last_run === '' ) {
							$provider_last_run = get_option( 'sc_wordai_agent_last_run', __( 'N/A', 'wordai-pro' ) );
						}
						?>
						<td id="wa-last-run"><?php echo esc_html( $provider_last_run ); ?></td>
					</tr>
				</tbody>
			</table>

			<div class="card-actions">
				<button id="wa-refresh-status" class="button button-secondary">
					<i class="fa-solid fa-rotate"></i>
					<span><?php esc_html_e('Refresh Status', 'wordai-pro'); ?></span>
				</button>
				<button id="wa-view-failed" class="button button-small" style="margin-left:8px; vertical-align:bottom;">
					<i class="fa-solid fa-circle-info" style="vertical-align: sub; color:orangered;"></i>
					<span><?php esc_html_e('View Failed', 'wordai-pro'); ?></span>
				</button>
			</div>
		</div>

		<!-- 🔹 CARD 4: Source Item Selection -->
		<div class="wordai-card wordai-agent-source-selection-card"
			data-embedding-limit="<?php echo esc_attr( $is_basic_tier ? $embedding_item_limit : 0 ); ?>"
			data-upgrade-url="<?php echo esc_url( $embedding_product_url ); ?>">
			<div class="wordai-card-header">📚 <?php esc_html_e( 'Content Items to Embed', 'wordai' ); ?></div>

			<div class="wordai-agent-source-selection-intro">
				<div>
					<p class="sc-wordai-settings-text-hints">
						<?php esc_html_e( 'Choose the exact posts, pages, products, or CPT entries that should become AI Agent knowledge. The selection is shared across all AI providers.', 'wordai' ); ?>
					</p>
					<?php if ( $is_basic_tier ) : ?>
						<p class="wordai-agent-source-limit-message">
							<?php
							printf(
								esc_html__( 'Free/basic mode allows %d selected content items total. Re-indexing already selected items remains available.', 'wordai' ),
								(int) $embedding_item_limit
							);
							?>
						</p>
					<?php endif; ?>
				</div>
				<div class="wordai-agent-source-counts">
					<span id="wa-source-selected-count">0</span>
					<span><?php echo esc_html( $is_basic_tier ? sprintf( __( '/ %d selected', 'wordai' ), (int) $embedding_item_limit ) : __( 'selected', 'wordai' ) ); ?></span>
				</div>
			</div>

			<div id="wa-source-tabs" class="wordai-agent-source-tabs" aria-label="<?php esc_attr_e( 'Selected content type tabs', 'wordai' ); ?>"></div>

			<div class="wordai-agent-source-toolbar">
				<label>
					<span class="screen-reader-text"><?php esc_html_e( 'Search content items', 'wordai' ); ?></span>
					<input type="search" id="wa-source-search" placeholder="<?php esc_attr_e( 'Search selected content type...', 'wordai' ); ?>">
				</label>
				<select id="wa-source-status-filter" aria-label="<?php esc_attr_e( 'Filter embedding status', 'wordai' ); ?>">
					<option value="all"><?php esc_html_e( 'All statuses', 'wordai' ); ?></option>
					<option value="embedded"><?php esc_html_e( 'Embedded', 'wordai' ); ?></option>
					<option value="needs_embedding"><?php esc_html_e( 'Needs embedding', 'wordai' ); ?></option>
					<option value="needs_reindex"><?php esc_html_e( 'Re-index required', 'wordai' ); ?></option>
					<option value="failed"><?php esc_html_e( 'Failed', 'wordai' ); ?></option>
				</select>
				<button type="button" id="wa-source-refresh" class="button button-secondary">
					<i class="fa-solid fa-rotate"></i>
					<span><?php esc_html_e( 'Refresh Items', 'wordai' ); ?></span>
				</button>
			</div>

			<div class="wordai-agent-source-table-wrap">
				<table class="widefat striped wordai-agent-source-table">
					<thead>
						<tr>
							<th style="width:58px;"><?php esc_html_e( 'Use', 'wordai' ); ?></th>
							<th><?php esc_html_e( 'Content', 'wordai' ); ?></th>
							<th style="width:150px;"><?php esc_html_e( 'Status', 'wordai' ); ?></th>
							<th style="width:155px;"><?php esc_html_e( 'Modified', 'wordai' ); ?></th>
							<th style="width:155px;"><?php esc_html_e( 'Last Embedded', 'wordai' ); ?></th>
						</tr>
					</thead>
					<tbody id="wa-source-items">
						<tr><td colspan="5"><?php esc_html_e( 'Loading content items...', 'wordai' ); ?></td></tr>
					</tbody>
				</table>
			</div>

			<div class="wordai-agent-source-pagination">
				<button type="button" id="wa-source-prev" class="button button-secondary"><?php esc_html_e( 'Previous', 'wordai' ); ?></button>
				<span id="wa-source-page-label"><?php esc_html_e( 'Page 1 of 1', 'wordai' ); ?></span>
				<button type="button" id="wa-source-next" class="button button-secondary"><?php esc_html_e( 'Next', 'wordai' ); ?></button>
			</div>
		</div>

		<!-- 🔍 Failed Items Modal -->
		<div id="wa-failed-modal"
			title="<?php esc_attr_e('❌ Failed Items', 'wordai-pro'); ?>"
			style="display:none;">
			<div class="inside" style="max-height:420px; overflow-y:auto; padding:6px 3px;">
				<table class="widefat striped" style="margin:0;">
					<thead>
						<tr>
							<th style="width:60px; text-align:center;"><i class="fa-solid fa-hashtag"></i> ID</th>
							<th style="width:80px;"><i class="fa-solid fa-layer-group"></i> Type</th>
							<th><i class="fa-regular fa-file-lines"></i> Title / Edit Link</th>
							<th><i class="fa-solid fa-triangle-exclamation"></i> Error Message</th>
						</tr>
					</thead>
					<tbody id="wa-failed-list">
						<tr><td colspan="4" style="text-align:center;"><?php esc_html_e('Loading…', 'wordai-pro'); ?></td></tr>
					</tbody>
				</table>
			</div>
		</div>

		
	</div><!-- /.wordai-options-grid -->


	<!-- 🔸 Verbose Logging Toggle -->
	<div style="margin-top:10px; font-size:12px; color:#555; text-align:left;">
		<label>
			<input type="checkbox" id="wa-enable-logging" value="1" style="vertical-align:middle; margin-right:5px;">
			<?php esc_html_e('Enable Verbose Logging (debug.log)', 'wordai-pro'); ?>
		</label>
	</div>

</div>
<script>
(function () {
	var root = document.getElementById('openai-agent-settings-wrapper');
	if (!root) {
		return;
	}

	var summary = root.querySelector('.wordai-agent-post-type-summary-text');
	var checkboxes = Array.prototype.slice.call(root.querySelectorAll('.wa-cpt'));

	function updateSummary() {
		var selected = checkboxes.filter(function (checkbox) {
			return checkbox.checked;
		}).map(function (checkbox) {
			return checkbox.getAttribute('data-label') || checkbox.value;
		});

		if (!summary) {
			return;
		}

		if (selected.length === 0) {
			summary.textContent = 'No content types selected';
		} else if (selected.length === checkboxes.length) {
			summary.textContent = 'All content types selected';
		} else if (selected.length === 1) {
			summary.textContent = selected[0] + ' selected';
		} else {
			summary.textContent = selected.slice(0, 2).join(', ') + (selected.length > 2 ? ' +' + (selected.length - 2) : '') + ' selected';
		}
	}

	checkboxes.forEach(function (checkbox) {
		checkbox.addEventListener('change', updateSummary);
	});

	var selectAll = root.querySelector('.wordai-agent-select-all-post-types');
	if (selectAll) {
		selectAll.addEventListener('click', function () {
			checkboxes.forEach(function (checkbox) {
				checkbox.checked = true;
				checkbox.dispatchEvent(new Event('change', { bubbles: true }));
			});
			updateSummary();
		});
	}

	var clearAll = root.querySelector('.wordai-agent-clear-post-types');
	if (clearAll) {
		clearAll.addEventListener('click', function () {
			checkboxes.forEach(function (checkbox) {
				checkbox.checked = false;
				checkbox.dispatchEvent(new Event('change', { bubbles: true }));
			});
			updateSummary();
		});
	}

	updateSummary();
}());
</script>
