<?php
/**
 * Admin Tools page.
 *
 * @package Effortless_Taiwan_Mandarin_Helper
 */

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

/**
 * Adds the Mandarin Translator page under WP Admin → Tools.
 */
class ELTMH_Admin {

	/** Registers hooks. */
	public function init(): void {
		add_action( 'admin_menu', array( $this, 'add_tools_page' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	/** Adds the Tools → Mandarin Helper submenu page. */
	public function add_tools_page(): void {
		add_management_page(
			__( 'Mandarin Helper', 'effortless-taiwan-mandarin-helper' ),
			__( 'Mandarin Helper', 'effortless-taiwan-mandarin-helper' ),
			'manage_options',
			'eltmh-translator',
			array( $this, 'render_page' )
		);
	}

	/**
	 * Enqueues CSS + JS only on the plugin's own admin page.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_assets( string $hook ): void {
		if ( 'tools_page_eltmh-translator' !== $hook ) {
			return;
		}

		wp_enqueue_style(
			'eltmh-style',
			ELTMH_URL . 'assets/css/eltmh-style.css',
			array(),
			ELTMH_VERSION
		);

		wp_enqueue_script(
			'eltmh-translator',
			ELTMH_URL . 'assets/js/eltmh-translator.js',
			array(),
			ELTMH_VERSION,
			true
		);

		wp_localize_script(
			'eltmh-translator',
			'eltmhData',
			array(
				'restUrl' => rest_url( 'eltmh/v1/translate' ),
				'nonce'   => wp_create_nonce( 'eltmh_translate' ),
			)
		);
	}

	/** Renders the admin translator page. */
	public function render_page(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Mandarin Helper', 'effortless-taiwan-mandarin-helper' ); ?> <small><?php echo esc_html( ELTMH_VERSION ); ?></small></h1>
			<?php echo self::widget_html( '', null, true, self::display_defaults() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- widget_html() escapes all output internally. ?>
		</div>
		<?php
	}

	/**
	 * Returns the site-wide "show this result row" defaults from eltmh_settings.
	 *
	 * @return array<string,bool>
	 */
	public static function display_defaults(): array {
		$settings = (array) get_option( 'eltmh_settings', array() );

		return array(
			'original'    => $settings['show_original'] ?? true,
			'chinese'     => $settings['show_chinese'] ?? true,
			'pinyin'      => $settings['show_pinyin'] ?? true,
			'zhuyin'      => $settings['show_zhuyin'] ?? true,
			'translation' => $settings['show_translation'] ?? true,
		);
	}

	/**
	 * Returns the shared widget HTML used by both admin page and shortcode.
	 *
	 * @param string                    $preset_text   Pre-filled textarea value.
	 * @param array<string,string>|null $preset_result Pre-cached result or null.
	 * @param bool                      $is_admin      True when rendering inside wp-admin.
	 * @param array<string,bool>        $display       Which result rows to render (all true by default).
	 * @return string
	 */
	public static function widget_html( string $preset_text, ?array $preset_result, bool $is_admin = false, array $display = array() ): string {
		$show = array_merge(
			array(
				'original'    => true,
				'chinese'     => true,
				'pinyin'      => true,
				'zhuyin'      => true,
				'translation' => true,
			),
			$display
		);

		$preset_json = $preset_result ? wp_json_encode( $preset_result ) : '';
		$rest_url    = rest_url( 'eltmh/v1/translate' );
		$dict_url    = ELTMH_URL . 'assets/js/eltmh-dict.json';
		$nonce       = $is_admin ? '' : wp_create_nonce( 'eltmh_translate' );

		ob_start();
		?>
		<div class="eltmh-translator-widget"
			data-rest-url="<?php echo esc_url( $rest_url ); ?>"
			data-dict-url="<?php echo esc_url( $dict_url ); ?>"
			data-nonce="<?php echo esc_attr( $nonce ); ?>"
			data-preset-result="<?php echo esc_attr( $preset_json ); ?>"
			data-version="<?php echo esc_attr( ELTMH_VERSION ); ?>">

			<form class="eltmh-form">
				<div class="eltmh-input-wrap">
					<textarea class="eltmh-input" rows="4"
						placeholder="<?php esc_attr_e( 'Enter text to translate…', 'effortless-taiwan-mandarin-helper' ); ?>"><?php echo esc_textarea( $preset_text ); ?></textarea>
					<button type="button" class="eltmh-clear" aria-label="<?php esc_attr_e( 'Clear text', 'effortless-taiwan-mandarin-helper' ); ?>" style="display:none;">&times;</button>
				</div>

				<button type="submit" class="eltmh-submit button button-primary">
					<?php esc_html_e( 'Translate', 'effortless-taiwan-mandarin-helper' ); ?>
				</button>
			</form>

			<div class="eltmh-spinner" style="display:none;" aria-live="polite">
				<?php esc_html_e( 'Translating…', 'effortless-taiwan-mandarin-helper' ); ?>
			</div>

			<div class="eltmh-error" role="alert" style="display:none;"></div>

			<div class="eltmh-history-nav" style="display:none;" aria-label="<?php esc_attr_e( 'Translation history', 'effortless-taiwan-mandarin-helper' ); ?>">
				<button type="button" class="eltmh-prev button" disabled><?php esc_html_e( '← Previous', 'effortless-taiwan-mandarin-helper' ); ?></button>
				<span class="eltmh-history-pos"></span>
				<button type="button" class="eltmh-next button" disabled><?php esc_html_e( 'Next →', 'effortless-taiwan-mandarin-helper' ); ?></button>
			</div>

			<div class="eltmh-results" style="display:none;" aria-live="polite" aria-atomic="true">
				<?php if ( $show['original'] ) : ?>
				<div class="eltmh-result-row eltmh-original">
					<span class="eltmh-label"><?php esc_html_e( 'Original', 'effortless-taiwan-mandarin-helper' ); ?> (<span class="eltmh-source-language"></span>):</span>
					<span class="eltmh-source-text"></span>
				</div>
				<?php endif; ?>
				<?php if ( $show['chinese'] ) : ?>
				<div class="eltmh-result-row">
					<span class="eltmh-label"><?php esc_html_e( 'Chinese', 'effortless-taiwan-mandarin-helper' ); ?>:</span>
					<span class="eltmh-chinese"></span>
				</div>
				<?php endif; ?>
				<?php if ( $show['pinyin'] ) : ?>
				<div class="eltmh-result-row">
					<span class="eltmh-label"><?php esc_html_e( 'Pinyin', 'effortless-taiwan-mandarin-helper' ); ?>:</span>
					<span class="eltmh-pinyin"></span>
				</div>
				<?php endif; ?>
				<?php if ( $show['zhuyin'] ) : ?>
				<div class="eltmh-result-row">
					<span class="eltmh-label"><?php esc_html_e( 'Bopomofo', 'effortless-taiwan-mandarin-helper' ); ?>:</span>
					<span class="eltmh-bopomofo"></span>
				</div>
				<?php endif; ?>
				<?php if ( $show['translation'] ) : ?>
				<div class="eltmh-result-row eltmh-english-row" style="display:none;">
					<span class="eltmh-label"><?php esc_html_e( 'English', 'effortless-taiwan-mandarin-helper' ); ?>:</span>
					<span class="eltmh-english"></span>
				</div>
				<?php endif; ?>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}
}
