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

const DATA_COMPONENT = 'data-eds-c-navigation-expander';

const classNames = {
	TETHERED: 'has-tethered'
};

const selectors = {
	DATA_COMPONENT: `[${DATA_COMPONENT}]`,
	NAVIGATION: '[data-eds-c-navigation]'
};

const findTarget = selector => {
	if (selector) {
		return document.querySelector(selector);
	}
	return null;
};

const navigation = () => {
	const triggerElements = document.querySelectorAll(selectors.DATA_COMPONENT);
	const navigationElement = document.querySelector(selectors.NAVIGATION);

	const triggerAttributes = [
		{name: 'role', value: 'button'}
	];

	if (triggerElements.length === 0 || !navigationElement) {
		return;
	}

	makeArray(triggerElements).forEach(trigger => {
		const targetElement = findTarget(trigger.hash); // #explore

		if (!targetElement) {
			return;
		}

		const parentNav = targetElement.closest('[data-eds-c-navigation-expander-nav]');

		if (parentNav) {
			parentNav.classList.add('u-display-none');
		}

		triggerAttributes.forEach(function (attribute) {
			trigger.setAttribute(attribute.name, attribute.value);
		});

		trigger.after(targetElement);
		targetElement.classList.add(classNames.TETHERED);

		const expander = new Expander(trigger, targetElement, {AUTOFOCUS: 'firstTabbable'});

		expander.init();

		return expander;
	});
};

export default navigation;
