/**
 * Rocketship UI JS
 *
 * contains: triggers for functions
 * Functions themselves are split off and grouped below each behavior
 *
 * Drupal behaviors:
 *
 * Means the JS is loaded when page is first loaded
 * \+ during AJAX requests (for newly added content)
 * use "once" to avoid processing the same element multiple times
 * use the "context" param to limit scope, by default this will return document
 * use the "settings" param to get stuff set via the theme hooks and such.
 *
 *
 * Avoid multiple triggers by using Once
 *
 * EXAMPLE 1:
 *
 * once('my-behavior', '.some-link', context).forEach(function(element) {
 *   $(element).click(function () {
 *     // Code here will only be applied once
 *   });
 * });
 *
 * EXAMPLE 2:
 *
 * once('my-behavior', '.some-element', context).forEach(function (element) {
 *   // The following click-binding will only be applied once
 * });
 */

(function (Drupal, window, document) {
  "use strict";

  // set namespace for frontend UI javascript
  if (typeof window.rocketshipUI == 'undefined') {
    window.rocketshipUI = {};
  }

  var self = window.rocketshipUI;

  ///////////////////////////////////////////////////////////////////////
  // Behavior for FAQ: triggers
  ///////////////////////////////////////////////////////////////////////

  Drupal.behaviors.rocketshipUI_cbFAQ = {
    attach: function (context, settings) {
      const faq = document.querySelectorAll('.block--type-cb-faq .field__item--type-tabbed-item', context);
      if (faq.length) {
        self.faqCollapsable(faq);
      }
    }
  };

  ///////////////////////////////////////////////////////////////////////
  // Behavior for FAQ: functions
  ///////////////////////////////////////////////////////////////////////

  /**
   * Open/close FAQ items
   */
  self.faqCollapsable = function (faq) {
    once('faq-collapsable', faq).forEach(function (element) {
      const faqItem = element;
      let trigger = faqItem.querySelector('.tab-item__title button');
      let target = faqItem.querySelector('.tab-item__content');

      // alternative field names for faq title
      if (typeof trigger === 'undefined' || trigger.length < 1) {
        trigger = faqItem.querySelector('h2:first-child, h3:first-child');
      }

      trigger.addEventListener('click', ()  => {
        // Close item.
        if (faqItem.classList.contains('js-open')) {
          trigger.setAttribute('aria-expanded', 'false');
          faqItem.classList.remove('js-open');
          slideUp(target, 250);
        }
        else {
          trigger.setAttribute('aria-expanded', 'true');
          faqItem.classList.add('js-open');
          slideDown(target, 250);

          faqItem.parentNode.querySelectorAll('.field__item--type-tabbed-item').forEach((sibling) => {
            if (sibling !== faqItem) {
              if (sibling.classList.contains('js-open')) {
                sibling.classList.remove('js-open');
                slideUp(sibling.querySelector('.tab-item__content'), 250);
              }
            }
          });
        }
      });
    });
  };

  /**
   * Increasing height of the Collapse element.
   *
   * @param {*} el
   * @param {*} progress
   */
  function incrementHeight(el, progress) {
    el.style.height = `${progress * el.scrollHeight}px`;
  }

  /**
   * Decrementing height of the Collapse element.
   *
   * @param {*} el
   * @param {*} progress
   */
  function decrementHeight(el, progress) {
    el.style.height = `${el.scrollHeight - progress * el.scrollHeight}px`;
    el.style.overflow = "hidden";
  }

  /**
   * Expanding Collapse element.
   */
  function slideDown(el, duration) {
    const start = performance.now();

    requestAnimationFrame(function animate(time) {
      const runtime = time - start;
      const relativeProgress = runtime / duration;
      const process = Math.min(relativeProgress, 1);


      if (process < 1) {
        incrementHeight(el, process);
        requestAnimationFrame(animate);
        el.style.display = "block";
      }

      if (process === 1) {
        el.style.height = "auto";
        el.style.overflow = "initial";
      }
    });
  }

  /**
   * Collapsing element.
   */
  function slideUp(el, duration) {
    const start = performance.now();
    requestAnimationFrame(function animate(time) {
      const runtime = time - start;
      const relativeProgress = runtime / duration;
      const process = Math.min(relativeProgress, 1);

      if (process < 1) {
        decrementHeight(el, process);
        requestAnimationFrame(animate);
      }

      if (process === 1) {
        el.style.height = "";
        el.style.overflow = "";
        el.style.display = "";
      }
    });
  }

})(Drupal, window, document);
