var overlay = null;
var expandedOverlay = null;
var isMovingExpandedOverlay = false;
var clickedPos = {x: 0, y: 0};

function waitForBody(callback) {
    if (document.body) {
        callback();
    } else {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', callback);
        } else {
            const observer = new MutationObserver(() => {
                if (document.body) {
                    observer.disconnect();
                    callback();
                }
            });
            observer.observe(document.documentElement, {
                childList: true,
                subtree: true
            });
        }
    }
}

function processAssetPaths(html) {
    const assetsBaseUrl = chrome.runtime.getURL('assets/');
    return html.replace(/\.\/assets\//g, assetsBaseUrl);
}

window.initOverlay = function() {
    if (document.getElementById('overlay')) return;
    fetch(chrome.runtime.getURL('UI.html'))
        .then(response => response.text())
        .then(html => {
            overlay = document.createElement('div');
            overlay.id = 'overlay';
            overlay.innerHTML = processAssetPaths(html);
            const backgroundImg = chrome.runtime.getURL('assets/imgs/background.png');
            overlay.style.backgroundImage = `url(${backgroundImg})`;
            overlay.style.backgroundSize = 'cover';
            overlay.style.backgroundPosition = 'center';
            overlay.style.backgroundRepeat = 'no-repeat';
            overlay.style.width = 'fit-content';
            overlay.style.height = 'fit-content';
            overlay.style.margin = '0';
            overlay.style.padding = '0';
            overlay.style.position = 'absolute';
            overlay.style.top = '4px';
            overlay.style.right = '4px';
            document.body.appendChild(overlay);
            setupOverlayEventListeners(overlay);
            makeOverlayDraggable(overlay);
        })
        .catch(err => console.error("An error occurred while initializing the overlay:", err));
};

window.setupOverlayEventListeners = function(overlay) {
        const expandedLoadoutBtn = overlay.querySelector('#expanded_loadout');
        if (expandedLoadoutBtn) {
            expandedLoadoutBtn.addEventListener('click', async () => {
                window.initExpandedOverlay();
            });
    }
}

window.makeOverlayDraggable = function(element) {
    let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
    element.onmousedown = dragMouseDown;
    function dragMouseDown(e) {
        e.preventDefault();
        if (element.style.transform && element.style.transform.includes('translate')) {
            const rect = element.getBoundingClientRect();
            element.style.top = (rect.top + window.scrollY) + "px";
            element.style.left = (rect.left + window.scrollX) + "px";
            element.style.transform = "none";
        }
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        document.onmousemove = elementDrag;
        element.classList.add('dragging');
    }

    function elementDrag(e) {
        e.preventDefault();
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;

        let newTop = element.offsetTop - pos2;
        let newLeft = element.offsetLeft - pos1;

        element.style.top = newTop + "px";
        element.style.left = newLeft + "px";
        element.style.right = "auto";
        element.style.transform = "none";
    }

    function closeDragElement() {
        document.onmouseup = null;
        document.onmousemove = null;
        element.classList.remove('dragging');
    }
};

window.initExpandedOverlay = function() {
    if (expandedOverlay) {
        expandedOverlay.style.display = expandedOverlay.style.display === 'none' ? 'block' : 'none';
        return;
    }
    expandedOverlay = document.createElement('div');
    expandedOverlay.id = 'expanded-overlay';
    expandedOverlay.style.width = '480px';
    expandedOverlay.style.height = '600px';
    expandedOverlay.style.position = 'absolute';
    expandedOverlay.style.top = '50%';
    expandedOverlay.style.left = '50%';
    expandedOverlay.style.transform = 'translate(-50%, -50%)';
    expandedOverlay.style.borderRadius = '0.15em';
    expandedOverlay.style.outline = '2px solid black';
    expandedOverlay.style.zIndex = '10000';
    expandedOverlay.style.overflow = 'hidden';
    expandedOverlay.style.backgroundColor = 'transparent';
    const iframe = document.createElement('iframe');
    iframe.id = 'expanded-loadouts-iframe';
    iframe.src = chrome.runtime.getURL('expanded_loadouts.html');
    iframe.style.width = '100%';
    iframe.style.height = '100%';
    iframe.style.border = 'none';
    iframe.style.margin = '0';
    iframe.style.padding = '0';
    expandedOverlay.appendChild(iframe);
    document.body.appendChild(expandedOverlay);
    window.addEventListener("message", (e) => {
        if (e.data.type === 'mousedown') {
            iframe.style.display = 'none';
            expandedOverlay.style.backgroundColor = 'grey';
            isMovingExpandedOverlay = true;
            clickedPos = {x: e.data.data.x, y: e.data.data.y};
        }
    });

window.addEventListener('mousemove', (e) => {
        if (isMovingExpandedOverlay) {
            const rect = expandedOverlay.getBoundingClientRect();
            expandedOverlay.style.top = e.clientY - clickedPos.y + (rect.height / 2) + 'px';
            expandedOverlay.style.left = e.clientX - clickedPos.x + (rect.width / 2) + 'px';
        }
    });

window.addEventListener('mouseup', (e) => {
        if (isMovingExpandedOverlay) {
            iframe.style.display = 'block';
            expandedOverlay.style.backgroundColor = 'transparent';
            isMovingExpandedOverlay = false;
        }
    });
}

document.addEventListener('keydown', (e) => {
    if (e.shiftKey && e.key === 'A') {
        window.initExpandedOverlay();
    }
});

waitForBody(window.initOverlay);
