<?php
defined( 'ABSPATH' ) || exit;

/**
 * Contentosapp Studio Standalone — Bootstrap
 *
 * Responsible for: autoloader, activation/deactivation hooks,
 * loading the compat layer, and initializing admin + REST.
 *
 * @since 1.0.0
 */
class Costudio_Standalone_Bootstrap {

	/**
	 * Class map for the autoloader.
	 * Order matters — compat must load before everything else.
	 *
	 * @var array<string, string>
	 */
	private static array $class_map = array(
		// Standalone-specific (new classes)
		'Costudio_Standalone_Crypto'   => 'includes/class-costudio-standalone-crypto.php',
		'Costudio_Standalone_Settings' => 'includes/class-costudio-standalone-settings.php',
		'Costudio_Standalone_Sites'    => 'includes/class-costudio-standalone-sites.php',
		'Costudio_Standalone_License'  => 'includes/class-costudio-standalone-license.php',
		'Costudio_Standalone_Migrator' => 'includes/class-costudio-standalone-migrator.php',

		// Copied from contentos-core (engine — no modifications)
		'Costudio_Exceptions'          => 'includes/class-costudio-exceptions.php',
		'Costudio_AI_Client'           => 'includes/class-costudio-ai-client.php',
		'Costudio_Crypto'              => 'includes/class-costudio-crypto.php',
		'Costudio_DB'                  => 'includes/class-costudio-db.php',
		'Costudio_Production'          => 'includes/class-costudio-production.php',
		'Costudio_Planning'            => 'includes/class-costudio-planning.php',
		'Costudio_Pipeline'            => 'includes/class-costudio-pipeline.php',
		'Costudio_Search_Engine'       => 'includes/class-costudio-search-engine.php',
		'Costudio_Search_Engine_ContentOS' => 'includes/class-costudio-search-engine-contentos.php',
		'Costudio_Search_Engine_Gemini' => 'includes/class-costudio-search-engine-gemini.php',
		'Costudio_Content_Word_Count'  => 'includes/class-costudio-content-word-count.php',
		'Costudio_Runner'              => 'includes/class-costudio-runner.php',
		'Costudio_Telemetry'           => 'includes/class-costudio-telemetry.php',
		'Costudio_Review_Prompt'       => 'includes/class-costudio-review-prompt.php',
		'Costudio_Pipeline_Input_Mapper' => 'includes/pipeline/class-costudio-pipeline-input-mapper.php',
		'Costudio_Pipeline_Links'      => 'includes/pipeline/class-costudio-pipeline-links.php',
		'Costudio_Pipeline_Summaries'  => 'includes/pipeline/class-costudio-pipeline-summaries.php',
		'Costudio_Pipeline_Image_Markers' => 'includes/pipeline/class-costudio-pipeline-image-markers.php',
		'Costudio_WP_Publisher'        => 'includes/class-costudio-wp-publisher.php',
		'Costudio_Publisher_Text_Extractor' => 'includes/publisher/class-costudio-publisher-text-extractor.php',
		'Costudio_Publisher_Content_Normalizer' => 'includes/publisher/class-costudio-publisher-content-normalizer.php',
		'Costudio_Publisher_Image_Prompts' => 'includes/publisher/class-costudio-publisher-image-prompts.php',
		'Costudio_Publisher_Schema'    => 'includes/publisher/class-costudio-publisher-schema.php',
		'Costudio_Publisher_Markdown_Renderer' => 'includes/publisher/class-costudio-publisher-markdown-renderer.php',
		'Costudio_References_Renderer' => 'includes/class-costudio-references-renderer.php',
		'Costudio_Image_Generator'     => 'includes/class-costudio-image-generator.php',
		'Costudio_Link_Finder'         => 'includes/class-costudio-link-finder.php',
		'Costudio_Rate_Limiter'        => 'includes/class-costudio-rate-limiter.php',
		'Costudio_Circuit_Breaker'     => 'includes/class-costudio-circuit-breaker.php',
		'Costudio_Usage'               => 'includes/class-costudio-usage.php',
		'Costudio_Logger'              => 'includes/class-costudio-logger.php',
		'Costudio_Housekeeping'        => 'includes/class-costudio-housekeeping.php',
		'Costudio_Production_Queue'    => 'includes/class-costudio-production-queue.php',
		'Costudio_Publication_Ledger'  => 'includes/class-costudio-publication-ledger.php',
		'Costudio_Publication_Recovery'=> 'includes/class-costudio-publication-recovery.php',
		'Costudio_Publication_Jobs'     => 'includes/class-costudio-publication-jobs.php',
		'Costudio_Publication_Worker'   => 'includes/class-costudio-publication-worker.php',
		'Costudio_Publication_Jobs_CLI' => 'includes/class-costudio-publication-jobs-cli.php',
		'Costudio_Remote_Jobs'         => 'includes/class-costudio-remote-jobs.php',
		'Costudio_BYOK_Jobs'           => 'includes/class-costudio-byok-jobs.php',
		'Costudio_BYOK_Jobs_CLI'       => 'includes/class-costudio-byok-jobs-cli.php',
		'Costudio_BYOK_Job_Codec'      => 'includes/class-costudio-byok-job-codec.php',
		'Costudio_BYOK_Gateway'        => 'includes/class-costudio-byok-gateway.php',
		'Costudio_BYOK_Provider_Executor' => 'includes/class-costudio-byok-provider-executor.php',
		'Costudio_BYOK_Worker'         => 'includes/class-costudio-byok-worker.php',
		'Costudio'                      => 'includes/class-costudio.php',

		// Adapters
		'Costudio_ContentOS_Adapter'    => 'includes/adapters/class-costudio-contentos-adapter.php',
		'Costudio_Gemini_Adapter'      => 'includes/adapters/class-costudio-gemini-adapter.php',
		'Costudio_Claude_Adapter'      => 'includes/adapters/class-costudio-claude-adapter.php',
		'Costudio_OpenAI_Adapter'      => 'includes/adapters/class-costudio-openai-adapter.php',
		'Costudio_Model_Fallback'      => 'includes/adapters/class-costudio-model-fallback.php',

		// Agent prompt seeder (fetches from contentosapp-api)
		'Costudio_Agent_Seeder'        => 'includes/class-costudio-agent-seeder.php',
		'Costudio_Prompt_Sanitizer'    => 'includes/class-costudio-prompt-sanitizer.php',

		// Admin
		'Costudio_Admin'                 => 'admin/class-costudio-admin.php',
		'Costudio_Admin_Sites'           => 'admin/class-costudio-admin-sites.php',
		'Costudio_Admin_Menu'            => 'admin/class-costudio-admin-menu.php',
		'Costudio_Admin_Assets'          => 'admin/class-costudio-admin-assets.php',
		'Costudio_Admin_Tables'          => 'admin/class-costudio-admin-tables.php',
		'Costudio_Admin_Model_Discovery' => 'admin/helpers/class-costudio-admin-model-discovery.php',
		'Costudio_Admin_Production_Lifecycle' => 'admin/helpers/class-costudio-admin-production-lifecycle.php',
		'Costudio_Admin_Production_Validator' => 'admin/helpers/class-costudio-admin-production-validator.php',
		'Costudio_Admin_Production_Exporter' => 'admin/helpers/class-costudio-admin-production-exporter.php',
		'Costudio_Admin_Remote_Post_Sync' => 'admin/helpers/class-costudio-admin-remote-post-sync.php',

		// Admin — AJAX controllers (Task 2 split)
		'Costudio_Admin_Ajax_Base'       => 'admin/ajax/class-costudio-admin-ajax-base.php',
		'Costudio_Admin_Ajax_Planning'   => 'admin/ajax/class-costudio-admin-ajax-planning.php',
		'Costudio_Admin_Ajax_Misc'       => 'admin/ajax/class-costudio-admin-ajax-misc.php',
		'Costudio_Admin_Ajax_Settings'   => 'admin/ajax/class-costudio-admin-ajax-settings.php',
		'Costudio_Admin_Ajax_Production' => 'admin/ajax/class-costudio-admin-ajax-production.php',
		'Costudio_Admin_Ajax_Tables'     => 'admin/ajax/class-costudio-admin-ajax-tables.php',
	);

	// -------------------------------------------------------------------------
	// Lifecycle
	// -------------------------------------------------------------------------

	/**
	 * Activation hook: create DB tables, set activation timestamp.
	 *
	 * @since 1.0.0
	 */
	public static function activate(): void {
		self::load_autoloader();
		self::load_engine_prerequisites();
		self::load_compat();

		// Install DB tables
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		Costudio_DB::install();

		// Seed language from WP site locale on first install.
		if ( ! function_exists( 'costudio_seed_language_on_activation' ) ) {
			require_once COSTUDIO_DIR . 'includes/costudio-i18n-locale.php';
		}
		costudio_seed_language_on_activation();

		// Fetch agent prompts from contentosapp-api (force refresh on activation).
		require_once COSTUDIO_DIR . 'includes/class-costudio-agent-seeder.php';
		$lang = function_exists( 'costudio_map_wp_locale_to_supported' )
			? costudio_map_wp_locale_to_supported( get_locale() )
			: 'pt_BR';
		Costudio_Agent_Seeder::fetch_and_store( $lang );

		update_option( 'costudio_activated_at', time(), false );
		update_option( 'costudio_plugin_version', COSTUDIO_VERSION, false );

		flush_rewrite_rules();
	}

	/**
	 * Deactivation hook.
	 *
	 * @since 1.0.0
	 */
	public static function deactivate(): void {
		wp_clear_scheduled_hook( 'costudio_telemetry_ping' );
		wp_clear_scheduled_hook( 'costudio_revalidate_license' );
		wp_clear_scheduled_hook( 'costudio_sync_prompts_cron' );
		wp_clear_scheduled_hook( 'costudio_housekeeping_cleanup' );
		wp_clear_scheduled_hook( 'costudio_stalled_pipeline_watchdog' );
		wp_clear_scheduled_hook( 'costudio_queue_dispatch_watchdog' );
		flush_rewrite_rules();
	}

	/**
	 * Sincroniza prompts via WP Cron (background, sem bloquear o admin).
	 * Também pode ser chamado manualmente via AJAX pelo botão no Settings.
	 */
	public static function maybe_refresh_prompts(): void {
		if ( ! class_exists( 'Costudio_Agent_Seeder' ) ) {
			require_once COSTUDIO_DIR . 'includes/class-costudio-agent-seeder.php';
		}
		$lang = function_exists( 'costudio_resolve_ui_locale_from_options' )
			? costudio_resolve_ui_locale_from_options()
			: 'pt_BR';
		Costudio_Agent_Seeder::maybe_fetch( $lang );
	}

	/**
	 * Main init — hooked on plugins_loaded (priority 10).
	 *
	 * @since 1.0.0
	 */
	public static function init(): void {
		if ( defined( 'CONTENTOS_VERSION' ) ) {
			self::register_migration_mode_hooks();
			return;
		}

		self::load_autoloader();
		self::load_engine_prerequisites();
		self::load_compat();

		// Phase 1: diagnostics and schema only. No provider work is registered here.
		if ( defined( 'WP_CLI' ) && WP_CLI && class_exists( 'Costudio_BYOK_Jobs_CLI' ) ) {
			Costudio_BYOK_Jobs_CLI::register();
		}
		if ( defined( 'WP_CLI' ) && WP_CLI && class_exists( 'Costudio_Publication_Jobs_CLI' ) ) {
			Costudio_Publication_Jobs_CLI::register();
		}

		if ( class_exists( 'Costudio_Standalone_Settings' ) ) {
			Costudio_Standalone_Settings::get_instance()->maybe_migrate_contentos_auto_grounding();
		}

		// Ensure language is seeded for existing installs that predate this feature.
		if ( ! function_exists( 'costudio_seed_language_on_activation' ) ) {
			require_once COSTUDIO_DIR . 'includes/costudio-i18n-locale.php';
		}
		costudio_seed_language_on_activation();

		// Load the UI-locale textdomain on `init` (not earlier) so translation
		// loading is never triggered before the `init` action — required since
		// WordPress 6.7 / 7.0 to avoid the "_doing_it_wrong" early-load notice.
		add_action( 'init', array( self::class, 'load_textdomain' ) );
		add_action( 'init', array( 'Costudio_Publisher_Schema', 'register_meta' ) );
		add_action( 'wp_head', array( 'Costudio_Publisher_Schema', 'render_head' ), 20 );

		// Prompt sync via WP Cron diário (background — nunca bloqueia o admin).
		add_action( 'costudio_sync_prompts_cron', [ self::class, 'maybe_refresh_prompts' ] );
		if ( ! wp_next_scheduled( 'costudio_sync_prompts_cron' ) ) {
			wp_schedule_event( time(), 'daily', 'costudio_sync_prompts_cron' );
		}

		// Admin panel
		if ( is_admin() ) {
			Costudio_Admin::get_instance()->register_hooks();
		}

		// REST API for background pipeline runner
		add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) );

		// Cron fallback when loopback HTTP does not start the next pipeline step.
		add_action( 'costudio_pipeline_cron_run', array( 'Costudio_Runner', 'cron_run_background' ), 10, 2 );
		if ( class_exists( 'Costudio_Publication_Jobs' ) ) {
			Costudio_Publication_Jobs::register_hooks();
		}

		// Telemetry scheduler/sender.
		if ( class_exists( 'Costudio_Telemetry' ) ) {
			Costudio_Telemetry::register_hooks();
			if ( is_admin() ) {
				add_action( 'admin_init', [ 'Costudio_Telemetry', 'maybe_flush_on_admin' ] );
			}
		}

		// Automatic database cleanup.
		if ( class_exists( 'Costudio_Housekeeping' ) ) {
			Costudio_Housekeeping::register_hooks();
		}

		// Local production queue / single-flight guard.
		if ( class_exists( 'Costudio_Production_Queue' ) ) {
			Costudio_Production_Queue::register_hooks();
		}

		// License revalidation — daily cron against contentosapp.com.
		add_action( 'costudio_revalidate_license', [ 'Costudio_Standalone_License', 'revalidate' ] );
		if ( ! wp_next_scheduled( 'costudio_revalidate_license' ) ) {
			wp_schedule_event( time(), 'daily', 'costudio_revalidate_license' );
		}

		// Admin notice when license is expired/inactive.
		if ( is_admin() ) {
			add_action( 'admin_notices', [ __CLASS__, 'license_admin_notice' ] );
			add_action( 'admin_notices', [ __CLASS__, 'telemetry_consent_notice' ] );
		}

		// Review prompt — asks for a WordPress.org review after the first
		// completed production. Registered unconditionally: its recorder hook
		// fires in background (REST/cron) requests where is_admin() is false.
		if ( class_exists( 'Costudio_Review_Prompt' ) ) {
			Costudio_Review_Prompt::register_hooks();
		}

		// Maybe run DB upgrades on each load (safe, uses version check internally)
		add_action( 'init', array( __CLASS__, 'maybe_upgrade_db' ) );

		// Invalidate quota cache when productions end.
		add_action( 'costudio_production_completed', [ 'Costudio_Standalone_License', 'on_production_change' ] );
		add_action( 'costudio_production_failed',    [ 'Costudio_Standalone_License', 'on_production_change' ] );
	}

	/**
	 * Register hooks used when ContentOS Core is active.
	 *
	 * This is called both from the plugin file's early Core detection and from
	 * init() as a late guard, because WordPress loads active plugins before it
	 * fires plugins_loaded and the active plugin order is not guaranteed.
	 */
	public static function register_migration_mode_hooks(): void {
		static $registered = false;
		if ( $registered ) {
			return;
		}
		$registered = true;

		add_action( 'contentos_loaded', array( 'Costudio_Standalone_Migrator', 'maybe_import_to_core' ) );
		if ( did_action( 'contentos_loaded' ) ) {
			Costudio_Standalone_Migrator::maybe_import_to_core();
		}

		add_action( 'admin_post_costudio_import_to_core', array( 'Costudio_Standalone_Migrator', 'import_to_core' ) );
		add_action( 'admin_post_costudio_dismiss_import', array( 'Costudio_Standalone_Migrator', 'dismiss_import' ) );
		add_action( 'admin_post_costudio_reset_migration', array( 'Costudio_Standalone_Migrator', 'reset_migration' ) );

		add_action( 'admin_menu', static function(): void {
			add_menu_page(
				'Contentosapp Studio Migration',
				'Contentosapp Studio ⤴',
				'manage_options',
				'contentos-costudio-migration',
				array( 'Costudio_Standalone_Migrator', 'render_migration_page' ),
				'dashicons-migrate',
				30
			);
		} );
	}

	// -------------------------------------------------------------------------
	// Internal helpers
	// -------------------------------------------------------------------------

	/**
	 * Load non-autoloaded engine dependencies.
	 *
	 * The bundled Markdown engine (Costudio_Vendor\Markdown, based on Parsedown)
	 * is renamed + namespaced and loaded behind a class_exists guard to avoid
	 * conflicts with other plugins shipping their own copy.
	 *
	 * @since 1.0.0
	 */
	private static function load_engine_prerequisites(): void {
		$markdown_file = COSTUDIO_DIR . 'includes/class-costudio-markdown.php';
		if ( ! class_exists( '\Costudio_Vendor\Markdown', false ) && file_exists( $markdown_file ) ) {
			require_once $markdown_file;
		}

		// Costudio_Grounding_Exception must be loaded before adapters so that
		// Costudio_Gemini_Adapter can throw/catch it. The autoloader key is
		// 'Costudio_Exceptions' (file-level alias) but PHP resolves the class
		// name 'Costudio_Grounding_Exception' — which is never in the class_map.
		$exceptions_file = COSTUDIO_DIR . 'includes/class-costudio-exceptions.php';
		if ( ! class_exists( 'Costudio_Grounding_Exception', false ) && file_exists( $exceptions_file ) ) {
			require_once $exceptions_file;
		}
	}

	/**
	 * Register the PSR-0-like autoloader from the class map.
	 *
	 * @since 1.0.0
	 */
	private static function load_autoloader(): void {
		spl_autoload_register( static function ( string $class ): void {
			if ( class_exists( $class, false ) ) {
				return;
			}
			if ( isset( self::$class_map[ $class ] ) ) {
				$file = COSTUDIO_DIR . self::$class_map[ $class ];
				if ( file_exists( $file ) ) {
					require_once $file;
				}
			}
		} );
	}

	/**
	 * Load the compat layer (stub functions that emulate the ContentOS Core API).
	 * Must run BEFORE any engine class is instantiated.
	 *
	 * @since 1.0.0
	 */
	private static function load_compat(): void {
		require_once COSTUDIO_DIR . 'includes/class-costudio-compat.php';
	}

	/**
	 * Load plugin textdomain.
	 *
	 * Hooked to `init` (see init()) so translations are never loaded before the
	 * `init` action. The `plugin_locale` filter registered on plugins_loaded:1
	 * resolves the Contentosapp Studio UI locale; this forces the matching bundled .mo.
	 *
	 * @since 1.0.0
	 */
	public static function load_textdomain(): void {
		unload_textdomain( 'contentosapp-studio' );
		if ( ! function_exists( 'costudio_resolve_ui_locale_from_options' ) ) {
			require_once COSTUDIO_DIR . 'includes/costudio-i18n-locale.php';
		}
		$locale = costudio_resolve_ui_locale_from_options();
		$mofile = COSTUDIO_DIR . 'languages/contentosapp-studio-' . $locale . '.mo';
		if ( is_readable( $mofile ) ) {
			load_textdomain( 'contentosapp-studio', $mofile );
		}
	}

	/**
	 * Register REST routes — delegates to the Runner.
	 *
	 * @since 1.0.0
	 */
	public static function register_rest_routes(): void {
		if ( class_exists( 'Costudio_Runner' ) ) {
			Costudio_Runner::register_rest_route();
		}
		if ( class_exists( 'Costudio_Publication_Jobs' ) ) {
			Costudio_Publication_Jobs::register_rest_route();
		}
	}

	/**
	 * Display an admin notice when the license is expired or inactive.
	 *
	 * @since 1.0.0
	 */
	public static function license_admin_notice(): void {
		// Limit to the plugin's own admin pages (Guideline 11 — no global admin nags).
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin routing parameter.
		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
		if ( strpos( $page, 'costudio' ) !== 0 ) {
			return;
		}

		$status  = get_option( 'costudio_license_status', '' );
		$key     = get_option( 'costudio_license_key', '' );

		// Only show if the user had a paid license that is now invalid.
		if ( empty( $key ) || $status === 'active' || $status === '' ) {
			return;
		}

		$messages = [
			'expired'  => __( 'Your Contentosapp Studio license has <strong>expired</strong>. Renew it to continue using the managed ContentOS service.', 'contentosapp-studio' ),
			'disabled' => __( 'Your Contentosapp Studio license has been <strong>disabled</strong>. Please contact support.', 'contentosapp-studio' ),
			'inactive' => __( 'Your Contentosapp Studio license is <strong>inactive</strong>. Please reactivate it in the License page.', 'contentosapp-studio' ),
		];

		$message = $messages[ $status ] ?? sprintf(
			/* translators: %s: license status */
			__( 'Your Contentosapp Studio license status is <strong>%s</strong>. Please check your license.', 'contentosapp-studio' ),
			esc_html( $status )
		);

		$upgrade_url = esc_url( admin_url( 'admin.php?page=costudio-license' ) );

		printf(
			'<div class="notice notice-warning"><p>%s &nbsp;<a href="%s">%s</a></p></div>',
			wp_kses( $message, [ 'strong' => [] ] ),
			esc_url( $upgrade_url ),
			esc_html__( 'View License →', 'contentosapp-studio' )
		);
	}

	/**
	 * Persistent admin notice asking the user to consent to (or decline)
	 * anonymous usage telemetry. Required for LGPD/GDPR compliance on installs
	 * that existed before the consent flow was introduced.
	 *
	 * Only shown on Contentosapp Studio admin pages (avoids polluting the rest of wp-admin)
	 * and only when the user has not yet made a choice. The setup wizard handles
	 * the same decision in Step 3, so it's excluded here to avoid duplicate UI.
	 *
	 * Not dismissable (no X button) — telemetry stays paused until the user
	 * picks one of the two options.
	 *
	 * @since 1.0.0
	 */
	public static function telemetry_consent_notice(): void {
		if ( ! class_exists( 'Costudio_Telemetry' ) || Costudio_Telemetry::has_user_decided() ) {
			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Restrict to Contentosapp Studio admin pages, except the wizard (which has its own UI).
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin routing parameter.
		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
		if ( strpos( $page, 'costudio' ) !== 0 ) {
			return;
		}
		if ( $page === 'costudio-setup' ) {
			return;
		}

		?>
		<div class="fos-tel-consent-banner" id="fos-telemetry-consent-notice" role="region" aria-label="<?php esc_attr_e( 'Privacy update', 'contentosapp-studio' ); ?>">
			<div class="fos-tel-consent-banner__icon" aria-hidden="true">📊</div>
			<div class="fos-tel-consent-banner__body">
				<h3 class="fos-tel-consent-banner__title">
					<?php esc_html_e( 'Privacy update', 'contentosapp-studio' ); ?>
				</h3>
				<p class="fos-tel-consent-banner__desc">
					<?php esc_html_e( 'We updated how we handle usage data. Want to keep helping us improve with anonymous data? We never send your content, keywords or credentials.', 'contentosapp-studio' ); ?>
				</p>
				<div class="fos-tel-consent-banner__actions">
					<button type="button" class="fos-tel-btn fos-tel-btn--primary" id="fos-telemetry-notice-accept">
						✓ <?php esc_html_e( 'Accept and help', 'contentosapp-studio' ); ?>
					</button>
					<button type="button" class="fos-tel-btn fos-tel-btn--ghost" id="fos-telemetry-notice-decline">
						<?php esc_html_e( 'No, thanks', 'contentosapp-studio' ); ?>
					</button>
					<a href="#" id="fos-telemetry-notice-details" class="fos-tel-link">
						<?php esc_html_e( 'See details', 'contentosapp-studio' ); ?> →
					</a>
				</div>
			</div>
		</div>

		<div id="fos-telemetry-notice-modal" style="display:none;position:fixed;inset:0;z-index:100000;background:rgba(0,0,0,0.5);align-items:center;justify-content:center;">
			<div class="fos-modal-card">
				<div class="fos-modal-card__header">
					<div class="fos-modal-card__title-wrap">
						<span class="fos-modal-card__hicon">📊</span>
						<span class="fos-modal-card__title"><?php esc_html_e( 'What we collect', 'contentosapp-studio' ); ?></span>
					</div>
					<button type="button" class="fos-modal-card__close" id="fos-telemetry-notice-modal-x" aria-label="<?php esc_attr_e( 'Close', 'contentosapp-studio' ); ?>">&times;</button>
				</div>
				<div class="fos-modal-card__body">
					<div class="fos-modal-card__section fos-modal-card__section--ok">
						<p class="fos-modal-card__section-title">✓ <?php esc_html_e( 'What we send', 'contentosapp-studio' ); ?></p>
						<ul class="fos-modal-card__list">
							<li><?php esc_html_e( 'AI models used (e.g. Gemini, Claude)', 'contentosapp-studio' ); ?></li>
							<li><?php esc_html_e( 'Article type (Pillar, News, etc.)', 'contentosapp-studio' ); ?></li>
							<li><?php esc_html_e( 'Output language', 'contentosapp-studio' ); ?></li>
							<li><?php esc_html_e( 'Tokens consumed and execution time', 'contentosapp-studio' ); ?></li>
							<li><?php esc_html_e( 'Anonymous site identifier (irreversible hash)', 'contentosapp-studio' ); ?></li>
						</ul>
					</div>
					<div class="fos-modal-card__section fos-modal-card__section--no">
						<p class="fos-modal-card__section-title">✗ <?php esc_html_e( 'What we never send', 'contentosapp-studio' ); ?></p>
						<ul class="fos-modal-card__list">
							<li><?php esc_html_e( 'Article content', 'contentosapp-studio' ); ?></li>
							<li><?php esc_html_e( 'Keywords or production briefings', 'contentosapp-studio' ); ?></li>
							<li><?php esc_html_e( 'Credentials (API keys, passwords)', 'contentosapp-studio' ); ?></li>
							<li><?php esc_html_e( 'Real site URLs', 'contentosapp-studio' ); ?></li>
						</ul>
					</div>
				</div>
				<div class="fos-modal-card__footer">
					<button type="button" class="fos-modal-card__btn--primary" id="fos-telemetry-notice-modal-close">
						<?php esc_html_e( 'Got it', 'contentosapp-studio' ); ?>
					</button>
				</div>
			</div>
		</div>

		<?php
	}

	/**
	 * Run DB upgrades if the stored schema version differs from current.
	 *
	 * Uses 'costudio_db_version' (set by Costudio_DB::install()) and compares
	 * against Costudio_DB::DB_VERSION — NOT COSTUDIO_VERSION. Earlier code
	 * compared COSTUDIO_VERSION against itself and the migrations never ran.
	 *
	 * @since 1.0.0
	 */
	public static function maybe_upgrade_db(): void {
		if ( ! class_exists( 'Costudio_DB' ) ) {
			return;
		}
		$stored = costudio_get_option( 'costudio_db_version', '0' );
		if ( $stored !== Costudio_DB::DB_VERSION ) {
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
			Costudio_DB::install();
		}
	}
}
