document.addEventListener("DOMContentLoaded", function () {
    const display = document.getElementById("workspace-display");
    const newSessionBtn = document.getElementById("new-session-btn");
    const clearWorkBtn = document.getElementById("clear-work-btn");

    function createNewWorkspace() {
        fetch("../app/api/create_workspace.php")
            .then(response => response.text())
            .then(data => {
                const parts = data.split(": ");
                if (parts.length === 2) {
                    const workspaceId = parts[1].trim();
                    localStorage.setItem("workspace_id", workspaceId);

                    if (display) {
                        display.textContent = workspaceId;
                    }

                    console.log("Workspace created:", workspaceId);
                } else {
                    if (display) {
                        display.textContent = "Could not create workspace";
                    }
                }
            })
            .catch(error => {
                console.error("Error creating workspace:", error);
                if (display) {
                    display.textContent = "Error creating workspace";
                }
            });
    }

    function clearCurrentWork() {
        const workspaceId = localStorage.getItem("workspace_id");

        if (!workspaceId) {
            alert("No workspace found.");
            return;
        }

        fetch("../app/api/clear_workspace_questions.php", {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: "workspace_id=" + encodeURIComponent(workspaceId)
        })
            .then(response => response.text())
            .then(data => {
                alert(data);
                console.log(data);
            })
            .catch(error => {
                console.error("Error clearing workspace questions:", error);
                alert("Error clearing current work.");
            });
    }

    let workspaceId = localStorage.getItem("workspace_id");

    if (!workspaceId) {
        createNewWorkspace();
    } else {
        if (display) {
            display.textContent = workspaceId;
        }
        console.log("Existing workspace found:", workspaceId);
    }

    if (newSessionBtn) {
        newSessionBtn.addEventListener("click", function () {
            createNewWorkspace();
        });
    }

    if (clearWorkBtn) {
        clearWorkBtn.addEventListener("click", function () {
            clearCurrentWork();
        });
    }
});