function openAccordion(detailTag) {
  const wrapper = detailTag.querySelector('.homegrade-dynamic-accordeon__content-wrapper') ?? null;
  const content = detailTag.querySelector('.homegrade-dynamic-accordeon__content') ?? null;
  if (!wrapper || !content) return;

  detailTag.setAttribute('open', 'true');
  detailTag.setAttribute('is_opening', '');

  wrapper.style.height = content.offsetHeight + 'px';
  // remove is opening after css transition

  detailTag.addEventListener('transitionend', () => {
    detailTag.removeAttribute('is_opening');
  });
}
function closeAccordion(detailTag) {
  const wrapper = detailTag.querySelector('.homegrade-dynamic-accordeon__content-wrapper');
  if (!wrapper) return;
  wrapper.style.height = '0px';

  setTimeout(() => {
    detailTag.removeAttribute('open');
  }, 300);
}
function openAllAccordions(detailTags) {
  Array.from(detailTags).forEach((detailTag) => {
    openAccordion(detailTag);
  });
}
function closeAllAccordions(detailTags) {
  Array.from(detailTags).forEach((detailTag) => {
    closeAccordion(detailTag);
  });
}
function handleAccordeonClick(detailTag, event) {
  // Return if the user clicked on a link
  if (event.target.tagName.toLowerCase() === 'a') return;
  event.preventDefault();

  let isOpen = detailTag.getAttribute('open');
  let isOpening = detailTag.getAttribute('is_opening');
  if (isOpen == null && isOpening == null) {
    openAccordion(detailTag);
  }
  if (isOpen == 'true') {
    closeAccordion(detailTag);
  }
}

export default function accordeonInit() {
  const detailsTags = document.querySelectorAll('details.homegrade-dynamic-accordeon');
  if (detailsTags.length === 0) return;

  // HANDLING CLICK
  Array.from(detailsTags).forEach((detailTag) => {
    closeAccordion(detailTag);

    detailTag.addEventListener('click', (event) => {
      handleAccordeonClick(detailTag, event);
    });
  });
}

export {
  openAccordion,
  closeAccordion,
  openAllAccordions,
  closeAllAccordions,
  handleAccordeonClick,
};
