/**
 * @file
 * Auto-submit the node type plugin selection step.
 *
 * When a plugin is chosen, advance straight to the configuration step instead
 * of requiring a separate "Continue" click. Submission is triggered only by an
 * explicit action — clicking a card or pressing Enter on a focused card — so
 * arrow-key navigation (which selects as it moves) does not submit.
 *
 * @param {object} Drupal The Drupal API namespace.
 */

((Drupal) => {
  Drupal.behaviors.flowdropPluginSelectionAutoSubmit = {
    attach(context) {
      const buttons = context.querySelectorAll(
        '.fd-plugin-continue:not([data-fd-autosubmit-init])',
      );

      buttons.forEach((button) => {
        button.setAttribute('data-fd-autosubmit-init', 'true');

        const form = button.closest('form');
        const selector = form
          ? form.querySelector('[data-flowdrop-plugin-selector]')
          : null;
        if (!form || !selector) {
          return;
        }

        // JS is active: the explicit Continue step is redundant. Keep the
        // button in the DOM (no-JS fallback) but hide and trigger it.
        button.hidden = true;

        // Defer so the selector syncs the hidden input before we submit.
        const submit = () => {
          window.setTimeout(() => button.click(), 0);
        };

        selector.addEventListener('click', (e) => {
          if (e.target.closest('.fd-plugin-selector__card')) {
            submit();
          }
        });

        selector.addEventListener('keydown', (e) => {
          if (
            e.key === 'Enter' &&
            e.target.closest('.fd-plugin-selector__card')
          ) {
            e.preventDefault();
            submit();
          }
        });
      });
    },
  };
})(Drupal);
