// Fetch data from the PHP file
fetch('../app/getdata.php')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json(); // Parse the JSON data
    })
    .then(data => {
        initializeTrades(data);
        // console.log(data);
    })
    .catch(error => {
        console.error('There was a problem with the fetch operation:', error);
    });

const marketData = [
    {
        "market": "Crypto",
        "tradingPairs": [
            { "pair": "BITSTAMP:BTCUSD", "description": "Bitcoin to US Dollar" },
            { "pair": "COINBASE:ETHUSD", "description": "Ethereum to US Dollar" },
            { "pair": "BINANCE:BNBUSDT", "description": "Binance Coin to USDT" },
            { "pair": "KRAKEN:XRPUSD", "description": "Ripple to US Dollar" }
        ]
    },
    {
        "market": "Forex",
        "tradingPairs": [
            { "pair": "OANDA:EURUSD", "description": "Euro to US Dollar" },
            { "pair": "OANDA:GBPJPY", "description": "British Pound to Japanese Yen" },
            { "pair": "OANDA:USDCHF", "description": "US Dollar to Swiss Franc" },
            { "pair": "OANDA:AUDCAD", "description": "Australian Dollar to Canadian Dollar" }
        ]
    },
    {
        "market": "Commodities",
        "tradingPairs": [
            { "pair": "TVC:GOLD", "description": "Gold to US Dollar" },
            { "pair": "TVC:SILVER", "description": "Silver to US Dollar" },
            { "pair": "TVC:USOIL", "description": "Crude Oil to US Dollar" },
            { "pair": "TVC:COPPER", "description": "Copper to US Dollar" }
        ]
    },
    {
        "market": "Stocks",
        "tradingPairs": [
            { "pair": "NASDAQ:AAPL", "description": "Apple Inc." },
            { "pair": "NASDAQ:TSLA", "description": "Tesla Inc." },
            { "pair": "NASDAQ:AMZN", "description": "Amazon Inc." },
            { "pair": "NASDAQ:GOOGL", "description": "Alphabet Inc." }
        ]
    },
    {
        "market": "Indices",
        "tradingPairs": [
            { "pair": "TVC:SPX", "description": "S&P 500 Index" },
            { "pair": "TVC:IXIC", "description": "NASDAQ Composite" },
            { "pair": "TVC:DJI", "description": "Dow Jones Industrial Average" },
            { "pair": "TVC:FTSE", "description": "FTSE 100 Index" }
        ]
    }
];


        // Function to update the trading pairs dropdown based on the selected market
        function updateTradingPairs(selectedMarket) {
            const tradingPairSelect = document.getElementById('tradingPairSelect');
            
            // Clear previous options
            tradingPairSelect.innerHTML = '';

            // Enable the select dropdown
            tradingPairSelect.disabled = false;

            // Add a default option
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = 'Select a trading pair';
            tradingPairSelect.appendChild(defaultOption);

            // Find the selected market in the JSON data
            const market = marketData.find(item => item.market === selectedMarket);

            // Populate the select dropdown with trading pairs of the selected market
            if (market) {
                market.tradingPairs.forEach(pair => {
                    const option = document.createElement('option');
                    option.value = pair.pair;
                    option.textContent = `${pair.pair} (${pair.description})`;
                    tradingPairSelect.appendChild(option);
                });
            }
        }

        // Event listener for market selection
        document.querySelectorAll('.market-trade-list li a').forEach(link => {
            link.addEventListener('click', function() {
                // Remove the active class from all links
                document.querySelectorAll('.market-trade-list li a').forEach(item => item.classList.remove('trade-active'));
                
                // Add the active class to the clicked link
                this.classList.add('trade-active');
                document.querySelector('#trade_market').value = this.innerHTML;
                // Update trading pairs based on the selected market
                updateTradingPairs(this.getAttribute('data-market'));
            });
        });



// class TradeSimulator {
//     constructor(tradeId, initialProfit, targetProfit, totalMinutes, allowDecrement) {
//         this.tradeId = tradeId;
//         this.initialProfit = initialProfit;
//         this.targetProfit = targetProfit;
//         this.totalMinutes = totalMinutes;
//         this.allowDecrement = allowDecrement;
//         this.intervalTime = 1000; // Update every 1 second (1000 milliseconds)
//         this.totalSteps = (this.totalMinutes * 60 * 1000) / this.intervalTime; // Total number of steps for updates
//         this.averageStepChange = Math.abs(this.targetProfit - this.initialProfit) / this.totalSteps; // Average change per step
//         this.currentProfit = this.initialProfit;
//         this.previousProfit = this.initialProfit;

//         // Create the display element for this trade
//         this.createTradeDisplay();
//         this.simulateProfitFluctuation();
//     }

//     createTradeDisplay() {
//         const tradesContainer = document.getElementById('tradesContainer');
//         this.tradeDisplay = document.createElement('div');
//         this.tradeDisplay.classList.add('profit-display');
//         this.tradeDisplay.setAttribute('id', `trade-${this.tradeId}`);
//         tradesContainer.appendChild(this.tradeDisplay);
//         this.updateProfitDisplay(this.currentProfit, this.previousProfit);
//     }

//     simulateProfitFluctuation() {
//         this.previousProfit = this.currentProfit;

//         // Determine if we should increase or decrease profit
//         let isIncrease = this.allowDecrement ? Math.random() > 0.5 : false; // 50% chance to increase if decrements are allowed

//         // If the target profit is negative, we need to prioritize decreasing
//         if (this.targetProfit < 0 && this.currentProfit > this.targetProfit) {
//             isIncrease = false; // Force decrease to reach the negative target
//         }

//         const fluctuationAmount = Math.random() * this.averageStepChange;

//         // Adjust profit based on the direction
//         this.currentProfit += isIncrease ? fluctuationAmount : -fluctuationAmount - this.averageStepChange;

//         // Ensure the profit does not exceed the initial profit or fall below the target profit
//         this.currentProfit = Math.max(this.targetProfit, Math.min(this.currentProfit, this.initialProfit));

//         // Update the display
//         this.updateProfitDisplay(this.currentProfit, this.previousProfit);

//         // Continue the simulation until we reach the target profit
//         if (this.currentProfit > this.targetProfit) {
//             setTimeout(() => this.simulateProfitFluctuation(), this.intervalTime);
//         }
//     }

//     updateProfitDisplay(current, previous) {
//         const formattedProfit = `$${current.toFixed(2)}`;
//         this.tradeDisplay.textContent = `Trade ${this.tradeId}: ${formattedProfit}`;

//         // Change the display color based on the profit value
//         if (current < 0) {
//             // If the profit is negative, always show red color
//             this.tradeDisplay.classList.remove('profit-increase');
//             this.tradeDisplay.classList.add('profit-decrease');
//         } else {
//             // Default logic for positive values
//             if (current > previous) {
//                 this.tradeDisplay.classList.remove('profit-decrease');
//                 this.tradeDisplay.classList.add('profit-increase');
//             } else {
//                 this.tradeDisplay.classList.remove('profit-increase');
//                 this.tradeDisplay.classList.add('profit-decrease');
//             }
//         }
//     }
// }
class TradeSimulator {
    constructor(tradeId, initialProfit, targetProfit, totalMinutes, allowDecrement) {
        this.tradeId = tradeId;
        this.initialProfit = Number(initialProfit); // Convert to number
        this.targetProfit = Number(targetProfit); // Convert to number
        this.totalMinutes = Number(totalMinutes); // Convert to number
        this.allowDecrement = allowDecrement;
        this.intervalTime = 1000; // Update every 1 second (1000 milliseconds)
        this.totalSteps = (this.totalMinutes * 60 * 1000) / this.intervalTime; // Total number of steps for updates
        this.averageStepChange = Math.abs(this.targetProfit - this.initialProfit) / this.totalSteps; // Average change per step
        this.currentProfit = this.initialProfit;
        this.previousProfit = this.initialProfit;

        console.log(tradeId, this.initialProfit, this.targetProfit, this.totalMinutes, allowDecrement);

        // Directly target the existing display element using the trade ID
        this.tradeDisplay = document.getElementById(`displayprofit-${this.tradeId}`);

        // Start the profit fluctuation simulation
        this.simulateProfitFluctuation();
    }
    simulateProfitFluctuation() {
        this.previousProfit = this.currentProfit;
    
        // Determine if we should increase or decrease profit
        let isIncrease = this.allowDecrement ? Math.random() > 0.5 : true; // Default to increase if decrements are not allowed
    
        // Adjust logic based on the target profit direction
        if (this.targetProfit > this.initialProfit) {
            // If the target is higher than the initial, we prioritize increasing
            isIncrease = true;
        } else if (this.targetProfit < 0 && this.currentProfit > this.targetProfit) {
            // If the target profit is negative and we haven't reached it yet, prioritize decreasing
            isIncrease = false;
        }
    
        const fluctuationAmount = Math.random() * this.averageStepChange;
    
        // Adjust profit based on the direction
        this.currentProfit += isIncrease ? fluctuationAmount : -fluctuationAmount - this.averageStepChange;
    
        // Ensure the profit does not exceed the initial profit or fall below the target profit
        if (this.targetProfit > this.initialProfit) {
            // If we are incrementing, ensure the current profit does not exceed the target profit
            this.currentProfit = Math.min(this.targetProfit, this.currentProfit);
        } else {
            // If we are decrementing, ensure the current profit does not go below the target profit
            this.currentProfit = Math.max(this.targetProfit, this.currentProfit);
        }
    
        // Update the display
        this.updateProfitDisplay(this.currentProfit, this.previousProfit);
    
        // Continue the simulation until we reach the target profit
        if ((this.targetProfit > this.initialProfit && this.currentProfit < this.targetProfit) || 
            (this.targetProfit < this.initialProfit && this.currentProfit > this.targetProfit)) {
            setTimeout(() => this.simulateProfitFluctuation(), this.intervalTime);
        }
    }
    
    // simulateProfitFluctuation() {
    //     this.previousProfit = this.currentProfit;

    //     // Determine if we should increase or decrease profit
    //     let isIncrease = this.allowDecrement ? Math.random() > 0.5 : false; // 50% chance to increase if decrements are allowed

    //     // If the target profit is negative, we need to prioritize decreasing
    //     if (this.targetProfit < 0 && this.currentProfit > this.targetProfit) {
    //         isIncrease = false; // Force decrease to reach the negative target
    //     }

    //     const fluctuationAmount = Math.random() * this.averageStepChange;

    //     // Adjust profit based on the direction
    //     this.currentProfit += isIncrease ? fluctuationAmount : -fluctuationAmount - this.averageStepChange;

    //     // Ensure the profit does not exceed the initial profit or fall below the target profit
    //     this.currentProfit = Math.max(this.targetProfit, Math.min(this.currentProfit, this.initialProfit));

    //     // Update the display
    //     this.updateProfitDisplay(this.currentProfit, this.previousProfit);

    //     // Continue the simulation until we reach the target profit
    //     if (this.currentProfit > this.targetProfit) {
    //         setTimeout(() => this.simulateProfitFluctuation(), this.intervalTime);
    //     }
    // }

    updateProfitDisplay(current, previous) {
        const formattedProfit = `${current.toFixed(2)}`;
        if (this.tradeDisplay) {
            this.tradeDisplay.textContent = `${formattedProfit}`;

            // Change the display color based on the profit value
            if (current < 0) {
                // If the profit is negative, always show red color
                this.tradeDisplay.classList.remove('profit-increase');
                this.tradeDisplay.classList.add('profit-decrease');
            } else {
                // Default logic for positive values
                if (current > previous) {
                    this.tradeDisplay.classList.remove('profit-decrease');
                    this.tradeDisplay.classList.add('profit-increase');
                } else {
                    this.tradeDisplay.classList.remove('profit-increase');
                    this.tradeDisplay.classList.add('profit-decrease');
                }
            }
        }
    }
}

// Function to initialize multiple trades using the array data
function initializeTrades(arr) {
    console.log(arr)
    arr.forEach(trade => {
        const {tradeId, initialProfit, targetProfit, totalMinutes, allowDecrement} = trade;
        // Create a new instance of TradeSimulator for each trade
        new TradeSimulator(tradeId, initialProfit, targetProfit, totalMinutes, allowDecrement);
    });
}

// const arr = [{'id':1, 'startprofit':100,'finalprofit':1000,'decrease':true},
//     {'id':1, 'startprofit':100,'finalprofit':1000,'decrease':true},
//     {'id':2, 'startprofit':200,'finalprofit':1400,'decrease':true},
//     {'id':3, 'startprofit':300,'finalprofit':1500,'decrease':true},
//     {'id':4, 'startprofit':400,'finalprofit':1300,'decrease':true}];
// // Function to initialize multiple trades
// function initializeTrades() {
//     const trade1 = new TradeSimulator(1, 100, -500, 5, true);
//     const trade2 = new TradeSimulator(2, 200, -300, 4, true);
//     const trade3 = new TradeSimulator(3, 150, 500, 6, true);
//     const trade4 = new TradeSimulator(4, 50, 300, 3, true);
// }

// Start the trades simulation
// initializeTrades();