<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Binance Price Tracker</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            padding: 20px;
            background-color: #f8f9fa;
        }
        .card {
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .price-positive {
            color: #198754;
        }
        .price-negative {
            color: #dc3545;
        }
        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 5px;
        }
        .status-active {
            background-color: #198754;
        }
        .status-error {
            background-color: #dc3545;
        }
        .last-update {
            font-size: 0.85rem;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="mb-4 text-center">Binance Price Tracker</h1>
        
        <!-- Status Display -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">API Status</h5>
                        <div id="api-status">
                            <span class="status-indicator status-active"></span>
                            <span>Connected to Binance API</span>
                        </div>
                        <div class="last-update mt-2">
                            Last Update: <span id="last-update-time">Never</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">Demo API</h5>
                        <div id="demo-api-status">
                            <span class="status-indicator status-active"></span>
                            <span>Ready to send data</span>
                        </div>
                        <div class="mt-2">
                            Calls to Demo API: <span id="demo-api-count">0</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Price Cards -->
        <div class="row" id="price-container">
            <!-- Prices will be loaded here -->
        </div>

        <!-- Log Section -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">API Call Log</h5>
                        <div id="api-log" class="border rounded p-2" style="max-height: 200px; overflow-y: auto; background-color: #f8f9fa;">
                            <div class="text-muted">Waiting for first API call...</div>
                        </div>
                        <div class="mt-2 d-flex justify-content-between">
                            <button id="clear-log" class="btn btn-sm btn-outline-secondary">Clear Log</button>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="auto-refresh" checked>
                                <label class="form-check-label" for="auto-refresh">Auto-refresh (2s)</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <!-- Bootstrap JS Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        $(document).ready(function() {
            let previousPrices = {};
            let demoApiCount = 0;
            let updateInterval;
            let isAutoRefresh = true;

            // Demo API endpoint - you can change this later
            const DEMO_API_URL = 'https://jsonplaceholder.typicode.com/posts';

            // Price template
            const priceCardTemplate = (symbol, price, change) => `
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">${symbol}</h5>
                            <h2 class="card-text">$${parseFloat(price).toFixed(2)}</h2>
                            <div class="${change >= 0 ? 'price-positive' : 'price-negative'}">
                                ${change >= 0 ? '+' : ''}${change.toFixed(2)}%
                            </div>
                            <div class="last-update mt-2">
                                Symbol: ${symbol}
                            </div>
                        </div>
                    </div>
                </div>
            `;

            // Add log entry
            function addLogEntry(message, type = 'info') {
                const time = new Date().toLocaleTimeString();
                const logEntry = `
                    <div class="mb-1">
                        <span class="text-muted">[${time}]</span>
                        <span class="${type === 'error' ? 'text-danger' : 'text-success'}">
                            ${message}
                        </span>
                    </div>
                `;
                
                $('#api-log').prepend(logEntry);
                
                // Keep only last 20 entries
                const logEntries = $('#api-log > div');
                if (logEntries.length > 20) {
                    logEntries.last().remove();
                }
            }

            // Update status
            function updateStatus(isError = false) {
                if (isError) {
                    $('#api-status').html('<span class="status-indicator status-error"></span><span class="text-danger">Error connecting to Binance API</span>');
                } else {
                    $('#api-status').html('<span class="status-indicator status-active"></span><span>Connected to Binance API</span>');
                }
            }

            // Fetch prices from Binance
            function fetchPrices() {
                // Update timestamp
                $('#last-update-time').text(new Date().toLocaleTimeString());

                // Fetch BTC/USDT price
                $.ajax({
                    url: 'https://api.binance.com/api/v3/ticker/price',
                    method: 'GET',
                    data: { symbol: 'BTCUSDT' },
                    success: function(btcResponse) {
                        addLogEntry(`Fetched BTC/USDT: $${parseFloat(btcResponse.price).toFixed(2)}`);
                        
                        // Fetch ETH/USDT price
                        $.ajax({
                            url: 'https://api.binance.com/api/v3/ticker/price',
                            method: 'GET',
                            data: { symbol: 'ETHUSDT' },
                            success: function(ethResponse) {
                                addLogEntry(`Fetched ETH/USDT: $${parseFloat(ethResponse.price).toFixed(2)}`);
                                
                                // Calculate percentage changes
                                const btcChange = calculateChange('BTCUSDT', btcResponse.price);
                                const ethChange = calculateChange('ETHUSDT', ethResponse.price);
                                
                                // Display prices
                                const priceHTML = priceCardTemplate('BTC/USD', btcResponse.price, btcChange) +
                                                 priceCardTemplate('ETH/USD', ethResponse.price, ethChange);
                                $('#price-container').html(priceHTML);
                                
                                // Update previous prices
                                previousPrices['BTCUSDT'] = parseFloat(btcResponse.price);
                                previousPrices['ETHUSDT'] = parseFloat(ethResponse.price);
                                
                                // Send data to demo API
                                sendToDemoApi(btcResponse.symbol,btcResponse.price);
                                sendToDemoApi(ethResponse.symbol,ethResponse.price);
                                
                                updateStatus(false);
                            },
                            error: function() {
                                addLogEntry('Error fetching ETH/USDT price', 'error');
                                updateStatus(true);
                            }
                        });
                    },
                    error: function() {
                        addLogEntry('Error fetching BTC/USDT price', 'error');
                        updateStatus(true);
                    }
                });
            }

            // Calculate percentage change
            function calculateChange(symbol, currentPrice) {
                const current = parseFloat(currentPrice);
                const previous = previousPrices[symbol] || current;
                
                if (previous === 0 || previous === current) return 0;
                return ((current - previous) / previous) * 100;
            }

            // Send data to demo API
            function sendToDemoApi(d1,d2) {
                //var dd=JSON.stringify(data);
                var d=d1.slice(0, -1);
                var sym=d.slice(0, 3) + '_' + d.slice(3, 6);
                //return false;
                var alldata=[d2+"|"+d2+"|"+sym+"|"+'#000|#000|0|0'];
                //console.log(alldata);
                $.ajax({
                    type: "POST",
                    url: '<?php echo base_url();?>home/ajax_trade_calc',
                    data: {alldata:alldata},
                    success: function(res){
                        //console.log(res);
                        //$("#live_trades").html(res);
                    }
                });

                

            }

            // Start auto-refresh
            function startAutoRefresh() {
                if (updateInterval) clearInterval(updateInterval);
                
                fetchPrices();
                updateInterval = setInterval(fetchPrices, 2000);
                isAutoRefresh = true;
                $('#auto-refresh').prop('checked', true);
            }

            // Stop auto-refresh
            function stopAutoRefresh() {
                if (updateInterval) {
                    clearInterval(updateInterval);
                    updateInterval = null;
                }
                isAutoRefresh = false;
                $('#auto-refresh').prop('checked', false);
                addLogEntry('Auto-refresh stopped');
            }

            // Event Listeners
            $('#auto-refresh').change(function() {
                if ($(this).is(':checked')) {
                    startAutoRefresh();
                } else {
                    stopAutoRefresh();
                }
            });

            $('#clear-log').click(function() {
                $('#api-log').html('<div class="text-muted">Log cleared</div>');
            });

            // Manual refresh function (if needed)
            window.refreshPrices = function() {
                fetchPrices();
            };

            // Initialize
            startAutoRefresh();
        });
    </script>
</body>
</html>