/**
 * @file
 * Modal management for EB UI module.
 *
 * Provides a reusable modal system for validation, preview, and import
 * dialogs. This module is used by both the YAML editor and grid-based
 * editors (eb_aggrid).
 */

((Drupal, drupalSettings) => {
  'use strict';

  /**
   * Initialize the ebUi namespace if not exists.
   */
  Drupal.ebUi = Drupal.ebUi || {};

  /**
   * Track created modals for cleanup.
   *
   * @type {Array}
   */
  Drupal.ebUi.modalIds = [];

  // ============================================
  // CORE MODAL SYSTEM
  // ============================================

  /**
   * Modal factory for creating consistent modal structures.
   *
   * @param {Object} config
   *   Modal configuration.
   * @param {string} config.id
   *   The modal element ID.
   * @param {string} config.title
   *   The modal title.
   * @param {string} config.dialogClass
   *   Optional additional dialog class.
   * @param {Array} config.footerButtons
   *   Array of button configurations.
   *
   * @return {HTMLElement}
   *   The modal element.
   */
  Drupal.ebUi.createModal = (config) => {
    const { createElement } = Drupal.ebUi;

    const modal = createElement('div', null, { id: config.id, class: 'eb-modal' });

    const backdrop = createElement('div', null, { class: 'eb-modal__backdrop' });
    modal.appendChild(backdrop);

    let dialogClass = 'eb-modal__dialog';
    if (config.dialogClass) {
      dialogClass += ` ${config.dialogClass}`;
    }
    const dialog = createElement('div', null, { class: dialogClass });

    // Header.
    const header = createElement('div', null, { class: 'eb-modal__header' });
    header.appendChild(createElement('h2', config.title, { class: 'eb-modal__title' }));
    const closeBtn = createElement('button', '\u00D7', {
      type: 'button',
      class: 'eb-modal__close',
      'aria-label': Drupal.t('Close')
    });
    header.appendChild(closeBtn);
    dialog.appendChild(header);

    // Content.
    const content = createElement('div', null, { class: 'eb-modal__content' });
    dialog.appendChild(content);

    // Footer.
    if (config.footerButtons?.length > 0) {
      const footer = createElement('div', null, { class: 'eb-modal__footer' });
      config.footerButtons.forEach((btnConfig) => {
        let btnClass = 'button';
        if (btnConfig.primary) {
          btnClass += ' button--primary';
        }
        if (btnConfig.class) {
          btnClass += ` ${btnConfig.class}`;
        }
        const btn = createElement('button', btnConfig.label, {
          type: 'button',
          class: btnClass
        });
        if (btnConfig.disabled) {
          btn.disabled = true;
        }
        footer.appendChild(btn);
      });
      dialog.appendChild(footer);
    }

    modal.appendChild(dialog);
    document.body.appendChild(modal);

    // Track for cleanup.
    Drupal.ebUi.modalIds.push(config.id);

    // Close event listeners.
    closeBtn.addEventListener('click', () => {
      Drupal.ebUi.closeModal(config.id);
    });
    backdrop.addEventListener('click', () => {
      Drupal.ebUi.closeModal(config.id);
    });

    return modal;
  };

  /**
   * Open a modal by ID, optionally creating it first if it doesn't exist.
   *
   * @param {string} modalId
   *   The modal element ID.
   * @param {Function} createFn
   *   Optional function to create the modal if it doesn't exist.
   */
  Drupal.ebUi.openModal = (modalId, createFn) => {
    let modal = document.getElementById(modalId);
    if (!modal && typeof createFn === 'function') {
      createFn();
      modal = document.getElementById(modalId);
    }
    if (modal) {
      modal.classList.add('eb-modal--open');
      document.body.classList.add('eb-modal-open');
    }
  };

  /**
   * Close a modal by ID.
   *
   * @param {string} modalId
   *   The modal element ID.
   */
  Drupal.ebUi.closeModal = (modalId) => {
    const modal = document.getElementById(modalId);
    if (modal) {
      modal.classList.remove('eb-modal--open');
      document.body.classList.remove('eb-modal-open');
    }
  };

  /**
   * Destroy all created modals.
   */
  Drupal.ebUi.destroyModals = () => {
    Drupal.ebUi.modalIds.forEach((modalId) => {
      const modal = document.getElementById(modalId);
      if (modal?.parentNode) {
        modal.parentNode.removeChild(modal);
      }
    });
    Drupal.ebUi.modalIds = [];
  };

  // ============================================
  // VALIDATION MODAL
  // ============================================

  /**
   * Open validation results modal.
   *
   * @param {Object} result
   *   Validation result from server.
   */
  Drupal.ebUi.openValidationModal = (result) => {
    Drupal.ebUi.openModal('eb-validation-modal', Drupal.ebUi.createValidationModal);
    Drupal.ebUi.renderValidationContent(result);
  };

  /**
   * Create validation modal element.
   */
  Drupal.ebUi.createValidationModal = () => {
    const modal = Drupal.ebUi.createModal({
      id: 'eb-validation-modal',
      title: Drupal.t('Validation Results'),
      footerButtons: [
        { label: Drupal.t('Close'), primary: true, class: 'eb-modal__close-btn' }
      ]
    });

    const closeBtn = modal.querySelector('.eb-modal__close-btn');
    if (closeBtn) {
      closeBtn.addEventListener('click', Drupal.ebUi.closeValidationModal);
    }
  };

  /**
   * Close validation modal.
   */
  Drupal.ebUi.closeValidationModal = () => {
    Drupal.ebUi.closeModal('eb-validation-modal');
  };

  /**
   * Render validation content in modal.
   *
   * @param {Object} result
   *   Validation result from server.
   * @param {HTMLElement} targetModal
   *   Optional target modal element. Defaults to validation modal.
   */
  Drupal.ebUi.renderValidationContent = (result, targetModal) => {
    const modal = targetModal || document.getElementById('eb-validation-modal');
    if (!modal) {
      return;
    }

    const content = modal.querySelector('.eb-modal__content');
    const html = [];

    if (result.valid) {
      html.push(
        '<div class="eb-validation eb-validation--success">',
        '  <div class="eb-validation__icon">&#10004;</div>',
        `  <div class="eb-validation__message">${Drupal.t('All data is valid!')}</div>`,
        `  <div class="eb-validation__summary">${Drupal.t('@count operation(s) ready to apply.', { '@count': result.operation_count || 0 })}</div>`,
        '</div>'
      );

      // Show extension warnings even when valid.
      if (result.extension_warnings?.length > 0) {
        html.push('<div class="eb-extension-warnings">');
        html.push(`<h4 class="eb-extension-warnings__title">${Drupal.t('Module Warnings')}</h4>`);
        result.extension_warnings.forEach((warning) => {
          html.push(
            '<div class="eb-extension-warning">',
            '  <span class="eb-extension-warning__icon">\u26A0</span>',
            `  <span class="eb-extension-warning__message">${Drupal.checkPlain(warning)}</span>`,
            '</div>'
          );
        });
        html.push('</div>');
      }
    } else {
      const errorCount = result.errors ? result.errors.length : 0;
      const groupedErrors = Drupal.ebUi.groupValidationErrors(result.errors || []);
      const categoryCount = Object.keys(groupedErrors).length;

      // Header with error count.
      html.push(
        '<div class="eb-validation eb-validation--error">',
        '  <div class="eb-validation__icon">&#10006;</div>',
        `  <div class="eb-validation__message">${Drupal.t('Validation Failed')}</div>`,
        `  <div class="eb-validation__subtitle">${Drupal.t('@count issue(s) found in @categories category(ies)', { '@count': errorCount, '@categories': categoryCount })}</div>`,
        '</div>'
      );

      // Display grouped errors.
      if (result.errors?.length > 0) {

        html.push('<div class="eb-validation__error-groups">');

        Object.keys(groupedErrors).forEach((category) => {
          const errors = groupedErrors[category];
          html.push(
            '<details class="eb-validation__error-group" open>',
            '  <summary class="eb-validation__error-group-header">',
            `    <span class="eb-validation__error-group-title">${Drupal.checkPlain(category)}</span>`,
            `    <span class="eb-validation__error-group-count">${errors.length}</span>`,
            '  </summary>',
            '  <div class="eb-validation__error-group-items">'
          );

          errors.forEach((error) => {
            let itemHtml = '<div class="eb-validation__error-item">';
            itemHtml += `<span class="eb-validation__error-message">${Drupal.checkPlain(error.message)}</span>`;
            if (error.context) {
              itemHtml += `<span class="eb-validation__error-context">${Drupal.checkPlain(error.context)}</span>`;
            }
            itemHtml += '</div>';
            html.push(itemHtml);
          });

          html.push('  </div>', '</details>');
        });

        html.push('</div>');
      }

      // Show extension warnings even with validation errors.
      if (result.extension_warnings?.length > 0) {
        html.push('<div class="eb-extension-warnings">');
        html.push(`<h4 class="eb-extension-warnings__title">${Drupal.t('Module Warnings')}</h4>`);
        result.extension_warnings.forEach((warning) => {
          html.push(
            '<div class="eb-extension-warning">',
            '  <span class="eb-extension-warning__icon">\u26A0</span>',
            `  <span class="eb-extension-warning__message">${Drupal.checkPlain(warning)}</span>`,
            '</div>'
          );
        });
        html.push('</div>');
      }
    }

    content.innerHTML = html.join('\n');
  };

  // ============================================
  // PREVIEW MODAL
  // ============================================

  /**
   * Open preview changes modal.
   *
   * @param {Object|Function} options
   *   Options object with validateFn and previewFn, or legacy function for preview only.
   * @param {Function} options.validateFn
   *   Function that returns a Promise resolving to validation result.
   * @param {Function} options.previewFn
   *   Function that returns a Promise resolving to preview data.
   */
  Drupal.ebUi.openPreviewModal = (options) => {
    Drupal.ebUi.openModal('eb-preview-modal', Drupal.ebUi.createPreviewModal);

    const modal = document.getElementById('eb-preview-modal');
    const content = modal.querySelector('.eb-modal__content');

    // Support legacy function-only call.
    let validateFn = null;
    let previewFn = null;

    if (typeof options === 'function') {
      // Legacy: just a preview function.
      previewFn = options;
    } else {
      validateFn = options.validateFn;
      previewFn = options.previewFn;
    }

    // Track validation result for rendering.
    let validationWarning = null;

    // Step 1: Validate first if validateFn is provided.
    if (validateFn) {
      content.innerHTML = `<div class="eb-modal__loading">${Drupal.t('Validating...')}</div>`;

      validateFn()
        .then((validationResult) => {
          if (!validationResult) {
            content.innerHTML = `<div class="eb-modal__error">${Drupal.t('Validation returned no result.')}</div>`;
            return null;
          }

          // Store validation errors to show as warning, but continue to preview.
          if (!validationResult.valid) {
            validationWarning = validationResult;
          }

          // Fetch preview regardless of validation result.
          content.innerHTML = `<div class="eb-modal__loading">${Drupal.t('Loading preview...')}</div>`;
          return previewFn();
        })
        .then((previewResult) => {
          if (previewResult) {
            Drupal.ebUi.renderPreviewContent(previewResult, validationWarning);
          }
        })
        .catch((error) => {
          console.error('Preview modal error:', error);
          content.innerHTML =
            `<div class="eb-modal__error">${Drupal.t('Error: @error', { '@error': error.message || error })}</div>`;
        });
    } else {
      // No validation - just fetch preview directly.
      content.innerHTML = `<div class="eb-modal__loading">${Drupal.t('Loading preview...')}</div>`;

      previewFn()
        .then((result) => {
          Drupal.ebUi.renderPreviewContent(result, null);
        })
        .catch((error) => {
          content.innerHTML =
            `<div class="eb-modal__error">${Drupal.t('Error loading preview: @error', { '@error': error.message })}</div>`;
        });
    }
  };

  /**
   * Create preview modal element.
   */
  Drupal.ebUi.createPreviewModal = () => {
    const modal = Drupal.ebUi.createModal({
      id: 'eb-preview-modal',
      title: Drupal.t('Preview Changes'),
      footerButtons: [
        { label: Drupal.t('Close'), primary: true, class: 'eb-modal__close-btn' }
      ]
    });

    const closeBtn = modal.querySelector('.eb-modal__close-btn');
    if (closeBtn) {
      closeBtn.addEventListener('click', Drupal.ebUi.closePreviewModal);
    }
  };

  /**
   * Close preview modal.
   */
  Drupal.ebUi.closePreviewModal = () => {
    Drupal.ebUi.closeModal('eb-preview-modal');
  };

  /**
   * Group preview operations by type.
   *
   * @param {Array} previews
   *   Array of preview objects.
   *
   * @return {Object}
   *   Operations grouped by type with counts.
   */
  Drupal.ebUi.groupPreviewOperations = (previews) => {
    const groups = {};
    const typeLabels = {
      create: Drupal.t('Create'),
      update: Drupal.t('Update'),
      delete: Drupal.t('Delete'),
      'no-change': Drupal.t('No Change')
    };

    previews.forEach((preview) => {
      const type = preview.type || 'other';
      if (!groups[type]) {
        groups[type] = {
          label: typeLabels[type] || type,
          items: []
        };
      }
      groups[type].items.push(preview);
    });

    return groups;
  };

  /**
   * Render preview content in modal.
   *
   * Uses Drupal.checkPlain for XSS protection on server-provided data.
   *
   * @param {Object} result
   *   Preview result from server.
   * @param {Object|null} validationWarning
   *   Optional validation result with errors to show as warning.
   */
  Drupal.ebUi.renderPreviewContent = (result, validationWarning) => {
    const modal = document.getElementById('eb-preview-modal');
    if (!modal) {
      return;
    }

    const content = modal.querySelector('.eb-modal__content');
    const escape = Drupal.checkPlain;

    if (!result.success) {
      content.innerHTML = `<div class="eb-modal__error">${Drupal.t('Preview failed: @message', { '@message': result.message || 'Unknown error' })}</div>`;
      return;
    }

    const operationCount = parseInt(result.operation_count, 10) || 0;
    const html = [];

    // Show validation warning if present.
    if (validationWarning && !validationWarning.valid) {
      const errorCount = validationWarning.errors?.length || 0;
      html.push(
        '<div class="eb-preview__warning-banner">',
        '  <span class="eb-preview__warning-icon">&#9888;</span>',
        `  <span class="eb-preview__warning-text">${Drupal.t('Has @count validation error(s)', { '@count': errorCount })}</span>`,
        '</div>'
      );
    }

    // Header with icon.
    html.push(
      '<div class="eb-preview eb-preview--ready">',
      '  <div class="eb-preview__icon">&#9654;</div>',
      `  <div class="eb-preview__message">${Drupal.t('Preview Changes')}</div>`,
      `  <div class="eb-preview__subtitle">${Drupal.t('Review the operations below.')}</div>`,
      '</div>'
    );

    if (result.previews?.length > 0) {
      // Group operations by type.
      const grouped = Drupal.ebUi.groupPreviewOperations(result.previews);
      const typeOrder = ['create', 'update', 'delete', 'no-change'];

      // Stats bar.
      html.push('<div class="eb-preview__stats">');
      let hasStats = false;
      typeOrder.forEach((type) => {
        if (grouped[type]) {
          hasStats = true;
          const count = grouped[type].items.length;
          html.push(
            `  <div class="eb-preview__stat eb-preview__stat--${type}">`,
            `    <span class="eb-preview__stat-value">${count}</span>`,
            `    <span class="eb-preview__stat-label">${grouped[type].label}</span>`,
            '  </div>'
          );
        }
      });
      // Add "other" types not in the order.
      Object.keys(grouped).forEach((type) => {
        if (!typeOrder.includes(type)) {
          hasStats = true;
          const count = grouped[type].items.length;
          html.push(
            `  <div class="eb-preview__stat eb-preview__stat--other">`,
            `    <span class="eb-preview__stat-value">${count}</span>`,
            `    <span class="eb-preview__stat-label">${escape(grouped[type].label)}</span>`,
            '  </div>'
          );
        }
      });
      if (!hasStats) {
        html.push(
          '  <div class="eb-preview__stat eb-preview__stat--total">',
          `    <span class="eb-preview__stat-value">${operationCount}</span>`,
          `    <span class="eb-preview__stat-label">${Drupal.t('Total')}</span>`,
          '  </div>'
        );
      }
      html.push('</div>');

      // Operation groups.
      html.push('<div class="eb-preview__groups">');
      typeOrder.forEach((type) => {
        if (grouped[type]) {
          html.push(...Drupal.ebUi.renderPreviewGroup(type, grouped[type], escape));
        }
      });
      // Add "other" types.
      Object.keys(grouped).forEach((type) => {
        if (!typeOrder.includes(type)) {
          html.push(...Drupal.ebUi.renderPreviewGroup(type, grouped[type], escape));
        }
      });
      html.push('</div>');
    } else {
      html.push(`<div class="eb-preview__empty">${Drupal.t('No operations to preview.')}</div>`);
    }

    content.innerHTML = html.join('\n');
  };

  /**
   * Render a preview operation group.
   *
   * @param {string} type
   *   The operation type.
   * @param {Object} group
   *   The group object with label and items.
   * @param {Function} escape
   *   The escape function.
   *
   * @return {Array}
   *   Array of HTML strings.
   */
  Drupal.ebUi.renderPreviewGroup = (type, group, escape) => {
    const html = [];
    const count = group.items.length;

    html.push(
      `<details class="eb-preview__group eb-preview__group--${type}" open>`,
      '  <summary class="eb-preview__group-header">',
      `    <span class="eb-preview__group-title">${escape(group.label)}</span>`,
      `    <span class="eb-preview__group-count">${count}</span>`,
      '  </summary>',
      '  <div class="eb-preview__group-items">'
    );

    group.items.forEach((preview) => {
      html.push(
        '    <details class="eb-preview__item">',
        '      <summary class="eb-preview__item-summary">',
        `        <span class="eb-preview__item-desc">${escape(preview.summary || '')}</span>`,
        '      </summary>',
        '      <div class="eb-preview__item-details">'
      );

      if (preview.details) {
        html.push(`        <pre>${escape(JSON.stringify(preview.details, null, 2))}</pre>`);
      }

      if (preview.warnings?.length > 0) {
        html.push('        <div class="eb-preview__warnings">');
        preview.warnings.forEach((warning) => {
          html.push(
            '          <div class="eb-preview__warning">',
            '            <span class="eb-preview__warning-icon">\u26A0</span>',
            `            <span class="eb-preview__warning-message">${escape(warning)}</span>`,
            '          </div>'
          );
        });
        html.push('        </div>');
      }

      html.push('      </div>', '    </details>');
    });

    html.push('  </div>', '</details>');
    return html;
  };

  // ============================================
  // IMPORT MODAL
  // ============================================

  /**
   * Store the current import modal options.
   *
   * @type {Object|null}
   */
  Drupal.ebUi._importModalOptions = null;

  /**
   * Open import from existing modal.
   *
   * @param {Object} options
   *   Import options.
   * @param {string} options.targetGridType
   *   The target grid type to import into (optional, for grid editors).
   * @param {Function} options.onImport
   *   Callback function when import completes.
   *   Receives (config, entityType, bundle, targetGridType).
   */
  Drupal.ebUi.openImportModal = (options) => {
    Drupal.ebUi._importModalOptions = options;
    Drupal.ebUi.openModal('eb-import-modal', Drupal.ebUi.createImportModal);

    const modal = document.getElementById('eb-import-modal');

    // Store target grid type if provided.
    if (options.targetGridType) {
      modal.setAttribute('data-target-grid', options.targetGridType);
    }

    // Reset form.
    const entityTypeSelect = modal.querySelector('#eb-import-entity-type');
    const bundleSelect = modal.querySelector('#eb-import-bundle');
    entityTypeSelect.value = '';
    Drupal.ebUi.resetSelectWithPlaceholder(bundleSelect, Drupal.t('- Select bundle -'));
    bundleSelect.disabled = true;
  };

  /**
   * Create import modal element.
   *
   * Uses safe DOM construction to prevent XSS vulnerabilities.
   */
  Drupal.ebUi.createImportModal = () => {
    // Get entity types from ebUi or ebAggrid settings.
    const settings = drupalSettings.ebUi || drupalSettings.ebAggrid || {};
    const entityTypes = settings.discovery?.entityTypes || settings.entityTypes || [];
    const { createElement } = Drupal.ebUi;

    const modal = Drupal.ebUi.createModal({
      id: 'eb-import-modal',
      title: Drupal.t('Import from Existing Configuration'),
      dialogClass: 'eb-modal__dialog--small',
      footerButtons: [
        { label: Drupal.t('Cancel'), class: 'eb-modal__cancel' },
        { label: Drupal.t('Import'), primary: true, class: 'eb-import-btn', disabled: true }
      ]
    });

    const content = modal.querySelector('.eb-modal__content');

    // Build form.
    const form = createElement('div', null, { class: 'eb-import-form' });

    // Entity type field.
    const entityTypeField = createElement('div', null, { class: 'eb-import-form__field' });
    entityTypeField.appendChild(createElement('label', Drupal.t('Entity Type'), { for: 'eb-import-entity-type' }));
    const entityTypeSelect = createElement('select', null, { id: 'eb-import-entity-type', class: 'form-select' });
    entityTypeSelect.appendChild(createElement('option', Drupal.t('- Select entity type -'), { value: '' }));
    entityTypes.forEach((type) => {
      entityTypeSelect.appendChild(createElement('option', type, { value: type }));
    });
    entityTypeField.appendChild(entityTypeSelect);
    form.appendChild(entityTypeField);

    // Bundle field.
    const bundleField = createElement('div', null, { class: 'eb-import-form__field' });
    bundleField.appendChild(createElement('label', Drupal.t('Bundle'), { for: 'eb-import-bundle' }));
    const bundleSelect = createElement('select', null, { id: 'eb-import-bundle', class: 'form-select', disabled: 'disabled' });
    bundleSelect.appendChild(createElement('option', Drupal.t('- Select bundle -'), { value: '' }));
    bundleField.appendChild(bundleSelect);
    form.appendChild(bundleField);

    // Loading indicator.
    const loading = createElement('div', Drupal.t('Loading configuration...'), { class: 'eb-import-form__loading', style: 'display: none;' });
    form.appendChild(loading);

    content.appendChild(form);

    // Event listeners.
    const cancelBtn = modal.querySelector('.eb-modal__cancel');
    if (cancelBtn) {
      cancelBtn.addEventListener('click', Drupal.ebUi.closeImportModal);
    }

    // Entity type change listener.
    entityTypeSelect.addEventListener('change', (event) => {
      const entityType = event.target.value;
      const importBtn = modal.querySelector('.eb-import-btn');

      Drupal.ebUi.resetSelectWithPlaceholder(bundleSelect, Drupal.t('- Select bundle -'));
      bundleSelect.disabled = true;
      importBtn.disabled = true;

      if (entityType) {
        Drupal.ebUi.fetchBundlesForEntityType(entityType).then((bundles) => {
          bundles.forEach((bundle) => {
            if (bundle) {
              bundleSelect.appendChild(createElement('option', bundle, { value: bundle }));
            }
          });
          bundleSelect.disabled = false;
        });
      }
    });

    // Bundle change listener.
    bundleSelect.addEventListener('change', (event) => {
      const importBtn = modal.querySelector('.eb-import-btn');
      importBtn.disabled = !event.target.value;
    });

    // Import button.
    const importBtn = modal.querySelector('.eb-import-btn');
    if (importBtn) {
      importBtn.addEventListener('click', () => {
        const entityType = modal.querySelector('#eb-import-entity-type').value;
        const bundle = modal.querySelector('#eb-import-bundle').value;
        const targetGridType = modal.getAttribute('data-target-grid');

        if (entityType && bundle) {
          Drupal.ebUi.executeImport(entityType, bundle, targetGridType);
        }
      });
    }
  };

  /**
   * Close import modal.
   */
  Drupal.ebUi.closeImportModal = () => {
    Drupal.ebUi.closeModal('eb-import-modal');
    Drupal.ebUi._importModalOptions = null;
  };

  /**
   * Execute import of existing configuration.
   *
   * @param {string} entityType
   *   The entity type.
   * @param {string} bundle
   *   The bundle.
   * @param {string} targetGridType
   *   The target grid type (optional).
   */
  Drupal.ebUi.executeImport = (entityType, bundle, targetGridType) => {
    const modal = document.getElementById('eb-import-modal');
    const loadingEl = modal.querySelector('.eb-import-form__loading');
    loadingEl.style.display = 'block';

    Drupal.ebUi.fetchJson(`/eb/api/entity-config/${encodeURIComponent(entityType)}/${encodeURIComponent(bundle)}`)
      .then((result) => {
        loadingEl.style.display = 'none';

        if (result.success && result.config) {
          // Call the onImport callback if provided.
          const options = Drupal.ebUi._importModalOptions;
          if (options?.onImport) {
            options.onImport(result.config, entityType, bundle, targetGridType);
          }
          Drupal.ebUi.closeImportModal();
        } else {
          alert(Drupal.t('Failed to import configuration: @message', { '@message': result.message || 'Unknown error' }));
        }
      })
      .catch((error) => {
        loadingEl.style.display = 'none';
        alert(Drupal.t('Error importing configuration: @error', { '@error': error.message }));
      });
  };

})(Drupal, drupalSettings);
