// Admin Dashboard JavaScript
document.addEventListener('DOMContentLoaded', function() {
    
    // Navigation functionality
    initializeNavigation();
    
    // Initialize charts
    initializeCharts();
    
    // Initialize modals
    initializeModals();
    
    // Initialize responsive features
    initializeResponsive();
    
    // Initialize table interactions
    initializeTableInteractions();
    
    // Initialize dashboard interactions
    initializeDashboardInteractions();
});

// Navigation Management
function initializeNavigation() {
    const navLinks = document.querySelectorAll('.nav-link');
    const pageContents = document.querySelectorAll('.page-content');
    const pageTitle = document.querySelector('.page-title');
    
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // Remove active class from all nav items
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            
            // Add active class to clicked item
            this.parentElement.classList.add('active');
            
            // Hide all pages
            pageContents.forEach(page => {
                page.style.display = 'none';
            });
            
            // Show selected page
            const targetPage = this.getAttribute('data-page');
            const targetElement = document.getElementById(targetPage);
            if (targetElement) {
                targetElement.style.display = 'block';
            }
            
            // Update page title
            const pageName = this.querySelector('span').textContent;
            pageTitle.textContent = pageName;
            
            // Initialize page-specific functionality
            initializePageSpecific(targetPage);
        });
    });
}

// Page-specific initializations
function initializePageSpecific(page) {
    switch(page) {
        case 'analytics':
            initializeAnalyticsCharts();
            break;
        case 'dashboard':
            // Dashboard charts are already initialized
            break;
    }
}

// Chart Initialization
function initializeCharts() {
    // Performance Chart
    const performanceCtx = document.getElementById('performanceChart');
    if (performanceCtx) {
        new Chart(performanceCtx, {
            type: 'line',
            data: {
                labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                datasets: [{
                    label: 'Recommendations Served',
                    data: [45000, 52000, 48000, 61000, 55000, 67000, 58000],
                    borderColor: '#dc2626',
                    backgroundColor: 'rgba(220, 38, 38, 0.1)',
                    tension: 0.4,
                    fill: true
                }, {
                    label: 'Click-through Rate (%)',
                    data: [18.2, 19.1, 17.8, 20.3, 18.9, 21.2, 19.5],
                    borderColor: '#f97316',
                    backgroundColor: 'rgba(249, 115, 22, 0.1)',
                    tension: 0.4,
                    fill: true,
                    yAxisID: 'y1'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    }
                },
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        grid: {
                            color: 'rgba(0, 0, 0, 0.1)'
                        }
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        grid: {
                            drawOnChartArea: false,
                        }
                    }
                }
            }
        });
    }

    // Adapter Distribution Chart
    const adapterCtx = document.getElementById('adapterChart');
    if (adapterCtx) {
        new Chart(adapterCtx, {
            type: 'doughnut',
            data: {
                labels: ['OTT', 'Retail', 'Pharma', 'Consulting'],
                datasets: [{
                    data: [45, 30, 15, 10],
                    backgroundColor: [
                        '#dc2626',
                        '#f97316', 
                        '#059669',
                        '#3b82f6'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            usePointStyle: true
                        }
                    }
                }
            }
        });
    }
}

// Analytics Charts
function initializeAnalyticsCharts() {
    // User Interactions Chart
    const interactionsCtx = document.getElementById('interactionsChart');
    if (interactionsCtx) {
        new Chart(interactionsCtx, {
            type: 'line',
            data: {
                labels: Array.from({length: 30}, (_, i) => i + 1),
                datasets: [{
                    label: 'Interactions',
                    data: generateRandomData(30, 35000, 45000),
                    borderColor: '#dc2626',
                    backgroundColor: 'rgba(220, 38, 38, 0.1)',
                    tension: 0.4,
                    fill: true,
                    pointRadius: 0,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    x: {
                        display: false
                    },
                    y: {
                        display: false
                    }
                }
            }
        });
    }

    // CTR Chart
    const ctrCtx = document.getElementById('ctrChart');
    if (ctrCtx) {
        new Chart(ctrCtx, {
            type: 'line',
            data: {
                labels: Array.from({length: 30}, (_, i) => i + 1),
                datasets: [{
                    label: 'CTR',
                    data: generateRandomData(30, 15, 22),
                    borderColor: '#f97316',
                    backgroundColor: 'rgba(249, 115, 22, 0.1)',
                    tension: 0.4,
                    fill: true,
                    pointRadius: 0,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    x: {
                        display: false
                    },
                    y: {
                        display: false
                    }
                }
            }
        });
    }

    // Conversion Chart
    const conversionCtx = document.getElementById('conversionChart');
    if (conversionCtx) {
        new Chart(conversionCtx, {
            type: 'line',
            data: {
                labels: Array.from({length: 30}, (_, i) => i + 1),
                datasets: [{
                    label: 'Conversion',
                    data: generateRandomData(30, 6, 10),
                    borderColor: '#059669',
                    backgroundColor: 'rgba(5, 150, 105, 0.1)',
                    tension: 0.4,
                    fill: true,
                    pointRadius: 0,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    x: {
                        display: false
                    },
                    y: {
                        display: false
                    }
                }
            }
        });
    }

    // Diversity Chart
    const diversityCtx = document.getElementById('diversityChart');
    if (diversityCtx) {
        new Chart(diversityCtx, {
            type: 'line',
            data: {
                labels: Array.from({length: 30}, (_, i) => i + 1),
                datasets: [{
                    label: 'Diversity',
                    data: generateRandomData(30, 0.6, 0.8),
                    borderColor: '#3b82f6',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    tension: 0.4,
                    fill: true,
                    pointRadius: 0,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    x: {
                        display: false
                    },
                    y: {
                        display: false,
                        min: 0,
                        max: 1
                    }
                }
            }
        });
    }
}

// Modal Management
function initializeModals() {
    const addTenantBtn = document.getElementById('addTenantBtn');
    const addAppBtn = document.getElementById('addAppBtn');
    const addTenantModal = document.getElementById('addTenantModal');
    const modalCloses = document.querySelectorAll('.modal-close');
    
    // Add Tenant Button
    if (addTenantBtn) {
        addTenantBtn.addEventListener('click', function() {
            showModal('addTenantModal');
        });
    }
    
    // Add App Button
    if (addAppBtn) {
        addAppBtn.addEventListener('click', function() {
            // Create app modal would be similar to tenant modal
            console.log('Add App clicked');
        });
    }
    
    // Modal close buttons
    modalCloses.forEach(closeBtn => {
        closeBtn.addEventListener('click', function() {
            closeModal(this.closest('.modal'));
        });
    });
    
    // Click outside to close
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('modal')) {
            closeModal(e.target);
        }
    });
}

function showModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.add('active');
    }
}

function closeModal(modal) {
    if (modal) {
        modal.classList.remove('active');
    }
}

// Responsive Features
function initializeResponsive() {
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    const sidebar = document.querySelector('.sidebar');
    
    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('active');
        });
    }
    
    // Close sidebar when clicking outside on mobile
    document.addEventListener('click', function(e) {
        if (window.innerWidth <= 1024) {
            if (!sidebar.contains(e.target) && !sidebarToggle.contains(e.target)) {
                sidebar.classList.remove('active');
            }
        }
    });
}

// Table Interactions
function initializeTableInteractions() {
    // Search functionality
    const searchInputs = document.querySelectorAll('.search-input');
    searchInputs.forEach(input => {
        input.addEventListener('input', function() {
            filterTable(this, this.value);
        });
    });
    
    // Filter selects
    const filterSelects = document.querySelectorAll('.filter-select');
    filterSelects.forEach(select => {
        select.addEventListener('change', function() {
            filterTable(this, this.value);
        });
    });
    
    // Action buttons
    document.addEventListener('click', function(e) {
        if (e.target.closest('.btn-icon')) {
            const action = e.target.closest('.btn-icon').getAttribute('title');
            console.log(`Action: ${action}`);
            
            // Handle different actions
            switch(action) {
                case 'Edit':
                    handleEdit(e.target);
                    break;
                case 'View':
                    handleView(e.target);
                    break;
                case 'Delete':
                    handleDelete(e.target);
                    break;
                case 'Settings':
                    handleSettings(e.target);
                    break;
            }
        }
    });
}

function filterTable(element, value) {
    const table = element.closest('.data-table-card').querySelector('table');
    const rows = table.querySelectorAll('tbody tr');
    
    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        if (text.includes(value.toLowerCase())) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
}

function handleEdit(element) {
    console.log('Edit action triggered');
    // Implement edit functionality
}

function handleView(element) {
    console.log('View action triggered');
    // Implement view functionality
}

function handleDelete(element) {
    if (confirm('Are you sure you want to delete this item?')) {
        console.log('Delete action confirmed');
        // Implement delete functionality
    }
}

function handleSettings(element) {
    console.log('Settings action triggered');
    // Implement settings functionality
}

// Dashboard Interactions
function initializeDashboardInteractions() {
    // Time filter changes
    const timeFilters = document.querySelectorAll('.time-filter');
    timeFilters.forEach(filter => {
        filter.addEventListener('change', function() {
            updateChartData(this.value);
        });
    });
    
    // Time range buttons
    const timeButtons = document.querySelectorAll('.time-btn');
    timeButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            // Remove active class from all buttons
            timeButtons.forEach(b => b.classList.remove('active'));
            // Add active class to clicked button
            this.classList.add('active');
            
            updateAnalyticsData(this.textContent);
        });
    });
    
    // Tab buttons
    const tabButtons = document.querySelectorAll('.tab-btn');
    tabButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            // Remove active class from siblings
            const siblings = this.parentElement.querySelectorAll('.tab-btn');
            siblings.forEach(s => s.classList.remove('active'));
            // Add active class to clicked button
            this.classList.add('active');
            
            updateContentList(this.textContent);
        });
    });
    
    // Notification button
    const notificationBtn = document.querySelector('.notification-btn');
    if (notificationBtn) {
        notificationBtn.addEventListener('click', function() {
            console.log('Notifications clicked');
            // Implement notifications dropdown
        });
    }
    
    // Auto-refresh data every 30 seconds
    setInterval(updateLiveData, 30000);
}

function updateChartData(timeRange) {
    console.log(`Updating charts for: ${timeRange}`);
    // Implement chart data update based on time range
}

function updateAnalyticsData(timeRange) {
    console.log(`Updating analytics for: ${timeRange}`);
    // Implement analytics data update
}

function updateContentList(adapter) {
    console.log(`Updating content list for: ${adapter}`);
    // Implement content list update based on adapter
}

function updateLiveData() {
    // Update real-time statistics
    const statValues = document.querySelectorAll('.stat-info h3');
    statValues.forEach(stat => {
        // Simulate live data updates with small random changes
        const currentValue = parseFloat(stat.textContent.replace(/[^\d.]/g, ''));
        const change = (Math.random() - 0.5) * 0.02; // ±1% change
        const newValue = Math.max(0, currentValue * (1 + change));
        
        // Format the value appropriately
        if (stat.textContent.includes('M')) {
            stat.textContent = (newValue).toFixed(1) + 'M';
        } else if (stat.textContent.includes('%')) {
            stat.textContent = (newValue).toFixed(1) + '%';
        } else {
            stat.textContent = Math.round(newValue).toString();
        }
    });
    
    // Update change indicators
    const changes = document.querySelectorAll('.stat-change');
    changes.forEach(change => {
        const randomChange = (Math.random() - 0.4) * 10; // Slight bias towards positive
        const isPositive = randomChange > 0;
        
        change.textContent = (isPositive ? '+' : '') + randomChange.toFixed(1) + '%';
        change.className = 'stat-change ' + (isPositive ? 'positive' : 'negative');
    });
}

// Utility Functions
function generateRandomData(length, min, max) {
    return Array.from({length}, () => Math.random() * (max - min) + min);
}

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

function formatDate(date) {
    return new Intl.DateTimeFormat('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    }).format(new Date(date));
}

// API simulation functions (would connect to real backend in production)
class API {
    static async getTenants() {
        // Simulate API call
        return new Promise(resolve => {
            setTimeout(() => {
                resolve([
                    { id: '001', name: 'StreamingCorp', status: 'active', apps: 3, created: '2024-01-15' },
                    { id: '002', name: 'RetailGiant', status: 'active', apps: 5, created: '2024-01-12' }
                ]);
            }, 500);
        });
    }
    
    static async getApps() {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve([
                    { id: '1-001', name: 'StreamingPlatform', tenant: 'StreamingCorp', adapter: 'ott', status: 'active', rpm: 2000 },
                    { id: '2-001', name: 'ShoppingApp', tenant: 'RetailGiant', adapter: 'retail', status: 'active', rpm: 5000 }
                ]);
            }, 500);
        });
    }
    
    static async getAnalytics(timeRange) {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve({
                    interactions: generateRandomData(30, 35000, 45000),
                    ctr: generateRandomData(30, 15, 22),
                    conversion: generateRandomData(30, 6, 10),
                    diversity: generateRandomData(30, 0.6, 0.8)
                });
            }, 500);
        });
    }
}

// Export for use in other scripts if needed
window.RecoraAdmin = {
    API,
    showModal,
    closeModal,
    updateChartData,
    updateAnalyticsData
};
