/**
 * KANews Widget Admin Scripts
 * 
 * @package KANews
 * @subpackage Widgets
 * @version 1.0.0
 */

(function($) {
    'use strict';
    
    // Initialize when document is ready
    $(document).ready(function() {
        // Initialize accordions
        initAccordions();
        
        // Initialize sliders
        initSliders();
        
        // Initialize Select2 fields
        initSelect2Fields();
        
        // Initialize color pickers
        initColorPickers();
        
        // Initialize toggle fields
        initToggleFields();
        
        // Update widget titles with visibility indicators
        updateWidgetTitles();
        
        // Initialize all components
        initComponents();
    });
    
    /**
     * Initialize accordions
     */
    function initAccordions() {
        $('.kanews-accordion-header').off('click').on('click', function() {
            $(this).parent().toggleClass('is-active');
        });
    }
    
    /**
     * Initialize sliders
     */
    function initSliders() {
        $('.kanews-slider-element').each(function() {
            var $slider = $(this);
            var $target = $('#' + $slider.data('target'));
            var $value = $slider.siblings('.kanews-slider-value');
            
            // Get slider options
            var min = parseInt($slider.data('min')) || 0;
            var max = parseInt($slider.data('max')) || 100;
            var step = parseInt($slider.data('step')) || 1;
            var value = parseInt($slider.data('value')) || min;
            var unit = $slider.data('unit') || '';
            var default_value = parseInt($slider.data('default')) || min;
            
            // Initialize slider
            $slider.slider({
                min: min,
                max: max,
                step: step,
                value: value,
                slide: function(event, ui) {
                    $target.val(ui.value);
                    $value.text(ui.value + unit);
                    // Trigger input change event
                    $target.trigger('change');
                },
                change: function(event, ui) {
                    $target.val(ui.value);
                    $value.text(ui.value + unit);
                    // Trigger input change event
                    $target.trigger('change');
                }
            });
            
            // Set initial value
            if (!$target.val()) {
                $target.val(default_value);
                $value.text(default_value + unit);
                $slider.slider('value', default_value);
            }
        });
    }
    
    /**
     * Initialize Select2 fields
     */
    function initSelect2Fields() {
        // Mevcut Select2 örneklerini güvenli bir şekilde kaldır
        $('.select2-categories, .select2-tags, .select2-taxonomy, .select2-posts, .kanews-field-select2').each(function() {
            if ($(this).data('select2')) {
                $(this).select2('destroy');
            }
        });
        
        // Yinelenen Select2 konteynerlerini kaldır
        $('.select2-container').remove();
        
        // Genel Select2 alanları
        $('.kanews-field-select2').each(function() {
            var $select = $(this);
            initBasicSelect2($select);
        });
        
        // Categories
        $('.select2-categories').each(function() {
            var $select = $(this);
            var isMultiple = $select.prop('multiple');
            
            $select.select2({
                ajax: {
                    url: ajaxurl,
                    dataType: 'json',
                    delay: 250,
                    data: function(params) {
                        return {
                            q: params.term,
                            action: 'kanews_search_categories',
                            nonce: kanews_ajax.nonce
                        };
                    },
                    processResults: function(data) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                multiple: isMultiple,
                minimumInputLength: 2,
                placeholder: function() {
                    return $(this).data('placeholder');
                }
            });
        });
        
        // Tags
        $('.select2-tags').each(function() {
            var $select = $(this);
            var isMultiple = $select.prop('multiple');
            
            $select.select2({
                ajax: {
                    url: ajaxurl,
                    dataType: 'json',
                    delay: 250,
                    data: function(params) {
                        return {
                            q: params.term,
                            action: 'kanews_search_tags',
                            nonce: kanews_ajax.nonce
                        };
                    },
                    processResults: function(data) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                multiple: isMultiple,
                minimumInputLength: 2,
                placeholder: function() {
                    return $(this).data('placeholder');
                }
            });
        });
        
        // Taxonomy
        $('.select2-taxonomy').each(function() {
            var $select = $(this);
            var isMultiple = $select.prop('multiple');
            
            $select.select2({
                ajax: {
                    url: ajaxurl,
                    dataType: 'json',
                    delay: 250,
                    data: function(params) {
                        return {
                            q: params.term,
                            action: 'kanews_search_taxonomy',
                            taxonomy: $(this).data('taxonomy'),
                            nonce: kanews_ajax.nonce
                        };
                    },
                    processResults: function(data) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                multiple: isMultiple,
                minimumInputLength: 2,
                placeholder: function() {
                    return $(this).data('placeholder');
                }
            });
        });
        
        // Posts
        $('.select2-posts').each(function() {
            var $select = $(this);
            var isMultiple = $select.prop('multiple');
            
            $select.select2({
                ajax: {
                    url: ajaxurl,
                    dataType: 'json',
                    delay: 250,
                    data: function(params) {
                        return {
                            q: params.term,
                            action: 'kanews_search_posts',
                            post_type: $(this).data('post-type'),
                            nonce: kanews_ajax.nonce
                        };
                    },
                    processResults: function(data) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                multiple: isMultiple,
                minimumInputLength: 2,
                placeholder: function() {
                    return $(this).data('placeholder');
                }
            });
        });
    }
    
    /**
     * Initialize basic Select2 field
     */
    function initBasicSelect2($element) {
        var options = {
            width: '100%',
            allowClear: true,
            placeholder: $element.data('placeholder') || 'Seçim yapın...',
            language: {
                noResults: function() {
                    return 'Sonuç bulunamadı';
                },
                searching: function() {
                    return 'Aranıyor...';
                }
            }
        };

        // Çoklu seçim kontrolü
        if ($element.prop('multiple')) {
            options.closeOnSelect = false;
            options.tags = false;
        }

        // Select2'yi başlat
        $element.select2(options);
    }

    // Widget eklendiğinde veya güncellendiğinde Select2'yi yeniden başlat
    $(document).on('widget-added widget-updated', function(e, widget) {
        var $widget = $(widget);
        
        // Widget içindeki Select2 alanlarını yeniden başlat
        $widget.find('.kanews-field-select2').each(function() {
            if ($(this).data('select2')) {
                $(this).select2('destroy');
            }
            initBasicSelect2($(this));
        });
    });
    
    /**
     * Initialize color pickers
     */
    function initColorPickers() {
        $('.color-picker').wpColorPicker();
    }
    
    /**
     * Initialize toggle fields
     */
    function initToggleFields() {

        
        $('.kanews-toggle-field input[type="checkbox"]').off('change').on('change', function() {
            var $toggle = $(this).closest('.kanews-toggle-field');
            var $icon = $toggle.find('.kanews-toggle-icon');
            if ($(this).is(':checked')) {
                $icon.addClass('is-active');
            } else {
                $icon.removeClass('is-active');
            }
        });
    }
    
    // Update widget titles with visibility indicators
    function updateWidgetTitles() {
        // Sadece widget alanındaki widget'ları seç
        $('.widgets-holder-wrap .widget').each(function() {
            var $widget = $(this);
            var $title = $widget.find('.widget-title');
            var $hideMobile = $widget.find('input[name*="hide_mobile"]');
            var $hideDesktop = $widget.find('input[name*="hide_desktop"]');
            var $grid = $widget.find('select[name*="grid"]');
            
            // Remove existing indicators
            $title.find('.kanews-visibility-indicators').remove();
            
            // Add new indicators based on visibility settings
            var indicators = [];
            
            // Eğer hem masaüstü hem de mobil için gizlenmişse, "Pasif Bileşen" göster
            if ($hideMobile.length && $hideDesktop.length && $hideMobile.is(':checked') && $hideDesktop.is(':checked')) {
                indicators.push('<span class="kanews-visibility-indicator kanews-visibility-inactive">Pasif Bileşen</span>');
            } else {
                if ($hideMobile.length && $hideMobile.is(':checked')) {
                    indicators.push('<span class="kanews-visibility-indicator kanews-visibility-desktop">Masaüstü</span>');
                }
                
                if ($hideDesktop.length && $hideDesktop.is(':checked')) {
                    indicators.push('<span class="kanews-visibility-indicator kanews-visibility-mobile">Mobil</span>');
                }
            }

            // Genişlik göstergesi ekle
            if ($grid.length) {
                var gridValue = $grid.val();
                var gridText = '';
                switch(gridValue) {
                    case 'col-12':
                        gridText = '12/12';
                        break;
                    case 'col-12 col-lg-8':
                        gridText = '12/8';
                        break;
                    case 'col-12 col-lg-6':
                        gridText = '12/6';
                        break;
                    case 'col-12 col-lg-4':
                        gridText = '12/4';
                        break;
                }
                if (gridText) {
                    indicators.push('<span class="kanews-visibility-indicator kanews-visibility-width">' + gridText + '</span>');
                }
            }
            
            if (indicators.length > 0) {
                $title.append('<span class="kanews-visibility-indicators">' + indicators.join(' ') + '</span>');
            }
        });
    }
    
    // Media Field Handler
    function initMediaFields() {
        // Her widget için ayrı bir mediaUploader örneği oluştur
        var mediaUploaders = {};
        
        $(document).on('click', '.kanews-field-media-button', function(e) {
            e.preventDefault();
            var $button = $(this);
            var $widget = $button.closest('.widget-content');
            var widgetId = $widget.find('.widget-id').val();
            
            // Widget için medya yükleyici oluştur veya var olanı kullan
            if (!mediaUploaders[widgetId]) {
                mediaUploaders[widgetId] = wp.media({
                    title: 'Medya Seç',
                    button: {
                        text: 'Seç'
                    },
                    multiple: false
                });

                // Medya seçim olayını bir kez bağla
                mediaUploaders[widgetId].on('select', function() {
                    var attachment = mediaUploaders[widgetId].state().get('selection').first().toJSON();
                    
                    // Input değerlerini güncelle
                    $button.siblings('input[type="text"]').val(attachment.url).trigger('change'); // URL'yi input'a aktar

                    
                    // Önizlemeyi güncelle
                    var $preview = $widget.find('.kanews-field-media-preview');
                    if ($preview.length) {
                        $preview.html('<img src="' + attachment.url + '" style="max-width:100%;height:auto;">');
                    }
                });
            }
            
            mediaUploaders[widgetId].open();
        });
        
        // Widget silindiğinde medya yükleyiciyi temizle
        $(document).on('widget-removed', function(event, widget) {
            var widgetId = widget.find('.widget-id').val();
            if (mediaUploaders[widgetId]) {
                delete mediaUploaders[widgetId];
            }
        });
    }

    // Icon Picker
    function initIconPicker() {
        function getIcons() {
            return new Promise((resolve, reject) => {
                jQuery.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'kanews_get_icons',
                        nonce: kanews_ajax.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            resolve(response.data);
                        } else {
                            reject(response.data);
                        }
                    },
                    error: function(xhr, status, error) {
                        reject(error);
                    }
                });
            });
        }

        let $currentPicker = null;

        async function createModal() {
            try {
                const icons = await getIcons();
                
                const $modal = jQuery(`
                    <div class="kanews-icon-picker-overlay">
                        <div class="kanews-icon-picker-modal">
                            <div class="kanews-icon-picker-header">
                                <h3>İkon Seç</h3>
                                <button type="button" class="button-link">
                                    <span class="dashicons dashicons-no-alt"></span>
                                </button>
                            </div>
                            <input type="text" class="kanews-icon-picker-search" placeholder="İkon ara...">
                            <div class="kanews-icon-picker-grid"></div>
                        </div>
                    </div>
                `);

                const $grid = $modal.find('.kanews-icon-picker-grid');
                icons.forEach((icon) => {
                    $grid.append(`
                        <div class="kanews-icon-picker-item" data-icon="${icon}">
                            <i class="${icon}"></i>
                            <span>${icon.replace('icon-', '')}</span>
                        </div>
                    `);
                });

                return $modal;
            } catch (error) {
                console.error('İkonlar yüklenirken hata:', error);
                return null;
            }
        }

        // İkon seçici butonuna tıklandığında
        jQuery(document).on('click', '.kanews-icon-picker-button', async function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            $currentPicker = jQuery(this).closest('.kanews-icon-picker');
            const $modal = await createModal();
            
            if ($modal) {
                const currentIcon = $currentPicker.find('.kanews-icon-picker-input').val();
                $modal.find(`[data-icon="${currentIcon}"]`).addClass('is-selected');
                jQuery('body').append($modal);
            }
        });

        // Modal kapatma
        jQuery(document).on('click', '.kanews-icon-picker-overlay, .kanews-icon-picker-modal .button-link', function(e) {
            if (e.target === this || jQuery(e.target).closest('.button-link').length) {
                jQuery('.kanews-icon-picker-overlay').remove();
            }
        });

        // Modal içindeki tıklamaların overlay'i kapatmasını engelle
        jQuery(document).on('click', '.kanews-icon-picker-modal', function(e) {
            e.stopPropagation();
        });

        // İkon arama
        jQuery(document).on('input', '.kanews-icon-picker-search', function() {
            const search = jQuery(this).val().toLowerCase();
            jQuery('.kanews-icon-picker-item').each(function() {
                const icon = jQuery(this).data('icon');
                jQuery(this).toggle(icon.toLowerCase().includes(search));
            });
        });

        // İkon seçme
        jQuery(document).on('click', '.kanews-icon-picker-item', function() {
            const icon = jQuery(this).data('icon');
            
            if ($currentPicker) {
                $currentPicker.find('.kanews-icon-picker-input').val(icon).trigger('change');
                $currentPicker.find('.kanews-icon-picker-preview i').attr('class', icon);
                $currentPicker.find('.kanews-icon-picker-name').text(icon);
            }

            jQuery('.kanews-icon-picker-overlay').remove();
        });
    }
    
    // Initialize all components
    function initComponents() {
        initAccordions();
        initSliders();
        initSelect2Fields();
        initColorPickers();
        initToggleFields();
        updateWidgetTitles();
        initMediaFields();
        initIconPicker();
    }
    
    // Initialize components for a specific widget
    function initWidgetComponents($widget) {
        // Initialize accordions
        $widget.find('.kanews-accordion-header').off('click').on('click', function() {
            $(this).parent().toggleClass('is-active');
        });
        
        // Initialize sliders in this widget
        $widget.find('.kanews-slider-element').each(function() {
            var $slider = $(this);
            var $target = $('#' + $slider.data('target'));
            var $value = $slider.siblings('.kanews-slider-value');
            
            // Get slider options
            var min = parseInt($slider.data('min')) || 0;
            var max = parseInt($slider.data('max')) || 100;
            var step = parseInt($slider.data('step')) || 1;
            var value = parseInt($slider.data('value')) || min;
            var unit = $slider.data('unit') || '';
            var default_value = parseInt($slider.data('default')) || min;
            
            // Initialize slider
            $slider.slider({
                min: min,
                max: max,
                step: step,
                value: value,
                slide: function(event, ui) {
                    $target.val(ui.value);
                    $value.text(ui.value + unit);
                    // Trigger input change event
                    $target.trigger('change');
                },
                change: function(event, ui) {
                    $target.val(ui.value);
                    $value.text(ui.value + unit);
                    // Trigger input change event
                    $target.trigger('change');
                }
            });
            
            // Set initial value
            if (!$target.val()) {
                $target.val(default_value);
                $value.text(default_value + unit);
                $slider.slider('value', default_value);
            }
        });
        
        // Initialize Select2 fields in this widget
        $widget.find('.select2-categories, .select2-tags, .select2-taxonomy, .select2-posts, .kanews-field-select2').each(function() {
            if ($(this).data('select2')) {
                $(this).select2('destroy');
            }
            
            if ($(this).hasClass('kanews-field-select2')) {
                initBasicSelect2($(this));
            } else if ($(this).hasClass('select2-categories')) {
                // Categories Select2 initialization
                $(this).select2({
                    ajax: {
                        url: ajaxurl,
                        dataType: 'json',
                        delay: 250,
                        data: function(params) {
                            return {
                                q: params.term,
                                action: 'kanews_search_categories',
                                nonce: kanews_ajax.nonce
                            };
                        },
                        processResults: function(data) {
                            return {
                                results: data
                            };
                        },
                        cache: true
                    },
                    multiple: true,
                    minimumInputLength: 2,
                    placeholder: function() {
                        return $(this).data('placeholder');
                    }
                });
            } else if ($(this).hasClass('select2-tags')) {
                // Tags Select2 initialization
                $(this).select2({
                    ajax: {
                        url: ajaxurl,
                        dataType: 'json',
                        delay: 250,
                        data: function(params) {
                            return {
                                q: params.term,
                                action: 'kanews_search_tags',
                                nonce: kanews_ajax.nonce
                            };
                        },
                        processResults: function(data) {
                            return {
                                results: data
                            };
                        },
                        cache: true
                    },
                    multiple: true,
                    minimumInputLength: 2,
                    placeholder: function() {
                        return $(this).data('placeholder');
                    }
                });
            } else if ($(this).hasClass('select2-taxonomy')) {
                // Taxonomy Select2 initialization
                $(this).select2({
                    ajax: {
                        url: ajaxurl,
                        dataType: 'json',
                        delay: 250,
                        data: function(params) {
                            return {
                                q: params.term,
                                action: 'kanews_search_taxonomy',
                                taxonomy: $(this).data('taxonomy'),
                                nonce: kanews_ajax.nonce
                            };
                        },
                        processResults: function(data) {
                            return {
                                results: data
                            };
                        },
                        cache: true
                    },
                    multiple: true,
                    minimumInputLength: 2,
                    placeholder: function() {
                        return $(this).data('placeholder');
                    }
                });
            } else if ($(this).hasClass('select2-posts')) {
                // Posts Select2 initialization
                $(this).select2({
                    ajax: {
                        url: ajaxurl,
                        dataType: 'json',
                        delay: 250,
                        data: function(params) {
                            return {
                                q: params.term,
                                action: 'kanews_search_posts',
                                post_type: $(this).data('post-type'),
                                nonce: kanews_ajax.nonce
                            };
                        },
                        processResults: function(data) {
                            return {
                                results: data
                            };
                        },
                        cache: true
                    },
                    multiple: true,
                    minimumInputLength: 2,
                    placeholder: function() {
                        return $(this).data('placeholder');
                    }
                });
            }
        });
        
        // Initialize color pickers in this widget
        $widget.find('.color-picker').wpColorPicker();
        
        // Initialize toggle fields in this widget
        $widget.find('.kanews-toggle-field input[type="checkbox"]').off('change').on('change', function() {
            var $toggle = $(this).closest('.kanews-toggle-field');
            var $icon = $toggle.find('.kanews-toggle-icon');
            if ($(this).is(':checked')) {
                $icon.addClass('is-active');
            } else {
                $icon.removeClass('is-active');
            }
        });
    }
    
    // Re-initialize when widget is updated
    $(document).on('widget-updated', function(event, widget) {
        // Initialize only the updated widget, not all widgets
        initWidgetComponents($(widget));
        updateWidgetTitles(); // This still needs to run on all widgets to keep UI consistent
    });
    
    // Re-initialize when widget is added
    $(document).on('widget-added', function(event, widget) {
        // Initialize only the added widget, not all widgets
        initWidgetComponents($(widget));
        updateWidgetTitles(); // This still needs to run on all widgets to keep UI consistent
    });
    
    // Update titles when visibility settings change
    $(document).on('change', 'input[name*="hide_mobile"], input[name*="hide_desktop"], select[name*="grid"]', function() {
        updateWidgetTitles();
    });


})(jQuery); 