<?php
/**
 * Command Center — dense operational dashboard body.
 *
 * Rendered for the populated dashboard state. Free panels use live data; Pro
 * panels (Chargeback Monitor, card-testing attack intelligence, Automation)
 * show real data only when the Pro classes are present, otherwise a purely
 * promotional upsell card. No Pro code paths run in the free build.
 *
 * Expects in scope (from dashboard.php): $avg_score, $health_segment,
 * $summary_stats, $segment_counts, $high_risk_customers, $trends, $risk_count,
 * $telemetry (TrustLens_Analytics::get_live_telemetry()).
 *
 * @package TrustLens\Admin\Views
 * @since   1.3.0
 */

defined( 'ABSPATH' ) || exit;

global $wpdb;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-scoped vars.
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Read-only dashboard widgets, table names from $wpdb->prefix.

/* ---- Pro availability (gating, no Pro code executed when false) ---- */
$cc_pro       = function_exists( 'wstl_can_use_pro' ) && wstl_can_use_pro();
$cc_charge    = function_exists( 'wstl_has_chargebacks' ) && wstl_has_chargebacks() && $cc_pro;
$cc_auto      = function_exists( 'wstl_has_automation' ) && wstl_has_automation() && $cc_pro;
$cc_ct_intel  = class_exists( 'TrustLens_Card_Testing_History_Query' ) && $cc_pro;
$cc_upgrade   = function_exists( 'wstl_get_upgrade_or_fallback_url' ) ? wstl_get_upgrade_or_fallback_url() : '#';

/* ---- Trust index / threat ---- */
$cc_score = (int) $avg_score;
$cc_tier  = wstl_get_segment_label( $health_segment );
$cc_crit  = (int) ( $segment_counts['critical'] ?? 0 );
$cc_riskn = (int) $risk_count;
if ( $cc_crit >= 10 || $cc_riskn >= 25 ) {
	$cc_threat = __( 'ELEVATED', 'trustlens' );
	$cc_threat_cls = 'warn';
} elseif ( $cc_riskn > 0 ) {
	$cc_threat = __( 'GUARDED', 'trustlens' );
	$cc_threat_cls = 'warn';
} else {
	$cc_threat = __( 'NOMINAL', 'trustlens' );
	$cc_threat_cls = 'ok';
}
// Ring geometry (r=52, circumference ~326.7).
$cc_dash = 326.7;
$cc_off  = $cc_dash * ( 1 - max( 0, min( 100, $cc_score ) ) / 100 );

/* ---- Detection modules (free) ---- */
$cc_modules = array(
	'returns'            => __( 'Return abuse', 'trustlens' ),
	'orders'             => __( 'Order tracking', 'trustlens' ),
	'coupons'            => __( 'Coupon abuse', 'trustlens' ),
	'categories'         => __( 'Category-aware', 'trustlens' ),
	'linked_accounts'    => __( 'Linked accounts', 'trustlens' ),
	'shipping_anomalies' => __( 'Shipping anomalies', 'trustlens' ),
	'chargebacks'        => __( 'Chargebacks', 'trustlens' ),
	'card_testing'       => __( 'Card-testing', 'trustlens' ),
);
$cc_mod_active = 0;
foreach ( $cc_modules as $cc_mk => $cc_ml ) {
	if ( get_option( 'trustlens_module_' . $cc_mk . '_enabled', true ) ) {
		$cc_mod_active++;
	}
}

/* ---- Card-Testing Defense (free metrics) ---- */
$cc_ct_state = 'IDLE';
$cc_held     = 0;
if ( class_exists( 'TrustLens_Lockdown_State' ) ) {
	$cc_lock     = new TrustLens_Lockdown_State();
	$cc_ct_state = strtoupper( (string) $cc_lock->current_state() );
	$cc_held     = count( $cc_lock->currently_targeted() );
}
$cc_decl = 0;
$cc_subs = 0;
$cc_vtbl = $wpdb->prefix . 'trustlens_velocity_events';
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $cc_vtbl ) ) === $cc_vtbl ) {
	$cc_decl = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$cc_vtbl} WHERE event_type = 'decline' AND created_at > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 24 HOUR)" );
	$cc_subs = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$cc_vtbl} WHERE event_type = 'submission' AND created_at > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 24 HOUR)" );
}
$cc_rate     = $cc_subs > 0 ? round( 100 * $cc_decl / $cc_subs, 1 ) : 0.0;
$cc_ct_clear = ( 'IDLE' === $cc_ct_state );

/* ---- Live activity feed (free) ---- */
$cc_etbl   = $wpdb->prefix . 'trustlens_events';
$cc_ctbl   = $wpdb->prefix . 'trustlens_customers';
$cc_events = $wpdb->get_results(
	"SELECT e.event_type, e.created_at, c.customer_email
	 FROM {$cc_etbl} e
	 LEFT JOIN {$cc_ctbl} c ON c.email_hash = e.email_hash
	 ORDER BY e.created_at DESC
	 LIMIT 7"
);
$cc_event_meta = array(
	'customer_blocked'          => array( 'ban',     __( 'blocked', 'trustlens' ),                 'block' ),
	'customer_unblocked'        => array( 'check',   __( 'unblocked', 'trustlens' ),               'allow' ),
	'customer_allowlisted'      => array( 'check',   __( 'allowlisted', 'trustlens' ),             'allow' ),
	'customer_allowlist_removed'=> array( 'refresh', __( 'removed from allowlist', 'trustlens' ),  'score' ),
	'dispute_created'           => array( 'card',    __( 'chargeback opened', 'trustlens' ),       'cb' ),
	'dispute_closed'            => array( 'card',    __( 'chargeback resolved', 'trustlens' ),      'cb' ),
	'automation_triggered'      => array( 'shield',  __( 'automation rule fired', 'trustlens' ),    'shield' ),
	'order_created'             => array( 'refresh', __( 'placed an order', 'trustlens' ),          'score' ),
);

/* ---- Trust trend series (rendered by Chart.js via command-center-charts.js) ---- */
$cc_series = array();
$cc_dates  = array();
if ( ! empty( $trends ) && is_array( $trends ) ) {
	foreach ( $trends as $cc_pt ) {
		if ( is_array( $cc_pt ) ) {
			foreach ( array( 'avg_score', 'score', 'value', 'y', 'average' ) as $cc_key ) {
				if ( isset( $cc_pt[ $cc_key ] ) && is_numeric( $cc_pt[ $cc_key ] ) ) {
					$cc_series[] = (float) $cc_pt[ $cc_key ];
					$cc_dates[]  = isset( $cc_pt['date'] ) ? (string) $cc_pt['date'] : '';
					break;
				}
			}
		} elseif ( is_numeric( $cc_pt ) ) {
			$cc_series[] = (float) $cc_pt;
			$cc_dates[]  = '';
		}
	}
}

// Need at least two points to draw a trend; below that we show the empty state.
$cc_has_trend  = count( $cc_series ) > 1;
// Payload consumed by command-center-charts.js (attached to each <canvas>).
// segment + score let the chart colour itself to the store's health and build
// an accessible label.
$cc_trend_json = wp_json_encode( array(
	'labels'  => $cc_dates,
	'values'  => $cc_series,
	'segment' => $health_segment,
	'score'   => $cc_score,
) );

/* ---- Segment stacked bar (free) ---- */
$cc_seg_order = array( 'vip', 'trusted', 'normal', 'caution', 'risk', 'critical' );
$cc_seg_total = (int) array_sum( $segment_counts );

/* Helper: a Pro upsell card body (promotional UI only). */
$cc_promo = static function ( string $title, string $blurb ) use ( $cc_upgrade ) {
	?>
	<div class="tlcc-promo">
		<span class="tlcc-promo-badge"><?php esc_html_e( 'Pro', 'trustlens' ); ?></span>
		<p class="tlcc-promo-title"><?php echo esc_html( $title ); ?></p>
		<p class="tlcc-promo-blurb"><?php echo esc_html( $blurb ); ?></p>
		<a class="tlcc-promo-btn" href="<?php echo esc_url( $cc_upgrade ); ?>" target="_blank" rel="noopener">
			<?php esc_html_e( 'Upgrade to Pro', 'trustlens' ); ?>
		</a>
	</div>
	<?php
};

/* Helper: a subtle "go to settings/page" chevron link for a card header. */
$cc_headlink = static function ( string $url, string $label ) {
	?>
	<a class="tlcc-headlink" href="<?php echo esc_url( $url ); ?>" aria-label="<?php echo esc_attr( $label ); ?>" title="<?php echo esc_attr( $label ); ?>">
		<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false"><path d="M6 3l5 5-5 5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
	</a>
	<?php
};
?>

<div class="tlcc">

	<!-- status bar -->
	<div class="tlcc-statusbar">
		<div class="tlcc-name"><?php esc_html_e( 'Command Center', 'trustlens' ); ?></div>
		<?php
		$cc_threat_seg = $cc_crit > 0 ? 'critical' : ( $cc_riskn > 0 ? 'risk' : '' );
		$cc_threat_url = $cc_threat_seg
			? admin_url( 'admin.php?page=trustlens-customers&segment=' . $cc_threat_seg )
			: admin_url( 'admin.php?page=trustlens-customers' );
		/* translators: 1: critical count, 2: risk count. */
		$cc_threat_tip = sprintf( __( '%1$d critical · %2$d risk — view high-risk customers', 'trustlens' ), (int) $cc_crit, (int) $cc_riskn );
		?>
		<div class="tlcc-threat">
			<a class="tlcc-threatlink" href="<?php echo esc_url( $cc_threat_url ); ?>" title="<?php echo esc_attr( $cc_threat_tip ); ?>">
				<?php esc_html_e( 'Threat level', 'trustlens' ); ?>
				<span class="tlcc-lvl tlcc-<?php echo esc_attr( $cc_threat_cls ); ?>"><?php echo esc_html( $cc_threat ); ?></span>
			</a>
		</div>
		<div class="tlcc-meta"><span class="tlcc-livedot"></span><?php esc_html_e( 'Core systems nominal', 'trustlens' ); ?> · <span id="tlcc-clock">--:--:--</span></div>
		<div class="tlcc-sp"></div>
		<?php if ( isset( $sync_status ) && 'running' === $sync_status['status'] ) : ?>
			<span class="tlcc-syncing"><span class="tlcc-spin"></span><?php esc_html_e( 'Importing orders…', 'trustlens' ); ?></span>
		<?php endif; ?>
		<a class="tlcc-meta tlcc-meta-link" href="<?php echo esc_url( admin_url( 'admin.php?page=trustlens-settings&tab=modules' ) ); ?>" title="<?php esc_attr_e( 'Module settings', 'trustlens' ); ?>">
			<?php
			/* translators: 1: active modules, 2: total modules */
			printf( esc_html__( '%1$d / %2$d modules active', 'trustlens' ), (int) $cc_mod_active, count( $cc_modules ) );
			?>
		</a>
		<a class="tlcc-refresh" href="<?php echo esc_url( admin_url( 'admin.php?page=trustlens' ) ); ?>" title="<?php esc_attr_e( 'Refresh dashboard', 'trustlens' ); ?>" aria-label="<?php esc_attr_e( 'Refresh dashboard', 'trustlens' ); ?>">
			<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true" focusable="false"><path d="M13.6 8a5.6 5.6 0 1 1-1.7-4M13.6 1.8v3.1h-3.1" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>
		</a>
		<a class="tlcc-panic" href="<?php echo esc_url( admin_url( 'admin.php?page=trustlens-card-testing#panic' ) ); ?>"><?php esc_html_e( 'Panic Freeze', 'trustlens' ); ?></a>
	</div>

	<div class="tlcc-grid">

		<!-- Trust Index -->
		<div class="tlcc-pnl tlcc-c3 tlcc-gauge tlcc-focal tlcc-seg-<?php echo esc_attr( $health_segment ); ?>">
			<div class="tlcc-ph" style="width:100%"><span class="tlcc-l"><span class="tlcc-ic tlcc-ic-shield"></span><?php esc_html_e( 'Trust Index', 'trustlens' ); ?></span><span class="tlcc-m"><?php printf( /* translators: %d: number of customers in the average */ esc_html__( 'avg · n=%d', 'trustlens' ), (int) $cc_seg_total ); ?></span></div>
			<div class="tlcc-gwrap">
				<svg viewBox="0 0 120 120" width="150" height="150">
					<circle class="tlcc-gtrack" cx="60" cy="60" r="52"></circle>
					<circle class="tlcc-gprog" cx="60" cy="60" r="52" style="stroke-dasharray:<?php echo esc_attr( $cc_dash ); ?>;--tlcc-off:<?php echo esc_attr( round( $cc_off, 1 ) ); ?>"></circle>
				</svg>
				<div class="tlcc-gtxt"><div><b data-count="<?php echo esc_attr( $cc_score ); ?>">0</b><small><?php esc_html_e( '/ 100', 'trustlens' ); ?></small></div></div>
			</div>
			<span class="tlcc-tier"><?php echo esc_html( strtoupper( $cc_tier ) ); ?></span>
			<?php if ( $cc_has_trend ) : ?>
				<div class="tlcc-titrend">
					<div class="tlcc-titrend-h"><span><?php esc_html_e( 'Trust trend', 'trustlens' ); ?></span><span class="tlcc-win"><?php esc_html_e( '30 days', 'trustlens' ); ?></span></div>
					<div class="tlcc-titrendwrap"><canvas class="tlcc-chart" data-tlcc-mode="full" data-tlcc-trend="<?php echo esc_attr( $cc_trend_json ); ?>"></canvas></div>
				</div>
			<?php endif; ?>
		</div>

		<!-- Live Telemetry -->
		<div class="tlcc-pnl tlcc-c5 tlcc-livetelem">
			<div class="tlcc-ph"><span class="tlcc-l"><span class="tlcc-ic tlcc-ic-up"></span><?php esc_html_e( 'Live Telemetry', 'trustlens' ); ?></span><span class="tlcc-m"><?php esc_html_e( 'live activity', 'trustlens' ); ?></span></div>
			<?php
			// Each tile is honestly windowed (24h / 7d / avg), carries a delta vs
			// the prior period where one exists, and gets an inline sparkline only
			// where a real hourly series is available (events, orders).
			$cc_t     = isset( $telemetry ) && is_array( $telemetry ) ? $telemetry : array();
			$cc_tiles = array(
				array(
					'label' => __( 'Events', 'trustlens' ),
					'win'   => '24h',
					'count' => (int) ( $cc_t['events']['value'] ?? ( $summary_stats['events_24h'] ?? 0 ) ),
					'delta' => isset( $cc_t['events'] ) ? (int) $cc_t['events']['value'] - (int) $cc_t['events']['prev'] : null,
					'pol'   => 'pos',
					'spark' => $cc_t['events']['spark'] ?? null,
				),
				array(
					'label' => __( 'Active', 'trustlens' ),
					'win'   => '24h',
					'count' => (int) ( $cc_t['active']['value'] ?? ( $summary_stats['active_customers_24h'] ?? 0 ) ),
					'delta' => isset( $cc_t['active'] ) ? (int) $cc_t['active']['value'] - (int) $cc_t['active']['prev'] : null,
					'pol'   => 'pos',
					'spark' => null,
				),
				array(
					'label' => __( 'Orders', 'trustlens' ),
					'win'   => '24h',
					'count' => (int) ( $cc_t['orders']['value'] ?? 0 ),
					'delta' => isset( $cc_t['orders'] ) ? (int) $cc_t['orders']['value'] - (int) $cc_t['orders']['prev'] : null,
					'pol'   => 'pos',
					'spark' => $cc_t['orders']['spark'] ?? null,
				),
				array(
					'label' => __( 'High-risk', 'trustlens' ),
					'win'   => '7d',
					'count' => (int) ( $cc_t['high_risk']['value'] ?? ( $summary_stats['new_high_risk_week'] ?? 0 ) ),
					'delta' => isset( $cc_t['high_risk'] ) ? (int) $cc_t['high_risk']['value'] - (int) $cc_t['high_risk']['prev'] : null,
					'pol'   => 'neg',
					'spark' => null,
					'flag'  => true,
				),
				array(
					'label'  => __( 'Return rate', 'trustlens' ),
					'win'    => __( 'avg', 'trustlens' ),
					'count'  => (float) ( $summary_stats['avg_return_rate'] ?? 0 ),
					'delta'  => null,
					'pol'    => 'pos',
					'spark'  => null,
					'suffix' => '%',
					'dec'    => 1,
				),
			);
			?>
			<div class="tlcc-telem">
				<?php
				foreach ( $cc_tiles as $cc_tile ) :
					$cc_d   = $cc_tile['delta'];
					$cc_dcl = 'flat';
					$cc_dtx = '';
					if ( null !== $cc_d && 0 !== $cc_d ) {
						$cc_up   = $cc_d > 0;
						$cc_good = ( 'neg' === $cc_tile['pol'] ) ? ! $cc_up : $cc_up;
						$cc_dcl  = $cc_good ? 'good' : 'bad';
						$cc_dtx  = ( $cc_up ? '▲ ' : '▼ ' ) . abs( $cc_d );
					}
					?>
					<div class="tlcc-k<?php echo ( ! empty( $cc_tile['flag'] ) && $cc_tile['count'] > 0 ) ? ' tlcc-flag' : ''; ?>">
						<small><?php echo esc_html( $cc_tile['label'] ); ?> <span class="tlcc-win"><?php echo esc_html( $cc_tile['win'] ); ?></span></small>
						<b data-count="<?php echo esc_attr( $cc_tile['count'] ); ?>"<?php echo isset( $cc_tile['dec'] ) ? ' data-dec="' . esc_attr( $cc_tile['dec'] ) . '"' : ''; ?><?php echo isset( $cc_tile['suffix'] ) ? ' data-suffix="' . esc_attr( $cc_tile['suffix'] ) . '"' : ''; ?>>0</b>
						<?php if ( '' !== $cc_dtx ) : ?>
							<span class="tlcc-delta tlcc-<?php echo esc_attr( $cc_dcl ); ?>"><?php echo esc_html( $cc_dtx ); ?></span>
						<?php elseif ( null !== $cc_d ) : ?>
							<span class="tlcc-delta tlcc-flat">&ndash;</span>
						<?php endif; ?>
					</div>
				<?php endforeach; ?>
				</div>
				<?php
				$cc_ev_spark = $cc_t['events']['spark'] ?? array();
				if ( is_array( $cc_ev_spark ) && array_sum( $cc_ev_spark ) > 0 ) :
					?>
					<div class="tlcc-strip">
						<div class="tlcc-strip-h"><span><?php esc_html_e( 'Activity', 'trustlens' ); ?></span><span class="tlcc-win"><?php esc_html_e( 'events · 24h', 'trustlens' ); ?></span></div>
						<div class="tlcc-stripwrap"><canvas class="tlcc-stripchart" data-tlcc-strip="<?php echo esc_attr( wp_json_encode( array_values( array_map( 'intval', $cc_ev_spark ) ) ) ); ?>" data-tlcc-color="#3377ee" data-tlcc-unit="events"></canvas></div>
					</div>
				<?php endif; ?>
			</div>

		<!-- Card-Testing Defense -->
		<div class="tlcc-pnl tlcc-c4">
			<div class="tlcc-ph"><span class="tlcc-l"><span class="tlcc-ic tlcc-ic-bolt"></span><?php esc_html_e( 'Card-Testing Defense', 'trustlens' ); ?></span>
				<span class="tlcc-state <?php echo $cc_ct_clear ? 'ok' : 'bad'; ?>"><span class="tlcc-livedot"></span><?php echo $cc_ct_clear ? esc_html__( 'Idle · all clear', 'trustlens' ) : esc_html( ucfirst( strtolower( $cc_ct_state ) ) ); ?></span>
				<?php $cc_headlink( admin_url( 'admin.php?page=trustlens-card-testing' ), __( 'Open Card-Testing Defense', 'trustlens' ) ); ?>
			</div>
			<div class="tlcc-mini">
				<div class="tlcc-t <?php echo $cc_decl > 50 ? 'bad' : ''; ?>"><b data-count="<?php echo esc_attr( $cc_decl ); ?>">0</b><small><?php esc_html_e( '24h declines', 'trustlens' ); ?></small></div>
				<div class="tlcc-t"><b data-count="<?php echo esc_attr( $cc_subs ); ?>">0</b><small><?php esc_html_e( '24h submissions', 'trustlens' ); ?></small></div>
				<div class="tlcc-t <?php echo $cc_rate > 30 ? 'warn' : ''; ?>"><b data-count="<?php echo esc_attr( $cc_rate ); ?>" data-dec="1" data-suffix="%">0</b><small><?php esc_html_e( 'Decline rate', 'trustlens' ); ?> <?php echo wstl_help_tip( __( 'Share of card attempts declined in the last 24 hours. Above ~30% usually signals an automated attack.', 'trustlens' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></small></div>
				<div class="tlcc-t"><b><?php echo esc_html( $cc_held ); ?></b><small><?php esc_html_e( 'Fingerprints held', 'trustlens' ); ?></small></div>
			</div>
			<?php if ( $cc_ct_intel && method_exists( 'TrustLens_Card_Testing_History_Query', 'count_declines_by_code' ) ) : ?>
				<div class="tlcc-ph" style="margin:2px 0 8px"><span class="tlcc-l"><?php esc_html_e( 'Decline codes · 24h', 'trustlens' ); ?></span></div>
				<div class="tlcc-codes">
					<?php
					$cc_codes = ( new TrustLens_Card_Testing_History_Query() )->count_declines_by_code( 24 );
					$cc_cmax   = $cc_codes ? max( array_map( 'intval', $cc_codes ) ) : 1;
					$cc_ctotal = array_sum( array_map( 'intval', $cc_codes ) );
					$cc_ci     = 0;
					foreach ( $cc_codes as $cc_code => $cc_cn ) :
						if ( $cc_ci++ >= 4 ) {
							break;
						}
						?>
						<div title="<?php echo esc_attr( sprintf( /* translators: 1: decline code, 2: number of declines, 3: percent of 24h declines */ __( '%1$s — %2$d declines (%3$d%% of 24h declines)', 'trustlens' ), $cc_code, (int) $cc_cn, $cc_ctotal > 0 ? (int) round( 100 * (int) $cc_cn / $cc_ctotal ) : 0 ) ); ?>"><span class="nm"><?php echo esc_html( $cc_code ); ?></span><span class="bar"><span style="width:<?php echo esc_attr( round( 100 * (int) $cc_cn / max( 1, $cc_cmax ) ) ); ?>%"></span></span><b><?php echo esc_html( (int) $cc_cn ); ?></b></div>
					<?php endforeach; ?>
				</div>
			<?php else : ?>
				<div class="tlcc-promo tlcc-promo-inline">
					<span class="tlcc-promo-badge"><?php esc_html_e( 'Pro', 'trustlens' ); ?></span>
					<span><?php esc_html_e( 'Attack intelligence — decline-code breakdown & timeline', 'trustlens' ); ?></span>
					<a href="<?php echo esc_url( $cc_upgrade ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Pro', 'trustlens' ); ?> &rarr;</a>
				</div>
			<?php endif; ?>
		</div>

		<!-- Priority Targets -->
		<div class="tlcc-pnl tlcc-c7">
			<div class="tlcc-ph"><span class="tlcc-l"><span class="tlcc-ic tlcc-ic-alert"></span><?php esc_html_e( 'Priority Targets · action required', 'trustlens' ); ?></span><span class="tlcc-m bad"><?php printf( /* translators: %d: number of high-risk customers */ esc_html__( '%d high-risk', 'trustlens' ), (int) $cc_riskn ); ?></span>
			<?php $cc_headlink( admin_url( 'admin.php?page=trustlens-customers' ), /* translators: link to the full customers list */ __( 'View all customers', 'trustlens' ) ); ?></div>
			<?php if ( empty( $high_risk_customers ) ) : ?>
				<p class="tlcc-empty"><?php esc_html_e( 'No high-risk customers right now. Your store is looking good.', 'trustlens' ); ?></p>
			<?php else : ?>
			<table class="tlcc-att">
				<thead><tr><th class="tlcc-rank-h"></th><th><?php esc_html_e( 'Customer', 'trustlens' ); ?></th><th><?php esc_html_e( 'Segment', 'trustlens' ); ?></th><th><?php esc_html_e( 'Score', 'trustlens' ); ?></th><th><?php esc_html_e( 'Return', 'trustlens' ); ?></th><th></th></tr></thead>
				<tbody>
					<?php foreach ( array_slice( $high_risk_customers, 0, 5 ) as $cc_idx => $cc_cust ) : ?>
						<tr class="tlcc-clickable" tabindex="0" role="link" aria-label="<?php echo esc_attr( sprintf( /* translators: %s: customer email or "guest" */ __( 'Review %s', 'trustlens' ), ( $cc_cust->customer_email ?: __( 'guest', 'trustlens' ) ) ) ); ?>" data-href="<?php echo esc_url( admin_url( 'admin.php?page=trustlens-customers&customer=' . $cc_cust->email_hash ) ); ?>">
							<td class="tlcc-rank"><?php echo (int) $cc_idx + 1; ?></td>
							<td class="em"><?php echo esc_html( $cc_cust->customer_email ?: __( 'Guest', 'trustlens' ) ); ?></td>
							<td><span class="tlcc-badge" style="background:<?php echo esc_attr( wstl_get_segment_color( $cc_cust->segment ) ); ?>"><?php echo esc_html( wstl_get_segment_label( $cc_cust->segment ) ); ?></span></td>
							<td class="tlcc-sc" style="color:<?php echo esc_attr( wstl_get_segment_color( $cc_cust->segment ) ); ?>"><?php echo esc_html( (int) $cc_cust->trust_score ); ?></td>
							<td><?php echo esc_html( number_format( (float) $cc_cust->return_rate, 0 ) ); ?>%</td>
							<td><a class="tlcc-btn pri" href="<?php echo esc_url( admin_url( 'admin.php?page=trustlens-customers&customer=' . $cc_cust->email_hash ) ); ?>"><?php esc_html_e( 'Review', 'trustlens' ); ?></a></td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
			<?php endif; ?>
		</div>

		<!-- Chargeback Ratio Monitor (Pro) -->
		<div class="tlcc-pnl tlcc-c5">
			<div class="tlcc-ph"><span class="tlcc-l"><span class="tlcc-ic tlcc-ic-card"></span><?php esc_html_e( 'Chargeback Ratio Monitor', 'trustlens' ); ?></span><span class="tlcc-m"><?php echo $cc_charge ? esc_html__( 'live', 'trustlens' ) : esc_html__( 'Pro', 'trustlens' ); ?></span><?php $cc_headlink( admin_url( 'admin.php?page=trustlens-chargeback-monitor' ), __( 'Open Chargeback Monitor', 'trustlens' ) ); ?></div>
			<?php
			$cc_ratios = $cc_charge ? get_transient( 'trustlens_chargeback_ratios' ) : false;
			$cc_window = array();
			if ( is_array( $cc_ratios ) ) {
				if ( ! empty( $cc_ratios['calendar_month'] ) ) {
					$cc_window = $cc_ratios['calendar_month'];
				} elseif ( ! empty( $cc_ratios['trailing_30'] ) ) {
					$cc_window = $cc_ratios['trailing_30'];
				}
			}
			if ( $cc_charge && ! empty( $cc_window ) ) :
				$cc_blended_o = (int) ( $cc_window['blended']['orders'] ?? 0 );
				$cc_blended_d = (int) ( $cc_window['blended']['disputes'] ?? 0 );
				$cc_blended   = $cc_blended_o > 0 ? round( 100 * $cc_blended_d / $cc_blended_o, 2 ) : 0;
				$cc_brands    = ( isset( $cc_window['brands'] ) && is_array( $cc_window['brands'] ) ) ? $cc_window['brands'] : array();
				$cc_thr       = array( 'visa' => 0.65, 'mastercard' => 1.5, 'amex' => 1.0, 'discover' => 1.0 );
				?>
				<div style="display:flex;align-items:baseline;gap:10px">
					<span class="tlcc-cbnum"><?php echo esc_html( number_format( $cc_blended, 2 ) ); ?>%<small> <?php esc_html_e( 'blended', 'trustlens' ); ?></small></span>
					<span style="margin-left:auto;font-size:11px;color:var(--tlcc-muted)" class="tlcc-mono"><?php printf( /* translators: 1: order count, 2: dispute count */ esc_html__( '%1$s orders · %2$s disputes', 'trustlens' ), esc_html( number_format_i18n( $cc_blended_o ) ), esc_html( number_format_i18n( $cc_blended_d ) ) ); ?></span>
				</div>
				<div class="tlcc-net">
					<?php
					$cc_shown = 0;
					foreach ( $cc_brands as $cc_brow ) :
						if ( $cc_shown >= 3 ) {
							break;
						}
						$cc_nk = (string) ( $cc_brow['brand'] ?? '' );
						$cc_no = (int) ( $cc_brow['orders'] ?? 0 );
						$cc_nd = (int) ( $cc_brow['disputes'] ?? 0 );
						if ( $cc_no <= 0 ) {
							continue;
						}
						$cc_shown++;
						$cc_nr   = 100 * $cc_nd / $cc_no;
						$cc_nt   = $cc_thr[ $cc_nk ] ?? 1.0;
						$cc_fill = min( 100, $cc_nt > 0 ? ( $cc_nr / $cc_nt * 88 ) : 0 );
						$cc_near = $cc_nr >= $cc_nt * 0.7;
						?>
						<div class="tlcc-row <?php echo $cc_near ? 'warn' : 'ok'; ?>" title="<?php echo esc_attr( sprintf( /* translators: 1: card brand, 2: percentage-point gap, 3: "under" or "over", 4: threshold percent */ __( '%1$s — %2$s%% %3$s the %4$s%% fine line', 'trustlens' ), ucfirst( $cc_nk ), number_format( abs( $cc_nt - $cc_nr ), 2 ), ( $cc_nt - $cc_nr ) >= 0 ? __( 'under', 'trustlens' ) : __( 'over', 'trustlens' ), number_format( $cc_nt, 2 ) ) ); ?>">
							<div class="top"><span class="nm"><?php echo esc_html( ucfirst( $cc_nk ) ); ?></span><span class="val tlcc-mono"><?php echo esc_html( number_format( $cc_nr, 2 ) ); ?>% · <?php echo esc_html( $cc_nd . '/' . $cc_no ); ?></span></div>
							<div class="track"><span class="thr" style="left:80%"></span><span class="fill" style="width:<?php echo esc_attr( round( $cc_fill ) ); ?>%"></span></div>
						</div>
					<?php endforeach; ?>
				</div>
				<?php
				// 12-month blended ratio trend vs the Visa fine line, so the card
				// shows trajectory, not just today's snapshot.
				if ( class_exists( 'TrustLens_Chargeback_Monitor' ) ) :
					$cc_cb_trend  = ( new TrustLens_Chargeback_Monitor() )->get_trend( 12 );
					$cc_cb_labels = array();
					$cc_cb_values = array();
					foreach ( (array) $cc_cb_trend as $cc_tp ) {
						if ( ! is_array( $cc_tp ) || ! isset( $cc_tp['month'] ) ) {
							continue;
						}
						$cc_cb_labels[] = gmdate( 'M', (int) strtotime( $cc_tp['month'] . '-01' ) );
						$cc_cb_values[] = round( ( (float) ( $cc_tp['ratio'] ?? 0 ) ) * 100, 3 );
					}
					if ( count( $cc_cb_values ) > 1 ) :
						?>
						<div class="tlcc-strip">
							<div class="tlcc-strip-h"><span><?php esc_html_e( 'Ratio trend', 'trustlens' ); ?></span><span class="tlcc-win"><?php esc_html_e( '12 mo · vs Visa 0.65%', 'trustlens' ); ?></span></div>
							<div class="tlcc-cbtrendwrap"><canvas class="tlcc-cbtrend" data-tlcc-cbtrend="<?php echo esc_attr( wp_json_encode( array( 'labels' => $cc_cb_labels, 'values' => $cc_cb_values, 'threshold' => 0.65 ) ) ); ?>"></canvas></div>
						</div>
						<?php
					endif;
				endif;
				?>
			<?php else : ?>
				<?php $cc_promo( __( 'Card-network chargeback monitoring', 'trustlens' ), __( 'Track your Visa, Mastercard & Amex dispute ratios against each network’s fraud-program thresholds — before they fine you.', 'trustlens' ) ); ?>
			<?php endif; ?>
		</div>

		<!-- Customer Segments -->
		<div class="tlcc-pnl tlcc-c6">
			<div class="tlcc-ph"><span class="tlcc-l"><span class="tlcc-ic tlcc-ic-users"></span><?php esc_html_e( 'Customer Segments', 'trustlens' ); ?></span><span class="tlcc-m"><?php printf( /* translators: %d: number of scored customers */ esc_html__( '%d scored', 'trustlens' ), (int) $cc_seg_total ); ?></span>
			<?php $cc_headlink( admin_url( 'admin.php?page=trustlens-customers' ), /* translators: link to the full customers list */ __( 'View all customers', 'trustlens' ) ); ?></div>
			<div class="tlcc-stack">
				<?php
				foreach ( $cc_seg_order as $cc_seg ) :
					$cc_cnt = (int) ( $segment_counts[ $cc_seg ] ?? 0 );
					$cc_pct = $cc_seg_total > 0 ? ( $cc_cnt / $cc_seg_total * 100 ) : 0;
					if ( $cc_pct <= 0 ) {
						continue;
					}
					?>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=trustlens-customers&segment=' . $cc_seg ) ); ?>" aria-label="<?php echo esc_attr( sprintf( /* translators: 1: segment name, 2: number of customers */ __( '%1$s segment, %2$d customers', 'trustlens' ), wstl_get_segment_label( $cc_seg ), $cc_cnt ) ); ?>" title="<?php echo esc_attr( wstl_get_segment_label( $cc_seg ) . ' · ' . $cc_cnt . ' · ' . round( $cc_pct ) . '%' ); ?>" style="width:<?php echo esc_attr( round( $cc_pct, 2 ) ); ?>%;background:<?php echo esc_attr( wstl_get_segment_color( $cc_seg ) ); ?>"></a>
				<?php endforeach; ?>
			</div>
			<div class="tlcc-leg">
				<?php foreach ( $cc_seg_order as $cc_seg ) : ?>
					<a class="tlcc-leg-link" href="<?php echo esc_url( admin_url( 'admin.php?page=trustlens-customers&segment=' . $cc_seg ) ); ?>"><i style="background:<?php echo esc_attr( wstl_get_segment_color( $cc_seg ) ); ?>"></i><?php echo esc_html( wstl_get_segment_label( $cc_seg ) ); ?> <b><?php echo esc_html( (int) ( $segment_counts[ $cc_seg ] ?? 0 ) ); ?></b></a>
				<?php endforeach; ?>
			</div>
		</div>

		<!-- Top Attacker Fingerprints (Pro) -->
		<div class="tlcc-pnl tlcc-c6">
			<div class="tlcc-ph"><span class="tlcc-l"><span class="tlcc-ic tlcc-ic-fingerprint"></span><?php esc_html_e( 'Top Attacker Fingerprints', 'trustlens' ); ?></span><span class="tlcc-m"><?php echo $cc_ct_intel ? esc_html__( '24h', 'trustlens' ) : esc_html__( 'Pro', 'trustlens' ); ?></span><?php $cc_headlink( admin_url( 'admin.php?page=trustlens-card-testing' ), __( 'Open Card-Testing Defense', 'trustlens' ) ); ?></div>
			<?php if ( $cc_ct_intel && method_exists( 'TrustLens_Card_Testing_History_Query', 'top_fingerprints_by_declines' ) ) : ?>
				<?php $cc_fps = ( new TrustLens_Card_Testing_History_Query() )->top_fingerprints_by_declines( 24, 5 ); ?>
				<?php if ( empty( $cc_fps ) ) : ?>
					<p class="tlcc-empty"><?php esc_html_e( 'No attacker fingerprints in the last 24 hours.', 'trustlens' ); ?></p>
				<?php else : ?>
				<div class="tlcc-fps">
					<?php foreach ( $cc_fps as $cc_fp ) : ?>
						<div><span class="hash tlcc-mono"><?php echo esc_html( substr( (string) ( $cc_fp->fingerprint_hash ?? '' ), 0, 12 ) ); ?></span><span class="cnt"><?php echo esc_html( (int) ( $cc_fp->decline_count ?? 0 ) ); ?></span></div>
					<?php endforeach; ?>
				</div>
				<?php endif; ?>
			<?php else : ?>
				<?php $cc_promo( __( 'Attacker fingerprint tracking', 'trustlens' ), __( 'See which devices are hammering your checkout, their decline counts and geography — and allowlist or hold them.', 'trustlens' ) ); ?>
			<?php endif; ?>
		</div>

		<!-- Live Activity -->
		<div class="tlcc-pnl tlcc-c5">
			<div class="tlcc-ph"><span class="tlcc-l"><span class="tlcc-ic tlcc-ic-clock"></span><?php esc_html_e( 'Live Activity', 'trustlens' ); ?></span><span class="tlcc-m"><span class="tlcc-livedot" style="margin-right:5px;display:inline-block;vertical-align:middle"></span><?php esc_html_e( 'recent', 'trustlens' ); ?></span>
			<?php $cc_headlink( admin_url( 'admin.php?page=trustlens-customers' ), /* translators: link to the full customers list */ __( 'View all customers', 'trustlens' ) ); ?></div>
			<?php if ( empty( $cc_events ) ) : ?>
				<p class="tlcc-empty"><?php esc_html_e( 'No recent activity recorded yet.', 'trustlens' ); ?></p>
			<?php else : ?>
			<div class="tlcc-feed">
				<?php
				foreach ( $cc_events as $cc_ev ) :
					$cc_meta = $cc_event_meta[ $cc_ev->event_type ] ?? array( 'refresh', str_replace( '_', ' ', $cc_ev->event_type ), 'score' );
					$cc_who  = $cc_ev->customer_email ? strstr( $cc_ev->customer_email, '@', true ) : __( 'A customer', 'trustlens' );
					$cc_ago  = human_time_diff( strtotime( $cc_ev->created_at . ' UTC' ), time() );
					?>
					<div class="e">
						<div class="ic-tile t-<?php echo esc_attr( $cc_meta[2] ); ?>"><span class="tlcc-ic tlcc-ic-<?php echo esc_attr( $cc_meta[0] ); ?>"></span></div>
						<div class="tx"><b><?php echo esc_html( $cc_who ); ?></b> <?php echo esc_html( $cc_meta[1] ); ?></div>
						<span class="ago"><?php echo esc_html( $cc_ago ); ?></span>
					</div>
				<?php endforeach; ?>
			</div>
			<?php endif; ?>
		</div>

		<!-- Detection Modules -->
		<div class="tlcc-pnl tlcc-c3">
			<div class="tlcc-ph"><span class="tlcc-l"><span class="tlcc-ic tlcc-ic-grid"></span><?php esc_html_e( 'Detection Modules', 'trustlens' ); ?></span><span class="tlcc-m ok"><?php echo esc_html( $cc_mod_active . ' / ' . count( $cc_modules ) ); ?></span><?php $cc_headlink( admin_url( 'admin.php?page=trustlens-settings&tab=modules' ), __( 'Module settings', 'trustlens' ) ); ?></div>
			<div class="tlcc-mods">
				<?php foreach ( $cc_modules as $cc_mk => $cc_ml ) : $cc_on = (bool) get_option( 'trustlens_module_' . $cc_mk . '_enabled', true ); ?>
					<div><span class="dot <?php echo $cc_on ? '' : 'off'; ?>"></span><span class="nm"><?php echo esc_html( $cc_ml ); ?></span><span class="st"><?php echo $cc_on ? esc_html__( 'On', 'trustlens' ) : esc_html__( 'Off', 'trustlens' ); ?></span></div>
				<?php endforeach; ?>
			</div>
		</div>

		<!-- Automation (Pro) -->
		<div class="tlcc-pnl tlcc-c4 tlcc-autocard">
			<div class="tlcc-ph"><span class="tlcc-l"><span class="tlcc-ic tlcc-ic-bolt"></span><?php esc_html_e( 'Automation', 'trustlens' ); ?></span><span class="tlcc-m"><?php echo $cc_auto ? esc_html__( 'active', 'trustlens' ) : esc_html__( 'Pro', 'trustlens' ); ?></span></div>
			<?php if ( $cc_auto ) : ?>
				<?php
				$cc_active_rules = array();
				foreach ( (array) get_option( 'trustlens_automation_rules', array() ) as $cc_ar ) {
					if ( ! empty( $cc_ar['enabled'] ) ) {
						$cc_active_rules[] = array(
							'id'    => (string) ( $cc_ar['id'] ?? '' ),
							'name'  => (string) ( $cc_ar['name'] ?? __( 'Untitled rule', 'trustlens' ) ),
							'fires' => 0,
						);
					}
				}
				$cc_auto_active = count( $cc_active_rules );
				$cc_auto_sum    = array( 'fires_today' => 0, 'errors_today' => 0, 'fires_24h' => 0 );
				$cc_rule_fires  = array();
				if ( class_exists( 'TrustLens_Automation_Log_Query' ) ) {
					$cc_alq        = new TrustLens_Automation_Log_Query();
					$cc_auto_sum   = $cc_alq->get_global_summary();
					$cc_rule_fires = $cc_auto_active > 0 ? $cc_alq->get_summary_by_rule( 7 ) : array();
				}
				foreach ( $cc_active_rules as &$cc_arr ) {
					$cc_arr['fires'] = (int) ( $cc_rule_fires[ $cc_arr['id'] ]['fires'] ?? 0 );
				}
				unset( $cc_arr );
				usort( $cc_active_rules, static function ( $a, $b ) { return $b['fires'] <=> $a['fires']; } );
				?>
				<?php if ( $cc_auto_active > 0 ) : ?>
					<div class="tlcc-mini">
						<div class="tlcc-t"><b data-count="<?php echo esc_attr( $cc_auto_active ); ?>">0</b><small><?php esc_html_e( 'Active rules', 'trustlens' ); ?></small></div>
						<div class="tlcc-t"><b data-count="<?php echo esc_attr( (int) $cc_auto_sum['fires_today'] ); ?>">0</b><small><?php esc_html_e( 'Fired today', 'trustlens' ); ?></small></div>
					</div>
					<div class="tlcc-rulelist">
						<?php foreach ( array_slice( $cc_active_rules, 0, 4 ) as $cc_arr ) : ?>
							<div class="tlcc-rulerow"><span class="nm"><?php echo esc_html( $cc_arr['name'] ); ?></span><span class="ct"><?php printf( esc_html( /* translators: %d: number of times the rule fired */ _n( '%d fire', '%d fires', $cc_arr['fires'], 'trustlens' ) ), (int) $cc_arr['fires'] ); ?></span></div>
						<?php endforeach; ?>
						<?php if ( $cc_auto_active > 4 ) : ?>
							<div class="tlcc-rulerow tlcc-rulemore"><?php printf( /* translators: %d: number of additional rules not shown */ esc_html__( '+%d more', 'trustlens' ), (int) ( $cc_auto_active - 4 ) ); ?></div>
						<?php endif; ?>
					</div>
					<p class="tlcc-autometa tlcc-mono">
						<span><?php echo esc_html( number_format_i18n( (int) $cc_auto_sum['fires_24h'] ) ); ?></span> <?php esc_html_e( 'fired · 24h', 'trustlens' ); ?>
						<?php if ( (int) $cc_auto_sum['errors_today'] > 0 ) : ?>
							<span class="tlcc-err-chip"><?php printf( /* translators: %d: number of automation errors today */ esc_html__( '%d errors today', 'trustlens' ), (int) $cc_auto_sum['errors_today'] ); ?></span>
						<?php endif; ?>
					</p>
				<?php else : ?>
					<div class="tlcc-autoempty">
						<p><?php esc_html_e( 'No automation rules yet', 'trustlens' ); ?></p>
						<p class="sub"><?php esc_html_e( 'Create a rule to auto-notify, flag, or block customers the moment they turn risky — no manual watching.', 'trustlens' ); ?></p>
					</div>
				<?php endif; ?>
				<a class="tlcc-btn pri tlcc-autobtn" href="<?php echo esc_url( admin_url( 'admin.php?page=trustlens-automation' ) ); ?>"><?php echo $cc_auto_active > 0 ? esc_html__( 'Open Automation', 'trustlens' ) : esc_html__( 'Create a rule', 'trustlens' ); ?> &rarr;</a>
			<?php else : ?>
				<?php $cc_promo( __( 'Hands-off automation rules', 'trustlens' ), __( 'Auto-notify, flag or block when a customer turns Critical, a score drops, or chargebacks pile up — no manual watching.', 'trustlens' ) ); ?>
			<?php endif; ?>
		</div>

	</div>
</div>

<script>
( function () {
	var cc = document.querySelector( '.tlcc' );
	if ( ! cc ) { return; }
	var ccLocale = '<?php echo esc_js( str_replace( '_', '-', get_locale() ) ); ?>';
	requestAnimationFrame( function () { cc.classList.add( 'tlcc-booted' ); } );

	var reduce = window.matchMedia && window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;
	if ( ! reduce ) {
		var ease = function ( k ) { return 1 - Math.pow( 1 - k, 3 ); };
		cc.querySelectorAll( '[data-count]' ).forEach( function ( el ) {
			var target = parseFloat( el.getAttribute( 'data-count' ) ) || 0;
			var dec = parseInt( el.getAttribute( 'data-dec' ) || '0', 10 );
			var suf = el.getAttribute( 'data-suffix' ) || '';
			var dur = 1000, t0 = performance.now();
			function step( t ) {
				var k = Math.min( 1, ( t - t0 ) / dur ), v = target * ease( k );
				el.textContent = v.toLocaleString( ccLocale, { minimumFractionDigits: dec, maximumFractionDigits: dec } ) + suf;
				if ( k < 1 ) { requestAnimationFrame( step ); }
			}
			requestAnimationFrame( step );
		} );
	} else {
		cc.querySelectorAll( '[data-count]' ).forEach( function ( el ) {
			var dec = parseInt( el.getAttribute( 'data-dec' ) || '0', 10 );
			el.textContent = ( parseFloat( el.getAttribute( 'data-count' ) ) || 0 ).toLocaleString( ccLocale, { minimumFractionDigits: dec, maximumFractionDigits: dec } ) + ( el.getAttribute( 'data-suffix' ) || '' );
		} );
	}

	cc.querySelectorAll( '.tlcc-clickable' ).forEach( function ( row ) {
		var go = function ( e ) {
			if ( e.target.closest( 'a, button' ) ) { return; }
			var href = row.getAttribute( 'data-href' );
			if ( href ) { window.location.href = href; }
		};
		row.addEventListener( 'click', go );
		row.addEventListener( 'keydown', function ( e ) {
			if ( e.key === 'Enter' ) { e.preventDefault(); go( e ); }
		} );
	} );

	var clk = document.getElementById( 'tlcc-clock' );
	if ( clk ) {
		var tick = function () { clk.textContent = new Date().toTimeString().slice( 0, 8 ); };
		tick(); setInterval( tick, 1000 );
	}
} )();
</script>

<?php
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
