<?php
namespace TeknoTok\AiTranslator\Admin;

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

use TeknoTok\AiTranslator\Database\JobRepository;
use TeknoTok\AiTranslator\Database\MemoryRepository;
use TeknoTok\AiTranslator\Queue\QueueManager;
use TeknoTok\AiTranslator\Utils\ErrorSanitizer;

/**
 * Controller to manage the system status, diagnostics, and queue logs UI.
 */
class DiagnosticController {
	/**
	 * Plugin coordinator.
	 *
	 * @var \TeknoTok\AiTranslator\Plugin
	 */
	private $plugin;

	/**
	 * Constructor.
	 *
	 * @param \TeknoTok\AiTranslator\Plugin $plugin Plugin instance.
	 */
	public function __construct( $plugin ) {
		$this->plugin = $plugin;

		add_action( 'admin_menu', array( $this, 'register_menu' ), 30 );
		add_action( 'admin_init', array( $this, 'handle_actions' ) );
		add_action( 'wp_ajax_teknotok_ait_get_queue_status', array( $this, 'ajax_get_queue_status' ) );
		add_action( 'wp_ajax_teknotok_ait_run_queue_admin', array( $this, 'ajax_run_queue_admin' ) );
		add_action( 'wp_ajax_teknotok_ait_pause_queue', array( $this, 'ajax_pause_queue' ) );
		add_action( 'wp_ajax_teknotok_ait_resume_queue', array( $this, 'ajax_resume_queue' ) );
		add_action( 'wp_ajax_teknotok_ait_retry_failed_jobs', array( $this, 'ajax_retry_failed_jobs' ) );
		add_action( 'wp_ajax_teknotok_ait_cancel_stale_language_jobs', array( $this, 'ajax_cancel_stale_language_jobs' ) );
		add_action( 'wp_ajax_teknotok_ait_cancel_waiting_jobs', array( $this, 'ajax_cancel_waiting_jobs' ) );
		add_action( 'wp_ajax_teknotok_ait_copy_system_report', array( $this, 'ajax_copy_system_report' ) );
	}

	/**
	 * Register submenu.
	 *
	 * @return void
	 */
	public function register_menu() {
		add_submenu_page(
			'teknotok-ait',
			__( 'Translation Status', 'teknotok-ai-translator' ),
			__( 'Translation Status', 'teknotok-ai-translator' ),
			'manage_options',
			'teknotok-ait-diagnostics',
			array( $this, 'render_diagnostics' )
		);
	}

	/**
	 * Handle admin commands for queues.
	 *
	 * @return void
	 */
	public function handle_actions() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$action = sanitize_key( wp_unslash( $_POST['teknotok_ait_diag_action'] ?? '' ) );
		if ( empty( $action ) ) {
			return;
		}

		if ( 'clear_logs' === $action ) {
			check_admin_referer( 'teknotok_ait_diag_nonce' );
			\TeknoTok\AiTranslator\Utils\Logger::clear_logs();
			add_settings_error( 'teknotok_ait_diagnostics', 'logs_cleared', __( 'Debug log file cleared.', 'teknotok-ai-translator' ), 'success' );
		}
	}

	/**
	 * AJAX endpoint to retrieve queue status counts dynamically.
	 *
	 * @return void
	 */
	public function ajax_get_queue_status() {
		if ( ! isset( $_GET['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_GET['nonce'] ) ), 'teknotok_ait_ajax' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Permission denied', 403 );
		}

		$queue_counts = JobRepository::get_counts();
		$queue_counts['retryable_failed'] = JobRepository::get_retryable_failed_count();
		$settings = get_option( 'teknotok_ait_settings', array() );
		$queue_counts['stale_language_jobs'] = JobRepository::get_stale_target_job_count( $settings['target_languages'] ?? array() );
		$queue_counts['paused'] = get_option( 'teknotok_ait_queue_paused', '0' ) === '1';
		$raw_pause_reason = get_option( 'teknotok_ait_queue_pause_reason', '' );
		$queue_counts['pause_reason'] = $queue_counts['paused'] ? ErrorSanitizer::sanitize_message( $raw_pause_reason ) : '';
		$queue_counts['pause_is_limit'] = $queue_counts['paused'] && ErrorSanitizer::is_limit_message( $raw_pause_reason );
		$queue_counts['local_warmup_skipped'] = get_option( 'teknotok_ait_local_warmup_skipped_message', '' );
		$lock_expires = (int) get_option( 'teknotok_ait_queue_lock_expires', 0 );
		$queue_counts['locked'] = $lock_expires > time();
		$queue_counts['logs'] = ErrorSanitizer::sanitize_log_output( \TeknoTok\AiTranslator\Utils\Logger::read_logs( 100 ) );
		$quota_snapshot = $this->get_quota_snapshot();
		$queue_counts['quota'] = $quota_snapshot;
		$queue_counts['health'] = $this->get_health_summary_snapshot( $queue_counts, $quota_snapshot );
		wp_send_json_success( $queue_counts );
	}

	/**
	 * AJAX endpoint to run the queue worker from the admin dashboard.
	 *
	 * @return void
	 */
	public function ajax_run_queue_admin() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'teknotok_ait_ajax' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Permission denied', 403 );
		}

		if ( function_exists( 'set_time_limit' ) ) {
			@set_time_limit( 0 );
		}

		$this->plugin->queue->process_queue();

		wp_send_json_success();
	}

	/**
	 * AJAX endpoint to resume queue execution after license/quota has been fixed.
	 *
	 * @return void
	 */
	public function ajax_resume_queue() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'teknotok_ait_ajax' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Permission denied', 403 );
		}

		$reset_jobs = QueueManager::resume_after_provider_limit();

		wp_send_json_success(
			array(
				'reset_jobs' => $reset_jobs,
			)
		);
	}

	/**
	 * AJAX endpoint to pause queue execution manually.
	 *
	 * @return void
	 */
	public function ajax_pause_queue() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'teknotok_ait_ajax' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Permission denied', 403 );
		}

		update_option( 'teknotok_ait_queue_paused', '1', false );
		update_option( 'teknotok_ait_queue_pause_reason', __( 'Manually paused by administrator.', 'teknotok-ai-translator' ), false );
		update_option( 'teknotok_ait_queue_paused_at', current_time( 'mysql', true ), false );

		wp_send_json_success();
	}

	/**
	 * AJAX endpoint to retry failed jobs after timeout/server issues are fixed.
	 *
	 * @return void
	 */
	public function ajax_retry_failed_jobs() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'teknotok_ait_ajax' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Permission denied', 403 );
		}

		$reset_jobs = QueueManager::retry_failed_jobs();

		wp_send_json_success(
			array(
				'reset_jobs' => $reset_jobs,
			)
		);
	}

	/**
	 * AJAX endpoint to cancel jobs for languages no longer selected in settings.
	 *
	 * @return void
	 */
	public function ajax_cancel_stale_language_jobs() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'teknotok_ait_ajax' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Permission denied', 403 );
		}

		$cancelled_jobs = QueueManager::cancel_unconfigured_language_jobs();

		wp_send_json_success(
			array(
				'cancelled_jobs' => $cancelled_jobs,
			)
		);
	}

	/**
	 * AJAX endpoint to cancel all unfinished queue work.
	 *
	 * @return void
	 */
	public function ajax_cancel_waiting_jobs() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'teknotok_ait_ajax' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Permission denied', 403 );
		}

		$cancelled_jobs = QueueManager::cancel_waiting_jobs();

		wp_send_json_success(
			array(
				'cancelled_jobs' => $cancelled_jobs,
			)
		);
	}

	/**
	 * AJAX endpoint to compile and return a raw system diagnostics report.
	 *
	 * @return void
	 */
	public function ajax_copy_system_report() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'teknotok_ait_ajax' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Permission denied', 403 );
		}

		$report = $this->compile_system_report();
		wp_send_json_success( $report );
	}

	/**
	 * Compile markdown-formatted system report.
	 *
	 * @return string System Report.
	 */
	public function compile_system_report() {
		global $wpdb;

		$settings = get_option( 'teknotok_ait_settings', array() );
		$license = get_option( 'teknotok_ait_license_status', array() );
		$queue_counts = JobRepository::get_counts();
		$cached_count = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}teknotok_translations" );

		$filters = self::get_active_filters_status();
		$targets = $settings['target_languages'] ?? array();
		$has_targets = ! empty( $targets );

		$filters_str = '';
		foreach ( $filters as $hook => $data ) {
			$status_label = $data['active'] ? 'ACTIVE' : 'INACTIVE';
			if ( ! $data['active'] && is_admin() && $has_targets ) {
				$status_label = 'ACTIVE (FRONTEND)';
			}
			$filters_str .= sprintf( "- %s (%s): %s\n", $hook, $data['method'], $status_label );
		}

		$report = "### TEKNOTOK AI TRANSLATOR - SYSTEM REPORT\n\n";
		$report .= "#### ENVIRONMENT\n";
		$report .= "- Plugin Version: " . TEKNOTOK_AIT_VERSION . "\n";
		$report .= "- PHP Version: " . PHP_VERSION . "\n";
		$report .= "- WordPress Version: " . ( $GLOBALS['wp_version'] ?? 'Unknown' ) . "\n";
		$report .= "- WooCommerce Version: " . ( class_exists( 'WooCommerce' ) ? WC()->version : 'Not Installed' ) . "\n";
		$report .= "- Memory Limit: " . ( defined( 'WP_MEMORY_LIMIT' ) ? WP_MEMORY_LIMIT : 'Unknown' ) . "\n";
		$report .= "- SQLite Active: " . ( QueueManager::is_sqlite_active() ? 'Yes' : 'No' ) . "\n\n";

		$report .= "#### PLUGIN CONFIGURATION\n";
		$report .= "- API Provider: " . ( $settings['api_provider'] ?? 'teknotok' ) . "\n";
		$report .= "- Source Language: " . ( $settings['source_language'] ?? 'en' ) . "\n";
		$report .= "- Target Languages: " . implode( ', ', $settings['target_languages'] ?? array() ) . "\n";
		$report .= "- URL Structure Mode: " . ( $settings['url_mode'] ?? 'subfolder' ) . "\n";
		$report .= "- Detect Browser: " . ( $settings['detect_browser'] ?? '1' ) . "\n";
		$report .= "- Auto Translate: " . ( $settings['auto_translate'] ?? '1' ) . "\n\n";

		$report .= "#### LICENSE DETAILS\n";
		$report .= "- Status: " . ( $license['status'] ?? 'free' ) . "\n";
		$report .= "- Key: " . ( empty( $license['license_key'] ) ? 'None' : substr( $license['license_key'], 0, 8 ) . '...' ) . "\n";
		$report .= "- Expires At: " . ( $license['expires_at'] ?? 'Never' ) . "\n";
		$report .= "- Grace Error Count: " . ( $license['error_count'] ?? 0 ) . "\n\n";

		$report .= "#### QUEUE & METRICS\n";
		$report .= "- Total Cached Translations: " . intval( $cached_count ) . "\n";
		$report .= "- Queue Paused: " . ( get_option( 'teknotok_ait_queue_paused' ) === '1' ? 'Yes' : 'No' ) . "\n";
		$report .= "- Queue Pause Reason: " . ErrorSanitizer::sanitize_message( get_option( 'teknotok_ait_queue_pause_reason', 'None' ) ) . "\n";
		$report .= "- Pending Jobs: " . intval( $queue_counts['pending'] ) . "\n";
		$report .= "- Processing Jobs: " . intval( $queue_counts['processing'] ) . "\n";
		$report .= "- Completed Jobs: " . intval( $queue_counts['completed'] ) . "\n";
		$report .= "- Failed Jobs: " . intval( $queue_counts['failed'] ) . "\n\n";

		$report .= "#### ACTIVE TRANSLATION HOOKS\n";
		$report .= $filters_str;

		return $report;
	}

	/**
	 * Get a customer-facing quota snapshot for the diagnostics dashboard.
	 *
	 * @return array
	 */
	private function get_quota_snapshot() {
		$license = \TeknoTok\AiTranslator\Integrations\LicenseManager::get_license_data();
		$quota = $this->plugin->license->get_quota_status();

		if ( is_wp_error( $quota ) || ! is_array( $quota ) ) {
			$quota = $license;
		}

		$limit = max( 0, (int) ( $quota['words_limit'] ?? ( $quota['limit'] ?? 0 ) ) );
		$used = max( 0, (int) ( $quota['words_used'] ?? ( $quota['word_count'] ?? 0 ) ) );
		$remaining = max( 0, (int) ( $quota['words_remaining'] ?? max( 0, $limit - $used ) ) );
		$percent = $limit > 0 ? min( 100, round( ( $used / $limit ) * 100 ) ) : 0;
		$plan = sanitize_key( $quota['plan_slug'] ?? ( $license['plan_slug'] ?? 'free' ) );
		$period = sanitize_key( $quota['quota_period'] ?? ( $license['quota_period'] ?? 'lifetime' ) );
		$is_exhausted = $limit > 0 && $remaining <= 0;
		$title = 'free' === $plan ? __( 'Free translation quota', 'teknotok-ai-translator' ) : __( 'Translation word quota', 'teknotok-ai-translator' );

		if ( $limit <= 0 ) {
			return array(
				'title'        => $title,
				'label'        => __( 'Unknown', 'teknotok-ai-translator' ),
				'usage'        => __( 'Usage unavailable', 'teknotok-ai-translator' ),
				'note'         => __( 'Quota details could not be refreshed yet.', 'teknotok-ai-translator' ),
				'used'         => $used,
				'limit'        => $limit,
				'remaining'    => $remaining,
				'percent'      => 0,
				'period'       => $period,
				'is_exhausted' => false,
			);
		}

		$note = sprintf(
			/* translators: %s: remaining word count */
			__( '%s words remaining.', 'teknotok-ai-translator' ),
			number_format_i18n( $remaining )
		);

		if ( 'free' === $plan && 'lifetime' === $period ) {
			$note .= ' ' . __( 'Free quota is a one-time allocation and does not reset.', 'teknotok-ai-translator' );
		} elseif ( ! empty( $quota['quota_period_end'] ) ) {
			$note .= ' ' . sprintf(
				/* translators: %s: quota renewal date */
				__( 'Renews on %s.', 'teknotok-ai-translator' ),
				date_i18n( get_option( 'date_format' ), strtotime( $quota['quota_period_end'] ) )
			);
		}

		if ( $is_exhausted ) {
			$note = __( 'Word quota is finished. Existing translations still work, but new translations are paused until more words are available.', 'teknotok-ai-translator' );
		}

		return array(
			'title'        => $title,
			'label'        => sprintf(
				/* translators: 1: used words, 2: total words */
				__( '%1$s / %2$s used', 'teknotok-ai-translator' ),
				number_format_i18n( $used ),
				number_format_i18n( $limit )
			),
			'usage'        => sprintf(
				/* translators: 1: used words, 2: total words */
				__( '%1$s / %2$s words', 'teknotok-ai-translator' ),
				number_format_i18n( $used ),
				number_format_i18n( $limit )
			),
			'note'         => $note,
			'used'         => $used,
			'limit'        => $limit,
			'remaining'    => $remaining,
			'percent'      => $percent,
			'period'       => $period,
			'is_exhausted' => $is_exhausted,
		);
	}

	/**
	 * Get a customer-facing estimated translation time label.
	 *
	 * @param array $queue_counts Current queue count snapshot.
	 * @param bool  $queue_paused Whether the queue is paused.
	 * @param bool  $setup_started Whether the customer just started setup.
	 * @return string
	 */
	private function get_estimated_translation_time_label( $queue_counts, $queue_paused, $setup_started = false ) {
		if ( $queue_paused ) {
			return __( 'Paused', 'teknotok-ai-translator' );
		}

		$pending    = (int) ( $queue_counts['pending'] ?? 0 );
		$processing = (int) ( $queue_counts['processing'] ?? 0 );
		$completed  = (int) ( $queue_counts['completed'] ?? 0 );
		$failed     = (int) ( $queue_counts['failed'] ?? 0 );
		$total      = $pending + $processing + $completed + $failed;

		if ( $pending > 0 || $processing > 0 ) {
			$string_pending = (int) ( $queue_counts['string_pending'] ?? 0 );
			$heavy_pending  = (int) ( $queue_counts['heavy_pending'] ?? 0 );
			$remaining_seconds = ( $string_pending * 0.1 ) + ( $heavy_pending * 6.0 );

			if ( $remaining_seconds < 60 ) {
				return __( 'Less than a minute', 'teknotok-ai-translator' );
			}

			$minutes = (int) ceil( $remaining_seconds / 60 );
			return sprintf(
				/* translators: %d: estimated minutes */
				_n( '~%d minute', '~%d minutes', $minutes, 'teknotok-ai-translator' ),
				$minutes
			);
		}

		if ( 0 === $total && $setup_started ) {
			return __( 'Calculating...', 'teknotok-ai-translator' );
		}

		return __( 'Complete', 'teknotok-ai-translator' );
	}

	/**
	 * Get live health summary values for the diagnostics polling endpoint.
	 *
	 * @param array $queue_counts Current queue count snapshot.
	 * @param array $quota_snapshot Current quota snapshot.
	 * @return array
	 */
	private function get_health_summary_snapshot( $queue_counts, $quota_snapshot = null ) {
		global $wpdb;

		$license_status = get_option( 'teknotok_ait_license_status', array() );
		$license_label  = $license_status['status'] ?? 'inactive';
		if ( 'active' === $license_label && ! \TeknoTok\AiTranslator\Integrations\LicenseManager::is_premium_active() ) {
			$license_label = 'expired';
		}

		$settings = get_option( 'teknotok_ait_settings', array() );
		$targets = $settings['target_languages'] ?? array();
		$target_count = is_array( $targets ) ? count( $targets ) : 0;
		$queue_paused = ! empty( $queue_counts['paused'] );
		$quota_snapshot = is_array( $quota_snapshot ) ? $quota_snapshot : $this->get_quota_snapshot();
		$license_ok = 'active' === $license_label || empty( $quota_snapshot['is_exhausted'] );
		$pending = (int) ( $queue_counts['pending'] ?? 0 );
		$processing = (int) ( $queue_counts['processing'] ?? 0 );
		$failed = (int) ( $queue_counts['failed'] ?? 0 );
		$warmup_pending = (int) ( $queue_counts['warmup_pending'] ?? 0 );
		$cached_count = 0;
		$translations_table_exists = false;
		$database_available = isset( $wpdb ) && is_object( $wpdb ) && isset( $wpdb->prefix );
		$translations_table = $database_available ? $wpdb->prefix . 'teknotok_translations' : '';

		if ( $database_available ) {
			if ( defined( 'DB_ENGINE' ) && 'sqlite' === DB_ENGINE ) {
				$translations_table_exists = (bool) $wpdb->get_var(
					$wpdb->prepare( "SELECT name FROM sqlite_master WHERE type='table' AND name = %s", $translations_table )
				);
			} else {
				$translations_table_exists = (bool) $wpdb->get_var(
					$wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $translations_table ) )
				);
			}

			if ( $translations_table_exists ) {
				$cached_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$translations_table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			}
		}

		return array(
			'license'  => array(
				'value' => ucfirst( (string) $license_label ),
				'ok'    => $license_ok,
			),
			'languages' => array(
				'value' => sprintf(
					/* translators: %d: target language count */
					_n( '%d target', '%d targets', $target_count, 'teknotok-ai-translator' ),
					$target_count
				),
				'ok'    => $target_count > 0,
			),
			'queue'    => array(
				'value' => $queue_paused ? __( 'Paused', 'teknotok-ai-translator' ) : ( $warmup_pending > 0 ? __( 'Warming Up', 'teknotok-ai-translator' ) : ( $pending + $processing > 0 ? __( 'Working', 'teknotok-ai-translator' ) : __( 'Clear', 'teknotok-ai-translator' ) ) ),
				'ok'    => ! $queue_paused && 0 === $failed,
			),
			'memory'   => array(
				'value' => sprintf(
					/* translators: %s: translation memory count */
					__( '%s saved', 'teknotok-ai-translator' ),
					number_format_i18n( $cached_count )
				),
				'ok'    => $translations_table_exists,
			),
		);
	}

	/**
	 * Get the active filter hook status check.
	 *
	 * @return array Hook check array.
	 */
	public static function get_active_filters_status() {
		global $wp_filter;
		$hooks = array(
			'the_title'                               => 'translate_title',
			'the_content'                             => 'translate_content',
			'the_excerpt'                             => 'translate_excerpt',
			'wp_get_nav_menu_items'                   => 'translate_menu_items',
			'get_post_metadata'                       => 'translate_metadata',
			'gettext'                                 => 'translate_gettext',
			'wp_template_enhancement_output_buffer'  => 'translate_page_output',
			'woocommerce_add_to_cart_fragments'       => 'translate_woocommerce_fragments',
			'woocommerce_update_order_review_fragments' => 'translate_woocommerce_fragments',
			'wp_head'                                 => 'render_hreflang_tags',
		);

		$status = array();
		foreach ( $hooks as $hook => $method ) {
			$status[ $hook ] = array(
				'method' => $method,
				'active' => false,
			);

			if ( ! isset( $wp_filter[ $hook ] ) ) {
				continue;
			}

			// Traverse the registered priorities
			$callbacks_list = $wp_filter[ $hook ]->callbacks ?? array();
			foreach ( $callbacks_list as $priority => $callbacks ) {
				foreach ( $callbacks as $callback_data ) {
					$function = $callback_data['function'] ?? null;
					if ( is_array( $function ) && isset( $function[0] ) && is_object( $function[0] ) ) {
						if ( is_a( $function[0], 'TeknoTok\AiTranslator\Frontend\TranslationFilters' ) && isset( $function[1] ) && $function[1] === $method ) {
							$status[ $hook ]['active'] = true;
							break 2;
						}
					}
				}
			}
		}

		return $status;
	}

	/**
	 * Render system status dashboard.

	 *
	 * @return void
	 */
	public function render_diagnostics() {
		global $wpdb;

		$queue_counts = JobRepository::get_counts();
		$queue_paused = get_option( 'teknotok_ait_queue_paused', '0' ) === '1';
		$raw_queue_pause_reason = get_option( 'teknotok_ait_queue_pause_reason', '' );
		$queue_pause_reason = $queue_paused ? ErrorSanitizer::sanitize_message( $raw_queue_pause_reason ) : '';
		$queue_pause_is_limit = $queue_paused && ErrorSanitizer::is_limit_message( $raw_queue_pause_reason );
		$lock_expires = (int) get_option( 'teknotok_ait_queue_lock_expires', 0 );
		$queue_locked = $lock_expires > time();
		$license_status = get_option( 'teknotok_ait_license_status', array() );
		$license_label = $license_status['status'] ?? 'inactive';
		if ( 'active' === $license_label && ! \TeknoTok\AiTranslator\Integrations\LicenseManager::is_premium_active() ) {
			$license_label = 'expired';
		}

		$database_available = isset( $wpdb ) && is_object( $wpdb ) && isset( $wpdb->prefix );
		$jobs_table = $database_available ? $wpdb->prefix . 'teknotok_jobs' : '';
		$translations_table = $database_available ? $wpdb->prefix . 'teknotok_translations' : '';
		$translations_table_exists = false;
		$jobs_table_exists = false;

		if ( $database_available ) {
			if ( QueueManager::is_sqlite_active() ) {
				$translations_table_exists = (bool) $wpdb->get_var(
					$wpdb->prepare( "SELECT name FROM sqlite_master WHERE type='table' AND name = %s", $translations_table )
				);
				$jobs_table_exists = (bool) $wpdb->get_var(
					$wpdb->prepare( "SELECT name FROM sqlite_master WHERE type='table' AND name = %s", $jobs_table )
				);
			} else {
				$translations_table_exists = (bool) $wpdb->get_var(
					$wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $translations_table ) )
				);
				$jobs_table_exists = (bool) $wpdb->get_var(
					$wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $jobs_table ) )
				);
			}
		}

		$settings = get_option( 'teknotok_ait_settings', array() );
		$targets = $settings['target_languages'] ?? array();
		$target_count = count( $targets );
		$pending = intval( $queue_counts['pending'] );
		$processing = intval( $queue_counts['processing'] );
		$completed = intval( $queue_counts['completed'] );
		$failed = intval( $queue_counts['failed'] );
		$warmup_pending = intval( $queue_counts['warmup_pending'] ?? 0 );
		$retryable_failed = JobRepository::get_retryable_failed_count();
		$stale_language_jobs = JobRepository::get_stale_target_job_count( $targets );
		$local_warmup_skipped = get_option( 'teknotok_ait_local_warmup_skipped_message', '' );
		$total = $pending + $processing + $completed + $failed;
		$cached_count = 0;

		if ( $database_available && $translations_table_exists ) {
			$cached_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$translations_table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		}

		$quota_snapshot = $this->get_quota_snapshot();
		$setup_started = isset( $_GET['setup'] ) && 'start' === sanitize_key( wp_unslash( $_GET['setup'] ) );
		$estimated_time_label = $this->get_estimated_translation_time_label( $queue_counts, $queue_paused, $setup_started );
		$license_ok = 'active' === $license_label || ! $quota_snapshot['is_exhausted'];

		$health_items = array(
			array(
				'label' => __( 'License', 'teknotok-ai-translator' ),
				'value' => ucfirst( (string) $license_label ),
				'ok'    => $license_ok,
				'id'    => 'teknotok-health-license-value',
			),
			array(
				'label' => __( 'Languages', 'teknotok-ai-translator' ),
				'value' => sprintf(
					/* translators: %d: target language count */
					_n( '%d target', '%d targets', $target_count, 'teknotok-ai-translator' ),
					$target_count
				),
				'ok'    => $target_count > 0,
				'id'    => 'teknotok-health-languages-value',
			),
			array(
				'label' => __( 'Queue', 'teknotok-ai-translator' ),
				'value' => $queue_paused ? __( 'Paused', 'teknotok-ai-translator' ) : ( $warmup_pending > 0 ? __( 'Warming Up', 'teknotok-ai-translator' ) : ( $pending + $processing > 0 ? __( 'Working', 'teknotok-ai-translator' ) : __( 'Clear', 'teknotok-ai-translator' ) ) ),
				'ok'    => ! $queue_paused && 0 === $failed,
				'id'    => 'teknotok-health-queue-value',
			),
			array(
				'label' => __( 'Memory', 'teknotok-ai-translator' ),
				'value' => sprintf(
					/* translators: %s: translation memory count */
					__( '%s saved', 'teknotok-ai-translator' ),
					number_format_i18n( $cached_count )
				),
				'ok'    => $translations_table_exists,
				'id'    => 'teknotok-health-memory-value',
			),
			array(
				'label' => __( 'Estimated Translation Time', 'teknotok-ai-translator' ),
				'value' => $estimated_time_label,
				'ok'    => ! $queue_paused,
				'id'    => 'teknotok-health-estimated-time-value',
			),
		);

		$health_issues = array();
		if ( 0 === $target_count ) {
			$health_issues[] = __( 'Choose at least one target language in Settings.', 'teknotok-ai-translator' );
		}
		if ( ! $translations_table_exists || ! $jobs_table_exists ) {
			$health_issues[] = __( 'Database tables are missing. Deactivate and reactivate the plugin, then recheck this page.', 'teknotok-ai-translator' );
		}
		if ( $queue_paused ) {
			$health_issues[] = $queue_pause_reason ? $queue_pause_reason : __( 'Translation queue is paused.', 'teknotok-ai-translator' );
		}
		if ( $quota_snapshot['is_exhausted'] ) {
			$health_issues[] = __( 'Your translation word quota is finished. Add a license or more words before starting new translations.', 'teknotok-ai-translator' );
		}

		$has_work = $pending > 0 || $processing > 0;
		$health_state = empty( $health_issues ) ? ( $has_work ? 'working' : 'ready' ) : 'attention';
		$health_label = array(
			'ready'     => __( 'Ready', 'teknotok-ai-translator' ),
			'working'   => __( 'Translating', 'teknotok-ai-translator' ),
			'attention' => __( 'Needs attention', 'teknotok-ai-translator' ),
		)[ $health_state ];

		if ( 'attention' === $health_state ) {
			$next_step_text = $health_issues[0];
		} elseif ( 'working' === $health_state ) {
			$next_step_text = __( 'Live translation progress updates automatically.', 'teknotok-ai-translator' );
		} else {
			$next_step_text = __( 'The translator is configured and ready.', 'teknotok-ai-translator' );
		}

		?>
		<div class="wrap teknotok-ait-wrap">
			<div class="teknotok-header-title-row">
				<h1 style="margin: 0;"><?php esc_html_e( 'Translation Status', 'teknotok-ai-translator' ); ?></h1>
			</div>
			<?php settings_errors(); ?>

			<div class="teknotok-health-panel teknotok-health-<?php echo esc_attr( $health_state ); ?>">
				<div class="teknotok-health-main">
					<div>
						<span class="teknotok-health-badge"><?php echo esc_html( $health_label ); ?></span>
						<h2><?php esc_html_e( 'Translator health summary', 'teknotok-ai-translator' ); ?></h2>
						<p><?php echo esc_html( $next_step_text ); ?></p>
					</div>
				</div>

				<div class="teknotok-health-grid">
					<?php foreach ( $health_items as $item ) : ?>
						<div class="teknotok-health-item <?php echo esc_attr( $item['ok'] ? 'is-ok' : 'needs-attention' ); ?>">
							<span><?php echo esc_html( $item['label'] ); ?></span>
							<strong <?php echo ! empty( $item['id'] ) ? 'id="' . esc_attr( $item['id'] ) . '"' : ''; ?>><?php echo esc_html( $item['value'] ); ?></strong>
							<?php if ( ! empty( $item['description'] ) ) : ?>
								<p><?php echo esc_html( $item['description'] ); ?></p>
							<?php endif; ?>
						</div>
					<?php endforeach; ?>
				</div>

				<div class="teknotok-health-quota" data-quota-period="<?php echo esc_attr( $quota_snapshot['period'] ); ?>">
					<div class="teknotok-health-quota-row">
						<span id="teknotok-health-quota-title"><?php echo esc_html( $quota_snapshot['title'] ); ?></span>
						<strong id="teknotok-health-quota-usage"><?php echo esc_html( $quota_snapshot['usage'] ); ?></strong>
					</div>
					<div class="teknotok-health-quota-track" aria-hidden="true">
						<div id="teknotok-health-quota-bar" class="teknotok-health-quota-bar <?php echo esc_attr( $quota_snapshot['is_exhausted'] ? 'is-exhausted' : '' ); ?>" style="width: <?php echo esc_attr( $quota_snapshot['percent'] ); ?>%;"></div>
					</div>
					<p id="teknotok-health-quota-note"><?php echo esc_html( $quota_snapshot['note'] ); ?></p>
				</div>

				<div class="teknotok-health-progress">
					<div class="card-header" style="display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 10px;">
						<div>
							<h2 style="margin: 0; display: inline-flex; align-items: center; gap: 10px;">
								<?php esc_html_e( 'Translation Progress', 'teknotok-ai-translator' ); ?>
								<span id="queue-paused-badge" class="badge badge-danger" style="background: #fee2e2; color: #991b1b; padding: 4px 8px; font-weight: 700; border-radius: 4px; font-size: 11px; <?php echo esc_attr( $queue_paused ? '' : 'display: none;' ); ?>"><?php esc_html_e( 'PAUSED', 'teknotok-ai-translator' ); ?></span>
							</h2>
							<p class="subtitle" style="margin: 5px 0 0 0;"><?php esc_html_e( 'See what is waiting, what is being translated, and what is already finished.', 'teknotok-ai-translator' ); ?></p>
							<div id="queue-paused-message" class="notice notice-warning" style="margin: 12px 0 0 0; <?php echo esc_attr( $queue_paused ? '' : 'display: none;' ); ?>">
								<p style="margin: 8px 0;">
									<strong><?php esc_html_e( 'Translation paused:', 'teknotok-ai-translator' ); ?></strong>
									<span id="queue-paused-reason"><?php echo esc_html( $queue_pause_reason ? $queue_pause_reason : __( 'Translation provider limit reached.', 'teknotok-ai-translator' ) ); ?></span>
								</p>
							</div>
							<div id="queue-local-warmup-message" class="notice notice-warning" style="margin: 12px 0 0 0; <?php echo esc_attr( ! empty( $local_warmup_skipped ) ? '' : 'display: none;' ); ?>">
								<p style="margin: 8px 0;">
									<strong><?php esc_html_e( 'Local warmup limited:', 'teknotok-ai-translator' ); ?></strong>
									<span id="queue-local-warmup-reason"><?php echo esc_html( $local_warmup_skipped ); ?></span>
								</p>
							</div>
						</div>
						<div class="teknotok-queue-actions">
							<button type="button" id="teknotok-retry-failed-jobs" class="button button-secondary" style="<?php echo esc_attr( $retryable_failed > 0 ? '' : 'display: none;' ); ?>">
								<?php esc_html_e( 'Retry Items', 'teknotok-ai-translator' ); ?>
							</button>
							<button type="button" id="teknotok-cancel-stale-language-jobs" class="button button-secondary" style="<?php echo esc_attr( $stale_language_jobs > 0 ? '' : 'display: none;' ); ?>">
								<?php esc_html_e( 'Cancel Removed Languages', 'teknotok-ai-translator' ); ?>
							</button>
							<button type="button" id="teknotok-resume-queue" class="button button-primary" style="<?php echo esc_attr( $queue_paused ? '' : 'display: none;' ); ?>">
								<?php esc_html_e( 'Resume Translation', 'teknotok-ai-translator' ); ?>
							</button>
							<button type="button" id="teknotok-pause-queue" class="button button-secondary" style="<?php echo esc_attr( ! $queue_paused ? '' : 'display: none;' ); ?>">
								<?php esc_html_e( 'Pause Translation', 'teknotok-ai-translator' ); ?>
							</button>
							<button type="button" id="teknotok-run-queue-btn" class="button button-primary" style="<?php echo esc_attr( ( $pending > 0 || $processing > 0 ) && ! $queue_paused && ! $queue_locked ? '' : 'display: none;' ); ?>">
								<?php esc_html_e( 'Continue Now', 'teknotok-ai-translator' ); ?>
							</button>
							<button type="button" id="teknotok-cancel-waiting-jobs" class="button button-link-delete" style="<?php echo esc_attr( ( $pending > 0 || $processing > 0 || $failed > 0 ) ? '' : 'display: none;' ); ?>">
								<?php esc_html_e( 'Reset Waiting Jobs', 'teknotok-ai-translator' ); ?>
							</button>
						</div>
					</div>

					<?php
					$pending = intval( $queue_counts['pending'] );
					$processing = intval( $queue_counts['processing'] );
					$completed = intval( $queue_counts['completed'] );
					$failed = intval( $queue_counts['failed'] );
					$total = $pending + $processing + $completed + $failed;
					$percentage = ( $total > 0 ) ? round( ( $completed / $total ) * 100 ) : 0;
					?>

					<!-- Translation Progress Bar Widget -->
					<?php if ( $total > 0 || ( isset( $_GET['setup'] ) && 'start' === sanitize_key( wp_unslash( $_GET['setup'] ) ) ) ) : ?>
						<div class="teknotok-progress-container" <?php if ( $total === 0 ) echo 'style="display: none;"'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
							<div class="teknotok-progress-header">
								<span><?php esc_html_e( 'Overall Translation Progress', 'teknotok-ai-translator' ); ?></span>
								<span id="queue-progress-percentage"><?php echo esc_html( $percentage ); ?>%</span>
							</div>
							<div class="teknotok-progress-track">
								<div id="queue-progress-bar" class="teknotok-progress-bar <?php echo esc_attr( ( $pending > 0 || $processing > 0 ) ? 'teknotok-progress-animated' : '' ); ?>" style="width: <?php echo esc_attr( $percentage ); ?>%;"></div>
							</div>
						</div>
					<?php endif; ?>

					<!-- Dashboard grid of status cards -->
					<div class="teknotok-status-grid">
						<div class="teknotok-status-card status-pending">
							<div class="status-icon"><span class="dashicons dashicons-clock"></span></div>
							<div class="status-info">
								<span class="status-label"><?php esc_html_e( 'Pending', 'teknotok-ai-translator' ); ?></span>
								<span class="status-value" id="queue-count-pending"><?php echo esc_html( $queue_counts['pending'] ); ?></span>
							</div>
						</div>
						<div class="teknotok-status-card status-processing">
							<div class="status-icon"><span class="dashicons dashicons-update <?php echo esc_attr( ( $queue_counts['pending'] > 0 || $queue_counts['processing'] > 0 ) ? 'spin' : '' ); ?>"></span></div>
							<div class="status-info">
								<span class="status-label"><?php esc_html_e( 'Processing', 'teknotok-ai-translator' ); ?></span>
								<span class="status-value" id="queue-count-processing"><?php echo esc_html( $queue_counts['processing'] ); ?></span>
							</div>
						</div>
						<div class="teknotok-status-card status-completed">
							<div class="status-icon"><span class="dashicons dashicons-yes-alt"></span></div>
							<div class="status-info">
								<span class="status-label"><?php esc_html_e( 'Completed', 'teknotok-ai-translator' ); ?></span>
								<span class="status-value" id="queue-count-completed"><?php echo esc_html( $queue_counts['completed'] ); ?></span>
							</div>
						</div>
						<div class="teknotok-status-card status-failed">
							<div class="status-icon"><span class="dashicons dashicons-warning"></span></div>
							<div class="status-info">
								<span class="status-label"><?php esc_html_e( 'Failed', 'teknotok-ai-translator' ); ?></span>
								<span class="status-value" id="queue-count-failed"><?php echo esc_html( $queue_counts['failed'] ); ?></span>
							</div>
						</div>
					</div>

					<p class="description" id="queue-resume-help" style="<?php echo esc_attr( $queue_paused && $queue_pause_is_limit ? '' : 'display: none;' ); ?>">
						<?php esc_html_e( 'After upgrading or fixing the word quota, click Resume Translation to unlock the waiting items, then click Continue Now.', 'teknotok-ai-translator' ); ?>
					</p>
					<p class="description" id="queue-retry-help" style="<?php echo esc_attr( $retryable_failed > 0 ? '' : 'display: none;' ); ?>">
						<?php esc_html_e( 'After fixing a connection or server issue, click Retry Items to move them back to the waiting list, then click Continue Now.', 'teknotok-ai-translator' ); ?>
					</p>
					<p class="description" id="queue-cancel-stale-help" style="<?php echo esc_attr( $stale_language_jobs > 0 ? '' : 'display: none;' ); ?>">
						<?php esc_html_e( 'Some unfinished jobs belong to languages that are no longer selected. Cancel them to stop spending queue time on removed languages.', 'teknotok-ai-translator' ); ?>
					</p>
					<p class="description" id="queue-cancel-waiting-help" style="<?php echo esc_attr( ( $pending > 0 || $processing > 0 || $failed > 0 ) ? '' : 'display: none;' ); ?>">
						<?php esc_html_e( 'Reset Waiting Jobs cancels unfinished queue rows only. Completed saved translations stay in translation memory.', 'teknotok-ai-translator' ); ?>
					</p>
					<p class="description" id="queue-breakdown-help" style="display: none;">
						<?php
						printf(
							/* translators: 1: string jobs, 2: page/content jobs, 3: warmup URL jobs */
							esc_html__( 'Pending breakdown: %1$d frontend string jobs, %2$d content jobs, %3$d warmup URL jobs.', 'teknotok-ai-translator' ),
							(int) ( $queue_counts['string_pending'] ?? 0 ),
							max( 0, (int) ( $queue_counts['heavy_pending'] ?? 0 ) - (int) ( $queue_counts['warmup_pending'] ?? 0 ) ),
							(int) ( $queue_counts['warmup_pending'] ?? 0 )
						);
						?>
					</p>
				</div>
			</div>

			<div class="teknotok-ait-dashboard">
				<details class="teknotok-ait-card teknotok-support-mode">
					<summary>
						<span><span class="dashicons dashicons-sos"></span> <?php esc_html_e( 'Support Mode', 'teknotok-ai-translator' ); ?></span>
						<span class="teknotok-advanced-diagnostics-hint"><?php esc_html_e( 'Only open this when TeknoTok support asks for details', 'teknotok-ai-translator' ); ?></span>
					</summary>
					<div class="teknotok-support-mode-body">
						<div class="teknotok-support-mode-header">
							<p class="subtitle"><?php esc_html_e( 'Technical environment details and debug logs are hidden from the normal customer view.', 'teknotok-ai-translator' ); ?></p>
							<button type="button" id="teknotok-copy-report" class="button button-secondary">
								<span class="dashicons dashicons-clipboard"></span>
								<span id="teknotok-copy-report-text"><?php esc_html_e( 'Copy System Report', 'teknotok-ai-translator' ); ?></span>
							</button>
						</div>

				<div class="teknotok-dashboard-grid">
					<div class="env-column" style="display: flex; flex-direction: column; gap: 24px;">
						<!-- Environment Details Card -->
						<div class="teknotok-ait-card env-section" style="margin-bottom: 0;">
							<h2><span class="dashicons dashicons-admin-settings"></span> <?php esc_html_e( 'System Environment', 'teknotok-ai-translator' ); ?></h2>
							<div class="env-info-list">
								<div class="env-item">
									<span class="env-label"><?php esc_html_e( 'PHP Version', 'teknotok-ai-translator' ); ?></span>
									<span class="env-value badge"><?php echo esc_html( PHP_VERSION ); ?></span>
								</div>
								<div class="env-item">
									<span class="env-label"><?php esc_html_e( 'WordPress Version', 'teknotok-ai-translator' ); ?></span>
									<span class="env-value badge"><?php echo esc_html( $GLOBALS['wp_version'] ); ?></span>
								</div>
								<div class="env-item">
									<span class="env-label"><?php esc_html_e( 'WooCommerce Version', 'teknotok-ai-translator' ); ?></span>
									<span class="env-value badge <?php echo esc_attr( class_exists( 'WooCommerce' ) ? 'badge-success' : 'badge-danger' ); ?>">
										<?php echo class_exists( 'WooCommerce' ) ? esc_html( WC()->version ) : esc_html__( 'Not Installed', 'teknotok-ai-translator' ); ?>
									</span>
								</div>
								<div class="env-item">
									<span class="env-label"><?php esc_html_e( 'Memory Limit', 'teknotok-ai-translator' ); ?></span>
									<span class="env-value badge"><?php echo esc_html( WP_MEMORY_LIMIT ); ?></span>
								</div>
								<div class="env-item">
									<span class="env-label"><?php esc_html_e( 'License Key Status', 'teknotok-ai-translator' ); ?></span>
									<span class="env-value badge <?php echo esc_attr( 'active' === $license_label ? 'badge-success' : 'badge-warning' ); ?>">
										<?php echo esc_html( $license_label ); ?>
									</span>
								</div>
								<div class="env-item">
									<span class="env-label"><?php esc_html_e( 'Translations Cache Table', 'teknotok-ai-translator' ); ?></span>
									<span class="env-value status-dot <?php echo esc_attr( $translations_table_exists ? 'dot-active' : 'dot-inactive' ); ?>">
										<?php echo $translations_table_exists ? esc_html__( 'Active', 'teknotok-ai-translator' ) : esc_html__( 'Missing', 'teknotok-ai-translator' ); ?>
									</span>
								</div>
								<div class="env-item">
									<span class="env-label"><?php esc_html_e( 'Jobs Queue Table', 'teknotok-ai-translator' ); ?></span>
									<span class="env-value status-dot <?php echo esc_attr( $jobs_table_exists ? 'dot-active' : 'dot-inactive' ); ?>">
										<?php echo $jobs_table_exists ? esc_html__( 'Active', 'teknotok-ai-translator' ) : esc_html__( 'Missing', 'teknotok-ai-translator' ); ?>
									</span>
								</div>
							</div>
						</div>

						<!-- Advanced support checks -->
						<details class="teknotok-ait-card hooks-section teknotok-advanced-diagnostics">
							<summary>
								<span><span class="dashicons dashicons-admin-plugins"></span> <?php esc_html_e( 'Advanced Support Checks', 'teknotok-ai-translator' ); ?></span>
								<span class="teknotok-advanced-diagnostics-hint"><?php esc_html_e( 'For support only', 'teknotok-ai-translator' ); ?></span>
							</summary>
							<p class="subtitle"><?php esc_html_e( 'Hook registration details are useful when TeknoTok support asks for deeper diagnostics.', 'teknotok-ai-translator' ); ?></p>
							<div class="env-info-list">
								<?php
								$filters = self::get_active_filters_status();
								$settings = get_option( 'teknotok_ait_settings', array() );
								$targets = $settings['target_languages'] ?? array();
								$has_targets = ! empty( $targets );

								foreach ( $filters as $hook => $data ) :
									$is_active = $data['active'];
									$status_class = $is_active ? 'dot-active' : 'dot-inactive';
									$status_text = $is_active ? __( 'Active', 'teknotok-ai-translator' ) : __( 'Inactive', 'teknotok-ai-translator' );

									// Since this page loads in the admin dashboard where frontend filters are returned early,
									// we display "Active (Frontend)" to avoid user confusion if target languages are configured.
									if ( ! $is_active && is_admin() && $has_targets ) {
										$status_class = 'dot-active';
										$status_text = __( 'Active (Frontend)', 'teknotok-ai-translator' );
									}
								?>
									<div class="env-item" style="padding: 10px 0;">
										<span class="env-label" style="font-family: monospace; font-size: 12px;"><?php echo esc_html( $hook ); ?></span>
										<span class="env-value status-dot <?php echo esc_attr( $status_class ); ?>">
											<?php echo esc_html( $status_text ); ?>
										</span>
									</div>
								<?php endforeach; ?>
							</div>
						</details>
					</div>
				</div>

				<!-- Debug Logs Card -->
				<div class="teknotok-ait-card logs-section" style="margin-top: 24px; padding: 24px;">
					<div class="logs-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
						<div>
							<h2><span class="dashicons dashicons-media-text"></span> <?php esc_html_e( 'Plugin Activity & Debug Logs', 'teknotok-ai-translator' ); ?></h2>
							<p class="subtitle" style="margin: 0;"><?php esc_html_e( 'View the last 100 log lines from the background processing and API communications.', 'teknotok-ai-translator' ); ?></p>
						</div>
						<form method="post" action="">
							<?php wp_nonce_field( 'teknotok_ait_diag_nonce' ); ?>
							<button type="submit" name="teknotok_ait_diag_action" value="clear_logs" class="button button-link-delete log-clear-btn" onclick="return confirm('<?php esc_attr_e( 'Are you sure you want to clear the debug log file?', 'teknotok-ai-translator' ); ?>');">
								<span class="dashicons dashicons-trash"></span> <?php esc_html_e( 'Clear Log File', 'teknotok-ai-translator' ); ?>
							</button>
						</form>
					</div>
					
					<?php
					$logs = ErrorSanitizer::sanitize_log_output( \TeknoTok\AiTranslator\Utils\Logger::read_logs( 100 ) );
					?>
					
					<div class="terminal-logs-container">
						<div class="terminal-header">
							<span class="terminal-dot red-dot"></span>
							<span class="terminal-dot yellow-dot"></span>
							<span class="terminal-dot green-dot"></span>
							<span class="terminal-title">teknotok-translator-debug.log</span>
						</div>
						<div class="terminal-body" id="log-terminal">
							<?php 
							if ( $logs ) {
								$log_lines = explode( "\n", $logs );
								foreach ( $log_lines as $line ) {
									if ( empty( trim( $line ) ) ) {
										continue;
									}
									
									$class = 'log-line';
									if ( false !== stripos( $line, 'error' ) || false !== stripos( $line, 'exception' ) ) {
										$class .= ' log-error';
									} elseif ( false !== stripos( $line, 'warning' ) ) {
										$class .= ' log-warning';
									} elseif ( false !== stripos( $line, 'info' ) ) {
										$class .= ' log-info';
									}
									echo '<div class="' . esc_attr( $class ) . '">' . esc_html( $line ) . '</div>';
								}
							} else {
								echo '<div class="log-empty">' . esc_html__( 'No log entries found.', 'teknotok-ai-translator' ) . '</div>';
							}
							?>
						</div>
					</div>
				</div>
					</div>
				</details>
			</div>
		</div>
		<?php
	}
}
