/* eslint-disable prefer-template */

( function( wp, _, sections ) {
	function getCSSKey( section, color, index ) {
		const key = index === 0 ? '' : 'on-';
		return section + key + color;
	}

	function setColor( key, value ) {
		document.documentElement.style.setProperty( key, value );
	}

	_.each( sections, function( section, sectionKey ) {
		_.each( section.colors, function( config, colorKey ) {
			const controlBaseId = 'nisje_theme_colors_' + sectionKey + '_' + colorKey;

			wp.customize( controlBaseId + '_toggle', function( value ) {
				value.bind( function( enabled ) {
					_.forEach( config.default, function( color, index ) {
						const key = getCSSKey( section.key, colorKey, index );
						if ( enabled ) {
							setColor( key, wp.customize.get()[ controlBaseId + '_color_' + ( index + 1 ) ] );
						} else {
							setColor( key, color );
						}
					} );
				} );
			} );

			_.forEach( config.default, function( __, index ) {
				wp.customize( controlBaseId + '_color_' + ( index + 1 ), function( value ) {
					value.bind( function( color ) {
						setColor( getCSSKey( section.key, colorKey, index ), color );
					} );
				} );
			} );
		} );
	} );
} )( window.wp, window._, window.nisjeCustomizerSections );
