(function ($) {
    'use strict';

    // Font Awesome 6 Free Icons - Verified list for website building
    // Only includes icons confirmed to exist in FA6 Free
    var fontAwesomeIcons = {

        // ===== ANIMALS & NATURE =====
        animals: [
            'dog', 'cat', 'paw', 'dove', 'fish', 'fish-fins', 'horse', 'horse-head', 'spider',
            'frog', 'crow', 'feather', 'feather-pointed', 'hippo', 'otter', 'dragon', 'kiwi-bird',
            'locust', 'mosquito', 'worm', 'bugs', 'bug', 'shrimp', 'cow'
        ],

        nature: [
            'tree', 'leaf', 'seedling', 'plant-wilt', 'clover', 'sun', 'moon', 'cloud', 'cloud-sun',
            'cloud-moon', 'cloud-rain', 'cloud-showers-heavy', 'cloud-bolt', 'snowflake', 'wind',
            'tornado', 'rainbow', 'umbrella', 'water', 'fire', 'fire-flame-curved',
            'mountain', 'mountain-sun', 'volcano', 'earth-americas', 'earth-europe', 'earth-asia',
            'globe', 'meteor'
        ],

        // ===== PET CARE & GROOMING =====
        petcare: [
            'bone', 'shield-dog', 'shield-cat', 'shower', 'scissors', 'brush',
            'spray-can-sparkles', 'spray-can', 'pump-soap', 'soap', 'droplet', 'tooth',
            'teeth', 'teeth-open'
        ],

        // ===== MEDICAL & HEALTH =====
        medical: [
            'stethoscope', 'syringe', 'vial', 'vials', 'suitcase-medical',
            'heart-pulse', 'heart', 'heart-circle-check', 'heart-circle-plus',
            'hospital', 'hospital-user', 'user-doctor', 'user-nurse',
            'weight-scale', 'lungs', 'lungs-virus',
            'bandage', 'virus', 'virus-slash', 'virus-covid', 'bacteria',
            'disease', 'biohazard', 'radiation', 'microscope', 'flask', 'flask-vial',
            'hand-holding-medical', 'notes-medical', 'clipboard-user',
            'wheelchair', 'wheelchair-move', 'crutch', 'person-cane', 'eye', 'eye-dropper',
            'brain', 'skull', 'head-side-virus', 'head-side-mask',
            'mask-face', 'hand-sparkles', 'pump-medical'
        ],

        // ===== BUSINESS & FINANCE =====
        business: [
            'briefcase', 'building', 'building-columns', 'landmark', 'industry', 'city',
            'chart-line', 'chart-bar', 'chart-pie', 'chart-area', 'chart-simple', 'chart-column',
            'money-bill', 'money-bill-wave', 'money-bills', 'money-check', 'money-check-dollar',
            'dollar-sign', 'euro-sign', 'sterling-sign', 'yen-sign', 'indian-rupee-sign',
            'vault', 'wallet', 'credit-card', 'cash-register',
            'receipt', 'file-invoice', 'file-invoice-dollar', 'calculator', 'percent',
            'handshake', 'hand-holding-dollar', 'hands-holding-circle',
            'scale-balanced', 'gavel',
            'sack-dollar', 'sack-xmark', 'hand-holding-hand', 'people-arrows',
            'sitemap', 'diagram-project', 'network-wired'
        ],

        // ===== AWARDS & ACHIEVEMENTS =====
        awards: [
            'award', 'medal', 'trophy', 'crown', 'certificate', 'ribbon', 'star', 'star-half',
            'star-half-stroke', 'ranking-star', 'thumbs-up', 'thumbs-down', 'hand-peace',
            'bolt', 'gem', 'diamond'
        ],

        // ===== SHOPPING & E-COMMERCE =====
        shopping: [
            'cart-shopping', 'cart-plus', 'cart-arrow-down', 'basket-shopping', 'bag-shopping',
            'store', 'store-slash', 'shop', 'shop-slash', 'shop-lock', 'tags', 'tag',
            'barcode', 'qrcode', 'gift', 'gifts', 'box', 'boxes-stacked',
            'truck', 'truck-fast', 'truck-ramp-box',
            'percent', 'money-bill-1-wave'
        ],

        // ===== COMMUNICATION =====
        communication: [
            'phone', 'phone-volume', 'phone-flip', 'mobile', 'mobile-screen',
            'mobile-button', 'tablet', 'tablet-button',
            'envelope', 'envelope-open', 'envelope-open-text', 'envelope-circle-check',
            'paper-plane', 'inbox', 'at', 'hashtag',
            'comment', 'comments', 'comment-dots', 'comment-slash', 'comment-medical',
            'quote-left', 'quote-right',
            'bullhorn', 'tower-broadcast', 'satellite-dish', 'rss',
            'fax', 'pager', 'voicemail', 'tty'
        ],

        // ===== SOCIAL MEDIA (Brands) =====
        social: [
            'facebook', 'facebook-f', 'facebook-messenger', 'twitter', 'x-twitter',
            'instagram', 'linkedin', 'linkedin-in', 'youtube', 'tiktok', 'snapchat',
            'pinterest', 'pinterest-p', 'whatsapp', 'telegram', 'discord', 'slack',
            'reddit', 'reddit-alien', 'tumblr', 'flickr', 'vimeo', 'vimeo-v',
            'dribbble', 'behance', 'deviantart', 'github', 'gitlab', 'bitbucket',
            'stack-overflow', 'codepen', 'medium', 'blogger', 'wordpress',
            'google', 'google-plus', 'apple', 'android', 'windows', 'linux', 'ubuntu',
            'chrome', 'firefox', 'safari', 'edge', 'opera', 'internet-explorer',
            'amazon', 'paypal', 'stripe', 'cc-visa', 'cc-mastercard', 'cc-amex',
            'cc-paypal', 'cc-stripe', 'cc-apple-pay', 'cc-amazon-pay', 'bitcoin',
            'ethereum', 'spotify', 'soundcloud', 'twitch', 'steam', 'xbox', 'playstation',
            'skype', 'viber', 'line', 'weixin', 'qq', 'weibo', 'vk', 'odnoklassniki',
            'yelp', 'airbnb', 'shopify', 'etsy', 'ebay',
            'dropbox', 'google-drive', 'creative-commons', 'angular', 'react',
            'vuejs', 'node-js', 'npm', 'yarn', 'python', 'java', 'php', 'laravel',
            'symfony', 'docker', 'aws', 'figma', 'sketch', 'invision', 'trello',
            'jira', 'confluence', 'notion', 'mailchimp', 'hubspot', 'salesforce', 'bluesky'
        ],

        // ===== TIME & CALENDAR =====
        time: [
            'clock', 'clock-rotate-left', 'calendar', 'calendar-days', 'calendar-week',
            'calendar-check', 'calendar-plus', 'calendar-minus', 'calendar-xmark', 'calendar-day',
            'hourglass', 'hourglass-start', 'hourglass-half', 'hourglass-end',
            'stopwatch', 'stopwatch-20', 'bell', 'bell-slash', 'bell-concierge',
            'business-time'
        ],

        // ===== NAVIGATION & UI =====
        navigation: [
            'bars', 'bars-staggered', 'grip', 'grip-lines', 'grip-vertical', 'ellipsis',
            'ellipsis-vertical', 'xmark', 'check', 'check-double', 'plus', 'minus',
            'arrow-right', 'arrow-left', 'arrow-up', 'arrow-down', 'arrow-right-long',
            'arrow-left-long', 'arrow-up-long', 'arrow-down-long',
            'arrows-rotate', 'arrows-spin', 'arrows-up-down', 'arrows-left-right',
            'arrows-up-down-left-right', 'arrows-to-circle', 'up-down-left-right',
            'angles-right', 'angles-left', 'angles-up', 'angles-down',
            'chevron-right', 'chevron-left', 'chevron-up', 'chevron-down',
            'angle-right', 'angle-left', 'angle-up', 'angle-down',
            'caret-right', 'caret-left', 'caret-up', 'caret-down',
            'circle-arrow-right', 'circle-arrow-left', 'circle-arrow-up', 'circle-arrow-down',
            'arrow-up-right-from-square', 'arrow-right-from-bracket', 'arrow-right-to-bracket',
            'arrow-rotate-right', 'arrow-rotate-left',
            'reply', 'share', 'shuffle',
            'arrow-turn-up', 'arrow-turn-down', 'minimize', 'expand', 'compress',
            'up-right-and-down-left-from-center', 'down-left-and-up-right-to-center'
        ],

        // ===== STATUS & FEEDBACK =====
        status: [
            'circle-check', 'circle-xmark', 'circle-info', 'circle-question', 'circle-exclamation',
            'square-check', 'square-plus', 'square-minus',
            'triangle-exclamation', 'radiation', 'biohazard', 'skull-crossbones',
            'ban', 'lock', 'lock-open', 'unlock', 'unlock-keyhole', 'key', 'shield', 'shield-halved',
            'user-shield', 'fingerprint', 'eye', 'eye-slash',
            'spinner', 'circle-notch'
        ],

        // ===== USERS & PEOPLE =====
        users: [
            'user', 'users', 'user-plus', 'user-xmark',
            'user-gear', 'user-lock', 'user-shield', 'user-tag',
            'user-tie', 'user-graduate', 'user-ninja', 'user-secret',
            'user-group', 'people-group', 'people-line', 'people-roof', 'person',
            'person-walking', 'person-running', 'person-biking', 'person-swimming',
            'person-hiking', 'person-skiing', 'person-snowboarding', 'person-skating',
            'circle-user', 'id-card', 'id-badge', 'address-card', 'address-book',
            'child', 'children', 'baby', 'person-pregnant', 'person-breastfeeding',
            'person-dress', 'restroom', 'mars', 'venus', 'mars-and-venus', 'transgender',
            'wheelchair', 'wheelchair-move', 'person-cane',
            'hand', 'hand-pointer', 'hand-point-up', 'hand-point-right',
            'hand-point-down', 'hand-point-left', 'hand-peace', 'hand-back-fist',
            'hand-fist', 'handshake', 'hands-praying', 'hand-holding',
            'hand-holding-heart', 'hand-holding-hand', 'hands-holding', 'hands-holding-child',
            'people-arrows', 'house-user'
        ],

        // ===== FILES & DOCUMENTS =====
        files: [
            'file', 'file-lines', 'file-pdf', 'file-word', 'file-excel',
            'file-powerpoint', 'file-image', 'file-video', 'file-audio', 'file-code',
            'file-zipper', 'file-csv', 'file-contract', 'file-signature',
            'file-invoice', 'file-invoice-dollar',
            'file-circle-check', 'file-circle-plus', 'file-circle-minus', 'file-circle-xmark',
            'file-arrow-up', 'file-arrow-down', 'file-import', 'file-export',
            'folder', 'folder-open', 'folder-plus', 'folder-minus', 'folder-tree', 'folder-closed',
            'clipboard', 'clipboard-list', 'clipboard-check', 'clipboard-question',
            'paste', 'copy', 'clone', 'newspaper', 'book', 'book-open', 'book-bookmark',
            'bookmark', 'scroll', 'note-sticky'
        ],

        // ===== MEDIA & IMAGES =====
        media: [
            'image', 'images', 'photo-film', 'panorama', 'camera', 'camera-retro',
            'camera-rotate', 'video', 'film', 'clapperboard',
            'play', 'pause', 'stop', 'circle-play',
            'forward', 'backward', 'forward-step', 'backward-step', 'forward-fast', 'backward-fast',
            'volume-high', 'volume-low', 'volume-off', 'volume-xmark',
            'microphone', 'microphone-slash', 'microphone-lines', 'headphones',
            'headphones-simple', 'headset', 'music', 'radio', 'guitar',
            'drum', 'compact-disc', 'record-vinyl', 'ticket', 'masks-theater',
            'palette', 'brush', 'paintbrush', 'paint-roller', 'pen', 'pencil',
            'pen-fancy', 'pen-nib', 'pen-ruler', 'marker', 'highlighter', 'eraser',
            'crop', 'crop-simple', 'object-group', 'object-ungroup', 'icons', 'shapes',
            'draw-polygon', 'bezier-curve', 'wand-magic', 'wand-magic-sparkles',
            'swatchbook', 'fill-drip', 'droplet', 'eye-dropper', 'stamp'
        ],

        // ===== TECHNOLOGY & DEVICES =====
        technology: [
            'laptop', 'laptop-code', 'desktop', 'computer', 'display', 'tv', 'mobile', 'mobile-screen',
            'tablet', 'tablet-button', 'keyboard', 'computer-mouse', 'gamepad', 'headphones',
            'microchip', 'memory', 'hard-drive', 'server', 'database', 'ethernet',
            'wifi', 'signal', 'satellite', 'satellite-dish', 'tower-cell', 'tower-broadcast',
            'network-wired', 'bluetooth', 'usb', 'plug', 'plug-circle-check',
            'battery-full', 'battery-three-quarters', 'battery-half', 'battery-quarter', 'battery-empty',
            'solar-panel', 'car-battery', 'charging-station', 'bolt', 'power-off',
            'code', 'code-branch', 'code-compare', 'code-fork', 'code-pull-request',
            'terminal',
            'bug', 'bug-slash', 'robot', 'qrcode', 'barcode',
            'print', 'fax', 'sim-card', 'sd-card', 'compact-disc',
            'floppy-disk', 'download', 'upload', 'cloud-arrow-up', 'cloud-arrow-down',
            'link', 'link-slash', 'paperclip', 'thumbtack', 'magnet',
            'gear', 'gears', 'wrench', 'screwdriver', 'screwdriver-wrench',
            'hammer', 'toolbox'
        ],

        // ===== LOCATION & MAPS =====
        location: [
            'location-dot', 'location-pin', 'location-crosshairs', 'location-arrow',
            'map', 'map-location', 'map-location-dot', 'map-pin', 'compass', 'signs-post',
            'route', 'road', 'diamond-turn-right', 'location-pin-lock',
            'earth-americas', 'earth-europe', 'earth-asia', 'earth-africa', 'earth-oceania',
            'globe', 'street-view', 'mountain', 'mountain-sun', 'mountain-city',
            'city', 'building', 'house', 'house-chimney', 'igloo', 'tent', 'campground',
            'flag', 'flag-checkered', 'flag-usa', 'landmark', 'landmark-dome', 'monument', 'archway',
            'dungeon', 'place-of-worship', 'church', 'mosque', 'synagogue', 'vihara',
            'torii-gate', 'kaaba', 'gopuram'
        ],

        // ===== TRANSPORTATION =====
        transport: [
            'car', 'car-side', 'car-rear', 'taxi', 'bus', 'bus-simple', 'van-shuttle',
            'truck', 'truck-pickup', 'truck-monster', 'truck-fast',
            'truck-medical', 'truck-ramp-box', 'trailer',
            'motorcycle', 'bicycle', 'person-biking', 'wheelchair', 'wheelchair-move',
            'train', 'train-subway', 'train-tram', 'cable-car', 'ferry', 'ship', 'anchor',
            'sailboat', 'plane', 'plane-departure', 'plane-arrival', 'plane-up',
            'helicopter', 'rocket', 'jet-fighter', 'road', 'road-bridge',
            'gas-pump', 'charging-station', 'square-parking', 'traffic-light'
        ],

        // ===== FOOD & DRINK =====
        food: [
            'utensils', 'bowl-food', 'bowl-rice', 'plate-wheat',
            'pizza-slice', 'burger', 'hotdog', 'bacon', 'egg', 'cheese', 'bread-slice',
            'cookie', 'cookie-bite', 'cake-candles', 'ice-cream', 'stroopwafel',
            'apple-whole', 'lemon', 'carrot', 'pepper-hot', 'drumstick-bite',
            'fish', 'fish-fins', 'shrimp', 'jar', 'jar-wheat', 'wheat-awn', 'seedling',
            'mug-hot', 'mug-saucer',
            'glass-water', 'glass-water-droplet', 'bottle-water', 'bottle-droplet',
            'wine-glass', 'wine-glass-empty', 'wine-bottle', 'champagne-glasses',
            'martini-glass', 'martini-glass-citrus', 'martini-glass-empty',
            'beer-mug-empty', 'whiskey-glass'
        ],

        // ===== BUILDINGS & PLACES =====
        buildings: [
            'house', 'house-chimney', 'house-user', 'house-medical', 'house-flag',
            'house-circle-check', 'house-circle-xmark', 'house-fire', 'house-flood-water',
            'building', 'building-columns', 'building-user', 'building-flag',
            'building-circle-check', 'building-circle-xmark', 'building-wheat',
            'hospital', 'hotel', 'school', 'school-flag', 'graduation-cap',
            'landmark', 'landmark-dome', 'landmark-flag',
            'church', 'mosque', 'synagogue', 'place-of-worship', 'gopuram',
            'store', 'store-slash', 'shop', 'shop-slash', 'industry',
            'city', 'tent', 'campground', 'igloo', 'kaaba', 'vihara', 'torii-gate',
            'monument', 'archway', 'dungeon', 'oil-well', 'tower-observation'
        ],

        // ===== SPORTS & FITNESS =====
        sports: [
            'futbol', 'football', 'baseball', 'basketball', 'volleyball', 'hockey-puck',
            'golf-ball-tee', 'table-tennis-paddle-ball', 'bowling-ball', 'dumbbell',
            'person-running', 'person-walking', 'person-biking', 'person-swimming',
            'person-hiking', 'person-skiing', 'person-skiing-nordic', 'person-snowboarding',
            'person-skating', 'medal', 'trophy', 'ranking-star', 'stopwatch',
            'heart-pulse', 'weight-scale', 'weight-hanging', 'bullseye',
            'chess', 'chess-board', 'chess-pawn', 'chess-rook', 'chess-knight',
            'chess-bishop', 'chess-queen', 'chess-king', 'dice', 'dice-d6', 'dice-d20',
            'puzzle-piece', 'gamepad', 'headset'
        ],

        // ===== EDUCATION =====
        education: [
            'book', 'book-open', 'book-open-reader', 'book-bookmark', 'book-atlas',
            'book-bible', 'book-journal-whills', 'book-quran', 'book-skull', 'book-tanakh',
            'graduation-cap', 'user-graduate', 'school', 'school-flag', 'chalkboard',
            'chalkboard-user', 'person-chalkboard', 'apple-whole', 'ruler', 'ruler-combined',
            'pen', 'pencil', 'pen-ruler', 'marker', 'highlighter', 'eraser',
            'microscope', 'flask', 'flask-vial', 'vial', 'vials', 'atom',
            'magnet', 'brain', 'lightbulb', 'compass-drafting', 'calculator',
            'square-root-variable', 'superscript', 'subscript',
            'spell-check', 'language', 'globe', 'earth-americas'
        ],

        // ===== SECURITY =====
        security: [
            'lock', 'lock-open', 'unlock', 'unlock-keyhole', 'key',
            'shield', 'shield-halved', 'shield-virus', 'shield-heart',
            'user-shield', 'user-lock', 'user-secret', 'fingerprint', 'id-card',
            'id-badge', 'passport', 'eye', 'eye-slash', 'mask', 'user-ninja',
            'ban', 'skull-crossbones', 'radiation', 'biohazard', 'tower-observation',
            'video', 'camera-rotate', 'bug', 'bug-slash', 'vault', 'file-shield'
        ],

        // ===== WEATHER =====
        weather: [
            'sun', 'moon', 'cloud', 'cloud-sun', 'cloud-moon', 'cloud-sun-rain', 'cloud-moon-rain',
            'cloud-rain', 'cloud-showers-heavy', 'cloud-showers-water', 'cloud-bolt',
            'bolt', 'bolt-lightning', 'snowflake', 'icicles',
            'temperature-high', 'temperature-low', 'temperature-arrow-up',
            'temperature-arrow-down', 'wind', 'tornado', 'hurricane', 'rainbow',
            'umbrella', 'umbrella-beach', 'smog', 'water', 'droplet'
        ],

        // ===== COMMON ICONS =====
        common: [
            'house', 'magnifying-glass', 'magnifying-glass-plus', 'magnifying-glass-minus',
            'filter', 'sort', 'sort-up', 'sort-down', 'sliders',
            'list', 'list-ul', 'list-ol', 'list-check', 'table', 'table-cells',
            'table-columns', 'table-list', 'border-all',
            'grip', 'grip-vertical', 'grip-lines', 'grip-lines-vertical',
            'align-left', 'align-center', 'align-right', 'align-justify',
            'indent', 'outdent', 'paragraph', 'text-height', 'text-width',
            'font', 'bold', 'italic', 'underline', 'strikethrough', 'subscript', 'superscript',
            'heading', 'quote-left', 'quote-right', 'code', 'link', 'link-slash',
            'scissors', 'copy', 'paste', 'clone', 'trash', 'trash-can',
            'trash-can-arrow-up', 'recycle', 'delete-left',
            'layer-group', 'object-group', 'object-ungroup', 'crop', 'crop-simple',
            'expand', 'compress', 'minimize',
            'up-right-and-down-left-from-center', 'down-left-and-up-right-to-center',
            'circle', 'square', 'rectangle-list', 'shapes', 'draw-polygon',
            'info', 'question', 'exclamation', 'circle-info', 'circle-question', 'circle-exclamation'
        ]
    };

    // Cache for loaded icons
    var iconsLoaded = false;
    var iconElements = [];

    wp.leatherhousecustomizerRepeater = {

        // Generate icon HTML elements
        generateIconElements: function() {
            if (iconsLoaded) return iconElements;

            iconElements = [];

            // Flatten all categories and create icon elements
            Object.keys(fontAwesomeIcons).forEach(function(category) {
                fontAwesomeIcons[category].forEach(function(iconName) {
                    // Determine if it's a brand icon or solid icon
                    var iconPrefix = (category === 'social') ? 'fa-brands' : 'fa-solid';
                    var iconClass = 'fa-' + iconName;

                    iconElements.push({
                        name: iconName,
                        prefix: iconPrefix,
                        iconClass: iconClass,
                        category: category
                    });
                });
            });

            iconsLoaded = true;
            return iconElements;
        },

        // Populate icon picker containers
        populateIconPickers: function() {
            var self = this;
            var icons = this.generateIconElements();

            $('.iconpicker-items').each(function() {
                var $container = $(this);

                // Check if already populated with new icons
                if ($container.data('icons-loaded')) return;

                // Clear existing icons (from static PHP file)
                $container.empty();

                // Add new icons
                icons.forEach(function(icon) {
                    var $icon = $('<i></i>')
                        .attr('data-type', 'iconpicker-item')
                        .attr('title', '.' + icon.name)
                        .attr('data-category', icon.category)
                        .attr('data-icon', icon.iconClass)
                        .attr('data-prefix', icon.prefix)
                        .addClass(icon.prefix)
                        .addClass(icon.iconClass);
                    $container.append($icon);
                });

                $container.data('icons-loaded', true);
            });
        },

        init: function () {
            var self = this;

            // Populate icon pickers with Font Awesome 6 icons
            this.populateIconPickers();

            // Handle icon click - use event delegation for dynamically added icons
            $(document).on('click', '.iconpicker-items>i', function () {
                var $icon = $(this);

                // Get only the icon name (e.g., fa-scissors) - prefix will be added in templates
                var iconClass = $icon.data('icon');
                var iconPrefix = $icon.data('prefix') || 'fa-solid';

                // Fallback: extract icon name from class list
                if (!iconClass) {
                    var classList = $icon.attr('class').split(/\s+/);
                    for (var i = 0; i < classList.length; i++) {
                        var cls = classList[i];
                        if (cls.indexOf('fa-') === 0 && cls !== 'fa-solid' && cls !== 'fa-brands' && cls !== 'fa-regular') {
                            iconClass = cls;
                            break;
                        }
                    }
                }

                var classInput = $icon.parents('.iconpicker-popover').prev().find('.icp');

                // Save only the icon name (e.g., fa-scissors)
                classInput.val(iconClass);
                classInput.attr('value', iconClass);

                // Preview with full class (prefix + icon)
                var iconPreview = classInput.next('.input-group-addon');
                var fullClass = iconPrefix + ' ' + iconClass;
                var iconElement = '<i class="' + fullClass + '"></i>';
                iconPreview.empty();
                iconPreview.append(iconElement);

                var th = $icon.parent().parent().parent();
                classInput.trigger('change');

                if (typeof leatherhouse_customizer_repeater_refresh_social_icons === 'function') {
                    leatherhouse_customizer_repeater_refresh_social_icons(th);
                }

                // Close the picker
                $icon.parents('.iconpicker-popover').removeClass('iconpicker-visible');

                return false;
            });
        },

        search: function ($searchField) {
            var itemsList = $searchField.parent().next().find('.iconpicker-items');
            var searchTerm = $searchField.val().toLowerCase();

            if (searchTerm.length > 0) {
                itemsList.children().each(function () {
                    var $icon = $(this);
                    var iconTitle = ($icon.attr('title') || '').toLowerCase();
                    var iconCategory = ($icon.attr('data-category') || '').toLowerCase();

                    if (iconTitle.indexOf(searchTerm) > -1 || iconCategory.indexOf(searchTerm) > -1) {
                        $icon.show();
                    } else {
                        $icon.hide();
                    }
                });
            } else {
                itemsList.children().show();
            }
        },

        iconPickerToggle: function ($input) {
            var iconPicker = $input.parent().next();

            // Re-populate icons if needed (for dynamically added repeater items)
            this.populateIconPickers();

            iconPicker.addClass('iconpicker-visible');
        }
    };

    $(document).ready(function () {
        wp.leatherhousecustomizerRepeater.init();

        $(document).on('keyup', '.iconpicker-search', function () {
            wp.leatherhousecustomizerRepeater.search($(this));
        });

        $(document).on('click', '.icp-auto', function () {
            wp.leatherhousecustomizerRepeater.iconPickerToggle($(this));
        });

        $(document).mouseup(function (e) {
            var container = $('.iconpicker-popover');

            if (!container.is(e.target) && container.has(e.target).length === 0) {
                container.removeClass('iconpicker-visible');
            }
        });

        // Re-init when new repeater items are added
        $(document).on('customizer-repeater-item-added', function() {
            wp.leatherhousecustomizerRepeater.populateIconPickers();
        });

    });

})(jQuery);
