// Landing Page JavaScript
(function () {
    'use strict';

    // ===================================
    // Navigation Scroll Effect
    // ===================================
    const navbar = document.getElementById('navbar');
    const navbarToggler = document.getElementById('navbarToggler');
    const navbarMenu = document.getElementById('navbarMenu');

    window.addEventListener('scroll', function () {
        if (window.scrollY > 50) {
            navbar.classList.add('scrolled');
        } else {
            navbar.classList.remove('scrolled');
        }
    });

    // Mobile Menu Toggle
    if (navbarToggler) {
        navbarToggler.addEventListener('click', function () {
            navbarMenu.classList.toggle('active');
        });
    }

    // Smooth Scroll for Navigation Links
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
                // Close mobile menu if open
                if (navbarMenu.classList.contains('active')) {
                    navbarMenu.classList.remove('active');
                }
            }
        });
    });

    // ===================================
    // Live Crypto Price Feed
    // ===================================
    const cryptoTableBody = document.getElementById('cryptoTableBody');
    let priceUpdateInterval;

    // Fetch and display cryptocurrency prices
    async function fetchCryptoPrices() {
        try {
            const response = await fetch(window.apiUrl);
            const data = await response.json();

            if (data.status === 'success' && data.data.length > 0) {
                displayCryptoPrices(data.data);
            } else {
                showError('No cryptocurrency data available');
            }
        } catch (error) {
            console.error('Error fetching crypto prices:', error);
            showError('Failed to load market data');
        }
    }

    // Display cryptocurrency prices in the table
    function displayCryptoPrices(cryptos) {
        if (!cryptoTableBody) return;

        cryptoTableBody.innerHTML = '';

        cryptos.forEach(crypto => {
            const row = document.createElement('tr');

            // Determine if price change is positive or negative
            const change = parseFloat(crypto.change_24h);
            const changeClass = change >= 0 ? 'positive' : 'negative';
            const changeSymbol = change >= 0 ? '+' : '';

            row.innerHTML = `
                <td>
                    <div class="crypto-name">
                        <div>
                            <div style="font-weight: 600;">${crypto.name_fa || crypto.name}</div>
                            <div class="crypto-symbol">${crypto.symbol}</div>
                        </div>
                    </div>
                </td>
                <td>
                    <span style="font-weight: 600;">$${formatNumber(crypto.price_usdt)}</span>
                </td>
                <td>
                    <span style="font-weight: 600;">${crypto.price_irt} IRT</span>
                </td>
                <td>
                    <span class="price-change ${changeClass}">
                        ${changeSymbol}${crypto.change_24h}%
                    </span>
                </td>
                <td>
                    <a href="${window.registerUrl}" class="btn btn-primary" style="padding: 0.5rem 1rem; font-size: 0.875rem;">
                        Trade
                    </a>
                </td>
            `;

            cryptoTableBody.appendChild(row);
        });
    }

    // Show error message in table
    function showError(message) {
        if (!cryptoTableBody) return;

        cryptoTableBody.innerHTML = `
            <tr>
                <td colspan="5" class="loading-cell">
                    <span style="color: var(--danger);">${message}</span>
                </td>
            </tr>
        `;
    }

    // Format number with commas
    function formatNumber(num) {
        if (!num) return '0';
        return parseFloat(num).toLocaleString('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }

    // Initialize price feed
    function initPriceFeed() {
        // Fetch prices immediately
        fetchCryptoPrices();

        // Update prices every 1 second for real-time updates
        priceUpdateInterval = setInterval(fetchCryptoPrices, 1000);
    }

    // ===================================
    // Page Load Initialization
    // ===================================
    document.addEventListener('DOMContentLoaded', function () {
        // Initialize crypto price feed
        initPriceFeed();

        // Add animation to elements on scroll
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };

        const observer = new IntersectionObserver(function (entries) {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                }
            });
        }, observerOptions);

        // Observe sections for animation
        document.querySelectorAll('.market-section, .about-section').forEach(section => {
            section.style.opacity = '0';
            section.style.transform = 'translateY(30px)';
            section.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
            observer.observe(section);
        });
    });

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

})();
