export function accordion(node: HTMLElement) {
  function handleToggle(event: Event) {
    const target = event.target;

    if (!(target instanceof HTMLDetailsElement) || !target.open || !node.contains(target)) {
      return;
    }

    const details = node.querySelectorAll('details');

    for (const item of details) {
      if (item !== target) {
        item.open = false;
      }
    }
  }

  node.addEventListener('toggle', handleToggle, true);

  return {
    destroy() {
      node.removeEventListener('toggle', handleToggle, true);
    }
  };
}
