export { dsButtonToggle, dsButtonToggleAll };

function dsButtonToggle(toggleElements = []) {
  if (!toggleElements.length) return;
  toggleElements.forEach((toggleEl) => {
    toggleEl.addEventListener('click', () => {
      if (toggleEl.classList.contains('ds-btn--disabled')) return;
      const selectedText = toggleEl.querySelector('.ds-btn__on').textContent;
      const unselectedText = toggleEl.querySelector('.ds-btn__off').textContent;
      toggleEl.classList.toggle('ds-btn--selected');
      const ariaChecked = toggleEl.getAttribute('aria-checked') === 'true' ? 'false' : 'true';
      const ariaLabel = toggleEl.getAttribute('aria-label') === selectedText ? unselectedText : selectedText;
      toggleEl.setAttribute('aria-checked', ariaChecked);
      toggleEl.setAttribute('aria-label', ariaLabel);
    });
  });
}

function dsButtonToggleAll() {
  const toggleElements = Array.from(document.getElementsByClassName('ds-btn--toggle'));
  dsButtonToggle(toggleElements);
}
