// Blogibot Dashboard JavaScript
(function (window, document) {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {
        // Initialize dashboard functionality
        initDashboard();
        initMetricCardAnimations();
        initTabNavigation();
        initAIGenerationToggle();
    });

    function initDashboard() {
        // Add smooth scrolling for in-page links
        document.querySelectorAll('a[href^="#"]').forEach(function (link) {
            link.addEventListener('click', function (e) {
                e.preventDefault();
                const target = document.querySelector(this.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });
    }

    function initMetricCardAnimations() {
        // Add hover animations to metric cards
        const metricCards = document.querySelectorAll('.blog82ai-metric-card, .metric-card');
        metricCards.forEach(function (card) {
            card.addEventListener('mouseenter', function () {
                this.style.transform = 'translateY(-2px)';
            });

            card.addEventListener('mouseleave', function () {
                this.style.transform = 'translateY(0)';
            });
        });
    }

    function initTabNavigation() {
        // Handle main tab navigation
        const mainTabs = document.querySelectorAll('.blog82ai-nav-tab');
        mainTabs.forEach(function (tab) {
            tab.addEventListener('click', function (e) {
                if (this.hasAttribute('disabled')) {
                    e.preventDefault();
                    return false;
                }

                // Update active state
                mainTabs.forEach(function (t) {
                    t.classList.remove('blog82ai-nav-tab-active');
                });
                this.classList.add('blog82ai-nav-tab-active');
            });
        });

        // Handle subtab navigation
        const subtabs = document.querySelectorAll('.blog82ai-subtab');
        subtabs.forEach(function (tab) {
            tab.addEventListener('click', function (e) {
                // Update active state
                subtabs.forEach(function (t) {
                    t.classList.remove('blog82ai-subtab-active');
                });
                this.classList.add('blog82ai-subtab-active');

                // Add loading animation
                showTabLoadingState();
            });
        });
    }

    function showTabLoadingState() {
        const content = document.querySelector('.blog82ai-tab-content');
        if (content) {
            content.style.opacity = '0.7';
            setTimeout(function () {
                content.style.opacity = '1';
            }, 200);
        }
    }

    // Utility functions for dashboard interactions
    window.BlogibotDashboard = {
        showNotification: function (message, type) {
            type = type || 'info';
            const notification = document.createElement('div');
            notification.className = 'blog82ai-notification blog82ai-notification-' + type;
            notification.textContent = message;
            notification.style.cssText = `
                position: fixed;
                top: 32px;
                right: 20px;
                background: ${type === 'success' ? '#46b450' : type === 'error' ? '#dc3232' : '#0073aa'};
                color: white;
                padding: 12px 20px;
                border-radius: 4px;
                z-index: 100000;
                box-shadow: 0 2px 8px rgba(0,0,0,0.15);
                font-weight: 500;
            `;

            document.body.appendChild(notification);

            setTimeout(function () {
                notification.remove();
            }, 4000);
        },

        refreshMetrics: function () {
            // In real implementation, this would make an AJAX call
            this.showNotification('Dashboard metrics refreshed', 'success');
        }
    };

    function initAIGenerationToggle() {
        // Make refreshDashboard function globally available
        window.refreshDashboard = function (button) {
            if (button.disabled) return;

            button.disabled = true;
            const originalHTML = button.innerHTML;
            button.innerHTML = '<span class="dashicons dashicons-update" style="animation: spin 1s linear infinite; vertical-align: middle;"></span> Refreshing...';

            // Make AJAX request to refresh dashboard data
            const formData = new FormData();
            formData.append('action', 'blog82ai_refresh_dashboard');
            formData.append('security', window.blog82aiApiData?.ajax_nonce || '');

            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        Blog82AIDashboard.showNotification(
                            'Dashboard refreshed successfully',
                            'success'
                        );

                        // Optionally reload the page for simplicity
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    } else {
                        Blog82AIDashboard.showNotification(
                            data.data?.message || 'Failed to refresh dashboard',
                            'error'
                        );
                    }
                })
                .catch(error => {
                    console.error('Error refreshing dashboard:', error);
                    Blog82AIDashboard.showNotification(
                        'Error communicating with server',
                        'error'
                    );
                })
                .finally(() => {
                    button.disabled = false;
                    button.innerHTML = originalHTML;
                });
        };

        // Make createSampleData function globally available
        window.createSampleData = function (button) {
            if (button.disabled) return;

            if (!confirm('This will create sample AI-generated blog posts for demonstration. Continue?')) {
                return;
            }

            button.disabled = true;
            const originalHTML = button.innerHTML;
            button.innerHTML = '<span class="dashicons dashicons-admin-post" style="vertical-align: middle;"></span> Creating...';

            // Make AJAX request to create sample data
            const formData = new FormData();
            formData.append('action', 'blog82ai_create_sample_data');
            formData.append('security', window.blog82aiApiData?.ajax_nonce || '');

            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        Blog82AIDashboard.showNotification(
                            'Sample data created successfully',
                            'success'
                        );

                        // Reload the page to show new data
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    } else {
                        Blog82AIDashboard.showNotification(
                            data.data?.message || 'Failed to create sample data',
                            'error'
                        );
                    }
                })
                .catch(error => {
                    console.error('Error creating sample data:', error);
                    Blog82AIDashboard.showNotification(
                        'Error communicating with server',
                        'error'
                    );
                })
                .finally(() => {
                    button.disabled = false;
                    button.innerHTML = originalHTML;
                });
        };
    }

})(window, document);
