<?php
/**
 * Changeloger Block Assets
 *
 * Registers core block assets for the free plugin
 *
 * @package Changeloger
 */

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

/**
 * Class Changeloger_Block_Assets
 */
class Changeloger_Block_Assets {

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'enqueue_block_editor_assets', [ $this, 'register_editor_assets' ] );
		add_action( 'enqueue_block_assets', [ $this, 'register_block_assets' ] );
	}

	/**
	 * Register block editor assets
	 */
	public function register_editor_assets() {
		wp_register_style(
			'changeloger',
			plugins_url( 'build/changeloger/style-index.css', dirname( __FILE__ ) ),
			[],
			CHANGELOGER_VERSION
		);

		wp_register_style(
			'tabbed-changeloger',
			plugins_url( 'build/tabbed-changeloger/style-index.css', dirname( __FILE__ ) ),
			[],
			CHANGELOGER_VERSION
		);

		// Auto-insert block when redirected from "Add Block to Page" buttons.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! empty( $_GET['cha_add_block'] ) ) {
			$block_name = sanitize_text_field( wp_unslash( $_GET['cha_add_block'] ) );

			wp_add_inline_script(
				'wp-block-editor',
				sprintf(
					'( function() {
						var blockSlug = %s;

						function tryInsertBlock() {
							/* Ensure the block type is registered first. */
							if ( ! wp.blocks.getBlockType( blockSlug ) ) {
								return false;
							}

							var blocks = wp.data.select( "core/block-editor" ).getBlocks();

							/* Only insert when the post is still empty. */
							if ( blocks.length > 0 ) {
								return true;
							}

							var block = wp.blocks.createBlock( blockSlug );
							if ( block ) {
								wp.data.dispatch( "core/block-editor" ).insertBlock( block );
							}

							return true;
						}

						wp.domReady( function() {
							/* Poll until the block type is available. */
							var poll = setInterval( function() {
								if ( tryInsertBlock() ) {
									clearInterval( poll );

									/* Clean up the URL parameter. */
									if ( window.history && window.history.replaceState ) {
										var url = new URL( window.location.href );
										url.searchParams.delete( "cha_add_block" );
										window.history.replaceState( {}, "", url.toString() );
									}
								}
							}, 200 );

							/* Safety: stop polling after 10 seconds. */
							setTimeout( function() { clearInterval( poll ); }, 10000 );
						} );
					} )();',
					wp_json_encode( 'cha/' . $block_name )
				)
			);
		}
	}

	/**
	 * Register frontend block assets
	 */
	public function register_block_assets() {
		global $post;

		// Tabbed changeloger frontend script
		wp_register_script(
			'tabbed-changeloger-frontend',
			plugins_url( 'assets/js/tabbed-frontend.js', CHANGELOGER_PLUGIN_FILE ),
			[ 'jquery' ],
			CHANGELOGER_VERSION,
			true
		);

		// Changeloger frontend script
		wp_register_script(
			'changeloger-frontend',
			plugins_url( 'assets/js/frontend.js', CHANGELOGER_PLUGIN_FILE ),
			[ 'jquery' ],
			CHANGELOGER_VERSION,
			true
		);

		// Release Hub frontend script
		wp_register_script(
			'cha-release-hub-js',
			plugins_url( 'assets/js/release-hub.js', CHANGELOGER_PLUGIN_FILE ),
			[],
			CHANGELOGER_VERSION,
			true
		);

		/**
		 * Action hook for pro plugin to register additional assets
		 * 
		 * Pro plugin can hook into this to register:
		 * - changeloger-filter (filter.js)
		 * - mark (jquery.mark.min.js)
		 * - cha-subscription (subscription.css + subscription.js)
		 */
		do_action( 'changeloger_register_block_assets' );

		// Localize script with common data
		$licensing = [ 'can_use_premium_code__premium_only' => function_exists( 'cha_fs' ) && cha_fs()->can_use_premium_code__premium_only() ];
		$data      = [
			'ajax_url'  => admin_url( 'admin-ajax.php' ),
			'nonce'     => wp_create_nonce( 'changeloger_nonce' ),
			'licensing' => $licensing['can_use_premium_code__premium_only'],
			'post_id'   => $post->ID ?? 0,
		];

		// Optimize: Only localize global jQuery in admin (editor).
		// On frontend, specific scripts are localized in their render callbacks when used.
		if ( is_admin() ) {
			wp_localize_script( 'jquery', 'changeloger_local_object', $data );
		}
	}

	/**
	 * Localize script with common data
	 *
	 * @param string $handle Script handle to localize.
	 */
	public static function localize_script( $handle ) {
		static $localized = [];

		if ( isset( $localized[ $handle ] ) ) {
			return;
		}

		global $post;

		$licensing = [ 'can_use_premium_code__premium_only' => function_exists( 'cha_fs' ) && cha_fs()->can_use_premium_code__premium_only() ];
		$data      = [
			'ajax_url'  => admin_url( 'admin-ajax.php' ),
			'nonce'     => wp_create_nonce( 'changeloger_nonce' ),
			'licensing' => $licensing['can_use_premium_code__premium_only'],
			'post_id'   => isset( $post->ID ) ? $post->ID : 0,
		];

		wp_localize_script( $handle, 'changeloger_local_object', $data );
		$localized[ $handle ] = true;
	}
}