<?php
/**
 * Shortcode handler.
 *
 * @package Effortless_Taiwan_Mandarin_Helper
 */

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

/**
 * Registers and renders the [eltmh_translator] shortcode.
 */
class ELTMH_Shortcode {

	/**
	 * Sets up the instance.
	 *
	 * @param ELTMH_Cache $cache    Cache instance for pre-rendering cached results.
	 * @param string      $provider Provider slug used for cache key lookup.
	 */
	public function __construct( private ELTMH_Cache $cache, private string $provider = 'openai' ) {}

	/** Registers hooks. */
	public function init(): void {
		add_shortcode( 'eltmh_translator', array( $this, 'render' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	/** Enqueues front-end assets. */
	public function enqueue_assets(): void {
		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
		);
	}

	/**
	 * Renders the translator widget.
	 *
	 * @param array<string,string>|string $atts Shortcode attributes.
	 * @return string HTML output.
	 */
	public function render( $atts ): string {
		$defaults = ELTMH_Admin::display_defaults();

		$atts = shortcode_atts(
			array(
				'text'        => '',
				'original'    => $defaults['original'] ? 'yes' : 'no',
				'chinese'     => $defaults['chinese'] ? 'yes' : 'no',
				'pinyin'      => $defaults['pinyin'] ? 'yes' : 'no',
				'zhuyin'      => $defaults['zhuyin'] ? 'yes' : 'no',
				'translation' => $defaults['translation'] ? 'yes' : 'no',
			),
			$atts,
			'eltmh_translator'
		);

		$preset_text = sanitize_text_field( $atts['text'] );

		$display = array(
			'original'    => 'no' !== $atts['original'],
			'chinese'     => 'no' !== $atts['chinese'],
			'pinyin'      => 'no' !== $atts['pinyin'],
			'zhuyin'      => 'no' !== $atts['zhuyin'],
			'translation' => 'no' !== $atts['translation'],
		);

		$preset_result = null;
		if ( '' !== $preset_text ) {
			$cached = $this->cache->get( $preset_text, $this->provider );
			if ( false !== $cached ) {
				$preset_result = $cached;
			}
		}

		return ELTMH_Admin::widget_html( $preset_text, $preset_result, false, $display );
	}
}
