
function createToggleButton(id)
{
    let container = document.createElement('div');
    var toggleButton = document.createElement('button');
    toggleButton.id = id;
    toggleButton.textContent = 'Draggable Off'; // Initial text
    

    // styles
    toggleButton.style.padding = '8px 10px';
    toggleButton.style.fontSize = '14px';
    toggleButton.style.margin = '5px';

    // Event listener to toggle state
    toggleButton.addEventListener('click', function() {
    let isClicked = toggleButton.classList.contains('light-green') || toggleButton.textContent.includes('On');
    if (isClicked) {
        this.textContent = 'Draggable Off';
        this.classList.remove('light-green');
        display_alerts();
    } else {
        this.textContent = 'Draggable On';
        this.classList.add('light-green');
        display_alerts();
    }
    });

    container.appendChild(toggleButton);
    return container;
}

function isButtonOn() {
    let toggleButton = document.getElementById('dragg');
    return toggleButton.classList.contains('light-green') || toggleButton.textContent.includes('On');
}


function createToggleResetButton()
{
    let container = document.createElement('div');
    var toggleButton = document.createElement('button');
    toggleButton.textContent = 'Reset Draggable'; // Initial text

    // styles
    toggleButton.style.padding = '8px 10px';
    toggleButton.style.fontSize = '14px';
    toggleButton.style.margin = '5px';

    // Function to check button state
    toggleButton.onclick = function() {
        showTriggersPanel();
        resetPositions();
    };
    container.appendChild(toggleButton);
    return container;
}

  function toggleDraggable() {
    isDraggingEnabled = !isDraggingEnabled; // Toggle the state

    document.querySelectorAll('.draggable').forEach(item => {
        const id = item.id;

        if (isDraggingEnabled) {
            // Enable dragging and restore the last known position
            $(item).draggable("enable");

            var savedPosition = localStorage.getItem(id);
            if (savedPosition) {
                var position = JSON.parse(savedPosition);

                $(item).css({
                    top: position.top,
                    left: position.left,
                    position: 'absolute'
                });
            }
        } else {
            // Save current position before disabling
            var currentPosition = $(item).position();
            localStorage.setItem(id, JSON.stringify(currentPosition));

            $(item).draggable("disable");
        }
    });
}

function resetPositions() {
    // No need to adjust based on 'boxPosition' if we're resetting relative to the container's initial layout
    for (const [id, originalPosition] of Object.entries(originalPositions)) {
        const element = document.getElementById(id);
        if (element) {
            // Reset the position using the stored initial relative position
            $(element).css({
                top: originalPosition.top + 'px',
                left: originalPosition.left + 'px',
                position: 'absolute' // Make sure this is correct based on your layout needs
            });

            // Since we're resetting to the initial position inside the container,
            // no need to adjust by the container's current position
        }
    }
}

// ---------------------------------------------------------------------------
// The Draggable Part
// ---------------------------------------------------------------------------

function makeElementDraggable(element) {


    $(element).draggable({
        containment: "document",
        start: function(event, ui) {
            // Check if the button is on
            if (!isButtonOn()) {
               
                // If the button is off, prevent dragging
                $(this).draggable('disable');
        
                // Reset the position to the last saved position or the original position
                var savedPosition = localStorage.getItem(element.id) || JSON.stringify(originalPositions[element.id]);
                if (savedPosition) {
                    var position = JSON.parse(savedPosition);
                    $(this).css({
                        top: position.top,
                        left: position.left,
                        position: 'absolute',
                        'z-index': '9991' 
                    });
                }
        
                // Since we've prevented dragging, we need to re-enable it for future checks
                $(this).draggable('enable');
                return false; // Prevent dragging
            } else {
                
                // Check if the saved position is off the screen
                var savedPosition = localStorage.getItem(element.id);
                if (savedPosition) {
                    var position = JSON.parse(savedPosition);
        
                    // Adding 100 extra pixels to the window width
                    var windowWidthPlus100 = $(window).width() + 200;

                    // Adding 100 extra pixels to the window height
                    var windowHeightPlus100 = $(window).height() + 1000;

                    // Check if position is off-screen
                    var isOffScreen = position.left < 0 || position.top < 0 ||
                      position.left > windowWidthPlus100 || position.top > windowHeightPlus100;
        
                
                    if (isOffScreen && browserZoom100orLess()) {
                        // Set to current cursor position with an offset
                        var offsetX = 10; // Offset the element 10 pixels to the right of the cursor
                        var offsetY = 10; // Offset the element 10 pixels below the cursor
                        
                        // Using event.clientX and event.clientY to get the cursor position at the start
                        position.left = event.clientX + offsetX;
                        position.top = event.clientY + offsetY;
        
                        // Ensure the element is positioned relative to the document
                        $(this).css({
                            top: position.top + 'px',
                            left: position.left + 'px',
                            position: 'absolute',
                            'z-index': '9991' 
                        });
        
                        // Update the position in localStorage
                        localStorage.setItem(element.id, JSON.stringify({left: position.left, top: position.top}));
                    }
                }
            }
        },
        drag: function(event, ui) {
            // This event fires during the drag. Use it to enforce custom boundaries.
            //const docWidth = $(document).width() - $(this).outerWidth();
            const docWidth = $(document).width();
            const docHeight = $(document).height() - $(this).outerHeight();
    
            ui.position.left = Math.min(Math.max(0, ui.position.left), docWidth);
            ui.position.top = Math.min(Math.max(0, ui.position.top), docHeight);

            // Enforce horizontal boundaries
            if (ui.position.left < 0) {
                ui.position.left = 0;
            } else if (ui.position.left + $(this).width() > docWidth) {
                ui.position.left = docWidth - $(this).width();
            }

            // Enforce vertical boundaries
            if (ui.position.top < 0) {
                ui.position.top = 0;
            } else if (ui.position.top + $(this).height() > docHeight) {
                ui.position.top = docHeight - $(this).height();
            }
        },
        create: function(event, ui) {
            
            // Capture and store the element's initial position relative to its container
            if (!originalPositions[element.id]) {
                let elementPos = element.getBoundingClientRect();
                originalPositions[element.id] = {
                    top: elementPos.top,
                    left: elementPos.left
                };
            }
        },
    
        stop: function(event, ui) {
        
            // Save the new position when dragging stops
            var position = ui.position;

                $(element).css({
                    top: position.top,
                    left: position.left,
                    position: 'absolute',
                    'z-index': '9991' 
                });


            localStorage.setItem(element.id, JSON.stringify(position));
        }
    });

    // Immediately apply the last known position
    var savedPosition = localStorage.getItem(element.id);
    if (savedPosition) {

        var position = JSON.parse(savedPosition);

        // Adding 100 extra pixels to the window width
        var windowWidthPlus100 = $(window).width() + 200;

        // Adding 100 extra pixels to the window height
        var windowHeightPlus100 = $(window).height() + 1000;

        // Check if position is off-screen
        var isOffScreen = position.left < 0 || position.top < 0 ||
                        position.left > windowWidthPlus100 || position.top > windowHeightPlus100;

        if (isOffScreen && browserZoom100orLess()) {
            // If out of bounds, set the element to appear at the cursor with an offset
            var offsetX = 10; // Offset by 10 pixels to avoid direct overlay
            var offsetY = 10;
            

            $(element).css({

                top: cursorPosition.y + offsetY + 'px',  // Apply offset to Y
                left: cursorPosition.x + offsetX + 'px', // Apply offset to X
                position: 'absolute'
            });
        } else {
            // Apply saved position if within bounds
            $(element).css({
                top: position.top + 'px',
                left: position.left + 'px',
                position: 'absolute'
            });
        }
    }
}
function browserZoom100orLess() {
    var zoomLevel = window.devicePixelRatio;
    if (zoomLevel <= 1) {
        return true;
    }
    else{
        return false;
    }
}

function makeElementDraggableNoToggle(element) {
    $(element).draggable({
        containment: "document",
        stop: function(event, ui) {
            // Save the new position when dragging stops
            var position = ui.position;
            localStorage.setItem(element.id, JSON.stringify(position));
        }
    });

    // Immediately apply the last known position
    var savedPosition = localStorage.getItem(element.id);
    if (savedPosition) {
        var position = JSON.parse(savedPosition);
        $(element).css({
            top: position.top + 'px',
            left: position.left + 'px',
            position: 'absolute'
        });
    }
}

