<?php
/**
 * The Widget Auditor admin page (under the Elementor menu).
 */

defined( 'ABSPATH' ) || exit;

class TFWA_Admin_Page {

	const SCREEN_SLUG = 'tfwa-widget-auditor';

	public static function init(): void {
		add_action( 'admin_menu', array( __CLASS__, 'register_menu' ), 200 );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
	}

	public static function register_menu(): void {
		$parent = menu_page_url( 'elementor', false ) ? 'elementor' : 'tools.php';

		add_submenu_page(
			$parent,
			__( 'Widget Auditor', 'tendforge-widget-auditor-for-elementor' ),
			__( 'Widget Auditor', 'tendforge-widget-auditor-for-elementor' ),
			'manage_options',
			self::SCREEN_SLUG,
			array( __CLASS__, 'render_page' )
		);
	}

	public static function enqueue_assets( string $hook ): void {
		if ( false === strpos( $hook, self::SCREEN_SLUG ) ) {
			return;
		}

		wp_enqueue_style( 'tfwa-admin', TFWA_PLUGIN_URL . 'assets/css/admin.css', array(), TFWA_VERSION );
		wp_enqueue_script( 'tfwa-admin', TFWA_PLUGIN_URL . 'assets/js/admin.js', array(), TFWA_VERSION, true );

		/**
		 * Fires after the auditor assets are enqueued, so extensions can add theirs.
		 */
		do_action( 'tfwa_enqueue_assets' );

		wp_localize_script(
			'tfwa-admin',
			'tfwaAdmin',
			/**
			 * Filters the data exposed to the auditor script.
			 *
			 * @param array $data Localized settings and strings.
			 */
			apply_filters( 'tfwa_admin_localize', array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'tfwa_admin' ),
				'i18n'    => array(
					'scanning'  => __( 'Scanning…', 'tendforge-widget-auditor-for-elementor' ),
					'scanError' => __( 'The scan failed. Please try again.', 'tendforge-widget-auditor-for-elementor' ),
				),
			) )
		);
	}

	public static function render_page(): void {
		$report   = TFWA_Scanner::get_report();
		$has_scan = $report['totals']['posts_scanned'] > 0;
		?>
		<div class="wrap tfwa-wrap">
			<h1><?php esc_html_e( 'Widget Auditor', 'tendforge-widget-auditor-for-elementor' ); ?></h1>

			<div class="tfwa-card tfwa-scan-card">
				<div class="tfwa-scan-row">
					<div>
						<?php if ( $has_scan && $report['totals']['completed'] ) : ?>
							<p>
								<?php
								printf(
									/* translators: 1: number of documents scanned, 2: human time diff */
									esc_html__( 'Last scan: %1$d Elementor documents, %2$s ago.', 'tendforge-widget-auditor-for-elementor' ),
									(int) $report['totals']['posts_scanned'],
									esc_html( human_time_diff( $report['totals']['completed'] ) )
								);
								?>
							</p>
						<?php else : ?>
							<p><?php esc_html_e( 'Scan your site to find out which widgets are actually used on your pages, templates and popups.', 'tendforge-widget-auditor-for-elementor' ); ?></p>
						<?php endif; ?>
					</div>
					<button type="button" class="button button-primary button-hero" id="tfwa-scan-start">
						<?php $has_scan ? esc_html_e( 'Re-scan site', 'tendforge-widget-auditor-for-elementor' ) : esc_html_e( 'Scan site', 'tendforge-widget-auditor-for-elementor' ); ?>
					</button>
				</div>
				<div id="tfwa-scan-progress" hidden>
					<div class="tfwa-progress"><div class="tfwa-progress-bar" style="width:0%"></div></div>
					<p id="tfwa-scan-status"></p>
				</div>
			</div>

			<?php if ( $has_scan ) : ?>
				<?php self::render_report( $report ); ?>
			<?php endif; ?>
		</div>
		<?php
	}

	private static function render_report( array $report ): void {
		$totals = $report['totals'];

		$zero_usage_addons = array_filter(
			$report['providers'],
			fn( $p ) => 0 === $p['used'] && ! in_array( $p['slug'], array( 'elementor', 'elementor-pro', 'theme', 'other', 'unknown', 'mu-plugin' ), true )
		);
		?>
		<div class="tfwa-kpis">
			<div class="tfwa-card tfwa-kpi">
				<span class="tfwa-kpi-value"><?php echo (int) $totals['registered']; ?></span>
				<span class="tfwa-kpi-label"><?php esc_html_e( 'Registered widgets', 'tendforge-widget-auditor-for-elementor' ); ?></span>
			</div>
			<div class="tfwa-card tfwa-kpi">
				<span class="tfwa-kpi-value tfwa-good"><?php echo (int) $totals['used']; ?></span>
				<span class="tfwa-kpi-label"><?php esc_html_e( 'Used on your site', 'tendforge-widget-auditor-for-elementor' ); ?></span>
			</div>
			<div class="tfwa-card tfwa-kpi">
				<span class="tfwa-kpi-value tfwa-warn"><?php echo (int) $totals['unused']; ?></span>
				<span class="tfwa-kpi-label"><?php esc_html_e( 'Never used', 'tendforge-widget-auditor-for-elementor' ); ?></span>
			</div>
			<div class="tfwa-card tfwa-kpi">
				<span class="tfwa-kpi-value <?php echo $zero_usage_addons ? 'tfwa-bad' : 'tfwa-good'; ?>"><?php echo count( $zero_usage_addons ); ?></span>
				<span class="tfwa-kpi-label"><?php esc_html_e( 'Addons with zero usage', 'tendforge-widget-auditor-for-elementor' ); ?></span>
			</div>
		</div>

		<?php if ( ! empty( $report['documents'] ) ) : ?>
			<div class="tfwa-card tfwa-doc-coverage">
				<h2><?php esc_html_e( 'Documents scanned by type', 'tendforge-widget-auditor-for-elementor' ); ?></h2>
				<p class="description"><?php esc_html_e( 'Every Elementor document is checked — including popups, headers, footers and theme-builder templates that Elementor\'s own Element Manager overlooks. So an "unused" widget really is safe to disable.', 'tendforge-widget-auditor-for-elementor' ); ?></p>
				<ul class="tfwa-doc-list">
					<?php foreach ( $report['documents'] as $doc ) : ?>
						<li><strong><?php echo (int) $doc['count']; ?></strong> <?php echo esc_html( $doc['label'] ); ?></li>
					<?php endforeach; ?>
				</ul>
			</div>
		<?php endif; ?>

		<?php
		/**
		 * Fires after the KPI cards, before the alert sections.
		 *
		 * @param array $report The full audit report.
		 */
		do_action( 'tfwa_report_after_kpis', $report );
		?>

		<?php if ( $zero_usage_addons ) : ?>
			<div class="tfwa-card tfwa-alert tfwa-alert-action">
				<h2><?php esc_html_e( 'Quick win: addons you can likely deactivate', 'tendforge-widget-auditor-for-elementor' ); ?></h2>
				<p>
					<?php esc_html_e( 'None of these addons\' widgets appear anywhere on your site, yet each one ships code that can load on every page view:', 'tendforge-widget-auditor-for-elementor' ); ?>
				</p>
				<ul>
					<?php $tfwa_dead_bytes = 0; $tfwa_loaded = $report['loaded_assets'] ?? array(); ?>
					<?php foreach ( $zero_usage_addons as $addon ) : ?>
						<?php
						$tfwa_fp          = $tfwa_loaded[ (string) $addon['slug'] ] ?? array( 'files' => 0, 'bytes' => 0 );
						$tfwa_dead_bytes += (int) $tfwa_fp['bytes'];
						?>
						<li>
							<strong><?php echo esc_html( $addon['label'] ); ?></strong>
							— <?php echo (int) count( $addon['widgets'] ); ?> <?php esc_html_e( 'widgets, 0 used', 'tendforge-widget-auditor-for-elementor' ); ?>
							<?php if ( $tfwa_fp['bytes'] > 0 ) : ?>
								· <span class="tfwa-footprint"><?php
									printf(
										/* translators: %s: human-readable file size, e.g. "240 KB" */
										esc_html__( 'loads ~%s on your home page', 'tendforge-widget-auditor-for-elementor' ),
										esc_html( TFWA_Footprint::format_bytes( (int) $tfwa_fp['bytes'] ) )
									);
								?></span>
							<?php endif; ?>
						</li>
					<?php endforeach; ?>
				</ul>
				<?php if ( $tfwa_dead_bytes > 0 ) : ?>
					<p class="tfwa-footprint-total">
						<?php
						printf(
							/* translators: %s: human-readable total size, e.g. "1.2 MB" */
							esc_html__( 'Together these unused addons load about %s on your home page — yet you use none of their widgets.', 'tendforge-widget-auditor-for-elementor' ),
							'<strong>' . esc_html( TFWA_Footprint::format_bytes( $tfwa_dead_bytes ) ) . '</strong>'
						);
						?>
						<span class="description"><?php esc_html_e( 'Measured on your home page. A caching or optimization plugin may combine or defer these files, which can change the exact figure.', 'tendforge-widget-auditor-for-elementor' ); ?></span>
					</p>
				<?php endif; ?>
				<p>
					<a href="<?php echo esc_url( admin_url( 'plugins.php' ) ); ?>" class="button"><?php esc_html_e( 'Manage plugins', 'tendforge-widget-auditor-for-elementor' ); ?></a>
					<span class="description"><?php esc_html_e( 'Tip: deactivate one at a time and check your key pages.', 'tendforge-widget-auditor-for-elementor' ); ?></span>
				</p>
			</div>
		<?php endif; ?>

		<?php if ( $report['orphans'] ) : ?>
			<div class="tfwa-card tfwa-alert tfwa-alert-danger">
				<h2><?php esc_html_e( 'Broken widgets found', 'tendforge-widget-auditor-for-elementor' ); ?></h2>
				<p><?php esc_html_e( 'These widgets are used in your content but are no longer registered — usually because their addon was deactivated or removed. They render as empty or broken areas for visitors:', 'tendforge-widget-auditor-for-elementor' ); ?></p>
				<ul>
					<?php foreach ( $report['orphans'] as $orphan ) : ?>
						<li>
							<code><?php echo esc_html( $orphan['name'] ); ?></code>
							× <?php echo (int) $orphan['count']; ?> —
							<?php self::page_links( $orphan['pages'] ); ?>
						</li>
					<?php endforeach; ?>
				</ul>
			</div>
		<?php endif; ?>

		<?php foreach ( $report['providers'] as $provider ) : ?>
			<div class="tfwa-card">
				<details <?php echo $provider['unused'] > 0 && 0 === $provider['used'] ? 'open' : ''; ?>>
					<summary>
						<strong><?php echo esc_html( $provider['label'] ); ?></strong>
						<span class="tfwa-provider-stats">
							<?php
							printf(
								/* translators: 1: used widget count, 2: total widget count */
								esc_html__( '%1$d of %2$d widgets used', 'tendforge-widget-auditor-for-elementor' ),
								(int) $provider['used'],
								(int) ( $provider['used'] + $provider['unused'] )
							);
							?>
						</span>
						<?php if ( $provider['unused'] > 0 ) : ?>
							<span class="tfwa-badge"><?php echo (int) $provider['unused']; ?> <?php esc_html_e( 'unused', 'tendforge-widget-auditor-for-elementor' ); ?></span>
						<?php endif; ?>
					</summary>
					<table class="widefat striped">
						<thead>
							<tr>
								<th><?php esc_html_e( 'Widget', 'tendforge-widget-auditor-for-elementor' ); ?></th>
								<th class="tfwa-num"><?php esc_html_e( 'Uses', 'tendforge-widget-auditor-for-elementor' ); ?></th>
								<th><?php esc_html_e( 'Where', 'tendforge-widget-auditor-for-elementor' ); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ( $provider['widgets'] as $widget ) : ?>
								<tr class="<?php echo 0 === $widget['count'] ? 'tfwa-row-unused' : ''; ?>">
									<td><?php echo esc_html( $widget['title'] ); ?> <code><?php echo esc_html( $widget['name'] ); ?></code></td>
									<td class="tfwa-num"><?php echo (int) $widget['count']; ?></td>
									<td><?php self::page_links( $widget['pages'] ); ?></td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				</details>
			</div>
		<?php endforeach; ?>

		<?php
		/**
		 * Fires after the provider tables, before the guidance card.
		 *
		 * @param array $report The full audit report.
		 */
		do_action( 'tfwa_report_end', $report );
		?>

		<div class="tfwa-card">
			<h2><?php esc_html_e( 'How to act on this', 'tendforge-widget-auditor-for-elementor' ); ?></h2>
			<ol>
				<li><?php esc_html_e( 'Addons with zero usage: deactivate the whole plugin (biggest win).', 'tendforge-widget-auditor-for-elementor' ); ?></li>
				<li>
					<?php
					printf(
						/* translators: %s: link to Elementor's Element Manager */
						wp_kses_post( __( 'Individual unused widgets: switch them off in <a href="%s">Elementor\'s Element Manager</a> so their assets stop loading.', 'tendforge-widget-auditor-for-elementor' ) ),
						esc_url( admin_url( 'admin.php?page=elementor-element-manager' ) )
					);
					?>
				</li>
				<li><?php esc_html_e( 'Broken widgets: edit the listed pages and remove or replace them.', 'tendforge-widget-auditor-for-elementor' ); ?></li>
			</ol>
		</div>
		<?php
	}

	private static function page_links( array $pages ): void {
		$links = array();
		foreach ( $pages as $page ) {
			$title = $page['title'] ? $page['title'] : '#' . $page['id'];
			if ( $page['link'] ) {
				$links[] = '<a href="' . esc_url( $page['link'] ) . '">' . esc_html( $title ) . '</a>';
			} else {
				$links[] = esc_html( $title );
			}
		}

		echo wp_kses_post( implode( ', ', $links ) );
	}
}
