class NavigationBar {
	constructor() {
		this.listWidthBreaks = [];
		
		this.updateNavigationBar();
		this.styleActiveHeading();

		$(window).on('resize', this.updateNavigationBar.bind(this));
		$('.nav button').on('click', this.toggleHiddenLinks);
	}
	
	updateNavigationBar() {
		var hamburger = $('.nav button');
		var hiddenLinks = $('.nav .hidden-links');
		var nav = $('.nav');
		var visibleLinks = $('.nav .visible-links');
		
		const hamburgerOffset = 10;		// Gap between right-most menu item and hamburger
		
		var availableSpace = hamburger.is(":visible") ? nav.width() - hamburger.outerWidth() - hamburgerOffset : 
			nav.width();
			
		// Visible list is overflowing nav
		if (visibleLinks.width() > availableSpace) {
			// Record the width of the list
			this.listWidthBreaks.push(visibleLinks.width());
			// Move an item to the hidden list
			visibleLinks.children().last().prependTo(hiddenLinks);
			// Make the hamburger visible
			if (!hamburger.is(":visible")) {
				hamburger.show();
			}
		} else {
			// There is space for another item
			if (availableSpace > this.listWidthBreaks[this.listWidthBreaks.length - 1]) {
				// Move item to visible list
				hiddenLinks.children().first().appendTo(visibleLinks);
				this.listWidthBreaks.pop();
			}
			// If hidden list is empty, hide the hamburger
			if (this.listWidthBreaks.length < 1) {
				hamburger.hide();
				hiddenLinks.hide();
			}
		}
		// Keep hamburger counter updated
		hamburger.attr('count', this.listWidthBreaks.length);
		
		// Adjust nav width, compensating for hamburger, logo and padding
		var sizeConst = parseFloat($('body').css('font-size'));
		var headerWidth = nav.closest('header').width() / sizeConst;
		var logoWidth = $('.site-title').width() / sizeConst;
		var hamburgerWidth = hamburger.is(":visible") ? hamburger.outerWidth() / sizeConst : 0;
		// Default width is 100 - 15 (logo) - 5 (margin) = 80%
		var availableNavWidth = Math.min(80, (headerWidth - logoWidth - hamburgerWidth) / headerWidth * 100);
		$('.nav-container').css("width", availableNavWidth + '%');
		
		// Recurse if visible list still overflowing
		if (visibleLinks.width() > availableSpace) {
			this.updateNavigationBar();
		}
	}
	
	// Show/hide hamburger menu
	toggleHiddenLinks() {
		$('.nav .hidden-links').toggle();
	}

	// Highlight the heading of the current page
	styleActiveHeading() {
		var activeHeading = $('.content-wrapper').attr('data-heading');
		$('.nav a[id="' + activeHeading + '"]').addClass('nav-item--selected');
	}
}