<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class AVIN_Admin {
	private $repository;
	private $analytics;
	private $wc_metrics;

	public function __construct( AVIN_Views_Repository $repository, AVIN_Analytics_Repository $analytics, AVIN_WooCommerce_Metrics $wc_metrics ) {
		$this->repository = $repository;
		$this->analytics  = $analytics;
		$this->wc_metrics = $wc_metrics;
	}

	public function init() {
		add_action( 'admin_menu', array( $this, 'menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'assets' ) );
		add_action( 'admin_post_avin_save_settings', array( $this, 'save_settings' ) );
		add_action( 'admin_post_avin_export_csv', array( $this, 'export_csv' ) );
	}

	public function menu() {
		$cap = $this->capability();
		add_menu_page( __( 'Apex View Insights', 'apex-view-insights' ), __( 'Apex Views', 'apex-view-insights' ), $cap, 'avin', array( $this, 'dashboard_page' ), 'dashicons-chart-bar', 57 );
		add_submenu_page( 'avin', __( 'Dashboard', 'apex-view-insights' ), __( 'Dashboard', 'apex-view-insights' ), $cap, 'avin', array( $this, 'dashboard_page' ) );
		add_submenu_page( 'avin', __( 'Commerce Intelligence', 'apex-view-insights' ), __( 'Commerce', 'apex-view-insights' ), $cap, 'avin-woocommerce', array( $this, 'woocommerce_page' ) );
		add_submenu_page( 'avin', __( 'Settings', 'apex-view-insights' ), __( 'Settings', 'apex-view-insights' ), $cap, 'avin-settings', array( $this, 'settings_page' ) );
	}

	public function assets( $hook ) {
		if ( false === strpos( (string) $hook, 'avin' ) ) {
			return;
		}

		wp_enqueue_style( 'avin-admin', AVIN_PLUGIN_URL . 'assets/admin/admin.css', array(), AVIN_VERSION );
		wp_enqueue_script( 'avin-admin', AVIN_PLUGIN_URL . 'assets/admin/admin.js', array(), AVIN_VERSION, true );

		if ( 'toplevel_page_avin' === $hook ) {
			wp_localize_script(
				'avin-admin',
				'avinAdmin',
				array(
					'charts' => array(
						'viewsTrend' => array(
							'seven'  => $this->repository->daily_totals( 7 ),
							'thirty' => $this->repository->daily_totals( 30 ),
						),
					),
				)
			);
		}
	}

	public function dashboard_page() {
		$top_products_today = $this->repository->top_objects( array( 'product' ), 1, 8 );
		$top_products_7     = $this->repository->top_objects( array( 'product' ), 7, 8 );
		$top_products_30    = $this->repository->top_objects( array( 'product' ), 30, 8 );
		$top_posts          = $this->decorate_object_trends( $this->repository->top_objects( array( 'post' ), 30, 8 ) );
		$top_pages_30       = $this->decorate_object_trends( $this->repository->top_objects( array( 'page' ), 30, 8 ) );
		$top_content        = $this->repository->top_objects( array( 'post', 'page' ), 30, 10 );
		$top_pages          = $this->repository->top_objects( array( 'page' ), 30, 1 );
		$rising_products    = $this->repository->rising_objects( array( 'product' ), 8 );
		$online             = $this->analytics->online_summary();
		$traffic_today      = $this->analytics->traffic_for_date( current_time( 'Y-m-d' ) );
		$device_breakdown   = $this->analytics->device_breakdown();
		$today              = $this->repository->total_views_today();
		$yesterday          = $this->repository->total_views_on_date( gmdate( 'Y-m-d', strtotime( current_time( 'Y-m-d' ) . ' -1 day' ) ) );
		$views_7            = $this->repository->total_views_for_days( 7 );
		$views_30           = $this->repository->total_views_for_days( 30 );
		$views_all          = $this->repository->total_views_all_time();
		$growth             = $this->growth_percent( $today, $yesterday );
		$tracking_mode      = strtoupper( get_option( 'avin_tracking_mode', 'beacon' ) );
		$opportunities      = $this->opportunity_cards( $top_products_today, $rising_products, $top_products_30, $top_pages );

		$this->wrap_start( __( 'Apex View Insights', 'apex-view-insights' ) );
		?>
		<div class="avin-hero">
			<?php $this->brand_header(); ?>
			<div class="avin-actions">
				<a class="button button-primary" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=avin_export_csv' ), 'avin_export_csv' ) ); ?>"><?php esc_html_e( 'Export CSV', 'apex-view-insights' ); ?></a>
				<a class="button" href="<?php echo esc_url( admin_url( 'admin.php?page=avin-settings' ) ); ?>"><?php esc_html_e( 'Settings', 'apex-view-insights' ); ?></a>
			</div>
		</div>

		<div class="avin-executive-grid">
			<?php $this->kpi( __( 'Visitors Online', 'apex-view-insights' ), number_format_i18n( $online['visitors'] ), __( 'Active in last 5 minutes', 'apex-view-insights' ), 'up' ); ?>
			<?php $this->kpi( __( 'Active Pages', 'apex-view-insights' ), number_format_i18n( $online['pages'] ), __( 'Pages being viewed now', 'apex-view-insights' ), 'neutral' ); ?>
			<?php $this->kpi( __( 'Sessions', 'apex-view-insights' ), number_format_i18n( $online['sessions'] ), __( 'Current active sessions', 'apex-view-insights' ), 'neutral' ); ?>
			<?php $this->kpi( __( 'Unique Visitors', 'apex-view-insights' ), number_format_i18n( absint( $traffic_today['unique_visitors'] ) ), __( 'Today', 'apex-view-insights' ), 'up' ); ?>
			<?php $this->kpi( __( 'Today Sessions', 'apex-view-insights' ), number_format_i18n( absint( $traffic_today['sessions'] ) ), __( 'Visitor sessions today', 'apex-view-insights' ), 'neutral' ); ?>
			<?php $this->kpi( __( 'Page Views', 'apex-view-insights' ), number_format_i18n( absint( $traffic_today['page_views'] ) ), __( 'Today', 'apex-view-insights' ), 'neutral' ); ?>
		</div>

		<div class="avin-executive-grid avin-pageview-grid">
			<?php $this->kpi( __( 'Today', 'apex-view-insights' ), number_format_i18n( $today ), $this->trend_label( $today, $yesterday ), $today >= $yesterday ? 'up' : 'down' ); ?>
			<?php $this->kpi( __( 'Yesterday', 'apex-view-insights' ), number_format_i18n( $yesterday ), __( 'Previous day baseline', 'apex-view-insights' ), 'neutral' ); ?>
			<?php $this->kpi( __( '7 Days', 'apex-view-insights' ), number_format_i18n( $views_7 ), __( 'Rolling aggregate', 'apex-view-insights' ), 'up' ); ?>
			<?php $this->kpi( __( '30 Days', 'apex-view-insights' ), number_format_i18n( $views_30 ), __( 'Longer demand signal', 'apex-view-insights' ), 'neutral' ); ?>
			<?php $this->kpi( __( 'All Time', 'apex-view-insights' ), number_format_i18n( $views_all ), __( 'Since tracking began', 'apex-view-insights' ), 'neutral' ); ?>
			<?php $this->kpi( __( 'Tracking Mode', 'apex-view-insights' ), $tracking_mode, __( 'No raw logs stored', 'apex-view-insights' ), 'neutral' ); ?>
		</div>

		<div class="avin-card avin-chart-card">
			<div class="avin-card-head">
				<div>
					<p class="avin-eyebrow"><?php esc_html_e( 'Overall Views Trend', 'apex-view-insights' ); ?></p>
					<h2><?php esc_html_e( 'Attention Momentum', 'apex-view-insights' ); ?></h2>
				</div>
				<div class="avin-chart-toggle" role="group" aria-label="<?php esc_attr_e( 'Chart range', 'apex-view-insights' ); ?>">
					<button type="button" class="is-active" data-avin-range="seven"><?php esc_html_e( '7 Days', 'apex-view-insights' ); ?></button>
					<button type="button" data-avin-range="thirty"><?php esc_html_e( '30 Days', 'apex-view-insights' ); ?></button>
				</div>
			</div>
			<div class="avin-chart-shell">
				<div class="avin-line-chart" data-avin-chart="viewsTrend"></div>
			</div>
		</div>

		<div class="avin-opportunities">
			<?php foreach ( $opportunities as $card ) : ?>
				<?php $this->insight_card( $card ); ?>
			<?php endforeach; ?>
		</div>

		<div class="avin-grid">
			<?php $this->card_table( __( 'Top Products Today', 'apex-view-insights' ), $top_products_today, 'product' ); ?>
			<?php $this->card_table( __( 'Top Products - 7 Days', 'apex-view-insights' ), $top_products_7, 'product' ); ?>
			<?php $this->trend_table( __( 'Top Posts', 'apex-view-insights' ), $top_posts, __( 'Trend', 'apex-view-insights' ), 'trend' ); ?>
			<?php $this->trend_table( __( 'Top Pages', 'apex-view-insights' ), $top_pages_30, __( 'Growth', 'apex-view-insights' ), 'growth' ); ?>
			<?php $this->device_breakdown_card( $device_breakdown ); ?>
			<?php $this->card_table( __( 'Top Posts & Pages - 30 Days', 'apex-view-insights' ), $top_content, 'content' ); ?>
		</div>
		<?php
		$this->wrap_end();
	}

	public function woocommerce_page() {
		$products = $this->repository->top_objects( array( 'product' ), 30, 50 );

		$product_ids = array();
		foreach ( $products as $product ) {
			$product_ids[] = absint( $product['object_id'] );
		}

		$sales = $this->wc_metrics->sales_for_products( $product_ids, 30 );

		foreach ( $products as &$product ) {
			$product_id            = absint( $product['object_id'] );
			$product['units']      = isset( $sales[ $product_id ] ) ? absint( $sales[ $product_id ]['units'] ) : 0;
			$product['revenue']    = isset( $sales[ $product_id ] ) ? (float) $sales[ $product_id ]['revenue'] : 0;
			$product['conversion'] = $product['period_views'] > 0 ? ( $product['units'] / $product['period_views'] ) * 100 : 0;
		}
		unset( $product );

		$high_views_low_sales = array_values(
			array_filter(
				$products,
				function ( $product ) {
					return $product['period_views'] >= 10 && $product['units'] < 1;
				}
			)
		);

		$low_views_high_conversion = array_values(
			array_filter(
				$products,
				function ( $product ) {
					return $product['period_views'] > 0 && $product['period_views'] < 25 && $product['conversion'] >= 10;
				}
			)
		);

		usort(
			$low_views_high_conversion,
			function ( $a, $b ) {
				return $b['conversion'] <=> $a['conversion'];
			}
		);

		$total_views   = 0;
		$total_units   = 0;
		$total_revenue = 0;
		foreach ( $products as $product ) {
			$total_views   += absint( $product['period_views'] );
			$total_units   += absint( $product['units'] );
			$total_revenue += (float) $product['revenue'];
		}
		$conversion = $total_views > 0 ? ( $total_units / $total_views ) * 100 : 0;

		$this->wrap_start( __( 'Apex View Insights', 'apex-view-insights' ) );
		?>
		<div class="avin-hero avin-hero-compact">
			<?php $this->brand_header(); ?>
		</div>

		<div class="avin-executive-grid avin-woo-kpis">
			<?php $this->kpi( __( 'Product Views', 'apex-view-insights' ), number_format_i18n( $total_views ), __( 'Top viewed products, 30 days', 'apex-view-insights' ), 'neutral' ); ?>
			<?php $this->kpi( __( 'Units Sold', 'apex-view-insights' ), number_format_i18n( $total_units ), __( 'WooCommerce completed/processing', 'apex-view-insights' ), 'up' ); ?>
			<?php $this->kpi( __( 'Revenue', 'apex-view-insights' ), function_exists( 'wc_price' ) ? wp_strip_all_tags( wc_price( $total_revenue ) ) : '$' . number_format_i18n( $total_revenue, 2 ), __( 'Matched products, 30 days', 'apex-view-insights' ), 'up' ); ?>
			<?php $this->kpi( __( 'Conversion', 'apex-view-insights' ), $this->format_percent( $conversion ), __( 'Units divided by views', 'apex-view-insights' ), $conversion > 0 ? 'up' : 'neutral' ); ?>
		</div>

		<div class="avin-grid">
			<?php $this->woocommerce_table( __( 'Views vs Sales - 30 Days', 'apex-view-insights' ), array_slice( $products, 0, 20 ) ); ?>
			<?php $this->woocommerce_table( __( 'High Views / Low Sales', 'apex-view-insights' ), array_slice( $high_views_low_sales, 0, 20 ) ); ?>
			<?php $this->woocommerce_table( __( 'Low Views / High Conversion', 'apex-view-insights' ), array_slice( $low_views_high_conversion, 0, 20 ) ); ?>
		</div>
		<?php
		$this->wrap_end();
	}

	public function settings_page() {
		$tracked = get_option( 'avin_tracked_post_types', array( 'post', 'page', 'product' ) );
		$this->wrap_start( __( 'Apex View Insights Settings', 'apex-view-insights' ) );
		?>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="avin-card avin-settings">
			<input type="hidden" name="action" value="avin_save_settings">
			<?php wp_nonce_field( 'avin_save_settings' ); ?>

			<h2><?php esc_html_e( 'Tracking', 'apex-view-insights' ); ?></h2>
			<p><label><input type="checkbox" name="tracked_post_types[]" value="product" <?php checked( in_array( 'product', (array) $tracked, true ) ); ?>> <?php esc_html_e( 'Products', 'apex-view-insights' ); ?></label></p>
			<p><label><input type="checkbox" name="tracked_post_types[]" value="post" <?php checked( in_array( 'post', (array) $tracked, true ) ); ?>> <?php esc_html_e( 'Posts', 'apex-view-insights' ); ?></label></p>
			<p><label><input type="checkbox" name="tracked_post_types[]" value="page" <?php checked( in_array( 'page', (array) $tracked, true ) ); ?>> <?php esc_html_e( 'Pages', 'apex-view-insights' ); ?></label></p>

			<div class="avin-form-row">
				<label for="avin_tracking_mode"><?php esc_html_e( 'Tracking mode', 'apex-view-insights' ); ?></label>
				<select id="avin_tracking_mode" name="tracking_mode">
					<option value="beacon" <?php selected( 'beacon', get_option( 'avin_tracking_mode', 'beacon' ) ); ?>><?php esc_html_e( 'Cache-compatible beacon', 'apex-view-insights' ); ?></option>
					<option value="php" <?php selected( 'php', get_option( 'avin_tracking_mode', 'beacon' ) ); ?>><?php esc_html_e( 'PHP - no frontend script', 'apex-view-insights' ); ?></option>
				</select>
			</div>

			<h2><?php esc_html_e( 'Exclusions', 'apex-view-insights' ); ?></h2>
			<p><label><input type="checkbox" name="exclude_admins" value="1" <?php checked( '1', get_option( 'avin_exclude_admins', '1' ) ); ?>> <?php esc_html_e( 'Exclude administrators', 'apex-view-insights' ); ?></label></p>
			<p><label><input type="checkbox" name="exclude_logged_in" value="1" <?php checked( '1', get_option( 'avin_exclude_logged_in', '0' ) ); ?>> <?php esc_html_e( 'Exclude all logged-in users', 'apex-view-insights' ); ?></label></p>
			<p><label><input type="checkbox" name="bot_filtering" value="1" <?php checked( '1', get_option( 'avin_bot_filtering', '1' ) ); ?>> <?php esc_html_e( 'Filter common bots and crawlers', 'apex-view-insights' ); ?></label></p>

			<div class="avin-form-row">
				<label for="avin_retention_days"><?php esc_html_e( 'Daily aggregate retention days', 'apex-view-insights' ); ?></label>
				<input id="avin_retention_days" type="number" min="30" max="3650" name="retention_days" value="<?php echo esc_attr( absint( get_option( 'avin_retention_days', 730 ) ) ); ?>">
			</div>

			<h2><?php esc_html_e( 'Dashboard Appearance', 'apex-view-insights' ); ?></h2>
			<div class="avin-form-row">
				<label for="avin_dashboard_theme"><?php esc_html_e( 'Dashboard theme', 'apex-view-insights' ); ?></label>
				<select id="avin_dashboard_theme" name="dashboard_theme">
					<option value="light" <?php selected( 'light', get_option( 'avin_dashboard_theme', 'dark' ) ); ?>><?php esc_html_e( 'Light', 'apex-view-insights' ); ?></option>
					<option value="dark" <?php selected( 'dark', get_option( 'avin_dashboard_theme', 'dark' ) ); ?>><?php esc_html_e( 'Dark', 'apex-view-insights' ); ?></option>
				</select>
			</div>

			<button class="button button-primary" type="submit"><?php esc_html_e( 'Save Settings', 'apex-view-insights' ); ?></button>
		</form>
		<?php
		$this->wrap_end();
	}

	public function save_settings() {
		if ( ! current_user_can( $this->capability() ) ) {
			wp_die( esc_html__( 'You do not have permission to update Apex View Insights settings.', 'apex-view-insights' ) );
		}

		check_admin_referer( 'avin_save_settings' );

		$tracked = isset( $_POST['tracked_post_types'] ) ? array_map( 'sanitize_key', (array) wp_unslash( $_POST['tracked_post_types'] ) ) : array();
		$tracked = array_values( array_intersect( $tracked, array( 'post', 'page', 'product' ) ) );
		if ( empty( $tracked ) ) {
			$tracked = array( 'product' );
		}

		update_option( 'avin_tracked_post_types', $tracked, false );
		$tracking_mode   = isset( $_POST['tracking_mode'] ) ? sanitize_key( wp_unslash( $_POST['tracking_mode'] ) ) : 'beacon';
		$dashboard_theme = isset( $_POST['dashboard_theme'] ) ? sanitize_key( wp_unslash( $_POST['dashboard_theme'] ) ) : 'dark';
		$retention_days  = isset( $_POST['retention_days'] ) ? absint( wp_unslash( $_POST['retention_days'] ) ) : 730;

		update_option( 'avin_tracking_mode', 'beacon' === $tracking_mode ? 'beacon' : 'php', false );
		update_option( 'avin_exclude_admins', isset( $_POST['exclude_admins'] ) ? '1' : '0', false );
		update_option( 'avin_exclude_logged_in', isset( $_POST['exclude_logged_in'] ) ? '1' : '0', false );
		update_option( 'avin_bot_filtering', isset( $_POST['bot_filtering'] ) ? '1' : '0', false );
		update_option( 'avin_retention_days', max( 30, $retention_days ), false );
		update_option( 'avin_dashboard_theme', 'light' === $dashboard_theme ? 'light' : 'dark', false );

		wp_safe_redirect(
			add_query_arg(
				array(
					'page'    => 'avin-settings',
					'updated' => 'true',
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	public function export_csv() {
		$exporter = new AVIN_Exporter( $this->repository, $this->wc_metrics );
		$exporter->export_csv();
	}

	private function opportunity_cards( $top_products_today, $rising_products, $top_products_30, $top_pages ) {
		$product_ids = array();
		foreach ( $top_products_30 as $product ) {
			$product_ids[] = absint( $product['object_id'] );
		}

		$sales = $this->wc_metrics->sales_for_products( $product_ids, 30 );
		foreach ( $top_products_30 as &$product ) {
			$product_id            = absint( $product['object_id'] );
			$product['units']      = isset( $sales[ $product_id ] ) ? absint( $sales[ $product_id ]['units'] ) : 0;
			$product['revenue']    = isset( $sales[ $product_id ] ) ? (float) $sales[ $product_id ]['revenue'] : 0;
			$product['conversion'] = $product['period_views'] > 0 ? ( $product['units'] / $product['period_views'] ) * 100 : 0;
		}
		unset( $product );

		$high_views_low_sales = $this->first_matching(
			$top_products_30,
			function ( $product ) {
				return absint( $product['period_views'] ) >= 10 && absint( $product['units'] ) < 1;
			}
		);
		$hidden_opportunity   = $this->first_matching(
			$top_products_30,
			function ( $product ) {
				return absint( $product['period_views'] ) > 0 && absint( $product['period_views'] ) < 25 && (float) $product['conversion'] >= 10;
			}
		);

		return array(
			array(
				'label' => __( 'Most Viewed Product Today', 'apex-view-insights' ),
				'title' => $this->row_title( $top_products_today[0] ?? null ),
				'value' => $this->row_views( $top_products_today[0] ?? null, 'period_views' ),
				'tone'  => 'blue',
			),
			array(
				'label' => __( 'Fastest Rising Product', 'apex-view-insights' ),
				'title' => $this->row_title( $rising_products[0] ?? null ),
				'value' => isset( $rising_products[0] ) ? '+' . number_format_i18n( max( 0, absint( $rising_products[0]['lift'] ) ) ) : '0',
				'tone'  => 'green',
			),
			array(
				'label' => __( 'High Views / Low Sales', 'apex-view-insights' ),
				'title' => $this->row_title( $high_views_low_sales ),
				'value' => $this->row_views( $high_views_low_sales, 'period_views' ),
				'tone'  => 'amber',
			),
			array(
				'label' => __( 'Hidden Opportunity Product', 'apex-view-insights' ),
				'title' => $this->row_title( $hidden_opportunity ),
				'value' => isset( $hidden_opportunity['conversion'] ) ? $this->format_percent( (float) $hidden_opportunity['conversion'] ) : '0%',
				'tone'  => 'purple',
			),
			array(
				'label' => __( 'Most Viewed Page', 'apex-view-insights' ),
				'title' => $this->row_title( $top_pages[0] ?? null ),
				'value' => $this->row_views( $top_pages[0] ?? null, 'period_views' ),
				'tone'  => 'blue',
			),
		);
	}

	private function first_matching( $rows, $callback ) {
		foreach ( $rows as $row ) {
			if ( $callback( $row ) ) {
				return $row;
			}
		}

		return null;
	}

	private function row_title( $row ) {
		if ( empty( $row ) ) {
			return __( 'Collecting data', 'apex-view-insights' );
		}

		return ! empty( $row['post_title'] ) ? $row['post_title'] : sprintf(
			/* translators: %d: object ID. */
			__( '#%d', 'apex-view-insights' ),
			absint( $row['object_id'] )
		);
	}

	private function row_views( $row, $key ) {
		if ( empty( $row ) || ! isset( $row[ $key ] ) ) {
			return '0';
		}

		return number_format_i18n( absint( $row[ $key ] ) );
	}

	private function growth_percent( $current, $previous ) {
		$current  = (float) $current;
		$previous = (float) $previous;

		if ( $previous <= 0 ) {
			return $current > 0 ? 100 : 0;
		}

		return round( ( ( $current - $previous ) / $previous ) * 100, 1 );
	}

	private function format_percent( $value ) {
		return number_format_i18n( (float) $value, 1 ) . '%';
	}

	private function trend_label( $current, $previous ) {
		$growth = $this->growth_percent( $current, $previous );
		if ( 0 === (float) $growth ) {
			return __( 'No change vs yesterday', 'apex-view-insights' );
		}

		return sprintf(
			/* translators: %s: growth percentage. */
			__( '%s vs yesterday', 'apex-view-insights' ),
			$this->format_percent( $growth )
		);
	}

	private function decorate_object_trends( $rows ) {
		$today     = current_time( 'Y-m-d' );
		$yesterday = gmdate( 'Y-m-d', strtotime( $today . ' -1 day' ) );

		foreach ( $rows as &$row ) {
			$current            = $this->repository->get_views_on_date( absint( $row['object_id'] ), $today );
			$previous           = $this->repository->get_views_on_date( absint( $row['object_id'] ), $yesterday );
			$row['trend_label'] = $current >= $previous ? '+' . number_format_i18n( max( 0, $current - $previous ) ) : '-' . number_format_i18n( max( 0, $previous - $current ) );
			$row['growth']      = $this->growth_percent( $current, $previous );
		}
		unset( $row );

		return $rows;
	}

	private function insight_card( $card ) {
		$tone = isset( $card['tone'] ) ? sanitize_html_class( $card['tone'] ) : 'blue';
		?>
		<div class="avin-insight avin-insight-<?php echo esc_attr( $tone ); ?>">
			<span><?php echo esc_html( $card['label'] ); ?></span>
			<strong><?php echo esc_html( $card['title'] ); ?></strong>
			<em><?php echo esc_html( $card['value'] ); ?></em>
		</div>
		<?php
	}

	private function card_table( $title, $rows, $kind ) {
		?>
		<div class="avin-card">
			<h2><?php echo esc_html( $title ); ?></h2>
			<table class="avin-table">
				<thead><tr><th><?php esc_html_e( 'Title', 'apex-view-insights' ); ?></th><th><?php esc_html_e( 'Views', 'apex-view-insights' ); ?></th><th><?php esc_html_e( 'Total', 'apex-view-insights' ); ?></th></tr></thead>
				<tbody>
				<?php if ( empty( $rows ) ) : ?>
					<tr><td colspan="3" class="avin-empty"><?php esc_html_e( 'No view data yet.', 'apex-view-insights' ); ?></td></tr>
				<?php endif; ?>
				<?php foreach ( $rows as $row ) : ?>
					<tr>
						<td><a href="<?php echo esc_url( get_edit_post_link( absint( $row['object_id'] ) ) ); ?>"><?php echo esc_html( $this->row_title( $row ) ); ?></a><?php echo 'content' === $kind ? ' <span class="avin-pill">' . esc_html( $row['post_type'] ) . '</span>' : ''; ?></td>
						<td><?php echo esc_html( number_format_i18n( absint( $row['period_views'] ) ) ); ?></td>
						<td><?php echo esc_html( number_format_i18n( absint( $row['total_views'] ) ) ); ?></td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	private function trend_table( $title, $rows, $third_label, $metric ) {
		?>
		<div class="avin-card">
			<h2><?php echo esc_html( $title ); ?></h2>
			<table class="avin-table">
				<thead><tr><th><?php esc_html_e( 'Title', 'apex-view-insights' ); ?></th><th><?php esc_html_e( 'Views', 'apex-view-insights' ); ?></th><th><?php echo esc_html( $third_label ); ?></th></tr></thead>
				<tbody>
				<?php if ( empty( $rows ) ) : ?>
					<tr><td colspan="3" class="avin-empty"><?php esc_html_e( 'No view data yet.', 'apex-view-insights' ); ?></td></tr>
				<?php endif; ?>
				<?php foreach ( $rows as $row ) : ?>
					<tr>
						<td><a href="<?php echo esc_url( get_edit_post_link( absint( $row['object_id'] ) ) ); ?>"><?php echo esc_html( $this->row_title( $row ) ); ?></a></td>
						<td><?php echo esc_html( number_format_i18n( absint( $row['period_views'] ) ) ); ?></td>
						<td><span class="avin-trend-pill <?php echo (float) $row['growth'] >= 0 ? 'is-up' : 'is-down'; ?>"><?php echo esc_html( 'growth' === $metric ? $this->format_percent( $row['growth'] ) : $row['trend_label'] ); ?></span></td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	private function device_breakdown_card( $rows ) {
		$labels  = array(
			'desktop' => __( 'Desktop', 'apex-view-insights' ),
			'mobile'  => __( 'Mobile', 'apex-view-insights' ),
			'tablet'  => __( 'Tablet', 'apex-view-insights' ),
		);
		$by_type = array();
		foreach ( $rows as $row ) {
			$by_type[ sanitize_key( $row['device_type'] ) ] = $row;
		}
		?>
		<div class="avin-card">
			<h2><?php esc_html_e( 'Device Breakdown', 'apex-view-insights' ); ?></h2>
			<div class="avin-device-bars">
				<?php foreach ( $labels as $type => $label ) : ?>
					<?php
						$row = $by_type[ $type ] ?? array(
							'visitors'   => 0,
							'page_views' => 0,
							'percentage' => 0,
						);
						$pct = max( 0, min( 100, (float) $row['percentage'] ) );
						?>
					<div class="avin-device-row">
						<div class="avin-device-meta">
							<strong><?php echo esc_html( $label ); ?></strong>
							<span><?php echo esc_html( number_format_i18n( absint( $row['page_views'] ) ) ); ?> <?php esc_html_e( 'views', 'apex-view-insights' ); ?> · <?php echo esc_html( number_format_i18n( absint( $row['visitors'] ) ) ); ?> <?php esc_html_e( 'visitors', 'apex-view-insights' ); ?></span>
						</div>
						<div class="avin-device-track"><span style="width: <?php echo esc_attr( $pct ); ?>%"></span></div>
						<em><?php echo esc_html( $this->format_percent( $pct ) ); ?></em>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
		<?php
	}

	private function woocommerce_table( $title, $rows ) {
		?>
		<div class="avin-card avin-wide">
			<h2><?php echo esc_html( $title ); ?></h2>
			<table class="avin-table">
				<thead><tr><th><?php esc_html_e( 'Product', 'apex-view-insights' ); ?></th><th><?php esc_html_e( 'Views', 'apex-view-insights' ); ?></th><th><?php esc_html_e( 'Units', 'apex-view-insights' ); ?></th><th><?php esc_html_e( 'Revenue', 'apex-view-insights' ); ?></th><th><?php esc_html_e( 'Conv.', 'apex-view-insights' ); ?></th></tr></thead>
				<tbody>
				<?php if ( empty( $rows ) ) : ?>
					<tr><td colspan="5" class="avin-empty"><?php esc_html_e( 'No matching product data yet.', 'apex-view-insights' ); ?></td></tr>
				<?php endif; ?>
				<?php foreach ( $rows as $row ) : ?>
					<tr>
						<td><a href="<?php echo esc_url( get_edit_post_link( absint( $row['object_id'] ) ) ); ?>"><?php echo esc_html( $row['post_title'] ); ?></a></td>
						<td><?php echo esc_html( number_format_i18n( absint( $row['period_views'] ) ) ); ?></td>
						<td><?php echo esc_html( number_format_i18n( absint( $row['units'] ) ) ); ?></td>
						<td><?php echo wp_kses_post( function_exists( 'wc_price' ) ? wc_price( (float) $row['revenue'] ) : '$' . number_format_i18n( (float) $row['revenue'], 2 ) ); ?></td>
						<td><?php echo esc_html( number_format_i18n( (float) $row['conversion'], 2 ) ); ?>%</td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	private function kpi( $label, $value, $meta = '', $trend = 'neutral' ) {
		$trend = sanitize_html_class( $trend );
		?>
		<div class="avin-kpi avin-trend-<?php echo esc_attr( $trend ); ?>">
			<span><?php echo esc_html( $label ); ?></span>
			<strong><?php echo esc_html( $value ); ?></strong>
			<?php if ( '' !== $meta ) : ?>
				<em><?php echo esc_html( $meta ); ?></em>
			<?php endif; ?>
		</div>
		<?php
	}

	private function brand_header() {
		$tracking_mode = 'beacon' === get_option( 'avin_tracking_mode', 'beacon' ) ? __( 'Beacon Tracking Active', 'apex-view-insights' ) : __( 'PHP Tracking Active', 'apex-view-insights' );
		?>
		<div class="avin-brand">
			<img class="avin-brand-logo" src="<?php echo esc_url( AVIN_PLUGIN_URL . 'assets/branding/avi-logo.png' ); ?>" alt="<?php esc_attr_e( 'Apex View Insights logo', 'apex-view-insights' ); ?>">
			<div class="avin-brand-copy">
				<p class="avin-eyebrow"><?php esc_html_e( 'Commerce Intelligence', 'apex-view-insights' ); ?></p>
				<h2><?php esc_html_e( 'Apex View Insights', 'apex-view-insights' ); ?></h2>
				<p><?php esc_html_e( 'Commerce Intelligence Platform', 'apex-view-insights' ); ?></p>
				<div class="avin-status-badges" aria-label="<?php esc_attr_e( 'Platform status', 'apex-view-insights' ); ?>">
					<span><?php echo esc_html( $tracking_mode ); ?></span>
					<span><?php esc_html_e( 'Commerce Analytics Active', 'apex-view-insights' ); ?></span>
					<span><?php esc_html_e( 'Data Collection Active', 'apex-view-insights' ); ?></span>
				</div>
			</div>
		</div>
		<?php
	}

	private function wrap_start( $title ) {
		$theme = 'light' === get_option( 'avin_dashboard_theme', 'dark' ) ? 'light' : 'dark';
		?>
		<div class="wrap avin-wrap avin-theme-<?php echo esc_attr( $theme ); ?>">
			<h1><?php echo esc_html( $title ); ?></h1>
		<?php
	}

	private function wrap_end() {
		echo '</div>';
	}

	private function capability() {
		return class_exists( 'WooCommerce' ) ? 'manage_woocommerce' : 'manage_options';
	}
}
