export { dsFactbox, dsFactboxAll };

const selector = 'ds-factbox';
const expandedClass = `${selector}--expanded`;
const maxHeight = 468; // this has to match max-height in factbox.scss exluding top/bottom spacing

function dsFactbox(factboxElements) {
  if (!factboxElements.length) return;
  factboxElements.forEach((factboxEl) => {
    if (factboxEl.classList.contains(expandedClass)) return;

    const contentEl = factboxEl.getElementsByClassName(`${selector}__content`)[0];
    if (contentEl.getBoundingClientRect().height <= maxHeight) {
      factboxEl.classList.add(expandedClass);
      return;
    }

    const showMoreEl = factboxEl.getElementsByClassName(`${selector}__show-more`)[0];
    showMoreEl.classList.add(`${selector}__show-more--collapsable`);

    const expandMoreBtn = factboxEl.getElementsByClassName(`${selector}__expand-more`)[0];
    const expandLessBtn = factboxEl.getElementsByClassName(`${selector}__expand-less`)[0];

    expandMoreBtn.addEventListener('click', () => {
      factboxEl.classList.add(expandedClass);
      showMoreEl.setAttribute('data-factbox-expanded', '');
    });

    expandLessBtn.addEventListener('click', () => {
      factboxEl.classList.remove(expandedClass);
      showMoreEl.removeAttribute('data-factbox-expanded');
    });
  });
}

function dsFactboxAll() {
  const factboxElements = Array.from(document.getElementsByClassName(`${selector}`));
  dsFactbox(factboxElements);
}
