<?php
/**
 * CartCue — Automations list.
 *
 * @var \CartCue\Plugin $plugin
 * @package CartCue
 */
defined( 'ABSPATH' ) || exit;

/* phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound */

global $wpdb;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- list filter UI only.
$search_q = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- list filter UI only.
$filter_status = isset( $_GET['play_status'] ) ? sanitize_key( wp_unslash( $_GET['play_status'] ) ) : '';

$sql    = 'SELECT * FROM %i';
$params = [ \CartCue\DB::workflows() ];
$where  = [];

if ( $filter_status && in_array( $filter_status, [ 'active', 'paused' ], true ) ) {
	$where[]  = 'status = %s';
	$params[] = $filter_status;
}
if ( $search_q ) {
	$like     = '%' . $wpdb->esc_like( $search_q ) . '%';
	$where[]  = '(name LIKE %s OR trigger_slug LIKE %s)';
	$params[] = $like;
	$params[] = $like;
}
if ( $where ) {
	$sql .= ' WHERE ' . implode( ' AND ', $where );
}
$sql .= ' ORDER BY created_at DESC LIMIT 500';

// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- dynamic WHERE from sanitized filters.
$plays = $wpdb->get_results( $wpdb->prepare( $sql, ...$params ), ARRAY_A ) ?: [];
$count           = count( $plays );
$templates_url   = add_query_arg( [ 'page' => 'cartcue-recipes' ], admin_url( 'admin.php' ) );
$new_url         = $templates_url;
$settings_url    = add_query_arg( [ 'page' => 'cartcue-settings' ], admin_url( 'admin.php' ) );
$mail_settings   = \CartCue\MarketingConsent::get_settings();
$mail_ready      = '' !== trim( (string) ( $mail_settings['from_email'] ?? '' ) );
$default_sender  = sanitize_email( get_option( 'admin_email' ) );
$import_url      = admin_url( 'admin-post.php' );
$last_runs       = \CartCue\Admin\ReportsRepository::fetch_play_last_activity();
$play_ids        = array_column( $plays, 'id' );
$revenue_rows    = \CartCue\ConversionTracker::get_revenue_by_plays( $play_ids );
$revenue_by_play = [];
$orders_by_play  = [];
foreach ( $revenue_rows as $revenue_row ) {
	$pid = (int) $revenue_row['workflow_id'];
	$revenue_by_play[ $pid ] = (float) $revenue_row['revenue'];
	$orders_by_play[ $pid ]  = (int) ( $revenue_row['orders'] ?? 0 );
}
$store_revenue   = \CartCue\ConversionTracker::get_revenue( 0 );
$store_orders    = 0;
if ( $store_revenue > 0 && function_exists( 'wc_get_orders' ) ) {
	global $wpdb;
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery
	$store_orders = (int) $wpdb->get_var(
		$wpdb->prepare( 'SELECT COUNT(id) FROM %i', \CartCue\DB::conversions() )
	);
}
$max_active      = $plugin->max_active_plays();
$active_count    = $max_active > 0 ? $plugin->active_play_count() : 0;
$at_active_limit = $max_active > 0 && $active_count >= $max_active;
$blocked_active  = [];
if ( $max_active > 0 ) {
	foreach ( $plays as $play_row ) {
		if ( 'active' !== ( $play_row['status'] ?? '' ) ) {
			continue;
		}
		if ( ! $plugin->is_play_allowed_to_run( (int) $play_row['id'] ) ) {
			$blocked_active[] = $play_row;
		}
	}
}
$overlap_groups  = \CartCue\PlayOverlap::find_groups( $plays );
$quickstart      = \CartCue\QuickStart::items();
$show_quickstart = \CartCue\QuickStart::should_show();
$dismiss_url     = wp_nonce_url(
	add_query_arg( [ 'action' => 'cartcue_dismiss_quickstart' ], admin_url( 'admin-post.php' ) ),
	'cartcue_dismiss_quickstart'
);
$scratch_url     = add_query_arg(
	[ 'page' => 'cartcue', 'action' => 'new', 'automation_type' => 'event' ],
	admin_url( 'admin.php' )
);
$cart_recovery_url = add_query_arg(
	[ 'page' => 'cartcue', 'action' => 'new', 'recipe' => 'cart_recovery' ],
	admin_url( 'admin.php' )
);
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$highlight_play_id = absint( $_GET['cartcue_highlight'] ?? 0 );
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$has_activated_param = isset( $_GET['ap_activated'] );
if ( ! $highlight_play_id && $has_activated_param ) {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$maybe_highlight = absint( wp_unslash( $_GET['ap_activated'] ) );
	if ( $maybe_highlight > 1 ) {
		$highlight_play_id = $maybe_highlight;
	}
}
$first_activation_pending = ! (bool) get_user_meta( get_current_user_id(), 'cartcue_first_activation_seen', true );
$show_celebrate_modal     = $first_activation_pending && $has_activated_param;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$show_activate_banner = ! $show_celebrate_modal && $has_activated_param && '1' === sanitize_key( wp_unslash( $_GET['ap_activated'] ) );
$highlight_play_name  = '';
if ( $highlight_play_id ) {
	foreach ( $plays as $play_row ) {
		if ( (int) ( $play_row['id'] ?? 0 ) === $highlight_play_id ) {
			$highlight_play_name = (string) ( $play_row['name'] ?? '' );
			break;
		}
	}
}

/**
 * Format a display name from a customer email for list cards.
 */
$format_last_customer = static function ( string $email ): string {
	$email = sanitize_email( $email );
	if ( ! $email ) {
		return '';
	}
	$local = strstr( $email, '@', true );
	if ( ! $local ) {
		return $email;
	}
	$parts = preg_split( '/[._+-]+/', $local, 2 );
	$first = ucfirst( strtolower( (string) ( $parts[0] ?? $local ) ) );
	$last  = isset( $parts[1] ) && '' !== $parts[1] ? strtoupper( substr( $parts[1], 0, 1 ) ) . '.' : '';
	return trim( $first . ( $last ? ' ' . $last : '' ) );
};
?>
<div class="ap-wrap">

	<div class="ap-page-header">
		<div>
			<h1 class="ap-page-title">
				<?php esc_html_e( 'Automations', 'cartcue-sales-automation' ); ?>
				<span class="ap-play-count"><?php echo esc_html( $count ); ?></span>
			</h1>
			<p class="ap-page-sub"><?php esc_html_e( 'Set up once, recover revenue forever.', 'cartcue-sales-automation' ); ?></p>
			<?php if ( $store_revenue > 0 ) : ?>
			<p class="ap-store-recovered">
				<span class="ap-store-recovered__label"><?php esc_html_e( 'Recovered so far', 'cartcue-sales-automation' ); ?></span>
				<strong class="ap-store-recovered__amount"><?php echo wp_kses_post( wc_price( $store_revenue ) ); ?></strong>
				<?php if ( $store_orders > 0 ) : ?>
				<span class="ap-store-recovered__meta">
					<?php
					echo esc_html(
						sprintf(
							/* translators: %d: number of attributed orders */
							_n( '%d order', '%d orders', $store_orders, 'cartcue-sales-automation' ),
							$store_orders
						)
					);
					?>
				</span>
				<?php endif; ?>
			</p>
			<?php endif; ?>
			<?php if ( $max_active > 0 ) : ?>
			<p class="ap-active-usage-bar">
				<span class="ap-active-usage-bar__text">
					<?php
					printf(
						/* translators: 1: active count, 2: max */
						esc_html__( '%1$d of %2$d automations active', 'cartcue-sales-automation' ),
						esc_html( (string) $active_count ),
						esc_html( (string) $max_active )
					);
					?>
				</span>
				<span class="ap-active-usage-bar__track">
					<span class="ap-active-usage-bar__fill"
						  style="width:<?php echo esc_attr( (string) round( ( $active_count / $max_active ) * 100 ) ); ?>%"
						<?php if ( $at_active_limit ) : ?>
						  aria-label="<?php esc_attr_e( 'Limit reached', 'cartcue-sales-automation' ); ?>"
						<?php endif; ?>></span>
				</span>
				<?php if ( $at_active_limit ) : ?>
				<a href="<?php echo esc_url( \CartCue\Plugin::upgrade_url( 'active_play_meter' ) ); ?>"
				   target="_blank" rel="noopener noreferrer" class="ap-upgrade-link">
					<?php esc_html_e( 'Upgrade for unlimited →', 'cartcue-sales-automation' ); ?>
				</a>
				<?php endif; ?>
			</p>
			<?php endif; ?>
		</div>
		<a href="<?php echo esc_url( $new_url ); ?>" class="ap-btn ap-btn-primary">
			+ <?php esc_html_e( 'New automation', 'cartcue-sales-automation' ); ?>
		</a>
	</div>

	<?php
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( isset( $_GET['wizard_skipped'] ) ) :
		?>
	<div class="notice notice-info is-dismissible">
		<p><?php esc_html_e( 'Setup skipped. Pick a template below or use the quick start checklist whenever you\'re ready.', 'cartcue-sales-automation' ); ?></p>
	</div>
	<?php endif; ?>
	<?php
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( isset( $_GET['wizard_error'] ) ) :
		?>
	<div class="notice notice-warning is-dismissible">
		<p><?php esc_html_e( 'We couldn\'t create that automation automatically. Please finish setting it up in the editor.', 'cartcue-sales-automation' ); ?></p>
	</div>
	<?php endif; ?>
	<?php
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( isset( $_GET['ap_imported'] ) ) :
		?>
	<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Automation imported successfully.', 'cartcue-sales-automation' ); ?></p></div>
	<?php endif; ?>
	<?php
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( isset( $_GET['ap_err'] ) && 'upload' === sanitize_key( wp_unslash( $_GET['ap_err'] ) ) ) :
		?>
	<div class="notice notice-error is-dismissible"><p><?php esc_html_e( 'Import failed. Please upload a valid JSON file exported from CartCue.', 'cartcue-sales-automation' ); ?></p></div>
	<?php endif; ?>
	<?php
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( isset( $_GET['ap_err'] ) && 'invalid' === sanitize_key( wp_unslash( $_GET['ap_err'] ) ) ) :
		?>
	<div class="notice notice-error is-dismissible"><p><?php esc_html_e( 'Import failed. The uploaded JSON format is not valid for CartCue.', 'cartcue-sales-automation' ); ?></p></div>
	<?php endif; ?>

	<?php
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( $has_activated_param && ! $show_celebrate_modal ) :
		?>
	<div class="notice notice-success is-dismissible">
		<p><?php esc_html_e( 'Automation activated! It\'s now live and watching for customers.', 'cartcue-sales-automation' ); ?></p>
	</div>
		<?php if ( ! $mail_ready ) : ?>
	<div class="notice notice-warning is-dismissible">
		<p>
			<?php
			printf(
				/* translators: %s: default WordPress/WooCommerce sender email */
				esc_html__( 'Live! Emails will send from %s.', 'cartcue-sales-automation' ),
				esc_html( $default_sender )
			);
			?>
			<a href="<?php echo esc_url( $settings_url ); ?>"><?php esc_html_e( 'Set your sender name & email', 'cartcue-sales-automation' ); ?> →</a>
		</p>
	</div>
		<?php endif; ?>
	<?php endif; ?>

	<?php if ( $count > 0 || '' !== $search_q || '' !== $filter_status ) : ?>
	<div class="ap-plays-toolbar">
		<form method="get" class="ap-plays-toolbar__search-form">
			<input type="hidden" name="page" value="cartcue">
			<input type="search" name="s" value="<?php echo esc_attr( $search_q ); ?>" placeholder="<?php esc_attr_e( 'Search automations…', 'cartcue-sales-automation' ); ?>" class="ap-input ap-plays-search">
		</form>
		<form method="get" class="ap-plays-toolbar__filters">
			<input type="hidden" name="page" value="cartcue">
			<?php if ( $search_q ) : ?>
			<input type="hidden" name="s" value="<?php echo esc_attr( $search_q ); ?>">
			<?php endif; ?>
			<label for="ap-play-status-filter" class="screen-reader-text"><?php esc_html_e( 'Filter by status', 'cartcue-sales-automation' ); ?></label>
			<select id="ap-play-status-filter" name="play_status" class="ap-select" onchange="this.form.submit()">
				<option value=""><?php esc_html_e( 'All statuses', 'cartcue-sales-automation' ); ?></option>
				<option value="active" <?php selected( $filter_status, 'active' ); ?>><?php esc_html_e( 'Active', 'cartcue-sales-automation' ); ?></option>
				<option value="paused" <?php selected( $filter_status, 'paused' ); ?>><?php esc_html_e( 'Paused', 'cartcue-sales-automation' ); ?></option>
			</select>
		</form>
	</div>
	<?php endif; ?>

	<?php if ( ! empty( $blocked_active ) ) : ?>
	<div class="ap-notice-card ap-notice-card--warning">
		<strong><?php esc_html_e( 'Some active automations are not running', 'cartcue-sales-automation' ); ?></strong>
		<p>
			<?php
			echo esc_html(
				sprintf(
					/* translators: %d: maximum active automations that may run on the free plan */
					__( 'The free plan runs automations for your %d oldest active plays only. These stay “on” but triggers are skipped until you pause a higher-priority automation or upgrade.', 'cartcue-sales-automation' ),
					$max_active
				)
			);
			?>
			<a href="<?php echo esc_url( \CartCue\Plugin::upgrade_url( 'active_play_cap_blocked' ) ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Upgrade to Pro', 'cartcue-sales-automation' ); ?> →</a>
		</p>
		<ul class="ap-overlap-list">
			<?php foreach ( $blocked_active as $blocked_play ) :
				$blocked_edit = add_query_arg(
					[ 'page' => 'cartcue', 'action' => 'edit', 'id' => $blocked_play['id'] ],
					admin_url( 'admin.php' )
				);
				?>
			<li>
				<a href="<?php echo esc_url( $blocked_edit ); ?>"><?php echo esc_html( $blocked_play['name'] ?? '' ); ?></a>
				<span class="ap-play-cap-badge"><?php esc_html_e( 'Not running (over cap)', 'cartcue-sales-automation' ); ?></span>
			</li>
			<?php endforeach; ?>
		</ul>
	</div>
	<?php endif; ?>

	<?php if ( empty( $plays ) ) : ?>

	<div class="ap-empty-state">
		<div class="ap-empty-icon">
			<i class="ti ti-bolt" style="font-size:48px;color:#534AB7" aria-hidden="true"></i>
		</div>
		<h2><?php esc_html_e( 'Your store\'s quiet… let\'s fix that.', 'cartcue-sales-automation' ); ?></h2>
		<p><?php esc_html_e( 'Pick a template below — most stores start with cart recovery.', 'cartcue-sales-automation' ); ?></p>

		<div class="ap-quickwin-card">
			<div class="ap-quickwin-card__icon">🛒</div>
			<div class="ap-quickwin-card__body">
				<strong><?php esc_html_e( 'Recover abandoned carts', 'cartcue-sales-automation' ); ?></strong>
				<p><?php esc_html_e( 'When someone leaves without buying → wait 1 hour → send a recovery email. Pre-configured and ready to activate.', 'cartcue-sales-automation' ); ?></p>
			</div>
			<a href="<?php echo esc_url( $cart_recovery_url ); ?>" class="ap-btn ap-btn-primary">
				<?php esc_html_e( 'Set up in 2 minutes →', 'cartcue-sales-automation' ); ?>
			</a>
		</div>

		<div class="ap-empty-state-secondary">
			<a href="<?php echo esc_url( $templates_url ); ?>" class="ap-btn ap-btn-primary">
				<?php esc_html_e( 'Browse automation templates →', 'cartcue-sales-automation' ); ?>
			</a>
			<p class="ap-empty-state__or">
				<a href="<?php echo esc_url( $scratch_url ); ?>" class="ap-link">
					<?php esc_html_e( 'Or start from scratch', 'cartcue-sales-automation' ); ?>
				</a>
			</p>
		</div>
	</div>

		<?php if ( $show_quickstart ) : ?>
	<div class="ap-quickstart-card">
		<?php
		$quickstart_done  = count( array_filter( $quickstart, static fn( $i ) => $i['done'] ) );
		$quickstart_total = count( $quickstart );
		?>
		<div class="ap-quickstart-card__header">
			<strong>
				<?php esc_html_e( 'Quick start', 'cartcue-sales-automation' ); ?>
				<span class="ap-quickstart-progress"><?php echo esc_html( sprintf( '%1$d of %2$d done', $quickstart_done, $quickstart_total ) ); ?></span>
			</strong>
			<a href="<?php echo esc_url( $dismiss_url ); ?>" class="ap-quickstart-dismiss"><?php esc_html_e( 'Dismiss', 'cartcue-sales-automation' ); ?></a>
		</div>
		<ul class="ap-quickstart-list">
			<?php foreach ( $quickstart as $item ) : ?>
			<li class="ap-quickstart-item<?php echo $item['done'] ? ' is-done' : ''; ?>">
				<span class="ap-quickstart-check" aria-hidden="true"><?php echo $item['done'] ? '✓' : '○'; ?></span>
				<span class="screen-reader-text"><?php echo $item['done'] ? esc_html__( 'Completed', 'cartcue-sales-automation' ) : esc_html__( 'To do', 'cartcue-sales-automation' ); ?></span>
				<?php if ( $item['done'] ) : ?>
					<span><?php echo esc_html( $item['label'] ); ?></span>
				<?php else : ?>
					<a href="<?php echo esc_url( $item['url'] ); ?>"><?php echo esc_html( $item['label'] ); ?></a>
				<?php endif; ?>
			</li>
			<?php endforeach; ?>
		</ul>
	</div>
		<?php endif; ?>

	<?php else : ?>

	<?php if ( $show_activate_banner ) : ?>
	<div class="ap-activate-banner" id="ap-activate-banner" role="status">
		<p class="ap-activate-banner__text">
			<?php if ( $highlight_play_name ) : ?>
				<?php
				printf(
					/* translators: %s: play name */
					esc_html__( '🎉 %s is live. It\'ll fire the next time someone matches the trigger. We\'ll show revenue here as it comes in.', 'cartcue-sales-automation' ),
					esc_html( $highlight_play_name )
				);
				?>
			<?php else : ?>
				<?php esc_html_e( '🎉 Your play is live. Revenue will show up here as orders roll in.', 'cartcue-sales-automation' ); ?>
			<?php endif; ?>
		</p>
		<?php if ( ! $mail_ready ) : ?>
		<p class="ap-activate-banner__cta">
			<?php esc_html_e( 'One more thing — set your sender address so emails actually send:', 'cartcue-sales-automation' ); ?>
			<a href="<?php echo esc_url( $settings_url ); ?>"><?php esc_html_e( 'Set it →', 'cartcue-sales-automation' ); ?></a>
		</p>
		<?php endif; ?>
	</div>
	<?php endif; ?>

	<div class="ap-plays-list">
		<?php foreach ( $plays as $play ) :
			$play_id            = (int) ( $play['id'] ?? 0 );
			$trigger            = $plugin->get_trigger( $play['trigger_slug'] );
			$trigger_lbl        = $trigger ? $trigger->get_label() : $play['trigger_slug'];
			$edit_url           = add_query_arg( [ 'page' => 'cartcue', 'action' => 'edit', 'id' => $play['id'] ], admin_url( 'admin.php' ) );
			$toggle_url         = wp_nonce_url( add_query_arg( [ 'action' => 'cartcue_toggle_play', 'id' => $play['id'] ], admin_url( 'admin-post.php' ) ), 'cartcue_toggle_' . $play['id'] );
			$dup_url            = wp_nonce_url( add_query_arg( [ 'action' => 'cartcue_duplicate_play', 'id' => $play['id'] ], admin_url( 'admin-post.php' ) ), 'cartcue_duplicate_' . $play['id'] );
			$export_url         = add_query_arg(
				[
					'action'   => 'cartcue_export_play',
					'play_id'  => $play['id'],
					'_wpnonce' => wp_create_nonce( 'cartcue_export_' . $play['id'] ),
				],
				admin_url( 'admin-ajax.php' )
			);
			$is_on              = 'active' === $play['status'];
			$is_blocked_runner  = $is_on && $max_active > 0 && ! $plugin->is_play_allowed_to_run( $play_id );
			$can_turn_on        = $is_on || $plugin->can_activate_more_plays( $play_id );
			$activity           = $last_runs[ $play_id ] ?? null;
			$last_at            = $activity['last_run_at'] ?? '';
			$last_customer      = $format_last_customer( (string) ( $activity['last_customer_email'] ?? '' ) );
			$revenue_recovered  = $revenue_by_play[ $play_id ] ?? 0;
			$orders_recovered   = $orders_by_play[ $play_id ] ?? 0;
			$has_overlap        = $play_id && \CartCue\PlayOverlap::play_is_in_overlap( $play_id, $overlap_groups );
		?>
		<div class="ap-play-card<?php echo $play_id === $highlight_play_id ? ' ap-play-card--highlight ap-pulse-once' : ''; ?>" data-trigger-slug="<?php echo esc_attr( (string) ( $play['trigger_slug'] ?? '' ) ); ?>"<?php echo $play_id === $highlight_play_id ? ' id="cartcue-highlight-play"' : ''; ?>>
			<div class="ap-play-card__left">
				<div class="ap-play-trigger-tag"><?php echo esc_html( $trigger_lbl ); ?></div>
				<a href="<?php echo esc_url( $edit_url ); ?>" class="ap-play-name"><?php echo esc_html( $play['name'] ); ?></a>
				<?php echo wp_kses_post( \CartCue\PlayHealth::render( $play, $activity, $plugin ) ); ?>
				<?php if ( $has_overlap ) : ?>
				<span class="ap-overlap-badge" title="<?php esc_attr_e( 'Another active automation uses this same trigger and sends email. Customers may receive duplicate messages.', 'cartcue-sales-automation' ); ?>">
					⚠ <?php esc_html_e( 'Overlap', 'cartcue-sales-automation' ); ?>
				</span>
				<?php endif; ?>
				<?php if ( $is_blocked_runner ) : ?>
				<div class="ap-play-meta">
					<span class="ap-play-cap-badge"><?php esc_html_e( 'Active but not running — free plan cap', 'cartcue-sales-automation' ); ?></span>
					<a href="<?php echo esc_url( \CartCue\Plugin::upgrade_url( 'active_play_cap_blocked' ) ); ?>" target="_blank" rel="noopener noreferrer" class="ap-play-cap-upgrade"><?php esc_html_e( 'Upgrade', 'cartcue-sales-automation' ); ?></a>
				</div>
				<?php endif; ?>
			</div>
			<div class="ap-play-card__right">
				<?php if ( $revenue_recovered > 0 ) : ?>
				<div class="ap-play-revenue">
					<?php echo wp_kses_post( wc_price( $revenue_recovered ) ); ?>
					<span class="ap-play-revenue__label">
						<?php
						if ( $orders_recovered > 0 ) {
							printf(
								/* translators: %d: number of attributed orders */
								esc_html( _n( '%d order · recovered', '%d orders · recovered', $orders_recovered, 'cartcue-sales-automation' ) ),
								(int) $orders_recovered
							);
						} else {
							esc_html_e( 'recovered', 'cartcue-sales-automation' );
						}
						?>
					</span>
				</div>
				<?php elseif ( $play_id ) : ?>
				<div class="ap-play-revenue ap-play-revenue--zero">
					<?php esc_html_e( 'No revenue yet', 'cartcue-sales-automation' ); ?>
				</div>
				<?php endif; ?>

				<?php if ( $last_at ) : ?>
				<div class="ap-play-last-sent">
					<?php if ( $last_customer ) : ?>
						<?php
						printf(
							/* translators: 1: customer display name, 2: human time diff */
							esc_html__( 'Last sent to %1$s — %2$s ago', 'cartcue-sales-automation' ),
							esc_html( $last_customer ),
							esc_html( human_time_diff( strtotime( $last_at ), time() ) )
						);
						?>
					<?php else : ?>
						<?php
						printf(
							/* translators: %s: human time diff */
							esc_html__( 'Last sent %s ago', 'cartcue-sales-automation' ),
							esc_html( human_time_diff( strtotime( $last_at ), time() ) )
						);
						?>
					<?php endif; ?>
					&middot; <?php echo esc_html( number_format_i18n( (int) $play['run_count'] ) ); ?>
					<?php esc_html_e( 'times total', 'cartcue-sales-automation' ); ?>
				</div>
				<?php elseif ( $is_on ) : ?>
				<div class="ap-play-last-sent ap-play-last-sent--waiting">
					<?php esc_html_e( 'Waiting for first trigger…', 'cartcue-sales-automation' ); ?>
				</div>
				<?php endif; ?>

				<label class="ap-toggle" title="<?php echo $is_on ? esc_attr__( 'Pause', 'cartcue-sales-automation' ) : ( $can_turn_on ? esc_attr__( 'Activate', 'cartcue-sales-automation' ) : esc_attr__( 'Active automation limit reached — pause another first', 'cartcue-sales-automation' ) ); ?>">
					<?php if ( $can_turn_on ) : ?>
					<a href="<?php echo esc_url( $toggle_url ); ?>" class="ap-toggle-link <?php echo $is_on ? 'is-on' : 'is-off'; ?>" aria-label="<?php echo $is_on ? esc_attr__( 'On — click to pause', 'cartcue-sales-automation' ) : esc_attr__( 'Off — click to activate', 'cartcue-sales-automation' ); ?>">
						<span class="ap-toggle-track"><span class="ap-toggle-thumb"></span></span>
					</a>
					<?php else : ?>
					<span class="ap-toggle-link is-off is-locked" aria-disabled="true" title="<?php esc_attr_e( 'Active automation limit reached', 'cartcue-sales-automation' ); ?>">
						<span class="ap-toggle-track"><span class="ap-toggle-thumb"></span></span>
					</span>
					<?php endif; ?>
				</label>
				<div class="ap-play-actions">
					<a href="<?php echo esc_url( $edit_url ); ?>"><?php esc_html_e( 'Edit', 'cartcue-sales-automation' ); ?></a>
					<div class="ap-play-overflow">
						<button type="button" class="ap-play-overflow__btn" aria-label="<?php esc_attr_e( 'More actions', 'cartcue-sales-automation' ); ?>" aria-haspopup="true" aria-expanded="false">⋯</button>
						<div class="ap-play-overflow__menu" role="menu" hidden>
							<a href="<?php echo esc_url( $dup_url ); ?>" class="ap-overflow-item" role="menuitem" tabindex="-1">
								<?php esc_html_e( 'Duplicate', 'cartcue-sales-automation' ); ?>
							</a>
							<a href="<?php echo esc_url( $export_url ); ?>" class="ap-overflow-item" role="menuitem" tabindex="-1">
								<?php esc_html_e( 'Export JSON', 'cartcue-sales-automation' ); ?>
							</a>
							<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
								  class="ap-delete-form">
								<?php wp_nonce_field( 'cartcue_delete_' . $play['id'] ); ?>
								<input type="hidden" name="action" value="cartcue_delete_play">
								<input type="hidden" name="id" value="<?php echo esc_attr( $play['id'] ); ?>">
								<button type="submit" class="ap-overflow-item ap-overflow-item--danger" role="menuitem" tabindex="-1">
									<?php esc_html_e( 'Delete', 'cartcue-sales-automation' ); ?>
								</button>
							</form>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php endforeach; ?>
	</div>

	<?php endif; ?>
</div>
<?php if ( $highlight_play_id ) : ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
	var el = document.getElementById('cartcue-highlight-play');
	if (el && el.scrollIntoView) {
		setTimeout(function () { el.scrollIntoView({ behavior: 'smooth', block: 'center' }); }, 200);
	}
});
</script>
<?php endif; ?>
<?php
/* phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound */
?>
