import styles from '!raw-loader!sass-loader!./styles/app-header.scss';

const isMobile = () => window.innerWidth < 720;

class AppHeader extends HTMLElement {
	constructor() {
		super();

		const root = this.attachShadow({ mode: 'open' });

		const style = document.createElement('style');
		style.textContent = styles;
		root.appendChild(style);

		const mobileHeader = document.createElement('div');
		mobileHeader.className = 'header_mobile';

		const hamburger = document.createElement('div');
		hamburger.className = 'header_mobile_hamburger';
		mobileHeader.appendChild(hamburger);

		const mobileLogo = document.createElement('img');
		mobileLogo.src = '/res/logo.png';
		mobileLogo.alt = 'logo';
		mobileLogo.className = 'header_mobile_icon';
		mobileHeader.appendChild(mobileLogo);

		root.appendChild(mobileHeader);

		const div = document.createElement('div');
		div.className = 'header';

		const mobileClose = document.createElement('div');
		mobileClose.className = 'header_mobile_close';
		div.appendChild(mobileClose);

		const logo = document.createElement('img');
		logo.src = '/res/logo.png';
		logo.alt = 'logo';
		logo.className = 'header_icon';
		logo.onclick = () => {
			window.location = '/';
		};
		div.appendChild(logo);

		this.getMenuItems().forEach(item => {
			let submenu;
			if (item.to == '/services/') {
				submenu = document.createElement('div');
				submenu.className = 'header_mobile_submenu';

				const serviceMenu = document.createElement('app-service-menu');
				serviceMenu.dataset.embedded = true;
				submenu.appendChild(serviceMenu);
			}

			const menuItem = document.createElement('div');
			menuItem.className = 'header_item';
			menuItem.innerText = item.name;
			menuItem.onclick = () => {
				console.log('wut', isMobile());
				if (item.to == '/services/' && isMobile()) {
					submenu.classList.toggle('header_mobile_submenu_open');
					return;
				}

				window.location.href = item.to;
			};

			if (window.location.pathname.includes(item.to)) {
				menuItem.classList.add('header_item_active');
			}

			div.appendChild(menuItem);

			if (item.to == '/services/') {
				div.appendChild(submenu);
			}
		});

		root.appendChild(div);

		hamburger.onclick = () => {
			div.classList.add('header_open');
		};
		mobileClose.onclick = () => {
			div.classList.remove('header_open');
		};
	}

	getMenuItems() {
		return [
			{ name: 'Firma', to: '/about' },
			{ name: 'Servicii', to: '/services/' },
			{ name: 'Prețuri', to: '/prices' },
			{ name: 'Contact', to: '/contact' }
		];
	}
}

customElements.define('app-header', AppHeader);
