/**
 * @param {HTMLElement} component
 */
KuferTools.InitCollapse = function(component) {
  function determineHeader() {
    let header = component;
    if (!header.matches('.kt-header-collapse')) {
      header = header.querySelector('> .kt-header-collapse') ?? undefined;
      if (header === undefined) {
        throw new Error(`header muss existieren!`);
      }
    }

    return header;
  }

  /**
   * @param {HTMLElement} header
   * @returns {HTMLElement}
   */
  function determinePanel(header) {
    let panel = header.nextElementSibling ?? undefined;
    if (panel !== undefined && !panel.matches('.kt-panel-collapse')) {
      panel = header.parentElement?.querySelector('> .kt-panel-collapse');
    }

    if (panel === undefined || !panel.matches('.kt-panel-collapse')) {
      throw new Error(`Body zu ${header.id} muss existieren!`);
    }

    return panel;
  }

  const header = determineHeader();
  //if (header.dataset.ktSet) {
  //  return;
  //}

  //header.dataset.ktSet = true;
  const panel = determinePanel(header);

  let state = !header.classList.contains('kt-collapsed');
  const icon = header.querySelector('.kt-icon-collapse') ?? undefined;
  const showIcon = icon === undefined ? function() {} : () => {
    icon.classList.remove('fa-plus');
    icon.classList.add('fa-minus');
  };
  const hideIcon = icon === undefined ? function() {} : () => {
    icon.classList.remove('fa-minus');
    icon.classList.add('fa-plus');
  };

  // Icon anpassen
  if (state) {
    showIcon();
  } else {
    hideIcon();
  }

  function showContent() {
    showIcon();
    header.classList.remove('kt-collapsed');
    header.setAttribute('aria-expanded', 'true');
    panel.setAttribute('aria-expanded', 'true');
    state = true;
  }

  function hideContent() {
    hideIcon();
    header.classList.add('kt-collapsed');
    header.setAttribute('aria-expanded', 'false');
    panel.setAttribute('aria-expanded', 'false');
    state = false;
  }

  let inTransition = false;
  header.addEventListener('click', () => {
    if (inTransition) {
      return;
    }

    inTransition = true;

    const setContent = state ? hideContent : showContent;

    if (!document.startViewTransition) {
      setContent();
      inTransition = false;
    } else {
      KuferTools.Utils.AjaxLadebildschirm.Stop();

      document.startViewTransition(() => {
        setContent();
        inTransition = false;
      });
    }
  }, { passive: true });
};

document.addEventListener('KursdetailsReiterLoaded', (event) => {
  for (const element of event.detail.element.querySelectorAll('.kt-header-collapse')) {
    KuferTools.InitCollapse(element);
  }
});

docReady(() => {
  for (const element of document.body.querySelectorAll('.kt-header-collapse')) {
    KuferTools.InitCollapse(element);
  }
});

