/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/

(function ($, Drupal) {
  Drupal.behaviors.textSummary = {
    attach(context, settings) {
      once('text-summary', '.js-text-summary', context).forEach(summary => {
        const $widget = $(summary).closest('.js-text-format-wrapper');
        const $summary = $widget.find('.js-text-summary-wrapper');
        const $summaryLabel = $summary.find('label').eq(0);
        const $full = $widget.children('.js-form-type-textarea');
        let $fullLabel = $full.find('label').eq(0);

        if ($fullLabel.length === 0) {
          $fullLabel = $('<label></label>').prependTo($full);
        }

        if ($fullLabel.hasClass('visually-hidden')) {
          $fullLabel.html((index, oldHtml) => `<span class="visually-hidden">${oldHtml}</span>`);
          $fullLabel.removeClass('visually-hidden');
        }

        const $link = $(`<span class="field-edit-link"> (<button type="button" class="link link-edit-summary">${Drupal.t('Hide summary')}</button>)</span>`);
        const $button = $link.find('button');
        let toggleClick = true;
        $link.on('click', e => {
          if (toggleClick) {
            $summary.hide();
            $button.html(Drupal.t('Edit summary'));
            $link.appendTo($fullLabel);
          } else {
            $summary.show();
            $button.html(Drupal.t('Hide summary'));
            $link.appendTo($summaryLabel);
          }

          e.preventDefault();
          toggleClick = !toggleClick;
        }).appendTo($summaryLabel);

        if (summary.value === '') {
          $link.trigger('click');
        }
      });
    }

  };
})(jQuery, Drupal);