jQuery(document).ready(function($) {
    'use strict';
    
    /**
     * Main WPDD Admin Object
     */
    window.WPDD_Admin = {
        
        init: function() {
            this.initFileManager();
            this.initPriceToggle();
            this.initFormValidation();
            this.initProductSync();
        },
        
        initFileManager: function() {
            var fileIndex = $('#wpdd-files-list .wpdd-file-item').length;
            
            // Add new file
            $('#wpdd-add-file').on('click', function(e) {
                e.preventDefault();
                
                var template = $('#wpdd-file-template').html();
                template = template.replace(/INDEX/g, fileIndex);
                
                var $newFile = $(template);
                $newFile.attr('data-index', fileIndex);
                
                $('#wpdd-files-list').append($newFile);
                fileIndex++;
                
                WPDD_Admin.updateFileIndices();
            });
            
            // Remove file
            $(document).on('click', '.wpdd-remove-file', function(e) {
                e.preventDefault();
                
                if (confirm('Are you sure you want to remove this file?')) {
                    $(this).closest('.wpdd-file-item').remove();
                    WPDD_Admin.updateFileIndices();
                }
            });
            
            // Upload file
            $(document).on('click', '.wpdd-upload-file', function(e) {
                e.preventDefault();
                
                var $button = $(this);
                var $container = $button.closest('.wpdd-file-item');
                var $urlInput = $container.find('.wpdd-file-url-input');
                var $idInput = $container.find('.wpdd-file-id');
                var $nameInput = $container.find('input[name*="[name]"]');
                
                // Create file input element
                var $fileInput = $('<input type="file" style="display:none;" />');
                
                $fileInput.on('change', function(event) {
                    var file = event.target.files[0];
                    if (!file) return;
                    
                    // Show loading state
                    $button.prop('disabled', true).text('Uploading...');
                    
                    var formData = new FormData();
                    formData.append('action', 'wpdd_upload_protected_file');
                    formData.append('file', file);
                    formData.append('nonce', wpdd_admin_nonce);
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(response) {
                            if (response.success) {
                                $urlInput.val(response.data.protected_url);
                                $idInput.val(response.data.file_id);
                                
                                if (!$nameInput.val()) {
                                    $nameInput.val(file.name);
                                }
                                
                                WPDD_Admin.showAdminNotice('File uploaded to protected directory', 'success');
                            } else {
                                WPDD_Admin.showAdminNotice(response.data || 'Upload failed', 'error');
                            }
                            
                            $button.prop('disabled', false).text('Upload File');
                        },
                        error: function() {
                            WPDD_Admin.showAdminNotice('Upload failed', 'error');
                            $button.prop('disabled', false).text('Upload File');
                        }
                    });
                    
                    // Clean up
                    $fileInput.remove();
                });
                
                // Trigger file selection
                $('body').append($fileInput);
                $fileInput.trigger('click');
            });
            
            // Make files sortable
            if ($.fn.sortable) {
                $('#wpdd-files-list').sortable({
                    handle: '.wpdd-file-handle',
                    placeholder: 'wpdd-file-placeholder',
                    update: function() {
                        WPDD_Admin.updateFileIndices();
                    }
                });
            }
        },
        
        moveToProtectedDirectory: function(attachmentId, $container) {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'wpdd_move_to_protected',
                    attachment_id: attachmentId,
                    nonce: wpdd_admin_nonce
                },
                success: function(response) {
                    if (response.success && response.data.protected_url) {
                        $container.find('.wpdd-file-url-input').val(response.data.protected_url);
                    }
                }
            });
        },
        
        updateFileIndices: function() {
            $('#wpdd-files-list .wpdd-file-item').each(function(index) {
                var $item = $(this);
                $item.attr('data-index', index);
                
                // Update input names
                $item.find('input').each(function() {
                    var name = $(this).attr('name');
                    if (name) {
                        name = name.replace(/\[\d+\]/, '[' + index + ']');
                        $(this).attr('name', name);
                    }
                });
            });
        },
        
        initPriceToggle: function() {
            $('#wpdd_is_free').on('change', function() {
                var $priceFields = $('.wpdd-price-field');
                if ($(this).is(':checked')) {
                    $priceFields.slideUp();
                } else {
                    $priceFields.slideDown();
                }
            }).trigger('change');
        },
        
        initFormValidation: function() {
            // Validate PayPal settings
            $('input[name="wpdd_paypal_client_id"], input[name="wpdd_paypal_secret"]').on('blur', function() {
                var $field = $(this);
                var value = $field.val().trim();
                
                if (value && value.length < 10) {
                    $field.addClass('error');
                    WPDD_Admin.showAdminNotice('Invalid PayPal credential format', 'error');
                } else {
                    $field.removeClass('error');
                }
            });
            
            // Validate email fields
            $('input[type="email"]').on('blur', function() {
                var $field = $(this);
                var value = $field.val().trim();
                var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                
                if (value && !emailRegex.test(value)) {
                    $field.addClass('error');
                } else {
                    $field.removeClass('error');
                }
            });
            
            // Validate number fields
            $('input[type="number"]').on('input', function() {
                var $field = $(this);
                var value = parseFloat($field.val());
                var min = parseFloat($field.attr('min'));
                var max = parseFloat($field.attr('max'));
                
                if (isNaN(value) || (min !== undefined && value < min) || (max !== undefined && value > max)) {
                    $field.addClass('error');
                } else {
                    $field.removeClass('error');
                }
            });
        },
        
        showAdminNotice: function(message, type) {
            type = type || 'info';
            
            var notice = $('<div class="notice notice-' + type + ' is-dismissible">' +
                          '<p>' + message + '</p>' +
                          '<button type="button" class="notice-dismiss"></button>' +
                          '</div>');
            
            $('.wrap h1').first().after(notice);
            
            // Handle dismiss
            notice.find('.notice-dismiss').on('click', function() {
                notice.fadeOut(function() {
                    notice.remove();
                });
            });
            
            // Auto-dismiss after 5 seconds for non-error notices
            if (type !== 'error') {
                setTimeout(function() {
                    notice.fadeOut(function() {
                        notice.remove();
                    });
                }, 5000);
            }
        },
        
        initReportsCharts: function() {
            // Placeholder for future chart implementation
            // Could integrate Chart.js or similar library
        },
        
        initBulkActions: function() {
            // Handle bulk actions for orders, customers, etc.
            $('.bulkactions select').on('change', function() {
                var action = $(this).val();
                var $button = $(this).siblings('input[type="submit"]');
                
                if (action) {
                    $button.prop('disabled', false);
                } else {
                    $button.prop('disabled', true);
                }
            });
        },
        
        initQuickEdit: function() {
            // Quick edit functionality for products
            $('.editinline').on('click', function() {
                var $row = $(this).closest('tr');
                var productId = $row.find('.check-column input').val();
                
                // Populate quick edit fields with current values
                setTimeout(function() {
                    var $quickEdit = $('.inline-edit-row');
                    
                    // Pre-fill price from the displayed value
                    var price = $row.find('.column-wpdd_price').text().replace('$', '');
                    if (price !== 'Free') {
                        $quickEdit.find('input[name="_wpdd_price"]').val(price);
                    }
                    
                }, 100);
            });
        },
        
        initFilePreview: function() {
            // Show file preview/details when hovering over file names
            $(document).on('mouseenter', '.wpdd-file-url-input', function() {
                var url = $(this).val();
                if (url) {
                    var filename = url.split('/').pop();
                    var extension = filename.split('.').pop().toLowerCase();
                    var fileType = WPDD_Admin.getFileType(extension);
                    
                    $(this).attr('title', 'File: ' + filename + ' (Type: ' + fileType + ')');
                }
            });
        },
        
        getFileType: function(extension) {
            var types = {
                'pdf': 'PDF Document',
                'doc': 'Word Document',
                'docx': 'Word Document',
                'zip': 'Archive',
                'rar': 'Archive',
                'jpg': 'Image',
                'jpeg': 'Image',
                'png': 'Image',
                'gif': 'Image',
                'mp3': 'Audio',
                'wav': 'Audio',
                'mp4': 'Video',
                'avi': 'Video'
            };
            
            return types[extension] || 'File';
        },
        
        initColorPicker: function() {
            // Initialize color picker for watermark settings
            if ($.fn.wpColorPicker) {
                $('.wpdd-color-picker').wpColorPicker();
            }
        },
        
        initTabs: function() {
            // Settings page tabs
            $('.wpdd-settings-tabs').on('click', 'a', function(e) {
                e.preventDefault();
                
                var $tab = $(this);
                var target = $tab.attr('href');
                
                // Update active tab
                $tab.siblings().removeClass('nav-tab-active');
                $tab.addClass('nav-tab-active');
                
                // Show/hide content
                $('.wpdd-settings-content').hide();
                $(target).show();
            });
        },
        
        initProductSync: function() {
            // Handle software product sync
            $(document).on('click', '.wpdd-sync-product', function(e) {
                e.preventDefault();
                
                var $button = $(this);
                var productId = $button.data('product-id');
                var nonce = $button.data('nonce');
                
                if (!productId || !nonce) {
                    WPDD_Admin.showAdminNotice('Invalid sync request', 'error');
                    return;
                }
                
                // Show loading state
                $button.prop('disabled', true).text('Syncing...');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'wpdd_sync_software_product',
                        product_id: productId,
                        nonce: nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            WPDD_Admin.showAdminNotice(response.message, 'success');
                            // Reload the page to show updated file count
                            setTimeout(function() {
                                window.location.reload();
                            }, 1500);
                        } else {
                            WPDD_Admin.showAdminNotice(response.message || 'Sync failed', 'error');
                            $button.prop('disabled', false).text('Sync Files');
                        }
                    },
                    error: function() {
                        WPDD_Admin.showAdminNotice('Sync request failed', 'error');
                        $button.prop('disabled', false).text('Sync Files');
                    }
                });
            });
        }
    };
    
    // Initialize admin functionality
    WPDD_Admin.init();
    
    // Add admin-specific styles
    $('<style>')
        .prop('type', 'text/css')
        .html(`
            .wpdd-file-item.ui-sortable-helper {
                box-shadow: 0 4px 8px rgba(0,0,0,0.2);
                transform: rotate(2deg);
            }
            
            .wpdd-file-placeholder {
                border: 2px dashed #0073aa !important;
                background: transparent !important;
                height: 80px !important;
            }
            
            input.error {
                border-color: #dc3232 !important;
                box-shadow: 0 0 2px rgba(220, 50, 50, 0.3) !important;
            }
            
            .wpdd-loading-overlay {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(255,255,255,0.8);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 9999;
            }
            
            .wpdd-spinner {
                width: 40px;
                height: 40px;
                border: 4px solid #f3f3f3;
                border-top: 4px solid #0073aa;
                border-radius: 50%;
                animation: spin 1s linear infinite;
            }
            
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
            
            .wpdd-help-tip {
                color: #666;
                cursor: help;
                margin-left: 5px;
            }
            
            .wpdd-help-tip:hover {
                color: #0073aa;
            }
        `)
        .appendTo('head');
    
    // Initialize additional features based on current page
    var currentScreen = window.pagenow || '';
    
    if (currentScreen === 'wpdd_product') {
        WPDD_Admin.initQuickEdit();
        WPDD_Admin.initFilePreview();
    }
    
    if (currentScreen.includes('wpdd-settings')) {
        WPDD_Admin.initColorPicker();
        WPDD_Admin.initTabs();
    }
    
    if (currentScreen.includes('wpdd-reports')) {
        WPDD_Admin.initReportsCharts();
    }
    
    // Global admin features
    WPDD_Admin.initBulkActions();
});