/**
 * @file
 * Pipeline monitoring JavaScript for auto-refresh functionality.
 *
 * @param {object} Drupal The Drupal API namespace.
 * @param {Function} once The Drupal core/once helper.
 */

((Drupal, once) => {
  Drupal.behaviors.flowdropRuntimePipelineMonitor = {
    attach(context) {
      let refreshInterval = null;

      const startAutoRefresh = () => {
        refreshInterval = setInterval(() => {
          const refreshButton = document.querySelector(
            'input[value="Refresh"]',
          );
          if (refreshButton) {
            refreshButton.click();
          }
        }, 30000);

        if (typeof Drupal.announce !== 'undefined') {
          Drupal.announce(
            Drupal.t(
              'Auto-refresh enabled. Page will refresh every 30 seconds.',
            ),
          );
        }
      };

      const stopAutoRefresh = () => {
        if (refreshInterval) {
          clearInterval(refreshInterval);
          refreshInterval = null;
        }

        if (typeof Drupal.announce !== 'undefined') {
          Drupal.announce(Drupal.t('Auto-refresh disabled.'));
        }
      };

      const checkboxes = once(
        'pipeline-monitor',
        'input[name="auto_refresh"]',
        context,
      );

      checkboxes.forEach((checkbox) => {
        checkbox.addEventListener('change', (event) => {
          if (event.target.checked) {
            startAutoRefresh();
          } else {
            stopAutoRefresh();
          }
        });

        if (checkbox.matches(':checked')) {
          startAutoRefresh();
        }

        window.addEventListener('beforeunload', stopAutoRefresh);
      });
    },
  };
})(Drupal, once);
