const apiUrl = "http://localhost/kvalifikacija_html/first_page/php";

document.addEventListener("DOMContentLoaded", async () => {
    await loadHistory();
});

async function loadHistory() {
    try {
        // Fetch the chat history from the backend
        const response = await axios.get(`${apiUrl}/getChatHistory.php`);
        const history = response.data;

        // Select the content container
        const contentContainer = document.querySelector(".content");
        contentContainer.innerHTML = ""; // Clear any previous items

        // Populate the content container with fetched history
        history.forEach((item) => {
            const itemDiv = document.createElement("div");
            itemDiv.className = "generated-item";

            itemDiv.innerHTML = `
                <span class="content-text">${item.content}</span>
                <button class="edit-button" onclick="enableEdit(this)">Edit</button>
                <a href="chat_history.html?chat=${encodeURIComponent(item.content)}">
                    <img src="images/arrow.png" class="arrow-icon" alt="View Chat">
                </a>
            `;

            contentContainer.appendChild(itemDiv);
        });
    } catch (error) {
        console.error("Error loading history:", error);
    }
}

function enableEdit(button) {
    const itemContainer = button.closest(".generated-item");
    const contentText = itemContainer.querySelector(".content-text");
    const input = document.createElement("input");
    input.type = "text";
    input.value = contentText.textContent;
    input.className = "edit-input";

    contentText.replaceWith(input);
    input.focus();

    input.addEventListener("blur", () => saveEdit(input));
    input.addEventListener("keypress", (e) => {
        if (e.key === "Enter") saveEdit(input);
    });
}

function saveEdit(input) {
    const contentText = document.createElement("span");
    contentText.className = "content-text";
    contentText.textContent = input.value;
    input.replaceWith(contentText);
}
