<?php
/**
 * Asset Enqueuing Service
 *
 * Handles WordPress asset enqueuing for plugin pages.
 *
 * @package AIPT\Core\Services
 * @since 2.4.0
 */

namespace AIPT\Core\Services;

use AIPT\Core\Init;

/**
 * Handles asset enqueuing logic
 *
 * @internal Used by Init
 */
class AssetEnqueuer {

	/**
	 * Init instance
	 *
	 * @var Init
	 */
	private $init;

	/**
	 * Localization data builder instance
	 *
	 * @var LocalizationDataBuilder
	 */
	private $data_builder;

	/**
	 * Constructor
	 *
	 * @param Init                      $init Init instance.
	 * @param LocalizationDataBuilder $data_builder Localization data builder.
	 */
	public function __construct( Init $init, LocalizationDataBuilder $data_builder ) {
		$this->init         = $init;
		$this->data_builder = $data_builder;
	}

	/**
	 * Set script translations for a given script handle.
	 *
	 * Enables JavaScript i18n via @wordpress/i18n for the specified script.
	 *
	 * @since 2.5.12
	 * @param string $handle Script handle to set translations for.
	 */
	private function set_script_translations( string $handle ): void {
		wp_set_script_translations(
			$handle,
			'ai-product-tools',
			AIPT_PLUGIN_DIR . 'languages'
		);
	}

	/**
	 * Enqueue assets for hook
	 *
	 * @param string $hook WordPress hook name.
	 */
	public function enqueueForHook( string $hook ): void {

		$screen = get_current_screen();

		$is_plugin_page = (
			'toplevel_page_ai-product-tools' === $hook ||
			strpos( $hook, 'page_aipt-' ) !== false ||
			( 'post.php' === $hook || 'post-new.php' === $hook ) && $screen && $screen->post_type === 'product'
		);

		if ( ! $is_plugin_page ) {
			return;
		}

		$this->enqueueBaseAssets( $hook );

		$this->enqueueNotificationManager();

		$this->enqueueMetaboxAssets( $hook, $screen );
		$this->enqueueSettingsAssets( $hook, $screen );
		$this->enqueueToolkitAssets( $hook, $screen );
		$this->enqueueDescriptionGeneratorAssets( $hook );
		$this->enqueueStandardGeneratorAssets( $hook );
		$this->enqueueFaqGeneratorAssets( $hook );
		$this->enqueueTitleGeneratorAssets( $hook );
		$this->enqueueAutomationJobsAssets( $hook );
		$this->enqueueStoreIndexAssets( $hook );
		$this->enqueueChatbotAdminAssets( $hook );
		$this->enqueueSeoMetaGeneratorAssets( $hook );
		$this->enqueueTaxonomyGeneratorAssets( $hook );
		$this->enqueueImageAltGeneratorAssets( $hook );
	}

	/**
	 * Enqueue base assets (vendors, commons, main styles)
	 *
	 * Main styles are always loaded - Freemius opt-in isolation is handled
	 * via CSS rules (all: revert) in tailwind.css instead of PHP gating.
	 *
	 * @param string $hook WordPress hook name.
	 */
	private function enqueueBaseAssets( string $hook ): void {

		if ( 'toplevel_page_ai-product-tools' === $hook ||
			strpos( $hook, 'page_aipt-advanced-bulk-generator' ) !== false ||
			strpos( $hook, 'page_aipt-standard-bulk-generator' ) !== false ||
			strpos( $hook, 'page_aipt-title-generator' ) !== false ||
			strpos( $hook, 'page_aipt-faq-generator' ) !== false ) {
			if ( function_exists( 'wp_enqueue_editor' ) ) {
				wp_enqueue_editor();
				wp_enqueue_media();
			}
		}

		if ( strpos( $hook, 'page_aipt-chatbot' ) !== false ) {
			wp_enqueue_media();
		}

		wp_enqueue_style(
			'aipt-google-fonts',
			'https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500;1,600;1,700&display=swap',
			array(),
			null
		);

		wp_enqueue_style(
			'aipt-main-styles',
			AIPT_PLUGIN_URL . $this->init->get_asset_path( 'css/commons.css' ),
			array( 'aipt-google-fonts' ),
			AIPT_VERSION
		);

		$vendor_js = $this->init->get_asset_path( 'js/vendors.js' );
		if ( $vendor_js ) {
			wp_enqueue_script(
				'aipt-vendors',
				AIPT_PLUGIN_URL . $vendor_js,
				array(),
				AIPT_VERSION,
				true
			);
		}

		$commons_js = $this->init->get_asset_path( 'js/commons.js' );
		if ( $commons_js ) {
			wp_enqueue_script(
				'aipt-commons',
				AIPT_PLUGIN_URL . $commons_js,
				array( 'aipt-vendors', 'wp-i18n' ),
				AIPT_VERSION,
				true
			);
			$this->set_script_translations( 'aipt-commons' );
		}
	}

	/**
	 * Enqueue notification manager assets
	 */
	private function enqueueNotificationManager(): void {

		$this->init->enqueue_virtual_style(
			'aipt-notification-manager',
			array( 'aipt-main-styles' )
		);

		wp_enqueue_script(
			'aipt-notification-manager',
			AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/notification-manager.js' ),
			array( 'aipt-commons', 'wp-element', 'wp-i18n' ),
			AIPT_VERSION,
			true
		);
		$this->set_script_translations( 'aipt-notification-manager' );
	}

	/**
	 * Enqueue metabox assets
	 *
	 * @param string $hook   WordPress hook name.
	 * @param object $screen Current screen object.
	 */
	private function enqueueMetaboxAssets( string $hook, $screen ): void {
		if ( 'post.php' === $hook || 'post-new.php' === $hook ) {
			if ( $screen && $screen->post_type === 'product' ) {
				$this->init->enqueue_virtual_style(
					'aipt-metabox',
					array( 'aipt-main-styles' )
				);

			wp_enqueue_script(
				'aipt-metabox',
				AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/metabox.js' ),
				array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
				AIPT_VERSION,
				true
			);
			$this->set_script_translations( 'aipt-metabox' );

				$metabox_data = $this->data_builder->buildMetaboxData();
				wp_localize_script( 'aipt-metabox', 'aiptData', $metabox_data );

				$prompts = $metabox_data;
				wp_add_inline_script(
					'aipt-metabox',
					'window.aipt = {
                    system_prompt: "' . esc_js( $prompts['system_prompt'] ) . '",
                    user_prompt: "' . esc_js( $prompts['user_prompt'] ) . '",
                    short_system_prompt: "' . esc_js( $prompts['short_system_prompt'] ) . '",
                    short_user_prompt: "' . esc_js( $prompts['short_user_prompt'] ) . '",
                    full_system_prompt: "' . esc_js( $prompts['full_system_prompt'] ) . '",
                    full_user_prompt: "' . esc_js( $prompts['full_user_prompt'] ) . '"
                };',
					'before'
				);
			}
		}
	}

	/**
	 * Enqueue settings page assets
	 *
	 * @param string $hook   WordPress hook name.
	 * @param object $screen Current screen object.
	 */
	private function enqueueSettingsAssets( string $hook, $screen ): void {
		if ( $screen && ( strpos( $hook, '_page_aipt-settings' ) !== false ) ) {

			$this->init->enqueue_virtual_style(
				'aipt-settings',
				array( 'aipt-main-styles' )
			);

			wp_enqueue_script(
				'aipt-settings',
				AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/settings.js' ),
				array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
				AIPT_VERSION,
				true
			);
			$this->set_script_translations( 'aipt-settings' );

			$settings_data = $this->data_builder->buildSettingsData();
			wp_localize_script( 'aipt-settings', 'aiptData', $settings_data );
		}
	}

	/**
	 * Enqueue toolkit page assets
	 *
	 * @param string $hook   WordPress hook name.
	 * @param object $screen Current screen object.
	 */
	private function enqueueToolkitAssets( string $hook, $screen ): void {
		if ( 'toplevel_page_ai-product-tools' === $hook && ( ! $screen || $screen->id === 'toplevel_page_ai-product-tools' ) ) {

			$toolkit_css = $this->init->get_asset_path( 'css/toolkit.css' );
			if ( file_exists( AIPT_PLUGIN_DIR . $toolkit_css ) ) {
				wp_enqueue_style(
					'aipt-toolkit',
					AIPT_PLUGIN_URL . $toolkit_css,
					array( 'aipt-main-styles' ),
					AIPT_VERSION
				);
			} else {
				$this->init->enqueue_virtual_style(
					'aipt-toolkit',
					array( 'aipt-main-styles' )
				);
			}

		wp_enqueue_script(
			'aipt-toolkit',
			AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/toolkit.js' ),
			array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
			AIPT_VERSION,
			true
		);
		$this->set_script_translations( 'aipt-toolkit' );

			$toolkit_data = $this->data_builder->buildToolkitData();
			wp_localize_script( 'aipt-toolkit', 'aiptData', $toolkit_data );
		}
	}

	/**
	 * Enqueue description generator assets
	 *
	 * @param string $hook WordPress hook name.
	 */
	private function enqueueDescriptionGeneratorAssets( string $hook ): void {
		if ( strpos( $hook, 'page_aipt-advanced-bulk-generator' ) !== false ) {
			$this->init->enqueue_virtual_style(
				'aipt-description-generator',
				array( 'aipt-main-styles' )
			);

		wp_enqueue_script(
			'aipt-description-generator',
			AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/description-generator.js' ),
			array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
			AIPT_VERSION,
			true
		);
		$this->set_script_translations( 'aipt-description-generator' );

			$desc_data = $this->data_builder->buildDescriptionGeneratorData();
			wp_localize_script( 'aipt-description-generator', 'aiptData', $desc_data );
		}
	}

	/**
	 * Enqueue standard generator assets
	 *
	 * @param string $hook WordPress hook name.
	 */
	private function enqueueStandardGeneratorAssets( string $hook ): void {
		if ( strpos( $hook, 'page_aipt-standard-bulk-generator' ) !== false ) {
			$this->init->enqueue_virtual_style(
				'aipt-standard-description-generator',
				array( 'aipt-main-styles' )
			);

		wp_enqueue_script(
			'aipt-standard-description-generator',
			AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/standard-description-generator.js' ),
			array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
			AIPT_VERSION,
			true
		);
		$this->set_script_translations( 'aipt-standard-description-generator' );

			$std_data = $this->data_builder->buildStandardGeneratorData();
			wp_localize_script( 'aipt-standard-description-generator', 'aiptData', $std_data );
		}
	}

	/**
	 * Enqueue FAQ generator assets
	 *
	 * @param string $hook WordPress hook name.
	 */
	private function enqueueFaqGeneratorAssets( string $hook ): void {
		if ( strpos( $hook, 'page_aipt-faq-generator' ) !== false ) {
			$this->init->enqueue_virtual_style(
				'aipt-faq-generator',
				array( 'aipt-main-styles' )
			);

			wp_enqueue_style(
				'aipt-faq-display',
				AIPT_PLUGIN_URL . 'dist/css/faq-display.css',
				array(),
				AIPT_VERSION
			);

		wp_enqueue_script(
			'aipt-faq-generator',
			AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/faq-generator.js' ),
			array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
			AIPT_VERSION,
			true
		);
		$this->set_script_translations( 'aipt-faq-generator' );

			$faq_data = $this->data_builder->buildFAQGeneratorData();
			wp_localize_script( 'aipt-faq-generator', 'aiptData', $faq_data );
		}
	}

	/**
	 * Enqueue title generator assets
	 *
	 * @param string $hook WordPress hook name.
	 */
	private function enqueueTitleGeneratorAssets( string $hook ): void {
		if ( strpos( $hook, 'page_aipt-title-generator' ) !== false ) {
			$this->init->enqueue_virtual_style(
				'aipt-title-generator',
				array( 'aipt-main-styles' )
			);

		wp_enqueue_script(
			'aipt-title-generator',
			AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/title-generator.js' ),
			array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
			AIPT_VERSION,
			true
		);
		$this->set_script_translations( 'aipt-title-generator' );

			$title_data = $this->data_builder->buildTitleGeneratorData();
			wp_localize_script( 'aipt-title-generator', 'aiptData', $title_data );
		}
	}

	/**
	 * Enqueue automation jobs assets
	 *
	 * @param string $hook WordPress hook name.
	 */
	private function enqueueAutomationJobsAssets( string $hook ): void {
		if ( strpos( $hook, 'page_aipt-automation-jobs' ) !== false ) {
			$this->init->enqueue_virtual_style(
				'aipt-automation-jobs',
				array( 'aipt-main-styles' )
			);

		wp_enqueue_script(
			'aipt-automation-jobs',
			AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/automation-jobs.js' ),
			array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
			AIPT_VERSION,
			true
		);
		$this->set_script_translations( 'aipt-automation-jobs' );

			$jobs_data = $this->data_builder->buildAutomationJobsData();
			wp_localize_script( 'aipt-automation-jobs', 'aiptData', $jobs_data );
		}
	}

	/**
	 * Enqueue AI Store Index assets
	 *
	 * @param string $hook WordPress hook name.
	 */
	private function enqueueStoreIndexAssets( string $hook ): void {
		if ( strpos( $hook, 'page_aipt-store-index' ) !== false ) {
			$this->init->enqueue_virtual_style(
				'aipt-store-index',
				array( 'aipt-main-styles' )
			);

		wp_enqueue_script(
			'aipt-store-index',
			AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/store-index.js' ),
			array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
			AIPT_VERSION,
			true
		);
		$this->set_script_translations( 'aipt-store-index' );

			$index_data = $this->data_builder->buildStoreIndexData();
			wp_localize_script( 'aipt-store-index', 'aiptData', $index_data );
		}
	}

	/**
	 * Enqueue AI Shop Assistant admin assets
	 *
	 * @param string $hook WordPress hook name.
	 */
	private function enqueueChatbotAdminAssets( string $hook ): void {
		if ( strpos( $hook, 'page_aipt-chatbot' ) !== false ) {
			$this->init->enqueue_virtual_style(
				'aipt-chatbot-admin',
				array( 'aipt-main-styles' )
			);

		wp_enqueue_script(
			'aipt-chatbot-admin',
			AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/chatbot-admin.js' ),
			array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
			AIPT_VERSION,
			true
		);
		$this->set_script_translations( 'aipt-chatbot-admin' );

			$chatbot_data = $this->data_builder->buildChatbotAdminData();
			wp_localize_script( 'aipt-chatbot-admin', 'aiptChatbotAdminData', $chatbot_data );
		}
	}

	/**
	 * Enqueue SEO Meta Generator assets
	 *
	 * @param string $hook WordPress hook name.
	 */
	private function enqueueSeoMetaGeneratorAssets( string $hook ): void {
		if ( strpos( $hook, 'page_aipt-seo-meta-generator' ) !== false ) {
			$this->init->enqueue_virtual_style(
				'aipt-seo-meta-generator',
				array( 'aipt-main-styles' )
			);

		wp_enqueue_script(
			'aipt-seo-meta-generator',
			AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/seo-meta-generator.js' ),
			array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
			AIPT_VERSION,
			true
		);
		$this->set_script_translations( 'aipt-seo-meta-generator' );

			$seo_data = $this->data_builder->buildSeoMetaGeneratorData();
			wp_localize_script( 'aipt-seo-meta-generator', 'aiptData', $seo_data );
		}
	}

	/**
	 * Enqueue Image Alt Text Generator admin assets.
	 *
	 * Loads the virtual stylesheet and JS bundle plus its localised aiptData
	 * payload when the current admin page hook matches the Image Alt
	 * Generator slug.
	 *
	 * @since 2.6.0
	 *
	 * @param string $hook Current admin page hook suffix.
	 * @return void
	 */
	private function enqueueImageAltGeneratorAssets( string $hook ): void {
		if ( strpos( $hook, 'page_aipt-image-alt' ) !== false ) {
			$this->init->enqueue_virtual_style(
				'aipt-image-alt-generator',
				array( 'aipt-main-styles' )
			);

			wp_enqueue_script(
				'aipt-image-alt-generator',
				AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/image-alt-generator.js' ),
				array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
				AIPT_VERSION,
				true
			);
			$this->set_script_translations( 'aipt-image-alt-generator' );

			$data = $this->data_builder->buildImageAltGeneratorData();
			wp_localize_script( 'aipt-image-alt-generator', 'aiptData', $data );
		}
	}

	private function enqueueTaxonomyGeneratorAssets( string $hook ): void {
		if ( strpos( $hook, 'page_aipt-taxonomy-generator' ) !== false ) {
			$this->init->enqueue_virtual_style(
				'aipt-taxonomy-generator',
				array( 'aipt-main-styles' )
			);

		wp_enqueue_script(
			'aipt-taxonomy-generator',
			AIPT_PLUGIN_URL . $this->init->get_asset_path( 'js/taxonomy-generator.js' ),
			array( 'aipt-commons', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'aipt-notification-manager' ),
			AIPT_VERSION,
			true
		);
		$this->set_script_translations( 'aipt-taxonomy-generator' );

			$taxonomy_data = $this->data_builder->buildTaxonomyGeneratorData();
			wp_localize_script( 'aipt-taxonomy-generator', 'aiptData', $taxonomy_data );
		}
	}

	/**
	 * Enqueue AI Shop Assistant widget assets for frontend
	 *
	 * @since 2.5.0
	 */
	public function enqueueChatbotWidgetAssets(): void {

		$settings = get_option( 'aipt_chatbot_settings', array() );
		$is_enabled = isset( $settings['general']['enabled'] ) ? (bool) $settings['general']['enabled'] : false;

		if ( ! $is_enabled ) {
			return;
		}

		if ( ! $this->init->should_show_chatbot_on_page( $settings ) ) {
			return;
		}

		$css_path = $this->init->get_asset_path( 'css/chatbot-widget.css' );
		if ( $css_path ) {
			wp_enqueue_style(
				'aipt-chatbot-widget',
				AIPT_PLUGIN_URL . $css_path,
				array(),
				AIPT_VERSION
			);
		}

		$js_path = $this->init->get_asset_path( 'js/chatbot-widget.js' );
		if ( $js_path ) {
			wp_enqueue_script(
				'aipt-chatbot-widget',
				AIPT_PLUGIN_URL . $js_path,
				array(),
				AIPT_VERSION,
				true
			);

			$widget_data = $this->data_builder->buildChatbotWidgetData();
			wp_localize_script( 'aipt-chatbot-widget', 'aiptChatbotWidgetData', $widget_data );
		}
	}

}
