/**
 * Extend Customizer Panel
 *
 * @package pawfect
 */

( function( $ ) {

	var api = wp.customize;

	api.bind( 'pane-contents-reflowed', function() {

		// Reflow sections
		var sections = [];

		api.section.each( function( section ) {

			if (
				'pawfect_section' !== section.params.type ||
				'undefined' === typeof section.params.section
			) {

				return;

			}

			sections.push( section );

		} );

		sections.sort( api.utils.prioritySort ).reverse();

		$.each( sections, function( i, section ) {

			var parentContainer = $( '#sub-accordion-section-' + section.params.section );

			parentContainer.children( '.section-meta' ).after( section.headContainer );

		} );

		// Reflow panels
		var panels = [];

		api.panel.each( function( panel ) {

			if (
				'pawfect_panel' !== panel.params.type ||
				'undefined' === typeof panel.params.panel
			) {

				return;

			}

			panels.push( panel );

		} );

		panels.sort( api.utils.prioritySort ).reverse();

		$.each( panels, function( i, panel ) {

			var parentContainer = $( '#sub-accordion-panel-' + panel.params.panel );

			parentContainer.children( '.panel-meta' ).after( panel.headContainer );

		} );

	} );


	// Extend Panel
	var _panelEmbed                = wp.customize.Panel.prototype.embed;
	var _panelIsContextuallyActive = wp.customize.Panel.prototype.isContextuallyActive;
	var _panelAttachEvents         = wp.customize.Panel.prototype.attachEvents;

	wp.customize.Panel = wp.customize.Panel.extend( {
		attachEvents        : function() {

			if (
				'pawfect_panel' !== this.params.type ||
				'undefined' === typeof this.params.panel
			) {

				_panelAttachEvents.call( this );

				return;

			}

			_panelAttachEvents.call( this );

			var panel = this;

			panel.expanded.bind( function( expanded ) {

				var parent = api.panel( panel.params.panel );

				if ( expanded ) {

					parent.contentContainer.addClass( 'current-panel-parent' );

				} else {

					parent.contentContainer.removeClass( 'current-panel-parent' );

				}

			} );

			panel.container.find( '.customize-panel-back' )
				.off( 'click keydown' )
				.on( 'click keydown', function( event ) {

					if ( api.utils.isKeydownButNotEnterEvent( event ) ) {

						return;

					}

					event.preventDefault(); // Keep this AFTER the key filter above

					if ( panel.expanded() ) {

						api.panel( panel.params.panel ).expand();

					}

				} );

		},
		embed               : function() {

			if (
				'pawfect_panel' !== this.params.type ||
				'undefined' === typeof this.params.panel
			) {

				_panelEmbed.call( this );

				return;

			}

			_panelEmbed.call( this );

			var panel           = this;
			var parentContainer = $( '#sub-accordion-panel-' + this.params.panel );

			parentContainer.append( panel.headContainer );

		},
		isContextuallyActive: function() {

			if (
				'pawfect_panel' !== this.params.type
			) {

				return _panelIsContextuallyActive.call( this );

			}

			var panel    = this;
			var children = this._children( 'panel', 'section' );

			api.panel.each( function( child ) {

				if ( !child.params.panel ) {

					return;

				}

				if ( child.params.panel !== panel.id ) {

					return;

				}

				children.push( child );

			} );

			children.sort( api.utils.prioritySort );

			var activeCount = 0;

			_( children ).each( function( child ) {

				if ( child.active() && child.isContextuallyActive() ) {

					activeCount += 1;

				}

			} );

			return ( activeCount !== 0 );

		}

	} );


	// Extend Section
	var _sectionEmbed                = wp.customize.Section.prototype.embed;
	var _sectionIsContextuallyActive = wp.customize.Section.prototype.isContextuallyActive;
	var _sectionAttachEvents         = wp.customize.Section.prototype.attachEvents;

	wp.customize.Section = wp.customize.Section.extend( {
		attachEvents        : function() {

			if (
				'pawfect_section' !== this.params.type ||
				'undefined' === typeof this.params.section
			) {

				_sectionAttachEvents.call( this );

				return;

			}

			_sectionAttachEvents.call( this );

			var section = this;

			section.expanded.bind( function( expanded ) {

				var parent = api.section( section.params.section );

				if ( expanded ) {

					parent.contentContainer.addClass( 'current-section-parent' );

				} else {

					parent.contentContainer.removeClass( 'current-section-parent' );

				}

			} );

			section.container.find( '.customize-section-back' )
				.off( 'click keydown' )
				.on( 'click keydown', function( event ) {

					if ( api.utils.isKeydownButNotEnterEvent( event ) ) {

						return;

					}

					event.preventDefault(); // Keep this AFTER the key filter above

					if ( section.expanded() ) {

						api.section( section.params.section ).expand();

					}

				} );

		},
		embed               : function() {

			if (
				'pawfect_section' !== this.params.type ||
				'undefined' === typeof this.params.section
			) {

				_sectionEmbed.call( this );

				return;

			}

			_sectionEmbed.call( this );

			var section         = this;
			var parentContainer = $( '#sub-accordion-section-' + this.params.section );

			parentContainer.append( section.headContainer );

		},
		isContextuallyActive: function() {

			if (
				'pawfect_section' !== this.params.type
			) {

				return _sectionIsContextuallyActive.call( this );

			}

			var section  = this;
			var children = this._children( 'section', 'control' );

			api.section.each( function( child ) {

				if ( !child.params.section ) {

					return;

				}

				if ( child.params.section !== section.id ) {

					return;

				}

				children.push( child );

			} );

			children.sort( api.utils.prioritySort );

			var activeCount = 0;

			_( children ).each( function( child ) {

				if ( 'undefined' !== typeof child.isContextuallyActive ) {

					if ( child.active() && child.isContextuallyActive() ) {

						activeCount += 1;

					}

				} else {

					if ( child.active() ) {

						activeCount += 1;

					}

				}

			} );

			return ( activeCount !== 0 );

		}

	} );

	// Tooltip injector
	api.bind( 'ready', function() {
        function convertDescriptionsToTooltips() {
            $('.customize-control').each(function() {
                var $control = $(this);
                if ($control.hasClass('pawfect-tooltip-processed')) return;

                var $desc = $control.find('.customize-control-description');
                var $title = $control.find('.customize-control-title');
                
                // Exclude repeater controls because they have nested titles and descriptions
                if ($control.find('.customizer-repeater-general-control-repeater').length > 0) {
                    return;
                }
                
                // Exclude some controls from getting a tooltip if they are explicitly designed to have large descriptions, like the Upgrade Notices!
                if ($desc.find('div, a').length > 0 && $desc.text().indexOf('Upgrade') !== -1) {
                    return; // Skip complex HTML descriptions (like the upgrade notice)
                }
                
                // Exclude heading controls since they often contain important setup instructions
                if ($control.hasClass('customize-control-pawfect-heading')) {
                    return; 
                }
                
                if ($desc.length && $title.length && $desc.text().trim() !== '') {
                    // Create info icon
                    var infoIcon = $('<span class="pawfect-tooltip-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm-1-11v6h2v-6h-2zm1-4a1.25 1.25 0 1 0 0 2.5A1.25 1.25 0 0 0 12 7z"/></svg></span>');
                    
                    // Wrap description in tooltip popup
                    var $tooltipWrapper = $('<div class="pawfect-tooltip-popup"></div>').append($desc.clone());
                    
                    infoIcon.append($tooltipWrapper);
                    
                    // Wrap title text so we can flex align it
                    var $titleInner = $('<span class="pawfect-title-text" style="display:inline-block; max-width:85%;"></span>').append($title.contents());
                    $title.empty().append($titleInner).append(infoIcon);
                    $title.css({
                        'display': 'flex',
                        'align-items': 'center',
                        'justify-content': 'space-between'
                    });
                    
                    // Remove original description
                    $desc.hide();
                    
                    $control.addClass('pawfect-tooltip-processed');
                }
            });
        }
        
        convertDescriptionsToTooltips();
        
        // Listen for dynamically added controls
        var observer = new MutationObserver(function(mutations) {
            var shouldRun = false;
            mutations.forEach(function(mutation) {
                if (mutation.addedNodes.length) {
                    shouldRun = true;
                }
            });
            if (shouldRun) {
                convertDescriptionsToTooltips();
            }
        });
        
        var targetNode = document.getElementById('customize-theme-controls');
        if (targetNode) {
            observer.observe(targetNode, { childList: true, subtree: true });
        }
	});

} )( jQuery );
