{% import '_includes/forms.twig' as forms %}
{% import 'codeeditor/codeEditor.twig' as codeEditor %}

{% set baseMonacoOptions = {
  tabSize: 2,
  showUnused: false,
} %}

{% set baseCodeEditorOptions = {
  wrapperClass: 'monaco-editor-background-frame',
} %}

{% if ckeConfig.uid %}
  {{ hiddenInput('uid', ckeConfig.uid) }}
{% endif %}

{{ forms.textField({
  first: true,
  label: 'Name'|t('app'),
  id: 'name',
  name: 'name',
  value: ckeConfig.name,
  errors: ckeConfig.getErrors('name'),
  autofocus: true,
  required: true,
}) }}

{% embed '_includes/forms/field.twig' with {
  label: 'Toolbar'|t('ckeditor'),
  instructions: 'Drag toolbar items into the editor.'|t('ckeditor'),
  id: 'toolbar',
  errors: ckeConfig.getErrors('toolbar'),
  ckeConfig: ckeConfig,
} %}
  {% block input %}
    <div id="toolbar-builder" class="ckeditor-tb pane">
      <div class="ck ck-reset_all">
        <div class="ckeditor-tb--items ckeditor-tb--source ck ck-reset ck-editor ck-rounded-corners">
          <div class="ck ck-toolbar">
            <div class="ck ck-toolbar__items"></div>
          </div>
        </div>

        <div class="ckeditor-tb--items ckeditor-tb--target ck ck-reset ck-editor ck-rounded-corners">
          <div class="ck ck-editor__top">
            <div class="ck ck-toolbar">
              <div class="ck ck-toolbar__items"></div>
            </div>
          </div>
          <div class="ck ck-editor__main">
            <div class="ck ck-content ck-editor__editable ck-editor__editable_inline"></div>
          </div>
        </div>
      </div>

      {{ hiddenInput('toolbar', ckeConfig.toolbar|json_encode) }}
    </div>
  {% endblock %}
{% endembed %}

{{ forms.checkboxSelectField({
  label: 'Heading Levels'|t('ckeditor'),
  instructions: 'Choose which heading levels should be available to fields.'|t('ckeditor'),
  id: 'heading-levels',
  name: 'headingLevels',
  options: [
    {label: 'Heading {level}'|t('ckeditor', {level: 1}), value: '1'},
    {label: 'Heading {level}'|t('ckeditor', {level: 2}), value: '2'},
    {label: 'Heading {level}'|t('ckeditor', {level: 3}), value: '3'},
    {label: 'Heading {level}'|t('ckeditor', {level: 4}), value: '4'},
    {label: 'Heading {level}'|t('ckeditor', {level: 5}), value: '5'},
    {label: 'Heading {level}'|t('ckeditor', {level: 6}), value: '6'},
  ],
  values: ckeConfig.headingLevels,
}) }}

{% embed '_includes/forms/field.twig' with {
  label: 'Config Options'|t('ckeditor'),
  instructions: 'Define custom [config options]({link}) which should be merged with the default config.'|t('ckeditor', {
    link: 'https://ckeditor.com/docs/ckeditor5/latest/api/module_core_editor_editorconfig-EditorConfig.html',
  }),
  id: 'config-options',
  errors: ckeConfig.getErrors('json')|merge(ckeConfig.getErrors('js')),
  ckeConfig: ckeConfig,
} %}
  {% block input %}
    {% import 'codeeditor/codeEditor.twig' as codeEditor %}
    {% set lang = ckeConfig.js ? 'js' : 'json' %}
    {% set isJson = lang == 'json' %}
    {% set isJs = lang == 'js' %}

    <div id="config-options">
      <section class="btngroup btngroup--exclusive small" aria-label="{{ 'Config option code language options' }}">
        {{ tag('button', {
          type: 'button',
          class: ['btn', 'small', isJson ? 'active']|filter,
          aria: {pressed: isJson ? 'true'}|filter,
          data: {language: 'json'},
          text: 'JSON',
        }) }}
        {{ tag('button', {
          type: 'button',
          class: ['btn', 'small', isJs ? 'active' : null]|filter,
          aria: {pressed: isJs ? 'true'}|filter,
          data: {language: 'js'},
          text: 'JavaScript',
        }) }}
      </section>
    </div>

    {% tag 'div' with {
      id: 'config-options-json-container',
      class: not isJson ? 'hidden' : null
    } %}
      {{ codeEditor.textarea(
        {
          id: 'config-options-json',
          name: 'json',
          value: isJson ? (ckeConfig.json ?? "{\n  \n}"),
        },
        'ckeditor:EditorConfigJson',
        baseMonacoOptions|merge({
          language: 'json',
        }),
        baseCodeEditorOptions|push(ckeConfig.hasErrors('json') ? 'has-errors'),
      ) }}
    {% endtag %}

    {% tag 'div' with {
      id: 'config-options-js-container',
      class: not isJs ? 'hidden' : null
    } %}
      {{ codeEditor.textarea(
        {
          id: 'config-options-js',
          name: 'js',
          value: isJs ? (ckeConfig.js ?? "return {\n  \n}"),
        },
        'ckeditor:EditorConfigJs',
        baseMonacoOptions|merge({
          language: 'javascript',
        }),
        baseCodeEditorOptions,
      ) }}
      {% endtag %}
  {% endblock %}
{% endembed %}

{% js %}
(() => {
  // Register the config options JSON schema
  const jsonSchemaUri = {{ jsonSchemaUri|json_encode|raw }};
  const schema = JSON.parse(
    JSON.stringify({{ jsonSchema|json_encode|raw }})
      .replace(
        new RegExp(Craft.escapeRegex(JSON.stringify('__PLUGIN_LIST__')), 'g'),
        JSON.stringify(CKEditor5.craftcms.pluginNames())
      )
  );

  monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
    validate: true,
    schemas: [
      {
        uri: jsonSchemaUri,
        fileMatch: [jsonSchemaUri],
        schema: schema,
      },
    ],
  });
})()
{% endjs %}

{{ codeEditor.textareaField(
  {
    label: 'Custom Styles'|t('ckeditor'),
    instructions: 'Define CSS styles that should be registered for editors, such as [style classes]({url}).'|t('ckeditor', {
    url: 'https://ckeditor.com/docs/ckeditor5/latest/features/style.html',
  }),
    id: 'css',
    name: 'css',
    value: ckeConfig.css,
  },
  'CodeEditor',
  baseMonacoOptions|merge({
    language: 'css',
  }),
  baseCodeEditorOptions,
) }}
