<?php

namespace ModernFields\WordPress\Services;

defined('ABSPATH') || exit;

/**
 * Registers and enqueues the Modern Fields render API bundle (window.modernFieldsFree).
 *
 * The bundle exposes the field engine (FieldWrapper, useFieldValue, MetaContext,
 * registerFieldComponents) and the editor helpers (registerFieldBlockType,
 * BlockWrapper) so third-party field add-ons can build a field with the same
 * setup and settings UI as native fields. Add-ons declare the public handle
 * `RenderApiService::HANDLE` as a dependency of their block editorScript so the
 * global is guaranteed to exist before their code runs.
 *
 * Call RenderApiService::enqueue() from any Hook/UseCase that renders Modern
 * Fields blocks: the field group editor (block configuration) and the data-entry
 * screens (post, term, user, options…). Idempotent — safe to call repeatedly and
 * from both the free and premium plugins (same handle).
 *
 * @since 1.1.1
 */
class RenderApiService
{
  /**
   * Public script handle add-ons can declare as a dependency.
   *
   * @since 1.1.1
   * @var string
   */
  public const HANDLE = 'modern-fields-render-api';

  /**
   * Registers (idempotently) and enqueues the render API bundle.
   *
   * @since 1.1.1
   * @return void
   */
  public static function enqueue(): void
  {
    if (wp_script_is(self::HANDLE, 'enqueued')) {
      return;
    }

    $asset_path = MODERN_FIELDS_PLUGIN_DIR . 'build/render-api/index.asset.php';

    if (!file_exists($asset_path)) {
      return;
    }

    $asset = require $asset_path;

    wp_enqueue_script(
      self::HANDLE,
      MODERN_FIELDS_PLUGIN_URL . 'build/render-api/index.js',
      $asset['dependencies'],
      $asset['version'],
      true
    );

    wp_set_script_translations(self::HANDLE, 'modern-fields');
  }
}
