<?php
/**
 * Dashboard page template.
 *
 * @package TrustLens\Admin\Views
 * @since   1.0.0
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template variables scoped to included view file.

$sync        = TrustLens_Historical_Sync::instance();
$sync_status = $sync->get_status();
$sync_progress = $sync->get_progress();

// Analytics data.
$segment_counts  = TrustLens_Analytics::get_segment_distribution();
$trends          = TrustLens_Analytics::get_score_trends( 30 );
$summary_stats   = TrustLens_Analytics::get_summary_stats();
$telemetry       = TrustLens_Analytics::get_live_telemetry();

// Customer repository data.
$repo                = new TrustLens_Customer_Repository();
$high_risk_customers = $repo->get_high_risk( 10 );

// Computed values.
$avg_score       = (int) round( $summary_stats['avg_trust_score'] );
$health_segment  = wstl_get_segment_from_score( $avg_score );
$total_customers = array_sum( $segment_counts );
$risk_count      = ( $segment_counts['risk'] ?? 0 ) + ( $segment_counts['critical'] ?? 0 );
$is_empty        = ( 0 === $total_customers );

// Count available WooCommerce orders (only when dashboard is empty, to avoid unnecessary queries).
$wc_order_count = 0;
if ( $is_empty ) {
	$wc_order_count = count( wc_get_orders( array(
		'limit'  => -1,
		'return' => 'ids',
		'status' => array( 'completed', 'processing', 'refunded', 'cancelled' ),
	) ) );
}

// Time-based greeting.
$current_hour = (int) current_time( 'G' );
if ( $current_hour < 12 ) {
	$greeting = __( 'Good morning', 'trustlens' );
} elseif ( $current_hour < 18 ) {
	$greeting = __( 'Good afternoon', 'trustlens' );
} else {
	$greeting = __( 'Good evening', 'trustlens' );
}

// The Command Center renders its Trust Trend via Chart.js (enqueued on this
// page) + command-center-charts.js, reading data from the canvas data-attrs.
?>

<div class="wrap wstl-wrap">
	<h1 class="screen-reader-text"><?php esc_html_e( 'TrustLens Dashboard', 'trustlens' ); ?></h1>
	<hr class="wp-header-end">

	<div class="wstl-dashboard">

		<?php if ( ! get_option( 'trustlens_quickstart_dismissed', false ) ) : ?>
			<?php include TRUSTLENS_PLUGIN_DIR . 'admin/views/partials/quickstart-card.php'; ?>
		<?php endif; ?>

		<?php if ( $is_empty ) : ?>
		<!-- S1: Header Bar (Empty State) -->
		<div class="wstl-dashboard-section">
			<div class="wstl-header-bar">
				<div class="wstl-header-health">
					<div class="wstl-health-ring">
						<span class="wstl-health-value">&mdash;</span>
						<span class="wstl-health-label"><?php esc_html_e( 'Health', 'trustlens' ); ?></span>
					</div>
				</div>
				<div class="wstl-header-info">
					<p class="wstl-header-greeting"><?php echo esc_html( $greeting ); ?></p>
					<p class="wstl-header-subtitle">
						<?php if ( $wc_order_count > 0 ) : ?>
							<?php
							printf(
								/* translators: %s: order count */
								esc_html__( 'You have %s orders ready to be analyzed.', 'trustlens' ),
								'<strong>' . esc_html( number_format( $wc_order_count ) ) . '</strong>'
							);
							?>
						<?php else : ?>
							<?php esc_html_e( 'New orders will be analyzed automatically as they come in.', 'trustlens' ); ?>
						<?php endif; ?>
					</p>
					<p class="wstl-header-health-msg is-setup">
						<?php
						if ( $wc_order_count > 0 ) {
							esc_html_e( 'Run a historical sync to build customer trust profiles', 'trustlens' );
						} else {
							esc_html_e( 'Awaiting your first WooCommerce orders', 'trustlens' );
						}
						?>
					</p>
					<div class="wstl-header-metrics">
						<span class="wstl-header-chip"><?php echo esc_html( number_format( $wc_order_count ) ); ?> <?php esc_html_e( 'Orders Ready', 'trustlens' ); ?></span>
						<span class="wstl-header-chip"><?php echo esc_html( $sync_progress ); ?>% <?php esc_html_e( 'Sync Progress', 'trustlens' ); ?></span>
					</div>
				</div>
			</div>
		</div>

		<!-- Onboarding Card -->
		<div class="wstl-dashboard-section">
			<div class="wstl-onboarding-card">
				<div class="wstl-onboarding-icon">
					<span class="dashicons dashicons-chart-area"></span>
				</div>
				<h2><?php esc_html_e( 'Get Started with TrustLens', 'trustlens' ); ?></h2>
				<p class="wstl-onboarding-desc">
					<?php esc_html_e( 'Follow these steps to start monitoring customer trust across your store.', 'trustlens' ); ?>
				</p>
				<?php
				$wstl_active_pills = array(
					'returns'            => (bool) get_option( 'trustlens_module_returns_enabled', true ),
					'orders'             => (bool) get_option( 'trustlens_module_orders_enabled', true ),
					'coupons'            => (bool) get_option( 'trustlens_module_coupons_enabled', true ),
					'categories'         => (bool) get_option( 'trustlens_module_categories_enabled', true ),
					'linked_accounts'    => (bool) get_option( 'trustlens_module_linked_accounts_enabled', true ),
					'shipping_anomalies' => (bool) get_option( 'trustlens_module_shipping_anomalies_enabled', true ),
					'chargebacks'        => (bool) get_option( 'trustlens_module_chargebacks_enabled', true ),
					'card_testing'       => (bool) get_option( 'trustlens_module_card_testing_enabled', false ),
				);
				$wstl_active_count = count( array_filter( $wstl_active_pills ) );
				?>
				<div class="wstl-onboarding-active">
					<span class="wstl-onboarding-active-dot" aria-hidden="true"></span>
					<span class="wstl-onboarding-active-text">
						<?php
						printf(
							/* translators: %d: number of detection modules currently enabled (0–8). */
							esc_html( _n(
								'Already protecting your store — %d detection module is active and scoring incoming orders right now.',
								'Already protecting your store — %d detection modules are active and scoring incoming orders right now.',
								$wstl_active_count,
								'trustlens'
							) ),
							(int) $wstl_active_count
						);
						?>
					</span>
				</div>
				<div class="wstl-onboarding-steps">
					<div class="wstl-onboarding-step">
						<div class="wstl-step-header">
							<span class="wstl-onboarding-step-num">1</span>
							<span class="dashicons dashicons-database-import wstl-step-icon"></span>
						</div>
						<h3><?php esc_html_e( 'Import Your Orders', 'trustlens' ); ?></h3>
						<p>
							<?php if ( $wc_order_count > 0 ) : ?>
								<?php
								printf(
									/* translators: %s: order count */
									esc_html__( '%s orders are waiting to be analyzed. Hit sync below and watch TrustLens build a trust profile for every customer.', 'trustlens' ),
									'<strong>' . esc_html( number_format( $wc_order_count ) ) . '</strong>'
								);
								?>
							<?php else : ?>
								<?php esc_html_e( 'As soon as WooCommerce orders come in, TrustLens will build a trust profile for every customer automatically.', 'trustlens' ); ?>
							<?php endif; ?>
						</p>
					</div>
					<div class="wstl-onboarding-step">
						<div class="wstl-step-header">
							<span class="wstl-onboarding-step-num">2</span>
							<span class="dashicons dashicons-admin-settings wstl-step-icon"></span>
						</div>
						<h3><?php esc_html_e( 'Customize Your Rules', 'trustlens' ); ?></h3>
						<p>
							<?php
							printf(
								/* translators: %1$s: opening link tag, %2$s: closing link tag */
								esc_html__( 'Adjust trust thresholds, turn on checkout blocking, and fine-tune detection modules in %1$sSettings%2$s.', 'trustlens' ),
								'<a href="' . esc_url( admin_url( 'admin.php?page=trustlens-settings' ) ) . '">',
								'</a>'
							);
							?>
						</p>
					</div>
					<div class="wstl-onboarding-step">
						<div class="wstl-step-header">
							<span class="wstl-onboarding-step-num">3</span>
							<span class="dashicons dashicons-shield wstl-step-icon"></span>
						</div>
						<h3><?php esc_html_e( 'Protect Your Store', 'trustlens' ); ?></h3>
						<p><?php esc_html_e( 'Your dashboard will light up with trust scores, segment trends, and flagged customers the moment the sync finishes.', 'trustlens' ); ?></p>
					</div>
				</div>
				<?php if ( wstl_show_pro_upsells() && wstl_get_upgrade_or_fallback_url() ) : ?>
				<p class="wstl-onboarding-pro-teaser">
					<?php
					printf(
						/* translators: %1$s: opening link tag, %2$s: closing link tag */
						esc_html__( 'Want to automate responses and get reports by email? %1$sSee Pro%2$s.', 'trustlens' ),
						'<a href="' . esc_url( wstl_get_upgrade_or_fallback_url() ) . '">',
						'</a>'
					);
					?>
				</p>
				<?php endif; ?>

				<!-- Sync Action -->
				<div class="wstl-onboarding-sync">
					<div id="wstl-sync-start-area" class="<?php echo 'running' === $sync_status['status'] ? 'wstl-modal-hidden' : ''; ?>">
						<button type="button" class="button button-primary button-hero" id="wstl-start-sync">
							<?php esc_html_e( 'Start Historical Sync', 'trustlens' ); ?>
						</button>
						<p class="wstl-onboarding-sync-note">
							<?php
							if ( $wc_order_count > 0 ) {
								esc_html_e( 'You\'ll see progress in real time — keep this tab open.', 'trustlens' );
							} else {
								esc_html_e( 'No eligible historical orders found yet. New WooCommerce orders are analyzed automatically as they come in.', 'trustlens' );
							}
							?>
						</p>
					</div>
					<div class="wstl-sync-progress <?php echo 'running' !== $sync_status['status'] ? 'wstl-modal-hidden' : ''; ?>" id="wstl-sync-progress-area">
						<div class="wstl-progress-bar">
							<div class="wstl-progress-fill" style="width: <?php echo esc_attr( $sync_progress ); ?>%;"></div>
						</div>
						<p class="wstl-sync-stats">
							<span id="wstl-sync-progress-text"><?php echo esc_html( $sync_progress ); ?>%</span> &mdash;
							<span id="wstl-sync-orders-text">
								<?php
								if ( 'running' === $sync_status['status'] ) {
									printf(
										/* translators: %1$s: processed orders, %2$s: total orders */
										esc_html__( '%1$s of %2$s orders processed', 'trustlens' ),
										number_format( $sync_status['processed_orders'] ),
										number_format( $sync_status['total_orders'] )
									);
								} else {
									printf(
										/* translators: %1$s: processed orders, %2$s: total orders */
										esc_html__( '%1$s of %2$s orders processed', 'trustlens' ),
										'0',
										number_format( $wc_order_count )
									);
								}
								?>
							</span>
						</p>
						<button type="button" class="button" id="wstl-stop-sync" <?php echo 'running' === $sync_status['status'] ? '' : 'style="display:none;"'; ?>>
							<?php esc_html_e( 'Stop Sync', 'trustlens' ); ?>
						</button>
					</div>
				</div>
			</div>
		</div>

		<?php else : ?>
		<!-- S0: Alert band — operationally critical states (panic freeze,
		     targeted lockdown, chargebacks over threshold). Renders nothing
		     when healthy. -->
		<?php include TRUSTLENS_PLUGIN_DIR . 'admin/views/partials/dashboard-alert-band.php'; ?>

		<!-- Command Center — populated dashboard body. -->
		<?php include TRUSTLENS_PLUGIN_DIR . 'admin/views/partials/command-center.php'; ?>

		<!-- Historical Data Sync — Command Center styled. -->
		<div class="tlcc">
			<?php
			if ( 'completed' === $sync_status['status'] || ( 'idle' === $sync_status['status'] && $sync_status['total_customers'] > 0 ) ) {
				$wstl_sync_state = 'ok';
				$wstl_sync_badge = __( 'Synced', 'trustlens' );
			} elseif ( 'running' === $sync_status['status'] ) {
				$wstl_sync_state = 'run';
				$wstl_sync_badge = __( 'Running', 'trustlens' );
			} else {
				$wstl_sync_state = 'idle';
				$wstl_sync_badge = __( 'Not started', 'trustlens' );
			}
			?>
			<div class="tlcc-sync tlcc-sync-<?php echo esc_attr( $wstl_sync_state ); ?>">
				<div class="tlcc-sync-head">
					<span class="tlcc-l"><?php esc_html_e( 'Historical Data Sync', 'trustlens' ); ?></span>
					<span class="tlcc-sync-badge tlcc-sync-badge-<?php echo esc_attr( $wstl_sync_state ); ?>"><?php echo esc_html( $wstl_sync_badge ); ?></span>
				</div>
					<div id="wstl-sync-start-area" class="<?php echo 'running' === $sync_status['status'] ? 'wstl-modal-hidden' : ''; ?>">
						<?php if ( 'completed' === $sync_status['status'] ) : ?>
							<div class="wstl-sync-complete">
								<span class="dashicons dashicons-yes-alt wstl-icon-success wstl-icon-32"></span>
								<p>
									<?php
									printf(
										/* translators: %1$s: customer count, %2$s: order count */
										esc_html__( 'Sync complete! %1$s customers from %2$s orders.', 'trustlens' ),
										'<strong>' . number_format( $sync_status['total_customers'] ) . '</strong>',
										'<strong>' . number_format( $sync_status['processed_orders'] ) . '</strong>'
									);
									?>
								</p>
								<p class="wstl-mt-15">
									<button type="button" class="button" id="wstl-resync">
										<?php esc_html_e( 'Re-sync', 'trustlens' ); ?>
									</button>
								</p>
							</div>
						<?php elseif ( 'idle' === $sync_status['status'] && $sync_status['total_customers'] > 0 ) : ?>
							<div class="wstl-sync-idle">
								<p>
									<?php
									printf(
										/* translators: %s: customer count */
										esc_html__( 'Tracking %s customers.', 'trustlens' ),
										'<strong>' . number_format( $sync_status['total_customers'] ) . '</strong>'
									);
									?>
								</p>
								<button type="button" class="button button-primary" id="wstl-start-sync">
									<?php esc_html_e( 'Start Sync', 'trustlens' ); ?>
								</button>
							</div>
						<?php else : ?>
							<div class="wstl-sync-intro">
								<p><?php esc_html_e( 'Import your existing WooCommerce orders to build customer trust profiles based on historical data.', 'trustlens' ); ?></p>
								<p><strong><?php esc_html_e( 'This process runs in the background and will not slow down your site.', 'trustlens' ); ?></strong></p>
								<button type="button" class="button button-primary" id="wstl-start-sync">
									<?php esc_html_e( 'Start Historical Sync', 'trustlens' ); ?>
								</button>
							</div>
						<?php endif; ?>
					</div>
					<div class="wstl-sync-progress <?php echo 'running' !== $sync_status['status'] ? 'wstl-modal-hidden' : ''; ?>" id="wstl-sync-progress-area">
						<div class="wstl-progress-bar">
							<div class="wstl-progress-fill" style="width: <?php echo esc_attr( $sync_progress ); ?>%;"></div>
						</div>
						<p class="wstl-sync-stats">
							<span id="wstl-sync-progress-text"><?php echo esc_html( $sync_progress ); ?>%</span> &mdash;
							<span id="wstl-sync-orders-text">
								<?php
								printf(
									/* translators: %1$s: processed orders, %2$s: total orders */
									esc_html__( '%1$s of %2$s orders processed', 'trustlens' ),
									number_format( $sync_status['processed_orders'] ),
									number_format( $sync_status['total_orders'] )
								);
								?>
							</span>
						</p>
						<button type="button" class="button" id="wstl-stop-sync">
							<?php esc_html_e( 'Stop Sync', 'trustlens' ); ?>
						</button>
					</div>
			</div>
		</div>
			<?php include TRUSTLENS_PLUGIN_DIR . 'admin/views/partials/dashboard-network-status.php'; ?>
		<?php endif; // End if ( $is_empty ) / else. ?>

	</div><!-- .wstl-dashboard -->
</div><!-- .wrap -->

<?php // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
