<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Forme_SEO_Admin {

	private string $hook_dashboard     = '';
	private string $hook_website_audit = '';
	private string $hook_content_plan  = '';
	private string $hook_articles      = '';
	private string $hook_reports       = '';
	private string $hook_settings      = '';

	private static array $tools = [
		'audit'           => [
			'label'  => 'SEO Audit',
			'lni'    => 'lni-search',
			'desc'   => 'Full SEO health check — meta tags, headings, content quality, and ranking signals.',
			'action' => 'forme_seo_run_audit',
		],
		'technical'       => [
			'label'  => 'Technical SEO',
			'lni'    => 'lni-cog',
			'desc'   => 'Crawlability, page speed, mobile-friendliness, and Core Web Vitals audit.',
			'action' => 'forme_seo_run_technical',
		],
		'content'         => [
			'label'  => 'Content SEO',
			'lni'    => 'lni-pencil',
			'desc'   => 'E-E-A-T signals, readability, keyword density, and content depth analysis.',
			'action' => 'forme_seo_run_content',
		],
		'schema'          => [
			'label'  => 'Schema Check',
			'lni'    => 'lni-code',
			'desc'   => 'Detect, validate, and generate Schema.org structured data for rich results.',
			'action' => 'forme_seo_run_schema',
		],
		'sitemap'         => [
			'label'  => 'Sitemap Check',
			'lni'    => 'lni-map',
			'desc'   => 'Validate XML sitemaps, check URL coverage, and flag indexation issues.',
			'action' => 'forme_seo_run_sitemap',
		],
		'images'          => [
			'label'  => 'Image SEO',
			'lni'    => 'lni-image',
			'desc'   => 'Audit alt text, file sizes, lazy loading, and next-gen format opportunities.',
			'action' => 'forme_seo_run_images',
		],
		'content-pillars' => [
			'label'  => 'Content Pillars',
			'lni'    => 'lni-link',
			'desc'   => 'Map topic clusters and identify content gaps for your authority strategy.',
			'action' => 'forme_seo_run_content_pillars',
		],
	];

	private static array $audit_tools = [
		'audit'     => [
			'label'  => 'SEO Audit',
			'lni'    => 'lni-search',
			'desc'   => 'Full SEO health check — meta tags, headings, content quality, and ranking signals.',
			'action' => 'forme_seo_run_audit',
		],
		'technical' => [
			'label'  => 'Technical SEO',
			'lni'    => 'lni-cog',
			'desc'   => 'Crawlability, page speed, mobile-friendliness, and Core Web Vitals audit.',
			'action' => 'forme_seo_run_technical',
		],
		'schema'    => [
			'label'  => 'Schema Check',
			'lni'    => 'lni-code',
			'desc'   => 'Detect, validate, and generate Schema.org structured data for rich results.',
			'action' => 'forme_seo_run_schema',
		],
		'sitemap'   => [
			'label'  => 'Sitemap Check',
			'lni'    => 'lni-map',
			'desc'   => 'Validate XML sitemaps, check URL coverage, and flag indexation issues.',
			'action' => 'forme_seo_run_sitemap',
		],
		'images'    => [
			'label'  => 'Image SEO',
			'lni'    => 'lni-image',
			'desc'   => 'Audit alt text, file sizes, lazy loading, and next-gen format opportunities.',
			'action' => 'forme_seo_run_images',
		],
	];

	public function __construct() {
		add_action( 'admin_menu',            [ $this, 'register_menus' ] );
		add_action( 'admin_init',            [ $this, 'register_settings' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
		add_action( 'forme_seo_process_audit_job', [ $this, 'process_local_audit_job' ], 10, 1 );

		$ajax_actions = [
			// Existing
			'forme_seo_register',
			'forme_seo_refresh',
			'forme_seo_test_connection',
			'forme_seo_checkout',
			'forme_seo_portal',
			'forme_seo_save_settings',
			'forme_seo_run_audit',
			'forme_seo_run_technical',
			'forme_seo_run_content',
			'forme_seo_run_schema',
			'forme_seo_run_sitemap',
			'forme_seo_run_images',
			'forme_seo_run_content_pillars',
			'forme_seo_poll_job',
			'forme_seo_gsc_auth_url',
			'forme_seo_gsc_properties',
			'forme_seo_gsc_select_property',
			'forme_seo_gsc_overview',
			'forme_seo_gsc_disconnect',
			// New
			'forme_seo_get_reports',
			'forme_seo_get_report',
			'forme_seo_get_tasks',
			'forme_seo_update_task',
			'forme_seo_get_content_projects',
			'forme_seo_get_content_project',
			'forme_seo_generate_outline',
			'forme_seo_generate_article',
			'forme_seo_get_jobs',
			'forme_seo_get_site_profile',
			'forme_seo_get_all_topics',
			'forme_seo_run_blog_strategy',
			'forme_seo_run_blog_calendar',
			'forme_seo_start_audit_async',
			'forme_seo_get_local_audit_jobs',
			'forme_seo_run_blog_write',
			'forme_seo_create_draft_post',
			'forme_seo_get_article_statuses',
		];

		foreach ( $ajax_actions as $action ) {
			add_action( "wp_ajax_{$action}", [ $this, $action ] );
		}
	}

	// ── Menus & Settings ──────────────────────────────────────────────────────

	public function register_menus(): void {
		$svg_path = FORME_SEO_DIR . 'assets/claude-seo-agent.svg';
		$svg_icon = file_exists( $svg_path )
			? 'data:image/svg+xml;base64,' . base64_encode( (string) file_get_contents( $svg_path ) )
			: 'dashicons-chart-area';

		$this->hook_dashboard = (string) add_menu_page(
			'Forme SEO AI Agent',
			'Forme SEO',
			'manage_options',
			'claude-seo-agent',
			[ $this, 'render_dashboard' ],
			$svg_icon,
			58
		);

		add_submenu_page(
			'claude-seo-agent',
			'Dashboard',
			'Dashboard',
			'manage_options',
			'claude-seo-agent',
			[ $this, 'render_dashboard' ]
		);

		$this->hook_website_audit = (string) add_submenu_page(
			'claude-seo-agent',
			'Website Audit — Forme SEO AI Agent',
			'Website Audit',
			'manage_options',
			'claude-seo-agent-website-audit',
			[ $this, 'render_website_audit' ]
		);

		$this->hook_content_plan = (string) add_submenu_page(
			'claude-seo-agent',
			'Content Plan — Forme SEO AI Agent',
			'Content Plan',
			'manage_options',
			'claude-seo-agent-content-plan',
			[ $this, 'render_content_plan' ]
		);

		$this->hook_articles = (string) add_submenu_page(
			'claude-seo-agent',
			'Articles — Forme SEO AI Agent',
			'Articles',
			'manage_options',
			'claude-seo-agent-articles',
			[ $this, 'render_articles' ]
		);

		$this->hook_reports = (string) add_submenu_page(
			'claude-seo-agent',
			'Reports — Forme SEO AI Agent',
			'Reports',
			'manage_options',
			'claude-seo-agent-reports',
			[ $this, 'render_reports' ]
		);

		$this->hook_settings = (string) add_submenu_page(
			'claude-seo-agent',
			'Settings — Forme SEO AI Agent',
			'Settings',
			'manage_options',
			'claude-seo-agent-settings',
			[ $this, 'render_settings' ]
		);
	}

	public function register_settings(): void {
		foreach (
			[
				FORME_SEO_OPT_API_BASE => [ 'type' => 'string', 'sanitize_callback' => 'esc_url_raw',         'default' => FORME_SEO_DEFAULT_API ],
				FORME_SEO_OPT_API_KEY  => [ 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'default' => '' ],
				FORME_SEO_OPT_EMAIL    => [ 'type' => 'string', 'sanitize_callback' => 'sanitize_email',      'default' => '' ],
			]
			as $key => $args
		) {
			register_setting( 'forme_seo_settings', $key, $args );
		}
	}

	public function enqueue_assets( string $hook ): void {
		$csa_hooks = [
			$this->hook_dashboard,
			$this->hook_website_audit,
			$this->hook_content_plan,
			$this->hook_articles,
			$this->hook_reports,
			$this->hook_settings,
		];
		if ( ! in_array( $hook, array_filter( $csa_hooks ), true ) ) {
			return;
		}

		wp_enqueue_style(
			'forme-seo-lineicons',
			FORME_SEO_URL . 'assets/vendor/lineicons/lineicons.css',
			[],
			'4.0'
		);

		wp_enqueue_style(
			'forme-seo-admin',
			FORME_SEO_URL . 'assets/css/admin.css',
			[ 'forme-seo-lineicons' ],
			FORME_SEO_VERSION
		);

		wp_enqueue_script(
			'forme-seo-chart',
			FORME_SEO_URL . 'assets/vendor/chart.umd.min.js',
			[],
			'4.4.0',
			true
		);

		wp_enqueue_script(
			'forme-seo-admin',
			FORME_SEO_URL . 'assets/js/admin.js',
			[ 'jquery', 'forme-seo-chart' ],
			FORME_SEO_VERSION,
			true
		);

		$api_key = (string) get_option( FORME_SEO_OPT_API_KEY, '' );

		$gsc_connected    = false;
		$gsc_property     = '';
		$has_audit        = false;
		if ( $api_key ) {
			$me = ( new Forme_SEO_API() )->me();
			if ( $me['success'] ) {
				$gsc_connected = (bool) ( $me['data']['gsc_connected']      ?? false );
				$gsc_property  = (string) ( $me['data']['gsc_property']     ?? '' );
				$has_audit     = (bool) ( $me['data']['has_completed_audit'] ?? false );
			}
		}

		wp_localize_script(
			'forme-seo-admin',
			'formeSEOAgent',
			[
				'ajaxUrl'             => admin_url( 'admin-ajax.php' ),
				'nonce'               => wp_create_nonce( 'forme_seo_nonce' ),
				'homeUrl'             => home_url(),
				'hasKey'              => ! empty( $api_key ),
				'apiBase'             => get_option( FORME_SEO_OPT_API_BASE, FORME_SEO_DEFAULT_API ),
				'gscConnected'        => $gsc_connected,
				'gscProperty'         => $gsc_property,
				'hasCompletedAudit'   => $has_audit,
				'adminUrl'        => admin_url( 'admin.php?page=claude-seo-agent' ),
				'currentPage'     => sanitize_text_field( wp_unslash( $_GET['page'] ?? '' ) ),
				'websiteAuditUrl' => admin_url( 'admin.php?page=claude-seo-agent-website-audit' ),
				'contentPlanUrl'  => admin_url( 'admin.php?page=claude-seo-agent-content-plan' ),
				'articlesUrl'     => admin_url( 'admin.php?page=claude-seo-agent-articles' ),
				'reportsUrl'      => admin_url( 'admin.php?page=claude-seo-agent-reports' ),
				'settingsUrl'     => admin_url( 'admin.php?page=claude-seo-agent-settings' ),
			]
		);
	}

	// ── Dashboard page ────────────────────────────────────────────────────────

	public function render_dashboard(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$has_key  = ! empty( get_option( FORME_SEO_OPT_API_KEY, '' ) );
		$email    = (string) get_option( FORME_SEO_OPT_EMAIL, '' );
		$api_base = (string) get_option( FORME_SEO_OPT_API_BASE, FORME_SEO_DEFAULT_API );
		?>
		<div class="csa-wrap">

			<header class="csa-header">
				<div class="csa-header-inner">
					<div class="csa-header-left">
						<div class="csa-logo">
							<img src="<?php echo esc_url( FORME_SEO_URL . 'assets/claude-seo-agent.svg' ); ?>" alt="" class="csa-logo-mark" width="28" height="28" aria-hidden="true">
							<span class="csa-logo-name">Forme SEO AI Agent</span>
							<span class="csa-version-pill">v<?php echo esc_html( FORME_SEO_VERSION ); ?></span>
						</div>
						<div class="csa-header-sub">AI-powered SEO audits and content strategy for WordPress</div>
					</div>
					<div class="csa-header-right">
						<?php if ( $has_key ) : ?>
						<div id="csa-header-badge" class="csa-header-badge csa-header-badge--checking" aria-live="polite">
							<span class="csa-header-badge-dot"></span>
							<span class="csa-header-badge-label">Checking…</span>
						</div>
						<button id="csa-refresh-btn" class="csa-hdr-btn">
							<span class="dashicons dashicons-update-alt"></span> Refresh
						</button>
						<?php else : ?>
						<div class="csa-header-badge csa-header-badge--disconnected">
							<span class="csa-header-badge-dot"></span>
							<span>Not Connected</span>
						</div>
						<?php endif; ?>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-settings' ) ); ?>" class="csa-hdr-btn">
							<span class="dashicons dashicons-admin-settings"></span> Settings
						</a>
					</div>
				</div>
			</header>

			<main class="csa-main">

			<?php if ( ! $has_key ) : ?>
				<!-- ONBOARDING — No API key -->
				<div class="csa-onboarding">
					<div class="csa-onboarding-card">
						<div class="csa-ob-icon">✦</div>
						<h2>Get started for free</h2>
						<p>Create your free API key and run AI-powered SEO audits directly from your WordPress dashboard. No credit card required.</p>

						<div class="csa-field">
							<label for="csa-reg-email">Your Email Address</label>
							<input type="email" id="csa-reg-email" placeholder="you@example.com"
								value="<?php echo esc_attr( $email ); ?>" autocomplete="email" />
						</div>

						<button id="csa-create-key-btn" class="csa-btn csa-btn--primary csa-btn--lg csa-btn--full">
							<span class="dashicons dashicons-admin-network"></span>
							Create Free API Key
						</button>

						<div class="csa-ob-perks">
							<span class="csa-ob-perks-label">Free plan includes</span>
							<ul>
								<li>2 SEO checks per month</li>
								<li>2 content strategy per month</li>
								<li>2 content generations per month</li>
								<li>No credit card required</li>
							</ul>
						</div>

						<p class="csa-ob-hint">
							Already have a key?
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-settings' ) ); ?>">Enter it in Settings →</a>
						</p>
					</div>
				</div>

			<?php else : ?>
				<!-- DASHBOARD — API key exists -->
				<div class="csa-dashboard-wrap">
				<div class="csa-dashboard">

					<!-- ══ MAIN COLUMN ══════════════════════════════════════════ -->
					<div class="csa-main-col">

						<!-- Stats row: Connection / Plan / Usage -->
						<div class="csa-stats-row">

							<div class="csa-card" id="csa-card-status">
								<div class="csa-card__head">
									<h3>SEO Health</h3>
									<span id="csa-seo-last-audit" class="csa-muted">—</span>
								</div>
								<div class="csa-card__body">

									<div class="csa-seo-health">

										<div class="csa-score-ring-wrap">

											<div class="csa-score-ring">
												<svg viewBox="0 0 120 120">
													<circle class="csa-score-ring__bg" cx="60" cy="60" r="52"></circle>

													<circle
														class="csa-score-ring__progress"
														cx="60"
														cy="60"
														r="52"
														stroke-dasharray="326.56"
														stroke-dashoffset="326.56"
													></circle>
												</svg>

												<div class="csa-score-ring__label">
													<div class="csa-score-ring__score">-</div>
													<div class="csa-score-ring__total">/100</div>
												</div>
											</div>

										</div>

										<div class="csa-seo-health-meta">

											<div class="csa-seo-health-breakdown">

												<div class="csa-health-row">
													<span>Technical SEO</span>
													<strong class="good">-</strong>
												</div>

												<div class="csa-health-row">
													<span>Content Quality</span>
													<strong class="warn">-</strong>
												</div>

												<div class="csa-health-row">
													<span>On-Page SEO</span>
													<strong class="mid">-</strong>
												</div>

												<div class="csa-health-row">
													<span>Schema</span>
													<strong class="bad">-</strong>
												</div>

												<div class="csa-health-row">
													<span>Performance</span>
													<strong class="warn">-</strong>
												</div>

												<div class="csa-health-row">
													<span>AI Readiness</span>
													<strong class="bad">-</strong>
												</div>

											</div>

										</div>

									</div>

								</div>
								<div class="csa-card__foot">
									<a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-website-audit' ) ); ?>" class="csa-btn csa-btn--outline csa-btn--sm">
										<i class="lni lni-search"></i> Run Website Audit
									</a>
								</div>
							</div>

							<div class="csa-card" id="csa-card-plan">
								<div class="csa-card__head">
									<h3>Current Plan</h3>
									<span class="csa-badge" id="csa-plan-badge">—</span>
								</div>
								<div class="csa-card__body">
									<div class="csa-plan-name-lg" id="csa-plan-name">Loading…</div>
									<div class="csa-kv-list">
										<div class="csa-kv">
											<span class="csa-kv__k">Status</span>
											<span id="csa-plan-status" class="csa-kv__v">—</span>
										</div>
										<div class="csa-kv">
											<span class="csa-kv__k">Renews</span>
											<span id="csa-plan-renews" class="csa-kv__v">—</span>
										</div>
									</div>
								</div>
								<div class="csa-card__foot">
									<button id="csa-portal-btn" class="csa-btn csa-btn--outline csa-btn--sm">
										<i class="lni lni-users"></i> Manage Billing
									</button>
								</div>
							</div>

							<div class="csa-card" id="csa-card-usage">
								<div class="csa-card__head">
									<h3>Monthly Usage</h3>
									<span id="csa-usage-period" class="csa-muted">—</span>
								</div>
								<div class="csa-card__body">
									<div class="csa-usage-list">
										<div class="csa-usage-row">
											<div class="csa-usage-meta">
												<span>SEO Audits</span>
												<span id="csa-usage-seo-label">—</span>
											</div>
											<div class="csa-track">
												<div class="csa-bar csa-bar--seo" id="csa-bar-seo" style="width:0%"></div>
											</div>
										</div>
										<div class="csa-usage-row">
											<div class="csa-usage-meta">
												<span>Content Strategy</span>
												<span id="csa-usage-content-label">—</span>
											</div>
											<div class="csa-track">
												<div class="csa-bar csa-bar--content" id="csa-bar-content" style="width:0%"></div>
											</div>
										</div>
										<div class="csa-usage-row">
											<div class="csa-usage-meta">
												<span>Blog Generation</span>
												<span id="csa-usage-blog-label">—</span>
											</div>
											<div class="csa-track">
												<div class="csa-bar csa-bar--blog" id="csa-bar-blog" style="width:0%"></div>
											</div>
										</div>
									</div>
								</div>
								
								<div class="csa-card__foot">
										<button id="csa-open-upgrade-modal" class="csa-btn csa-btn--outline csa-btn--sm">
											<i class="lni lni-rocket"></i> Upgrade Plan
										</button>
									</div>
							</div>

						</div><!-- .csa-stats-row -->

						<!-- Plans & Pricing -->
						 <div id="csa-upgrade-modal-overlay" class="csa-modal-overlay" style="display:none;"></div>

						<div id="csa-upgrade-modal" class="csa-modal" style="display:none;">
							<div class="csa-modal__head">
								<h3>Plans &amp; Pricing</h3>
								<button id="csa-close-upgrade-modal" class="csa-btn csa-btn--ghost-dark csa-btn--sm">
									<i class="lni lni-close"></i> Close
								</button>
							</div>
							<div class="csa-card__body">
								<div class="csa-plans">

									<div class="csa-plan" data-plan="free">
										<div class="csa-plan__name">Free</div>
										<div class="csa-plan__price">$0<span>/mo</span></div>
										<div class="csa-plan__tagline">Best for testing</div>
										<ul class="csa-plan__features">
											<li>2 SEO checks / month</li>
											<li>2 content strategy / month</li>
											<li>2 content generations / month</li>
										</ul>
										<div class="csa-plan__cta">
											<span class="csa-current-badge" id="csa-free-badge">Current Plan</span>
										</div>
									</div>

									<div class="csa-plan csa-plan--pro" data-plan="pro">
										<div class="csa-plan__popular">Most Popular</div>
										<div class="csa-plan__name">Pro</div>
										<div class="csa-plan__price">$20<span>/mo</span></div>
										<div class="csa-plan__tagline">Best for solo site owners</div>
										<ul class="csa-plan__features">
											<li>10 SEO checks / month</li>
											<li>10 content strategy / month</li>
											<li>10 content generations / month</li>
										</ul>
										<div class="csa-plan__cta">
											<span class="csa-current-badge" id="csa-pro-badge" style="display:none;">Current Plan</span>
											<button class="csa-btn csa-btn--primary csa-upgrade-btn" data-plan="pro">Upgrade to Pro →</button>
										</div>
									</div>

									<div class="csa-plan csa-plan--agency" data-plan="agency">
										<div class="csa-plan__name">Agency</div>
										<div class="csa-plan__price">$40<span>/mo</span></div>
										<div class="csa-plan__tagline">Best for agencies and freelancers</div>
										<ul class="csa-plan__features">
											<li>30 SEO checks / month</li>
											<li>30 content strategy / month</li>
											<li>30 content generations / month</li>
										</ul>
										<div class="csa-plan__cta">
											<span class="csa-current-badge" id="csa-agency-badge" style="display:none;">Current Plan</span>
											<button class="csa-btn csa-btn--agency csa-upgrade-btn" data-plan="agency">Upgrade to Agency →</button>
										</div>
									</div>

								</div>
							</div>
						</div>

						<!-- Quick navigation links -->
						<div class="csa-card csa-card--nav" id="csa-card-nav">
							<div class="csa-nav-links">
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-website-audit' ) ); ?>" class="csa-nav-link">
									<i class="lni lni-search"></i>
									<span>Website Audit</span>
								</a>
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-content-plan' ) ); ?>" class="csa-nav-link">
									<i class="lni lni-pencil"></i>
									<span>Content Strategy</span>
								</a>
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-articles' ) ); ?>" class="csa-nav-link">
									<i class="lni lni-layers"></i>
									<span>Articles</span>
								</a>
								<a style="display:none;" href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-rankings' ) ); ?>" class="csa-nav-link">
									<i class="lni lni-bar-chart"></i>
									<span>Rankings</span>
								</a>
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-reports' ) ); ?>" class="csa-nav-link">
									<i class="lni lni-list"></i>
									<span>Reports</span>
								</a>
							</div>
						</div>

						<!-- Recent Reports -->
						<div class="csa-card" id="csa-reports-card" style="display:none;">
							<div class="csa-card__head">
								<div class="csa-card-title-group">
									<i class="lni lni-files csa-card-title-icon"></i>
									<h3>Recent Reports</h3>
								</div>
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-website-audit' ) ); ?>" class="csa-btn csa-btn--ghost csa-btn--sm">View all →</a>
							</div>
							<div class="csa-card__body csa-card__body--flush">
								<div id="csa-reports-list">
									<div class="csa-empty-state">
										<i class="lni lni-files"></i>
										<p>No reports yet. <a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-website-audit' ) ); ?>">Run an audit →</a></p>
									</div>
								</div>
							</div>
						</div>

						<!-- SEO Action Plan -->
						<div class="csa-card" id="csa-card-action-plan">
							<div class="csa-card__head">
								<div class="csa-card-title-group">
									<i class="lni lni-list csa-card-title-icon"></i>
									<h3>SEO Action Plan</h3>
								</div>
								<a style="display: none;" href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-tasks' ) ); ?>" class="csa-btn csa-btn--ghost csa-btn--sm">View all →</a>
							</div>
							<div class="csa-card__body">
								<p class="csa-sidebar-sub">Top priority tasks from your most recent analyses</p>
								<div class="csa-task-list" id="csa-task-list">
									<div class="csa-empty-state csa-empty-state--sm">
										<p>Run an audit to populate tasks.</p>
									</div>
								</div>
							</div>
						</div>

						<!-- Quick Wins -->
						<div class="csa-card" id="csa-card-quick-wins">
							<div class="csa-card__head">
								<div class="csa-card-title-group">
									<i class="lni lni-bolt csa-card-title-icon"></i>
									<h3>Quick Wins</h3>
								</div>
							</div>
							<div class="csa-card__body">
								<div class="csa-qw-list" id="csa-qw-list">
									<div class="csa-empty-state csa-empty-state--sm">
										<p>Run an audit to see quick wins.</p>
									</div>
								</div>
							</div>
						</div>

					</div><!-- .csa-main-col -->

					<!-- ══ SIDEBAR (GSC mini-widget) ═════════════════════════════ -->
					<aside class="csa-sidebar">

						<div class="csa-card" id="csa-card-ranking">
							<div class="csa-card__head">
								<div class="csa-card-title-group">
									<i class="lni lni-bar-chart csa-card-title-icon"></i>
									<h3>Ranking Snapshot</h3>
								</div>
								<span id="csa-gsc-badge" class="csa-badge csa-badge--warning">GSC Required</span>
							</div>
							<div class="csa-card__body">								

								<div id="csa-gsc-connect-state">
									<div class="csa-rank-metrics">
										<div class="csa-rank-metric">
											<span class="csa-rank-metric__value">--</span>
											<span class="csa-rank-metric__label">Avg Position</span>
										</div>
										<div class="csa-rank-metric">
											<span class="csa-rank-metric__value">--</span>
											<span class="csa-rank-metric__label">Clicks</span>
										</div>
										<div class="csa-rank-metric">
											<span class="csa-rank-metric__value">--</span>
											<span class="csa-rank-metric__label">Impressions</span>
										</div>
										<div class="csa-rank-metric">
											<span class="csa-rank-metric__value">--</span>
											<span class="csa-rank-metric__label">CTR</span>
										</div>
									</div>
									<button id="csa-gsc-connect-btn" class="csa-btn csa-btn--primary csa-btn--sm csa-btn--full">
										<i class="lni lni-google"></i> Connect GSC
									</button>
								</div>
								<div id="csa-gsc-connected-state" style="display:none;">
									<div class="csa-gsc-stats" id="csa-gsc-stats" style="display:none;">
										<div class="csa-gsc-stat">
											<div class="csa-gsc-stat__value" id="csa-gsc-clicks">—</div>
											<div class="csa-gsc-stat__label">Clicks</div>
										</div>
										<div class="csa-gsc-stat">
											<div class="csa-gsc-stat__value" id="csa-gsc-impressions">—</div>
											<div class="csa-gsc-stat__label">Impressions</div>
										</div>
										<div class="csa-gsc-stat">
											<div class="csa-gsc-stat__value" id="csa-gsc-ctr">—</div>
											<div class="csa-gsc-stat__label">CTR</div>
										</div>
										<div class="csa-gsc-stat">
											<div class="csa-gsc-stat__value" id="csa-gsc-position">—</div>
											<div class="csa-gsc-stat__label">Avg Position</div>
										</div>
									</div>
									<a style="display:none;" href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-rankings' ) ); ?>" class="csa-btn csa-btn--outline csa-btn--sm csa-btn--full" style="margin-top:8px;">View full Rankings →</a>
								</div>
							</div>
						</div>

					</aside><!-- .csa-sidebar -->

				</div><!-- .csa-dashboard -->
				</div><!-- .csa-dashboard-wrap -->

			<?php endif; ?>

			</main>

			<!-- Shared report drawer — used by all View buttons on the dashboard -->
			<div id="csa-report-drawer-overlay" style="display:none;"></div>
			<div id="csa-report-detail-card" class="csa-report-drawer" style="display:none;">
				<div class="csa-card__head">
					<h3 id="csa-report-detail-title">Report</h3>
					<button id="csa-report-detail-close" class="csa-btn csa-btn--ghost-dark csa-btn--sm">
						<i class="lni lni-close"></i> Close
					</button>
				</div>

				<div class="csa-card__body">
					<div id="csa-report-detail-content"></div>
				</div>
			</div>

			<div id="csa-spinner-overlay" style="display:none;" aria-live="polite">
				<div class="csa-spinner-box">
					<div class="csa-spinner"></div>
					<p id="csa-spinner-msg">Please wait…</p>
				</div>
			</div>

		</div><!-- .csa-wrap -->
		<?php
	}

	// ── Shared page header helper ─────────────────────────────────────────────

	private function render_page_header( string $title, string $sub, string $back_url = '' ): void {
		?>
		<header class="csa-header">
			<div class="csa-header-inner">
				<div class="csa-header-left">
					<div class="csa-logo">
						<img src="<?php echo esc_url( FORME_SEO_URL . 'assets/claude-seo-agent.svg' ); ?>" alt="" class="csa-logo-mark" width="28" height="28" aria-hidden="true">
						<span class="csa-logo-name">Forme SEO AI Agent</span>
						<span class="csa-version-pill"><?php echo esc_html( $title ); ?></span>
					</div>
					<div class="csa-header-sub"><?php echo esc_html( $sub ); ?></div>
				</div>
				<div class="csa-header-right">
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent' ) ); ?>" class="csa-hdr-btn">
						← Dashboard
					</a>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-settings' ) ); ?>" class="csa-hdr-btn">
						<span class="dashicons dashicons-admin-settings"></span> Settings
					</a>
				</div>
			</div>
		</header>
		<?php
	}

	// ── Audits & Tools page ───────────────────────────────────────────────────

	public function render_audits(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		?>
		<div class="csa-wrap">
			<?php $this->render_page_header( 'Audits &amp; Tools', 'Run AI-powered SEO audits and analyses on any URL' ); ?>
			<main class="csa-main">
				<div class="csa-dashboard">
					<div class="csa-main-col">

						<!-- URL input -->
						<div class="csa-card" id="csa-audit-url-card">
							<div class="csa-card__head">
								<h3>Target URL</h3>
							</div>
							<div class="csa-card__body">
								<div class="csa-url-row">
									<div class="csa-url-locked-wrap">
										<i class="lni lni-lock" aria-hidden="true"></i>
										<input type="url" id="csa-tool-url" class="csa-input csa-input--url csa-input--locked"
											value="<?php echo esc_attr( home_url() ); ?>"
											readonly />
									</div>
								</div>
								<p class="csa-input-hint">Audits always run against this WordPress site.</p>
							</div>
						</div>

						<!-- Audit tool cards (5 audit tools) -->
						<div class="csa-card" id="csa-card-tools">
							<div class="csa-card__head">
								<h3>SEO Audits</h3>
							</div>
							<div class="csa-card__body csa-card__body--flush">
								<div class="csa-tool-cards">
									<?php foreach ( self::$audit_tools as $id => $tool ) : ?>
									<div class="csa-tool-card">
										<div class="csa-tool-card-icon">
											<i class="lni <?php echo esc_attr( $tool['lni'] ); ?>"></i>
										</div>
										<div class="csa-tool-card-body">
											<div class="csa-tool-card-name"><?php echo esc_html( $tool['label'] ); ?></div>
											<div class="csa-tool-card-desc"><?php echo esc_html( $tool['desc'] ); ?></div>
										</div>
										<button
											class="csa-btn csa-btn--outline csa-btn--sm csa-tool-btn"
											data-action="<?php echo esc_attr( $tool['action'] ); ?>"
											data-label="<?php echo esc_attr( $tool['label'] ); ?>"
										>Run →</button>
									</div>
									<?php endforeach; ?>
								</div>
							</div>
						</div>

						<!-- Report Panel (inline result + progress) -->
						<div class="csa-card" id="csa-report-panel" style="display:none;">
							<div class="csa-card__head">
								<h3 id="csa-report-title">Report</h3>
								<div class="csa-result-actions">
									<span id="csa-cached-badge" class="csa-badge csa-badge--info" style="display:none;">Cached</span>
									<button id="csa-copy-btn" class="csa-btn csa-btn--ghost-dark csa-btn--sm">
										<i class="lni lni-clipboard"></i> Copy JSON
									</button>
									<button id="csa-result-close" class="csa-btn csa-btn--ghost-dark csa-btn--sm">
										<i class="lni lni-close"></i> Clear
									</button>
								</div>
							</div>
							<div class="csa-card__body" id="csa-report-body">
								<div id="csa-result-loading" class="csa-result-loading" style="display:none;">
									<div class="csa-spinner-sm"></div>
									<div class="csa-progress-wrap" style="display:none;" id="csa-progress-wrap">
										<div class="csa-progress-track">
											<div class="csa-progress-bar" id="csa-progress-bar" style="width:0%"></div>
										</div>
									</div>
									<span id="csa-result-loading-msg">Running analysis…</span>
								</div>
								<div id="csa-report-content" style="display:none;"></div>
							</div>
							<pre id="csa-result-viewer" style="display:none;"></pre>
						</div>

						<!-- Content Workflow (shown after content-pillars runs) -->
						<div class="csa-card" id="csa-content-card" style="display:none;">
							<div class="csa-card__head">
								<div class="csa-card-title-group">
									<i class="lni lni-layers csa-card-title-icon"></i>
									<h3>Content Workflow</h3>
								</div>
								<span id="csa-content-project-status" class="csa-badge csa-badge--success">Active</span>
							</div>
							<div class="csa-card__body" id="csa-content-body">
								<div id="csa-content-project-info" class="csa-content-project-info"></div>
								<div id="csa-topic-grid" class="csa-topic-grid"></div>
							</div>
						</div>

						<!-- Job History -->
						<div class="csa-card" id="csa-job-history-card">
							<div class="csa-card__head">
								<div class="csa-card-title-group">
									<i class="lni lni-timer csa-card-title-icon"></i>
									<h3>Job History</h3>
								</div>
								<div class="csa-card-head-actions">
									<button id="csa-jobs-refresh-btn" class="csa-btn csa-btn--outline csa-btn--sm">
										<i class="lni lni-reload"></i> Refresh
									</button>
								</div>
							</div>
							<div class="csa-card__body csa-card__body--flush">
								<div class="csa-jobs-filter-row">
									<select id="csa-jobs-filter-status" class="csa-select csa-select--sm">
										<option value="">All statuses</option>
										<option value="queued">Queued</option>
										<option value="running">Running</option>
										<option value="completed">Completed</option>
										<option value="failed">Failed</option>
										<option value="rate_limited">Rate Limited</option>
									</select>
									<select id="csa-jobs-filter-tool" class="csa-select csa-select--sm">
										<option value="">All tools</option>
										<?php foreach ( self::$audit_tools as $id => $tool ) : ?>
										<option value="<?php echo esc_attr( $id ); ?>"><?php echo esc_html( $tool['label'] ); ?></option>
										<?php endforeach; ?>
									</select>
									<input type="search" id="csa-jobs-search" class="csa-input csa-input--sm"
										placeholder="Search URL…" />
								</div>
								<div id="csa-jobs-table-wrap">
									<div class="csa-empty-state">
										<i class="lni lni-timer"></i>
										<p>No jobs yet. Run an audit above to get started.</p>
									</div>
								</div>
								<div id="csa-jobs-pagination" class="csa-pagination" style="display:none;"></div>
							</div>
						</div>

					</div><!-- .csa-main-col -->

					<aside class="csa-sidebar">
						<div class="csa-card" id="csa-card-action-plan">
							<div class="csa-card__head">
								<div class="csa-card-title-group">
									<i class="lni lni-list csa-card-title-icon"></i>
									<h3>SEO Action Plan</h3>
								</div>
							</div>
							<div class="csa-card__body">
								<div class="csa-task-list" id="csa-task-list">
									<div class="csa-empty-state csa-empty-state--sm">
										<p>Run an audit to populate tasks.</p>
									</div>
								</div>
							</div>
						</div>
						<div class="csa-card" id="csa-card-quick-wins">
							<div class="csa-card__head">
								<div class="csa-card-title-group">
									<i class="lni lni-bolt csa-card-title-icon"></i>
									<h3>Quick Wins</h3>
								</div>
							</div>
							<div class="csa-card__body">
								<div class="csa-qw-list" id="csa-qw-list">
									<div class="csa-empty-state csa-empty-state--sm">
										<p>Run an audit to see quick wins.</p>
									</div>
								</div>
							</div>
						</div>
					</aside>
				</div>
			</main>
			<div id="csa-spinner-overlay" style="display:none;" aria-live="polite">
				<div class="csa-spinner-box"><div class="csa-spinner"></div><p id="csa-spinner-msg">Please wait…</p></div>
			</div>
		</div>
		<?php
	}

	// ── Reports page ──────────────────────────────────────────────────────────

	public function render_reports(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		?>
		<div class="csa-wrap">
			<?php $this->render_page_header( 'Reports', 'View and manage all your SEO analysis reports' ); ?>
			<main class="csa-main">

				<div class="csa-card" id="csa-reports-page-card">
					<div class="csa-card__head">
						<div class="csa-card-title-group">
							<i class="lni lni-files csa-card-title-icon"></i>
							<h3>All Reports</h3>
						</div>
						<div class="csa-card-head-actions">
							<select id="csa-reports-filter-tool" class="csa-select csa-select--sm">
								<option value="">All tools</option>
								<?php foreach ( self::$tools as $id => $tool ) : ?>
								<option value="<?php echo esc_attr( $id ); ?>"><?php echo esc_html( $tool['label'] ); ?></option>
								<?php endforeach; ?>
							</select>
							<button id="csa-reports-load-btn" class="csa-btn csa-btn--outline csa-btn--sm">
								<i class="lni lni-reload"></i> Refresh
							</button>
						</div>
					</div>
					<div class="csa-card__body csa-card__body--flush">
						<div id="csa-reports-page-list">
							<div class="csa-empty-state">
								<i class="lni lni-files"></i>
								<p>Loading reports…</p>
							</div>
						</div>
						<div id="csa-reports-pagination" class="csa-pagination" style="display:none;"></div>
					</div>
				</div>

				<!-- Report detail panel -->
				<div id="csa-report-drawer-overlay" style="display:none;"></div>
				<div id="csa-report-detail-card" class="csa-report-drawer" style="display:none;">
					<div class="csa-card__head">
						<h3 id="csa-report-detail-title">Report Detail</h3>
						<div class="csa-result-actions">
							<span id="csa-cached-badge" class="csa-badge csa-badge--info" style="display:none;">Cached</span>
							<!--<button id="csa-copy-btn" class="csa-btn csa-btn--ghost-dark csa-btn--sm">
								<i class="lni lni-clipboard"></i> Copy JSON
							</button>-->
							<button id="csa-report-detail-close" class="csa-btn csa-btn--ghost-dark csa-btn--sm">
								<i class="lni lni-close"></i> Close
							</button>
						</div>
					</div>
					<div class="csa-card__body">
						<div id="csa-report-detail-content"></div>
					</div>
					<pre id="csa-result-viewer" style="display:none;"></pre>
				</div>

			</main>
			<div id="csa-spinner-overlay" style="display:none;" aria-live="polite">
				<div class="csa-spinner-box"><div class="csa-spinner"></div><p id="csa-spinner-msg">Please wait…</p></div>
			</div>
		</div>
		<?php
	}

	// ── Content Planner page ─────────────────────────────────────────────────

	public function render_content_planner(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		?>
		<div class="csa-wrap">
			<?php $this->render_page_header( 'Content Planner', 'Manage topic clusters and generate articles' ); ?>
			<main class="csa-main">

				<div class="csa-card" id="csa-projects-list-card">
					<div class="csa-card__head">
						<div class="csa-card-title-group">
							<i class="lni lni-layers csa-card-title-icon"></i>
							<h3>Content Projects</h3>
						</div>
						<button id="csa-projects-refresh-btn" class="csa-btn csa-btn--ghost csa-btn--sm">
							<i class="lni lni-reload"></i>
						</button>
					</div>
					<div class="csa-card__body" id="csa-projects-body">
						<div class="csa-empty-state">
							<i class="lni lni-layers"></i>
							<p>Loading projects… Run <a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-audits' ) ); ?>">Content Pillars</a> to create one.</p>
						</div>
					</div>
				</div>

				<!-- Topic grid for selected project -->
				<div class="csa-card" id="csa-content-card" style="display:none;">
					<div class="csa-card__head">
						<div class="csa-card-title-group">
							<i class="lni lni-link csa-card-title-icon"></i>
							<h3 id="csa-content-project-name">Topics</h3>
						</div>
						<span id="csa-content-project-status" class="csa-badge csa-badge--success">Active</span>
					</div>
					<div class="csa-card__body" id="csa-content-body">
						<div id="csa-content-project-info" class="csa-content-project-info"></div>
						<div id="csa-topic-grid" class="csa-topic-grid"></div>
					</div>
				</div>

				<!-- Article preview -->
				<div class="csa-card" id="csa-article-preview-card" style="display:none;">
					<div class="csa-card__head">
						<h3 id="csa-article-preview-title">Generated Article</h3>
						<div class="csa-card-head-actions">
							<button id="csa-article-close-btn" class="csa-btn csa-btn--ghost-dark csa-btn--sm">
								<i class="lni lni-close"></i> Close
							</button>
						</div>
					</div>
					<div class="csa-card__body">
						<div id="csa-article-preview-content" class="csa-article-preview"></div>
					</div>
				</div>

				<!-- Inline job progress for outline/write -->
				<div id="csa-content-job-progress" class="csa-result-loading" style="display:none;">
					<div class="csa-spinner-sm"></div>
					<div class="csa-progress-wrap" id="csa-content-progress-wrap">
						<div class="csa-progress-track">
							<div class="csa-progress-bar" id="csa-content-progress-bar" style="width:0%"></div>
						</div>
					</div>
					<span id="csa-content-loading-msg">Generating…</span>
				</div>

			</main>
			<div id="csa-spinner-overlay" style="display:none;" aria-live="polite">
				<div class="csa-spinner-box"><div class="csa-spinner"></div><p id="csa-spinner-msg">Please wait…</p></div>
			</div>
		</div>
		<?php
	}

	// ── Website Audit page ───────────────────────────────────────────────────

	public function render_website_audit(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$content_plan_url = admin_url( 'admin.php?page=claude-seo-agent-content-plan' );
		?>
		<div class="csa-wrap">
			<?php $this->render_page_header( 'Website Audit', 'Run a full AI-powered SEO audit on your website' ); ?>
			<main class="csa-main">

				<!-- Run Audit card -->
				<div class="csa-card" id="csa-audit-run-card">
					<div class="csa-card__head">
						<div class="csa-card-title-group">
							<i class="lni lni-search csa-card-title-icon"></i>
							<h3>Full Website Audit</h3>
						</div>
						<span id="csa-audit-industry-badge" class="csa-badge csa-badge--neutral" style="display:none;"></span>
					</div>
					<div class="csa-card__body">
						<p class="csa-card-desc">Analyse your site for technical SEO issues, content quality, schema markup, and ranking opportunities. This is the required first step before generating a content plan.</p>
						<div class="csa-url-row">
							<div class="csa-url-locked-wrap">
								<i class="lni lni-lock" aria-hidden="true"></i>
								<input type="url" id="csa-audit-url" class="csa-input csa-input--url csa-input--locked"
									value="<?php echo esc_attr( home_url() ); ?>"
									readonly />
							</div>
							<button id="csa-run-audit-btn" class="csa-btn csa-btn--primary">
								<i class="lni lni-search"></i> Run Full Audit
							</button>
						</div>

						<!-- Progress bar (shown while job runs) -->
						<div id="csa-audit-progress" class="csa-result-loading" style="display:none;">
							<div class="csa-spinner-sm"></div>
							<div class="csa-progress-wrap" id="csa-audit-progress-wrap">
								<div class="csa-progress-track">
									<div class="csa-progress-bar" id="csa-audit-progress-bar" style="width:0%"></div>
								</div>
							</div>
							<span id="csa-audit-loading-msg">Starting audit…</span>
						</div>
					</div>
				</div>

				<!-- Latest result card (shown after audit completes) -->
				<div class="csa-card" id="csa-audit-result-card" style="display:none;">
					<div class="csa-card__head">
						<h3>Latest Audit Result</h3>
						<div class="csa-card-head-actions">
							<button id="csa-audit-copy-btn" class="csa-btn csa-btn--ghost-dark csa-btn--sm">
								<i class="lni lni-clipboard"></i> Copy JSON
							</button>
							<button id="csa-audit-clear-btn" class="csa-btn csa-btn--ghost-dark csa-btn--sm">
								<i class="lni lni-close"></i> Clear
							</button>
						</div>
					</div>
					<div class="csa-card__body">
						<div id="csa-audit-report-body"></div>
						<div id="csa-audit-next-step" style="display:none; margin-top:1.5rem; padding-top:1rem; border-top:1px solid #e5e7eb;">
							<p><strong>Audit complete.</strong> Your site profile has been saved. Ready to generate your SEO plan and content strategy.</p>
							<a href="<?php echo esc_url( $content_plan_url ); ?>" class="csa-btn csa-btn--primary">
								Generate Content Plan →
							</a>
						</div>
					</div>
				</div>

				<!-- Audit history -->
				<div class="csa-card" id="csa-audit-history-card">
					<div class="csa-card__head">
						<div class="csa-card-title-group">
							<i class="lni lni-files csa-card-title-icon"></i>
							<h3>Audit History</h3>
						</div>
						<button id="csa-audit-history-refresh" class="csa-btn csa-btn--ghost csa-btn--sm">
							<i class="lni lni-reload"></i>
						</button>
					</div>
					<div class="csa-card__body csa-card__body--flush">
						<div id="csa-audit-history-list">
							<div class="csa-empty-state">
								<i class="lni lni-files"></i>
								<p>No audits run yet.</p>
							</div>
						</div>
					</div>
				</div>

			</main>
			<div id="csa-spinner-overlay" style="display:none;" aria-live="polite">
				<div class="csa-spinner-box"><div class="csa-spinner"></div><p id="csa-spinner-msg">Please wait…</p></div>
			</div>
		</div>
		<?php
	}

	// ── Content Plan page ─────────────────────────────────────────────────────

	public function render_content_plan(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$audit_url    = admin_url( 'admin.php?page=claude-seo-agent-website-audit' );
		$articles_url = admin_url( 'admin.php?page=claude-seo-agent-articles' );
		?>
		<div class="csa-wrap">
			<?php $this->render_page_header( 'Content Plan', 'Build your SEO roadmap and editorial strategy' ); ?>
			<main class="csa-main" id="csa-content-plan-main" data-step="1">

				<!-- No audit gate -->
				<div id="csa-plan-no-audit" class="csa-card" style="display:none;">
					<div class="csa-card__body">
						<div class="csa-empty-state csa-empty-state--page">
							<i class="lni lni-search"></i>
							<h3>Run a Website Audit First</h3>
							<p>A completed audit is required before generating your content plan. It gives Claude the context needed to build a strategy tailored to your site.</p>
							<a href="<?php echo esc_url( $audit_url ); ?>" class="csa-btn csa-btn--primary">Run Website Audit →</a>
						</div>
					</div>
				</div>

				<!-- Step 1: SEO Plan -->
				<div class="csa-card" id="csa-plan-step1">
					<div class="csa-card__head">
						<div class="csa-card-title-group">
							<span class="csa-step-number">1</span>
							<h3>SEO Implementation Roadmap</h3>
						</div>
						<div class="csa-card-head-actions">
							<span id="csa-plan-industry-tag" class="csa-badge csa-badge--neutral" style="display:none;"></span>
							<button id="csa-generate-plan-btn" class="csa-btn csa-btn--primary csa-btn--sm">
								<i class="lni lni-map"></i> Run New Audit
							</button>
						</div>
					</div>
					<div class="csa-card__body">
						<p class="csa-card-desc" id="csa-plan-step1-desc">Generate a 4-phase SEO implementation roadmap based on your audit results and detected industry.</p>

						<div id="csa-plan-progress" class="csa-result-loading" style="display:none;">
							<div class="csa-spinner-sm"></div>
							<div class="csa-progress-wrap">
								<div class="csa-progress-track">
									<div class="csa-progress-bar" id="csa-plan-progress-bar" style="width:0%"></div>
								</div>
							</div>
							<span id="csa-plan-loading-msg">Generating plan…</span>
						</div>

						<div id="csa-plan-roadmap" style="display:none;">
							<div class="csa-roadmap-grid" id="csa-roadmap-phases"></div>
						</div>
					</div>
				</div>

				<!-- Step 2: Blog Strategy -->
				<div class="csa-card" id="csa-plan-step2" style="opacity:.45; pointer-events:none;">
					<div class="csa-card__head">
						<div class="csa-card-title-group">
							<span class="csa-step-number">2</span>
							<h3>Blog Plan</h3>
						</div>
						<button id="csa-generate-strategy-btn" class="csa-btn csa-btn--primary csa-btn--sm">
							<i class="lni lni-pencil"></i> Generate Blog Plan
						</button>
					</div>
					<div class="csa-card__body">
						<p class="csa-card-desc">Generate article topics and an editorial calendar using your cadence and content goals.</p>
						<div id="csa-blog-strategy-preview" style="display:none;"></div>
						<div class="csa-strategy-fields">
							<div class="csa-field-row">
								<div class="csa-field">
									<label>Target Audience</label>
									<input type="text" id="csa-strategy-audience" class="csa-input" placeholder="e.g. small business owners in the US" />
								</div>
								<div class="csa-field">
									<label>Tone &amp; Voice</label>
									<input type="text" id="csa-strategy-tone" class="csa-input" placeholder="e.g. professional, friendly, authoritative" />
								</div>
							</div>
							<div class="csa-field-row">
								<div class="csa-field">
									<label>Location / Market</label>
									<input type="text" id="csa-strategy-location" class="csa-input" placeholder="e.g. New York, UK, global" />
								</div>
								<div class="csa-field">
									<label>Content Goals</label>
									<input type="text" id="csa-strategy-goals" class="csa-input" placeholder="e.g. generate leads, build authority" />
								</div>
							</div>
						</div>

						<div id="csa-strategy-progress" class="csa-result-loading" style="display:none;">
							<div class="csa-spinner-sm"></div>
							<div class="csa-progress-wrap">
								<div class="csa-progress-track">
									<div class="csa-progress-bar" id="csa-strategy-progress-bar" style="width:0%"></div>
								</div>
							</div>
							<span id="csa-strategy-loading-msg">Generating strategy…</span>
						</div>

						<div id="csa-strategy-result" style="display:none;"></div>
					</div>
					<div class="csa-card__body">
						<p class="csa-card-desc">Set your publishing cadence and generate a full editorial calendar with topics, intent, and a publish schedule.</p>
						<div id="csa-editorial-calendar-preview" style="display:none;"></div>

						<div style="margin:1.5rem 0; border-top:1px solid #e5e7eb; padding-top:1.5rem;">

							<h4 style="margin:0 0 1rem; font-size:14px; font-weight:600; color:#111827;">
								Editorial Calendar Settings
							</h4>

							<div class="csa-calendar-controls">

								<div class="csa-field">
									<label>Quarter</label>
									<select id="csa-cal-quarter" class="csa-select">
										<option value="Q1">Q1 (Jan–Mar)</option>
										<option value="Q2" selected>Q2 (Apr–Jun)</option>
										<option value="Q3">Q3 (Jul–Sep)</option>
										<option value="Q4">Q4 (Oct–Dec)</option>
									</select>
								</div>

								<div class="csa-field">
									<label>Posts per week</label>
									<select id="csa-cal-frequency" class="csa-select">
										<option value="1">1 per week</option>
										<option value="2" selected>2 per week</option>
										<option value="3">3 per week</option>
										<option value="5">5 per week</option>
									</select>
								</div>

								<div class="csa-field">
									<label>Months</label>
									<select id="csa-cal-months" class="csa-select">
										<option value="1">1 month</option>
										<option value="2">2 months</option>
										<option value="3" selected>3 months</option>
									</select>
								</div>

								<div class="csa-field">
									<label>Start Date</label>
									<input
										type="date"
										id="csa-cal-start-date"
										class="csa-input"
										value="<?php echo esc_attr( gmdate( 'Y-m-d' ) ); ?>"
									/>
								</div>

							</div>

						</div>

						<div id="csa-calendar-progress" class="csa-result-loading" style="display:none;">
							<div class="csa-spinner-sm"></div>
							<div class="csa-progress-wrap">
								<div class="csa-progress-track">
									<div class="csa-progress-bar" id="csa-calendar-progress-bar" style="width:0%"></div>
								</div>
							</div>
							<span id="csa-calendar-loading-msg">Building calendar…</span>
						</div>

						<div id="csa-calendar-result" style="display:none;">
							<div id="csa-calendar-table-wrap"></div>
							<div style="margin-top:1.25rem; padding-top:1rem; border-top:1px solid #e5e7eb;">
								<button id="csa-add-to-queue-btn" class="csa-btn csa-btn--primary">
									<i class="lni lni-plus"></i> Add All to Article Queue
								</button>
								<a href="<?php echo esc_url( $articles_url ); ?>" class="csa-btn csa-btn--outline" style="margin-left:.5rem;">
									View Articles →
								</a>
							</div>
						</div>
					</div>
				</div>

				<!-- Step 3: Editorial Calendar -->
				<div class="csa-card" id="csa-plan-step3" style="opacity:.45; pointer-events:none; display:none;">
					<div class="csa-card__head">
						<div class="csa-card-title-group">
							<span class="csa-step-number">3</span>
							<h3>Editorial Calendar</h3>
						</div>
						<button id="csa-generate-calendar-btn" class="csa-btn csa-btn--primary csa-btn--sm">
							<i class="lni lni-calendar"></i> Generate Calendar
						</button>
					</div>
					<div class="csa-card__body">
						<p class="csa-card-desc">Set your publishing cadence and generate a full editorial calendar with topics, intent, and a publish schedule.</p>
						<div id="csa-editorial-calendar-preview" style="display:none;"></div>

						<div class="csa-calendar-controls">
							<div class="csa-field">
								<label>Start Date</label>
								<input type="date" id="csa-cal-start-date" class="csa-input" />
							</div>
							<div class="csa-field">
								<label>Quarter</label>
								<select id="csa-cal-quarter" class="csa-select">
									<option value="Q1">Q1 (Jan–Mar)</option>
									<option value="Q2" selected>Q2 (Apr–Jun)</option>
									<option value="Q3">Q3 (Jul–Sep)</option>
									<option value="Q4">Q4 (Oct–Dec)</option>
								</select>
							</div>
							<div class="csa-field">
								<label>Posts per week</label>
								<select id="csa-cal-frequency" class="csa-select">
									<option value="1">1 per week</option>
									<option value="2" selected>2 per week</option>
									<option value="3">3 per week</option>
									<option value="5">5 per week</option>
								</select>
							</div>
							<div class="csa-field">
								<label>Months</label>
								<select id="csa-cal-months" class="csa-select">
									<option value="1">1 month</option>
									<option value="2">2 months</option>
									<option value="3" selected>3 months</option>
								</select>
							</div>
						</div>

						<div id="csa-calendar-progress" class="csa-result-loading" style="display:none;">
							<div class="csa-spinner-sm"></div>
							<div class="csa-progress-wrap">
								<div class="csa-progress-track">
									<div class="csa-progress-bar" id="csa-calendar-progress-bar" style="width:0%"></div>
								</div>
							</div>
							<span id="csa-calendar-loading-msg">Building calendar…</span>
						</div>

						<div id="csa-calendar-result" style="display:none;">
							<div id="csa-calendar-table-wrap"></div>
							<div style="margin-top:1.25rem; padding-top:1rem; border-top:1px solid #e5e7eb;">
								<button id="csa-add-to-queue-btn" class="csa-btn csa-btn--primary">
									<i class="lni lni-plus"></i> Add All to Article Queue
								</button>
								<a href="<?php echo esc_url( $articles_url ); ?>" class="csa-btn csa-btn--outline" style="margin-left:.5rem;">
									View Articles →
								</a>
							</div>
						</div>
					</div>
				</div>
				
				<div id="csa-report-drawer-overlay" style="display:none;"></div>

					<div id="csa-report-detail-card" class="csa-report-drawer" style="display:none;">
						<div class="csa-card__head">
							<h3 id="csa-report-detail-title">Report</h3>
							<button id="csa-report-detail-close" class="csa-btn csa-btn--ghost-dark csa-btn--sm">
								<i class="lni lni-close"></i> Close
							</button>
						</div>

						<div class="csa-card__body">
							<div id="csa-report-detail-content"></div>
						</div>
					</div>
			</main>
			<div id="csa-spinner-overlay" style="display:none;" aria-live="polite">
				<div class="csa-spinner-box"><div class="csa-spinner"></div><p id="csa-spinner-msg">Please wait…</p></div>
			</div>
		</div>
		<?php
	}

	// ── Articles page ─────────────────────────────────────────────────────────

	public function render_articles(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$content_plan_url = admin_url( 'admin.php?page=claude-seo-agent-content-plan' );
		?>
		<div class="csa-wrap">
			<?php $this->render_page_header( 'Articles', 'Generate, review, and publish your article queue' ); ?>
			<main class="csa-main">

				<div class="csa-card" id="csa-projects-list-card">
					<div class="csa-card__head">
						<div class="csa-card-title-group">
							<i class="lni lni-layers csa-card-title-icon"></i>
							<h3>Content Projects</h3>
						</div>
						<button id="csa-projects-refresh-btn" class="csa-btn csa-btn--ghost csa-btn--sm">
							<i class="lni lni-reload"></i>
						</button>
					</div>
					<div class="csa-card__body" id="csa-projects-body">
						<div class="csa-empty-state">
							<i class="lni lni-layers"></i>
							<p>No projects yet. <a href="<?php echo esc_url( $content_plan_url ); ?>">Complete your Content Plan</a> to create an article queue.</p>
						</div>
					</div>
				</div>

				<!-- Topic table for selected project -->
				<div class="csa-card" id="csa-content-card" style="display:none;">
					<div class="csa-card__head">
						<div class="csa-card-title-group">
							<i class="lni lni-link csa-card-title-icon"></i>
							<h3 id="csa-content-project-name">Topics</h3>
						</div>
						<span id="csa-content-project-status" class="csa-badge csa-badge--success">Active</span>
					</div>
					<div class="csa-card__body" id="csa-content-body">
						<div id="csa-content-project-info" class="csa-content-project-info"></div>
						<div id="csa-topic-grid" class="csa-topic-grid"></div>
					</div>
				</div>

				<!-- Article preview -->
				<div class="csa-card" id="csa-article-preview-card" style="display:none;">
					<div class="csa-card__head">
						<h3 id="csa-article-preview-title">Generated Article</h3>
						<div class="csa-card-head-actions">
							<button id="csa-article-close-btn" class="csa-btn csa-btn--ghost-dark csa-btn--sm">
								<i class="lni lni-close"></i> Close
							</button>
						</div>
					</div>
					<div class="csa-card__body">
						<div id="csa-article-preview-content" class="csa-article-preview"></div>
					</div>
				</div>

				<!-- Inline job progress for outline/write -->
				<div id="csa-content-job-progress" class="csa-result-loading" style="display:none;">
					<div class="csa-spinner-sm"></div>
					<div class="csa-progress-wrap" id="csa-content-progress-wrap">
						<div class="csa-progress-track">
							<div class="csa-progress-bar" id="csa-content-progress-bar" style="width:0%"></div>
						</div>
					</div>
					<span id="csa-content-loading-msg">Generating…</span>
				</div>
				<div id="csa-report-drawer-overlay" style="display:none;"></div>

				<div id="csa-report-detail-card" class="csa-report-drawer" style="display:none;">
					<div class="csa-card__head">
						<h3 id="csa-report-detail-title">Report</h3>

						<button id="csa-report-detail-close" class="csa-btn csa-btn--ghost-dark csa-btn--sm">
							<i class="lni lni-close"></i> Close
						</button>
					</div>

					<div class="csa-card__body">
						<div id="csa-report-detail-content"></div>
					</div>
				</div>
			</main>
			<div id="csa-spinner-overlay" style="display:none;" aria-live="polite">
				<div class="csa-spinner-box"><div class="csa-spinner"></div><p id="csa-spinner-msg">Please wait…</p></div>
			</div>
		</div>
		<?php
	}

	// ── Content Assessment page ───────────────────────────────────────────────

	public function render_content_assessment(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		?>
		<div class="csa-wrap">
			<?php $this->render_page_header( 'Content Assessment', 'AI-powered content quality analysis' ); ?>
			<main class="csa-main">
				<div class="csa-empty-state csa-empty-state--page">
					<i class="lni lni-pencil"></i>
					<h3>Content Assessment</h3>
					<p>Coming soon — content quality analysis, E-E-A-T checks, and blog audits.</p>
				</div>
			</main>
		</div>
		<?php
	}

	// ── Rankings page ─────────────────────────────────────────────────────────

	public function render_rankings(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		?>
		<div class="csa-wrap">
			<?php $this->render_page_header( 'Rankings', 'Google Search Console performance data' ); ?>
			<main class="csa-main">

				<div class="csa-card" id="csa-card-ranking">
					<div class="csa-card__head">
						<div class="csa-card-title-group">
							<i class="lni lni-bar-chart csa-card-title-icon"></i>
							<h3>Ranking Snapshot</h3>
						</div>
						<span id="csa-gsc-badge" class="csa-badge csa-badge--warning">GSC Required</span>
					</div>
					<div class="csa-card__body">

						<!-- Not connected -->
						<div id="csa-gsc-connect-state">
							<div class="csa-rank-metrics">
								<div class="csa-rank-metric">
									<span class="csa-rank-metric__value">--</span>
									<span class="csa-rank-metric__label">Avg Position</span>
								</div>
								<div class="csa-rank-metric">
									<span class="csa-rank-metric__value">--</span>
									<span class="csa-rank-metric__label">Clicks</span>
								</div>
								<div class="csa-rank-metric">
									<span class="csa-rank-metric__value">--</span>
									<span class="csa-rank-metric__label">Impressions</span>
								</div>
								<div class="csa-rank-metric">
									<span class="csa-rank-metric__value">--</span>
									<span class="csa-rank-metric__label">CTR</span>
								</div>
							</div>
							<div class="csa-spark-wrap">
								<div class="csa-spark">
									<span style="height:32%"></span><span style="height:45%"></span>
									<span style="height:28%"></span><span style="height:55%"></span>
									<span style="height:48%"></span><span style="height:62%"></span>
									<span style="height:41%"></span><span style="height:70%"></span>
									<span style="height:58%"></span><span style="height:66%"></span>
									<span style="height:52%"></span><span style="height:78%"></span>
									<span style="height:63%"></span><span style="height:75%"></span>
								</div>
								<p class="csa-spark-label">28-day trend — connect GSC to unlock</p>
							</div>
							<button id="csa-gsc-connect-btn" class="csa-btn csa-btn--primary csa-btn--sm csa-btn--full">
								<i class="lni lni-google"></i> Connect GSC
							</button>
						</div><!-- #csa-gsc-connect-state -->

						<!-- Connected state -->
						<div id="csa-gsc-connected-state" style="display:none;">
							<div class="csa-gsc-property-row">
								<label for="csa-gsc-property-select" class="csa-gsc-property-label">Property</label>
								<select id="csa-gsc-property-select" class="csa-select">
									<option value="">Loading properties…</option>
								</select>
								<button id="csa-gsc-set-property-btn" class="csa-btn csa-btn--outline csa-btn--sm">Set</button>
								<button id="csa-gsc-disconnect-btn" class="csa-btn csa-btn--ghost-dark csa-btn--sm">Disconnect</button>
							</div>
							<div class="csa-gsc-stats" id="csa-gsc-stats" style="display:none;">
								<div class="csa-gsc-stat">
									<div class="csa-gsc-stat__value" id="csa-gsc-clicks">—</div>
									<div class="csa-gsc-stat__label">Clicks</div>
								</div>
								<div class="csa-gsc-stat">
									<div class="csa-gsc-stat__value" id="csa-gsc-impressions">—</div>
									<div class="csa-gsc-stat__label">Impressions</div>
								</div>
								<div class="csa-gsc-stat">
									<div class="csa-gsc-stat__value" id="csa-gsc-ctr">—</div>
									<div class="csa-gsc-stat__label">CTR</div>
								</div>
								<div class="csa-gsc-stat">
									<div class="csa-gsc-stat__value" id="csa-gsc-position">—</div>
									<div class="csa-gsc-stat__label">Avg Position</div>
								</div>
							</div>
							<div class="csa-gsc-chart-wrap" id="csa-gsc-chart-wrap" style="display:none;">
								<canvas id="csa-gsc-chart" height="120" aria-label="28-day clicks and impressions trend"></canvas>
							</div>
						</div><!-- #csa-gsc-connected-state -->

					</div>
				</div>

			</main>
			<div id="csa-spinner-overlay" style="display:none;" aria-live="polite">
				<div class="csa-spinner-box"><div class="csa-spinner"></div><p id="csa-spinner-msg">Please wait…</p></div>
			</div>
		</div>
		<?php
	}

	// ── Settings page ─────────────────────────────────────────────────────────

	public function render_settings(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$api_base = (string) get_option( FORME_SEO_OPT_API_BASE, FORME_SEO_DEFAULT_API );
		$api_key  = (string) get_option( FORME_SEO_OPT_API_KEY, '' );
		$email    = (string) get_option( FORME_SEO_OPT_EMAIL, '' );
		?>
		<div class="csa-wrap">

			<header class="csa-header">
				<div class="csa-header-inner">
					<div class="csa-header-left">
						<div class="csa-logo">
							<img src="<?php echo esc_url( FORME_SEO_URL . 'assets/claude-seo-agent.svg' ); ?>" alt="" class="csa-logo-mark" width="28" height="28" aria-hidden="true">
							<span class="csa-logo-name">Forme SEO AI Agent</span>
							<span class="csa-version-pill">Settings</span>
						</div>
						<div class="csa-header-sub">API configuration and account management</div>
					</div>
					<div class="csa-header-right">
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent' ) ); ?>" class="csa-hdr-btn">
							← Dashboard
						</a>
					</div>
				</div>
			</header>

			<main class="csa-main csa-main--narrow">

				<div class="csa-card">
					<div class="csa-card__head"><h3>API Configuration</h3></div>
					<div class="csa-card__body">
						<table class="form-table csa-settings-table">
							<tr style="display:none;">
								<th scope="row"><label for="csa-s-api-base">API Base URL</label></th>
								<td>
									<input type="url" id="csa-s-api-base" class="regular-text"
										value="<?php echo esc_attr( $api_base ); ?>"
										placeholder="<?php echo esc_attr( FORME_SEO_DEFAULT_API ); ?>" />
									<p class="description">Default: <?php echo esc_html( FORME_SEO_DEFAULT_API ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row"><label for="csa-s-email">Account Email</label></th>
								<td>
									<input type="email" id="csa-s-email" class="regular-text"
										value="<?php echo esc_attr( $email ); ?>"
										placeholder="you@example.com" />
								</td>
							</tr>
							<tr>
								<th scope="row"><label for="csa-s-api-key">API Key</label></th>
								<td>
									<div class="csa-key-field">
										<input type="password" id="csa-s-api-key" class="regular-text"
											value="<?php echo esc_attr( $api_key ); ?>"
											autocomplete="off"
											placeholder="<?php echo $api_key ? '••••••••••••' . esc_attr( substr( $api_key, -4 ) ) : 'Paste your API key'; ?>" />
										<button type="button" id="csa-key-reveal" class="csa-btn csa-btn--outline csa-btn--sm">Reveal</button>
										<button type="button" id="csa-key-replace" class="csa-btn csa-btn--outline csa-btn--sm">Replace</button>
									</div>
									<p class="description">Stored securely in WordPress options. Never exposed in page HTML.</p>
								</td>
							</tr>
						</table>
					</div>
					<div class="csa-card__foot">
						<button id="csa-save-btn" class="csa-btn csa-btn--primary">
							<i class="lni lni-save"></i> Save Settings
						</button>

						<button id="csa-test-btn" class="csa-btn csa-btn--outline">
							<i class="lni lni-checkmark-circle"></i> Test Connection
						</button>

						<a href="<?php echo esc_url( admin_url( 'admin.php?page=claude-seo-agent-website-audit' ) ); ?>" class="csa-btn csa-btn--outline">
							<i class="lni lni-search"></i> Run Website Audit
						</a>
					</div>
				</div>
				
				<div class="csa-card" id="csa-settings-gsc-card">
					<div class="csa-card__head">
						<div class="csa-card-title-group">
							<i class="lni lni-google csa-card-title-icon"></i>
							<h3>Google Search Console</h3>
						</div>
						<span id="csa-gsc-badge" class="csa-badge csa-badge--warning">Not Connected</span>
					</div>

					<div class="csa-card__body">
						<p class="description" style="margin-bottom:16px;">
							Connect Google Search Console and choose the property used for ranking snapshots.
						</p>

						<div class="csa-gsc-manager">
							<div class="csa-gsc-row">
								<label for="csa-gsc-property-select">Search Console Property</label>
								<select id="csa-gsc-property-select">
									<option value="">Loading properties…</option>
								</select>
							</div>

							<p id="csa-gsc-selected-note" class="csa-muted"></p>
						</div>
					</div>

					<div class="csa-card__foot">
						<button id="csa-gsc-connect-btn" class="csa-btn csa-btn--primary">
							<i class="lni lni-google"></i> Connect GSC
						</button>

						<button id="csa-gsc-save-property" class="csa-btn csa-btn--outline">
							<i class="lni lni-checkmark-circle"></i> Save Property
						</button>

						<button id="csa-gsc-reconnect-btn" class="csa-btn csa-btn--outline">
							<i class="lni lni-reload"></i> Reconnect
						</button>

						<button id="csa-gsc-disconnect-btn" class="csa-btn csa-btn--danger">
							<i class="lni lni-unlink"></i> Disconnect
						</button>
					</div>
				</div>
			</main>

			<div id="csa-spinner-overlay" style="display:none;" aria-live="polite">
				<div class="csa-spinner-box">
					<div class="csa-spinner"></div>
					<p id="csa-spinner-msg">Please wait…</p>
				</div>
			</div>

		</div><!-- .csa-wrap -->
		<?php
	}

	// ── AJAX helpers ──────────────────────────────────────────────────────────

	private function verify(): void {
		check_ajax_referer( 'forme_seo_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => 'Insufficient permissions.' ], 403 );
		}
	}

	private function api( string $base = '', string $key = '' ): Forme_SEO_API {
		return new Forme_SEO_API( $base, $key );
	}

	// ── AJAX handlers ─────────────────────────────────────────────────────────

	public function forme_seo_register(): void {
		$this->verify();

		$email = sanitize_email( wp_unslash( $_POST['email'] ?? '' ) );
		if ( ! is_email( $email ) ) {
			wp_send_json_error( [ 'message' => 'Please enter a valid email address.' ] );
		}

		$result = $this->api()->register( $email, home_url() );
		if ( ! $result['success'] ) {
			wp_send_json_error( $result );
		}

		$api_key = $result['data']['api_key'] ?? '';
		if ( ! $api_key ) {
			wp_send_json_error( [ 'message' => 'No API key returned from server.' ] );
		}

		update_option( FORME_SEO_OPT_API_KEY, sanitize_text_field( $api_key ) );
		update_option( FORME_SEO_OPT_EMAIL, $email );

		$client = $this->api( '', $api_key );
		$me     = $client->me();
		$usage  = $client->usage();

		wp_send_json_success( [
			'api_key' => $api_key,
			'me'      => $me['success'] ? $me['data'] : null,
			'usage'   => $usage['success'] ? $usage['data'] : null,
		] );
	}

	public function forme_seo_refresh(): void {
		$this->verify();

		$client = $this->api();
		$me     = $client->me();
		$usage  = $client->usage();

		if ( ! $me['success'] ) {
			wp_send_json_error( $me );
		}

		wp_send_json_success( [
			'me'    => $me['data'],
			'usage' => $usage['success'] ? $usage['data'] : null,
		] );
	}

	public function forme_seo_test_connection(): void {
		$this->verify();

		$base = sanitize_text_field( wp_unslash( $_POST['api_base'] ?? '' ) );
		$key  = sanitize_text_field( wp_unslash( $_POST['api_key']  ?? '' ) );

		$client = $this->api( $base, $key );
		$result = $client->me();

		if ( $result['success'] ) {
			wp_send_json_success( [ 'me' => $result['data'], 'message' => 'Connection successful!' ] );
		} else {
			wp_send_json_error( $result );
		}
	}

	public function forme_seo_checkout(): void {
		$this->verify();

		$plan = sanitize_key( wp_unslash( $_POST['plan'] ?? '' ) );
		if ( ! in_array( $plan, [ 'pro', 'agency' ], true ) ) {
			wp_send_json_error( [ 'message' => 'Invalid plan selected.' ] );
		}

		$result = $this->api()->create_checkout_session( $plan );
		if ( ! $result['success'] ) {
			wp_send_json_error( $result );
		}

		$url = $result['data']['checkout_url'] ?? '';
		if ( ! $url ) {
			wp_send_json_error( [ 'message' => 'No checkout URL returned from server.' ] );
		}

		wp_send_json_success( [ 'checkout_url' => $url ] );
	}

	public function forme_seo_portal(): void {
		$this->verify();

		$result = $this->api()->create_portal_session();
		if ( ! $result['success'] ) {
			wp_send_json_error( $result );
		}

		$url = $result['data']['portal_url'] ?? '';
		if ( ! $url ) {
			wp_send_json_error( [ 'message' => 'No portal URL returned from server.' ] );
		}

		wp_send_json_success( [ 'portal_url' => $url ] );
	}

	public function forme_seo_save_settings(): void {
		$this->verify();

		if ( ! empty( $_POST['clear_key'] ) ) {
			delete_option( FORME_SEO_OPT_API_KEY );
			wp_send_json_success( [ 'message' => 'API key cleared.', 'cleared' => true ] );
		}

		$base = sanitize_text_field( wp_unslash( $_POST['api_base'] ?? '' ) );
		$key  = sanitize_text_field( wp_unslash( $_POST['api_key']  ?? '' ) );
		$mail = sanitize_email(      wp_unslash( $_POST['email']    ?? '' ) );

		if ( $base ) update_option( FORME_SEO_OPT_API_BASE, esc_url_raw( $base ) );
		if ( $key )  update_option( FORME_SEO_OPT_API_KEY, $key );
		if ( $mail ) update_option( FORME_SEO_OPT_EMAIL, $mail );

		wp_send_json_success( [ 'message' => 'Settings saved.' ] );
	}

	private function run_tool( callable $fn ): void {
		$this->verify();

		$url = home_url(); // Always locked to current site — ignore any POSTed URL.
		if ( ! $url ) {
			wp_send_json_error( [ 'message' => 'URL is required.' ] );
		}

		$result = $fn( $url );
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	public function forme_seo_run_audit():           void { $a = $this->api(); $this->run_tool( [ $a, 'audit' ] ); }
	public function forme_seo_run_technical():       void { $a = $this->api(); $this->run_tool( [ $a, 'technical' ] ); }
	public function forme_seo_run_content():         void { $a = $this->api(); $this->run_tool( [ $a, 'content' ] ); }
	public function forme_seo_run_schema():          void { $a = $this->api(); $this->run_tool( [ $a, 'schema' ] ); }
	public function forme_seo_run_sitemap():         void { $a = $this->api(); $this->run_tool( [ $a, 'sitemap' ] ); }
	public function forme_seo_run_images():          void { $a = $this->api(); $this->run_tool( [ $a, 'images' ] ); }
	public function forme_seo_run_content_pillars(): void { $a = $this->api(); $this->run_tool( [ $a, 'content_pillars' ] ); }

	public function forme_seo_poll_job(): void {
		$this->verify();
		$job_id = sanitize_text_field( wp_unslash( $_POST['job_id'] ?? '' ) );
		if ( ! $job_id ) {
			wp_send_json_error( [ 'message' => 'job_id is required.' ] );
		}
		$result = $this->api()->poll_job( $job_id );
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	// ── Reports AJAX handlers ─────────────────────────────────────────────────

	public function forme_seo_get_reports(): void {
		$this->verify();
		$tool   = sanitize_key( wp_unslash( $_POST['tool'] ?? '' ) );
		$limit  = (int) ( $_POST['limit'] ?? 10 );
		$offset = (int) ( $_POST['offset'] ?? 0 );

		$result = $this->api()->get_reports( $tool, min( $limit, 50 ), max( $offset, 0 ) );
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	public function forme_seo_get_report(): void {
		$this->verify();
		$report_id = sanitize_text_field( wp_unslash( $_POST['report_id'] ?? '' ) );
		if ( ! $report_id ) {
			wp_send_json_error( [ 'message' => 'report_id is required.' ] );
		}
		$result = $this->api()->get_report( $report_id );
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	// ── Tasks AJAX handlers ───────────────────────────────────────────────────

	public function forme_seo_get_tasks(): void {
		$this->verify();
		$status   = sanitize_key( wp_unslash( $_POST['status']   ?? '' ) );
		$priority = sanitize_key( wp_unslash( $_POST['priority'] ?? '' ) );
		$category = sanitize_key( wp_unslash( $_POST['category'] ?? '' ) );
		$limit    = (int) ( $_POST['limit'] ?? 10 );

		$result = $this->api()->get_tasks( $status, $priority, $category, min( $limit, 50 ) );
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	public function forme_seo_update_task(): void {
		$this->verify();
		$task_id = (int) ( $_POST['task_id'] ?? 0 );
		$status  = sanitize_key( wp_unslash( $_POST['status'] ?? '' ) );

		if ( ! $task_id || ! $status ) {
			wp_send_json_error( [ 'message' => 'task_id and status are required.' ] );
		}

		$result = $this->api()->update_task( $task_id, $status );
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	// ── Content project AJAX handlers ─────────────────────────────────────────

	public function forme_seo_get_content_projects(): void {
		$this->verify();
		$result = $this->api()->get_content_projects();
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	public function forme_seo_get_content_project(): void {
		$this->verify();
		$project_id = sanitize_text_field( wp_unslash( $_POST['project_id'] ?? '' ) );
		if ( ! $project_id ) {
			wp_send_json_error( [ 'message' => 'project_id is required.' ] );
		}
		$result = $this->api()->get_content_project( $project_id );
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	public function forme_seo_generate_outline(): void {
		$this->verify();
		$project_id = sanitize_text_field( wp_unslash( $_POST['project_id'] ?? '' ) );
		$topic_id   = sanitize_text_field( wp_unslash( $_POST['topic_id']   ?? '' ) );

		if ( ! $project_id || ! $topic_id ) {
			wp_send_json_error( [ 'message' => 'project_id and topic_id are required.' ] );
		}

		$result = $this->api()->generate_outline( $project_id, $topic_id );
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	public function forme_seo_generate_article(): void {
		$this->verify();
		$project_id = sanitize_text_field( wp_unslash( $_POST['project_id'] ?? '' ) );
		$topic_id   = sanitize_text_field( wp_unslash( $_POST['topic_id']   ?? '' ) );

		if ( ! $project_id || ! $topic_id ) {
			wp_send_json_error( [ 'message' => 'project_id and topic_id are required.' ] );
		}

		$result = $this->api()->generate_article( $project_id, $topic_id );
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	// ── Jobs AJAX handler ────────────────────────────────────────────────────

	public function forme_seo_get_jobs(): void {
		$this->verify();
		$category = sanitize_key( wp_unslash( $_POST['category'] ?? '' ) );
		$tool     = sanitize_key( wp_unslash( $_POST['tool']     ?? '' ) );
		$limit    = min( (int) ( $_POST['limit']  ?? 20 ), 100 );
		$offset   = max( (int) ( $_POST['offset'] ?? 0 ),  0 );

		$result = $this->api()->list_jobs( $category, $tool, $limit, $offset );
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	// ── Site profile + topics AJAX handlers ──────────────────────────────────

	public function forme_seo_get_site_profile(): void {
		$this->verify();
		$result = $this->api()->site_profile();
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	public function forme_seo_get_all_topics(): void {
		$this->verify();
		$status = sanitize_key( wp_unslash( $_POST['status'] ?? '' ) );
		$limit  = min( (int) ( $_POST['limit'] ?? 50 ), 200 );

		$result = $this->api()->get_content_topics( $status, $limit );
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	public function forme_seo_run_blog_strategy(): void {
		$this->verify();

		$niche = sanitize_text_field(
			wp_unslash( $_POST['niche'] ?? '' )
		);

		if ( empty( $niche ) ) {
			wp_send_json_error(
				[
					'message' => 'Niche is required.',
				],
				400
			);
		}

		$payload = [
			'niche'      => $niche,
			'quarter'    => sanitize_text_field( wp_unslash( $_POST['quarter'] ?? 'Q2' ) ),
			'frequency'  => intval( $_POST['frequency'] ?? 2 ),
			'months'     => intval( $_POST['months'] ?? 3 ),
			'start_date' => sanitize_text_field(
				wp_unslash( $_POST['start_date'] ?? gmdate( 'Y-m-d' ) )
			),
		];

		$result = $this->api()->blog_strategy( $payload );

		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		}

		wp_send_json_error( $result );
	}

	public function forme_seo_run_blog_calendar(): void {
		$this->verify();

		$url       = home_url(); // Always locked to current site — ignore any POSTed URL.
		$quarter   = sanitize_text_field( wp_unslash( $_POST['quarter']   ?? 'Q1' ) );
		$frequency = (int) ( $_POST['frequency'] ?? 2 );
		$months    = (int) ( $_POST['months']    ?? 3 );

		$result = $this->api()->blog_calendar( $url, $quarter, $frequency, $months );
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	public function forme_seo_run_blog_write(): void {
		$this->verify();

		$topic = sanitize_text_field( wp_unslash( $_POST['topic'] ?? '' ) );

		if ( empty( $topic ) ) {
			wp_send_json_error( [ 'message' => 'Topic is required.' ], 400 );
		}

		$result = $this->api()->blog_write_async( $topic );

		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		}

		wp_send_json_error( $result );
	}

	// ── GSC AJAX handlers ─────────────────────────────────────────────────────

	public function forme_seo_gsc_auth_url(): void {
		$this->verify();

		$return_url = esc_url_raw( wp_unslash( $_POST['return_url'] ?? admin_url( 'admin.php?page=claude-seo-agent' ) ) );

		$result = $this->api()->gsc_auth_url( $return_url );

		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		}

		wp_send_json_error( $result );
	}

	public function forme_seo_gsc_properties(): void {
		$this->verify();
		$result = $this->api()->gsc_properties();
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	public function forme_seo_gsc_select_property(): void {
		$this->verify();

		$property = sanitize_text_field( wp_unslash( $_POST['property'] ?? '' ) );

		if ( ! $property ) {
			wp_send_json_error( [ 'message' => 'Property is required.' ] );
		}

		$result = $this->api()->gsc_select_property( $property );

		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		}

		wp_send_json_error( $result );
	}

	public function forme_seo_gsc_overview(): void {
		$this->verify();
		$result = $this->api()->gsc_overview();
		if ( $result['success'] ) {
			wp_send_json_success( $result['data'] );
		} else {
			wp_send_json_error( $result );
		}
	}

	public function forme_seo_gsc_disconnect(): void {
		$this->verify();
		$result = $this->api()->gsc_disconnect();
		if ( $result['success'] ) {
			wp_send_json_success( [ 'disconnected' => true ] );
		} else {
			wp_send_json_error( $result );
		}
	}

	private function csa_audit_jobs(): array {
		return get_option( 'forme_seo_local_audit_jobs', [] );
	}

	private function csa_save_audit_jobs( array $jobs ): void {
		update_option( 'forme_seo_local_audit_jobs', $jobs, false );
	}

	private function csa_update_audit_job( string $job_id, array $patch ): void {
		$jobs = $this->csa_audit_jobs();

		if ( empty( $jobs[ $job_id ] ) ) {
			return;
		}

		$jobs[ $job_id ] = array_merge( $jobs[ $job_id ], $patch, [
			'updated_at' => current_time( 'mysql' ),
		] );

		$this->csa_save_audit_jobs( $jobs );
	}

	private function csa_reconcile_local_audit_jobs(): void {
		$jobs = $this->csa_audit_jobs();

		if ( empty( $jobs ) ) {
			return;
		}

		$has_active = false;

		foreach ( $jobs as $job ) {
			if ( in_array( $job['status'] ?? '', [ 'queued', 'running' ], true ) ) {
				$has_active = true;
				break;
			}
		}

		if ( ! $has_active ) {
			return;
		}

		$reports_result = $this->api()->get_reports( 'audit', 20, 0 );

		if ( empty( $reports_result['success'] ) ) {
			return;
		}

		$reports = $reports_result['data']['reports'] ?? [];

		if ( empty( $reports ) ) {
			return;
		}

		foreach ( $jobs as $job_id => $job ) {
			$status = $job['status'] ?? '';

			if ( ! in_array( $status, [ 'queued', 'running' ], true ) ) {
				continue;
			}

			$job_url = untrailingslashit( $job['input_url'] ?? '' );

			foreach ( $reports as $report ) {
				if ( ( $report['tool'] ?? '' ) !== 'audit' ) {
					continue;
				}

				if ( ( $report['status'] ?? '' ) !== 'completed' ) {
					continue;
				}

				$report_url = untrailingslashit(
					$report['target_url'] ??
					$report['input_url'] ??
					$report['url'] ??
					''
				);

				if ( ! $job_url || ! $report_url || $job_url !== $report_url ) {
					continue;
				}

				$jobs[ $job_id ] = array_merge( $job, [
					'status'    => 'completed',
					'score'     => $report['score'] ?? null,
					'report_id' => $report['id'] ?? null,
					'message'   => 'Audit completed.',
					'result'    => $report,
					'updated_at' => current_time( 'mysql' ),
				] );

				break;
			}
		}

		$this->csa_save_audit_jobs( $jobs );
	}

	public function forme_seo_start_audit_async(): void {
		$this->verify();

		$url = home_url(); // Always locked to current site — ignore any POSTed URL.

		if ( ! $url ) {
			wp_send_json_error( [ 'message' => 'URL is required.' ] );
		}

		$job_id = 'wp_audit_' . wp_generate_uuid4();

		$jobs = $this->csa_audit_jobs();

		$jobs[ $job_id ] = [
			'job_id'     => $job_id,
			'tool'       => 'audit',
			'category'   => 'audit_tools',
			'input_url'  => $url,
			'status'     => 'queued',
			'score'      => null,
			'report_id'  => null,
			'message'    => 'Queued locally in WordPress.',
			'created_at' => current_time( 'mysql' ),
			'updated_at' => current_time( 'mysql' ),
			'result'     => null,
			'error'      => null,
		];

		$this->csa_save_audit_jobs( $jobs );

		error_log( '[SEO AI Agent] Audit queued locally: ' . $job_id . ' URL: ' . $url );

		if ( ! wp_next_scheduled( 'forme_seo_process_audit_job', [ $job_id ] ) ) {
			wp_schedule_single_event( time() + 5, 'forme_seo_process_audit_job', [ $job_id ] );
		}

		wp_send_json_success( [
			'job_id' => $job_id,
			'status' => 'queued',
			'message' => 'Audit queued. You can safely leave this page open and watch history.',
		] );
	}

	public function process_local_audit_job( string $job_id ): void {
		$jobs = $this->csa_audit_jobs();

		if ( empty( $jobs[ $job_id ] ) ) {
			error_log( '[SEO AI Agent] Local audit job not found: ' . $job_id );
			return;
		}

		$url = $jobs[ $job_id ]['input_url'] ?? home_url();

		$this->csa_update_audit_job( $job_id, [
			'status'  => 'running',
			'message' => 'Running audit on server...',
		] );

		error_log( '[SEO AI Agent] Audit started: ' . $job_id . ' URL: ' . $url );

		$result = $this->api()->audit( $url );

		if ( $result['success'] ) {
			$data = $result['data'];

			$this->csa_update_audit_job( $job_id, [
				'status'    => 'completed',
				'score'     => $data['score'] ?? null,
				'report_id' => $data['report_id'] ?? null,
				'message'   => 'Audit completed.',
				'result'    => $data,
			] );

			error_log( '[SEO AI Agent] Audit completed: ' . $job_id );
			return;
		}

		$this->csa_update_audit_job( $job_id, [
			'status'  => $result['code'] === 429 ? 'rate_limited' : 'failed',
			'message' => $result['message'] ?? 'Audit failed.',
			'error'   => $result,
		] );

		error_log( '[SEO AI Agent] Audit failed: ' . $job_id . ' ' . wp_json_encode( $result ) );
	}

	public function forme_seo_get_local_audit_jobs(): void {
		$this->verify();

		$this->csa_reconcile_local_audit_jobs();

		$jobs = array_values( $this->csa_audit_jobs() );

		usort( $jobs, function ( $a, $b ) {
			return strcmp( $b['created_at'] ?? '', $a['created_at'] ?? '' );
		} );

		wp_send_json_success( [
			'jobs'  => array_slice( $jobs, 0, 20 ),
			'total' => count( $jobs ),
		] );
	}

	public function forme_seo_create_draft_post(): void {

		$this->verify();

		$title   = sanitize_text_field( wp_unslash( $_POST['title'] ?? '' ) );
		$content = wp_kses_post( wp_unslash( $_POST['content'] ?? '' ) );
		$report  = sanitize_text_field( wp_unslash( $_POST['report_id'] ?? '' ) );

		$post_html = $this->markdown_to_html( $content );

		$post_html = preg_replace( '/^---.*?---/sm', '', $post_html );

		$post_html = preg_replace(
			'/━━━━━━━━.*$/sm',
			'',
			$post_html
		);

		$post_html = str_replace(
			[
				'[Internal link placeholder:',
				']*',
				'*[',
			],
			'',
			$post_html
		);

		$post_html = trim( $post_html );

		if ( empty( $title ) || empty( $content ) ) {
			wp_send_json_error( [ 'message' => 'Missing title/content.' ] );
		}

		$existing = get_posts( [
			'post_type'   => 'post',
			'post_status' => [ 'draft', 'publish' ],
			'meta_key'    => '_csa_report_id',
			'meta_value'  => $report,
			'numberposts' => 1,
		] );

		if ( $existing ) {

			wp_send_json_success( [
				'post_id'  => $existing[0]->ID,
				'topic'    => get_post_meta( $existing[0]->ID, '_csa_topic_title', true ),
				'edit_url' => get_edit_post_link( $existing[0]->ID, '' ),
				'status'   => get_post_status( $existing[0]->ID ),
			] );

		}

		$post_id = wp_insert_post( [
			'post_title'   => $title,
			'post_content' => wp_kses_post( $post_html ),
			'post_status'  => 'draft',
			'post_type'    => 'post',
		] );

		if ( is_wp_error( $post_id ) ) {

			wp_send_json_error( [
				'message' => $post_id->get_error_message(),
			] );

		}

		update_post_meta( $post_id, '_csa_report_id', $report );
		update_post_meta( $post_id, '_csa_topic_title', $title );

		wp_send_json_success( [
			'post_id' => $post_id,
			'edit_url' => get_edit_post_link( $post_id, '' ),
			'status' => 'draft',
		] );
	}

	public function forme_seo_get_article_statuses(): void {

	$this->verify();

	$posts = get_posts( [
		'post_type'      => 'post',
		'post_status'    => [ 'draft', 'publish', 'pending', 'private' ],
		'posts_per_page' => -1,
		'meta_query'     => [
			'relation' => 'OR',
			[
				'key'     => '_csa_report_id',
				'compare' => 'EXISTS',
			],
			[
				'key'     => '_csa_topic_title',
				'compare' => 'EXISTS',
			],
		],
	] );

	$data = [];

	foreach ( $posts as $p ) {

		$rid   = (string) get_post_meta( $p->ID, '_csa_report_id', true );
		$topic = (string) get_post_meta( $p->ID, '_csa_topic_title', true );

			if ( empty( $topic ) ) {
				$topic = get_the_title( $p );
			}

			$row = [
				'post_id'  => $p->ID,
				'report_id'=> $rid,
				'topic'    => $topic,
				'status'   => get_post_status( $p ),
				'edit_url' => get_edit_post_link( $p->ID, '' ),
				'view_url' => get_permalink( $p->ID ),
			];

			if ( $rid ) {
				$data[ 'report_' . $rid ] = $row;
			}

			if ( $topic ) {
				$data[ 'topic_' . md5( strtolower( trim( $topic ) ) ) ] = $row;
			}
		}

		wp_send_json_success( $data );
	}

	private function markdown_to_html( string $md ): string {

	// Remove YAML frontmatter
	$md = preg_replace( '/\A\s*---[\s\S]*?---\s*/', '', $md );

	// Remove promo/footer blocks
	$md = preg_replace( '/━━━━━━━━[\s\S]*$/', '', $md );
	$md = preg_replace( '/Built by agricidaniel[\s\S]*$/i', '', $md );

	// Remove markdown horizontal rules
	$md = preg_replace( '/^\s*---+\s*$/m', '', $md );

	// Clean internal-link placeholders
	$md = preg_replace( '/\*?\[Internal link placeholder:\s*(.*?)\]\*?/i', '', $md );
	$md = preg_replace( '/\*?\[INTERNAL-LINK:\s*(.*?)\]\*?/i', '', $md );

	$lines  = preg_split( "/\r\n|\n|\r/", trim( $md ) );
	$html   = '';
	$buffer = '';
	$in_ul  = false;

	$flush_p = function () use ( &$html, &$buffer ) {
		$text = trim( $buffer );

			if ( '' === $text ) {
				$buffer = '';
				return;
			}

			$text = esc_html( $text );
			$text = preg_replace( '/\*\*(.*?)\*\*/', '<strong>$1</strong>', $text );
			$text = preg_replace( '/\*(.*?)\*/', '<em>$1</em>', $text );

			$html .= "<!-- wp:paragraph -->\n<p>{$text}</p>\n<!-- /wp:paragraph -->\n\n";

			$buffer = '';
		};

		$close_ul = function () use ( &$html, &$in_ul ) {
			if ( $in_ul ) {
				$html .= "</ul>\n<!-- /wp:list -->\n\n";
				$in_ul = false;
			}
		};

		foreach ( $lines as $line ) {
			$line = trim( $line );

			if ( '' === $line ) {
				$flush_p();
				$close_ul();
				continue;
			}

			// H1 becomes H2 to avoid duplicate post title
			if ( preg_match( '/^#\s+(.+)$/', $line, $m ) ) {
				$flush_p();
				$close_ul();
				$text  = esc_html( trim( $m[1] ) );
				$html .= "<!-- wp:heading -->\n<h2>{$text}</h2>\n<!-- /wp:heading -->\n\n";
				continue;
			}

			if ( preg_match( '/^##\s+(.+)$/', $line, $m ) ) {
				$flush_p();
				$close_ul();
				$text  = esc_html( trim( $m[1] ) );
				$html .= "<!-- wp:heading -->\n<h2>{$text}</h2>\n<!-- /wp:heading -->\n\n";
				continue;
			}

			if ( preg_match( '/^###\s+(.+)$/', $line, $m ) ) {
				$flush_p();
				$close_ul();
				$text  = esc_html( trim( $m[1] ) );
				$html .= "<!-- wp:heading {\"level\":3} -->\n<h3>{$text}</h3>\n<!-- /wp:heading -->\n\n";
				continue;
			}

			if ( preg_match( '/^-+\s+(.+)$/', $line, $m ) ) {
				$flush_p();

				if ( ! $in_ul ) {
					$html .= "<!-- wp:list -->\n<ul>\n";
					$in_ul = true;
				}

				$item = esc_html( trim( $m[1] ) );
				$item = preg_replace( '/\*\*(.*?)\*\*/', '<strong>$1</strong>', $item );
				$item = preg_replace( '/\*(.*?)\*/', '<em>$1</em>', $item );

				$html .= "<li>{$item}</li>\n";
				continue;
			}

			$close_ul();

			$buffer .= $buffer ? ' ' . $line : $line;
		}

		$flush_p();
		$close_ul();

		return trim( $html );
	}
}
