<?php
/**
 * Frontend chat widget.
 *
 * @package Maca_Tjatt
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class Maca_Tjatt_Frontend
 */
class Maca_Tjatt_Frontend {

	/**
	 * @var bool
	 */
	private static $assets_enqueued = false;

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_shortcode( 'maca_tjatt', array( $this, 'render_shortcode' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'maybe_enqueue_floating' ) );
		add_action( 'wp_footer', array( $this, 'maybe_render_floating' ) );
		add_action( 'wp_ajax_maca_tjatt_ask', array( $this, 'ajax_ask' ) );
		add_action( 'wp_ajax_nopriv_maca_tjatt_ask', array( $this, 'ajax_ask' ) );
	}

	/**
	 * @return bool
	 */
	private function is_available() {
		return Maca_Tjatt_Service::is_enabled() && Maca_Tjatt_Service::is_ai_available();
	}

	/**
	 * Enqueue assets once.
	 */
	private function enqueue_assets() {
		if ( self::$assets_enqueued ) {
			return;
		}

		self::$assets_enqueued = true;

		wp_enqueue_style(
			'maca-tjatt',
			MACA_TJATT_PLUGIN_URL . 'assets/css/tjatt.css',
			array(),
			MACA_TJATT_VERSION
		);

		wp_add_inline_style(
			'maca-tjatt',
			sprintf(
				'.maca-tjatt { --maca-tjatt-toggle-bg: %1$s; --maca-tjatt-accent: %1$s; } .maca-tjatt--floating .maca-tjatt-toggle-avatar { %2$s }',
				esc_attr( Maca_Tjatt_Service::get_avatar_bg_color() ),
				esc_attr( Maca_Tjatt_Service::get_avatar_ring_style() )
			)
		);

		wp_enqueue_script(
			'maca-tjatt',
			MACA_TJATT_PLUGIN_URL . 'assets/js/tjatt.js',
			array(),
			MACA_TJATT_VERSION,
			true
		);

		wp_localize_script(
			'maca-tjatt',
			'macaTjatt',
			array_merge(
				array(
					'ajaxUrl' => admin_url( 'admin-ajax.php' ),
					'nonce'   => wp_create_nonce( 'maca_tjatt_ask' ),
				),
				Maca_Tjatt_Service::get_guest_ui_strings(),
				array(
					'assistantName' => Maca_Tjatt_Service::get_display_name(),
					'avatarUrl'     => Maca_Tjatt_Service::get_avatar_display_url(),
					'avatarBgColor' => Maca_Tjatt_Service::get_avatar_bg_color(),
				)
			)
		);
	}

	/**
	 * @param bool $floating Floating layout.
	 * @return string
	 */
	private function render_widget( $floating = false ) {
		if ( ! $this->is_available() ) {
			return '';
		}

		$this->enqueue_assets();

		$classes           = 'maca-tjatt';
		$display_name      = Maca_Tjatt_Service::get_display_name();
		$avatar_url        = Maca_Tjatt_Service::get_avatar_display_url();
		$avatar_bg_color   = Maca_Tjatt_Service::get_avatar_bg_color();
		$avatar_ring_style = Maca_Tjatt_Service::get_avatar_ring_style( $avatar_bg_color );
		$avatar_dimensions = Maca_Tjatt_Service::get_avatar_dimensions();
		$strings           = Maca_Tjatt_Service::get_guest_ui_strings();
		$widget_style      = sprintf( '--maca-tjatt-toggle-bg:%s;--maca-tjatt-accent:%s;', esc_attr( $avatar_bg_color ), esc_attr( $avatar_bg_color ) );

		$classes .= ' ' . Maca_Tjatt_Service::get_avatar_size_class();

		if ( $floating ) {
			$classes .= ' maca-tjatt--floating';
		}

		ob_start();
		?>
		<div class="<?php echo esc_attr( $classes ); ?>" data-maca-tjatt="1" data-maca-tjatt-bg="<?php echo esc_attr( $avatar_bg_color ); ?>" style="<?php echo esc_attr( $widget_style ); ?>">
			<?php if ( $floating ) : ?>
				<button type="button" class="maca-tjatt-toggle" aria-expanded="false" aria-controls="maca-tjatt-panel">
					<img class="maca-tjatt-toggle-avatar" src="<?php echo esc_url( $avatar_url ); ?>" alt="" width="<?php echo esc_attr( (string) $avatar_dimensions['toggle'] ); ?>" height="<?php echo esc_attr( (string) $avatar_dimensions['toggle'] ); ?>" decoding="async" style="<?php echo esc_attr( $avatar_ring_style ); ?>">
				</button>
			<?php endif; ?>
			<div class="maca-tjatt-panel" id="maca-tjatt-panel"<?php echo $floating ? ' hidden' : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static boolean HTML attribute. ?>>
				<div class="maca-tjatt-header">
					<div class="maca-tjatt-header-main">
						<img class="maca-tjatt-avatar" src="<?php echo esc_url( $avatar_url ); ?>" alt="" width="<?php echo esc_attr( (string) $avatar_dimensions['header'] ); ?>" height="<?php echo esc_attr( (string) $avatar_dimensions['header'] ); ?>">
						<strong class="maca-tjatt-title"><?php echo esc_html( $display_name ); ?></strong>
					</div>
					<?php if ( $floating ) : ?>
						<button type="button" class="maca-tjatt-close" aria-label="<?php echo esc_attr( $strings['close'] ); ?>">&times;</button>
					<?php endif; ?>
				</div>
				<div class="maca-tjatt-messages" role="log" aria-live="polite"></div>
				<form class="maca-tjatt-form">
					<label class="screen-reader-text" for="maca-tjatt-input"><?php echo esc_html( $strings['yourQuestion'] ); ?></label>
					<textarea id="maca-tjatt-input" class="maca-tjatt-input" rows="2" placeholder="<?php echo esc_attr( $strings['placeholder'] ); ?>"></textarea>
					<button type="submit" class="maca-tjatt-send"><?php echo esc_html( $strings['send'] ); ?></button>
				</form>
			</div>
		</div>
		<?php
		return (string) ob_get_clean();
	}

	/**
	 * @return string
	 */
	public function render_shortcode() {
		return $this->render_widget( false );
	}

	/**
	 * Enqueue assets when floating mode is on.
	 */
	public function maybe_enqueue_floating() {
		if ( ! $this->is_available() || is_admin() ) {
			return;
		}

		if ( '1' !== (string) get_option( 'maca_tjatt_floating', '1' ) ) {
			return;
		}

		$this->enqueue_assets();
	}

	/**
	 * Output floating widget in footer.
	 */
	public function maybe_render_floating() {
		if ( ! $this->is_available() || is_admin() ) {
			return;
		}

		if ( '1' !== (string) get_option( 'maca_tjatt_floating', '1' ) ) {
			return;
		}

		echo $this->render_widget( true ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}

	/**
	 * AJAX: ask the chatbot.
	 */
	public function ajax_ask() {
		check_ajax_referer( 'maca_tjatt_ask', 'nonce' );

		$question = isset( $_POST['question'] ) ? sanitize_text_field( wp_unslash( $_POST['question'] ) ) : '';
		$history = array();

		if ( isset( $_POST['history'] ) ) {
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized in parse_request_history().
			$history = Maca_Tjatt_Service::parse_request_history( wp_unslash( $_POST['history'] ) );
		}

		$result = Maca_Tjatt_Service::ask( $question, $history );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success( $result );
	}
}
