/* global wp, jQuery */
/**
 * File customizer.js.
 *
 * Theme Customizer enhancements for a better user experience.
 *
 * Contains handlers to make Theme Customizer preview reload changes asynchronously.
 */

( function( $ ) {

	$( document ).ready( function() {
		// prefix for customizer settings
		var prefix = 'travelfic_customizer_settings_';


		/**
		 * 
		 * Theme Color Palette
		 * 
		*/
	
		var isPresetUpdate = false;

		const palettes = {
			'design-1': ['#0E3DD8', '#003C7A', '#C9D4F7', '#060D1C', '#686E7A', '#F3F5FD', '#16275F', '#dddddd', '#ffffff', '#FFF9F5', '#0E3DD8', '#e0e8ee52'],
			'design-2': ['#B58E53', '#917242', '#FAEEDC', '#595349', '#99948d', '#FDF9F3', '#5F4216', '#EEE2D1', '#ffffff', '#FDF9F3', '#917242', '#e0e8ee52'],
			'design-3': ['#FF6B00', '#C15100', '#FDDCC3', '#1A0B00', '#6E655E', '#FDF7F3', '#5F3416', '#EEDDD1', '#ffffff', '#FFF9F5', '#FF6B00', '#e0e8ee52'],
			'design-4': ['#003162', '#0054A8', '#C2E0FF', '#000000', '#000000', '#F3F8FD', '#163A5F', '#D1DFEE', '#ffffff', '#F5FAFF', '#003162', '#e0e8ee52'],
		};

		wp.customize(`${prefix}color_palette`, function (value) {
		value.bind(function (newPalette) {
				if (palettes[newPalette]) {
					// Set flag so custom update does not override the preset update
					isPresetUpdate = true;
					const colors = palettes[newPalette];
					wp.customize(`${prefix}primary_color`).set(colors[0]);
					wp.customize(`${prefix}secondary_color`).set(colors[1]);
					wp.customize(`${prefix}brand_lite_color`).set(colors[2]);
					wp.customize(`${prefix}heading_color`).set(colors[3]);
					wp.customize(`${prefix}body_text_color`).set(colors[4]);
					wp.customize(`${prefix}text_lite_color`).set(colors[5]);
					wp.customize(`${prefix}border_default_color`).set(colors[6]);
					wp.customize(`${prefix}border_lite_color`).set(colors[7]);
					wp.customize(`${prefix}filling_background`).set(colors[8]);
					wp.customize(`${prefix}filling_foreground`).set(colors[9]);
					wp.customize(`${prefix}links_color`).set(colors[10]);
					wp.customize(`${prefix}box_shadow_color`).set(colors[11]);

					setTimeout(function () {
						isPresetUpdate = false;
					}, 300);
				}
			});
		});
		// Update custom palette
		function updateCustomPalette() {
			if (isPresetUpdate){
				return;
			}
			const primary      = wp.customize(`${prefix}primary_color`).get();
			const secondary    = wp.customize(`${prefix}secondary_color`).get();
			const brandLite    = wp.customize(`${prefix}brand_lite_color`).get();
			const heading      = wp.customize(`${prefix}heading_color`).get();
			const bodyText     = wp.customize(`${prefix}body_text_color`).get();
			const textLite     = wp.customize(`${prefix}text_lite_color`).get();
			const border 	   = wp.customize(`${prefix}border_default_color`).get();
			const borderLite   = wp.customize(`${prefix}border_lite_color`).get();
			const fillingBg    = wp.customize(`${prefix}filling_background`).get();
			const fillingFg    = wp.customize(`${prefix}filling_foreground`).get();
			const links   	   = wp.customize(`${prefix}links_color`).get();
			const boxShadow    = wp.customize(`${prefix}box_shadow_color`).get();

			// Create new custom palette array
			const newPalette = [
				primary,
				secondary,
				brandLite,
				heading,
				bodyText,
				textLite,
				border,
				borderLite,
				fillingBg,
				fillingFg,
				links,
				boxShadow,
			];

			wp.customize(`${prefix}color_palette`).set('custom');

			const paletteControl = wp.customize.control(`${prefix}color_palette`);
			if (paletteControl && paletteControl.params && paletteControl.params.choices) {
				paletteControl.params.choices['custom'] = newPalette;
			}

			jQuery('input[data-customize-setting-link="' + prefix + 'color_palette"]').each(function () {
				var val = jQuery(this).val();
				jQuery(this).prop('checked', val === 'custom');
			});

		}

		// Bind color settings
		const colorSettings = [
			'primary_color',
			'secondary_color',
			'brand_lite_color',
			'heading_color',
			'body_text_color',
			'text_lite_color',
			'border_default_color',
			'border_lite_color',
			'filling_background',
			'filling_foreground',
			'links_color',
			'box_shadow_color',
		];

		// Bind color settings to update custom palette
		colorSettings.forEach(function (setting) {
			wp.customize(`${prefix}${setting}`, function (value) {
				value.bind(function (newValue) {
					if (!isPresetUpdate) {
						updateCustomPalette();
					}
				});
			});
		});


		/**
		 * 
		 * Theme Typography 
		 * 
		*/
		function initializeTypographyPopup(type) {
			var fields = [
				'font_family', 'font_weight', 'font_size', 'font_size-desktop', 'font_size-tablet', 'font_size-mobile', 'font_line_height',
				'font_letter_space', 'font_transform', 'font_decoration'
			];
			
			var wrapperClass = `.travelfic-${type}-font-wrapper`;
			var popupId = `#typography-${type}-popup`;
			var editClass = `.tf-${type}-font-edit`;

			var sectionDivider = $('#customize-control-travelfic_customizer_settings_section_divider').hide();
			var controls = {};

			// Store the original parent of each control
			var originalParents = {};
			let responsiveFields = ['font_size']; 

			fields.forEach(field => {
				let settingId = `${prefix}${type}_${field}`;
				let controlId = responsiveFields.includes(field) ? `customize-control-kirki_responsive__${settingId}` : `customize-control-${settingId}`;
				
				controls[field] = $(`#${controlId}`).hide();
   				originalParents[field] = controls[field].parent();
			});

			// Edit button
			$(editClass).on('click', function (e) {
				e.preventDefault();
				e.stopPropagation();
				$('.travelfic-customizer-popup').remove();
				$('.tf-edit .dashicons-no-alt').hide();
				$('.tf-edit .dashicons-edit').show();

				$(this).find('.dashicons-edit').toggle();
				$(this).find('.dashicons-no-alt').toggle();
				
				if ($(popupId).length) {
					fields.forEach(field => {
						originalParents[field].append(controls[field].hide());
					});
					$(popupId).remove();
					return;
				}
				
				// Create the popup
				var popupContent = `<div id="typography-${type}-popup" class="travelfic-customizer-popup"></div>`;
				$(wrapperClass).append(popupContent);
				
				fields.forEach((field, index) => {
					var fieldSection = `<div class="${field}-section"></div>`;
					$(popupId).append(fieldSection);
					$(`${popupId} .${field}-section`).append(controls[field].show());
					
					// Append section-divider after font_letter_space-section
					if (field === 'font_letter_space') {
						$(popupId).append('<div class="section-divider"></div>');
						$('.section-divider').append(sectionDivider.show());
					}
				});
				$(popupId).append(`<button type="button" class="tf-clear-typography-popup button" data-type="${type}">Clear</button>`);

				// Handle slider input placeholder
				var kirkiSliderInput = $('.travelfic-customizer-popup .customize-control-kirki-input-slider .kirki-control-input');
				if ($(kirkiSliderInput).val() == '0NaN' || $(kirkiSliderInput).val() == '0') {
					$(kirkiSliderInput).val('');
					$(kirkiSliderInput).attr('placeholder', 'Auto');
				}
			
				
			});

			// Close button
			$(`${editClass} .dashicons-no-alt`).on('click', function (e) {
				e.stopPropagation();
				$(`#typography-${type}-popup`).remove(); 
				$(this).hide(); 
				$(this).siblings('.dashicons-edit').show();
			});
		}

		// Prevent click events on popup
		$('body').on('click', '.travelfic-customizer-popup', function(e) {
			if ($(e.target).is('input, .switch-label, select')) {
				return; 
			}
			e.stopPropagation();
			e.preventDefault();
		});

		// Handle typography field updates
		$('body').on('change', '.travelfic-customizer-popup input, .travelfic-customizer-popup select', function(e) {
			var $el = $(this);
			var value = $el.val();
			var fieldId;

			// Prevent input value 0 (both number and string "0")
			if (value === "0" || value === 0) {
				$el.val('');
				return;
			}else{
				// Check if it's a radio input
				if ($el.is(':radio')) {
					fieldId = $el.attr('data-customize-setting-link');
				} else {
					var idAttr = $el.attr('id');
					if (typeof idAttr !== 'undefined') {
						fieldId = idAttr.replace('customize-input-', '');
					}
				}

				if (typeof fieldId === 'undefined' || fieldId.trim() === '') {
					return;
				}

				$(`#customize-control-${fieldId}`).closest('.travelfic-customizer-popup').find('.tf-clear-typography-popup').prop('disabled', false);
				wp.customize(fieldId, function(setting) {
					setting.set(value);
				});

				wp.customize.previewer.refresh();
			}

			
		});

		// Store the default font families for all types
		var defaultFontFamilies = {};
		['body', 'heading', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'buttons'].forEach(function(type) {
			wp.customize(`travelfic_customizer_settings_${type}_font_family`, function(value) {
				defaultFontFamilies[type] = value.get();
			});
		});
			
		// Reset typography settings
		$('body').on('click', '.tf-clear-typography-popup', function(e) {
			e.stopPropagation();
			e.preventDefault();
			
			var type = $(this).attr('data-type');
			var popupId = `#typography-${type}-popup`;

			// Get stored default value
			var defaultFontFamily = defaultFontFamilies[type] || '';
			if(defaultFontFamily === '') {
				$(`#customize-control-travelfic_customizer_settings_${type}_font_family .kirki-react-select__single-value >div`).html('Select...');
			}

			// Reset fields
			$(`${popupId} input, ${popupId} select`).each(function () {
				var $el = $(this);
				var fieldId;

				if ($el.is(':radio')) {
					const name = $el.attr('name');
					fieldId = $el.attr('data-customize-setting-link');
					$(`input[name="${name}"]`).each(function () {
						this.checked = this.defaultChecked;
					});

					const newValue = $(`input[name="${name}"]:checked`).val();

					if (fieldId && typeof newValue !== 'undefined') {
						wp.customize(fieldId, function (setting) {
							setting.set(newValue);
						});
					}
				} else {
					let defaultValue = $el.prop('defaultValue');
					let currentValue = $el.val();
					const placeholder = $el.attr('placeholder');
					const idAttr = $el.attr('id');
					const fieldId = typeof idAttr !== 'undefined' 
						? idAttr.replace(/^(customize-input-|kirki-control-input-|kirki-react-select-input--)/, '') 
						: null;

					if (currentValue != defaultValue && currentValue != 0) {

						if ((defaultValue === 0 || defaultValue === '0') && placeholder?.toLowerCase() === 'auto') {
							defaultValue = ''; // or use 'auto' if that makes more sense for your UX
						}

						$el.val(defaultValue).trigger('change');

						if (fieldId && typeof defaultValue !== 'undefined') {
							wp.customize(fieldId, function (setting) {
								setting.set(defaultValue);
							});
						}
					}
				}
			});
			// Reset font family
			wp.customize(`travelfic_customizer_settings_${type}_font_family`, function(value) {
				value.set(defaultFontFamily);
			});
		});

		// Close popups when clicking outside
		$(document).on('click', function (event) {
			if (!$(event.target).closest('.travelfic-customizer-popup, .tf-edit, input, .kirki-react-select__menu, .kirki-react-select-container').length) {
				$('.travelfic-customizer-popup').remove();
				$('.tf-edit .dashicons-no-alt').hide();
				$('.tf-edit .dashicons-edit').show();
			}
		});

		// Bind typography presets
		wp.customize( 'travelfic_customizer_settings_typography_preset', function( value ) {
			value.bind( function( fonts ) {
				const fontSplit = fonts.split('/');
				const headingFont = fontSplit[0];
				const bodyFont = fontSplit[1];

				// Set fonts
				wp.customize( 'travelfic_customizer_settings_heading_font_family', function( value ) {
					value.set(headingFont);
				});
				wp.customize( 'travelfic_customizer_settings_body_font_family', function( value ) {
					value.set(bodyFont);
				});

			});
		});

		initializeTypographyPopup('body');
		initializeTypographyPopup('heading');
		initializeTypographyPopup('h1');
		initializeTypographyPopup('h2');
		initializeTypographyPopup('h3');
		initializeTypographyPopup('h4');
		initializeTypographyPopup('h5');
		initializeTypographyPopup('h6');
		initializeTypographyPopup('menu');
		initializeTypographyPopup('submenu');
		initializeTypographyPopup('buttons');

	
		// Bind button presets
		let globalPrimaryColor;

		wp.customize('travelfic_customizer_settings_primary_color',function(primaryColorSetting){
			globalPrimaryColor = primaryColorSetting.get();
		});

		wp.customize('travelfic_customizer_settings_button_primary_preset', function(value) {
			value.bind(function(preset) {
				// Initialize with proper structure
				let defaultBorder = {
					desktop: { top: 0, right: 0, bottom: 0, left: 0 },
					tablet: { top: 0, right: 0, bottom: 0, left: 0 },
					mobile: { top: 0, right: 0, bottom: 0, left: 0 }
				};
				
				let defaultBorderRadius = {
					desktop: { top: 0, right: 0, bottom: 0, left: 0 },
					tablet: { top: 0, right: 0, bottom: 0, left: 0 },
					mobile: { top: 0, right: 0, bottom: 0, left: 0 }
				};
				
				
				let defaultButtonColor = '#ffffff';
		
				// Apply preset values
				switch (preset) {
					case 'set-1':
						// Defaults (already set)
						break;
					case 'set-2':
						defaultBorderRadius.desktop = { top: 3, right: 3, bottom: 3, left: 3 };
						defaultBorderRadius.tablet = { top: 3, right: 3, bottom: 3, left: 3 };
						defaultBorderRadius.mobile = { top: 3, right: 3, bottom: 3, left: 3 };
						break;
					case 'set-3':
						defaultBorderRadius.desktop = { top: 100, right: 100, bottom: 100, left: 100 };
						defaultBorderRadius.tablet = { top: 100, right: 100, bottom: 100, left: 100 };
						defaultBorderRadius.mobile = { top: 100, right: 100, bottom: 100, left: 100 };
						break;
					case 'set-4':
						defaultBorder.desktop = { top: 1, right: 1, bottom: 1, left: 1 };
						defaultBorder.tablet = { top: 1, right: 1, bottom: 1, left: 1 };
						defaultBorder.mobile = { top: 1, right: 1, bottom: 1, left: 1 };
						defaultButtonColor = globalPrimaryColor;
						break;
					case 'set-5':
						defaultBorder.desktop = { top: 1, right: 1, bottom: 1, left: 1 };
						defaultBorder.tablet = { top: 1, right: 1, bottom: 1, left: 1 };
						defaultBorder.mobile = { top: 1, right: 1, bottom: 1, left: 1 };
						defaultBorderRadius.desktop = { top: 3, right: 3, bottom: 3, left: 3 };
						defaultBorderRadius.tablet = { top: 3, right: 3, bottom: 3, left: 3 };
						defaultBorderRadius.mobile = { top: 3, right: 3, bottom: 3, left: 3 };
						defaultButtonColor = globalPrimaryColor;
						break;
					case 'set-6':
						defaultBorder.desktop = { top: 1, right: 1, bottom: 1, left: 1 };
						defaultBorder.tablet = { top: 1, right: 1, bottom: 1, left: 1 };
						defaultBorder.mobile = { top: 1, right: 1, bottom: 1, left: 1 };
						defaultBorderRadius.desktop = { top: 100, right: 100, bottom: 100, left: 100 };
						defaultBorderRadius.tablet = { top: 100, right: 100, bottom: 100, left: 100 };
						defaultBorderRadius.mobile = { top: 100, right: 100, bottom: 100, left: 100 };
						defaultButtonColor = globalPrimaryColor;
						break;
				}

				wp.customize('travelfic_customizer_settings_button_primary_text_colors[normal]', function(buttonColorSetting) {
					buttonColorSetting.set(defaultButtonColor);
				});

				setTimeout(() => wp.customize.previewer.refresh(), 300);
			});
		});

		// Handle section changes
		if (typeof wp !== 'undefined' && wp.customize && wp.customize.section) {
			wp.customize.section.bind('change', function() {
				$('.travelfic-customizer-popup').remove();
				fields.forEach(field => {
					originalParents[field].append(controls[field].hide());
				});
			});
		}
		
		// Setup toggle controls
		function setupToggleControls() {
			// Toggle controls
			var toggleControls = [
				'travelfic_customizer_settings_header_design_2_topbar',
				'travelfic_customizer_settings_header_design_3_topbar',
				'travelfic_customizer_settings_sticky_header',
				'travelfic_customizer_settings_transparent_header',
				'travelfic_customizer_settings_header_design_select',
				'travelfic_customizer_settings_header_design_3_search',
				'travelfic_customizer_settings_header_design_3_cart',
				'travelfic_customizer_settings_header_design_3_button',
				'travelfic_customizer_settings_page_width',
				'travelfic_customizer_settings_enable_scroll_to_top',
				'travelfic_customizer_settings_page_loader',
			];
			
			// Font groups and fields
			const fontGroups = ['body', 'heading', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'menu', 'submenu', 'buttons'];
			const fontFields = [
				'font_family',
				'font_weight',
				'font_line_height',
				'font_letter_space',
				'font_transform',
				'font_decoration'
			];
			
			// Generate control IDs
			let controlsToHideOnAnyToggle = [];
			
			fontGroups.forEach(group => {
				fontFields.forEach(field => {
					controlsToHideOnAnyToggle.push(`travelfic_customizer_settings_${group}_${field}`);
				});
				controlsToHideOnAnyToggle.push(`kirki_responsive__travelfic_customizer_settings_${group}_font_size`);
			});
			
			// Generate device selectors
			let specificDeviceSelectors = fontGroups.flatMap(group => [
				`#customize-control-travelfic_customizer_settings_${group}_font_size-desktop`,
				`#customize-control-travelfic_customizer_settings_${group}_font_size-tablet`,
				`#customize-control-travelfic_customizer_settings_${group}_font_size-mobile`
			]);
			
			// Loop through each toggle
			toggleControls.forEach(controlId => {
				const control = wp.customize.control(controlId);
				if (!control) {
					return;
				}
				
				// Handler function
				const updateControls = () => {
					$('.travelfic-customizer-popup').remove();
					
					setTimeout(() => {
                        specificDeviceSelectors.forEach(selector => $(selector).hide());
                    }, 200);

					// Hide device-specific controls
					controlsToHideOnAnyToggle.forEach(id => {
						const ctrl = wp.customize.control(id);
						if (ctrl) ctrl.container.hide();
					});
				};
				
				// Bind changes
				control.setting.bind(updateControls);
				
				// Trigger immediately
				updateControls();
			});
		}

		// Run on page load or after customizer initialization
		if (wp.customize && wp.customize.control) {
			setupToggleControls();
		} else {
			wp.customize?.bind('ready', setupToggleControls);
		}
		
		jQuery('.customize-control[data-kirki-parent-responsive-id="kirki_responsive__travelfic_customizer_settings_container_width"] .kirki-control-input').each(function () {
			if (jQuery(this).val() == '0NaN' || jQuery(this).val() == '0') {
				jQuery(this).val('');
				jQuery(this).attr('placeholder', 'Auto');
			}
		});

		jQuery('.customize-control[data-kirki-parent-responsive-id="kirki_responsive__travelfic_customizer_settings_logo_width"] .kirki-control-input').each(function () {
			const val = jQuery(this).val();
			if (val === '0NaN' || val === '0') {
				jQuery(this).val('');
				jQuery(this).attr('placeholder', 'Auto');
			}
		});

		// Loop through each preset option
		$('#customize-control-travelfic_customizer_settings_typography_preset .image label').each(function() {
			var tooltipText = $(this).find('input').data('tooltip');

			// Add tooltip element
			if (tooltipText) {
				$(this).append('<span class="tooltip">' + tooltipText + '</span>');
			}
		});

		// Show tooltip on hover
		$(document).on('mouseenter', '#customize-control-travelfic_customizer_settings_typography_preset .image label', function() {
			$(this).find('.tooltip').fadeIn(200);
		}).on('mouseleave', '#customize-control-travelfic_customizer_settings_typography_preset .image label', function() {
			$(this).find('.tooltip').fadeOut(200);
		});

		// Logo
		wp.customize('custom_logo', function(value) {
			value.bind(function(to) {
				wp.customize.previewer.refresh();
			});
		});

		// on device change refresh
		$('body').on('click', '.devices-wrapper button, .kirki-responsive .kirki-device-button', function() {
			var kirkiSliderInput = $('.travelfic-customizer-popup .customize-control-kirki-input-slider .kirki-control-input');
			if ($(kirkiSliderInput).val() == '0NaN' || $(kirkiSliderInput).val() == '0') {
				$(kirkiSliderInput).val('');
				$(kirkiSliderInput).attr('placeholder', 'Auto');
			}else{
				$(kirkiSliderInput).val($(kirkiSliderInput).val());
			}
			wp.customize.previewer.refresh();
		});
		
		// Site title and description.
		wp.customize( 'blogname', function( value ) {
			value.bind( function( to ) {
				$( '.site-title a' ).text( to );
			} );
		} );
		wp.customize( 'blogdescription', function( value ) {
			value.bind( function( to ) {
				$( '.site-description' ).text( to );
			} );
		} );

	} );
}( jQuery ) );
