document.addEventListener('DOMContentLoaded', function() {
    const accountName = document.getElementById('account_name').textContent;
    let currentPage = 1;
    const rowsPerPage = 10;
    let tradeData = []; // Store trade data here

    // Get modal and close button elements
    const tradeInfoModal = document.getElementById('tradeInfoModal');
    const tradeInfoContent = document.getElementById('trade-info-content');
    const closeTradeInfoModal = document.getElementById('close-trade-info-modal');

    // Function to fetch trade data from the backend
    async function fetchTradeHistory() {
        try {
            const response = await fetch(`../php/get_trade_history.php?account_name=${accountName}`);
            tradeData = await response.json();
            setupPagination();
        } catch (error) {
            console.error('Error fetching trade history:', error);
        }
    }

    // Set up pagination
    function setupPagination() {
        const totalPages = Math.ceil(tradeData.length / rowsPerPage);
        const prevButton = document.getElementById('prev-page');
        const nextButton = document.getElementById('next-page');
        const pageInfo = document.getElementById('page-info');

        // Show first page of data
        displayPage(currentPage);

        // Disable/Enable buttons based on page count
        prevButton.disabled = currentPage === 1;
        nextButton.disabled = currentPage === totalPages || totalPages === 0;

        // Update page info
        pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;

        // Event listeners for buttons
        prevButton.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                displayPage(currentPage);
                pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;
                prevButton.disabled = currentPage === 1;
                nextButton.disabled = currentPage === totalPages;
            }
        });

        nextButton.addEventListener('click', () => {
            if (currentPage < totalPages) {
                currentPage++;
                displayPage(currentPage);
                pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;
                prevButton.disabled = currentPage === 1;
                nextButton.disabled = currentPage === totalPages;
            }
        });
    }

    // Function to display a specific page of data
    function displayPage(page) {
        const tableBody = document.getElementById('trade-history-body');
        tableBody.innerHTML = '';  // Clear previous rows

        const start = (page - 1) * rowsPerPage;
        const end = start + rowsPerPage;

        const pageData = tradeData.slice(start, end); // Get data for current page

        pageData.forEach((trade, index) => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${trade.coin_name}</td>
                <td>${trade.direction}</td>
                <td>${trade.leverage}X</td>
                <td>${trade.percents}%</td>
                <td>${trade.close_date}</td>
            `;

            // Add click event listener to the row
            row.addEventListener('click', function() {
                // Fetch trade info and display it in the modal
                fetchTradeInfo(trade.trade_id);
            });

            tableBody.appendChild(row);
        });
    }

    // Function to fetch trade details and display in the modal
    async function fetchTradeInfo(tradeId) {
        try {
            const response = await fetch(`../php/get_trade_info.php?trade_id=${tradeId}`);
            const tradeDetails = await response.json();

            if (tradeDetails.error) {
                tradeInfoContent.innerHTML = `<p>${tradeDetails.error}</p>`;
            } else {
                // Fill the modal with the trade details
                tradeInfoContent.innerHTML = `
                    <h2>Trade Info</h2>
                    <p><strong>Trade ID:</strong> ${tradeDetails.trade_id}</p>
                    <p><strong>Coin Name:</strong> ${tradeDetails.coin_name}</p>
                    <p><strong>Coin Pair:</strong> ${tradeDetails.coinpair_name}</p>
                    <p><strong>Direction:</strong> ${tradeDetails.direction}</p>
                    <p><strong>Leverage:</strong> ${tradeDetails.leverage}X</p>
                    <p><strong>Open Price:</strong> ${tradeDetails.open_price}</p>
                    <p><strong>Close Price:</strong> ${tradeDetails.close_price}</p>
                    <p><strong>Percents:</strong> ${tradeDetails.percents}%</p>
                    <p><strong>Close Date:</strong> ${tradeDetails.close_date}</p>
                    ${tradeDetails.photo ? `<img src="${tradeDetails.photo}" alt="Trade Photo" />` : ''}
                `;
            }

            // Display the modal
            tradeInfoModal.style.display = 'block';
        } catch (error) {
            console.error('Error fetching trade details:', error);
            tradeInfoContent.innerHTML = '<p>Error loading trade details.</p>';
        }
    }

    // Close the modal when the user clicks on the close button
    closeTradeInfoModal.addEventListener('click', function() {
        tradeInfoModal.style.display = 'none';
    });

    // Close the modal when the user clicks outside of the modal content
    window.addEventListener('click', function(event) {
        if (event.target == tradeInfoModal) {
            tradeInfoModal.style.display = 'none';
        }
    });

    // Fetch trade history when the page loads
    fetchTradeHistory();
});
