<?php

namespace SoftminalB2B\Storefront;

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

use SoftminalB2B\Vite\Vite;

/**
 * Loads the block-editor script that registers the plugin's dynamic blocks on
 * the client (see resources/storefront/blocks-editor.js).
 *
 * The blocks are registered server-side in each feature class (with a
 * render_callback for the front end), but the inserter is populated from
 * client-side registrations — so without this script the blocks never appear
 * when searching the inserter.
 */
class BlockEditor
{
    private static bool $registered = false;

    public static function init(): void
    {
        if (self::$registered) {
            return;
        }

        self::$registered = true;

        add_action('enqueue_block_editor_assets', [self::class, 'enqueue']);
    }

    public static function enqueue(): void
    {
        // wp_enqueue_scripts (where the storefront configures Vite) does not run
        // in the block editor, so configure it here before enqueuing.
        Vite::configure([
            'devServerUrl' => apply_filters('smb2b_vite_dev_server_url', BulkOrderForm::devServerUrl()),
            'pluginDir'    => SMB2B_DIR,
            'pluginUrl'    => SMB2B_URL,
            'version'      => SMB2B_VERSION,
        ]);

        $enqueued = Vite::enqueueAsset(
            'smb2b-blocks-editor',
            'resources/storefront/blocks-editor.js',
            ['wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n'],
            true
        );

        if ($enqueued) {
            // The bulk-order block's inspector + preview need the category list
            // and the store currency symbol.
            Vite::localize('smb2b-blocks-editor', 'smb2bBlocks', [
                'categories'     => BulkOrderForm::productCategories(),
                'currencySymbol' => function_exists('get_woocommerce_currency_symbol')
                    ? html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8')
                    : '',
            ]);
        }
    }
}
