// Main JavaScript for CryptoExchange Pro

// Global variables
let priceUpdateInterval;
let tradeRefreshInterval;

// Initialize application
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

function initializeApp() {
    // Initialize price updates
    if (document.querySelector('[id^="price-"]')) {
        startPriceUpdates();
    }
    
    // Initialize trade refresh
    if (document.getElementById('tradesTable')) {
        startTradeRefresh();
    }
    
    // Initialize form validations
    initializeFormValidations();
    
    // Initialize tooltips and popovers
    initializeTooltips();
    
    // Initialize real-time notifications
    initializeNotifications();
    
    // Initialize chart updates
    if (typeof Chart !== 'undefined') {
        initializeCharts();
    }
}

// Price update functionality
function startPriceUpdates() {
    updatePrices(); // Initial update
    priceUpdateInterval = setInterval(updatePrices, 30000); // Update every 30 seconds
}

async function updatePrices() {
    try {
        const response = await fetch('api/prices.php');
        const data = await response.json();
        
        if (data.success) {
            data.prices.forEach(price => {
                const priceElement = document.getElementById(`price-${price.symbol}`);
                if (priceElement) {
                    const oldPrice = parseFloat(priceElement.textContent.replace('$', ''));
                    const newPrice = parseFloat(price.current_price);
                    
                    // Update price
                    priceElement.textContent = '$' + newPrice.toFixed(8);
                    
                    // Add animation based on price change
                    if (newPrice > oldPrice) {
                        priceElement.classList.add('price-up');
                        setTimeout(() => priceElement.classList.remove('price-up'), 1000);
                    } else if (newPrice < oldPrice) {
                        priceElement.classList.add('price-down');
                        setTimeout(() => priceElement.classList.remove('price-down'), 1000);
                    }
                }
            });
        }
    } catch (error) {
        console.error('Price update error:', error);
    }
}

// Trade refresh functionality
function startTradeRefresh() {
    tradeRefreshInterval = setInterval(() => {
        if (document.getElementById('tradesTable')) {
            refreshTrades();
        }
    }, 15000); // Refresh every 15 seconds
}

function refreshTrades() {
    // Only refresh if user is not actively interacting
    if (!document.activeElement || document.activeElement.tagName !== 'INPUT') {
        location.reload();
    }
}

// Form validation
function initializeFormValidations() {
    const forms = document.querySelectorAll('.needs-validation');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(event) {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        });
    });
    
    // Real-time validation for specific fields
    const emailInputs = document.querySelectorAll('input[type="email"]');
    emailInputs.forEach(input => {
        input.addEventListener('blur', validateEmail);
    });
    
    const passwordInputs = document.querySelectorAll('input[type="password"]');
    passwordInputs.forEach(input => {
        input.addEventListener('input', validatePassword);
    });
}

function validateEmail(event) {
    const email = event.target.value;
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    
    if (email && !emailRegex.test(email)) {
        event.target.setCustomValidity('Please enter a valid email address');
    } else {
        event.target.setCustomValidity('');
    }
}

function validatePassword(event) {
    const password = event.target.value;
    const minLength = 8;
    const hasUpperCase = /[A-Z]/.test(password);
    const hasLowerCase = /[a-z]/.test(password);
    const hasNumbers = /\d/.test(password);
    const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
    
    if (password.length < minLength) {
        event.target.setCustomValidity(`Password must be at least ${minLength} characters long`);
    } else if (!hasUpperCase) {
        event.target.setCustomValidity('Password must contain at least one uppercase letter');
    } else if (!hasLowerCase) {
        event.target.setCustomValidity('Password must contain at least one lowercase letter');
    } else if (!hasNumbers) {
        event.target.setCustomValidity('Password must contain at least one number');
    } else if (!hasSpecialChar) {
        event.target.setCustomValidity('Password must contain at least one special character');
    } else {
        event.target.setCustomValidity('');
    }
}

// Tooltip initialization
function initializeTooltips() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

// Notification system
function initializeNotifications() {
    // Check for browser notification support
    if ('Notification' in window) {
        if (Notification.permission === 'default') {
            Notification.requestPermission();
        }
    }
}

function showNotification(title, message, type = 'info') {
    // Browser notification
    if ('Notification' in window && Notification.permission === 'granted') {
        new Notification(title, {
            body: message,
            icon: '/assets/images/logo.png'
        });
    }
    
    // In-app notification
    showToast(message, type);
}

function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type === 'error' ? 'danger' : type === 'success' ? 'success' : 'primary'} border-0`;
    toast.setAttribute('role', 'alert');
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">${message}</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    `;
    
    const toastContainer = document.getElementById('toastContainer') || createToastContainer();
    toastContainer.appendChild(toast);
    
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
    
    // Remove toast after it's hidden
    toast.addEventListener('hidden.bs.toast', () => {
        toast.remove();
    });
}

function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toastContainer';
    container.className = 'toast-container position-fixed top-0 end-0 p-3';
    container.style.zIndex = '9999';
    document.body.appendChild(container);
    return container;
}

// Chart initialization
function initializeCharts() {
    const chartElements = document.querySelectorAll('.chart-container canvas');
    
    chartElements.forEach(canvas => {
        const chartType = canvas.dataset.chartType || 'line';
        const chartData = JSON.parse(canvas.dataset.chartData || '{}');
        
        new Chart(canvas, {
            type: chartType,
            data: chartData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: canvas.dataset.chartTitle || 'Chart'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    });
}

// Utility functions
function formatCurrency(amount, decimals = 2) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: decimals,
        maximumFractionDigits: decimals
    }).format(amount);
}

function formatCrypto(amount, decimals = 8) {
    return parseFloat(amount).toFixed(decimals);
}

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

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// API helper functions
async function apiRequest(url, options = {}) {
    const defaultOptions = {
        headers: {
            'Content-Type': 'application/json',
        },
    };
    
    const config = { ...defaultOptions, ...options };
    
    try {
        const response = await fetch(url, config);
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.message || 'API request failed');
        }
        
        return data;
    } catch (error) {
        console.error('API Error:', error);
        throw error;
    }
}

// Security functions
function sanitizeInput(input) {
    const div = document.createElement('div');
    div.textContent = input;
    return div.innerHTML;
}

function validateCSRFToken() {
    const token = document.querySelector('meta[name="csrf-token"]');
    return token ? token.getAttribute('content') : null;
}

// Performance monitoring
function measurePerformance(name, fn) {
    const start = performance.now();
    const result = fn();
    const end = performance.now();
    console.log(`${name} took ${end - start} milliseconds`);
    return result;
}

// Error handling
window.addEventListener('error', function(event) {
    console.error('Global error:', event.error);
    // You could send this to a logging service
});

window.addEventListener('unhandledrejection', function(event) {
    console.error('Unhandled promise rejection:', event.reason);
    // You could send this to a logging service
});

// Cleanup on page unload
window.addEventListener('beforeunload', function() {
    if (priceUpdateInterval) {
        clearInterval(priceUpdateInterval);
    }
    if (tradeRefreshInterval) {
        clearInterval(tradeRefreshInterval);
    }
});

// Export functions for use in other scripts
window.CryptoExchange = {
    updatePrices,
    refreshTrades,
    showNotification,
    showToast,
    formatCurrency,
    formatCrypto,
    formatDate,
    apiRequest,
    sanitizeInput
};