/**
 * @file
 * Dark mode toggle behavior for Gutenberg Base theme.
 */

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

  var STORAGE_KEY = 'gutenberg_base_dark_mode';

  Drupal.behaviors.gutenbergBaseDarkMode = {
    attach: function (context) {
      once('dark-mode-toggle', '.dark-mode-toggle', context).forEach(function (button) {
        var isDark = document.documentElement.classList.contains('dark-mode');
        button.setAttribute('aria-pressed', String(isDark));
        button.setAttribute('aria-label',
          isDark ? Drupal.t('Switch to light mode') : Drupal.t('Switch to dark mode')
        );

        button.addEventListener('click', function () {
          document.documentElement.classList.add('dark-mode-transition');

          var nowDark = document.documentElement.classList.toggle('dark-mode');

          button.setAttribute('aria-pressed', String(nowDark));
          button.setAttribute('aria-label',
            nowDark ? Drupal.t('Switch to light mode') : Drupal.t('Switch to dark mode')
          );

          try {
            localStorage.setItem(STORAGE_KEY, nowDark ? 'dark' : 'light');
          }
          catch (e) {
            // localStorage may be unavailable.
          }

          // Remove transition class once the body transition ends, so
          // subsequent transitions (e.g. hover effects) are not affected.
          document.body.addEventListener('transitionend', function removeTransition() {
            document.documentElement.classList.remove('dark-mode-transition');
            document.body.removeEventListener('transitionend', removeTransition);
          });
        });
      });
    },
  };
})(Drupal, once);
