import {makeArray, Expander} from '../../../themes/springernature/js/helpers';

class EdsCAccordion {

	constructor(selector = 'data-eds-c-accordion'){
		this.triggersSelector = `[${selector}]`;
	}

	findTarget(headerElement, selector){
		if (selector) {
			return document.querySelector(selector);
		}
		return null;
	}

	init() {
		const triggerElements = document.querySelectorAll(this.triggersSelector);
		if (triggerElements.length === 0) {
			return;
		}

		makeArray(triggerElements).forEach(trigger => {
			const targetElementSelector = trigger.getAttribute('aria-controls');
			if (!targetElementSelector) {
				return;
			}
			const targetElement = document.querySelector(`#${targetElementSelector}`);
			if (!targetElement) {
				return;
			}

			const defaultOpen = trigger.getAttribute('aria-expanded');

			const expander = new Expander(trigger, targetElement, {AUTOFOCUS: 'firstTabbable', DEFAULT_OPEN: defaultOpen === 'true', CLOSE_ON_DOCUMENT_CLICK: false});
			expander.init();

			return expander;
		});
	}
}

export default EdsCAccordion;

