<?php
/**
 * Admin template for External Sources management.
 *
 * @package Askany
 * @since 1.3.1
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
?>

<div class="wrap">
	<h1>
		<?php esc_html_e( 'External Sources', 'askany' ); ?>
		<?php
		$plugin = \Askany\Plugin::get_instance();
		$is_pro = $plugin->is_pro_active();
		$sources_count = $data['stats']['total_sources'];
		$free_limit = 2;
		
		if ( ! $is_pro ) {
			echo '<span class="askany-sources-limit-badge">';
			echo esc_html( sprintf( __( '%d / %d sources', 'askany' ), $sources_count, $free_limit ) );
			echo '</span>';
		}
		?>
	</h1>
	<p><?php esc_html_e( 'Add external websites to crawl and index their content for your AI assistant.', 'askany' ); ?></p>

	<!-- Statistics Cards -->
	<div class="askany-stats-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 20px 0;">
		<div class="askany-stat-card" style="background: #fff; padding: 20px; border: 1px solid #ddd; border-radius: 8px;">
			<h3 style="margin: 0 0 10px 0; color: #2271b1;"><?php echo esc_html( $data['stats']['total_sources'] ); ?></h3>
			<p style="margin: 0; color: #666;"><?php esc_html_e( 'Total Sources', 'askany' ); ?></p>
		</div>
		<div class="askany-stat-card" style="background: #fff; padding: 20px; border: 1px solid #ddd; border-radius: 8px;">
			<h3 style="margin: 0 0 10px 0; color: #00a32a;"><?php echo esc_html( $data['stats']['completed_sources'] ); ?></h3>
			<p style="margin: 0; color: #666;"><?php esc_html_e( 'Completed', 'askany' ); ?></p>
		</div>
		<div class="askany-stat-card" style="background: #fff; padding: 20px; border: 1px solid #ddd; border-radius: 8px;">
			<h3 style="margin: 0 0 10px 0; color: #dba617;"><?php echo esc_html( $data['stats']['processing_sources'] ); ?></h3>
			<p style="margin: 0; color: #666;"><?php esc_html_e( 'Processing', 'askany' ); ?></p>
		</div>
		<div class="askany-stat-card" style="background: #fff; padding: 20px; border: 1px solid #ddd; border-radius: 8px;">
			<h3 style="margin: 0 0 10px 0; color: #d63638;"><?php echo esc_html( $data['stats']['failed_sources'] ); ?></h3>
			<p style="margin: 0; color: #666;"><?php esc_html_e( 'Failed', 'askany' ); ?></p>
		</div>
		<div class="askany-stat-card" style="background: #fff; padding: 20px; border: 1px solid #ddd; border-radius: 8px;">
			<h3 style="margin: 0 0 10px 0; color: #2271b1;"><?php echo esc_html( $data['stats']['total_crawled_urls'] ); ?></h3>
			<p style="margin: 0; color: #666;"><?php esc_html_e( 'Crawled URLs', 'askany' ); ?></p>
		</div>
	</div>

	<!-- Add New Source Form -->
	<div class="askany-card" style="background: #fff; padding: 20px; border: 1px solid #ddd; border-radius: 8px; margin: 20px 0;">
		<h2><?php esc_html_e( 'Add External Source', 'askany' ); ?></h2>
		<?php
		$is_limit_reached = ! $is_pro && $sources_count >= $free_limit;
		if ( $is_limit_reached ) : ?>
			<div class="askany-pro-notice">
				<div class="askany-pro-notice-icon">
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
						<path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
					</svg>
				</div>
				<div class="askany-pro-notice-content">
					<h3><?php esc_html_e( 'External Sources Limit Reached', 'askany' ); ?></h3>
					<p><?php echo esc_html( sprintf( __( 'Free plan allows up to %d external sources. Upgrade to Pro for unlimited external sources.', 'askany' ), $free_limit ) ); ?></p>
					<button type="button" class="button button-primary askany-open-pro-modal">
						<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 6px;">
							<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
						</svg>
						<?php esc_html_e( 'Upgrade to Pro', 'askany' ); ?>
					</button>
				</div>
			</div>
		<?php endif; ?>
		<form id="add-external-source-form" <?php echo $is_limit_reached ? 'style="display:none;"' : ''; ?>>
			<table class="form-table">
				<tr>
					<th scope="row">
						<label for="external-url"><?php esc_html_e( 'Website URL', 'askany' ); ?></label>
					</th>
					<td>
						<input type="url" id="external-url" name="url" class="regular-text" placeholder="https://example.com" required>
						<p class="description"><?php esc_html_e( 'Enter the URL of the website you want to crawl and index.', 'askany' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="follow-links"><?php esc_html_e( 'Follow Links', 'askany' ); ?></label>
					</th>
					<td>
						<label>
							<input type="checkbox" id="follow-links" name="follow_links" value="1">
							<?php esc_html_e( 'Crawl linked pages from the main URL', 'askany' ); ?>
						</label>
						<p class="description"><?php esc_html_e( 'When enabled, the crawler will also process pages linked from the main URL.', 'askany' ); ?></p>
					</td>
				</tr>
			</table>

			<!-- Advanced Options -->
			<div id="advanced-options" style="display: none;">
				<h3><?php esc_html_e( 'Advanced Options', 'askany' ); ?></h3>
				<table class="form-table">
					<tr>
						<th scope="row">
							<label for="include-paths"><?php esc_html_e( 'Include Paths', 'askany' ); ?></label>
						</th>
						<td>
							<input type="text" id="include-paths" name="include_paths" class="regular-text" placeholder="/blog, /docs, /help">
							<p class="description"><?php esc_html_e( 'Comma-separated list of paths to include. Leave empty to include all paths.', 'askany' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="exclude-paths"><?php esc_html_e( 'Exclude Paths', 'askany' ); ?></label>
						</th>
						<td>
							<input type="text" id="exclude-paths" name="exclude_paths" class="regular-text" placeholder="/admin, /login, /cart">
							<p class="description"><?php esc_html_e( 'Comma-separated list of paths to exclude from crawling.', 'askany' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="include-selectors"><?php esc_html_e( 'Include Selectors', 'askany' ); ?></label>
						</th>
						<td>
							<input type="text" id="include-selectors" name="include_selectors" class="regular-text" placeholder=".content, #main, article">
							<p class="description"><?php esc_html_e( 'CSS selectors for content to include. Leave empty to include all content.', 'askany' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="exclude-selectors"><?php esc_html_e( 'Exclude Selectors', 'askany' ); ?></label>
						</th>
						<td>
							<input type="text" id="exclude-selectors" name="exclude_selectors" class="regular-text" placeholder=".sidebar, .ads, .comments">
							<p class="description"><?php esc_html_e( 'CSS selectors for content to exclude from indexing.', 'askany' ); ?></p>
						</td>
					</tr>
				</table>
			</div>

			<p class="submit">
				<button type="button" id="toggle-advanced" class="button"><?php esc_html_e( 'Show Advanced Options', 'askany' ); ?></button>
				<input type="submit" class="button-primary" value="<?php esc_attr_e( 'Add External Source', 'askany' ); ?>">
			</p>
		</form>
	</div>

	<!-- External Sources List -->
	<div class="askany-card" style="background: #fff; padding: 20px; border: 1px solid #ddd; border-radius: 8px; margin: 20px 0;">
		<h2><?php esc_html_e( 'External Sources', 'askany' ); ?></h2>
		<div id="external-sources-list">
			<p><?php esc_html_e( 'Loading external sources...', 'askany' ); ?></p>
		</div>
	</div>

	<!-- View URLs Modal -->
	<div id="view-urls-modal" class="askany-modal" style="display: none;">
		<div class="askany-modal-content" style="background: #fff; padding: 20px; border-radius: 8px; max-width: 600px; margin: 50px auto;">
			<div class="askany-modal-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
				<h3 id="modal-title"><?php esc_html_e( 'Crawled URLs', 'askany' ); ?></h3>
				<button type="button" class="askany-modal-close" style="background: none; border: none; font-size: 24px; cursor: pointer;">&times;</button>
			</div>
			<div id="modal-urls-list">
				<!-- URLs will be loaded here -->
			</div>
		</div>
	</div>

	<!-- Processing Status -->
	<div id="processing-status" style="display: none; background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 4px; margin: 20px 0;">
		<p><strong><?php esc_html_e( 'Processing:', 'askany' ); ?></strong> <span id="processing-message"></span></p>
		<div class="progress-bar" style="background: #e9ecef; height: 20px; border-radius: 10px; overflow: hidden;">
			<div class="progress-fill" style="background: #007cba; height: 100%; width: 0%; transition: width 0.3s ease;"></div>
		</div>
	</div>
</div>

<style>
/* Sources limit badge */
.askany-sources-limit-badge {
	display: inline-block;
	padding: 4px 12px;
	background: #f0f0f1;
	border: 1px solid #c3c4c7;
	border-radius: 12px;
	font-size: 13px;
	font-weight: 500;
	color: #50575e;
	margin-left: 10px;
	vertical-align: middle;
}

/* Pro notice box */
.askany-pro-notice {
	display: flex;
	align-items: flex-start;
	gap: 20px;
	padding: 20px;
	background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
	border: 2px solid #667eea;
	border-radius: 12px;
	margin-bottom: 20px;
}

.askany-pro-notice-icon {
	flex-shrink: 0;
	width: 48px;
	height: 48px;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.askany-pro-notice-icon svg {
	stroke: white;
}

.askany-pro-notice-content {
	flex: 1;
}

.askany-pro-notice-content h3 {
	margin: 0 0 8px 0;
	font-size: 18px;
	font-weight: 600;
	color: #2d3748;
}

.askany-pro-notice-content p {
	margin: 0 0 15px 0;
	font-size: 14px;
	color: #4a5568;
	line-height: 1.6;
}

.askany-open-pro-modal {
	display: inline-flex;
	align-items: center;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
	border-color: #667eea !important;
	color: white !important;
	font-weight: 600;
	padding: 8px 20px !important;
	height: auto !important;
	transition: all 0.3s ease;
}

.askany-open-pro-modal:hover {
	transform: translateY(-2px);
	box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4) !important;
}

.askany-open-pro-modal svg {
	vertical-align: middle;
}

.askany-modal {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	z-index: 100000;
}

.askany-modal-content {
	position: relative;
	max-height: 80vh;
	overflow-y: auto;
}

.askany-source-item {
	border: 1px solid #ddd;
	border-radius: 8px;
	padding: 15px;
	margin-bottom: 15px;
	background: #f9f9f9;
}

.askany-source-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
}

.askany-source-url {
	font-weight: bold;
	color: #2271b1;
	text-decoration: none;
}

.askany-source-url:hover {
	text-decoration: underline;
}

.askany-status-badge {
	padding: 4px 8px;
	border-radius: 4px;
	font-size: 12px;
	font-weight: bold;
	text-transform: uppercase;
}

.status-completed {
	background: #d1e7dd;
	color: #0f5132;
}

.status-processing {
	background: #fff3cd;
	color: #664d03;
}

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

.status-pending {
	background: #cff4fc;
	color: #055160;
}

.askany-source-actions {
	margin-top: 10px;
}

.askany-source-actions button {
	margin-right: 10px;
}

.askany-url-list {
	max-height: 300px;
	overflow-y: auto;
	border: 1px solid #ddd;
	border-radius: 4px;
	padding: 10px;
}

.askany-url-item {
	padding: 5px 0;
	border-bottom: 1px solid #eee;
}

.askany-url-item:last-child {
	border-bottom: none;
}

.askany-url-item a {
	color: #2271b1;
	text-decoration: none;
}

.askany-url-item a:hover {
	text-decoration: underline;
}

/* Processing progress styles */
.askany-processing-info {
	background: #f0f6fc;
	border: 1px solid #0969da;
	border-radius: 6px;
	padding: 15px;
	margin: 15px 0;
}

.processing-header {
	display: flex;
	align-items: center;
	gap: 8px;
	margin-bottom: 12px;
	color: #0969da;
	font-size: 14px;
}

.processing-icon {
	font-size: 18px;
	animation: spin 2s linear infinite;
}

@keyframes spin {
	from { transform: rotate(0deg); }
	to { transform: rotate(360deg); }
}

.processing-details {
	margin-top: 10px;
}

.progress-text {
	display: flex;
	justify-content: space-between;
	margin-bottom: 8px;
	font-size: 13px;
	color: #57606a;
}

.progress-bar-container {
	width: 100%;
	height: 20px;
	background: #d0d7de;
	border-radius: 10px;
	overflow: hidden;
	position: relative;
}

.progress-bar-fill {
	height: 100%;
	background: linear-gradient(90deg, #0969da 0%, #54aeff 100%);
	transition: width 0.3s ease;
	position: relative;
	overflow: hidden;
}

.progress-bar-fill::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%); }
}

.current-url {
	margin-top: 8px;
	padding: 6px 10px;
	background: white;
	border-radius: 4px;
	font-family: monospace;
	font-size: 12px;
	color: #57606a;
	word-break: break-all;
}
</style>

<script>
jQuery(document).ready(function($) {
	// Pro status and limits
	var isPro = <?php echo $is_pro ? 'true' : 'false'; ?>;
	var sourcesCount = <?php echo (int) $sources_count; ?>;
	var freeLimit = 2;
	
	let isAdvancedVisible = false;

	// Toggle advanced options
	$('#toggle-advanced').on('click', function() {
		if (isAdvancedVisible) {
			$('#advanced-options').slideUp();
			$(this).text('<?php esc_html_e( 'Show Advanced Options', 'askany' ); ?>');
		} else {
			$('#advanced-options').slideDown();
			$(this).text('<?php esc_html_e( 'Hide Advanced Options', 'askany' ); ?>');
		}
		isAdvancedVisible = !isAdvancedVisible;
	});

	// Handle Pro modal open button
	$(document).on('click', '.askany-open-pro-modal', function(e) {
		e.preventDefault();
		if (typeof AskanyPro !== 'undefined') {
			AskanyPro.openModal({
				title: '<?php esc_html_e( 'Upgrade to Pro', 'askany' ); ?>',
				description: '<?php esc_html_e( 'Unlock unlimited external sources and premium features', 'askany' ); ?>',
				features: [
					'<?php esc_html_e( 'Unlimited external sources', 'askany' ); ?>',
					'<?php esc_html_e( 'Unlimited Q&A pairs', 'askany' ); ?>',
					'<?php esc_html_e( 'Unlimited chat agents', 'askany' ); ?>',
					'<?php esc_html_e( 'Unlimited chat sessions', 'askany' ); ?>',
					'<?php esc_html_e( 'Priority support', 'askany' ); ?>'
				]
			});
		}
	});
	
	// Add external source form submission
	$('#add-external-source-form').on('submit', function(e) {
		e.preventDefault();
		
		// Check Pro limit before submission
		if (!isPro && sourcesCount >= freeLimit) {
			if (typeof AskanyPro !== 'undefined') {
				AskanyPro.openModal();
			}
			return false;
		}
		
		const formData = {
			url: $('#external-url').val(),
			follow_links: $('#follow-links').is(':checked'),
			include_paths: $('#include-paths').val(),
			exclude_paths: $('#exclude-paths').val(),
			include_selectors: $('#include-selectors').val(),
			exclude_selectors: $('#exclude-selectors').val()
		};

		$.ajax({
			url: '<?php echo esc_url( rest_url( 'askany/v1/external-sources' ) ); ?>',
			method: 'POST',
			data: formData,
			beforeSend: function(xhr) {
				xhr.setRequestHeader('X-WP-Nonce', '<?php echo esc_js( wp_create_nonce( 'wp_rest' ) ); ?>');
			},
			success: function(response) {
				if (response.success) {
					// Show success message
					showNotice(response.message, 'success');
					
					// Reset form
					$('#add-external-source-form')[0].reset();
					
					// Increment sources count
					sourcesCount++;
					
					// Update Pro lock UI
					updateProLockUI();
					
					// Reload sources list
					loadExternalSources();
					
					// Start status checking immediately
					startStatusChecking();
				} else {
					showNotice(response.message || '<?php esc_html_e( 'Failed to add external source.', 'askany' ); ?>', 'error');
				}
			},
			error: function(xhr) {
				const response = xhr.responseJSON;
				showNotice(response?.message || '<?php esc_html_e( 'Failed to add external source.', 'askany' ); ?>', 'error');
			}
		});
	});

	// Load external sources
	function loadExternalSources() {
		$.ajax({
			url: '<?php echo esc_url( rest_url( 'askany/v1/external-sources' ) ); ?>',
			method: 'GET',
			cache: false, // Disable caching
			data: {
				_: new Date().getTime() // Cache buster
			},
			beforeSend: function(xhr) {
				xhr.setRequestHeader('X-WP-Nonce', '<?php echo esc_js( wp_create_nonce( 'wp_rest' ) ); ?>');
				xhr.setRequestHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
				xhr.setRequestHeader('Pragma', 'no-cache');
				xhr.setRequestHeader('Expires', '0');
			},
			success: function(response) {
				if (response.success) {
					// Update sources count from response
					if (response.sources) {
						sourcesCount = response.sources.length;
					}
					
					renderExternalSources(response.sources);
				} else {
					$('#external-sources-list').html('<p><?php esc_html_e( 'Failed to load external sources.', 'askany' ); ?></p>');
				}
			},
			error: function() {
				$('#external-sources-list').html('<p><?php esc_html_e( 'Failed to load external sources.', 'askany' ); ?></p>');
			}
		});
	}

	// Render external sources
	function renderExternalSources(sources) {
		if (sources.length === 0) {
			$('#external-sources-list').html('<p><?php esc_html_e( 'No external sources added yet.', 'askany' ); ?></p>');
			return;
		}

		let html = '';
		sources.forEach(function(source) {
			const statusClass = 'status-' + source.status;
			const statusText = source.status.charAt(0).toUpperCase() + source.status.slice(1);
			
			// Parse processing progress
			let progressData = null;
			if (source.processing_progress) {
				try {
					progressData = JSON.parse(source.processing_progress);
					// Debug: Log progress data for processing sources
					if (source.status === 'processing') {
						console.log('Source #' + source.id + ' progress:', progressData);
					}
				} catch(e) {
					console.error('Failed to parse progress data for source #' + source.id, e);
					progressData = null;
				}
			}
			
			html += `
				<div class="askany-source-item" data-id="${source.id}">
					<div class="askany-source-header">
						<a href="${source.url}" target="_blank" class="askany-source-url">${source.url}</a>
						<span class="askany-status-badge ${statusClass}">${statusText}</span>
					</div>
					<div class="askany-source-meta">
						<p><strong><?php esc_html_e( 'Title:', 'askany' ); ?></strong> ${source.title || '<?php esc_html_e( 'N/A', 'askany' ); ?>'}</p>
						<p><strong><?php esc_html_e( 'Follow Links:', 'askany' ); ?></strong> ${source.follow_links ? '<?php esc_html_e( 'Yes', 'askany' ); ?>' : '<?php esc_html_e( 'No', 'askany' ); ?>'}</p>
						<p><strong><?php esc_html_e( 'Crawled URLs:', 'askany' ); ?></strong> ${source.crawled_count || 0}</p>
						<p><strong><?php esc_html_e( 'Last Crawled:', 'askany' ); ?></strong> ${source.last_crawled || '<?php esc_html_e( 'Never', 'askany' ); ?>'}</p>
						${source.error_message ? `<p style="color: #d63638;"><strong><?php esc_html_e( 'Error:', 'askany' ); ?></strong> ${source.error_message}</p>` : ''}
					</div>`;
			
			// Show processing progress if status is processing
			if (source.status === 'processing' && progressData) {
				html += `
					<div class="askany-processing-info">
						<div class="processing-header">
							<span class="processing-icon">⚙️</span>
							<strong>${progressData.message || 'Processing...'}</strong>
						</div>
						<div class="processing-details">
							<div class="progress-text">
								<span><?php esc_html_e( 'Progress:', 'askany' ); ?> ${progressData.current} / ${progressData.total}</span>
								<span>${progressData.percentage || 0}%</span>
							</div>
							<div class="progress-bar-container">
								<div class="progress-bar-fill" style="width: ${progressData.percentage || 0}%"></div>
							</div>
							${progressData.current_url ? `<div class="current-url"><small><?php esc_html_e( 'Current:', 'askany' ); ?> ${progressData.current_url}</small></div>` : ''}
						</div>
					</div>`;
			}
			
			html += `
					<div class="askany-source-actions">
						${source.crawled_count > 0 ? `<button type="button" class="button view-urls-btn" data-id="${source.id}"><?php esc_html_e( 'View URLs', 'askany' ); ?></button>` : ''}
						<button type="button" class="button reprocess-btn" data-id="${source.id}" ${source.status === 'processing' ? 'disabled' : ''}><?php esc_html_e( 'Reprocess', 'askany' ); ?></button>
						<button type="button" class="button button-link-delete delete-btn" data-id="${source.id}" ${source.status === 'processing' ? 'disabled' : ''}><?php esc_html_e( 'Delete', 'askany' ); ?></button>
					</div>
				</div>
			`;
		});

		$('#external-sources-list').html(html);
	}

	// View URLs
	$(document).on('click', '.view-urls-btn', function() {
		const sourceId = $(this).data('id');
		
		$.ajax({
			url: `<?php echo esc_url( rest_url( 'askany/v1/external-sources/' ) ); ?>${sourceId}/urls`,
			method: 'GET',
			beforeSend: function(xhr) {
				xhr.setRequestHeader('X-WP-Nonce', '<?php echo esc_js( wp_create_nonce( 'wp_rest' ) ); ?>');
			},
			success: function(response) {
				if (response.success) {
					let urlsHtml = '<div class="askany-url-list">';
					if (response.urls.length === 0) {
						urlsHtml += '<p><?php esc_html_e( 'No URLs crawled yet.', 'askany' ); ?></p>';
					} else {
						response.urls.forEach(function(url) {
							urlsHtml += `<div class="askany-url-item"><a href="${url}" target="_blank">${url}</a></div>`;
						});
					}
					urlsHtml += '</div>';
					
					$('#modal-urls-list').html(urlsHtml);
					$('#view-urls-modal').show();
				}
			}
		});
	});

	// Reprocess source
	$(document).on('click', '.reprocess-btn', function() {
		const sourceId = $(this).data('id');
		
		if (!confirm('<?php esc_html_e( 'Are you sure you want to reprocess this external source?', 'askany' ); ?>')) {
			return;
		}
		
		$.ajax({
			url: `<?php echo esc_url( rest_url( 'askany/v1/external-sources/' ) ); ?>${sourceId}/reprocess`,
			method: 'POST',
			beforeSend: function(xhr) {
				xhr.setRequestHeader('X-WP-Nonce', '<?php echo esc_js( wp_create_nonce( 'wp_rest' ) ); ?>');
			},
			success: function(response) {
				if (response.success) {
					showNotice(response.message, 'success');
					loadExternalSources();
					startStatusChecking();
				} else {
					showNotice(response.message || '<?php esc_html_e( 'Failed to reprocess external source.', 'askany' ); ?>', 'error');
				}
			},
			error: function(xhr) {
				const response = xhr.responseJSON;
				showNotice(response?.message || '<?php esc_html_e( 'Failed to reprocess external source.', 'askany' ); ?>', 'error');
			}
		});
	});

	// Delete source
	$(document).on('click', '.delete-btn', function() {
		const sourceId = $(this).data('id');
		
		if (!confirm('<?php esc_html_e( 'Are you sure you want to delete this external source? This will also remove all crawled content.', 'askany' ); ?>')) {
			return;
		}
		
		$.ajax({
			url: `<?php echo esc_url( rest_url( 'askany/v1/external-sources/' ) ); ?>${sourceId}`,
			method: 'DELETE',
			beforeSend: function(xhr) {
				xhr.setRequestHeader('X-WP-Nonce', '<?php echo esc_js( wp_create_nonce( 'wp_rest' ) ); ?>');
			},
			success: function(response) {
				if (response.success) {
					showNotice(response.message, 'success');
					
					// Decrement sources count
					sourcesCount--;
					
					// Update Pro lock UI
					updateProLockUI();
					
					// Reload sources list
					loadExternalSources();
				} else {
					showNotice(response.message || '<?php esc_html_e( 'Failed to delete external source.', 'askany' ); ?>', 'error');
				}
			},
			error: function(xhr) {
				const response = xhr.responseJSON;
				showNotice(response?.message || '<?php esc_html_e( 'Failed to delete external source.', 'askany' ); ?>', 'error');
			}
		});
	});

	// Close modal
	$(document).on('click', '.askany-modal-close, .askany-modal', function(e) {
		if (e.target === this) {
			$('#view-urls-modal').hide();
		}
	});

	// Status checking
	let statusCheckInterval;
	
	function startStatusChecking() {
		if (statusCheckInterval) {
			clearInterval(statusCheckInterval);
		}
		
		// Load sources immediately to show initial state
		loadExternalSources();
		
		// Poll every 2 seconds for real-time updates
		statusCheckInterval = setInterval(function() {
			// Always load sources to show progress updates
			loadExternalSources();
			
			// Check status to determine if we should continue polling
			$.ajax({
				url: '<?php echo esc_url( rest_url( 'askany/v1/external-sources/status' ) ); ?>',
				method: 'GET',
				beforeSend: function(xhr) {
					xhr.setRequestHeader('X-WP-Nonce', '<?php echo esc_js( wp_create_nonce( 'wp_rest' ) ); ?>');
				},
				success: function(response) {
					if (response.success) {
						// Check for any sources that are pending or processing
						const hasActiveProcessing = response.processing_sources && response.processing_sources.length > 0;
						
						if (hasActiveProcessing) {
							$('#processing-status').show();
							$('#processing-message').text(`${response.processing_sources.length} source(s) being processed...`);
						} else {
							// No more processing sources, stop polling
							clearInterval(statusCheckInterval);
							statusCheckInterval = null;
							$('#processing-status').hide();
							// Final load to show completed state
							loadExternalSources();
							// Update sources count
							if (response.total_sources !== undefined) {
								sourcesCount = response.total_sources;
							}
						}
					}
				},
				error: function() {
					// On error, keep polling but don't stop
					console.log('Status check failed, will retry...');
				}
			});
		}, 2000); // Check every 2 seconds for real-time updates
	}

	// Update Pro lock UI based on current sources count
	function updateProLockUI() {
		const isLimitReached = !isPro && sourcesCount >= freeLimit;
		
		if (isLimitReached) {
			// Show Pro notice and hide form
			if ($('.askany-pro-notice').length === 0) {
				const proNoticeHtml = `
					<div class="askany-pro-notice">
						<div class="askany-pro-notice-icon">
							<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
								<rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
								<path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
							</svg>
						</div>
						<div class="askany-pro-notice-content">
							<h3><?php esc_html_e( 'External Sources Limit Reached', 'askany' ); ?></h3>
							<p><?php echo esc_html( sprintf( __( 'Free plan allows up to %d external sources. Upgrade to Pro for unlimited external sources.', 'askany' ), $free_limit ) ); ?></p>
							<button type="button" class="button button-primary askany-open-pro-modal">
								<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 6px;">
									<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
								</svg>
								<?php esc_html_e( 'Upgrade to Pro', 'askany' ); ?>
							</button>
						</div>
					</div>
				`;
				$('#add-external-source-form').before(proNoticeHtml);
			}
			$('#add-external-source-form').hide();
		} else {
			// Remove Pro notice and show form
			$('.askany-pro-notice').remove();
			$('#add-external-source-form').show();
		}
		
		// Update badge count if it exists
		$('.askany-sources-limit-badge').text(`${sourcesCount} / ${freeLimit} sources`);
	}
	
	// Show notice
	function showNotice(message, type) {
		const noticeClass = type === 'success' ? 'notice-success' : 'notice-error';
		const notice = $(`<div class="notice ${noticeClass} is-dismissible"><p>${message}</p></div>`);
		$('.wrap h1').after(notice);
		
		setTimeout(function() {
			notice.fadeOut();
		}, 5000);
	}

	// Initial load
	loadExternalSources();
	
	// Check if there are any processing sources on page load
	$.ajax({
		url: '<?php echo esc_url( rest_url( 'askany/v1/external-sources/status' ) ); ?>',
		method: 'GET',
		beforeSend: function(xhr) {
			xhr.setRequestHeader('X-WP-Nonce', '<?php echo esc_js( wp_create_nonce( 'wp_rest' ) ); ?>');
		},
		success: function(response) {
			if (response.success && response.processing_sources.length > 0) {
				// Start polling if there are processing sources
				startStatusChecking();
			}
		}
	});
});
</script>