<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @since 1.0.0
 * @license GPL-2.0-or-later
 */
namespace Wisewand\Admin;

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

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

/**
 * Wisewand Dashboard - Central command center for content automation.
 *
 * Implements a "Silicon Valley SaaS" style dashboard with:
 * - Key performance metrics (Velocity, Success Rate)
 * - Visual data representation
 * - Action-oriented layout
 * - System health monitoring
 */
class Dashboard_Page {

	/**
	 * Plugin options instance.
	 *
	 * @var Options
	 */
	private $options;

	/**
	 * Logger instance.
	 *
	 * @var Logger
	 */
	private $logger;

	/**
	 * Calendar Entry Manager instance.
	 *
	 * @var Calendar_Entry_Manager
	 */
	private $entry_manager;

	/**
	 * Database table name for editorial calendar.
	 *
	 * @var string
	 */
	private $table_name;

	/**
	 * Constructor.
	 *
	 * @param Options $options Plugin options.
	 * @param Logger  $logger  Logger instance.
	 */
	public function __construct( Options $options, Logger $logger ) {
		global $wpdb;
		$this->options    = $options;
		$this->logger     = $logger;
		$this->table_name = $wpdb->prefix . 'wisewand_editorial_calendar';

		// Initialize dependencies if not already loaded
		if ( ! class_exists( 'Wisewand\\Calendar\\Calendar_Entry_Manager' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Calendar/Calendar_Entry_Manager.php';
		}
		if ( ! class_exists( 'Wisewand\\Utils\\Wisewand_Payload_Builder' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_Payload_Builder.php';
		}

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

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

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

		wp_localize_script(
			'wisewand-dashboard-admin',
			'wisewandDashboard',
			array(
				'ajaxUrl'     => admin_url( 'admin-ajax.php' ),
				'nonce'       => wp_create_nonce( 'wisewand_dashboard' ),
				'calendarUrl' => admin_url( 'admin.php?page=wisewand-editorial-calendar' ),
			)
		);
	}

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

		$metrics = $this->get_dashboard_metrics();
		$this->enqueue_assets();

		?>
		<div class="wrap wisewand-dashboard-page">
			<!-- Header -->
			<div class="dashboard-header">
				<div class="header-title">
					<h1><?php esc_html_e( 'Wisewand Overview', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h1>
					<p class="header-subtitle"><?php esc_html_e( 'Your AI content automation command center.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				</div>
				<div class="header-actions">
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-editorial-calendar' ) ); ?>" class="ww-btn ww-btn-secondary">
						📅 <?php esc_html_e( 'View Calendar', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</a>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-seo-intelligence' ) ); ?>" class="ww-btn ww-btn-primary">
						✨ <?php esc_html_e( 'New Article', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</a>
				</div>
			</div>

			<!-- Key Metrics Grid -->
			<div class="metrics-grid">
				<!-- Velocity Metric -->
				<div class="metric-card">
					<div class="metric-header">
						<span class="metric-title"><?php esc_html_e( 'Content Velocity', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						<div class="metric-icon">🚀</div>
					</div>
					<div class="metric-value"><?php echo esc_html( $metrics['velocity']['current'] ); ?></div>
					<div class="metric-trend">
						<?php echo $this->render_trend( $metrics['velocity']['trend'] ); ?>
						<span class="trend-label"><?php esc_html_e( 'vs last month', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					</div>
				</div>

				<!-- Success Rate Metric -->
				<div class="metric-card">
					<div class="metric-header">
						<span class="metric-title"><?php esc_html_e( 'Success Rate', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						<span class="metric-icon">🎯</span>
					</div>
					<div class="metric-value"><?php echo round( $metrics['success_rate']['percentage'] ); ?>%</div>
					<div class="metric-trend">
						<span class="trend-neutral"><?php echo esc_html( $metrics['success_rate']['total'] . ' ' . __( 'total generated', 'wisewand-ai-content-writer-seo-content-generator' ) ); ?></span>
					</div>
				</div>

				<!-- Queue Status Metric -->
				<div class="metric-card">
					<div class="metric-header">
						<span class="metric-title"><?php esc_html_e( 'In Queue', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						<div class="metric-icon">⏳</div>
					</div>
					<div class="metric-value"><?php echo esc_html( $metrics['queue']['total'] ); ?></div>
					<div class="metric-trend">
						<span class="trend-neutral"><?php echo esc_html( $metrics['queue']['generating'] ); ?> <?php esc_html_e( 'processing now', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					</div>
				</div>

				<!-- Total Imported Metric -->
				<div class="metric-card">
					<div class="metric-header">
						<span class="metric-title"><?php esc_html_e( 'Total Imported', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						<div class="metric-icon">📚</div>
					</div>
					<div class="metric-value"><?php echo esc_html( $metrics['imported']['total'] ); ?></div>
					<div class="metric-trend">
						<span class="trend-up">+<?php echo esc_html( $metrics['imported']['last_30d'] ); ?></span>
						<span class="trend-label"><?php esc_html_e( 'this month', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
					</div>
				</div>

				<!-- WiseWand Credits -->
				<?php
				$credit_balance = null;
				$api_key        = $this->options->get( 'wisewand_api_key', '' );
				if ( ! empty( $api_key ) ) {
					if ( ! class_exists( 'Wisewand\\Utils\\Wisewand_API_Client' ) ) {
						require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_API_Client.php';
					}
					$api_client     = new \Wisewand\Utils\Wisewand_API_Client( $api_key, $this->logger );
					$credit_balance = $api_client->get_credit_balance();
				}

				$credits_value = 0;
				$credits_class = 'credits-ok';
				if ( is_wp_error( $credit_balance ) || null === $credit_balance ) {
					$credits_display = '—';
					$credits_class   = 'credits-unknown';
				} else {
					$credits_value   = $credit_balance['credits'];
					$credits_display = number_format( $credits_value, 1 );
					if ( $credits_value <= 0 ) {
						$credits_class = 'credits-empty';
					} elseif ( $credits_value < 10 ) {
						$credits_class = 'credits-low';
					}
				}
				?>
				<div class="metric-card <?php echo esc_attr( $credits_class ); ?>">
					<div class="metric-header">
						<span class="metric-title"><?php esc_html_e( 'Wisewand Credits', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						<div class="metric-icon">💰</div>
					</div>
					<div class="metric-value"><?php echo esc_html( $credits_display ); ?></div>
					<div class="metric-trend">
						<a href="https://app.wisewand.ai/buy-credits" target="_blank" rel="noopener" class="trend-link">
							<?php esc_html_e( 'Get more credits', 'wisewand-ai-content-writer-seo-content-generator' ); ?> &rarr;
						</a>
					</div>
				</div>
			</div>

			<!-- Main Layout Grid -->
			<div class="dashboard-main-grid">
				<!-- Left Column: Activity & Performance -->
				<div class="main-column">
					<!-- Recent Activity -->
					<div class="content-card">
						<div class="card-header">
							<h3 class="card-title"><?php esc_html_e( 'Recent Activity', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
						</div>
						<div class="card-body">
							<?php if ( empty( $metrics['recent_activity'] ) ) : ?>
								<div class="empty-state">
									<p><?php esc_html_e( 'No recent activity found. Start generating content!', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
								</div>
							<?php else : ?>
								<div class="activity-list">
									<?php foreach ( $metrics['recent_activity'] as $activity ) : ?>
										<div class="activity-item">
											<div class="activity-icon-wrapper">
												<?php echo $activity['icon']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Icon is safe HTML ?>
											</div>
											<div class="activity-details">
												<div class="activity-title"><?php echo esc_html( $activity['title'] ); ?></div>
												<div class="activity-meta">
													<?php echo esc_html( $activity['time_ago'] ); ?> • 
													<span class="status-badge <?php echo esc_attr( $activity['status_class'] ); ?>">
														<?php echo esc_html( $activity['status_label'] ); ?>
													</span>
												</div>
											</div>
											<div class="activity-action">
												<?php if ( ! empty( $activity['action_url'] ) ) : ?>
													<a href="<?php echo esc_url( $activity['action_url'] ); ?>" class="ww-btn ww-btn-secondary" style="padding: 4px 8px; font-size: 12px;">
														<?php esc_html_e( 'View', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
													</a>
												<?php endif; ?>
											</div>
										</div>
									<?php endforeach; ?>
								</div>
							<?php endif; ?>
						</div>
					</div>
				</div>

				<!-- Right Column: System Health & Quick Links -->
				<div class="sidebar-column">
					<!-- Automation Hub -->
					<div class="content-card">
						<div class="card-header">
							<h3 class="card-title"><?php esc_html_e( 'Automation Hub', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
						</div>
						<div class="card-body">
							<div class="automation-grid">
								<!-- Status Check -->
								<div class="automation-card">
									<div class="automation-icon status-check">⚡</div>
									<div class="automation-content">
										<h4 class="automation-title"><?php esc_html_e( 'Status Check', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h4>
										<p class="automation-meta">
											<?php 
											$next = $metrics['automation']['status_check']['next_run'];
											if ( $next ) {
												/* translators: %s: Time until next run */
												printf( esc_html__( 'Next: %s', 'wisewand-ai-content-writer-seo-content-generator' ), human_time_diff( current_time( 'timestamp' ), $next ) );
											} else {
												esc_html_e( 'Not scheduled', 'wisewand-ai-content-writer-seo-content-generator' );
											}
											?>
										</p>
									</div>
									<button type="button" class="ww-btn ww-btn-sm run-automation" data-action="wisewand_manual_cron_trigger">
										<?php esc_html_e( 'Run Now', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</button>
								</div>

								<!-- Daily Generation -->
								<div class="automation-card">
									<div class="automation-icon daily-gen">📅</div>
									<div class="automation-content">
										<h4 class="automation-title"><?php esc_html_e( 'Daily Builder', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h4>
										<p class="automation-meta">
											<?php 
											$next = $metrics['automation']['daily_gen']['next_run'];
											if ( $next ) {
												/* translators: %s: Time until next run */
												printf( esc_html__( 'Next: %s', 'wisewand-ai-content-writer-seo-content-generator' ), human_time_diff( current_time( 'timestamp' ), $next ) );
											} else {
												esc_html_e( 'Not scheduled', 'wisewand-ai-content-writer-seo-content-generator' );
											}
											?>
										</p>
									</div>
									<button type="button" class="ww-btn ww-btn-sm run-automation" data-action="wisewand_manual_full_cron_trigger">
										<?php esc_html_e( 'Run Now', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</button>
								</div>

								<!-- RSS Sync -->
								<div class="automation-card">
									<div class="automation-icon rss-sync">📡</div>
									<div class="automation-content">
										<h4 class="automation-title"><?php esc_html_e( 'RSS Sync', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h4>
										<p class="automation-meta">
											<?php 
											$next = $metrics['automation']['rss_sync']['next_run'];
											if ( $next ) {
												/* translators: %s: Time until next run */
												printf( esc_html__( 'Next: %s', 'wisewand-ai-content-writer-seo-content-generator' ), human_time_diff( current_time( 'timestamp' ), $next ) );
											} else {
												esc_html_e( 'Not scheduled', 'wisewand-ai-content-writer-seo-content-generator' );
											}
											?>
										</p>
									</div>
									<button type="button" class="ww-btn ww-btn-sm run-automation" data-action="wisewand_manual_rss_trigger">
										<?php esc_html_e( 'Sync Now', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</button>
								</div>
							</div>
						</div>
					</div>

					<!-- System Health -->
					<div class="content-card">
						<div class="card-header">
							<h3 class="card-title"><?php esc_html_e( 'System Health', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
						</div>
						<div class="card-body">
							<div class="health-list">
								<div class="health-item">
									<span class="health-label">
										<span class="health-status-dot <?php echo $metrics['health']['api'] ? 'active' : 'offline'; ?>"></span>
										<?php esc_html_e( 'API Connection', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</span>
									<span class="health-value"><?php echo $metrics['health']['api'] ? esc_html__( 'Connected', 'wisewand-ai-content-writer-seo-content-generator' ) : esc_html__( 'Error', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
								</div>
								<div class="health-item">
									<span class="health-label">
										<span class="health-status-dot <?php echo $metrics['health']['cron'] ? 'active' : 'issue'; ?>"></span>
										<?php esc_html_e( 'Background Jobs', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</span>
									<span class="health-value"><?php echo $metrics['health']['cron'] ? esc_html__( 'Running', 'wisewand-ai-content-writer-seo-content-generator' ) : esc_html__( 'Check CRON', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
								</div>
								<div class="health-item">
									<span class="health-label">
										<span class="health-status-dot <?php echo $metrics['health']['rss'] > 0 ? 'active' : 'neutral'; ?>"></span>
										<?php esc_html_e( 'Active RSS Feeds', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</span>
									<span class="health-value"><?php echo esc_html( $metrics['health']['rss'] ); ?></span>
								</div>
							</div>
						</div>
					</div>

					<!-- Quick Links -->
					<div class="quick-links-grid">
						<a href="https://help.wisewand.ai" target="_blank" class="quick-link-card">
							<span class="quick-link-icon">📚</span>
							<span class="quick-link-text"><?php esc_html_e( 'Docs', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						</a>
						<a href="https://app.wisewand.ai" target="_blank" class="quick-link-card">
							<span class="quick-link-icon">💬</span>
							<span class="quick-link-text"><?php esc_html_e( 'Support', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						</a>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-settings' ) ); ?>" class="quick-link-card">
							<span class="quick-link-icon">⚙️</span>
							<span class="quick-link-text"><?php esc_html_e( 'Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						</a>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-articles' ) ); ?>" class="quick-link-card">
							<span class="quick-link-icon">📝</span>
							<span class="quick-link-text"><?php esc_html_e( 'Articles', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						</a>
					</div>
				</div>
			</div>

			<!-- Footer -->
			<div class="dashboard-footer">
				<p>
					Wisewand v<?php echo esc_html( WISEWAND_PLUGIN_VERSION ); ?> • 
					<a href="https://wisewand.ai/privacy" target="_blank"><?php esc_html_e( 'Privacy Policy', 'wisewand-ai-content-writer-seo-content-generator' ); ?></a> • 
					<a href="https://wisewand.ai/terms" target="_blank"><?php esc_html_e( 'Terms of Service', 'wisewand-ai-content-writer-seo-content-generator' ); ?></a>
				</p>
			</div>
		</div>
		<?php
	}

	/**
	 * Gather all dashboard metrics in a single optimized pass.
	 * v1.9.6: Consolidated to include RSS stats.
	 *
	 * @return array
	 */
	private function get_dashboard_metrics() {
		global $wpdb;
		$rss_table_name = $wpdb->prefix . 'wisewand_rss_articles';

		// --- 1. Velocity (Current Month vs Last Month) ---
		// Calendar
		$cal_files_cm = $wpdb->get_var(
			"SELECT COUNT(*) FROM {$this->table_name} 
             WHERE wisewand_status = 'ready' 
             AND MONTH(updated_at) = MONTH(CURRENT_DATE()) 
             AND YEAR(updated_at) = YEAR(CURRENT_DATE())"
		);
		$cal_files_lm = $wpdb->get_var(
			"SELECT COUNT(*) FROM {$this->table_name} 
             WHERE wisewand_status = 'ready' 
             AND MONTH(updated_at) = MONTH(CURRENT_DATE() - INTERVAL 1 MONTH) 
             AND YEAR(updated_at) = YEAR(CURRENT_DATE() - INTERVAL 1 MONTH)"
		);

		// RSS
		$rss_files_cm = $wpdb->get_var(
			"SELECT COUNT(*) FROM {$rss_table_name} 
             WHERE import_status = 'imported' 
             AND MONTH(imported_at) = MONTH(CURRENT_DATE()) 
             AND YEAR(imported_at) = YEAR(CURRENT_DATE())"
		);
		$rss_files_lm = $wpdb->get_var(
			"SELECT COUNT(*) FROM {$rss_table_name} 
             WHERE import_status = 'imported' 
             AND MONTH(imported_at) = MONTH(CURRENT_DATE() - INTERVAL 1 MONTH) 
             AND YEAR(imported_at) = YEAR(CURRENT_DATE() - INTERVAL 1 MONTH)"
		);

		$current_month_count = (int)$cal_files_cm + (int)$rss_files_cm;
		$last_month_count    = (int)$cal_files_lm + (int)$rss_files_lm;

		$velocity_trend = 0;
		if ( $last_month_count > 0 ) {
			$velocity_trend = ( ( $current_month_count - $last_month_count ) / $last_month_count ) * 100;
		} elseif ( $current_month_count > 0 ) {
			$velocity_trend = 100; // 100% increase if starting from 0
		}


		// --- 2. Success Rate (All Time) ---
		// Calendar
		$cal_stats = $wpdb->get_row(
			"SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN wisewand_status = 'ready' OR wordpress_status = 'published' THEN 1 ELSE 0 END) as successful
             FROM {$this->table_name}",
			ARRAY_A
		);
		
		// RSS
		$rss_stats = $wpdb->get_row(
			"SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN import_status = 'imported' THEN 1 ELSE 0 END) as successful
             FROM {$rss_table_name}",
			ARRAY_A
		);

		$total_attempts = (int)$cal_stats['total'] + (int)$rss_stats['total'];
		$total_success  = (int)$cal_stats['successful'] + (int)$rss_stats['successful'];
		
		$success_percentage = ( $total_attempts > 0 ) ? ( $total_success / $total_attempts ) * 100 : 0;


		// --- 3. Queue Status ---
		// Calendar
		$cal_queue = $wpdb->get_row(
			"SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN wisewand_status IN ('creating', 'generating') THEN 1 ELSE 0 END) as generating
             FROM {$this->table_name} 
             WHERE wisewand_status IN ('not_created', 'creating', 'generating')",
			ARRAY_A
		);

		// RSS (Pending/Importing)
		$rss_queue = $wpdb->get_row(
			"SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN import_status = 'importing' THEN 1 ELSE 0 END) as generating
             FROM {$rss_table_name} 
             WHERE import_status IN ('pending', 'importing')",
			ARRAY_A
		);

		$queue_total      = (int)($cal_queue['total'] ?? 0) + (int)($rss_queue['total'] ?? 0);
		$queue_generating = (int)($cal_queue['generating'] ?? 0) + (int)($rss_queue['generating'] ?? 0);


		// --- 4. Imported Stats (Total Published via Plugin) ---
		// Calendar
		$cal_imported = $wpdb->get_row(
			"SELECT 
				COUNT(*) as total,
				SUM(CASE WHEN published_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) as last_30d
             FROM {$this->table_name} WHERE wordpress_post_id > 0",
			ARRAY_A
		);

		// RSS
		$rss_imported = $wpdb->get_row(
			"SELECT 
				COUNT(*) as total,
				SUM(CASE WHEN imported_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) as last_30d
             FROM {$rss_table_name} WHERE wordpress_post_id > 0",
			ARRAY_A
		);
		
		$imported_total = (int)$cal_imported['total'] + (int)$rss_imported['total'];
		$imported_30d   = (int)$cal_imported['last_30d'] + (int)$rss_imported['last_30d'];


		// --- 5. Recent Activity (Merged) ---
		// Fetch 5 from each, merge, sort, take top 5
		$cal_recent = $wpdb->get_results(
			"SELECT *, 'calendar' as source_type FROM {$this->table_name} ORDER BY updated_at DESC LIMIT 5",
			ARRAY_A
		);

		$rss_recent = $wpdb->get_results(
			"SELECT 
				id, 
				article_title as keyword, 
				import_status as wisewand_status, 
				wordpress_post_id,
				wisewand_article_id, 
				updated_at, 
				import_status, 
				'rss' as source_type 
			 FROM {$rss_table_name} ORDER BY updated_at DESC LIMIT 5",
			ARRAY_A
		);
		
		// Normalize RSS status to match format_activity_entry expectations if needed
		// But verify format_activity_entry handles generic statuses or add logic there.
		
		$all_recent = array_merge( $cal_recent, $rss_recent ?? array() );
		
		// Sort by updated_at DESC
		usort( $all_recent, function($a, $b) {
			return strtotime($b['updated_at']) - strtotime($a['updated_at']);
		});
		
		$all_recent = array_slice( $all_recent, 0, 5 );

		$recent_activity = array();
		foreach ( $all_recent as $entry ) {
			$recent_activity[] = $this->format_activity_entry( $entry );
		}

		// --- 6. System Health ---
		$api_key = Wisewand_API_Client::get_stored_api_key();
		$cron_ok = ( wp_next_scheduled( 'wisewand_check_article_status' ) !== false );
		$rss_count = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}wisewand_rss_feeds WHERE sync_status = 'enabled'" );

		// --- 7. Automation Hub Data ---
		$automation = array(
			'status_check' => array(
				'next_run' => wp_next_scheduled( 'wisewand_check_article_status' ),
				'last_run' => get_option( 'wisewand_cron_last_status_check', null ),
			),
			'daily_gen'    => array(
				'next_run' => wp_next_scheduled( 'wisewand_editorial_calendar_cron' ),
				'last_run' => get_option( 'wisewand_cron_last_run', null ),
			),
			'rss_sync'     => array(
				'next_run' => wp_next_scheduled( 'wisewand_rss_sync' ),
				'last_run' => get_option( 'wisewand_rss_last_sync', null ), // Assuming this option exists or we might need to add it
			),
		);

		return array(
			'velocity'        => array(
				'current' => $current_month_count,
				'last'    => $last_month_count,
				'trend'   => $velocity_trend,
			),
			'success_rate'    => array(
				'percentage' => $success_percentage,
				'total'      => $total_attempts, // Used for 'Total Actions'
			),
			'queue'           => array(
				'total'      => $queue_total,
				'generating' => $queue_generating,
			),
			'imported'        => array(
				'total'    => $imported_total,
				'last_30d' => $imported_30d,
			),
			'recent_activity' => $recent_activity,
			'health'          => array(
				'api'  => ! empty( $api_key ),
				'cron' => $cron_ok,
				'rss'  => $rss_count,
			),
			'automation'      => $automation,
		);
	}

	/**
	 * Format a database entry into an activity item.
	 *
	 * @param array $entry Database row.
	 * @return array Formatted activity item.
	 */
	private function format_activity_entry( $entry ) {
		// Determine status to use
		$status_key = $entry['wisewand_status'];
		if ( isset( $entry['source_type'] ) && $entry['source_type'] === 'rss' ) {
			$status_key = $entry['import_status'];
		}
		
		$status_config = $this->get_status_config( $status_key );
		$time_ago      = human_time_diff( strtotime( $entry['updated_at'] ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'wisewand-ai-content-writer-seo-content-generator' );
		
		$action_url = '';
		if ( $entry['wordpress_post_id'] ) {
			$action_url = get_edit_post_link( $entry['wordpress_post_id'] );
		} elseif ( ! empty( $entry['wisewand_article_id'] ) && ( ! isset( $entry['source_type'] ) || $entry['source_type'] !== 'rss' ) ) {
			// Only link to AI editor if likely an AI article
			$action_url = 'https://app.wisewand.ai/articles/' . $entry['wisewand_article_id'] . '/result';
		}

		return array(
			'title'        => $entry['keyword'], // RSS query aliases title as keyword
			'time_ago'     => $time_ago,
			'status_label' => $status_config['label'],
			'status_class' => $status_config['class'],
			'icon'         => $status_config['icon'],
			'action_url'   => $action_url,
		);
	}

	/**
	 * Get UI config for a status.
	 *
	 * @param string $status Status string.
	 * @return array UI config (label, class, icon).
	 */
	private function get_status_config( $status ) {
		switch ( $status ) {
			case 'ready':
			case 'published':
			case 'imported': // RSS
				return array(
					'label' => __( 'Success', 'wisewand-ai-content-writer-seo-content-generator' ),
					'class' => 'status-success',
					'icon'  => '✅',
				);
			case 'failed':
				return array(
					'label' => __( 'Failed', 'wisewand-ai-content-writer-seo-content-generator' ),
					'class' => 'status-error',
					'icon'  => '⚠️',
				);
			case 'generating':
			case 'creating':
			case 'importing': // RSS
				return array(
					'label' => __( 'Processing', 'wisewand-ai-content-writer-seo-content-generator' ),
					'class' => 'status-warning',
					'icon'  => '🔄',
				);
			case 'pending': // RSS
				return array(
					'label' => __( 'Queued', 'wisewand-ai-content-writer-seo-content-generator' ),
					'class' => 'status-neutral',
					'icon'  => '⏳',
				);
			case 'skipped': // RSS
				return array(
					'label' => __( 'Skipped', 'wisewand-ai-content-writer-seo-content-generator' ),
					'class' => 'status-neutral',
					'icon'  => '⏭️',
				);
			default:
				return array(
					'label' => __( 'Scheduled', 'wisewand-ai-content-writer-seo-content-generator' ),
					'class' => 'status-neutral',
					'icon'  => '📅',
				);
		}
	}

	/**
	 * Render trend HTML.
	 *
	 * @param float $trend Trend percentage.
	 * @return string HTML.
	 */
	private function render_trend( $trend ) {
		if ( $trend > 0 ) {
			return '<span class="trend-up">⬆️ ' . round( $trend ) . '%</span>';
		} elseif ( $trend < 0 ) {
			return '<span class="trend-down">⬇️ ' . round( abs( $trend ) ) . '%</span>';
		}
		return '<span class="trend-neutral">➖ 0%</span>';
	}
}
