<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\Admin;

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

use Signocore\Multilanguage\Application\Constants;
use Signocore\Multilanguage\Application\Entitlements;
use Signocore\Multilanguage\Application\LicenseManager;
use Signocore\Multilanguage\Features\LanguageManager;
use Signocore\Multilanguage\Infrastructure\Traits\Singleton;
use Signocore\Multilanguage\Support\FlagHelper;
use Signocore\Multilanguage\Support\LanguageHelper;

final class SetupWizard
{
	use Singleton;

	private const PAGE_SLUG = 'sml-setup-wizard';

	private const OPTION_COMPLETED = Constants::OPTION_PREFIX . 'wizard_completed';

	protected function init(): void
	{
		add_action('admin_init', [$this, 'maybeRedirect'], 1);
		add_action('admin_init', [$this, 'maybeRenderWizard'], 2);
		add_action('admin_menu', [$this, 'registerPage']);
		add_action('wp_ajax_sml_wizard_save', [$this, 'handleSave']);
		add_action('wp_ajax_sml_wizard_skip', [$this, 'handleSkip']);
	}

	/**
	 * Redirect to the wizard if it hasn't been completed yet.
	 */
	public function maybeRedirect(): void
	{
		if (!current_user_can('manage_options')) {
			return;
		}

		if (get_option(self::OPTION_COMPLETED)) {
			return;
		}

		if (wp_doing_ajax()) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page = $_GET['page'] ?? '';
		if ($page === self::PAGE_SLUG) {
			return;
		}

		// Redirect on first activation via transient
		$redirect = get_transient(Constants::OPTION_PREFIX . 'activation_redirect');
		if ($redirect) {
			delete_transient(Constants::OPTION_PREFIX . 'activation_redirect');
			wp_safe_redirect(admin_url('admin.php?page=' . self::PAGE_SLUG));
			exit;
		}

		// Redirect when navigating to our own plugin pages
		if (is_string($page) && str_starts_with($page, 'signocore-ml')) {
			wp_safe_redirect(admin_url('admin.php?page=' . self::PAGE_SLUG));
			exit;
		}
	}

	/**
	 * Render the wizard page early to bypass admin-header.php.
	 */
	public function maybeRenderWizard(): void
	{
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page = $_GET['page'] ?? '';
		if ($page !== self::PAGE_SLUG) {
			return;
		}

		if (!current_user_can('manage_options')) {
			wp_die(__('You do not have sufficient permissions.', 'signocore-multilanguage'));
		}

		$this->renderPage();
		exit;
	}

	/**
	 * Register the hidden wizard admin page.
	 */
	public function registerPage(): void
	{
		add_submenu_page(
			'', // Hidden from menu
			__('Signocore Multilanguage Setup', 'signocore-multilanguage'),
			'',
			'manage_options',
			self::PAGE_SLUG,
			[$this, 'renderPage']
		);
	}

	/**
	 * Render the wizard page.
	 */
	public function renderPage(): void
	{
		$currentStep = $this->getCurrentStep();
		$languages = LanguageHelper::getAllLanguages();
		$activeLanguages = LanguageManager::load()->getActiveLanguages();
		$defaultCode = LanguageHelper::detectDefaultLanguageCode();
		$isPro = LicenseManager::load()->isPro();
		$siteUrl = home_url();
		$currentStrategy = get_option(Constants::OPTION_PREFIX . 'url_strategy', Constants::URL_STRATEGY_DIRECTORY);
		$defaultLanguage = LanguageManager::load()->getDefaultLanguage();
		$urlStrategy = $currentStrategy;
		$nonce = wp_create_nonce(Constants::AJAX_NONCE);

		?>
		<!DOCTYPE html>
		<html <?php language_attributes(); ?>>
		<head>
			<meta charset="<?php bloginfo('charset'); ?>">
			<meta name="viewport" content="width=device-width, initial-scale=1.0">
			<title><?php esc_html_e('Signocore Multilanguage Setup', 'signocore-multilanguage'); ?></title>
			<?php wp_print_styles('dashicons'); ?>
			<style>
				<?php $this->renderStyles(); ?>
			</style>
		</head>
		<body class="sml-wizard-body">
			<div class="sml-wizard-wrapper">
				<div class="sml-wizard-header">
					<div class="sml-wizard-logo">
						<span class="dashicons dashicons-translation" style="font-size: 28px; width: 28px; height: 28px; color: #b8642a;"></span>
						<span class="sml-wizard-logo-text"><?php esc_html_e('Signocore Multilanguage', 'signocore-multilanguage'); ?></span>
					</div>
					<div class="sml-wizard-steps-indicator">
						<?php for ($i = 1; $i <= 3; $i++): ?>
							<div class="sml-step-dot <?php echo $i === $currentStep ? 'active' : ''; ?> <?php echo $i < $currentStep ? 'completed' : ''; ?>">
								<span class="sml-step-number"><?php echo $i < $currentStep ? '<span class="dashicons dashicons-yes"></span>' : (string) $i; ?></span>
								<span class="sml-step-label">
									<?php
									switch ($i) {
										case 1:
											esc_html_e('Languages', 'signocore-multilanguage');
											break;
										case 2:
											esc_html_e('URLs', 'signocore-multilanguage');
											break;
										case 3:
											esc_html_e('Done', 'signocore-multilanguage');
											break;
									}
									?>
								</span>
							</div>
							<?php if ($i < 3): ?>
								<div class="sml-step-line <?php echo $i < $currentStep ? 'completed' : ''; ?>"></div>
							<?php endif; ?>
						<?php endfor; ?>
					</div>
				</div>

				<div class="sml-wizard-content">
					<input type="hidden" id="sml-wizard-nonce" value="<?php echo esc_attr($nonce); ?>">
					<input type="hidden" id="sml-wizard-step" value="<?php echo esc_attr((string) $currentStep); ?>">

					<?php
					switch ($currentStep) {
						case 1:
							$this->renderView('wizard-step-languages', [
								'languages' => $languages,
								'activeLanguages' => $activeLanguages,
								'defaultCode' => $defaultCode,
							]);
							break;
						case 2:
							$this->renderView('wizard-step-urls', [
								'currentStrategy' => $currentStrategy,
								'isPro' => $isPro,
								'siteUrl' => $siteUrl,
							]);
							break;
						case 3:
							$this->renderView('wizard-step-done', [
								'activeLanguages' => LanguageManager::load()->getActiveLanguages(),
								'defaultLanguage' => LanguageManager::load()->getDefaultLanguage(),
								'urlStrategy' => get_option(Constants::OPTION_PREFIX . 'url_strategy', Constants::URL_STRATEGY_DIRECTORY),
							]);
							break;
					}
					?>
				</div>
			</div>

			<script>
				<?php $this->renderScript(); ?>
			</script>
		</body>
		</html>
		<?php
	}

	/**
	 * Handle AJAX save for each wizard step.
	 */
	public function handleSave(): void
	{
		check_ajax_referer(Constants::AJAX_NONCE, 'nonce');

		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => __('Insufficient permissions.', 'signocore-multilanguage')], 403);
		}

		$step = (int) ($_POST['step'] ?? 0);

		switch ($step) {
			case 1:
				$this->saveStepLanguages();
				break;
			case 2:
				$this->saveStepUrls();
				break;
			case 3:
				$this->saveStepDone();
				break;
			default:
				wp_send_json_error(['message' => __('Invalid step.', 'signocore-multilanguage')], 400);
		}
	}

	/**
	 * Handle AJAX skip wizard.
	 */
	public function handleSkip(): void
	{
		check_ajax_referer(Constants::AJAX_NONCE, 'nonce');

		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => __('Insufficient permissions.', 'signocore-multilanguage')], 403);
		}

		// Ensure at least the default language is configured before marking complete
		LanguageManager::load()->ensureDefaultLanguage();

		update_option(self::OPTION_COMPLETED, 1);

		wp_send_json_success(['redirect' => admin_url('admin.php?page=signocore-ml-dashboard')]);
	}

	/**
	 * Save step 1: Languages.
	 */
	private function saveStepLanguages(): void
	{
		$languageCodes = $_POST['languages'] ?? [];
		$defaultCode = sanitize_text_field($_POST['default_language'] ?? '');

		if (!is_array($languageCodes) || count($languageCodes) < 2) {
			wp_send_json_error(['message' => __('Please select at least 2 languages.', 'signocore-multilanguage')], 400);
		}

		if (!LicenseManager::load()->isPro() && count($languageCodes) > Entitlements::FREE_LANGUAGE_LIMIT) {
			wp_send_json_error(['message' => sprintf(
				/* translators: %d: maximum number of languages on the free plan */
				__('The free plan supports up to %d languages. Upgrade to Pro for unlimited languages.', 'signocore-multilanguage'),
				Entitlements::FREE_LANGUAGE_LIMIT
			)], 403);
		}

		$languageCodes = array_map('sanitize_text_field', $languageCodes);

		if (empty($defaultCode) || !in_array($defaultCode, $languageCodes, true)) {
			wp_send_json_error(['message' => __('Please select a default language.', 'signocore-multilanguage')], 400);
		}

		$allLanguages = LanguageHelper::getAllLanguages();
		$languageManager = LanguageManager::load();

		// Remove all existing languages first
		$existing = $languageManager->getAllLanguages();
		foreach ($existing as $lang) {
			LanguageManager::load()->removeLanguage($lang->code);
		}

		// Clear default so we can delete the default language too
		\Signocore\Multilanguage\Infrastructure\Database\LanguageRepository::clearDefault();

		// Delete remaining (including the old default)
		foreach ($existing as $lang) {
			\Signocore\Multilanguage\Infrastructure\Database\LanguageRepository::delete($lang->code);
		}

		// Add selected languages
		$sortOrder = 0;
		foreach ($languageCodes as $code) {
			$langData = $allLanguages[$code] ?? null;
			if ($langData === null) {
				continue;
			}

			$languageManager->addLanguage([
				'code' => $langData['code'],
				'locale' => $langData['locale'],
				'name' => $langData['name'],
				'native_name' => $langData['native_name'],
				'is_default' => $code === $defaultCode ? 1 : 0,
				'is_active' => 1,
				'is_rtl' => (int) $langData['rtl'],
				'flag' => $langData['code'] . '.svg',
				'sort_order' => $sortOrder++,
			]);
		}

		wp_send_json_success([
			'redirect' => admin_url('admin.php?page=' . self::PAGE_SLUG . '&step=2'),
		]);
	}

	/**
	 * Save step 2: URL strategy.
	 */
	private function saveStepUrls(): void
	{
		$strategy = sanitize_text_field($_POST['url_strategy'] ?? Constants::URL_STRATEGY_DIRECTORY);
		$hideDefault = (int) ($_POST['hide_default_prefix'] ?? 1);

		$validStrategies = [
			Constants::URL_STRATEGY_DIRECTORY,
			Constants::URL_STRATEGY_SUBDOMAIN,
			Constants::URL_STRATEGY_DOMAIN,
		];

		if (!in_array($strategy, $validStrategies, true)) {
			$strategy = Constants::URL_STRATEGY_DIRECTORY;
		}

		// Check Pro features
		$isPro = LicenseManager::load()->isPro();
		if (!$isPro && in_array($strategy, [Constants::URL_STRATEGY_SUBDOMAIN, Constants::URL_STRATEGY_DOMAIN], true)) {
			wp_send_json_error(['message' => __('This URL strategy requires a Pro license.', 'signocore-multilanguage')], 403);
		}

		update_option(Constants::OPTION_PREFIX . 'url_strategy', $strategy);
		update_option(Constants::OPTION_PREFIX . 'hide_default_language_prefix', $hideDefault);

		wp_send_json_success([
			'redirect' => admin_url('admin.php?page=' . self::PAGE_SLUG . '&step=3'),
		]);
	}

	/**
	 * Save step 3: Mark wizard as completed.
	 */
	private function saveStepDone(): void
	{
		update_option(self::OPTION_COMPLETED, 1);

		wp_send_json_success([
			'redirect' => admin_url('admin.php?page=signocore-ml-settings'),
		]);
	}

	/**
	 * Get the current wizard step from the query string.
	 */
	private function getCurrentStep(): int
	{
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$step = (int) ($_GET['step'] ?? 1);
		return max(1, min(3, $step));
	}

	/**
	 * Render a view template with variables.
	 *
	 * @param string $view
	 * @param array<string, mixed> $data
	 */
	private function renderView(string $view, array $data = []): void
	{
		extract($data, EXTR_SKIP);
		include __DIR__ . '/Views/' . $view . '.php';
	}

	/**
	 * Render the wizard CSS styles.
	 */
	private function renderStyles(): void
	{
		?>
		* {
			margin: 0;
			padding: 0;
			box-sizing: border-box;
		}

		body.sml-wizard-body {
			background: #f0f0f1;
			font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
			color: #1d2327;
			line-height: 1.5;
			min-height: 100vh;
			display: flex;
			align-items: flex-start;
			justify-content: center;
			padding: 40px 20px;
		}

		.sml-wizard-wrapper {
			width: 100%;
			max-width: 700px;
			background: #fff;
			border-radius: 8px;
			box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08), 0 4px 12px rgba(0, 0, 0, 0.04);
			overflow: hidden;
		}

		/* Header */
		.sml-wizard-header {
			padding: 28px 32px 24px;
			border-bottom: 1px solid #e0e0e0;
		}

		.sml-wizard-logo {
			display: flex;
			align-items: center;
			gap: 10px;
			margin-bottom: 24px;
		}

		.sml-wizard-logo-text {
			font-size: 18px;
			font-weight: 600;
			color: #1d2327;
		}

		/* Step indicator */
		.sml-wizard-steps-indicator {
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 0;
		}

		.sml-step-dot {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 6px;
			position: relative;
		}

		.sml-step-number {
			width: 32px;
			height: 32px;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 14px;
			font-weight: 600;
			background: #e0e0e0;
			color: #787c82;
			transition: all 0.2s ease;
		}

		.sml-step-dot.active .sml-step-number {
			background: #b8642a;
			color: #fff;
		}

		.sml-step-dot.completed .sml-step-number {
			background: #b8642a;
			color: #fff;
		}

		.sml-step-dot.completed .sml-step-number .dashicons {
			font-size: 18px;
			width: 18px;
			height: 18px;
			line-height: 1;
		}

		.sml-step-label {
			font-size: 12px;
			color: #787c82;
			font-weight: 500;
		}

		.sml-step-dot.active .sml-step-label {
			color: #b8642a;
			font-weight: 600;
		}

		.sml-step-dot.completed .sml-step-label {
			color: #b8642a;
		}

		.sml-step-line {
			width: 60px;
			height: 2px;
			background: #e0e0e0;
			margin: 0 8px;
			margin-bottom: 22px;
			transition: background 0.2s ease;
		}

		.sml-step-line.completed {
			background: #b8642a;
		}

		/* Content */
		.sml-wizard-content {
			padding: 32px;
		}

		.sml-wizard-title {
			font-size: 22px;
			font-weight: 600;
			margin-bottom: 6px;
			color: #1d2327;
		}

		.sml-wizard-subtitle {
			font-size: 14px;
			color: #787c82;
			margin-bottom: 24px;
		}

		/* Search input */
		.sml-search-wrap {
			position: relative;
			margin-bottom: 20px;
		}

		.sml-search-wrap .dashicons {
			position: absolute;
			left: 12px;
			top: 50%;
			transform: translateY(-50%);
			color: #a0a5aa;
			font-size: 18px;
			width: 18px;
			height: 18px;
		}

		.sml-search-input {
			width: 100%;
			padding: 10px 12px 10px 38px;
			border: 1px solid #c3c4c7;
			border-radius: 4px;
			font-size: 14px;
			outline: none;
			transition: border-color 0.15s ease;
		}

		.sml-search-input:focus {
			border-color: #b8642a;
			box-shadow: 0 0 0 1px #b8642a;
		}

		/* Language grid */
		.sml-language-grid {
			display: grid;
			grid-template-columns: 1fr 1fr;
			gap: 8px;
			max-height: 380px;
			overflow-y: auto;
			padding-right: 4px;
			margin-bottom: 24px;
		}

		.sml-language-grid::-webkit-scrollbar {
			width: 6px;
		}

		.sml-language-grid::-webkit-scrollbar-track {
			background: #f0f0f1;
			border-radius: 3px;
		}

		.sml-language-grid::-webkit-scrollbar-thumb {
			background: #c3c4c7;
			border-radius: 3px;
		}

		.sml-language-item {
			display: flex;
			align-items: center;
			gap: 10px;
			padding: 10px 12px;
			border: 1px solid #e0e0e0;
			border-radius: 6px;
			cursor: pointer;
			transition: all 0.15s ease;
			user-select: none;
		}

		.sml-language-item:hover {
			border-color: #b8642a;
			background: #fdf8f4;
		}

		.sml-language-item.selected {
			border-color: #b8642a;
			background: #fdf8f4;
		}

		.sml-language-item.hidden {
			display: none;
		}

		.sml-language-checkbox {
			flex-shrink: 0;
		}

		.sml-language-checkbox input[type="checkbox"] {
			margin: 0;
			accent-color: #b8642a;
		}

		.sml-language-flag {
			flex-shrink: 0;
			width: 24px;
			height: 18px;
			border-radius: 2px;
			object-fit: cover;
		}

		.sml-language-info {
			flex: 1;
			min-width: 0;
			display: flex;
			flex-direction: column;
			gap: 1px;
		}

		.sml-language-name {
			font-size: 13px;
			font-weight: 500;
			color: #1d2327;
			line-height: 1.3;
		}

		.sml-language-native {
			font-size: 11px;
			color: #787c82;
			line-height: 1.3;
		}

		.sml-language-default {
			flex-shrink: 0;
		}

		.sml-language-default input[type="radio"] {
			margin: 0;
			accent-color: #b8642a;
		}

		.sml-language-default label {
			font-size: 11px;
			color: #787c82;
			cursor: pointer;
			display: flex;
			align-items: center;
			gap: 4px;
		}

		.sml-selected-count {
			font-size: 13px;
			color: #787c82;
			margin-bottom: 16px;
		}

		.sml-selected-count strong {
			color: #b8642a;
		}

		.sml-min-warning {
			color: #d63638;
			font-size: 13px;
			margin-bottom: 16px;
			display: none;
		}

		.sml-min-warning.visible {
			display: block;
		}

		.sml-limit-warning {
			color: #b8642a;
			font-size: 13px;
			margin-bottom: 16px;
			display: none;
		}

		.sml-limit-warning.visible {
			display: block;
		}

		.sml-language-item.disabled {
			opacity: 0.4;
			pointer-events: none;
		}

		/* URL strategy cards */
		.sml-strategy-cards {
			display: flex;
			flex-direction: column;
			gap: 12px;
			margin-bottom: 24px;
		}

		.sml-strategy-card {
			display: flex;
			align-items: flex-start;
			gap: 14px;
			padding: 16px;
			border: 2px solid #e0e0e0;
			border-radius: 8px;
			cursor: pointer;
			transition: all 0.15s ease;
			position: relative;
		}

		.sml-strategy-card:hover {
			border-color: #b8642a;
			background: #fdf8f4;
		}

		.sml-strategy-card.selected {
			border-color: #b8642a;
			background: #fdf8f4;
		}

		.sml-strategy-card.locked {
			opacity: 0.7;
			cursor: default;
		}

		.sml-strategy-card.locked:hover {
			border-color: #e0e0e0;
			background: transparent;
		}

		.sml-strategy-radio {
			flex-shrink: 0;
			margin-top: 2px;
		}

		.sml-strategy-radio input[type="radio"] {
			margin: 0;
			accent-color: #b8642a;
		}

		.sml-strategy-content {
			flex: 1;
		}

		.sml-strategy-title {
			font-size: 15px;
			font-weight: 600;
			color: #1d2327;
			display: flex;
			align-items: center;
			gap: 8px;
			margin-bottom: 4px;
		}

		.sml-strategy-badge {
			font-size: 11px;
			font-weight: 600;
			padding: 1px 8px;
			border-radius: 10px;
			text-transform: uppercase;
			letter-spacing: 0.3px;
		}

		.sml-strategy-badge.free {
			background: #e7f5e7;
			color: #00a32a;
		}

		.sml-strategy-badge.pro {
			background: #fdf1e6;
			color: #b8642a;
		}

		.sml-strategy-lock {
			color: #787c82;
			font-size: 14px;
		}

		.sml-strategy-lock .dashicons {
			font-size: 16px;
			width: 16px;
			height: 16px;
		}

		.sml-strategy-description {
			font-size: 13px;
			color: #787c82;
			margin-bottom: 8px;
		}

		.sml-strategy-example {
			font-size: 13px;
			font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
			background: #f6f7f7;
			padding: 6px 10px;
			border-radius: 4px;
			color: #50575e;
			border: 1px solid #e0e0e0;
		}

		.sml-strategy-example strong {
			color: #b8642a;
		}

		/* Hide default checkbox */
		.sml-hide-default-wrap {
			margin-bottom: 24px;
			display: flex;
			align-items: flex-start;
			gap: 8px;
			padding: 14px 16px;
			background: #f6f7f7;
			border-radius: 6px;
			border: 1px solid #e0e0e0;
		}

		.sml-hide-default-wrap input[type="checkbox"] {
			margin-top: 2px;
			accent-color: #b8642a;
		}

		.sml-hide-default-wrap label {
			font-size: 14px;
			color: #1d2327;
			cursor: pointer;
		}

		.sml-hide-default-wrap .sml-hide-default-desc {
			font-size: 12px;
			color: #787c82;
			margin-top: 2px;
		}

		/* Done step */
		.sml-done-icon {
			text-align: center;
			margin-bottom: 20px;
		}

		.sml-done-icon .dashicons {
			font-size: 48px;
			width: 48px;
			height: 48px;
			color: #00a32a;
			background: #e7f5e7;
			border-radius: 50%;
			padding: 12px;
			box-sizing: content-box;
		}

		.sml-done-summary {
			margin-bottom: 28px;
		}

		.sml-done-section {
			margin-bottom: 20px;
		}

		.sml-done-section-title {
			font-size: 13px;
			font-weight: 600;
			color: #787c82;
			text-transform: uppercase;
			letter-spacing: 0.5px;
			margin-bottom: 10px;
		}

		.sml-done-languages {
			display: flex;
			flex-wrap: wrap;
			gap: 8px;
		}

		.sml-done-language-tag {
			display: inline-flex;
			align-items: center;
			gap: 6px;
			padding: 6px 12px;
			background: #f6f7f7;
			border: 1px solid #e0e0e0;
			border-radius: 20px;
			font-size: 13px;
		}

		.sml-done-language-tag.is-default {
			border-color: #b8642a;
			background: #fdf8f4;
		}

		.sml-done-language-tag .sml-default-badge {
			font-size: 10px;
			font-weight: 600;
			color: #b8642a;
			text-transform: uppercase;
		}

		.sml-done-strategy {
			padding: 12px 16px;
			background: #f6f7f7;
			border: 1px solid #e0e0e0;
			border-radius: 6px;
			font-size: 14px;
		}

		/* Buttons */
		.sml-wizard-actions {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-top: 20px;
			border-top: 1px solid #e0e0e0;
			gap: 12px;
		}

		.sml-wizard-actions-right {
			display: flex;
			align-items: center;
			gap: 12px;
		}

		.sml-btn {
			display: inline-flex;
			align-items: center;
			gap: 6px;
			padding: 10px 24px;
			border-radius: 4px;
			font-size: 14px;
			font-weight: 500;
			border: none;
			cursor: pointer;
			text-decoration: none;
			transition: all 0.15s ease;
			line-height: 1.4;
		}

		.sml-btn-primary {
			background: #b8642a;
			color: #fff;
		}

		.sml-btn-primary:hover {
			background: #a0562a;
		}

		.sml-btn-primary:disabled {
			background: #c3c4c7;
			cursor: not-allowed;
		}

		.sml-btn-secondary {
			background: #f6f7f7;
			color: #50575e;
			border: 1px solid #c3c4c7;
		}

		.sml-btn-secondary:hover {
			background: #e9e9e9;
		}

		.sml-btn-outline {
			background: transparent;
			color: #b8642a;
			border: 1px solid #b8642a;
		}

		.sml-btn-outline:hover {
			background: #fdf8f4;
		}

		.sml-skip-link {
			color: #787c82;
			text-decoration: none;
			font-size: 13px;
			cursor: pointer;
			border: none;
			background: none;
			padding: 0;
		}

		.sml-skip-link:hover {
			color: #50575e;
			text-decoration: underline;
		}

		/* Done action buttons */
		.sml-done-actions {
			display: flex;
			gap: 12px;
			justify-content: center;
		}

		/* Spinner */
		.sml-spinner {
			display: none;
			width: 16px;
			height: 16px;
			border: 2px solid rgba(255, 255, 255, 0.3);
			border-top-color: #fff;
			border-radius: 50%;
			animation: sml-spin 0.6s linear infinite;
		}

		.sml-btn-primary .sml-spinner {
			border-color: rgba(255, 255, 255, 0.3);
			border-top-color: #fff;
		}

		.sml-btn.loading .sml-spinner {
			display: inline-block;
		}

		@keyframes sml-spin {
			to { transform: rotate(360deg); }
		}

		/* No results */
		.sml-no-results {
			grid-column: 1 / -1;
			text-align: center;
			padding: 32px;
			color: #787c82;
			font-size: 14px;
			display: none;
		}

		/* Responsive */
		@media (max-width: 600px) {
			body.sml-wizard-body {
				padding: 16px 12px;
			}

			.sml-wizard-header {
				padding: 20px 20px 18px;
			}

			.sml-wizard-content {
				padding: 24px 20px;
			}

			.sml-language-grid {
				grid-template-columns: 1fr;
			}

			.sml-step-line {
				width: 30px;
			}

			.sml-done-actions {
				flex-direction: column;
			}

			.sml-wizard-actions {
				flex-direction: column-reverse;
				align-items: stretch;
			}

			.sml-wizard-actions-right {
				justify-content: center;
			}

			.sml-btn {
				justify-content: center;
			}
		}
		<?php
	}

	/**
	 * Render the wizard JavaScript.
	 */
	private function renderScript(): void
	{
		?>
		(function() {
			'use strict';

			const ajaxUrl = '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';
			const nonce = document.getElementById('sml-wizard-nonce').value;
			const step = parseInt(document.getElementById('sml-wizard-step').value, 10);
			const isPro = <?php echo LicenseManager::load()->isPro() ? 'true' : 'false'; ?>;
			const languageLimit = <?php echo (int) Entitlements::FREE_LANGUAGE_LIMIT; ?>;

			// Language search filter
			const searchInput = document.getElementById('sml-language-search');
			if (searchInput) {
				searchInput.addEventListener('input', function() {
					const query = this.value.toLowerCase().trim();
					const items = document.querySelectorAll('.sml-language-item');
					let visibleCount = 0;

					items.forEach(function(item) {
						const name = (item.dataset.name || '').toLowerCase();
						const native = (item.dataset.native || '').toLowerCase();
						const code = (item.dataset.code || '').toLowerCase();
						const matches = !query || name.includes(query) || native.includes(query) || code.includes(query);

						item.classList.toggle('hidden', !matches);
						if (matches) visibleCount++;
					});

					const noResults = document.getElementById('sml-no-results');
					if (noResults) {
						noResults.style.display = visibleCount === 0 ? 'block' : 'none';
					}
				});
			}

			// Language item click handler
			document.querySelectorAll('.sml-language-item').forEach(function(item) {
				item.addEventListener('click', function(e) {
					if (e.target.type === 'radio' || e.target.tagName === 'LABEL') return;

					const checkbox = item.querySelector('input[type="checkbox"]');
					if (checkbox) {
						checkbox.checked = !checkbox.checked;
						checkbox.dispatchEvent(new Event('change'));
					}
				});
			});

			// Checkbox change handler - update selected state and count
			document.querySelectorAll('.sml-language-item input[type="checkbox"]').forEach(function(cb) {
				cb.addEventListener('change', function() {
					const item = cb.closest('.sml-language-item');
					item.classList.toggle('selected', cb.checked);

					// Show/hide default radio
					const radio = item.querySelector('.sml-language-default');
					if (radio) {
						radio.style.display = cb.checked ? 'block' : 'none';
						if (!cb.checked) {
							const radioInput = radio.querySelector('input[type="radio"]');
							if (radioInput) radioInput.checked = false;
						}
					}

					updateSelectedCount();
				});
			});

			function updateSelectedCount() {
				const checked = document.querySelectorAll('.sml-language-item input[type="checkbox"]:checked');
				const countEl = document.getElementById('sml-selected-count');
				const warningEl = document.getElementById('sml-min-warning');
				const limitEl = document.getElementById('sml-limit-warning');
				const nextBtn = document.getElementById('sml-next-btn');
				const atLimit = !isPro && checked.length >= languageLimit;

				if (countEl) {
					countEl.innerHTML = '<strong>' + checked.length + '</strong> language' + (checked.length !== 1 ? 's' : '') + ' selected';
				}

				if (warningEl) {
					warningEl.classList.toggle('visible', checked.length > 0 && checked.length < 2);
				}

				if (limitEl) {
					limitEl.classList.toggle('visible', atLimit);
				}

				// Disable unchecked checkboxes when free limit reached
				if (!isPro) {
					document.querySelectorAll('.sml-language-item input[type="checkbox"]').forEach(function(cb) {
						if (!cb.checked) {
							cb.disabled = atLimit;
							cb.closest('.sml-language-item').classList.toggle('disabled', atLimit);
						}
					});
				}

				if (nextBtn) {
					nextBtn.disabled = checked.length < 2;
				}
			}

			// Strategy card click
			document.querySelectorAll('.sml-strategy-card:not(.locked)').forEach(function(card) {
				card.addEventListener('click', function() {
					document.querySelectorAll('.sml-strategy-card').forEach(function(c) {
						c.classList.remove('selected');
					});
					card.classList.add('selected');

					const radio = card.querySelector('input[type="radio"]');
					if (radio) radio.checked = true;
				});
			});

			// Next button handlers
			const nextBtn = document.getElementById('sml-next-btn');
			if (nextBtn) {
				nextBtn.addEventListener('click', function() {
					if (nextBtn.disabled) return;
					saveStep();
				});
			}

			// Back button
			const backBtn = document.getElementById('sml-back-btn');
			if (backBtn) {
				backBtn.addEventListener('click', function() {
					const prevStep = step - 1;
					window.location.href = ajaxUrl.replace('admin-ajax.php', 'admin.php?page=sml-setup-wizard&step=' + prevStep);
				});
			}

			// Skip link
			document.querySelectorAll('.sml-skip-link').forEach(function(link) {
				link.addEventListener('click', function(e) {
					e.preventDefault();
					skipWizard();
				});
			});

			// Finish button
			const finishBtn = document.getElementById('sml-finish-btn');
			if (finishBtn) {
				finishBtn.addEventListener('click', function() {
					saveStep();
				});
			}

			function saveStep() {
				const btn = document.getElementById('sml-next-btn') || document.getElementById('sml-finish-btn');
				if (btn) {
					btn.classList.add('loading');
					btn.disabled = true;
				}

				const formData = new FormData();
				formData.append('action', 'sml_wizard_save');
				formData.append('nonce', nonce);
				formData.append('step', step.toString());

				if (step === 1) {
					const checked = document.querySelectorAll('.sml-language-item input[type="checkbox"]:checked');
					checked.forEach(function(cb) {
						formData.append('languages[]', cb.value);
					});

					const defaultRadio = document.querySelector('input[name="default_language"]:checked');
					if (defaultRadio) {
						formData.append('default_language', defaultRadio.value);
					}
				}

				if (step === 2) {
					const strategyRadio = document.querySelector('input[name="url_strategy"]:checked');
					if (strategyRadio) {
						formData.append('url_strategy', strategyRadio.value);
					}

					const hideDefault = document.getElementById('sml-hide-default-prefix');
					if (hideDefault) {
						formData.append('hide_default_prefix', hideDefault.checked ? '1' : '0');
					}
				}

				fetch(ajaxUrl, {
					method: 'POST',
					credentials: 'same-origin',
					body: formData
				})
				.then(function(response) { return response.json(); })
				.then(function(data) {
					if (data.success && data.data.redirect) {
						window.location.href = data.data.redirect;
					} else {
						alert(data.data?.message || 'An error occurred. Please try again.');
						if (btn) {
							btn.classList.remove('loading');
							btn.disabled = false;
						}
					}
				})
				.catch(function() {
					alert('An error occurred. Please try again.');
					if (btn) {
						btn.classList.remove('loading');
						btn.disabled = false;
					}
				});
			}

			function skipWizard() {
				const formData = new FormData();
				formData.append('action', 'sml_wizard_skip');
				formData.append('nonce', nonce);

				fetch(ajaxUrl, {
					method: 'POST',
					credentials: 'same-origin',
					body: formData
				})
				.then(function(response) { return response.json(); })
				.then(function(data) {
					if (data.success && data.data.redirect) {
						window.location.href = data.data.redirect;
					}
				});
			}

			// Initialize state on load
			if (step === 1) {
				updateSelectedCount();
			}
		})();
		<?php
	}
}
