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;

    // Sānu joslas izmēru maiņa
    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); // Minimālais platums ir 100px
            elementList.style.width = `${newWidth}px`;
            resizeHandle.style.right = `${newWidth}px`;
        }
    });

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

    // Meklēšanas joslas ievade
    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";
        });
    });

    // Poga "Notīrīt visu"
    clearAllButton.addEventListener("click", () => {
        const elements = gameContainer.querySelectorAll(".game-element");
        elements.forEach((element) => element.remove());
        alert("Visi elementi notīrīti!");
    });

    // Datu ielāde no servera un elementu saraksta veidošana
    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;

                // Notikums velkšanai no elementu saraksta
                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("Kļūda, ielādējot elementus:", error));

    // Velkamo elementu apstrāde spēles laukā
    gameContainer.addEventListener("dragover", (event) => event.preventDefault());

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

        // Ja elements tiek vilkts no saraksta
        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);

            checkForCombination(newElement);
        }

        // Ja elementi tiek apvienoti spēles laukumā
        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`;

            checkForCombination(draggedElement);
        }
    });

    // Elementu apvienošana spēles laukumā
    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();

            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;

            const x = (parseFloat(draggedElement.style.left) + parseFloat(overlappingTarget.style.left)) / 2;
            const y = (parseFloat(draggedElement.style.top) + parseFloat(overlappingTarget.style.top)) / 2;

            draggedElement.remove();
            overlappingTarget.remove();

            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;

                        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);
                        }

                        const gameElement = createGameElement(newElement);
                        gameElement.style.left = `${x}px`;
                        gameElement.style.top = `${y}px`;
                        gameContainer.appendChild(gameElement);
                    } else {
                        alert("Neizdevās apvienot elementus: " + data.message);
                    }
                })
                .catch((error) => console.error("Kļūda, apvienojot elementus:", error));
        }
    }

    // Saglabāšanas laukuma funkcionalitāte
    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;

            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("Elements veiksmīgi saglabāts!");
                        draggedElement.remove();
                    } else {
                        alert("Neizdevās saglabāt elementu.");
                    }
                })
                .catch((error) => console.error("Kļūda, saglabājot elementu:", error));
        }
    });
    fetch('fetch_saved_elements.php')
    .then(response => response.json())
    .then(data => {
        console.log("Fetched elements:", data);
        if (Array.isArray(data)) {
            data.forEach(element => {
                //Prevent duplicates by checking if element already exists visually
                const alreadyExists = gameContainer.querySelector(`[data-element="${element.name}"]`);
                if (!alreadyExists) {
                    const el = createGameElement(element.name);
                    el.style.left = `${Math.random() * 300}px`;
                    el.style.top = `${Math.random() * 300}px`;
                }
            });
        } else {
            console.error("Failed to load elements:", data);
        }
    })
    .catch(err => console.error("Error loading elements:", err));

    // Dzēšanas laukuma funkcionalitāte
    clearArea.addEventListener("dragover", (event) => event.preventDefault());
    clearArea.addEventListener("drop", (event) => {
        event.preventDefault();
        const draggedElement = document.querySelector(".dragging");
        if (draggedElement && draggedElement.parentNode === gameContainer) {
            draggedElement.remove();
        }
    });

    // Palīgfunkcija spēles elementa izveidei
    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;
    }
});

// Funkcija, lai atgrieztos uz sākumlapu
function goBack() {
    window.location.href = "homepage.html"; // Pielāgot ceļu uz sākumlapu
}
