<?php
/**
 * CartCue — Story Builder (play editor).
 *
 * New in v1.3:
 *  - Test Play button
 *  - "Re-verify before sending" checkbox (DeferredStateCheck)
 *  - Frequency limit controls (per-customer run limit + cooldown)
 *  - Sentence-based story bar (uses get_sentence())
 *
 * @var array|null   $play    Decoded existing play (null when creating new).
 * @var array|null   $recipe  Pre-built recipe config (null when blank).
 * @var \CartCue\Plugin $plugin
 * @package CartCue
 */
defined( 'ABSPATH' ) || exit;

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

$src          = $play ?? $recipe ?? [];
$is_new       = empty( $play );
$play_id      = (int) ( $play['id'] ?? 0 );
$wf_name      = esc_attr( $src['name']                ?? '' );
$wf_trigger   = esc_attr( $src['trigger_slug']        ?? $src['trigger'] ?? '' );
$wf_t_setts   = $src['trigger_settings']              ?? [];
$wf_rules     = $src['rules']                         ?? [];
$wf_actions   = $src['actions']                       ?? [];
$wf_sequence = isset( $src['sequence'] ) && is_array( $src['sequence'] ) ? $src['sequence'] : [];
$wf_timing    = $src['timing']                        ?? [ 'type' => 'immediate' ];
$wf_status    = esc_attr( $src['status']              ?? 'active' );
$max_runs     = (int) ( $src['max_runs_per_customer'] ?? 0 );
$cooldown     = (int) ( $src['cooldown_days']         ?? 0 );

$timing_type  = $wf_timing['type']        ?? 'immediate';
$delay_val    = (int) ( $wf_timing['delay_value'] ?? 1 );
$delay_unit   = $wf_timing['delay_unit']  ?? 'hours';
$sched_h      = (int) ( $wf_timing['schedule_hour'] ?? 9 );
$sched_m      = (int) ( $wf_timing['schedule_minute'] ?? 0 );
$sched_time_val = sprintf( '%02d:%02d', $sched_h, $sched_m );
$back_url            = add_query_arg( [ 'page' => 'cartcue' ], admin_url( 'admin.php' ) );
$current_trigger_obj = $wf_trigger ? $plugin->get_trigger( $wf_trigger ) : null;
$is_ghost_trigger    = $current_trigger_obj instanceof \CartCue\Triggers\GhostTrigger;
$is_pro              = $plugin->is_pro();
$max_sequence_steps  = $plugin->max_sequence_steps();
$max_active_plays    = $plugin->max_active_plays();
$at_active_limit     = $max_active_plays > 0 && ! $plugin->can_activate_more_plays( $play_id );
$can_use_sequence    = $is_pro || $max_sequence_steps > 0;
$can_use_branching   = $plugin->can_use_branching();
$has_conditions_data = ! empty( $wf_rules );
$has_sequence_data   = ! empty( $wf_sequence );
if ( ! isset( $automation_type ) || '' === $automation_type ) {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- editor UI state only.
	$automation_type = sanitize_key( wp_unslash( $_GET['automation_type'] ?? ( $play['automation_type'] ?? 'event' ) ) );
}
if ( 'triggered' === $automation_type ) {
	$automation_type = 'event';
}
if ( ! in_array( $automation_type, [ 'event', 'campaign' ], true ) ) {
	$automation_type = 'event';
}
$seq_panel_open = $has_sequence_data || 'event' === $automation_type;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- UI state only.
$guided_step = isset( $_GET['guided_step'] )
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- UI state only.
	? sanitize_key( wp_unslash( $_GET['guided_step'] ) )
	: ( ! empty( $recipe ) ? 'action' : 'trigger' );
if ( ! in_array( $guided_step, [ 'trigger', 'timing', 'action', 'review' ], true ) ) {
	$guided_step = ! empty( $recipe ) ? 'action' : 'trigger';
}

$editor_layout = isset( $editor_layout ) && is_string( $editor_layout ) && '' !== $editor_layout
	? $editor_layout
	: 'guided';

$show_timeline_shell  = false;
$use_timeline_editor  = false;

if ( empty( $wf_actions ) ) {
	if ( ! empty( $recipe ) ) {
		$wf_actions = \CartCue\RecipeNormalizer::default_email_action();
	} elseif ( $is_new ) {
		$wf_actions = [
			[
				'type'      => '',
				'settings'  => [],
				'condition' => [],
			],
		];
	}
}
$campaigns = $is_pro ? \CartCue\CampaignRepository::all() : [];

$free_triggers = [];
$pro_triggers  = [];
foreach ( $plugin->get_triggers() as $slug => $trigger ) {
	if ( ! $trigger->show_in_picker() ) {
		continue;
	}
	if ( $trigger instanceof \CartCue\Triggers\GhostTrigger ) {
		$pro_triggers[ $slug ] = $trigger;
	} else {
		$free_triggers[ $slug ] = $trigger;
	}
}

$pro_triggers_featured = [];
$pro_triggers_more     = [];
$pro_trigger_count     = count( $pro_triggers );
if ( ! $is_pro && ! empty( $pro_triggers ) ) {
	$featured_slugs = [ 'customer_birthday', 'new_review', 'manual' ];
	foreach ( $pro_triggers as $slug => $trigger ) {
		if ( in_array( $slug, $featured_slugs, true ) ) {
			$pro_triggers_featured[ $slug ] = $trigger;
		} else {
			$pro_triggers_more[ $slug ] = $trigger;
		}
	}
}

$has_email_action = false;
foreach ( $wf_actions as $a ) {
	if ( 'send_email' === ( $a['type'] ?? '' ) ) {
		$has_email_action = true;
		break;
	}
}
$has_selected_action = false;
foreach ( $wf_actions as $a ) {
	if ( '' !== (string) ( $a['type'] ?? '' ) ) {
		$has_selected_action = true;
		break;
	}
}

$timing_primary = [
	[ 'type' => 'immediate', 'label' => __( 'Right away', 'cartcue-sales-automation' ) ],
	[ 'type' => 'delay', 'v' => 30, 'u' => 'minutes', 'label' => __( 'After 30 minutes', 'cartcue-sales-automation' ) ],
	[ 'type' => 'delay', 'v' => 1,  'u' => 'hours', 'label' => __( 'After 1 hour (recommended for carts)', 'cartcue-sales-automation' ) ],
	[ 'type' => 'delay', 'v' => 1,  'u' => 'days',  'label' => __( 'After 1 day', 'cartcue-sales-automation' ) ],
	[ 'type' => 'delay', 'v' => 3,  'u' => 'days',  'label' => __( 'After 3 days', 'cartcue-sales-automation' ) ],
];
$timing_custom_presets = [
	[ 'type' => 'delay', 'v' => 15, 'u' => 'minutes', 'label' => __( '15 minutes', 'cartcue-sales-automation' ) ],
	[ 'type' => 'delay', 'v' => 3,  'u' => 'hours',   'label' => __( '3 hours', 'cartcue-sales-automation' ) ],
	[ 'type' => 'delay', 'v' => 5,  'u' => 'days',    'label' => __( 'Day 5 check-in', 'cartcue-sales-automation' ) ],
	[ 'type' => 'delay', 'v' => 14, 'u' => 'days',    'label' => __( 'Day 14 follow-up', 'cartcue-sales-automation' ) ],
	[ 'type' => 'delay', 'v' => 7,  'u' => 'days',    'label' => __( '1 week', 'cartcue-sales-automation' ) ],
];
$primary_delay_keys = [ '30:minutes', '1:hours', '1:days', '3:days' ];
$timing_custom_active = ( 'delay' === $timing_type && ! in_array( $delay_val . ':' . $delay_unit, $primary_delay_keys, true ) )
	|| ( 'schedule_time' === $timing_type );

global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$all_plays_for_overlap = $wpdb->get_results(
	$wpdb->prepare( 'SELECT * FROM %i', \CartCue\DB::workflows() ),
	ARRAY_A
) ?: [];
$overlap_groups        = \CartCue\PlayOverlap::find_groups( $all_plays_for_overlap );
$play_has_overlap      = $play_id && \CartCue\PlayOverlap::play_is_in_overlap( $play_id, $overlap_groups );
$play_revenue          = 0;
$play_run_count        = (int) ( $src['run_count'] ?? 0 );
$skip_summary          = [];
if ( $play_id ) {
	$rev_rows = \CartCue\ConversionTracker::get_revenue_by_plays( [ $play_id ] );
	$play_revenue = (float) ( $rev_rows[0]['revenue'] ?? 0 );
	$skip_summary = $plugin->logger->get_skip_summary( $play_id, 5 );
}
?>
<div class="ap-wrap ap-wrap--play-editor">

	<div class="ap-play-editor-header">
		<a href="<?php echo esc_url( $back_url ); ?>" class="ap-back-link">← <?php esc_html_e( 'Automations', 'cartcue-sales-automation' ); ?></a>
		<?php if ( $play_id && 'active' === $wf_status && 0 === $play_run_count ) : ?>
		<span class="ap-never-fired-badge" title="<?php esc_attr_e( 'This automation is active but has not completed a live run yet.', 'cartcue-sales-automation' ); ?>">
			<?php esc_html_e( 'Never fired live', 'cartcue-sales-automation' ); ?>
		</span>
		<?php endif; ?>
		<div class="ap-play-editor-header__actions">
			<label class="ap-test-to-label">
				<span class="screen-reader-text"><?php esc_html_e( 'Send test to', 'cartcue-sales-automation' ); ?></span>
				<input type="email" id="ap-test-to" class="ap-input ap-test-to-input"
					   value="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>"
					   placeholder="<?php esc_attr_e( 'Send test to…', 'cartcue-sales-automation' ); ?>">
			</label>
			<button type="button" id="ap-test-btn" class="ap-btn ap-btn-test"
					data-play="<?php echo esc_attr( $play_id ); ?>">
				<span class="ap-test-idle"><?php echo $has_email_action ? esc_html__( '▷ Send test email', 'cartcue-sales-automation' ) : esc_html__( '▷ Run test', 'cartcue-sales-automation' ); ?></span>
				<span class="ap-test-loading" style="display:none">⏳ <?php esc_html_e( 'Sending test…', 'cartcue-sales-automation' ); ?></span>
			</button>
		</div>
	</div>

	<?php
	$story_when_text = ( $wf_trigger && $current_trigger_obj )
		? $current_trigger_obj->get_sentence()
		: __( 'something happens', 'cartcue-sales-automation' );
	if ( 'delay' === $timing_type ) {
		$story_wait_text = "wait {$delay_val} {$delay_unit}";
	} elseif ( 'schedule_time' === $timing_type ) {
		$story_wait_text = sprintf(
			/* translators: %s: time like 09:00 */
			__( 'at %s (store time)', 'cartcue-sales-automation' ),
			$sched_time_val
		);
	} else {
		$story_wait_text = __( 'immediately', 'cartcue-sales-automation' );
	}
	$story_then_text = __( 'do something', 'cartcue-sales-automation' );
	if ( $has_selected_action ) {
		$labels = [];
		foreach ( $wf_actions as $a ) {
			$type = $a['type'] ?? '';
			if ( 'send_email' === $type ) {
				$labels[] = __( 'send email', 'cartcue-sales-automation' );
			} elseif ( 'send_sms' === $type ) {
				$labels[] = __( 'send SMS', 'cartcue-sales-automation' );
			} elseif ( 'send_whatsapp' === $type ) {
				$labels[] = __( 'send WhatsApp', 'cartcue-sales-automation' );
			} else {
				$ao = $plugin->get_action( $type );
				if ( $ao ) {
					$labels[] = strtolower( $ao->get_label() );
				}
			}
		}
		if ( $labels ) {
			$story_then_text = implode( ' + ', $labels );
		}
	}
	?>
	<div class="ap-play-editor-layout">
	<div class="ap-play-editor-main">

	<!-- Test play result -->
	<div id="ap-test-result" class="ap-test-result" role="status" aria-live="polite" aria-atomic="true" style="display:none"></div>
	<div id="ap-test-toast" class="ap-test-toast" role="status" aria-live="polite" hidden></div>

	<?php if ( $play_id && ! empty( $skip_summary ) ) : ?>
	<div class="ap-skip-diagnostics" id="ap-skip-diagnostics">
		<div class="ap-skip-diagnostics__header">
			<strong><?php esc_html_e( 'What\'s happened so far', 'cartcue-sales-automation' ); ?></strong>
			<a href="<?php echo esc_url( add_query_arg( [ 'page' => 'cartcue-reports', 'tab' => 'logs', 'play_id' => $play_id, 'status' => 'skipped' ], admin_url( 'admin.php' ) ) ); ?>">
				<?php esc_html_e( 'View all skips', 'cartcue-sales-automation' ); ?> →
			</a>
		</div>
		<ul class="ap-skip-diagnostics__list">
			<?php foreach ( $skip_summary as $skip_row ) : ?>
			<li>
				<span class="ap-skip-diagnostics__reason"><?php echo esc_html( $skip_row['message'] ); ?></span>
				<span class="ap-skip-diagnostics__meta">
					<?php
					printf(
						/* translators: 1: skip count, 2: human time diff */
						esc_html__( '%1$s× · last %2$s ago', 'cartcue-sales-automation' ),
						esc_html( number_format_i18n( (int) $skip_row['count'] ) ),
						esc_html( human_time_diff( strtotime( $skip_row['last_at'] ), time() ) )
					);
					?>
				</span>
			</li>
			<?php endforeach; ?>
		</ul>
	</div>
	<?php endif; ?>

	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" id="ap-play-form" class="ap-guided-mode ap-automation-editor ap-automation-editor--<?php echo esc_attr( $automation_type ); ?><?php echo $use_timeline_editor ? ' ap-editor-timeline-mode' : ''; ?>" data-editor-layout="<?php echo esc_attr( $editor_layout ); ?>" data-automation-type="<?php echo esc_attr( $automation_type ); ?>" data-guided-step="<?php echo esc_attr( $guided_step ); ?>" data-is-new="<?php echo $is_new ? '1' : '0'; ?>" data-timeline-eligible="<?php echo $can_use_sequence ? '1' : '0'; ?>" data-is-sequence="<?php echo $has_sequence_data ? 'true' : 'false'; ?>">
		<?php wp_nonce_field( 'cartcue_save_play' ); ?>
		<input type="hidden" name="action"   value="cartcue_save_play">
		<input type="hidden" name="play_id"  value="<?php echo esc_attr( $play_id ); ?>">
		<input type="hidden" name="automation_type" value="<?php echo esc_attr( $automation_type ); ?>">
		<input type="hidden" name="name" id="ap-play-name" value="<?php echo esc_attr( $src['name'] ?? '' ); ?>">
		<div class="ap-guided-stepper" id="ap-guided-stepper" aria-label="<?php esc_attr_e( 'Automation setup steps', 'cartcue-sales-automation' ); ?>">
			<button type="button" class="ap-guided-stepper__item is-active" data-guided-step="trigger">
				<span class="ap-guided-stepper__num">1</span>
				<span><?php esc_html_e( 'When…', 'cartcue-sales-automation' ); ?></span>
			</button>
			<button type="button" class="ap-guided-stepper__item" data-guided-step="timing">
				<span class="ap-guided-stepper__num">2</span>
				<span><?php esc_html_e( 'Wait…', 'cartcue-sales-automation' ); ?></span>
			</button>
			<button type="button" class="ap-guided-stepper__item" data-guided-step="action">
				<span class="ap-guided-stepper__num">3</span>
				<span><?php esc_html_e( 'Then…', 'cartcue-sales-automation' ); ?></span>
			</button>
			<button type="button" class="ap-guided-stepper__item" data-guided-step="review">
				<span class="ap-guided-stepper__num">4</span>
				<span><?php esc_html_e( 'Activate', 'cartcue-sales-automation' ); ?></span>
			</button>
		</div>

		<!-- ====================================================== -->
		<!-- STEP 1 — TRIGGER                                        -->
		<!-- ====================================================== -->
		<div class="ap-step-panel ap-step-panel--optional" id="ap-section-if" data-guided-step-panel="trigger">
			<div class="ap-step-header">
				<span class="ap-step-num">1</span>
				<div>
					<div class="ap-step-label"><?php esc_html_e( 'When…', 'cartcue-sales-automation' ); ?></div>
					<div class="ap-step-sub"><?php esc_html_e( 'Choose what starts this automation.', 'cartcue-sales-automation' ); ?></div>
				</div>
			</div>
			<div class="ap-trigger-grid" id="ap-trigger-grid">
				<?php
				$render_trigger_card = static function ( string $slug, $trigger, bool $is_ghost, bool $is_sel, bool $is_featured = false ) use ( $is_pro ) {
					$classes = 'ap-trigger-card' . ( $is_sel ? ' is-selected' : '' ) . ( $is_ghost ? ' is-pro' : '' );
					if ( $is_featured ) {
						$classes .= ' ap-trigger-card--featured';
					}
					if ( 'customer_birthday' === $slug ) {
						$classes .= ' ap-trigger-card--birthday';
					}
					$title   = $is_ghost ? esc_attr__( 'Popular in Pro', 'cartcue-sales-automation' ) : '';
					$tag     = $is_ghost && ! $is_pro ? 'div' : 'label';
					?>
				<<?php echo esc_attr( $tag ); ?> class="<?php echo esc_attr( $classes ); ?>" data-trigger-slug="<?php echo esc_attr( $slug ); ?>"<?php echo $title ? ' title="' . esc_attr( $title ) . '"' : ''; ?>>
					<?php if ( ! $is_ghost || $is_pro ) : ?>
					<input type="radio" name="trigger_slug" value="<?php echo esc_attr( $slug ); ?>"
						   <?php checked( $is_sel ); ?> class="ap-trigger-radio">
					<?php endif; ?>
					<?php if ( $is_ghost ) : ?>
					<span class="ap-pro-badge"><?php esc_html_e( 'Popular in Pro', 'cartcue-sales-automation' ); ?></span>
					<?php endif; ?>
					<?php if ( 'customer_birthday' === $slug && $is_ghost ) : ?>
					<span class="ap-trigger-stat"><?php esc_html_e( '40%+ open rate', 'cartcue-sales-automation' ); ?></span>
					<?php endif; ?>
					<span class="ap-trigger-label"><?php echo esc_html( $trigger->get_label() ); ?></span>
					<span class="ap-trigger-desc"><?php echo esc_html( $trigger->get_description() ); ?></span>
					<?php if ( $is_ghost ) : ?>
					<span class="ap-trigger-learn"><?php esc_html_e( 'See why this helps', 'cartcue-sales-automation' ); ?></span>
					<?php endif; ?>
				</<?php echo esc_attr( $tag ); ?>>
					<?php
				};
				foreach ( $free_triggers as $slug => $trigger ) {
					$render_trigger_card( $slug, $trigger, false, $wf_trigger === $slug );
				}
				?>
			</div>
			<?php if ( ! $is_pro && ! empty( $pro_triggers_featured ) ) : ?>
			<div class="ap-trigger-featured-pro">
				<h3 class="ap-subsection-label"><?php esc_html_e( 'Popular in Pro', 'cartcue-sales-automation' ); ?></h3>
				<div class="ap-trigger-grid ap-trigger-grid--featured">
					<?php
					foreach ( $pro_triggers_featured as $slug => $trigger ) {
						$render_trigger_card( $slug, $trigger, true, $wf_trigger === $slug, true );
					}
					?>
				</div>
			</div>
			<?php endif; ?>
			<?php if ( ! $is_pro && ! empty( $pro_triggers_more ) ) : ?>
			<div class="ap-trigger-grid ap-trigger-grid--more" id="ap-trigger-grid-more">
				<?php
				foreach ( $pro_triggers_more as $slug => $trigger ) {
					$render_trigger_card( $slug, $trigger, true, $wf_trigger === $slug );
				}
				?>
			</div>
			<?php endif; ?>
			<?php if ( ! $is_pro && ! empty( $pro_triggers ) ) : ?>
			<p class="ap-trigger-more-pro">
				<a href="<?php echo esc_url( \CartCue\Plugin::upgrade_url( 'trigger_picker_more' ) ); ?>" target="_blank" rel="noopener noreferrer" class="ap-upgrade-link">
					<?php
					printf(
						/* translators: %d: number of Pro triggers */
						esc_html__( '%d more triggers in Pro →', 'cartcue-sales-automation' ),
						(int) $pro_trigger_count
					);
					?>
				</a>
			</p>
			<?php endif; ?>

			<div id="ap-ghost-gate" class="ap-ghost-gate" <?php echo $is_ghost_trigger ? '' : 'style="display:none"'; ?>>
				<?php if ( $is_ghost_trigger && $current_trigger_obj ) :
					echo wp_kses_post( $current_trigger_obj->get_upgrade_html() );
				endif; ?>
			</div>

			<div id="ap-trigger-settings" class="ap-trigger-settings-panel" <?php echo $is_ghost_trigger ? 'style="display:none"' : ''; ?>>
				<?php foreach ( $plugin->get_triggers() as $slug => $trigger ) :
					if ( empty( $trigger->get_settings_fields() ) ) { continue; } ?>
				<div class="ap-tsettings-group <?php echo $wf_trigger === $slug ? 'is-visible' : ''; ?>"
					 data-trigger="<?php echo esc_attr( $slug ); ?>">
					<?php foreach ( $trigger->get_settings_fields() as $f ) :
						$fval = $wf_t_setts[ $f['key'] ] ?? $f['default']; ?>
					<div class="ap-field-row">
						<label class="ap-field-label"><?php echo esc_html( $f['label'] ); ?></label>
						<?php if ( 'select' === $f['type'] ) : ?>
						<select name="trigger_settings[<?php echo esc_attr( $f['key'] ); ?>]" class="ap-select">
							<?php foreach ( $f['options'] as $ov => $ol ) : ?>
							<option value="<?php echo esc_attr( $ov ); ?>" <?php selected( $fval, $ov ); ?>><?php echo esc_html( $ol ); ?></option>
							<?php endforeach; ?>
						</select>
						<?php else : ?>
						<input type="<?php echo esc_attr( $f['type'] ); ?>" class="ap-input"
							   name="trigger_settings[<?php echo esc_attr( $f['key'] ); ?>]"
							   value="<?php echo esc_attr( $fval ); ?>">
						<?php endif; ?>
					</div>
					<?php endforeach; ?>
					<?php if ( 'inbound_webhook' === $slug ) :
						$inbound_token = sanitize_text_field( (string) ( $wf_t_setts['token'] ?? '' ) );
						$inbound_url   = ( $play_id > 0 && '' !== $inbound_token )
							? rest_url( 'cartcue/v1/inbound/' . $play_id . '/' . rawurlencode( $inbound_token ) )
							: '';
						?>
					<div class="ap-field-row">
						<label class="ap-field-label"><?php esc_html_e( 'Inbound endpoint', 'cartcue-sales-automation' ); ?></label>
						<input type="text" class="ap-input" value="<?php echo esc_attr( $inbound_url ?: __( 'Save once to generate your endpoint URL.', 'cartcue-sales-automation' ) ); ?>" readonly>
						<p class="description"><?php esc_html_e( 'Send JSON payloads with POST. CartCue uses this tokenized endpoint to route events to this play only.', 'cartcue-sales-automation' ); ?></p>
					</div>
					<?php endif; ?>

					<?php if ( $trigger->supports_recheck() ) :
						$recheck = $wf_t_setts['recheck_before_run'] ?? 'no'; ?>
					<div class="ap-field-row ap-recheck-row">
						<label class="ap-recheck-label">
							<input type="checkbox" name="trigger_settings[recheck_before_run]" value="yes"
								   <?php checked( $recheck, 'yes' ); ?>>
							<strong><?php esc_html_e( 'Cancel if they complete the action before this sends', 'cartcue-sales-automation' ); ?></strong>
							<span class="ap-recheck-hint"><?php esc_html_e( 'If they complete the qualifying action before this runs, CartCue cancels it automatically.', 'cartcue-sales-automation' ); ?></span>
						</label>
					</div>
					<?php endif; ?>

				</div>
				<?php endforeach; ?>
			</div>
		</div>

		<div class="ap-step-connector"><span class="ap-step-connector-line"></span></div>

		<!-- ====================================================== -->
		<!-- STEP 2 — TIMING                                         -->
		<!-- ====================================================== -->
		<div class="ap-step-panel" id="ap-section-then-wait" data-guided-step-panel="timing">
			<div class="ap-step-header">
				<span class="ap-step-num">2</span>
				<div>
					<div class="ap-step-label"><?php esc_html_e( 'Wait…', 'cartcue-sales-automation' ); ?></div>
					<div class="ap-step-sub"><?php esc_html_e( 'How long after the trigger should this run?', 'cartcue-sales-automation' ); ?></div>
				</div>
			</div>
			<input type="hidden" name="timing_type" id="ap-timing-type" value="<?php echo esc_attr( $timing_type ); ?>">
			<input type="hidden" name="delay_value" id="ap-delay-value" value="<?php echo esc_attr( $delay_val ); ?>">
			<input type="hidden" name="delay_unit"  id="ap-delay-unit"  value="<?php echo esc_attr( $delay_unit ); ?>">
			<div class="ap-timing-pills">
				<?php
				foreach ( $timing_primary as $opt ) :
					$is_sel = ( 'immediate' === $opt['type'] && 'immediate' === $timing_type )
						|| ( 'delay' === $opt['type'] && 'delay' === $timing_type && (int) ( $opt['v'] ?? 0 ) === $delay_val && ( $opt['u'] ?? '' ) === $delay_unit );
					?>
				<button type="button" class="ap-timing-pill <?php echo $is_sel ? 'is-selected' : ''; ?>"
						data-type="<?php echo esc_attr( $opt['type'] ); ?>"
						data-value="<?php echo esc_attr( $opt['v'] ?? 0 ); ?>"
						data-unit="<?php echo esc_attr( $opt['u'] ?? '' ); ?>">
					<?php echo esc_html( $opt['label'] ); ?>
				</button>
				<?php endforeach; ?>
				<button type="button" class="ap-timing-pill ap-timing-pill--custom-toggle <?php echo $timing_custom_active ? 'is-selected' : ''; ?>">
					<?php esc_html_e( 'Custom timing...', 'cartcue-sales-automation' ); ?>
				</button>
			</div>
			<div id="ap-timing-custom-panel" class="ap-timing-custom-panel <?php echo $timing_custom_active ? 'is-open' : ''; ?>">
				<div class="ap-timing-custom-presets">
					<?php foreach ( $timing_custom_presets as $opt ) :
						$is_sel = 'delay' === $timing_type && (int) ( $opt['v'] ?? 0 ) === $delay_val && ( $opt['u'] ?? '' ) === $delay_unit;
						?>
					<button type="button" class="ap-timing-pill <?php echo $is_sel ? 'is-selected' : ''; ?>"
							data-type="delay"
							data-value="<?php echo esc_attr( $opt['v'] ); ?>"
							data-unit="<?php echo esc_attr( $opt['u'] ); ?>">
						<?php echo esc_html( $opt['label'] ); ?>
					</button>
					<?php endforeach; ?>
					<button type="button" class="ap-timing-pill <?php echo 'schedule_time' === $timing_type ? 'is-selected' : ''; ?>"
							data-type="schedule_time" data-value="0" data-unit="">
						<?php esc_html_e( 'At a specific time each day', 'cartcue-sales-automation' ); ?>
					</button>
					<span class="ap-timing-hint" style="font-size:12px;color:#666;display:block;margin-top:4px">
						<?php esc_html_e( 'Sends at the store clock time you set below, once per qualifying customer.', 'cartcue-sales-automation' ); ?>
					</span>
				</div>
				<div class="ap-timing-custom-wrap">
					<input type="number" id="ap-custom-val" class="ap-input ap-input--tiny" min="1" value="<?php echo esc_attr( $delay_val ); ?>">
					<select id="ap-custom-unit" class="ap-select ap-select--sm">
						<option value="minutes" <?php selected( $delay_unit, 'minutes' ); ?>><?php esc_html_e( 'minutes', 'cartcue-sales-automation' ); ?></option>
						<option value="hours"   <?php selected( $delay_unit, 'hours' ); ?>><?php esc_html_e( 'hours',   'cartcue-sales-automation' ); ?></option>
						<option value="days"    <?php selected( $delay_unit, 'days' ); ?>><?php esc_html_e( 'days',    'cartcue-sales-automation' ); ?></option>
					</select>
					<button type="button" id="ap-custom-timing-btn" class="ap-btn ap-btn-sm"><?php esc_html_e( 'Set', 'cartcue-sales-automation' ); ?></button>
				</div>
				<span id="ap-schedule-time-row" class="ap-schedule-time-row" style="<?php echo 'schedule_time' === $timing_type ? '' : 'display:none'; ?>">
					<label for="ap-schedule-time" class="ap-field-label"><?php esc_html_e( 'Send at (store timezone)', 'cartcue-sales-automation' ); ?></label>
					<input type="time" name="schedule_time" id="ap-schedule-time" class="ap-input" value="<?php echo esc_attr( $sched_time_val ); ?>">
				</span>
			</div>

			<div class="ap-timing-timeline" id="ap-timing-timeline" aria-live="polite"></div>
		</div>

		<div class="ap-step-connector"><span class="ap-step-connector-line"></span></div>

		<!-- ====================================================== -->
		<!-- STEP 3 — ACTIONS                                        -->
		<!-- ====================================================== -->
		<?php
		$render_action_type_picker = static function ( int $idx, string $current_type = '' ) {
			$hidden = '' !== $current_type ? ' hidden' : '';
			?>
			<div class="ap-action-inserter-slot" data-card-index="<?php echo esc_attr( (string) $idx ); ?>"<?php echo esc_attr( $hidden ); ?>>
				<button type="button" class="ap-btn ap-btn-ghost ap-action-inserter-trigger">
					+ <?php esc_html_e( 'Choose what happens', 'cartcue-sales-automation' ); ?>
				</button>
			</div>
			<?php
		};
		?>
		<div class="ap-step-panel" id="ap-step-4-actions" data-guided-step-panel="action">
			<div class="ap-step-header">
				<span class="ap-step-num">3</span>
				<div>
					<div class="ap-step-label" id="ap-section-do"><?php esc_html_e( 'Then…', 'cartcue-sales-automation' ); ?></div>
					<p id="ap-step-4-sub" class="ap-step-sub"><?php esc_html_e( 'Choose what happens after the wait.', 'cartcue-sales-automation' ); ?></p>
					<p class="ap-step-sub ap-orchestration-hint">
						<?php esc_html_e( 'Mix coupon + message + CRM/webhook actions in one flow. Use "Trigger Another Play" for multi-stage funnels.', 'cartcue-sales-automation' ); ?>
					</p>
				</div>
			</div>
			<?php if ( $show_timeline_shell ) : ?>
			<div class="ap-timeline-editor" id="ap-timeline-editor">
				<nav class="ap-timeline-rail" id="ap-timeline-rail" aria-label="<?php esc_attr_e( 'Message sequence', 'cartcue-sales-automation' ); ?>"></nav>
				<div class="ap-timeline-canvas" id="ap-timeline-canvas">
					<div id="ap-timeline-pane-timing" class="ap-timeline-pane ap-timeline-pane--timing" hidden></div>
					<div id="ap-timeline-pane-seq" class="ap-timeline-pane ap-timeline-pane--seq" hidden></div>
					<div id="ap-timeline-pane-actions" class="ap-timeline-pane ap-timeline-pane--actions">
			<?php endif; ?>
			<div id="ap-actions-list">
				<?php foreach ( $wf_actions as $i => $action_row ) :
					$action_type = $action_row['type'] ?? '';
					$action_obj  = $plugin->get_action( $action_type );
					$action_condition = is_array( $action_row['condition'] ?? null ) ? $action_row['condition'] : [];
					$condition_enabled = ! empty( $action_condition['enabled'] );
					$condition_field = sanitize_key( (string) ( $action_condition['field'] ?? '' ) );
					$condition_operator = sanitize_key( (string) ( $action_condition['operator'] ?? 'equals' ) );
					$condition_value = (string) ( $action_condition['value'] ?? '' ); ?>
				<div class="ap-action-card<?php echo $action_type ? ' ap-action-card--has-type' : ''; ?>" data-index="<?php echo esc_attr( $i ); ?>">
					<input type="hidden" name="actions[<?php echo esc_attr( $i ); ?>][type]" class="ap-action-type" value="<?php echo esc_attr( $action_type ); ?>">
					<?php $render_action_type_picker( (int) $i, $action_type ); ?>
					<div class="ap-action-card__header" <?php echo $action_type ? '' : 'style="display:none"'; ?>>
						<span class="ap-action-type-label"><?php echo $action_obj ? esc_html( $action_obj->get_label() ) : ''; ?></span>
						<button type="button" class="ap-btn ap-btn-ghost ap-btn-sm ap-change-action-type"><?php esc_html_e( 'Change', 'cartcue-sales-automation' ); ?></button>
						<button type="button" class="ap-icon-btn ap-remove-action" aria-label="<?php esc_attr_e( 'Remove action', 'cartcue-sales-automation' ); ?>" title="<?php esc_attr_e( 'Remove this action', 'cartcue-sales-automation' ); ?>">✕</button>
					</div>
					<?php if ( $action_obj ) : ?>
					<div class="ap-action-fields">
						<?php foreach ( $action_obj->get_settings_fields() as $f ) :
							$fv = $action_row['settings'][ $f['key'] ] ?? $f['default']; ?>
						<?php if ( 'hidden' === ( $f['type'] ?? '' ) ) : ?>
						<input type="hidden"
							   name="actions[<?php echo esc_attr($i); ?>][settings][<?php echo esc_attr($f['key']); ?>]"
							   value="<?php echo esc_attr($fv); ?>">
						<?php continue; endif; ?>
						<div class="ap-field-row">
							<label class="ap-field-label"><?php echo esc_html( $f['label'] ); ?></label>
							<?php if ( 'textarea' === $f['type'] ) : ?>
							<textarea name="actions[<?php echo esc_attr($i); ?>][settings][<?php echo esc_attr($f['key']); ?>]"
									  class="ap-textarea<?php echo 'body' === $f['key'] ? ' ap-gutenberg-source' : ''; ?>" rows="<?php echo esc_attr($f['rows']??5); ?>"
									  <?php echo 'body' === $f['key'] ? ' data-gutenberg-label="' . esc_attr__( 'Email content', 'cartcue-sales-automation' ) . '"' : ''; ?>
									  placeholder="<?php echo esc_attr($f['placeholder']??''); ?>"><?php echo esc_textarea( $fv ); ?></textarea>
							<?php elseif ( 'select' === $f['type'] ) : ?>
							<select name="actions[<?php echo esc_attr($i); ?>][settings][<?php echo esc_attr($f['key']); ?>]" class="ap-select">
								<?php foreach ( $f['options'] as $ov => $ol ) : ?>
								<option value="<?php echo esc_attr($ov); ?>" <?php selected($fv,$ov); ?>><?php echo esc_html($ol); ?></option>
								<?php endforeach; ?>
							</select>
							<?php else : ?>
							<input type="<?php echo esc_attr($f['type']); ?>"
								   name="actions[<?php echo esc_attr($i); ?>][settings][<?php echo esc_attr($f['key']); ?>]"
								   class="ap-input<?php echo ! empty( $f['async_source'] ) ? ' ap-async-input' : ''; ?>" value="<?php echo esc_attr($fv); ?>"
								   <?php if ( ! empty( $f['async_source'] ) ) : ?>
								   data-async-source="<?php echo esc_attr( $f['async_source'] ); ?>"
								   data-async-multiple="<?php echo ! empty( $f['async_multiple'] ) ? '1' : '0'; ?>"
								   <?php endif; ?>
								   placeholder="<?php echo esc_attr($f['placeholder']??''); ?>">
							<?php endif; ?>
							<?php if ( 'subject' === $f['key'] ) : ?>
							<button type="button"
									class="ap-tags-btn"
									data-field-key="<?php echo esc_attr( $f['key'] ); ?>"
									title="<?php esc_attr_e( 'Insert a magic tag', 'cartcue-sales-automation' ); ?>">
								<i class="ti ti-braces" aria-hidden="true"></i>
								<?php esc_html_e( '{ } Tags', 'cartcue-sales-automation' ); ?>
							</button>
							<div class="ap-tags-popover" id="ap-tags-popover-<?php echo esc_attr( $i ); ?>-<?php echo esc_attr( $f['key'] ); ?>" hidden>
								<?php
								$quick_tags = [
									'{{customer.first_name}}' => __( 'First name', 'cartcue-sales-automation' ),
									'{{customer.last_name}}'  => __( 'Last name', 'cartcue-sales-automation' ),
									'{{customer.email}}'      => __( 'Email', 'cartcue-sales-automation' ),
									'{{order.number}}'        => __( 'Order number', 'cartcue-sales-automation' ),
									'{{order.total}}'         => __( 'Order total', 'cartcue-sales-automation' ),
									'{{cart.total}}'          => __( 'Cart total', 'cartcue-sales-automation' ),
									'{{cart.recover_url}}'    => __( 'Recovery link', 'cartcue-sales-automation' ),
									'{{coupon.code}}'         => __( 'Coupon code', 'cartcue-sales-automation' ),
									'{{shop.name}}'           => __( 'Shop name', 'cartcue-sales-automation' ),
								];
								foreach ( $quick_tags as $tag => $tag_label ) :
									?>
								<button type="button" class="ap-tag-insert-btn" data-tag="<?php echo esc_attr( $tag ); ?>">
									<code><?php echo esc_html( $tag ); ?></code>
									<span><?php echo esc_html( $tag_label ); ?></span>
								</button>
								<?php endforeach; ?>
							</div>
							<?php endif; ?>
							<?php if ( ! empty( $f['description'] ) ) : ?>
							<p class="ap-field-hint"><?php echo esc_html( $f['description'] ); ?></p>
							<?php endif; ?>
						</div>
						<?php endforeach; ?>
						<?php if ( ! $is_pro && 'create_coupon' === ( $action_row['type'] ?? '' ) && method_exists( $action_obj, 'get_pro_feature_labels' ) ) : ?>
						<div class="ap-action-pro-upsell">
							<p class="ap-action-pro-upsell__title"><?php esc_html_e( 'Need unique codes per customer?', 'cartcue-sales-automation' ); ?></p>
							<ul class="ap-action-pro-upsell__list">
								<?php foreach ( $action_obj->get_pro_feature_labels() as $pro_label ) : ?>
								<li><?php echo esc_html( $pro_label ); ?></li>
								<?php endforeach; ?>
							</ul>
							<a href="<?php echo esc_url( \CartCue\Plugin::upgrade_url( 'action_create_coupon' ) ); ?>" target="_blank" rel="noopener noreferrer" class="ap-btn ap-btn-primary ap-btn-sm">
								<?php esc_html_e( 'Upgrade to CartCue Pro', 'cartcue-sales-automation' ); ?> →
							</a>
						</div>
						<?php elseif ( ! $is_pro && method_exists( $action_obj, 'get_pro_feature_labels' ) ) : ?>
							<?php foreach ( $action_obj->get_pro_feature_labels() as $pro_label ) : ?>
						<div class="ap-field-row ap-field-row--locked">
							<label class="ap-field-label"><?php echo esc_html( $pro_label ); ?></label>
							<div class="ap-pro-lock">
								<i class="ti ti-lock" aria-hidden="true"></i> <?php esc_html_e( 'Pro', 'cartcue-sales-automation' ); ?>
							</div>
						</div>
							<?php endforeach; ?>
						<?php endif; ?>
					</div>
					<?php endif; ?>
				</div>
				<?php endforeach; ?>
			</div>
			<?php if ( $show_timeline_shell ) : ?>
					</div>
				</div>
			</div>
			<?php endif; ?>
			<div class="ap-timing-sequence-wrap <?php echo $seq_panel_open ? 'is-expanded' : ''; ?>" id="ap-timing-sequence-wrap">
				<button type="button" id="ap-timing-add-followup" class="ap-btn ap-btn-ghost ap-timing-followup-cta"
						aria-expanded="<?php echo $seq_panel_open ? 'true' : 'false'; ?>">
					+ <?php esc_html_e( 'Add follow-up step', 'cartcue-sales-automation' ); ?>
				</button>
				<div class="ap-timing-sequence-body <?php echo $seq_panel_open ? 'is-open' : ''; ?>" id="ap-sequence-body">
					<?php if ( $show_timeline_shell ) : ?>
					<div class="ap-timeline-seq-sync" id="ap-timeline-seq-sync" hidden aria-hidden="true">
					<?php endif; ?>
					<?php if ( $can_use_sequence ) : ?>
					<?php if ( ! $is_pro && $max_sequence_steps > 0 ) : ?>
					<p class="description"><?php echo esc_html( sprintf(
						/* translators: %d: maximum sequence steps on free plan */
						__( 'Free plan: up to %d timed follow-up steps. Upgrade to Pro for unlimited follow-up steps.', 'cartcue-sales-automation' ),
						$max_sequence_steps
					) ); ?></p>
					<?php endif; ?>
					<div id="ap-sequence-builder" class="ap-sequence-builder" aria-label="<?php echo esc_attr( $is_pro ? __( 'Sequence steps', 'cartcue-sales-automation' ) : __( 'Follow-up steps', 'cartcue-sales-automation' ) ); ?>"></div>
					<button type="button" id="ap-add-sequence-step" class="ap-btn ap-btn-ghost">
						+ <?php esc_html_e( 'Add another follow-up step', 'cartcue-sales-automation' ); ?>
					</button>
					<?php if ( $can_use_branching ) : ?>
					<button type="button" id="ap-add-sequence-branch" class="ap-btn ap-btn-ghost">
						+ <?php esc_html_e( 'Add If/Else branch', 'cartcue-sales-automation' ); ?>
					</button>
					<?php else : ?>
					<div class="ap-pro-gate ap-pro-gate--branch">
						<div class="ap-pro-gate__icon"><i class="ti ti-lock" aria-hidden="true"></i></div>
						<div class="ap-pro-gate__title"><?php esc_html_e( 'If/Else branching is a Pro feature', 'cartcue-sales-automation' ); ?></div>
						<p class="ap-pro-gate__desc"><?php esc_html_e( 'Free lets you filter on email opens and clicks. Pro adds If/Else branches — e.g. send a reminder if they opened, or a different offer if they did not.', 'cartcue-sales-automation' ); ?></p>
						<a href="<?php echo esc_url( \CartCue\Plugin::upgrade_url( 'play_editor_branch' ) ); ?>" target="_blank" rel="noopener noreferrer" class="ap-btn ap-btn-primary">
							<?php esc_html_e( 'Upgrade to CartCue Pro', 'cartcue-sales-automation' ); ?> →
						</a>
					</div>
					<?php endif; ?>
					<script>
					window.apSequenceInitial = <?php echo wp_json_encode( array_values( $wf_sequence ) ); ?>;
					</script>
					<?php else : ?>
					<div class="ap-pro-gate ap-pro-gate--sequence">
						<div class="ap-pro-gate__icon">🔒</div>
						<div class="ap-pro-gate__title"><?php esc_html_e( 'Multi-step sequences are a Pro feature', 'cartcue-sales-automation' ); ?></div>
						<p class="ap-pro-gate__desc"><?php esc_html_e( 'Most cart recovery sequences use 4–5 steps. Free plan includes 2. Upgrade to add unlimited follow-up steps.', 'cartcue-sales-automation' ); ?></p>
						<a href="<?php echo esc_url( \CartCue\Plugin::upgrade_url( 'play_editor_sequence' ) ); ?>" target="_blank" class="ap-btn ap-btn-primary">
							<?php esc_html_e( 'Upgrade to CartCue Pro', 'cartcue-sales-automation' ); ?> →
						</a>
					</div>
					<?php endif; ?>
					<?php if ( $show_timeline_shell ) : ?>
					</div>
					<?php endif; ?>
				</div>
			</div>

			<button type="button" id="ap-add-action" class="ap-btn ap-btn-ghost">+ <?php esc_html_e( 'Add action', 'cartcue-sales-automation' ); ?></button>
		</div>

		<div class="ap-step-panel ap-review-panel" id="ap-review-step" data-guided-step-panel="review">
			<div class="ap-step-header">
				<span class="ap-step-num">4</span>
				<div>
					<div class="ap-step-label"><?php esc_html_e( 'Activate', 'cartcue-sales-automation' ); ?></div>
					<div class="ap-step-sub"><?php esc_html_e( 'Review your sentence, then save and go live.', 'cartcue-sales-automation' ); ?></div>
				</div>
			</div>
			<?php if ( $play_has_overlap ) : ?>
			<div class="ap-notice-card ap-notice-card--warning ap-notice-card--inline">
				<strong><?php esc_html_e( 'This automation overlaps with others', 'cartcue-sales-automation' ); ?></strong>
				<p><?php esc_html_e( 'Another active automation uses the same trigger and sends a message. Customers might get multiple messages for one event.', 'cartcue-sales-automation' ); ?></p>
			</div>
			<?php endif; ?>
			<?php if ( $show_timeline_shell ) : ?>
			<div class="ap-notice-card ap-notice-card--warning ap-notice-card--inline ap-review-incomplete" id="ap-review-incomplete" hidden>
				<strong><?php esc_html_e( 'Some messages are incomplete', 'cartcue-sales-automation' ); ?></strong>
				<p class="ap-review-incomplete__intro"><?php esc_html_e( 'Complete these steps before activating:', 'cartcue-sales-automation' ); ?></p>
				<ul class="ap-review-incomplete__list" id="ap-review-incomplete-list"></ul>
			</div>
			<?php endif; ?>
			<div class="ap-review-card">
				<div class="ap-review-card__label"><?php esc_html_e( 'This automation will:', 'cartcue-sales-automation' ); ?></div>
				<div class="ap-review-sentence" id="ap-review-sentence">
					<?php esc_html_e( 'When', 'cartcue-sales-automation' ); ?>
					<strong data-review-part="when"><?php esc_html_e( 'something happens', 'cartcue-sales-automation' ); ?></strong>
					<span>→</span>
					<strong data-review-part="wait"><?php esc_html_e( 'immediately', 'cartcue-sales-automation' ); ?></strong>
					<span>→</span>
					<strong data-review-part="then"><?php esc_html_e( 'do something', 'cartcue-sales-automation' ); ?></strong>
				</div>
				<dl class="ap-review-details">
					<div class="ap-review-details__row">
						<dt><?php esc_html_e( 'Automation name', 'cartcue-sales-automation' ); ?></dt>
						<dd data-review-part="name">—</dd>
					</div>
					<?php if ( $has_email_action ) : ?>
					<div class="ap-review-details__row">
						<dt><?php esc_html_e( 'Subject line', 'cartcue-sales-automation' ); ?></dt>
						<dd data-review-part="subject">—</dd>
					</div>
					<?php endif; ?>
					<div class="ap-review-details__row">
						<dt><?php esc_html_e( 'Audience filters', 'cartcue-sales-automation' ); ?></dt>
						<dd data-review-part="filters">—</dd>
					</div>
					<div class="ap-review-details__row">
						<dt><?php esc_html_e( 'Follow-up steps', 'cartcue-sales-automation' ); ?></dt>
						<dd data-review-part="sequence">—</dd>
					</div>
				</dl>
			</div>
			<div class="ap-timing-timeline ap-timing-timeline--review" id="ap-review-timeline" aria-live="polite"></div>
			<div class="ap-review-settings">
				<h3 class="ap-review-settings__title"><?php esc_html_e( 'Settings', 'cartcue-sales-automation' ); ?></h3>
				<div class="ap-review-settings__block">
					<label for="ap-play-name-review" class="ap-field-label"><?php esc_html_e( 'Automation name', 'cartcue-sales-automation' ); ?></label>
					<input type="text" id="ap-play-name-review" class="ap-input" value="<?php echo esc_attr( $src['name'] ?? '' ); ?>" placeholder="<?php esc_attr_e( 'e.g. Abandoned Cart Recovery', 'cartcue-sales-automation' ); ?>" autocomplete="off">
				</div>

				<div class="ap-review-settings__block ap-inline-conditions">
					<div class="ap-inline-conditions__header">
						<div class="ap-step-label"><?php esc_html_e( 'Who should receive this?', 'cartcue-sales-automation' ); ?></div>
						<button type="button" class="ap-collapse-btn ap-collapse-btn--conditions" id="ap-conditions-toggle"
								data-open-label="<?php esc_attr_e( 'Hide filters', 'cartcue-sales-automation' ); ?>"
								data-closed-label="<?php esc_attr_e( 'Add audience filters', 'cartcue-sales-automation' ); ?>"
								aria-expanded="<?php echo $has_conditions_data ? 'true' : 'false'; ?>">
							<?php echo $has_conditions_data
								? esc_html__( 'Hide filters', 'cartcue-sales-automation' )
								: esc_html__( 'Add audience filters', 'cartcue-sales-automation' ); ?>
						</button>
					</div>
					<div class="ap-conditions-body <?php echo $has_conditions_data ? 'is-open' : ''; ?>" id="ap-conditions-body">
						<div id="ap-rules-list">
							<?php if ( empty( $wf_rules ) ) : ?>
							<p class="ap-rules-empty"><?php esc_html_e( 'All customers who match the trigger. Optionally filter by order history, product, or role.', 'cartcue-sales-automation' ); ?></p>
							<?php endif; ?>
							<?php foreach ( $wf_rules as $i => $rule ) :
								$rule_obj = $plugin->get_rule( $rule['slug'] ?? '' ); ?>
							<div class="ap-rule-row ap-rule-row--sentence" data-index="<?php echo esc_attr( $i ); ?>">
								<span class="ap-rule-prefix"><?php esc_html_e( 'Customer', 'cartcue-sales-automation' ); ?></span>
								<select name="rules[<?php echo esc_attr( $i ); ?>][slug]" class="ap-select ap-rule-slug">
									<option value="">— <?php esc_html_e( 'Choose a filter', 'cartcue-sales-automation' ); ?> —</option>
									<?php foreach ( $plugin->get_rules() as $rs => $ro ) : ?>
									<option value="<?php echo esc_attr( $rs ); ?>" <?php selected( $rule['slug'] ?? '', $rs ); ?>><?php echo esc_html( $ro->get_label() ); ?></option>
									<?php endforeach; ?>
								</select>
								<?php if ( $rule_obj ) : ?>
								<select name="rules[<?php echo esc_attr( $i ); ?>][operator]" class="ap-select ap-rule-op">
									<?php foreach ( $rule_obj->get_operators() as $ok => $ol ) : ?>
									<option value="<?php echo esc_attr( $ok ); ?>" <?php selected( $rule['operator'] ?? '', $ok ); ?>><?php echo esc_html( $ol ); ?></option>
									<?php endforeach; ?>
								</select>
								<?php if ( 'hidden' !== $rule_obj->get_value_type() ) :
									if ( 'select' === $rule_obj->get_value_type() ) : ?>
									<select name="rules[<?php echo esc_attr( $i ); ?>][value]" class="ap-select ap-rule-val">
										<?php foreach ( $rule_obj->get_value_options() as $vk => $vl ) : ?>
										<option value="<?php echo esc_attr( $vk ); ?>" <?php selected( $rule['value'] ?? '', $vk ); ?>><?php echo esc_html( $vl ); ?></option>
										<?php endforeach; ?>
									</select>
									<?php elseif ( 'async_select' === $rule_obj->get_value_type() ) : ?>
									<input type="text"
										class="ap-input ap-rule-val ap-async-input"
										name="rules[<?php echo esc_attr( $i ); ?>][value]"
										value="<?php echo esc_attr( $rule['value'] ?? '' ); ?>"
										data-async-source="<?php echo esc_attr( $rule_obj->get_value_source() ); ?>"
										data-async-multiple="<?php echo $rule_obj->is_value_multiple() ? '1' : '0'; ?>"
										placeholder="<?php echo esc_attr( $rule_obj->get_value_placeholder() ); ?>">
									<?php else : ?>
									<input type="text" class="ap-input ap-rule-val" name="rules[<?php echo esc_attr( $i ); ?>][value]" value="<?php echo esc_attr( $rule['value'] ?? '' ); ?>">
									<?php endif; endif; ?>
								<?php endif; ?>
								<button type="button" class="ap-icon-btn ap-remove-rule" aria-label="<?php esc_attr_e( 'Remove filter', 'cartcue-sales-automation' ); ?>">✕</button>
							</div>
							<?php endforeach; ?>
						</div>
						<button type="button" id="ap-add-rule" class="ap-btn ap-btn-ghost">+ <?php esc_html_e( 'Add filter', 'cartcue-sales-automation' ); ?></button>
						<div id="cartcue-audience-count" class="ap-audience-count"></div>
					</div>
				</div>

				<div class="ap-review-settings__block">
					<div class="ap-inline-conditions__header">
						<div class="ap-step-label"><?php esc_html_e( 'Advanced settings', 'cartcue-sales-automation' ); ?></div>
						<button type="button" class="ap-collapse-btn" id="ap-advanced-settings-toggle"
								data-open-label="<?php esc_attr_e( 'Hide advanced settings', 'cartcue-sales-automation' ); ?>"
								data-closed-label="<?php esc_attr_e( 'Show advanced settings', 'cartcue-sales-automation' ); ?>"
								aria-expanded="false">
							<?php esc_html_e( 'Show advanced settings', 'cartcue-sales-automation' ); ?>
						</button>
					</div>
					<div id="ap-advanced-settings-body" class="ap-conditions-body">
				<div class="ap-review-settings__block ap-review-section">
				<div class="ap-review-section__label">
					<?php esc_html_e( 'Frequency', 'cartcue-sales-automation' ); ?>
				</div>
				<div class="ap-freq-pills">
					<button type="button" class="ap-freq-pill <?php echo ( 0 === $max_runs && 0 === $cooldown ) ? 'is-selected' : ''; ?>"
							data-max-runs="0" data-cooldown="0">
						<?php esc_html_e( 'Every time', 'cartcue-sales-automation' ); ?>
					</button>
					<button type="button" class="ap-freq-pill <?php echo ( 1 === $max_runs ) ? 'is-selected' : ''; ?>"
							data-max-runs="1" data-cooldown="0">
						<?php esc_html_e( 'Once per customer', 'cartcue-sales-automation' ); ?>
					</button>
					<button type="button" class="ap-freq-pill <?php echo $cooldown > 0 ? 'is-selected' : ''; ?>"
							data-custom="cooldown" data-max-runs="0" data-cooldown="custom">
						<?php esc_html_e( 'At most every', 'cartcue-sales-automation' ); ?>
						<input type="number" id="ap-cooldown-val" class="ap-input ap-input--tiny"
							   value="<?php echo esc_attr( $cooldown ?: 30 ); ?>" min="1" onclick="event.stopPropagation()">
						<?php esc_html_e( 'days', 'cartcue-sales-automation' ); ?>
					</button>
				</div>
				<input type="hidden" name="max_runs_per_customer" id="ap-max-runs" value="<?php echo esc_attr( $max_runs ); ?>">
				<input type="hidden" name="cooldown_days" id="ap-cooldown-days" value="<?php echo esc_attr( $cooldown ); ?>">
				</div>
					<?php if ( ! empty( $campaigns ) ) : ?>
				<div class="ap-review-settings__block ap-review-settings__block--tertiary">
					<label class="ap-field-label"><?php esc_html_e( 'Campaign (optional)', 'cartcue-sales-automation' ); ?></label>
					<select name="campaign_id" class="ap-select">
						<option value="0"><?php esc_html_e( '— No campaign —', 'cartcue-sales-automation' ); ?></option>
						<?php foreach ( $campaigns as $campaign ) : ?>
						<option value="<?php echo esc_attr( $campaign['id'] ); ?>" <?php selected( (int) ( $play['campaign_id'] ?? 0 ), (int) $campaign['id'] ); ?>>
							<?php echo esc_html( $campaign['name'] ); ?>
						</option>
						<?php endforeach; ?>
					</select>
				</div>
					<?php endif; ?>

					<?php if ( ! $play || 'paused' === ( $play['status'] ?? 'paused' ) ) : ?>
				<div class="ap-review-settings__block" id="ap-past-matches-row">
					<label class="ap-checkbox-label">
						<input type="checkbox" name="send_to_past_matches" value="1" <?php checked( (int) ( $play['send_to_past_matches'] ?? 0 ), 1 ); ?>>
						<?php esc_html_e( 'Also apply to existing customers who already match', 'cartcue-sales-automation' ); ?>
					</label>
					<p class="description" id="ap-past-count-hint">
						<?php esc_html_e( 'This will send to customers who already match today. For lists over 500, start with a date filter (for example: purchased in last 30 days).', 'cartcue-sales-automation' ); ?>
					</p>
				</div>
					<?php endif; ?>
					</div>
				</div>

				<div class="ap-review-settings__block">
					<div class="ap-review-section__label"><?php esc_html_e( 'Status', 'cartcue-sales-automation' ); ?></div>
					<div class="ap-status-toggle" role="group" aria-label="<?php esc_attr_e( 'Automation status', 'cartcue-sales-automation' ); ?>">
						<button type="button" class="ap-status-toggle__btn <?php echo 'active' === $wf_status ? 'is-selected' : ''; ?>"
								data-status="active" aria-pressed="<?php echo 'active' === $wf_status ? 'true' : 'false'; ?>" <?php disabled( $at_active_limit && 'active' !== $wf_status ); ?>>
							<?php esc_html_e( 'Active', 'cartcue-sales-automation' ); ?>
						</button>
						<button type="button" class="ap-status-toggle__btn <?php echo 'paused' === $wf_status ? 'is-selected' : ''; ?>"
								data-status="paused" aria-pressed="<?php echo 'paused' === $wf_status ? 'true' : 'false'; ?>">
							<?php esc_html_e( 'Paused', 'cartcue-sales-automation' ); ?>
						</button>
					</div>
					<input type="hidden" name="status" id="ap-status-input" value="<?php echo esc_attr( $wf_status ); ?>">
					<?php if ( $at_active_limit && 'active' !== $wf_status ) : ?>
					<p class="description">
						<?php
						echo esc_html(
							sprintf(
								/* translators: %d: maximum active automations on the free plan */
								__( 'Free plan allows %d active automations. Pause another or upgrade to Pro.', 'cartcue-sales-automation' ),
								$max_active_plays
							)
						);
						?>
						<a href="<?php echo esc_url( \CartCue\Plugin::upgrade_url( 'active_play_limit' ) ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Upgrade to Pro', 'cartcue-sales-automation' ); ?> →</a>
					</p>
					<?php endif; ?>
				</div>

			</div>

			<div class="ap-save-row ap-save-row--review">
				<p id="ap-ghost-save-hint" class="ap-ghost-save-hint" style="display:<?php echo $is_ghost_trigger ? 'block' : 'none'; ?>;">
					<?php esc_html_e( 'Pro-only triggers cannot be saved on the free plan. Pick a trigger above or upgrade to Pro.', 'cartcue-sales-automation' ); ?>
				</p>
				<button type="submit" class="ap-btn ap-btn-primary ap-btn-lg ap-save-submit" id="ap-save-submit"<?php echo $is_ghost_trigger ? ' disabled' : ''; ?>>
					<?php echo 'active' === $wf_status
						? esc_html__( 'Save & Activate', 'cartcue-sales-automation' )
						: esc_html__( 'Save (Paused)', 'cartcue-sales-automation' ); ?> ✓
				</button>
			</div>

			<?php if ( ! $is_pro ) : ?>
			<div class="ap-review-upgrade-nudge">
				<strong><?php esc_html_e( 'Want more power?', 'cartcue-sales-automation' ); ?></strong>
				<p><?php esc_html_e( 'Pro unlocks birthday triggers, manual campaigns, SMS, webhooks, If/Else branching, and unlimited follow-up steps.', 'cartcue-sales-automation' ); ?></p>
				<a href="<?php echo esc_url( \CartCue\Plugin::upgrade_url( 'review_step_upsell' ) ); ?>"
				   target="_blank" rel="noopener noreferrer" class="ap-btn ap-btn-ghost ap-btn-sm">
					<?php esc_html_e( 'See what\'s in Pro →', 'cartcue-sales-automation' ); ?>
				</a>
			</div>
			<?php endif; ?>
		</div>

		<div class="ap-guided-actions" id="ap-guided-actions">
			<button type="button" class="ap-btn ap-guided-prev"><?php esc_html_e( 'Back', 'cartcue-sales-automation' ); ?></button>
			<button type="button" class="ap-btn ap-btn-primary ap-guided-next"><?php esc_html_e( 'Next step', 'cartcue-sales-automation' ); ?></button>
		</div>

		<?php
		$vars_all = [
			'{{customer.first_name}}'    => __( 'First name', 'cartcue-sales-automation' ),
			'{{customer.last_name}}'     => __( 'Last name', 'cartcue-sales-automation' ),
			'{{customer.email}}'         => __( 'Email address', 'cartcue-sales-automation' ),
			'{{order.number}}'           => __( 'Order number', 'cartcue-sales-automation' ),
			'{{order.total}}'            => __( 'Order total', 'cartcue-sales-automation' ),
			'{{order.items}}'            => __( 'Items list (HTML)', 'cartcue-sales-automation' ),
			'{{order.status}}'           => __( 'Order status', 'cartcue-sales-automation' ),
			'{{shop.name}}'              => __( 'Store name', 'cartcue-sales-automation' ),
			'{{shop.url}}'               => __( 'Store URL', 'cartcue-sales-automation' ),
			'{{shop.unsubscribe_url}}'   => __( 'Unsubscribe link', 'cartcue-sales-automation' ),
			'{{order.payment_url}}'      => __( 'Payment retry link', 'cartcue-sales-automation' ),
			'{{order.tracking_link}}'    => __( 'Shipment tracking link', 'cartcue-sales-automation' ),
			'{{order.cross_sells}}'      => __( 'Cross-sell products', 'cartcue-sales-automation' ),
			'{{order.related_products}}' => __( 'Related products', 'cartcue-sales-automation' ),
			'{{coupon.code}}'            => __( 'Coupon code', 'cartcue-sales-automation' ),
			'{{coupon.expiry}}'          => __( 'Coupon expiry date', 'cartcue-sales-automation' ),
			'{{coupon.amount}}'          => __( 'Coupon amount', 'cartcue-sales-automation' ),
			'{{order.admin_url}}'        => __( 'Admin order URL', 'cartcue-sales-automation' ),
			'{{review.rating}}'          => __( 'Review star rating', 'cartcue-sales-automation' ),
			'{{review.product}}'         => __( 'Reviewed product', 'cartcue-sales-automation' ),
			'{{product.name}}'           => __( 'Product name', 'cartcue-sales-automation' ),
			'{{product.stock}}'          => __( 'Stock quantity', 'cartcue-sales-automation' ),
			'{{product.threshold}}'      => __( 'Low-stock threshold', 'cartcue-sales-automation' ),
		];
		?>
	</form>
	</div>
	</div>
</div>

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