<?php
/**
 * RAG Management Page Template
 *
 * @package Askany
 */

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

// Check if compatible embedding provider API key is available
$has_openai_key = !empty(get_option('askany_api_key_openai'));
$has_gemini_key = !empty(get_option('askany_api_key_gemini'));
$has_embedding_provider = $has_openai_key || $has_gemini_key;
$rag_enabled = get_option('askany_rag_enabled', false);

// Get dismissed notice state
$dismissed_notice_type = get_option('askany_rag_notice_dismissed', '');

// Get the ACTIVE provider from settings
$active_provider = get_option('askany_api_provider', 'deepseek');
$selected_embedding_model = get_option('askany_embedding_model', ''); // Custom model selection

// Check if active provider supports embeddings
$active_supports_embeddings = in_array($active_provider, array('openai', 'gemini'));

// Determine which provider will be used for embeddings
$provider_name = '';
$provider_model = '';
$provider_info = '';
$can_change_model = false;
$show_fallback_notice = false;

// Define available models for each provider
$openai_models = array(
	'text-embedding-3-small' => __('text-embedding-3-small (1536 dim, recommended)', 'askany'),
	'text-embedding-3-large' => __('text-embedding-3-large (3072 dim, higher quality)', 'askany'),
	'text-embedding-ada-002' => __('text-embedding-ada-002 (1536 dim, legacy)', 'askany'),
);

$gemini_models = array(
	'gemini-embedding-001' => __('gemini-embedding-001 (768 dim, current model)', 'askany'),
);

// Check if the active provider supports embeddings
if ($active_provider === 'openai' && $has_openai_key) {
	$provider_name = 'OpenAI';
	// Use saved model if it's an OpenAI model, otherwise use default
	$is_openai_model = array_key_exists($selected_embedding_model, $openai_models);
	$provider_model = ($is_openai_model && $selected_embedding_model) ? $selected_embedding_model : 'text-embedding-3-small';
	$provider_info = __('Supports multiple embedding models with different dimensions', 'askany');
	$can_change_model = true;
	$available_models = $openai_models;
} elseif ($active_provider === 'gemini' && $has_gemini_key) {
	$provider_name = 'Google Gemini';
	// Use saved model if it's a Gemini model, otherwise use default
	$is_gemini_model = array_key_exists($selected_embedding_model, $gemini_models);
	$provider_model = ($is_gemini_model && $selected_embedding_model) ? $selected_embedding_model : 'gemini-embedding-001';
	$provider_info = __('768 dimensions, multilingual support', 'askany');
	$can_change_model = true;
	$available_models = $gemini_models;
} else {
	// Active provider doesn't support embeddings - show fallback
	$show_fallback_notice = true;
	
	if ($has_openai_key) {
		$provider_name = 'OpenAI';
		$is_openai_model = array_key_exists($selected_embedding_model, $openai_models);
		$provider_model = ($is_openai_model && $selected_embedding_model) ? $selected_embedding_model : 'text-embedding-3-small';
		$provider_info = __('Supports multiple embedding models with different dimensions', 'askany');
		$can_change_model = true;
		$available_models = $openai_models;
	} elseif ($has_gemini_key) {
		$provider_name = 'Google Gemini';
		$is_gemini_model = array_key_exists($selected_embedding_model, $gemini_models);
		$provider_model = ($is_gemini_model && $selected_embedding_model) ? $selected_embedding_model : 'gemini-embedding-001';
		$provider_info = __('768 dimensions, multilingual support', 'askany');
		$can_change_model = true;
		$available_models = $gemini_models;
	}
}

// Auto-save the default model if not set or if it doesn't match the current provider
if ($can_change_model && (!$selected_embedding_model || 
    ($provider_name === 'OpenAI' && !array_key_exists($selected_embedding_model, $openai_models)) ||
    ($provider_name === 'Google Gemini' && !array_key_exists($selected_embedding_model, $gemini_models)))) {
	update_option('askany_embedding_model', $provider_model);
}
?>

<div class="wrap askany-rag-management">
	<h1><?php esc_html_e('RAG Management', 'askany'); ?></h1>
	<p class="description">
		<?php esc_html_e('Manage embeddings for Retrieval-Augmented Generation (RAG). Monitor processing status, retry failed items, and regenerate all embeddings.', 'askany'); ?>
	</p>

	<?php if (!$has_embedding_provider): ?>
		<div class="notice notice-error">
			<p>
				<strong><?php esc_html_e('No Embedding Provider Configured', 'askany'); ?></strong><br>
				<?php esc_html_e('RAG requires an OpenAI or Google Gemini API key. Please configure an API key in Settings to use RAG features.', 'askany'); ?>
			</p>
			<p>
				<a href="<?php echo esc_url(admin_url('admin.php?page=askany-settings')); ?>" class="button button-primary">
					<?php esc_html_e('Go to Settings', 'askany'); ?>
				</a>
			</p>
		</div>
		<style>
			.askany-rag-management .askany-rag-content {
				opacity: 0.3;
				pointer-events: none;
			}
		</style>
	<?php endif; ?>

	<?php if (!$rag_enabled && $has_embedding_provider): ?>
		<div class="notice notice-warning">
			<p>
				<strong><?php esc_html_e('RAG is Currently Disabled', 'askany'); ?></strong><br>
				<?php esc_html_e('Enable RAG in Settings to start generating embeddings and use semantic search.', 'askany'); ?>
			</p>
			<p>
				<a href="<?php echo esc_url(admin_url('admin.php?page=askany-settings')); ?>" class="button button-primary">
					<?php esc_html_e('Enable RAG in Settings', 'askany'); ?>
				</a>
			</p>
		</div>
	<?php endif; ?>

	<?php if ($show_fallback_notice && $has_embedding_provider): ?>
		<div class="notice notice-info">
			<p>
				<strong><?php esc_html_e('Active Provider Does Not Support Embeddings', 'askany'); ?></strong><br>
				<?php 
				printf(
					__('Your active provider is <strong>%s</strong>, which does not support embeddings. RAG will use <strong>%s</strong> for embeddings instead.', 'askany'),
					esc_html(ucfirst($active_provider)),
					esc_html($provider_name)
				);
				?>
			</p>
			<p class="description">
				<?php esc_html_e('To use your active provider for chat responses while using a different provider for embeddings is supported. Only OpenAI and Google Gemini support embeddings.', 'askany'); ?>
			</p>
		</div>
	<?php endif; ?>

	<!-- RAG Status Notice (like in settings page) -->
	<div id="askany-rag-status-notice"></div>

	<div class="askany-rag-content">
		<!-- Provider Information -->
		<div class="askany-rag-provider-info">
			<h2><?php esc_html_e('Embedding Provider', 'askany'); ?></h2>
			<table class="form-table">
				<tr>
					<th><?php esc_html_e('Provider:', 'askany'); ?></th>
					<td><strong><?php echo esc_html($provider_name ?: __('Not Configured', 'askany')); ?></strong></td>
				</tr>
				<tr>
					<th><?php esc_html_e('Model:', 'askany'); ?></th>
					<td>
						<code><?php echo esc_html($provider_model ?: __('N/A', 'askany')); ?></code>
						<?php if ($can_change_model): ?>
							<button type="button" class="button button-small" id="btn-change-model" style="margin-left: 10px;">
								<span class="dashicons dashicons-edit"></span>
								<?php esc_html_e('Change Model', 'askany'); ?>
							</button>
						<?php endif; ?>
					</td>
				</tr>
				<?php if ($provider_info): ?>
				<tr>
					<th><?php esc_html_e('Info:', 'askany'); ?></th>
					<td><em><?php echo esc_html($provider_info); ?></em></td>
				</tr>
				<?php endif; ?>
				<tr>
					<th><?php esc_html_e('Status:', 'askany'); ?></th>
					<td>
						<?php if ($rag_enabled): ?>
							<span class="askany-status-badge askany-status-active"><?php esc_html_e('Active', 'askany'); ?></span>
						<?php else: ?>
							<span class="askany-status-badge askany-status-inactive"><?php esc_html_e('Inactive', 'askany'); ?></span>
						<?php endif; ?>
					</td>
				</tr>
			</table>
		</div>

		<!-- Statistics Dashboard -->
		<div class="askany-rag-stats-dashboard">
			<h2><?php esc_html_e('Embedding Statistics', 'askany'); ?></h2>
			<div class="askany-rag-stats-grid">
				<div class="askany-stat-card">
					<div class="askany-stat-icon">📊</div>
					<div class="askany-stat-value" id="stat-total-content">-</div>
					<div class="askany-stat-label"><?php esc_html_e('Total Content Items', 'askany'); ?></div>
				</div>
				<div class="askany-stat-card askany-stat-success">
					<div class="askany-stat-icon">✓</div>
					<div class="askany-stat-value" id="stat-completed">-</div>
					<div class="askany-stat-label"><?php esc_html_e('Completed', 'askany'); ?></div>
				</div>
				<div class="askany-stat-card askany-stat-pending">
					<div class="askany-stat-icon">⏳</div>
					<div class="askany-stat-value" id="stat-pending">-</div>
					<div class="askany-stat-label"><?php esc_html_e('Pending', 'askany'); ?></div>
				</div>
				<div class="askany-stat-card askany-stat-processing">
					<div class="askany-stat-icon">⚙️</div>
					<div class="askany-stat-value" id="stat-processing">-</div>
					<div class="askany-stat-label"><?php esc_html_e('Processing', 'askany'); ?></div>
				</div>
				<div class="askany-stat-card askany-stat-failed">
					<div class="askany-stat-icon">✗</div>
					<div class="askany-stat-value" id="stat-failed">-</div>
					<div class="askany-stat-label"><?php esc_html_e('Failed', 'askany'); ?></div>
				</div>
				<div class="askany-stat-card">
					<div class="askany-stat-icon">🔢</div>
					<div class="askany-stat-value" id="stat-total-embeddings">-</div>
					<div class="askany-stat-label"><?php esc_html_e('Total Embeddings', 'askany'); ?></div>
				</div>
			</div>
		</div>

		<!-- Progress Bar -->
		<div class="askany-rag-progress-section" id="progress-section" style="display: none;">
			<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
				<h3 style="margin: 0;"><?php esc_html_e('Processing Status', 'askany'); ?></h3>
				<button type="button" class="button button-secondary" id="btn-stop-processing-inline" style="display: none;">
					<span class="dashicons dashicons-controls-pause"></span>
					<?php esc_html_e('Stop Processing', 'askany'); ?>
				</button>
			</div>
			<div class="askany-rag-progress-bar-container">
				<div class="askany-rag-progress-bar" id="progress-bar" style="width: 0%"></div>
			</div>
			<div class="askany-rag-progress-text" id="progress-text">0%</div>
		</div>

		<!-- Action Buttons -->
		<div class="askany-rag-actions">
			<h2><?php esc_html_e('Actions', 'askany'); ?></h2>
			<div class="askany-action-buttons">
				<button type="button" class="button button-primary button-large" id="btn-start-processing">
					<span class="dashicons dashicons-update"></span>
					<?php esc_html_e('Start Processing', 'askany'); ?>
				</button>
				<button type="button" class="button button-secondary button-large" id="btn-stop-processing" style="display: none;">
					<span class="dashicons dashicons-controls-pause"></span>
					<?php esc_html_e('Stop Processing', 'askany'); ?>
				</button>
				<button type="button" class="button button-secondary button-large" id="btn-reset-stuck">
					<span class="dashicons dashicons-undo"></span>
					<?php esc_html_e('Reset Stuck Items', 'askany'); ?>
				</button>
				<button type="button" class="button button-secondary button-large" id="btn-retry-failed">
					<span class="dashicons dashicons-backup"></span>
					<?php esc_html_e('Retry Failed Items', 'askany'); ?>
				</button>
				<button type="button" class="button button-secondary button-large" id="btn-view-error-log">
					<span class="dashicons dashicons-list-view"></span>
					<?php esc_html_e('View Error Log', 'askany'); ?>
				</button>
				<button type="button" class="button button-secondary button-large" id="btn-regenerate-all">
					<span class="dashicons dashicons-image-rotate"></span>
					<?php esc_html_e('Regenerate All Embeddings', 'askany'); ?>
				</button>
				<button type="button" class="button button-link-delete button-large" id="btn-clear-all">
					<span class="dashicons dashicons-trash"></span>
					<?php esc_html_e('Clear All Embeddings', 'askany'); ?>
				</button>
			</div>
		</div>

		<!-- Error Log -->
		<div class="askany-rag-error-log" id="error-log-section" style="display: none;">
			<h2><?php esc_html_e('Recent Errors', 'askany'); ?></h2>
			<div class="askany-error-log-content" id="error-log-content"></div>
		</div>
	</div>

	<!-- Model Selection Modal -->
	<?php if ($can_change_model): ?>
	<div id="model-selection-modal" class="askany-modal" style="display: none;">
		<div class="askany-modal-overlay"></div>
		<div class="askany-modal-content">
			<div class="askany-modal-header">
				<h2><?php esc_html_e('Select Embedding Model', 'askany'); ?></h2>
				<button type="button" class="askany-modal-close">&times;</button>
			</div>
			<div class="askany-modal-body">
				<p><?php esc_html_e('Choose the embedding model for', 'askany'); ?> <strong><?php echo esc_html($provider_name); ?></strong>:</p>
				<div class="askany-model-options">
					<?php foreach ($available_models as $model_id => $model_label): ?>
						<label class="askany-model-option">
							<input type="radio" name="embedding_model" value="<?php echo esc_attr($model_id); ?>" 
								<?php checked($model_id, $provider_model); ?>>
							<span class="askany-model-label"><?php echo esc_html($model_label); ?></span>
						</label>
					<?php endforeach; ?>
				</div>
				<p class="description">
					<?php esc_html_e('Note: Changing the model will require regenerating all embeddings for consistency.', 'askany'); ?>
				</p>
			</div>
			<div class="askany-modal-footer">
				<button type="button" class="button button-secondary askany-modal-cancel">
					<?php esc_html_e('Cancel', 'askany'); ?>
				</button>
				<button type="button" class="button button-primary" id="btn-save-model">
					<?php esc_html_e('Save & Regenerate', 'askany'); ?>
				</button>
			</div>
		</div>
	</div>
	<?php endif; ?>
</div>

<style>
.askany-rag-management {
	max-width: 1200px;
}

.askany-rag-provider-info {
	background: #fff;
	border: 1px solid #c3c4c7;
	border-radius: 4px;
	padding: 20px;
	margin: 20px 0;
}

.askany-status-badge {
	display: inline-block;
	padding: 4px 12px;
	border-radius: 12px;
	font-size: 12px;
	font-weight: 600;
	text-transform: uppercase;
}

.askany-status-active {
	background: #d4edda;
	color: #155724;
}

.askany-status-inactive {
	background: #f8d7da;
	color: #721c24;
}

.askany-rag-stats-dashboard {
	background: #fff;
	border: 1px solid #c3c4c7;
	border-radius: 4px;
	padding: 20px;
	margin: 20px 0;
}

.askany-rag-stats-grid {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 15px;
	margin-top: 15px;
}

@media (max-width: 782px) {
	.askany-rag-stats-grid {
		grid-template-columns: repeat(2, 1fr);
	}
}

@media (max-width: 480px) {
	.askany-rag-stats-grid {
		grid-template-columns: 1fr;
	}
}

.askany-stat-card {
	background: #f6f7f7;
	border: 2px solid #dcdcde;
	border-radius: 8px;
	padding: 20px;
	text-align: center;
	transition: all 0.3s ease;
}

.askany-stat-card:hover {
	transform: translateY(-2px);
	box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.askany-stat-success {
	border-color: #00a32a;
	background: #f0f9f4;
}

.askany-stat-pending {
	border-color: #dba617;
	background: #fcf9e8;
}

.askany-stat-processing {
	border-color: #2271b1;
	background: #f0f6fc;
}

.askany-stat-failed {
	border-color: #d63638;
	background: #fcf0f1;
}

.askany-stat-icon {
	font-size: 32px;
	margin-bottom: 10px;
}

.askany-stat-value {
	font-size: 36px;
	font-weight: 700;
	color: #1d2327;
	margin: 10px 0;
}

.askany-stat-label {
	font-size: 13px;
	color: #646970;
	text-transform: uppercase;
	letter-spacing: 0.5px;
}

.askany-rag-progress-section {
	background: #fff;
	border: 1px solid #c3c4c7;
	border-radius: 4px;
	padding: 20px;
	margin: 20px 0;
}

.askany-rag-progress-bar-container {
	width: 100%;
	height: 30px;
	background: #f0f0f1;
	border-radius: 15px;
	overflow: hidden;
	margin: 15px 0;
	box-shadow: inset 0 2px 4px rgba(0,0,0,0.1);
}

.askany-rag-progress-bar {
	height: 100%;
	background: linear-gradient(90deg, #2271b1, #135e96);
	transition: width 0.5s ease;
	position: relative;
	overflow: hidden;
}

.askany-rag-progress-bar::after {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
	background: linear-gradient(
		90deg,
		transparent,
		rgba(255,255,255,0.3),
		transparent
	);
	animation: shimmer 2s infinite;
}

@keyframes shimmer {
	0% { transform: translateX(-100%); }
	100% { transform: translateX(100%); }
}

.askany-rag-progress-text {
	text-align: center;
	font-size: 16px;
	font-weight: 600;
	color: #1d2327;
}

.askany-rag-actions {
	background: #fff;
	border: 1px solid #c3c4c7;
	border-radius: 4px;
	padding: 20px;
	margin: 20px 0;
}

.askany-action-buttons {
	display: flex;
	gap: 10px;
	flex-wrap: wrap;
	margin-top: 15px;
}

.askany-action-buttons .button {
	display: inline-flex;
	align-items: center;
	gap: 8px;
}

.askany-action-buttons .dashicons {
	font-size: 18px;
	width: 18px;
	height: 18px;
}

.askany-rag-error-log {
	background: #fff;
	border: 1px solid #c3c4c7;
	border-radius: 4px;
	padding: 20px;
	margin: 20px 0;
}

.askany-error-log-content {
	background: #f6f7f7;
	border: 1px solid #dcdcde;
	border-radius: 4px;
	padding: 15px;
	max-height: 600px;
	overflow-y: auto;
}

.askany-error-summary {
	background: #fff;
	padding: 15px;
	margin-bottom: 15px;
	border-left: 4px solid #d63638;
	border-radius: 2px;
}

.askany-error-summary p {
	margin: 0;
	font-size: 14px;
}

.askany-error-list {
	display: flex;
	flex-direction: column;
	gap: 10px;
}

.askany-error-item {
	padding: 15px;
	background: #fff;
	border-left: 4px solid #d63638;
	border-radius: 2px;
	box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.askany-error-item:last-child {
	margin-bottom: 0;
}

.askany-error-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 8px;
	padding-bottom: 8px;
	border-bottom: 1px solid #f0f0f1;
}

.askany-error-id {
	font-weight: 600;
	color: #d63638;
	font-size: 13px;
}

.askany-error-type {
	background: #f0f0f1;
	color: #646970;
	padding: 3px 8px;
	border-radius: 3px;
	font-size: 11px;
	text-transform: uppercase;
	font-weight: 600;
}

.askany-error-title {
	color: #1d2327;
	margin-bottom: 8px;
	font-size: 13px;
}

.askany-error-message {
	color: #646970;
	margin-top: 8px;
	font-size: 13px;
	line-height: 1.6;
}

.askany-error-text {
	display: block;
	margin-top: 4px;
	padding: 8px;
	background: #fcf0f1;
	border-radius: 3px;
	font-family: monospace;
	font-size: 12px;
	color: #d63638;
}

.askany-error-time {
	margin-top: 8px;
	font-size: 12px;
	color: #646970;
	font-style: italic;
}

/* Modal Styles */
.askany-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 100000;
}

.askany-modal-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.7);
}

.askany-modal-content {
	position: relative;
	background: #fff;
	max-width: 600px;
	margin: 50px auto;
	border-radius: 8px;
	box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
	z-index: 100001;
}

.askany-modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20px 25px;
	border-bottom: 1px solid #dcdcde;
}

.askany-modal-header h2 {
	margin: 0;
	font-size: 20px;
}

.askany-modal-close {
	background: none;
	border: none;
	font-size: 32px;
	line-height: 1;
	color: #646970;
	cursor: pointer;
	padding: 0;
	width: 32px;
	height: 32px;
}

.askany-modal-close:hover {
	color: #d63638;
}

.askany-modal-body {
	padding: 25px;
}

.askany-model-options {
	margin: 20px 0;
}

.askany-model-option {
	display: block;
	padding: 15px;
	margin-bottom: 10px;
	background: #f6f7f7;
	border: 2px solid #dcdcde;
	border-radius: 6px;
	cursor: pointer;
	transition: all 0.2s ease;
}

.askany-model-option:hover {
	background: #fff;
	border-color: #2271b1;
}

.askany-model-option input[type="radio"] {
	margin-right: 10px;
}

.askany-model-option input[type="radio"]:checked + .askany-model-label {
	font-weight: 600;
	color: #2271b1;
}

.askany-model-label {
	font-size: 14px;
}

.askany-modal-footer {
	display: flex;
	justify-content: flex-end;
	gap: 10px;
	padding: 20px 25px;
	border-top: 1px solid #dcdcde;
	background: #f6f7f7;
	border-radius: 0 0 8px 8px;
}

/* RAG Status Notice Styles */
.askany-rag-status-notice {
	margin: 20px 0;
	border-left-width: 4px;
}

.askany-rag-stats {
	font-family: monospace;
	background: rgba(0,0,0,0.05);
	padding: 2px 8px;
	border-radius: 3px;
	margin-left: 8px;
}

.askany-rag-progress-container {
	margin-top: 12px;
}

.askany-rag-progress {
	width: 100%;
	height: 24px;
	background: #f0f0f1;
	border-radius: 4px;
	overflow: hidden;
	box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
}

.askany-rag-progress-bar {
	height: 100%;
	background: linear-gradient(90deg, #2271b1, #135e96);
	transition: width 0.5s ease;
	position: relative;
	overflow: hidden;
}

.askany-rag-progress-bar::after {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
	background: linear-gradient(
		90deg,
		transparent,
		rgba(255,255,255,0.3),
		transparent
	);
	animation: shimmer 2s infinite;
}

@keyframes shimmer {
	0% { transform: translateX(-100%); }
	100% { transform: translateX(100%); }
}

.askany-rag-details {
	display: flex;
	gap: 20px;
	margin-top: 10px;
	padding: 10px;
	background: rgba(0,0,0,0.02);
	border-radius: 4px;
	flex-wrap: wrap;
}

.askany-rag-detail {
	font-size: 13px;
	color: #646970;
}

.askany-rag-detail strong {
	color: #1d2327;
}

.askany-rag-by-type {
	margin-top: 10px;
	padding: 8px 10px;
	background: rgba(0,0,0,0.02);
	border-radius: 4px;
	font-size: 12px;
	color: #646970;
}

.askany-rag-by-type strong {
	color: #1d2327;
}
</style>

<script>
jQuery(document).ready(function($) {
	// Use global RAG processor from rag-processor.js
	// All processing logic is now centralized there
	
	let currentErrors = [];
	let dismissedNoticeType = '<?php echo esc_js($dismissed_notice_type); ?>';

	// Load Toastmaster if not already loaded
	if (typeof Toast === 'undefined') {
		console.warn('Toast library not loaded, using fallback notifications');
	}

	// Load initial stats
	if (typeof window.AskanyRAG !== 'undefined') {
		window.AskanyRAG.refreshStatus();
	}

	// Start processing button
	$('#btn-start-processing').on('click', function() {
		if (typeof window.AskanyRAG === 'undefined') {
			showNotice('RAG processor not loaded', 'error');
			return;
		}
		
		const status = window.AskanyRAG.getStatus();
		if (status.isProcessing) {
			showNotice('Processing is already in progress', 'warning');
			return;
		}

		if (typeof Toast !== 'undefined' && Toast.ask) {
			Toast.ask('Start Processing', '<?php esc_html_e('Start generating embeddings for all pending content?', 'askany'); ?>')
				.then(result => {
					if (!result.ok) return;
					window.AskanyRAG.startProcessing();
				});
		} else {
			if (confirm('<?php esc_html_e('Start generating embeddings for all pending content?', 'askany'); ?>')) {
				window.AskanyRAG.startProcessing();
			}
		}
	});

	// Stop processing buttons
	$('#btn-stop-processing, #btn-stop-processing-inline, #btn-stop-processing-notice').on('click', function() {
		if (typeof window.AskanyRAG === 'undefined') {
			return;
		}
		
		const status = window.AskanyRAG.getStatus();
		if (!status.isProcessing) {
			return;
		}

		if (typeof Toast !== 'undefined' && Toast.ask) {
			Toast.ask('Stop Processing', '<?php esc_html_e('Stop the current embedding generation process?', 'askany'); ?>')
				.then(result => {
					if (!result.ok) return;
					window.AskanyRAG.stopProcessing();
				});
		} else {
			if (confirm('<?php esc_html_e('Stop the current embedding generation process?', 'askany'); ?>')) {
				window.AskanyRAG.stopProcessing();
			}
		}
	});

	// Reset stuck items
	$('#btn-reset-stuck').on('click', function() {
		const status = window.AskanyRAG ? window.AskanyRAG.getStatus() : {isProcessing: false};
		if (status.isProcessing) {
			showNotice('Cannot reset while processing', 'warning');
			return;
		}

		if (typeof Toast !== 'undefined' && Toast.ask) {
			Toast.ask('Reset Stuck Items', '<?php esc_html_e('Reset items stuck in "processing" status back to "pending"?', 'askany'); ?>')
				.then(result => {
					if (!result.ok) return;
					resetStuckItems();
				});
		} else {
			if (confirm('<?php esc_html_e('Reset items stuck in "processing" status back to "pending"?', 'askany'); ?>')) {
				resetStuckItems();
			}
		}
	});

	function resetStuckItems() {
		$.ajax({
			url: ajaxurl,
			type: 'POST',
			data: {
				action: 'askany_reset_stuck_embeddings',
				nonce: '<?php echo wp_create_nonce('askany_chat_nonce'); ?>'
			},
			success: function(response) {
				if (response.success) {
					if (typeof Toast !== 'undefined' && Toast.success) {
						Toast.success(response.data.message);
					} else {
						showNotice(response.data.message, 'success');
					}
					if (window.AskanyRAG) {
						window.AskanyRAG.refreshStatus();
					}
				} else {
					if (typeof Toast !== 'undefined' && Toast.error) {
						Toast.error('<?php esc_html_e('Failed to reset stuck items', 'askany'); ?>');
					} else {
						showNotice('<?php esc_html_e('Failed to reset stuck items', 'askany'); ?>', 'error');
					}
				}
			},
			error: function() {
				if (typeof Toast !== 'undefined' && Toast.error) {
					Toast.error('<?php esc_html_e('Network error occurred', 'askany'); ?>');
				} else {
					showNotice('<?php esc_html_e('Network error occurred', 'askany'); ?>', 'error');
				}
			}
		});
	}

	// Retry failed items
	$('#btn-retry-failed').on('click', function() {
		if (typeof window.AskanyRAG === 'undefined') {
			showNotice('RAG processor not loaded', 'error');
			return;
		}
		
		const status = window.AskanyRAG.getStatus();
		if (status.isProcessing) {
			showNotice('Processing is already in progress', 'warning');
			return;
		}

		if (typeof Toast !== 'undefined' && Toast.ask) {
			Toast.ask('Retry Failed', '<?php esc_html_e('Retry generating embeddings for all failed items?', 'askany'); ?>')
				.then(result => {
					if (!result.ok) return;
					window.AskanyRAG.startProcessing();
				});
		} else {
			if (confirm('<?php esc_html_e('Retry generating embeddings for all failed items?', 'askany'); ?>')) {
				window.AskanyRAG.startProcessing();
			}
		}
	});

	// View error log
	$('#btn-view-error-log').on('click', function() {
		loadErrorLog();
	});

	// Regenerate all
	$('#btn-regenerate-all').on('click', function() {
		const status = window.AskanyRAG ? window.AskanyRAG.getStatus() : {isProcessing: false};
		if (status.isProcessing) {
			showNotice('Processing is already in progress', 'warning');
			return;
		}

		if (typeof Toast !== 'undefined' && Toast.ask) {
			Toast.ask('Regenerate All', '<?php esc_html_e('This will clear all existing embeddings and regenerate them. This may take a while. Continue?', 'askany'); ?>')
				.then(result => {
					if (!result.ok) return;
					regenerateAll();
				});
		} else {
			if (confirm('<?php esc_html_e('This will clear all existing embeddings and regenerate them. This may take a while. Continue?', 'askany'); ?>')) {
				regenerateAll();
			}
		}
	});

	function regenerateAll() {
		// Clear all embeddings first
		$.ajax({
			url: ajaxurl,
			type: 'POST',
			data: {
				action: 'askany_clear_all_embeddings',
				nonce: '<?php echo wp_create_nonce('askany_chat_nonce'); ?>'
			},
			success: function(response) {
				if (response.success) {
					currentErrors = [];
					$('#error-log-section').hide();
					if (window.AskanyRAG) {
						window.AskanyRAG.startProcessing();
					}
				} else {
					showNotice('Failed to clear embeddings', 'error');
				}
			}
		});
	}

	// Clear all embeddings
	$('#btn-clear-all').on('click', function() {
		const status = window.AskanyRAG ? window.AskanyRAG.getStatus() : {isProcessing: false};
		if (status.isProcessing) {
			showNotice('Cannot clear embeddings while processing', 'warning');
			return;
		}

		if (typeof Toast !== 'undefined' && Toast.ask) {
			Toast.ask('Clear All', '<?php esc_html_e('This will permanently delete all embeddings. Are you sure?', 'askany'); ?>')
				.then(result => {
					if (!result.ok) return;
					clearAllEmbeddings();
				});
		} else {
			if (confirm('<?php esc_html_e('This will permanently delete all embeddings. Are you sure?', 'askany'); ?>')) {
				clearAllEmbeddings();
			}
		}
	});

	function clearAllEmbeddings() {
		$.ajax({
			url: ajaxurl,
			type: 'POST',
			data: {
				action: 'askany_clear_all_embeddings',
				nonce: '<?php echo wp_create_nonce('askany_chat_nonce'); ?>'
			},
			success: function(response) {
				if (response.success) {
					if (typeof Toast !== 'undefined' && Toast.success) {
						Toast.success('All embeddings cleared successfully');
					} else {
						showNotice('All embeddings cleared successfully', 'success');
					}
					if (window.AskanyRAG) {
						window.AskanyRAG.refreshStatus();
					}
				} else {
					if (typeof Toast !== 'undefined' && Toast.error) {
						Toast.error('Failed to clear embeddings');
					} else {
						showNotice('Failed to clear embeddings', 'error');
					}
				}
			}
		});
	}

	// Load error log from database
	function loadErrorLog() {
		$.ajax({
			url: ajaxurl,
			type: 'POST',
			data: {
				action: 'askany_get_embedding_errors',
				nonce: '<?php echo wp_create_nonce('askany_chat_nonce'); ?>'
			},
			success: function(response) {
				if (response.success && response.data) {
					displayErrorLog(response.data.errors);
				} else {
					showNotice('<?php esc_html_e('No errors found', 'askany'); ?>', 'info');
				}
			},
			error: function() {
				showNotice('<?php esc_html_e('Failed to load error log', 'askany'); ?>', 'error');
			}
		});
	}

	// Display error log
	function displayErrorLog(errors) {
		if (!errors || errors.length === 0) {
			$('#error-log-content').html('<p><?php esc_html_e('No errors found. All embeddings generated successfully!', 'askany'); ?></p>');
			$('#error-log-section').show();
			return;
		}

		let html = '<div class="askany-error-summary">';
		html += '<p><strong><?php esc_html_e('Total Failed Items:', 'askany'); ?></strong> ' + errors.length + '</p>';
		html += '</div>';
		
		html += '<div class="askany-error-list">';
		errors.forEach(function(error) {
			html += '<div class="askany-error-item">';
			html += '<div class="askany-error-header">';
			html += '<span class="askany-error-id"><strong><?php esc_html_e('Content ID:', 'askany'); ?></strong> ' + error.content_id + '</span>';
			html += '<span class="askany-error-type">' + error.content_type + '</span>';
			html += '</div>';
			
			if (error.title) {
				html += '<div class="askany-error-title"><strong><?php esc_html_e('Title:', 'askany'); ?></strong> ' + error.title + '</div>';
			}
			
			html += '<div class="askany-error-message">';
			html += '<strong><?php esc_html_e('Error:', 'askany'); ?></strong> ';
			html += '<span class="askany-error-text">' + error.error_message + '</span>';
			html += '</div>';
			
			if (error.last_attempt) {
				html += '<div class="askany-error-time">';
				html += '<strong><?php esc_html_e('Last Attempt:', 'askany'); ?></strong> ' + error.last_attempt;
				html += '</div>';
			}
			
			html += '</div>';
		});
		html += '</div>';

		$('#error-log-content').html(html);
		$('#error-log-section').show();
		
		// Scroll to error log
		$('html, body').animate({
			scrollTop: $('#error-log-section').offset().top - 100
		}, 500);
	}

	// Display errors (for real-time processing)
	function displayErrors() {
		if (currentErrors.length === 0) {
			$('#error-log-section').hide();
			return;
		}

		let html = '<div class="askany-error-summary">';
		html += '<p><strong><?php esc_html_e('Processing Errors:', 'askany'); ?></strong> <?php esc_html_e('The following items failed during this processing session:', 'askany'); ?></p>';
		html += '</div>';
		
		html += '<div class="askany-error-list">';
		currentErrors.slice(-20).forEach(function(error) {
			html += '<div class="askany-error-item">';
			html += '<div class="askany-error-header">';
			html += '<span class="askany-error-id"><strong><?php esc_html_e('ID:', 'askany'); ?></strong> ' + error.id + '</span>';
			html += '<span class="askany-error-type">' + error.type + '</span>';
			html += '</div>';
			html += '<div class="askany-error-message">';
			html += '<strong><?php esc_html_e('Error:', 'askany'); ?></strong> ';
			html += '<span class="askany-error-text">' + error.error + '</span>';
			html += '</div>';
			html += '</div>';
		});
		html += '</div>';

		if (currentErrors.length > 20) {
			html += '<p class="description"><?php esc_html_e('Showing last 20 errors. Total failed in this session:', 'askany'); ?> ' + currentErrors.length + '</p>';
		}

		$('#error-log-content').html(html);
		$('#error-log-section').show();
	}

	// Show notice
	function showNotice(message, type) {
		const noticeClass = 'notice-' + type;
		const notice = $('<div class="notice ' + noticeClass + ' is-dismissible"><p>' + message + '</p></div>');
		$('.askany-rag-management h1').after(notice);
		
		setTimeout(function() {
			notice.fadeOut(function() {
				$(this).remove();
			});
		}, 5000);
	}

	// Model selection modal
	$('#btn-change-model').on('click', function() {
		$('#model-selection-modal').fadeIn(200);
	});

	$('.askany-modal-close, .askany-modal-cancel, .askany-modal-overlay').on('click', function() {
		$('#model-selection-modal').fadeOut(200);
	});

	// Prevent modal close when clicking inside modal content
	$('.askany-modal-content').on('click', function(e) {
		e.stopPropagation();
	});

	// Save model selection
	$('#btn-save-model').on('click', function() {
		const selectedModel = $('input[name="embedding_model"]:checked').val();
		
		if (!selectedModel) {
			if (typeof Toast !== 'undefined' && Toast.error) {
				Toast.error('<?php esc_html_e('Please select a model', 'askany'); ?>');
			} else {
				showNotice('<?php esc_html_e('Please select a model', 'askany'); ?>', 'error');
			}
			return;
		}

		// Save the model selection
		$.ajax({
			url: ajaxurl,
			type: 'POST',
			data: {
				action: 'askany_save_embedding_model',
				nonce: '<?php echo wp_create_nonce('askany_chat_nonce'); ?>',
				model: selectedModel
			},
			success: function(response) {
				if (response.success) {
					$('#model-selection-modal').fadeOut(200);
					if (typeof Toast !== 'undefined' && Toast.success) {
						Toast.success('<?php esc_html_e('Model saved successfully. Regenerating embeddings...', 'askany'); ?>');
					} else {
						showNotice('<?php esc_html_e('Model saved successfully. Regenerating embeddings...', 'askany'); ?>', 'success');
					}
					
					// Clear and regenerate embeddings
					$.ajax({
						url: ajaxurl,
						type: 'POST',
						data: {
							action: 'askany_clear_all_embeddings',
							nonce: '<?php echo wp_create_nonce('askany_chat_nonce'); ?>'
						},
						success: function(response) {
							if (response.success) {
								// Reload page to show new model
								setTimeout(function() {
									location.reload();
								}, 1000);
							}
						}
					});
				} else {
					if (typeof Toast !== 'undefined' && Toast.error) {
						Toast.error('<?php esc_html_e('Failed to save model', 'askany'); ?>');
					} else {
						showNotice('<?php esc_html_e('Failed to save model', 'askany'); ?>', 'error');
					}
				}
			}
		});
	});
});
</script>
