/* global wp, jQuery */
wp.customize.controlConstructor['kirki-iconpicker'] = wp.customize.Control.extend({

    ready: function() {
        var self = this;

        // Picker toggle
        this.container.on( 'click', '.kirki-iconpicker-picker-btn', function( e ) {
            e.preventDefault();
            self.togglePicker();
        });

        // Tab switching
        this.container.on( 'click', '.kirki-iconpicker-tab', function( e ) {
            e.preventDefault();
            self.switchTab( jQuery( this ).data( 'tab' ) );
        });

        // Icon selection
        this.container.on( 'click', '.kirki-iconpicker-icons-container i', function( e ) {
            e.preventDefault();
            self.selectIcon( jQuery( this ).data( 'icon' ) );
        });

        // Search functionality
        this.container.on( 'input', '.kirki-iconpicker-search', function( e ) {
            self.searchIcons( jQuery( this ).val() );
        });

        // Input change
        this.container.on( 'input change', '.kirki-iconpicker-input', function( e ) {
            self.updatePreview( jQuery( this ).val() );
        });

        // Close picker when clicking outside
        jQuery( document ).on( 'click', function( e ) {
            if ( ! jQuery( e.target ).closest( '.kirki-iconpicker-control' ).length ) {
                self.closePicker();
            }
        });

        // Initialize preview
        self.updatePreview( this.setting.get() );
    },

    togglePicker: function() {
        var picker = this.container.find( '.kirki-iconpicker-picker-popover' );
        picker.toggleClass( 'active' );
    },

    closePicker: function() {
        var picker = this.container.find( '.kirki-iconpicker-picker-popover' );
        picker.removeClass( 'active' );
    },

    switchTab: function( tab ) {
        // Update tab buttons
        this.container.find( '.kirki-iconpicker-tab' ).removeClass( 'active' );
        this.container.find( '.kirki-iconpicker-tab[data-tab="' + tab + '"]' ).addClass( 'active' );

        // Update tab content
        this.container.find( '.kirki-iconpicker-icons-tab' ).removeClass( 'active' );
        this.container.find( '.kirki-iconpicker-icons-' + tab ).addClass( 'active' );
    },

    selectIcon: function( icon ) {
        var input = this.container.find( '.kirki-iconpicker-input' );
        input.val( icon ).trigger( 'change' );
        this.updatePreview( icon );
        this.closePicker();
    },

    updatePreview: function( icon ) {
        var preview = this.container.find( '.kirki-iconpicker-preview i' );
        preview.attr( 'class', icon );

        // Hide preview if no icon selected
        if ( ! icon || icon === '' ) {
            preview.hide();
        } else {
            preview.show();
        }
    },

    searchIcons: function( searchTerm ) {
        var activeTab = this.container.find( '.kirki-iconpicker-icons-tab.active' );
        var icons = activeTab.find( 'i' );

        if ( searchTerm === '' ) {
            icons.show();
            return;
        }

        searchTerm = searchTerm.toLowerCase();
        icons.each( function() {
            var icon = jQuery( this );
            var iconName = icon.data( 'icon' ).toLowerCase();
            var iconTitle = icon.attr( 'title' ) ? icon.attr( 'title' ).toLowerCase() : '';

            if ( iconName.indexOf( searchTerm ) !== -1 || iconTitle.indexOf( searchTerm ) !== -1 ) {
                icon.show();
            } else {
                icon.hide();
            }
        });
    }
});

// Support for repeater fields
jQuery( document ).ready( function( $ ) {
    // Initialize IconPicker controls in repeater
    $( document ).on( 'kirki-repeater-row-added', function( e, row ) {
        initializeIconPickerInRow( row );
    });

    function initializeIconPickerInRow( row ) {
        var iconPickerControls = row.find( '.kirki-iconpicker-control' );
        
        iconPickerControls.each( function() {
            var control = $( this );

            // Bind events for repeater row controls
            control.off( '.iconpicker' );
            
            control.on( 'click.iconpicker', '.kirki-iconpicker-picker-btn', function( e ) {
                e.preventDefault();
                togglePickerInRow( control );
            });

            control.on( 'click.iconpicker', '.kirki-iconpicker-tab', function( e ) {
                e.preventDefault();
                switchTabInRow( control, $( this ).data( 'tab' ) );
            });

            control.on( 'click.iconpicker', '.kirki-iconpicker-icons-container i', function( e ) {
                e.preventDefault();
                selectIconInRow( control, $( this ).data( 'icon' ) );
            });

            control.on( 'input.iconpicker', '.kirki-iconpicker-search', function( e ) {
                searchIconsInRow( control, $( this ).val() );
            });

            control.on( 'input.iconpicker change.iconpicker', '.kirki-iconpicker-input', function( e ) {
                updatePreviewInRow( control, $( this ).val() );
            });
        });
    }

    // Helper functions for repeater rows
    function togglePickerInRow( control ) {
        var picker = control.find( '.kirki-iconpicker-picker-popover' );
        picker.toggleClass( 'active' );
    }

    function switchTabInRow( control, tab ) {
        control.find( '.kirki-iconpicker-tab' ).removeClass( 'active' );
        control.find( '.kirki-iconpicker-tab[data-tab="' + tab + '"]' ).addClass( 'active' );
        control.find( '.kirki-iconpicker-icons-tab' ).removeClass( 'active' );
        control.find( '.kirki-iconpicker-icons-' + tab ).addClass( 'active' );
    }

    function selectIconInRow( control, icon ) {
        var input = control.find( '.kirki-iconpicker-input' );
        input.val( icon ).trigger( 'change' );
        updatePreviewInRow( control, icon );
        control.find( '.kirki-iconpicker-picker-popover' ).removeClass( 'active' );
    }

    function updatePreviewInRow( control, icon ) {
        var preview = control.find( '.kirki-iconpicker-preview i' );
        preview.attr( 'class', icon );
        
        if ( ! icon || icon === '' ) {
            preview.hide();
        } else {
            preview.show();
        }
    }

    function searchIconsInRow( control, searchTerm ) {
        var activeTab = control.find( '.kirki-iconpicker-icons-tab.active' );
        var icons = activeTab.find( 'i' );
        
        if ( searchTerm === '' ) {
            icons.show();
            return;
        }
        
        searchTerm = searchTerm.toLowerCase();
        icons.each( function() {
            var icon = $( this );
            var iconName = icon.data( 'icon' ).toLowerCase();
            var iconTitle = icon.attr( 'title' ) ? icon.attr( 'title' ).toLowerCase() : '';
            
            if ( iconName.indexOf( searchTerm ) !== -1 || iconTitle.indexOf( searchTerm ) !== -1 ) {
                icon.show();
            } else {
                icon.hide();
            }
        });
    }

    // Close picker when clicking outside
    $( document ).on( 'click', function( e ) {
        if ( ! $( e.target ).closest( '.kirki-iconpicker-control' ).length ) {
            $( '.kirki-iconpicker-picker-popover' ).removeClass( 'active' );
        }
    });

    // Fallback – initialize any existing repeater rows that were added before the listener.
    $('.repeater-row').each(function(){
        initializeIconPickerInRow( $(this) );
    });
});