<?php

namespace EasyCriticalCSS;

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

class Gutenberg {
	public static function init() {
		add_action( 'enqueue_block_editor_assets', [ __CLASS__, 'enqueue_gutenberg_assets' ] );
	}

	public static function enqueue_gutenberg_assets() {
		global $post;

		wp_enqueue_script(
			'ecc-gutenberg-sidebar',
			plugin_dir_url( __DIR__ ) . 'build/index.js',
			[ 'wp-plugins', 'wp-edit-post', 'wp-components', 'wp-data', 'wp-api-fetch', 'wp-element' ],
			filemtime( plugin_dir_path( __DIR__ ) . 'build/index.js' ),
			true
		);

		$post_url     = ! empty( $post->ID ) ? get_permalink( $post->ID ) : '';
		$current_user = wp_get_current_user();
		$user_email   = $current_user->user_email ? $current_user->user_email : '';

		wp_localize_script(
			'ecc-gutenberg-sidebar',
			'eccSettings',
			[
				'settingsSchema'    => Individual_Settings::get_settings_schema(),
				'settings'          => ! empty( $post->ID ) ? Individual_Settings::get_settings( $post->ID ) : [],
				'mode'              => Settings::get_global_mode(),
				'secondaryBehavior' => Settings::get_global_secondary_behavior(),
				'pluginVersion'     => Plugin::get_plugin_version(),
				'postUrl'           => $post_url,
				'userEmail'         => $user_email,
			]
		);
	}
}
