<?php

namespace ModernFields\WordPress\Hooks;

use ModernFields\WordPress\Interfaces\Hooks;
use ModernFields\WordPress\Services\RenderApiService;
use ModernFields\WordPress\Services\ScriptDataService;

defined('ABSPATH') || exit;

/**
 * Handles registration of the editor scripts.
 * 
 * This class is responsible for registering the editor scripts used by
 * the Modern Fields plugin to add custom panels to the block editor.
 * 
 * @package ModernFields
 * @since 1.0.0
 */
class EditorScripts implements Hooks
{

  public function registerHooks(): void
  {
    add_action('enqueue_block_editor_assets', [$this, 'enqueueSidebarAssets']);
  }

  /**
   * Enqueues assets for the custom editor scripts in the block editor.
   * 
   * Loads the custom sidebar JavaScript file that adds a custom panel
   * to the block editor.
   * 
   * @since 1.0.0
   * @return void
   */
  public function enqueueSidebarAssets()
  {
    if (get_current_screen()?->post_type !== MODERN_FIELDS_CPT_SLUG) {
      return;
    }

    # Path to the asset file containing dependencies and version info
    $file_path = MODERN_FIELDS_PLUGIN_DIR . 'build/group-settings/index.asset.php';

    # Exit if the asset file doesn't exist
    if (!file_exists($file_path)) {
      return;
    }

    # Load asset file to get dependencies and version
    $asset_file = include $file_path;

    # Enqueue the editor JavaScript file
    wp_enqueue_script(
      'mf-field-group-editor',
      MODERN_FIELDS_PLUGIN_URL . 'build/group-settings/index.js',
      $asset_file['dependencies'],
      $asset_file['version'],
      ['in_footer' => true]
    );

    wp_set_script_translations('mf-field-group-editor', 'modern-fields');

    # Expose window.modernFieldsFree (field engine + editor helpers) so third-party
    # field add-ons can register their block here with the same setup as native fields.
    RenderApiService::enqueue();

    ScriptDataService::enqueue([
      'onboardingDone' => (bool) get_option('modern_fields_onboarding_done', false),
    ]);
  }
}
