document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM fully loaded and parsed');

    // Helper function to make POST requests
    async function postData(url = '', data = {}) {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams(data),
        });
        return response.text();
    }

    // Password change handler
    function setupChangePasswordHandler() {
        const form = document.getElementById('changePasswordForm');
        if (form) {
            form.addEventListener('submit', async function(event) {
                event.preventDefault();
                const currentPassword = document.getElementById('currentPasswordInput').value.trim();
                const newPassword = document.getElementById('newPassword').value.trim();

                if (!currentPassword || !newPassword) {
                    alert('Please fill in all fields');
                    return;
                }

                const data = await postData('change_password.php', { currentPassword, newPassword });
                alert(data);
            });
        }
    }

    // User registration handler
    function setupRegistrationHandler() {
        const button = document.getElementById('registerButton');
        if (button) {
            button.addEventListener('click', async function() {
                const regUsername = document.getElementById('regUsername').value.trim();
                const regEmail = document.getElementById('regEmail').value.trim();
                const regPassword = document.getElementById('regPassword').value.trim();

                if (!regUsername || !regEmail || !regPassword) {
                    alert('Please fill in all fields');
                    return;
                }

                const data = await postData('register.php', { regUsername, regEmail, regPassword });
                alert(data);
                if (data === 'Registration successful') {
                    window.location.href = 'login.html';
                }
            });
        }
    }

    // User login handler
    function setupLoginHandler() {
        const button = document.getElementById('loginButton');
        if (button) {
            button.addEventListener('click', async function() {
                const login = document.getElementById('login').value.trim();
                const password = document.getElementById('password').value.trim();

                if (!login || !password) {
                    alert('Please fill in all fields');
                    return;
                }

                const data = await postData('login.php', { login, password });
                alert(data);
                if (data === 'Login successful') {
                    window.location.href = 'index.html';
                }
            });
        }
    }

    // Fetch and display user data
    function fetchUserData() {
        fetch('get_user_info.php')
            .then(response => response.json())
            .then(data => {
                document.getElementById('currentUsername').textContent = data.username;
                document.getElementById('currentPassword').textContent = '*'.repeat(data.password_hash.length);
            })
            .catch(error => console.error('Error fetching user data:', error));
    }

    // Fetch and display cryptocurrency data
    function fetchCryptoData() {
        fetch('get_crypto_data.php')
            .then(response => response.json())
            .then(data => {
                const cryptoDataBlock = document.getElementById('test');
                if (!cryptoDataBlock) {
                    console.error('Crypto data container not found');
                    return;
                }

                console.log('Container found:', cryptoDataBlock);
                const table = createCryptoTable(data);
                cryptoDataBlock.appendChild(table);
            })
            .catch(error => console.error('Error fetching cryptocurrency data:', error));
    }

    // Create table for displaying cryptocurrency data
    function createCryptoTable(data) {
        const table = document.createElement('table');
        const thead = document.createElement('thead');
        const tbody = document.createElement('tbody');

        // Table headers
        const headers = ['Name', 'Price', 'Price Change-24h'];
        const headerRow = document.createElement('tr');
        headers.forEach(headerText => {
            const th = document.createElement('th');
            th.textContent = headerText;
            th.classList.add('sortable');
            th.addEventListener('click', () => sortTableByColumn(headerText.toLowerCase()));
            headerRow.appendChild(th);
        });
        thead.appendChild(headerRow);
        table.appendChild(thead);

        // Table rows
        data.forEach(crypto => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${crypto.currency_name}</td>
                <td>${crypto.price}</td>
                <td>${crypto.price_change_24h}</td>
            `;
            tbody.appendChild(row);
        });
        table.appendChild(tbody);

        return table;
    }

    // Sort table by column
    function sortTableByColumn(columnName) {
        const table = document.querySelector('table');
        const tbody = table.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr'));

        const columnIndex = {
            name: 0,
            price: 1,
            'price change-24h': 2,
        }[columnName];

        rows.sort((a, b) => {
            const aValue = columnName === 'name' 
                ? a.cells[columnIndex].textContent.toLowerCase() 
                : parseFloat(a.cells[columnIndex].textContent);
            const bValue = columnName === 'name' 
                ? b.cells[columnIndex].textContent.toLowerCase() 
                : parseFloat(b.cells[columnIndex].textContent);

            if (columnName === 'name') {
                return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
            }
            return columnName === 'price' 
                ? bValue - aValue 
                : (aValue >= 0 && bValue >= 0) || (aValue < 0 && bValue < 0)
                    ? bValue - aValue
                    : aValue >= 0
                        ? -1
                        : 1;
        });

        rows.forEach(row => tbody.appendChild(row));
    }

    // Cryptocurrency search handler
    function setupCryptoSearchHandler() {
        const searchInput = document.getElementById('cryptoSearch');
        searchInput.addEventListener('input', function() {
            const searchTerm = searchInput.value.toLowerCase();
            const rows = document.querySelectorAll('tbody tr');

            rows.forEach(row => {
                const cryptoName = row.cells[0].textContent.toLowerCase();
                row.style.display = cryptoName.includes(searchTerm) ? '' : 'none';
            });
        });
    }

    // Fetch and display last database update time
    function fetchLastUpdateTime() {
        fetch('get_last_update.php')
            .then(response => response.text())
            .then(data => {
                const lastUpdateElement = document.getElementById('lastUpdate');
                if (lastUpdateElement) {
                    lastUpdateElement.textContent = data;
                } else {
                    console.error('Element with ID "lastUpdate" not found');
                }
            })
            .catch(error => console.error('Error fetching last update data:', error));
    }

    // Fade out animation
    function setupFadeOutLinks() {
        const mainContainer = document.querySelector('.main-container');
        function fadeOut(link) {
            mainContainer.classList.add('page-fade-out');
            setTimeout(() => window.location.href = link, 300);
        }

        document.querySelectorAll('.navbar ul li a').forEach(link => {
            link.addEventListener('click', function(event) {
                event.preventDefault();
                fadeOut(this.getAttribute('href'));
            });
        });

        document.querySelector('.logo img').addEventListener('click', function() {
            fadeOut('CryptoWebLapa.html');
        });
    }

    // Initialize all functionalities
    function initialize() {
        setupChangePasswordHandler();
        setupRegistrationHandler();
        setupLoginHandler();
        fetchUserData();
        fetchCryptoData();
        setupCryptoSearchHandler();
        fetchLastUpdateTime();
        setupFadeOutLinks();
    }

    initialize();
});
