/**
 * Customizer Presets
 * Handles updating individual color pickers when a preset palette is selected.
 */
( function( $, api ) {

	api.bind( 'ready', function() {

		// Preset palettes
		var palettes = {
			warm: {
				pawfect_primary_color: '#F4A259',
				pawfect_secondary_color: '#313134',
				pawfect_background_color: '#fef9f5',
				pawfect_text_color: '#6B7280',
				pawfect_header_background_color: '#313134',
				pawfect_header_text_color: '#1f2937',
				pawfect_footer_background_color: '#313134',
				pawfect_footer_text_color: '#ffffff',
				pawfect_cta_background_color: '#1f2937',
				pawfect_cta_text_color: '#ffffff',
				pawfect_feature_highlight_bg_color: '#ffffff',
				pawfect_feature_highlight_text_color: '#1f2937',
				pawfect_featured_collection_bg_color: '#ffffff',
				pawfect_main_slider_caption_subtitle_title_color: '#F4A259',
				pawfect_mission_background_color: '#1a202c',
				pawfect_promo_banner_background_color: '#fef9f5',
				pawfect_promo_banner_subtitle_color: '#F4A259',
				pawfect_promo_timer_desc_color: '#F4A259',
				pawfect_testimonial_background_color: '#f9fafb',
				pawfect_testimonial_accent_color: '#f59e0b',
				pawfect_press_mentions_background_color: '#313134',
				pawfect_portfolio_bg_color: '#ffffff',
				pawfect_service_bg_color: '#fef9f5',
				pawfect_service_text_color: '#1f2937',
				pawfect_blog_background_color: '#fef9f5',
				pawfect_topbar_bg_color: '#333333',
				pawfect_topbar_text_color: '#ffffff',
				pawfect_page_header_background_color: '#FFFFFF',
				pawfect_page_header_text_color: '#333333',
				pawfect_why_choose_bg_color: '#FFF9F5',
				pawfect_why_choose_text_color: '#1f2937'
			},
			fresh: {
				pawfect_primary_color: '#000000',
				pawfect_secondary_color: '#313134',
				pawfect_background_color: '#ffffff',
				pawfect_text_color: '#1F2937',
				pawfect_header_background_color: '#133827',
				pawfect_header_text_color: '#ffffff',
				pawfect_footer_background_color: '#133827',
				pawfect_footer_text_color: '#ffffff',
				pawfect_cta_background_color: '#ffffff',
				pawfect_cta_text_color: '#1F2937',
				pawfect_feature_highlight_bg_color: '#ffffff',
				pawfect_feature_highlight_text_color: '#1F2937',
				pawfect_featured_collection_bg_color: '#ffffff',
				pawfect_main_slider_caption_subtitle_title_color: '#000000',
				pawfect_mission_background_color: '#ffffff',
				pawfect_promo_banner_background_color: '#DEF1F0',
				pawfect_promo_banner_subtitle_color: '#000000',
				pawfect_promo_timer_desc_color: '#000000',
				pawfect_testimonial_background_color: '#C1CFB3',
				pawfect_testimonial_accent_color: '#000000',
				pawfect_press_mentions_background_color: '#DEF1F0',
				pawfect_portfolio_bg_color: '#ffffff',
				pawfect_service_bg_color: '#F5F5F5',
				pawfect_service_text_color: '#1F2937',
				pawfect_blog_background_color: '#DEF1F0',
				pawfect_topbar_bg_color: '#133827',
				pawfect_topbar_text_color: '#ffffff',
				pawfect_page_header_background_color: '#DEF1F0',
				pawfect_page_header_text_color: '#000000',
				pawfect_why_choose_bg_color: '#F5F5F5',
				pawfect_why_choose_text_color: '#1F2937'
			}
		};

		var individualColors = [
			'pawfect_primary_color',
			'pawfect_secondary_color',
			'pawfect_background_color',
			'pawfect_text_color',
			'pawfect_header_background_color',
			'pawfect_header_text_color',
			'pawfect_footer_background_color',
			'pawfect_footer_text_color',
			'pawfect_cta_background_color',
			'pawfect_cta_text_color',
			'pawfect_feature_highlight_bg_color',
			'pawfect_feature_highlight_text_color',
			'pawfect_featured_collection_bg_color',
			'pawfect_main_slider_caption_subtitle_title_color',
			'pawfect_mission_background_color',
			'pawfect_promo_banner_background_color',
			'pawfect_promo_banner_subtitle_color',
			'pawfect_promo_timer_desc_color',
			'pawfect_testimonial_background_color',
			'pawfect_testimonial_accent_color',
			'pawfect_press_mentions_background_color',
			'pawfect_portfolio_bg_color',
			'pawfect_service_bg_color',
			'pawfect_service_text_color',
			'pawfect_blog_background_color',
			'pawfect_topbar_bg_color',
			'pawfect_topbar_text_color',
			'pawfect_page_header_background_color',
			'pawfect_page_header_text_color',
			'pawfect_why_choose_bg_color',
			'pawfect_why_choose_text_color'
		];

        // Helper to update the visual UI of the radio options
        function updatePaletteUI( value ) {
            var $allOptions = $('.pawfect-palette-option');
            
            // Reset all
            $allOptions.css({
                'border-color': '#e2e8f0',
                'box-shadow': '0 1px 2px 0 rgba(0, 0, 0, 0.05)'
            });
            $allOptions.find('.pawfect-radio-indicator').css('border-color', '#cbd5e1');
            $allOptions.find('.pawfect-radio-dot').css({
                'opacity': '0',
                'transform': 'scale(0)'
            });
            $allOptions.find('span').css('color', '#475569');
            
            // Set active
            var $activeInput = $('.pawfect-palette-option input[value="' + value + '"]');
            if ( $activeInput.length ) {
                var $activeOption = $activeInput.closest('.pawfect-palette-option');
                $activeOption.css({
                    'border-color': '#0D9488',
                    'box-shadow': '0 4px 6px -1px rgba(13, 148, 136, 0.1)'
                });
                $activeOption.find('.pawfect-radio-indicator').css('border-color', '#0D9488');
                $activeOption.find('.pawfect-radio-dot').css({
                    'opacity': '1',
                    'transform': 'scale(1)'
                });
                $activeOption.find('span').css('color', '#0f172a');
            }
        }

        // Helper to natively toggle individual color controls using WP Customizer API
        function toggleColorPickers( value ) {
            if ( value === 'custom' ) {
                $('body').removeClass('pawfect-palette-hide-colors');
            } else {
                $('body').addClass('pawfect-palette-hide-colors');
            }
        }

        // --- Core Logic ---

        var paletteSetting = api( 'pawfect_color_palette' );
        if ( ! paletteSetting ) {
            return; // Exit gracefully if the setting isn't registered yet
        }
        
        var initialValue = paletteSetting.get();
        updatePaletteUI( initialValue );
        toggleColorPickers( initialValue );

        // 2. Delegate click/change events on our custom radio HTML
        $(document).on('change', '.pawfect-palette-option input[type="radio"]', function() {
            var val = $(this).val();
            // Force WP API to update (this triggers the bind event below)
            api( 'pawfect_color_palette' ).set( val );
        });

		// 3. Listen for preset changes in the API
        var isApplyingPreset = false;

		api( 'pawfect_color_palette', function( setting ) {
			setting.bind( function( value ) {
                
                // Update UI and visibility
                updatePaletteUI( value );
                toggleColorPickers( value );

				// Prevent looping or trying to apply 'custom' palette values
				if ( value === 'custom' || ! palettes[ value ] ) {
					return;
				}

                isApplyingPreset = true;
				var colors = palettes[ value ];

				// Update all individual colors
				$.each( colors, function( colorSetting, colorValue ) {
					if ( api( colorSetting ) ) {
						api( colorSetting ).set( colorValue );
						
						// Refresh visual color picker UI
						var control = api.control( colorSetting );
						if ( control && control.container ) {
							var $input = control.container.find('.pawfect-color-control');
							if ( $input.length ) {
								$input.wpColorPicker('color', colorValue);
							}
						}
					}
				} );

                // Use setTimeout to allow the WP API setting updates to finish before unlocking
                setTimeout(function() {
                    isApplyingPreset = false;
                }, 100);
			} );
		} );

		// 4. Listen for manual individual color changes to flip preset to 'custom'
		$.each( individualColors, function( index, colorSetting ) {
			api( colorSetting, function( setting ) {
				setting.bind( function( value ) {
                    if ( isApplyingPreset ) {
                        return; // Ignore changes caused by selecting a preset
                    }

					var paletteSetting = api( 'pawfect_color_palette' );
					if ( ! paletteSetting ) {
						return; // Exit if the palette setting isn't registered yet
					}
					var currentPreset = paletteSetting.get();
					
					if ( currentPreset === 'custom' ) {
						return; // Already custom
					}

					// Check if it deviates from current preset (case-insensitive)
					if ( palettes[ currentPreset ] ) {
                        var presetColor = palettes[ currentPreset ][ colorSetting ] ? palettes[ currentPreset ][ colorSetting ].toLowerCase() : '';
                        var newValue = value ? value.toLowerCase() : '';
                        
                        if ( presetColor !== newValue ) {
						    api( 'pawfect_color_palette' ).set( 'custom' );
                        }
					}
				} );
			} );
		} );

	} );

} )( jQuery, wp.customize );
