<?php
/**
 * Onboarding Checklist Feature
 *
 * Provides a horizontal progress bar onboarding checklist that appears at the top
 * of plugin admin pages when setup is incomplete.
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Initialize onboarding hooks
 */
function saiap_onboarding_init() {
	// Only show on plugin admin pages (any tab under the main plugin page).
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( is_admin() && isset( $_GET['page'] ) && 'saiap' === sanitize_text_field( wp_unslash( $_GET['page'] ) ) ) {
		// Use trial-aware onboarding routing.
		$scenario = function_exists( 'saiap_get_user_scenario' ) ? saiap_get_user_scenario() : 'no_trial_no_keys';

		switch ( $scenario ) {
			case 'no_trial_no_keys':
			case 'no_trial_has_keys':
				// Dashboard handles trial CTA for these scenarios.
				// No separate onboarding checklist needed.
				break;

			case 'active_trial':
				// Trial progress: Show progress through trial setup.
				// Disabled: Banner removed as it duplicates calendar information below.
				// add_action( 'admin_notices', 'saiap_render_trial_progress_onboarding' );
				break;

			case 'expired_trial':
				// Don't show onboarding - paywall notice takes precedence.
				// The global banner and dashboard handle expired trial messaging.
				break;

			case 'paid':
				// Paid users: No onboarding banner needed - dashboard shows full functionality.
				break;

			default:
				// Fallback - no onboarding shown.
				break;
		}
	}

	// Register AJAX handlers.
	add_action( 'wp_ajax_saiap_dismiss_onboarding', 'saiap_ajax_dismiss_onboarding' );
}
add_action( 'admin_init', 'saiap_onboarding_init' );

/**
 * Check if Step 1 is complete: Save at least one AI provider API key (or have premium license)
 */
function saiap_onboarding_step1_complete() {

	// Check if any API key is saved
	$openai_key    = get_option( 'saiap_openai_api_key', '' );
	$anthropic_key = get_option( 'saiap_anthropic_api_key', '' );
	$gemini_key    = get_option( 'saiap_gemini_api_key', '' );

	return ! empty( $openai_key ) || ! empty( $anthropic_key ) || ! empty( $gemini_key );
}

/**
 * Check if Step 2 is complete: Generate first post (detected via prompt history)
 */
function saiap_onboarding_step2_complete() {
	global $wpdb;

	$table_name = $wpdb->prefix . 'saiap_prompts';
	// Using direct query with sanitized table name (WordPress core table prefix + hardcoded suffix)
	$count = $wpdb->get_var( "SELECT COUNT(*) FROM {$table_name}" );

	return $count > 0;
}

/**
 * Check if Step 3 is complete: Publish first generated post (detected via prompt-post relationship and post status)
 */
function saiap_onboarding_step3_complete() {
	global $wpdb;

	$prompt_posts_table = $wpdb->prefix . 'saiap_prompt_posts';

	// Get all post IDs that were generated from prompts
	// Using direct query with sanitized table name (WordPress core table prefix + hardcoded suffix)
	$post_ids = $wpdb->get_col( "SELECT post_id FROM {$prompt_posts_table}" );

	if ( empty( $post_ids ) ) {
		return false;
	}

	// Check if any of these posts are published
	$post_ids        = array_map( 'intval', $post_ids ); // Ensure all are integers
	$placeholders    = implode( ',', array_fill( 0, count( $post_ids ), '%d' ) );
	$published_count = $wpdb->get_var(
		$wpdb->prepare(
			"SELECT COUNT(*) FROM {$wpdb->posts} WHERE ID IN ({$placeholders}) AND post_status = %s",
			array_merge( $post_ids, array( 'publish' ) )
		)
	);

	return $published_count > 0;
}

/**
 * Check if onboarding is complete
 */
function saiap_onboarding_is_complete() {
	return saiap_onboarding_step1_complete() &&
			saiap_onboarding_step2_complete() &&
			saiap_onboarding_step3_complete();
}

/**
 * Check if onboarding has been dismissed
 */
function saiap_onboarding_is_dismissed() {
	return get_option( 'saiap_onboarding_dismissed', false );
}

/**
 * Check if a premium onboarding step is complete.
 *
 * @param int $step Step number (1–4).
 * @return bool
 */
function saiap_premium_onboarding_step_is_complete( $step ) {
	$step = (int) $step;

	if ( $step < 1 || $step > 4 ) {
		return false;
	}

	$option_key = 'saiap_premium_onboarding_step' . $step . '_done';

	// Step 1 is also complete if site context has been updated (even if flag wasn't set).
	if ( 1 === $step ) {
		$context_last_updated = (int) get_option( 'saiap_context_last_updated', 0 );
		if ( $context_last_updated > 0 ) {
			return true;
		}
	}

	return (bool) get_option( $option_key, false );
}

/**
 * Mark a premium onboarding step as complete.
 *
 * @param int $step Step number (1–4).
 * @return void
 */
function saiap_premium_onboarding_mark_step_complete( $step ) {
	$step = (int) $step;

	if ( $step < 1 || $step > 4 ) {
		return;
	}

	$option_key = 'saiap_premium_onboarding_step' . $step . '_done';

	if ( ! get_option( $option_key, false ) ) {
		update_option( $option_key, true );
	}
}

/**
 * Check if premium onboarding is complete.
 *
 * @return bool
 */
function saiap_premium_onboarding_is_complete() {
	for ( $step = 1; $step <= 4; $step++ ) {
		if ( ! saiap_premium_onboarding_step_is_complete( $step ) ) {
			return false;
		}
	}

	return true;
}

/**
 * Check if premium onboarding has been dismissed.
 *
 * @return bool
 */
function saiap_premium_onboarding_is_dismissed() {
	return (bool) get_option( 'saiap_premium_onboarding_dismissed', false );
}

/**
 * Get the steps configuration for premium onboarding.
 *
 * @return array[]
 */
function saiap_get_premium_onboarding_steps() {
	$step1_complete = saiap_premium_onboarding_step_is_complete( 1 );
	$step2_complete = saiap_premium_onboarding_step_is_complete( 2 );
	$step3_complete = saiap_premium_onboarding_step_is_complete( 3 );
	$step4_complete = saiap_premium_onboarding_step_is_complete( 4 );

	$post_types_url = add_query_arg(
		array(
			'page' => 'saiap',
			'tab'  => 'site-context',
		),
		admin_url( 'admin.php' )
	) . '#saiap-post-types-section';

	$step1_description = sprintf(
		/* translators: 1: opening link tag, 2: closing link tag. */
		__(
			'Run “Update Context Now” so the AI learns your content, keywords, and style. %1$sAdd a Post Type template%2$s so the AI knows exactly what structure to use.',
			'clearpost-simple-ai-auto-post'
		),
		'<a href="' . esc_url( $post_types_url ) . '" target="_blank" rel="noopener noreferrer">',
		'</a>'
	);

	return array(
		array(
			'number'         => 1,
			'completed'      => $step1_complete,
			'title'          => __( 'Teach ClearPost your site', 'clearpost-simple-ai-auto-post' ),
			'description'    => $step1_description,
			'primary_action' => array(
				'label'      => __( 'Go to Context tab', 'clearpost-simple-ai-auto-post' ),
				'url'        => add_query_arg(
					array(
						'page' => 'saiap',
						'tab'  => 'site-context',
					),
					admin_url( 'admin.php' )
				),
				'is_primary' => true,
				'enabled'    => ! $step1_complete,
			),
		),
		array(
			'number'         => 2,
			'completed'      => $step2_complete,
			'title'          => __( 'Generate your first Premium draft', 'clearpost-simple-ai-auto-post' ),
			'description'    => __( 'Use the Generate tab to create a post using your site context and SEO plan.', 'clearpost-simple-ai-auto-post' ),
			'primary_action' => array(
				'label'      => __( 'Open Generate', 'clearpost-simple-ai-auto-post' ),
				'url'        => add_query_arg(
					array(
						'page' => 'saiap',
						'tab'  => 'settings',
					),
					admin_url( 'admin.php' )
				),
				'is_primary' => false,
				'enabled'    => $step1_complete && ! $step2_complete,
			),
		),
		array(
			'number'         => 3,
			'completed'      => $step3_complete,
			'title'          => __( 'View your Content Calendar', 'clearpost-simple-ai-auto-post' ),
			'description'    => __( 'See your SEO-powered 30-day content calendar on the Dashboard.', 'clearpost-simple-ai-auto-post' ),
			'primary_action' => array(
				'label'      => __( 'Open Dashboard', 'clearpost-simple-ai-auto-post' ),
				'url'        => add_query_arg(
					array(
						'page' => 'saiap',
						'tab'  => 'dashboard',
					),
					admin_url( 'admin.php' )
				),
				'is_primary' => false,
				'enabled'    => $step2_complete && ! $step3_complete,
			),
		),
		array(
			'number'         => 4,
			'completed'      => $step4_complete,
			'title'          => __( 'Enable Autopilot', 'clearpost-simple-ai-auto-post' ),
			'description'    => __( 'Turn on autopilot and ClearPost will generate drafts automatically from your calendar.', 'clearpost-simple-ai-auto-post' ),
			'primary_action' => array(
				'label'      => __( 'Configure Autopilot', 'clearpost-simple-ai-auto-post' ),
				'url'        => add_query_arg(
					array(
						'page' => 'saiap',
						'tab'  => 'dashboard',
					),
					admin_url( 'admin.php' )
				),
				'is_primary' => false,
				'enabled'    => $step3_complete && ! $step4_complete,
			),
		),
	);
}

// =============================================================================
// Trial-Aware Onboarding Functions
// =============================================================================

/**
 * Render trial-first onboarding for users without trial and without API keys.
 *
 * This is the primary onboarding for new users. The goal is to get them
 * started with a free trial as quickly as possible.
 */
function saiap_render_trial_first_onboarding() {
	// Don't show if dismissed.
	if ( saiap_trial_onboarding_is_dismissed() ) {
		return;
	}

	$step1_complete = saiap_has_active_trial();
	$step2_complete = saiap_trial_onboarding_step_complete( 'site_analyzed' );
	$step3_complete = saiap_trial_onboarding_step_complete( 'first_post_generated' );

	// If all steps complete, don't show.
	if ( $step1_complete && $step2_complete && $step3_complete ) {
		return;
	}

	$completed_steps     = ( $step1_complete ? 1 : 0 ) + ( $step2_complete ? 1 : 0 ) + ( $step3_complete ? 1 : 0 );
	$progress_percentage = ( $completed_steps / 3 ) * 100;

	?>
	<div id="saiap-onboarding-checklist" class="notice notice-info is-dismissible saiap-trial-onboarding">
		<div class="saiap-onboarding-container">
			<div class="saiap-onboarding-header">
				<h3><?php esc_html_e( 'Get Started with ClearPost', 'clearpost-simple-ai-auto-post' ); ?></h3>
				<p><?php esc_html_e( 'Let AI run your content engine on autopilot:', 'clearpost-simple-ai-auto-post' ); ?></p>
			</div>

			<div class="saiap-onboarding-progress">
				<div class="saiap-progress-bar">
					<div class="saiap-progress-fill" style="width: <?php echo esc_attr( $progress_percentage ); ?>%;"></div>
				</div>
				<div class="saiap-progress-text">
					<?php
					printf(
						/* translators: 1: completed steps, 2: total steps. */
						esc_html__( '%1$d/%2$d steps completed', 'clearpost-simple-ai-auto-post' ),
						(int) $completed_steps,
						3
					);
					?>
				</div>
			</div>

			<div class="saiap-onboarding-steps">
				<!-- Step 1: Start Free Trial -->
				<div class="saiap-step <?php echo $step1_complete ? 'completed' : 'incomplete'; ?>">
					<div class="saiap-step-indicator">
						<?php if ( $step1_complete ) : ?>
							<span class="dashicons dashicons-yes-alt"></span>
						<?php else : ?>
							<span class="saiap-step-number">1</span>
						<?php endif; ?>
					</div>
					<div class="saiap-step-content">
						<h4><?php esc_html_e( 'Start Free Trial', 'clearpost-simple-ai-auto-post' ); ?></h4>
						<p><?php esc_html_e( 'Experience the full power of automated SEO content generation. No credit card required.', 'clearpost-simple-ai-auto-post' ); ?></p>
						<?php if ( ! $step1_complete ) : ?>
							<button type="button" class="button button-primary saiap-step-primary-action saiap-start-trial-btn">
								<?php esc_html_e( 'Start 7-Day Free Trial', 'clearpost-simple-ai-auto-post' ); ?>
							</button>
						<?php endif; ?>
					</div>
				</div>

				<!-- Step 2: Site Analysis -->
				<div class="saiap-step <?php echo $step2_complete ? 'completed' : 'incomplete'; ?>">
					<div class="saiap-step-indicator">
						<?php if ( $step2_complete ) : ?>
							<span class="dashicons dashicons-yes-alt"></span>
						<?php else : ?>
							<span class="saiap-step-number">2</span>
						<?php endif; ?>
					</div>
					<div class="saiap-step-content">
						<h4><?php esc_html_e( 'Teach ClearPost Your Site', 'clearpost-simple-ai-auto-post' ); ?></h4>
						<p><?php esc_html_e( 'ClearPost will analyze your content, keywords, and writing style to match your brand.', 'clearpost-simple-ai-auto-post' ); ?></p>
						<?php if ( $step1_complete && ! $step2_complete ) : ?>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=saiap&tab=site-context' ) ); ?>" class="saiap-step-link">
								<?php esc_html_e( 'Run Site Analysis →', 'clearpost-simple-ai-auto-post' ); ?>
							</a>
						<?php endif; ?>
					</div>
				</div>

				<!-- Step 3: Watch Posts Generate -->
				<div class="saiap-step <?php echo $step3_complete ? 'completed' : 'incomplete'; ?>">
					<div class="saiap-step-indicator">
						<?php if ( $step3_complete ) : ?>
							<span class="dashicons dashicons-yes-alt"></span>
						<?php else : ?>
							<span class="saiap-step-number">3</span>
						<?php endif; ?>
					</div>
					<div class="saiap-step-content">
						<h4><?php esc_html_e( 'Watch the Magic', 'clearpost-simple-ai-auto-post' ); ?></h4>
						<p><?php esc_html_e( 'Your 30-day content calendar is ready. ClearPost generates and schedules posts automatically.', 'clearpost-simple-ai-auto-post' ); ?></p>
						<?php if ( $step2_complete && ! $step3_complete ) : ?>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=saiap&tab=dashboard' ) ); ?>" class="saiap-step-link">
								<?php esc_html_e( 'View Dashboard →', 'clearpost-simple-ai-auto-post' ); ?>
							</a>
						<?php endif; ?>
					</div>
				</div>
			</div>

			<div class="saiap-onboarding-help">
				<p>
					<?php esc_html_e( 'Prefer manual control?', 'clearpost-simple-ai-auto-post' ); ?>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=saiap&tab=ai-settings' ) ); ?>" class="saiap-help-link">
						<?php esc_html_e( 'Add your own API keys instead', 'clearpost-simple-ai-auto-post' ); ?>
					</a>
				</p>
			</div>
		</div>

		<button type="button" class="notice-dismiss" onclick="saiapDismissOnboarding()">
			<span class="screen-reader-text"><?php esc_html_e( 'Dismiss this notice.', 'clearpost-simple-ai-auto-post' ); ?></span>
		</button>
	</div>
	<?php
}

/**
 * Render trial upgrade onboarding for users without trial but with API keys.
 *
 * These users have already invested in manual setup. Show them the value
 * of upgrading to automation.
 */
function saiap_render_trial_upgrade_onboarding() {
	// Don't show if dismissed.
	if ( saiap_trial_onboarding_is_dismissed() ) {
		return;
	}

	?>
	<div id="saiap-onboarding-checklist" class="notice notice-info is-dismissible saiap-trial-upgrade-onboarding">
		<div class="saiap-onboarding-container">
			<div class="saiap-onboarding-header saiap-onboarding-header--compact">
				<div class="saiap-onboarding-header__content">
					<h3><?php esc_html_e( 'Unlock Automated Publishing', 'clearpost-simple-ai-auto-post' ); ?></h3>
					<p><?php esc_html_e( 'You have API keys configured for manual generation. Try automated publishing with SEO keyword research, content calendar, and autopilot — free for 7 days.', 'clearpost-simple-ai-auto-post' ); ?></p>
				</div>
				<div class="saiap-onboarding-header__action">
					<button type="button" class="button button-primary saiap-start-trial-btn">
						<?php esc_html_e( 'Start Free Trial', 'clearpost-simple-ai-auto-post' ); ?>
					</button>
				</div>
			</div>
		</div>

		<button type="button" class="notice-dismiss" onclick="saiapDismissOnboarding()">
			<span class="screen-reader-text"><?php esc_html_e( 'Dismiss this notice.', 'clearpost-simple-ai-auto-post' ); ?></span>
		</button>
	</div>
	<?php
}

/**
 * Render trial progress onboarding for active trial users.
 *
 * Shows progress through the trial setup: Site analyzed, strategy created,
 * posts generating.
 */
function saiap_render_trial_progress_onboarding() {
	// Don't show if dismissed or all steps complete.
	if ( saiap_trial_onboarding_is_dismissed() ) {
		return;
	}

	$step1_complete = saiap_trial_onboarding_step_complete( 'site_analyzed' );
	$step2_complete = saiap_trial_onboarding_step_complete( 'strategy_created' );
	$step3_complete = saiap_trial_onboarding_step_complete( 'first_post_generated' );

	// If all steps complete, hide onboarding.
	if ( $step1_complete && $step2_complete && $step3_complete ) {
		return;
	}

	$days_remaining      = function_exists( 'saiap_get_trial_days_remaining' ) ? saiap_get_trial_days_remaining() : 7;
	$completed_steps     = ( $step1_complete ? 1 : 0 ) + ( $step2_complete ? 1 : 0 ) + ( $step3_complete ? 1 : 0 );
	$progress_percentage = ( $completed_steps / 3 ) * 100;

	?>
	<div id="saiap-onboarding-checklist" class="notice notice-info is-dismissible saiap-trial-progress-onboarding">
		<div class="saiap-onboarding-container">
			<div class="saiap-onboarding-header">
				<div class="saiap-onboarding-trial-badge">
					<?php
					printf(
						/* translators: %d: days remaining in trial */
						esc_html__( 'Trial: %d days remaining', 'clearpost-simple-ai-auto-post' ),
						absint( $days_remaining )
					);
					?>
				</div>
				<h3><?php esc_html_e( 'Your Content Engine is Starting Up', 'clearpost-simple-ai-auto-post' ); ?></h3>
			</div>

			<div class="saiap-onboarding-progress">
				<div class="saiap-progress-bar">
					<div class="saiap-progress-fill" style="width: <?php echo esc_attr( $progress_percentage ); ?>%;"></div>
				</div>
			</div>

			<div class="saiap-onboarding-steps saiap-onboarding-steps--horizontal">
				<!-- Step 1: Site Analyzed -->
				<div class="saiap-step <?php echo $step1_complete ? 'completed' : 'incomplete'; ?>">
					<div class="saiap-step-indicator">
						<?php if ( $step1_complete ) : ?>
							<span class="dashicons dashicons-yes-alt"></span>
						<?php else : ?>
							<span class="saiap-step-spinner spinner is-active"></span>
						<?php endif; ?>
					</div>
					<div class="saiap-step-content">
						<h4><?php esc_html_e( 'Site Analyzed', 'clearpost-simple-ai-auto-post' ); ?></h4>
						<?php if ( ! $step1_complete ) : ?>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=saiap&tab=site-context' ) ); ?>" class="saiap-step-link">
								<?php esc_html_e( 'Run Analysis →', 'clearpost-simple-ai-auto-post' ); ?>
							</a>
						<?php endif; ?>
					</div>
				</div>

				<!-- Step 2: Strategy Created -->
				<div class="saiap-step <?php echo $step2_complete ? 'completed' : 'incomplete'; ?>">
					<div class="saiap-step-indicator">
						<?php if ( $step2_complete ) : ?>
							<span class="dashicons dashicons-yes-alt"></span>
						<?php elseif ( $step1_complete ) : ?>
							<span class="saiap-step-spinner spinner is-active"></span>
						<?php else : ?>
							<span class="saiap-step-number">2</span>
						<?php endif; ?>
					</div>
					<div class="saiap-step-content">
						<h4><?php esc_html_e( 'SEO Strategy Created', 'clearpost-simple-ai-auto-post' ); ?></h4>
						<?php if ( $step1_complete && ! $step2_complete ) : ?>
							<p class="saiap-step-status"><?php esc_html_e( 'Researching keywords...', 'clearpost-simple-ai-auto-post' ); ?></p>
						<?php endif; ?>
					</div>
				</div>

				<!-- Step 3: Posts Generating -->
				<div class="saiap-step <?php echo $step3_complete ? 'completed' : 'incomplete'; ?>">
					<div class="saiap-step-indicator">
						<?php if ( $step3_complete ) : ?>
							<span class="dashicons dashicons-yes-alt"></span>
						<?php elseif ( $step2_complete ) : ?>
							<span class="saiap-step-spinner spinner is-active"></span>
						<?php else : ?>
							<span class="saiap-step-number">3</span>
						<?php endif; ?>
					</div>
					<div class="saiap-step-content">
						<h4><?php esc_html_e( 'Posts Generating', 'clearpost-simple-ai-auto-post' ); ?></h4>
						<?php if ( $step2_complete && ! $step3_complete ) : ?>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=saiap&tab=dashboard' ) ); ?>" class="saiap-step-link">
								<?php esc_html_e( 'View Dashboard →', 'clearpost-simple-ai-auto-post' ); ?>
							</a>
						<?php endif; ?>
					</div>
				</div>
			</div>
		</div>

		<button type="button" class="notice-dismiss" onclick="saiapDismissOnboarding()">
			<span class="screen-reader-text"><?php esc_html_e( 'Dismiss this notice.', 'clearpost-simple-ai-auto-post' ); ?></span>
		</button>
	</div>
	<?php
}

/**
 * Check if a trial onboarding step is complete.
 *
 * For trial users, the premium backend handles site analysis and strategy creation
 * via the automated setup process. Since there's no callback from the backend,
 * we infer completion of earlier steps from calendar items existing (the final output).
 *
 * @param string $step Step key: 'site_analyzed', 'strategy_created', 'first_post_generated'.
 * @return bool
 */
function saiap_trial_onboarding_step_complete( $step ) {
	switch ( $step ) {
		case 'site_analyzed':
			// For paid users: check if site context has been updated locally.
			$context_last_updated = (int) get_option( 'saiap_context_last_updated', 0 );
			if ( $context_last_updated > 0 ) {
				return true;
			}

			// For trial users: if calendar items exist, the backend completed
			// the entire setup (including site analysis).
			if ( function_exists( 'saiap_calendar_items_exist' ) && saiap_calendar_items_exist() ) {
				return true;
			}

			return false;

		case 'strategy_created':
			// For paid users: check context timestamp with 60+ seconds elapsed.
			$context_updated = (int) get_option( 'saiap_context_last_updated', 0 );
			if ( $context_updated > 0 && ( time() - $context_updated ) > 60 ) {
				return true;
			}

			// For trial users: if calendar items exist, the backend completed
			// the entire setup (including strategy/keyword research).
			if ( function_exists( 'saiap_calendar_items_exist' ) && saiap_calendar_items_exist() ) {
				return true;
			}

			return false;

		case 'first_post_generated':
			// Check if any post has been generated during the trial.
			$trial_started = get_option( 'saiap_trial_started_at', '' );
			if ( empty( $trial_started ) ) {
				return false;
			}
			$count = saiap_get_generated_posts_count( $trial_started );
			return $count > 0;

		default:
			return false;
	}
}

/**
 * Check if trial onboarding has been dismissed.
 *
 * @return bool
 */
function saiap_trial_onboarding_is_dismissed() {
	return (bool) get_option( 'saiap_trial_onboarding_dismissed', false );
}

/**
 * Check if user has an active trial.
 *
 * @return bool
 */
function saiap_has_active_trial() {
	if ( ! function_exists( 'saiap_get_user_scenario' ) ) {
		return false;
	}
	return 'active_trial' === saiap_get_user_scenario();
}

// =============================================================================
// Legacy Onboarding Functions (for users with API keys, no trial)
// =============================================================================

/**
 * Render the main onboarding checklist.
 */
function saiap_render_onboarding_checklist() {
	// Do not render onboarding for premium users (license key present)
	$license_key = get_option( 'saiap_license_key', '' );
	if ( ! empty( $license_key ) ) {
		return;
	}

	// Don't show if dismissed or complete
	if ( saiap_onboarding_is_dismissed() || saiap_onboarding_is_complete() ) {
		return;
	}

	$step1_complete = saiap_onboarding_step1_complete();
	$step2_complete = saiap_onboarding_step2_complete();
	$step3_complete = saiap_onboarding_step3_complete();

	$completed_steps = 0;
	if ( $step1_complete ) {
		++$completed_steps;
	}
	if ( $step2_complete ) {
		++$completed_steps;
	}
	if ( $step3_complete ) {
		++$completed_steps;
	}

	$progress_percentage = ( $completed_steps / 3 ) * 100;

	?>
	<div id="saiap-onboarding-checklist" class="notice notice-info is-dismissible">
		<div class="saiap-onboarding-container">
			<div class="saiap-onboarding-header">
				<h3><?php esc_html_e( 'Get Started with ClearPost Simple AI Auto Post', 'clearpost-simple-ai-auto-post' ); ?></h3>
				<p><?php esc_html_e( 'Complete these steps to start generating content with AI:', 'clearpost-simple-ai-auto-post' ); ?></p>
			</div>
			
			<div class="saiap-onboarding-steps">
				<div class="saiap-step <?php echo $step1_complete ? 'completed' : 'incomplete'; ?>">
					<div class="saiap-step-indicator">
						<?php if ( $step1_complete ) : ?>
							<span class="dashicons dashicons-yes-alt"></span>
						<?php else : ?>
							<span class="saiap-step-number">1</span>
						<?php endif; ?>
					</div>
					<div class="saiap-step-content">
						<h4><?php esc_html_e( 'Add AI Provider API Key', 'clearpost-simple-ai-auto-post' ); ?></h4>
						<p><?php esc_html_e( 'Configure your OpenAI, Anthropic, or Google Gemini API key to enable AI content generation.', 'clearpost-simple-ai-auto-post' ); ?></p>
						<?php if ( ! $step1_complete ) : ?>
						<a href="?page=saiap&tab=ai-settings" class="button button-primary saiap-step-primary-action"><?php esc_html_e( 'Add API Key', 'clearpost-simple-ai-auto-post' ); ?></a>
						<?php endif; ?>
					</div>
				</div>
				
				<div class="saiap-step <?php echo $step2_complete ? 'completed' : 'incomplete'; ?>">
					<div class="saiap-step-indicator">
						<?php if ( $step2_complete ) : ?>
							<span class="dashicons dashicons-yes-alt"></span>
						<?php else : ?>
							<span class="saiap-step-number">2</span>
						<?php endif; ?>
					</div>
					<div class="saiap-step-content">
						<h4><?php esc_html_e( 'Generate Your First Post', 'clearpost-simple-ai-auto-post' ); ?></h4>
						<p><?php esc_html_e( 'Create your first AI-generated content using the Generate tab.', 'clearpost-simple-ai-auto-post' ); ?></p>
						<?php if ( ! $step2_complete && $step1_complete ) : ?>
							<a href="?page=saiap&tab=settings" class="saiap-step-link"><?php esc_html_e( 'Generate Content →', 'clearpost-simple-ai-auto-post' ); ?></a>
						<?php endif; ?>
					</div>
				</div>
				
				<div class="saiap-step <?php echo $step3_complete ? 'completed' : 'incomplete'; ?>">
					<div class="saiap-step-indicator">
						<?php if ( $step3_complete ) : ?>
							<span class="dashicons dashicons-yes-alt"></span>
						<?php else : ?>
							<span class="saiap-step-number">3</span>
						<?php endif; ?>
					</div>
					<div class="saiap-step-content">
						<h4><?php esc_html_e( 'Publish Your First Post', 'clearpost-simple-ai-auto-post' ); ?></h4>
						<p><?php esc_html_e( 'Review and publish your post to start getting traffic from search and ChatGPT.', 'clearpost-simple-ai-auto-post' ); ?></p>
						<?php if ( ! $step3_complete && $step2_complete ) : ?>
							<a href="<?php echo esc_url( admin_url( 'edit.php' ) ); ?>" class="saiap-step-link"><?php esc_html_e( 'View Posts →', 'clearpost-simple-ai-auto-post' ); ?></a>
						<?php endif; ?>
					</div>
				</div>
			</div>
			
			<div class="saiap-onboarding-help">
				<p><?php esc_html_e( 'Need help?', 'clearpost-simple-ai-auto-post' ); ?> <a href="https://clearpostplugin.com/getting-started-with-clearpost-wordpress-plugin/" class="saiap-help-link" target="_blank"><?php esc_html_e( 'View our getting started guide', 'clearpost-simple-ai-auto-post' ); ?></a></p>
				<p class="saiap-onboarding-upsell-footnote"><a href="https://clearpostplugin.com/" target="_blank" rel="noopener noreferrer" class="saiap-help-link button button-primary button-hero"><?php esc_html_e( 'Skip the setup and start generating traffic on autopilot', 'clearpost-simple-ai-auto-post' ); ?></a></p>
			</div>
		</div>
		
		<button type="button" class="notice-dismiss" onclick="saiapDismissOnboarding()">
			<span class="screen-reader-text"><?php esc_html_e( 'Dismiss this notice.', 'clearpost-simple-ai-auto-post' ); ?></span>
		</button>
	</div>
	<?php
}

/**
 * Render the premium onboarding checklist.
 */
function saiap_render_premium_onboarding_checklist() {
	// Only render for licensed sites.
	$license_key = get_option( 'saiap_license_key', '' );
	if ( empty( $license_key ) ) {
		return;
	}

	if ( saiap_premium_onboarding_is_dismissed() || saiap_premium_onboarding_is_complete() ) {
		return;
	}

	$steps = saiap_get_premium_onboarding_steps();
	if ( empty( $steps ) || ! is_array( $steps ) ) {
		return;
	}

	$total_steps     = count( $steps );
	$completed_steps = 0;

	foreach ( $steps as $step ) {
		if ( ! empty( $step['completed'] ) ) {
			++$completed_steps;
		}
	}

	$progress_percentage = $total_steps > 0 ? ( $completed_steps / $total_steps ) * 100 : 0;
	?>
	<div id="saiap-onboarding-checklist" class="notice notice-info is-dismissible">
		<div class="saiap-onboarding-container">
			<div class="saiap-onboarding-header">
				<h3><?php esc_html_e( 'Get Started with ClearPost Premium', 'clearpost-simple-ai-auto-post' ); ?></h3>
				<p><?php esc_html_e( 'Complete these steps to put your AI content engine on autopilot:', 'clearpost-simple-ai-auto-post' ); ?></p>
			</div>

			<div class="saiap-onboarding-progress">
				<div class="saiap-progress-bar">
					<div class="saiap-progress-fill" style="width: <?php echo esc_attr( $progress_percentage ); ?>%;"></div>
				</div>
				<div class="saiap-progress-text">
					<?php
					printf(
						/* translators: 1: completed steps, 2: total steps. */
						esc_html__( '%1$d/%2$d steps completed', 'clearpost-simple-ai-auto-post' ),
						(int) $completed_steps,
						(int) $total_steps
					);
					?>
				</div>
			</div>

			<div class="saiap-onboarding-steps">
				<?php foreach ( $steps as $step ) : ?>
					<?php
					$is_completed       = ! empty( $step['completed'] );
					$primary_action     = isset( $step['primary_action'] ) ? $step['primary_action'] : array();
					$secondary_action   = isset( $step['secondary_action'] ) ? $step['secondary_action'] : array();
					$can_show_primary   = ! empty( $primary_action );
					$can_show_secondary = empty( $primary_action ) && ! empty( $secondary_action );
					?>
					<div class="saiap-step <?php echo $is_completed ? 'completed' : 'incomplete'; ?>">
						<div class="saiap-step-indicator">
							<?php if ( $is_completed ) : ?>
								<span class="dashicons dashicons-yes-alt"></span>
							<?php else : ?>
								<span class="saiap-step-number"><?php echo esc_html( $step['number'] ); ?></span>
							<?php endif; ?>
						</div>
						<div class="saiap-step-content">
							<h4><?php echo esc_html( $step['title'] ); ?></h4>
							<p><?php echo wp_kses_post( $step['description'] ); ?></p>
							<?php if ( $can_show_primary ) : ?>
								<a href="<?php echo esc_url( $primary_action['url'] ); ?>" class="<?php echo ! empty( $primary_action['is_primary'] ) ? 'button button-primary saiap-step-primary-action' : 'saiap-step-link'; ?>">
									<?php echo esc_html( $primary_action['label'] ); ?>
								</a>
							<?php elseif ( $can_show_secondary ) : ?>
								<a href="<?php echo esc_url( $secondary_action['url'] ); ?>" class="<?php echo ! empty( $secondary_action['is_primary'] ) ? 'button button-primary saiap-step-primary-action' : 'saiap-step-link'; ?>">
									<?php echo esc_html( $secondary_action['label'] ); ?>
								</a>
							<?php endif; ?>
						</div>
					</div>
				<?php endforeach; ?>
			</div>

			<div class="saiap-onboarding-help">
				<p>
					<?php esc_html_e( 'Want a deeper walkthrough?', 'clearpost-simple-ai-auto-post' ); ?>
					<a href="https://clearpostplugin.com/getting-started-with-clearpost-wordpress-plugin/" class="saiap-help-link" target="_blank" rel="noopener noreferrer">
						<?php esc_html_e( 'Read the getting started guide', 'clearpost-simple-ai-auto-post' ); ?>
					</a>
				</p>
			</div>
		</div>

		<button type="button" class="notice-dismiss" onclick="saiapDismissOnboarding()">
			<span class="screen-reader-text"><?php esc_html_e( 'Dismiss this notice.', 'clearpost-simple-ai-auto-post' ); ?></span>
		</button>
	</div>
	<?php
}

/**
 * AJAX handler for dismissing onboarding
 */
function saiap_ajax_dismiss_onboarding() {
	// Verify nonce.
	$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
	if ( ! wp_verify_nonce( $nonce, 'saiap_dismiss_onboarding' ) ) {
		wp_send_json_error( 'Security check failed' );
		return;
	}

	// Check user capabilities.
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'Insufficient permissions' );
		return;
	}

	// Dismiss onboarding based on user scenario.
	$scenario = function_exists( 'saiap_get_user_scenario' ) ? saiap_get_user_scenario() : 'no_trial_no_keys';

	switch ( $scenario ) {
		case 'no_trial_no_keys':
		case 'no_trial_has_keys':
		case 'active_trial':
			// Trial-related onboarding.
			update_option( 'saiap_trial_onboarding_dismissed', true );
			break;

		case 'paid':
			// Premium onboarding.
			update_option( 'saiap_premium_onboarding_dismissed', true );
			break;

		default:
			// Legacy free onboarding.
		update_option( 'saiap_onboarding_dismissed', true );
			break;
	}

	wp_send_json_success();
}

/**
 * Enqueue onboarding assets
 */
function saiap_enqueue_onboarding_assets( $hook ) {
	// Only load on plugin settings page
	if ( $hook !== 'toplevel_page_saiap' ) {
		return;
	}

	$license_key = get_option( 'saiap_license_key', '' );
	if ( empty( $license_key ) ) {
		if ( saiap_onboarding_is_dismissed() || saiap_onboarding_is_complete() ) {
			return;
		}
	} else {
		if ( saiap_premium_onboarding_is_dismissed() || saiap_premium_onboarding_is_complete() ) {
			return;
		}
	}

	// Enqueue CSS
	wp_enqueue_style(
		'saiap-onboarding',
		plugin_dir_url( __DIR__ ) . 'assets/css/onboarding.css',
		array( 'saiap-design-system' ),
		SAIAP_VERSION
	);

	// Enqueue JS
	wp_enqueue_script(
		'saiap-onboarding',
		plugin_dir_url( __DIR__ ) . 'assets/js/onboarding.js',
		array( 'jquery' ),
		SAIAP_VERSION,
		true
	);

	// Localize script
	wp_localize_script(
		'saiap-onboarding',
		'saiapOnboarding',
		array(
			'ajaxurl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( 'saiap_dismiss_onboarding' ),
			'i18n'    => array(
				'dismissSuccess' => __( 'Onboarding dismissed successfully.', 'clearpost-simple-ai-auto-post' ),
				'dismissError'   => __( 'Failed to dismiss onboarding. Please try again.', 'clearpost-simple-ai-auto-post' ),
			),
		)
	);
}
add_action( 'admin_enqueue_scripts', 'saiap_enqueue_onboarding_assets' );
