<?php
/**
 * Front-end widget injection. Adds the Aetheris widget script via
 * wp_enqueue_script() when the plugin is enabled and a public_key is configured.
 *
 * @package AetherisAIChat
 */

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

final class Aetheris_AI_Chat_Embed {

	const HANDLE = 'aetheris-ai-chat-widget';

	public static function init() {
		add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_widget' ), 99 );
		add_filter( 'script_loader_tag', array( __CLASS__, 'tag_attributes' ), 10, 2 );
	}

	public static function enqueue_widget() {
		$settings = Aetheris_AI_Chat_Settings::get();

		if ( empty( $settings['enabled'] ) ) {
			return;
		}
		if ( empty( $settings['public_key'] ) ) {
			return;
		}

		// Honour load_on rules. wp_enqueue_scripts already skips admin, but we
		// still gate feeds/robots/trackbacks here for callers that re-route the
		// hook.
		if ( 'front_only' === $settings['load_on'] && ( is_feed() || is_robots() || is_trackback() ) ) {
			return;
		}

		/**
		 * Last-chance gate so site builders can hide the widget per-route.
		 *
		 * @param bool  $should_load
		 * @param array $settings
		 */
		$should_load = apply_filters( 'aetheris_ai_chat_should_load', true, $settings );
		if ( ! $should_load ) {
			return;
		}

		$widget_url = add_query_arg(
			array( 'client' => $settings['public_key'] ),
			$settings['widget_src']
		);

		// Surface customer-facing config to the widget. The widget reads
		// window.__AETHERIS_API__ and window.AetherisChatConfig at boot.
		$config = array(
			'apiBase'    => $settings['api_base'],
			'position'   => $settings['position'],
			'whiteLabel' => (bool) $settings['white_label'],
			'source'     => 'wordpress',
		);

		wp_register_script(
			self::HANDLE,
			$widget_url,
			array(),
			AETHERIS_AI_CHAT_VERSION,
			true
		);

		wp_add_inline_script(
			self::HANDLE,
			'window.__AETHERIS_API__ = ' . wp_json_encode( $settings['api_base'] ) . ';' .
			'window.AetherisChatConfig = ' . wp_json_encode( $config ) . ';',
			'before'
		);

		wp_enqueue_script( self::HANDLE );
	}

	/**
	 * Add async + provenance attributes to the enqueued widget script tag.
	 * Kept as a filter so we don't fight WP's tag rendering pipeline.
	 */
	public static function tag_attributes( $tag, $handle ) {
		if ( self::HANDLE !== $handle ) {
			return $tag;
		}
		if ( false !== strpos( $tag, ' async' ) ) {
			return str_replace( '<script ', '<script data-aetheris-source="wordpress" ', $tag );
		}
		return str_replace( '<script ', '<script async data-aetheris-source="wordpress" ', $tag );
	}
}
