/*jshint esversion: 6 */
( function( $, l10n ) {
	'use strict';

	if ( ! wp || ! wp.customize ) {
		console.log( 'wp or wp.customize objects not found.' );
		return;
	}

	/**
	 * Custom Selects.
	 */
	var controls = [
		'wpex-dropdown-pages',
		'wpex-card-select',
		'wpex-dropdown-templates'
	];

	_.each( controls, function( control ) {
		wp.customize.controlConstructor[control] = wp.customize.Control.extend( {
			ready: function() {
				if ( 'undefined' === typeof $.fn.chosen ) {
					return;
				}
				var $select = this.container.find( 'select' );
				if ( ! $select ) {
					return;
				}
				var optionCount = $select.find( 'option' ).length;
				if ( optionCount < 14 ) {
					return;
				}
				$select.chosen( {
					width: '100%',
					search_contains: true,
					disable_search_threshold: 5
				} );
			}
		} );
	} );

	/**
	 * Multi-Select.
	 */
	wp.customize.controlConstructor.wpex_multi_select = wp.customize.Control.extend( {
		ready: function() {
			const control = this;
			control.container.on( 'change', '.wpex-customize-multi-select__input', function( event ) {
				event.preventDefault();
				let newVal = '';
				control.container.find( '.wpex-customize-multi-select__input' ).each( function() {
					if ( $( this ).is( ':checked' ) ) {
						newVal += $( this ).attr( 'value' ) + ',';
					}
				} );
				control.setting.set( newVal.replace(/,+$/, "") );
			} );
		}
	} );

	/**
	 * Font Family.
	 */
	 wp.customize.controlConstructor['wpex-font-family'] = wp.customize.Control.extend( {
		ready: function() {
			if ( 'undefined' === typeof $.fn.chosen ) {
				return;
			}
			var $select = this.container.find( '.wpex-customizer-chosen-select select' );
			if ( ! $select ) {
				return;
			}
			$select.chosen( {
				width: '100%',
				search_contains: true,
				disable_search_threshold: 5
			} );
		}
	} );

	/**
	 * Sortable.
	 */
	wp.customize.controlConstructor.wpex_sortable = wp.customize.Control.extend( {
		ready: function() {
			const control = this;
			const sortableEl = control.container.find( '.wpex-customize-sortable__list' );

			sortableEl.sortable();
			sortableEl.disableSelection();

			const updateSortableVal = () => {
				let values = [];
				sortableEl.find( '.wpex-customize-sortable__item' ).each( function() {
					if ( ! $( this ).hasClass( 'wpex-customize-sortable__item--disabled' ) ) {
						values.push( $( this ).attr( 'data-wpex-value' ) );
					}
				} );
				control.setting.set( values.length ? values.join( ',' ) : '' );
			};

			sortableEl.on( 'sortstop', function( event, ui ) {
				updateSortableVal();
			} );

			control.container.on( 'click', '.wpex-customize-sortable__button', function( event ) {
				event.preventDefault();
				const parentLi = $( this ).closest( '.wpex-customize-sortable__item' );
				parentLi.toggleClass( 'wpex-customize-sortable__item--disabled' );
				parentLi.find( '.wpex-customize-sortable__icon' ).toggleClass( 'ticon-rotate-180' );
				updateSortableVal();
			} );
		}
	} );

	/**
	 * Social profiles.
	 */
	wp.customize.controlConstructor.wpex_social_profiles = wp.customize.Control.extend( {
		ready: function() {
			var control = this;
			var container = control.container;
			var sortableUl = container.find( '.wpex-customize-social-profiles__list' );

			sortableUl.sortable();

			sortableUl.on( 'sortstop', function( event, ui ) {
				control.updateValue();
			} );

			$( document ).on( 'input', '.wpex-customize-social-profiles__item input[type="text"]', function() {
				control.updateValue();
			} );

			container.on( 'click', '.wpex-customize-social-profiles__delete-item', function( event ) {
				var result = confirm(l10n.deleteConfirm);
				if (result) {
					$(this).parents( '.wpex-customize-social-profiles__item' ).remove();
					control.updateValue();
				}
				event.preventDefault();
			} );

			container.find( '.wpex-customize-social-profiles__add-item' ).click( function( event ) {
				event.preventDefault();
				var select = container.find( '.wpex-customize-social-profiles__select' );
				var selectedSite = select.find( ':selected' );
				if ( selectedSite ) {
					var selectedSiteVal = selectedSite.val();
					if ( container.find( 'input[data-wpex-key="' + selectedSiteVal + '"]' ).length ) {
						alert(l10n.duplicate);
						return;
					}
					var clone = container.find( '.wpex-customize-social-profiles__template' ).clone();
					clone.removeClass( 'wpex-customize-social-profiles__template' );
					clone.addClass( 'wpex-customize-social-profiles__item' );
					clone.find( 'label' ).text( selectedSite.text() );
					clone.find( 'input' ).val( '#' ).attr( 'data-wpex-key', selectedSiteVal );
					clone.appendTo( container.find( '.wpex-customize-social-profiles__list' ) );
					control.updateValue();
					container.find( '.wpex-customize-social-profiles__list' ).sortable( 'refresh' );
				}
			} );
		},
		updateValue: function() {
			var control = this;
			var newValue = {};
			var valCount = 0;
			control.container.find( '.wpex-customize-social-profiles__item input[type="text"]' ).each( function( index, el ) {
				var $this = $( this );
				var val = $this.val();
				if ( val ) {
					valCount++;
					newValue[$this.attr( 'data-wpex-key' )] = val;
				}
			} );
			if ( valCount == 0 ) {
				control.setting.set( '' );
			} else {
				control.setting.set( JSON.stringify( newValue ) );
			}
		}
	} );

	/**
	 * Textarea.
	 */
	wp.customize.controlConstructor.wpex_textarea = wp.customize.Control.extend( {
		ready: function() {
			var container = this.container;
			var decode = function( text ) {
				var map = {
					'&amp;': '&',
					'&#038;': "&",
					'&lt;': '<',
					'&gt;': '>',
					'&quot;': '"',
					'&#039;': "'",
					'&#8217;': "’",
					'&#8216;': "‘",
					'&#8211;': "–",
					'&#8212;': "—",
					'&#8230;': "…",
					'&#8221;': '”'
				};
				return text.replace(/\&[\w\d\#]{2,5}\;/g, function(m) { return map[m]; });
			};
			container.find( '.wpex-customize-textarea-toolbar button' ).on( 'click', function( event ) {
				var data = $( this ).data( 'wpex-insert' );
				if ( data ) {
					var textBox = container.find( '.wpex-customize-textarea' );
					var textBoxVal = textBox.val();
					if ( textBoxVal ) {
						textBox.val( textBoxVal + '\n' + decode( data ) );
					} else {
						textBox.val( decode( data ) );
					}
					textBox.trigger( 'change' );
				}
				event.preventDefault();
			} );
		}
	} );

	/**
	 * Icon Selects.
	 */
	wp.customize.controlConstructor.wpex_ticon_select = wp.customize.Control.extend( {
		ready: function() {
			const control     = this;
			const $modal      = control.container.find( '.wpex-customize-icon-select-modal' );
			const $preview    = control.container.find( '.wpex-customize-icon-select__preview' );
			const $svg        = $preview.find( '.wpex-customize-icon-select__svg' );

			const openModal = () => {
				$modal.addClass( 'wpex-customize-icon-select-modal--open' );
				$modal.find( '.wpex-customize-icon-select-modal__search' ).val( '' ).focus();
				$modal.find( '.wpex-customize-icon-select-modal__choices a' ).show();
			};

			const closeModal = () => {
				$modal.removeClass( 'wpex-customize-icon-select-modal--open' );
			};

			const onButtonClick = ( event ) => {
				openModal();
				event.preventDefault();
			};

			const onCloseClick = ( event ) => {
				closeModal();
				event.preventDefault();
			};

			const onModalClick = ( event ) => {
				if ( ! event.target.closest( '.wpex-customize-icon-select-modal__inner' ) ) {
					closeModal();
				}
			};

			const onRemove = ( event ) => {
				$preview.addClass( 'wpex-customize-icon-select__preview--empty' );
				$svg.html( '' );
				control.setting.set( '' );
			};

			const onIconClick = ( event ) => {
				console.log( control );
				const link = event.target.closest( 'a' );
				if ( ! link ) {
					return;
				}
				const value = link.getAttribute( 'data-value' );
				if ( value && '0' !== value ) {
					control.setting.set( value );
					$preview.removeClass( 'wpex-customize-icon-select__preview--empty' );
				} else {
					control.setting.set( '' );
					$preview.addClass( 'wpex-customize-icon-select__preview--empty' );
				}
				$svg.html( link.innerHTML );
				closeModal();
			};

			const onSearch = ( event ) => {
				const search = event.target.closest( '.wpex-customize-icon-select-modal__search' );
				if ( ! search ) {
					return;
				}
				const $this  = $( search );
				const value  = $this.val().toLowerCase();
				const $icons = $this.next().find( 'a' );
				$icons.filter( function() {
					$( this ).toggle( $( this ).attr( 'data-value' ).toLowerCase().indexOf( value ) > -1 );
				} );
			};

			control.container.on( 'click', '.wpex-customize-icon-select__remove', onRemove );
			control.container.on( 'click', '.wpex-customize-icon-select__button', onButtonClick );

			$modal.click( onModalClick );
			$modal.on( 'click', '.wpex-customize-icon-select-modal__choices a', onIconClick );
			$modal.on( 'click', '.wpex-customize-icon-select-modal__close', onCloseClick );
			$modal.on( 'input', '.wpex-customize-icon-select-modal__search', onSearch );
		}
	} );

	/**
	 * Icon Selects.
	 */
	wp.customize.controlConstructor.wpex_toggle = wp.customize.Control.extend( {
		ready: function() {
			this.container.find( 'input[type="checkbox"]' ).change( function() {
				$( this ).closest( '.wpex-customize-toggle-control' ).toggleClass( 'wpex-customize-toggle-control--checked', this.checked);
			} );
		}
	} );

	/**
	 * Custom Columns.
	 *
	 */
	wp.customize.controlConstructor['wpex-columns'] = wp.customize.Control.extend( {
		ready: function() {
			var control = this;
			control.container.find( '.wpex-cols-select' ).change( function( e ) {
				control.updateValue();
			} );
			control.container.find( '.wpex-toggle-settings' ).on( 'click', function() {
				control.container.find( '.wpex-customizer-columns-field > li.wpex-extra' ).toggleClass( 'wpex-hidden' );
				if ( 'false' == $( this ).attr( 'aria-expanded' ) ) {
					$( this ).attr( 'aria-expanded', 'true' );
					control.container.find( '.wpex-customizer-columns-field li.wpex-extra:first select' ).focus();
				} else {
					$( this ).attr( 'aria-expanded', 'false' );
				}
				return false;
			} );
		},
		updateValue: function() {
			var control = this;
			var newValue = {};
			var valCount = 0;
			var $hiddenInput = control.container.find( '.wpex-hidden-input' );
			$hiddenInput.trigger( 'change' );
			control.container.find( '.wpex-cols-select' ).each( function( index, el ) {
				var $this = $( this ),
					val = $this.children( 'option:selected' ).val();
				if ( val ) {
					valCount++;
					newValue[$this.attr( 'data-name' )] = val;
				}
			} );
			if ( valCount == 0 ) {
				newValue = '';
			} else if ( valCount == 1 ) {
				newValue = newValue['d'];
			}
			control.setting.set( newValue );
		}
	} );

	/**
	 * Top/Right/Bottom/Left.
	 */
	wp.customize.controlConstructor.wpex_trbl = wp.customize.Control.extend( {
		ready: function() {
			const control = this;
			const controlEl = control.container.find( '.wpex-customize-trbl' );
			const shorthand = controlEl.attr( 'data-wpex-shorthand' );
			const $inputs = control.container.find( '.wpex-customize-trbl__input' );
			const selectedUnit = 'px';
			control.container.on( 'input', '.wpex-customize-trbl__input', function() {
				let newVal = '';
				let firstValue = null;
				let allSame = true;
				let allEmpty = true;
				let valArray = [];
				let parsedArray = [];
				$inputs.each( function( index, el ) {
					let $this = $( this );
					let val = $this.val();
					if ( '' !== val ) {
						allEmpty = false;
					}
					if ( 0 === index ) {
						firstValue = val;
					}
					if ( firstValue !== val ) {
						allSame = false;
					}
					if ( 'true' === shorthand ) {
						val = val || '0px';
						if ( ! isNaN( val ) ) {
							val = val + selectedUnit;
						}
						valArray.push( val );
					} else {
						if ( val ) {
							if ( ! isNaN( val ) ) {
								val = val + selectedUnit;
							}
							parsedArray.push( $this.attr( 'data-name' ) + ':' + val );
							valArray.push( val );
						}
					}
				} );
				if ( allEmpty ) {
					newVal = '';
				} else if ( allSame ) {
					if ( ! isNaN( firstValue ) ) {
						firstValue = firstValue + selectedUnit;
					}
					newVal = firstValue;
				} else {
					if ( 4 === valArray.length && ( valArray[0] == valArray[2] && valArray[1] == valArray[3] ) ) {
						newVal = valArray[0] + ' ' + valArray[1];
					} else {
						newVal = ( 'true' === shorthand ) ? valArray.join(' ') : parsedArray.join('|');
					}
				}
				control.setting.set( newVal );
			} );
		}
	} );

	/**
	 * Length Unit.
	 */
	wp.customize.controlConstructor.wpex_length_unit = wp.customize.Control.extend( {
		ready: function() {
			const control = this;

			control.container.on( 'input', '.wpex-customize-length-unit__input', function() {
				control.updateValue( $( this ) );
			} );

			control.container.on( 'focus', '.wpex-customize-length-unit__input', function() {
				control.container.find( '.wpex-customize-length-unit' ).addClass( 'wpex-customize-length-unit--focused' );
			} );

			control.container.on( 'blur', '.wpex-customize-length-unit__input', function() {
				control.container.find( '.wpex-customize-length-unit' ).removeClass( 'wpex-customize-length-unit--focused' );
			} );

			control.container.on( 'change', '.wpex-customize-length-unit__select', function() {
				const $this        = $( this );
				const selectedUnit = $this.find( 'option:selected' ).val();
				const input        = control.container.find( '.wpex-customize-length-unit__input' );
				if ( selectedUnit !== $this.find( 'option' ).first().val() ) {
					input.attr( 'placeholder', '' );
				} else {
					input.attr( 'placeholder', input.attr( 'data-placeholder' ) );
				}
				if ( 'func' === selectedUnit || 'var' === selectedUnit || 'calc' === selectedUnit || 'clamp' === selectedUnit ) {
					input.attr( 'type', 'text' );
					input.attr( 'inputmode', 'text' );
				} else {
					input.attr( 'type', 'number' );
					input.attr( 'inputmode', 'numeric' );
				}
				control.updateValue( input );
				/*
				input.val( '' );
				control.setting.set( '' );
				*/
			} );
		},
		updateValue: function( input ) {
			const control = this;
			let val = input.val();
			if ( val ) {
				let selectedUnit = control.container.find( '.wpex-customize-length-unit__select option:selected' ).val();
				if ( 'num' === selectedUnit ) {
					selectedUnit = '';
				}
				switch( selectedUnit ) {
					case 'func':
						// no tweaks here.
						break;
					case 'var':
						val = 'var(' + val.trim() + ')';
						break;
					case 'clamp':
						val = 'clamp(' + val.trim() + ')';
						break;
					case 'calc':
						val = 'calc(' + val.trim() + ')';
						break;
					default:
						val = parseFloat( val );
						val = ! isNaN( val ) ? val + selectedUnit : '';
						break;
				}
			} else {
				control.updatePlaceholder();
			}
			control.setting.set( String( val.trim() ) );
		},
		updatePlaceholder: function() {
			const control = this;
			const input = control.container.find( '.wpex-customize-length-unit__input' );
			if ( control.container.find( '.wpex-customize-length-unit__select option:selected' ).val() !== control.container.find( '.wpex-customize-length-unit__select option' ).first().val() ) {
				input.attr( 'placeholder', '' );
			} else {
				input.attr( 'placeholder', input.attr( 'data-placeholder' ) );
			}
		}
	} );

	/**
	 * Responsive Fields.
	 */
	wp.customize.controlConstructor.wpex_responsive_field = wp.customize.Control.extend( {
		ready: function() {
			const control = this;
			control.container.find( '.wpex-customize-responsive-field__input' ).on( 'input', function( e ) {
				control.updateValue();
			} );
		},
		updateValue: function() {
			const control = this;
			var newValue = {};
			var valCount = 0;
			control.container.find( '.wpex-customize-responsive-field__input' ).each( function( index, el ) {
				const $this = $( this );
				const val = $this.val();
				if ( val ) {
					valCount++;
					newValue[$this.attr( 'data-name' )] = val;
				}
			} );
			if ( valCount == 0 ) {
				control.setting.set('');
			} else {
				control.setting.set( JSON.stringify( newValue ) );
			}
		}
	} );

	/**
	 * SVG Select.
	 */
	wp.customize.controlConstructor.wpex_svg_select = wp.customize.Control.extend( {
		ready: function() {
			const control = this;
			control.container.on( 'change', '.wpex-customize-svg-select select', function() {
				const $this       = $( this );
				const selected    = $this.find( 'option:selected' ).val();
				control.container.find( '.wpex-customize-svg-select-icon' ).each( function() {
					let icon = $( this );
					if ( ! selected ) {
						if ( icon.hasClass( 'wpex-customize-svg-select-icon--default' ) ) {
							icon.removeClass( 'wpex-customize-svg-select-icon--hidden' );
						} else {
							icon.addClass( 'wpex-customize-svg-select-icon--hidden' );
						}
					} else {
						if ( icon.attr( 'data-wpex-value' ) == selected ) {
							icon.removeClass( 'wpex-customize-svg-select-icon--hidden' );
						} else {
							icon.addClass( 'wpex-customize-svg-select-icon--hidden' );
						}
					}
				} );
			} );
		},
	} );

	/**
	 * Blocks Control.
	 */
	wp.customize.controlConstructor.wpex_blocks = wp.customize.Control.extend( {
		ready: function() {
			var control = this;
			var container = control.container;
			var sortableUl = container.find( '.wpex-customize-blocks__list' );

			sortableUl.sortable();

			sortableUl.on( 'sortstop', function( event, ui ) {
				control.updateValue();
			} );

			container.on( 'click', '.wpex-customize-blocks__delete-item', function( event ) {
				var result = confirm(l10n.deleteConfirm);
				if (result) {
					$( this ).parents( '.wpex-customize-blocks__item' ).remove();
					control.updateValue();
				}
				event.preventDefault();
			} );

			container.find( '.wpex-customize-blocks__add-button' ).click( function( event ) {
				event.preventDefault();
				var select = container.find( '.wpex-customize-blocks__select' );
				var selectedBlock = select.find( ':selected' );
				if ( selectedBlock ) {
					var selectedSiteVal = selectedBlock.val();
					if ( container.find( '.wpex-customize-blocks__item[data-wpex-key="' + selectedSiteVal + '"]' ).length ) {
						alert(l10n.duplicate);
						return;
					}
					var clone = container.find( '.wpex-customize-blocks__template' ).clone();
					clone.removeClass( 'wpex-customize-blocks__template' );
					clone.addClass( 'wpex-customize-blocks__item' ).attr( 'data-wpex-key', selectedSiteVal );
					clone.find( '.wpex-customize-blocks__item-name' ).text( selectedBlock.text() );
					clone.appendTo( container.find( '.wpex-customize-blocks__list' ) );
					control.updateValue();
					container.find( '.wpex-customize-blocks__list' ).sortable( 'refresh' );
				}
			} );
		},
		updateValue: function() {
			const control = this;
			let newValue = '';
			control.container.find( '.wpex-customize-blocks__item' ).each( function( index, el ) {
				newValue += $( this ).attr( 'data-wpex-key' ) + ',';
			} );
			if ( newValue.trim() ) {
				control.container.find( '.wpex-customize-blocks' ).addClass( 'wpex-customize-blocks--has-blocks' );
				control.setting.set( newValue.replace(/,+$/, '') );
			} else {
				control.container.find( '.wpex-customize-blocks' ).removeClass( 'wpex-customize-blocks--has-blocks' );
				control.setting.set( '' );
			}
		}
	} );

} ( jQuery, wpex_custom_controls ) );