jQuery(document).ready(function ($) {
    
    function twsscInitSliderAdmin() {
        const $imageList = $('#twssc-slider-images-list');
        
        if (!$imageList.length) {
            return;
        }
        
        function twsscInitSortable() {
            if (typeof $.fn.sortable !== 'undefined') {
                $imageList.sortable({
                    placeholder: 'twssc-sortable-placeholder',
                    cursor: 'move',
                    opacity: 0.7,
                    tolerance: 'pointer',
                    update: function () {
                        let ids = [];
                        $imageList.find('.twssc-slider-image-item').each(function () {
                            ids.push($(this).data('image-id'));
                        });
                        
                        $imageList.find('input[name="twssc_slider_images[]"]').each(function (i) {
                            $(this).val(ids[i]);
                        });
                    }
                });
                
                if (!$imageList.find('.twssc-slider-image-item').length) {
                    $imageList.sortable('disable');
                }
            }
        }
        
        twsscInitSortable();
        
        $('#twssc-slider-add-images').on('click', function (e) {
            e.preventDefault();
            
            if (typeof wp.media === 'undefined') {
                alert(twssc_admin.strings.media_error);
                return;
            }
            
            try {
                const frame = wp.media({
                    title: twssc_admin.strings.select_images,
                    button: {
                        text: twssc_admin.strings.add_to_slider
                    },
                    multiple: 'add',
                    library: {
                        type: 'image'
                    }
                });
                
                frame.on('select', function () {
                    const attachments = frame.state().get('selection').toJSON();
                    
                    $('.twssc-no-images').remove();
                    
                    attachments.forEach(function(attachment) {
                        const imageUrl = attachment.sizes && attachment.sizes.medium 
                            ? attachment.sizes.medium.url 
                            : attachment.url;
                        
                        if ($imageList.find('[data-image-id="' + attachment.id + '"]').length) {
                            return;
                        }
                        
                        const imageItem = `
                        <div class="twssc-slider-image-item" data-image-id="${attachment.id}">
                            <div class="twssc-slider-image-preview">
                                <img src="${imageUrl}" alt="">
                                <input type="hidden" name="twssc_slider_images[]" value="${attachment.id}">
                            </div>
                            <button type="button" class="button button-small twssc-slider-remove-image">${twssc_admin.strings.remove}</button>
                        </div>
                        `;
                        
                        $imageList.append(imageItem);
                    });
                    
                    if ($imageList.sortable('instance')) {
                        $imageList.sortable('refresh');
                    } else {
                        twsscInitSortable();
                    }
                    
                    if ($imageList.find('.twssc-slider-image-item').length) {
                        $imageList.sortable('enable');
                    }
                });
                
                frame.open();
            } catch (error) {
                console.error('Media uploader error:', error);
            }
        });
        
        $(document).on('click', '.twssc-slider-remove-image', function (e) {
            e.preventDefault();
            
            $(this).closest('.twssc-slider-image-item').remove();
            
            if (!$imageList.find('.twssc-slider-image-item').length) {
                $imageList.html('<p class="twssc-no-images">' + twssc_admin.strings.no_images + '</p>');
                if ($imageList.sortable('instance')) {
                    $imageList.sortable('disable');
                }
            }
        });
        
        if (typeof $.fn.wpColorPicker !== 'undefined') {
            $('.color-picker').wpColorPicker();
        }
        
        function twsscUpdateFadeAnimationStatus() {
            let slides = parseInt($('#twssc_slider_slides_to_show').val()) || 1;
            if (slides < 1) slides = 1;
            $('#twssc_slider_slides_to_show').val(slides);
            
            const fadeCheckbox = $('#twssc_slider_fade_animation');
            const isSingleSlide = (slides === 1);
            
            fadeCheckbox.prop('disabled', !isSingleSlide);
            
            if (!isSingleSlide && fadeCheckbox.is(':checked')) {
                fadeCheckbox.prop('checked', false);
            }
        }
        
        $('#twssc_slider_slides_to_show').on('input change', twsscUpdateFadeAnimationStatus);
        
        $('input[name="twssc_slider_autoplay"]').on('change', function() {
            const $pauseContainer = $('#pause_on_hover_container');
            if ($(this).is(':checked')) {
                $pauseContainer.show();
            } else {
                $pauseContainer.hide();
                $('input[name="twssc_slider_pause_on_hover"]').prop('checked', false);
            }
        });
        
        twsscUpdateFadeAnimationStatus();
        
        $('.arrow-type-option').on('change', function() {
            if ($(this).val() === 'custom') {
                $('.custom-arrow-fields').show();
            } else {
                $('.custom-arrow-fields').hide();
            }
        });
        
        $('.twssc-upload-arrow').on('click', function(e) {
            e.preventDefault();
            
            const button = $(this);
            const target = button.data('target');
            const preview = button.closest('td').find('.custom-arrow-preview');
            const removeBtn = button.siblings('.twssc-remove-arrow');
            
            const frame = wp.media({
                title: twssc_admin.strings.select_images,
                button: { text: twssc_admin.strings.add_to_slider },
                multiple: false,
                library: { type: 'image' }
            });
            
            frame.on('select', function() {
                const attachment = frame.state().get('selection').first().toJSON();
                
                $('#' + target).val(attachment.id);
                preview.html('<img src="' + attachment.url + '" style="max-width: 100px; height: auto; display: block; margin-bottom: 5px;">');
                removeBtn.show();
            });
            
            frame.open();
        });
        
        $('.twssc-remove-arrow').on('click', function(e) {
            e.preventDefault();
            
            const button = $(this);
            const target = button.data('target');
            const preview = button.closest('td').find('.custom-arrow-preview');
            
            $('#' + target).val('');
            preview.html('');
            button.hide();
        });
    }
    
    twsscInitSliderAdmin();
});