class Accordion {
	constructor(domNode) {
		this.blockEl = domNode.parentElement;
		this.rootEl = domNode;
		this.buttonEl = this.rootEl.querySelector('.accordion__trigger');

		const controlsId = this.buttonEl.getAttribute('aria-controls');
		this.contentEl = () => document.getElementById(controlsId);
	
		this.open = this.buttonEl.getAttribute('aria-expanded') === 'true';

		this.buttonEl.addEventListener('click', this.onButtonClick.bind(this));
		
		if (this.rootEl.parentElement.classList.contains('accordion--toggleable')) {
			this.buttonEl.addEventListener('accordion-toggle', this.onAccordionToggle.bind(this));
		}
	}

	onButtonClick() {
		for (let i = 0; i < this.blockEl.children.length; i++) {
			if (
				this.blockEl.children[i].classList.contains('accordion__item') &&
				this.blockEl.children[i] !== this.rootEl
			) {
				this.blockEl.children[i].children[0].dispatchEvent(new Event('accordion-toggle'));
			}
		}
		this.toggle(!this.open);
	}

	onAccordionToggle() {
		if (this.open) {
			this.toggle(!this.open);
		}
	}

	toggle(open) {
		if (open === this.open) return;
	
		this.open = open;
		this.buttonEl.setAttribute('aria-expanded', `${open}`);
	
		const contentEl = this.contentEl();
	
		if (open) {
			contentEl?.removeAttribute('hidden');
			setTimeout(() => {
				contentEl?.classList.add('accordion__content-active');
			}, 10);
			this.rootEl.classList.add('accordion__item-active');
		} else {
			contentEl?.classList.remove('accordion__content-active');
			setTimeout(() => {
				contentEl?.setAttribute('hidden', '');
			}, 510);
			this.rootEl.classList.remove('accordion__item-active');
		}
	}

	// Add public open and close methods for convenience
	open() {
		this.toggle(true);
	}

	close() {
		this.toggle(false);
	}
}

export function initAccordions(root = document) {
	const accordions = root.querySelectorAll('.accordion__item');

	accordions.forEach((accordion) => {
		if (accordion.dataset.accordionInitialized) return;

		new Accordion(accordion);
		accordion.dataset.accordionInitialized = 'true';
	});
}

// init accordions
window.addEventListener('DOMContentLoaded', function () {
	initAccordions();
});
