document.addEventListener("DOMContentLoaded", () => {
    const elementList = document.getElementById("element-list");
    const resizeHandle = document.createElement("div");
    resizeHandle.id = "resize-handle";
    document.body.appendChild(resizeHandle);
    
    const gameContainer = document.getElementById("game-container");
    const saveArea = document.getElementById("save-area");
    const clearArea = document.getElementById("clear-area");
    const searchBar = document.querySelector(".search-bar");
    const clearAllButton = document.getElementById("clear-all-button");

    let dragOffsetX = 0;
    let dragOffsetY = 0;
    let isResizing = false;

    // Sidebar resizing functionality
    resizeHandle.addEventListener("mousedown", (event) => {
        isResizing = true;
        document.body.style.cursor = "ew-resize";
        event.preventDefault();
    });

    document.addEventListener("mousemove", (event) => {
        if (isResizing) {
            const newWidth = Math.max(window.innerWidth - event.clientX, 100); // Minimum width of 100px
            elementList.style.width = `${newWidth}px`;
            resizeHandle.style.right = `${newWidth}px`;
        }
    });

    document.addEventListener("mouseup", () => {
        if (isResizing) {
            isResizing = false;
            document.body.style.cursor = "";
        }
    });

    // Handle Search Bar Input
    searchBar.addEventListener("input", (event) => {
        const query = event.target.value.toLowerCase();
        const elements = elementList.querySelectorAll(".draggable-button");

        elements.forEach((element) => {
            const elementText = element.textContent.toLowerCase();
            element.style.display = elementText.includes(query) ? "" : "none";
        });
    });

    // Handle "Clear All" Button
    clearAllButton.addEventListener("click", () => {
        const elements = gameContainer.querySelectorAll(".game-element");
        elements.forEach((element) => element.remove());
        alert("All elements cleared!");
    });

    // Fetch Elements from Database and Populate Element List
    fetch("fetch_elements.php")
        .then((response) => response.json())
        .then((elements) => {
            elements.forEach((element) => {
                const button = document.createElement("div");
                button.classList.add("draggable-button");
                button.draggable = true;
                button.dataset.element = element.name;
                button.textContent = element.name;

                // Drag Start Event for Element List
                button.addEventListener("dragstart", (event) => {
                    const rect = event.target.getBoundingClientRect();
                    dragOffsetX = event.clientX - rect.left;
                    dragOffsetY = event.clientY - rect.top;
                    event.dataTransfer.setData("text/plain", event.target.dataset.element);
                    event.dataTransfer.setData("source", "element-list");
                });

                elementList.appendChild(button);
            });
        })
        .catch((error) => console.error("Error fetching elements:", error));

    // Allow Dragging into Game Container
    gameContainer.addEventListener("dragover", (event) => event.preventDefault());

    // Unified Drop Logic for Game Container
    gameContainer.addEventListener("drop", (event) => {
        event.preventDefault();
        const draggedElement = document.querySelector(".dragging");
        const elementType = event.dataTransfer.getData("text/plain");
        const source = event.dataTransfer.getData("source");

        // Handle Drops from the Element List
        if (source === "element-list") {
            const newX = event.clientX - dragOffsetX - gameContainer.offsetLeft;
            const newY = event.clientY - dragOffsetY - gameContainer.offsetTop;

            const newElement = createGameElement(elementType);
            newElement.style.left = `${newX}px`;
            newElement.style.top = `${newY}px`;

            gameContainer.appendChild(newElement);

            // Check for immediate overlap after adding
            checkForCombination(newElement);
        }

        // Handle Combining Elements in the Game Container
        if (source === "game-container" && draggedElement) {
            const newX = event.clientX - dragOffsetX - gameContainer.offsetLeft;
            const newY = event.clientY - dragOffsetY - gameContainer.offsetTop;

            draggedElement.style.left = `${newX}px`;
            draggedElement.style.top = `${newY}px`;

            // Check for immediate overlap after repositioning
            checkForCombination(draggedElement);
        }
    });

    // Function to check for overlapping elements and combine them
    function checkForCombination(draggedElement) {
        const dropTargets = Array.from(gameContainer.querySelectorAll(".game-element")).filter(
            (el) => el !== draggedElement
        );

        let overlappingTarget = null;

        dropTargets.forEach((target) => {
            const targetRect = target.getBoundingClientRect();
            const draggedRect = draggedElement.getBoundingClientRect();

            // Check if the rectangles overlap
            const isOverlapping =
                targetRect.left < draggedRect.right &&
                targetRect.right > draggedRect.left &&
                targetRect.top < draggedRect.bottom &&
                targetRect.bottom > draggedRect.top;

            if (isOverlapping) {
                overlappingTarget = target;
            }
        });

        if (overlappingTarget) {
            const element1 = draggedElement.dataset.element;
            const element2 = overlappingTarget.dataset.element;

            // Calculate New Position for Combined Element
            const x = (parseFloat(draggedElement.style.left) + parseFloat(overlappingTarget.style.left)) / 2;
            const y = (parseFloat(draggedElement.style.top) + parseFloat(overlappingTarget.style.top)) / 2;

            // Remove Both Elements
            draggedElement.remove();
            overlappingTarget.remove();

            // Send Combined Elements to Server
            fetch("combine_elements.php", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                body: `element1=${encodeURIComponent(element1)}&element2=${encodeURIComponent(element2)}`,
            })
                .then((response) => response.json())
                .then((data) => {
                    if (data.status === "success" || data.status === "exists") {
                        const newElement = data.newElement;

                        // Check for Duplicates in the Element List
                        const existingElement = Array.from(elementList.children).find(
                            (child) => child.textContent === newElement
                        );

                        if (!existingElement) {
                            const button = document.createElement("div");
                            button.classList.add("draggable-button");
                            button.draggable = true;
                            button.dataset.element = newElement;
                            button.textContent = newElement;

                            button.addEventListener("dragstart", (event) => {
                                const rect = event.target.getBoundingClientRect();
                                dragOffsetX = event.clientX - rect.left;
                                dragOffsetY = event.clientY - rect.top;
                                event.dataTransfer.setData("text/plain", event.target.dataset.element);
                                event.dataTransfer.setData("source", "element-list");
                            });

                            elementList.appendChild(button);
                        }

                        // Add the New Element to the Game Area
                        const gameElement = createGameElement(newElement);
                        gameElement.style.left = `${x}px`;
                        gameElement.style.top = `${y}px`;
                        gameContainer.appendChild(gameElement);
                    } else {
                        alert("Failed to combine elements: " + data.message);
                    }
                })
                .catch((error) => console.error("Error combining elements:", error));
        }
    }

    // Save Area Functionality
    saveArea.addEventListener("dragover", (event) => event.preventDefault());

    saveArea.addEventListener("drop", (event) => {
        event.preventDefault();
        const draggedElement = document.querySelector(".dragging");

        if (draggedElement && draggedElement.parentNode === gameContainer) {
            const elementType = draggedElement.dataset.element;

            // Send the element to the server for saving
            fetch("save_element.php", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                body: `name=${encodeURIComponent(elementType)}`
            })
                .then((response) => response.json())
                .then((data) => {
                    if (data.status === "success") {
                        alert("Element saved successfully!");
                        draggedElement.remove(); // Remove element after saving
                    } else {
                        alert("Failed to save the element.");
                    }
                })
                .catch((error) => console.error("Error saving element:", error));
        }
    });

    // Clear Area Functionality
    clearArea.addEventListener("dragover", (event) => event.preventDefault());
    clearArea.addEventListener("drop", (event) => {
        event.preventDefault();
        const draggedElement = document.querySelector(".dragging");
        if (draggedElement && draggedElement.parentNode === gameContainer) {
            draggedElement.remove();
        }
    });

    // Helper Function to Create Draggable Game Element
    function createGameElement(type) {
        const element = document.createElement("div");
        element.classList.add("game-element");
        element.dataset.element = type;
        element.textContent = type;
        element.style.position = "absolute";

        element.draggable = true;
        element.addEventListener("dragstart", (event) => {
            const rect = event.target.getBoundingClientRect();
            dragOffsetX = event.clientX - rect.left;
            dragOffsetY = event.clientY - rect.top;
            event.dataTransfer.setData("text/plain", event.target.dataset.element);
            event.dataTransfer.setData("source", "game-container");
            element.classList.add("dragging");
        });

        element.addEventListener("dragend", () => {
            element.classList.remove("dragging");
        });

        return element;
    }
});

function goBack() {
    window.location.href = "homepage.html"; // Adjust the path to your homepage
}
