<?php
namespace TeknoTok\AiTranslator;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Main Plugin Coordinator class.
 */
class Plugin {
	/**
	 * Singleton instance.
	 *
	 * @var Plugin|null
	 */
	private static $instance = null;

	/**
	 * Settings controller.
	 *
	 * @var Admin\SettingsController|null
	 */
	public $settings = null;

	/**
	 * License client.
	 *
	 * @var Integrations\LicenseManager|null
	 */
	public $license = null;

	/**
	 * Queue Manager.
	 *
	 * @var Queue\QueueManager|null
	 */
	public $queue = null;

	/**
	 * WooCommerce integration.
	 *
	 * @var Integrations\WooCommerceIntegration|null
	 */
	public $woocommerce = null;

	/**
	 * SEO integration.
	 *
	 * @var Integrations\SeoIntegration|null
	 */
	public $seo = null;

	/**
	 * Switcher controller.
	 *
	 * @var Frontend\SwitcherController|null
	 */
	public $switcher = null;

	/**
	 * URL manager.
	 *
	 * @var Frontend\UrlManager|null
	 */
	public $url_manager = null;

	/**
	 * Redirect controller.
	 *
	 * @var Frontend\RedirectController|null
	 */
	public $redirect = null;

	/**
	 * Return the singleton.
	 *
	 * @return Plugin
	 */
	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	private function __construct() {
		$this->init();
	}

	/**
	 * Wire services and hooks.
	 *
	 * @return void
	 */
	private function init() {
		// Load textdomain on init hook
		add_action( 'init', array( $this, 'load_textdomain' ) );

		// Dynamic locale filter to switch core and WC language packs
		add_filter( 'locale', array( $this, 'set_locale' ), 10 );

		// Cron hook for background downloading of language packs
		add_action( 'teknotok_ait_download_translations', array( $this, 'download_translations_cron' ) );

		// Initialize Schema upgrades if version changed
		self::maybe_upgrade_schema();

		// Instantiate modules
		$this->license     = new Integrations\LicenseManager();
		$this->queue       = new Queue\QueueManager();
		$this->woocommerce = new Integrations\WooCommerceIntegration();
		$this->seo         = new Integrations\SeoIntegration();
		$this->switcher    = new Frontend\SwitcherController();
		$this->redirect    = new Frontend\RedirectController();
		$this->url_manager = new Frontend\UrlManager();
		new Frontend\TranslationFilters();

		// Schedule check hooks
		add_action( 'teknotok_ait_daily_license_check', array( $this->license, 'daily_check' ) );

		// Auto-queue hook on post saves
		add_action( 'save_post', array( $this, 'auto_queue_post_translations' ), 10, 3 );

		// Hook controllers
		$this->license->init_hooks();

		// Handle Setup action
		add_action( 'admin_init', array( $this, 'handle_setup_action' ) );

		if ( is_admin() ) {
			new Admin\SettingsController( $this );
			new Admin\LicenseController( $this );
			new Admin\DiagnosticController( $this );
			new Admin\EditorController( $this );
			add_action( 'admin_notices', array( $this, 'admin_notices' ) );
		}
	}

	/**
	 * Get the active language based on GET variables or cookie states.
	 *
	 * @return string Language code.
	 */
	public static function get_active_language() {
		$settings = get_option( 'teknotok_ait_settings', array() );
		$source = $settings['source_language'] ?? 'en';
		$targets = $settings['target_languages'] ?? array();

		// 1. Try to parse from request URI path (for subfolder mode early detection)
		if ( isset( $_SERVER['REQUEST_URI'] ) ) {
			$req_path = trim( parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ), '/' );
			// If WordPress is installed in a subdirectory, strip it
			$home_path = parse_url( get_option( 'home' ), PHP_URL_PATH );
			if ( ! empty( $home_path ) && '/' !== $home_path ) {
				$home_path = trim( $home_path, '/' );
				if ( 0 === strpos( $req_path, $home_path ) ) {
					$req_path = trim( substr( $req_path, strlen( $home_path ) ), '/' );
				}
			}
			$segments = explode( '/', $req_path );
			$first_segment = isset( $segments[0] ) ? sanitize_key( $segments[0] ) : '';
			if ( in_array( $first_segment, $targets, true ) ) {
				return $first_segment;
			}
		}

		// 2. Try to get from query vars (if already parsed)
		$lang = '';
		global $wp_query;
		if ( isset( $wp_query ) && $wp_query instanceof \WP_Query && function_exists( 'get_query_var' ) ) {
			$lang = get_query_var( 'lang' );
		}

		// 3. Try to get from GET parameter
		if ( empty( $lang ) && isset( $_GET['lang'] ) ) {
			$lang = sanitize_key( $_GET['lang'] );
		}

		if ( ! empty( $lang ) && ( in_array( $lang, $targets, true ) || $lang === $source ) ) {
			return $lang;
		}

		// 4. Try to get from cookie
		if ( isset( $_COOKIE['teknotok_ait_language'] ) ) {
			$lang = sanitize_key( $_COOKIE['teknotok_ait_language'] );
			if ( in_array( $lang, $targets, true ) || $lang === $source ) {
				return $lang;
			}
		}

		return $source;
	}

	/**
	 * Load translations.
	 *
	 * @return void
	 */
	public function load_textdomain() {
		load_plugin_textdomain( 'teknotok-ai-translator-pro', false, dirname( TEKNOTOK_AIT_BASENAME ) . '/languages' );
	}

	/**
	 * Save post hook to queue translations automatically.
	 *
	 * @param int      $post_id Post ID.
	 * @param \WP_Post $post    Post object.
	 * @param bool     $update  Whether this is an existing post being updated.
	 * @return void
	 */
	public function auto_queue_post_translations( $post_id, $post, $update ) {
		if ( wp_is_post_revision( $post_id ) || ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) ) {
			return;
		}

		if ( ! Integrations\LicenseManager::is_premium_active() ) {
			return;
		}

		if ( ! self::is_ready_for_translations() ) {
			return;
		}

		$settings = get_option( 'teknotok_ait_settings', array() );
		$auto_translate = $settings['auto_translate'] ?? '1';

		if ( '1' !== $auto_translate ) {
			return;
		}

		$targets = $settings['target_languages'] ?? array();
		if ( empty( $targets ) ) {
			return;
		}

		$source_hash = \TeknoTok\AiTranslator\Database\JobRepository::get_post_source_hash( $post_id );
		foreach ( $targets as $lang ) {
			\TeknoTok\AiTranslator\Database\JobRepository::add_job( 'post', $post_id, $lang, $source_hash );
		}
	}

	/**
	 * Plugin activation.
	 *
	 * @return void
	 */
	public static function activate() {
		require_once TEKNOTOK_AIT_DIR . 'includes/Database/Schema.php';
		Database\Schema::create_tables();
		Database\Schema::seed_defaults();

		// Schedule daily license check
		if ( ! wp_next_scheduled( 'teknotok_ait_daily_license_check' ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'teknotok_ait_daily_license_check' );
		}

		update_option( 'teknotok_ait_activation_notice', 1, false );
		update_option( 'teknotok_ait_db_version', TEKNOTOK_AIT_VERSION, false );

		// Send registration ping to licensing server for free usage tracking
		wp_remote_post(
			TEKNOTOK_AIT_LICENSE_API . 'register-free',
			array(
				'method'      => 'POST',
				'timeout'     => 15,
				'redirection' => 5,
				'httpversion' => '1.0',
				'blocking'    => false,
				'headers'     => array(
					'Content-Type' => 'application/json',
				),
				'body'        => wp_json_encode( array(
					'product_slug' => TEKNOTOK_AIT_PRODUCT_SLUG,
					'site_url'     => get_site_url(),
				) ),
			)
		);

		flush_rewrite_rules();
	}

	/**
	 * Plugin deactivation.
	 *
	 * @return void
	 */
	public static function deactivate() {
		$timestamp = wp_next_scheduled( 'teknotok_ait_daily_license_check' );
		if ( $timestamp ) {
			wp_unschedule_event( $timestamp, 'teknotok_ait_daily_license_check' );
		}

		flush_rewrite_rules();
	}

	/**
	 * Run schema migrations on updates.
	 *
	 * @return void
	 */
	private static function maybe_upgrade_schema() {
		require_once TEKNOTOK_AIT_DIR . 'includes/Database/Schema.php';

		if ( get_option( 'teknotok_ait_db_version' ) === TEKNOTOK_AIT_VERSION && Database\Schema::jobs_support_string_payloads() ) {
			return;
		}

		Database\Schema::create_tables();
		Database\Schema::seed_defaults();
		update_option( 'teknotok_ait_db_version', TEKNOTOK_AIT_VERSION, false );
	}

	/**
	 * Render administrative alerts for WooCommerce and licensing checks.
	 *
	 * @return void
	 */
	public function admin_notices() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( ! class_exists( 'WooCommerce' ) ) {
			echo '<div class="notice notice-error"><p>' . esc_html__( 'TeknoTok AI Translator Pro requires WooCommerce to be installed and active.', 'teknotok-ai-translator-pro' ) . '</p></div>';
			return;
		}

		// Setup Wizard Notice
		if ( get_option( 'teknotok_ait_setup_complete' ) !== '1' ) {
			$languages = array(
				'en' => __( 'English', 'teknotok-ai-translator-pro' ),
				'es' => __( 'Spanish', 'teknotok-ai-translator-pro' ),
				'tr' => __( 'Turkish', 'teknotok-ai-translator-pro' ),
				'zh' => __( 'Chinese', 'teknotok-ai-translator-pro' ),
				'hi' => __( 'Hindi', 'teknotok-ai-translator-pro' ),
				'ar' => __( 'Arabic', 'teknotok-ai-translator-pro' ),
				'pt' => __( 'Portuguese', 'teknotok-ai-translator-pro' ),
				'bn' => __( 'Bengali', 'teknotok-ai-translator-pro' ),
				'ru' => __( 'Russian', 'teknotok-ai-translator-pro' ),
				'ja' => __( 'Japanese', 'teknotok-ai-translator-pro' ),
				'fr' => __( 'French', 'teknotok-ai-translator-pro' ),
			);

			$locale = substr( get_locale(), 0, 2 );
			unset( $languages[ $locale ] );

			?>
			<div class="notice notice-info is-dismissible teknotok-setup-notice" style="border-left-color: #6366f1; padding: 20px; border-radius: 12px; background: #ffffff; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); margin-top: 15px;">
				<div style="display: flex; align-items: center; gap: 20px;">
					<div style="background: #e0e7ff; color: #4f46e5; border-radius: 10px; width: 48px; height: 48px; display: flex; align-items: center; justify-content: center; font-size: 24px;">
						<span class="dashicons dashicons-translation" style="font-size: 24px; width: 24px; height: 24px; line-height: 24px;"></span>
					</div>
					<div style="flex: 1;">
						<h2 style="margin: 0 0 5px 0; color: #1e293b; font-size: 16px; font-weight: 700;"><?php esc_html_e( 'TeknoTok AI Translator: Setup Wizard', 'teknotok-ai-translator-pro' ); ?></h2>
						<p style="margin: 0; color: #64748b; font-size: 14px;"><?php esc_html_e( 'Choose your target language below to automatically translate your pages, posts, and WooCommerce products in the background!', 'teknotok-ai-translator-pro' ); ?></p>
					</div>
				</div>
				<form method="post" action="" style="margin-top: 18px; display: flex; align-items: center; gap: 15px; flex-wrap: wrap;">
					<?php wp_nonce_field( 'teknotok_ait_setup_wizard' ); ?>
					<input type="hidden" name="teknotok_ait_setup_action" value="save_setup" />
					
					<label for="target_language" style="font-weight: 600; color: #334155; font-size: 13px;"><?php esc_html_e( 'Translate my site to:', 'teknotok-ai-translator-pro' ); ?></label>
					<select name="target_language" id="target_language" style="padding: 6px 12px; border: 1px solid #cbd5e1; border-radius: 6px; background: #fff; min-width: 180px;">
						<?php foreach ( $languages as $code => $name ) : ?>
							<option value="<?php echo esc_attr( $code ); ?>"><?php echo esc_html( $name ); ?></option>
						<?php endforeach; ?>
					</select>
					
					<button type="submit" class="button button-primary" style="background: linear-gradient(135deg, #6366f1, #4f46e5); color: white; border: none; padding: 6px 18px; font-weight: 600; border-radius: 6px; cursor: pointer; height: auto; line-height: 1.5; box-shadow: 0 4px 6px -1px rgba(99, 102, 241, 0.2);"><?php esc_html_e( 'Start Translating & View Progress', 'teknotok-ai-translator-pro' ); ?></button>
				</form>
			</div>
			<?php
			return; // Don't show regular notices during setup
		}

		if ( ! Integrations\LicenseManager::is_premium_active() ) {
			$page = sanitize_key( $_GET['page'] ?? '' );
			if ( 0 === strpos( $page, 'teknotok-ait' ) ) {
				$free_usage = $this->license->get_free_usage();
				if ( ! is_wp_error( $free_usage ) && ! empty( $free_usage ) && isset( $free_usage['word_count'] ) ) {
					$word_count = (int) $free_usage['word_count'];
					$limit      = (int) $free_usage['limit'];
					$percentage = $limit > 0 ? min( 100, round( ( $word_count / $limit ) * 100 ) ) : 0;
					$bar_color  = $percentage >= 100 ? '#ef4444' : ( $percentage > 80 ? '#f59e0b' : '#6366f1' );
					$bar_bg     = $percentage >= 100 ? '#fecaca' : ( $percentage > 80 ? '#fef3c7' : '#e0e7ff' );
					$license_url = admin_url( 'admin.php?page=teknotok-ait-license' );
					?>
					<div class="notice notice-info teknotok-limit-notice" style="border-left-color: <?php echo esc_attr( $bar_color ); ?>; padding: 20px; border-radius: 12px; background: #ffffff; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); margin-top: 15px; margin-bottom: 20px; border: 1px solid #e2e8f0;">
						<div style="display: flex; align-items: center; justify-content: space-between; gap: 20px; flex-wrap: wrap;">
							<div style="display: flex; align-items: center; gap: 15px; flex: 2; min-width: 280px;">
								<div style="background: <?php echo esc_attr( $bar_bg ); ?>; color: <?php echo esc_attr( $bar_color ); ?>; border-radius: 10px; width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; font-size: 20px; flex-shrink: 0;">
									<span class="dashicons dashicons-translation"></span>
								</div>
								<div>
									<h4 style="margin: 0; color: #1e293b; font-size: 14px; font-weight: 700;">
										<?php esc_html_e( 'Free Translation Quota:', 'teknotok-ai-translator-pro' ); ?> 
										<span style="font-weight: 800; color: #334155;"><?php echo esc_html( number_format_i18n( $word_count ) ); ?> / <?php echo esc_html( number_format_i18n( $limit ) ); ?> <?php esc_html_e( 'words used', 'teknotok-ai-translator-pro' ); ?></span>
									</h4>
									<p style="margin: 3px 0 0 0; color: #64748b; font-size: 12px;">
										<?php if ( $word_count >= $limit ) : ?>
											<strong style="color: #ef4444;"><?php esc_html_e( 'Lifetime word limit exceeded!', 'teknotok-ai-translator-pro' ); ?></strong>
										<?php else : ?>
											<?php printf( esc_html__( 'You have %s free words remaining.', 'teknotok-ai-translator-pro' ), number_format_i18n( max( 0, $limit - $word_count ) ) ); ?>
										<?php endif; ?>
										&bull; <?php esc_html_e( 'One-time allocation, does not reset.', 'teknotok-ai-translator-pro' ); ?>
									</p>
								</div>
							</div>
							
							<div style="flex: 3; min-width: 200px; max-width: 400px; margin: 0 10px;">
								<div style="width: 100%; height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden; position: relative;">
									<div style="width: <?php echo esc_attr( $percentage ); ?>%; height: 100%; background: <?php echo esc_attr( $bar_color ); ?>; border-radius: 4px; transition: width 0.3s ease;"></div>
								</div>
							</div>

							<div style="flex: 1; min-width: 180px; text-align: right;">
								<a href="<?php echo esc_url( $license_url ); ?>" class="button button-primary" style="background: linear-gradient(135deg, #6366f1, #4f46e5); color: white; border: none; padding: 6px 16px; font-weight: 600; border-radius: 6px; display: inline-block; text-decoration: none; box-shadow: 0 4px 6px -1px rgba(99, 102, 241, 0.2); height: auto; line-height: 1.5;">
									<?php esc_html_e( 'Upgrade to Pro / Enter Key', 'teknotok-ai-translator-pro' ); ?>
								</a>
							</div>
						</div>
					</div>
					<?php
				}
			} else {
				$url = esc_url( admin_url( 'admin.php?page=teknotok-ait-license' ) );
				echo '<div class="notice notice-warning"><p>';
				printf(
					/* translators: %s: license settings page url */
					wp_kses_post( __( 'TeknoTok AI Translator Pro premium features are locked. <a href="%s">Enter and verify your license key</a>.', 'teknotok-ai-translator-pro' ) ),
					$url
				);
				echo '</p></div>';
			}
		}
	}

	/**
	 * Dynamically switch the WordPress locale based on the active language.
	 *
	 * @param string $locale Current locale.
	 * @return string Modified locale.
	 */
	public function set_locale( $locale ) {
		// Do not change locale in admin panel, to preserve admin interface language
		if ( is_admin() ) {
			return $locale;
		}

		$active_lang = self::get_active_language();
		$settings = get_option( 'teknotok_ait_settings', array() );
		$source = $settings['source_language'] ?? 'en';

		if ( $active_lang === $source ) {
			return $locale;
		}

		$locales_map = array(
			'en' => 'en_US',
			'es' => 'es_ES',
			'tr' => 'tr_TR',
			'zh' => 'zh_CN',
			'hi' => 'hi_IN',
			'ar' => 'ar',
			'pt' => 'pt_BR',
			'bn' => 'bn_BD',
			'ru' => 'ru_RU',
			'ja' => 'ja',
			'fr' => 'fr_FR',
		);

		return $locales_map[ $active_lang ] ?? $locale;
	}

	/**
	 * Background task to download translations for new locales.
	 *
	 * @param array $targets List of target language codes.
	 * @return void
	 */
	public function download_translations_cron( $targets ) {
		if ( empty( $targets ) ) {
			return;
		}

		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/template.php';
		require_once ABSPATH . 'wp-admin/includes/translation-install.php';

		$locales_map = array(
			'en' => 'en_US',
			'es' => 'es_ES',
			'tr' => 'tr_TR',
			'zh' => 'zh_CN',
			'hi' => 'hi_IN',
			'ar' => 'ar',
			'pt' => 'pt_BR',
			'bn' => 'bn_BD',
			'ru' => 'ru_RU',
			'ja' => 'ja',
			'fr' => 'fr_FR',
		);

		$downloaded_any = false;
		if ( function_exists( 'wp_download_language_pack' ) ) {
			foreach ( $targets as $lang ) {
				if ( isset( $locales_map[ $lang ] ) ) {
					$locale_code = $locales_map[ $lang ];
					// Download WordPress core translation pack
					$downloaded = wp_download_language_pack( $locale_code );
					if ( $downloaded ) {
						$downloaded_any = true;
						\TeknoTok\AiTranslator\Utils\Logger::log( sprintf( 'Downloaded core translation pack for %s (%s)', $lang, $locale_code ), 'info' );
					}
				}
			}
		}

		// Force check for plugin and theme translation updates
		delete_site_transient( 'translation_updates' );
		delete_site_transient( 'update_plugins' );
		delete_site_transient( 'update_themes' );
		wp_clean_plugins_cache();
		wp_clean_themes_cache();
		wp_update_plugins();
		wp_update_themes();

		// Bulk upgrade translations for WooCommerce, plugins, and themes
		require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		if ( class_exists( '\Language_Pack_Upgrader' ) && class_exists( '\Automatic_Upgrader_Skin' ) ) {
			$upgrader = new \Language_Pack_Upgrader( new \Automatic_Upgrader_Skin() );
			$upgrader->bulk_upgrade();
			\TeknoTok\AiTranslator\Utils\Logger::log( 'Completed bulk translation upgrades for plugins and themes.', 'info' );
		}

		$this->queue_existing_content_for_targets( $targets );
	}

	/**
	 * Queue existing published content for target languages.
	 *
	 * @param array $targets Target language codes.
	 * @return void
	 */
	public function queue_existing_content_for_targets( $targets ) {
		if ( empty( $targets ) ) {
			return;
		}

		global $wpdb;
		$post_types = array( 'post', 'page', 'product' );
		foreach ( $targets as $lang ) {
			foreach ( $post_types as $type ) {
				$post_ids = $wpdb->get_col( $wpdb->prepare(
					"SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND post_status = 'publish'",
					$type
				) );
				if ( ! empty( $post_ids ) ) {
					foreach ( $post_ids as $post_id ) {
						\TeknoTok\AiTranslator\Database\JobRepository::add_job( 'post', $post_id, $lang );
					}
					\TeknoTok\AiTranslator\Utils\Logger::log( sprintf( 'Queued %d %s posts for target language %s to warm up cache.', count( $post_ids ), $type, $lang ), 'info' );
				}
			}
		}

		$this->queue_frontend_warmup_jobs_for_targets( $targets );
	}

	/**
	 * Queue translated frontend URL warmups so theme, menu, header, and footer strings are discovered.
	 *
	 * @param array $targets Target language codes.
	 * @return void
	 */
	private function queue_frontend_warmup_jobs_for_targets( $targets ) {
		$urls = $this->get_frontend_warmup_urls();
		$shared_strings = $this->get_frontend_shared_strings();

		foreach ( $targets as $lang ) {
			$lang = sanitize_key( $lang );
			if ( empty( $lang ) ) {
				continue;
			}

			foreach ( $shared_strings as $string ) {
				\TeknoTok\AiTranslator\Database\JobRepository::add_string_job( $string, $lang );
			}
		}

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

		foreach ( $targets as $lang ) {
			$lang = sanitize_key( $lang );
			if ( empty( $lang ) ) {
				continue;
			}

			foreach ( $urls as $url ) {
				\TeknoTok\AiTranslator\Database\JobRepository::add_frontend_warmup_job( $url, $lang );
			}

			\TeknoTok\AiTranslator\Utils\Logger::log( sprintf( 'Queued %d frontend warmup URLs for target language %s.', count( $urls ), $lang ), 'info' );
		}
	}

	/**
	 * Collect representative shared frontend URLs to render after setup or target-language changes.
	 *
	 * @return array Local source-language URLs.
	 */
	private function get_frontend_warmup_urls() {
		$urls = array( home_url( '/' ) );

		if ( 'page' === get_option( 'show_on_front' ) && get_option( 'page_on_front' ) ) {
			$front_url = get_permalink( (int) get_option( 'page_on_front' ) );
			if ( $front_url ) {
				$urls[] = $front_url;
			}
		}

		$urls = array_filter( array_unique( $urls ), array( $this, 'is_local_frontend_warmup_url' ) );

		return array_values( $urls );
	}

	/**
	 * Collect known shared frontend strings without rendering every content page.
	 *
	 * @return array Shared source-language strings.
	 */
	private function get_frontend_shared_strings() {
		$strings = array(
			get_bloginfo( 'name' ),
			get_bloginfo( 'description' ),
		);

		$locations = get_nav_menu_locations();
		if ( ! empty( $locations ) ) {
			foreach ( $locations as $menu_id ) {
				$items = wp_get_nav_menu_items( $menu_id );
				if ( empty( $items ) || is_wp_error( $items ) ) {
					continue;
				}

				foreach ( $items as $item ) {
					if ( ! empty( $item->title ) ) {
						$strings[] = $item->title;
					}
				}
			}
		}

		$strings = array_filter( array_unique( array_map( 'trim', $strings ) ) );

		return array_values( $strings );
	}

	/**
	 * Check whether a warmup URL belongs to this WordPress site.
	 *
	 * @param string $url URL to inspect.
	 * @return bool True for local site URLs.
	 */
	private function is_local_frontend_warmup_url( $url ) {
		$home_host = wp_parse_url( home_url( '/' ), PHP_URL_HOST );
		$url_host  = wp_parse_url( $url, PHP_URL_HOST );

		return empty( $url_host ) || strtolower( (string) $url_host ) === strtolower( (string) $home_host );
	}

	/**
	 * Build the translated URL for a source-language URL using current URL-mode settings.
	 *
	 * @param string $source_url  Source-language URL.
	 * @param string $target_lang Target language code.
	 * @return string Translated frontend URL.
	 */
	public static function get_translated_url_for_source( $source_url, $target_lang ) {
		$settings    = get_option( 'teknotok_ait_settings', array() );
		$source      = $settings['source_language'] ?? 'en';
		$targets     = $settings['target_languages'] ?? array();
		$url_mode    = isset( $settings['url_mode'] ) ? sanitize_key( $settings['url_mode'] ) : 'subfolder';
		$target_lang = sanitize_key( $target_lang );

		if ( empty( $source_url ) || empty( $target_lang ) || $target_lang === $source ) {
			return $source_url;
		}

		if ( 'query' === $url_mode ) {
			return add_query_arg( 'lang', $target_lang, $source_url );
		}

		$home = rtrim( get_option( 'home' ), '/' );
		if ( 0 !== strpos( $source_url, $home ) ) {
			return $source_url;
		}

		$path = substr( $source_url, strlen( $home ) );
		$path = \TeknoTok\AiTranslator\Frontend\UrlManager::clean_path_from_language_prefix( $path, $targets );

		return $home . '/' . $target_lang . '/' . ltrim( $path, '/' );
	}

	/**
	 * Handle Setup wizard request.
	 *
	 * @return void
	 */
	public function handle_setup_action() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( empty( $_POST['teknotok_ait_setup_action'] ) || 'save_setup' !== $_POST['teknotok_ait_setup_action'] ) {
			return;
		}

		check_admin_referer( 'teknotok_ait_setup_wizard' );

		$target = sanitize_key( $_POST['target_language'] ?? '' );
		if ( ! empty( $target ) ) {
			// Save default settings
			$settings = get_option( 'teknotok_ait_settings', array() );
			$settings['api_provider']     = 'teknotok';
			$settings['source_language']  = substr( get_locale(), 0, 2 );
			$settings['target_languages'] = array( $target );
			$settings['switcher_position']= 'floating-bottom-right';
			$settings['detect_browser']   = '1';
			$settings['auto_translate']   = '1';
			$settings['url_mode']         = 'subfolder';
			$settings['gateway_base_url'] = 'https://soft.teknotok.com';
			$settings['translation_tone'] = 'standard';
			$settings['queue_batch_size'] = 10;
			$settings['delete_data_on_uninstall'] = '0';

			update_option( 'teknotok_ait_settings', $settings, false );

			$this->queue_existing_content_for_targets( array( $target ) );

			// Trigger language pack download and warming up the queue for this target language
			if ( function_exists( 'as_enqueue_async_action' ) && ! \TeknoTok\AiTranslator\Queue\QueueManager::is_sqlite_active() ) {
				as_enqueue_async_action( 'teknotok_ait_download_translations', array( array( $target ) ), 'teknotok-ait' );
			} else {
				wp_schedule_single_event( time(), 'teknotok_ait_download_translations', array( array( $target ) ) );
				spawn_cron();
			}
		}

		// Mark setup as complete
		update_option( 'teknotok_ait_setup_complete', '1', false );

		// Redirect to diagnostics screen with setup parameters
		wp_safe_redirect( admin_url( 'admin.php?page=teknotok-ait-diagnostics&setup=start' ) );
		exit;
	}

	/**
	 * Check if the plugin has an active premium license and is fully configured.
	 *
	 * @return bool True if licensed and configured, false otherwise.
	 */
	public static function is_ready_for_translations() {
		static $is_ready = null;
		if ( null !== $is_ready ) {
			return $is_ready;
		}

		try {
			$provider = Providers\ProviderFactory::get_provider();
			$is_ready = $provider->is_configured();
		} catch ( \Exception $e ) {
			$is_ready = false;
		}

		return $is_ready;
	}
}
