document.addEventListener("DOMContentLoaded", () => {
    const elementsContainer = document.querySelector(".elements");
    const searchBar = document.querySelector(".search-bar");

    // Fetch saved elements from the database
    fetch("fetch_saved_elements.php")
        .then((response) => response.json())
        .then((elements) => {
            elementsContainer.innerHTML = ""; // Clear any existing content
            elements.forEach((element) => {
                const elementItem = document.createElement("div");
                elementItem.classList.add("element-item");
                elementItem.textContent = element.name; // Assuming `name` is the column in the saved_elements table
                elementsContainer.appendChild(elementItem);
            });
        })
        .catch((error) => console.error("Error fetching library elements:", error));

    // Handle search bar input
    searchBar.addEventListener("input", (event) => {
        const query = event.target.value.toLowerCase();
        const elementItems = elementsContainer.querySelectorAll(".element-item");

        elementItems.forEach((item) => {
            const itemText = item.textContent.toLowerCase();
            item.style.display = itemText.includes(query) ? "" : "none";
        });
    });
});

function goBack() {
    window.location.href = 'homepage.html'; // Redirect to the home page
}
