<?php

add_action('acf/input/admin_enqueue_scripts', function () {
    $screen = function_exists('get_current_screen') ? get_current_screen() : null;

    if (!$screen || !str_contains((string) $screen->id, 'theme-options-scripts')) {
        return;
    }

    $settings = wp_enqueue_code_editor([
        'type' => 'text/html',
        'codemirror' => [
            'indentUnit'  => 2,
            'tabSize'     => 2,
            'lineNumbers' => true,
            'lineWrapping' => true,
        ],
    ]);

    if (false === $settings) {
        return;
    }

    wp_enqueue_script('jquery');
    wp_enqueue_script('wp-theme-plugin-editor');
    wp_enqueue_style('wp-codemirror');

    wp_add_inline_script(
        'wp-theme-plugin-editor',
        sprintf(
            '(function($){
                $(function(){
                    $(".codelibry-code-field textarea").each(function(){
                        wp.codeEditor.initialize(this, %s);
                    });
                });
            })(jQuery);',
            wp_json_encode($settings)
        )
    );
});
