let masonryInstance;
document.addEventListener('DOMContentLoaded', () => {
    // Handle all bootstrap popover inits
    const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]')
    const popoverList = [...popoverTriggerList].map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl))

    // Initialize all toggle functions
    toggleVisibility('editModeSwitch', 'edit-mode');
    toggleVisibility('showArchivedSwitch', 'link-archived');
    toggleVisibility('showHiddenSwitch', 'link-hidden');
    toggleVisibility('archiveButtonSwitch', 'btn-archive');
    toggleVisibility('visibilityButtonSwitch', 'btn-hideshow');
    toggleVisibility('privacyButtonSwitch', 'btn-publish');
    toggleVisibility('addButtonSwitch', 'btn-addlink');
    toggleVisibility('shareButtonSwitch', 'btn-share');

    toggleVisibility('dashShowArchivedSwitch', 'link-archived');
    toggleVisibility('dashShowHiddenSwitch', 'link-hidden');
    toggleVisibility('dashAddButtonSwitch', 'btn-addlink');
    toggleVisibility('dashShareButtonSwitch', 'btn-share');

    // Retrieve the list of collapsed folderCard IDs from local storage
    
    const onDashboard = document.getElementById("dash_id");
    let collapsedFolders;
    if ( onDashboard ) {
        collapsedFolders = JSON.parse(localStorage.getItem( 'collapsedDashFolders' + onDashboard.value  )) || [];
    } else {
        collapsedFolders = JSON.parse(localStorage.getItem( 'collapsedFolders' )) || [];
    }

    // Collapse the elements stored in local storage when the page loads
    collapsedFolders.forEach((folderId) => {
        const collapseElement = document.querySelector(`#Collapse${folderId}`);
        if ( collapseElement ) {
            collapseElement.classList.remove('show');
        }
    });

    // Add event listeners to track expand and collapse actions
    document.querySelectorAll('.accordion-item').forEach((item) => {
        const folderCardId = item.closest('.bookmark-card')?.id?.replace('folderCard', '');

        if ( ! folderCardId ) return;

        const collapseElement = item.querySelector('.collapse');

        // Listen for collapse and expand events
        collapseElement.addEventListener('hidden.bs.collapse', () => {
            let storageName;
            // Add the folderCard ID to local storage when collapsed
            if (!collapsedFolders.includes(folderCardId)) {
                collapsedFolders.push(folderCardId);
                if ( onDashboard ) {
                    storageName = 'collapsedDashFolders' + onDashboard.value;
                } else {
                    storageName = 'collapsedFolders';
                }
                localStorage.setItem( storageName , JSON.stringify(collapsedFolders));
            }
        });

        collapseElement.addEventListener('shown.bs.collapse', () => {
            let storageName;
            // Remove the folderCard ID from local storage when expanded
            const index = collapsedFolders.indexOf(folderCardId);
            if (index > -1) {
                collapsedFolders.splice(index, 1);
                if ( onDashboard ) {
                    storageName = 'collapsedDashFolders' + onDashboard.value;
                } else {
                    storageName = 'collapsedFolders';
                }
                localStorage.setItem( storageName , JSON.stringify(collapsedFolders));
            }
        });
    });

    const masonryContainer = document.getElementById("bookmarkSort");

    if ( ! masonryContainer ) {
        return;
    }

    if ( localStorage.getItem('manageFolderOrder') ) {
        loadDashLinkOrder();
    }

    masonryInstance = new Masonry(masonryContainer, {
        columnHeight: '.accordion',
        itemSelector: ".bookmark-card",
        percentPosition: false
    });

    const test = () => masonryInstance.layout();

    masonryContainer.addEventListener('hidden.bs.collapse', test );
    masonryContainer.addEventListener('shown.bs.collapse', test );

    // Select all folder-raise and folder-lower buttons
    
    const raiseButtons = document.querySelectorAll(".folder-raise");
    const lowerButtons = document.querySelectorAll(".folder-lower");

    // Function to move the folderCard up
    function moveUp(event) {
        const folderCard = event.target.closest(".bookmark-card");
        const bookmarkSort = document.getElementById("bookmarkSort");
        const orderId = document.getElementById("dashLinkOrder");

        if (folderCard) {
            const previousSibling = folderCard.previousElementSibling;
            if (previousSibling) {
                // Remove and reinsert the element before the previous sibling
                bookmarkSort.removeChild(folderCard);
                bookmarkSort.insertBefore(folderCard, previousSibling);
                masonryInstance.reloadItems();
                masonryInstance.layout();
                updateDashLinkOrder();
            }
        }
    }

    // Function to move the folderCard down
    function moveDown(event) {
        const folderCard = event.target.closest(".bookmark-card");
        const bookmarkSort = document.getElementById("bookmarkSort");

        if (folderCard) {
            const nextSibling = folderCard.nextElementSibling;
            if (nextSibling) {
                // Remove and reinsert the element after the next sibling
                bookmarkSort.removeChild(folderCard);
                bookmarkSort.insertBefore(folderCard, nextSibling.nextSibling);
                masonryInstance.reloadItems();
                masonryInstance.layout();
                updateDashLinkOrder();
            }
        }
    }

    // Add event listeners to the raise buttons
    raiseButtons.forEach(button => {
        button.addEventListener("click", moveUp);
    });

    // Add event listeners to the lower buttons
    lowerButtons.forEach(button => {
        button.addEventListener("click", moveDown);
    });
    // after hiding/showing elements
    masonryInstance.layout();
});

// Function to handle showing or hiding elements based on the checkbox state
function toggleVisibility(switchId, className) {
    const switchElement = document.getElementById(switchId);
    const elementsToToggle = document.querySelectorAll(`.${className}`);

    if ( ! switchElement ) {
        return;
    }

    // Listen for changes to the checkbox
    switchElement.addEventListener('change', () => {
        if (switchElement.checked) {
            elementsToToggle.forEach(element => {
                element.style.display = '';
            });
        } else {
            elementsToToggle.forEach(element => {
                element.style.display = 'none';
            });
        }
        if (typeof masonryInstance !== 'undefined') {
            masonryInstance.reloadItems();
            masonryInstance.layout()
            return;
        }
    });

    // Trigger the toggle initially to set the correct visibility on page load
    switchElement.dispatchEvent(new Event('change'));
}

function updateDashLinkOrder() {
    const bookmarkCards = document.querySelectorAll("#bookmarkSort .bookmark-card");
    const ids = Array.from( bookmarkCards ).map( card => {
        const match = card.id.match(/folderCard(\d+)/);
        return match ? match[1] : null;
    }).filter( id => id !== null );
  
    const dashLinkOrder = document.getElementById("dashLinkOrder");
    if (dashLinkOrder) {
        dashLinkOrder.value = ids.join(",");
    } else {
        localStorage.setItem('manageFolderOrder', ids.join(","));
    }
}

function loadDashLinkOrder() {
    const onDashboard = document.getElementById("dash_id");
    const storedOrder = localStorage.getItem("manageFolderOrder"); // Get the saved order
    const bookmarkSort = document.getElementById("bookmarkSort");
    
    if ( onDashboard || !storedOrder || !bookmarkSort ) return; // Exit if no saved order or no container
  
    const orderArray = storedOrder.split(","); // Convert the saved order into an array
    const bookmarkCards = Array.from(document.querySelectorAll("#bookmarkSort .bookmark-card"));
  
    // Create a map for quick lookup of cards by their ID
    const cardMap = new Map();
    bookmarkCards.forEach(card => {
      const match = card.id.match(/folderCard(\d+)/);
      if (match) cardMap.set(match[1], card);
    });
  
    // Reorder elements based on the saved order
    const orderedElements = [];
    orderArray.forEach(id => {
      if (cardMap.has(id)) {
        orderedElements.push(cardMap.get(id)); // Add elements in the specified order
        cardMap.delete(id); // Remove from the map once processed
      }
    });
  
    // Add any remaining (unspecified) elements to the end of the list
    const remainingElements = Array.from(cardMap.values());
    orderedElements.push(...remainingElements);
  
    // Clear the container and append the elements in the new order
    bookmarkSort.innerHTML = ""; // Remove all children
    orderedElements.forEach(element => bookmarkSort.appendChild(element)); // Append in order
}
