<script>
      $(document).ready(function(){
          
            // Crypto Data Array
            const cryptos = [
                { symbol: 'BTC', name: 'Bitcoin', icon: 'logos/bitcoin-btc-logo.png' },
                { symbol: 'ETH', name: 'Ethereum', icon: 'logos/ethereum-eth-logo.png' },
                { symbol: 'BNB', name: 'Binance Coin', icon: 'logos/bnb-bnb-logo.png' },
                { symbol: 'XRP', name: 'Ripple', icon: 'logos/xrp-xrp-logo.png' },
                { symbol: 'ADA', name: 'Cardano', icon: 'logos/cardano-ada-logo.png' },
                { symbol: 'SOL', name: 'Solana', icon: 'logos/solana-sol-logo.png' },
                { symbol: 'DOT', name: 'Polkadot', icon: 'logos/polkadot-new-dot-logo.png' },
                { symbol: 'DOGE', name: 'Dogecoin', icon: 'logos/dogecoin-doge-logo.png' }
            ];

            const apiKey = 'YOUR_COINMARKETCAP_API_KEY'; // Replace with actual API key
            const tickerContent = $('#tickerContent');
            const priceTableBody = $('#priceTableBody');

            // Fetch Crypto Prices for Ticker and Table
            function fetchCryptoPrices() {
                const symbols = cryptos.map(c => c.symbol).join(',');
                const url = `/php/coins.php`;

                $.ajax({
                    url: url,
                    method: 'GET',
                      success: function(datas) {
                        // console.log(datas);
                       d = JSON.parse(datas);
                        // Ticker Update
                        let tickerHtml = '';
                        cryptos.forEach((crypto,index) => {
                            data =  d[index]
                            const changeClass = data.changes >= 0 ? 'positive' : 'negative';
                            const changeSign = data.changes >= 0 ? '+' : '';
                            
                            tickerHtml += `
                                <div class="crypto-item">
                                    <img src="${crypto.icon}" alt="${crypto.name} icon" class="crypto-icon" onerror="this.src='assets/img/default-coin.png'">
                                    <span class="crypto-symbol">${(data.symbol).toUpperCase()}</span>
                                    <span class="crypto-price">$${parseFloat(data.price).toLocaleString(undefined, {maximumFractionDigits: 2})}</span>
                                    <span class="crypto-change ${changeClass}">${changeSign}${parseFloat(data.changes).toFixed(2)}%</span>
                                </div>
                            `;
                        });
                        tickerContent.html(tickerHtml + tickerHtml); // Duplicate for seamless loop

                        // Table Update
                        let tableHtml = '';
                        cryptos.forEach((crypto , index) => {
                             data =  d[index]
                            const changeClass = data.changes >= 0 ? 'positive' : 'negative';
                            const changeSign = data.changes >= 0 ? '+' : '';
                            tableHtml += `
                                <tr>
                                    <td>
                                        <img src="${crypto.icon}" alt="${crypto.name} icon" class="coin-icon" onerror="this.src='assets/img/default-coin.png'">
                                        <span class="coin-name">${crypto.name} (${crypto.symbol})</span>
                                    </td>
                                    <td class="price">$${parseFloat(data.price).toLocaleString(undefined, {maximumFractionDigits: 2})}</td>
                                    <td class="change ${changeClass}">${changeSign}${parseFloat(data.changes).toFixed(2)}%</td>
                                    <td class="market-cap">$${data.market_cap.toLocaleString(undefined, {maximumFractionDigits: 0})}</td>
                                </tr>
                            `;
                        });
                        priceTableBody.html(tableHtml);
                    },
                    error: function() {
                        // Fallback with demo data
                        let tickerHtml = '';
                        let tableHtml = '';
                        cryptos.forEach(crypto => {
                            const mockPrice = Math.random() * 100000;
                            const mockChange = (Math.random() - 0.5) * 10;
                            const mockMarketCap = Math.random() * 1000000000000;
                            const changeClass = mockChange >= 0 ? 'positive' : 'negative';
                            const changeSign = mockChange >= 0 ? '+' : '';

                            // Ticker Fallback
                            tickerHtml += `
                                <div class="crypto-item">
                                    <img src="${crypto.icon}" alt="${crypto.name} icon" class="crypto-icon" onerror="this.src='assets/img/default-coin.png'">
                                    <span class="crypto-symbol">${crypto.symbol}</span>
                                    <span class="crypto-price">$${mockPrice.toLocaleString(undefined, {maximumFractionDigits: 2})}</span>
                                    <span class="crypto-change ${changeClass}">${changeSign}${mockChange.toFixed(2)}%</span>
                                </div>
                            `;

                            // Table Fallback
                            tableHtml += `
                                <tr>
                                    <td>
                                        <img src="${crypto.icon}" alt="${crypto.name} icon" class="coin-icon" onerror="this.src='assets/img/default-coin.png'">
                                        <span class="coin-name">${crypto.name} (${crypto.symbol})</span>
                                    </td>
                                    <td class="price">$${mockPrice.toLocaleString(undefined, {maximumFractionDigits: 2})}</td>
                                    <td class="change ${changeClass}">${changeSign}${mockChange.toFixed(2)}%</td>
                                    <td class="market-cap">$${mockMarketCap.toLocaleString(undefined, {maximumFractionDigits: 0})}</td>
                                </tr>
                            `;
                        });
                        tickerContent.html(tickerHtml + tickerHtml);
                        priceTableBody.html(tableHtml);
                    }
                });
            }

            // Table Sorting
            $('.crypto-price-table th').on('click', function() {
                const sortKey = $(this).data('sort');
                const $table = $(this).closest('table');
                const $rows = $table.find('tbody tr').get();

                // Remove existing sort indicators
                $('.crypto-price-table th').removeClass('sort-asc sort-desc');

                // Toggle sort direction
                const isAsc = $(this).hasClass('sort-asc');
                $(this).addClass(isAsc ? 'sort-desc' : 'sort-asc').removeClass(isAsc ? 'sort-asc' : 'sort-desc');

                $rows.sort((a, b) => {
                    let aValue, bValue;
                    if (sortKey === 'symbol') {
                        aValue = $(a).find('.coin-name').text().toLowerCase();
                        bValue = $(b).find('.coin-name').text().toLowerCase();
                    } else if (sortKey === 'price') {
                        aValue = parseFloat($(a).find('.price').text().replace(/[$,]/g, ''));
                        bValue = parseFloat($(b).find('.price').text().replace(/[$,]/g, ''));
                    } else if (sortKey === 'change') {
                        aValue = parseFloat($(a).find('.change').text().replace('%', ''));
                        bValue = parseFloat($(b).find('.change').text().replace('%', ''));
                    } else if (sortKey === 'marketCap') {
                        aValue = parseFloat($(a).find('.market-cap').text().replace(/[$,]/g, ''));
                        bValue = parseFloat($(b).find('.market-cap').text().replace(/[$,]/g, ''));
                    }

                    if (isAsc) {
                        return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
                    } else {
                        return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
                    }
                });

                $.each($rows, function(index, row) {
                    $table.find('tbody').append(row);
                });
            });

            // Fetch prices every 30 seconds
            fetchCryptoPrices();
            setInterval(fetchCryptoPrices, 30000);
          
      });
</script>
          