<?php
namespace WpRigel\Commandify;

defined( 'ABSPATH' ) || exit;

class Assets {

	public static function init() {
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
		add_action( 'admin_footer', array( __CLASS__, 'render_root' ) );
	}

	public static function enqueue_assets() {
		if ( ! commandify_is_enabled() ) {
			return;
		}

		$asset_file = COMMANDIFY_PATH . 'assets/build/index.asset.php';

		// Check if build exists.
		if ( ! file_exists( $asset_file ) ) {
			return;
		}

		$asset = require $asset_file;

		// Enqueue script.
		wp_enqueue_script(
			'commandify',
			COMMANDIFY_URL . 'assets/build/index.js',
			$asset['dependencies'],
			$asset['version'],
			true
		);

		// Enqueue styles.
		if ( file_exists( COMMANDIFY_PATH . 'assets/build/index.css' ) ) {
			wp_enqueue_style(
				'commandify',
				COMMANDIFY_URL . 'assets/build/index.css',
				array(),
				$asset['version']
			);
		}

		// Get user preferences.
		$preferences = Settings::get_effective_preferences();

		// Get current screen with action detection.
		$current_screen = get_current_screen();
		$screen_id      = $current_screen ? $current_screen->id : '';

		// Differentiate between new and edit screens.
		global $pagenow;

		// For edit screens, check if we have a post ID.
		$post_id = filter_input( INPUT_GET, 'post', FILTER_VALIDATE_INT ) ?: 0;

		// Determine if this is a post-type screen (post, page, custom post type).
		$is_post_type_screen = $current_screen && 'post' === $current_screen->base;

		// Build more specific screen context.
		if ( $is_post_type_screen ) {
			if ( 'post-new.php' === $pagenow || 0 === $post_id ) {
				// New post screen: append '-new' to screen ID.
				$screen_id = $screen_id . '-new';
			} elseif ( 0 < $post_id ) {
				// Edit post screen with post ID: append '-edit'.
				$screen_id = $screen_id . '-edit';
			}
		}

		// Detect if we're in the block editor.
		$is_block_editor = false;
		if ( $current_screen && method_exists( $current_screen, 'is_block_editor' ) ) {
			$is_block_editor = $current_screen->is_block_editor();
		}

		// Get all commands filtered by capability.
		$commands = Registry::get_instance()->get_commands();

		// Allow Pro features to enrich commands (add metadata, state, etc.)
		$commands = apply_filters( 'commandify_get_commands', $commands );

		wp_localize_script(
			'commandify',
			'commandifyData',
			array(
				'nonce'         => wp_create_nonce( 'wp_rest' ),
				'apiUrl'        => rest_url( 'commandify/v1' ),
				'userId'        => get_current_user_id(),
				'isRTL'         => is_rtl(),
				'preferences'   => $preferences,
				'currentScreen' => $screen_id,
				'postId'        => $post_id,
				'isBlockEditor' => $is_block_editor,
				'commands'      => $commands,
			)
		);
	}

	public static function render_root() {
		if ( ! commandify_is_enabled() ) {
			return;
		}

		echo '<div id="commandify-root"></div>';
	}
}
