<?php
/**
 * WP PowerSuite Performance Dashboard View
 *
 * Displays module performance metrics including execution times,
 * memory usage, and hook counts.
 *
 * @package WP_PowerSuite\Admin\Views
 * @since 1.0.0
 *
 * @var string $page_title Page title (set by AdminMenu).
 */

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

use WP_PowerSuite\Admin\PageHero;
use WP_PowerSuite\Core\PerformanceMonitor;
use WP_PowerSuite\Core\ModuleRegistry;
use WP_PowerSuite\Core\OptionStore;

$performance_monitor = PerformanceMonitor::getInstance();
$module_registry = ModuleRegistry::getInstance();
$option_store = OptionStore::getInstance();

$module_registry->init();

$all_modules = $module_registry->getAllModules();

$all_metrics = $performance_monitor->getAllMetrics();
$enabled_modules = $option_store->getEnabledModules();

$modules_data = [];
foreach ( $all_modules as $module_id => $module_meta ) {
	$metrics = $all_metrics[ $module_id ] ?? [];
	
	$modules_data[ $module_id ] = [
		'id'            => $module_id,
		'name'          => $module_meta['name'] ?? $module_id,
		'category'      => $module_meta['category'] ?? 'Uncategorized',
		'enabled'       => in_array( $module_id, $enabled_modules, true ),
		'hook_count'    => $metrics['hook_count'] ?? 0,
		'execution_time' => $metrics['execution_time'] ?? null,
		'memory_usage'  => $metrics['memory_usage'] ?? null,
	];
}

$sort_by    = isset( $_GET['sort'] ) ? sanitize_key( wp_unslash( $_GET['sort'] ) ) : 'time';
$sort_order = isset( $_GET['order'] ) ? sanitize_key( wp_unslash( $_GET['order'] ) ) : 'desc';

$valid_sorts = [ 'time', 'hooks', 'name', 'category' ];
if ( ! in_array( $sort_by, $valid_sorts, true ) ) {
	$sort_by = 'time';
}

$valid_orders = [ 'asc', 'desc' ];
if ( ! in_array( $sort_order, $valid_orders, true ) ) {
	$sort_order = 'desc';
}

usort( $modules_data, function( $a, $b ) use ( $sort_by, $sort_order ) {
	$result = 0;
	
	switch ( $sort_by ) {
		case 'time':
			$time_a = $a['execution_time'] ?? 0;
			$time_b = $b['execution_time'] ?? 0;
			$result = $time_b <=> $time_a; // Default descending
			break;
			
		case 'hooks':
			$hooks_a = $a['hook_count'] ?? 0;
			$hooks_b = $b['hook_count'] ?? 0;
			$result = $hooks_b <=> $hooks_a; // Default descending
			break;
			
		case 'name':
			$name_a = strtolower( $a['name'] ?? '' );
			$name_b = strtolower( $b['name'] ?? '' );
			$result = $name_a <=> $name_b; // Default ascending
			break;
			
		case 'category':
			$cat_a = strtolower( $a['category'] ?? '' );
			$cat_b = strtolower( $b['category'] ?? '' );
			$result = $cat_a <=> $cat_b; // Default ascending
			break;
	}
	
	// Reverse if ascending order
	if ( $sort_order === 'asc' ) {
		$result = -$result;
	}
	
	return $result;
} );

$hook_budget  = $performance_monitor->getMaxHooksPerModule();
$crit_hooks   = $hook_budget + 10;
$loaded_count = count(
	array_filter(
		$modules_data,
		static function ( array $m ): bool {
			return ( $m['hook_count'] ?? 0 ) > 0 || ( $m['execution_time'] ?? null ) !== null;
		}
	)
);

$sort_url = function( $column, $current_sort, $current_order ) {
	$url = admin_url( 'admin.php?page=powersuite-performance' );
	$new_order = ( $current_sort === $column && $current_order === 'desc' ) ? 'asc' : 'desc';
	$url = add_query_arg( 'sort', $column, $url );
	$url = add_query_arg( 'order', ( $current_sort === $column ? $new_order : 'desc' ), $url );
	return $url;
};

$enabled_module_count = count( array_filter( $modules_data, static fn( $m ) => ! empty( $m['enabled'] ) ) );
$perf_stats           = [
	[
		'value' => number_format_i18n( count( $modules_data ) ),
		'label' => __( 'Modules', 'wp-powersuite' ),
	],
	[
		'value' => number_format_i18n( $enabled_module_count ),
		'label' => __( 'Enabled', 'wp-powersuite' ),
	],
];
$total_time   = array_sum( array_column( $modules_data, 'execution_time' ) );
$perf_stats[] = [
	'value' => number_format( (float) $total_time, 2 ) . ' ms',
	'label' => __( 'Init time', 'wp-powersuite' ),
];
$perf_stats[] = [
	'value' => number_format_i18n( $loaded_count ),
	'label' => __( 'Loaded', 'wp-powersuite' ),
];
$sort_column_class = static function ( string $column ) use ( $sort_by, $sort_order ): string {
	if ( $sort_by !== $column ) {
		return '';
	}

	return 'sorted ' . esc_attr( $sort_order );
};
?>
<div class="wrap wpps-performance-wrap">
	<hr class="wp-header-end" style="margin:0; padding:0; border:none; height:0; overflow:hidden;">
	<?php
	PageHero::render(
		[
			'eyebrow' => '',
			'title'   => $page_title,
			'icon'    => 'dashicons-performance',
			'actions' => PageHero::nav_actions(),
			'stats'   => $perf_stats,
		]
	);
	?>

	<div class="wpps-performance-dashboard">
		<table class="wp-list-table widefat fixed striped wpps-performance-table">
			<thead>
				<tr>
					<th scope="col" class="column-module sortable <?php echo esc_attr( $sort_column_class( 'name' ) ); ?>">
						<a href="<?php echo esc_url( $sort_url( 'name', $sort_by, $sort_order ) ); ?>">
							<span><?php esc_html_e( 'Module', 'wp-powersuite' ); ?></span>
							<span class="sorting-indicator"></span>
						</a>
					</th>
					<th scope="col" class="column-status"><?php esc_html_e( 'Status', 'wp-powersuite' ); ?></th>
					<th scope="col" class="column-category sortable <?php echo esc_attr( $sort_column_class( 'category' ) ); ?>">
						<a href="<?php echo esc_url( $sort_url( 'category', $sort_by, $sort_order ) ); ?>">
							<span><?php esc_html_e( 'Category', 'wp-powersuite' ); ?></span>
							<span class="sorting-indicator"></span>
						</a>
					</th>
					<th scope="col" class="column-hooks sortable <?php echo esc_attr( $sort_column_class( 'hooks' ) ); ?>">
						<a href="<?php echo esc_url( $sort_url( 'hooks', $sort_by, $sort_order ) ); ?>">
							<span><?php esc_html_e( 'Hooks', 'wp-powersuite' ); ?></span>
							<span class="sorting-indicator"></span>
						</a>
					</th>
					<th scope="col" class="column-time sortable <?php echo esc_attr( $sort_column_class( 'time' ) ); ?>">
						<a href="<?php echo esc_url( $sort_url( 'time', $sort_by, $sort_order ) ); ?>">
							<span><?php esc_html_e( 'Init Time (ms)', 'wp-powersuite' ); ?></span>
							<span class="sorting-indicator"></span>
						</a>
					</th>
					<th scope="col" class="column-memory"><?php esc_html_e( 'Memory', 'wp-powersuite' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php if ( empty( $modules_data ) ) : ?>
					<tr>
						<td colspan="6" class="no-items">
							<?php esc_html_e( 'No module metrics available.', 'wp-powersuite' ); ?>
						</td>
					</tr>
				<?php else : ?>
					<?php foreach ( $modules_data as $module ) : ?>
						<?php
						$execution_time = $module['execution_time'] ?? null;
						$memory_usage = $module['memory_usage'] ?? null;
						$hook_count = (int) ( $module['hook_count'] ?? 0 );
						$warn_hooks = (int) round( $hook_budget * 0.85 );
						$crit_hooks = $hook_budget + 10;
						$performance_class = '';
						if ( $execution_time && $execution_time > 50 ) {
							$performance_class = 'wpps-performance-warning';
						}
						if ( $execution_time && $execution_time > 100 ) {
							$performance_class = 'wpps-performance-critical';
						}
						if ( $hook_count > $warn_hooks ) {
							$performance_class = 'wpps-performance-warning';
						}
						if ( $hook_count > $crit_hooks ) {
							$performance_class = 'wpps-performance-critical';
						}

						$hook_pct = $hook_budget > 0 ? min( 100, ( $hook_count / $hook_budget ) * 100 ) : 0;
						?>
						<tr class="<?php echo esc_attr( $performance_class ); ?>">
							<td class="column-module">
								<strong><?php echo esc_html( $module['name'] ); ?></strong>
								<br>
								<code class="wpps-module-id"><?php echo esc_html( $module['id'] ); ?></code>
							</td>
							<td class="column-status">
								<?php if ( $module['enabled'] ) : ?>
									<span class="wpps-status-enabled"><?php esc_html_e( 'Enabled', 'wp-powersuite' ); ?></span>
								<?php else : ?>
									<span class="wpps-status-disabled"><?php esc_html_e( 'Disabled', 'wp-powersuite' ); ?></span>
								<?php endif; ?>
							</td>
							<td class="column-category"><?php echo esc_html( $module['category'] ); ?></td>
							<td class="column-hooks">
								<div class="wpps-hook-meter-wrap">
									<span class="wpps-hook-count"><?php echo esc_html( (string) $hook_count ); ?></span>
									<div class="wpps-hook-meter" role="presentation" aria-hidden="true">
										<span class="wpps-hook-meter__fill" style="width: <?php echo esc_attr( (string) $hook_pct ); ?>%;"></span>
									</div>
								</div>
								<?php if ( $hook_count > $hook_budget ) : ?>
									<span class="dashicons dashicons-warning wpps-warning-icon" title="<?php esc_attr_e( 'Exceeds hook budget', 'wp-powersuite' ); ?>"></span>
							<?php endif; ?>
						</td>
						<td class="column-time">
							<?php if ( $execution_time !== null ) : ?>
								<?php echo esc_html( number_format( $execution_time, 2 ) ); ?>
								<?php if ( $execution_time > 50 ) : ?>
									<span class="wpps-warning-icon" title="<?php esc_attr_e( 'Slow initialization', 'wp-powersuite' ); ?>">⚠️</span>
								<?php endif; ?>
							<?php else : ?>
								<span class="wpps-metric-na">—</span>
							<?php endif; ?>
						</td>
						<td class="column-memory">
							<?php if ( $memory_usage !== null ) : ?>
								<?php
								// Memory is already clamped to 0 in PerformanceMonitor
								$memory_usage = max( 0, $memory_usage );
								if ( $memory_usage >= 1024 ) : ?>
									<?php echo esc_html( size_format( $memory_usage ) ); ?>
									<?php if ( $memory_usage > 1048576 ) : // 1MB ?>
										<span class="dashicons dashicons-warning wpps-warning-icon" title="<?php esc_attr_e( 'High memory usage can impact performance.', 'wp-powersuite' ); ?>"></span>
									<?php endif; ?>
								<?php else : ?>
									<span title="<?php echo esc_attr( sprintf( __( 'Memory used: %s (memory may have been freed during initialization)', 'wp-powersuite' ), size_format( $memory_usage ) ) ); ?>">
										< 1 KB
									</span>
								<?php endif; ?>
							<?php else : ?>
								<span class="wpps-metric-na" title="<?php esc_attr_e( 'Module not initialized during this request.', 'wp-powersuite' ); ?>">—</span>
							<?php endif; ?>
						</td>
					</tr>
					<?php endforeach; ?>
				<?php endif; ?>
			</tbody>
		</table>

		<div class="wpps-performance-legend">
			<h3><?php esc_html_e( 'Performance Indicators', 'wp-powersuite' ); ?></h3>
			<ul>
				<li><span class="wpps-performance-warning"></span> <strong><?php esc_html_e( 'Warning', 'wp-powersuite' ); ?></strong>: <?php echo esc_html( sprintf( __( 'Hook count above ~85%% of budget (%d) or init time > 50ms', 'wp-powersuite' ), $hook_budget ) ); ?></li>
				<li><span class="wpps-performance-critical"></span> <strong><?php esc_html_e( 'Critical', 'wp-powersuite' ); ?></strong>: <?php echo esc_html( sprintf( __( 'Hook count > %d or init time > 100ms', 'wp-powersuite' ), $crit_hooks ) ); ?></li>
			</ul>
		</div>
	</div>
</div>
