// dropdownUtils.js
function populateDropdown(inputId, items) {
    const input = document.getElementById(inputId);
    const dropdown = document.getElementById(`${inputId}-list`);

    if (!input || !dropdown) return; // Skip if the dropdown elements are not found

    // Clear existing items in the dropdown
    dropdown.innerHTML = '';

    // Populate with new items
    items.forEach(item => {
        const option = document.createElement('div');
        option.classList.add('dropdown-item');
        option.textContent = item;
        dropdown.appendChild(option);

        // Add click event to select item
        option.addEventListener('click', () => {
            input.value = item;
            dropdown.classList.add('hidden'); // Hide the list after selection
        });
    });

    // Show dropdown on input focus and click
    input.addEventListener('focus', () => {
        dropdown.classList.remove('hidden');
    });

    input.addEventListener('click', () => {
        dropdown.classList.remove('hidden');
    });

    // Filter the dropdown items as the user types
    input.addEventListener('input', () => {
        const value = input.value.toLowerCase();
        dropdown.classList.remove('hidden'); // Show the dropdown on input

        document.querySelectorAll(`#${inputId}-list .dropdown-item`).forEach(option => {
            option.style.display = option.textContent.toLowerCase().includes(value) ? '' : 'none';
        });
    });

    // Hide dropdown when clicking outside of the input and dropdown
    document.addEventListener('click', (e) => {
        if (!input.contains(e.target) && !dropdown.contains(e.target)) {
            dropdown.classList.add('hidden');
        }
    });
}

export function populateDropdowns() {
    // Retrieve account_name from the HTML element
    const account_name = document.getElementById('account_name').innerText.trim();
    const profile_id = document.getElementById('profile_id').innerText.trim();

    // Append account_name to the URL as a query parameter
    fetch(`../php/get_coin_names.php?account_name=${encodeURIComponent(account_name)}&profile_id=${encodeURIComponent(profile_id)}`)
        .then(response => response.json())
        .then(data => {
            // Populate 'coin' dropdown if it exists in the DOM
            if (document.getElementById('coin')) {
                populateDropdown('coin', data.coins || []);
            }

            // Populate 'coinpair' dropdown if it exists in the DOM
            if (document.getElementById('coinpair')) {
                populateDropdown('coinpair', data.coinpairs || []);
            }
        })
        .catch(error => {
            console.error('Error fetching dropdown data:', error);
        });
}
