<?php
/**
 * Customer detail page template — Analyst Grid redesign.
 *
 * @package TrustLens\Admin\Views
 * @since   1.2.1
 */

defined( 'ABSPATH' ) || exit;

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

/*
 * Template variables passed in by TrustLens_Admin_Pages::render_customer_detail_page():
 *
 * @var object                     $customer         Customer row from trustlens_customers.
 * @var array                      $signals          Signal rows from trustlens_signals.
 * @var array                      $events           Up to 20 event rows from trustlens_events.
 * @var string                     $email_hash       Normalized customer email hash.
 * @var array                      $trend_data       12-week return rate trend (see Customer_Repository).
 * @var float                      $avg_return_rate  Site-wide average return rate.
 */

$segment_label = wstl_get_segment_label( $customer->segment );

/**
 * Render an inline SVG semicircular gauge for the trust score.
 *
 * @param int    $score Score 0–100.
 * @param string $color Fill color (hex).
 * @return string Escaped SVG markup.
 */
$wstl_cd_render_gauge = static function ( int $score, string $color ): string {
	$score     = max( 0, min( 100, $score ) );
	$angle_deg = 180 - ( $score * 1.8 );          // 180° = score 0 (left), 0° = score 100 (right)
	$angle_rad = deg2rad( $angle_deg );
	$cx        = 110.0;
	$cy        = 110.0;
	$r         = 90.0;
	$nr        = 60.0;                             // needle length
	$end_x     = $cx + $r * cos( $angle_rad );
	$end_y     = $cy - $r * sin( $angle_rad );
	$nx        = $cx + $nr * cos( $angle_rad );
	$ny        = $cy - $nr * sin( $angle_rad );
	$fmt       = static fn( float $n ): string => number_format( $n, 2, '.', '' );

	ob_start();
	?>
	<svg viewBox="0 0 220 130" class="wstl-cd-gauge-svg" role="img" aria-hidden="true">
		<path d="M 20 110 A 90 90 0 0 1 200 110" class="wstl-cd-gauge-bg"/>
		<path d="M 20 110 A 90 90 0 0 1 <?php echo esc_attr( $fmt( $end_x ) ); ?> <?php echo esc_attr( $fmt( $end_y ) ); ?>"
		      class="wstl-cd-gauge-fill" stroke="<?php echo esc_attr( $color ); ?>"/>
		<line x1="110" y1="110"
		      x2="<?php echo esc_attr( $fmt( $nx ) ); ?>"
		      y2="<?php echo esc_attr( $fmt( $ny ) ); ?>"
		      class="wstl-cd-gauge-needle"/>
		<circle cx="110" cy="110" r="6" class="wstl-cd-gauge-hub"/>
	</svg>
	<?php
	return (string) ob_get_clean();
};

/**
 * Render an inline SVG area chart for the 12-week return rate trend.
 *
 * @param array $trend Weekly trend array from Customer_Repository::get_return_rate_trend().
 * @return string Escaped SVG markup, or an empty-state <p> element.
 */
$wstl_cd_render_trend = static function ( array $trend ): string {
	$non_null = 0;
	foreach ( $trend as $w ) {
		if ( null !== $w['rate'] ) {
			$non_null++;
		}
	}

	if ( $non_null < 2 ) {
		return '<p class="wstl-cd-empty">' . esc_html__( 'Not enough history yet.', 'trustlens' ) . '</p>';
	}

	$width          = 320.0;
	$height         = 140.0;
	$padding_top    = 10.0;
	$padding_bottom = 20.0;
	$plot_h         = $height - $padding_top - $padding_bottom;
	$count          = max( 1, count( $trend ) - 1 );
	$fmt            = static fn( float $n ): string => number_format( $n, 1, '.', '' );

	// Seed $last_rate from the first non-null entry so leading null weeks
	// don't spike from 0% up to the first real data point.
	$last_rate = 0.0;
	foreach ( $trend as $w ) {
		if ( null !== $w['rate'] ) {
			$last_rate = (float) $w['rate'];
			break;
		}
	}

	// Build point list, carrying the previous value forward across null weeks
	// (simple interpolation — keeps the line continuous).
	$points = array();
	foreach ( $trend as $i => $w ) {
		$rate      = null === $w['rate'] ? $last_rate : (float) $w['rate'];
		$last_rate = $rate;
		$x         = ( $i / $count ) * $width;
		$y         = $padding_top + ( 1 - ( min( 100.0, $rate ) / 100.0 ) ) * $plot_h;
		$points[]  = $fmt( $x ) . ',' . $fmt( $y );
	}

	$polyline  = implode( ' ', $points );
	$area_path = 'M ' . $fmt( 0 ) . ' ' . $fmt( $padding_top + $plot_h )
		. ' L ' . implode( ' L ', $points )
		. ' L ' . $fmt( $width ) . ' ' . $fmt( $padding_top + $plot_h ) . ' Z';

	$guide_y_25 = $fmt( $padding_top + $plot_h * 0.75 ); // 25% line (inverted because y grows down)
	$guide_y_50 = $fmt( $padding_top + $plot_h * 0.50 ); // 50% line
	$guide_y_75 = $fmt( $padding_top + $plot_h * 0.25 ); // 75% line

	ob_start();
	?>
	<svg viewBox="0 0 <?php echo esc_attr( (string) $width ); ?> <?php echo esc_attr( (string) $height ); ?>"
	     class="wstl-cd-trend-svg" role="img" aria-hidden="true" preserveAspectRatio="none">
		<defs>
			<linearGradient id="wstl-cd-trend-grad" x1="0" y1="0" x2="0" y2="1">
				<stop offset="0%" stop-color="#dc2626" stop-opacity="0.3"/>
				<stop offset="100%" stop-color="#dc2626" stop-opacity="0"/>
			</linearGradient>
		</defs>
		<line x1="0" y1="<?php echo esc_attr( $guide_y_25 ); ?>" x2="<?php echo esc_attr( (string) $width ); ?>" y2="<?php echo esc_attr( $guide_y_25 ); ?>" class="wstl-cd-trend-guide"/>
		<line x1="0" y1="<?php echo esc_attr( $guide_y_50 ); ?>" x2="<?php echo esc_attr( (string) $width ); ?>" y2="<?php echo esc_attr( $guide_y_50 ); ?>" class="wstl-cd-trend-guide"/>
		<line x1="0" y1="<?php echo esc_attr( $guide_y_75 ); ?>" x2="<?php echo esc_attr( (string) $width ); ?>" y2="<?php echo esc_attr( $guide_y_75 ); ?>" class="wstl-cd-trend-guide"/>
		<path d="<?php echo esc_attr( $area_path ); ?>" fill="url(#wstl-cd-trend-grad)"/>
		<polyline points="<?php echo esc_attr( $polyline ); ?>" class="wstl-cd-trend-line"/>
	</svg>
	<?php
	return (string) ob_get_clean();
};
?>

<div class="wrap wstl-wrap">
	<?php
	/* =================== Page bar: identity, status, actions =================== */
	$cd_level_map = array(
		'vip'      => 'good',
		'trusted'  => 'good',
		'normal'   => 'info',
		'caution'  => 'warn',
		'risk'     => 'danger',
		'critical' => 'danger',
	);
	$cd_chips = array(
		array(
			'type'  => 'state',
			'level' => isset( $cd_level_map[ $customer->segment ] ) ? $cd_level_map[ $customer->segment ] : 'info',
			'value' => $segment_label,
		),
	);
	if ( $customer->is_blocked ) {
		$cd_chips[] = array( 'type' => 'state', 'level' => 'danger', 'value' => __( 'Blocked', 'trustlens' ), 'key' => 'blocked' );
	}
	if ( $customer->is_allowlisted ) {
		$cd_chips[] = array( 'type' => 'state', 'level' => 'good', 'value' => __( 'Allowlisted', 'trustlens' ), 'key' => 'allowlisted' );
	}
	if ( ! empty( $customer->is_flagged ) ) {
		$cd_chips[] = array( 'type' => 'state', 'level' => 'warn', 'value' => __( 'Flagged for review', 'trustlens' ), 'key' => 'flagged' );
	}

	ob_start();
	?>
	<a class="button" href="<?php echo esc_url( admin_url( 'admin.php?page=trustlens-customers' ) ); ?>">&lsaquo; <?php esc_html_e( 'Back', 'trustlens' ); ?></a>
	<?php if ( $customer->is_blocked ) : ?>
		<button type="button" class="button button-primary wstl-action-unblock" data-hash="<?php echo esc_attr( $customer->email_hash ); ?>"><?php esc_html_e( 'Unblock', 'trustlens' ); ?></button>
	<?php else : ?>
		<button type="button" class="button button-primary wstl-action-block" data-hash="<?php echo esc_attr( $customer->email_hash ); ?>"><?php esc_html_e( 'Block customer', 'trustlens' ); ?></button>
	<?php endif; ?>
	<?php if ( $customer->is_allowlisted ) : ?>
		<button type="button" class="button wstl-action-remove-allowlist" data-hash="<?php echo esc_attr( $customer->email_hash ); ?>"><?php esc_html_e( 'Remove from allowlist', 'trustlens' ); ?></button>
	<?php else : ?>
		<button type="button" class="button wstl-action-allowlist" data-hash="<?php echo esc_attr( $customer->email_hash ); ?>"><?php esc_html_e( 'Add to allowlist', 'trustlens' ); ?></button>
	<?php endif; ?>
	<?php if ( ! empty( $customer->is_flagged ) ) : ?>
			<button type="button" class="button wstl-action-unflag" data-hash="<?php echo esc_attr( $customer->email_hash ); ?>"><?php esc_html_e( 'Clear review flag', 'trustlens' ); ?></button>
		<?php endif; ?>
		<button type="button" class="button wstl-action-recalculate" data-hash="<?php echo esc_attr( $customer->email_hash ); ?>"><?php esc_html_e( 'Recalculate', 'trustlens' ); ?></button>
	<?php if ( $customer->customer_id ) : ?>
		<a class="button" href="<?php echo esc_url( admin_url( 'user-edit.php?user_id=' . $customer->customer_id ) ); ?>"><?php esc_html_e( 'View user', 'trustlens' ); ?></a>
	<?php endif; ?>
	<?php
	/**
	 * Fires after the core customer profile action buttons.
	 *
	 * @since 1.2.0
	 * @param object $customer Customer object.
	 */
	do_action( 'trustlens/customer_profile_actions', $customer );
	$cd_actions = ob_get_clean();

	wstl_render_page_header( array(
		'title'    => $customer->customer_email ? $customer->customer_email : __( 'Guest customer', 'trustlens' ),
		'meta'     => $cd_chips,
		'actions'  => $cd_actions,
	) );
	?>
	<hr class="wp-header-end">

	<div class="wstl-customer-detail">

		<?php /* =================== Zone 2: KPI row =================== */ ?>
		<?php
		$return_rate        = (float) $customer->return_rate;
		$return_rate_delta  = null;
		if ( (int) $customer->total_orders > 0 && $avg_return_rate > 0 ) {
			$return_rate_delta = $return_rate - $avg_return_rate;
		}
		$cancelled_pct = (int) $customer->total_orders > 0
			? round( ( (int) $customer->cancelled_orders / (int) $customer->total_orders ) * 100 )
			: 0;
		$is_high_rate  = $return_rate >= 40;
		$is_low_score  = (int) $customer->trust_score < 50;
		?>
		<div class="wstl-cd-kpis">

			<div class="wstl-cd-kpi">
				<p class="wstl-cd-kpi-label"><?php esc_html_e( 'Orders', 'trustlens' ); ?></p>
				<p class="wstl-cd-kpi-value"><?php echo esc_html( number_format( (int) $customer->total_orders ) ); ?></p>
				<p class="wstl-cd-kpi-sub">
					<?php
					printf(
						/* translators: %s: formatted price HTML */
						wp_kses_post( __( '%s total', 'trustlens' ) ),
						wp_kses_post( wc_price( $customer->total_order_value ) )
					);
					?>
				</p>
			</div>

			<div class="wstl-cd-kpi">
				<p class="wstl-cd-kpi-label"><?php esc_html_e( 'Return rate', 'trustlens' ); ?></p>
				<p class="wstl-cd-kpi-value <?php echo esc_attr( $is_high_rate ? 'is-danger' : '' ); ?>">
					<?php echo esc_html( number_format( $return_rate, 1 ) ); ?>%
				</p>
				<?php if ( null !== $return_rate_delta ) : ?>
					<p class="wstl-cd-kpi-delta <?php echo esc_attr( $return_rate_delta >= 0 ? 'is-up' : 'is-down' ); ?>">
						<?php
						printf(
							/* translators: %s: signed delta like "+12.3%" or "-4.1%" */
							esc_html__( '%s vs. avg', 'trustlens' ),
							esc_html( ( $return_rate_delta >= 0 ? '▲ ' : '▼ ' ) . number_format( abs( $return_rate_delta ), 1 ) . '%' )
						);
						?>
					</p>
				<?php else : ?>
					<p class="wstl-cd-kpi-sub"><?php esc_html_e( 'No orders yet', 'trustlens' ); ?></p>
				<?php endif; ?>
			</div>

			<div class="wstl-cd-kpi">
				<p class="wstl-cd-kpi-label"><?php esc_html_e( 'Refunded', 'trustlens' ); ?></p>
				<p class="wstl-cd-kpi-value"><?php echo wp_kses_post( wc_price( $customer->total_refund_value ) ); ?></p>
				<p class="wstl-cd-kpi-sub">
					<?php
					printf(
						/* translators: %s: number of refunds */
						esc_html( _n( '%s refund', '%s refunds', (int) $customer->total_refunds, 'trustlens' ) ),
						esc_html( number_format( (int) $customer->total_refunds ) )
					);
					?>
				</p>
			</div>

			<div class="wstl-cd-kpi">
				<p class="wstl-cd-kpi-label"><?php esc_html_e( 'Cancelled', 'trustlens' ); ?></p>
				<p class="wstl-cd-kpi-value"><?php echo esc_html( number_format( (int) $customer->cancelled_orders ) ); ?></p>
				<p class="wstl-cd-kpi-sub">
					<?php
					printf(
						/* translators: %d: percentage of orders cancelled */
						esc_html__( '%d%% of orders', 'trustlens' ),
						(int) $cancelled_pct
					);
					?>
				</p>
			</div>

			<div class="wstl-cd-kpi">
				<p class="wstl-cd-kpi-label"><?php esc_html_e( 'Trust score', 'trustlens' ); ?></p>
				<p class="wstl-cd-kpi-value <?php echo esc_attr( $is_low_score ? 'is-danger' : 'is-good' ); ?>">
					<?php echo esc_html( (int) $customer->trust_score ); ?>
				</p>
				<p class="wstl-cd-kpi-sub"><?php echo esc_html( $segment_label ); ?></p>
			</div>
		</div>

		<?php /* =================== Zone 3: Analytical tiles (Tasks 6–8) =================== */ ?>
		<div class="wstl-cd-charts">
			<div class="wstl-cd-tile">
				<h3><?php esc_html_e( 'Trust score', 'trustlens' ); ?></h3>
				<?php $segment_color = wstl_get_segment_color( $customer->segment ); ?>
				<div class="wstl-cd-gauge-wrap">
					<?php echo $wstl_cd_render_gauge( (int) $customer->trust_score, $segment_color ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG markup is pre-escaped in the closure. ?>
					<p class="wstl-cd-gauge-value"><?php echo esc_html( (int) $customer->trust_score ); ?></p>
					<p class="wstl-cd-gauge-label" style="color: <?php echo esc_attr( $segment_color ); ?>;">
						<?php echo esc_html( $segment_label ); ?>
					</p>
					<span class="screen-reader-text">
						<?php
						printf(
							/* translators: 1: numeric score, 2: segment label */
							esc_html__( 'Trust score %1$d out of 100, %2$s segment.', 'trustlens' ),
							(int) $customer->trust_score,
							esc_html( $segment_label )
						);
						?>
					</span>
				</div>
			</div>
			<?php if ( get_option( 'trustlens_module_linked_accounts_enabled', true ) ) : ?>
				<?php $links = TrustLens_Linked_Accounts::instance()->find_linked_accounts( $email_hash ); ?>
				<div class="wstl-cd-tile">
					<h3>
						<?php esc_html_e( 'Linked accounts', 'trustlens' ); ?>
						<?php if ( ! empty( $links ) ) : ?>
							&middot; <?php echo esc_html( count( $links ) ); ?>
						<?php endif; ?>
					</h3>
					<?php if ( empty( $links ) ) : ?>
						<p class="wstl-cd-empty"><?php esc_html_e( 'No linked accounts detected.', 'trustlens' ); ?></p>
					<?php else : ?>
						<div class="wstl-cd-linked">
							<?php foreach ( $links as $link ) :
								$linked_customer = wstl_get_customer( $link['email_hash'] );
								if ( ! $linked_customer ) {
									continue;
								}
								$link_color = wstl_get_segment_color( $linked_customer->segment );
								$is_risky   = in_array( $linked_customer->segment, array( 'risk', 'critical' ), true ) || $linked_customer->is_blocked;
								$type_labels = array(
									'device'      => __( 'Same device', 'trustlens' ),
									'ip'          => __( 'Same IP', 'trustlens' ),
									'fingerprint' => __( 'Same fingerprint', 'trustlens' ),
								);
								$type_names = array_map(
									static function ( $type ) use ( $type_labels ) {
										return $type_labels[ $type ] ?? ucfirst( $type );
									},
									$link['match_types']
								);
								?>
								<div class="wstl-cd-linked-item <?php echo esc_attr( $is_risky ? 'is-risky' : '' ); ?>">
									<div class="wstl-cd-linked-top">
										<span class="wstl-cd-badge is-<?php echo esc_attr( $linked_customer->segment ); ?>">
											<?php echo esc_html( wstl_get_segment_label( $linked_customer->segment ) ); ?>
										</span>
										<a href="<?php echo esc_url( admin_url( 'admin.php?page=trustlens-customers&customer=' . $link['email_hash'] ) ); ?>">
											<?php echo esc_html( $linked_customer->customer_email ?: __( 'Guest', 'trustlens' ) ); ?>
										</a>
										<?php if ( $linked_customer->is_blocked ) : ?>
											<span class="wstl-cd-badge is-blocked"><?php esc_html_e( 'Blocked', 'trustlens' ); ?></span>
										<?php endif; ?>
									</div>
									<div class="wstl-cd-linked-meta">
										<span><?php echo esc_html( implode( ', ', $type_names ) ); ?></span>
										<span class="wstl-cd-linked-score" style="color: <?php echo esc_attr( $link_color ); ?>;">
											<?php esc_html_e( 'Score:', 'trustlens' ); ?> <?php echo esc_html( (int) $linked_customer->trust_score ); ?>
										</span>
										<span>
											<?php
											printf(
												/* translators: %d: number of matching fingerprints */
												esc_html( _n( '%d match', '%d matches', (int) $link['match_count'], 'trustlens' ) ),
												(int) $link['match_count']
											);
											?>
										</span>
									</div>
								</div>
							<?php endforeach; ?>
						</div>
					<?php endif; ?>
				</div>
			<?php else : ?>
				<div class="wstl-cd-tile">
					<h3><?php esc_html_e( 'Linked accounts', 'trustlens' ); ?></h3>
					<p class="wstl-cd-empty"><?php esc_html_e( 'Linked accounts module is disabled.', 'trustlens' ); ?></p>
				</div>
			<?php endif; ?>
			<div class="wstl-cd-tile">
				<h3><?php esc_html_e( 'Return rate trend', 'trustlens' ); ?><span style="font-weight:400; color: var(--tl-ink-faint); margin-left:6px;">&middot; <?php esc_html_e( '12 weeks', 'trustlens' ); ?></span></h3>
				<div class="wstl-cd-trend-wrap">
					<?php echo $wstl_cd_render_trend( $trend_data ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG markup is pre-escaped in the closure. ?>
					<?php
					// Screen reader summary.
					$first = null;
					$last  = null;
					foreach ( $trend_data as $w ) {
						if ( null !== $w['rate'] ) {
							if ( null === $first ) {
								$first = (float) $w['rate'];
							}
							$last = (float) $w['rate'];
						}
					}
					if ( null !== $first && null !== $last ) :
						?>
						<span class="screen-reader-text">
							<?php
							printf(
								/* translators: 1: starting return rate, 2: ending return rate */
								esc_html__( 'Return rate over the last 12 weeks, going from %1$s%% to %2$s%%.', 'trustlens' ),
								esc_html( number_format( $first, 1 ) ),
								esc_html( number_format( $last, 1 ) )
							);
							?>
						</span>
					<?php endif; ?>
				</div>
			</div>
		</div>

		<?php /* =================== Zone 4: Details =================== */ ?>
		<div class="wstl-cd-details">

			<div class="wstl-cd-tile">
				<h3><?php esc_html_e( 'Recent activity', 'trustlens' ); ?></h3>
				<?php if ( empty( $events ) ) : ?>
					<p class="wstl-cd-empty"><?php esc_html_e( 'No activity recorded yet.', 'trustlens' ); ?></p>
				<?php else : ?>
					<div class="wstl-cd-activity">
						<?php
						$icons = array(
							'order_completed'            => 'cart',
							'full_refund'                => 'money-alt',
							'partial_refund'             => 'money-alt',
							'order_cancelled'            => 'no',
							'customer_blocked'           => 'lock',
							'customer_unblocked'         => 'unlock',
							'customer_allowlisted'       => 'yes-alt',
							'customer_allowlist_removed' => 'dismiss',
							'network_early_warning'      => 'shield',
						);

						// Resolve which referenced orders actually exist so we only
						// link to real edit screens. Demo/test events (and events
						// whose order was later deleted) carry IDs with no order
						// behind them — those render as plain text, not a 404 link.
						$existing_orders = array();
						if ( function_exists( 'wc_get_order' ) ) {
							foreach ( array_unique( array_filter( wp_list_pluck( $events, 'order_id' ) ) ) as $maybe_order_id ) {
								if ( wc_get_order( (int) $maybe_order_id ) ) {
									$existing_orders[ (int) $maybe_order_id ] = true;
								}
							}
						}

						foreach ( $events as $event ) :
							$event_data = json_decode( $event->event_data, true );
							$icon       = $icons[ $event->event_type ] ?? 'marker';
							$icon_class = '';
							if ( in_array( $event->event_type, array( 'full_refund', 'partial_refund' ), true ) ) {
								$icon_class = 'is-refund';
							} elseif ( 'order_completed' === $event->event_type ) {
								$icon_class = 'is-order';
							}
							?>
							<div class="wstl-cd-activity-item">
								<div class="wstl-cd-activity-icon <?php echo esc_attr( $icon_class ); ?>">
									<span class="dashicons dashicons-<?php echo esc_attr( $icon ); ?>"></span>
								</div>
								<div class="wstl-cd-activity-body">
									<p class="wstl-cd-activity-title">
										<?php echo esc_html( ucfirst( str_replace( '_', ' ', $event->event_type ) ) ); ?>
										<?php if ( $event->order_id && ! empty( $existing_orders[ (int) $event->order_id ] ) ) : ?>
											&middot; <a href="<?php echo esc_url( admin_url( 'post.php?post=' . $event->order_id . '&action=edit' ) ); ?>">#<?php echo esc_html( $event->order_id ); ?></a>
										<?php elseif ( $event->order_id ) : ?>
											&middot; #<?php echo esc_html( $event->order_id ); ?>
										<?php endif; ?>
									</p>
									<p class="wstl-cd-activity-meta">
										<?php
										echo esc_html( human_time_diff( strtotime( $event->created_at ), time() ) );
										esc_html_e( ' ago', 'trustlens' );
										?>
										<?php if ( isset( $event_data['refund_amount'] ) ) : ?>
											&middot; <?php echo wp_kses_post( wc_price( $event_data['refund_amount'] ) ); ?>
										<?php endif; ?>
									</p>
								</div>
							</div>
						<?php endforeach; ?>
					</div>
				<?php endif; ?>
			</div>

			<div class="wstl-cd-tile">
				<h3><?php esc_html_e( 'Signal impact', 'trustlens' ); ?></h3>
				<?php if ( empty( $signals ) ) : ?>
					<p class="wstl-cd-empty"><?php esc_html_e( 'No signals recorded yet.', 'trustlens' ); ?></p>
				<?php else : ?>
					<?php
					// Normalize bar widths to the largest absolute signal score on the page,
					// and gather the biggest drivers for a plain-English summary.
					$max_abs = 1;
					$neg     = array();
					$pos     = array();
					foreach ( $signals as $s ) {
						$sc      = (int) $s->signal_score;
						$max_abs = max( $max_abs, abs( $sc ) );
						$nm      = ucfirst( str_replace( '_', ' ', $s->module_id ) );
						if ( $sc < 0 ) {
							$neg[] = array( 'name' => $nm, 'score' => $sc );
						} elseif ( $sc > 0 ) {
							$pos[] = array( 'name' => $nm, 'score' => $sc );
						}
					}
					usort( $neg, static fn( $a, $b ) => $a['score'] <=> $b['score'] );
					usort( $pos, static fn( $a, $b ) => $b['score'] <=> $a['score'] );

					$summary_bits = array();
					if ( $neg ) {
						$labels = array();
						foreach ( array_slice( $neg, 0, 3 ) as $n ) {
							$labels[] = $n['name'] . ' (' . $n['score'] . ')';
						}
						/* translators: %s: comma-separated list of the signals lowering the score. */
						$summary_bits[] = sprintf( __( 'Weighing the score down: %s.', 'trustlens' ), implode( ', ', $labels ) );
					}
					if ( $pos ) {
						$labels = array();
						foreach ( array_slice( $pos, 0, 2 ) as $p ) {
							$labels[] = $p['name'] . ' (+' . $p['score'] . ')';
						}
						/* translators: %s: comma-separated list of the signals helping the score. */
						$summary_bits[] = sprintf( __( 'In their favour: %s.', 'trustlens' ), implode( ', ', $labels ) );
					}
					?>
					<?php if ( $summary_bits ) : ?>
						<p class="wstl-cd-signal-summary"><?php echo esc_html( implode( ' ', $summary_bits ) ); ?></p>
					<?php endif; ?>
					<div class="wstl-cd-signals">
						<?php foreach ( $signals as $signal ) : ?>
							<?php
							$score    = (int) $signal->signal_score;
							$abs_pct  = min( 50, ( abs( $score ) / $max_abs ) * 50 );
							$is_pos   = $score > 0;
							$is_neg   = $score < 0;
							$name     = ucfirst( str_replace( '_', ' ', $signal->module_id ) );
							$sr_class = $is_pos ? 'is-pos' : ( $is_neg ? 'is-neg' : '' );
							?>
							<div class="wstl-cd-signal" tabindex="0" title="<?php echo esc_attr( $signal->signal_reason ); ?>" aria-label="<?php echo esc_attr( $name . ': ' . ( $score > 0 ? '+' : '' ) . $score . '. ' . $signal->signal_reason ); ?>">
								<div class="wstl-cd-signal-name"><?php echo esc_html( $name ); ?></div>
								<div class="wstl-cd-signal-track">
									<div class="wstl-cd-signal-zero"></div>
									<?php if ( $is_pos ) : ?>
										<div class="wstl-cd-signal-fill is-pos" style="width: <?php echo esc_attr( number_format( $abs_pct, 2, '.', '' ) ); ?>%;"></div>
									<?php elseif ( $is_neg ) : ?>
										<div class="wstl-cd-signal-fill is-neg" style="width: <?php echo esc_attr( number_format( $abs_pct, 2, '.', '' ) ); ?>%;"></div>
									<?php endif; ?>
								</div>
								<div class="wstl-cd-signal-value <?php echo esc_attr( $sr_class ); ?>">
									<?php echo esc_html( ( $score > 0 ? '+' : '' ) . $score ); ?>
								</div>
							</div>
						<?php endforeach; ?>
					</div>
					<span class="screen-reader-text">
						<?php esc_html_e( 'Signal impact bars. Negative signals extend left in red, positive signals extend right in green.', 'trustlens' ); ?>
					</span>
				<?php endif; ?>
			</div>
		</div>

		<?php
		/* =================== Store Trust Network =================== */
		if ( function_exists( 'wstl_network_is_active' ) && wstl_network_is_active() ) :
			$cd_net_hash  = wstl_get_network_email_hash( (string) ( $customer->customer_email ?? '' ) );
			$cd_net_flags = '' !== $cd_net_hash
				? ( new TrustLens_Network_Flag_Repository() )->get_remote_flags( $cd_net_hash )
				: array();
			if ( ! empty( $cd_net_flags ) ) :
				$cd_net_sum = TrustLens_Network_Flag_Repository::summarize_remote_flags( $cd_net_flags );
				?>
				<div class="wstl-card wstl-cd-network">
					<h3><?php esc_html_e( 'Store Trust Network', 'trustlens' ); ?></h3>
					<p class="wstl-cd-network-head">
						<?php
						printf(
							/* translators: %s: number of linked stores. */
							esc_html__( 'Flagged at %s of your linked stores.', 'trustlens' ),
							'<strong>' . esc_html( number_format_i18n( (int) $cd_net_sum['store_count'] ) ) . '</strong>'
						);
						?>
					</p>
					<?php if ( ! empty( $customer->is_allowlisted ) ) : ?>
						<p class="wstl-cd-network-note">
							<?php esc_html_e( 'Allowlisted here — these flags are shown for context and are not affecting this customer\'s score.', 'trustlens' ); ?>
						</p>
					<?php endif; ?>
					<ul class="wstl-cd-network-list">
						<?php foreach ( $cd_net_flags as $cd_flag ) : ?>
							<?php $cd_host = wp_parse_url( (string) $cd_flag['source_site'], PHP_URL_HOST ); ?>
							<li>
								<span class="wstl-cd-network-badge is-<?php echo esc_attr( 'high' === $cd_flag['level'] ? 'high' : 'caution' ); ?>">
									<?php echo esc_html( 'high' === $cd_flag['level'] ? __( 'High', 'trustlens' ) : __( 'Caution', 'trustlens' ) ); ?>
								</span>
								<?php echo esc_html( TrustLens_Network_Flag_Repository::reason_label( (string) $cd_flag['reason'] ) ); ?>
								<span class="wstl-cd-network-meta">
									<?php echo esc_html( $cd_host ? (string) $cd_host : (string) $cd_flag['source_site'] ); ?>
									&middot;
									<?php
									/* translators: %s: human-readable time difference, e.g. "5 mins". */
									echo esc_html( sprintf( __( '%s ago', 'trustlens' ), human_time_diff( (int) strtotime( (string) $cd_flag['updated_at'] ) ) ) );
									?>
								</span>
							</li>
						<?php endforeach; ?>
					</ul>
					<style>
					.wstl-cd-network-list{list-style:none;margin:10px 0 0;padding:0}
					.wstl-cd-network-list li{padding:6px 0;border-top:1px solid #eef1f4;font-size:13px}
					.wstl-cd-network-badge{display:inline-block;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;padding:2px 7px;border-radius:999px;margin-right:6px;color:#fff}
					.wstl-cd-network-badge.is-high{background:#B23A48}.wstl-cd-network-badge.is-caution{background:#B88318}
					.wstl-cd-network-meta{color:#64748b;margin-left:6px}
					.wstl-cd-network-note{color:#1E7A46;font-size:12px;margin:6px 0 0}
					</style>
				</div>
				<?php
			endif;
		endif;
		?>

		<?php
		/* =================== Tags =================== */
		$cd_tags = ! empty( $customer->tags ) ? json_decode( (string) $customer->tags, true ) : array();
		$cd_tags = is_array( $cd_tags ) ? array_values( array_filter( $cd_tags, 'is_string' ) ) : array();
		if ( ! empty( $cd_tags ) ) :
			?>
			<div class="wstl-cd-tags">
				<span class="wstl-cd-tags-label"><?php esc_html_e( 'Tags', 'trustlens' ); ?></span>
				<?php foreach ( $cd_tags as $cd_tag ) : ?>
					<span class="wstl-cd-tag"><?php echo esc_html( $cd_tag ); ?></span>
				<?php endforeach; ?>
			</div>
		<?php endif; ?>

		<?php /* =================== Admin notes (collapsible) =================== */ ?>
		<details class="wstl-cd-notes"<?php echo $customer->admin_notes ? ' open' : ''; ?>>
			<summary><?php esc_html_e( 'Admin notes', 'trustlens' ); ?></summary>
			<div class="wstl-cd-notes-body">
				<?php if ( $customer->admin_notes ) : ?>
					<pre class="wstl-cd-notes-existing"><?php echo esc_html( $customer->admin_notes ); ?></pre>
				<?php else : ?>
					<p class="wstl-cd-notes-empty"><?php esc_html_e( 'No notes yet.', 'trustlens' ); ?></p>
				<?php endif; ?>
				<textarea id="wstl-add-note" class="large-text" rows="3" placeholder="<?php esc_attr_e( 'Add a note…', 'trustlens' ); ?>"></textarea>
				<p style="margin-top:8px;">
					<button type="button" class="button wstl-save-note" data-hash="<?php echo esc_attr( $customer->email_hash ); ?>">
						<?php esc_html_e( 'Save note', 'trustlens' ); ?>
					</button>
				</p>
			</div>
		</details>

	</div>
</div>

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