export function extendDetailsBehaviour() {
  enhanceDetails();
  openDetailsFromHash();
  window.addEventListener('hashchange', openDetailsFromHash);
}

function openDetailsAndScroll(detailsElement: Element) {
  detailsElement.setAttribute('open', '');
  setTimeout(() => {
    detailsElement.scrollIntoView({
      block: 'center',
      behavior: 'smooth',
    });
  }, 0);
}

function enhanceDetails() {
  const existingIds: string[] = [];
  Array.from(document.getElementsByTagName('details')).forEach((detailsElement, index) => {
    if (detailsElement.id) {
      return;
    }

    const generatedId =
      detailsElement.querySelector('summary')?.textContent?.replace(/\s+/g, '-').toLowerCase() ||
      `details-${index}`;

    detailsElement.id = existingIds.includes(generatedId) ? `${generatedId}-${index}` : generatedId;

    existingIds.push(detailsElement.id);
  });
}

function openDetailsFromHash() {
  const hash = window.location.hash;
  if (!hash) return;

  const detailsElement = document.getElementById(hash.substring(1));

  if (detailsElement?.tagName === 'DETAILS') {
    openDetailsAndScroll(detailsElement);
  }
}
