/**
 * Shop Explorer Frontend JavaScript
 */

(function($) {
    'use strict';

    // Initialize when document is ready
    $(document).ready(function() {
        ShopExplorerFrontend.init();
    });

    // Main frontend object
    window.ShopExplorerFrontend = {
        
        // Configuration
        config: {
            ajaxUrl: window.shopExplorerFrontend?.ajaxUrl || '/wp-admin/admin-ajax.php',
            apiUrl: window.shopExplorerFrontend?.apiUrl || '/wp-json/shop-explorer/v1',
            nonce: window.shopExplorerFrontend?.nonce || '',
            strings: window.shopExplorerFrontend?.strings || {}
        },

        // Initialize the frontend
        init: function() {
            this.bindEvents();
            this.loadDashboardData();
            this.initializeComponents();
        },

        // Bind event handlers
        bindEvents: function() {
            // Sync data button
            $(document).on('click', '#sync-data-btn', this.handleSyncData.bind(this));
            
            // Refresh stats button
            $(document).on('click', '.refresh-stats', this.loadDashboardData.bind(this));
            
            // Action card clicks
            $(document).on('click', '.action-card[data-action]', this.handleActionCard.bind(this));
            
            // Auto-refresh stats every 5 minutes
            setInterval(this.loadDashboardData.bind(this), 300000);
        },

        // Initialize components
        initializeComponents: function() {
            // Initialize tooltips if available
            if (typeof $.fn.tooltip === 'function') {
                $('[data-toggle="tooltip"]').tooltip();
            }

            // Initialize any charts or graphs
            this.initializeCharts();

            // Setup real-time updates if WebSocket is available
            this.setupRealTimeUpdates();
        },

        // Load dashboard statistics
        loadDashboardData: function() {
            const self = this;
            
            $.ajax({
                url: this.config.apiUrl + '/dashboard/stats',
                type: 'GET',
                headers: {
                    'X-WP-Nonce': this.config.nonce
                },
                beforeSend: function() {
                    self.showLoadingState();
                },
                success: function(response) {
                    if (response.success && response.stats) {
                        self.updateStats(response.stats);
                        self.loadRecentActivity();
                    } else {
                        self.showError(self.config.strings.error || 'Failed to load dashboard data');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Dashboard stats error:', error);
                    self.showError(self.config.strings.error || 'Failed to load dashboard data');
                },
                complete: function() {
                    self.hideLoadingState();
                }
            });
        },

        // Update statistics display
        updateStats: function(stats) {
            // Update order stats
            if (stats.orders) {
                $('#orders-count').text(stats.orders.total || 0);
                this.updateStatDetails('orders', stats.orders);
            }

            // Update product stats
            if (stats.products) {
                $('#products-count').text(stats.products.total || 0);
                this.updateStatDetails('products', stats.products);
            }

            // Update vendor stats
            if (stats.vendors) {
                $('#vendor-sales').text(stats.vendors.total || 0);
                this.updateStatDetails('vendors', stats.vendors);
            }

            // Animate the numbers
            this.animateNumbers();
        },

        // Update detailed stats
        updateStatDetails: function(type, data) {
            const $card = $(`.stat-card[data-type="${type}"]`);
            if ($card.length) {
                // Update additional details if available
                let details = '';
                switch (type) {
                    case 'orders':
                        details = `Pending: ${data.pending || 0}, Completed: ${data.completed || 0}`;
                        break;
                    case 'products':
                        details = `In Stock: ${data.in_stock || 0}, Out of Stock: ${data.out_of_stock || 0}`;
                        break;
                    case 'vendors':
                        details = `Active: ${data.active || 0}`;
                        break;
                }
                $card.find('.stat-details').text(details);
            }
        },

        // Animate number changes
        animateNumbers: function() {
            $('.stat-number').each(function() {
                const $this = $(this);
                const newValue = parseInt($this.text()) || 0;
                const currentValue = parseInt($this.data('current-value')) || 0;
                
                if (newValue !== currentValue) {
                    $this.data('current-value', newValue);
                    $this.addClass('stat-updated');
                    setTimeout(() => $this.removeClass('stat-updated'), 1000);
                }
            });
        },

        // Load recent activity
        loadRecentActivity: function() {
            const self = this;
            
            $.ajax({
                url: this.config.apiUrl + '/dashboard/activity',
                type: 'GET',
                headers: {
                    'X-WP-Nonce': this.config.nonce
                },
                success: function(response) {
                    if (response.success && response.activities) {
                        self.updateActivityList(response.activities);
                    }
                },
                error: function() {
                    $('#activity-list').html('<p>Unable to load recent activity.</p>');
                }
            });
        },

        // Update activity list
        updateActivityList: function(activities) {
            const $list = $('#activity-list');
            
            if (!activities || activities.length === 0) {
                $list.html('<p>No recent activity.</p>');
                return;
            }

            let html = '';
            activities.forEach(function(activity) {
                html += `
                    <div class="activity-item">
                        <div class="activity-icon">${activity.icon || '📋'}</div>
                        <div class="activity-content">
                            <div class="activity-title">${activity.title}</div>
                            <div class="activity-time">${activity.time}</div>
                        </div>
                    </div>
                `;
            });
            
            $list.html(html);
        },

        // Handle sync data button click
        handleSyncData: function(e) {
            e.preventDefault();
            
            const $btn = $(e.currentTarget);
            const originalText = $btn.find('h3').text();
            
            // Show loading state
            $btn.addClass('syncing');
            $btn.find('h3').text(this.config.strings.loading || 'Syncing...');
            
            // Perform sync
            this.performSync()
                .then(() => {
                    this.showSuccess('Data synchronized successfully!');
                    this.loadDashboardData(); // Refresh data
                })
                .catch((error) => {
                    console.error('Sync error:', error);
                    this.showError('Sync failed. Please try again.');
                })
                .finally(() => {
                    // Reset button state
                    $btn.removeClass('syncing');
                    $btn.find('h3').text(originalText);
                });
        },

        // Perform data synchronization
        performSync: function() {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: this.config.apiUrl + '/sync/orders',
                    type: 'POST',
                    headers: {
                        'X-WP-Nonce': this.config.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            resolve(response);
                        } else {
                            reject(new Error(response.message || 'Sync failed'));
                        }
                    },
                    error: function(xhr, status, error) {
                        reject(new Error(error));
                    }
                });
            });
        },

        // Handle action card clicks
        handleActionCard: function(e) {
            const $card = $(e.currentTarget);
            const action = $card.data('action');
            
            if (action) {
                this.executeAction(action, $card);
            }
        },

        // Execute specific actions
        executeAction: function(action, $element) {
            switch (action) {
                case 'quick-add-product':
                    this.showQuickAddProduct();
                    break;
                case 'quick-view-orders':
                    this.showQuickOrderView();
                    break;
                case 'export-data':
                    this.exportData();
                    break;
                default:
                    console.log('Unknown action:', action);
            }
        },

        // Initialize charts and graphs
        initializeCharts: function() {
            // This would integrate with Chart.js or similar library
            // For now, just a placeholder
            if (window.Chart && $('#stats-chart').length) {
                // Initialize chart here
            }
        },

        // Setup real-time updates
        setupRealTimeUpdates: function() {
            // This would setup WebSocket connections for real-time updates
            // For now, just use polling
            if (window.WebSocket) {
                // Setup WebSocket connection
            }
        },

        // Show loading state
        showLoadingState: function() {
            $('.stat-number').addClass('loading');
        },

        // Hide loading state
        hideLoadingState: function() {
            $('.stat-number').removeClass('loading');
        },

        // Show success message
        showSuccess: function(message) {
            this.showNotification(message, 'success');
        },

        // Show error message
        showError: function(message) {
            this.showNotification(message, 'error');
        },

        // Show notification
        showNotification: function(message, type) {
            // Create notification element
            const $notification = $(`
                <div class="shop-explorer-notification ${type}">
                    <span class="message">${message}</span>
                    <button class="close">&times;</button>
                </div>
            `);

            // Add to page
            $('body').append($notification);

            // Show notification
            setTimeout(() => $notification.addClass('show'), 100);

            // Auto-hide after 5 seconds
            setTimeout(() => this.hideNotification($notification), 5000);

            // Handle close button
            $notification.find('.close').on('click', () => {
                this.hideNotification($notification);
            });
        },

        // Hide notification
        hideNotification: function($notification) {
            $notification.removeClass('show');
            setTimeout(() => $notification.remove(), 300);
        },

        // Utility: Format numbers
        formatNumber: function(num) {
            if (num >= 1000000) {
                return (num / 1000000).toFixed(1) + 'M';
            } else if (num >= 1000) {
                return (num / 1000).toFixed(1) + 'K';
            }
            return num.toString();
        },

        // Utility: Format currency
        formatCurrency: function(amount, currency = '$') {
            return currency + parseFloat(amount).toFixed(2);
        },

        // Utility: Time ago format
        timeAgo: function(date) {
            const now = new Date();
            const diffInSeconds = Math.floor((now - new Date(date)) / 1000);
            
            if (diffInSeconds < 60) return 'Just now';
            if (diffInSeconds < 3600) return Math.floor(diffInSeconds / 60) + ' minutes ago';
            if (diffInSeconds < 86400) return Math.floor(diffInSeconds / 3600) + ' hours ago';
            return Math.floor(diffInSeconds / 86400) + ' days ago';
        }
    };

})(jQuery);

// Add notification styles
const notificationStyles = `
<style>
.shop-explorer-notification {
    position: fixed;
    top: 20px;
    right: 20px;
    background: white;
    border-radius: 8px;
    padding: 15px 20px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    z-index: 10000;
    transform: translateX(100%);
    transition: transform 0.3s ease;
    max-width: 400px;
    display: flex;
    align-items: center;
    gap: 15px;
}

.shop-explorer-notification.show {
    transform: translateX(0);
}

.shop-explorer-notification.success {
    border-left: 4px solid #28a745;
}

.shop-explorer-notification.error {
    border-left: 4px solid #dc3545;
}

.shop-explorer-notification .close {
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
    color: #666;
    padding: 0;
    margin-left: auto;
}

.stat-number.loading {
    opacity: 0.5;
    position: relative;
}

.stat-number.stat-updated {
    animation: pulse 0.5s ease-in-out;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}
</style>
`;

// Inject notification styles
document.head.insertAdjacentHTML('beforeend', notificationStyles);