( function() {
	'use strict';

	function syncColor( picker, hex ) {
		if ( ! picker || ! hex ) {
			return;
		}

		picker.addEventListener( 'input', function() {
			hex.value = picker.value;
		} );

		hex.addEventListener( 'input', function() {
			var value = ( hex.value || '' ).replace( /^#/, '' );

			if ( /^[0-9A-Fa-f]{6}$/.test( value ) ) {
				picker.value = '#' + value;
			}
		} );
	}

	function activateTab( tabId ) {
		var tabs = document.querySelectorAll( '.zrcb-nav-tabs .nav-tab' );
		var panels = document.querySelectorAll( '.zrcb-tab-panel' );
		var targetPanel = document.getElementById( 'zrcb-tab-' + tabId );

		if ( ! targetPanel ) {
			return;
		}

		tabs.forEach( function( tab ) {
			var isActive = tab.getAttribute( 'data-zrcb-tab' ) === tabId;

			tab.classList.toggle( 'nav-tab-active', isActive );
			tab.setAttribute( 'aria-selected', isActive ? 'true' : 'false' );
		} );

		panels.forEach( function( panel ) {
			var isActive = panel.id === 'zrcb-tab-' + tabId;

			panel.classList.toggle( 'is-active', isActive );
			panel.hidden = ! isActive;
		} );

		var formSubmit = document.querySelector( '.zrcb-form-submit' );

		if ( formSubmit ) {
			formSubmit.hidden = tabId === 'about';
		}

		if ( window.history && window.history.replaceState ) {
			window.history.replaceState( null, '', '#zrcb-tab-' + tabId );
		}
	}

	function initTabs() {
		var tabLinks = document.querySelectorAll( '.zrcb-nav-tabs .nav-tab' );

		if ( ! tabLinks.length ) {
			return;
		}

		tabLinks.forEach( function( link ) {
			link.addEventListener( 'click', function( event ) {
				event.preventDefault();
				activateTab( link.getAttribute( 'data-zrcb-tab' ) );
			} );
		} );

		var hash = window.location.hash.replace( /^#/, '' );

		if ( hash.indexOf( 'zrcb-tab-' ) === 0 ) {
			var tabFromHash = hash.replace( 'zrcb-tab-', '' );
			activateTab( tabFromHash );
		}
	}

	document.addEventListener( 'DOMContentLoaded', function() {
		document.querySelectorAll( '.zrcb-color-picker' ).forEach( function( picker ) {
			var hexId = picker.getAttribute( 'data-hex-target' );
			var hex = hexId ? document.getElementById( hexId ) : null;

			syncColor( picker, hex );
		} );

		initTabs();
	} );
}() );
