<?php

/**

 * Sensfrx.ai (SFX) Dashboard Widget

 *

 * Displays fraud prevention metrics and insights on WordPress admin dashboard

 *

 * @package    Sensfrx

 * @subpackage Sensfrx/admin

 */



if ( ! defined( 'ABSPATH' ) ) {

	die;

}



class SensFRX_Dashboard_Widget {



	/**

	 * Register dashboard widget

	 */

	public static function register() {

		add_action( 'wp_dashboard_setup', array( __CLASS__, 'add_dashboard_widget' ) );

		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_dashboard_styles' ) );

	}



	/**

	 * Add dashboard widget

	 */

	public static function add_dashboard_widget() {

		wp_add_dashboard_widget(

			'sensfrx_dashboard_widget',

			'<div style="display: flex; align-items: center; gap: 8px;"><img src="' . plugin_dir_url( dirname( __FILE__ ) ) . 'admin/image/sensfrx.png" style="height: 20px;"> <span style="font-weight: 600;">Sensfrx.ai (SFX) - Fraud Protection</span></div>',

			array( __CLASS__, 'render_dashboard_widget' )

		);

	}



	/**

	 * Enqueue dashboard styles

	 */

	public static function enqueue_dashboard_styles( $hook ) {

		if ( 'index.php' !== $hook ) {

			return;

		}



		wp_add_inline_style( 'dashboard', '

			#sensfrx_dashboard_widget .inside {

				margin: 0;

				padding: 0;

			}

			.sfx-dashboard {

				font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, sans-serif;

			}

			.sfx-stat-grid {

				display: grid;

				grid-template-columns: repeat(2, 1fr);

				gap: 12px;

				padding: 16px;

				background: #f8f9fa;

			}

			.sfx-stat-card {

				background: #fff;

				padding: 16px;

				border-radius: 6px;

				border-left: 3px solid #246cf2;

				box-shadow: 0 1px 3px rgba(0,0,0,0.05);

			}

			.sfx-stat-label {

				font-size: 12px;

				color: #6c757d;

				text-transform: uppercase;

				letter-spacing: 0.5px;

				margin-bottom: 6px;

				font-weight: 500;

			}

			.sfx-stat-value {

				font-size: 28px;

				font-weight: 700;

				color: #1d2327;

				line-height: 1;

			}

			.sfx-stat-value.success {

				color: #28a745;

			}

			.sfx-stat-value.warning {

				color: #ffc107;

			}

			.sfx-stat-value.danger {

				color: #dc3545;

			}

			.sfx-stat-change {

				font-size: 11px;

				color: #28a745;

				margin-top: 6px;

			}

			.sfx-attack-types {

				padding: 16px;

				background: #fff;

			}

			.sfx-attack-item {

				display: flex;

				justify-content: space-between;

				align-items: center;

				padding: 10px 0;

				border-bottom: 1px solid #e5e7eb;

			}

			.sfx-attack-item:last-child {

				border-bottom: none;

			}

			.sfx-attack-name {

				font-size: 13px;

				color: #1d2327;

				font-weight: 500;

			}

			.sfx-attack-count {

				font-size: 13px;

				color: #fff;

				background: #246cf2;

				padding: 3px 10px;

				border-radius: 12px;

				font-weight: 600;

			}

			.sfx-status-banner {

				padding: 14px 16px;

				background: linear-gradient(135deg, #246cf2 0%, #1a56d4 100%);

				color: #fff;

				display: flex;

				justify-content: space-between;

				align-items: center;

			}

			.sfx-status-banner.inactive {

				background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%);

			}

			.sfx-status-text {

				font-size: 14px;

				font-weight: 600;

			}

			.sfx-status-badge {

				background: rgba(255,255,255,0.2);

				padding: 4px 12px;

				border-radius: 12px;

				font-size: 11px;

				font-weight: 700;

				text-transform: uppercase;

				letter-spacing: 0.5px;

			}

			.sfx-footer {

				padding: 12px 16px;

				background: #f8f9fa;

				border-top: 1px solid #e5e7eb;

				display: flex;

				justify-content: space-between;

				align-items: center;

			}

			.sfx-footer-link {

				font-size: 13px;

				color: #246cf2;

				text-decoration: none;

				font-weight: 500;

			}

			.sfx-footer-link:hover {

				color: #1a56d4;

			}

			.sfx-empty-state {

				padding: 40px 16px;

				text-align: center;

			}

			.sfx-empty-icon {

				font-size: 48px;

				margin-bottom: 16px;

				opacity: 0.3;

			}

			.sfx-empty-title {

				font-size: 16px;

				font-weight: 600;

				color: #1d2327;

				margin-bottom: 8px;

			}

			.sfx-empty-text {

				font-size: 13px;

				color: #6c757d;

				margin-bottom: 16px;

			}

			.sfx-setup-btn {

				display: inline-block;

				background: #246cf2;

				color: #fff;

				padding: 10px 24px;

				border-radius: 4px;

				text-decoration: none;

				font-weight: 600;

				font-size: 14px;

			}

			.sfx-setup-btn:hover {

				background: #1a56d4;

				color: #fff;

			}

			.sfx-insights {

				background: #fff3cd;

				border-left: 4px solid #ffc107;

				padding: 14px 16px;

				margin: 0;

			}

			.sfx-insights-title {

				font-size: 13px;

				font-weight: 700;

				color: #856404;

				margin-bottom: 8px;

				display: flex;

				align-items: center;

				gap: 6px;

			}

			.sfx-insight-item {

				display: flex;

				align-items: flex-start;

				gap: 10px;

				padding: 8px 0;

				border-bottom: 1px solid rgba(255, 193, 7, 0.2);

			}

			.sfx-insight-item:last-child {

				border-bottom: none;

				padding-bottom: 0;

			}

			.sfx-insight-icon {

				font-size: 16px;

				flex-shrink: 0;

			}

			.sfx-insight-content {

				flex: 1;

			}

			.sfx-insight-text {

				font-size: 13px;

				color: #856404;

				margin-bottom: 6px;

				line-height: 1.5;

			}

			.sfx-insight-action {

				display: inline-flex;

				align-items: center;

				gap: 4px;

				font-size: 12px;

				color: #246cf2;

				text-decoration: none;

				font-weight: 600;

			}

			.sfx-insight-action:hover {

				color: #1a56d4;

			}

		' );

	}



	/**

	 * Render dashboard widget content

	 */

	public static function render_dashboard_widget() {

		// Check if plugin is configured

		$options = get_option( 'sensfrx_options', SensFRX::default_options() );

		$has_credentials = ! empty( $options['sensfrx_property_id'] ) && ! empty( $options['sensfrx_property_secret'] );



		if ( ! $has_credentials ) {

			self::render_setup_required();

			return;

		}



		// Get fraud prevention stats

		$stats = self::get_dashboard_stats();



		// Get actionable insights

		$insights = self::get_actionable_insights( $stats );



		?>

		<div class="sfx-dashboard">

			<?php self::render_status_banner( $stats ); ?>

			<?php if ( ! empty( $insights ) ) : ?>

				<?php self::render_insights( $insights ); ?>

			<?php endif; ?>

			<?php self::render_stats_grid( $stats ); ?>

			<?php self::render_attack_types( $stats ); ?>

			<?php self::render_footer(); ?>

		</div>

		<?php

	}



	/**

	 * Render setup required state

	 */

	private static function render_setup_required() {

		?>

		<div class="sfx-dashboard">

			<div class="sfx-empty-state">

				<div class="sfx-empty-icon">⚙</div>

				<div class="sfx-empty-title">Fraud Protection Not Active</div>

				<div class="sfx-empty-text">

					Complete your Sensfrx.ai (SFX) setup to start protecting your store from fraud

				</div>



				<!-- Tic-Tac-Toe Game -->

				<div class="sfx-game-container" style="margin: 24px 0;">

					<div class="sfx-game-header" style="font-size: 13px; color: #6c757d; margin-bottom: 12px;">

						Meanwhile, play a quick game! <span id="sfx-game-status" style="font-weight: 600; color: #246cf2;"></span>

					</div>

					<div id="sfx-tictactoe-board" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; max-width: 240px; margin: 0 auto 16px;">

						<div class="sfx-cell" data-index="0"></div>

						<div class="sfx-cell" data-index="1"></div>

						<div class="sfx-cell" data-index="2"></div>

						<div class="sfx-cell" data-index="3"></div>

						<div class="sfx-cell" data-index="4"></div>

						<div class="sfx-cell" data-index="5"></div>

						<div class="sfx-cell" data-index="6"></div>

						<div class="sfx-cell" data-index="7"></div>

						<div class="sfx-cell" data-index="8"></div>

					</div>

					<div id="sfx-game-result" style="font-size: 14px; font-weight: 600; color: #246cf2; min-height: 40px; display: flex; align-items: center; justify-content: center;"></div>

					<button onclick="sfxResetGame()" style="background: #e9ecef; border: 1px solid #dee2e6; color: #495057; padding: 8px 16px; border-radius: 4px; font-size: 13px; cursor: pointer; margin-bottom: 16px;">

						New Game

					</button>

				</div>



				<a href="<?php echo esc_url( admin_url( 'admin.php?page=sensfrx_fpwoo' ) ); ?>" class="sfx-setup-btn">

					Complete Setup

				</a>

			</div>

		</div>



		<style>

		.sfx-cell {

			background: #fff;

			border: 2px solid #dee2e6;

			border-radius: 6px;

			height: 70px;

			display: flex;

			align-items: center;

			justify-content: center;

			font-size: 32px;

			font-weight: 700;

			cursor: pointer;

			transition: all 0.2s;

		}

		.sfx-cell:hover:not(.taken) {

			background: #f8f9fa;

			border-color: #246cf2;

			transform: scale(1.05);

		}

		.sfx-cell.taken {

			cursor: not-allowed;

		}

		.sfx-cell.x {

			color: #246cf2;

		}

		.sfx-cell.o {

			color: #28a745;

		}

		.sfx-cell.winning {

			background: #fff3cd;

			border-color: #ffc107;

			animation: sfxWinPulse 0.5s ease-in-out;

		}

		@keyframes sfxWinPulse {

			0%, 100% { transform: scale(1); }

			50% { transform: scale(1.1); }

		}

		</style>



		<script>

		let sfxBoard = ['', '', '', '', '', '', '', '', ''];

		let sfxCurrentPlayer = 'X';

		let sfxGameActive = true;



		const sfxWinPatterns = [

			[0, 1, 2], [3, 4, 5], [6, 7, 8], // Rows

			[0, 3, 6], [1, 4, 7], [2, 5, 8], // Columns

			[0, 4, 8], [2, 4, 6]              // Diagonals

		];



		function sfxUpdateStatus(message) {

			document.getElementById('sfx-game-status').textContent = message;

		}



		function sfxCheckWinner() {

			for (let pattern of sfxWinPatterns) {

				const [a, b, c] = pattern;

				if (sfxBoard[a] && sfxBoard[a] === sfxBoard[b] && sfxBoard[a] === sfxBoard[c]) {

					return { winner: sfxBoard[a], pattern: pattern };

				}

			}

			if (!sfxBoard.includes('')) {

				return { winner: 'Draw', pattern: null };

			}

			return null;

		}



		function sfxHandleClick(e) {

			const cell = e.target;

			const index = parseInt(cell.dataset.index);



			if (sfxBoard[index] !== '' || !sfxGameActive) return;



			sfxBoard[index] = sfxCurrentPlayer;

			cell.textContent = sfxCurrentPlayer;

			cell.classList.add('taken', sfxCurrentPlayer.toLowerCase());



			const result = sfxCheckWinner();

			if (result) {

				sfxGameActive = false;

				if (result.winner === 'Draw') {

					document.getElementById('sfx-game-result').innerHTML = '<div style="color: #6c757d;">It\'s a draw! Try again?</div>';

					sfxUpdateStatus('');

				} else {

					if (result.pattern) {

						result.pattern.forEach(i => {

							document.querySelectorAll('.sfx-cell')[i].classList.add('winning');

						});

					}

					if (result.winner === 'X') {

						document.getElementById('sfx-game-result').innerHTML = '<div style="color: #246cf2;">✓ You won! Now complete your setup to protect your store!</div>';

					} else {

						document.getElementById('sfx-game-result').innerHTML = '<div style="color: #28a745;">SFX wins! Complete setup to beat fraud like you beat this game!</div>';

					}

					sfxUpdateStatus('');

				}

				return;

			}



			sfxCurrentPlayer = sfxCurrentPlayer === 'X' ? 'O' : 'X';

			sfxUpdateStatus(sfxCurrentPlayer === 'X' ? 'Your turn (X)' : 'SFX\'s turn (O)');



			if (sfxCurrentPlayer === 'O') {

				setTimeout(sfxAiMove, 500);

			}

		}



		function sfxAiMove() {

			if (!sfxGameActive) return;



			// Simple AI: Try to win, block player, or pick random

			let move = sfxFindWinningMove('O') || sfxFindWinningMove('X') || sfxGetRandomMove();



			if (move !== null) {

				sfxBoard[move] = 'O';

				const cell = document.querySelectorAll('.sfx-cell')[move];

				cell.textContent = 'O';

				cell.classList.add('taken', 'o');



				const result = sfxCheckWinner();

				if (result) {

					sfxGameActive = false;

					if (result.pattern) {

						result.pattern.forEach(i => {

							document.querySelectorAll('.sfx-cell')[i].classList.add('winning');

						});

					}

					document.getElementById('sfx-game-result').innerHTML = '<div style="color: #28a745;">SFX wins! Complete setup to beat fraud like you beat this game!</div>';

					sfxUpdateStatus('');

				} else {

					sfxCurrentPlayer = 'X';

					sfxUpdateStatus('Your turn (X)');

				}

			}

		}



		function sfxFindWinningMove(player) {

			for (let pattern of sfxWinPatterns) {

				const [a, b, c] = pattern;

				const line = [sfxBoard[a], sfxBoard[b], sfxBoard[c]];

				if (line.filter(cell => cell === player).length === 2 && line.includes('')) {

					return pattern[line.indexOf('')];

				}

			}

			return null;

		}



		function sfxGetRandomMove() {

			const available = sfxBoard.map((cell, i) => cell === '' ? i : null).filter(i => i !== null);

			return available.length > 0 ? available[Math.floor(Math.random() * available.length)] : null;

		}



		function sfxResetGame() {

			sfxBoard = ['', '', '', '', '', '', '', '', ''];

			sfxCurrentPlayer = 'X';

			sfxGameActive = true;

			document.querySelectorAll('.sfx-cell').forEach(cell => {

				cell.textContent = '';

				cell.classList.remove('taken', 'x', 'o', 'winning');

			});

			document.getElementById('sfx-game-result').innerHTML = '';

			sfxUpdateStatus('Your turn (X)');

		}



		// Initialize game

		document.addEventListener('DOMContentLoaded', function() {

			document.querySelectorAll('.sfx-cell').forEach(cell => {

				cell.addEventListener('click', sfxHandleClick);

			});

			sfxUpdateStatus('Your turn (X)');

		});

		</script>

		<?php

	}



	/**

	 * Render status banner

	 */

	private static function render_status_banner( $stats ) {

		$is_active = $stats['is_active'];

		$mode = $stats['mode'];

		?>

		<div class="sfx-status-banner <?php echo $is_active ? '' : 'inactive'; ?>">

			<div class="sfx-status-text">

				<?php if ( $is_active ) : ?>

					Fraud Protection Active

				<?php else : ?>

					Fraud Protection Inactive

				<?php endif; ?>

			</div>

			<div class="sfx-status-badge">

				<?php echo esc_html( $mode ); ?>

			</div>

		</div>

		<?php

	}



	/**

	 * Render stats grid

	 */

	private static function render_stats_grid( $stats ) {

		?>

		<div class="sfx-stat-grid">

			<div class="sfx-stat-card">

				<div class="sfx-stat-label">Threats Blocked Today</div>

				<div class="sfx-stat-value success"><?php echo number_format( $stats['blocked_today'] ); ?></div>

				<div class="sfx-stat-change">↑ <?php echo esc_html( $stats['blocked_change'] ); ?>% vs yesterday</div>

			</div>

			<div class="sfx-stat-card">

				<div class="sfx-stat-label">Total This Week</div>

				<div class="sfx-stat-value"><?php echo number_format( $stats['blocked_week'] ); ?></div>

				<div class="sfx-stat-change">↑ <?php echo esc_html( $stats['week_change'] ); ?>% vs last week</div>

			</div>

			<div class="sfx-stat-card">

				<div class="sfx-stat-label">High Risk Events</div>

				<div class="sfx-stat-value danger"><?php echo number_format( $stats['high_risk'] ); ?></div>

				<div class="sfx-stat-change">Last 24 hours</div>

			</div>

			<div class="sfx-stat-card">

				<div class="sfx-stat-label">Challenges Issued</div>

				<div class="sfx-stat-value warning"><?php echo number_format( $stats['challenges'] ); ?></div>

				<div class="sfx-stat-change">Pending verification</div>

			</div>

		</div>

		<?php

	}



	/**

	 * Render attack types

	 */

	private static function render_attack_types( $stats ) {

		?>

		<div class="sfx-attack-types">

			<div style="font-size: 13px; font-weight: 600; color: #1d2327; margin-bottom: 12px; text-transform: uppercase; letter-spacing: 0.5px;">

				Top Attack Types (24h)

			</div>

			<?php foreach ( $stats['attack_types'] as $attack ) : ?>

				<div class="sfx-attack-item">

					<div class="sfx-attack-name"><?php echo esc_html( $attack['name'] ); ?></div>

					<div class="sfx-attack-count"><?php echo number_format( $attack['count'] ); ?></div>

				</div>

			<?php endforeach; ?>

		</div>

		<?php

	}



	/**

	 * Render footer

	 */

	private static function render_footer() {

		?>

		<div class="sfx-footer">

			<a href="<?php echo esc_url( admin_url( 'admin.php?page=sensfrx_fpwoo' ) ); ?>" class="sfx-footer-link">

				View Detailed Reports →

			</a>

			<a href="https://discord.gg/zGBGQdwT4r" target="_blank" rel="noopener" class="sfx-footer-link">

				Get Support

			</a>

		</div>

		<?php

	}



	/**

	 * Get dashboard statistics

	 */

	private static function get_dashboard_stats() {

		global $wpdb;



		// Get today's blocked events

		$today_start = strtotime( 'today midnight' );

		$yesterday_start = strtotime( 'yesterday midnight' );

		$week_start = strtotime( '-7 days' );

		$last_week_start = strtotime( '-14 days' );



		// Count blocked events today

		$blocked_today = (int) $wpdb->get_var(

			$wpdb->prepare(

				"SELECT COUNT(*) FROM {$wpdb->prefix}sensfrx_real_activity

				WHERE action IN ('deny', 'block')

				AND UNIX_TIMESTAMP(time) >= %d",

				$today_start

			)

		);



		// Count blocked events yesterday

		$blocked_yesterday = (int) $wpdb->get_var(

			$wpdb->prepare(

				"SELECT COUNT(*) FROM {$wpdb->prefix}sensfrx_real_activity

				WHERE action IN ('deny', 'block')

				AND UNIX_TIMESTAMP(time) >= %d

				AND UNIX_TIMESTAMP(time) < %d",

				$yesterday_start,

				$today_start

			)

		);



		// Count blocked events this week

		$blocked_week = (int) $wpdb->get_var(

			$wpdb->prepare(

				"SELECT COUNT(*) FROM {$wpdb->prefix}sensfrx_real_activity

				WHERE action IN ('deny', 'block')

				AND UNIX_TIMESTAMP(time) >= %d",

				$week_start

			)

		);



		// Count blocked events last week

		$blocked_last_week = (int) $wpdb->get_var(

			$wpdb->prepare(

				"SELECT COUNT(*) FROM {$wpdb->prefix}sensfrx_real_activity

				WHERE action IN ('deny', 'block')

				AND UNIX_TIMESTAMP(time) >= %d

				AND UNIX_TIMESTAMP(time) < %d",

				$last_week_start,

				$week_start

			)

		);



		// Count high risk events (last 24h)

		$high_risk = (int) $wpdb->get_var(

			$wpdb->prepare(

				"SELECT COUNT(*) FROM {$wpdb->prefix}sensfrx_real_activity

				WHERE severity = 'high'

				AND UNIX_TIMESTAMP(time) >= %d",

				strtotime( '-24 hours' )

			)

		);



		// Count challenges (last 24h)

		$challenges = (int) $wpdb->get_var(

			$wpdb->prepare(

				"SELECT COUNT(*) FROM {$wpdb->prefix}sensfrx_real_activity

				WHERE action = 'challenge'

				AND UNIX_TIMESTAMP(time) >= %d",

				strtotime( '-24 hours' )

			)

		);



		// Get top attack types (last 24h)

		$attack_types = $wpdb->get_results(

			$wpdb->prepare(

				"SELECT event_type, COUNT(*) as count

				FROM {$wpdb->prefix}sensfrx_real_activity

				WHERE action IN ('deny', 'block', 'challenge')

				AND UNIX_TIMESTAMP(time) >= %d

				GROUP BY event_type

				ORDER BY count DESC

				LIMIT 5",

				strtotime( '-24 hours' )

			),

			ARRAY_A

		);



		// Format attack types

		$formatted_attacks = array();

		foreach ( $attack_types as $attack ) {

			$formatted_attacks[] = array(

				'name' => self::format_event_type( $attack['event_type'] ),

				'count' => (int) $attack['count'],

			);

		}



		// If no data, show placeholder

		if ( empty( $formatted_attacks ) ) {

			$formatted_attacks = array(

				array( 'name' => 'Suspicious Login Attempts', 'count' => 0 ),

				array( 'name' => 'Fraudulent Transactions', 'count' => 0 ),

				array( 'name' => 'Bot Registrations', 'count' => 0 ),

			);

		}



		// Calculate percentage changes

		$blocked_change = $blocked_yesterday > 0 ? round( ( ( $blocked_today - $blocked_yesterday ) / $blocked_yesterday ) * 100 ) : 0;

		$week_change = $blocked_last_week > 0 ? round( ( ( $blocked_week - $blocked_last_week ) / $blocked_last_week ) * 100 ) : 0;



		// Check if protection is active

		$options = get_option( 'sensfrx_options', SensFRX::default_options() );

		$is_active = ! empty( $options['sensfrx_property_id'] ) && ! empty( $options['sensfrx_property_secret'] );



		// Determine mode

		$mode = 'Live';

		if ( isset( $options['sensfrx_shadow_mode'] ) && 'on' === $options['sensfrx_shadow_mode'] ) {

			$mode = 'Shadow';

		}



		return array(

			'is_active' => $is_active,

			'mode' => $mode,

			'blocked_today' => $blocked_today,

			'blocked_change' => $blocked_change,

			'blocked_week' => $blocked_week,

			'week_change' => $week_change,

			'high_risk' => $high_risk,

			'challenges' => $challenges,

			'attack_types' => $formatted_attacks,

		);

	}



	/**

	 * Format event type for display

	 */

	private static function format_event_type( $event_type ) {

		$types = array(

			'login' => 'Suspicious Login Attempts',

			'registration' => 'Bot Registrations',

			'transaction' => 'Fraudulent Transactions',

			'payment' => 'Payment Fraud Attempts',

			'account_takeover' => 'Account Takeover Attempts',

			'password_reset' => 'Password Reset Abuse',

			'profile_update' => 'Suspicious Profile Changes',

		);



		return isset( $types[ $event_type ] ) ? $types[ $event_type ] : ucwords( str_replace( '_', ' ', $event_type ) );

	}



	/**

	 * Render actionable insights

	 */

	private static function render_insights( $insights ) {

		?>

		<div class="sfx-insights">

			<div class="sfx-insights-title">

				ACTIONABLE INSIGHTS

			</div>

			<?php foreach ( $insights as $insight ) : ?>

				<div class="sfx-insight-item">

					<div class="sfx-insight-icon"><?php echo esc_html( $insight['icon'] ); ?></div>

					<div class="sfx-insight-content">

						<div class="sfx-insight-text"><?php echo esc_html( $insight['text'] ); ?></div>

						<?php if ( ! empty( $insight['action_url'] ) ) : ?>

							<a href="<?php echo esc_url( $insight['action_url'] ); ?>" class="sfx-insight-action">

								<?php echo esc_html( $insight['action_text'] ); ?> →

							</a>

						<?php endif; ?>

					</div>

				</div>

			<?php endforeach; ?>

		</div>

		<?php

	}



	/**

	 * Get actionable insights based on data patterns

	 */

	private static function get_actionable_insights( $stats ) {

		$insights = array();



		// Insight 1: Spike in fraud attempts

		if ( $stats['blocked_change'] > 50 ) {

			$insights[] = array(

				'icon' => '▲',

				'text' => sprintf( 'Fraud attempts increased by %d%% today. Consider enabling stricter verification rules.', $stats['blocked_change'] ),

				'action_text' => 'Adjust Security Rules',

				'action_url' => admin_url( 'admin.php?page=sensfrx_fpwoo' ),

			);

		}



		// Insight 2: High risk events require attention

		if ( $stats['high_risk'] > 5 ) {

			$insights[] = array(

				'icon' => '●',

				'text' => sprintf( '%d high-risk events detected in 24h. Review and block suspicious IPs to prevent future attacks.', $stats['high_risk'] ),

				'action_text' => 'Review High-Risk Events',

				'action_url' => admin_url( 'admin.php?page=sensfrx_fpwoo' ),

			);

		}



		// Insight 3: Shadow mode suggestion for new users

		if ( $stats['mode'] === 'Live' && $stats['blocked_today'] < 3 ) {

			$insights[] = array(

				'icon' => '✓',

				'text' => 'Your store is well protected! Consider reviewing blocked events to ensure no false positives.',

				'action_text' => 'View Activity Log',

				'action_url' => admin_url( 'admin.php?page=sensfrx_fpwoo' ),

			);

		}



		// Insight 4: Pending challenges need review

		if ( $stats['challenges'] > 10 ) {

			$insights[] = array(

				'icon' => '◷',

				'text' => sprintf( '%d users are waiting for verification challenges. Timely reviews improve customer experience.', $stats['challenges'] ),

				'action_text' => 'Review Challenges',

				'action_url' => admin_url( 'admin.php?page=sensfrx_fpwoo' ),

			);

		}



		// Insight 5: Pattern detected in attack types

		if ( ! empty( $stats['attack_types'][0] ) && $stats['attack_types'][0]['count'] > 10 ) {

			$attack_name = $stats['attack_types'][0]['name'];

			$attack_count = $stats['attack_types'][0]['count'];

			$insights[] = array(

				'icon' => '◆',

				'text' => sprintf( '%s is your top threat (%d attempts). Create a custom rule to auto-block similar patterns.', $attack_name, $attack_count ),

				'action_text' => 'Create Auto-Block Rule',

				'action_url' => admin_url( 'admin.php?page=sensfrx_fpwoo' ),

			);

		}



		// Limit to top 2 most important insights

		return array_slice( $insights, 0, 2 );

	}

}



// Initialize dashboard widget

SensFRX_Dashboard_Widget::register();

