document.addEventListener('DOMContentLoaded', function () {
    const userEmail = document.getElementById("user-email").getAttribute("data-email");
    const profileId = document.getElementById("profile_id").getAttribute("data-profile-id");

    const createButton = document.getElementById('create-object-btn');
    const objectsContainer = document.getElementById('objects-container');

    const popupDialog = document.getElementById('popup-dialog');
    const confirmBtn = document.getElementById('confirm-btn');
    const cancelBtn = document.getElementById('cancel-btn');
    const objectNameInput = document.getElementById('object-name-input');

    function fetchExistingObjects() {
        fetch("../php/getaccounts.php", {
            method: "POST",
            body: new URLSearchParams({
                profile_id: profileId
            })
        })
            .then(response => response.json())
            .then(data => {
                if (!data.error) {
                    data.forEach(accountName => addObjectToContainer(accountName));
                }
            })
            .catch(error => console.error("Error fetching accounts:", error));
    }
    function addObjectToContainer(accountName) {
        const objectBox = document.createElement('div');
        objectBox.classList.add('object-box');
    
        const textBox = document.createElement('div');
        textBox.textContent = accountName;
        textBox.classList.add('text-box');
    
        const deleteBtn = document.createElement('button');
        deleteBtn.innerHTML = '<i class="fas fa-trash"></i>';
        deleteBtn.classList.add('delete-btn');
    
        objectBox.appendChild(textBox);
        objectBox.appendChild(deleteBtn);
        objectsContainer.appendChild(objectBox);
    
        // Make the entire objectBox clickable
        objectBox.style.cursor = 'pointer';
        objectBox.addEventListener('click', function () {
            window.location.href = `../html/history.html?email=${encodeURIComponent(userEmail)}&profile_id=${encodeURIComponent(profileId)}&account_name=${encodeURIComponent(accountName)}`;
        });
    
        // If delete button is clicked, stop propagation so it doesn't trigger the objectBox click
        deleteBtn.addEventListener('click', function (e) {
            e.stopPropagation(); // Prevent the click event from bubbling up to the objectBox
            if (confirm("Are you sure you want to delete this account?")) {
                deleteAccount(accountName, profileId, objectBox);
            }
        });
    }
    
    function deleteAccount(accountName, profileId, objectBox) {
        fetch("../php/deleteaccount.php", {
            method: "POST",
            body: new URLSearchParams({
                account_name: accountName,
                profile_id: profileId
            })
        })
            .then(response => response.json())
            .then(data => {
                if (!data.error) {
                    objectsContainer.removeChild(objectBox);
                }
            })
            .catch(error => console.error("Error deleting account:", error));
    }

    fetchExistingObjects();

    createButton.addEventListener('click', function () {
        popupDialog.style.display = 'flex';
    });

    confirmBtn.addEventListener('click', function () {
        const accountName = objectNameInput.value;
        if (accountName) {
            addObjectToContainer(accountName);
            fetch("../php/registersubacc.php", {
                method: "POST",
                body: new URLSearchParams({
                    account_name: accountName,
                    profile_id: profileId
                })
            })
                .then(response => response.text())
                .then(() => {
                    popupDialog.style.display = 'none';
                    objectNameInput.value = '';
                })
                .catch(error => console.error("Error creating account:", error));
        } else {
            alert('Please enter a valid name.');
        }
    });
    // Cancel button to close the popup without creating a new account
    cancelBtn.addEventListener('click', function () {
        popupDialog.style.display = 'none';
        objectNameInput.value = '';  // Clear the input field
    });
});
