/**
 * @file
 * JavaScript for EB export form select all functionality.
 */

(function (Drupal, once) {
  'use strict';

  /**
   * Handles select all checkbox functionality for export form.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches the select all behavior.
   */
  Drupal.behaviors.ebExportSelectAll = {
    attach: function (context) {
      const selectAllCheckboxes = once('eb-export-select-all', '.eb-export-select-all', context);

      selectAllCheckboxes.forEach(function (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function () {
          const isChecked = this.checked;
          const details = this.closest('details');

          if (details) {
            const bundleCheckboxes = details.querySelectorAll('.eb-export-bundle-checkbox');
            bundleCheckboxes.forEach(function (bundleCheckbox) {
              bundleCheckbox.checked = isChecked;
            });
          }
        });
      });

      // Update "select all" when individual bundle checkboxes change.
      const bundleCheckboxes = once('eb-export-bundle-checkbox', '.eb-export-bundle-checkbox', context);

      bundleCheckboxes.forEach(function (bundleCheckbox) {
        bundleCheckbox.addEventListener('change', function () {
          const details = this.closest('details');
          if (!details) {
            return;
          }

          const selectAll = details.querySelector('.eb-export-select-all');
          if (!selectAll) {
            return;
          }

          const allBundles = details.querySelectorAll('.eb-export-bundle-checkbox');
          const checkedBundles = details.querySelectorAll('.eb-export-bundle-checkbox:checked');

          selectAll.checked = allBundles.length === checkedBundles.length;
          selectAll.indeterminate = checkedBundles.length > 0 && checkedBundles.length < allBundles.length;
        });
      });
    }
  };

})(Drupal, once);
