/**
 * Admin Bar Custom Links Scripts
 *
 * @package Polanger_Dashboard_Tools_Pro
 * @since 3.2.0
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        var i18n = window.pdtAdminBarLinksI18n || {};
        function t(key) {
            return i18n[key] || '';
        }
        
        var linkIndex = $('.pdt-link-item').length;
        
        // Toggle link content
        $(document).on('click', '.pdt-link-toggle', function(e) {
            e.preventDefault();
            var $item = $(this).closest('.pdt-link-item');
            var $content = $item.find('.pdt-link-content');
            var $icon = $(this).find('.dashicons');
            
            $content.slideToggle(200);
            $icon.toggleClass('dashicons-arrow-down-alt2 dashicons-arrow-up-alt2');
            $(this).attr('aria-expanded', $content.is(':visible'));
        });
        
        // Update title preview on input
        $(document).on('input', '.pdt-link-title-input', function() {
            var title = $(this).val() || t('newLinkText');
            $(this).closest('.pdt-link-item').find('.pdt-link-title-preview').text(title);
        });
        
        // Add new link
        $('#pdt-add-new-link').on('click', function() {
            var template = getLinkTemplate(linkIndex);
            $('#pdt-custom-links-container').append(template);
            
            // Open the new item
            var $newItem = $('#pdt-custom-links-container .pdt-link-item').last();
            $newItem.find('.pdt-link-content').slideDown(200);
            $newItem.find('.pdt-link-toggle .dashicons').removeClass('dashicons-arrow-down-alt2').addClass('dashicons-arrow-up-alt2');
            $newItem.find('.pdt-link-title-input').focus();
            
            linkIndex++;
        });
        
        // Remove link
        $(document).on('click', '.pdt-link-remove', function(e) {
            e.preventDefault();
            if (confirm(t('removeConfirm'))) {
                $(this).closest('.pdt-link-item').slideUp(200, function() {
                    $(this).remove();
                    reindexLinks();
                });
            }
        });
        
        // Add submenu item
        $(document).on('click', '.pdt-add-submenu-btn', function() {
            var $container = $(this).siblings('.pdt-submenu-items');
            var parentIndex = $container.data('parent');
            var subIndex = $container.find('.pdt-submenu-item').length;
            
            var template = getSubmenuTemplate(parentIndex, subIndex);
            $container.append(template);
            $container.find('.pdt-submenu-item').last().find('input[type="text"]').focus();
        });
        
        // Remove submenu item
        $(document).on('click', '.pdt-remove-submenu-btn', function(e) {
            e.preventDefault();
            $(this).closest('.pdt-submenu-item').slideUp(200, function() {
                var $container = $(this).closest('.pdt-submenu-items');
                $(this).remove();
                reindexSubmenus($container);
            });
        });
        
        // Icon picker
        $(document).on('click', '.pdt-icon-picker-btn', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            var $btn = $(this);
            var $selector = $btn.closest('.pdt-icon-selector');
            var $input = $selector.find('.pdt-icon-input');
            
            // Check if picker already exists
            if ($('.pdt-icon-picker-popup').length) {
                $('.pdt-icon-picker-popup').remove();
                return;
            }
            
            var popup = createIconPicker($btn, $input);
            $('body').append(popup);
            
            // Position popup - use getBoundingClientRect for fixed positioning
            var btnRect = $btn[0].getBoundingClientRect();
            $('.pdt-icon-picker-popup').css({
                top: btnRect.bottom + 5,
                left: btnRect.left
            });
        });
        
        // Close icon picker on outside click
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.pdt-icon-picker-btn, .pdt-icon-picker-popup').length) {
                $('.pdt-icon-picker-popup').remove();
            }
        });
        
        // Select icon
        $(document).on('click', '.pdt-icon-picker-popup .pdt-icon-option', function() {
            var icon = $(this).data('icon');
            var $popup = $(this).closest('.pdt-icon-picker-popup');
            var $btn = $popup.data('btn');
            var $input = $popup.data('input');
            
            $input.val(icon);
            $btn.find('.dashicons').attr('class', 'dashicons ' + icon);
            $popup.remove();
        });
        
        // Search icons
        $(document).on('input', '.pdt-icon-search', function() {
            var search = $(this).val().toLowerCase();
            $(this).closest('.pdt-icon-picker-popup').find('.pdt-icon-option').each(function() {
                var icon = $(this).data('icon').toLowerCase();
                $(this).toggle(icon.indexOf(search) > -1);
            });
        });
        
        // Reindex links after removal
        function reindexLinks() {
            $('.pdt-link-item').each(function(index) {
                $(this).attr('data-index', index);
                $(this).find('input, select').each(function() {
                    var name = $(this).attr('name');
                    if (name) {
                        name = name.replace(/pdt_admin_bar_settings\[links\]\[\d+\]/, 'pdt_admin_bar_settings[links][' + index + ']');
                        $(this).attr('name', name);
                    }
                });
                $(this).find('.pdt-submenu-items').attr('data-parent', index);
            });
            linkIndex = $('.pdt-link-item').length;
        }
        
        // Reindex submenus after removal
        function reindexSubmenus($container) {
            var parentIndex = $container.data('parent');
            $container.find('.pdt-submenu-item').each(function(index) {
                $(this).attr('data-sub-index', index);
                $(this).find('input, select').each(function() {
                    var name = $(this).attr('name');
                    if (name) {
                        name = name.replace(/\[submenu\]\[\d+\]/, '[submenu][' + index + ']');
                        $(this).attr('name', name);
                    }
                });
            });
        }
        
        // Get link template
        function getLinkTemplate(index) {
            return '<div class="pdt-link-item" data-index="' + index + '">' +
                '<div class="pdt-link-header">' +
                    '<span class="pdt-link-drag-handle dashicons dashicons-menu"></span>' +
                    '<span class="pdt-link-title-preview">' + t('newLinkText') + '</span>' +
                    '<button type="button" class="pdt-link-toggle" aria-expanded="false">' +
                        '<span class="dashicons dashicons-arrow-down-alt2"></span>' +
                    '</button>' +
                    '<button type="button" class="pdt-link-remove" title="' + t('removeText') + '">' +
                        '<span class="dashicons dashicons-trash"></span>' +
                    '</button>' +
                '</div>' +
                '<div class="pdt-link-content pdt-is-hidden">' +
                    '<div class="pdt-link-row">' +
                        '<div class="pdt-link-field">' +
                            '<label>' + t('titleLabel') + '</label>' +
                            '<input type="text" name="pdt_admin_bar_settings[links][' + index + '][title]" value="" class="pdt-link-title-input" placeholder="' + t('titlePlaceholder') + '" />' +
                        '</div>' +
                        '<div class="pdt-link-field">' +
                            '<label>' + t('urlLabel') + '</label>' +
                            '<input type="url" name="pdt_admin_bar_settings[links][' + index + '][url]" value="" placeholder="' + t('urlPlaceholder') + '" />' +
                        '</div>' +
                    '</div>' +
                    '<div class="pdt-link-row">' +
                        '<div class="pdt-link-field">' +
                            '<label>' + t('iconLabel') + '</label>' +
                            '<div class="pdt-icon-selector">' +
                                '<button type="button" class="pdt-icon-picker-btn">' +
                                    '<span class="dashicons dashicons-admin-links"></span>' +
                                    '<span class="pdt-icon-picker-label">' + t('selectIconText') + '</span>' +
                                '</button>' +
                                '<input type="hidden" name="pdt_admin_bar_settings[links][' + index + '][icon]" value="dashicons-admin-links" class="pdt-icon-input" />' +
                            '</div>' +
                        '</div>' +
                        '<div class="pdt-link-field">' +
                            '<label>' + t('openInLabel') + '</label>' +
                            '<select name="pdt_admin_bar_settings[links][' + index + '][target]">' +
                                '<option value="_self">' + t('sameWindowText') + '</option>' +
                                '<option value="_blank">' + t('newTabText') + '</option>' +
                            '</select>' +
                        '</div>' +
                    '</div>' +
                    '<div class="pdt-submenu-section">' +
                        '<h4>' + t('submenuItemsText') + '</h4>' +
                        '<div class="pdt-submenu-items" data-parent="' + index + '"></div>' +
                        '<button type="button" class="button pdt-add-submenu-btn">' +
                            '<span class="dashicons dashicons-plus"></span> ' + t('addSubmenuItemText') +
                        '</button>' +
                    '</div>' +
                '</div>' +
            '</div>';
        }
        
        // Get submenu template
        function getSubmenuTemplate(parentIndex, subIndex) {
            return '<div class="pdt-submenu-item" data-sub-index="' + subIndex + '">' +
                '<div class="pdt-submenu-row">' +
                    '<input type="text" name="pdt_admin_bar_settings[links][' + parentIndex + '][submenu][' + subIndex + '][title]" value="" placeholder="' + t('submenuTitlePlaceholder') + '" />' +
                    '<input type="url" name="pdt_admin_bar_settings[links][' + parentIndex + '][submenu][' + subIndex + '][url]" value="" placeholder="' + t('urlPlaceholder') + '" />' +
                    '<select name="pdt_admin_bar_settings[links][' + parentIndex + '][submenu][' + subIndex + '][target]">' +
                        '<option value="_self">' + t('sameText') + '</option>' +
                        '<option value="_blank">' + t('newTabText') + '</option>' +
                    '</select>' +
                    '<button type="button" class="pdt-remove-submenu-btn" title="' + t('removeText') + '">' +
                        '<span class="dashicons dashicons-no-alt"></span>' +
                    '</button>' +
                '</div>' +
            '</div>';
        }
        
        // Create icon picker popup
        function createIconPicker($btn, $input) {
            var icons = [
                'dashicons-admin-site', 'dashicons-admin-site-alt', 'dashicons-admin-site-alt2', 'dashicons-admin-site-alt3',
                'dashicons-dashboard', 'dashicons-admin-post', 'dashicons-admin-media', 'dashicons-admin-links',
                'dashicons-admin-page', 'dashicons-admin-comments', 'dashicons-admin-appearance', 'dashicons-admin-plugins',
                'dashicons-admin-users', 'dashicons-admin-tools', 'dashicons-admin-settings', 'dashicons-admin-network',
                'dashicons-admin-home', 'dashicons-admin-generic', 'dashicons-admin-collapse', 'dashicons-filter',
                'dashicons-admin-customizer', 'dashicons-admin-multisite', 'dashicons-welcome-write-blog', 'dashicons-welcome-add-page',
                'dashicons-welcome-view-site', 'dashicons-welcome-widgets-menus', 'dashicons-welcome-comments', 'dashicons-welcome-learn-more',
                'dashicons-format-aside', 'dashicons-format-image', 'dashicons-format-gallery', 'dashicons-format-video',
                'dashicons-format-status', 'dashicons-format-quote', 'dashicons-format-chat', 'dashicons-format-audio',
                'dashicons-camera', 'dashicons-images-alt', 'dashicons-images-alt2', 'dashicons-video-alt',
                'dashicons-video-alt2', 'dashicons-video-alt3', 'dashicons-media-archive', 'dashicons-media-audio',
                'dashicons-media-code', 'dashicons-media-default', 'dashicons-media-document', 'dashicons-media-interactive',
                'dashicons-media-spreadsheet', 'dashicons-media-text', 'dashicons-media-video', 'dashicons-playlist-audio',
                'dashicons-playlist-video', 'dashicons-controls-play', 'dashicons-controls-pause', 'dashicons-controls-forward',
                'dashicons-controls-skipforward', 'dashicons-controls-back', 'dashicons-controls-skipback', 'dashicons-controls-repeat',
                'dashicons-controls-volumeon', 'dashicons-controls-volumeoff', 'dashicons-image-crop', 'dashicons-image-rotate',
                'dashicons-image-rotate-left', 'dashicons-image-rotate-right', 'dashicons-image-flip-vertical', 'dashicons-image-flip-horizontal',
                'dashicons-image-filter', 'dashicons-undo', 'dashicons-redo', 'dashicons-editor-bold',
                'dashicons-editor-italic', 'dashicons-editor-ul', 'dashicons-editor-ol', 'dashicons-editor-quote',
                'dashicons-editor-alignleft', 'dashicons-editor-aligncenter', 'dashicons-editor-alignright', 'dashicons-editor-insertmore',
                'dashicons-editor-spellcheck', 'dashicons-editor-expand', 'dashicons-editor-contract', 'dashicons-editor-kitchensink',
                'dashicons-editor-underline', 'dashicons-editor-justify', 'dashicons-editor-textcolor', 'dashicons-editor-paste-word',
                'dashicons-editor-paste-text', 'dashicons-editor-removeformatting', 'dashicons-editor-video', 'dashicons-editor-customchar',
                'dashicons-editor-outdent', 'dashicons-editor-indent', 'dashicons-editor-help', 'dashicons-editor-strikethrough',
                'dashicons-editor-unlink', 'dashicons-editor-rtl', 'dashicons-editor-ltr', 'dashicons-editor-break',
                'dashicons-editor-code', 'dashicons-editor-paragraph', 'dashicons-editor-table', 'dashicons-align-left',
                'dashicons-align-right', 'dashicons-align-center', 'dashicons-align-none', 'dashicons-lock',
                'dashicons-unlock', 'dashicons-calendar', 'dashicons-calendar-alt', 'dashicons-visibility',
                'dashicons-hidden', 'dashicons-post-status', 'dashicons-edit', 'dashicons-trash',
                'dashicons-sticky', 'dashicons-external', 'dashicons-arrow-up', 'dashicons-arrow-down',
                'dashicons-arrow-right', 'dashicons-arrow-left', 'dashicons-arrow-up-alt', 'dashicons-arrow-down-alt',
                'dashicons-arrow-right-alt', 'dashicons-arrow-left-alt', 'dashicons-arrow-up-alt2', 'dashicons-arrow-down-alt2',
                'dashicons-arrow-right-alt2', 'dashicons-arrow-left-alt2', 'dashicons-sort', 'dashicons-leftright',
                'dashicons-randomize', 'dashicons-list-view', 'dashicons-exerpt-view', 'dashicons-grid-view',
                'dashicons-move', 'dashicons-share', 'dashicons-share-alt', 'dashicons-share-alt2',
                'dashicons-twitter', 'dashicons-rss', 'dashicons-email', 'dashicons-email-alt',
                'dashicons-email-alt2', 'dashicons-facebook', 'dashicons-facebook-alt', 'dashicons-googleplus',
                'dashicons-networking', 'dashicons-hammer', 'dashicons-art', 'dashicons-migrate',
                'dashicons-performance', 'dashicons-universal-access', 'dashicons-universal-access-alt', 'dashicons-tickets',
                'dashicons-nametag', 'dashicons-clipboard', 'dashicons-heart', 'dashicons-megaphone',
                'dashicons-schedule', 'dashicons-wordpress', 'dashicons-wordpress-alt', 'dashicons-pressthis',
                'dashicons-update', 'dashicons-update-alt', 'dashicons-screenoptions', 'dashicons-info',
                'dashicons-cart', 'dashicons-feedback', 'dashicons-cloud', 'dashicons-translation',
                'dashicons-tag', 'dashicons-category', 'dashicons-archive', 'dashicons-tagcloud',
                'dashicons-text', 'dashicons-yes', 'dashicons-yes-alt', 'dashicons-no',
                'dashicons-no-alt', 'dashicons-plus', 'dashicons-plus-alt', 'dashicons-plus-alt2',
                'dashicons-minus', 'dashicons-dismiss', 'dashicons-marker', 'dashicons-star-filled',
                'dashicons-star-half', 'dashicons-star-empty', 'dashicons-flag', 'dashicons-warning',
                'dashicons-location', 'dashicons-location-alt', 'dashicons-vault', 'dashicons-shield',
                'dashicons-shield-alt', 'dashicons-sos', 'dashicons-search', 'dashicons-slides',
                'dashicons-analytics', 'dashicons-chart-pie', 'dashicons-chart-bar', 'dashicons-chart-line',
                'dashicons-chart-area', 'dashicons-groups', 'dashicons-businessman', 'dashicons-businesswoman',
                'dashicons-businessperson', 'dashicons-id', 'dashicons-id-alt', 'dashicons-products',
                'dashicons-awards', 'dashicons-forms', 'dashicons-testimonial', 'dashicons-portfolio',
                'dashicons-book', 'dashicons-book-alt', 'dashicons-download', 'dashicons-upload',
                'dashicons-backup', 'dashicons-clock', 'dashicons-lightbulb', 'dashicons-microphone',
                'dashicons-desktop', 'dashicons-laptop', 'dashicons-tablet', 'dashicons-smartphone',
                'dashicons-phone', 'dashicons-index-card', 'dashicons-carrot', 'dashicons-building',
                'dashicons-store', 'dashicons-album', 'dashicons-palmtree', 'dashicons-tickets-alt',
                'dashicons-money', 'dashicons-money-alt', 'dashicons-smiley', 'dashicons-thumbs-up',
                'dashicons-thumbs-down', 'dashicons-layout', 'dashicons-paperclip', 'dashicons-color-picker',
                'dashicons-edit-large', 'dashicons-edit-page', 'dashicons-airplane', 'dashicons-bank',
                'dashicons-beer', 'dashicons-calculator', 'dashicons-car', 'dashicons-coffee',
                'dashicons-drumstick', 'dashicons-food', 'dashicons-fullscreen-alt', 'dashicons-fullscreen-exit-alt',
                'dashicons-games', 'dashicons-hourglass', 'dashicons-open-folder', 'dashicons-pdf',
                'dashicons-pets', 'dashicons-printer', 'dashicons-privacy', 'dashicons-superhero',
                'dashicons-superhero-alt', 'dashicons-database', 'dashicons-database-add', 'dashicons-database-export',
                'dashicons-database-import', 'dashicons-database-remove', 'dashicons-database-view', 'dashicons-html'
            ];
            
            var html = '<div class="pdt-icon-picker-popup">' +
                '<input type="text" class="pdt-icon-search" placeholder="' + t('searchIconsPlaceholder') + '" />' +
                '<div class="pdt-icon-grid">';
            
            icons.forEach(function(icon) {
                html += '<span class="pdt-icon-option" data-icon="' + icon + '" title="' + icon + '">' +
                    '<span class="dashicons ' + icon + '"></span>' +
                '</span>';
            });
            
            html += '</div></div>';
            
            var $popup = $(html);
            $popup.data('btn', $btn);
            $popup.data('input', $input);
            
            return $popup;
        }
        
    });
    
})(jQuery);
