/**
 * BW Gallery Admin JavaScript
 */

(function($) {
    'use strict';
    
    var BWGAdmin = {
        frame: null,
        galleryImages: [],
        
        init: function() {
            this.bindEvents();
            this.loadGalleryData();
            this.initSortable();
        },
        
        bindEvents: function() {
            var self = this;
            
            // Add images button
            $('#bwg-add-images').on('click', function(e) {
                e.preventDefault();
                self.openMediaLibrary();
            });
            
            // Remove image
            $(document).on('click', '.bwg-remove-image', function(e) {
                e.preventDefault();
                $(this).closest('.bwg-image-item').fadeOut(300, function() {
                    $(this).remove();
                });
            });
            
            // Gallery form submission
            $('#bwg-gallery-form').on('submit', function(e) {
                e.preventDefault();
                self.saveGallery();
            });
            
            // Delete gallery
            $('.bwg-delete-gallery').on('click', function() {
                if (confirm(bwg_admin.strings.confirm_delete)) {
                    self.deleteGallery($(this).data('id'));
                }
            });
            
            // Copy shortcode
            $('.bwg-copy-shortcode').on('click', function() {
                self.copyToClipboard($(this).data('shortcode'));
                var $btn = $(this);
                var originalText = $btn.text();
                $btn.text('Copied!');
                setTimeout(function() {
                    $btn.text(originalText);
                }, 2000);
            });
            
            // Enable tabs checkbox
            $('input[name="enable_tabs"]').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#bwg-tab-notice').show();
                    $('.bwg-image-tab').show();
                } else {
                    $('#bwg-tab-notice').hide();
                    $('.bwg-image-tab').hide();
                }
            }).trigger('change');
        },
        
        openMediaLibrary: function() {
            var self = this;
            
            if (this.frame) {
                this.frame.open();
                return;
            }
            
            this.frame = wp.media({
                title: bwg_admin.strings.select_images,
                button: {
                    text: bwg_admin.strings.use_images
                },
                multiple: true,
                library: {
                    type: 'image'
                }
            });
            
            this.frame.on('select', function() {
                var attachments = self.frame.state().get('selection').toJSON();
                self.addImages(attachments);
            });
            
            this.frame.open();
        },
        
        addImages: function(attachments) {
            var self = this;
            var template = $('#bwg-image-template').html();
            
            $.each(attachments, function(index, attachment) {
                var imageHtml = template
                    .replace(/{{ id }}/g, attachment.id)
                    .replace(/{{ url }}/g, attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url)
                    .replace(/{{ caption }}/g, attachment.caption || '');
                
                $('#bwg-images-list').append(imageHtml);
            });
            
            // Show/hide tab inputs based on checkbox state
            if ($('input[name="enable_tabs"]').is(':checked')) {
                $('.bwg-image-tab').show();
            }
        },
        
        initSortable: function() {
            $('#bwg-images-list').sortable({
                items: '.bwg-image-item',
                placeholder: 'bwg-image-placeholder',
                tolerance: 'pointer',
                distance: 5,
                forcePlaceholderSize: true
            });
        },
        
        loadGalleryData: function() {
            var galleryId = $('#gallery_id').val();
            if (!galleryId || galleryId === '0') {
                return;
            }
            
            var self = this;
            
            $.ajax({
                url: bwg_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'bwg_get_gallery',
                    nonce: bwg_admin.nonce,
                    gallery_id: galleryId
                },
                success: function(response) {
                    if (response.success && response.data.images) {
                        self.displayImages(response.data.images);
                    }
                }
            });
        },
        
        displayImages: function(images) {
            var self = this;
            var template = $('#bwg-image-template').html();
            
            $.each(images, function(index, image) {
                wp.media.attachment(image.image_id).fetch().then(function(attachment) {
                    var imageHtml = template
                        .replace(/{{ id }}/g, image.image_id)
                        .replace(/{{ url }}/g, attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url)
                        .replace(/{{ caption }}/g, image.caption || '');
                    
                    var $imageItem = $(imageHtml);
                    $('#bwg-images-list').append($imageItem);
                    
                    // Set the selected tab value
                    if (image.tab_name) {
                        $imageItem.find('.bwg-image-tab').val(image.tab_name);
                    }
                    
                    // Show/hide tab inputs
                    if ($('input[name="enable_tabs"]').is(':checked')) {
                        $('.bwg-image-tab').show();
                    }
                });
            });
        },
        
        saveGallery: function() {
            var self = this;
            var $form = $('#bwg-gallery-form');
            var $submitBtn = $form.find('button[type="submit"]');
            
            // Collect image data
            var images = [];
            $('#bwg-images-list .bwg-image-item').each(function() {
                var $item = $(this);
                images.push({
                    id: $item.data('id'),
                    tab: $item.find('.bwg-image-tab').val(),
                    caption: $item.find('.bwg-image-caption').val()
                });
            });
            
            // Prepare form data
            var formData = {
                action: 'bwg_save_gallery',
                nonce: bwg_admin.nonce,
                gallery_id: $('#gallery_id').val(),
                name: $('#gallery_name').val(),
                description: $('#gallery_description').val(),
                enable_tabs: $('input[name="enable_tabs"]').is(':checked') ? 1 : 0,
                lightbox: $('input[name="lightbox"]').is(':checked') ? 1 : 0,
                columns: $('#gallery_columns').val(),
                gap: $('#gallery_gap').val(),
                images: images
            };
            
            // Show loading state
            $submitBtn.text(bwg_admin.strings.saving).prop('disabled', true);
            
            $.ajax({
                url: bwg_admin.ajax_url,
                type: 'POST',
                data: formData,
                success: function(response) {
                    if (response.success) {
                        $submitBtn.text(bwg_admin.strings.saved);
                        
                        // Update gallery ID if new
                        if (!$('#gallery_id').val()) {
                            $('#gallery_id').val(response.data.gallery_id);
                            window.history.replaceState({}, '', window.location.pathname + '?page=bw-gallery-new&id=' + response.data.gallery_id);
                        }
                        
                        setTimeout(function() {
                            $submitBtn.text('Save Gallery').prop('disabled', false);
                        }, 2000);
                    } else {
                        alert(bwg_admin.strings.error);
                        $submitBtn.text('Save Gallery').prop('disabled', false);
                    }
                },
                error: function() {
                    alert(bwg_admin.strings.error);
                    $submitBtn.text('Save Gallery').prop('disabled', false);
                }
            });
        },
        
        deleteGallery: function(galleryId) {
            $.ajax({
                url: bwg_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'bwg_delete_gallery',
                    nonce: bwg_admin.nonce,
                    gallery_id: galleryId
                },
                success: function(response) {
                    if (response.success) {
                        window.location.reload();
                    } else {
                        alert(bwg_admin.strings.error);
                    }
                },
                error: function() {
                    alert(bwg_admin.strings.error);
                }
            });
        },
        
        copyToClipboard: function(text) {
            var $temp = $('<input>');
            $('body').append($temp);
            $temp.val(text).select();
            document.execCommand('copy');
            $temp.remove();
        }
    };
    
    $(document).ready(function() {
        BWGAdmin.init();
    });
    
})(jQuery);