<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bybit Order Status Dashboard</title>
    <style>
        /* Dark theme styling */
        body { 
            font-family: Arial, sans-serif; 
            margin: 20px; 
            background-color: #1e1e2f; 
            color: #dcdcdc; 
        }
        h1 { 
            color: #f0a500; 
            text-align: center;
            margin-bottom: 10px; 
        }
        /* New styling for total Unrealized P&L */
        #total-unrealized-pnl {
            font-size: 16px; 
            margin-bottom: 20px; 
            text-align: center;
            color: #f0a500;
        }
        .filter-container {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            margin-bottom: 10px;
        }
        .filter-container select {
            padding: 5px;
            background-color: #2a2a3c;
            color: #dcdcdc;
            border: 1px solid #33334d;
            border-radius: 5px;
            font-size: 14px;
            margin-top: 5px;
            margin-bottom: 10px;
        }
        .summary {
            margin-top: 10px;
            font-size: 14px;
            line-height: 1.6;
        }
        .profit-positive { 
            color: #4caf50; /* Green for positive profit */
        }
        .profit-negative { 
            color: #e74c3c; /* Red for negative profit */
        }
        /* Hide the summary table by default */
        #summary-table-container {
            display: none;
        }
        /* Styling for the summary table */
        #summary-table {
            width: 100%; 
            border-collapse: collapse; 
            margin-top: 20px; 
            background-color: #2a2a3c;
            border-radius: 8px;
            overflow: hidden;
        }
        table { 
            width: 100%; 
            border-collapse: collapse; 
            margin-top: 20px; 
            background-color: #2a2a3c;
            border-radius: 8px; 
            overflow: hidden;
        }
        th, td { 
            padding: 12px 15px; 
            text-align: left; 
            font-size: 14px;
        }
        th { 
            background-color: #33334d; 
            color: #f0a500; 
            font-weight: bold;
        }
        td { 
            border-bottom: 1px solid #444; 
        }
        tr:hover { 
            background-color: #3a3a4f; 
        }
        .status-open { 
            color: #4caf50; /* Green for open status */
            font-weight: bold;
        }
        .status-closed { 
            color: #e74c3c; /* Red for closed status */
            font-weight: bold;
        }

        .status-pending { 
            color: #ffa500; 
            font-weight: bold;
        }

        #entries-container {
            display: none;
            margin-top: 20px;
            color: #dcdcdc;
        }
        #entries-container h2 {
            color: #f0a500;
        }
        #entries-list {
            display: flex;
            justify-content: space-between;
            gap: 20px;
        }
        #entries-list div {
            width: 45%;
            padding: 10px;
            background-color: #2a2a3c;
            border-radius: 5px;
        }
        .channel-list {
            list-style-type: none;
            padding: 0;
            margin: 0;
        }
        .channel-list li {
            padding: 5px 0;
            border-bottom: 1px solid #444;
        }

        span#price-${transaction.id} {
    font-style: italic;
    color: #a5d6a7; /* Light green for price */
    margin-left: 5px;
}


        /* Hide the summary tables by default */
    #summary-table-container-daily,
    #summary-table-container-all {
        display: none; /* Hidden by default */
    }
    </style>
</head>
<body>
    <h1>Bybit Order Status Dashboard</h1>
    <!-- New Total Unrealized P&L(ROI) Display -->
    <div id="total-unrealized-pnl">
        Total Unrealized P&L(ROI): <span id="unrealized-pnl-value">N/A</span>
    </div>
    
    <div class="filter-container">
        <label for="channel-filter">Channel:</label>
        <select id="channel-filter" onchange="fetchTransactionData()">
            <option value="all">All Channels</option>
            <option value="-1002129889353">Test Richard</option>
            <option value="-1001903052876">Aish Crypto</option>
            <option value="-1001760828529">Always Win Trades</option>
            <option value="-1001622651246">Binance Pumps</option>
            <option value="-1001660926818">Bitcoin Boom Signals</option>
            <option value="-1001756316676">Boom Boom Billionaires</option>
            <option value="-1001982472141">Crypto Beast</option>
            <option value="-1001703983152">Crypto Beast VIP</option>
            <option value="-1001862208549">Crypto Bullets 2.0</option>
            <option value="-1001700533698">Crypto Bulls</option>
            <option value="-1001446149432">Crypto CLUB</option>
            <option value="-1001598691683">Crypto Devil Private</option>
            <option value="-1001302965247">Crypto Ease</option>
            <option value="-1001784672307">Crypto Indicator HarmonicTeam</option>
            <option value="-1001783301467">Crypto Safe Calls</option>
            <option value="-1001884208468">Crypto Signal 🇧🇩</option>
            <option value="-1001966506182">Crypto Vip Signals Club</option>
            <option value="-1002052872813">CRYPTO LEOPARD</option>
            <option value="-1001656921849">ESTR</option>
            <option value="-1001175262142">GGShot Indicator</option>
            <option value="-1002083609143">LFD Crypto</option>
            <option value="-1001834171116">Market Owners</option>
            <option value="-1002007658025">The Wolf Crypto</option>
            <option value="-1001786419872">Ulysse</option>
            <option value="-1001446149432">VIP CLUB</option>
            <option value="-1001775729912">VIP For LifeTime</option>
            <option value="-1001700314832">Whales Circle</option>
            <option value="-1001340073215">Whales Crypto Trading Coach</option>
            <option value="-1001594522150">Whales Pumps</option>
            <option value="-1001394941879">Wolfx Signals Vip</option>

          

        </select>
        
        
        <div id="account-info">
            <div>
                <p>Account Balance: <span id="account-balance">N/A</span></p>
                <p>Account Balance: <span id="account-equity">N/A</span></p>
                <p>Total Initial Margin: <span id="account-initial-margin">N/A</span></p>
                <p>Total Maintenance Margin: <span id="account-maintenance-margin">N/A</span></p>
            </div>
        </div>
    </div>

  <!--  <div id="channel-summary-container">
    <h2>Channel Profits Summary</h2>
    <ul id="channel-summary-list"></ul>
</div> -->


<div>
        <h2>All Profit</h2>
    <table id="all-profit-table">
        <thead>
            <tr>
                <th>Week Range</th>
                <th>Monday</th>
                <th>Tuesday</th>
                <th>Wednesday</th>
                <th>Thursday</th>
                <th>Friday</th>
                <th>Saturday</th>
                <th>Sunday</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <!-- Rows will be added dynamically -->
        </tbody>
    </table>
</div><br>

<!-- Add Pending Orders Button -->
<div id="toggle-buttons">
    <button class="toggle-button" onclick="showMainTable()">Show All Trades</button>
    <button class="toggle-button" onclick="showActiveOrders()">Active Orders</button>
    <button class="toggle-button" onclick="showPendingOrders()">Pending Orders</button> 
    <button class="toggle-button" onclick="showStopLossOrders()">StopLoss Orders</button> 
    <button class="toggle-button" onclick="showLastUpdated()">Last Updated</button>
    <button class="toggle-button" onclick="showSummaryTable('daily')">Show Daily Resume</button>
    <button class="toggle-button" onclick="showSummaryTable('all')">Show All Resume</button>
    <button class="toggle-button" onclick="showEntries()">Entries</button>
    <button class="toggle-button" onclick="showTotalInitial()">Show Total Initial Margin</button>



</div>

    <div class="center" id="main-table-container">
        <table id="transaction-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Channel ID</th>
                    <th>Symbol</th>
                    <th>Side</th>
                    <th>Leverage</th>
                    <th>Entry Price</th>
                    <th>Stop Loss</th>
                    <th>Quantity</th>
                    <th>Status</th>
                    <th>Close Status</th>
                    <th>Unrealized P&L(ROI)</th>
                    <th>Profit</th>
                    <th>TP1</th>
                    <th>TP1 Profit</th>
                    <th>TP1 Hit</th> 
                    <th>TP2</th>
                    <th>TP2 Profit</th>
                    <th>TP2 Hit</th> 
                    <th>Created At</th>
                    <th>Filled At</th>
                    <th>Closed Time</th> <!-- New Closed Time Column -->
                </tr>
            </thead>
            <tbody>
                <!-- Rows will be added here dynamically -->
            </tbody>
        </table>
    </div>

   
    <!-- Daily Summary Table Container -->
    <div id="summary-table-container-daily">
        <h2>Last 24 Hours Summary</h2>
        <table id="summary-table-daily">
            <thead>
                <tr>
                    <th>Channel ID</th>
                    <th>Profit</th>
                    <th>Total Trades</th>
                    <th>TP1 Profit</th>
                    <th>TP2 Profit</th>
                    <th>TP1 Hit</th>
                    <th>TP2 Hit</th>
                    <th>Stoploss Profit</th>
                    <th>Stoploss Hit</th>
                </tr>
            </thead>
            <tbody>
                <!-- Rows will be added dynamically -->
            </tbody>
        </table>
    </div>


    <!-- All Data Summary Table Container -->
<div id="summary-table-container-all">
    <h2>All Data Summary</h2>
    <table id="summary-table-all">
        <thead>
            <tr>
                <th>Channel ID</th>
                <th>Profit</th>
                <th>Total Trades</th>
                <th>TP1 Profit</th>
                <th>TP2 Profit</th>
                <th>TP1 Hit</th>
                <th>TP2 Hit</th>
                <th>Stoploss Profit</th>
                <th>Stoploss Hit</th>
                <th>Actions</th> <!-- New column for Show/Hide button -->
            </tr>
        </thead>
        <tbody>
            <!-- Rows will be dynamically generated -->
        </tbody>
    </table>
</div>


        <!-- Container to show entries lists -->
    <div id="entries-container">
        <h2>Channel Entries in the Last 24 Hours</h2>
        <div id="entries-list">
            <div>
                <h3>Channels with Trades</h3>
                <ul id="channels-with-entries" class="channel-list"></ul>
            </div>
            <div>
                <h3>Channels without Trades</h3>
                <ul id="channels-without-entries" class="channel-list"></ul>
            </div>
        </div>
    </div>


    <div id="total-initial-container" style="display:none; margin-top:20px;">
    <h2>Highest Total Initial Margin (Last 24 Hours)</h2>
    <table id="total-initial-table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Highest Total Initial Margin</th>
            </tr>
        </thead>
        <tbody>
            <!-- Rows will be added dynamically -->
        </tbody>
    </table>
</div>

<script>
        let transactionCellMap = {}; // Global map to store cell references

          function getChannelName(channel_id) {
        return {
            '-1002129889353': 'Test Richard',
            '-1001760828529': 'Always Win Trades',
            '-1001446149432': 'VIP CLUB',
            '-1001622651246': 'Binance Pumps',
            '-1001394941879': 'Wolfx Signals Vip',
            '-1002007658025': 'The Wolf Crypto',
            '-1001700314832': 'Whales Circle',
            '-1001903052876': 'Aish Crypto',
            '-1001756316676': 'Boom Boom Billionaires',
            '-1001784672307': 'Crypto Indicator HarmonicTeam',
            '-1001594522150': 'Whales Pumps',
            '-1001783301467': 'Crypto Safe Calls',
            '-1001656921849': 'ESTR',
            '-1001982472141': 'Crypto Beast',
            '-1001703983152': 'Crypto Beast VIP',
            '-1002083609143': 'LFD Crypto',
            '-1001175262142': 'GGShot Indicator',
            '-1001834171116': 'Market Owners',
            '-1002052872813': 'CRYPTO LEOPARD',
            '-1001660926818': 'Bitcoin Boom Signals',
            '-1001598691683': 'Crypto Devil Private',
            '-1001700533698': 'Crypto Bulls',
            '-1001862208549': 'Crypto Bullets 2.0',
            '-1001884208468': 'Crypto Signal 🇧🇩',
            '-1001302965247': 'Crypto Ease',
            '-1001340073215': 'Whales Crypto Trading Coach',
            '-1001786419872': 'Ulysse',
            '-1001775729912': 'VIP For LifeTime',

            '-1001966506182': 'Crypto Vip Signals Club'
            

        }[channel_id] || channel_id; // Default to channel_id if not found
    }

const REFRESH_INTERVAL = 1000; // Refresh every 1000ms (1 seconds)

async function fetchTransactionData(updateButtonsOnly = false) {
    try {
        const response = await fetch('/data');
        const data = await response.json();

        // Update buttons
        updateAllTradesButton(data);
        updateActiveOrdersButton(data);
        updatePendingOrdersButton(data);
        updateStopLossOrdersButton(data);

        if (!updateButtonsOnly) {
            // Render the main table and update Unrealized P&L
            renderTable(data);
            updateUnrealizedPnL(data);
        }
    } catch (error) {
        console.error("Error fetching transaction data:", error);
    }
}

// Example: Call with `true` to only update buttons
setInterval(() => fetchTransactionData(true), REFRESH_INTERVAL);


function updateAllTradesButton(data) {
    const allTradesButton = document.querySelector('button[onclick="showMainTable()"]');
    allTradesButton.textContent = `${data.length} All Trades`;
}

function updateActiveOrdersButton(data) {
    const activeOrdersButton = document.querySelector('button[onclick="showActiveOrders()"]');
    const activeOrders = data.filter(transaction => 
        transaction.status === 'Filled' && 
        transaction.close_status.toLowerCase() === 'open'
    );
    activeOrdersButton.textContent = `${activeOrders.length} Active Orders`;
}

function updatePendingOrdersButton(data) {
    const pendingOrdersButton = document.querySelector('button[onclick="showPendingOrders()"]');
    const pendingOrders = data.filter(transaction => 
        transaction.status.toLowerCase() === 'pending'
    );
    pendingOrdersButton.textContent = `${pendingOrders.length} Pending Orders`;
}

function updateStopLossOrdersButton(data) {
    const stopLossOrdersButton = document.querySelector('button[onclick="showStopLossOrders()"]');
    const stopLossOrders = data.filter(transaction => 
        transaction.close_status.toLowerCase() === 'closed' &&
        parseFloat(transaction.profit) < 0
    );
    stopLossOrdersButton.textContent = `${stopLossOrders.length} StopLoss Orders`;
}


    function showPendingOrders() {
    const mainContainer = document.getElementById('main-table-container');
    const dailyContainer = document.getElementById('summary-table-container-daily');
    const allContainer = document.getElementById('summary-table-container-all');
    const entriesContainer = document.getElementById('entries-container');

    // Hide other sections and show the main table
    dailyContainer.style.display = 'none';
    allContainer.style.display = 'none';
    entriesContainer.style.display = 'none';
    mainContainer.style.display = 'block';

    // Fetch the transaction data and filter for pending orders
    fetch('/data')
        .then(response => response.json())
        .then(data => {
            // Filter data for pending orders (status is "Pending")
            const pendingOrders = data.filter(transaction => 
                transaction.status.toLowerCase() === 'pending'
            );

            // Render the table with pending orders
            renderTable(pendingOrders);
        })
        .catch(error => {
            console.error("Error fetching transaction data for Pending Orders:", error);
        });
}

function showStopLossOrders() {
    const mainContainer = document.getElementById('main-table-container');
    const dailyContainer = document.getElementById('summary-table-container-daily');
    const allContainer = document.getElementById('summary-table-container-all');
    const entriesContainer = document.getElementById('entries-container');

    // Hide other sections and show the main table
    dailyContainer.style.display = 'none';
    allContainer.style.display = 'none';
    entriesContainer.style.display = 'none';
    mainContainer.style.display = 'block';

    // Fetch the transaction data and filter for StopLoss orders
    fetch('/data')
        .then(response => response.json())
        .then(data => {
            // Filter data for StopLoss orders (close_status is "Closed" and profit is negative)
            const stopLossOrders = data.filter(transaction => 
                transaction.close_status.toLowerCase() === 'closed' &&
                parseFloat(transaction.profit) < 0
            );

            // Render the table with StopLoss orders and use the "stoploss" context
            renderTable(stopLossOrders, 'stoploss');
        })
        .catch(error => {
            console.error("Error fetching transaction data for StopLoss Orders:", error);
        });
}





 function showActiveOrders() {
    const mainContainer = document.getElementById('main-table-container');
    const dailyContainer = document.getElementById('summary-table-container-daily');
    const allContainer = document.getElementById('summary-table-container-all');
    const entriesContainer = document.getElementById('entries-container');
    const activeOrdersButton = document.querySelector('button[onclick="showActiveOrders()"]');

    // Hide other sections and show the main table
    dailyContainer.style.display = 'none';
    allContainer.style.display = 'none';
    entriesContainer.style.display = 'none';
    mainContainer.style.display = 'block';

    // Fetch the transaction data and filter for active orders
    fetch('/data')
        .then(response => response.json())
        .then(data => {
            // Filter data for active orders (status is "Filled" and close_status is "Open")
            const activeOrders = data.filter(transaction => 
                transaction.status === 'Filled' && 
                transaction.close_status.toLowerCase() === 'open'
            );

            // Update the button text with the number of active orders
            activeOrdersButton.textContent = `${activeOrders.length} Active Orders`;

            // Render the table with active orders
            renderTable(activeOrders);
        })
        .catch(error => {
            console.error("Error fetching transaction data for Active Orders:", error);
        });
}



function renderTable(data, context = '') {
    const tbody = document.getElementById('transaction-table').querySelector('tbody');
    tbody.innerHTML = ''; // Clear the existing rows
    transactionCellMap = {}; // Clear the previous cell map

    // Filter data based on selected channel
    const selectedChannel = document.getElementById('channel-filter').value;
    const filteredData = selectedChannel === 'all'
        ? data
        : data.filter(transaction => transaction.channel_id === selectedChannel);

    // Sort logic based on context
    if (context === 'stoploss') {
        // Sort by Closed Time in descending order (newest first)
        filteredData.sort((a, b) => new Date(b.closed_time) - new Date(a.closed_time));
    } else if (context === 'lastUpdated') {
        // Sort by the latest update (TP1 hit, TP2 hit, or Closed Time)
        filteredData.sort((a, b) => {
            const parseDate = dateStr => dateStr ? new Date(dateStr.replace(' ', 'T')).getTime() : 0;

            const getLatestUpdate = transaction => {
                const tp1Hit = parseDate(transaction.take_profit_1_hit);
                const tp2Hit = parseDate(transaction.take_profit_2_hit);
                const closedTime = parseDate(transaction.closed_time);
                return Math.max(tp1Hit, tp2Hit, closedTime); // Get the latest timestamp
            };

            return getLatestUpdate(b) - getLatestUpdate(a); // Sort descending (newest first)
        });
    } else {
        // Default: Sort by Created At in descending order (most recent first)
        filteredData.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
    }

    let totalProfit = 0, totalTP1Profit = 0, totalTP2Profit = 0;
    let tp1Count = 0, tp2Count = 0;
    let stoplossHitCount = 0; // Initialize Stoploss Hit counter

    for (const transaction of filteredData) {
        // Define variables for profits and TP hits
        const profit = parseFloat(transaction.profit) || 0;
        const tp1Profit = parseFloat(transaction.take_profit_1_profit) || 0;
        const tp2Profit = parseFloat(transaction.take_profit_2_profit) || 0;

        // Format dates to "YYYY-MM-DD HH:MM:SS" with -3 hours adjustment
        const formatDate = (dateStr) => {
            const date = new Date(dateStr);
            date.setHours(date.getHours() - 3); // Subtract 3 hours
            return date.toLocaleString('en-CA', { timeZone: 'America/New_York', hour12: false })
                .replace(',', ''); // Remove comma between date and time
        };

        const formatDate2 = (dateStr) => {
            const date = new Date(dateStr);
            date.setHours(date.getHours()); // No adjustment
            return date.toLocaleString('en-CA', { timeZone: 'America/New_York', hour12: false })
                .replace(',', ''); // Remove comma between date and time
        };

        const formatDateClose = (dateStr) => {
            const date = new Date(dateStr);
            date.setHours(date.getHours() - 3); // Subtract 3 hours
            return date.toLocaleString('en-CA', { timeZone: 'America/New_York', hour12: false })
                .replace(',', ''); // Remove comma between date and time
        };

        const tp1Hit = transaction.take_profit_1_hit ? formatDate(transaction.take_profit_1_hit) : "N/A";
        const tp2Hit = transaction.take_profit_2_hit ? formatDate(transaction.take_profit_2_hit) : "N/A";

        // Convert created_at and closed_time to the specified timezone (America/New_York)
        const formattedCreatedAt = formatDate2(transaction.created_at);
        const formattedFilledAt = transaction.filled_time ? formatDateClose(transaction.filled_time) : "N/A";
        const formattedClosedTime = transaction.closed_time ? formatDateClose(transaction.closed_time) : "N/A";

        totalProfit += profit;
        totalTP1Profit += tp1Profit;
        totalTP2Profit += tp2Profit;

        if (tp1Profit !== 0) tp1Count++;
        if (tp2Profit !== 0) tp2Count++;

        // Calculate Stoploss Hit if closed time is before TP1 hit or if TP1 hit is "N/A"
        if (transaction.stop_loss_hit = '1' ) {
            stoplossHitCount++;
        }

        const channelName = getChannelName(transaction.channel_id);

        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${transaction.id}</td>
            <td>${channelName || ''}</td>
            <td>${transaction.symbol}</td>
            <td>${transaction.side}</td>
            <td>${transaction.leverage}</td>
            <td>${transaction.entry_price}</td>
            <td>${parseFloat(transaction.stop_loss).toFixed(4)}</td>
            <td>${parseFloat(transaction.quantity).toFixed(0)}</td>
            <td class="${
                transaction.status.toLowerCase() === 'pending' ? 'status-pending' :
                    transaction.status.toLowerCase() === 'filled' ? 'status-open' : ''
            }">${transaction.status}</td>
            <td class="${
                transaction.close_status.toLowerCase() === 'closed' ? 'status-closed' : 'status-open'
            }">${transaction.close_status}</td>
            <td id="unrealized-${transaction.id}">N/A</td>
            <td class="${profit > 0 ? 'profit-positive' : 'profit-negative'}">${profit.toFixed(2)}</td>
            <td>${transaction.take_profit_1}</td>
            <td class="${tp1Profit > 0 ? 'profit-positive' : tp1Profit < 0 ? 'profit-negative' : ''}">
                ${!isNaN(tp1Profit) ? tp1Profit.toFixed(2) : 'N/A'}
            </td>
            <td>${tp1Hit}</td>
            <td>${transaction.take_profit_2}</td>
            <td class="${tp2Profit > 0 ? 'profit-positive' : tp2Profit < 0 ? 'profit-negative' : ''}">
                ${!isNaN(tp2Profit) ? tp2Profit.toFixed(2) : 'N/A'}
            </td>
            <td>${tp2Hit}</td>
            <td>${formattedCreatedAt}</td>
            <td>${formattedFilledAt}</td>
            <td>${formattedClosedTime}</td>
        `;

        tbody.appendChild(row);

        // Store a reference to the Unrealized P&L cell
        const unrealizedCell = document.getElementById(`unrealized-${transaction.id}`);
        transactionCellMap[transaction.id] = {
            cell: unrealizedCell,
            transaction: transaction
        };
    }

    // Update Stoploss Hit count in the summary
    document.getElementById('stoploss-hit-count').textContent = stoplossHitCount;

    // Calculate TP hit percentages
    const totalEntries = filteredData.length;
    const tp1Percentage = totalEntries > 0 ? (tp1Count / totalEntries) * 100 : 0;
    const tp2Percentage = totalEntries > 0 ? (tp2Count / totalEntries) * 100 : 0;

    console.log('Take-Profit Hit Percentages:', {
        tp1Percentage,
        tp2Percentage
    });

    // Update summary
    document.getElementById('total-profit').textContent = totalProfit.toFixed(8);
    document.getElementById('total-tp1-profit').textContent = totalTP1Profit.toFixed(8);
    document.getElementById('tp1-percentage').textContent = `(${tp1Percentage.toFixed(2)}%)`;
    document.getElementById('total-tp2-profit').textContent = totalTP2Profit.toFixed(8);
    document.getElementById('tp2-percentage').textContent = `(${tp2Percentage.toFixed(2)}%)`;
}


async function updateUnrealizedPnL(data) {
    const selectedChannel = document.getElementById('channel-filter').value;
    const filteredData = selectedChannel === 'all'
        ? data
        : data.filter(transaction => transaction.channel_id === selectedChannel);

    const symbols = [...new Set(filteredData.map(t => t.symbol))];
    const bybitAPIUrl = `https://api.bybit.com/v5/market/tickers?category=linear`;

    let priceMap = {};
    try {
        const response = await fetch(bybitAPIUrl);
        const priceData = await response.json();

        if (priceData.retCode !== 0) {
            console.error("Bybit API error:", priceData.retMsg);
        } else {
            priceData.result.list.forEach(item => {
                priceMap[item.symbol] = parseFloat(item.lastPrice);
            });
        }

    } catch (error) {
        console.error("Error fetching price data from Bybit:", error);
    }

    let totalUnrealizedPnLValue = 0;
    let totalCost = 0;

for (const transaction of filteredData) {
    const unrealizedCell = transactionCellMap[transaction.id]?.cell;
    if (!unrealizedCell) continue;

    const priceCellId = `price-${transaction.id}`;
    let priceCell = document.getElementById(priceCellId);
    if (!priceCell) {
        priceCell = document.createElement('span');
        priceCell.id = priceCellId;
        unrealizedCell.appendChild(priceCell);
    }

    const isFilledAndOpen = transaction.status === 'Filled' && transaction.close_status.toLowerCase() === 'open';

    let unrealizedPnLText = 'N/A'; // Declare and initialize unrealizedPnLText here

    if (!isFilledAndOpen) {
        unrealizedCell.textContent = unrealizedPnLText + ' (Price: N/A)';
        continue;
    }

    const entryPrice = parseFloat(transaction.entry_price) || 0;
    const quantity = parseFloat(transaction.quantity) || 0;
    let adjustedQty = quantity;

    for (let i = 1; i <= 4; i++) {
        if (transaction[`take_profit_${i}_filled`] == 1) {
            adjustedQty -= parseFloat(transaction[`take_profit_${i}_fill_qty`] || 0);
        }
    }

    const currentPrice = priceMap[transaction.symbol.toUpperCase()];

    if (!currentPrice) {
        console.warn(`Price not found for symbol: ${transaction.symbol}`);
        unrealizedCell.textContent = unrealizedPnLText + ' (Price: N/A)';
    } else {
        let unrealizedPnL = 0;
        if (transaction.side.toLowerCase() === 'sell') {
            unrealizedPnL = (entryPrice - currentPrice) * adjustedQty;
        } else {
            unrealizedPnL = (currentPrice - entryPrice) * adjustedQty;
        }

        const cost = entryPrice * adjustedQty;
        const roi = cost ? (unrealizedPnL / cost) * 100 : 0;

        unrealizedPnLText = `${unrealizedPnL.toFixed(2)} (${roi.toFixed(2)}%)`;

        // Include current price in the Unrealized P&L cell
        unrealizedCell.textContent = `${unrealizedPnLText} (${currentPrice.toFixed(4)})`;

        totalUnrealizedPnLValue += unrealizedPnL;
        totalCost += cost;

    }

    unrealizedCell.offsetHeight; // Force reflow
}



    const totalROI = totalCost ? (totalUnrealizedPnLValue / totalCost) * 100 : 0;

    document.getElementById('unrealized-pnl-value').textContent = `
        ${totalUnrealizedPnLValue.toFixed(2)} (${totalROI.toFixed(2)}%)
    `;
}


    async function updateDailySummary() {
        const response = await fetch('/data');
        const data = await response.json();

        // Filter data for the last 24 hours
        const oneDayAgo = new Date();
        oneDayAgo.setHours(oneDayAgo.getHours() - 24);
        const filteredData = data.filter(transaction => new Date(transaction.closed_time) >= oneDayAgo);

        updateSummary(filteredData);
    }

    async function updateAllSummary() {
        const response = await fetch('/data');
        const data = await response.json();

        updateSummary(data);
    }

    function updateSummary(data) {
        let totalProfit = 0;
        let totalTP1Profit = 0, totalTP2Profit = 0;
        let tp1Count = 0, tp2Count = 0;
        let stoplossHitCount = 0;

        data.forEach(transaction => {
            const profit = parseFloat(transaction.profit) || 0;
            totalProfit += profit;

            const tpProfits = [
                parseFloat(transaction.take_profit_1_profit) || 0,
                parseFloat(transaction.take_profit_2_profit) || 0
            ];

            totalTP1Profit += tpProfits[0]; if (tpProfits[0] !== 0) tp1Count++;
            totalTP2Profit += tpProfits[1]; if (tpProfits[1] !== 0) tp2Count++;

            if (transaction.stop_loss_hit = '1') {
                stoplossHitCount++;
            }
        });

        const totalEntries = data.length;
        const tp1Percentage = totalEntries > 0 ? (tp1Count / totalEntries) * 100 : 0;
        const tp2Percentage = totalEntries > 0 ? (tp2Count / totalEntries) * 100 : 0;

        // Update the summary section
        document.getElementById('total-profit').textContent = totalProfit.toFixed(2);
        document.getElementById('total-tp1-profit').textContent = totalTP1Profit.toFixed(2);
        document.getElementById('tp1-percentage').textContent = `(${tp1Percentage.toFixed(2)}%)`;
        document.getElementById('total-tp2-profit').textContent = totalTP2Profit.toFixed(2);
        document.getElementById('tp2-percentage').textContent = `(${tp2Percentage.toFixed(2)}%)`;
        document.getElementById('stoploss-hit-count').textContent = stoplossHitCount;
    }

    function showSummaryTable(type) {
        const mainContainer = document.getElementById('main-table-container');
        const dailyContainer = document.getElementById('summary-table-container-daily');
        const allContainer = document.getElementById('summary-table-container-all');

        if (type === 'daily') {
            mainContainer.style.display = 'none';
            dailyContainer.style.display = 'block';
            allContainer.style.display = 'none';
            renderDailySummaryTable();
            updateDailySummary(); // Update summary for last 24 hours
        } else if (type === 'all') {
            mainContainer.style.display = 'none';
            dailyContainer.style.display = 'none';
            allContainer.style.display = 'block';
            renderAllSummaryTable();
            updateAllSummary(); // Update summary for all data
        }
    }

     // Function to show channels based on recent trades
    async function showEntries() {
        const entriesContainer = document.getElementById('entries-container');
        const channelsWithEntries = document.getElementById('channels-with-entries');
        const channelsWithoutEntries = document.getElementById('channels-without-entries');

        // Show entries container and hide other sections
        document.getElementById('main-table-container').style.display = 'none';
        document.getElementById('summary-table-container-daily').style.display = 'none';
        document.getElementById('summary-table-container-all').style.display = 'none';
        entriesContainer.style.display = 'block';

        // Fetch data and determine entries
        const response = await fetch('/data');
        const data = await response.json();

        const oneDayAgo = new Date();
        oneDayAgo.setHours(oneDayAgo.getHours() - 24);

        const channelNames = {
           '-1002129889353': 'Test Richard',
            '-1001760828529': 'Always Win Trades',
            '-1001446149432': 'VIP CLUB',
            '-1001622651246': 'Binance Pumps',
            '-1001394941879': 'Wolfx Signals Vip',
            '-1002007658025': 'The Wolf Crypto',
            '-1001700314832': 'Whales Circle',
            '-1001903052876': 'Aish Crypto',
            '-1001756316676': 'Boom Boom Billionaires',
            '-1001784672307': 'Crypto Indicator HarmonicTeam',
            '-1001594522150': 'Whales Pumps',
            '-1001783301467': 'Crypto Safe Calls',
            '-1001656921849': 'ESTR',
            '-1001982472141': 'Crypto Beast',
            '-1001703983152': 'Crypto Beast VIP',
            
            '-1002083609143': 'LFD Crypto',
            '-1001175262142': 'GGShot Indicator',
            '-1001834171116': 'Market Owners',
            '-1002052872813': 'CRYPTO LEOPARD',
            '-1001660926818': 'Bitcoin Boom Signals',
            '-1001598691683': 'Crypto Devil Private',
            '-1001700533698': 'Crypto Bulls',
            '-1001862208549': 'Crypto Bullets 2.0',
            '-1001884208468': 'Crypto Signal 🇧🇩',
            '-1001302965247': 'Crypto Ease',
            '-1001340073215': 'Whales Crypto Trading Coach',
            '-1001786419872': 'Ulysse',
            '-1001775729912': 'VIP For LifeTime',

            '-1001966506182': 'Crypto Vip Signals Club'
        };

        const recentChannels = new Set(data
            .filter(transaction => new Date(transaction.created_at) >= oneDayAgo)
            .map(transaction => transaction.channel_id)
        );

        const allChannels = Object.keys(channelNames);
        const channelsWithTrades = [];
        const channelsWithoutTrades = [];

        allChannels.forEach(channelID => {
            if (recentChannels.has(channelID)) {
                channelsWithTrades.push(channelNames[channelID]);
            } else {
                channelsWithoutTrades.push(channelNames[channelID]);
            }
        });

        // Populate the lists
        channelsWithEntries.innerHTML = channelsWithTrades.map(name => `<li>${name}</li>`).join('');
        channelsWithoutEntries.innerHTML = channelsWithoutTrades.map(name => `<li>${name}</li>`).join('');
    }

    // Function to hide entries and show the main table
    function showMainTable() {
    const mainContainer = document.getElementById('main-table-container');
    const dailyContainer = document.getElementById('summary-table-container-daily');
    const allContainer = document.getElementById('summary-table-container-all');
    const entriesContainer = document.getElementById('entries-container');

    // Hide other sections and show the main table
    dailyContainer.style.display = 'none';
    allContainer.style.display = 'none';
    entriesContainer.style.display = 'none';
    mainContainer.style.display = 'block';

    // Fetch the transaction data and render the full table (remove any filters)
    fetchTransactionData();
}


async function renderDailySummaryTable() {
    const response = await fetch('/data');
    const data = await response.json();

    // Group data by date (based on closed_time)
    const groupedData = {};
    data.forEach(transaction => {
        if (!transaction.closed_time || isNaN(new Date(transaction.closed_time))) {
            return; // Skip invalid dates
        }

        // Extract the date from closed_time
        const closedDate = new Date(transaction.closed_time);
        closedDate.setHours(0, 0, 0, 0); // Normalize to midnight
        const dateKey = closedDate.toISOString().split('T')[0]; // Use YYYY-MM-DD format

        // Initialize group if it doesn't exist
        if (!groupedData[dateKey]) {
            groupedData[dateKey] = [];
        }

        // Add transaction to the corresponding group
        groupedData[dateKey].push(transaction);
    });

    // Clear the existing table body
    const tbody = document.getElementById('summary-table-daily').querySelector('tbody');
    tbody.innerHTML = '';

    // Sort dates in descending order (newest first)
    const sortedDates = Object.keys(groupedData).sort((a, b) => new Date(b) - new Date(a));

    // Loop through grouped data and populate the table
    sortedDates.forEach(date => {
        const transactions = groupedData[date];

        // Aggregate data for the date
        let totalProfit = 0;
        let totalTP1Profit = 0, totalTP2Profit = 0;
        let tp1Count = 0, tp2Count = 0;
        let stoplossHitCount = 0;
        let stoplossProfit = 0;

        transactions.forEach(transaction => {
            const profit = parseFloat(transaction.profit) || 0;
            totalProfit += profit;

            const tpProfits = [
                parseFloat(transaction.take_profit_1_profit) || 0,
                parseFloat(transaction.take_profit_2_profit) || 0
            ];

            totalTP1Profit += tpProfits[0];
            if (tpProfits[0] !== 0) tp1Count++;

            totalTP2Profit += tpProfits[1];
            if (tpProfits[1] !== 0) tp2Count++;

            if (transaction.stop_loss_hit === 1) {
                stoplossHitCount++;
                stoplossProfit += profit; // Add profit from Stoploss transactions
            }
        });

        // Calculate percentages
        const totalEntries = transactions.length;
        const tp1Percentage = totalEntries > 0 ? (tp1Count / totalEntries) * 100 : 0;
        const tp2Percentage = totalEntries > 0 ? (tp2Count / totalEntries) * 100 : 0;

        // Create a new row for the date
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${date}</td>
            <td>${totalProfit.toFixed(2)}</td>
            <td>${totalEntries}</td>
            <td>${totalTP1Profit.toFixed(2)}</td>
            <td>${totalTP2Profit.toFixed(2)}</td>
            <td>${tp1Count} (${tp1Percentage.toFixed(2)}%)</td>
            <td>${tp2Count} (${tp2Percentage.toFixed(2)}%)</td>
            <td>${stoplossProfit.toFixed(2)}</td>
            <td>${stoplossHitCount}</td>
        `;
        tbody.appendChild(row);
    });
}


async function renderAllSummaryTable() {
    const response = await fetch('/data');
    const data = await response.json();

    const filteredData = data.filter(transaction => {
        const closedTime = new Date(transaction.closed_time);
        return !isNaN(closedTime); // Only include transactions with valid closed_time
    });

    renderSummaryTable(filteredData, 'summary-table-all');
}

function renderSummaryTable(data, tableId) {
    const channelSummary = {};

    // Aggregate data by channel ID
    data.forEach(transaction => {
        const channelID = transaction.channel_id;
        const channelName = getChannelName(channelID); // Get the channel name
        const tpHits = [
            transaction.take_profit_1_hit ? 1 : 0,
            transaction.take_profit_2_hit ? 1 : 0
        ];

        if (!channelSummary[channelName]) {
            channelSummary[channelName] = {
                profit: 0,
                totalTrades: 0,
                tpProfits: [0, 0, 0, 0, 0, 0],
                tpHits: [0, 0, 0, 0, 0, 0],
                stoplossProfit: 0,
                stoplossHit: 0
            };
        }

        // Update totals
        const channel = channelSummary[channelName];
        channel.profit += parseFloat(transaction.profit || 0);
        // Increment totalTrades only if the transaction is not cancelled
if (transaction.status !== 'Cancelled') {
    channel.totalTrades += 1;
}
        channel.tpProfits = channel.tpProfits.map((tp, idx) => tp + parseFloat(transaction[`take_profit_${idx + 1}_profit`] || 0));
        channel.tpHits = channel.tpHits.map((hit, idx) => hit + tpHits[idx]);

        // Check stop loss condition
        // Check stop loss condition
        if (
            transaction.stop_loss_hit === 1 && // Check if stop_loss_hit equals 1 
            transaction.take_profit_1_filled === 0 // Check if stop_loss_hit equals 1
        ) {
            channel.stoplossHit += 1;
            channel.stoplossProfit += parseFloat(transaction.profit || 0);
        }

    });

    // Sort channels by profit in descending order
    const sortedChannels = Object.entries(channelSummary).sort((a, b) => b[1].profit - a[1].profit);

    const tbody = document.getElementById(tableId).querySelector('tbody');
    tbody.innerHTML = ''; // Clear existing rows

    // Populate summary table with aggregated and sorted data
    sortedChannels.forEach(([channelName, summary]) => {
        const row = document.createElement('tr');

        // Calculate hit percentages for each TP column
        const tpHitPercentages = summary.tpHits.map(hit => summary.totalTrades > 0 ? ((hit / summary.totalTrades) * 100).toFixed(2) : '0.00');

        row.innerHTML = `
            <td>${channelName}</td>
            <td>${summary.profit.toFixed(2)}</td>
            <td>${summary.totalTrades}</td>
            <td>${summary.tpProfits[0] !== 0 ? summary.tpProfits[0].toFixed(2) : 'N/A'}</td>
            <td>${summary.tpProfits[1] !== 0 ? summary.tpProfits[1].toFixed(2) : 'N/A'}</td>
            <td>${summary.tpHits[0]} (${tpHitPercentages[0]}%)</td>
            <td>${summary.tpHits[1]} (${tpHitPercentages[1]}%)</td>
            <td>${summary.stoplossProfit !== 0 ? summary.stoplossProfit.toFixed(2) : 'N/A'}</td>
            <td>${summary.stoplossHit}</td>
            <td>
                <button onclick="toggleChannelProfit('${channelName}')">Show/Hide Profit</button>
                <div id="profit-details-${channelName}" style="display: none; margin-top: 10px;"></div>
            </td>
        `;
        tbody.appendChild(row);
    });
}


async function renderAllProfitTable() {
    try {
        const response = await fetch('/data');
        const data = await response.json();

        const weeklyData = {};

        // Process all transactions to group by week
        data.forEach(transaction => {
            if (!transaction.closed_time || isNaN(new Date(transaction.closed_time))) {
                return;
            }

            const closedTime = new Date(transaction.closed_time);

            // Adjust closed time manually for timezone (if necessary)
            const offsetHours = -3; // Adjust for EST (example)
            const localClosedTime = new Date(closedTime.setHours(closedTime.getHours() + offsetHours));

            // Determine the Monday and Sunday of the transaction's week
            const dayOfWeek = localClosedTime.getDay(); // 0 = Sunday, ..., 6 = Saturday
            const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;

            const monday = new Date(localClosedTime);
            monday.setDate(localClosedTime.getDate() - daysFromMonday);
            monday.setHours(0, 0, 0, 0);

            const sunday = new Date(monday);
            sunday.setDate(monday.getDate() + 6);

            const weekRange = `${monday.toISOString().split('T')[0]} to ${sunday.toISOString().split('T')[0]}`;

            // Initialize weekly data if not already present
            if (!weeklyData[weekRange]) {
                weeklyData[weekRange] = {
                    Monday: 0,
                    Tuesday: 0,
                    Wednesday: 0,
                    Thursday: 0,
                    Friday: 0,
                    Saturday: 0,
                    Sunday: 0,
                    Total: 0
                };
            }

            // Map the transaction's day to the corresponding weekday
            const dayIndex = localClosedTime.getDay(); // 0 = Sunday, ..., 6 = Saturday
            const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
            const dayName = dayNames[dayIndex];

            const profit = parseFloat(transaction.profit) || 0;

            // Add the profit to the respective day and the total
            weeklyData[weekRange][dayName] += profit;
            weeklyData[weekRange].Total += profit;
        });

        // Ensure the current week exists
        const today = new Date();
        const dayOfWeek = today.getDay();
        const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;

        const currentMonday = new Date(today);
        currentMonday.setDate(today.getDate() - daysFromMonday);
        currentMonday.setHours(0, 0, 0, 0);

        const currentSunday = new Date(currentMonday);
        currentSunday.setDate(currentMonday.getDate() + 6);

        const currentWeekRange = `${currentMonday.toISOString().split('T')[0]} to ${currentSunday.toISOString().split('T')[0]}`;

        if (!weeklyData[currentWeekRange]) {
            weeklyData[currentWeekRange] = {
                Monday: 0,
                Tuesday: 0,
                Wednesday: 0,
                Thursday: 0,
                Friday: 0,
                Saturday: 0,
                Sunday: 0,
                Total: 0
            };
        }

        // Populate the "All Profit" table
        const tbody = document.getElementById('all-profit-table').querySelector('tbody');
        tbody.innerHTML = ''; // Clear existing rows

        Object.entries(weeklyData).forEach(([weekRange, days]) => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${weekRange}</td>
                ${['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Total']
                    .map(day => {
                        const value = days[day];
                        let color = 'grey';
                        if (value > 0) color = 'green';
                        else if (value < 0) color = 'red';
                        return `<td style="color: ${color}; font-weight: bold;">${value.toFixed(2)}</td>`;
                    })
                    .join('')}
            `;
            tbody.appendChild(row);
        });
    } catch (error) {
        console.error('Error in renderAllProfitTable:', error.message);
    }
}


    // Event to show the "All Profit" and "All Data Summary" tables
    function showAllProfit() {
        const allProfitContainer = document.getElementById('all-profit-container');
        const allSummaryContainer = document.getElementById('summary-table-container-all');

        allProfitContainer.style.display = 'block';
        allSummaryContainer.style.display = 'block';

        renderAllProfitTable(); // Render the All Profit table
        renderAllSummaryTable(); // Render the All Data Summary table
    }

    // Event to toggle visibility
    function toggleAllProfit() {
        const allProfitContainer = document.getElementById('all-profit-container');
        const isVisible = allProfitContainer.style.display === 'block';

        allProfitContainer.style.display = isVisible ? 'none' : 'block';
    }

    // Initialize the tables
    document.addEventListener('DOMContentLoaded', () => {
        renderAllProfitTable(); // Initial rendering of All Profit table
    });


async function toggleChannelProfit(channelName) {
    const profitRowId = `profit-row-${channelName}`;
    const existingRow = document.getElementById(profitRowId);

    if (existingRow) {
        // Toggle visibility if the row already exists
        existingRow.style.display = existingRow.style.display === 'none' ? 'table-row' : 'none';
        return;
    }

    // Fetch data for the selected channel
    const response = await fetch('/data');
    const data = await response.json();
    const channelData = data.filter(
        (transaction) => getChannelName(transaction.channel_id) === channelName
    );

    const weeklyData = {};

    // Process transactions for the channel, grouping by week
    channelData.forEach((transaction) => {
        const date = new Date(transaction.created_at);

        // Calculate the Monday and Sunday of the transaction's week
        const dayOfWeek = date.getDay();
        const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;

        const monday = new Date(date);
        monday.setDate(date.getDate() - daysFromMonday);
        monday.setHours(0, 0, 0, 0);

        const sunday = new Date(monday);
        sunday.setDate(monday.getDate() + 6);

        const weekRange = `${monday.toISOString().split('T')[0]} to ${sunday.toISOString().split('T')[0]}`;

        if (!weeklyData[weekRange]) {
            weeklyData[weekRange] = {
                Monday: 0,
                Tuesday: 0,
                Wednesday: 0,
                Thursday: 0,
                Friday: 0,
                Saturday: 0,
                Sunday: 0,
                Total: 0
            };
        }

        // Map the transaction's day to the corresponding weekday
        const dayName = date.toLocaleString('en-US', { weekday: 'long' });
        const profit = parseFloat(transaction.profit) || 0;

        // Add the profit to the respective day and the total
        weeklyData[weekRange][dayName] += profit;
        weeklyData[weekRange].Total += profit;
    });

    // Ensure the current week exists
    const today = new Date();
    const dayOfWeek = today.getDay();
    const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;

    const currentMonday = new Date(today);
    currentMonday.setDate(today.getDate() - daysFromMonday);
    currentMonday.setHours(0, 0, 0, 0);

    const currentSunday = new Date(currentMonday);
    currentSunday.setDate(currentMonday.getDate() + 6);

    const currentWeekRange = `${currentMonday.toISOString().split('T')[0]} to ${currentSunday.toISOString().split('T')[0]}`;

    if (!weeklyData[currentWeekRange]) {
        weeklyData[currentWeekRange] = {
            Monday: 0,
            Tuesday: 0,
            Wednesday: 0,
            Thursday: 0,
            Friday: 0,
            Saturday: 0,
            Sunday: 0,
            Total: 0
        };
    }

    // Generate the weekly profit table for the channel
    const tableHtml = `
      <table style="width: 100%; border-collapse: collapse; margin-top: 10px; background-color: #2a2a3c; color: #dcdcdc;">
        <thead>
          <tr>
            <th>Week Range</th>
            <th>Monday</th>
            <th>Tuesday</th>
            <th>Wednesday</th>
            <th>Thursday</th>
            <th>Friday</th>
            <th>Saturday</th>
            <th>Sunday</th>
            <th>Total</th>
          </tr>
        </thead>
        <tbody>
          ${Object.entries(weeklyData)
            .map(
                ([weekRange, days]) => `
            <tr>
              <td>${weekRange}</td>
              <td>${days.Monday.toFixed(2)}</td>
              <td>${days.Tuesday.toFixed(2)}</td>
              <td>${days.Wednesday.toFixed(2)}</td>
              <td>${days.Thursday.toFixed(2)}</td>
              <td>${days.Friday.toFixed(2)}</td>
              <td>${days.Saturday.toFixed(2)}</td>
              <td>${days.Sunday.toFixed(2)}</td>
              <td>${days.Total.toFixed(2)}</td>
            </tr>
          `
            )
            .join('')}
        </tbody>
      </table>
    `;

    // Find the table row corresponding to the channel
    const summaryTable = document.getElementById('summary-table-all').querySelector('tbody');
    const rows = Array.from(summaryTable.rows);
    const channelRow = rows.find((row) => row.cells[0].textContent === channelName);

    if (channelRow) {
        // Create a new row for the profit details
        const profitRow = document.createElement('tr');
        profitRow.id = profitRowId;
        profitRow.style.display = 'table-row';
        profitRow.innerHTML = `
          <td colspan="18">
            ${tableHtml}
          </td>
        `;
        // Insert the new row after the channel row
        channelRow.parentNode.insertBefore(profitRow, channelRow.nextSibling);
    }
}



async function fetchAccountData() {
    try {
        // Fetch account data from the backend
        const response = await fetch(`/account-data?t=${Date.now()}`, { cache: 'no-store' });
        const data = await response.json();

        // Parse the required values
        const balance = parseFloat(data.balance);
        const totalEquity = parseFloat(data.total_equity); // Same as balance
        const initialMargin = parseFloat(data.total_initial_margin); // Dynamic value
        const maintenanceMargin = parseFloat(data.total_maintenance_margin); // Dynamic value

        // Calculate percentages dynamically
        const initialMarginPercentage = totalEquity > 0 ? (initialMargin / totalEquity) * 100 : 0;
        const maintenanceMarginPercentage = totalEquity > 0 ? (maintenanceMargin / totalEquity) * 100 : 0;

        // Update DOM with the fetched values
        document.getElementById('account-balance').textContent = balance.toFixed(2);
        document.getElementById('account-equity').textContent = totalEquity.toFixed(2); // Same as balance
        document.getElementById('account-initial-margin').textContent = 
            `${initialMargin.toFixed(2)} (${initialMarginPercentage.toFixed(2)}%)`;
        document.getElementById('account-maintenance-margin').textContent = 
            `${maintenanceMargin.toFixed(2)} (${maintenanceMarginPercentage.toFixed(2)}%)`;

    } catch (error) {
        console.error('Error fetching account data:', error.message);
    }
}


async function showTotalInitial() {
    // Hide all other sections
    const sectionsToHide = document.querySelectorAll(
        '#main-table-container, #summary-table-container-daily, #summary-table-container-all, #entries-container'
    );
    sectionsToHide.forEach(section => (section.style.display = 'none'));

    // Show only the Total Initial Margin container
    const container = document.getElementById('total-initial-container');
    const tableBody = document.getElementById('total-initial-table').querySelector('tbody');

    // Clear existing rows
    tableBody.innerHTML = '';

    try {
        // Fetch all daily results
        const response = await fetch('/highest-total-initial');

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        if (!data || data.length === 0) {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td colspan="2">No data available.</td>
            `;
            tableBody.appendChild(row);
        } else {
            // Populate the table with all results
            data.forEach(entry => {
                const row = document.createElement('tr');

                // Format the date
                const formattedDate = new Date(entry.date).toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                });

                row.innerHTML = `
                    <td>${formattedDate}</td>
                    <td>${parseFloat(entry.highest_total).toFixed(2)}</td>
                `;
                tableBody.appendChild(row);
            });
        }

        // Show the container
        container.style.display = 'block';
    } catch (error) {
        console.error('Error fetching total initial margin data:', error);

        // Display an error message in the table
        const row = document.createElement('tr');
        row.innerHTML = `
            <td colspan="2">Error loading data. Please try again later.</td>
        `;
        tableBody.appendChild(row);
        container.style.display = 'block';
    }
}

function showLastUpdated() {
    const mainContainer = document.getElementById('main-table-container');
    const dailyContainer = document.getElementById('summary-table-container-daily');
    const allContainer = document.getElementById('summary-table-container-all');
    const entriesContainer = document.getElementById('entries-container');

    // Hide other sections and show the main table
    dailyContainer.style.display = 'none';
    allContainer.style.display = 'none';
    entriesContainer.style.display = 'none';
    mainContainer.style.display = 'block';

    // Fetch the transaction data and sort by the most recent update
    fetch('/data')
        .then(response => response.json())
        .then(data => {
            if (!data || !Array.isArray(data)) {
                console.error("Invalid data format received.");
                return;
            }

            // Render the table with the last updated context
            renderTable(data, 'lastUpdated');
        })
        .catch(error => {
            console.error("Error fetching transaction data for Last Updated:", error);
        });
}

async function updateChannelSummary() {
    try {
        const response = await fetch('/data');
        const data = await response.json();

        // Aggregate profits per channel
        const channelProfits = data.reduce((acc, transaction) => {
            const channel = getChannelName(transaction.channel_id);
            const tp1Profit = parseFloat(transaction.take_profit_1_profit) || 0;
            const tradeProfit = parseFloat(transaction.profit) || 0;

            // Adjust TP1 Profit for 100% quantity
            const adjustedProfit = transaction.take_profit_1_hit
                ? tp1Profit * (100 / 60)
                : tp1Profit;

            // Initialize channel if not exists
            if (!acc[channel]) acc[channel] = { totalProfit: 0, negativeProfit: 0 };

            // Add adjusted TP1 profit
            acc[channel].totalProfit += adjustedProfit;

            // Subtract negative trade profits
            if (tradeProfit < 0) {
                acc[channel].negativeProfit += tradeProfit; // Accumulate negative profit
            }

            return acc;
        }, {});

        // Adjust total profits for negative trade profits
        Object.keys(channelProfits).forEach(channel => {
            channelProfits[channel].totalProfit += channelProfits[channel].negativeProfit;
        });

        // Sort channels by total profit (descending order)
        const sortedChannels = Object.entries(channelProfits).sort(
            (a, b) => b[1].totalProfit - a[1].totalProfit
        );

        // Calculate total profit across all channels
        const totalProfit = sortedChannels.reduce(
            (sum, [, { totalProfit }]) => sum + totalProfit,
            0
        );

        // Render the summary
        const summaryList = document.getElementById('channel-summary-list');
        summaryList.innerHTML = `
            <li style="font-weight: bold; color: #f0a500;">Total Profit: ${totalProfit.toFixed(2)}</li>
            ${sortedChannels
                .map(
                    ([channel, { totalProfit, negativeProfit }]) =>
                        `<li>${channel}: <span style="font-weight: bold; color: ${
                            totalProfit >= 0 ? '#4caf50' : '#e74c3c'
                        };">${totalProfit.toFixed(2)}</span> 
                        <small>(Negative Profit: ${negativeProfit.toFixed(2)})</small></li>`
                )
                .join('')}`;
    } catch (error) {
        console.error('Error updating channel summary:', error);
    }
}


// Call the function on page load and periodically
document.addEventListener('DOMContentLoaded', updateChannelSummary);
setInterval(updateChannelSummary, 10000); // Update every 10 seconds


// Fetch account data every 5 seconds
setInterval(fetchAccountData, 5000);
fetchAccountData(); // Initial call

// Fetch and update the Unrealized P&L every 5 seconds
setInterval(async () => {
    const response = await fetch('/data');
    const data = await response.json();
    await updateUnrealizedPnL(data);

   renderAllProfitTable();
}, 1000);

    fetchTransactionData(); // Initial fetch
</script>

</body>
</html>

